blob: c28d0363bdf2a3f3394b92e4a0d8a654607dd153 [file] [log] [blame]
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001/* Type object implementation */
2
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003#include "Python.h"
Guido van Rossumcd16bf62007-06-13 18:07:49 +00004#include "frameobject.h"
Tim Peters6d6c1a32001-08-02 04:15:00 +00005#include "structmember.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00006
Guido van Rossum9923ffe2002-06-04 19:52:53 +00007#include <ctype.h>
8
Christian Heimesa62da1d2008-01-12 19:39:10 +00009
10/* Support type attribute cache */
11
12/* The cache can keep references to the names alive for longer than
13 they normally would. This is why the maximum size is limited to
14 MCACHE_MAX_ATTR_SIZE, since it might be a problem if very large
15 strings are used as attribute names. */
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +000016#define MCACHE_MAX_ATTR_SIZE 100
17#define MCACHE_SIZE_EXP 10
18#define MCACHE_HASH(version, name_hash) \
19 (((unsigned int)(version) * (unsigned int)(name_hash)) \
20 >> (8*sizeof(unsigned int) - MCACHE_SIZE_EXP))
Christian Heimesa62da1d2008-01-12 19:39:10 +000021#define MCACHE_HASH_METHOD(type, name) \
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +000022 MCACHE_HASH((type)->tp_version_tag, \
23 ((PyUnicodeObject *)(name))->hash)
Christian Heimesa62da1d2008-01-12 19:39:10 +000024#define MCACHE_CACHEABLE_NAME(name) \
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +000025 PyUnicode_CheckExact(name) && \
26 PyUnicode_GET_SIZE(name) <= MCACHE_MAX_ATTR_SIZE
Christian Heimesa62da1d2008-01-12 19:39:10 +000027
28struct method_cache_entry {
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +000029 unsigned int version;
30 PyObject *name; /* reference to exactly a str or None */
31 PyObject *value; /* borrowed */
Christian Heimesa62da1d2008-01-12 19:39:10 +000032};
33
34static struct method_cache_entry method_cache[1 << MCACHE_SIZE_EXP];
35static unsigned int next_version_tag = 0;
Christian Heimes26855632008-01-27 23:50:43 +000036
37unsigned int
38PyType_ClearCache(void)
39{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +000040 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 PyType_Modified(&PyBaseObject_Type);
51 return cur_version_tag;
Christian Heimes26855632008-01-27 23:50:43 +000052}
Christian Heimesa62da1d2008-01-12 19:39:10 +000053
Georg Brandlf08a9dd2008-06-10 16:57:31 +000054void
55PyType_Modified(PyTypeObject *type)
Christian Heimesa62da1d2008-01-12 19:39:10 +000056{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +000057 /* 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.
Christian Heimesa62da1d2008-01-12 19:39:10 +000060
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +000061 Invariants:
Christian Heimesa62da1d2008-01-12 19:39:10 +000062
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +000063 - 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)
Christian Heimesa62da1d2008-01-12 19:39:10 +000066
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +000067 - before Py_TPFLAGS_VALID_VERSION_TAG can be set on a type,
68 it must first be set on all super types.
Christian Heimesa62da1d2008-01-12 19:39:10 +000069
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +000070 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;
Christian Heimesa62da1d2008-01-12 19:39:10 +000078
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +000079 if (!PyType_HasFeature(type, Py_TPFLAGS_VALID_VERSION_TAG))
80 return;
Christian Heimesa62da1d2008-01-12 19:39:10 +000081
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +000082 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 PyType_Modified((PyTypeObject *)ref);
90 }
91 }
92 }
93 type->tp_flags &= ~Py_TPFLAGS_VALID_VERSION_TAG;
Christian Heimesa62da1d2008-01-12 19:39:10 +000094}
95
96static void
97type_mro_modified(PyTypeObject *type, PyObject *bases) {
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +000098 /*
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.
Christian Heimesa62da1d2008-01-12 19:39:10 +0000102
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000103 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.
Christian Heimesa62da1d2008-01-12 19:39:10 +0000108
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000109 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;
Christian Heimesa62da1d2008-01-12 19:39:10 +0000114
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000115 if (!PyType_HasFeature(type, Py_TPFLAGS_HAVE_VERSION_TAG))
116 return;
Christian Heimesa62da1d2008-01-12 19:39:10 +0000117
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000118 n = PyTuple_GET_SIZE(bases);
119 for (i = 0; i < n; i++) {
120 PyObject *b = PyTuple_GET_ITEM(bases, i);
121 PyTypeObject *cls;
Christian Heimesa62da1d2008-01-12 19:39:10 +0000122
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000123 if (!PyType_Check(b) ) {
124 clear = 1;
125 break;
126 }
Christian Heimesa62da1d2008-01-12 19:39:10 +0000127
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000128 cls = (PyTypeObject *)b;
Christian Heimesa62da1d2008-01-12 19:39:10 +0000129
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000130 if (!PyType_HasFeature(cls, Py_TPFLAGS_HAVE_VERSION_TAG) ||
131 !PyType_IsSubtype(type, cls)) {
132 clear = 1;
133 break;
134 }
135 }
Christian Heimesa62da1d2008-01-12 19:39:10 +0000136
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000137 if (clear)
138 type->tp_flags &= ~(Py_TPFLAGS_HAVE_VERSION_TAG|
139 Py_TPFLAGS_VALID_VERSION_TAG);
Christian Heimesa62da1d2008-01-12 19:39:10 +0000140}
141
142static int
143assign_version_tag(PyTypeObject *type)
144{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000145 /* 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;
Christian Heimesa62da1d2008-01-12 19:39:10 +0000152
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000153 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;
Christian Heimesa62da1d2008-01-12 19:39:10 +0000159
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000160 type->tp_version_tag = next_version_tag++;
161 /* for stress-testing: next_version_tag &= 0xFF; */
Christian Heimesa62da1d2008-01-12 19:39:10 +0000162
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000163 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 PyType_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;
Christian Heimesa62da1d2008-01-12 19:39:10 +0000188}
189
190
Guido van Rossum6f799372001-09-20 20:46:19 +0000191static PyMemberDef type_members[] = {
Benjamin Peterson039d0a02010-08-25 23:19:30 +0000192 {"__basicsize__", T_PYSSIZET, offsetof(PyTypeObject,tp_basicsize),READONLY},
193 {"__itemsize__", T_PYSSIZET, offsetof(PyTypeObject, tp_itemsize), READONLY},
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000194 {"__flags__", T_LONG, offsetof(PyTypeObject, tp_flags), READONLY},
195 {"__weakrefoffset__", T_LONG,
196 offsetof(PyTypeObject, tp_weaklistoffset), READONLY},
197 {"__base__", T_OBJECT, offsetof(PyTypeObject, tp_base), READONLY},
198 {"__dictoffset__", T_LONG,
199 offsetof(PyTypeObject, tp_dictoffset), READONLY},
200 {"__mro__", T_OBJECT, offsetof(PyTypeObject, tp_mro), READONLY},
201 {0}
Tim Peters6d6c1a32001-08-02 04:15:00 +0000202};
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{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000207 const char *s;
Guido van Rossumc3542212001-08-16 09:18:56 +0000208
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000209 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
210 PyHeapTypeObject* et = (PyHeapTypeObject*)type;
Tim Petersea7f75d2002-12-07 21:39:16 +0000211
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000212 Py_INCREF(et->ht_name);
213 return et->ht_name;
214 }
215 else {
216 s = strrchr(type->tp_name, '.');
217 if (s == NULL)
218 s = type->tp_name;
219 else
220 s++;
221 return PyUnicode_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{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000228 PyHeapTypeObject* et;
229 char *tp_name;
230 PyObject *tmp;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000231
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000232 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
233 PyErr_Format(PyExc_TypeError,
234 "can't set %s.__name__", type->tp_name);
235 return -1;
236 }
237 if (!value) {
238 PyErr_Format(PyExc_TypeError,
239 "can't delete %s.__name__", type->tp_name);
240 return -1;
241 }
242 if (!PyUnicode_Check(value)) {
243 PyErr_Format(PyExc_TypeError,
244 "can only assign string to %s.__name__, not '%s'",
245 type->tp_name, Py_TYPE(value)->tp_name);
246 return -1;
247 }
Guido van Rossume845c0f2007-11-02 23:07:07 +0000248
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000249 /* Check absence of null characters */
250 tmp = PyUnicode_FromStringAndSize("\0", 1);
251 if (tmp == NULL)
252 return -1;
253 if (PyUnicode_Contains(value, tmp) != 0) {
254 Py_DECREF(tmp);
255 PyErr_Format(PyExc_ValueError,
256 "__name__ must not contain null bytes");
257 return -1;
258 }
259 Py_DECREF(tmp);
Guido van Rossume845c0f2007-11-02 23:07:07 +0000260
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000261 tp_name = _PyUnicode_AsString(value);
262 if (tp_name == NULL)
263 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000264
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000265 et = (PyHeapTypeObject*)type;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000266
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000267 Py_INCREF(value);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000268
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000269 Py_DECREF(et->ht_name);
270 et->ht_name = value;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000271
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000272 type->tp_name = tp_name;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000273
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000274 return 0;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000275}
276
Guido van Rossumc3542212001-08-16 09:18:56 +0000277static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000278type_module(PyTypeObject *type, void *context)
Guido van Rossum29ca26e1995-01-07 11:58:15 +0000279{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000280 PyObject *mod;
281 char *s;
Guido van Rossumc3542212001-08-16 09:18:56 +0000282
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000283 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
284 mod = PyDict_GetItemString(type->tp_dict, "__module__");
285 if (!mod) {
286 PyErr_Format(PyExc_AttributeError, "__module__");
287 return 0;
288 }
289 Py_XINCREF(mod);
290 return mod;
291 }
292 else {
293 s = strrchr(type->tp_name, '.');
294 if (s != NULL)
295 return PyUnicode_FromStringAndSize(
296 type->tp_name, (Py_ssize_t)(s - type->tp_name));
297 return PyUnicode_FromString("builtins");
298 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000299}
300
Guido van Rossum3926a632001-09-25 16:25:58 +0000301static int
302type_set_module(PyTypeObject *type, PyObject *value, void *context)
303{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000304 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
305 PyErr_Format(PyExc_TypeError,
306 "can't set %s.__module__", type->tp_name);
307 return -1;
308 }
309 if (!value) {
310 PyErr_Format(PyExc_TypeError,
311 "can't delete %s.__module__", type->tp_name);
312 return -1;
313 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000314
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000315 PyType_Modified(type);
Christian Heimesa62da1d2008-01-12 19:39:10 +0000316
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000317 return PyDict_SetItemString(type->tp_dict, "__module__", value);
Guido van Rossum3926a632001-09-25 16:25:58 +0000318}
319
Tim Peters6d6c1a32001-08-02 04:15:00 +0000320static PyObject *
Christian Heimes9e7f1d22008-02-28 12:27:11 +0000321type_abstractmethods(PyTypeObject *type, void *context)
322{
Benjamin Peterson0ad44fa2010-10-02 18:04:55 +0000323 PyObject *mod = NULL;
Benjamin Peterson866c74e2010-10-03 02:19:18 +0000324 /* type itself has an __abstractmethods__ descriptor (this). Don't return
325 that. */
Benjamin Peterson0ad44fa2010-10-02 18:04:55 +0000326 if (type != &PyType_Type)
327 mod = PyDict_GetItemString(type->tp_dict, "__abstractmethods__");
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000328 if (!mod) {
329 PyErr_Format(PyExc_AttributeError, "__abstractmethods__");
330 return NULL;
331 }
332 Py_XINCREF(mod);
333 return mod;
Christian Heimes9e7f1d22008-02-28 12:27:11 +0000334}
335
336static int
337type_set_abstractmethods(PyTypeObject *type, PyObject *value, void *context)
338{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000339 /* __abstractmethods__ should only be set once on a type, in
340 abc.ABCMeta.__new__, so this function doesn't do anything
341 special to update subclasses.
342 */
343 int res = PyDict_SetItemString(type->tp_dict,
344 "__abstractmethods__", value);
345 if (res == 0) {
346 PyType_Modified(type);
347 if (value && PyObject_IsTrue(value)) {
348 type->tp_flags |= Py_TPFLAGS_IS_ABSTRACT;
349 }
350 else {
351 type->tp_flags &= ~Py_TPFLAGS_IS_ABSTRACT;
352 }
353 }
354 return res;
Christian Heimes9e7f1d22008-02-28 12:27:11 +0000355}
356
357static PyObject *
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000358type_get_bases(PyTypeObject *type, void *context)
359{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000360 Py_INCREF(type->tp_bases);
361 return type->tp_bases;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000362}
363
364static PyTypeObject *best_base(PyObject *);
365static int mro_internal(PyTypeObject *);
366static int compatible_for_assignment(PyTypeObject *, PyTypeObject *, char *);
367static int add_subclass(PyTypeObject*, PyTypeObject*);
368static void remove_subclass(PyTypeObject *, PyTypeObject *);
369static void update_all_slots(PyTypeObject *);
370
Guido van Rossum8d24ee92003-03-24 23:49:49 +0000371typedef int (*update_callback)(PyTypeObject *, void *);
372static int update_subclasses(PyTypeObject *type, PyObject *name,
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000373 update_callback callback, void *data);
Guido van Rossum8d24ee92003-03-24 23:49:49 +0000374static int recurse_down_subclasses(PyTypeObject *type, PyObject *name,
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000375 update_callback callback, void *data);
Guido van Rossum8d24ee92003-03-24 23:49:49 +0000376
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000377static int
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000378mro_subclasses(PyTypeObject *type, PyObject* temp)
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000379{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000380 PyTypeObject *subclass;
381 PyObject *ref, *subclasses, *old_mro;
382 Py_ssize_t i, n;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000383
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000384 subclasses = type->tp_subclasses;
385 if (subclasses == NULL)
386 return 0;
387 assert(PyList_Check(subclasses));
388 n = PyList_GET_SIZE(subclasses);
389 for (i = 0; i < n; i++) {
390 ref = PyList_GET_ITEM(subclasses, i);
391 assert(PyWeakref_CheckRef(ref));
392 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
393 assert(subclass != NULL);
394 if ((PyObject *)subclass == Py_None)
395 continue;
396 assert(PyType_Check(subclass));
397 old_mro = subclass->tp_mro;
398 if (mro_internal(subclass) < 0) {
399 subclass->tp_mro = old_mro;
400 return -1;
401 }
402 else {
403 PyObject* tuple;
404 tuple = PyTuple_Pack(2, subclass, old_mro);
405 Py_DECREF(old_mro);
406 if (!tuple)
407 return -1;
408 if (PyList_Append(temp, tuple) < 0)
409 return -1;
410 Py_DECREF(tuple);
411 }
412 if (mro_subclasses(subclass, temp) < 0)
413 return -1;
414 }
415 return 0;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000416}
417
418static int
419type_set_bases(PyTypeObject *type, PyObject *value, void *context)
420{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000421 Py_ssize_t i;
422 int r = 0;
423 PyObject *ob, *temp;
424 PyTypeObject *new_base, *old_base;
425 PyObject *old_bases, *old_mro;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000426
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000427 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
428 PyErr_Format(PyExc_TypeError,
429 "can't set %s.__bases__", type->tp_name);
430 return -1;
431 }
432 if (!value) {
433 PyErr_Format(PyExc_TypeError,
434 "can't delete %s.__bases__", type->tp_name);
435 return -1;
436 }
437 if (!PyTuple_Check(value)) {
438 PyErr_Format(PyExc_TypeError,
439 "can only assign tuple to %s.__bases__, not %s",
440 type->tp_name, Py_TYPE(value)->tp_name);
441 return -1;
442 }
443 if (PyTuple_GET_SIZE(value) == 0) {
444 PyErr_Format(PyExc_TypeError,
445 "can only assign non-empty tuple to %s.__bases__, not ()",
446 type->tp_name);
447 return -1;
448 }
449 for (i = 0; i < PyTuple_GET_SIZE(value); i++) {
450 ob = PyTuple_GET_ITEM(value, i);
451 if (!PyType_Check(ob)) {
452 PyErr_Format(
453 PyExc_TypeError,
454 "%s.__bases__ must be tuple of old- or new-style classes, not '%s'",
455 type->tp_name, Py_TYPE(ob)->tp_name);
456 return -1;
457 }
458 if (PyType_Check(ob)) {
459 if (PyType_IsSubtype((PyTypeObject*)ob, type)) {
460 PyErr_SetString(PyExc_TypeError,
461 "a __bases__ item causes an inheritance cycle");
462 return -1;
463 }
464 }
465 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000466
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000467 new_base = best_base(value);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000468
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000469 if (!new_base) {
470 return -1;
471 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000472
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000473 if (!compatible_for_assignment(type->tp_base, new_base, "__bases__"))
474 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000475
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000476 Py_INCREF(new_base);
477 Py_INCREF(value);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000478
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000479 old_bases = type->tp_bases;
480 old_base = type->tp_base;
481 old_mro = type->tp_mro;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000482
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000483 type->tp_bases = value;
484 type->tp_base = new_base;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000485
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000486 if (mro_internal(type) < 0) {
487 goto bail;
488 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000489
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000490 temp = PyList_New(0);
491 if (!temp)
492 goto bail;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000493
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000494 r = mro_subclasses(type, temp);
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000495
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000496 if (r < 0) {
497 for (i = 0; i < PyList_Size(temp); i++) {
498 PyTypeObject* cls;
499 PyObject* mro;
500 PyArg_UnpackTuple(PyList_GET_ITEM(temp, i),
501 "", 2, 2, &cls, &mro);
502 Py_INCREF(mro);
503 ob = cls->tp_mro;
504 cls->tp_mro = mro;
505 Py_DECREF(ob);
506 }
507 Py_DECREF(temp);
508 goto bail;
509 }
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000510
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000511 Py_DECREF(temp);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000512
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000513 /* any base that was in __bases__ but now isn't, we
514 need to remove |type| from its tp_subclasses.
515 conversely, any class now in __bases__ that wasn't
516 needs to have |type| added to its subclasses. */
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000517
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000518 /* for now, sod that: just remove from all old_bases,
519 add to all new_bases */
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000520
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000521 for (i = PyTuple_GET_SIZE(old_bases) - 1; i >= 0; i--) {
522 ob = PyTuple_GET_ITEM(old_bases, i);
523 if (PyType_Check(ob)) {
524 remove_subclass(
525 (PyTypeObject*)ob, type);
526 }
527 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000528
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000529 for (i = PyTuple_GET_SIZE(value) - 1; i >= 0; i--) {
530 ob = PyTuple_GET_ITEM(value, i);
531 if (PyType_Check(ob)) {
532 if (add_subclass((PyTypeObject*)ob, type) < 0)
533 r = -1;
534 }
535 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000536
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000537 update_all_slots(type);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000538
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000539 Py_DECREF(old_bases);
540 Py_DECREF(old_base);
541 Py_DECREF(old_mro);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000542
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000543 return r;
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000544
545 bail:
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000546 Py_DECREF(type->tp_bases);
547 Py_DECREF(type->tp_base);
548 if (type->tp_mro != old_mro) {
549 Py_DECREF(type->tp_mro);
550 }
Michael W. Hudsone723e452003-08-07 14:58:10 +0000551
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000552 type->tp_bases = old_bases;
553 type->tp_base = old_base;
554 type->tp_mro = old_mro;
Tim Petersea7f75d2002-12-07 21:39:16 +0000555
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000556 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000557}
558
559static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000560type_dict(PyTypeObject *type, void *context)
561{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000562 if (type->tp_dict == NULL) {
563 Py_INCREF(Py_None);
564 return Py_None;
565 }
566 return PyDictProxy_New(type->tp_dict);
Guido van Rossum29ca26e1995-01-07 11:58:15 +0000567}
568
Tim Peters24008312002-03-17 18:56:20 +0000569static PyObject *
570type_get_doc(PyTypeObject *type, void *context)
571{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000572 PyObject *result;
573 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE) && type->tp_doc != NULL)
574 return PyUnicode_FromString(type->tp_doc);
575 result = PyDict_GetItemString(type->tp_dict, "__doc__");
576 if (result == NULL) {
577 result = Py_None;
578 Py_INCREF(result);
579 }
580 else if (Py_TYPE(result)->tp_descr_get) {
581 result = Py_TYPE(result)->tp_descr_get(result, NULL,
582 (PyObject *)type);
583 }
584 else {
585 Py_INCREF(result);
586 }
587 return result;
Tim Peters24008312002-03-17 18:56:20 +0000588}
589
Antoine Pitrouec569b72008-08-26 22:40:48 +0000590static PyObject *
591type___instancecheck__(PyObject *type, PyObject *inst)
592{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000593 switch (_PyObject_RealIsInstance(inst, type)) {
594 case -1:
595 return NULL;
596 case 0:
597 Py_RETURN_FALSE;
598 default:
599 Py_RETURN_TRUE;
600 }
Antoine Pitrouec569b72008-08-26 22:40:48 +0000601}
602
603
604static PyObject *
Antoine Pitrouec569b72008-08-26 22:40:48 +0000605type___subclasscheck__(PyObject *type, PyObject *inst)
606{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000607 switch (_PyObject_RealIsSubclass(inst, type)) {
608 case -1:
609 return NULL;
610 case 0:
611 Py_RETURN_FALSE;
612 default:
613 Py_RETURN_TRUE;
614 }
Antoine Pitrouec569b72008-08-26 22:40:48 +0000615}
616
Antoine Pitrouec569b72008-08-26 22:40:48 +0000617
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000618static PyGetSetDef type_getsets[] = {
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000619 {"__name__", (getter)type_name, (setter)type_set_name, NULL},
620 {"__bases__", (getter)type_get_bases, (setter)type_set_bases, NULL},
621 {"__module__", (getter)type_module, (setter)type_set_module, NULL},
622 {"__abstractmethods__", (getter)type_abstractmethods,
623 (setter)type_set_abstractmethods, NULL},
624 {"__dict__", (getter)type_dict, NULL, NULL},
625 {"__doc__", (getter)type_get_doc, NULL, NULL},
626 {0}
Tim Peters6d6c1a32001-08-02 04:15:00 +0000627};
628
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000629static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000630type_repr(PyTypeObject *type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000631{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000632 PyObject *mod, *name, *rtn;
Guido van Rossumc3542212001-08-16 09:18:56 +0000633
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000634 mod = type_module(type, NULL);
635 if (mod == NULL)
636 PyErr_Clear();
637 else if (!PyUnicode_Check(mod)) {
638 Py_DECREF(mod);
639 mod = NULL;
640 }
641 name = type_name(type, NULL);
642 if (name == NULL)
643 return NULL;
Barry Warsaw7ce36942001-08-24 18:34:26 +0000644
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000645 if (mod != NULL && PyUnicode_CompareWithASCIIString(mod, "builtins"))
646 rtn = PyUnicode_FromFormat("<class '%U.%U'>", mod, name);
647 else
648 rtn = PyUnicode_FromFormat("<class '%s'>", type->tp_name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000649
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000650 Py_XDECREF(mod);
651 Py_DECREF(name);
652 return rtn;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000653}
654
Tim Peters6d6c1a32001-08-02 04:15:00 +0000655static PyObject *
656type_call(PyTypeObject *type, PyObject *args, PyObject *kwds)
657{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000658 PyObject *obj;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000659
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000660 if (type->tp_new == NULL) {
661 PyErr_Format(PyExc_TypeError,
662 "cannot create '%.100s' instances",
663 type->tp_name);
664 return NULL;
665 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000666
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000667 obj = type->tp_new(type, args, kwds);
668 if (obj != NULL) {
669 /* Ugly exception: when the call was type(something),
670 don't call tp_init on the result. */
671 if (type == &PyType_Type &&
672 PyTuple_Check(args) && PyTuple_GET_SIZE(args) == 1 &&
673 (kwds == NULL ||
674 (PyDict_Check(kwds) && PyDict_Size(kwds) == 0)))
675 return obj;
676 /* If the returned object is not an instance of type,
677 it won't be initialized. */
678 if (!PyType_IsSubtype(Py_TYPE(obj), type))
679 return obj;
680 type = Py_TYPE(obj);
681 if (type->tp_init != NULL &&
682 type->tp_init(obj, args, kwds) < 0) {
683 Py_DECREF(obj);
684 obj = NULL;
685 }
686 }
687 return obj;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000688}
689
690PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000691PyType_GenericAlloc(PyTypeObject *type, Py_ssize_t nitems)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000692{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000693 PyObject *obj;
694 const size_t size = _PyObject_VAR_SIZE(type, nitems+1);
695 /* note that we need to add one, for the sentinel */
Tim Peters406fe3b2001-10-06 19:04:01 +0000696
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000697 if (PyType_IS_GC(type))
698 obj = _PyObject_GC_Malloc(size);
699 else
700 obj = (PyObject *)PyObject_MALLOC(size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000701
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000702 if (obj == NULL)
703 return PyErr_NoMemory();
Tim Peters406fe3b2001-10-06 19:04:01 +0000704
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000705 memset(obj, '\0', size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000706
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000707 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
708 Py_INCREF(type);
Tim Peters406fe3b2001-10-06 19:04:01 +0000709
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000710 if (type->tp_itemsize == 0)
711 PyObject_INIT(obj, type);
712 else
713 (void) PyObject_INIT_VAR((PyVarObject *)obj, type, nitems);
Tim Peters406fe3b2001-10-06 19:04:01 +0000714
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000715 if (PyType_IS_GC(type))
716 _PyObject_GC_TRACK(obj);
717 return obj;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000718}
719
720PyObject *
721PyType_GenericNew(PyTypeObject *type, PyObject *args, PyObject *kwds)
722{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000723 return type->tp_alloc(type, 0);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000724}
725
Guido van Rossum9475a232001-10-05 20:51:39 +0000726/* Helpers for subtyping */
727
728static int
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000729traverse_slots(PyTypeObject *type, PyObject *self, visitproc visit, void *arg)
730{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000731 Py_ssize_t i, n;
732 PyMemberDef *mp;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000733
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000734 n = Py_SIZE(type);
735 mp = PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type);
736 for (i = 0; i < n; i++, mp++) {
737 if (mp->type == T_OBJECT_EX) {
738 char *addr = (char *)self + mp->offset;
739 PyObject *obj = *(PyObject **)addr;
740 if (obj != NULL) {
741 int err = visit(obj, arg);
742 if (err)
743 return err;
744 }
745 }
746 }
747 return 0;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000748}
749
750static int
Guido van Rossum9475a232001-10-05 20:51:39 +0000751subtype_traverse(PyObject *self, visitproc visit, void *arg)
752{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000753 PyTypeObject *type, *base;
754 traverseproc basetraverse;
Guido van Rossum9475a232001-10-05 20:51:39 +0000755
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000756 /* Find the nearest base with a different tp_traverse,
757 and traverse slots while we're at it */
758 type = Py_TYPE(self);
759 base = type;
760 while ((basetraverse = base->tp_traverse) == subtype_traverse) {
761 if (Py_SIZE(base)) {
762 int err = traverse_slots(base, self, visit, arg);
763 if (err)
764 return err;
765 }
766 base = base->tp_base;
767 assert(base);
768 }
Guido van Rossum9475a232001-10-05 20:51:39 +0000769
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000770 if (type->tp_dictoffset != base->tp_dictoffset) {
771 PyObject **dictptr = _PyObject_GetDictPtr(self);
772 if (dictptr && *dictptr)
773 Py_VISIT(*dictptr);
774 }
Guido van Rossum9475a232001-10-05 20:51:39 +0000775
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000776 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
777 /* For a heaptype, the instances count as references
778 to the type. Traverse the type so the collector
779 can find cycles involving this link. */
780 Py_VISIT(type);
Guido van Rossuma3862092002-06-10 15:24:42 +0000781
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000782 if (basetraverse)
783 return basetraverse(self, visit, arg);
784 return 0;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000785}
786
787static void
788clear_slots(PyTypeObject *type, PyObject *self)
789{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000790 Py_ssize_t i, n;
791 PyMemberDef *mp;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000792
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000793 n = Py_SIZE(type);
794 mp = PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type);
795 for (i = 0; i < n; i++, mp++) {
796 if (mp->type == T_OBJECT_EX && !(mp->flags & READONLY)) {
797 char *addr = (char *)self + mp->offset;
798 PyObject *obj = *(PyObject **)addr;
799 if (obj != NULL) {
800 *(PyObject **)addr = NULL;
801 Py_DECREF(obj);
802 }
803 }
804 }
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000805}
806
807static int
808subtype_clear(PyObject *self)
809{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000810 PyTypeObject *type, *base;
811 inquiry baseclear;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000812
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000813 /* Find the nearest base with a different tp_clear
814 and clear slots while we're at it */
815 type = Py_TYPE(self);
816 base = type;
817 while ((baseclear = base->tp_clear) == subtype_clear) {
818 if (Py_SIZE(base))
819 clear_slots(base, self);
820 base = base->tp_base;
821 assert(base);
822 }
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000823
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000824 /* There's no need to clear the instance dict (if any);
825 the collector will call its tp_clear handler. */
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000826
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000827 if (baseclear)
828 return baseclear(self);
829 return 0;
Guido van Rossum9475a232001-10-05 20:51:39 +0000830}
Tim Peters6d6c1a32001-08-02 04:15:00 +0000831
832static void
833subtype_dealloc(PyObject *self)
834{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000835 PyTypeObject *type, *base;
836 destructor basedealloc;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000837
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000838 /* Extract the type; we expect it to be a heap type */
839 type = Py_TYPE(self);
840 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000841
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000842 /* Test whether the type has GC exactly once */
Guido van Rossum22b13872002-08-06 21:41:44 +0000843
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000844 if (!PyType_IS_GC(type)) {
845 /* It's really rare to find a dynamic type that doesn't have
846 GC; it can only happen when deriving from 'object' and not
847 adding any slots or instance variables. This allows
848 certain simplifications: there's no need to call
849 clear_slots(), or DECREF the dict, or clear weakrefs. */
Guido van Rossum22b13872002-08-06 21:41:44 +0000850
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000851 /* Maybe call finalizer; exit early if resurrected */
852 if (type->tp_del) {
853 type->tp_del(self);
854 if (self->ob_refcnt > 0)
855 return;
856 }
Guido van Rossum22b13872002-08-06 21:41:44 +0000857
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000858 /* Find the nearest base with a different tp_dealloc */
859 base = type;
860 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
861 assert(Py_SIZE(base) == 0);
862 base = base->tp_base;
863 assert(base);
864 }
Guido van Rossum22b13872002-08-06 21:41:44 +0000865
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000866 /* Extract the type again; tp_del may have changed it */
867 type = Py_TYPE(self);
Benjamin Peterson193152c2009-04-25 01:08:45 +0000868
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000869 /* Call the base tp_dealloc() */
870 assert(basedealloc);
871 basedealloc(self);
Guido van Rossum22b13872002-08-06 21:41:44 +0000872
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000873 /* Can't reference self beyond this point */
874 Py_DECREF(type);
Guido van Rossum22b13872002-08-06 21:41:44 +0000875
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000876 /* Done */
877 return;
878 }
Guido van Rossum22b13872002-08-06 21:41:44 +0000879
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000880 /* We get here only if the type has GC */
Guido van Rossum22b13872002-08-06 21:41:44 +0000881
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000882 /* UnTrack and re-Track around the trashcan macro, alas */
883 /* See explanation at end of function for full disclosure */
884 PyObject_GC_UnTrack(self);
885 ++_PyTrash_delete_nesting;
886 Py_TRASHCAN_SAFE_BEGIN(self);
887 --_PyTrash_delete_nesting;
888 /* DO NOT restore GC tracking at this point. weakref callbacks
889 * (if any, and whether directly here or indirectly in something we
890 * call) may trigger GC, and if self is tracked at that point, it
891 * will look like trash to GC and GC will try to delete self again.
892 */
Guido van Rossum22b13872002-08-06 21:41:44 +0000893
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000894 /* Find the nearest base with a different tp_dealloc */
895 base = type;
896 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
897 base = base->tp_base;
898 assert(base);
899 }
Guido van Rossum14227b42001-12-06 02:35:58 +0000900
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000901 /* If we added a weaklist, we clear it. Do this *before* calling
902 the finalizer (__del__), clearing slots, or clearing the instance
903 dict. */
Guido van Rossum59195fd2003-06-13 20:54:40 +0000904
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000905 if (type->tp_weaklistoffset && !base->tp_weaklistoffset)
906 PyObject_ClearWeakRefs(self);
Guido van Rossum1987c662003-05-29 14:29:23 +0000907
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000908 /* Maybe call finalizer; exit early if resurrected */
909 if (type->tp_del) {
910 _PyObject_GC_TRACK(self);
911 type->tp_del(self);
912 if (self->ob_refcnt > 0)
913 goto endlabel; /* resurrected */
914 else
915 _PyObject_GC_UNTRACK(self);
916 /* New weakrefs could be created during the finalizer call.
917 If this occurs, clear them out without calling their
918 finalizers since they might rely on part of the object
919 being finalized that has already been destroyed. */
920 if (type->tp_weaklistoffset && !base->tp_weaklistoffset) {
921 /* Modeled after GET_WEAKREFS_LISTPTR() */
922 PyWeakReference **list = (PyWeakReference **) \
923 PyObject_GET_WEAKREFS_LISTPTR(self);
924 while (*list)
925 _PyWeakref_ClearRef(*list);
926 }
927 }
Guido van Rossum1987c662003-05-29 14:29:23 +0000928
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000929 /* Clear slots up to the nearest base with a different tp_dealloc */
930 base = type;
931 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
932 if (Py_SIZE(base))
933 clear_slots(base, self);
934 base = base->tp_base;
935 assert(base);
936 }
Guido van Rossum59195fd2003-06-13 20:54:40 +0000937
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000938 /* If we added a dict, DECREF it */
939 if (type->tp_dictoffset && !base->tp_dictoffset) {
940 PyObject **dictptr = _PyObject_GetDictPtr(self);
941 if (dictptr != NULL) {
942 PyObject *dict = *dictptr;
943 if (dict != NULL) {
944 Py_DECREF(dict);
945 *dictptr = NULL;
946 }
947 }
948 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000949
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000950 /* Extract the type again; tp_del may have changed it */
951 type = Py_TYPE(self);
Benjamin Peterson193152c2009-04-25 01:08:45 +0000952
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000953 /* Call the base tp_dealloc(); first retrack self if
954 * basedealloc knows about gc.
955 */
956 if (PyType_IS_GC(base))
957 _PyObject_GC_TRACK(self);
958 assert(basedealloc);
959 basedealloc(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000960
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000961 /* Can't reference self beyond this point */
962 Py_DECREF(type);
Guido van Rossum22b13872002-08-06 21:41:44 +0000963
Guido van Rossum0906e072002-08-07 20:42:09 +0000964 endlabel:
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000965 ++_PyTrash_delete_nesting;
966 Py_TRASHCAN_SAFE_END(self);
967 --_PyTrash_delete_nesting;
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000968
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000969 /* Explanation of the weirdness around the trashcan macros:
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000970
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000971 Q. What do the trashcan macros do?
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000972
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000973 A. Read the comment titled "Trashcan mechanism" in object.h.
974 For one, this explains why there must be a call to GC-untrack
975 before the trashcan begin macro. Without understanding the
976 trashcan code, the answers to the following questions don't make
977 sense.
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000978
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000979 Q. Why do we GC-untrack before the trashcan and then immediately
980 GC-track again afterward?
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000981
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000982 A. In the case that the base class is GC-aware, the base class
983 probably GC-untracks the object. If it does that using the
984 UNTRACK macro, this will crash when the object is already
985 untracked. Because we don't know what the base class does, the
986 only safe thing is to make sure the object is tracked when we
987 call the base class dealloc. But... The trashcan begin macro
988 requires that the object is *untracked* before it is called. So
989 the dance becomes:
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000990
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000991 GC untrack
992 trashcan begin
993 GC track
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000994
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000995 Q. Why did the last question say "immediately GC-track again"?
996 It's nowhere near immediately.
Tim Petersf7f9e992003-11-13 21:59:32 +0000997
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000998 A. Because the code *used* to re-track immediately. Bad Idea.
999 self has a refcount of 0, and if gc ever gets its hands on it
1000 (which can happen if any weakref callback gets invoked), it
1001 looks like trash to gc too, and gc also tries to delete self
1002 then. But we're already deleting self. Double dealloction is
1003 a subtle disaster.
Tim Petersf7f9e992003-11-13 21:59:32 +00001004
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001005 Q. Why the bizarre (net-zero) manipulation of
1006 _PyTrash_delete_nesting around the trashcan macros?
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001007
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001008 A. Some base classes (e.g. list) also use the trashcan mechanism.
1009 The following scenario used to be possible:
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001010
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001011 - suppose the trashcan level is one below the trashcan limit
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001012
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001013 - subtype_dealloc() is called
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001014
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001015 - the trashcan limit is not yet reached, so the trashcan level
1016 is incremented and the code between trashcan begin and end is
1017 executed
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001018
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001019 - this destroys much of the object's contents, including its
1020 slots and __dict__
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001021
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001022 - basedealloc() is called; this is really list_dealloc(), or
1023 some other type which also uses the trashcan macros
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001024
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001025 - the trashcan limit is now reached, so the object is put on the
1026 trashcan's to-be-deleted-later list
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001027
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001028 - basedealloc() returns
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001029
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001030 - subtype_dealloc() decrefs the object's type
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001031
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001032 - subtype_dealloc() returns
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001033
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001034 - later, the trashcan code starts deleting the objects from its
1035 to-be-deleted-later list
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001036
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001037 - subtype_dealloc() is called *AGAIN* for the same object
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001038
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001039 - at the very least (if the destroyed slots and __dict__ don't
1040 cause problems) the object's type gets decref'ed a second
1041 time, which is *BAD*!!!
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001042
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001043 The remedy is to make sure that if the code between trashcan
1044 begin and end in subtype_dealloc() is called, the code between
1045 trashcan begin and end in basedealloc() will also be called.
1046 This is done by decrementing the level after passing into the
1047 trashcan block, and incrementing it just before leaving the
1048 block.
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001049
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001050 But now it's possible that a chain of objects consisting solely
1051 of objects whose deallocator is subtype_dealloc() will defeat
1052 the trashcan mechanism completely: the decremented level means
1053 that the effective level never reaches the limit. Therefore, we
1054 *increment* the level *before* entering the trashcan block, and
1055 matchingly decrement it after leaving. This means the trashcan
1056 code will trigger a little early, but that's no big deal.
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001057
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001058 Q. Are there any live examples of code in need of all this
1059 complexity?
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001060
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001061 A. Yes. See SF bug 668433 for code that crashed (when Python was
1062 compiled in debug mode) before the trashcan level manipulations
1063 were added. For more discussion, see SF patches 581742, 575073
1064 and bug 574207.
1065 */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001066}
1067
Jeremy Hylton938ace62002-07-17 16:30:39 +00001068static PyTypeObject *solid_base(PyTypeObject *type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001069
Tim Peters6d6c1a32001-08-02 04:15:00 +00001070/* type test with subclassing support */
1071
1072int
1073PyType_IsSubtype(PyTypeObject *a, PyTypeObject *b)
1074{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001075 PyObject *mro;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001076
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001077 mro = a->tp_mro;
1078 if (mro != NULL) {
1079 /* Deal with multiple inheritance without recursion
1080 by walking the MRO tuple */
1081 Py_ssize_t i, n;
1082 assert(PyTuple_Check(mro));
1083 n = PyTuple_GET_SIZE(mro);
1084 for (i = 0; i < n; i++) {
1085 if (PyTuple_GET_ITEM(mro, i) == (PyObject *)b)
1086 return 1;
1087 }
1088 return 0;
1089 }
1090 else {
1091 /* a is not completely initilized yet; follow tp_base */
1092 do {
1093 if (a == b)
1094 return 1;
1095 a = a->tp_base;
1096 } while (a != NULL);
1097 return b == &PyBaseObject_Type;
1098 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001099}
1100
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001101/* Internal routines to do a method lookup in the type
Guido van Rossum60718732001-08-28 17:47:51 +00001102 without looking in the instance dictionary
1103 (so we can't use PyObject_GetAttr) but still binding
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001104 it to the instance. The arguments are the object,
Guido van Rossum60718732001-08-28 17:47:51 +00001105 the method name as a C string, and the address of a
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001106 static variable used to cache the interned Python string.
1107
1108 Two variants:
1109
1110 - lookup_maybe() returns NULL without raising an exception
1111 when the _PyType_Lookup() call fails;
1112
1113 - lookup_method() always raises an exception upon errors.
Benjamin Peterson224205f2009-05-08 03:25:19 +00001114
1115 - _PyObject_LookupSpecial() exported for the benefit of other places.
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001116*/
Guido van Rossum60718732001-08-28 17:47:51 +00001117
1118static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001119lookup_maybe(PyObject *self, char *attrstr, PyObject **attrobj)
Guido van Rossum60718732001-08-28 17:47:51 +00001120{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001121 PyObject *res;
Guido van Rossum60718732001-08-28 17:47:51 +00001122
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001123 if (*attrobj == NULL) {
1124 *attrobj = PyUnicode_InternFromString(attrstr);
1125 if (*attrobj == NULL)
1126 return NULL;
1127 }
1128 res = _PyType_Lookup(Py_TYPE(self), *attrobj);
1129 if (res != NULL) {
1130 descrgetfunc f;
1131 if ((f = Py_TYPE(res)->tp_descr_get) == NULL)
1132 Py_INCREF(res);
1133 else
1134 res = f(res, self, (PyObject *)(Py_TYPE(self)));
1135 }
1136 return res;
Guido van Rossum60718732001-08-28 17:47:51 +00001137}
1138
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001139static PyObject *
1140lookup_method(PyObject *self, char *attrstr, PyObject **attrobj)
1141{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001142 PyObject *res = lookup_maybe(self, attrstr, attrobj);
1143 if (res == NULL && !PyErr_Occurred())
1144 PyErr_SetObject(PyExc_AttributeError, *attrobj);
1145 return res;
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001146}
1147
Benjamin Peterson224205f2009-05-08 03:25:19 +00001148PyObject *
1149_PyObject_LookupSpecial(PyObject *self, char *attrstr, PyObject **attrobj)
1150{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001151 return lookup_maybe(self, attrstr, attrobj);
Benjamin Peterson224205f2009-05-08 03:25:19 +00001152}
1153
Guido van Rossum2730b132001-08-28 18:22:14 +00001154/* A variation of PyObject_CallMethod that uses lookup_method()
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001155 instead of PyObject_GetAttrString(). This uses the same convention
Guido van Rossum2730b132001-08-28 18:22:14 +00001156 as lookup_method to cache the interned name string object. */
1157
Neil Schemenauerf23473f2001-10-21 22:28:58 +00001158static PyObject *
Guido van Rossum2730b132001-08-28 18:22:14 +00001159call_method(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
1160{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001161 va_list va;
1162 PyObject *args, *func = 0, *retval;
1163 va_start(va, format);
Guido van Rossum2730b132001-08-28 18:22:14 +00001164
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001165 func = lookup_maybe(o, name, nameobj);
1166 if (func == NULL) {
1167 va_end(va);
1168 if (!PyErr_Occurred())
1169 PyErr_SetObject(PyExc_AttributeError, *nameobj);
1170 return NULL;
1171 }
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001172
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001173 if (format && *format)
1174 args = Py_VaBuildValue(format, va);
1175 else
1176 args = PyTuple_New(0);
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001177
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001178 va_end(va);
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001179
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001180 if (args == NULL)
1181 return NULL;
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001182
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001183 assert(PyTuple_Check(args));
1184 retval = PyObject_Call(func, args, NULL);
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001185
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001186 Py_DECREF(args);
1187 Py_DECREF(func);
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001188
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001189 return retval;
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001190}
1191
1192/* Clone of call_method() that returns NotImplemented when the lookup fails. */
1193
Neil Schemenauerf23473f2001-10-21 22:28:58 +00001194static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001195call_maybe(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
1196{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001197 va_list va;
1198 PyObject *args, *func = 0, *retval;
1199 va_start(va, format);
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001200
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001201 func = lookup_maybe(o, name, nameobj);
1202 if (func == NULL) {
1203 va_end(va);
1204 if (!PyErr_Occurred()) {
1205 Py_INCREF(Py_NotImplemented);
1206 return Py_NotImplemented;
1207 }
1208 return NULL;
1209 }
Guido van Rossum2730b132001-08-28 18:22:14 +00001210
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001211 if (format && *format)
1212 args = Py_VaBuildValue(format, va);
1213 else
1214 args = PyTuple_New(0);
Guido van Rossum2730b132001-08-28 18:22:14 +00001215
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001216 va_end(va);
Guido van Rossum2730b132001-08-28 18:22:14 +00001217
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001218 if (args == NULL)
1219 return NULL;
Guido van Rossum2730b132001-08-28 18:22:14 +00001220
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001221 assert(PyTuple_Check(args));
1222 retval = PyObject_Call(func, args, NULL);
Guido van Rossum2730b132001-08-28 18:22:14 +00001223
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001224 Py_DECREF(args);
1225 Py_DECREF(func);
Guido van Rossum2730b132001-08-28 18:22:14 +00001226
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001227 return retval;
Guido van Rossum2730b132001-08-28 18:22:14 +00001228}
1229
Tim Petersea7f75d2002-12-07 21:39:16 +00001230/*
Guido van Rossum1f121312002-11-14 19:49:16 +00001231 Method resolution order algorithm C3 described in
1232 "A Monotonic Superclass Linearization for Dylan",
1233 by Kim Barrett, Bob Cassel, Paul Haahr,
Tim Petersea7f75d2002-12-07 21:39:16 +00001234 David A. Moon, Keith Playford, and P. Tucker Withington.
Guido van Rossum1f121312002-11-14 19:49:16 +00001235 (OOPSLA 1996)
1236
Guido van Rossum98f33732002-11-25 21:36:54 +00001237 Some notes about the rules implied by C3:
1238
Tim Petersea7f75d2002-12-07 21:39:16 +00001239 No duplicate bases.
Guido van Rossum98f33732002-11-25 21:36:54 +00001240 It isn't legal to repeat a class in a list of base classes.
1241
1242 The next three properties are the 3 constraints in "C3".
1243
Tim Petersea7f75d2002-12-07 21:39:16 +00001244 Local precendece order.
Guido van Rossum98f33732002-11-25 21:36:54 +00001245 If A precedes B in C's MRO, then A will precede B in the MRO of all
1246 subclasses of C.
1247
1248 Monotonicity.
1249 The MRO of a class must be an extension without reordering of the
1250 MRO of each of its superclasses.
1251
1252 Extended Precedence Graph (EPG).
1253 Linearization is consistent if there is a path in the EPG from
1254 each class to all its successors in the linearization. See
1255 the paper for definition of EPG.
Guido van Rossum1f121312002-11-14 19:49:16 +00001256 */
1257
Tim Petersea7f75d2002-12-07 21:39:16 +00001258static int
Guido van Rossum1f121312002-11-14 19:49:16 +00001259tail_contains(PyObject *list, int whence, PyObject *o) {
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001260 Py_ssize_t j, size;
1261 size = PyList_GET_SIZE(list);
Guido van Rossum1f121312002-11-14 19:49:16 +00001262
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001263 for (j = whence+1; j < size; j++) {
1264 if (PyList_GET_ITEM(list, j) == o)
1265 return 1;
1266 }
1267 return 0;
Guido van Rossum1f121312002-11-14 19:49:16 +00001268}
1269
Guido van Rossum98f33732002-11-25 21:36:54 +00001270static PyObject *
1271class_name(PyObject *cls)
1272{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001273 PyObject *name = PyObject_GetAttrString(cls, "__name__");
1274 if (name == NULL) {
1275 PyErr_Clear();
1276 Py_XDECREF(name);
1277 name = PyObject_Repr(cls);
1278 }
1279 if (name == NULL)
1280 return NULL;
1281 if (!PyUnicode_Check(name)) {
1282 Py_DECREF(name);
1283 return NULL;
1284 }
1285 return name;
Guido van Rossum98f33732002-11-25 21:36:54 +00001286}
1287
1288static int
1289check_duplicates(PyObject *list)
1290{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001291 Py_ssize_t i, j, n;
1292 /* Let's use a quadratic time algorithm,
1293 assuming that the bases lists is short.
1294 */
1295 n = PyList_GET_SIZE(list);
1296 for (i = 0; i < n; i++) {
1297 PyObject *o = PyList_GET_ITEM(list, i);
1298 for (j = i + 1; j < n; j++) {
1299 if (PyList_GET_ITEM(list, j) == o) {
1300 o = class_name(o);
1301 if (o != NULL) {
1302 PyErr_Format(PyExc_TypeError,
1303 "duplicate base class %U",
1304 o);
1305 Py_DECREF(o);
1306 } else {
1307 PyErr_SetString(PyExc_TypeError,
1308 "duplicate base class");
1309 }
1310 return -1;
1311 }
1312 }
1313 }
1314 return 0;
Guido van Rossum98f33732002-11-25 21:36:54 +00001315}
1316
1317/* Raise a TypeError for an MRO order disagreement.
1318
1319 It's hard to produce a good error message. In the absence of better
1320 insight into error reporting, report the classes that were candidates
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001321 to be put next into the MRO. There is some conflict between the
Guido van Rossum98f33732002-11-25 21:36:54 +00001322 order in which they should be put in the MRO, but it's hard to
1323 diagnose what constraint can't be satisfied.
1324*/
1325
1326static void
1327set_mro_error(PyObject *to_merge, int *remain)
1328{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001329 Py_ssize_t i, n, off, to_merge_size;
1330 char buf[1000];
1331 PyObject *k, *v;
1332 PyObject *set = PyDict_New();
1333 if (!set) return;
Guido van Rossum98f33732002-11-25 21:36:54 +00001334
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001335 to_merge_size = PyList_GET_SIZE(to_merge);
1336 for (i = 0; i < to_merge_size; i++) {
1337 PyObject *L = PyList_GET_ITEM(to_merge, i);
1338 if (remain[i] < PyList_GET_SIZE(L)) {
1339 PyObject *c = PyList_GET_ITEM(L, remain[i]);
1340 if (PyDict_SetItem(set, c, Py_None) < 0) {
1341 Py_DECREF(set);
1342 return;
1343 }
1344 }
1345 }
1346 n = PyDict_Size(set);
Guido van Rossum98f33732002-11-25 21:36:54 +00001347
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001348 off = PyOS_snprintf(buf, sizeof(buf), "Cannot create a \
Raymond Hettingerf394df42003-04-06 19:13:41 +00001349consistent method resolution\norder (MRO) for bases");
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001350 i = 0;
1351 while (PyDict_Next(set, &i, &k, &v) && (size_t)off < sizeof(buf)) {
1352 PyObject *name = class_name(k);
1353 off += PyOS_snprintf(buf + off, sizeof(buf) - off, " %s",
1354 name ? _PyUnicode_AsString(name) : "?");
1355 Py_XDECREF(name);
1356 if (--n && (size_t)(off+1) < sizeof(buf)) {
1357 buf[off++] = ',';
1358 buf[off] = '\0';
1359 }
1360 }
1361 PyErr_SetString(PyExc_TypeError, buf);
1362 Py_DECREF(set);
Guido van Rossum98f33732002-11-25 21:36:54 +00001363}
1364
Tim Petersea7f75d2002-12-07 21:39:16 +00001365static int
Guido van Rossum1f121312002-11-14 19:49:16 +00001366pmerge(PyObject *acc, PyObject* to_merge) {
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001367 Py_ssize_t i, j, to_merge_size, empty_cnt;
1368 int *remain;
1369 int ok;
Tim Petersea7f75d2002-12-07 21:39:16 +00001370
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001371 to_merge_size = PyList_GET_SIZE(to_merge);
Guido van Rossum1f121312002-11-14 19:49:16 +00001372
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001373 /* remain stores an index into each sublist of to_merge.
1374 remain[i] is the index of the next base in to_merge[i]
1375 that is not included in acc.
1376 */
1377 remain = (int *)PyMem_MALLOC(SIZEOF_INT*to_merge_size);
1378 if (remain == NULL)
1379 return -1;
1380 for (i = 0; i < to_merge_size; i++)
1381 remain[i] = 0;
Guido van Rossum1f121312002-11-14 19:49:16 +00001382
1383 again:
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001384 empty_cnt = 0;
1385 for (i = 0; i < to_merge_size; i++) {
1386 PyObject *candidate;
Tim Petersea7f75d2002-12-07 21:39:16 +00001387
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001388 PyObject *cur_list = PyList_GET_ITEM(to_merge, i);
Guido van Rossum1f121312002-11-14 19:49:16 +00001389
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001390 if (remain[i] >= PyList_GET_SIZE(cur_list)) {
1391 empty_cnt++;
1392 continue;
1393 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001394
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001395 /* Choose next candidate for MRO.
Guido van Rossum98f33732002-11-25 21:36:54 +00001396
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001397 The input sequences alone can determine the choice.
1398 If not, choose the class which appears in the MRO
1399 of the earliest direct superclass of the new class.
1400 */
Guido van Rossum98f33732002-11-25 21:36:54 +00001401
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001402 candidate = PyList_GET_ITEM(cur_list, remain[i]);
1403 for (j = 0; j < to_merge_size; j++) {
1404 PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
1405 if (tail_contains(j_lst, remain[j], candidate)) {
1406 goto skip; /* continue outer loop */
1407 }
1408 }
1409 ok = PyList_Append(acc, candidate);
1410 if (ok < 0) {
1411 PyMem_Free(remain);
1412 return -1;
1413 }
1414 for (j = 0; j < to_merge_size; j++) {
1415 PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
1416 if (remain[j] < PyList_GET_SIZE(j_lst) &&
1417 PyList_GET_ITEM(j_lst, remain[j]) == candidate) {
1418 remain[j]++;
1419 }
1420 }
1421 goto again;
1422 skip: ;
1423 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001424
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001425 if (empty_cnt == to_merge_size) {
1426 PyMem_FREE(remain);
1427 return 0;
1428 }
1429 set_mro_error(to_merge, remain);
1430 PyMem_FREE(remain);
1431 return -1;
Guido van Rossum1f121312002-11-14 19:49:16 +00001432}
1433
Tim Peters6d6c1a32001-08-02 04:15:00 +00001434static PyObject *
1435mro_implementation(PyTypeObject *type)
1436{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001437 Py_ssize_t i, n;
1438 int ok;
1439 PyObject *bases, *result;
1440 PyObject *to_merge, *bases_aslist;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001441
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001442 if (type->tp_dict == NULL) {
1443 if (PyType_Ready(type) < 0)
1444 return NULL;
1445 }
Guido van Rossum63517572002-06-18 16:44:57 +00001446
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001447 /* Find a superclass linearization that honors the constraints
1448 of the explicit lists of bases and the constraints implied by
1449 each base class.
Guido van Rossum98f33732002-11-25 21:36:54 +00001450
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001451 to_merge is a list of lists, where each list is a superclass
1452 linearization implied by a base class. The last element of
1453 to_merge is the declared list of bases.
1454 */
Guido van Rossum98f33732002-11-25 21:36:54 +00001455
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001456 bases = type->tp_bases;
1457 n = PyTuple_GET_SIZE(bases);
Guido van Rossum1f121312002-11-14 19:49:16 +00001458
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001459 to_merge = PyList_New(n+1);
1460 if (to_merge == NULL)
1461 return NULL;
Guido van Rossum1f121312002-11-14 19:49:16 +00001462
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001463 for (i = 0; i < n; i++) {
1464 PyObject *base = PyTuple_GET_ITEM(bases, i);
1465 PyObject *parentMRO;
1466 parentMRO = PySequence_List(((PyTypeObject*)base)->tp_mro);
1467 if (parentMRO == NULL) {
1468 Py_DECREF(to_merge);
1469 return NULL;
1470 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001471
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001472 PyList_SET_ITEM(to_merge, i, parentMRO);
1473 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001474
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001475 bases_aslist = PySequence_List(bases);
1476 if (bases_aslist == NULL) {
1477 Py_DECREF(to_merge);
1478 return NULL;
1479 }
1480 /* This is just a basic sanity check. */
1481 if (check_duplicates(bases_aslist) < 0) {
1482 Py_DECREF(to_merge);
1483 Py_DECREF(bases_aslist);
1484 return NULL;
1485 }
1486 PyList_SET_ITEM(to_merge, n, bases_aslist);
Guido van Rossum1f121312002-11-14 19:49:16 +00001487
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001488 result = Py_BuildValue("[O]", (PyObject *)type);
1489 if (result == NULL) {
1490 Py_DECREF(to_merge);
1491 return NULL;
1492 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001493
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001494 ok = pmerge(result, to_merge);
1495 Py_DECREF(to_merge);
1496 if (ok < 0) {
1497 Py_DECREF(result);
1498 return NULL;
1499 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001500
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001501 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001502}
1503
1504static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001505mro_external(PyObject *self)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001506{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001507 PyTypeObject *type = (PyTypeObject *)self;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001508
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001509 return mro_implementation(type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001510}
1511
1512static int
1513mro_internal(PyTypeObject *type)
1514{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001515 PyObject *mro, *result, *tuple;
1516 int checkit = 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001517
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001518 if (Py_TYPE(type) == &PyType_Type) {
1519 result = mro_implementation(type);
1520 }
1521 else {
1522 static PyObject *mro_str;
1523 checkit = 1;
1524 mro = lookup_method((PyObject *)type, "mro", &mro_str);
1525 if (mro == NULL)
1526 return -1;
1527 result = PyObject_CallObject(mro, NULL);
1528 Py_DECREF(mro);
1529 }
1530 if (result == NULL)
1531 return -1;
1532 tuple = PySequence_Tuple(result);
1533 Py_DECREF(result);
1534 if (tuple == NULL)
1535 return -1;
1536 if (checkit) {
1537 Py_ssize_t i, len;
1538 PyObject *cls;
1539 PyTypeObject *solid;
Armin Rigo037d1e02005-12-29 17:07:39 +00001540
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001541 solid = solid_base(type);
Armin Rigo037d1e02005-12-29 17:07:39 +00001542
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001543 len = PyTuple_GET_SIZE(tuple);
Armin Rigo037d1e02005-12-29 17:07:39 +00001544
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001545 for (i = 0; i < len; i++) {
1546 PyTypeObject *t;
1547 cls = PyTuple_GET_ITEM(tuple, i);
1548 if (!PyType_Check(cls)) {
1549 PyErr_Format(PyExc_TypeError,
1550 "mro() returned a non-class ('%.500s')",
1551 Py_TYPE(cls)->tp_name);
1552 Py_DECREF(tuple);
1553 return -1;
1554 }
1555 t = (PyTypeObject*)cls;
1556 if (!PyType_IsSubtype(solid, solid_base(t))) {
1557 PyErr_Format(PyExc_TypeError,
1558 "mro() returned base with unsuitable layout ('%.500s')",
1559 t->tp_name);
1560 Py_DECREF(tuple);
1561 return -1;
1562 }
1563 }
1564 }
1565 type->tp_mro = tuple;
Christian Heimesa62da1d2008-01-12 19:39:10 +00001566
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001567 type_mro_modified(type, type->tp_mro);
1568 /* corner case: the old-style super class might have been hidden
1569 from the custom MRO */
1570 type_mro_modified(type, type->tp_bases);
Christian Heimesa62da1d2008-01-12 19:39:10 +00001571
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001572 PyType_Modified(type);
Christian Heimesa62da1d2008-01-12 19:39:10 +00001573
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001574 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001575}
1576
1577
1578/* Calculate the best base amongst multiple base classes.
1579 This is the first one that's on the path to the "solid base". */
1580
1581static PyTypeObject *
1582best_base(PyObject *bases)
1583{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001584 Py_ssize_t i, n;
1585 PyTypeObject *base, *winner, *candidate, *base_i;
1586 PyObject *base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001587
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001588 assert(PyTuple_Check(bases));
1589 n = PyTuple_GET_SIZE(bases);
1590 assert(n > 0);
1591 base = NULL;
1592 winner = NULL;
1593 for (i = 0; i < n; i++) {
1594 base_proto = PyTuple_GET_ITEM(bases, i);
1595 if (!PyType_Check(base_proto)) {
1596 PyErr_SetString(
1597 PyExc_TypeError,
1598 "bases must be types");
1599 return NULL;
1600 }
1601 base_i = (PyTypeObject *)base_proto;
1602 if (base_i->tp_dict == NULL) {
1603 if (PyType_Ready(base_i) < 0)
1604 return NULL;
1605 }
1606 candidate = solid_base(base_i);
1607 if (winner == NULL) {
1608 winner = candidate;
1609 base = base_i;
1610 }
1611 else if (PyType_IsSubtype(winner, candidate))
1612 ;
1613 else if (PyType_IsSubtype(candidate, winner)) {
1614 winner = candidate;
1615 base = base_i;
1616 }
1617 else {
1618 PyErr_SetString(
1619 PyExc_TypeError,
1620 "multiple bases have "
1621 "instance lay-out conflict");
1622 return NULL;
1623 }
1624 }
1625 if (base == NULL)
1626 PyErr_SetString(PyExc_TypeError,
1627 "a new-style class can't have only classic bases");
1628 return base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001629}
1630
1631static int
1632extra_ivars(PyTypeObject *type, PyTypeObject *base)
1633{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001634 size_t t_size = type->tp_basicsize;
1635 size_t b_size = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001636
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001637 assert(t_size >= b_size); /* Else type smaller than base! */
1638 if (type->tp_itemsize || base->tp_itemsize) {
1639 /* If itemsize is involved, stricter rules */
1640 return t_size != b_size ||
1641 type->tp_itemsize != base->tp_itemsize;
1642 }
1643 if (type->tp_weaklistoffset && base->tp_weaklistoffset == 0 &&
1644 type->tp_weaklistoffset + sizeof(PyObject *) == t_size &&
1645 type->tp_flags & Py_TPFLAGS_HEAPTYPE)
1646 t_size -= sizeof(PyObject *);
1647 if (type->tp_dictoffset && base->tp_dictoffset == 0 &&
1648 type->tp_dictoffset + sizeof(PyObject *) == t_size &&
1649 type->tp_flags & Py_TPFLAGS_HEAPTYPE)
1650 t_size -= sizeof(PyObject *);
Guido van Rossum9676b222001-08-17 20:32:36 +00001651
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001652 return t_size != b_size;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001653}
1654
1655static PyTypeObject *
1656solid_base(PyTypeObject *type)
1657{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001658 PyTypeObject *base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001659
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001660 if (type->tp_base)
1661 base = solid_base(type->tp_base);
1662 else
1663 base = &PyBaseObject_Type;
1664 if (extra_ivars(type, base))
1665 return type;
1666 else
1667 return base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001668}
1669
Jeremy Hylton938ace62002-07-17 16:30:39 +00001670static void object_dealloc(PyObject *);
1671static int object_init(PyObject *, PyObject *, PyObject *);
1672static int update_slot(PyTypeObject *, PyObject *);
1673static void fixup_slot_dispatchers(PyTypeObject *);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001674
Guido van Rossum360e4b82007-05-14 22:51:27 +00001675/*
1676 * Helpers for __dict__ descriptor. We don't want to expose the dicts
1677 * inherited from various builtin types. The builtin base usually provides
1678 * its own __dict__ descriptor, so we use that when we can.
1679 */
1680static PyTypeObject *
1681get_builtin_base_with_dict(PyTypeObject *type)
1682{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001683 while (type->tp_base != NULL) {
1684 if (type->tp_dictoffset != 0 &&
1685 !(type->tp_flags & Py_TPFLAGS_HEAPTYPE))
1686 return type;
1687 type = type->tp_base;
1688 }
1689 return NULL;
Guido van Rossum360e4b82007-05-14 22:51:27 +00001690}
1691
1692static PyObject *
1693get_dict_descriptor(PyTypeObject *type)
1694{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001695 static PyObject *dict_str;
1696 PyObject *descr;
Guido van Rossum360e4b82007-05-14 22:51:27 +00001697
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001698 if (dict_str == NULL) {
1699 dict_str = PyUnicode_InternFromString("__dict__");
1700 if (dict_str == NULL)
1701 return NULL;
1702 }
1703 descr = _PyType_Lookup(type, dict_str);
1704 if (descr == NULL || !PyDescr_IsData(descr))
1705 return NULL;
Guido van Rossum360e4b82007-05-14 22:51:27 +00001706
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001707 return descr;
Guido van Rossum360e4b82007-05-14 22:51:27 +00001708}
1709
1710static void
1711raise_dict_descr_error(PyObject *obj)
1712{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001713 PyErr_Format(PyExc_TypeError,
1714 "this __dict__ descriptor does not support "
1715 "'%.200s' objects", Py_TYPE(obj)->tp_name);
Guido van Rossum360e4b82007-05-14 22:51:27 +00001716}
1717
Tim Peters6d6c1a32001-08-02 04:15:00 +00001718static PyObject *
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001719subtype_dict(PyObject *obj, void *context)
1720{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001721 PyObject **dictptr;
1722 PyObject *dict;
1723 PyTypeObject *base;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001724
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001725 base = get_builtin_base_with_dict(Py_TYPE(obj));
1726 if (base != NULL) {
1727 descrgetfunc func;
1728 PyObject *descr = get_dict_descriptor(base);
1729 if (descr == NULL) {
1730 raise_dict_descr_error(obj);
1731 return NULL;
1732 }
1733 func = Py_TYPE(descr)->tp_descr_get;
1734 if (func == NULL) {
1735 raise_dict_descr_error(obj);
1736 return NULL;
1737 }
1738 return func(descr, obj, (PyObject *)(Py_TYPE(obj)));
1739 }
Guido van Rossum360e4b82007-05-14 22:51:27 +00001740
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001741 dictptr = _PyObject_GetDictPtr(obj);
1742 if (dictptr == NULL) {
1743 PyErr_SetString(PyExc_AttributeError,
1744 "This object has no __dict__");
1745 return NULL;
1746 }
1747 dict = *dictptr;
1748 if (dict == NULL)
1749 *dictptr = dict = PyDict_New();
1750 Py_XINCREF(dict);
1751 return dict;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001752}
1753
Guido van Rossum6661be32001-10-26 04:26:12 +00001754static int
1755subtype_setdict(PyObject *obj, PyObject *value, void *context)
1756{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001757 PyObject **dictptr;
1758 PyObject *dict;
1759 PyTypeObject *base;
Guido van Rossum6661be32001-10-26 04:26:12 +00001760
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001761 base = get_builtin_base_with_dict(Py_TYPE(obj));
1762 if (base != NULL) {
1763 descrsetfunc func;
1764 PyObject *descr = get_dict_descriptor(base);
1765 if (descr == NULL) {
1766 raise_dict_descr_error(obj);
1767 return -1;
1768 }
1769 func = Py_TYPE(descr)->tp_descr_set;
1770 if (func == NULL) {
1771 raise_dict_descr_error(obj);
1772 return -1;
1773 }
1774 return func(descr, obj, value);
1775 }
Guido van Rossum360e4b82007-05-14 22:51:27 +00001776
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001777 dictptr = _PyObject_GetDictPtr(obj);
1778 if (dictptr == NULL) {
1779 PyErr_SetString(PyExc_AttributeError,
1780 "This object has no __dict__");
1781 return -1;
1782 }
1783 if (value != NULL && !PyDict_Check(value)) {
1784 PyErr_Format(PyExc_TypeError,
1785 "__dict__ must be set to a dictionary, "
1786 "not a '%.200s'", Py_TYPE(value)->tp_name);
1787 return -1;
1788 }
1789 dict = *dictptr;
1790 Py_XINCREF(value);
1791 *dictptr = value;
1792 Py_XDECREF(dict);
1793 return 0;
Guido van Rossum6661be32001-10-26 04:26:12 +00001794}
1795
Guido van Rossumad47da02002-08-12 19:05:44 +00001796static PyObject *
1797subtype_getweakref(PyObject *obj, void *context)
1798{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001799 PyObject **weaklistptr;
1800 PyObject *result;
Guido van Rossumad47da02002-08-12 19:05:44 +00001801
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001802 if (Py_TYPE(obj)->tp_weaklistoffset == 0) {
1803 PyErr_SetString(PyExc_AttributeError,
1804 "This object has no __weakref__");
1805 return NULL;
1806 }
1807 assert(Py_TYPE(obj)->tp_weaklistoffset > 0);
1808 assert(Py_TYPE(obj)->tp_weaklistoffset + sizeof(PyObject *) <=
1809 (size_t)(Py_TYPE(obj)->tp_basicsize));
1810 weaklistptr = (PyObject **)
1811 ((char *)obj + Py_TYPE(obj)->tp_weaklistoffset);
1812 if (*weaklistptr == NULL)
1813 result = Py_None;
1814 else
1815 result = *weaklistptr;
1816 Py_INCREF(result);
1817 return result;
Guido van Rossumad47da02002-08-12 19:05:44 +00001818}
1819
Guido van Rossum373c7412003-01-07 13:41:37 +00001820/* Three variants on the subtype_getsets list. */
1821
1822static PyGetSetDef subtype_getsets_full[] = {
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001823 {"__dict__", subtype_dict, subtype_setdict,
1824 PyDoc_STR("dictionary for instance variables (if defined)")},
1825 {"__weakref__", subtype_getweakref, NULL,
1826 PyDoc_STR("list of weak references to the object (if defined)")},
1827 {0}
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001828};
1829
Guido van Rossum373c7412003-01-07 13:41:37 +00001830static PyGetSetDef subtype_getsets_dict_only[] = {
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001831 {"__dict__", subtype_dict, subtype_setdict,
1832 PyDoc_STR("dictionary for instance variables (if defined)")},
1833 {0}
Guido van Rossum373c7412003-01-07 13:41:37 +00001834};
1835
1836static PyGetSetDef subtype_getsets_weakref_only[] = {
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001837 {"__weakref__", subtype_getweakref, NULL,
1838 PyDoc_STR("list of weak references to the object (if defined)")},
1839 {0}
Guido van Rossum373c7412003-01-07 13:41:37 +00001840};
1841
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001842static int
1843valid_identifier(PyObject *s)
1844{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001845 if (!PyUnicode_Check(s)) {
1846 PyErr_Format(PyExc_TypeError,
1847 "__slots__ items must be strings, not '%.200s'",
1848 Py_TYPE(s)->tp_name);
1849 return 0;
1850 }
1851 if (!PyUnicode_IsIdentifier(s)) {
1852 PyErr_SetString(PyExc_TypeError,
1853 "__slots__ must be identifiers");
1854 return 0;
1855 }
1856 return 1;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001857}
1858
Guido van Rossumd8faa362007-04-27 19:54:29 +00001859/* Forward */
1860static int
1861object_init(PyObject *self, PyObject *args, PyObject *kwds);
1862
1863static int
1864type_init(PyObject *cls, PyObject *args, PyObject *kwds)
1865{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001866 int res;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001867
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001868 assert(args != NULL && PyTuple_Check(args));
1869 assert(kwds == NULL || PyDict_Check(kwds));
Guido van Rossumd8faa362007-04-27 19:54:29 +00001870
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001871 if (kwds != NULL && PyDict_Check(kwds) && PyDict_Size(kwds) != 0) {
1872 PyErr_SetString(PyExc_TypeError,
1873 "type.__init__() takes no keyword arguments");
1874 return -1;
1875 }
Guido van Rossumd8faa362007-04-27 19:54:29 +00001876
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001877 if (args != NULL && PyTuple_Check(args) &&
1878 (PyTuple_GET_SIZE(args) != 1 && PyTuple_GET_SIZE(args) != 3)) {
1879 PyErr_SetString(PyExc_TypeError,
1880 "type.__init__() takes 1 or 3 arguments");
1881 return -1;
1882 }
Guido van Rossumd8faa362007-04-27 19:54:29 +00001883
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001884 /* Call object.__init__(self) now. */
1885 /* XXX Could call super(type, cls).__init__() but what's the point? */
1886 args = PyTuple_GetSlice(args, 0, 0);
1887 res = object_init(cls, args, NULL);
1888 Py_DECREF(args);
1889 return res;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001890}
1891
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001892static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00001893type_new(PyTypeObject *metatype, PyObject *args, PyObject *kwds)
1894{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001895 PyObject *name, *bases, *dict;
1896 static char *kwlist[] = {"name", "bases", "dict", 0};
1897 PyObject *slots, *tmp, *newslots;
1898 PyTypeObject *type, *base, *tmptype, *winner;
1899 PyHeapTypeObject *et;
1900 PyMemberDef *mp;
1901 Py_ssize_t i, nbases, nslots, slotoffset, add_dict, add_weak;
1902 int j, may_add_dict, may_add_weak;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001903
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001904 assert(args != NULL && PyTuple_Check(args));
1905 assert(kwds == NULL || PyDict_Check(kwds));
Tim Peters3abca122001-10-27 19:37:48 +00001906
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001907 /* Special case: type(x) should return x->ob_type */
1908 {
1909 const Py_ssize_t nargs = PyTuple_GET_SIZE(args);
1910 const Py_ssize_t nkwds = kwds == NULL ? 0 : PyDict_Size(kwds);
Tim Peters3abca122001-10-27 19:37:48 +00001911
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001912 if (PyType_CheckExact(metatype) && nargs == 1 && nkwds == 0) {
1913 PyObject *x = PyTuple_GET_ITEM(args, 0);
1914 Py_INCREF(Py_TYPE(x));
1915 return (PyObject *) Py_TYPE(x);
1916 }
Tim Peters3abca122001-10-27 19:37:48 +00001917
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001918 /* SF bug 475327 -- if that didn't trigger, we need 3
1919 arguments. but PyArg_ParseTupleAndKeywords below may give
1920 a msg saying type() needs exactly 3. */
1921 if (nargs + nkwds != 3) {
1922 PyErr_SetString(PyExc_TypeError,
1923 "type() takes 1 or 3 arguments");
1924 return NULL;
1925 }
1926 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001927
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001928 /* Check arguments: (name, bases, dict) */
1929 if (!PyArg_ParseTupleAndKeywords(args, kwds, "UO!O!:type", kwlist,
1930 &name,
1931 &PyTuple_Type, &bases,
1932 &PyDict_Type, &dict))
1933 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001934
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001935 /* Determine the proper metatype to deal with this,
1936 and check for metatype conflicts while we're at it.
1937 Note that if some other metatype wins to contract,
1938 it's possible that its instances are not types. */
1939 nbases = PyTuple_GET_SIZE(bases);
1940 winner = metatype;
1941 for (i = 0; i < nbases; i++) {
1942 tmp = PyTuple_GET_ITEM(bases, i);
1943 tmptype = Py_TYPE(tmp);
1944 if (PyType_IsSubtype(winner, tmptype))
1945 continue;
1946 if (PyType_IsSubtype(tmptype, winner)) {
1947 winner = tmptype;
1948 continue;
1949 }
1950 PyErr_SetString(PyExc_TypeError,
1951 "metaclass conflict: "
1952 "the metaclass of a derived class "
1953 "must be a (non-strict) subclass "
1954 "of the metaclasses of all its bases");
1955 return NULL;
1956 }
1957 if (winner != metatype) {
1958 if (winner->tp_new != type_new) /* Pass it to the winner */
1959 return winner->tp_new(winner, args, kwds);
1960 metatype = winner;
1961 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001962
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001963 /* Adjust for empty tuple bases */
1964 if (nbases == 0) {
1965 bases = PyTuple_Pack(1, &PyBaseObject_Type);
1966 if (bases == NULL)
1967 return NULL;
1968 nbases = 1;
1969 }
1970 else
1971 Py_INCREF(bases);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001972
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001973 /* XXX From here until type is allocated, "return NULL" leaks bases! */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001974
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001975 /* Calculate best base, and check that all bases are type objects */
1976 base = best_base(bases);
1977 if (base == NULL) {
1978 Py_DECREF(bases);
1979 return NULL;
1980 }
1981 if (!PyType_HasFeature(base, Py_TPFLAGS_BASETYPE)) {
1982 PyErr_Format(PyExc_TypeError,
1983 "type '%.100s' is not an acceptable base type",
1984 base->tp_name);
1985 Py_DECREF(bases);
1986 return NULL;
1987 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001988
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001989 /* Check for a __slots__ sequence variable in dict, and count it */
1990 slots = PyDict_GetItemString(dict, "__slots__");
1991 nslots = 0;
1992 add_dict = 0;
1993 add_weak = 0;
1994 may_add_dict = base->tp_dictoffset == 0;
1995 may_add_weak = base->tp_weaklistoffset == 0 && base->tp_itemsize == 0;
1996 if (slots == NULL) {
1997 if (may_add_dict) {
1998 add_dict++;
1999 }
2000 if (may_add_weak) {
2001 add_weak++;
2002 }
2003 }
2004 else {
2005 /* Have slots */
Guido van Rossumad47da02002-08-12 19:05:44 +00002006
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002007 /* Make it into a tuple */
2008 if (PyUnicode_Check(slots))
2009 slots = PyTuple_Pack(1, slots);
2010 else
2011 slots = PySequence_Tuple(slots);
2012 if (slots == NULL) {
2013 Py_DECREF(bases);
2014 return NULL;
2015 }
2016 assert(PyTuple_Check(slots));
Guido van Rossumad47da02002-08-12 19:05:44 +00002017
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002018 /* Are slots allowed? */
2019 nslots = PyTuple_GET_SIZE(slots);
2020 if (nslots > 0 && base->tp_itemsize != 0) {
2021 PyErr_Format(PyExc_TypeError,
2022 "nonempty __slots__ "
2023 "not supported for subtype of '%s'",
2024 base->tp_name);
2025 bad_slots:
2026 Py_DECREF(bases);
2027 Py_DECREF(slots);
2028 return NULL;
2029 }
Guido van Rossumad47da02002-08-12 19:05:44 +00002030
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002031 /* Check for valid slot names and two special cases */
2032 for (i = 0; i < nslots; i++) {
2033 PyObject *tmp = PyTuple_GET_ITEM(slots, i);
2034 if (!valid_identifier(tmp))
2035 goto bad_slots;
2036 assert(PyUnicode_Check(tmp));
2037 if (PyUnicode_CompareWithASCIIString(tmp, "__dict__") == 0) {
2038 if (!may_add_dict || add_dict) {
2039 PyErr_SetString(PyExc_TypeError,
2040 "__dict__ slot disallowed: "
2041 "we already got one");
2042 goto bad_slots;
2043 }
2044 add_dict++;
2045 }
2046 if (PyUnicode_CompareWithASCIIString(tmp, "__weakref__") == 0) {
2047 if (!may_add_weak || add_weak) {
2048 PyErr_SetString(PyExc_TypeError,
2049 "__weakref__ slot disallowed: "
2050 "either we already got one, "
2051 "or __itemsize__ != 0");
2052 goto bad_slots;
2053 }
2054 add_weak++;
2055 }
2056 }
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00002057
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002058 /* Copy slots into a list, mangle names and sort them.
2059 Sorted names are needed for __class__ assignment.
2060 Convert them back to tuple at the end.
2061 */
2062 newslots = PyList_New(nslots - add_dict - add_weak);
2063 if (newslots == NULL)
2064 goto bad_slots;
2065 for (i = j = 0; i < nslots; i++) {
2066 tmp = PyTuple_GET_ITEM(slots, i);
2067 if ((add_dict &&
2068 PyUnicode_CompareWithASCIIString(tmp, "__dict__") == 0) ||
2069 (add_weak &&
2070 PyUnicode_CompareWithASCIIString(tmp, "__weakref__") == 0))
2071 continue;
2072 tmp =_Py_Mangle(name, tmp);
2073 if (!tmp)
2074 goto bad_slots;
2075 PyList_SET_ITEM(newslots, j, tmp);
2076 j++;
2077 }
2078 assert(j == nslots - add_dict - add_weak);
2079 nslots = j;
2080 Py_DECREF(slots);
2081 if (PyList_Sort(newslots) == -1) {
2082 Py_DECREF(bases);
2083 Py_DECREF(newslots);
2084 return NULL;
2085 }
2086 slots = PyList_AsTuple(newslots);
2087 Py_DECREF(newslots);
2088 if (slots == NULL) {
2089 Py_DECREF(bases);
2090 return NULL;
2091 }
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00002092
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002093 /* Secondary bases may provide weakrefs or dict */
2094 if (nbases > 1 &&
2095 ((may_add_dict && !add_dict) ||
2096 (may_add_weak && !add_weak))) {
2097 for (i = 0; i < nbases; i++) {
2098 tmp = PyTuple_GET_ITEM(bases, i);
2099 if (tmp == (PyObject *)base)
2100 continue; /* Skip primary base */
2101 assert(PyType_Check(tmp));
2102 tmptype = (PyTypeObject *)tmp;
2103 if (may_add_dict && !add_dict &&
2104 tmptype->tp_dictoffset != 0)
2105 add_dict++;
2106 if (may_add_weak && !add_weak &&
2107 tmptype->tp_weaklistoffset != 0)
2108 add_weak++;
2109 if (may_add_dict && !add_dict)
2110 continue;
2111 if (may_add_weak && !add_weak)
2112 continue;
2113 /* Nothing more to check */
2114 break;
2115 }
2116 }
2117 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002118
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002119 /* XXX From here until type is safely allocated,
2120 "return NULL" may leak slots! */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002121
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002122 /* Allocate the type object */
2123 type = (PyTypeObject *)metatype->tp_alloc(metatype, nslots);
2124 if (type == NULL) {
2125 Py_XDECREF(slots);
2126 Py_DECREF(bases);
2127 return NULL;
2128 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002129
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002130 /* Keep name and slots alive in the extended type object */
2131 et = (PyHeapTypeObject *)type;
2132 Py_INCREF(name);
2133 et->ht_name = name;
2134 et->ht_slots = slots;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002135
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002136 /* Initialize tp_flags */
2137 type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE |
2138 Py_TPFLAGS_BASETYPE;
2139 if (base->tp_flags & Py_TPFLAGS_HAVE_GC)
2140 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossumdc91b992001-08-08 22:26:22 +00002141
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002142 /* Initialize essential fields */
2143 type->tp_as_number = &et->as_number;
2144 type->tp_as_sequence = &et->as_sequence;
2145 type->tp_as_mapping = &et->as_mapping;
2146 type->tp_as_buffer = &et->as_buffer;
2147 type->tp_name = _PyUnicode_AsString(name);
2148 if (!type->tp_name) {
2149 Py_DECREF(type);
2150 return NULL;
2151 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002152
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002153 /* Set tp_base and tp_bases */
2154 type->tp_bases = bases;
2155 Py_INCREF(base);
2156 type->tp_base = base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002157
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002158 /* Initialize tp_dict from passed-in dict */
2159 type->tp_dict = dict = PyDict_Copy(dict);
2160 if (dict == NULL) {
2161 Py_DECREF(type);
2162 return NULL;
2163 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002164
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002165 /* Set __module__ in the dict */
2166 if (PyDict_GetItemString(dict, "__module__") == NULL) {
2167 tmp = PyEval_GetGlobals();
2168 if (tmp != NULL) {
2169 tmp = PyDict_GetItemString(tmp, "__name__");
2170 if (tmp != NULL) {
2171 if (PyDict_SetItemString(dict, "__module__",
2172 tmp) < 0)
2173 return NULL;
2174 }
2175 }
2176 }
Guido van Rossumc3542212001-08-16 09:18:56 +00002177
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002178 /* Set tp_doc to a copy of dict['__doc__'], if the latter is there
2179 and is a string. The __doc__ accessor will first look for tp_doc;
2180 if that fails, it will still look into __dict__.
2181 */
2182 {
2183 PyObject *doc = PyDict_GetItemString(dict, "__doc__");
2184 if (doc != NULL && PyUnicode_Check(doc)) {
2185 Py_ssize_t len;
2186 char *doc_str;
2187 char *tp_doc;
Alexandre Vassalottia85998a2008-05-03 18:24:43 +00002188
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002189 doc_str = _PyUnicode_AsString(doc);
2190 if (doc_str == NULL) {
2191 Py_DECREF(type);
2192 return NULL;
2193 }
2194 /* Silently truncate the docstring if it contains null bytes. */
2195 len = strlen(doc_str);
2196 tp_doc = (char *)PyObject_MALLOC(len + 1);
2197 if (tp_doc == NULL) {
2198 Py_DECREF(type);
2199 return NULL;
2200 }
2201 memcpy(tp_doc, doc_str, len + 1);
2202 type->tp_doc = tp_doc;
2203 }
2204 }
Tim Peters2f93e282001-10-04 05:27:00 +00002205
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002206 /* Special-case __new__: if it's a plain function,
2207 make it a static function */
2208 tmp = PyDict_GetItemString(dict, "__new__");
2209 if (tmp != NULL && PyFunction_Check(tmp)) {
2210 tmp = PyStaticMethod_New(tmp);
2211 if (tmp == NULL) {
2212 Py_DECREF(type);
2213 return NULL;
2214 }
2215 PyDict_SetItemString(dict, "__new__", tmp);
2216 Py_DECREF(tmp);
2217 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002218
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002219 /* Add descriptors for custom slots from __slots__, or for __dict__ */
2220 mp = PyHeapType_GET_MEMBERS(et);
2221 slotoffset = base->tp_basicsize;
2222 if (slots != NULL) {
2223 for (i = 0; i < nslots; i++, mp++) {
2224 mp->name = _PyUnicode_AsString(
2225 PyTuple_GET_ITEM(slots, i));
2226 mp->type = T_OBJECT_EX;
2227 mp->offset = slotoffset;
Guido van Rossumd8faa362007-04-27 19:54:29 +00002228
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002229 /* __dict__ and __weakref__ are already filtered out */
2230 assert(strcmp(mp->name, "__dict__") != 0);
2231 assert(strcmp(mp->name, "__weakref__") != 0);
Guido van Rossumd8faa362007-04-27 19:54:29 +00002232
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002233 slotoffset += sizeof(PyObject *);
2234 }
2235 }
2236 if (add_dict) {
2237 if (base->tp_itemsize)
2238 type->tp_dictoffset = -(long)sizeof(PyObject *);
2239 else
2240 type->tp_dictoffset = slotoffset;
2241 slotoffset += sizeof(PyObject *);
2242 }
2243 if (add_weak) {
2244 assert(!base->tp_itemsize);
2245 type->tp_weaklistoffset = slotoffset;
2246 slotoffset += sizeof(PyObject *);
2247 }
2248 type->tp_basicsize = slotoffset;
2249 type->tp_itemsize = base->tp_itemsize;
2250 type->tp_members = PyHeapType_GET_MEMBERS(et);
Guido van Rossum373c7412003-01-07 13:41:37 +00002251
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002252 if (type->tp_weaklistoffset && type->tp_dictoffset)
2253 type->tp_getset = subtype_getsets_full;
2254 else if (type->tp_weaklistoffset && !type->tp_dictoffset)
2255 type->tp_getset = subtype_getsets_weakref_only;
2256 else if (!type->tp_weaklistoffset && type->tp_dictoffset)
2257 type->tp_getset = subtype_getsets_dict_only;
2258 else
2259 type->tp_getset = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002260
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002261 /* Special case some slots */
2262 if (type->tp_dictoffset != 0 || nslots > 0) {
2263 if (base->tp_getattr == NULL && base->tp_getattro == NULL)
2264 type->tp_getattro = PyObject_GenericGetAttr;
2265 if (base->tp_setattr == NULL && base->tp_setattro == NULL)
2266 type->tp_setattro = PyObject_GenericSetAttr;
2267 }
2268 type->tp_dealloc = subtype_dealloc;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002269
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002270 /* Enable GC unless there are really no instance variables possible */
2271 if (!(type->tp_basicsize == sizeof(PyObject) &&
2272 type->tp_itemsize == 0))
2273 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossum9475a232001-10-05 20:51:39 +00002274
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002275 /* Always override allocation strategy to use regular heap */
2276 type->tp_alloc = PyType_GenericAlloc;
2277 if (type->tp_flags & Py_TPFLAGS_HAVE_GC) {
2278 type->tp_free = PyObject_GC_Del;
2279 type->tp_traverse = subtype_traverse;
2280 type->tp_clear = subtype_clear;
2281 }
2282 else
2283 type->tp_free = PyObject_Del;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002284
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002285 /* Initialize the rest */
2286 if (PyType_Ready(type) < 0) {
2287 Py_DECREF(type);
2288 return NULL;
2289 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002290
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002291 /* Put the proper slots in place */
2292 fixup_slot_dispatchers(type);
Guido van Rossumf040ede2001-08-07 16:40:56 +00002293
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002294 return (PyObject *)type;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002295}
2296
2297/* Internal API to look for a name through the MRO.
2298 This returns a borrowed reference, and doesn't set an exception! */
2299PyObject *
2300_PyType_Lookup(PyTypeObject *type, PyObject *name)
2301{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002302 Py_ssize_t i, n;
2303 PyObject *mro, *res, *base, *dict;
2304 unsigned int h;
Christian Heimesa62da1d2008-01-12 19:39:10 +00002305
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002306 if (MCACHE_CACHEABLE_NAME(name) &&
2307 PyType_HasFeature(type, Py_TPFLAGS_VALID_VERSION_TAG)) {
2308 /* fast path */
2309 h = MCACHE_HASH_METHOD(type, name);
2310 if (method_cache[h].version == type->tp_version_tag &&
2311 method_cache[h].name == name)
2312 return method_cache[h].value;
2313 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002314
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002315 /* Look in tp_dict of types in MRO */
2316 mro = type->tp_mro;
Guido van Rossum23094982002-06-10 14:30:43 +00002317
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002318 /* If mro is NULL, the type is either not yet initialized
2319 by PyType_Ready(), or already cleared by type_clear().
2320 Either way the safest thing to do is to return NULL. */
2321 if (mro == NULL)
2322 return NULL;
Guido van Rossum23094982002-06-10 14:30:43 +00002323
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002324 res = NULL;
2325 assert(PyTuple_Check(mro));
2326 n = PyTuple_GET_SIZE(mro);
2327 for (i = 0; i < n; i++) {
2328 base = PyTuple_GET_ITEM(mro, i);
2329 assert(PyType_Check(base));
2330 dict = ((PyTypeObject *)base)->tp_dict;
2331 assert(dict && PyDict_Check(dict));
2332 res = PyDict_GetItem(dict, name);
2333 if (res != NULL)
2334 break;
2335 }
Christian Heimesa62da1d2008-01-12 19:39:10 +00002336
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002337 if (MCACHE_CACHEABLE_NAME(name) && assign_version_tag(type)) {
2338 h = MCACHE_HASH_METHOD(type, name);
2339 method_cache[h].version = type->tp_version_tag;
2340 method_cache[h].value = res; /* borrowed */
2341 Py_INCREF(name);
2342 Py_DECREF(method_cache[h].name);
2343 method_cache[h].name = name;
2344 }
2345 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002346}
2347
2348/* This is similar to PyObject_GenericGetAttr(),
2349 but uses _PyType_Lookup() instead of just looking in type->tp_dict. */
2350static PyObject *
2351type_getattro(PyTypeObject *type, PyObject *name)
2352{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002353 PyTypeObject *metatype = Py_TYPE(type);
2354 PyObject *meta_attribute, *attribute;
2355 descrgetfunc meta_get;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002356
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002357 /* Initialize this type (we'll assume the metatype is initialized) */
2358 if (type->tp_dict == NULL) {
2359 if (PyType_Ready(type) < 0)
2360 return NULL;
2361 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002362
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002363 /* No readable descriptor found yet */
2364 meta_get = NULL;
Tim Peters34592512002-07-11 06:23:50 +00002365
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002366 /* Look for the attribute in the metatype */
2367 meta_attribute = _PyType_Lookup(metatype, name);
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002368
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002369 if (meta_attribute != NULL) {
2370 meta_get = Py_TYPE(meta_attribute)->tp_descr_get;
Tim Peters34592512002-07-11 06:23:50 +00002371
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002372 if (meta_get != NULL && PyDescr_IsData(meta_attribute)) {
2373 /* Data descriptors implement tp_descr_set to intercept
2374 * writes. Assume the attribute is not overridden in
2375 * type's tp_dict (and bases): call the descriptor now.
2376 */
2377 return meta_get(meta_attribute, (PyObject *)type,
2378 (PyObject *)metatype);
2379 }
2380 Py_INCREF(meta_attribute);
2381 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002382
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002383 /* No data descriptor found on metatype. Look in tp_dict of this
2384 * type and its bases */
2385 attribute = _PyType_Lookup(type, name);
2386 if (attribute != NULL) {
2387 /* Implement descriptor functionality, if any */
2388 descrgetfunc local_get = Py_TYPE(attribute)->tp_descr_get;
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00002389
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002390 Py_XDECREF(meta_attribute);
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00002391
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002392 if (local_get != NULL) {
2393 /* NULL 2nd argument indicates the descriptor was
2394 * found on the target object itself (or a base) */
2395 return local_get(attribute, (PyObject *)NULL,
2396 (PyObject *)type);
2397 }
Tim Peters34592512002-07-11 06:23:50 +00002398
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002399 Py_INCREF(attribute);
2400 return attribute;
2401 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002402
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002403 /* No attribute found in local __dict__ (or bases): use the
2404 * descriptor from the metatype, if any */
2405 if (meta_get != NULL) {
2406 PyObject *res;
2407 res = meta_get(meta_attribute, (PyObject *)type,
2408 (PyObject *)metatype);
2409 Py_DECREF(meta_attribute);
2410 return res;
2411 }
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002412
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002413 /* If an ordinary attribute was found on the metatype, return it now */
2414 if (meta_attribute != NULL) {
2415 return meta_attribute;
2416 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002417
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002418 /* Give up */
2419 PyErr_Format(PyExc_AttributeError,
2420 "type object '%.50s' has no attribute '%U'",
2421 type->tp_name, name);
2422 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002423}
2424
2425static int
2426type_setattro(PyTypeObject *type, PyObject *name, PyObject *value)
2427{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002428 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
2429 PyErr_Format(
2430 PyExc_TypeError,
2431 "can't set attributes of built-in/extension type '%s'",
2432 type->tp_name);
2433 return -1;
2434 }
2435 if (PyObject_GenericSetAttr((PyObject *)type, name, value) < 0)
2436 return -1;
2437 return update_slot(type, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002438}
2439
2440static void
2441type_dealloc(PyTypeObject *type)
2442{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002443 PyHeapTypeObject *et;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002444
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002445 /* Assert this is a heap-allocated type object */
2446 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
2447 _PyObject_GC_UNTRACK(type);
2448 PyObject_ClearWeakRefs((PyObject *)type);
2449 et = (PyHeapTypeObject *)type;
2450 Py_XDECREF(type->tp_base);
2451 Py_XDECREF(type->tp_dict);
2452 Py_XDECREF(type->tp_bases);
2453 Py_XDECREF(type->tp_mro);
2454 Py_XDECREF(type->tp_cache);
2455 Py_XDECREF(type->tp_subclasses);
2456 /* A type's tp_doc is heap allocated, unlike the tp_doc slots
2457 * of most other objects. It's okay to cast it to char *.
2458 */
2459 PyObject_Free((char *)type->tp_doc);
2460 Py_XDECREF(et->ht_name);
2461 Py_XDECREF(et->ht_slots);
2462 Py_TYPE(type)->tp_free((PyObject *)type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002463}
2464
Guido van Rossum1c450732001-10-08 15:18:27 +00002465static PyObject *
2466type_subclasses(PyTypeObject *type, PyObject *args_ignored)
2467{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002468 PyObject *list, *raw, *ref;
2469 Py_ssize_t i, n;
Guido van Rossum1c450732001-10-08 15:18:27 +00002470
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002471 list = PyList_New(0);
2472 if (list == NULL)
2473 return NULL;
2474 raw = type->tp_subclasses;
2475 if (raw == NULL)
2476 return list;
2477 assert(PyList_Check(raw));
2478 n = PyList_GET_SIZE(raw);
2479 for (i = 0; i < n; i++) {
2480 ref = PyList_GET_ITEM(raw, i);
2481 assert(PyWeakref_CheckRef(ref));
2482 ref = PyWeakref_GET_OBJECT(ref);
2483 if (ref != Py_None) {
2484 if (PyList_Append(list, ref) < 0) {
2485 Py_DECREF(list);
2486 return NULL;
2487 }
2488 }
2489 }
2490 return list;
Guido van Rossum1c450732001-10-08 15:18:27 +00002491}
2492
Guido van Rossum47374822007-08-02 16:48:17 +00002493static PyObject *
2494type_prepare(PyObject *self, PyObject *args, PyObject *kwds)
2495{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002496 return PyDict_New();
Guido van Rossum47374822007-08-02 16:48:17 +00002497}
2498
Tim Peters6d6c1a32001-08-02 04:15:00 +00002499static PyMethodDef type_methods[] = {
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002500 {"mro", (PyCFunction)mro_external, METH_NOARGS,
2501 PyDoc_STR("mro() -> list\nreturn a type's method resolution order")},
2502 {"__subclasses__", (PyCFunction)type_subclasses, METH_NOARGS,
2503 PyDoc_STR("__subclasses__() -> list of immediate subclasses")},
2504 {"__prepare__", (PyCFunction)type_prepare,
2505 METH_VARARGS | METH_KEYWORDS | METH_CLASS,
2506 PyDoc_STR("__prepare__() -> dict\n"
2507 "used to create the namespace for the class statement")},
2508 {"__instancecheck__", type___instancecheck__, METH_O,
2509 PyDoc_STR("__instancecheck__() -> check if an object is an instance")},
2510 {"__subclasscheck__", type___subclasscheck__, METH_O,
Alexander Belopolsky102594f2010-08-16 20:26:04 +00002511 PyDoc_STR("__subclasscheck__() -> check if a class is a subclass")},
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002512 {0}
Tim Peters6d6c1a32001-08-02 04:15:00 +00002513};
2514
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002515PyDoc_STRVAR(type_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00002516"type(object) -> the object's type\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002517"type(name, bases, dict) -> a new type");
Tim Peters6d6c1a32001-08-02 04:15:00 +00002518
Guido van Rossum048eb752001-10-02 21:24:57 +00002519static int
2520type_traverse(PyTypeObject *type, visitproc visit, void *arg)
2521{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002522 /* Because of type_is_gc(), the collector only calls this
2523 for heaptypes. */
2524 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002525
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002526 Py_VISIT(type->tp_dict);
2527 Py_VISIT(type->tp_cache);
2528 Py_VISIT(type->tp_mro);
2529 Py_VISIT(type->tp_bases);
2530 Py_VISIT(type->tp_base);
Guido van Rossuma3862092002-06-10 15:24:42 +00002531
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002532 /* There's no need to visit type->tp_subclasses or
2533 ((PyHeapTypeObject *)type)->ht_slots, because they can't be involved
2534 in cycles; tp_subclasses is a list of weak references,
2535 and slots is a tuple of strings. */
Guido van Rossum048eb752001-10-02 21:24:57 +00002536
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002537 return 0;
Guido van Rossum048eb752001-10-02 21:24:57 +00002538}
2539
2540static int
2541type_clear(PyTypeObject *type)
2542{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002543 /* Because of type_is_gc(), the collector only calls this
2544 for heaptypes. */
2545 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002546
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002547 /* The only field we need to clear is tp_mro, which is part of a
2548 hard cycle (its first element is the class itself) that won't
2549 be broken otherwise (it's a tuple and tuples don't have a
2550 tp_clear handler). None of the other fields need to be
2551 cleared, and here's why:
Guido van Rossum048eb752001-10-02 21:24:57 +00002552
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002553 tp_dict:
2554 It is a dict, so the collector will call its tp_clear.
Guido van Rossuma3862092002-06-10 15:24:42 +00002555
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002556 tp_cache:
2557 Not used; if it were, it would be a dict.
Guido van Rossuma3862092002-06-10 15:24:42 +00002558
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002559 tp_bases, tp_base:
2560 If these are involved in a cycle, there must be at least
2561 one other, mutable object in the cycle, e.g. a base
2562 class's dict; the cycle will be broken that way.
Guido van Rossuma3862092002-06-10 15:24:42 +00002563
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002564 tp_subclasses:
2565 A list of weak references can't be part of a cycle; and
2566 lists have their own tp_clear.
Guido van Rossuma3862092002-06-10 15:24:42 +00002567
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002568 slots (in PyHeapTypeObject):
2569 A tuple of strings can't be part of a cycle.
2570 */
Guido van Rossuma3862092002-06-10 15:24:42 +00002571
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002572 Py_CLEAR(type->tp_mro);
Guido van Rossum048eb752001-10-02 21:24:57 +00002573
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002574 return 0;
Guido van Rossum048eb752001-10-02 21:24:57 +00002575}
2576
2577static int
2578type_is_gc(PyTypeObject *type)
2579{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002580 return type->tp_flags & Py_TPFLAGS_HEAPTYPE;
Guido van Rossum048eb752001-10-02 21:24:57 +00002581}
2582
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002583PyTypeObject PyType_Type = {
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002584 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2585 "type", /* tp_name */
2586 sizeof(PyHeapTypeObject), /* tp_basicsize */
2587 sizeof(PyMemberDef), /* tp_itemsize */
2588 (destructor)type_dealloc, /* tp_dealloc */
2589 0, /* tp_print */
2590 0, /* tp_getattr */
2591 0, /* tp_setattr */
2592 0, /* tp_reserved */
2593 (reprfunc)type_repr, /* tp_repr */
2594 0, /* tp_as_number */
2595 0, /* tp_as_sequence */
2596 0, /* tp_as_mapping */
2597 0, /* tp_hash */
2598 (ternaryfunc)type_call, /* tp_call */
2599 0, /* tp_str */
2600 (getattrofunc)type_getattro, /* tp_getattro */
2601 (setattrofunc)type_setattro, /* tp_setattro */
2602 0, /* tp_as_buffer */
2603 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
2604 Py_TPFLAGS_BASETYPE | Py_TPFLAGS_TYPE_SUBCLASS, /* tp_flags */
2605 type_doc, /* tp_doc */
2606 (traverseproc)type_traverse, /* tp_traverse */
2607 (inquiry)type_clear, /* tp_clear */
2608 0, /* tp_richcompare */
2609 offsetof(PyTypeObject, tp_weaklist), /* tp_weaklistoffset */
2610 0, /* tp_iter */
2611 0, /* tp_iternext */
2612 type_methods, /* tp_methods */
2613 type_members, /* tp_members */
2614 type_getsets, /* tp_getset */
2615 0, /* tp_base */
2616 0, /* tp_dict */
2617 0, /* tp_descr_get */
2618 0, /* tp_descr_set */
2619 offsetof(PyTypeObject, tp_dict), /* tp_dictoffset */
2620 type_init, /* tp_init */
2621 0, /* tp_alloc */
2622 type_new, /* tp_new */
2623 PyObject_GC_Del, /* tp_free */
2624 (inquiry)type_is_gc, /* tp_is_gc */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002625};
Tim Peters6d6c1a32001-08-02 04:15:00 +00002626
2627
2628/* The base type of all types (eventually)... except itself. */
2629
Guido van Rossumd8faa362007-04-27 19:54:29 +00002630/* You may wonder why object.__new__() only complains about arguments
2631 when object.__init__() is not overridden, and vice versa.
2632
2633 Consider the use cases:
2634
2635 1. When neither is overridden, we want to hear complaints about
2636 excess (i.e., any) arguments, since their presence could
2637 indicate there's a bug.
2638
2639 2. When defining an Immutable type, we are likely to override only
2640 __new__(), since __init__() is called too late to initialize an
2641 Immutable object. Since __new__() defines the signature for the
2642 type, it would be a pain to have to override __init__() just to
2643 stop it from complaining about excess arguments.
2644
2645 3. When defining a Mutable type, we are likely to override only
2646 __init__(). So here the converse reasoning applies: we don't
2647 want to have to override __new__() just to stop it from
2648 complaining.
2649
2650 4. When __init__() is overridden, and the subclass __init__() calls
2651 object.__init__(), the latter should complain about excess
2652 arguments; ditto for __new__().
2653
2654 Use cases 2 and 3 make it unattractive to unconditionally check for
2655 excess arguments. The best solution that addresses all four use
2656 cases is as follows: __init__() complains about excess arguments
2657 unless __new__() is overridden and __init__() is not overridden
2658 (IOW, if __init__() is overridden or __new__() is not overridden);
2659 symmetrically, __new__() complains about excess arguments unless
2660 __init__() is overridden and __new__() is not overridden
2661 (IOW, if __new__() is overridden or __init__() is not overridden).
2662
2663 However, for backwards compatibility, this breaks too much code.
2664 Therefore, in 2.6, we'll *warn* about excess arguments when both
2665 methods are overridden; for all other cases we'll use the above
2666 rules.
2667
2668*/
2669
2670/* Forward */
2671static PyObject *
2672object_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
2673
2674static int
2675excess_args(PyObject *args, PyObject *kwds)
2676{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002677 return PyTuple_GET_SIZE(args) ||
2678 (kwds && PyDict_Check(kwds) && PyDict_Size(kwds));
Guido van Rossumd8faa362007-04-27 19:54:29 +00002679}
2680
Tim Peters6d6c1a32001-08-02 04:15:00 +00002681static int
2682object_init(PyObject *self, PyObject *args, PyObject *kwds)
2683{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002684 int err = 0;
2685 if (excess_args(args, kwds)) {
2686 PyTypeObject *type = Py_TYPE(self);
2687 if (type->tp_init != object_init &&
2688 type->tp_new != object_new)
2689 {
2690 err = PyErr_WarnEx(PyExc_DeprecationWarning,
2691 "object.__init__() takes no parameters",
2692 1);
2693 }
2694 else if (type->tp_init != object_init ||
2695 type->tp_new == object_new)
2696 {
2697 PyErr_SetString(PyExc_TypeError,
2698 "object.__init__() takes no parameters");
2699 err = -1;
2700 }
2701 }
2702 return err;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002703}
2704
Guido van Rossum298e4212003-02-13 16:30:16 +00002705static PyObject *
2706object_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2707{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002708 int err = 0;
2709 if (excess_args(args, kwds)) {
2710 if (type->tp_new != object_new &&
2711 type->tp_init != object_init)
2712 {
2713 err = PyErr_WarnEx(PyExc_DeprecationWarning,
2714 "object.__new__() takes no parameters",
2715 1);
2716 }
2717 else if (type->tp_new != object_new ||
2718 type->tp_init == object_init)
2719 {
2720 PyErr_SetString(PyExc_TypeError,
2721 "object.__new__() takes no parameters");
2722 err = -1;
2723 }
2724 }
2725 if (err < 0)
2726 return NULL;
Christian Heimes9e7f1d22008-02-28 12:27:11 +00002727
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002728 if (type->tp_flags & Py_TPFLAGS_IS_ABSTRACT) {
2729 static PyObject *comma = NULL;
2730 PyObject *abstract_methods = NULL;
2731 PyObject *builtins;
2732 PyObject *sorted;
2733 PyObject *sorted_methods = NULL;
2734 PyObject *joined = NULL;
Christian Heimes9e7f1d22008-02-28 12:27:11 +00002735
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002736 /* Compute ", ".join(sorted(type.__abstractmethods__))
2737 into joined. */
2738 abstract_methods = type_abstractmethods(type, NULL);
2739 if (abstract_methods == NULL)
2740 goto error;
2741 builtins = PyEval_GetBuiltins();
2742 if (builtins == NULL)
2743 goto error;
2744 sorted = PyDict_GetItemString(builtins, "sorted");
2745 if (sorted == NULL)
2746 goto error;
2747 sorted_methods = PyObject_CallFunctionObjArgs(sorted,
2748 abstract_methods,
2749 NULL);
2750 if (sorted_methods == NULL)
2751 goto error;
2752 if (comma == NULL) {
2753 comma = PyUnicode_InternFromString(", ");
2754 if (comma == NULL)
2755 goto error;
2756 }
2757 joined = PyObject_CallMethod(comma, "join",
2758 "O", sorted_methods);
2759 if (joined == NULL)
2760 goto error;
Christian Heimes9e7f1d22008-02-28 12:27:11 +00002761
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002762 PyErr_Format(PyExc_TypeError,
2763 "Can't instantiate abstract class %s "
2764 "with abstract methods %U",
2765 type->tp_name,
2766 joined);
2767 error:
2768 Py_XDECREF(joined);
2769 Py_XDECREF(sorted_methods);
2770 Py_XDECREF(abstract_methods);
2771 return NULL;
2772 }
2773 return type->tp_alloc(type, 0);
Guido van Rossum298e4212003-02-13 16:30:16 +00002774}
2775
Tim Peters6d6c1a32001-08-02 04:15:00 +00002776static void
2777object_dealloc(PyObject *self)
2778{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002779 Py_TYPE(self)->tp_free(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002780}
2781
Guido van Rossum8e248182001-08-12 05:17:56 +00002782static PyObject *
2783object_repr(PyObject *self)
2784{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002785 PyTypeObject *type;
2786 PyObject *mod, *name, *rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00002787
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002788 type = Py_TYPE(self);
2789 mod = type_module(type, NULL);
2790 if (mod == NULL)
2791 PyErr_Clear();
2792 else if (!PyUnicode_Check(mod)) {
2793 Py_DECREF(mod);
2794 mod = NULL;
2795 }
2796 name = type_name(type, NULL);
2797 if (name == NULL)
2798 return NULL;
2799 if (mod != NULL && PyUnicode_CompareWithASCIIString(mod, "builtins"))
2800 rtn = PyUnicode_FromFormat("<%U.%U object at %p>", mod, name, self);
2801 else
2802 rtn = PyUnicode_FromFormat("<%s object at %p>",
2803 type->tp_name, self);
2804 Py_XDECREF(mod);
2805 Py_DECREF(name);
2806 return rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00002807}
2808
Guido van Rossumb8f63662001-08-15 23:57:02 +00002809static PyObject *
2810object_str(PyObject *self)
2811{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002812 unaryfunc f;
Guido van Rossumb8f63662001-08-15 23:57:02 +00002813
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002814 f = Py_TYPE(self)->tp_repr;
2815 if (f == NULL)
2816 f = object_repr;
2817 return f(self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002818}
2819
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002820static PyObject *
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002821object_richcompare(PyObject *self, PyObject *other, int op)
2822{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002823 PyObject *res;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002824
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002825 switch (op) {
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002826
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002827 case Py_EQ:
2828 /* Return NotImplemented instead of False, so if two
2829 objects are compared, both get a chance at the
2830 comparison. See issue #1393. */
2831 res = (self == other) ? Py_True : Py_NotImplemented;
2832 Py_INCREF(res);
2833 break;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002834
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002835 case Py_NE:
2836 /* By default, != returns the opposite of ==,
2837 unless the latter returns NotImplemented. */
2838 res = PyObject_RichCompare(self, other, Py_EQ);
2839 if (res != NULL && res != Py_NotImplemented) {
2840 int ok = PyObject_IsTrue(res);
2841 Py_DECREF(res);
2842 if (ok < 0)
2843 res = NULL;
2844 else {
2845 if (ok)
2846 res = Py_False;
2847 else
2848 res = Py_True;
2849 Py_INCREF(res);
2850 }
2851 }
2852 break;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002853
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002854 default:
2855 res = Py_NotImplemented;
2856 Py_INCREF(res);
2857 break;
2858 }
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002859
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002860 return res;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002861}
2862
2863static PyObject *
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002864object_get_class(PyObject *self, void *closure)
2865{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002866 Py_INCREF(Py_TYPE(self));
2867 return (PyObject *)(Py_TYPE(self));
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002868}
2869
2870static int
2871equiv_structs(PyTypeObject *a, PyTypeObject *b)
2872{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002873 return a == b ||
2874 (a != NULL &&
2875 b != NULL &&
2876 a->tp_basicsize == b->tp_basicsize &&
2877 a->tp_itemsize == b->tp_itemsize &&
2878 a->tp_dictoffset == b->tp_dictoffset &&
2879 a->tp_weaklistoffset == b->tp_weaklistoffset &&
2880 ((a->tp_flags & Py_TPFLAGS_HAVE_GC) ==
2881 (b->tp_flags & Py_TPFLAGS_HAVE_GC)));
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002882}
2883
2884static int
2885same_slots_added(PyTypeObject *a, PyTypeObject *b)
2886{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002887 PyTypeObject *base = a->tp_base;
2888 Py_ssize_t size;
2889 PyObject *slots_a, *slots_b;
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002890
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002891 if (base != b->tp_base)
2892 return 0;
2893 if (equiv_structs(a, base) && equiv_structs(b, base))
2894 return 1;
2895 size = base->tp_basicsize;
2896 if (a->tp_dictoffset == size && b->tp_dictoffset == size)
2897 size += sizeof(PyObject *);
2898 if (a->tp_weaklistoffset == size && b->tp_weaklistoffset == size)
2899 size += sizeof(PyObject *);
Guido van Rossumd8faa362007-04-27 19:54:29 +00002900
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002901 /* Check slots compliance */
2902 slots_a = ((PyHeapTypeObject *)a)->ht_slots;
2903 slots_b = ((PyHeapTypeObject *)b)->ht_slots;
2904 if (slots_a && slots_b) {
2905 if (PyObject_RichCompareBool(slots_a, slots_b, Py_EQ) != 1)
2906 return 0;
2907 size += sizeof(PyObject *) * PyTuple_GET_SIZE(slots_a);
2908 }
2909 return size == a->tp_basicsize && size == b->tp_basicsize;
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002910}
2911
2912static int
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002913compatible_for_assignment(PyTypeObject* oldto, PyTypeObject* newto, char* attr)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002914{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002915 PyTypeObject *newbase, *oldbase;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002916
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002917 if (newto->tp_dealloc != oldto->tp_dealloc ||
2918 newto->tp_free != oldto->tp_free)
2919 {
2920 PyErr_Format(PyExc_TypeError,
2921 "%s assignment: "
2922 "'%s' deallocator differs from '%s'",
2923 attr,
2924 newto->tp_name,
2925 oldto->tp_name);
2926 return 0;
2927 }
2928 newbase = newto;
2929 oldbase = oldto;
2930 while (equiv_structs(newbase, newbase->tp_base))
2931 newbase = newbase->tp_base;
2932 while (equiv_structs(oldbase, oldbase->tp_base))
2933 oldbase = oldbase->tp_base;
2934 if (newbase != oldbase &&
2935 (newbase->tp_base != oldbase->tp_base ||
2936 !same_slots_added(newbase, oldbase))) {
2937 PyErr_Format(PyExc_TypeError,
2938 "%s assignment: "
2939 "'%s' object layout differs from '%s'",
2940 attr,
2941 newto->tp_name,
2942 oldto->tp_name);
2943 return 0;
2944 }
Tim Petersea7f75d2002-12-07 21:39:16 +00002945
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002946 return 1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002947}
2948
2949static int
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002950object_set_class(PyObject *self, PyObject *value, void *closure)
2951{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002952 PyTypeObject *oldto = Py_TYPE(self);
2953 PyTypeObject *newto;
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002954
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002955 if (value == NULL) {
2956 PyErr_SetString(PyExc_TypeError,
2957 "can't delete __class__ attribute");
2958 return -1;
2959 }
2960 if (!PyType_Check(value)) {
2961 PyErr_Format(PyExc_TypeError,
2962 "__class__ must be set to new-style class, not '%s' object",
2963 Py_TYPE(value)->tp_name);
2964 return -1;
2965 }
2966 newto = (PyTypeObject *)value;
2967 if (!(newto->tp_flags & Py_TPFLAGS_HEAPTYPE) ||
2968 !(oldto->tp_flags & Py_TPFLAGS_HEAPTYPE))
2969 {
2970 PyErr_Format(PyExc_TypeError,
2971 "__class__ assignment: only for heap types");
2972 return -1;
2973 }
2974 if (compatible_for_assignment(newto, oldto, "__class__")) {
2975 Py_INCREF(newto);
2976 Py_TYPE(self) = newto;
2977 Py_DECREF(oldto);
2978 return 0;
2979 }
2980 else {
2981 return -1;
2982 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002983}
2984
2985static PyGetSetDef object_getsets[] = {
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002986 {"__class__", object_get_class, object_set_class,
2987 PyDoc_STR("the object's class")},
2988 {0}
Tim Peters6d6c1a32001-08-02 04:15:00 +00002989};
2990
Guido van Rossumc53f0092003-02-18 22:05:12 +00002991
Guido van Rossum036f9992003-02-21 22:02:54 +00002992/* Stuff to implement __reduce_ex__ for pickle protocols >= 2.
Alexandre Vassalottif7fa63d2008-05-11 08:55:36 +00002993 We fall back to helpers in copyreg for:
Guido van Rossum036f9992003-02-21 22:02:54 +00002994 - pickle protocols < 2
2995 - calculating the list of slot names (done only once per class)
2996 - the __newobj__ function (which is used as a token but never called)
2997*/
2998
2999static PyObject *
Alexandre Vassalottif7fa63d2008-05-11 08:55:36 +00003000import_copyreg(void)
Guido van Rossum036f9992003-02-21 22:02:54 +00003001{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003002 static PyObject *copyreg_str;
Guido van Rossum3926a632001-09-25 16:25:58 +00003003
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003004 if (!copyreg_str) {
3005 copyreg_str = PyUnicode_InternFromString("copyreg");
3006 if (copyreg_str == NULL)
3007 return NULL;
3008 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003009
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003010 return PyImport_Import(copyreg_str);
Guido van Rossum036f9992003-02-21 22:02:54 +00003011}
3012
3013static PyObject *
3014slotnames(PyObject *cls)
3015{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003016 PyObject *clsdict;
3017 PyObject *copyreg;
3018 PyObject *slotnames;
Guido van Rossum036f9992003-02-21 22:02:54 +00003019
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003020 if (!PyType_Check(cls)) {
3021 Py_INCREF(Py_None);
3022 return Py_None;
3023 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003024
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003025 clsdict = ((PyTypeObject *)cls)->tp_dict;
3026 slotnames = PyDict_GetItemString(clsdict, "__slotnames__");
3027 if (slotnames != NULL && PyList_Check(slotnames)) {
3028 Py_INCREF(slotnames);
3029 return slotnames;
3030 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003031
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003032 copyreg = import_copyreg();
3033 if (copyreg == NULL)
3034 return NULL;
Guido van Rossum036f9992003-02-21 22:02:54 +00003035
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003036 slotnames = PyObject_CallMethod(copyreg, "_slotnames", "O", cls);
3037 Py_DECREF(copyreg);
3038 if (slotnames != NULL &&
3039 slotnames != Py_None &&
3040 !PyList_Check(slotnames))
3041 {
3042 PyErr_SetString(PyExc_TypeError,
3043 "copyreg._slotnames didn't return a list or None");
3044 Py_DECREF(slotnames);
3045 slotnames = NULL;
3046 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003047
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003048 return slotnames;
Guido van Rossum036f9992003-02-21 22:02:54 +00003049}
3050
3051static PyObject *
3052reduce_2(PyObject *obj)
3053{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003054 PyObject *cls, *getnewargs;
3055 PyObject *args = NULL, *args2 = NULL;
3056 PyObject *getstate = NULL, *state = NULL, *names = NULL;
3057 PyObject *slots = NULL, *listitems = NULL, *dictitems = NULL;
3058 PyObject *copyreg = NULL, *newobj = NULL, *res = NULL;
3059 Py_ssize_t i, n;
Guido van Rossum036f9992003-02-21 22:02:54 +00003060
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003061 cls = PyObject_GetAttrString(obj, "__class__");
3062 if (cls == NULL)
3063 return NULL;
Guido van Rossum036f9992003-02-21 22:02:54 +00003064
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003065 getnewargs = PyObject_GetAttrString(obj, "__getnewargs__");
3066 if (getnewargs != NULL) {
3067 args = PyObject_CallObject(getnewargs, NULL);
3068 Py_DECREF(getnewargs);
3069 if (args != NULL && !PyTuple_Check(args)) {
3070 PyErr_Format(PyExc_TypeError,
3071 "__getnewargs__ should return a tuple, "
3072 "not '%.200s'", Py_TYPE(args)->tp_name);
3073 goto end;
3074 }
3075 }
3076 else {
3077 PyErr_Clear();
3078 args = PyTuple_New(0);
3079 }
3080 if (args == NULL)
3081 goto end;
Guido van Rossum036f9992003-02-21 22:02:54 +00003082
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003083 getstate = PyObject_GetAttrString(obj, "__getstate__");
3084 if (getstate != NULL) {
3085 state = PyObject_CallObject(getstate, NULL);
3086 Py_DECREF(getstate);
3087 if (state == NULL)
3088 goto end;
3089 }
3090 else {
3091 PyErr_Clear();
3092 state = PyObject_GetAttrString(obj, "__dict__");
3093 if (state == NULL) {
3094 PyErr_Clear();
3095 state = Py_None;
3096 Py_INCREF(state);
3097 }
3098 names = slotnames(cls);
3099 if (names == NULL)
3100 goto end;
3101 if (names != Py_None) {
3102 assert(PyList_Check(names));
3103 slots = PyDict_New();
3104 if (slots == NULL)
3105 goto end;
3106 n = 0;
3107 /* Can't pre-compute the list size; the list
3108 is stored on the class so accessible to other
3109 threads, which may be run by DECREF */
3110 for (i = 0; i < PyList_GET_SIZE(names); i++) {
3111 PyObject *name, *value;
3112 name = PyList_GET_ITEM(names, i);
3113 value = PyObject_GetAttr(obj, name);
3114 if (value == NULL)
3115 PyErr_Clear();
3116 else {
3117 int err = PyDict_SetItem(slots, name,
3118 value);
3119 Py_DECREF(value);
3120 if (err)
3121 goto end;
3122 n++;
3123 }
3124 }
3125 if (n) {
3126 state = Py_BuildValue("(NO)", state, slots);
3127 if (state == NULL)
3128 goto end;
3129 }
3130 }
3131 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003132
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003133 if (!PyList_Check(obj)) {
3134 listitems = Py_None;
3135 Py_INCREF(listitems);
3136 }
3137 else {
3138 listitems = PyObject_GetIter(obj);
3139 if (listitems == NULL)
3140 goto end;
3141 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003142
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003143 if (!PyDict_Check(obj)) {
3144 dictitems = Py_None;
3145 Py_INCREF(dictitems);
3146 }
3147 else {
3148 PyObject *items = PyObject_CallMethod(obj, "items", "");
3149 if (items == NULL)
3150 goto end;
3151 dictitems = PyObject_GetIter(items);
3152 Py_DECREF(items);
3153 if (dictitems == NULL)
3154 goto end;
3155 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003156
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003157 copyreg = import_copyreg();
3158 if (copyreg == NULL)
3159 goto end;
3160 newobj = PyObject_GetAttrString(copyreg, "__newobj__");
3161 if (newobj == NULL)
3162 goto end;
Guido van Rossum036f9992003-02-21 22:02:54 +00003163
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003164 n = PyTuple_GET_SIZE(args);
3165 args2 = PyTuple_New(n+1);
3166 if (args2 == NULL)
3167 goto end;
3168 PyTuple_SET_ITEM(args2, 0, cls);
3169 cls = NULL;
3170 for (i = 0; i < n; i++) {
3171 PyObject *v = PyTuple_GET_ITEM(args, i);
3172 Py_INCREF(v);
3173 PyTuple_SET_ITEM(args2, i+1, v);
3174 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003175
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003176 res = PyTuple_Pack(5, newobj, args2, state, listitems, dictitems);
Guido van Rossum036f9992003-02-21 22:02:54 +00003177
3178 end:
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003179 Py_XDECREF(cls);
3180 Py_XDECREF(args);
3181 Py_XDECREF(args2);
3182 Py_XDECREF(slots);
3183 Py_XDECREF(state);
3184 Py_XDECREF(names);
3185 Py_XDECREF(listitems);
3186 Py_XDECREF(dictitems);
3187 Py_XDECREF(copyreg);
3188 Py_XDECREF(newobj);
3189 return res;
Guido van Rossum036f9992003-02-21 22:02:54 +00003190}
3191
Guido van Rossumd8faa362007-04-27 19:54:29 +00003192/*
3193 * There were two problems when object.__reduce__ and object.__reduce_ex__
3194 * were implemented in the same function:
3195 * - trying to pickle an object with a custom __reduce__ method that
3196 * fell back to object.__reduce__ in certain circumstances led to
3197 * infinite recursion at Python level and eventual RuntimeError.
3198 * - Pickling objects that lied about their type by overwriting the
3199 * __class__ descriptor could lead to infinite recursion at C level
3200 * and eventual segfault.
3201 *
3202 * Because of backwards compatibility, the two methods still have to
3203 * behave in the same way, even if this is not required by the pickle
3204 * protocol. This common functionality was moved to the _common_reduce
3205 * function.
3206 */
3207static PyObject *
3208_common_reduce(PyObject *self, int proto)
3209{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003210 PyObject *copyreg, *res;
Guido van Rossumd8faa362007-04-27 19:54:29 +00003211
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003212 if (proto >= 2)
3213 return reduce_2(self);
Guido van Rossumd8faa362007-04-27 19:54:29 +00003214
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003215 copyreg = import_copyreg();
3216 if (!copyreg)
3217 return NULL;
Guido van Rossumd8faa362007-04-27 19:54:29 +00003218
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003219 res = PyEval_CallMethod(copyreg, "_reduce_ex", "(Oi)", self, proto);
3220 Py_DECREF(copyreg);
Guido van Rossumd8faa362007-04-27 19:54:29 +00003221
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003222 return res;
Guido van Rossumd8faa362007-04-27 19:54:29 +00003223}
3224
3225static PyObject *
3226object_reduce(PyObject *self, PyObject *args)
3227{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003228 int proto = 0;
Guido van Rossumd8faa362007-04-27 19:54:29 +00003229
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003230 if (!PyArg_ParseTuple(args, "|i:__reduce__", &proto))
3231 return NULL;
Guido van Rossumd8faa362007-04-27 19:54:29 +00003232
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003233 return _common_reduce(self, proto);
Guido van Rossumd8faa362007-04-27 19:54:29 +00003234}
3235
Guido van Rossum036f9992003-02-21 22:02:54 +00003236static PyObject *
3237object_reduce_ex(PyObject *self, PyObject *args)
3238{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003239 PyObject *reduce, *res;
3240 int proto = 0;
Guido van Rossum036f9992003-02-21 22:02:54 +00003241
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003242 if (!PyArg_ParseTuple(args, "|i:__reduce_ex__", &proto))
3243 return NULL;
Guido van Rossum036f9992003-02-21 22:02:54 +00003244
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003245 reduce = PyObject_GetAttrString(self, "__reduce__");
3246 if (reduce == NULL)
3247 PyErr_Clear();
3248 else {
3249 PyObject *cls, *clsreduce, *objreduce;
3250 int override;
3251 cls = PyObject_GetAttrString(self, "__class__");
3252 if (cls == NULL) {
3253 Py_DECREF(reduce);
3254 return NULL;
3255 }
3256 clsreduce = PyObject_GetAttrString(cls, "__reduce__");
3257 Py_DECREF(cls);
3258 if (clsreduce == NULL) {
3259 Py_DECREF(reduce);
3260 return NULL;
3261 }
3262 objreduce = PyDict_GetItemString(PyBaseObject_Type.tp_dict,
3263 "__reduce__");
3264 override = (clsreduce != objreduce);
3265 Py_DECREF(clsreduce);
3266 if (override) {
3267 res = PyObject_CallObject(reduce, NULL);
3268 Py_DECREF(reduce);
3269 return res;
3270 }
3271 else
3272 Py_DECREF(reduce);
3273 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003274
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003275 return _common_reduce(self, proto);
Guido van Rossum3926a632001-09-25 16:25:58 +00003276}
3277
Christian Heimes9e7f1d22008-02-28 12:27:11 +00003278static PyObject *
3279object_subclasshook(PyObject *cls, PyObject *args)
3280{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003281 Py_INCREF(Py_NotImplemented);
3282 return Py_NotImplemented;
Christian Heimes9e7f1d22008-02-28 12:27:11 +00003283}
3284
3285PyDoc_STRVAR(object_subclasshook_doc,
3286"Abstract classes can override this to customize issubclass().\n"
3287"\n"
3288"This is invoked early on by abc.ABCMeta.__subclasscheck__().\n"
3289"It should return True, False or NotImplemented. If it returns\n"
3290"NotImplemented, the normal algorithm is used. Otherwise, it\n"
3291"overrides the normal algorithm (and the outcome is cached).\n");
Eric Smith8c663262007-08-25 02:26:07 +00003292
3293/*
3294 from PEP 3101, this code implements:
3295
3296 class object:
3297 def __format__(self, format_spec):
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003298 return format(str(self), format_spec)
Eric Smith8c663262007-08-25 02:26:07 +00003299*/
3300static PyObject *
3301object_format(PyObject *self, PyObject *args)
3302{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003303 PyObject *format_spec;
3304 PyObject *self_as_str = NULL;
3305 PyObject *result = NULL;
3306 PyObject *format_meth = NULL;
Eric Smith8c663262007-08-25 02:26:07 +00003307
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003308 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
3309 return NULL;
Eric Smith8c663262007-08-25 02:26:07 +00003310
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003311 self_as_str = PyObject_Str(self);
3312 if (self_as_str != NULL) {
3313 /* find the format function */
3314 format_meth = PyObject_GetAttrString(self_as_str, "__format__");
3315 if (format_meth != NULL) {
3316 /* and call it */
3317 result = PyObject_CallFunctionObjArgs(format_meth, format_spec, NULL);
Eric Smith8c663262007-08-25 02:26:07 +00003318 }
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003319 }
Eric Smith8c663262007-08-25 02:26:07 +00003320
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003321 Py_XDECREF(self_as_str);
3322 Py_XDECREF(format_meth);
Eric Smith8c663262007-08-25 02:26:07 +00003323
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003324 return result;
Eric Smith8c663262007-08-25 02:26:07 +00003325}
3326
Martin v. Löwis00709aa2008-06-04 14:18:43 +00003327static PyObject *
3328object_sizeof(PyObject *self, PyObject *args)
3329{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003330 Py_ssize_t res, isize;
Martin v. Löwis00709aa2008-06-04 14:18:43 +00003331
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003332 res = 0;
3333 isize = self->ob_type->tp_itemsize;
3334 if (isize > 0)
3335 res = Py_SIZE(self->ob_type) * isize;
3336 res += self->ob_type->tp_basicsize;
Martin v. Löwis00709aa2008-06-04 14:18:43 +00003337
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003338 return PyLong_FromSsize_t(res);
Martin v. Löwis00709aa2008-06-04 14:18:43 +00003339}
3340
Guido van Rossum3926a632001-09-25 16:25:58 +00003341static PyMethodDef object_methods[] = {
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003342 {"__reduce_ex__", object_reduce_ex, METH_VARARGS,
3343 PyDoc_STR("helper for pickle")},
3344 {"__reduce__", object_reduce, METH_VARARGS,
3345 PyDoc_STR("helper for pickle")},
3346 {"__subclasshook__", object_subclasshook, METH_CLASS | METH_VARARGS,
3347 object_subclasshook_doc},
3348 {"__format__", object_format, METH_VARARGS,
3349 PyDoc_STR("default object formatter")},
3350 {"__sizeof__", object_sizeof, METH_NOARGS,
3351 PyDoc_STR("__sizeof__() -> size of object in memory, in bytes")},
3352 {0}
Guido van Rossum3926a632001-09-25 16:25:58 +00003353};
3354
Guido van Rossum036f9992003-02-21 22:02:54 +00003355
Tim Peters6d6c1a32001-08-02 04:15:00 +00003356PyTypeObject PyBaseObject_Type = {
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003357 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3358 "object", /* tp_name */
3359 sizeof(PyObject), /* tp_basicsize */
3360 0, /* tp_itemsize */
3361 object_dealloc, /* tp_dealloc */
3362 0, /* tp_print */
3363 0, /* tp_getattr */
3364 0, /* tp_setattr */
3365 0, /* tp_reserved */
3366 object_repr, /* tp_repr */
3367 0, /* tp_as_number */
3368 0, /* tp_as_sequence */
3369 0, /* tp_as_mapping */
3370 (hashfunc)_Py_HashPointer, /* tp_hash */
3371 0, /* tp_call */
3372 object_str, /* tp_str */
3373 PyObject_GenericGetAttr, /* tp_getattro */
3374 PyObject_GenericSetAttr, /* tp_setattro */
3375 0, /* tp_as_buffer */
3376 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
3377 PyDoc_STR("The most base type"), /* tp_doc */
3378 0, /* tp_traverse */
3379 0, /* tp_clear */
3380 object_richcompare, /* tp_richcompare */
3381 0, /* tp_weaklistoffset */
3382 0, /* tp_iter */
3383 0, /* tp_iternext */
3384 object_methods, /* tp_methods */
3385 0, /* tp_members */
3386 object_getsets, /* tp_getset */
3387 0, /* tp_base */
3388 0, /* tp_dict */
3389 0, /* tp_descr_get */
3390 0, /* tp_descr_set */
3391 0, /* tp_dictoffset */
3392 object_init, /* tp_init */
3393 PyType_GenericAlloc, /* tp_alloc */
3394 object_new, /* tp_new */
3395 PyObject_Del, /* tp_free */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003396};
3397
3398
Guido van Rossum50e9fb92006-08-17 05:42:55 +00003399/* Add the methods from tp_methods to the __dict__ in a type object */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003400
3401static int
3402add_methods(PyTypeObject *type, PyMethodDef *meth)
3403{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003404 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003405
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003406 for (; meth->ml_name != NULL; meth++) {
3407 PyObject *descr;
3408 if (PyDict_GetItemString(dict, meth->ml_name) &&
3409 !(meth->ml_flags & METH_COEXIST))
3410 continue;
3411 if (meth->ml_flags & METH_CLASS) {
3412 if (meth->ml_flags & METH_STATIC) {
3413 PyErr_SetString(PyExc_ValueError,
3414 "method cannot be both class and static");
3415 return -1;
3416 }
3417 descr = PyDescr_NewClassMethod(type, meth);
3418 }
3419 else if (meth->ml_flags & METH_STATIC) {
3420 PyObject *cfunc = PyCFunction_New(meth, NULL);
3421 if (cfunc == NULL)
3422 return -1;
3423 descr = PyStaticMethod_New(cfunc);
3424 Py_DECREF(cfunc);
3425 }
3426 else {
3427 descr = PyDescr_NewMethod(type, meth);
3428 }
3429 if (descr == NULL)
3430 return -1;
3431 if (PyDict_SetItemString(dict, meth->ml_name, descr) < 0)
3432 return -1;
3433 Py_DECREF(descr);
3434 }
3435 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003436}
3437
3438static int
Guido van Rossum6f799372001-09-20 20:46:19 +00003439add_members(PyTypeObject *type, PyMemberDef *memb)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003440{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003441 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003442
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003443 for (; memb->name != NULL; memb++) {
3444 PyObject *descr;
3445 if (PyDict_GetItemString(dict, memb->name))
3446 continue;
3447 descr = PyDescr_NewMember(type, memb);
3448 if (descr == NULL)
3449 return -1;
3450 if (PyDict_SetItemString(dict, memb->name, descr) < 0)
3451 return -1;
3452 Py_DECREF(descr);
3453 }
3454 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003455}
3456
3457static int
Guido van Rossum32d34c82001-09-20 21:45:26 +00003458add_getset(PyTypeObject *type, PyGetSetDef *gsp)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003459{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003460 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003461
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003462 for (; gsp->name != NULL; gsp++) {
3463 PyObject *descr;
3464 if (PyDict_GetItemString(dict, gsp->name))
3465 continue;
3466 descr = PyDescr_NewGetSet(type, gsp);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003467
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003468 if (descr == NULL)
3469 return -1;
3470 if (PyDict_SetItemString(dict, gsp->name, descr) < 0)
3471 return -1;
3472 Py_DECREF(descr);
3473 }
3474 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003475}
3476
Guido van Rossum13d52f02001-08-10 21:24:08 +00003477static void
3478inherit_special(PyTypeObject *type, PyTypeObject *base)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003479{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003480 Py_ssize_t oldsize, newsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003481
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003482 /* Copying basicsize is connected to the GC flags */
3483 oldsize = base->tp_basicsize;
3484 newsize = type->tp_basicsize ? type->tp_basicsize : oldsize;
3485 if (!(type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
3486 (base->tp_flags & Py_TPFLAGS_HAVE_GC) &&
3487 (!type->tp_traverse && !type->tp_clear)) {
3488 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
3489 if (type->tp_traverse == NULL)
3490 type->tp_traverse = base->tp_traverse;
3491 if (type->tp_clear == NULL)
3492 type->tp_clear = base->tp_clear;
3493 }
3494 {
3495 /* The condition below could use some explanation.
3496 It appears that tp_new is not inherited for static types
3497 whose base class is 'object'; this seems to be a precaution
3498 so that old extension types don't suddenly become
3499 callable (object.__new__ wouldn't insure the invariants
3500 that the extension type's own factory function ensures).
3501 Heap types, of course, are under our control, so they do
3502 inherit tp_new; static extension types that specify some
3503 other built-in type as the default are considered
3504 new-style-aware so they also inherit object.__new__. */
3505 if (base != &PyBaseObject_Type ||
3506 (type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
3507 if (type->tp_new == NULL)
3508 type->tp_new = base->tp_new;
3509 }
3510 }
3511 type->tp_basicsize = newsize;
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00003512
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003513 /* Copy other non-function slots */
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00003514
3515#undef COPYVAL
3516#define COPYVAL(SLOT) \
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003517 if (type->SLOT == 0) type->SLOT = base->SLOT
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00003518
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003519 COPYVAL(tp_itemsize);
3520 COPYVAL(tp_weaklistoffset);
3521 COPYVAL(tp_dictoffset);
Thomas Wouters27d517b2007-02-25 20:39:11 +00003522
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003523 /* Setup fast subclass flags */
3524 if (PyType_IsSubtype(base, (PyTypeObject*)PyExc_BaseException))
3525 type->tp_flags |= Py_TPFLAGS_BASE_EXC_SUBCLASS;
3526 else if (PyType_IsSubtype(base, &PyType_Type))
3527 type->tp_flags |= Py_TPFLAGS_TYPE_SUBCLASS;
3528 else if (PyType_IsSubtype(base, &PyLong_Type))
3529 type->tp_flags |= Py_TPFLAGS_LONG_SUBCLASS;
3530 else if (PyType_IsSubtype(base, &PyBytes_Type))
3531 type->tp_flags |= Py_TPFLAGS_BYTES_SUBCLASS;
3532 else if (PyType_IsSubtype(base, &PyUnicode_Type))
3533 type->tp_flags |= Py_TPFLAGS_UNICODE_SUBCLASS;
3534 else if (PyType_IsSubtype(base, &PyTuple_Type))
3535 type->tp_flags |= Py_TPFLAGS_TUPLE_SUBCLASS;
3536 else if (PyType_IsSubtype(base, &PyList_Type))
3537 type->tp_flags |= Py_TPFLAGS_LIST_SUBCLASS;
3538 else if (PyType_IsSubtype(base, &PyDict_Type))
3539 type->tp_flags |= Py_TPFLAGS_DICT_SUBCLASS;
Guido van Rossum13d52f02001-08-10 21:24:08 +00003540}
3541
Guido van Rossumf5243f02008-01-01 04:06:48 +00003542static char *hash_name_op[] = {
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003543 "__eq__",
3544 "__hash__",
3545 NULL
Guido van Rossum38938152006-08-21 23:36:26 +00003546};
3547
3548static int
Guido van Rossumf5243f02008-01-01 04:06:48 +00003549overrides_hash(PyTypeObject *type)
Guido van Rossum38938152006-08-21 23:36:26 +00003550{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003551 char **p;
3552 PyObject *dict = type->tp_dict;
Guido van Rossum38938152006-08-21 23:36:26 +00003553
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003554 assert(dict != NULL);
3555 for (p = hash_name_op; *p; p++) {
3556 if (PyDict_GetItemString(dict, *p) != NULL)
3557 return 1;
3558 }
3559 return 0;
Guido van Rossum38938152006-08-21 23:36:26 +00003560}
3561
Guido van Rossum13d52f02001-08-10 21:24:08 +00003562static void
3563inherit_slots(PyTypeObject *type, PyTypeObject *base)
3564{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003565 PyTypeObject *basebase;
Guido van Rossum13d52f02001-08-10 21:24:08 +00003566
3567#undef SLOTDEFINED
Tim Peters6d6c1a32001-08-02 04:15:00 +00003568#undef COPYSLOT
3569#undef COPYNUM
3570#undef COPYSEQ
3571#undef COPYMAP
Guido van Rossum5af588b2001-10-12 14:13:21 +00003572#undef COPYBUF
Guido van Rossum13d52f02001-08-10 21:24:08 +00003573
3574#define SLOTDEFINED(SLOT) \
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003575 (base->SLOT != 0 && \
3576 (basebase == NULL || base->SLOT != basebase->SLOT))
Guido van Rossum13d52f02001-08-10 21:24:08 +00003577
Tim Peters6d6c1a32001-08-02 04:15:00 +00003578#define COPYSLOT(SLOT) \
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003579 if (!type->SLOT && SLOTDEFINED(SLOT)) type->SLOT = base->SLOT
Tim Peters6d6c1a32001-08-02 04:15:00 +00003580
3581#define COPYNUM(SLOT) COPYSLOT(tp_as_number->SLOT)
3582#define COPYSEQ(SLOT) COPYSLOT(tp_as_sequence->SLOT)
3583#define COPYMAP(SLOT) COPYSLOT(tp_as_mapping->SLOT)
Tim Petersfc57ccb2001-10-12 02:38:24 +00003584#define COPYBUF(SLOT) COPYSLOT(tp_as_buffer->SLOT)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003585
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003586 /* This won't inherit indirect slots (from tp_as_number etc.)
3587 if type doesn't provide the space. */
Guido van Rossum13d52f02001-08-10 21:24:08 +00003588
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003589 if (type->tp_as_number != NULL && base->tp_as_number != NULL) {
3590 basebase = base->tp_base;
3591 if (basebase->tp_as_number == NULL)
3592 basebase = NULL;
3593 COPYNUM(nb_add);
3594 COPYNUM(nb_subtract);
3595 COPYNUM(nb_multiply);
3596 COPYNUM(nb_remainder);
3597 COPYNUM(nb_divmod);
3598 COPYNUM(nb_power);
3599 COPYNUM(nb_negative);
3600 COPYNUM(nb_positive);
3601 COPYNUM(nb_absolute);
3602 COPYNUM(nb_bool);
3603 COPYNUM(nb_invert);
3604 COPYNUM(nb_lshift);
3605 COPYNUM(nb_rshift);
3606 COPYNUM(nb_and);
3607 COPYNUM(nb_xor);
3608 COPYNUM(nb_or);
3609 COPYNUM(nb_int);
3610 COPYNUM(nb_float);
3611 COPYNUM(nb_inplace_add);
3612 COPYNUM(nb_inplace_subtract);
3613 COPYNUM(nb_inplace_multiply);
3614 COPYNUM(nb_inplace_remainder);
3615 COPYNUM(nb_inplace_power);
3616 COPYNUM(nb_inplace_lshift);
3617 COPYNUM(nb_inplace_rshift);
3618 COPYNUM(nb_inplace_and);
3619 COPYNUM(nb_inplace_xor);
3620 COPYNUM(nb_inplace_or);
3621 COPYNUM(nb_true_divide);
3622 COPYNUM(nb_floor_divide);
3623 COPYNUM(nb_inplace_true_divide);
3624 COPYNUM(nb_inplace_floor_divide);
3625 COPYNUM(nb_index);
3626 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003627
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003628 if (type->tp_as_sequence != NULL && base->tp_as_sequence != NULL) {
3629 basebase = base->tp_base;
3630 if (basebase->tp_as_sequence == NULL)
3631 basebase = NULL;
3632 COPYSEQ(sq_length);
3633 COPYSEQ(sq_concat);
3634 COPYSEQ(sq_repeat);
3635 COPYSEQ(sq_item);
3636 COPYSEQ(sq_ass_item);
3637 COPYSEQ(sq_contains);
3638 COPYSEQ(sq_inplace_concat);
3639 COPYSEQ(sq_inplace_repeat);
3640 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003641
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003642 if (type->tp_as_mapping != NULL && base->tp_as_mapping != NULL) {
3643 basebase = base->tp_base;
3644 if (basebase->tp_as_mapping == NULL)
3645 basebase = NULL;
3646 COPYMAP(mp_length);
3647 COPYMAP(mp_subscript);
3648 COPYMAP(mp_ass_subscript);
3649 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003650
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003651 if (type->tp_as_buffer != NULL && base->tp_as_buffer != NULL) {
3652 basebase = base->tp_base;
3653 if (basebase->tp_as_buffer == NULL)
3654 basebase = NULL;
3655 COPYBUF(bf_getbuffer);
3656 COPYBUF(bf_releasebuffer);
3657 }
Tim Petersfc57ccb2001-10-12 02:38:24 +00003658
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003659 basebase = base->tp_base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003660
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003661 COPYSLOT(tp_dealloc);
3662 if (type->tp_getattr == NULL && type->tp_getattro == NULL) {
3663 type->tp_getattr = base->tp_getattr;
3664 type->tp_getattro = base->tp_getattro;
3665 }
3666 if (type->tp_setattr == NULL && type->tp_setattro == NULL) {
3667 type->tp_setattr = base->tp_setattr;
3668 type->tp_setattro = base->tp_setattro;
3669 }
3670 /* tp_reserved is ignored */
3671 COPYSLOT(tp_repr);
3672 /* tp_hash see tp_richcompare */
3673 COPYSLOT(tp_call);
3674 COPYSLOT(tp_str);
3675 {
3676 /* Copy comparison-related slots only when
3677 not overriding them anywhere */
3678 if (type->tp_richcompare == NULL &&
3679 type->tp_hash == NULL &&
3680 !overrides_hash(type))
3681 {
3682 type->tp_richcompare = base->tp_richcompare;
3683 type->tp_hash = base->tp_hash;
3684 }
3685 }
3686 {
3687 COPYSLOT(tp_iter);
3688 COPYSLOT(tp_iternext);
3689 }
3690 {
3691 COPYSLOT(tp_descr_get);
3692 COPYSLOT(tp_descr_set);
3693 COPYSLOT(tp_dictoffset);
3694 COPYSLOT(tp_init);
3695 COPYSLOT(tp_alloc);
3696 COPYSLOT(tp_is_gc);
3697 if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) ==
3698 (base->tp_flags & Py_TPFLAGS_HAVE_GC)) {
3699 /* They agree about gc. */
3700 COPYSLOT(tp_free);
3701 }
3702 else if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
3703 type->tp_free == NULL &&
3704 base->tp_free == PyObject_Free) {
3705 /* A bit of magic to plug in the correct default
3706 * tp_free function when a derived class adds gc,
3707 * didn't define tp_free, and the base uses the
3708 * default non-gc tp_free.
3709 */
3710 type->tp_free = PyObject_GC_Del;
3711 }
3712 /* else they didn't agree about gc, and there isn't something
3713 * obvious to be done -- the type is on its own.
3714 */
3715 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003716}
3717
Jeremy Hylton938ace62002-07-17 16:30:39 +00003718static int add_operators(PyTypeObject *);
Guido van Rossum13d52f02001-08-10 21:24:08 +00003719
Tim Peters6d6c1a32001-08-02 04:15:00 +00003720int
Guido van Rossum528b7eb2001-08-07 17:24:28 +00003721PyType_Ready(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003722{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003723 PyObject *dict, *bases;
3724 PyTypeObject *base;
3725 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003726
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003727 if (type->tp_flags & Py_TPFLAGS_READY) {
3728 assert(type->tp_dict != NULL);
3729 return 0;
3730 }
3731 assert((type->tp_flags & Py_TPFLAGS_READYING) == 0);
Guido van Rossumd614f972001-08-10 17:39:49 +00003732
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003733 type->tp_flags |= Py_TPFLAGS_READYING;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003734
Tim Peters36eb4df2003-03-23 03:33:13 +00003735#ifdef Py_TRACE_REFS
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003736 /* PyType_Ready is the closest thing we have to a choke point
3737 * for type objects, so is the best place I can think of to try
3738 * to get type objects into the doubly-linked list of all objects.
3739 * Still, not all type objects go thru PyType_Ready.
3740 */
3741 _Py_AddToAllObjects((PyObject *)type, 0);
Tim Peters36eb4df2003-03-23 03:33:13 +00003742#endif
3743
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003744 /* Initialize tp_base (defaults to BaseObject unless that's us) */
3745 base = type->tp_base;
3746 if (base == NULL && type != &PyBaseObject_Type) {
3747 base = type->tp_base = &PyBaseObject_Type;
3748 Py_INCREF(base);
3749 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003750
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003751 /* Now the only way base can still be NULL is if type is
3752 * &PyBaseObject_Type.
3753 */
Guido van Rossum692cdbc2006-03-10 02:04:28 +00003754
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003755 /* Initialize the base class */
3756 if (base != NULL && base->tp_dict == NULL) {
3757 if (PyType_Ready(base) < 0)
3758 goto error;
3759 }
Guido van Rossum323a9cf2002-08-14 17:26:30 +00003760
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003761 /* Initialize ob_type if NULL. This means extensions that want to be
3762 compilable separately on Windows can call PyType_Ready() instead of
3763 initializing the ob_type field of their type objects. */
3764 /* The test for base != NULL is really unnecessary, since base is only
3765 NULL when type is &PyBaseObject_Type, and we know its ob_type is
3766 not NULL (it's initialized to &PyType_Type). But coverity doesn't
3767 know that. */
3768 if (Py_TYPE(type) == NULL && base != NULL)
3769 Py_TYPE(type) = Py_TYPE(base);
Guido van Rossum0986d822002-04-08 01:38:42 +00003770
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003771 /* Initialize tp_bases */
3772 bases = type->tp_bases;
3773 if (bases == NULL) {
3774 if (base == NULL)
3775 bases = PyTuple_New(0);
3776 else
3777 bases = PyTuple_Pack(1, base);
3778 if (bases == NULL)
3779 goto error;
3780 type->tp_bases = bases;
3781 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003782
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003783 /* Initialize tp_dict */
3784 dict = type->tp_dict;
3785 if (dict == NULL) {
3786 dict = PyDict_New();
3787 if (dict == NULL)
3788 goto error;
3789 type->tp_dict = dict;
3790 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003791
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003792 /* Add type-specific descriptors to tp_dict */
3793 if (add_operators(type) < 0)
3794 goto error;
3795 if (type->tp_methods != NULL) {
3796 if (add_methods(type, type->tp_methods) < 0)
3797 goto error;
3798 }
3799 if (type->tp_members != NULL) {
3800 if (add_members(type, type->tp_members) < 0)
3801 goto error;
3802 }
3803 if (type->tp_getset != NULL) {
3804 if (add_getset(type, type->tp_getset) < 0)
3805 goto error;
3806 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003807
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003808 /* Calculate method resolution order */
3809 if (mro_internal(type) < 0) {
3810 goto error;
3811 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003812
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003813 /* Inherit special flags from dominant base */
3814 if (type->tp_base != NULL)
3815 inherit_special(type, type->tp_base);
Guido van Rossum13d52f02001-08-10 21:24:08 +00003816
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003817 /* Initialize tp_dict properly */
3818 bases = type->tp_mro;
3819 assert(bases != NULL);
3820 assert(PyTuple_Check(bases));
3821 n = PyTuple_GET_SIZE(bases);
3822 for (i = 1; i < n; i++) {
3823 PyObject *b = PyTuple_GET_ITEM(bases, i);
3824 if (PyType_Check(b))
3825 inherit_slots(type, (PyTypeObject *)b);
3826 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003827
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003828 /* Sanity check for tp_free. */
3829 if (PyType_IS_GC(type) && (type->tp_flags & Py_TPFLAGS_BASETYPE) &&
3830 (type->tp_free == NULL || type->tp_free == PyObject_Del)) {
3831 /* This base class needs to call tp_free, but doesn't have
3832 * one, or its tp_free is for non-gc'ed objects.
3833 */
3834 PyErr_Format(PyExc_TypeError, "type '%.100s' participates in "
3835 "gc and is a base type but has inappropriate "
3836 "tp_free slot",
3837 type->tp_name);
3838 goto error;
3839 }
Tim Peters3cfe7542003-05-21 21:29:48 +00003840
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003841 /* if the type dictionary doesn't contain a __doc__, set it from
3842 the tp_doc slot.
3843 */
3844 if (PyDict_GetItemString(type->tp_dict, "__doc__") == NULL) {
3845 if (type->tp_doc != NULL) {
3846 PyObject *doc = PyUnicode_FromString(type->tp_doc);
3847 if (doc == NULL)
3848 goto error;
3849 PyDict_SetItemString(type->tp_dict, "__doc__", doc);
3850 Py_DECREF(doc);
3851 } else {
3852 PyDict_SetItemString(type->tp_dict,
3853 "__doc__", Py_None);
3854 }
3855 }
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00003856
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003857 /* Hack for tp_hash and __hash__.
3858 If after all that, tp_hash is still NULL, and __hash__ is not in
3859 tp_dict, set tp_hash to PyObject_HashNotImplemented and
3860 tp_dict['__hash__'] equal to None.
3861 This signals that __hash__ is not inherited.
3862 */
3863 if (type->tp_hash == NULL) {
3864 if (PyDict_GetItemString(type->tp_dict, "__hash__") == NULL) {
3865 if (PyDict_SetItemString(type->tp_dict, "__hash__", Py_None) < 0)
3866 goto error;
3867 type->tp_hash = PyObject_HashNotImplemented;
3868 }
3869 }
Guido van Rossum38938152006-08-21 23:36:26 +00003870
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003871 /* Some more special stuff */
3872 base = type->tp_base;
3873 if (base != NULL) {
3874 if (type->tp_as_number == NULL)
3875 type->tp_as_number = base->tp_as_number;
3876 if (type->tp_as_sequence == NULL)
3877 type->tp_as_sequence = base->tp_as_sequence;
3878 if (type->tp_as_mapping == NULL)
3879 type->tp_as_mapping = base->tp_as_mapping;
3880 if (type->tp_as_buffer == NULL)
3881 type->tp_as_buffer = base->tp_as_buffer;
3882 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003883
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003884 /* Link into each base class's list of subclasses */
3885 bases = type->tp_bases;
3886 n = PyTuple_GET_SIZE(bases);
3887 for (i = 0; i < n; i++) {
3888 PyObject *b = PyTuple_GET_ITEM(bases, i);
3889 if (PyType_Check(b) &&
3890 add_subclass((PyTypeObject *)b, type) < 0)
3891 goto error;
3892 }
Guido van Rossum1c450732001-10-08 15:18:27 +00003893
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003894 /* Warn for a type that implements tp_compare (now known as
3895 tp_reserved) but not tp_richcompare. */
3896 if (type->tp_reserved && !type->tp_richcompare) {
3897 int error;
3898 char msg[240];
3899 PyOS_snprintf(msg, sizeof(msg),
3900 "Type %.100s defines tp_reserved (formerly "
3901 "tp_compare) but not tp_richcompare. "
3902 "Comparisons may not behave as intended.",
3903 type->tp_name);
3904 error = PyErr_WarnEx(PyExc_DeprecationWarning, msg, 1);
3905 if (error == -1)
3906 goto error;
3907 }
Mark Dickinson2a7d45b2009-02-08 11:02:10 +00003908
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003909 /* All done -- set the ready flag */
3910 assert(type->tp_dict != NULL);
3911 type->tp_flags =
3912 (type->tp_flags & ~Py_TPFLAGS_READYING) | Py_TPFLAGS_READY;
3913 return 0;
Guido van Rossumd614f972001-08-10 17:39:49 +00003914
3915 error:
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003916 type->tp_flags &= ~Py_TPFLAGS_READYING;
3917 return -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003918}
3919
Guido van Rossum1c450732001-10-08 15:18:27 +00003920static int
3921add_subclass(PyTypeObject *base, PyTypeObject *type)
3922{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003923 Py_ssize_t i;
3924 int result;
3925 PyObject *list, *ref, *newobj;
Guido van Rossum1c450732001-10-08 15:18:27 +00003926
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003927 list = base->tp_subclasses;
3928 if (list == NULL) {
3929 base->tp_subclasses = list = PyList_New(0);
3930 if (list == NULL)
3931 return -1;
3932 }
3933 assert(PyList_Check(list));
3934 newobj = PyWeakref_NewRef((PyObject *)type, NULL);
3935 i = PyList_GET_SIZE(list);
3936 while (--i >= 0) {
3937 ref = PyList_GET_ITEM(list, i);
3938 assert(PyWeakref_CheckRef(ref));
3939 if (PyWeakref_GET_OBJECT(ref) == Py_None)
3940 return PyList_SetItem(list, i, newobj);
3941 }
3942 result = PyList_Append(list, newobj);
3943 Py_DECREF(newobj);
3944 return result;
Guido van Rossum1c450732001-10-08 15:18:27 +00003945}
3946
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003947static void
3948remove_subclass(PyTypeObject *base, PyTypeObject *type)
3949{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003950 Py_ssize_t i;
3951 PyObject *list, *ref;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003952
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003953 list = base->tp_subclasses;
3954 if (list == NULL) {
3955 return;
3956 }
3957 assert(PyList_Check(list));
3958 i = PyList_GET_SIZE(list);
3959 while (--i >= 0) {
3960 ref = PyList_GET_ITEM(list, i);
3961 assert(PyWeakref_CheckRef(ref));
3962 if (PyWeakref_GET_OBJECT(ref) == (PyObject*)type) {
3963 /* this can't fail, right? */
3964 PySequence_DelItem(list, i);
3965 return;
3966 }
3967 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003968}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003969
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003970static int
3971check_num_args(PyObject *ob, int n)
3972{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003973 if (!PyTuple_CheckExact(ob)) {
3974 PyErr_SetString(PyExc_SystemError,
3975 "PyArg_UnpackTuple() argument list is not a tuple");
3976 return 0;
3977 }
3978 if (n == PyTuple_GET_SIZE(ob))
3979 return 1;
3980 PyErr_Format(
3981 PyExc_TypeError,
3982 "expected %d arguments, got %zd", n, PyTuple_GET_SIZE(ob));
3983 return 0;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003984}
3985
Tim Peters6d6c1a32001-08-02 04:15:00 +00003986/* Generic wrappers for overloadable 'operators' such as __getitem__ */
3987
3988/* There's a wrapper *function* for each distinct function typedef used
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003989 for type object slots (e.g. binaryfunc, ternaryfunc, etc.). There's a
Tim Peters6d6c1a32001-08-02 04:15:00 +00003990 wrapper *table* for each distinct operation (e.g. __len__, __add__).
3991 Most tables have only one entry; the tables for binary operators have two
3992 entries, one regular and one with reversed arguments. */
3993
3994static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00003995wrap_lenfunc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003996{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003997 lenfunc func = (lenfunc)wrapped;
3998 Py_ssize_t res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003999
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004000 if (!check_num_args(args, 0))
4001 return NULL;
4002 res = (*func)(self);
4003 if (res == -1 && PyErr_Occurred())
4004 return NULL;
4005 return PyLong_FromLong((long)res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004006}
4007
Tim Peters6d6c1a32001-08-02 04:15:00 +00004008static PyObject *
Raymond Hettingerf34f2642003-10-11 17:29:04 +00004009wrap_inquirypred(PyObject *self, PyObject *args, void *wrapped)
4010{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004011 inquiry func = (inquiry)wrapped;
4012 int res;
Raymond Hettingerf34f2642003-10-11 17:29:04 +00004013
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004014 if (!check_num_args(args, 0))
4015 return NULL;
4016 res = (*func)(self);
4017 if (res == -1 && PyErr_Occurred())
4018 return NULL;
4019 return PyBool_FromLong((long)res);
Raymond Hettingerf34f2642003-10-11 17:29:04 +00004020}
4021
4022static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00004023wrap_binaryfunc(PyObject *self, PyObject *args, void *wrapped)
4024{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004025 binaryfunc func = (binaryfunc)wrapped;
4026 PyObject *other;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004027
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004028 if (!check_num_args(args, 1))
4029 return NULL;
4030 other = PyTuple_GET_ITEM(args, 0);
4031 return (*func)(self, other);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004032}
4033
4034static PyObject *
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00004035wrap_binaryfunc_l(PyObject *self, PyObject *args, void *wrapped)
4036{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004037 binaryfunc func = (binaryfunc)wrapped;
4038 PyObject *other;
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00004039
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004040 if (!check_num_args(args, 1))
4041 return NULL;
4042 other = PyTuple_GET_ITEM(args, 0);
4043 return (*func)(self, other);
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00004044}
4045
4046static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00004047wrap_binaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
4048{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004049 binaryfunc func = (binaryfunc)wrapped;
4050 PyObject *other;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004051
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004052 if (!check_num_args(args, 1))
4053 return NULL;
4054 other = PyTuple_GET_ITEM(args, 0);
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004055 return (*func)(other, self);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004056}
4057
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004058static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00004059wrap_ternaryfunc(PyObject *self, PyObject *args, void *wrapped)
4060{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004061 ternaryfunc func = (ternaryfunc)wrapped;
4062 PyObject *other;
4063 PyObject *third = Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004064
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004065 /* Note: This wrapper only works for __pow__() */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004066
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004067 if (!PyArg_UnpackTuple(args, "", 1, 2, &other, &third))
4068 return NULL;
4069 return (*func)(self, other, third);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004070}
4071
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00004072static PyObject *
4073wrap_ternaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
4074{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004075 ternaryfunc func = (ternaryfunc)wrapped;
4076 PyObject *other;
4077 PyObject *third = Py_None;
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00004078
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004079 /* Note: This wrapper only works for __pow__() */
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00004080
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004081 if (!PyArg_UnpackTuple(args, "", 1, 2, &other, &third))
4082 return NULL;
4083 return (*func)(other, self, third);
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00004084}
4085
Tim Peters6d6c1a32001-08-02 04:15:00 +00004086static PyObject *
4087wrap_unaryfunc(PyObject *self, PyObject *args, void *wrapped)
4088{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004089 unaryfunc func = (unaryfunc)wrapped;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004090
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004091 if (!check_num_args(args, 0))
4092 return NULL;
4093 return (*func)(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004094}
4095
Tim Peters6d6c1a32001-08-02 04:15:00 +00004096static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004097wrap_indexargfunc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004098{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004099 ssizeargfunc func = (ssizeargfunc)wrapped;
4100 PyObject* o;
4101 Py_ssize_t i;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004102
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004103 if (!PyArg_UnpackTuple(args, "", 1, 1, &o))
4104 return NULL;
4105 i = PyNumber_AsSsize_t(o, PyExc_OverflowError);
4106 if (i == -1 && PyErr_Occurred())
4107 return NULL;
4108 return (*func)(self, i);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004109}
4110
Martin v. Löwis18e16552006-02-15 17:27:45 +00004111static Py_ssize_t
Guido van Rossum5d815f32001-08-17 21:57:47 +00004112getindex(PyObject *self, PyObject *arg)
4113{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004114 Py_ssize_t i;
Guido van Rossum5d815f32001-08-17 21:57:47 +00004115
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004116 i = PyNumber_AsSsize_t(arg, PyExc_OverflowError);
4117 if (i == -1 && PyErr_Occurred())
4118 return -1;
4119 if (i < 0) {
4120 PySequenceMethods *sq = Py_TYPE(self)->tp_as_sequence;
4121 if (sq && sq->sq_length) {
4122 Py_ssize_t n = (*sq->sq_length)(self);
4123 if (n < 0)
4124 return -1;
4125 i += n;
4126 }
4127 }
4128 return i;
Guido van Rossum5d815f32001-08-17 21:57:47 +00004129}
4130
4131static PyObject *
4132wrap_sq_item(PyObject *self, PyObject *args, void *wrapped)
4133{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004134 ssizeargfunc func = (ssizeargfunc)wrapped;
4135 PyObject *arg;
4136 Py_ssize_t i;
Guido van Rossum5d815f32001-08-17 21:57:47 +00004137
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004138 if (PyTuple_GET_SIZE(args) == 1) {
4139 arg = PyTuple_GET_ITEM(args, 0);
4140 i = getindex(self, arg);
4141 if (i == -1 && PyErr_Occurred())
4142 return NULL;
4143 return (*func)(self, i);
4144 }
4145 check_num_args(args, 1);
4146 assert(PyErr_Occurred());
4147 return NULL;
Guido van Rossum5d815f32001-08-17 21:57:47 +00004148}
4149
Tim Peters6d6c1a32001-08-02 04:15:00 +00004150static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00004151wrap_sq_setitem(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004152{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004153 ssizeobjargproc func = (ssizeobjargproc)wrapped;
4154 Py_ssize_t i;
4155 int res;
4156 PyObject *arg, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004157
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004158 if (!PyArg_UnpackTuple(args, "", 2, 2, &arg, &value))
4159 return NULL;
4160 i = getindex(self, arg);
4161 if (i == -1 && PyErr_Occurred())
4162 return NULL;
4163 res = (*func)(self, i, value);
4164 if (res == -1 && PyErr_Occurred())
4165 return NULL;
4166 Py_INCREF(Py_None);
4167 return Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004168}
4169
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004170static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00004171wrap_sq_delitem(PyObject *self, PyObject *args, void *wrapped)
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004172{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004173 ssizeobjargproc func = (ssizeobjargproc)wrapped;
4174 Py_ssize_t i;
4175 int res;
4176 PyObject *arg;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004177
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004178 if (!check_num_args(args, 1))
4179 return NULL;
4180 arg = PyTuple_GET_ITEM(args, 0);
4181 i = getindex(self, arg);
4182 if (i == -1 && PyErr_Occurred())
4183 return NULL;
4184 res = (*func)(self, i, NULL);
4185 if (res == -1 && PyErr_Occurred())
4186 return NULL;
4187 Py_INCREF(Py_None);
4188 return Py_None;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004189}
4190
Tim Peters6d6c1a32001-08-02 04:15:00 +00004191/* XXX objobjproc is a misnomer; should be objargpred */
4192static PyObject *
4193wrap_objobjproc(PyObject *self, PyObject *args, void *wrapped)
4194{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004195 objobjproc func = (objobjproc)wrapped;
4196 int res;
4197 PyObject *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004198
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004199 if (!check_num_args(args, 1))
4200 return NULL;
4201 value = PyTuple_GET_ITEM(args, 0);
4202 res = (*func)(self, value);
4203 if (res == -1 && PyErr_Occurred())
4204 return NULL;
4205 else
4206 return PyBool_FromLong(res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004207}
4208
Tim Peters6d6c1a32001-08-02 04:15:00 +00004209static PyObject *
4210wrap_objobjargproc(PyObject *self, PyObject *args, void *wrapped)
4211{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004212 objobjargproc func = (objobjargproc)wrapped;
4213 int res;
4214 PyObject *key, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004215
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004216 if (!PyArg_UnpackTuple(args, "", 2, 2, &key, &value))
4217 return NULL;
4218 res = (*func)(self, key, value);
4219 if (res == -1 && PyErr_Occurred())
4220 return NULL;
4221 Py_INCREF(Py_None);
4222 return Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004223}
4224
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004225static PyObject *
4226wrap_delitem(PyObject *self, PyObject *args, void *wrapped)
4227{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004228 objobjargproc func = (objobjargproc)wrapped;
4229 int res;
4230 PyObject *key;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004231
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004232 if (!check_num_args(args, 1))
4233 return NULL;
4234 key = PyTuple_GET_ITEM(args, 0);
4235 res = (*func)(self, key, NULL);
4236 if (res == -1 && PyErr_Occurred())
4237 return NULL;
4238 Py_INCREF(Py_None);
4239 return Py_None;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004240}
4241
Guido van Rossum4dcdb782003-04-14 21:46:03 +00004242/* Helper to check for object.__setattr__ or __delattr__ applied to a type.
Guido van Rossum52b27052003-04-15 20:05:10 +00004243 This is called the Carlo Verre hack after its discoverer. */
Guido van Rossum4dcdb782003-04-14 21:46:03 +00004244static int
4245hackcheck(PyObject *self, setattrofunc func, char *what)
4246{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004247 PyTypeObject *type = Py_TYPE(self);
4248 while (type && type->tp_flags & Py_TPFLAGS_HEAPTYPE)
4249 type = type->tp_base;
4250 /* If type is NULL now, this is a really weird type.
4251 In the spirit of backwards compatibility (?), just shut up. */
4252 if (type && type->tp_setattro != func) {
4253 PyErr_Format(PyExc_TypeError,
4254 "can't apply this %s to %s object",
4255 what,
4256 type->tp_name);
4257 return 0;
4258 }
4259 return 1;
Guido van Rossum4dcdb782003-04-14 21:46:03 +00004260}
4261
Tim Peters6d6c1a32001-08-02 04:15:00 +00004262static PyObject *
4263wrap_setattr(PyObject *self, PyObject *args, void *wrapped)
4264{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004265 setattrofunc func = (setattrofunc)wrapped;
4266 int res;
4267 PyObject *name, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004268
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004269 if (!PyArg_UnpackTuple(args, "", 2, 2, &name, &value))
4270 return NULL;
4271 if (!hackcheck(self, func, "__setattr__"))
4272 return NULL;
4273 res = (*func)(self, name, value);
4274 if (res < 0)
4275 return NULL;
4276 Py_INCREF(Py_None);
4277 return Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004278}
4279
4280static PyObject *
4281wrap_delattr(PyObject *self, PyObject *args, void *wrapped)
4282{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004283 setattrofunc func = (setattrofunc)wrapped;
4284 int res;
4285 PyObject *name;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004286
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004287 if (!check_num_args(args, 1))
4288 return NULL;
4289 name = PyTuple_GET_ITEM(args, 0);
4290 if (!hackcheck(self, func, "__delattr__"))
4291 return NULL;
4292 res = (*func)(self, name, NULL);
4293 if (res < 0)
4294 return NULL;
4295 Py_INCREF(Py_None);
4296 return Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004297}
4298
Tim Peters6d6c1a32001-08-02 04:15:00 +00004299static PyObject *
4300wrap_hashfunc(PyObject *self, PyObject *args, void *wrapped)
4301{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004302 hashfunc func = (hashfunc)wrapped;
4303 long res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004304
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004305 if (!check_num_args(args, 0))
4306 return NULL;
4307 res = (*func)(self);
4308 if (res == -1 && PyErr_Occurred())
4309 return NULL;
4310 return PyLong_FromLong(res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004311}
4312
Tim Peters6d6c1a32001-08-02 04:15:00 +00004313static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00004314wrap_call(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004315{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004316 ternaryfunc func = (ternaryfunc)wrapped;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004317
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004318 return (*func)(self, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004319}
4320
Tim Peters6d6c1a32001-08-02 04:15:00 +00004321static PyObject *
4322wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op)
4323{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004324 richcmpfunc func = (richcmpfunc)wrapped;
4325 PyObject *other;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004326
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004327 if (!check_num_args(args, 1))
4328 return NULL;
4329 other = PyTuple_GET_ITEM(args, 0);
4330 return (*func)(self, other, op);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004331}
4332
4333#undef RICHCMP_WRAPPER
4334#define RICHCMP_WRAPPER(NAME, OP) \
4335static PyObject * \
4336richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \
4337{ \
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004338 return wrap_richcmpfunc(self, args, wrapped, OP); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004339}
4340
Jack Jansen8e938b42001-08-08 15:29:49 +00004341RICHCMP_WRAPPER(lt, Py_LT)
4342RICHCMP_WRAPPER(le, Py_LE)
4343RICHCMP_WRAPPER(eq, Py_EQ)
4344RICHCMP_WRAPPER(ne, Py_NE)
4345RICHCMP_WRAPPER(gt, Py_GT)
4346RICHCMP_WRAPPER(ge, Py_GE)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004347
Tim Peters6d6c1a32001-08-02 04:15:00 +00004348static PyObject *
4349wrap_next(PyObject *self, PyObject *args, void *wrapped)
4350{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004351 unaryfunc func = (unaryfunc)wrapped;
4352 PyObject *res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004353
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004354 if (!check_num_args(args, 0))
4355 return NULL;
4356 res = (*func)(self);
4357 if (res == NULL && !PyErr_Occurred())
4358 PyErr_SetNone(PyExc_StopIteration);
4359 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004360}
4361
Tim Peters6d6c1a32001-08-02 04:15:00 +00004362static PyObject *
4363wrap_descr_get(PyObject *self, PyObject *args, void *wrapped)
4364{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004365 descrgetfunc func = (descrgetfunc)wrapped;
4366 PyObject *obj;
4367 PyObject *type = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004368
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004369 if (!PyArg_UnpackTuple(args, "", 1, 2, &obj, &type))
4370 return NULL;
4371 if (obj == Py_None)
4372 obj = NULL;
4373 if (type == Py_None)
4374 type = NULL;
4375 if (type == NULL &&obj == NULL) {
4376 PyErr_SetString(PyExc_TypeError,
4377 "__get__(None, None) is invalid");
4378 return NULL;
4379 }
4380 return (*func)(self, obj, type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004381}
4382
Tim Peters6d6c1a32001-08-02 04:15:00 +00004383static PyObject *
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004384wrap_descr_set(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004385{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004386 descrsetfunc func = (descrsetfunc)wrapped;
4387 PyObject *obj, *value;
4388 int ret;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004389
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004390 if (!PyArg_UnpackTuple(args, "", 2, 2, &obj, &value))
4391 return NULL;
4392 ret = (*func)(self, obj, value);
4393 if (ret < 0)
4394 return NULL;
4395 Py_INCREF(Py_None);
4396 return Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004397}
Guido van Rossum22b13872002-08-06 21:41:44 +00004398
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00004399static PyObject *
4400wrap_descr_delete(PyObject *self, PyObject *args, void *wrapped)
4401{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004402 descrsetfunc func = (descrsetfunc)wrapped;
4403 PyObject *obj;
4404 int ret;
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00004405
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004406 if (!check_num_args(args, 1))
4407 return NULL;
4408 obj = PyTuple_GET_ITEM(args, 0);
4409 ret = (*func)(self, obj, NULL);
4410 if (ret < 0)
4411 return NULL;
4412 Py_INCREF(Py_None);
4413 return Py_None;
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00004414}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004415
Tim Peters6d6c1a32001-08-02 04:15:00 +00004416static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00004417wrap_init(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004418{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004419 initproc func = (initproc)wrapped;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004420
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004421 if (func(self, args, kwds) < 0)
4422 return NULL;
4423 Py_INCREF(Py_None);
4424 return Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004425}
4426
Tim Peters6d6c1a32001-08-02 04:15:00 +00004427static PyObject *
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004428tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004429{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004430 PyTypeObject *type, *subtype, *staticbase;
4431 PyObject *arg0, *res;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004432
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004433 if (self == NULL || !PyType_Check(self))
4434 Py_FatalError("__new__() called with non-type 'self'");
4435 type = (PyTypeObject *)self;
4436 if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) {
4437 PyErr_Format(PyExc_TypeError,
4438 "%s.__new__(): not enough arguments",
4439 type->tp_name);
4440 return NULL;
4441 }
4442 arg0 = PyTuple_GET_ITEM(args, 0);
4443 if (!PyType_Check(arg0)) {
4444 PyErr_Format(PyExc_TypeError,
4445 "%s.__new__(X): X is not a type object (%s)",
4446 type->tp_name,
4447 Py_TYPE(arg0)->tp_name);
4448 return NULL;
4449 }
4450 subtype = (PyTypeObject *)arg0;
4451 if (!PyType_IsSubtype(subtype, type)) {
4452 PyErr_Format(PyExc_TypeError,
4453 "%s.__new__(%s): %s is not a subtype of %s",
4454 type->tp_name,
4455 subtype->tp_name,
4456 subtype->tp_name,
4457 type->tp_name);
4458 return NULL;
4459 }
Barry Warsaw60f01882001-08-22 19:24:42 +00004460
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004461 /* Check that the use doesn't do something silly and unsafe like
4462 object.__new__(dict). To do this, we check that the
4463 most derived base that's not a heap type is this type. */
4464 staticbase = subtype;
4465 while (staticbase && (staticbase->tp_flags & Py_TPFLAGS_HEAPTYPE))
4466 staticbase = staticbase->tp_base;
4467 /* If staticbase is NULL now, it is a really weird type.
4468 In the spirit of backwards compatibility (?), just shut up. */
4469 if (staticbase && staticbase->tp_new != type->tp_new) {
4470 PyErr_Format(PyExc_TypeError,
4471 "%s.__new__(%s) is not safe, use %s.__new__()",
4472 type->tp_name,
4473 subtype->tp_name,
4474 staticbase == NULL ? "?" : staticbase->tp_name);
4475 return NULL;
4476 }
Barry Warsaw60f01882001-08-22 19:24:42 +00004477
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004478 args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
4479 if (args == NULL)
4480 return NULL;
4481 res = type->tp_new(subtype, args, kwds);
4482 Py_DECREF(args);
4483 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004484}
4485
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004486static struct PyMethodDef tp_new_methoddef[] = {
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004487 {"__new__", (PyCFunction)tp_new_wrapper, METH_VARARGS|METH_KEYWORDS,
4488 PyDoc_STR("T.__new__(S, ...) -> "
4489 "a new object with type S, a subtype of T")},
4490 {0}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004491};
4492
4493static int
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004494add_tp_new_wrapper(PyTypeObject *type)
4495{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004496 PyObject *func;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004497
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004498 if (PyDict_GetItemString(type->tp_dict, "__new__") != NULL)
4499 return 0;
4500 func = PyCFunction_New(tp_new_methoddef, (PyObject *)type);
4501 if (func == NULL)
4502 return -1;
4503 if (PyDict_SetItemString(type->tp_dict, "__new__", func)) {
4504 Py_DECREF(func);
4505 return -1;
4506 }
4507 Py_DECREF(func);
4508 return 0;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004509}
4510
Guido van Rossumf040ede2001-08-07 16:40:56 +00004511/* Slot wrappers that call the corresponding __foo__ slot. See comments
4512 below at override_slots() for more explanation. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004513
Guido van Rossumdc91b992001-08-08 22:26:22 +00004514#define SLOT0(FUNCNAME, OPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004515static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004516FUNCNAME(PyObject *self) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004517{ \
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004518 static PyObject *cache_str; \
4519 return call_method(self, OPSTR, &cache_str, "()"); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004520}
4521
Guido van Rossumdc91b992001-08-08 22:26:22 +00004522#define SLOT1(FUNCNAME, OPSTR, ARG1TYPE, ARGCODES) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004523static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004524FUNCNAME(PyObject *self, ARG1TYPE arg1) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004525{ \
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004526 static PyObject *cache_str; \
4527 return call_method(self, OPSTR, &cache_str, "(" ARGCODES ")", arg1); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004528}
4529
Guido van Rossumcd118802003-01-06 22:57:47 +00004530/* Boolean helper for SLOT1BINFULL().
4531 right.__class__ is a nontrivial subclass of left.__class__. */
4532static int
4533method_is_overloaded(PyObject *left, PyObject *right, char *name)
4534{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004535 PyObject *a, *b;
4536 int ok;
Guido van Rossumcd118802003-01-06 22:57:47 +00004537
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004538 b = PyObject_GetAttrString((PyObject *)(Py_TYPE(right)), name);
4539 if (b == NULL) {
4540 PyErr_Clear();
4541 /* If right doesn't have it, it's not overloaded */
4542 return 0;
4543 }
Guido van Rossumcd118802003-01-06 22:57:47 +00004544
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004545 a = PyObject_GetAttrString((PyObject *)(Py_TYPE(left)), name);
4546 if (a == NULL) {
4547 PyErr_Clear();
4548 Py_DECREF(b);
4549 /* If right has it but left doesn't, it's overloaded */
4550 return 1;
4551 }
Guido van Rossumcd118802003-01-06 22:57:47 +00004552
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004553 ok = PyObject_RichCompareBool(a, b, Py_NE);
4554 Py_DECREF(a);
4555 Py_DECREF(b);
4556 if (ok < 0) {
4557 PyErr_Clear();
4558 return 0;
4559 }
Guido van Rossumcd118802003-01-06 22:57:47 +00004560
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004561 return ok;
Guido van Rossumcd118802003-01-06 22:57:47 +00004562}
4563
Guido van Rossumdc91b992001-08-08 22:26:22 +00004564
4565#define SLOT1BINFULL(FUNCNAME, TESTFUNC, SLOTNAME, OPSTR, ROPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004566static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004567FUNCNAME(PyObject *self, PyObject *other) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004568{ \
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004569 static PyObject *cache_str, *rcache_str; \
4570 int do_other = Py_TYPE(self) != Py_TYPE(other) && \
4571 Py_TYPE(other)->tp_as_number != NULL && \
4572 Py_TYPE(other)->tp_as_number->SLOTNAME == TESTFUNC; \
4573 if (Py_TYPE(self)->tp_as_number != NULL && \
4574 Py_TYPE(self)->tp_as_number->SLOTNAME == TESTFUNC) { \
4575 PyObject *r; \
4576 if (do_other && \
4577 PyType_IsSubtype(Py_TYPE(other), Py_TYPE(self)) && \
4578 method_is_overloaded(self, other, ROPSTR)) { \
4579 r = call_maybe( \
4580 other, ROPSTR, &rcache_str, "(O)", self); \
4581 if (r != Py_NotImplemented) \
4582 return r; \
4583 Py_DECREF(r); \
4584 do_other = 0; \
4585 } \
4586 r = call_maybe( \
4587 self, OPSTR, &cache_str, "(O)", other); \
4588 if (r != Py_NotImplemented || \
4589 Py_TYPE(other) == Py_TYPE(self)) \
4590 return r; \
4591 Py_DECREF(r); \
4592 } \
4593 if (do_other) { \
4594 return call_maybe( \
4595 other, ROPSTR, &rcache_str, "(O)", self); \
4596 } \
4597 Py_INCREF(Py_NotImplemented); \
4598 return Py_NotImplemented; \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004599}
4600
4601#define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) \
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004602 SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR)
Guido van Rossumdc91b992001-08-08 22:26:22 +00004603
4604#define SLOT2(FUNCNAME, OPSTR, ARG1TYPE, ARG2TYPE, ARGCODES) \
4605static PyObject * \
4606FUNCNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \
4607{ \
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004608 static PyObject *cache_str; \
4609 return call_method(self, OPSTR, &cache_str, \
4610 "(" ARGCODES ")", arg1, arg2); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004611}
4612
Martin v. Löwis18e16552006-02-15 17:27:45 +00004613static Py_ssize_t
Tim Peters6d6c1a32001-08-02 04:15:00 +00004614slot_sq_length(PyObject *self)
4615{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004616 static PyObject *len_str;
4617 PyObject *res = call_method(self, "__len__", &len_str, "()");
4618 Py_ssize_t len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004619
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004620 if (res == NULL)
4621 return -1;
4622 len = PyNumber_AsSsize_t(res, PyExc_OverflowError);
4623 Py_DECREF(res);
4624 if (len < 0) {
4625 if (!PyErr_Occurred())
4626 PyErr_SetString(PyExc_ValueError,
4627 "__len__() should return >= 0");
4628 return -1;
4629 }
4630 return len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004631}
4632
Guido van Rossumf4593e02001-10-03 12:09:30 +00004633/* Super-optimized version of slot_sq_item.
4634 Other slots could do the same... */
4635static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00004636slot_sq_item(PyObject *self, Py_ssize_t i)
Guido van Rossumf4593e02001-10-03 12:09:30 +00004637{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004638 static PyObject *getitem_str;
4639 PyObject *func, *args = NULL, *ival = NULL, *retval = NULL;
4640 descrgetfunc f;
Guido van Rossumf4593e02001-10-03 12:09:30 +00004641
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004642 if (getitem_str == NULL) {
4643 getitem_str = PyUnicode_InternFromString("__getitem__");
4644 if (getitem_str == NULL)
4645 return NULL;
4646 }
4647 func = _PyType_Lookup(Py_TYPE(self), getitem_str);
4648 if (func != NULL) {
4649 if ((f = Py_TYPE(func)->tp_descr_get) == NULL)
4650 Py_INCREF(func);
4651 else {
4652 func = f(func, self, (PyObject *)(Py_TYPE(self)));
4653 if (func == NULL) {
4654 return NULL;
4655 }
4656 }
4657 ival = PyLong_FromSsize_t(i);
4658 if (ival != NULL) {
4659 args = PyTuple_New(1);
4660 if (args != NULL) {
4661 PyTuple_SET_ITEM(args, 0, ival);
4662 retval = PyObject_Call(func, args, NULL);
4663 Py_XDECREF(args);
4664 Py_XDECREF(func);
4665 return retval;
4666 }
4667 }
4668 }
4669 else {
4670 PyErr_SetObject(PyExc_AttributeError, getitem_str);
4671 }
4672 Py_XDECREF(args);
4673 Py_XDECREF(ival);
4674 Py_XDECREF(func);
4675 return NULL;
Guido van Rossumf4593e02001-10-03 12:09:30 +00004676}
4677
Tim Peters6d6c1a32001-08-02 04:15:00 +00004678static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00004679slot_sq_ass_item(PyObject *self, Py_ssize_t index, PyObject *value)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004680{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004681 PyObject *res;
4682 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004683
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004684 if (value == NULL)
4685 res = call_method(self, "__delitem__", &delitem_str,
4686 "(n)", index);
4687 else
4688 res = call_method(self, "__setitem__", &setitem_str,
4689 "(nO)", index, value);
4690 if (res == NULL)
4691 return -1;
4692 Py_DECREF(res);
4693 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004694}
4695
4696static int
Tim Peters6d6c1a32001-08-02 04:15:00 +00004697slot_sq_contains(PyObject *self, PyObject *value)
4698{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004699 PyObject *func, *res, *args;
4700 int result = -1;
Tim Petersbf9b2442003-03-23 05:35:36 +00004701
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004702 static PyObject *contains_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004703
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004704 func = lookup_maybe(self, "__contains__", &contains_str);
4705 if (func != NULL) {
4706 args = PyTuple_Pack(1, value);
4707 if (args == NULL)
4708 res = NULL;
4709 else {
4710 res = PyObject_Call(func, args, NULL);
4711 Py_DECREF(args);
4712 }
4713 Py_DECREF(func);
4714 if (res != NULL) {
4715 result = PyObject_IsTrue(res);
4716 Py_DECREF(res);
4717 }
4718 }
4719 else if (! PyErr_Occurred()) {
4720 /* Possible results: -1 and 1 */
4721 result = (int)_PySequence_IterSearch(self, value,
4722 PY_ITERSEARCH_CONTAINS);
4723 }
4724 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004725}
4726
Tim Peters6d6c1a32001-08-02 04:15:00 +00004727#define slot_mp_length slot_sq_length
4728
Guido van Rossumdc91b992001-08-08 22:26:22 +00004729SLOT1(slot_mp_subscript, "__getitem__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004730
4731static int
4732slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value)
4733{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004734 PyObject *res;
4735 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004736
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004737 if (value == NULL)
4738 res = call_method(self, "__delitem__", &delitem_str,
4739 "(O)", key);
4740 else
4741 res = call_method(self, "__setitem__", &setitem_str,
4742 "(OO)", key, value);
4743 if (res == NULL)
4744 return -1;
4745 Py_DECREF(res);
4746 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004747}
4748
Guido van Rossumdc91b992001-08-08 22:26:22 +00004749SLOT1BIN(slot_nb_add, nb_add, "__add__", "__radd__")
4750SLOT1BIN(slot_nb_subtract, nb_subtract, "__sub__", "__rsub__")
4751SLOT1BIN(slot_nb_multiply, nb_multiply, "__mul__", "__rmul__")
Guido van Rossumdc91b992001-08-08 22:26:22 +00004752SLOT1BIN(slot_nb_remainder, nb_remainder, "__mod__", "__rmod__")
4753SLOT1BIN(slot_nb_divmod, nb_divmod, "__divmod__", "__rdivmod__")
4754
Jeremy Hylton938ace62002-07-17 16:30:39 +00004755static PyObject *slot_nb_power(PyObject *, PyObject *, PyObject *);
Guido van Rossumdc91b992001-08-08 22:26:22 +00004756
4757SLOT1BINFULL(slot_nb_power_binary, slot_nb_power,
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004758 nb_power, "__pow__", "__rpow__")
Guido van Rossumdc91b992001-08-08 22:26:22 +00004759
4760static PyObject *
4761slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus)
4762{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004763 static PyObject *pow_str;
Guido van Rossum2730b132001-08-28 18:22:14 +00004764
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004765 if (modulus == Py_None)
4766 return slot_nb_power_binary(self, other);
4767 /* Three-arg power doesn't use __rpow__. But ternary_op
4768 can call this when the second argument's type uses
4769 slot_nb_power, so check before calling self.__pow__. */
4770 if (Py_TYPE(self)->tp_as_number != NULL &&
4771 Py_TYPE(self)->tp_as_number->nb_power == slot_nb_power) {
4772 return call_method(self, "__pow__", &pow_str,
4773 "(OO)", other, modulus);
4774 }
4775 Py_INCREF(Py_NotImplemented);
4776 return Py_NotImplemented;
Guido van Rossumdc91b992001-08-08 22:26:22 +00004777}
4778
4779SLOT0(slot_nb_negative, "__neg__")
4780SLOT0(slot_nb_positive, "__pos__")
4781SLOT0(slot_nb_absolute, "__abs__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004782
4783static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00004784slot_nb_bool(PyObject *self)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004785{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004786 PyObject *func, *args;
4787 static PyObject *bool_str, *len_str;
4788 int result = -1;
4789 int using_len = 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004790
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004791 func = lookup_maybe(self, "__bool__", &bool_str);
4792 if (func == NULL) {
4793 if (PyErr_Occurred())
4794 return -1;
4795 func = lookup_maybe(self, "__len__", &len_str);
4796 if (func == NULL)
4797 return PyErr_Occurred() ? -1 : 1;
4798 using_len = 1;
4799 }
4800 args = PyTuple_New(0);
4801 if (args != NULL) {
4802 PyObject *temp = PyObject_Call(func, args, NULL);
4803 Py_DECREF(args);
4804 if (temp != NULL) {
4805 if (using_len) {
4806 /* enforced by slot_nb_len */
4807 result = PyObject_IsTrue(temp);
4808 }
4809 else if (PyBool_Check(temp)) {
4810 result = PyObject_IsTrue(temp);
4811 }
4812 else {
4813 PyErr_Format(PyExc_TypeError,
4814 "__bool__ should return "
4815 "bool, returned %s",
4816 Py_TYPE(temp)->tp_name);
4817 result = -1;
4818 }
4819 Py_DECREF(temp);
4820 }
4821 }
4822 Py_DECREF(func);
4823 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004824}
4825
Guido van Rossum38fff8c2006-03-07 18:50:55 +00004826
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00004827static PyObject *
Guido van Rossum38fff8c2006-03-07 18:50:55 +00004828slot_nb_index(PyObject *self)
4829{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004830 static PyObject *index_str;
4831 return call_method(self, "__index__", &index_str, "()");
Guido van Rossum38fff8c2006-03-07 18:50:55 +00004832}
4833
4834
Guido van Rossumdc91b992001-08-08 22:26:22 +00004835SLOT0(slot_nb_invert, "__invert__")
4836SLOT1BIN(slot_nb_lshift, nb_lshift, "__lshift__", "__rlshift__")
4837SLOT1BIN(slot_nb_rshift, nb_rshift, "__rshift__", "__rrshift__")
4838SLOT1BIN(slot_nb_and, nb_and, "__and__", "__rand__")
4839SLOT1BIN(slot_nb_xor, nb_xor, "__xor__", "__rxor__")
4840SLOT1BIN(slot_nb_or, nb_or, "__or__", "__ror__")
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004841
Guido van Rossumdc91b992001-08-08 22:26:22 +00004842SLOT0(slot_nb_int, "__int__")
Guido van Rossumdc91b992001-08-08 22:26:22 +00004843SLOT0(slot_nb_float, "__float__")
Guido van Rossumdc91b992001-08-08 22:26:22 +00004844SLOT1(slot_nb_inplace_add, "__iadd__", PyObject *, "O")
4845SLOT1(slot_nb_inplace_subtract, "__isub__", PyObject *, "O")
4846SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *, "O")
Guido van Rossumdc91b992001-08-08 22:26:22 +00004847SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *, "O")
Thomas Wouterscf297e42007-02-23 15:07:44 +00004848/* Can't use SLOT1 here, because nb_inplace_power is ternary */
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004849static PyObject *
4850slot_nb_inplace_power(PyObject *self, PyObject * arg1, PyObject *arg2)
4851{
4852 static PyObject *cache_str;
4853 return call_method(self, "__ipow__", &cache_str, "(" "O" ")", arg1);
Thomas Wouterscf297e42007-02-23 15:07:44 +00004854}
Guido van Rossumdc91b992001-08-08 22:26:22 +00004855SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *, "O")
4856SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *, "O")
4857SLOT1(slot_nb_inplace_and, "__iand__", PyObject *, "O")
4858SLOT1(slot_nb_inplace_xor, "__ixor__", PyObject *, "O")
4859SLOT1(slot_nb_inplace_or, "__ior__", PyObject *, "O")
4860SLOT1BIN(slot_nb_floor_divide, nb_floor_divide,
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004861 "__floordiv__", "__rfloordiv__")
Guido van Rossumdc91b992001-08-08 22:26:22 +00004862SLOT1BIN(slot_nb_true_divide, nb_true_divide, "__truediv__", "__rtruediv__")
4863SLOT1(slot_nb_inplace_floor_divide, "__ifloordiv__", PyObject *, "O")
4864SLOT1(slot_nb_inplace_true_divide, "__itruediv__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004865
Guido van Rossumb8f63662001-08-15 23:57:02 +00004866static PyObject *
4867slot_tp_repr(PyObject *self)
4868{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004869 PyObject *func, *res;
4870 static PyObject *repr_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004871
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004872 func = lookup_method(self, "__repr__", &repr_str);
4873 if (func != NULL) {
4874 res = PyEval_CallObject(func, NULL);
4875 Py_DECREF(func);
4876 return res;
4877 }
4878 PyErr_Clear();
4879 return PyUnicode_FromFormat("<%s object at %p>",
4880 Py_TYPE(self)->tp_name, self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004881}
4882
4883static PyObject *
4884slot_tp_str(PyObject *self)
4885{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004886 PyObject *func, *res;
4887 static PyObject *str_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004888
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004889 func = lookup_method(self, "__str__", &str_str);
4890 if (func != NULL) {
4891 res = PyEval_CallObject(func, NULL);
4892 Py_DECREF(func);
4893 return res;
4894 }
4895 else {
4896 PyObject *ress;
4897 PyErr_Clear();
4898 res = slot_tp_repr(self);
4899 if (!res)
4900 return NULL;
4901 ress = _PyUnicode_AsDefaultEncodedString(res, NULL);
4902 Py_DECREF(res);
4903 return ress;
4904 }
Guido van Rossumb8f63662001-08-15 23:57:02 +00004905}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004906
4907static long
4908slot_tp_hash(PyObject *self)
4909{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004910 PyObject *func, *res;
4911 static PyObject *hash_str;
4912 long h;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004913
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004914 func = lookup_method(self, "__hash__", &hash_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004915
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004916 if (func == Py_None) {
4917 Py_DECREF(func);
4918 func = NULL;
4919 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +00004920
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004921 if (func == NULL) {
4922 return PyObject_HashNotImplemented(self);
4923 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +00004924
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004925 res = PyEval_CallObject(func, NULL);
4926 Py_DECREF(func);
4927 if (res == NULL)
4928 return -1;
4929 if (PyLong_Check(res))
4930 h = PyLong_Type.tp_hash(res);
4931 else
4932 h = PyLong_AsLong(res);
4933 Py_DECREF(res);
4934 if (h == -1 && !PyErr_Occurred())
4935 h = -2;
4936 return h;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004937}
4938
4939static PyObject *
4940slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds)
4941{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004942 static PyObject *call_str;
4943 PyObject *meth = lookup_method(self, "__call__", &call_str);
4944 PyObject *res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004945
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004946 if (meth == NULL)
4947 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004948
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004949 res = PyObject_Call(meth, args, kwds);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004950
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004951 Py_DECREF(meth);
4952 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004953}
4954
Guido van Rossum14a6f832001-10-17 13:59:09 +00004955/* There are two slot dispatch functions for tp_getattro.
4956
4957 - slot_tp_getattro() is used when __getattribute__ is overridden
4958 but no __getattr__ hook is present;
4959
4960 - slot_tp_getattr_hook() is used when a __getattr__ hook is present.
4961
Guido van Rossumc334df52002-04-04 23:44:47 +00004962 The code in update_one_slot() always installs slot_tp_getattr_hook(); this
4963 detects the absence of __getattr__ and then installs the simpler slot if
4964 necessary. */
Guido van Rossum14a6f832001-10-17 13:59:09 +00004965
Tim Peters6d6c1a32001-08-02 04:15:00 +00004966static PyObject *
4967slot_tp_getattro(PyObject *self, PyObject *name)
4968{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004969 static PyObject *getattribute_str = NULL;
4970 return call_method(self, "__getattribute__", &getattribute_str,
4971 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004972}
4973
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004974static PyObject *
Benjamin Peterson9262b842008-11-17 22:45:50 +00004975call_attribute(PyObject *self, PyObject *attr, PyObject *name)
4976{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004977 PyObject *res, *descr = NULL;
4978 descrgetfunc f = Py_TYPE(attr)->tp_descr_get;
Benjamin Peterson9262b842008-11-17 22:45:50 +00004979
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004980 if (f != NULL) {
4981 descr = f(attr, self, (PyObject *)(Py_TYPE(self)));
4982 if (descr == NULL)
4983 return NULL;
4984 else
4985 attr = descr;
4986 }
4987 res = PyObject_CallFunctionObjArgs(attr, name, NULL);
4988 Py_XDECREF(descr);
4989 return res;
Benjamin Peterson9262b842008-11-17 22:45:50 +00004990}
4991
4992static PyObject *
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004993slot_tp_getattr_hook(PyObject *self, PyObject *name)
4994{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004995 PyTypeObject *tp = Py_TYPE(self);
4996 PyObject *getattr, *getattribute, *res;
4997 static PyObject *getattribute_str = NULL;
4998 static PyObject *getattr_str = NULL;
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004999
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00005000 if (getattr_str == NULL) {
5001 getattr_str = PyUnicode_InternFromString("__getattr__");
5002 if (getattr_str == NULL)
5003 return NULL;
5004 }
5005 if (getattribute_str == NULL) {
5006 getattribute_str =
5007 PyUnicode_InternFromString("__getattribute__");
5008 if (getattribute_str == NULL)
5009 return NULL;
5010 }
5011 /* speed hack: we could use lookup_maybe, but that would resolve the
5012 method fully for each attribute lookup for classes with
5013 __getattr__, even when the attribute is present. So we use
5014 _PyType_Lookup and create the method only when needed, with
5015 call_attribute. */
5016 getattr = _PyType_Lookup(tp, getattr_str);
5017 if (getattr == NULL) {
5018 /* No __getattr__ hook: use a simpler dispatcher */
5019 tp->tp_getattro = slot_tp_getattro;
5020 return slot_tp_getattro(self, name);
5021 }
5022 Py_INCREF(getattr);
5023 /* speed hack: we could use lookup_maybe, but that would resolve the
5024 method fully for each attribute lookup for classes with
5025 __getattr__, even when self has the default __getattribute__
5026 method. So we use _PyType_Lookup and create the method only when
5027 needed, with call_attribute. */
5028 getattribute = _PyType_Lookup(tp, getattribute_str);
5029 if (getattribute == NULL ||
5030 (Py_TYPE(getattribute) == &PyWrapperDescr_Type &&
5031 ((PyWrapperDescrObject *)getattribute)->d_wrapped ==
5032 (void *)PyObject_GenericGetAttr))
5033 res = PyObject_GenericGetAttr(self, name);
5034 else {
5035 Py_INCREF(getattribute);
5036 res = call_attribute(self, getattribute, name);
5037 Py_DECREF(getattribute);
5038 }
5039 if (res == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) {
5040 PyErr_Clear();
5041 res = call_attribute(self, getattr, name);
5042 }
5043 Py_DECREF(getattr);
5044 return res;
Guido van Rossum19c1cd52001-09-21 21:24:49 +00005045}
5046
Tim Peters6d6c1a32001-08-02 04:15:00 +00005047static int
5048slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value)
5049{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00005050 PyObject *res;
5051 static PyObject *delattr_str, *setattr_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005052
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00005053 if (value == NULL)
5054 res = call_method(self, "__delattr__", &delattr_str,
5055 "(O)", name);
5056 else
5057 res = call_method(self, "__setattr__", &setattr_str,
5058 "(OO)", name, value);
5059 if (res == NULL)
5060 return -1;
5061 Py_DECREF(res);
5062 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005063}
5064
Guido van Rossumf5243f02008-01-01 04:06:48 +00005065static char *name_op[] = {
5066 "__lt__",
5067 "__le__",
5068 "__eq__",
5069 "__ne__",
5070 "__gt__",
5071 "__ge__",
5072};
5073
Tim Peters6d6c1a32001-08-02 04:15:00 +00005074static PyObject *
Guido van Rossumb8f63662001-08-15 23:57:02 +00005075half_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005076{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00005077 PyObject *func, *args, *res;
5078 static PyObject *op_str[6];
Tim Peters6d6c1a32001-08-02 04:15:00 +00005079
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00005080 func = lookup_method(self, name_op[op], &op_str[op]);
5081 if (func == NULL) {
5082 PyErr_Clear();
5083 Py_INCREF(Py_NotImplemented);
5084 return Py_NotImplemented;
5085 }
5086 args = PyTuple_Pack(1, other);
5087 if (args == NULL)
5088 res = NULL;
5089 else {
5090 res = PyObject_Call(func, args, NULL);
5091 Py_DECREF(args);
5092 }
5093 Py_DECREF(func);
5094 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005095}
5096
Guido van Rossumb8f63662001-08-15 23:57:02 +00005097static PyObject *
5098slot_tp_richcompare(PyObject *self, PyObject *other, int op)
5099{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00005100 PyObject *res;
Guido van Rossumb8f63662001-08-15 23:57:02 +00005101
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00005102 if (Py_TYPE(self)->tp_richcompare == slot_tp_richcompare) {
5103 res = half_richcompare(self, other, op);
5104 if (res != Py_NotImplemented)
5105 return res;
5106 Py_DECREF(res);
5107 }
5108 if (Py_TYPE(other)->tp_richcompare == slot_tp_richcompare) {
5109 res = half_richcompare(other, self, _Py_SwappedOp[op]);
5110 if (res != Py_NotImplemented) {
5111 return res;
5112 }
5113 Py_DECREF(res);
5114 }
5115 Py_INCREF(Py_NotImplemented);
5116 return Py_NotImplemented;
Guido van Rossumb8f63662001-08-15 23:57:02 +00005117}
5118
5119static PyObject *
5120slot_tp_iter(PyObject *self)
5121{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00005122 PyObject *func, *res;
5123 static PyObject *iter_str, *getitem_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00005124
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00005125 func = lookup_method(self, "__iter__", &iter_str);
5126 if (func != NULL) {
5127 PyObject *args;
5128 args = res = PyTuple_New(0);
5129 if (args != NULL) {
5130 res = PyObject_Call(func, args, NULL);
5131 Py_DECREF(args);
5132 }
5133 Py_DECREF(func);
5134 return res;
5135 }
5136 PyErr_Clear();
5137 func = lookup_method(self, "__getitem__", &getitem_str);
5138 if (func == NULL) {
5139 PyErr_Format(PyExc_TypeError,
5140 "'%.200s' object is not iterable",
5141 Py_TYPE(self)->tp_name);
5142 return NULL;
5143 }
5144 Py_DECREF(func);
5145 return PySeqIter_New(self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005146}
Tim Peters6d6c1a32001-08-02 04:15:00 +00005147
5148static PyObject *
5149slot_tp_iternext(PyObject *self)
5150{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00005151 static PyObject *next_str;
5152 return call_method(self, "__next__", &next_str, "()");
Tim Peters6d6c1a32001-08-02 04:15:00 +00005153}
5154
Guido van Rossum1a493502001-08-17 16:47:50 +00005155static PyObject *
5156slot_tp_descr_get(PyObject *self, PyObject *obj, PyObject *type)
5157{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00005158 PyTypeObject *tp = Py_TYPE(self);
5159 PyObject *get;
5160 static PyObject *get_str = NULL;
Guido van Rossum1a493502001-08-17 16:47:50 +00005161
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00005162 if (get_str == NULL) {
5163 get_str = PyUnicode_InternFromString("__get__");
5164 if (get_str == NULL)
5165 return NULL;
5166 }
5167 get = _PyType_Lookup(tp, get_str);
5168 if (get == NULL) {
5169 /* Avoid further slowdowns */
5170 if (tp->tp_descr_get == slot_tp_descr_get)
5171 tp->tp_descr_get = NULL;
5172 Py_INCREF(self);
5173 return self;
5174 }
5175 if (obj == NULL)
5176 obj = Py_None;
5177 if (type == NULL)
5178 type = Py_None;
5179 return PyObject_CallFunctionObjArgs(get, self, obj, type, NULL);
Guido van Rossum1a493502001-08-17 16:47:50 +00005180}
Tim Peters6d6c1a32001-08-02 04:15:00 +00005181
5182static int
5183slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value)
5184{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00005185 PyObject *res;
5186 static PyObject *del_str, *set_str;
Guido van Rossum2c252392001-08-24 10:13:31 +00005187
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00005188 if (value == NULL)
5189 res = call_method(self, "__delete__", &del_str,
5190 "(O)", target);
5191 else
5192 res = call_method(self, "__set__", &set_str,
5193 "(OO)", target, value);
5194 if (res == NULL)
5195 return -1;
5196 Py_DECREF(res);
5197 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005198}
5199
5200static int
5201slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds)
5202{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00005203 static PyObject *init_str;
5204 PyObject *meth = lookup_method(self, "__init__", &init_str);
5205 PyObject *res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005206
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00005207 if (meth == NULL)
5208 return -1;
5209 res = PyObject_Call(meth, args, kwds);
5210 Py_DECREF(meth);
5211 if (res == NULL)
5212 return -1;
5213 if (res != Py_None) {
5214 PyErr_Format(PyExc_TypeError,
5215 "__init__() should return None, not '%.200s'",
5216 Py_TYPE(res)->tp_name);
5217 Py_DECREF(res);
5218 return -1;
5219 }
5220 Py_DECREF(res);
5221 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005222}
5223
5224static PyObject *
5225slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
5226{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00005227 static PyObject *new_str;
5228 PyObject *func;
5229 PyObject *newargs, *x;
5230 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005231
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00005232 if (new_str == NULL) {
5233 new_str = PyUnicode_InternFromString("__new__");
5234 if (new_str == NULL)
5235 return NULL;
5236 }
5237 func = PyObject_GetAttr((PyObject *)type, new_str);
5238 if (func == NULL)
5239 return NULL;
5240 assert(PyTuple_Check(args));
5241 n = PyTuple_GET_SIZE(args);
5242 newargs = PyTuple_New(n+1);
5243 if (newargs == NULL)
5244 return NULL;
5245 Py_INCREF(type);
5246 PyTuple_SET_ITEM(newargs, 0, (PyObject *)type);
5247 for (i = 0; i < n; i++) {
5248 x = PyTuple_GET_ITEM(args, i);
5249 Py_INCREF(x);
5250 PyTuple_SET_ITEM(newargs, i+1, x);
5251 }
5252 x = PyObject_Call(func, newargs, kwds);
5253 Py_DECREF(newargs);
5254 Py_DECREF(func);
5255 return x;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005256}
5257
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005258static void
5259slot_tp_del(PyObject *self)
5260{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00005261 static PyObject *del_str = NULL;
5262 PyObject *del, *res;
5263 PyObject *error_type, *error_value, *error_traceback;
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005264
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00005265 /* Temporarily resurrect the object. */
5266 assert(self->ob_refcnt == 0);
5267 self->ob_refcnt = 1;
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005268
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00005269 /* Save the current exception, if any. */
5270 PyErr_Fetch(&error_type, &error_value, &error_traceback);
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005271
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00005272 /* Execute __del__ method, if any. */
5273 del = lookup_maybe(self, "__del__", &del_str);
5274 if (del != NULL) {
5275 res = PyEval_CallObject(del, NULL);
5276 if (res == NULL)
5277 PyErr_WriteUnraisable(del);
5278 else
5279 Py_DECREF(res);
5280 Py_DECREF(del);
5281 }
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005282
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00005283 /* Restore the saved exception. */
5284 PyErr_Restore(error_type, error_value, error_traceback);
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005285
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00005286 /* Undo the temporary resurrection; can't use DECREF here, it would
5287 * cause a recursive call.
5288 */
5289 assert(self->ob_refcnt > 0);
5290 if (--self->ob_refcnt == 0)
5291 return; /* this is the normal path out */
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005292
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00005293 /* __del__ resurrected it! Make it look like the original Py_DECREF
5294 * never happened.
5295 */
5296 {
5297 Py_ssize_t refcnt = self->ob_refcnt;
5298 _Py_NewReference(self);
5299 self->ob_refcnt = refcnt;
5300 }
5301 assert(!PyType_IS_GC(Py_TYPE(self)) ||
5302 _Py_AS_GC(self)->gc.gc_refs != _PyGC_REFS_UNTRACKED);
5303 /* If Py_REF_DEBUG, _Py_NewReference bumped _Py_RefTotal, so
5304 * we need to undo that. */
5305 _Py_DEC_REFTOTAL;
5306 /* If Py_TRACE_REFS, _Py_NewReference re-added self to the object
5307 * chain, so no more to do there.
5308 * If COUNT_ALLOCS, the original decref bumped tp_frees, and
5309 * _Py_NewReference bumped tp_allocs: both of those need to be
5310 * undone.
5311 */
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005312#ifdef COUNT_ALLOCS
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00005313 --Py_TYPE(self)->tp_frees;
5314 --Py_TYPE(self)->tp_allocs;
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005315#endif
5316}
5317
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005318
5319/* Table mapping __foo__ names to tp_foo offsets and slot_tp_foo wrapper
Tim Petersbf9b2442003-03-23 05:35:36 +00005320 functions. The offsets here are relative to the 'PyHeapTypeObject'
Guido van Rossume5c691a2003-03-07 15:13:17 +00005321 structure, which incorporates the additional structures used for numbers,
5322 sequences and mappings.
5323 Note that multiple names may map to the same slot (e.g. __eq__,
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005324 __ne__ etc. all map to tp_richcompare) and one name may map to multiple
Guido van Rossumc334df52002-04-04 23:44:47 +00005325 slots (e.g. __str__ affects tp_str as well as tp_repr). The table is
5326 terminated with an all-zero entry. (This table is further initialized and
5327 sorted in init_slotdefs() below.) */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005328
Guido van Rossum6d204072001-10-21 00:44:31 +00005329typedef struct wrapperbase slotdef;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005330
5331#undef TPSLOT
Guido van Rossumc8e56452001-10-22 00:43:43 +00005332#undef FLSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005333#undef ETSLOT
5334#undef SQSLOT
5335#undef MPSLOT
5336#undef NBSLOT
Guido van Rossum6d204072001-10-21 00:44:31 +00005337#undef UNSLOT
5338#undef IBSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005339#undef BINSLOT
5340#undef RBINSLOT
5341
Guido van Rossum6d204072001-10-21 00:44:31 +00005342#define TPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00005343 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
5344 PyDoc_STR(DOC)}
Guido van Rossumc8e56452001-10-22 00:43:43 +00005345#define FLSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC, FLAGS) \
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00005346 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
5347 PyDoc_STR(DOC), FLAGS}
Guido van Rossum6d204072001-10-21 00:44:31 +00005348#define ETSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00005349 {NAME, offsetof(PyHeapTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
5350 PyDoc_STR(DOC)}
Guido van Rossum6d204072001-10-21 00:44:31 +00005351#define SQSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00005352 ETSLOT(NAME, as_sequence.SLOT, FUNCTION, WRAPPER, DOC)
Guido van Rossum6d204072001-10-21 00:44:31 +00005353#define MPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00005354 ETSLOT(NAME, as_mapping.SLOT, FUNCTION, WRAPPER, DOC)
Guido van Rossum6d204072001-10-21 00:44:31 +00005355#define NBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00005356 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, DOC)
Guido van Rossum6d204072001-10-21 00:44:31 +00005357#define UNSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00005358 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
5359 "x." NAME "() <==> " DOC)
Guido van Rossum6d204072001-10-21 00:44:31 +00005360#define IBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00005361 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
5362 "x." NAME "(y) <==> x" DOC "y")
Guido van Rossum6d204072001-10-21 00:44:31 +00005363#define BINSLOT(NAME, SLOT, FUNCTION, DOC) \
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00005364 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
5365 "x." NAME "(y) <==> x" DOC "y")
Guido van Rossum6d204072001-10-21 00:44:31 +00005366#define RBINSLOT(NAME, SLOT, FUNCTION, DOC) \
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00005367 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
5368 "x." NAME "(y) <==> y" DOC "x")
Anthony Baxter56616992005-06-03 14:12:21 +00005369#define BINSLOTNOTINFIX(NAME, SLOT, FUNCTION, DOC) \
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00005370 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
5371 "x." NAME "(y) <==> " DOC)
Anthony Baxter56616992005-06-03 14:12:21 +00005372#define RBINSLOTNOTINFIX(NAME, SLOT, FUNCTION, DOC) \
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00005373 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
5374 "x." NAME "(y) <==> " DOC)
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005375
5376static slotdef slotdefs[] = {
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00005377 SQSLOT("__len__", sq_length, slot_sq_length, wrap_lenfunc,
5378 "x.__len__() <==> len(x)"),
5379 /* Heap types defining __add__/__mul__ have sq_concat/sq_repeat == NULL.
5380 The logic in abstract.c always falls back to nb_add/nb_multiply in
5381 this case. Defining both the nb_* and the sq_* slots to call the
5382 user-defined methods has unexpected side-effects, as shown by
5383 test_descr.notimplemented() */
5384 SQSLOT("__add__", sq_concat, NULL, wrap_binaryfunc,
5385 "x.__add__(y) <==> x+y"),
5386 SQSLOT("__mul__", sq_repeat, NULL, wrap_indexargfunc,
5387 "x.__mul__(n) <==> x*n"),
5388 SQSLOT("__rmul__", sq_repeat, NULL, wrap_indexargfunc,
5389 "x.__rmul__(n) <==> n*x"),
5390 SQSLOT("__getitem__", sq_item, slot_sq_item, wrap_sq_item,
5391 "x.__getitem__(y) <==> x[y]"),
5392 SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_setitem,
5393 "x.__setitem__(i, y) <==> x[i]=y"),
5394 SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_delitem,
5395 "x.__delitem__(y) <==> del x[y]"),
5396 SQSLOT("__contains__", sq_contains, slot_sq_contains, wrap_objobjproc,
5397 "x.__contains__(y) <==> y in x"),
5398 SQSLOT("__iadd__", sq_inplace_concat, NULL,
5399 wrap_binaryfunc, "x.__iadd__(y) <==> x+=y"),
5400 SQSLOT("__imul__", sq_inplace_repeat, NULL,
5401 wrap_indexargfunc, "x.__imul__(y) <==> x*=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005402
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00005403 MPSLOT("__len__", mp_length, slot_mp_length, wrap_lenfunc,
5404 "x.__len__() <==> len(x)"),
5405 MPSLOT("__getitem__", mp_subscript, slot_mp_subscript,
5406 wrap_binaryfunc,
5407 "x.__getitem__(y) <==> x[y]"),
5408 MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript,
5409 wrap_objobjargproc,
5410 "x.__setitem__(i, y) <==> x[i]=y"),
5411 MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript,
5412 wrap_delitem,
5413 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005414
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00005415 BINSLOT("__add__", nb_add, slot_nb_add,
5416 "+"),
5417 RBINSLOT("__radd__", nb_add, slot_nb_add,
5418 "+"),
5419 BINSLOT("__sub__", nb_subtract, slot_nb_subtract,
5420 "-"),
5421 RBINSLOT("__rsub__", nb_subtract, slot_nb_subtract,
5422 "-"),
5423 BINSLOT("__mul__", nb_multiply, slot_nb_multiply,
5424 "*"),
5425 RBINSLOT("__rmul__", nb_multiply, slot_nb_multiply,
5426 "*"),
5427 BINSLOT("__mod__", nb_remainder, slot_nb_remainder,
5428 "%"),
5429 RBINSLOT("__rmod__", nb_remainder, slot_nb_remainder,
5430 "%"),
5431 BINSLOTNOTINFIX("__divmod__", nb_divmod, slot_nb_divmod,
5432 "divmod(x, y)"),
5433 RBINSLOTNOTINFIX("__rdivmod__", nb_divmod, slot_nb_divmod,
5434 "divmod(y, x)"),
5435 NBSLOT("__pow__", nb_power, slot_nb_power, wrap_ternaryfunc,
5436 "x.__pow__(y[, z]) <==> pow(x, y[, z])"),
5437 NBSLOT("__rpow__", nb_power, slot_nb_power, wrap_ternaryfunc_r,
5438 "y.__rpow__(x[, z]) <==> pow(x, y[, z])"),
5439 UNSLOT("__neg__", nb_negative, slot_nb_negative, wrap_unaryfunc, "-x"),
5440 UNSLOT("__pos__", nb_positive, slot_nb_positive, wrap_unaryfunc, "+x"),
5441 UNSLOT("__abs__", nb_absolute, slot_nb_absolute, wrap_unaryfunc,
5442 "abs(x)"),
5443 UNSLOT("__bool__", nb_bool, slot_nb_bool, wrap_inquirypred,
5444 "x != 0"),
5445 UNSLOT("__invert__", nb_invert, slot_nb_invert, wrap_unaryfunc, "~x"),
5446 BINSLOT("__lshift__", nb_lshift, slot_nb_lshift, "<<"),
5447 RBINSLOT("__rlshift__", nb_lshift, slot_nb_lshift, "<<"),
5448 BINSLOT("__rshift__", nb_rshift, slot_nb_rshift, ">>"),
5449 RBINSLOT("__rrshift__", nb_rshift, slot_nb_rshift, ">>"),
5450 BINSLOT("__and__", nb_and, slot_nb_and, "&"),
5451 RBINSLOT("__rand__", nb_and, slot_nb_and, "&"),
5452 BINSLOT("__xor__", nb_xor, slot_nb_xor, "^"),
5453 RBINSLOT("__rxor__", nb_xor, slot_nb_xor, "^"),
5454 BINSLOT("__or__", nb_or, slot_nb_or, "|"),
5455 RBINSLOT("__ror__", nb_or, slot_nb_or, "|"),
5456 UNSLOT("__int__", nb_int, slot_nb_int, wrap_unaryfunc,
5457 "int(x)"),
5458 UNSLOT("__float__", nb_float, slot_nb_float, wrap_unaryfunc,
5459 "float(x)"),
5460 NBSLOT("__index__", nb_index, slot_nb_index, wrap_unaryfunc,
5461 "x[y:z] <==> x[y.__index__():z.__index__()]"),
5462 IBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add,
5463 wrap_binaryfunc, "+"),
5464 IBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract,
5465 wrap_binaryfunc, "-"),
5466 IBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply,
5467 wrap_binaryfunc, "*"),
5468 IBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder,
5469 wrap_binaryfunc, "%"),
5470 IBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power,
5471 wrap_binaryfunc, "**"),
5472 IBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift,
5473 wrap_binaryfunc, "<<"),
5474 IBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift,
5475 wrap_binaryfunc, ">>"),
5476 IBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and,
5477 wrap_binaryfunc, "&"),
5478 IBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor,
5479 wrap_binaryfunc, "^"),
5480 IBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or,
5481 wrap_binaryfunc, "|"),
5482 BINSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
5483 RBINSLOT("__rfloordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
5484 BINSLOT("__truediv__", nb_true_divide, slot_nb_true_divide, "/"),
5485 RBINSLOT("__rtruediv__", nb_true_divide, slot_nb_true_divide, "/"),
5486 IBSLOT("__ifloordiv__", nb_inplace_floor_divide,
5487 slot_nb_inplace_floor_divide, wrap_binaryfunc, "//"),
5488 IBSLOT("__itruediv__", nb_inplace_true_divide,
5489 slot_nb_inplace_true_divide, wrap_binaryfunc, "/"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005490
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00005491 TPSLOT("__str__", tp_str, slot_tp_str, wrap_unaryfunc,
5492 "x.__str__() <==> str(x)"),
5493 TPSLOT("__repr__", tp_repr, slot_tp_repr, wrap_unaryfunc,
5494 "x.__repr__() <==> repr(x)"),
5495 TPSLOT("__hash__", tp_hash, slot_tp_hash, wrap_hashfunc,
5496 "x.__hash__() <==> hash(x)"),
5497 FLSLOT("__call__", tp_call, slot_tp_call, (wrapperfunc)wrap_call,
5498 "x.__call__(...) <==> x(...)", PyWrapperFlag_KEYWORDS),
5499 TPSLOT("__getattribute__", tp_getattro, slot_tp_getattr_hook,
5500 wrap_binaryfunc, "x.__getattribute__('name') <==> x.name"),
5501 TPSLOT("__getattribute__", tp_getattr, NULL, NULL, ""),
5502 TPSLOT("__getattr__", tp_getattro, slot_tp_getattr_hook, NULL, ""),
5503 TPSLOT("__getattr__", tp_getattr, NULL, NULL, ""),
5504 TPSLOT("__setattr__", tp_setattro, slot_tp_setattro, wrap_setattr,
5505 "x.__setattr__('name', value) <==> x.name = value"),
5506 TPSLOT("__setattr__", tp_setattr, NULL, NULL, ""),
5507 TPSLOT("__delattr__", tp_setattro, slot_tp_setattro, wrap_delattr,
5508 "x.__delattr__('name') <==> del x.name"),
5509 TPSLOT("__delattr__", tp_setattr, NULL, NULL, ""),
5510 TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare, richcmp_lt,
5511 "x.__lt__(y) <==> x<y"),
5512 TPSLOT("__le__", tp_richcompare, slot_tp_richcompare, richcmp_le,
5513 "x.__le__(y) <==> x<=y"),
5514 TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare, richcmp_eq,
5515 "x.__eq__(y) <==> x==y"),
5516 TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare, richcmp_ne,
5517 "x.__ne__(y) <==> x!=y"),
5518 TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare, richcmp_gt,
5519 "x.__gt__(y) <==> x>y"),
5520 TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare, richcmp_ge,
5521 "x.__ge__(y) <==> x>=y"),
5522 TPSLOT("__iter__", tp_iter, slot_tp_iter, wrap_unaryfunc,
5523 "x.__iter__() <==> iter(x)"),
5524 TPSLOT("__next__", tp_iternext, slot_tp_iternext, wrap_next,
5525 "x.__next__() <==> next(x)"),
5526 TPSLOT("__get__", tp_descr_get, slot_tp_descr_get, wrap_descr_get,
5527 "descr.__get__(obj[, type]) -> value"),
5528 TPSLOT("__set__", tp_descr_set, slot_tp_descr_set, wrap_descr_set,
5529 "descr.__set__(obj, value)"),
5530 TPSLOT("__delete__", tp_descr_set, slot_tp_descr_set,
5531 wrap_descr_delete, "descr.__delete__(obj)"),
5532 FLSLOT("__init__", tp_init, slot_tp_init, (wrapperfunc)wrap_init,
5533 "x.__init__(...) initializes x; "
Alexander Belopolsky102594f2010-08-16 20:26:04 +00005534 "see help(type(x)) for signature",
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00005535 PyWrapperFlag_KEYWORDS),
5536 TPSLOT("__new__", tp_new, slot_tp_new, NULL, ""),
5537 TPSLOT("__del__", tp_del, slot_tp_del, NULL, ""),
5538 {NULL}
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005539};
5540
Guido van Rossumc334df52002-04-04 23:44:47 +00005541/* Given a type pointer and an offset gotten from a slotdef entry, return a
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00005542 pointer to the actual slot. This is not quite the same as simply adding
Guido van Rossumc334df52002-04-04 23:44:47 +00005543 the offset to the type pointer, since it takes care to indirect through the
5544 proper indirection pointer (as_buffer, etc.); it returns NULL if the
5545 indirection pointer is NULL. */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005546static void **
Martin v. Löwis18e16552006-02-15 17:27:45 +00005547slotptr(PyTypeObject *type, int ioffset)
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005548{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00005549 char *ptr;
5550 long offset = ioffset;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005551
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00005552 /* Note: this depends on the order of the members of PyHeapTypeObject! */
5553 assert(offset >= 0);
5554 assert((size_t)offset < offsetof(PyHeapTypeObject, as_buffer));
5555 if ((size_t)offset >= offsetof(PyHeapTypeObject, as_sequence)) {
5556 ptr = (char *)type->tp_as_sequence;
5557 offset -= offsetof(PyHeapTypeObject, as_sequence);
5558 }
5559 else if ((size_t)offset >= offsetof(PyHeapTypeObject, as_mapping)) {
5560 ptr = (char *)type->tp_as_mapping;
5561 offset -= offsetof(PyHeapTypeObject, as_mapping);
5562 }
5563 else if ((size_t)offset >= offsetof(PyHeapTypeObject, as_number)) {
5564 ptr = (char *)type->tp_as_number;
5565 offset -= offsetof(PyHeapTypeObject, as_number);
5566 }
5567 else {
5568 ptr = (char *)type;
5569 }
5570 if (ptr != NULL)
5571 ptr += offset;
5572 return (void **)ptr;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005573}
Guido van Rossumf040ede2001-08-07 16:40:56 +00005574
Guido van Rossumc334df52002-04-04 23:44:47 +00005575/* Length of array of slotdef pointers used to store slots with the
5576 same __name__. There should be at most MAX_EQUIV-1 slotdef entries with
5577 the same __name__, for any __name__. Since that's a static property, it is
5578 appropriate to declare fixed-size arrays for this. */
5579#define MAX_EQUIV 10
5580
5581/* Return a slot pointer for a given name, but ONLY if the attribute has
5582 exactly one slot function. The name must be an interned string. */
5583static void **
5584resolve_slotdups(PyTypeObject *type, PyObject *name)
5585{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00005586 /* XXX Maybe this could be optimized more -- but is it worth it? */
Guido van Rossumc334df52002-04-04 23:44:47 +00005587
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00005588 /* pname and ptrs act as a little cache */
5589 static PyObject *pname;
5590 static slotdef *ptrs[MAX_EQUIV];
5591 slotdef *p, **pp;
5592 void **res, **ptr;
Guido van Rossumc334df52002-04-04 23:44:47 +00005593
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00005594 if (pname != name) {
5595 /* Collect all slotdefs that match name into ptrs. */
5596 pname = name;
5597 pp = ptrs;
5598 for (p = slotdefs; p->name_strobj; p++) {
5599 if (p->name_strobj == name)
5600 *pp++ = p;
5601 }
5602 *pp = NULL;
5603 }
Guido van Rossumc334df52002-04-04 23:44:47 +00005604
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00005605 /* Look in all matching slots of the type; if exactly one of these has
5606 a filled-in slot, return its value. Otherwise return NULL. */
5607 res = NULL;
5608 for (pp = ptrs; *pp; pp++) {
5609 ptr = slotptr(type, (*pp)->offset);
5610 if (ptr == NULL || *ptr == NULL)
5611 continue;
5612 if (res != NULL)
5613 return NULL;
5614 res = ptr;
5615 }
5616 return res;
Guido van Rossumc334df52002-04-04 23:44:47 +00005617}
5618
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005619/* Common code for update_slots_callback() and fixup_slot_dispatchers(). This
Guido van Rossumc334df52002-04-04 23:44:47 +00005620 does some incredibly complex thinking and then sticks something into the
5621 slot. (It sees if the adjacent slotdefs for the same slot have conflicting
5622 interests, and then stores a generic wrapper or a specific function into
5623 the slot.) Return a pointer to the next slotdef with a different offset,
5624 because that's convenient for fixup_slot_dispatchers(). */
5625static slotdef *
5626update_one_slot(PyTypeObject *type, slotdef *p)
5627{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00005628 PyObject *descr;
5629 PyWrapperDescrObject *d;
5630 void *generic = NULL, *specific = NULL;
5631 int use_generic = 0;
5632 int offset = p->offset;
5633 void **ptr = slotptr(type, offset);
Guido van Rossumc334df52002-04-04 23:44:47 +00005634
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00005635 if (ptr == NULL) {
5636 do {
5637 ++p;
5638 } while (p->offset == offset);
5639 return p;
5640 }
5641 do {
5642 descr = _PyType_Lookup(type, p->name_strobj);
5643 if (descr == NULL) {
5644 if (ptr == (void**)&type->tp_iternext) {
5645 specific = _PyObject_NextNotImplemented;
5646 }
5647 continue;
5648 }
5649 if (Py_TYPE(descr) == &PyWrapperDescr_Type) {
5650 void **tptr = resolve_slotdups(type, p->name_strobj);
5651 if (tptr == NULL || tptr == ptr)
5652 generic = p->function;
5653 d = (PyWrapperDescrObject *)descr;
5654 if (d->d_base->wrapper == p->wrapper &&
5655 PyType_IsSubtype(type, d->d_type))
5656 {
5657 if (specific == NULL ||
5658 specific == d->d_wrapped)
5659 specific = d->d_wrapped;
5660 else
5661 use_generic = 1;
5662 }
5663 }
5664 else if (Py_TYPE(descr) == &PyCFunction_Type &&
5665 PyCFunction_GET_FUNCTION(descr) ==
5666 (PyCFunction)tp_new_wrapper &&
5667 ptr == (void**)&type->tp_new)
5668 {
5669 /* The __new__ wrapper is not a wrapper descriptor,
5670 so must be special-cased differently.
5671 If we don't do this, creating an instance will
5672 always use slot_tp_new which will look up
5673 __new__ in the MRO which will call tp_new_wrapper
5674 which will look through the base classes looking
5675 for a static base and call its tp_new (usually
5676 PyType_GenericNew), after performing various
5677 sanity checks and constructing a new argument
5678 list. Cut all that nonsense short -- this speeds
5679 up instance creation tremendously. */
5680 specific = (void *)type->tp_new;
5681 /* XXX I'm not 100% sure that there isn't a hole
5682 in this reasoning that requires additional
5683 sanity checks. I'll buy the first person to
5684 point out a bug in this reasoning a beer. */
5685 }
5686 else if (descr == Py_None &&
5687 ptr == (void**)&type->tp_hash) {
5688 /* We specifically allow __hash__ to be set to None
5689 to prevent inheritance of the default
5690 implementation from object.__hash__ */
5691 specific = PyObject_HashNotImplemented;
5692 }
5693 else {
5694 use_generic = 1;
5695 generic = p->function;
5696 }
5697 } while ((++p)->offset == offset);
5698 if (specific && !use_generic)
5699 *ptr = specific;
5700 else
5701 *ptr = generic;
5702 return p;
Guido van Rossumc334df52002-04-04 23:44:47 +00005703}
5704
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005705/* In the type, update the slots whose slotdefs are gathered in the pp array.
5706 This is a callback for update_subclasses(). */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005707static int
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005708update_slots_callback(PyTypeObject *type, void *data)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005709{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00005710 slotdef **pp = (slotdef **)data;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005711
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00005712 for (; *pp; pp++)
5713 update_one_slot(type, *pp);
5714 return 0;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005715}
5716
Guido van Rossumc334df52002-04-04 23:44:47 +00005717/* Comparison function for qsort() to compare slotdefs by their offset, and
5718 for equal offset by their address (to force a stable sort). */
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005719static int
5720slotdef_cmp(const void *aa, const void *bb)
5721{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00005722 const slotdef *a = (const slotdef *)aa, *b = (const slotdef *)bb;
5723 int c = a->offset - b->offset;
5724 if (c != 0)
5725 return c;
5726 else
5727 /* Cannot use a-b, as this gives off_t,
5728 which may lose precision when converted to int. */
5729 return (a > b) ? 1 : (a < b) ? -1 : 0;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005730}
5731
Guido van Rossumc334df52002-04-04 23:44:47 +00005732/* Initialize the slotdefs table by adding interned string objects for the
5733 names and sorting the entries. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005734static void
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005735init_slotdefs(void)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005736{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00005737 slotdef *p;
5738 static int initialized = 0;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005739
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00005740 if (initialized)
5741 return;
5742 for (p = slotdefs; p->name; p++) {
5743 p->name_strobj = PyUnicode_InternFromString(p->name);
5744 if (!p->name_strobj)
5745 Py_FatalError("Out of memory interning slotdef names");
5746 }
5747 qsort((void *)slotdefs, (size_t)(p-slotdefs), sizeof(slotdef),
5748 slotdef_cmp);
5749 initialized = 1;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005750}
5751
Guido van Rossumc334df52002-04-04 23:44:47 +00005752/* Update the slots after assignment to a class (type) attribute. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005753static int
5754update_slot(PyTypeObject *type, PyObject *name)
5755{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00005756 slotdef *ptrs[MAX_EQUIV];
5757 slotdef *p;
5758 slotdef **pp;
5759 int offset;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005760
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00005761 /* Clear the VALID_VERSION flag of 'type' and all its
5762 subclasses. This could possibly be unified with the
5763 update_subclasses() recursion below, but carefully:
5764 they each have their own conditions on which to stop
5765 recursing into subclasses. */
5766 PyType_Modified(type);
Christian Heimesa62da1d2008-01-12 19:39:10 +00005767
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00005768 init_slotdefs();
5769 pp = ptrs;
5770 for (p = slotdefs; p->name; p++) {
5771 /* XXX assume name is interned! */
5772 if (p->name_strobj == name)
5773 *pp++ = p;
5774 }
5775 *pp = NULL;
5776 for (pp = ptrs; *pp; pp++) {
5777 p = *pp;
5778 offset = p->offset;
5779 while (p > slotdefs && (p-1)->offset == offset)
5780 --p;
5781 *pp = p;
5782 }
5783 if (ptrs[0] == NULL)
5784 return 0; /* Not an attribute that affects any slots */
5785 return update_subclasses(type, name,
5786 update_slots_callback, (void *)ptrs);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005787}
5788
Guido van Rossumc334df52002-04-04 23:44:47 +00005789/* Store the proper functions in the slot dispatches at class (type)
5790 definition time, based upon which operations the class overrides in its
5791 dict. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00005792static void
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005793fixup_slot_dispatchers(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005794{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00005795 slotdef *p;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005796
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00005797 init_slotdefs();
5798 for (p = slotdefs; p->name; )
5799 p = update_one_slot(type, p);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005800}
Guido van Rossum705f0f52001-08-24 16:47:00 +00005801
Michael W. Hudson98bbc492002-11-26 14:47:27 +00005802static void
5803update_all_slots(PyTypeObject* type)
5804{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00005805 slotdef *p;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00005806
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00005807 init_slotdefs();
5808 for (p = slotdefs; p->name; p++) {
5809 /* update_slot returns int but can't actually fail */
5810 update_slot(type, p->name_strobj);
5811 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +00005812}
5813
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005814/* recurse_down_subclasses() and update_subclasses() are mutually
5815 recursive functions to call a callback for all subclasses,
5816 but refraining from recursing into subclasses that define 'name'. */
5817
5818static int
5819update_subclasses(PyTypeObject *type, PyObject *name,
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00005820 update_callback callback, void *data)
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005821{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00005822 if (callback(type, data) < 0)
5823 return -1;
5824 return recurse_down_subclasses(type, name, callback, data);
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005825}
5826
5827static int
5828recurse_down_subclasses(PyTypeObject *type, PyObject *name,
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00005829 update_callback callback, void *data)
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005830{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00005831 PyTypeObject *subclass;
5832 PyObject *ref, *subclasses, *dict;
5833 Py_ssize_t i, n;
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005834
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00005835 subclasses = type->tp_subclasses;
5836 if (subclasses == NULL)
5837 return 0;
5838 assert(PyList_Check(subclasses));
5839 n = PyList_GET_SIZE(subclasses);
5840 for (i = 0; i < n; i++) {
5841 ref = PyList_GET_ITEM(subclasses, i);
5842 assert(PyWeakref_CheckRef(ref));
5843 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
5844 assert(subclass != NULL);
5845 if ((PyObject *)subclass == Py_None)
5846 continue;
5847 assert(PyType_Check(subclass));
5848 /* Avoid recursing down into unaffected classes */
5849 dict = subclass->tp_dict;
5850 if (dict != NULL && PyDict_Check(dict) &&
5851 PyDict_GetItem(dict, name) != NULL)
5852 continue;
5853 if (update_subclasses(subclass, name, callback, data) < 0)
5854 return -1;
5855 }
5856 return 0;
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005857}
5858
Guido van Rossum6d204072001-10-21 00:44:31 +00005859/* This function is called by PyType_Ready() to populate the type's
5860 dictionary with method descriptors for function slots. For each
Guido van Rossum09638c12002-06-13 19:17:46 +00005861 function slot (like tp_repr) that's defined in the type, one or more
5862 corresponding descriptors are added in the type's tp_dict dictionary
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00005863 under the appropriate name (like __repr__). Some function slots
Guido van Rossum09638c12002-06-13 19:17:46 +00005864 cause more than one descriptor to be added (for example, the nb_add
5865 slot adds both __add__ and __radd__ descriptors) and some function
5866 slots compete for the same descriptor (for example both sq_item and
5867 mp_subscript generate a __getitem__ descriptor).
5868
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00005869 In the latter case, the first slotdef entry encoutered wins. Since
Tim Petersbf9b2442003-03-23 05:35:36 +00005870 slotdef entries are sorted by the offset of the slot in the
Guido van Rossume5c691a2003-03-07 15:13:17 +00005871 PyHeapTypeObject, this gives us some control over disambiguating
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005872 between competing slots: the members of PyHeapTypeObject are listed
5873 from most general to least general, so the most general slot is
5874 preferred. In particular, because as_mapping comes before as_sequence,
5875 for a type that defines both mp_subscript and sq_item, mp_subscript
5876 wins.
Guido van Rossum09638c12002-06-13 19:17:46 +00005877
5878 This only adds new descriptors and doesn't overwrite entries in
5879 tp_dict that were previously defined. The descriptors contain a
5880 reference to the C function they must call, so that it's safe if they
5881 are copied into a subtype's __dict__ and the subtype has a different
5882 C function in its slot -- calling the method defined by the
5883 descriptor will call the C function that was used to create it,
5884 rather than the C function present in the slot when it is called.
5885 (This is important because a subtype may have a C function in the
5886 slot that calls the method from the dictionary, and we want to avoid
5887 infinite recursion here.) */
Guido van Rossum6d204072001-10-21 00:44:31 +00005888
5889static int
5890add_operators(PyTypeObject *type)
5891{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00005892 PyObject *dict = type->tp_dict;
5893 slotdef *p;
5894 PyObject *descr;
5895 void **ptr;
Guido van Rossum6d204072001-10-21 00:44:31 +00005896
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00005897 init_slotdefs();
5898 for (p = slotdefs; p->name; p++) {
5899 if (p->wrapper == NULL)
5900 continue;
5901 ptr = slotptr(type, p->offset);
5902 if (!ptr || !*ptr)
5903 continue;
5904 if (PyDict_GetItem(dict, p->name_strobj))
5905 continue;
5906 if (*ptr == PyObject_HashNotImplemented) {
5907 /* Classes may prevent the inheritance of the tp_hash
5908 slot by storing PyObject_HashNotImplemented in it. Make it
5909 visible as a None value for the __hash__ attribute. */
5910 if (PyDict_SetItem(dict, p->name_strobj, Py_None) < 0)
5911 return -1;
5912 }
5913 else {
5914 descr = PyDescr_NewWrapper(type, p, *ptr);
5915 if (descr == NULL)
5916 return -1;
5917 if (PyDict_SetItem(dict, p->name_strobj, descr) < 0)
5918 return -1;
5919 Py_DECREF(descr);
5920 }
5921 }
5922 if (type->tp_new != NULL) {
5923 if (add_tp_new_wrapper(type) < 0)
5924 return -1;
5925 }
5926 return 0;
Guido van Rossum6d204072001-10-21 00:44:31 +00005927}
5928
Guido van Rossum705f0f52001-08-24 16:47:00 +00005929
5930/* Cooperative 'super' */
5931
5932typedef struct {
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00005933 PyObject_HEAD
5934 PyTypeObject *type;
5935 PyObject *obj;
5936 PyTypeObject *obj_type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005937} superobject;
5938
Guido van Rossum6f799372001-09-20 20:46:19 +00005939static PyMemberDef super_members[] = {
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00005940 {"__thisclass__", T_OBJECT, offsetof(superobject, type), READONLY,
5941 "the class invoking super()"},
5942 {"__self__", T_OBJECT, offsetof(superobject, obj), READONLY,
5943 "the instance invoking super(); may be None"},
5944 {"__self_class__", T_OBJECT, offsetof(superobject, obj_type), READONLY,
5945 "the type of the instance invoking super(); may be None"},
5946 {0}
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005947};
5948
Guido van Rossum705f0f52001-08-24 16:47:00 +00005949static void
5950super_dealloc(PyObject *self)
5951{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00005952 superobject *su = (superobject *)self;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005953
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00005954 _PyObject_GC_UNTRACK(self);
5955 Py_XDECREF(su->obj);
5956 Py_XDECREF(su->type);
5957 Py_XDECREF(su->obj_type);
5958 Py_TYPE(self)->tp_free(self);
Guido van Rossum705f0f52001-08-24 16:47:00 +00005959}
5960
5961static PyObject *
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005962super_repr(PyObject *self)
5963{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00005964 superobject *su = (superobject *)self;
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005965
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00005966 if (su->obj_type)
5967 return PyUnicode_FromFormat(
5968 "<super: <class '%s'>, <%s object>>",
5969 su->type ? su->type->tp_name : "NULL",
5970 su->obj_type->tp_name);
5971 else
5972 return PyUnicode_FromFormat(
5973 "<super: <class '%s'>, NULL>",
5974 su->type ? su->type->tp_name : "NULL");
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005975}
5976
5977static PyObject *
Guido van Rossum705f0f52001-08-24 16:47:00 +00005978super_getattro(PyObject *self, PyObject *name)
5979{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00005980 superobject *su = (superobject *)self;
5981 int skip = su->obj_type == NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005982
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00005983 if (!skip) {
5984 /* We want __class__ to return the class of the super object
5985 (i.e. super, or a subclass), not the class of su->obj. */
5986 skip = (PyUnicode_Check(name) &&
5987 PyUnicode_GET_SIZE(name) == 9 &&
5988 PyUnicode_CompareWithASCIIString(name, "__class__") == 0);
5989 }
Guido van Rossum76ba09f2003-04-16 19:40:58 +00005990
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00005991 if (!skip) {
5992 PyObject *mro, *res, *tmp, *dict;
5993 PyTypeObject *starttype;
5994 descrgetfunc f;
5995 Py_ssize_t i, n;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005996
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00005997 starttype = su->obj_type;
5998 mro = starttype->tp_mro;
Guido van Rossum155db9a2002-04-02 17:53:47 +00005999
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00006000 if (mro == NULL)
6001 n = 0;
6002 else {
6003 assert(PyTuple_Check(mro));
6004 n = PyTuple_GET_SIZE(mro);
6005 }
6006 for (i = 0; i < n; i++) {
6007 if ((PyObject *)(su->type) == PyTuple_GET_ITEM(mro, i))
6008 break;
6009 }
6010 i++;
6011 res = NULL;
6012 for (; i < n; i++) {
6013 tmp = PyTuple_GET_ITEM(mro, i);
6014 if (PyType_Check(tmp))
6015 dict = ((PyTypeObject *)tmp)->tp_dict;
6016 else
6017 continue;
6018 res = PyDict_GetItem(dict, name);
6019 if (res != NULL) {
6020 Py_INCREF(res);
6021 f = Py_TYPE(res)->tp_descr_get;
6022 if (f != NULL) {
6023 tmp = f(res,
6024 /* Only pass 'obj' param if
6025 this is instance-mode super
6026 (See SF ID #743627)
6027 */
6028 (su->obj == (PyObject *)
6029 su->obj_type
6030 ? (PyObject *)NULL
6031 : su->obj),
6032 (PyObject *)starttype);
6033 Py_DECREF(res);
6034 res = tmp;
6035 }
6036 return res;
6037 }
6038 }
6039 }
6040 return PyObject_GenericGetAttr(self, name);
Guido van Rossum705f0f52001-08-24 16:47:00 +00006041}
6042
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006043static PyTypeObject *
Guido van Rossum5b443c62001-12-03 15:38:28 +00006044supercheck(PyTypeObject *type, PyObject *obj)
6045{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00006046 /* Check that a super() call makes sense. Return a type object.
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006047
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00006048 obj can be a new-style class, or an instance of one:
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006049
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00006050 - If it is a class, it must be a subclass of 'type'. This case is
6051 used for class methods; the return value is obj.
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006052
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00006053 - If it is an instance, it must be an instance of 'type'. This is
6054 the normal case; the return value is obj.__class__.
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006055
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00006056 But... when obj is an instance, we want to allow for the case where
6057 Py_TYPE(obj) is not a subclass of type, but obj.__class__ is!
6058 This will allow using super() with a proxy for obj.
6059 */
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006060
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00006061 /* Check for first bullet above (special case) */
6062 if (PyType_Check(obj) && PyType_IsSubtype((PyTypeObject *)obj, type)) {
6063 Py_INCREF(obj);
6064 return (PyTypeObject *)obj;
6065 }
Guido van Rossum8e80a722003-02-18 19:22:22 +00006066
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00006067 /* Normal case */
6068 if (PyType_IsSubtype(Py_TYPE(obj), type)) {
6069 Py_INCREF(Py_TYPE(obj));
6070 return Py_TYPE(obj);
6071 }
6072 else {
6073 /* Try the slow way */
6074 static PyObject *class_str = NULL;
6075 PyObject *class_attr;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006076
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00006077 if (class_str == NULL) {
6078 class_str = PyUnicode_FromString("__class__");
6079 if (class_str == NULL)
6080 return NULL;
6081 }
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006082
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00006083 class_attr = PyObject_GetAttr(obj, class_str);
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006084
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00006085 if (class_attr != NULL &&
6086 PyType_Check(class_attr) &&
6087 (PyTypeObject *)class_attr != Py_TYPE(obj))
6088 {
6089 int ok = PyType_IsSubtype(
6090 (PyTypeObject *)class_attr, type);
6091 if (ok)
6092 return (PyTypeObject *)class_attr;
6093 }
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006094
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00006095 if (class_attr == NULL)
6096 PyErr_Clear();
6097 else
6098 Py_DECREF(class_attr);
6099 }
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006100
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00006101 PyErr_SetString(PyExc_TypeError,
6102 "super(type, obj): "
6103 "obj must be an instance or subtype of type");
6104 return NULL;
Guido van Rossum5b443c62001-12-03 15:38:28 +00006105}
6106
Guido van Rossum705f0f52001-08-24 16:47:00 +00006107static PyObject *
6108super_descr_get(PyObject *self, PyObject *obj, PyObject *type)
6109{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00006110 superobject *su = (superobject *)self;
6111 superobject *newobj;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006112
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00006113 if (obj == NULL || obj == Py_None || su->obj != NULL) {
6114 /* Not binding to an object, or already bound */
6115 Py_INCREF(self);
6116 return self;
6117 }
6118 if (Py_TYPE(su) != &PySuper_Type)
6119 /* If su is an instance of a (strict) subclass of super,
6120 call its type */
6121 return PyObject_CallFunctionObjArgs((PyObject *)Py_TYPE(su),
6122 su->type, obj, NULL);
6123 else {
6124 /* Inline the common case */
6125 PyTypeObject *obj_type = supercheck(su->type, obj);
6126 if (obj_type == NULL)
6127 return NULL;
6128 newobj = (superobject *)PySuper_Type.tp_new(&PySuper_Type,
6129 NULL, NULL);
6130 if (newobj == NULL)
6131 return NULL;
6132 Py_INCREF(su->type);
6133 Py_INCREF(obj);
6134 newobj->type = su->type;
6135 newobj->obj = obj;
6136 newobj->obj_type = obj_type;
6137 return (PyObject *)newobj;
6138 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00006139}
6140
6141static int
6142super_init(PyObject *self, PyObject *args, PyObject *kwds)
6143{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00006144 superobject *su = (superobject *)self;
6145 PyTypeObject *type = NULL;
6146 PyObject *obj = NULL;
6147 PyTypeObject *obj_type = NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006148
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00006149 if (!_PyArg_NoKeywords("super", kwds))
6150 return -1;
6151 if (!PyArg_ParseTuple(args, "|O!O:super", &PyType_Type, &type, &obj))
6152 return -1;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00006153
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00006154 if (type == NULL) {
6155 /* Call super(), without args -- fill in from __class__
6156 and first local variable on the stack. */
6157 PyFrameObject *f = PyThreadState_GET()->frame;
6158 PyCodeObject *co = f->f_code;
6159 int i, n;
6160 if (co == NULL) {
6161 PyErr_SetString(PyExc_SystemError,
6162 "super(): no code object");
6163 return -1;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00006164 }
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00006165 if (co->co_argcount == 0) {
6166 PyErr_SetString(PyExc_SystemError,
6167 "super(): no arguments");
6168 return -1;
6169 }
6170 obj = f->f_localsplus[0];
6171 if (obj == NULL) {
6172 PyErr_SetString(PyExc_SystemError,
6173 "super(): arg[0] deleted");
6174 return -1;
6175 }
6176 if (co->co_freevars == NULL)
6177 n = 0;
6178 else {
6179 assert(PyTuple_Check(co->co_freevars));
6180 n = PyTuple_GET_SIZE(co->co_freevars);
6181 }
6182 for (i = 0; i < n; i++) {
6183 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
6184 assert(PyUnicode_Check(name));
6185 if (!PyUnicode_CompareWithASCIIString(name,
6186 "__class__")) {
6187 Py_ssize_t index = co->co_nlocals +
6188 PyTuple_GET_SIZE(co->co_cellvars) + i;
6189 PyObject *cell = f->f_localsplus[index];
6190 if (cell == NULL || !PyCell_Check(cell)) {
6191 PyErr_SetString(PyExc_SystemError,
6192 "super(): bad __class__ cell");
6193 return -1;
6194 }
6195 type = (PyTypeObject *) PyCell_GET(cell);
6196 if (type == NULL) {
6197 PyErr_SetString(PyExc_SystemError,
6198 "super(): empty __class__ cell");
6199 return -1;
6200 }
6201 if (!PyType_Check(type)) {
6202 PyErr_Format(PyExc_SystemError,
6203 "super(): __class__ is not a type (%s)",
6204 Py_TYPE(type)->tp_name);
6205 return -1;
6206 }
6207 break;
6208 }
6209 }
6210 if (type == NULL) {
6211 PyErr_SetString(PyExc_SystemError,
6212 "super(): __class__ cell not found");
6213 return -1;
6214 }
6215 }
Guido van Rossumcd16bf62007-06-13 18:07:49 +00006216
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00006217 if (obj == Py_None)
6218 obj = NULL;
6219 if (obj != NULL) {
6220 obj_type = supercheck(type, obj);
6221 if (obj_type == NULL)
6222 return -1;
6223 Py_INCREF(obj);
6224 }
6225 Py_INCREF(type);
6226 su->type = type;
6227 su->obj = obj;
6228 su->obj_type = obj_type;
6229 return 0;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006230}
6231
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00006232PyDoc_STRVAR(super_doc,
Guido van Rossumcd16bf62007-06-13 18:07:49 +00006233"super() -> same as super(__class__, <first argument>)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00006234"super(type) -> unbound super object\n"
6235"super(type, obj) -> bound super object; requires isinstance(obj, type)\n"
Guido van Rossume705ef12001-08-29 15:47:06 +00006236"super(type, type2) -> bound super object; requires issubclass(type2, type)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00006237"Typical use to call a cooperative superclass method:\n"
6238"class C(B):\n"
6239" def meth(self, arg):\n"
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00006240" super().meth(arg)\n"
Guido van Rossumcd16bf62007-06-13 18:07:49 +00006241"This works for class methods too:\n"
6242"class C(B):\n"
6243" @classmethod\n"
6244" def cmeth(cls, arg):\n"
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00006245" super().cmeth(arg)\n");
Guido van Rossum705f0f52001-08-24 16:47:00 +00006246
Guido van Rossum048eb752001-10-02 21:24:57 +00006247static int
6248super_traverse(PyObject *self, visitproc visit, void *arg)
6249{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00006250 superobject *su = (superobject *)self;
Guido van Rossum048eb752001-10-02 21:24:57 +00006251
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00006252 Py_VISIT(su->obj);
6253 Py_VISIT(su->type);
6254 Py_VISIT(su->obj_type);
Guido van Rossum048eb752001-10-02 21:24:57 +00006255
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00006256 return 0;
Guido van Rossum048eb752001-10-02 21:24:57 +00006257}
6258
Guido van Rossum705f0f52001-08-24 16:47:00 +00006259PyTypeObject PySuper_Type = {
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00006260 PyVarObject_HEAD_INIT(&PyType_Type, 0)
6261 "super", /* tp_name */
6262 sizeof(superobject), /* tp_basicsize */
6263 0, /* tp_itemsize */
6264 /* methods */
6265 super_dealloc, /* tp_dealloc */
6266 0, /* tp_print */
6267 0, /* tp_getattr */
6268 0, /* tp_setattr */
6269 0, /* tp_reserved */
6270 super_repr, /* tp_repr */
6271 0, /* tp_as_number */
6272 0, /* tp_as_sequence */
6273 0, /* tp_as_mapping */
6274 0, /* tp_hash */
6275 0, /* tp_call */
6276 0, /* tp_str */
6277 super_getattro, /* tp_getattro */
6278 0, /* tp_setattro */
6279 0, /* tp_as_buffer */
6280 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
6281 Py_TPFLAGS_BASETYPE, /* tp_flags */
6282 super_doc, /* tp_doc */
6283 super_traverse, /* tp_traverse */
6284 0, /* tp_clear */
6285 0, /* tp_richcompare */
6286 0, /* tp_weaklistoffset */
6287 0, /* tp_iter */
6288 0, /* tp_iternext */
6289 0, /* tp_methods */
6290 super_members, /* tp_members */
6291 0, /* tp_getset */
6292 0, /* tp_base */
6293 0, /* tp_dict */
6294 super_descr_get, /* tp_descr_get */
6295 0, /* tp_descr_set */
6296 0, /* tp_dictoffset */
6297 super_init, /* tp_init */
6298 PyType_GenericAlloc, /* tp_alloc */
6299 PyType_GenericNew, /* tp_new */
6300 PyObject_GC_Del, /* tp_free */
Guido van Rossum705f0f52001-08-24 16:47:00 +00006301};