blob: caa405b9455ba1ecf32de1d2f658c80e8c58158a [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) {
Benjamin Petersona53d2ac2011-01-12 19:02:36 +0000329 PyErr_SetString(PyExc_AttributeError, "__abstractmethods__");
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000330 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 */
Benjamin Petersonde368712011-01-12 15:42:34 +0000343 int res;
344 if (value != NULL) {
345 res = PyDict_SetItemString(type->tp_dict, "__abstractmethods__", value);
346 }
347 else {
348 res = PyDict_DelItemString(type->tp_dict, "__abstractmethods__");
349 if (res && PyErr_ExceptionMatches(PyExc_KeyError)) {
Benjamin Petersona53d2ac2011-01-12 19:02:36 +0000350 PyErr_SetString(PyExc_AttributeError, "__abstractmethods__");
Benjamin Petersonde368712011-01-12 15:42:34 +0000351 return -1;
352 }
353 }
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000354 if (res == 0) {
355 PyType_Modified(type);
356 if (value && PyObject_IsTrue(value)) {
357 type->tp_flags |= Py_TPFLAGS_IS_ABSTRACT;
358 }
359 else {
360 type->tp_flags &= ~Py_TPFLAGS_IS_ABSTRACT;
361 }
362 }
363 return res;
Christian Heimes9e7f1d22008-02-28 12:27:11 +0000364}
365
366static PyObject *
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000367type_get_bases(PyTypeObject *type, void *context)
368{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000369 Py_INCREF(type->tp_bases);
370 return type->tp_bases;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000371}
372
373static PyTypeObject *best_base(PyObject *);
374static int mro_internal(PyTypeObject *);
375static int compatible_for_assignment(PyTypeObject *, PyTypeObject *, char *);
376static int add_subclass(PyTypeObject*, PyTypeObject*);
377static void remove_subclass(PyTypeObject *, PyTypeObject *);
378static void update_all_slots(PyTypeObject *);
379
Guido van Rossum8d24ee92003-03-24 23:49:49 +0000380typedef int (*update_callback)(PyTypeObject *, void *);
381static int update_subclasses(PyTypeObject *type, PyObject *name,
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000382 update_callback callback, void *data);
Guido van Rossum8d24ee92003-03-24 23:49:49 +0000383static int recurse_down_subclasses(PyTypeObject *type, PyObject *name,
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000384 update_callback callback, void *data);
Guido van Rossum8d24ee92003-03-24 23:49:49 +0000385
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000386static int
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000387mro_subclasses(PyTypeObject *type, PyObject* temp)
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000388{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000389 PyTypeObject *subclass;
390 PyObject *ref, *subclasses, *old_mro;
391 Py_ssize_t i, n;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000392
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000393 subclasses = type->tp_subclasses;
394 if (subclasses == NULL)
395 return 0;
396 assert(PyList_Check(subclasses));
397 n = PyList_GET_SIZE(subclasses);
398 for (i = 0; i < n; i++) {
399 ref = PyList_GET_ITEM(subclasses, i);
400 assert(PyWeakref_CheckRef(ref));
401 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
402 assert(subclass != NULL);
403 if ((PyObject *)subclass == Py_None)
404 continue;
405 assert(PyType_Check(subclass));
406 old_mro = subclass->tp_mro;
407 if (mro_internal(subclass) < 0) {
408 subclass->tp_mro = old_mro;
409 return -1;
410 }
411 else {
412 PyObject* tuple;
413 tuple = PyTuple_Pack(2, subclass, old_mro);
414 Py_DECREF(old_mro);
415 if (!tuple)
416 return -1;
417 if (PyList_Append(temp, tuple) < 0)
418 return -1;
419 Py_DECREF(tuple);
420 }
421 if (mro_subclasses(subclass, temp) < 0)
422 return -1;
423 }
424 return 0;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000425}
426
427static int
428type_set_bases(PyTypeObject *type, PyObject *value, void *context)
429{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000430 Py_ssize_t i;
431 int r = 0;
432 PyObject *ob, *temp;
433 PyTypeObject *new_base, *old_base;
434 PyObject *old_bases, *old_mro;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000435
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000436 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
437 PyErr_Format(PyExc_TypeError,
438 "can't set %s.__bases__", type->tp_name);
439 return -1;
440 }
441 if (!value) {
442 PyErr_Format(PyExc_TypeError,
443 "can't delete %s.__bases__", type->tp_name);
444 return -1;
445 }
446 if (!PyTuple_Check(value)) {
447 PyErr_Format(PyExc_TypeError,
448 "can only assign tuple to %s.__bases__, not %s",
449 type->tp_name, Py_TYPE(value)->tp_name);
450 return -1;
451 }
452 if (PyTuple_GET_SIZE(value) == 0) {
453 PyErr_Format(PyExc_TypeError,
454 "can only assign non-empty tuple to %s.__bases__, not ()",
455 type->tp_name);
456 return -1;
457 }
458 for (i = 0; i < PyTuple_GET_SIZE(value); i++) {
459 ob = PyTuple_GET_ITEM(value, i);
460 if (!PyType_Check(ob)) {
461 PyErr_Format(
462 PyExc_TypeError,
463 "%s.__bases__ must be tuple of old- or new-style classes, not '%s'",
464 type->tp_name, Py_TYPE(ob)->tp_name);
465 return -1;
466 }
467 if (PyType_Check(ob)) {
468 if (PyType_IsSubtype((PyTypeObject*)ob, type)) {
469 PyErr_SetString(PyExc_TypeError,
470 "a __bases__ item causes an inheritance cycle");
471 return -1;
472 }
473 }
474 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000475
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000476 new_base = best_base(value);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000477
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000478 if (!new_base) {
479 return -1;
480 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000481
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000482 if (!compatible_for_assignment(type->tp_base, new_base, "__bases__"))
483 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000484
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000485 Py_INCREF(new_base);
486 Py_INCREF(value);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000487
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000488 old_bases = type->tp_bases;
489 old_base = type->tp_base;
490 old_mro = type->tp_mro;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000491
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000492 type->tp_bases = value;
493 type->tp_base = new_base;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000494
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000495 if (mro_internal(type) < 0) {
496 goto bail;
497 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000498
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000499 temp = PyList_New(0);
500 if (!temp)
501 goto bail;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000502
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000503 r = mro_subclasses(type, temp);
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000504
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000505 if (r < 0) {
506 for (i = 0; i < PyList_Size(temp); i++) {
507 PyTypeObject* cls;
508 PyObject* mro;
509 PyArg_UnpackTuple(PyList_GET_ITEM(temp, i),
510 "", 2, 2, &cls, &mro);
511 Py_INCREF(mro);
512 ob = cls->tp_mro;
513 cls->tp_mro = mro;
514 Py_DECREF(ob);
515 }
516 Py_DECREF(temp);
517 goto bail;
518 }
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000519
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000520 Py_DECREF(temp);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000521
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000522 /* any base that was in __bases__ but now isn't, we
523 need to remove |type| from its tp_subclasses.
524 conversely, any class now in __bases__ that wasn't
525 needs to have |type| added to its subclasses. */
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000526
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000527 /* for now, sod that: just remove from all old_bases,
528 add to all new_bases */
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000529
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000530 for (i = PyTuple_GET_SIZE(old_bases) - 1; i >= 0; i--) {
531 ob = PyTuple_GET_ITEM(old_bases, i);
532 if (PyType_Check(ob)) {
533 remove_subclass(
534 (PyTypeObject*)ob, type);
535 }
536 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000537
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000538 for (i = PyTuple_GET_SIZE(value) - 1; i >= 0; i--) {
539 ob = PyTuple_GET_ITEM(value, i);
540 if (PyType_Check(ob)) {
541 if (add_subclass((PyTypeObject*)ob, type) < 0)
542 r = -1;
543 }
544 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000545
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000546 update_all_slots(type);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000547
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000548 Py_DECREF(old_bases);
549 Py_DECREF(old_base);
550 Py_DECREF(old_mro);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000551
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000552 return r;
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000553
554 bail:
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000555 Py_DECREF(type->tp_bases);
556 Py_DECREF(type->tp_base);
557 if (type->tp_mro != old_mro) {
558 Py_DECREF(type->tp_mro);
559 }
Michael W. Hudsone723e452003-08-07 14:58:10 +0000560
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000561 type->tp_bases = old_bases;
562 type->tp_base = old_base;
563 type->tp_mro = old_mro;
Tim Petersea7f75d2002-12-07 21:39:16 +0000564
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000565 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000566}
567
568static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000569type_dict(PyTypeObject *type, void *context)
570{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000571 if (type->tp_dict == NULL) {
572 Py_INCREF(Py_None);
573 return Py_None;
574 }
575 return PyDictProxy_New(type->tp_dict);
Guido van Rossum29ca26e1995-01-07 11:58:15 +0000576}
577
Tim Peters24008312002-03-17 18:56:20 +0000578static PyObject *
579type_get_doc(PyTypeObject *type, void *context)
580{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000581 PyObject *result;
582 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE) && type->tp_doc != NULL)
583 return PyUnicode_FromString(type->tp_doc);
584 result = PyDict_GetItemString(type->tp_dict, "__doc__");
585 if (result == NULL) {
586 result = Py_None;
587 Py_INCREF(result);
588 }
589 else if (Py_TYPE(result)->tp_descr_get) {
590 result = Py_TYPE(result)->tp_descr_get(result, NULL,
591 (PyObject *)type);
592 }
593 else {
594 Py_INCREF(result);
595 }
596 return result;
Tim Peters24008312002-03-17 18:56:20 +0000597}
598
Antoine Pitrouec569b72008-08-26 22:40:48 +0000599static PyObject *
600type___instancecheck__(PyObject *type, PyObject *inst)
601{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000602 switch (_PyObject_RealIsInstance(inst, type)) {
603 case -1:
604 return NULL;
605 case 0:
606 Py_RETURN_FALSE;
607 default:
608 Py_RETURN_TRUE;
609 }
Antoine Pitrouec569b72008-08-26 22:40:48 +0000610}
611
612
613static PyObject *
Antoine Pitrouec569b72008-08-26 22:40:48 +0000614type___subclasscheck__(PyObject *type, PyObject *inst)
615{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000616 switch (_PyObject_RealIsSubclass(inst, type)) {
617 case -1:
618 return NULL;
619 case 0:
620 Py_RETURN_FALSE;
621 default:
622 Py_RETURN_TRUE;
623 }
Antoine Pitrouec569b72008-08-26 22:40:48 +0000624}
625
Antoine Pitrouec569b72008-08-26 22:40:48 +0000626
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000627static PyGetSetDef type_getsets[] = {
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000628 {"__name__", (getter)type_name, (setter)type_set_name, NULL},
629 {"__bases__", (getter)type_get_bases, (setter)type_set_bases, NULL},
630 {"__module__", (getter)type_module, (setter)type_set_module, NULL},
631 {"__abstractmethods__", (getter)type_abstractmethods,
632 (setter)type_set_abstractmethods, NULL},
633 {"__dict__", (getter)type_dict, NULL, NULL},
634 {"__doc__", (getter)type_get_doc, NULL, NULL},
635 {0}
Tim Peters6d6c1a32001-08-02 04:15:00 +0000636};
637
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000638static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000639type_repr(PyTypeObject *type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000640{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000641 PyObject *mod, *name, *rtn;
Guido van Rossumc3542212001-08-16 09:18:56 +0000642
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000643 mod = type_module(type, NULL);
644 if (mod == NULL)
645 PyErr_Clear();
646 else if (!PyUnicode_Check(mod)) {
647 Py_DECREF(mod);
648 mod = NULL;
649 }
650 name = type_name(type, NULL);
651 if (name == NULL)
652 return NULL;
Barry Warsaw7ce36942001-08-24 18:34:26 +0000653
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000654 if (mod != NULL && PyUnicode_CompareWithASCIIString(mod, "builtins"))
655 rtn = PyUnicode_FromFormat("<class '%U.%U'>", mod, name);
656 else
657 rtn = PyUnicode_FromFormat("<class '%s'>", type->tp_name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000658
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000659 Py_XDECREF(mod);
660 Py_DECREF(name);
661 return rtn;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000662}
663
Tim Peters6d6c1a32001-08-02 04:15:00 +0000664static PyObject *
665type_call(PyTypeObject *type, PyObject *args, PyObject *kwds)
666{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000667 PyObject *obj;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000668
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000669 if (type->tp_new == NULL) {
670 PyErr_Format(PyExc_TypeError,
671 "cannot create '%.100s' instances",
672 type->tp_name);
673 return NULL;
674 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000675
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000676 obj = type->tp_new(type, args, kwds);
677 if (obj != NULL) {
678 /* Ugly exception: when the call was type(something),
679 don't call tp_init on the result. */
680 if (type == &PyType_Type &&
681 PyTuple_Check(args) && PyTuple_GET_SIZE(args) == 1 &&
682 (kwds == NULL ||
683 (PyDict_Check(kwds) && PyDict_Size(kwds) == 0)))
684 return obj;
685 /* If the returned object is not an instance of type,
686 it won't be initialized. */
687 if (!PyType_IsSubtype(Py_TYPE(obj), type))
688 return obj;
689 type = Py_TYPE(obj);
690 if (type->tp_init != NULL &&
691 type->tp_init(obj, args, kwds) < 0) {
692 Py_DECREF(obj);
693 obj = NULL;
694 }
695 }
696 return obj;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000697}
698
699PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000700PyType_GenericAlloc(PyTypeObject *type, Py_ssize_t nitems)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000701{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000702 PyObject *obj;
703 const size_t size = _PyObject_VAR_SIZE(type, nitems+1);
704 /* note that we need to add one, for the sentinel */
Tim Peters406fe3b2001-10-06 19:04:01 +0000705
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000706 if (PyType_IS_GC(type))
707 obj = _PyObject_GC_Malloc(size);
708 else
709 obj = (PyObject *)PyObject_MALLOC(size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000710
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000711 if (obj == NULL)
712 return PyErr_NoMemory();
Tim Peters406fe3b2001-10-06 19:04:01 +0000713
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000714 memset(obj, '\0', size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000715
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000716 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
717 Py_INCREF(type);
Tim Peters406fe3b2001-10-06 19:04:01 +0000718
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000719 if (type->tp_itemsize == 0)
720 PyObject_INIT(obj, type);
721 else
722 (void) PyObject_INIT_VAR((PyVarObject *)obj, type, nitems);
Tim Peters406fe3b2001-10-06 19:04:01 +0000723
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000724 if (PyType_IS_GC(type))
725 _PyObject_GC_TRACK(obj);
726 return obj;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000727}
728
729PyObject *
730PyType_GenericNew(PyTypeObject *type, PyObject *args, PyObject *kwds)
731{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000732 return type->tp_alloc(type, 0);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000733}
734
Guido van Rossum9475a232001-10-05 20:51:39 +0000735/* Helpers for subtyping */
736
737static int
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000738traverse_slots(PyTypeObject *type, PyObject *self, visitproc visit, void *arg)
739{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000740 Py_ssize_t i, n;
741 PyMemberDef *mp;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000742
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000743 n = Py_SIZE(type);
744 mp = PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type);
745 for (i = 0; i < n; i++, mp++) {
746 if (mp->type == T_OBJECT_EX) {
747 char *addr = (char *)self + mp->offset;
748 PyObject *obj = *(PyObject **)addr;
749 if (obj != NULL) {
750 int err = visit(obj, arg);
751 if (err)
752 return err;
753 }
754 }
755 }
756 return 0;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000757}
758
759static int
Guido van Rossum9475a232001-10-05 20:51:39 +0000760subtype_traverse(PyObject *self, visitproc visit, void *arg)
761{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000762 PyTypeObject *type, *base;
763 traverseproc basetraverse;
Guido van Rossum9475a232001-10-05 20:51:39 +0000764
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000765 /* Find the nearest base with a different tp_traverse,
766 and traverse slots while we're at it */
767 type = Py_TYPE(self);
768 base = type;
769 while ((basetraverse = base->tp_traverse) == subtype_traverse) {
770 if (Py_SIZE(base)) {
771 int err = traverse_slots(base, self, visit, arg);
772 if (err)
773 return err;
774 }
775 base = base->tp_base;
776 assert(base);
777 }
Guido van Rossum9475a232001-10-05 20:51:39 +0000778
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000779 if (type->tp_dictoffset != base->tp_dictoffset) {
780 PyObject **dictptr = _PyObject_GetDictPtr(self);
781 if (dictptr && *dictptr)
782 Py_VISIT(*dictptr);
783 }
Guido van Rossum9475a232001-10-05 20:51:39 +0000784
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000785 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
786 /* For a heaptype, the instances count as references
787 to the type. Traverse the type so the collector
788 can find cycles involving this link. */
789 Py_VISIT(type);
Guido van Rossuma3862092002-06-10 15:24:42 +0000790
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000791 if (basetraverse)
792 return basetraverse(self, visit, arg);
793 return 0;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000794}
795
796static void
797clear_slots(PyTypeObject *type, PyObject *self)
798{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000799 Py_ssize_t i, n;
800 PyMemberDef *mp;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000801
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000802 n = Py_SIZE(type);
803 mp = PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type);
804 for (i = 0; i < n; i++, mp++) {
805 if (mp->type == T_OBJECT_EX && !(mp->flags & READONLY)) {
806 char *addr = (char *)self + mp->offset;
807 PyObject *obj = *(PyObject **)addr;
808 if (obj != NULL) {
809 *(PyObject **)addr = NULL;
810 Py_DECREF(obj);
811 }
812 }
813 }
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000814}
815
816static int
817subtype_clear(PyObject *self)
818{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000819 PyTypeObject *type, *base;
820 inquiry baseclear;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000821
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000822 /* Find the nearest base with a different tp_clear
823 and clear slots while we're at it */
824 type = Py_TYPE(self);
825 base = type;
826 while ((baseclear = base->tp_clear) == subtype_clear) {
827 if (Py_SIZE(base))
828 clear_slots(base, self);
829 base = base->tp_base;
830 assert(base);
831 }
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000832
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000833 /* There's no need to clear the instance dict (if any);
834 the collector will call its tp_clear handler. */
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000835
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000836 if (baseclear)
837 return baseclear(self);
838 return 0;
Guido van Rossum9475a232001-10-05 20:51:39 +0000839}
Tim Peters6d6c1a32001-08-02 04:15:00 +0000840
841static void
842subtype_dealloc(PyObject *self)
843{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000844 PyTypeObject *type, *base;
845 destructor basedealloc;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000846
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000847 /* Extract the type; we expect it to be a heap type */
848 type = Py_TYPE(self);
849 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000850
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000851 /* Test whether the type has GC exactly once */
Guido van Rossum22b13872002-08-06 21:41:44 +0000852
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000853 if (!PyType_IS_GC(type)) {
854 /* It's really rare to find a dynamic type that doesn't have
855 GC; it can only happen when deriving from 'object' and not
856 adding any slots or instance variables. This allows
857 certain simplifications: there's no need to call
858 clear_slots(), or DECREF the dict, or clear weakrefs. */
Guido van Rossum22b13872002-08-06 21:41:44 +0000859
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000860 /* Maybe call finalizer; exit early if resurrected */
861 if (type->tp_del) {
862 type->tp_del(self);
863 if (self->ob_refcnt > 0)
864 return;
865 }
Guido van Rossum22b13872002-08-06 21:41:44 +0000866
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000867 /* Find the nearest base with a different tp_dealloc */
868 base = type;
869 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
870 assert(Py_SIZE(base) == 0);
871 base = base->tp_base;
872 assert(base);
873 }
Guido van Rossum22b13872002-08-06 21:41:44 +0000874
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000875 /* Extract the type again; tp_del may have changed it */
876 type = Py_TYPE(self);
Benjamin Peterson193152c2009-04-25 01:08:45 +0000877
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000878 /* Call the base tp_dealloc() */
879 assert(basedealloc);
880 basedealloc(self);
Guido van Rossum22b13872002-08-06 21:41:44 +0000881
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000882 /* Can't reference self beyond this point */
883 Py_DECREF(type);
Guido van Rossum22b13872002-08-06 21:41:44 +0000884
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000885 /* Done */
886 return;
887 }
Guido van Rossum22b13872002-08-06 21:41:44 +0000888
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000889 /* We get here only if the type has GC */
Guido van Rossum22b13872002-08-06 21:41:44 +0000890
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000891 /* UnTrack and re-Track around the trashcan macro, alas */
892 /* See explanation at end of function for full disclosure */
893 PyObject_GC_UnTrack(self);
894 ++_PyTrash_delete_nesting;
895 Py_TRASHCAN_SAFE_BEGIN(self);
896 --_PyTrash_delete_nesting;
897 /* DO NOT restore GC tracking at this point. weakref callbacks
898 * (if any, and whether directly here or indirectly in something we
899 * call) may trigger GC, and if self is tracked at that point, it
900 * will look like trash to GC and GC will try to delete self again.
901 */
Guido van Rossum22b13872002-08-06 21:41:44 +0000902
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000903 /* Find the nearest base with a different tp_dealloc */
904 base = type;
905 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
906 base = base->tp_base;
907 assert(base);
908 }
Guido van Rossum14227b42001-12-06 02:35:58 +0000909
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000910 /* If we added a weaklist, we clear it. Do this *before* calling
911 the finalizer (__del__), clearing slots, or clearing the instance
912 dict. */
Guido van Rossum59195fd2003-06-13 20:54:40 +0000913
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000914 if (type->tp_weaklistoffset && !base->tp_weaklistoffset)
915 PyObject_ClearWeakRefs(self);
Guido van Rossum1987c662003-05-29 14:29:23 +0000916
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000917 /* Maybe call finalizer; exit early if resurrected */
918 if (type->tp_del) {
919 _PyObject_GC_TRACK(self);
920 type->tp_del(self);
921 if (self->ob_refcnt > 0)
922 goto endlabel; /* resurrected */
923 else
924 _PyObject_GC_UNTRACK(self);
925 /* New weakrefs could be created during the finalizer call.
926 If this occurs, clear them out without calling their
927 finalizers since they might rely on part of the object
928 being finalized that has already been destroyed. */
929 if (type->tp_weaklistoffset && !base->tp_weaklistoffset) {
930 /* Modeled after GET_WEAKREFS_LISTPTR() */
931 PyWeakReference **list = (PyWeakReference **) \
932 PyObject_GET_WEAKREFS_LISTPTR(self);
933 while (*list)
934 _PyWeakref_ClearRef(*list);
935 }
936 }
Guido van Rossum1987c662003-05-29 14:29:23 +0000937
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000938 /* Clear slots up to the nearest base with a different tp_dealloc */
939 base = type;
940 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
941 if (Py_SIZE(base))
942 clear_slots(base, self);
943 base = base->tp_base;
944 assert(base);
945 }
Guido van Rossum59195fd2003-06-13 20:54:40 +0000946
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000947 /* If we added a dict, DECREF it */
948 if (type->tp_dictoffset && !base->tp_dictoffset) {
949 PyObject **dictptr = _PyObject_GetDictPtr(self);
950 if (dictptr != NULL) {
951 PyObject *dict = *dictptr;
952 if (dict != NULL) {
953 Py_DECREF(dict);
954 *dictptr = NULL;
955 }
956 }
957 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000958
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000959 /* Extract the type again; tp_del may have changed it */
960 type = Py_TYPE(self);
Benjamin Peterson193152c2009-04-25 01:08:45 +0000961
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000962 /* Call the base tp_dealloc(); first retrack self if
963 * basedealloc knows about gc.
964 */
965 if (PyType_IS_GC(base))
966 _PyObject_GC_TRACK(self);
967 assert(basedealloc);
968 basedealloc(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000969
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000970 /* Can't reference self beyond this point */
971 Py_DECREF(type);
Guido van Rossum22b13872002-08-06 21:41:44 +0000972
Guido van Rossum0906e072002-08-07 20:42:09 +0000973 endlabel:
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000974 ++_PyTrash_delete_nesting;
975 Py_TRASHCAN_SAFE_END(self);
976 --_PyTrash_delete_nesting;
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000977
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000978 /* Explanation of the weirdness around the trashcan macros:
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000979
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000980 Q. What do the trashcan macros do?
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000981
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000982 A. Read the comment titled "Trashcan mechanism" in object.h.
983 For one, this explains why there must be a call to GC-untrack
984 before the trashcan begin macro. Without understanding the
985 trashcan code, the answers to the following questions don't make
986 sense.
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000987
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000988 Q. Why do we GC-untrack before the trashcan and then immediately
989 GC-track again afterward?
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000990
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000991 A. In the case that the base class is GC-aware, the base class
992 probably GC-untracks the object. If it does that using the
993 UNTRACK macro, this will crash when the object is already
994 untracked. Because we don't know what the base class does, the
995 only safe thing is to make sure the object is tracked when we
996 call the base class dealloc. But... The trashcan begin macro
997 requires that the object is *untracked* before it is called. So
998 the dance becomes:
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000999
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001000 GC untrack
1001 trashcan begin
1002 GC track
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001003
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001004 Q. Why did the last question say "immediately GC-track again"?
1005 It's nowhere near immediately.
Tim Petersf7f9e992003-11-13 21:59:32 +00001006
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001007 A. Because the code *used* to re-track immediately. Bad Idea.
1008 self has a refcount of 0, and if gc ever gets its hands on it
1009 (which can happen if any weakref callback gets invoked), it
1010 looks like trash to gc too, and gc also tries to delete self
1011 then. But we're already deleting self. Double dealloction is
1012 a subtle disaster.
Tim Petersf7f9e992003-11-13 21:59:32 +00001013
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001014 Q. Why the bizarre (net-zero) manipulation of
1015 _PyTrash_delete_nesting around the trashcan macros?
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001016
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001017 A. Some base classes (e.g. list) also use the trashcan mechanism.
1018 The following scenario used to be possible:
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001019
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001020 - suppose the trashcan level is one below the trashcan limit
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001021
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001022 - subtype_dealloc() is called
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001023
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001024 - the trashcan limit is not yet reached, so the trashcan level
1025 is incremented and the code between trashcan begin and end is
1026 executed
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001027
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001028 - this destroys much of the object's contents, including its
1029 slots and __dict__
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001030
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001031 - basedealloc() is called; this is really list_dealloc(), or
1032 some other type which also uses the trashcan macros
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001033
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001034 - the trashcan limit is now reached, so the object is put on the
1035 trashcan's to-be-deleted-later list
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001036
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001037 - basedealloc() returns
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001038
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001039 - subtype_dealloc() decrefs the object's type
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001040
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001041 - subtype_dealloc() returns
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001042
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001043 - later, the trashcan code starts deleting the objects from its
1044 to-be-deleted-later list
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001045
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001046 - subtype_dealloc() is called *AGAIN* for the same object
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001047
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001048 - at the very least (if the destroyed slots and __dict__ don't
1049 cause problems) the object's type gets decref'ed a second
1050 time, which is *BAD*!!!
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001051
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001052 The remedy is to make sure that if the code between trashcan
1053 begin and end in subtype_dealloc() is called, the code between
1054 trashcan begin and end in basedealloc() will also be called.
1055 This is done by decrementing the level after passing into the
1056 trashcan block, and incrementing it just before leaving the
1057 block.
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001058
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001059 But now it's possible that a chain of objects consisting solely
1060 of objects whose deallocator is subtype_dealloc() will defeat
1061 the trashcan mechanism completely: the decremented level means
1062 that the effective level never reaches the limit. Therefore, we
1063 *increment* the level *before* entering the trashcan block, and
1064 matchingly decrement it after leaving. This means the trashcan
1065 code will trigger a little early, but that's no big deal.
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001066
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001067 Q. Are there any live examples of code in need of all this
1068 complexity?
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001069
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001070 A. Yes. See SF bug 668433 for code that crashed (when Python was
1071 compiled in debug mode) before the trashcan level manipulations
1072 were added. For more discussion, see SF patches 581742, 575073
1073 and bug 574207.
1074 */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001075}
1076
Jeremy Hylton938ace62002-07-17 16:30:39 +00001077static PyTypeObject *solid_base(PyTypeObject *type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001078
Tim Peters6d6c1a32001-08-02 04:15:00 +00001079/* type test with subclassing support */
1080
1081int
1082PyType_IsSubtype(PyTypeObject *a, PyTypeObject *b)
1083{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001084 PyObject *mro;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001085
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001086 mro = a->tp_mro;
1087 if (mro != NULL) {
1088 /* Deal with multiple inheritance without recursion
1089 by walking the MRO tuple */
1090 Py_ssize_t i, n;
1091 assert(PyTuple_Check(mro));
1092 n = PyTuple_GET_SIZE(mro);
1093 for (i = 0; i < n; i++) {
1094 if (PyTuple_GET_ITEM(mro, i) == (PyObject *)b)
1095 return 1;
1096 }
1097 return 0;
1098 }
1099 else {
1100 /* a is not completely initilized yet; follow tp_base */
1101 do {
1102 if (a == b)
1103 return 1;
1104 a = a->tp_base;
1105 } while (a != NULL);
1106 return b == &PyBaseObject_Type;
1107 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001108}
1109
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001110/* Internal routines to do a method lookup in the type
Guido van Rossum60718732001-08-28 17:47:51 +00001111 without looking in the instance dictionary
1112 (so we can't use PyObject_GetAttr) but still binding
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001113 it to the instance. The arguments are the object,
Guido van Rossum60718732001-08-28 17:47:51 +00001114 the method name as a C string, and the address of a
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001115 static variable used to cache the interned Python string.
1116
1117 Two variants:
1118
1119 - lookup_maybe() returns NULL without raising an exception
1120 when the _PyType_Lookup() call fails;
1121
1122 - lookup_method() always raises an exception upon errors.
Benjamin Peterson224205f2009-05-08 03:25:19 +00001123
1124 - _PyObject_LookupSpecial() exported for the benefit of other places.
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001125*/
Guido van Rossum60718732001-08-28 17:47:51 +00001126
1127static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001128lookup_maybe(PyObject *self, char *attrstr, PyObject **attrobj)
Guido van Rossum60718732001-08-28 17:47:51 +00001129{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001130 PyObject *res;
Guido van Rossum60718732001-08-28 17:47:51 +00001131
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001132 if (*attrobj == NULL) {
1133 *attrobj = PyUnicode_InternFromString(attrstr);
1134 if (*attrobj == NULL)
1135 return NULL;
1136 }
1137 res = _PyType_Lookup(Py_TYPE(self), *attrobj);
1138 if (res != NULL) {
1139 descrgetfunc f;
1140 if ((f = Py_TYPE(res)->tp_descr_get) == NULL)
1141 Py_INCREF(res);
1142 else
1143 res = f(res, self, (PyObject *)(Py_TYPE(self)));
1144 }
1145 return res;
Guido van Rossum60718732001-08-28 17:47:51 +00001146}
1147
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001148static PyObject *
1149lookup_method(PyObject *self, char *attrstr, PyObject **attrobj)
1150{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001151 PyObject *res = lookup_maybe(self, attrstr, attrobj);
1152 if (res == NULL && !PyErr_Occurred())
1153 PyErr_SetObject(PyExc_AttributeError, *attrobj);
1154 return res;
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001155}
1156
Benjamin Peterson224205f2009-05-08 03:25:19 +00001157PyObject *
1158_PyObject_LookupSpecial(PyObject *self, char *attrstr, PyObject **attrobj)
1159{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001160 return lookup_maybe(self, attrstr, attrobj);
Benjamin Peterson224205f2009-05-08 03:25:19 +00001161}
1162
Guido van Rossum2730b132001-08-28 18:22:14 +00001163/* A variation of PyObject_CallMethod that uses lookup_method()
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001164 instead of PyObject_GetAttrString(). This uses the same convention
Guido van Rossum2730b132001-08-28 18:22:14 +00001165 as lookup_method to cache the interned name string object. */
1166
Neil Schemenauerf23473f2001-10-21 22:28:58 +00001167static PyObject *
Guido van Rossum2730b132001-08-28 18:22:14 +00001168call_method(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
1169{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001170 va_list va;
1171 PyObject *args, *func = 0, *retval;
1172 va_start(va, format);
Guido van Rossum2730b132001-08-28 18:22:14 +00001173
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001174 func = lookup_maybe(o, name, nameobj);
1175 if (func == NULL) {
1176 va_end(va);
1177 if (!PyErr_Occurred())
1178 PyErr_SetObject(PyExc_AttributeError, *nameobj);
1179 return NULL;
1180 }
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001181
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001182 if (format && *format)
1183 args = Py_VaBuildValue(format, va);
1184 else
1185 args = PyTuple_New(0);
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001186
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001187 va_end(va);
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001188
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001189 if (args == NULL)
1190 return NULL;
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001191
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001192 assert(PyTuple_Check(args));
1193 retval = PyObject_Call(func, args, NULL);
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001194
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001195 Py_DECREF(args);
1196 Py_DECREF(func);
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001197
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001198 return retval;
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001199}
1200
1201/* Clone of call_method() that returns NotImplemented when the lookup fails. */
1202
Neil Schemenauerf23473f2001-10-21 22:28:58 +00001203static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001204call_maybe(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
1205{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001206 va_list va;
1207 PyObject *args, *func = 0, *retval;
1208 va_start(va, format);
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001209
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001210 func = lookup_maybe(o, name, nameobj);
1211 if (func == NULL) {
1212 va_end(va);
1213 if (!PyErr_Occurred()) {
1214 Py_INCREF(Py_NotImplemented);
1215 return Py_NotImplemented;
1216 }
1217 return NULL;
1218 }
Guido van Rossum2730b132001-08-28 18:22:14 +00001219
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001220 if (format && *format)
1221 args = Py_VaBuildValue(format, va);
1222 else
1223 args = PyTuple_New(0);
Guido van Rossum2730b132001-08-28 18:22:14 +00001224
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001225 va_end(va);
Guido van Rossum2730b132001-08-28 18:22:14 +00001226
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001227 if (args == NULL)
1228 return NULL;
Guido van Rossum2730b132001-08-28 18:22:14 +00001229
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001230 assert(PyTuple_Check(args));
1231 retval = PyObject_Call(func, args, NULL);
Guido van Rossum2730b132001-08-28 18:22:14 +00001232
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001233 Py_DECREF(args);
1234 Py_DECREF(func);
Guido van Rossum2730b132001-08-28 18:22:14 +00001235
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001236 return retval;
Guido van Rossum2730b132001-08-28 18:22:14 +00001237}
1238
Tim Petersea7f75d2002-12-07 21:39:16 +00001239/*
Guido van Rossum1f121312002-11-14 19:49:16 +00001240 Method resolution order algorithm C3 described in
1241 "A Monotonic Superclass Linearization for Dylan",
1242 by Kim Barrett, Bob Cassel, Paul Haahr,
Tim Petersea7f75d2002-12-07 21:39:16 +00001243 David A. Moon, Keith Playford, and P. Tucker Withington.
Guido van Rossum1f121312002-11-14 19:49:16 +00001244 (OOPSLA 1996)
1245
Guido van Rossum98f33732002-11-25 21:36:54 +00001246 Some notes about the rules implied by C3:
1247
Tim Petersea7f75d2002-12-07 21:39:16 +00001248 No duplicate bases.
Guido van Rossum98f33732002-11-25 21:36:54 +00001249 It isn't legal to repeat a class in a list of base classes.
1250
1251 The next three properties are the 3 constraints in "C3".
1252
Tim Petersea7f75d2002-12-07 21:39:16 +00001253 Local precendece order.
Guido van Rossum98f33732002-11-25 21:36:54 +00001254 If A precedes B in C's MRO, then A will precede B in the MRO of all
1255 subclasses of C.
1256
1257 Monotonicity.
1258 The MRO of a class must be an extension without reordering of the
1259 MRO of each of its superclasses.
1260
1261 Extended Precedence Graph (EPG).
1262 Linearization is consistent if there is a path in the EPG from
1263 each class to all its successors in the linearization. See
1264 the paper for definition of EPG.
Guido van Rossum1f121312002-11-14 19:49:16 +00001265 */
1266
Tim Petersea7f75d2002-12-07 21:39:16 +00001267static int
Guido van Rossum1f121312002-11-14 19:49:16 +00001268tail_contains(PyObject *list, int whence, PyObject *o) {
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001269 Py_ssize_t j, size;
1270 size = PyList_GET_SIZE(list);
Guido van Rossum1f121312002-11-14 19:49:16 +00001271
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001272 for (j = whence+1; j < size; j++) {
1273 if (PyList_GET_ITEM(list, j) == o)
1274 return 1;
1275 }
1276 return 0;
Guido van Rossum1f121312002-11-14 19:49:16 +00001277}
1278
Guido van Rossum98f33732002-11-25 21:36:54 +00001279static PyObject *
1280class_name(PyObject *cls)
1281{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001282 PyObject *name = PyObject_GetAttrString(cls, "__name__");
1283 if (name == NULL) {
1284 PyErr_Clear();
1285 Py_XDECREF(name);
1286 name = PyObject_Repr(cls);
1287 }
1288 if (name == NULL)
1289 return NULL;
1290 if (!PyUnicode_Check(name)) {
1291 Py_DECREF(name);
1292 return NULL;
1293 }
1294 return name;
Guido van Rossum98f33732002-11-25 21:36:54 +00001295}
1296
1297static int
1298check_duplicates(PyObject *list)
1299{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001300 Py_ssize_t i, j, n;
1301 /* Let's use a quadratic time algorithm,
1302 assuming that the bases lists is short.
1303 */
1304 n = PyList_GET_SIZE(list);
1305 for (i = 0; i < n; i++) {
1306 PyObject *o = PyList_GET_ITEM(list, i);
1307 for (j = i + 1; j < n; j++) {
1308 if (PyList_GET_ITEM(list, j) == o) {
1309 o = class_name(o);
1310 if (o != NULL) {
1311 PyErr_Format(PyExc_TypeError,
1312 "duplicate base class %U",
1313 o);
1314 Py_DECREF(o);
1315 } else {
1316 PyErr_SetString(PyExc_TypeError,
1317 "duplicate base class");
1318 }
1319 return -1;
1320 }
1321 }
1322 }
1323 return 0;
Guido van Rossum98f33732002-11-25 21:36:54 +00001324}
1325
1326/* Raise a TypeError for an MRO order disagreement.
1327
1328 It's hard to produce a good error message. In the absence of better
1329 insight into error reporting, report the classes that were candidates
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001330 to be put next into the MRO. There is some conflict between the
Guido van Rossum98f33732002-11-25 21:36:54 +00001331 order in which they should be put in the MRO, but it's hard to
1332 diagnose what constraint can't be satisfied.
1333*/
1334
1335static void
1336set_mro_error(PyObject *to_merge, int *remain)
1337{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001338 Py_ssize_t i, n, off, to_merge_size;
1339 char buf[1000];
1340 PyObject *k, *v;
1341 PyObject *set = PyDict_New();
1342 if (!set) return;
Guido van Rossum98f33732002-11-25 21:36:54 +00001343
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001344 to_merge_size = PyList_GET_SIZE(to_merge);
1345 for (i = 0; i < to_merge_size; i++) {
1346 PyObject *L = PyList_GET_ITEM(to_merge, i);
1347 if (remain[i] < PyList_GET_SIZE(L)) {
1348 PyObject *c = PyList_GET_ITEM(L, remain[i]);
1349 if (PyDict_SetItem(set, c, Py_None) < 0) {
1350 Py_DECREF(set);
1351 return;
1352 }
1353 }
1354 }
1355 n = PyDict_Size(set);
Guido van Rossum98f33732002-11-25 21:36:54 +00001356
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001357 off = PyOS_snprintf(buf, sizeof(buf), "Cannot create a \
Raymond Hettingerf394df42003-04-06 19:13:41 +00001358consistent method resolution\norder (MRO) for bases");
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001359 i = 0;
1360 while (PyDict_Next(set, &i, &k, &v) && (size_t)off < sizeof(buf)) {
1361 PyObject *name = class_name(k);
1362 off += PyOS_snprintf(buf + off, sizeof(buf) - off, " %s",
1363 name ? _PyUnicode_AsString(name) : "?");
1364 Py_XDECREF(name);
1365 if (--n && (size_t)(off+1) < sizeof(buf)) {
1366 buf[off++] = ',';
1367 buf[off] = '\0';
1368 }
1369 }
1370 PyErr_SetString(PyExc_TypeError, buf);
1371 Py_DECREF(set);
Guido van Rossum98f33732002-11-25 21:36:54 +00001372}
1373
Tim Petersea7f75d2002-12-07 21:39:16 +00001374static int
Guido van Rossum1f121312002-11-14 19:49:16 +00001375pmerge(PyObject *acc, PyObject* to_merge) {
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001376 Py_ssize_t i, j, to_merge_size, empty_cnt;
1377 int *remain;
1378 int ok;
Tim Petersea7f75d2002-12-07 21:39:16 +00001379
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001380 to_merge_size = PyList_GET_SIZE(to_merge);
Guido van Rossum1f121312002-11-14 19:49:16 +00001381
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001382 /* remain stores an index into each sublist of to_merge.
1383 remain[i] is the index of the next base in to_merge[i]
1384 that is not included in acc.
1385 */
1386 remain = (int *)PyMem_MALLOC(SIZEOF_INT*to_merge_size);
1387 if (remain == NULL)
1388 return -1;
1389 for (i = 0; i < to_merge_size; i++)
1390 remain[i] = 0;
Guido van Rossum1f121312002-11-14 19:49:16 +00001391
1392 again:
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001393 empty_cnt = 0;
1394 for (i = 0; i < to_merge_size; i++) {
1395 PyObject *candidate;
Tim Petersea7f75d2002-12-07 21:39:16 +00001396
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001397 PyObject *cur_list = PyList_GET_ITEM(to_merge, i);
Guido van Rossum1f121312002-11-14 19:49:16 +00001398
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001399 if (remain[i] >= PyList_GET_SIZE(cur_list)) {
1400 empty_cnt++;
1401 continue;
1402 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001403
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001404 /* Choose next candidate for MRO.
Guido van Rossum98f33732002-11-25 21:36:54 +00001405
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001406 The input sequences alone can determine the choice.
1407 If not, choose the class which appears in the MRO
1408 of the earliest direct superclass of the new class.
1409 */
Guido van Rossum98f33732002-11-25 21:36:54 +00001410
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001411 candidate = PyList_GET_ITEM(cur_list, remain[i]);
1412 for (j = 0; j < to_merge_size; j++) {
1413 PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
1414 if (tail_contains(j_lst, remain[j], candidate)) {
1415 goto skip; /* continue outer loop */
1416 }
1417 }
1418 ok = PyList_Append(acc, candidate);
1419 if (ok < 0) {
1420 PyMem_Free(remain);
1421 return -1;
1422 }
1423 for (j = 0; j < to_merge_size; j++) {
1424 PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
1425 if (remain[j] < PyList_GET_SIZE(j_lst) &&
1426 PyList_GET_ITEM(j_lst, remain[j]) == candidate) {
1427 remain[j]++;
1428 }
1429 }
1430 goto again;
1431 skip: ;
1432 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001433
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001434 if (empty_cnt == to_merge_size) {
1435 PyMem_FREE(remain);
1436 return 0;
1437 }
1438 set_mro_error(to_merge, remain);
1439 PyMem_FREE(remain);
1440 return -1;
Guido van Rossum1f121312002-11-14 19:49:16 +00001441}
1442
Tim Peters6d6c1a32001-08-02 04:15:00 +00001443static PyObject *
1444mro_implementation(PyTypeObject *type)
1445{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001446 Py_ssize_t i, n;
1447 int ok;
1448 PyObject *bases, *result;
1449 PyObject *to_merge, *bases_aslist;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001450
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001451 if (type->tp_dict == NULL) {
1452 if (PyType_Ready(type) < 0)
1453 return NULL;
1454 }
Guido van Rossum63517572002-06-18 16:44:57 +00001455
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001456 /* Find a superclass linearization that honors the constraints
1457 of the explicit lists of bases and the constraints implied by
1458 each base class.
Guido van Rossum98f33732002-11-25 21:36:54 +00001459
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001460 to_merge is a list of lists, where each list is a superclass
1461 linearization implied by a base class. The last element of
1462 to_merge is the declared list of bases.
1463 */
Guido van Rossum98f33732002-11-25 21:36:54 +00001464
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001465 bases = type->tp_bases;
1466 n = PyTuple_GET_SIZE(bases);
Guido van Rossum1f121312002-11-14 19:49:16 +00001467
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001468 to_merge = PyList_New(n+1);
1469 if (to_merge == NULL)
1470 return NULL;
Guido van Rossum1f121312002-11-14 19:49:16 +00001471
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001472 for (i = 0; i < n; i++) {
1473 PyObject *base = PyTuple_GET_ITEM(bases, i);
1474 PyObject *parentMRO;
1475 parentMRO = PySequence_List(((PyTypeObject*)base)->tp_mro);
1476 if (parentMRO == NULL) {
1477 Py_DECREF(to_merge);
1478 return NULL;
1479 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001480
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001481 PyList_SET_ITEM(to_merge, i, parentMRO);
1482 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001483
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001484 bases_aslist = PySequence_List(bases);
1485 if (bases_aslist == NULL) {
1486 Py_DECREF(to_merge);
1487 return NULL;
1488 }
1489 /* This is just a basic sanity check. */
1490 if (check_duplicates(bases_aslist) < 0) {
1491 Py_DECREF(to_merge);
1492 Py_DECREF(bases_aslist);
1493 return NULL;
1494 }
1495 PyList_SET_ITEM(to_merge, n, bases_aslist);
Guido van Rossum1f121312002-11-14 19:49:16 +00001496
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001497 result = Py_BuildValue("[O]", (PyObject *)type);
1498 if (result == NULL) {
1499 Py_DECREF(to_merge);
1500 return NULL;
1501 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001502
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001503 ok = pmerge(result, to_merge);
1504 Py_DECREF(to_merge);
1505 if (ok < 0) {
1506 Py_DECREF(result);
1507 return NULL;
1508 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001509
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001510 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001511}
1512
1513static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001514mro_external(PyObject *self)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001515{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001516 PyTypeObject *type = (PyTypeObject *)self;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001517
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001518 return mro_implementation(type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001519}
1520
1521static int
1522mro_internal(PyTypeObject *type)
1523{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001524 PyObject *mro, *result, *tuple;
1525 int checkit = 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001526
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001527 if (Py_TYPE(type) == &PyType_Type) {
1528 result = mro_implementation(type);
1529 }
1530 else {
1531 static PyObject *mro_str;
1532 checkit = 1;
1533 mro = lookup_method((PyObject *)type, "mro", &mro_str);
1534 if (mro == NULL)
1535 return -1;
1536 result = PyObject_CallObject(mro, NULL);
1537 Py_DECREF(mro);
1538 }
1539 if (result == NULL)
1540 return -1;
1541 tuple = PySequence_Tuple(result);
1542 Py_DECREF(result);
1543 if (tuple == NULL)
1544 return -1;
1545 if (checkit) {
1546 Py_ssize_t i, len;
1547 PyObject *cls;
1548 PyTypeObject *solid;
Armin Rigo037d1e02005-12-29 17:07:39 +00001549
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001550 solid = solid_base(type);
Armin Rigo037d1e02005-12-29 17:07:39 +00001551
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001552 len = PyTuple_GET_SIZE(tuple);
Armin Rigo037d1e02005-12-29 17:07:39 +00001553
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001554 for (i = 0; i < len; i++) {
1555 PyTypeObject *t;
1556 cls = PyTuple_GET_ITEM(tuple, i);
1557 if (!PyType_Check(cls)) {
1558 PyErr_Format(PyExc_TypeError,
1559 "mro() returned a non-class ('%.500s')",
1560 Py_TYPE(cls)->tp_name);
1561 Py_DECREF(tuple);
1562 return -1;
1563 }
1564 t = (PyTypeObject*)cls;
1565 if (!PyType_IsSubtype(solid, solid_base(t))) {
1566 PyErr_Format(PyExc_TypeError,
1567 "mro() returned base with unsuitable layout ('%.500s')",
1568 t->tp_name);
1569 Py_DECREF(tuple);
1570 return -1;
1571 }
1572 }
1573 }
1574 type->tp_mro = tuple;
Christian Heimesa62da1d2008-01-12 19:39:10 +00001575
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001576 type_mro_modified(type, type->tp_mro);
1577 /* corner case: the old-style super class might have been hidden
1578 from the custom MRO */
1579 type_mro_modified(type, type->tp_bases);
Christian Heimesa62da1d2008-01-12 19:39:10 +00001580
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001581 PyType_Modified(type);
Christian Heimesa62da1d2008-01-12 19:39:10 +00001582
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001583 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001584}
1585
1586
1587/* Calculate the best base amongst multiple base classes.
1588 This is the first one that's on the path to the "solid base". */
1589
1590static PyTypeObject *
1591best_base(PyObject *bases)
1592{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001593 Py_ssize_t i, n;
1594 PyTypeObject *base, *winner, *candidate, *base_i;
1595 PyObject *base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001596
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001597 assert(PyTuple_Check(bases));
1598 n = PyTuple_GET_SIZE(bases);
1599 assert(n > 0);
1600 base = NULL;
1601 winner = NULL;
1602 for (i = 0; i < n; i++) {
1603 base_proto = PyTuple_GET_ITEM(bases, i);
1604 if (!PyType_Check(base_proto)) {
1605 PyErr_SetString(
1606 PyExc_TypeError,
1607 "bases must be types");
1608 return NULL;
1609 }
1610 base_i = (PyTypeObject *)base_proto;
1611 if (base_i->tp_dict == NULL) {
1612 if (PyType_Ready(base_i) < 0)
1613 return NULL;
1614 }
1615 candidate = solid_base(base_i);
1616 if (winner == NULL) {
1617 winner = candidate;
1618 base = base_i;
1619 }
1620 else if (PyType_IsSubtype(winner, candidate))
1621 ;
1622 else if (PyType_IsSubtype(candidate, winner)) {
1623 winner = candidate;
1624 base = base_i;
1625 }
1626 else {
1627 PyErr_SetString(
1628 PyExc_TypeError,
1629 "multiple bases have "
1630 "instance lay-out conflict");
1631 return NULL;
1632 }
1633 }
1634 if (base == NULL)
1635 PyErr_SetString(PyExc_TypeError,
1636 "a new-style class can't have only classic bases");
1637 return base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001638}
1639
1640static int
1641extra_ivars(PyTypeObject *type, PyTypeObject *base)
1642{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001643 size_t t_size = type->tp_basicsize;
1644 size_t b_size = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001645
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001646 assert(t_size >= b_size); /* Else type smaller than base! */
1647 if (type->tp_itemsize || base->tp_itemsize) {
1648 /* If itemsize is involved, stricter rules */
1649 return t_size != b_size ||
1650 type->tp_itemsize != base->tp_itemsize;
1651 }
1652 if (type->tp_weaklistoffset && base->tp_weaklistoffset == 0 &&
1653 type->tp_weaklistoffset + sizeof(PyObject *) == t_size &&
1654 type->tp_flags & Py_TPFLAGS_HEAPTYPE)
1655 t_size -= sizeof(PyObject *);
1656 if (type->tp_dictoffset && base->tp_dictoffset == 0 &&
1657 type->tp_dictoffset + sizeof(PyObject *) == t_size &&
1658 type->tp_flags & Py_TPFLAGS_HEAPTYPE)
1659 t_size -= sizeof(PyObject *);
Guido van Rossum9676b222001-08-17 20:32:36 +00001660
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001661 return t_size != b_size;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001662}
1663
1664static PyTypeObject *
1665solid_base(PyTypeObject *type)
1666{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001667 PyTypeObject *base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001668
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001669 if (type->tp_base)
1670 base = solid_base(type->tp_base);
1671 else
1672 base = &PyBaseObject_Type;
1673 if (extra_ivars(type, base))
1674 return type;
1675 else
1676 return base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001677}
1678
Jeremy Hylton938ace62002-07-17 16:30:39 +00001679static void object_dealloc(PyObject *);
1680static int object_init(PyObject *, PyObject *, PyObject *);
1681static int update_slot(PyTypeObject *, PyObject *);
1682static void fixup_slot_dispatchers(PyTypeObject *);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001683
Guido van Rossum360e4b82007-05-14 22:51:27 +00001684/*
1685 * Helpers for __dict__ descriptor. We don't want to expose the dicts
1686 * inherited from various builtin types. The builtin base usually provides
1687 * its own __dict__ descriptor, so we use that when we can.
1688 */
1689static PyTypeObject *
1690get_builtin_base_with_dict(PyTypeObject *type)
1691{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001692 while (type->tp_base != NULL) {
1693 if (type->tp_dictoffset != 0 &&
1694 !(type->tp_flags & Py_TPFLAGS_HEAPTYPE))
1695 return type;
1696 type = type->tp_base;
1697 }
1698 return NULL;
Guido van Rossum360e4b82007-05-14 22:51:27 +00001699}
1700
1701static PyObject *
1702get_dict_descriptor(PyTypeObject *type)
1703{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001704 static PyObject *dict_str;
1705 PyObject *descr;
Guido van Rossum360e4b82007-05-14 22:51:27 +00001706
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001707 if (dict_str == NULL) {
1708 dict_str = PyUnicode_InternFromString("__dict__");
1709 if (dict_str == NULL)
1710 return NULL;
1711 }
1712 descr = _PyType_Lookup(type, dict_str);
1713 if (descr == NULL || !PyDescr_IsData(descr))
1714 return NULL;
Guido van Rossum360e4b82007-05-14 22:51:27 +00001715
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001716 return descr;
Guido van Rossum360e4b82007-05-14 22:51:27 +00001717}
1718
1719static void
1720raise_dict_descr_error(PyObject *obj)
1721{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001722 PyErr_Format(PyExc_TypeError,
1723 "this __dict__ descriptor does not support "
1724 "'%.200s' objects", Py_TYPE(obj)->tp_name);
Guido van Rossum360e4b82007-05-14 22:51:27 +00001725}
1726
Tim Peters6d6c1a32001-08-02 04:15:00 +00001727static PyObject *
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001728subtype_dict(PyObject *obj, void *context)
1729{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001730 PyObject **dictptr;
1731 PyObject *dict;
1732 PyTypeObject *base;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001733
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001734 base = get_builtin_base_with_dict(Py_TYPE(obj));
1735 if (base != NULL) {
1736 descrgetfunc func;
1737 PyObject *descr = get_dict_descriptor(base);
1738 if (descr == NULL) {
1739 raise_dict_descr_error(obj);
1740 return NULL;
1741 }
1742 func = Py_TYPE(descr)->tp_descr_get;
1743 if (func == NULL) {
1744 raise_dict_descr_error(obj);
1745 return NULL;
1746 }
1747 return func(descr, obj, (PyObject *)(Py_TYPE(obj)));
1748 }
Guido van Rossum360e4b82007-05-14 22:51:27 +00001749
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001750 dictptr = _PyObject_GetDictPtr(obj);
1751 if (dictptr == NULL) {
1752 PyErr_SetString(PyExc_AttributeError,
1753 "This object has no __dict__");
1754 return NULL;
1755 }
1756 dict = *dictptr;
1757 if (dict == NULL)
1758 *dictptr = dict = PyDict_New();
1759 Py_XINCREF(dict);
1760 return dict;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001761}
1762
Guido van Rossum6661be32001-10-26 04:26:12 +00001763static int
1764subtype_setdict(PyObject *obj, PyObject *value, void *context)
1765{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001766 PyObject **dictptr;
1767 PyObject *dict;
1768 PyTypeObject *base;
Guido van Rossum6661be32001-10-26 04:26:12 +00001769
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001770 base = get_builtin_base_with_dict(Py_TYPE(obj));
1771 if (base != NULL) {
1772 descrsetfunc func;
1773 PyObject *descr = get_dict_descriptor(base);
1774 if (descr == NULL) {
1775 raise_dict_descr_error(obj);
1776 return -1;
1777 }
1778 func = Py_TYPE(descr)->tp_descr_set;
1779 if (func == NULL) {
1780 raise_dict_descr_error(obj);
1781 return -1;
1782 }
1783 return func(descr, obj, value);
1784 }
Guido van Rossum360e4b82007-05-14 22:51:27 +00001785
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001786 dictptr = _PyObject_GetDictPtr(obj);
1787 if (dictptr == NULL) {
1788 PyErr_SetString(PyExc_AttributeError,
1789 "This object has no __dict__");
1790 return -1;
1791 }
1792 if (value != NULL && !PyDict_Check(value)) {
1793 PyErr_Format(PyExc_TypeError,
1794 "__dict__ must be set to a dictionary, "
1795 "not a '%.200s'", Py_TYPE(value)->tp_name);
1796 return -1;
1797 }
1798 dict = *dictptr;
1799 Py_XINCREF(value);
1800 *dictptr = value;
1801 Py_XDECREF(dict);
1802 return 0;
Guido van Rossum6661be32001-10-26 04:26:12 +00001803}
1804
Guido van Rossumad47da02002-08-12 19:05:44 +00001805static PyObject *
1806subtype_getweakref(PyObject *obj, void *context)
1807{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001808 PyObject **weaklistptr;
1809 PyObject *result;
Guido van Rossumad47da02002-08-12 19:05:44 +00001810
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001811 if (Py_TYPE(obj)->tp_weaklistoffset == 0) {
1812 PyErr_SetString(PyExc_AttributeError,
1813 "This object has no __weakref__");
1814 return NULL;
1815 }
1816 assert(Py_TYPE(obj)->tp_weaklistoffset > 0);
1817 assert(Py_TYPE(obj)->tp_weaklistoffset + sizeof(PyObject *) <=
1818 (size_t)(Py_TYPE(obj)->tp_basicsize));
1819 weaklistptr = (PyObject **)
1820 ((char *)obj + Py_TYPE(obj)->tp_weaklistoffset);
1821 if (*weaklistptr == NULL)
1822 result = Py_None;
1823 else
1824 result = *weaklistptr;
1825 Py_INCREF(result);
1826 return result;
Guido van Rossumad47da02002-08-12 19:05:44 +00001827}
1828
Guido van Rossum373c7412003-01-07 13:41:37 +00001829/* Three variants on the subtype_getsets list. */
1830
1831static PyGetSetDef subtype_getsets_full[] = {
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001832 {"__dict__", subtype_dict, subtype_setdict,
1833 PyDoc_STR("dictionary for instance variables (if defined)")},
1834 {"__weakref__", subtype_getweakref, NULL,
1835 PyDoc_STR("list of weak references to the object (if defined)")},
1836 {0}
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001837};
1838
Guido van Rossum373c7412003-01-07 13:41:37 +00001839static PyGetSetDef subtype_getsets_dict_only[] = {
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001840 {"__dict__", subtype_dict, subtype_setdict,
1841 PyDoc_STR("dictionary for instance variables (if defined)")},
1842 {0}
Guido van Rossum373c7412003-01-07 13:41:37 +00001843};
1844
1845static PyGetSetDef subtype_getsets_weakref_only[] = {
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001846 {"__weakref__", subtype_getweakref, NULL,
1847 PyDoc_STR("list of weak references to the object (if defined)")},
1848 {0}
Guido van Rossum373c7412003-01-07 13:41:37 +00001849};
1850
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001851static int
1852valid_identifier(PyObject *s)
1853{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001854 if (!PyUnicode_Check(s)) {
1855 PyErr_Format(PyExc_TypeError,
1856 "__slots__ items must be strings, not '%.200s'",
1857 Py_TYPE(s)->tp_name);
1858 return 0;
1859 }
1860 if (!PyUnicode_IsIdentifier(s)) {
1861 PyErr_SetString(PyExc_TypeError,
1862 "__slots__ must be identifiers");
1863 return 0;
1864 }
1865 return 1;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001866}
1867
Guido van Rossumd8faa362007-04-27 19:54:29 +00001868/* Forward */
1869static int
1870object_init(PyObject *self, PyObject *args, PyObject *kwds);
1871
1872static int
1873type_init(PyObject *cls, PyObject *args, PyObject *kwds)
1874{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001875 int res;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001876
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001877 assert(args != NULL && PyTuple_Check(args));
1878 assert(kwds == NULL || PyDict_Check(kwds));
Guido van Rossumd8faa362007-04-27 19:54:29 +00001879
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001880 if (kwds != NULL && PyDict_Check(kwds) && PyDict_Size(kwds) != 0) {
1881 PyErr_SetString(PyExc_TypeError,
1882 "type.__init__() takes no keyword arguments");
1883 return -1;
1884 }
Guido van Rossumd8faa362007-04-27 19:54:29 +00001885
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001886 if (args != NULL && PyTuple_Check(args) &&
1887 (PyTuple_GET_SIZE(args) != 1 && PyTuple_GET_SIZE(args) != 3)) {
1888 PyErr_SetString(PyExc_TypeError,
1889 "type.__init__() takes 1 or 3 arguments");
1890 return -1;
1891 }
Guido van Rossumd8faa362007-04-27 19:54:29 +00001892
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001893 /* Call object.__init__(self) now. */
1894 /* XXX Could call super(type, cls).__init__() but what's the point? */
1895 args = PyTuple_GetSlice(args, 0, 0);
1896 res = object_init(cls, args, NULL);
1897 Py_DECREF(args);
1898 return res;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001899}
1900
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001901static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00001902type_new(PyTypeObject *metatype, PyObject *args, PyObject *kwds)
1903{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001904 PyObject *name, *bases, *dict;
1905 static char *kwlist[] = {"name", "bases", "dict", 0};
1906 PyObject *slots, *tmp, *newslots;
1907 PyTypeObject *type, *base, *tmptype, *winner;
1908 PyHeapTypeObject *et;
1909 PyMemberDef *mp;
1910 Py_ssize_t i, nbases, nslots, slotoffset, add_dict, add_weak;
1911 int j, may_add_dict, may_add_weak;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001912
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001913 assert(args != NULL && PyTuple_Check(args));
1914 assert(kwds == NULL || PyDict_Check(kwds));
Tim Peters3abca122001-10-27 19:37:48 +00001915
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001916 /* Special case: type(x) should return x->ob_type */
1917 {
1918 const Py_ssize_t nargs = PyTuple_GET_SIZE(args);
1919 const Py_ssize_t nkwds = kwds == NULL ? 0 : PyDict_Size(kwds);
Tim Peters3abca122001-10-27 19:37:48 +00001920
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001921 if (PyType_CheckExact(metatype) && nargs == 1 && nkwds == 0) {
1922 PyObject *x = PyTuple_GET_ITEM(args, 0);
1923 Py_INCREF(Py_TYPE(x));
1924 return (PyObject *) Py_TYPE(x);
1925 }
Tim Peters3abca122001-10-27 19:37:48 +00001926
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001927 /* SF bug 475327 -- if that didn't trigger, we need 3
1928 arguments. but PyArg_ParseTupleAndKeywords below may give
1929 a msg saying type() needs exactly 3. */
1930 if (nargs + nkwds != 3) {
1931 PyErr_SetString(PyExc_TypeError,
1932 "type() takes 1 or 3 arguments");
1933 return NULL;
1934 }
1935 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001936
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001937 /* Check arguments: (name, bases, dict) */
1938 if (!PyArg_ParseTupleAndKeywords(args, kwds, "UO!O!:type", kwlist,
1939 &name,
1940 &PyTuple_Type, &bases,
1941 &PyDict_Type, &dict))
1942 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001943
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001944 /* Determine the proper metatype to deal with this,
1945 and check for metatype conflicts while we're at it.
1946 Note that if some other metatype wins to contract,
1947 it's possible that its instances are not types. */
1948 nbases = PyTuple_GET_SIZE(bases);
1949 winner = metatype;
1950 for (i = 0; i < nbases; i++) {
1951 tmp = PyTuple_GET_ITEM(bases, i);
1952 tmptype = Py_TYPE(tmp);
1953 if (PyType_IsSubtype(winner, tmptype))
1954 continue;
1955 if (PyType_IsSubtype(tmptype, winner)) {
1956 winner = tmptype;
1957 continue;
1958 }
1959 PyErr_SetString(PyExc_TypeError,
1960 "metaclass conflict: "
1961 "the metaclass of a derived class "
1962 "must be a (non-strict) subclass "
1963 "of the metaclasses of all its bases");
1964 return NULL;
1965 }
1966 if (winner != metatype) {
1967 if (winner->tp_new != type_new) /* Pass it to the winner */
1968 return winner->tp_new(winner, args, kwds);
1969 metatype = winner;
1970 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001971
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001972 /* Adjust for empty tuple bases */
1973 if (nbases == 0) {
1974 bases = PyTuple_Pack(1, &PyBaseObject_Type);
1975 if (bases == NULL)
1976 return NULL;
1977 nbases = 1;
1978 }
1979 else
1980 Py_INCREF(bases);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001981
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001982 /* XXX From here until type is allocated, "return NULL" leaks bases! */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001983
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001984 /* Calculate best base, and check that all bases are type objects */
1985 base = best_base(bases);
1986 if (base == NULL) {
1987 Py_DECREF(bases);
1988 return NULL;
1989 }
1990 if (!PyType_HasFeature(base, Py_TPFLAGS_BASETYPE)) {
1991 PyErr_Format(PyExc_TypeError,
1992 "type '%.100s' is not an acceptable base type",
1993 base->tp_name);
1994 Py_DECREF(bases);
1995 return NULL;
1996 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001997
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001998 /* Check for a __slots__ sequence variable in dict, and count it */
1999 slots = PyDict_GetItemString(dict, "__slots__");
2000 nslots = 0;
2001 add_dict = 0;
2002 add_weak = 0;
2003 may_add_dict = base->tp_dictoffset == 0;
2004 may_add_weak = base->tp_weaklistoffset == 0 && base->tp_itemsize == 0;
2005 if (slots == NULL) {
2006 if (may_add_dict) {
2007 add_dict++;
2008 }
2009 if (may_add_weak) {
2010 add_weak++;
2011 }
2012 }
2013 else {
2014 /* Have slots */
Guido van Rossumad47da02002-08-12 19:05:44 +00002015
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002016 /* Make it into a tuple */
2017 if (PyUnicode_Check(slots))
2018 slots = PyTuple_Pack(1, slots);
2019 else
2020 slots = PySequence_Tuple(slots);
2021 if (slots == NULL) {
2022 Py_DECREF(bases);
2023 return NULL;
2024 }
2025 assert(PyTuple_Check(slots));
Guido van Rossumad47da02002-08-12 19:05:44 +00002026
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002027 /* Are slots allowed? */
2028 nslots = PyTuple_GET_SIZE(slots);
2029 if (nslots > 0 && base->tp_itemsize != 0) {
2030 PyErr_Format(PyExc_TypeError,
2031 "nonempty __slots__ "
2032 "not supported for subtype of '%s'",
2033 base->tp_name);
2034 bad_slots:
2035 Py_DECREF(bases);
2036 Py_DECREF(slots);
2037 return NULL;
2038 }
Guido van Rossumad47da02002-08-12 19:05:44 +00002039
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002040 /* Check for valid slot names and two special cases */
2041 for (i = 0; i < nslots; i++) {
2042 PyObject *tmp = PyTuple_GET_ITEM(slots, i);
2043 if (!valid_identifier(tmp))
2044 goto bad_slots;
2045 assert(PyUnicode_Check(tmp));
2046 if (PyUnicode_CompareWithASCIIString(tmp, "__dict__") == 0) {
2047 if (!may_add_dict || add_dict) {
2048 PyErr_SetString(PyExc_TypeError,
2049 "__dict__ slot disallowed: "
2050 "we already got one");
2051 goto bad_slots;
2052 }
2053 add_dict++;
2054 }
2055 if (PyUnicode_CompareWithASCIIString(tmp, "__weakref__") == 0) {
2056 if (!may_add_weak || add_weak) {
2057 PyErr_SetString(PyExc_TypeError,
2058 "__weakref__ slot disallowed: "
2059 "either we already got one, "
2060 "or __itemsize__ != 0");
2061 goto bad_slots;
2062 }
2063 add_weak++;
2064 }
2065 }
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00002066
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002067 /* Copy slots into a list, mangle names and sort them.
2068 Sorted names are needed for __class__ assignment.
2069 Convert them back to tuple at the end.
2070 */
2071 newslots = PyList_New(nslots - add_dict - add_weak);
2072 if (newslots == NULL)
2073 goto bad_slots;
2074 for (i = j = 0; i < nslots; i++) {
2075 tmp = PyTuple_GET_ITEM(slots, i);
2076 if ((add_dict &&
2077 PyUnicode_CompareWithASCIIString(tmp, "__dict__") == 0) ||
2078 (add_weak &&
2079 PyUnicode_CompareWithASCIIString(tmp, "__weakref__") == 0))
2080 continue;
2081 tmp =_Py_Mangle(name, tmp);
2082 if (!tmp)
2083 goto bad_slots;
2084 PyList_SET_ITEM(newslots, j, tmp);
2085 j++;
2086 }
2087 assert(j == nslots - add_dict - add_weak);
2088 nslots = j;
2089 Py_DECREF(slots);
2090 if (PyList_Sort(newslots) == -1) {
2091 Py_DECREF(bases);
2092 Py_DECREF(newslots);
2093 return NULL;
2094 }
2095 slots = PyList_AsTuple(newslots);
2096 Py_DECREF(newslots);
2097 if (slots == NULL) {
2098 Py_DECREF(bases);
2099 return NULL;
2100 }
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00002101
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002102 /* Secondary bases may provide weakrefs or dict */
2103 if (nbases > 1 &&
2104 ((may_add_dict && !add_dict) ||
2105 (may_add_weak && !add_weak))) {
2106 for (i = 0; i < nbases; i++) {
2107 tmp = PyTuple_GET_ITEM(bases, i);
2108 if (tmp == (PyObject *)base)
2109 continue; /* Skip primary base */
2110 assert(PyType_Check(tmp));
2111 tmptype = (PyTypeObject *)tmp;
2112 if (may_add_dict && !add_dict &&
2113 tmptype->tp_dictoffset != 0)
2114 add_dict++;
2115 if (may_add_weak && !add_weak &&
2116 tmptype->tp_weaklistoffset != 0)
2117 add_weak++;
2118 if (may_add_dict && !add_dict)
2119 continue;
2120 if (may_add_weak && !add_weak)
2121 continue;
2122 /* Nothing more to check */
2123 break;
2124 }
2125 }
2126 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002127
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002128 /* XXX From here until type is safely allocated,
2129 "return NULL" may leak slots! */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002130
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002131 /* Allocate the type object */
2132 type = (PyTypeObject *)metatype->tp_alloc(metatype, nslots);
2133 if (type == NULL) {
2134 Py_XDECREF(slots);
2135 Py_DECREF(bases);
2136 return NULL;
2137 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002138
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002139 /* Keep name and slots alive in the extended type object */
2140 et = (PyHeapTypeObject *)type;
2141 Py_INCREF(name);
2142 et->ht_name = name;
2143 et->ht_slots = slots;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002144
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002145 /* Initialize tp_flags */
2146 type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE |
2147 Py_TPFLAGS_BASETYPE;
2148 if (base->tp_flags & Py_TPFLAGS_HAVE_GC)
2149 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossumdc91b992001-08-08 22:26:22 +00002150
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002151 /* Initialize essential fields */
2152 type->tp_as_number = &et->as_number;
2153 type->tp_as_sequence = &et->as_sequence;
2154 type->tp_as_mapping = &et->as_mapping;
2155 type->tp_as_buffer = &et->as_buffer;
2156 type->tp_name = _PyUnicode_AsString(name);
2157 if (!type->tp_name) {
2158 Py_DECREF(type);
2159 return NULL;
2160 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002161
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002162 /* Set tp_base and tp_bases */
2163 type->tp_bases = bases;
2164 Py_INCREF(base);
2165 type->tp_base = base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002166
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002167 /* Initialize tp_dict from passed-in dict */
2168 type->tp_dict = dict = PyDict_Copy(dict);
2169 if (dict == NULL) {
2170 Py_DECREF(type);
2171 return NULL;
2172 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002173
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002174 /* Set __module__ in the dict */
2175 if (PyDict_GetItemString(dict, "__module__") == NULL) {
2176 tmp = PyEval_GetGlobals();
2177 if (tmp != NULL) {
2178 tmp = PyDict_GetItemString(tmp, "__name__");
2179 if (tmp != NULL) {
2180 if (PyDict_SetItemString(dict, "__module__",
2181 tmp) < 0)
2182 return NULL;
2183 }
2184 }
2185 }
Guido van Rossumc3542212001-08-16 09:18:56 +00002186
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002187 /* Set tp_doc to a copy of dict['__doc__'], if the latter is there
2188 and is a string. The __doc__ accessor will first look for tp_doc;
2189 if that fails, it will still look into __dict__.
2190 */
2191 {
2192 PyObject *doc = PyDict_GetItemString(dict, "__doc__");
2193 if (doc != NULL && PyUnicode_Check(doc)) {
2194 Py_ssize_t len;
2195 char *doc_str;
2196 char *tp_doc;
Alexandre Vassalottia85998a2008-05-03 18:24:43 +00002197
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002198 doc_str = _PyUnicode_AsString(doc);
2199 if (doc_str == NULL) {
2200 Py_DECREF(type);
2201 return NULL;
2202 }
2203 /* Silently truncate the docstring if it contains null bytes. */
2204 len = strlen(doc_str);
2205 tp_doc = (char *)PyObject_MALLOC(len + 1);
2206 if (tp_doc == NULL) {
2207 Py_DECREF(type);
2208 return NULL;
2209 }
2210 memcpy(tp_doc, doc_str, len + 1);
2211 type->tp_doc = tp_doc;
2212 }
2213 }
Tim Peters2f93e282001-10-04 05:27:00 +00002214
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002215 /* Special-case __new__: if it's a plain function,
2216 make it a static function */
2217 tmp = PyDict_GetItemString(dict, "__new__");
2218 if (tmp != NULL && PyFunction_Check(tmp)) {
2219 tmp = PyStaticMethod_New(tmp);
2220 if (tmp == NULL) {
2221 Py_DECREF(type);
2222 return NULL;
2223 }
2224 PyDict_SetItemString(dict, "__new__", tmp);
2225 Py_DECREF(tmp);
2226 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002227
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002228 /* Add descriptors for custom slots from __slots__, or for __dict__ */
2229 mp = PyHeapType_GET_MEMBERS(et);
2230 slotoffset = base->tp_basicsize;
2231 if (slots != NULL) {
2232 for (i = 0; i < nslots; i++, mp++) {
2233 mp->name = _PyUnicode_AsString(
2234 PyTuple_GET_ITEM(slots, i));
2235 mp->type = T_OBJECT_EX;
2236 mp->offset = slotoffset;
Guido van Rossumd8faa362007-04-27 19:54:29 +00002237
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002238 /* __dict__ and __weakref__ are already filtered out */
2239 assert(strcmp(mp->name, "__dict__") != 0);
2240 assert(strcmp(mp->name, "__weakref__") != 0);
Guido van Rossumd8faa362007-04-27 19:54:29 +00002241
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002242 slotoffset += sizeof(PyObject *);
2243 }
2244 }
2245 if (add_dict) {
2246 if (base->tp_itemsize)
2247 type->tp_dictoffset = -(long)sizeof(PyObject *);
2248 else
2249 type->tp_dictoffset = slotoffset;
2250 slotoffset += sizeof(PyObject *);
2251 }
2252 if (add_weak) {
2253 assert(!base->tp_itemsize);
2254 type->tp_weaklistoffset = slotoffset;
2255 slotoffset += sizeof(PyObject *);
2256 }
2257 type->tp_basicsize = slotoffset;
2258 type->tp_itemsize = base->tp_itemsize;
2259 type->tp_members = PyHeapType_GET_MEMBERS(et);
Guido van Rossum373c7412003-01-07 13:41:37 +00002260
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002261 if (type->tp_weaklistoffset && type->tp_dictoffset)
2262 type->tp_getset = subtype_getsets_full;
2263 else if (type->tp_weaklistoffset && !type->tp_dictoffset)
2264 type->tp_getset = subtype_getsets_weakref_only;
2265 else if (!type->tp_weaklistoffset && type->tp_dictoffset)
2266 type->tp_getset = subtype_getsets_dict_only;
2267 else
2268 type->tp_getset = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002269
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002270 /* Special case some slots */
2271 if (type->tp_dictoffset != 0 || nslots > 0) {
2272 if (base->tp_getattr == NULL && base->tp_getattro == NULL)
2273 type->tp_getattro = PyObject_GenericGetAttr;
2274 if (base->tp_setattr == NULL && base->tp_setattro == NULL)
2275 type->tp_setattro = PyObject_GenericSetAttr;
2276 }
2277 type->tp_dealloc = subtype_dealloc;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002278
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002279 /* Enable GC unless there are really no instance variables possible */
2280 if (!(type->tp_basicsize == sizeof(PyObject) &&
2281 type->tp_itemsize == 0))
2282 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossum9475a232001-10-05 20:51:39 +00002283
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002284 /* Always override allocation strategy to use regular heap */
2285 type->tp_alloc = PyType_GenericAlloc;
2286 if (type->tp_flags & Py_TPFLAGS_HAVE_GC) {
2287 type->tp_free = PyObject_GC_Del;
2288 type->tp_traverse = subtype_traverse;
2289 type->tp_clear = subtype_clear;
2290 }
2291 else
2292 type->tp_free = PyObject_Del;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002293
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002294 /* Initialize the rest */
2295 if (PyType_Ready(type) < 0) {
2296 Py_DECREF(type);
2297 return NULL;
2298 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002299
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002300 /* Put the proper slots in place */
2301 fixup_slot_dispatchers(type);
Guido van Rossumf040ede2001-08-07 16:40:56 +00002302
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002303 return (PyObject *)type;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002304}
2305
2306/* Internal API to look for a name through the MRO.
2307 This returns a borrowed reference, and doesn't set an exception! */
2308PyObject *
2309_PyType_Lookup(PyTypeObject *type, PyObject *name)
2310{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002311 Py_ssize_t i, n;
2312 PyObject *mro, *res, *base, *dict;
2313 unsigned int h;
Christian Heimesa62da1d2008-01-12 19:39:10 +00002314
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002315 if (MCACHE_CACHEABLE_NAME(name) &&
2316 PyType_HasFeature(type, Py_TPFLAGS_VALID_VERSION_TAG)) {
2317 /* fast path */
2318 h = MCACHE_HASH_METHOD(type, name);
2319 if (method_cache[h].version == type->tp_version_tag &&
2320 method_cache[h].name == name)
2321 return method_cache[h].value;
2322 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002323
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002324 /* Look in tp_dict of types in MRO */
2325 mro = type->tp_mro;
Guido van Rossum23094982002-06-10 14:30:43 +00002326
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002327 /* If mro is NULL, the type is either not yet initialized
2328 by PyType_Ready(), or already cleared by type_clear().
2329 Either way the safest thing to do is to return NULL. */
2330 if (mro == NULL)
2331 return NULL;
Guido van Rossum23094982002-06-10 14:30:43 +00002332
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002333 res = NULL;
2334 assert(PyTuple_Check(mro));
2335 n = PyTuple_GET_SIZE(mro);
2336 for (i = 0; i < n; i++) {
2337 base = PyTuple_GET_ITEM(mro, i);
2338 assert(PyType_Check(base));
2339 dict = ((PyTypeObject *)base)->tp_dict;
2340 assert(dict && PyDict_Check(dict));
2341 res = PyDict_GetItem(dict, name);
2342 if (res != NULL)
2343 break;
2344 }
Christian Heimesa62da1d2008-01-12 19:39:10 +00002345
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002346 if (MCACHE_CACHEABLE_NAME(name) && assign_version_tag(type)) {
2347 h = MCACHE_HASH_METHOD(type, name);
2348 method_cache[h].version = type->tp_version_tag;
2349 method_cache[h].value = res; /* borrowed */
2350 Py_INCREF(name);
2351 Py_DECREF(method_cache[h].name);
2352 method_cache[h].name = name;
2353 }
2354 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002355}
2356
2357/* This is similar to PyObject_GenericGetAttr(),
2358 but uses _PyType_Lookup() instead of just looking in type->tp_dict. */
2359static PyObject *
2360type_getattro(PyTypeObject *type, PyObject *name)
2361{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002362 PyTypeObject *metatype = Py_TYPE(type);
2363 PyObject *meta_attribute, *attribute;
2364 descrgetfunc meta_get;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002365
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002366 /* Initialize this type (we'll assume the metatype is initialized) */
2367 if (type->tp_dict == NULL) {
2368 if (PyType_Ready(type) < 0)
2369 return NULL;
2370 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002371
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002372 /* No readable descriptor found yet */
2373 meta_get = NULL;
Tim Peters34592512002-07-11 06:23:50 +00002374
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002375 /* Look for the attribute in the metatype */
2376 meta_attribute = _PyType_Lookup(metatype, name);
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002377
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002378 if (meta_attribute != NULL) {
2379 meta_get = Py_TYPE(meta_attribute)->tp_descr_get;
Tim Peters34592512002-07-11 06:23:50 +00002380
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002381 if (meta_get != NULL && PyDescr_IsData(meta_attribute)) {
2382 /* Data descriptors implement tp_descr_set to intercept
2383 * writes. Assume the attribute is not overridden in
2384 * type's tp_dict (and bases): call the descriptor now.
2385 */
2386 return meta_get(meta_attribute, (PyObject *)type,
2387 (PyObject *)metatype);
2388 }
2389 Py_INCREF(meta_attribute);
2390 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002391
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002392 /* No data descriptor found on metatype. Look in tp_dict of this
2393 * type and its bases */
2394 attribute = _PyType_Lookup(type, name);
2395 if (attribute != NULL) {
2396 /* Implement descriptor functionality, if any */
2397 descrgetfunc local_get = Py_TYPE(attribute)->tp_descr_get;
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00002398
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002399 Py_XDECREF(meta_attribute);
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00002400
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002401 if (local_get != NULL) {
2402 /* NULL 2nd argument indicates the descriptor was
2403 * found on the target object itself (or a base) */
2404 return local_get(attribute, (PyObject *)NULL,
2405 (PyObject *)type);
2406 }
Tim Peters34592512002-07-11 06:23:50 +00002407
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002408 Py_INCREF(attribute);
2409 return attribute;
2410 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002411
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002412 /* No attribute found in local __dict__ (or bases): use the
2413 * descriptor from the metatype, if any */
2414 if (meta_get != NULL) {
2415 PyObject *res;
2416 res = meta_get(meta_attribute, (PyObject *)type,
2417 (PyObject *)metatype);
2418 Py_DECREF(meta_attribute);
2419 return res;
2420 }
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002421
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002422 /* If an ordinary attribute was found on the metatype, return it now */
2423 if (meta_attribute != NULL) {
2424 return meta_attribute;
2425 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002426
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002427 /* Give up */
2428 PyErr_Format(PyExc_AttributeError,
2429 "type object '%.50s' has no attribute '%U'",
2430 type->tp_name, name);
2431 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002432}
2433
2434static int
2435type_setattro(PyTypeObject *type, PyObject *name, PyObject *value)
2436{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002437 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
2438 PyErr_Format(
2439 PyExc_TypeError,
2440 "can't set attributes of built-in/extension type '%s'",
2441 type->tp_name);
2442 return -1;
2443 }
2444 if (PyObject_GenericSetAttr((PyObject *)type, name, value) < 0)
2445 return -1;
2446 return update_slot(type, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002447}
2448
2449static void
2450type_dealloc(PyTypeObject *type)
2451{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002452 PyHeapTypeObject *et;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002453
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002454 /* Assert this is a heap-allocated type object */
2455 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
2456 _PyObject_GC_UNTRACK(type);
2457 PyObject_ClearWeakRefs((PyObject *)type);
2458 et = (PyHeapTypeObject *)type;
2459 Py_XDECREF(type->tp_base);
2460 Py_XDECREF(type->tp_dict);
2461 Py_XDECREF(type->tp_bases);
2462 Py_XDECREF(type->tp_mro);
2463 Py_XDECREF(type->tp_cache);
2464 Py_XDECREF(type->tp_subclasses);
2465 /* A type's tp_doc is heap allocated, unlike the tp_doc slots
2466 * of most other objects. It's okay to cast it to char *.
2467 */
2468 PyObject_Free((char *)type->tp_doc);
2469 Py_XDECREF(et->ht_name);
2470 Py_XDECREF(et->ht_slots);
2471 Py_TYPE(type)->tp_free((PyObject *)type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002472}
2473
Guido van Rossum1c450732001-10-08 15:18:27 +00002474static PyObject *
2475type_subclasses(PyTypeObject *type, PyObject *args_ignored)
2476{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002477 PyObject *list, *raw, *ref;
2478 Py_ssize_t i, n;
Guido van Rossum1c450732001-10-08 15:18:27 +00002479
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002480 list = PyList_New(0);
2481 if (list == NULL)
2482 return NULL;
2483 raw = type->tp_subclasses;
2484 if (raw == NULL)
2485 return list;
2486 assert(PyList_Check(raw));
2487 n = PyList_GET_SIZE(raw);
2488 for (i = 0; i < n; i++) {
2489 ref = PyList_GET_ITEM(raw, i);
2490 assert(PyWeakref_CheckRef(ref));
2491 ref = PyWeakref_GET_OBJECT(ref);
2492 if (ref != Py_None) {
2493 if (PyList_Append(list, ref) < 0) {
2494 Py_DECREF(list);
2495 return NULL;
2496 }
2497 }
2498 }
2499 return list;
Guido van Rossum1c450732001-10-08 15:18:27 +00002500}
2501
Guido van Rossum47374822007-08-02 16:48:17 +00002502static PyObject *
2503type_prepare(PyObject *self, PyObject *args, PyObject *kwds)
2504{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002505 return PyDict_New();
Guido van Rossum47374822007-08-02 16:48:17 +00002506}
2507
Tim Peters6d6c1a32001-08-02 04:15:00 +00002508static PyMethodDef type_methods[] = {
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002509 {"mro", (PyCFunction)mro_external, METH_NOARGS,
2510 PyDoc_STR("mro() -> list\nreturn a type's method resolution order")},
2511 {"__subclasses__", (PyCFunction)type_subclasses, METH_NOARGS,
2512 PyDoc_STR("__subclasses__() -> list of immediate subclasses")},
2513 {"__prepare__", (PyCFunction)type_prepare,
2514 METH_VARARGS | METH_KEYWORDS | METH_CLASS,
2515 PyDoc_STR("__prepare__() -> dict\n"
2516 "used to create the namespace for the class statement")},
2517 {"__instancecheck__", type___instancecheck__, METH_O,
2518 PyDoc_STR("__instancecheck__() -> check if an object is an instance")},
2519 {"__subclasscheck__", type___subclasscheck__, METH_O,
Alexander Belopolsky102594f2010-08-16 20:26:04 +00002520 PyDoc_STR("__subclasscheck__() -> check if a class is a subclass")},
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002521 {0}
Tim Peters6d6c1a32001-08-02 04:15:00 +00002522};
2523
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002524PyDoc_STRVAR(type_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00002525"type(object) -> the object's type\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002526"type(name, bases, dict) -> a new type");
Tim Peters6d6c1a32001-08-02 04:15:00 +00002527
Guido van Rossum048eb752001-10-02 21:24:57 +00002528static int
2529type_traverse(PyTypeObject *type, visitproc visit, void *arg)
2530{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002531 /* Because of type_is_gc(), the collector only calls this
2532 for heaptypes. */
2533 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002534
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002535 Py_VISIT(type->tp_dict);
2536 Py_VISIT(type->tp_cache);
2537 Py_VISIT(type->tp_mro);
2538 Py_VISIT(type->tp_bases);
2539 Py_VISIT(type->tp_base);
Guido van Rossuma3862092002-06-10 15:24:42 +00002540
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002541 /* There's no need to visit type->tp_subclasses or
2542 ((PyHeapTypeObject *)type)->ht_slots, because they can't be involved
2543 in cycles; tp_subclasses is a list of weak references,
2544 and slots is a tuple of strings. */
Guido van Rossum048eb752001-10-02 21:24:57 +00002545
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002546 return 0;
Guido van Rossum048eb752001-10-02 21:24:57 +00002547}
2548
2549static int
2550type_clear(PyTypeObject *type)
2551{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002552 /* Because of type_is_gc(), the collector only calls this
2553 for heaptypes. */
2554 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002555
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002556 /* The only field we need to clear is tp_mro, which is part of a
2557 hard cycle (its first element is the class itself) that won't
2558 be broken otherwise (it's a tuple and tuples don't have a
2559 tp_clear handler). None of the other fields need to be
2560 cleared, and here's why:
Guido van Rossum048eb752001-10-02 21:24:57 +00002561
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002562 tp_dict:
2563 It is a dict, so the collector will call its tp_clear.
Guido van Rossuma3862092002-06-10 15:24:42 +00002564
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002565 tp_cache:
2566 Not used; if it were, it would be a dict.
Guido van Rossuma3862092002-06-10 15:24:42 +00002567
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002568 tp_bases, tp_base:
2569 If these are involved in a cycle, there must be at least
2570 one other, mutable object in the cycle, e.g. a base
2571 class's dict; the cycle will be broken that way.
Guido van Rossuma3862092002-06-10 15:24:42 +00002572
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002573 tp_subclasses:
2574 A list of weak references can't be part of a cycle; and
2575 lists have their own tp_clear.
Guido van Rossuma3862092002-06-10 15:24:42 +00002576
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002577 slots (in PyHeapTypeObject):
2578 A tuple of strings can't be part of a cycle.
2579 */
Guido van Rossuma3862092002-06-10 15:24:42 +00002580
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002581 Py_CLEAR(type->tp_mro);
Guido van Rossum048eb752001-10-02 21:24:57 +00002582
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002583 return 0;
Guido van Rossum048eb752001-10-02 21:24:57 +00002584}
2585
2586static int
2587type_is_gc(PyTypeObject *type)
2588{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002589 return type->tp_flags & Py_TPFLAGS_HEAPTYPE;
Guido van Rossum048eb752001-10-02 21:24:57 +00002590}
2591
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002592PyTypeObject PyType_Type = {
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002593 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2594 "type", /* tp_name */
2595 sizeof(PyHeapTypeObject), /* tp_basicsize */
2596 sizeof(PyMemberDef), /* tp_itemsize */
2597 (destructor)type_dealloc, /* tp_dealloc */
2598 0, /* tp_print */
2599 0, /* tp_getattr */
2600 0, /* tp_setattr */
2601 0, /* tp_reserved */
2602 (reprfunc)type_repr, /* tp_repr */
2603 0, /* tp_as_number */
2604 0, /* tp_as_sequence */
2605 0, /* tp_as_mapping */
2606 0, /* tp_hash */
2607 (ternaryfunc)type_call, /* tp_call */
2608 0, /* tp_str */
2609 (getattrofunc)type_getattro, /* tp_getattro */
2610 (setattrofunc)type_setattro, /* tp_setattro */
2611 0, /* tp_as_buffer */
2612 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
2613 Py_TPFLAGS_BASETYPE | Py_TPFLAGS_TYPE_SUBCLASS, /* tp_flags */
2614 type_doc, /* tp_doc */
2615 (traverseproc)type_traverse, /* tp_traverse */
2616 (inquiry)type_clear, /* tp_clear */
2617 0, /* tp_richcompare */
2618 offsetof(PyTypeObject, tp_weaklist), /* tp_weaklistoffset */
2619 0, /* tp_iter */
2620 0, /* tp_iternext */
2621 type_methods, /* tp_methods */
2622 type_members, /* tp_members */
2623 type_getsets, /* tp_getset */
2624 0, /* tp_base */
2625 0, /* tp_dict */
2626 0, /* tp_descr_get */
2627 0, /* tp_descr_set */
2628 offsetof(PyTypeObject, tp_dict), /* tp_dictoffset */
2629 type_init, /* tp_init */
2630 0, /* tp_alloc */
2631 type_new, /* tp_new */
2632 PyObject_GC_Del, /* tp_free */
2633 (inquiry)type_is_gc, /* tp_is_gc */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002634};
Tim Peters6d6c1a32001-08-02 04:15:00 +00002635
2636
2637/* The base type of all types (eventually)... except itself. */
2638
Guido van Rossumd8faa362007-04-27 19:54:29 +00002639/* You may wonder why object.__new__() only complains about arguments
2640 when object.__init__() is not overridden, and vice versa.
2641
2642 Consider the use cases:
2643
2644 1. When neither is overridden, we want to hear complaints about
2645 excess (i.e., any) arguments, since their presence could
2646 indicate there's a bug.
2647
2648 2. When defining an Immutable type, we are likely to override only
2649 __new__(), since __init__() is called too late to initialize an
2650 Immutable object. Since __new__() defines the signature for the
2651 type, it would be a pain to have to override __init__() just to
2652 stop it from complaining about excess arguments.
2653
2654 3. When defining a Mutable type, we are likely to override only
2655 __init__(). So here the converse reasoning applies: we don't
2656 want to have to override __new__() just to stop it from
2657 complaining.
2658
2659 4. When __init__() is overridden, and the subclass __init__() calls
2660 object.__init__(), the latter should complain about excess
2661 arguments; ditto for __new__().
2662
2663 Use cases 2 and 3 make it unattractive to unconditionally check for
2664 excess arguments. The best solution that addresses all four use
2665 cases is as follows: __init__() complains about excess arguments
2666 unless __new__() is overridden and __init__() is not overridden
2667 (IOW, if __init__() is overridden or __new__() is not overridden);
2668 symmetrically, __new__() complains about excess arguments unless
2669 __init__() is overridden and __new__() is not overridden
2670 (IOW, if __new__() is overridden or __init__() is not overridden).
2671
2672 However, for backwards compatibility, this breaks too much code.
2673 Therefore, in 2.6, we'll *warn* about excess arguments when both
2674 methods are overridden; for all other cases we'll use the above
2675 rules.
2676
2677*/
2678
2679/* Forward */
2680static PyObject *
2681object_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
2682
2683static int
2684excess_args(PyObject *args, PyObject *kwds)
2685{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002686 return PyTuple_GET_SIZE(args) ||
2687 (kwds && PyDict_Check(kwds) && PyDict_Size(kwds));
Guido van Rossumd8faa362007-04-27 19:54:29 +00002688}
2689
Tim Peters6d6c1a32001-08-02 04:15:00 +00002690static int
2691object_init(PyObject *self, PyObject *args, PyObject *kwds)
2692{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002693 int err = 0;
2694 if (excess_args(args, kwds)) {
2695 PyTypeObject *type = Py_TYPE(self);
2696 if (type->tp_init != object_init &&
2697 type->tp_new != object_new)
2698 {
2699 err = PyErr_WarnEx(PyExc_DeprecationWarning,
2700 "object.__init__() takes no parameters",
2701 1);
2702 }
2703 else if (type->tp_init != object_init ||
2704 type->tp_new == object_new)
2705 {
2706 PyErr_SetString(PyExc_TypeError,
2707 "object.__init__() takes no parameters");
2708 err = -1;
2709 }
2710 }
2711 return err;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002712}
2713
Guido van Rossum298e4212003-02-13 16:30:16 +00002714static PyObject *
2715object_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2716{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002717 int err = 0;
2718 if (excess_args(args, kwds)) {
2719 if (type->tp_new != object_new &&
2720 type->tp_init != object_init)
2721 {
2722 err = PyErr_WarnEx(PyExc_DeprecationWarning,
2723 "object.__new__() takes no parameters",
2724 1);
2725 }
2726 else if (type->tp_new != object_new ||
2727 type->tp_init == object_init)
2728 {
2729 PyErr_SetString(PyExc_TypeError,
2730 "object.__new__() takes no parameters");
2731 err = -1;
2732 }
2733 }
2734 if (err < 0)
2735 return NULL;
Christian Heimes9e7f1d22008-02-28 12:27:11 +00002736
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002737 if (type->tp_flags & Py_TPFLAGS_IS_ABSTRACT) {
2738 static PyObject *comma = NULL;
2739 PyObject *abstract_methods = NULL;
2740 PyObject *builtins;
2741 PyObject *sorted;
2742 PyObject *sorted_methods = NULL;
2743 PyObject *joined = NULL;
Christian Heimes9e7f1d22008-02-28 12:27:11 +00002744
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002745 /* Compute ", ".join(sorted(type.__abstractmethods__))
2746 into joined. */
2747 abstract_methods = type_abstractmethods(type, NULL);
2748 if (abstract_methods == NULL)
2749 goto error;
2750 builtins = PyEval_GetBuiltins();
2751 if (builtins == NULL)
2752 goto error;
2753 sorted = PyDict_GetItemString(builtins, "sorted");
2754 if (sorted == NULL)
2755 goto error;
2756 sorted_methods = PyObject_CallFunctionObjArgs(sorted,
2757 abstract_methods,
2758 NULL);
2759 if (sorted_methods == NULL)
2760 goto error;
2761 if (comma == NULL) {
2762 comma = PyUnicode_InternFromString(", ");
2763 if (comma == NULL)
2764 goto error;
2765 }
2766 joined = PyObject_CallMethod(comma, "join",
2767 "O", sorted_methods);
2768 if (joined == NULL)
2769 goto error;
Christian Heimes9e7f1d22008-02-28 12:27:11 +00002770
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002771 PyErr_Format(PyExc_TypeError,
2772 "Can't instantiate abstract class %s "
2773 "with abstract methods %U",
2774 type->tp_name,
2775 joined);
2776 error:
2777 Py_XDECREF(joined);
2778 Py_XDECREF(sorted_methods);
2779 Py_XDECREF(abstract_methods);
2780 return NULL;
2781 }
2782 return type->tp_alloc(type, 0);
Guido van Rossum298e4212003-02-13 16:30:16 +00002783}
2784
Tim Peters6d6c1a32001-08-02 04:15:00 +00002785static void
2786object_dealloc(PyObject *self)
2787{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002788 Py_TYPE(self)->tp_free(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002789}
2790
Guido van Rossum8e248182001-08-12 05:17:56 +00002791static PyObject *
2792object_repr(PyObject *self)
2793{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002794 PyTypeObject *type;
2795 PyObject *mod, *name, *rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00002796
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002797 type = Py_TYPE(self);
2798 mod = type_module(type, NULL);
2799 if (mod == NULL)
2800 PyErr_Clear();
2801 else if (!PyUnicode_Check(mod)) {
2802 Py_DECREF(mod);
2803 mod = NULL;
2804 }
2805 name = type_name(type, NULL);
2806 if (name == NULL)
2807 return NULL;
2808 if (mod != NULL && PyUnicode_CompareWithASCIIString(mod, "builtins"))
2809 rtn = PyUnicode_FromFormat("<%U.%U object at %p>", mod, name, self);
2810 else
2811 rtn = PyUnicode_FromFormat("<%s object at %p>",
2812 type->tp_name, self);
2813 Py_XDECREF(mod);
2814 Py_DECREF(name);
2815 return rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00002816}
2817
Guido van Rossumb8f63662001-08-15 23:57:02 +00002818static PyObject *
2819object_str(PyObject *self)
2820{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002821 unaryfunc f;
Guido van Rossumb8f63662001-08-15 23:57:02 +00002822
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002823 f = Py_TYPE(self)->tp_repr;
2824 if (f == NULL)
2825 f = object_repr;
2826 return f(self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002827}
2828
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002829static PyObject *
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002830object_richcompare(PyObject *self, PyObject *other, int op)
2831{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002832 PyObject *res;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002833
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002834 switch (op) {
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002835
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002836 case Py_EQ:
2837 /* Return NotImplemented instead of False, so if two
2838 objects are compared, both get a chance at the
2839 comparison. See issue #1393. */
2840 res = (self == other) ? Py_True : Py_NotImplemented;
2841 Py_INCREF(res);
2842 break;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002843
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002844 case Py_NE:
2845 /* By default, != returns the opposite of ==,
2846 unless the latter returns NotImplemented. */
2847 res = PyObject_RichCompare(self, other, Py_EQ);
2848 if (res != NULL && res != Py_NotImplemented) {
2849 int ok = PyObject_IsTrue(res);
2850 Py_DECREF(res);
2851 if (ok < 0)
2852 res = NULL;
2853 else {
2854 if (ok)
2855 res = Py_False;
2856 else
2857 res = Py_True;
2858 Py_INCREF(res);
2859 }
2860 }
2861 break;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002862
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002863 default:
2864 res = Py_NotImplemented;
2865 Py_INCREF(res);
2866 break;
2867 }
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002868
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002869 return res;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002870}
2871
2872static PyObject *
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002873object_get_class(PyObject *self, void *closure)
2874{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002875 Py_INCREF(Py_TYPE(self));
2876 return (PyObject *)(Py_TYPE(self));
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002877}
2878
2879static int
2880equiv_structs(PyTypeObject *a, PyTypeObject *b)
2881{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002882 return a == b ||
2883 (a != NULL &&
2884 b != NULL &&
2885 a->tp_basicsize == b->tp_basicsize &&
2886 a->tp_itemsize == b->tp_itemsize &&
2887 a->tp_dictoffset == b->tp_dictoffset &&
2888 a->tp_weaklistoffset == b->tp_weaklistoffset &&
2889 ((a->tp_flags & Py_TPFLAGS_HAVE_GC) ==
2890 (b->tp_flags & Py_TPFLAGS_HAVE_GC)));
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002891}
2892
2893static int
2894same_slots_added(PyTypeObject *a, PyTypeObject *b)
2895{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002896 PyTypeObject *base = a->tp_base;
2897 Py_ssize_t size;
2898 PyObject *slots_a, *slots_b;
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002899
Benjamin Petersonacd17592011-01-17 19:36:44 +00002900 assert(base == b->tp_base);
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002901 size = base->tp_basicsize;
2902 if (a->tp_dictoffset == size && b->tp_dictoffset == size)
2903 size += sizeof(PyObject *);
2904 if (a->tp_weaklistoffset == size && b->tp_weaklistoffset == size)
2905 size += sizeof(PyObject *);
Guido van Rossumd8faa362007-04-27 19:54:29 +00002906
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002907 /* Check slots compliance */
2908 slots_a = ((PyHeapTypeObject *)a)->ht_slots;
2909 slots_b = ((PyHeapTypeObject *)b)->ht_slots;
2910 if (slots_a && slots_b) {
2911 if (PyObject_RichCompareBool(slots_a, slots_b, Py_EQ) != 1)
2912 return 0;
2913 size += sizeof(PyObject *) * PyTuple_GET_SIZE(slots_a);
2914 }
2915 return size == a->tp_basicsize && size == b->tp_basicsize;
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002916}
2917
2918static int
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002919compatible_for_assignment(PyTypeObject* oldto, PyTypeObject* newto, char* attr)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002920{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002921 PyTypeObject *newbase, *oldbase;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002922
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002923 if (newto->tp_dealloc != oldto->tp_dealloc ||
2924 newto->tp_free != oldto->tp_free)
2925 {
2926 PyErr_Format(PyExc_TypeError,
2927 "%s assignment: "
2928 "'%s' deallocator differs from '%s'",
2929 attr,
2930 newto->tp_name,
2931 oldto->tp_name);
2932 return 0;
2933 }
2934 newbase = newto;
2935 oldbase = oldto;
2936 while (equiv_structs(newbase, newbase->tp_base))
2937 newbase = newbase->tp_base;
2938 while (equiv_structs(oldbase, oldbase->tp_base))
2939 oldbase = oldbase->tp_base;
2940 if (newbase != oldbase &&
2941 (newbase->tp_base != oldbase->tp_base ||
2942 !same_slots_added(newbase, oldbase))) {
2943 PyErr_Format(PyExc_TypeError,
2944 "%s assignment: "
2945 "'%s' object layout differs from '%s'",
2946 attr,
2947 newto->tp_name,
2948 oldto->tp_name);
2949 return 0;
2950 }
Tim Petersea7f75d2002-12-07 21:39:16 +00002951
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002952 return 1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002953}
2954
2955static int
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002956object_set_class(PyObject *self, PyObject *value, void *closure)
2957{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002958 PyTypeObject *oldto = Py_TYPE(self);
2959 PyTypeObject *newto;
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002960
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002961 if (value == NULL) {
2962 PyErr_SetString(PyExc_TypeError,
2963 "can't delete __class__ attribute");
2964 return -1;
2965 }
2966 if (!PyType_Check(value)) {
2967 PyErr_Format(PyExc_TypeError,
2968 "__class__ must be set to new-style class, not '%s' object",
2969 Py_TYPE(value)->tp_name);
2970 return -1;
2971 }
2972 newto = (PyTypeObject *)value;
2973 if (!(newto->tp_flags & Py_TPFLAGS_HEAPTYPE) ||
2974 !(oldto->tp_flags & Py_TPFLAGS_HEAPTYPE))
2975 {
2976 PyErr_Format(PyExc_TypeError,
2977 "__class__ assignment: only for heap types");
2978 return -1;
2979 }
2980 if (compatible_for_assignment(newto, oldto, "__class__")) {
2981 Py_INCREF(newto);
2982 Py_TYPE(self) = newto;
2983 Py_DECREF(oldto);
2984 return 0;
2985 }
2986 else {
2987 return -1;
2988 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002989}
2990
2991static PyGetSetDef object_getsets[] = {
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002992 {"__class__", object_get_class, object_set_class,
2993 PyDoc_STR("the object's class")},
2994 {0}
Tim Peters6d6c1a32001-08-02 04:15:00 +00002995};
2996
Guido van Rossumc53f0092003-02-18 22:05:12 +00002997
Guido van Rossum036f9992003-02-21 22:02:54 +00002998/* Stuff to implement __reduce_ex__ for pickle protocols >= 2.
Alexandre Vassalottif7fa63d2008-05-11 08:55:36 +00002999 We fall back to helpers in copyreg for:
Guido van Rossum036f9992003-02-21 22:02:54 +00003000 - pickle protocols < 2
3001 - calculating the list of slot names (done only once per class)
3002 - the __newobj__ function (which is used as a token but never called)
3003*/
3004
3005static PyObject *
Alexandre Vassalottif7fa63d2008-05-11 08:55:36 +00003006import_copyreg(void)
Guido van Rossum036f9992003-02-21 22:02:54 +00003007{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003008 static PyObject *copyreg_str;
Guido van Rossum3926a632001-09-25 16:25:58 +00003009
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003010 if (!copyreg_str) {
3011 copyreg_str = PyUnicode_InternFromString("copyreg");
3012 if (copyreg_str == NULL)
3013 return NULL;
3014 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003015
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003016 return PyImport_Import(copyreg_str);
Guido van Rossum036f9992003-02-21 22:02:54 +00003017}
3018
3019static PyObject *
3020slotnames(PyObject *cls)
3021{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003022 PyObject *clsdict;
3023 PyObject *copyreg;
3024 PyObject *slotnames;
Guido van Rossum036f9992003-02-21 22:02:54 +00003025
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003026 if (!PyType_Check(cls)) {
3027 Py_INCREF(Py_None);
3028 return Py_None;
3029 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003030
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003031 clsdict = ((PyTypeObject *)cls)->tp_dict;
3032 slotnames = PyDict_GetItemString(clsdict, "__slotnames__");
3033 if (slotnames != NULL && PyList_Check(slotnames)) {
3034 Py_INCREF(slotnames);
3035 return slotnames;
3036 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003037
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003038 copyreg = import_copyreg();
3039 if (copyreg == NULL)
3040 return NULL;
Guido van Rossum036f9992003-02-21 22:02:54 +00003041
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003042 slotnames = PyObject_CallMethod(copyreg, "_slotnames", "O", cls);
3043 Py_DECREF(copyreg);
3044 if (slotnames != NULL &&
3045 slotnames != Py_None &&
3046 !PyList_Check(slotnames))
3047 {
3048 PyErr_SetString(PyExc_TypeError,
3049 "copyreg._slotnames didn't return a list or None");
3050 Py_DECREF(slotnames);
3051 slotnames = NULL;
3052 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003053
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003054 return slotnames;
Guido van Rossum036f9992003-02-21 22:02:54 +00003055}
3056
3057static PyObject *
3058reduce_2(PyObject *obj)
3059{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003060 PyObject *cls, *getnewargs;
3061 PyObject *args = NULL, *args2 = NULL;
3062 PyObject *getstate = NULL, *state = NULL, *names = NULL;
3063 PyObject *slots = NULL, *listitems = NULL, *dictitems = NULL;
3064 PyObject *copyreg = NULL, *newobj = NULL, *res = NULL;
3065 Py_ssize_t i, n;
Guido van Rossum036f9992003-02-21 22:02:54 +00003066
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003067 cls = PyObject_GetAttrString(obj, "__class__");
3068 if (cls == NULL)
3069 return NULL;
Guido van Rossum036f9992003-02-21 22:02:54 +00003070
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003071 getnewargs = PyObject_GetAttrString(obj, "__getnewargs__");
3072 if (getnewargs != NULL) {
3073 args = PyObject_CallObject(getnewargs, NULL);
3074 Py_DECREF(getnewargs);
3075 if (args != NULL && !PyTuple_Check(args)) {
3076 PyErr_Format(PyExc_TypeError,
3077 "__getnewargs__ should return a tuple, "
3078 "not '%.200s'", Py_TYPE(args)->tp_name);
3079 goto end;
3080 }
3081 }
3082 else {
3083 PyErr_Clear();
3084 args = PyTuple_New(0);
3085 }
3086 if (args == NULL)
3087 goto end;
Guido van Rossum036f9992003-02-21 22:02:54 +00003088
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003089 getstate = PyObject_GetAttrString(obj, "__getstate__");
3090 if (getstate != NULL) {
3091 state = PyObject_CallObject(getstate, NULL);
3092 Py_DECREF(getstate);
3093 if (state == NULL)
3094 goto end;
3095 }
3096 else {
3097 PyErr_Clear();
3098 state = PyObject_GetAttrString(obj, "__dict__");
3099 if (state == NULL) {
3100 PyErr_Clear();
3101 state = Py_None;
3102 Py_INCREF(state);
3103 }
3104 names = slotnames(cls);
3105 if (names == NULL)
3106 goto end;
3107 if (names != Py_None) {
3108 assert(PyList_Check(names));
3109 slots = PyDict_New();
3110 if (slots == NULL)
3111 goto end;
3112 n = 0;
3113 /* Can't pre-compute the list size; the list
3114 is stored on the class so accessible to other
3115 threads, which may be run by DECREF */
3116 for (i = 0; i < PyList_GET_SIZE(names); i++) {
3117 PyObject *name, *value;
3118 name = PyList_GET_ITEM(names, i);
3119 value = PyObject_GetAttr(obj, name);
3120 if (value == NULL)
3121 PyErr_Clear();
3122 else {
3123 int err = PyDict_SetItem(slots, name,
3124 value);
3125 Py_DECREF(value);
3126 if (err)
3127 goto end;
3128 n++;
3129 }
3130 }
3131 if (n) {
3132 state = Py_BuildValue("(NO)", state, slots);
3133 if (state == NULL)
3134 goto end;
3135 }
3136 }
3137 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003138
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003139 if (!PyList_Check(obj)) {
3140 listitems = Py_None;
3141 Py_INCREF(listitems);
3142 }
3143 else {
3144 listitems = PyObject_GetIter(obj);
3145 if (listitems == NULL)
3146 goto end;
3147 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003148
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003149 if (!PyDict_Check(obj)) {
3150 dictitems = Py_None;
3151 Py_INCREF(dictitems);
3152 }
3153 else {
3154 PyObject *items = PyObject_CallMethod(obj, "items", "");
3155 if (items == NULL)
3156 goto end;
3157 dictitems = PyObject_GetIter(items);
3158 Py_DECREF(items);
3159 if (dictitems == NULL)
3160 goto end;
3161 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003162
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003163 copyreg = import_copyreg();
3164 if (copyreg == NULL)
3165 goto end;
3166 newobj = PyObject_GetAttrString(copyreg, "__newobj__");
3167 if (newobj == NULL)
3168 goto end;
Guido van Rossum036f9992003-02-21 22:02:54 +00003169
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003170 n = PyTuple_GET_SIZE(args);
3171 args2 = PyTuple_New(n+1);
3172 if (args2 == NULL)
3173 goto end;
3174 PyTuple_SET_ITEM(args2, 0, cls);
3175 cls = NULL;
3176 for (i = 0; i < n; i++) {
3177 PyObject *v = PyTuple_GET_ITEM(args, i);
3178 Py_INCREF(v);
3179 PyTuple_SET_ITEM(args2, i+1, v);
3180 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003181
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003182 res = PyTuple_Pack(5, newobj, args2, state, listitems, dictitems);
Guido van Rossum036f9992003-02-21 22:02:54 +00003183
3184 end:
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003185 Py_XDECREF(cls);
3186 Py_XDECREF(args);
3187 Py_XDECREF(args2);
3188 Py_XDECREF(slots);
3189 Py_XDECREF(state);
3190 Py_XDECREF(names);
3191 Py_XDECREF(listitems);
3192 Py_XDECREF(dictitems);
3193 Py_XDECREF(copyreg);
3194 Py_XDECREF(newobj);
3195 return res;
Guido van Rossum036f9992003-02-21 22:02:54 +00003196}
3197
Guido van Rossumd8faa362007-04-27 19:54:29 +00003198/*
3199 * There were two problems when object.__reduce__ and object.__reduce_ex__
3200 * were implemented in the same function:
3201 * - trying to pickle an object with a custom __reduce__ method that
3202 * fell back to object.__reduce__ in certain circumstances led to
3203 * infinite recursion at Python level and eventual RuntimeError.
3204 * - Pickling objects that lied about their type by overwriting the
3205 * __class__ descriptor could lead to infinite recursion at C level
3206 * and eventual segfault.
3207 *
3208 * Because of backwards compatibility, the two methods still have to
3209 * behave in the same way, even if this is not required by the pickle
3210 * protocol. This common functionality was moved to the _common_reduce
3211 * function.
3212 */
3213static PyObject *
3214_common_reduce(PyObject *self, int proto)
3215{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003216 PyObject *copyreg, *res;
Guido van Rossumd8faa362007-04-27 19:54:29 +00003217
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003218 if (proto >= 2)
3219 return reduce_2(self);
Guido van Rossumd8faa362007-04-27 19:54:29 +00003220
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003221 copyreg = import_copyreg();
3222 if (!copyreg)
3223 return NULL;
Guido van Rossumd8faa362007-04-27 19:54:29 +00003224
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003225 res = PyEval_CallMethod(copyreg, "_reduce_ex", "(Oi)", self, proto);
3226 Py_DECREF(copyreg);
Guido van Rossumd8faa362007-04-27 19:54:29 +00003227
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003228 return res;
Guido van Rossumd8faa362007-04-27 19:54:29 +00003229}
3230
3231static PyObject *
3232object_reduce(PyObject *self, PyObject *args)
3233{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003234 int proto = 0;
Guido van Rossumd8faa362007-04-27 19:54:29 +00003235
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003236 if (!PyArg_ParseTuple(args, "|i:__reduce__", &proto))
3237 return NULL;
Guido van Rossumd8faa362007-04-27 19:54:29 +00003238
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003239 return _common_reduce(self, proto);
Guido van Rossumd8faa362007-04-27 19:54:29 +00003240}
3241
Guido van Rossum036f9992003-02-21 22:02:54 +00003242static PyObject *
3243object_reduce_ex(PyObject *self, PyObject *args)
3244{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003245 PyObject *reduce, *res;
3246 int proto = 0;
Guido van Rossum036f9992003-02-21 22:02:54 +00003247
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003248 if (!PyArg_ParseTuple(args, "|i:__reduce_ex__", &proto))
3249 return NULL;
Guido van Rossum036f9992003-02-21 22:02:54 +00003250
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003251 reduce = PyObject_GetAttrString(self, "__reduce__");
3252 if (reduce == NULL)
3253 PyErr_Clear();
3254 else {
3255 PyObject *cls, *clsreduce, *objreduce;
3256 int override;
3257 cls = PyObject_GetAttrString(self, "__class__");
3258 if (cls == NULL) {
3259 Py_DECREF(reduce);
3260 return NULL;
3261 }
3262 clsreduce = PyObject_GetAttrString(cls, "__reduce__");
3263 Py_DECREF(cls);
3264 if (clsreduce == NULL) {
3265 Py_DECREF(reduce);
3266 return NULL;
3267 }
3268 objreduce = PyDict_GetItemString(PyBaseObject_Type.tp_dict,
3269 "__reduce__");
3270 override = (clsreduce != objreduce);
3271 Py_DECREF(clsreduce);
3272 if (override) {
3273 res = PyObject_CallObject(reduce, NULL);
3274 Py_DECREF(reduce);
3275 return res;
3276 }
3277 else
3278 Py_DECREF(reduce);
3279 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003280
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003281 return _common_reduce(self, proto);
Guido van Rossum3926a632001-09-25 16:25:58 +00003282}
3283
Christian Heimes9e7f1d22008-02-28 12:27:11 +00003284static PyObject *
3285object_subclasshook(PyObject *cls, PyObject *args)
3286{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003287 Py_INCREF(Py_NotImplemented);
3288 return Py_NotImplemented;
Christian Heimes9e7f1d22008-02-28 12:27:11 +00003289}
3290
3291PyDoc_STRVAR(object_subclasshook_doc,
3292"Abstract classes can override this to customize issubclass().\n"
3293"\n"
3294"This is invoked early on by abc.ABCMeta.__subclasscheck__().\n"
3295"It should return True, False or NotImplemented. If it returns\n"
3296"NotImplemented, the normal algorithm is used. Otherwise, it\n"
3297"overrides the normal algorithm (and the outcome is cached).\n");
Eric Smith8c663262007-08-25 02:26:07 +00003298
3299/*
3300 from PEP 3101, this code implements:
3301
3302 class object:
3303 def __format__(self, format_spec):
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003304 return format(str(self), format_spec)
Eric Smith8c663262007-08-25 02:26:07 +00003305*/
3306static PyObject *
3307object_format(PyObject *self, PyObject *args)
3308{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003309 PyObject *format_spec;
3310 PyObject *self_as_str = NULL;
3311 PyObject *result = NULL;
3312 PyObject *format_meth = NULL;
Eric Smith8c663262007-08-25 02:26:07 +00003313
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003314 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
3315 return NULL;
Eric Smith8c663262007-08-25 02:26:07 +00003316
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003317 self_as_str = PyObject_Str(self);
3318 if (self_as_str != NULL) {
3319 /* find the format function */
3320 format_meth = PyObject_GetAttrString(self_as_str, "__format__");
3321 if (format_meth != NULL) {
3322 /* and call it */
3323 result = PyObject_CallFunctionObjArgs(format_meth, format_spec, NULL);
Eric Smith8c663262007-08-25 02:26:07 +00003324 }
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003325 }
Eric Smith8c663262007-08-25 02:26:07 +00003326
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003327 Py_XDECREF(self_as_str);
3328 Py_XDECREF(format_meth);
Eric Smith8c663262007-08-25 02:26:07 +00003329
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003330 return result;
Eric Smith8c663262007-08-25 02:26:07 +00003331}
3332
Martin v. Löwis00709aa2008-06-04 14:18:43 +00003333static PyObject *
3334object_sizeof(PyObject *self, PyObject *args)
3335{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003336 Py_ssize_t res, isize;
Martin v. Löwis00709aa2008-06-04 14:18:43 +00003337
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003338 res = 0;
3339 isize = self->ob_type->tp_itemsize;
3340 if (isize > 0)
3341 res = Py_SIZE(self->ob_type) * isize;
3342 res += self->ob_type->tp_basicsize;
Martin v. Löwis00709aa2008-06-04 14:18:43 +00003343
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003344 return PyLong_FromSsize_t(res);
Martin v. Löwis00709aa2008-06-04 14:18:43 +00003345}
3346
Guido van Rossum3926a632001-09-25 16:25:58 +00003347static PyMethodDef object_methods[] = {
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003348 {"__reduce_ex__", object_reduce_ex, METH_VARARGS,
3349 PyDoc_STR("helper for pickle")},
3350 {"__reduce__", object_reduce, METH_VARARGS,
3351 PyDoc_STR("helper for pickle")},
3352 {"__subclasshook__", object_subclasshook, METH_CLASS | METH_VARARGS,
3353 object_subclasshook_doc},
3354 {"__format__", object_format, METH_VARARGS,
3355 PyDoc_STR("default object formatter")},
3356 {"__sizeof__", object_sizeof, METH_NOARGS,
3357 PyDoc_STR("__sizeof__() -> size of object in memory, in bytes")},
3358 {0}
Guido van Rossum3926a632001-09-25 16:25:58 +00003359};
3360
Guido van Rossum036f9992003-02-21 22:02:54 +00003361
Tim Peters6d6c1a32001-08-02 04:15:00 +00003362PyTypeObject PyBaseObject_Type = {
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003363 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3364 "object", /* tp_name */
3365 sizeof(PyObject), /* tp_basicsize */
3366 0, /* tp_itemsize */
3367 object_dealloc, /* tp_dealloc */
3368 0, /* tp_print */
3369 0, /* tp_getattr */
3370 0, /* tp_setattr */
3371 0, /* tp_reserved */
3372 object_repr, /* tp_repr */
3373 0, /* tp_as_number */
3374 0, /* tp_as_sequence */
3375 0, /* tp_as_mapping */
3376 (hashfunc)_Py_HashPointer, /* tp_hash */
3377 0, /* tp_call */
3378 object_str, /* tp_str */
3379 PyObject_GenericGetAttr, /* tp_getattro */
3380 PyObject_GenericSetAttr, /* tp_setattro */
3381 0, /* tp_as_buffer */
3382 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
3383 PyDoc_STR("The most base type"), /* tp_doc */
3384 0, /* tp_traverse */
3385 0, /* tp_clear */
3386 object_richcompare, /* tp_richcompare */
3387 0, /* tp_weaklistoffset */
3388 0, /* tp_iter */
3389 0, /* tp_iternext */
3390 object_methods, /* tp_methods */
3391 0, /* tp_members */
3392 object_getsets, /* tp_getset */
3393 0, /* tp_base */
3394 0, /* tp_dict */
3395 0, /* tp_descr_get */
3396 0, /* tp_descr_set */
3397 0, /* tp_dictoffset */
3398 object_init, /* tp_init */
3399 PyType_GenericAlloc, /* tp_alloc */
3400 object_new, /* tp_new */
3401 PyObject_Del, /* tp_free */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003402};
3403
3404
Guido van Rossum50e9fb92006-08-17 05:42:55 +00003405/* Add the methods from tp_methods to the __dict__ in a type object */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003406
3407static int
3408add_methods(PyTypeObject *type, PyMethodDef *meth)
3409{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003410 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003411
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003412 for (; meth->ml_name != NULL; meth++) {
3413 PyObject *descr;
3414 if (PyDict_GetItemString(dict, meth->ml_name) &&
3415 !(meth->ml_flags & METH_COEXIST))
3416 continue;
3417 if (meth->ml_flags & METH_CLASS) {
3418 if (meth->ml_flags & METH_STATIC) {
3419 PyErr_SetString(PyExc_ValueError,
3420 "method cannot be both class and static");
3421 return -1;
3422 }
3423 descr = PyDescr_NewClassMethod(type, meth);
3424 }
3425 else if (meth->ml_flags & METH_STATIC) {
3426 PyObject *cfunc = PyCFunction_New(meth, NULL);
3427 if (cfunc == NULL)
3428 return -1;
3429 descr = PyStaticMethod_New(cfunc);
3430 Py_DECREF(cfunc);
3431 }
3432 else {
3433 descr = PyDescr_NewMethod(type, meth);
3434 }
3435 if (descr == NULL)
3436 return -1;
3437 if (PyDict_SetItemString(dict, meth->ml_name, descr) < 0)
3438 return -1;
3439 Py_DECREF(descr);
3440 }
3441 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003442}
3443
3444static int
Guido van Rossum6f799372001-09-20 20:46:19 +00003445add_members(PyTypeObject *type, PyMemberDef *memb)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003446{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003447 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003448
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003449 for (; memb->name != NULL; memb++) {
3450 PyObject *descr;
3451 if (PyDict_GetItemString(dict, memb->name))
3452 continue;
3453 descr = PyDescr_NewMember(type, memb);
3454 if (descr == NULL)
3455 return -1;
3456 if (PyDict_SetItemString(dict, memb->name, descr) < 0)
3457 return -1;
3458 Py_DECREF(descr);
3459 }
3460 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003461}
3462
3463static int
Guido van Rossum32d34c82001-09-20 21:45:26 +00003464add_getset(PyTypeObject *type, PyGetSetDef *gsp)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003465{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003466 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003467
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003468 for (; gsp->name != NULL; gsp++) {
3469 PyObject *descr;
3470 if (PyDict_GetItemString(dict, gsp->name))
3471 continue;
3472 descr = PyDescr_NewGetSet(type, gsp);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003473
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003474 if (descr == NULL)
3475 return -1;
3476 if (PyDict_SetItemString(dict, gsp->name, descr) < 0)
3477 return -1;
3478 Py_DECREF(descr);
3479 }
3480 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003481}
3482
Guido van Rossum13d52f02001-08-10 21:24:08 +00003483static void
3484inherit_special(PyTypeObject *type, PyTypeObject *base)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003485{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003486 Py_ssize_t oldsize, newsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003487
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003488 /* Copying basicsize is connected to the GC flags */
3489 oldsize = base->tp_basicsize;
3490 newsize = type->tp_basicsize ? type->tp_basicsize : oldsize;
3491 if (!(type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
3492 (base->tp_flags & Py_TPFLAGS_HAVE_GC) &&
3493 (!type->tp_traverse && !type->tp_clear)) {
3494 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
3495 if (type->tp_traverse == NULL)
3496 type->tp_traverse = base->tp_traverse;
3497 if (type->tp_clear == NULL)
3498 type->tp_clear = base->tp_clear;
3499 }
3500 {
3501 /* The condition below could use some explanation.
3502 It appears that tp_new is not inherited for static types
3503 whose base class is 'object'; this seems to be a precaution
3504 so that old extension types don't suddenly become
3505 callable (object.__new__ wouldn't insure the invariants
3506 that the extension type's own factory function ensures).
3507 Heap types, of course, are under our control, so they do
3508 inherit tp_new; static extension types that specify some
3509 other built-in type as the default are considered
3510 new-style-aware so they also inherit object.__new__. */
3511 if (base != &PyBaseObject_Type ||
3512 (type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
3513 if (type->tp_new == NULL)
3514 type->tp_new = base->tp_new;
3515 }
3516 }
3517 type->tp_basicsize = newsize;
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00003518
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003519 /* Copy other non-function slots */
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00003520
3521#undef COPYVAL
3522#define COPYVAL(SLOT) \
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003523 if (type->SLOT == 0) type->SLOT = base->SLOT
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00003524
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003525 COPYVAL(tp_itemsize);
3526 COPYVAL(tp_weaklistoffset);
3527 COPYVAL(tp_dictoffset);
Thomas Wouters27d517b2007-02-25 20:39:11 +00003528
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003529 /* Setup fast subclass flags */
3530 if (PyType_IsSubtype(base, (PyTypeObject*)PyExc_BaseException))
3531 type->tp_flags |= Py_TPFLAGS_BASE_EXC_SUBCLASS;
3532 else if (PyType_IsSubtype(base, &PyType_Type))
3533 type->tp_flags |= Py_TPFLAGS_TYPE_SUBCLASS;
3534 else if (PyType_IsSubtype(base, &PyLong_Type))
3535 type->tp_flags |= Py_TPFLAGS_LONG_SUBCLASS;
3536 else if (PyType_IsSubtype(base, &PyBytes_Type))
3537 type->tp_flags |= Py_TPFLAGS_BYTES_SUBCLASS;
3538 else if (PyType_IsSubtype(base, &PyUnicode_Type))
3539 type->tp_flags |= Py_TPFLAGS_UNICODE_SUBCLASS;
3540 else if (PyType_IsSubtype(base, &PyTuple_Type))
3541 type->tp_flags |= Py_TPFLAGS_TUPLE_SUBCLASS;
3542 else if (PyType_IsSubtype(base, &PyList_Type))
3543 type->tp_flags |= Py_TPFLAGS_LIST_SUBCLASS;
3544 else if (PyType_IsSubtype(base, &PyDict_Type))
3545 type->tp_flags |= Py_TPFLAGS_DICT_SUBCLASS;
Guido van Rossum13d52f02001-08-10 21:24:08 +00003546}
3547
Guido van Rossumf5243f02008-01-01 04:06:48 +00003548static char *hash_name_op[] = {
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003549 "__eq__",
3550 "__hash__",
3551 NULL
Guido van Rossum38938152006-08-21 23:36:26 +00003552};
3553
3554static int
Guido van Rossumf5243f02008-01-01 04:06:48 +00003555overrides_hash(PyTypeObject *type)
Guido van Rossum38938152006-08-21 23:36:26 +00003556{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003557 char **p;
3558 PyObject *dict = type->tp_dict;
Guido van Rossum38938152006-08-21 23:36:26 +00003559
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003560 assert(dict != NULL);
3561 for (p = hash_name_op; *p; p++) {
3562 if (PyDict_GetItemString(dict, *p) != NULL)
3563 return 1;
3564 }
3565 return 0;
Guido van Rossum38938152006-08-21 23:36:26 +00003566}
3567
Guido van Rossum13d52f02001-08-10 21:24:08 +00003568static void
3569inherit_slots(PyTypeObject *type, PyTypeObject *base)
3570{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003571 PyTypeObject *basebase;
Guido van Rossum13d52f02001-08-10 21:24:08 +00003572
3573#undef SLOTDEFINED
Tim Peters6d6c1a32001-08-02 04:15:00 +00003574#undef COPYSLOT
3575#undef COPYNUM
3576#undef COPYSEQ
3577#undef COPYMAP
Guido van Rossum5af588b2001-10-12 14:13:21 +00003578#undef COPYBUF
Guido van Rossum13d52f02001-08-10 21:24:08 +00003579
3580#define SLOTDEFINED(SLOT) \
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003581 (base->SLOT != 0 && \
3582 (basebase == NULL || base->SLOT != basebase->SLOT))
Guido van Rossum13d52f02001-08-10 21:24:08 +00003583
Tim Peters6d6c1a32001-08-02 04:15:00 +00003584#define COPYSLOT(SLOT) \
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003585 if (!type->SLOT && SLOTDEFINED(SLOT)) type->SLOT = base->SLOT
Tim Peters6d6c1a32001-08-02 04:15:00 +00003586
3587#define COPYNUM(SLOT) COPYSLOT(tp_as_number->SLOT)
3588#define COPYSEQ(SLOT) COPYSLOT(tp_as_sequence->SLOT)
3589#define COPYMAP(SLOT) COPYSLOT(tp_as_mapping->SLOT)
Tim Petersfc57ccb2001-10-12 02:38:24 +00003590#define COPYBUF(SLOT) COPYSLOT(tp_as_buffer->SLOT)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003591
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003592 /* This won't inherit indirect slots (from tp_as_number etc.)
3593 if type doesn't provide the space. */
Guido van Rossum13d52f02001-08-10 21:24:08 +00003594
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003595 if (type->tp_as_number != NULL && base->tp_as_number != NULL) {
3596 basebase = base->tp_base;
3597 if (basebase->tp_as_number == NULL)
3598 basebase = NULL;
3599 COPYNUM(nb_add);
3600 COPYNUM(nb_subtract);
3601 COPYNUM(nb_multiply);
3602 COPYNUM(nb_remainder);
3603 COPYNUM(nb_divmod);
3604 COPYNUM(nb_power);
3605 COPYNUM(nb_negative);
3606 COPYNUM(nb_positive);
3607 COPYNUM(nb_absolute);
3608 COPYNUM(nb_bool);
3609 COPYNUM(nb_invert);
3610 COPYNUM(nb_lshift);
3611 COPYNUM(nb_rshift);
3612 COPYNUM(nb_and);
3613 COPYNUM(nb_xor);
3614 COPYNUM(nb_or);
3615 COPYNUM(nb_int);
3616 COPYNUM(nb_float);
3617 COPYNUM(nb_inplace_add);
3618 COPYNUM(nb_inplace_subtract);
3619 COPYNUM(nb_inplace_multiply);
3620 COPYNUM(nb_inplace_remainder);
3621 COPYNUM(nb_inplace_power);
3622 COPYNUM(nb_inplace_lshift);
3623 COPYNUM(nb_inplace_rshift);
3624 COPYNUM(nb_inplace_and);
3625 COPYNUM(nb_inplace_xor);
3626 COPYNUM(nb_inplace_or);
3627 COPYNUM(nb_true_divide);
3628 COPYNUM(nb_floor_divide);
3629 COPYNUM(nb_inplace_true_divide);
3630 COPYNUM(nb_inplace_floor_divide);
3631 COPYNUM(nb_index);
3632 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003633
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003634 if (type->tp_as_sequence != NULL && base->tp_as_sequence != NULL) {
3635 basebase = base->tp_base;
3636 if (basebase->tp_as_sequence == NULL)
3637 basebase = NULL;
3638 COPYSEQ(sq_length);
3639 COPYSEQ(sq_concat);
3640 COPYSEQ(sq_repeat);
3641 COPYSEQ(sq_item);
3642 COPYSEQ(sq_ass_item);
3643 COPYSEQ(sq_contains);
3644 COPYSEQ(sq_inplace_concat);
3645 COPYSEQ(sq_inplace_repeat);
3646 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003647
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003648 if (type->tp_as_mapping != NULL && base->tp_as_mapping != NULL) {
3649 basebase = base->tp_base;
3650 if (basebase->tp_as_mapping == NULL)
3651 basebase = NULL;
3652 COPYMAP(mp_length);
3653 COPYMAP(mp_subscript);
3654 COPYMAP(mp_ass_subscript);
3655 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003656
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003657 if (type->tp_as_buffer != NULL && base->tp_as_buffer != NULL) {
3658 basebase = base->tp_base;
3659 if (basebase->tp_as_buffer == NULL)
3660 basebase = NULL;
3661 COPYBUF(bf_getbuffer);
3662 COPYBUF(bf_releasebuffer);
3663 }
Tim Petersfc57ccb2001-10-12 02:38:24 +00003664
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003665 basebase = base->tp_base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003666
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003667 COPYSLOT(tp_dealloc);
3668 if (type->tp_getattr == NULL && type->tp_getattro == NULL) {
3669 type->tp_getattr = base->tp_getattr;
3670 type->tp_getattro = base->tp_getattro;
3671 }
3672 if (type->tp_setattr == NULL && type->tp_setattro == NULL) {
3673 type->tp_setattr = base->tp_setattr;
3674 type->tp_setattro = base->tp_setattro;
3675 }
3676 /* tp_reserved is ignored */
3677 COPYSLOT(tp_repr);
3678 /* tp_hash see tp_richcompare */
3679 COPYSLOT(tp_call);
3680 COPYSLOT(tp_str);
3681 {
3682 /* Copy comparison-related slots only when
3683 not overriding them anywhere */
3684 if (type->tp_richcompare == NULL &&
3685 type->tp_hash == NULL &&
3686 !overrides_hash(type))
3687 {
3688 type->tp_richcompare = base->tp_richcompare;
3689 type->tp_hash = base->tp_hash;
3690 }
3691 }
3692 {
3693 COPYSLOT(tp_iter);
3694 COPYSLOT(tp_iternext);
3695 }
3696 {
3697 COPYSLOT(tp_descr_get);
3698 COPYSLOT(tp_descr_set);
3699 COPYSLOT(tp_dictoffset);
3700 COPYSLOT(tp_init);
3701 COPYSLOT(tp_alloc);
3702 COPYSLOT(tp_is_gc);
3703 if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) ==
3704 (base->tp_flags & Py_TPFLAGS_HAVE_GC)) {
3705 /* They agree about gc. */
3706 COPYSLOT(tp_free);
3707 }
3708 else if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
3709 type->tp_free == NULL &&
3710 base->tp_free == PyObject_Free) {
3711 /* A bit of magic to plug in the correct default
3712 * tp_free function when a derived class adds gc,
3713 * didn't define tp_free, and the base uses the
3714 * default non-gc tp_free.
3715 */
3716 type->tp_free = PyObject_GC_Del;
3717 }
3718 /* else they didn't agree about gc, and there isn't something
3719 * obvious to be done -- the type is on its own.
3720 */
3721 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003722}
3723
Jeremy Hylton938ace62002-07-17 16:30:39 +00003724static int add_operators(PyTypeObject *);
Guido van Rossum13d52f02001-08-10 21:24:08 +00003725
Tim Peters6d6c1a32001-08-02 04:15:00 +00003726int
Guido van Rossum528b7eb2001-08-07 17:24:28 +00003727PyType_Ready(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003728{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003729 PyObject *dict, *bases;
3730 PyTypeObject *base;
3731 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003732
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003733 if (type->tp_flags & Py_TPFLAGS_READY) {
3734 assert(type->tp_dict != NULL);
3735 return 0;
3736 }
3737 assert((type->tp_flags & Py_TPFLAGS_READYING) == 0);
Guido van Rossumd614f972001-08-10 17:39:49 +00003738
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003739 type->tp_flags |= Py_TPFLAGS_READYING;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003740
Tim Peters36eb4df2003-03-23 03:33:13 +00003741#ifdef Py_TRACE_REFS
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003742 /* PyType_Ready is the closest thing we have to a choke point
3743 * for type objects, so is the best place I can think of to try
3744 * to get type objects into the doubly-linked list of all objects.
3745 * Still, not all type objects go thru PyType_Ready.
3746 */
3747 _Py_AddToAllObjects((PyObject *)type, 0);
Tim Peters36eb4df2003-03-23 03:33:13 +00003748#endif
3749
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003750 /* Initialize tp_base (defaults to BaseObject unless that's us) */
3751 base = type->tp_base;
3752 if (base == NULL && type != &PyBaseObject_Type) {
3753 base = type->tp_base = &PyBaseObject_Type;
3754 Py_INCREF(base);
3755 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003756
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003757 /* Now the only way base can still be NULL is if type is
3758 * &PyBaseObject_Type.
3759 */
Guido van Rossum692cdbc2006-03-10 02:04:28 +00003760
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003761 /* Initialize the base class */
3762 if (base != NULL && base->tp_dict == NULL) {
3763 if (PyType_Ready(base) < 0)
3764 goto error;
3765 }
Guido van Rossum323a9cf2002-08-14 17:26:30 +00003766
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003767 /* Initialize ob_type if NULL. This means extensions that want to be
3768 compilable separately on Windows can call PyType_Ready() instead of
3769 initializing the ob_type field of their type objects. */
3770 /* The test for base != NULL is really unnecessary, since base is only
3771 NULL when type is &PyBaseObject_Type, and we know its ob_type is
3772 not NULL (it's initialized to &PyType_Type). But coverity doesn't
3773 know that. */
3774 if (Py_TYPE(type) == NULL && base != NULL)
3775 Py_TYPE(type) = Py_TYPE(base);
Guido van Rossum0986d822002-04-08 01:38:42 +00003776
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003777 /* Initialize tp_bases */
3778 bases = type->tp_bases;
3779 if (bases == NULL) {
3780 if (base == NULL)
3781 bases = PyTuple_New(0);
3782 else
3783 bases = PyTuple_Pack(1, base);
3784 if (bases == NULL)
3785 goto error;
3786 type->tp_bases = bases;
3787 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003788
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003789 /* Initialize tp_dict */
3790 dict = type->tp_dict;
3791 if (dict == NULL) {
3792 dict = PyDict_New();
3793 if (dict == NULL)
3794 goto error;
3795 type->tp_dict = dict;
3796 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003797
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003798 /* Add type-specific descriptors to tp_dict */
3799 if (add_operators(type) < 0)
3800 goto error;
3801 if (type->tp_methods != NULL) {
3802 if (add_methods(type, type->tp_methods) < 0)
3803 goto error;
3804 }
3805 if (type->tp_members != NULL) {
3806 if (add_members(type, type->tp_members) < 0)
3807 goto error;
3808 }
3809 if (type->tp_getset != NULL) {
3810 if (add_getset(type, type->tp_getset) < 0)
3811 goto error;
3812 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003813
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003814 /* Calculate method resolution order */
3815 if (mro_internal(type) < 0) {
3816 goto error;
3817 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003818
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003819 /* Inherit special flags from dominant base */
3820 if (type->tp_base != NULL)
3821 inherit_special(type, type->tp_base);
Guido van Rossum13d52f02001-08-10 21:24:08 +00003822
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003823 /* Initialize tp_dict properly */
3824 bases = type->tp_mro;
3825 assert(bases != NULL);
3826 assert(PyTuple_Check(bases));
3827 n = PyTuple_GET_SIZE(bases);
3828 for (i = 1; i < n; i++) {
3829 PyObject *b = PyTuple_GET_ITEM(bases, i);
3830 if (PyType_Check(b))
3831 inherit_slots(type, (PyTypeObject *)b);
3832 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003833
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003834 /* Sanity check for tp_free. */
3835 if (PyType_IS_GC(type) && (type->tp_flags & Py_TPFLAGS_BASETYPE) &&
3836 (type->tp_free == NULL || type->tp_free == PyObject_Del)) {
3837 /* This base class needs to call tp_free, but doesn't have
3838 * one, or its tp_free is for non-gc'ed objects.
3839 */
3840 PyErr_Format(PyExc_TypeError, "type '%.100s' participates in "
3841 "gc and is a base type but has inappropriate "
3842 "tp_free slot",
3843 type->tp_name);
3844 goto error;
3845 }
Tim Peters3cfe7542003-05-21 21:29:48 +00003846
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003847 /* if the type dictionary doesn't contain a __doc__, set it from
3848 the tp_doc slot.
3849 */
3850 if (PyDict_GetItemString(type->tp_dict, "__doc__") == NULL) {
3851 if (type->tp_doc != NULL) {
3852 PyObject *doc = PyUnicode_FromString(type->tp_doc);
3853 if (doc == NULL)
3854 goto error;
3855 PyDict_SetItemString(type->tp_dict, "__doc__", doc);
3856 Py_DECREF(doc);
3857 } else {
3858 PyDict_SetItemString(type->tp_dict,
3859 "__doc__", Py_None);
3860 }
3861 }
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00003862
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003863 /* Hack for tp_hash and __hash__.
3864 If after all that, tp_hash is still NULL, and __hash__ is not in
3865 tp_dict, set tp_hash to PyObject_HashNotImplemented and
3866 tp_dict['__hash__'] equal to None.
3867 This signals that __hash__ is not inherited.
3868 */
3869 if (type->tp_hash == NULL) {
3870 if (PyDict_GetItemString(type->tp_dict, "__hash__") == NULL) {
3871 if (PyDict_SetItemString(type->tp_dict, "__hash__", Py_None) < 0)
3872 goto error;
3873 type->tp_hash = PyObject_HashNotImplemented;
3874 }
3875 }
Guido van Rossum38938152006-08-21 23:36:26 +00003876
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003877 /* Some more special stuff */
3878 base = type->tp_base;
3879 if (base != NULL) {
3880 if (type->tp_as_number == NULL)
3881 type->tp_as_number = base->tp_as_number;
3882 if (type->tp_as_sequence == NULL)
3883 type->tp_as_sequence = base->tp_as_sequence;
3884 if (type->tp_as_mapping == NULL)
3885 type->tp_as_mapping = base->tp_as_mapping;
3886 if (type->tp_as_buffer == NULL)
3887 type->tp_as_buffer = base->tp_as_buffer;
3888 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003889
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003890 /* Link into each base class's list of subclasses */
3891 bases = type->tp_bases;
3892 n = PyTuple_GET_SIZE(bases);
3893 for (i = 0; i < n; i++) {
3894 PyObject *b = PyTuple_GET_ITEM(bases, i);
3895 if (PyType_Check(b) &&
3896 add_subclass((PyTypeObject *)b, type) < 0)
3897 goto error;
3898 }
Guido van Rossum1c450732001-10-08 15:18:27 +00003899
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003900 /* Warn for a type that implements tp_compare (now known as
3901 tp_reserved) but not tp_richcompare. */
3902 if (type->tp_reserved && !type->tp_richcompare) {
3903 int error;
3904 char msg[240];
3905 PyOS_snprintf(msg, sizeof(msg),
3906 "Type %.100s defines tp_reserved (formerly "
3907 "tp_compare) but not tp_richcompare. "
3908 "Comparisons may not behave as intended.",
3909 type->tp_name);
3910 error = PyErr_WarnEx(PyExc_DeprecationWarning, msg, 1);
3911 if (error == -1)
3912 goto error;
3913 }
Mark Dickinson2a7d45b2009-02-08 11:02:10 +00003914
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003915 /* All done -- set the ready flag */
3916 assert(type->tp_dict != NULL);
3917 type->tp_flags =
3918 (type->tp_flags & ~Py_TPFLAGS_READYING) | Py_TPFLAGS_READY;
3919 return 0;
Guido van Rossumd614f972001-08-10 17:39:49 +00003920
3921 error:
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003922 type->tp_flags &= ~Py_TPFLAGS_READYING;
3923 return -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003924}
3925
Guido van Rossum1c450732001-10-08 15:18:27 +00003926static int
3927add_subclass(PyTypeObject *base, PyTypeObject *type)
3928{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003929 Py_ssize_t i;
3930 int result;
3931 PyObject *list, *ref, *newobj;
Guido van Rossum1c450732001-10-08 15:18:27 +00003932
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003933 list = base->tp_subclasses;
3934 if (list == NULL) {
3935 base->tp_subclasses = list = PyList_New(0);
3936 if (list == NULL)
3937 return -1;
3938 }
3939 assert(PyList_Check(list));
3940 newobj = PyWeakref_NewRef((PyObject *)type, NULL);
3941 i = PyList_GET_SIZE(list);
3942 while (--i >= 0) {
3943 ref = PyList_GET_ITEM(list, i);
3944 assert(PyWeakref_CheckRef(ref));
3945 if (PyWeakref_GET_OBJECT(ref) == Py_None)
3946 return PyList_SetItem(list, i, newobj);
3947 }
3948 result = PyList_Append(list, newobj);
3949 Py_DECREF(newobj);
3950 return result;
Guido van Rossum1c450732001-10-08 15:18:27 +00003951}
3952
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003953static void
3954remove_subclass(PyTypeObject *base, PyTypeObject *type)
3955{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003956 Py_ssize_t i;
3957 PyObject *list, *ref;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003958
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003959 list = base->tp_subclasses;
3960 if (list == NULL) {
3961 return;
3962 }
3963 assert(PyList_Check(list));
3964 i = PyList_GET_SIZE(list);
3965 while (--i >= 0) {
3966 ref = PyList_GET_ITEM(list, i);
3967 assert(PyWeakref_CheckRef(ref));
3968 if (PyWeakref_GET_OBJECT(ref) == (PyObject*)type) {
3969 /* this can't fail, right? */
3970 PySequence_DelItem(list, i);
3971 return;
3972 }
3973 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003974}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003975
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003976static int
3977check_num_args(PyObject *ob, int n)
3978{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003979 if (!PyTuple_CheckExact(ob)) {
3980 PyErr_SetString(PyExc_SystemError,
3981 "PyArg_UnpackTuple() argument list is not a tuple");
3982 return 0;
3983 }
3984 if (n == PyTuple_GET_SIZE(ob))
3985 return 1;
3986 PyErr_Format(
3987 PyExc_TypeError,
3988 "expected %d arguments, got %zd", n, PyTuple_GET_SIZE(ob));
3989 return 0;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003990}
3991
Tim Peters6d6c1a32001-08-02 04:15:00 +00003992/* Generic wrappers for overloadable 'operators' such as __getitem__ */
3993
3994/* There's a wrapper *function* for each distinct function typedef used
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003995 for type object slots (e.g. binaryfunc, ternaryfunc, etc.). There's a
Tim Peters6d6c1a32001-08-02 04:15:00 +00003996 wrapper *table* for each distinct operation (e.g. __len__, __add__).
3997 Most tables have only one entry; the tables for binary operators have two
3998 entries, one regular and one with reversed arguments. */
3999
4000static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00004001wrap_lenfunc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004002{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004003 lenfunc func = (lenfunc)wrapped;
4004 Py_ssize_t res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004005
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004006 if (!check_num_args(args, 0))
4007 return NULL;
4008 res = (*func)(self);
4009 if (res == -1 && PyErr_Occurred())
4010 return NULL;
4011 return PyLong_FromLong((long)res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004012}
4013
Tim Peters6d6c1a32001-08-02 04:15:00 +00004014static PyObject *
Raymond Hettingerf34f2642003-10-11 17:29:04 +00004015wrap_inquirypred(PyObject *self, PyObject *args, void *wrapped)
4016{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004017 inquiry func = (inquiry)wrapped;
4018 int res;
Raymond Hettingerf34f2642003-10-11 17:29:04 +00004019
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004020 if (!check_num_args(args, 0))
4021 return NULL;
4022 res = (*func)(self);
4023 if (res == -1 && PyErr_Occurred())
4024 return NULL;
4025 return PyBool_FromLong((long)res);
Raymond Hettingerf34f2642003-10-11 17:29:04 +00004026}
4027
4028static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00004029wrap_binaryfunc(PyObject *self, PyObject *args, void *wrapped)
4030{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004031 binaryfunc func = (binaryfunc)wrapped;
4032 PyObject *other;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004033
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004034 if (!check_num_args(args, 1))
4035 return NULL;
4036 other = PyTuple_GET_ITEM(args, 0);
4037 return (*func)(self, other);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004038}
4039
4040static PyObject *
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00004041wrap_binaryfunc_l(PyObject *self, PyObject *args, void *wrapped)
4042{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004043 binaryfunc func = (binaryfunc)wrapped;
4044 PyObject *other;
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00004045
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004046 if (!check_num_args(args, 1))
4047 return NULL;
4048 other = PyTuple_GET_ITEM(args, 0);
4049 return (*func)(self, other);
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00004050}
4051
4052static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00004053wrap_binaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
4054{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004055 binaryfunc func = (binaryfunc)wrapped;
4056 PyObject *other;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004057
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004058 if (!check_num_args(args, 1))
4059 return NULL;
4060 other = PyTuple_GET_ITEM(args, 0);
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004061 return (*func)(other, self);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004062}
4063
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004064static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00004065wrap_ternaryfunc(PyObject *self, PyObject *args, void *wrapped)
4066{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004067 ternaryfunc func = (ternaryfunc)wrapped;
4068 PyObject *other;
4069 PyObject *third = Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004070
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004071 /* Note: This wrapper only works for __pow__() */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004072
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004073 if (!PyArg_UnpackTuple(args, "", 1, 2, &other, &third))
4074 return NULL;
4075 return (*func)(self, other, third);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004076}
4077
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00004078static PyObject *
4079wrap_ternaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
4080{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004081 ternaryfunc func = (ternaryfunc)wrapped;
4082 PyObject *other;
4083 PyObject *third = Py_None;
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00004084
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004085 /* Note: This wrapper only works for __pow__() */
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00004086
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004087 if (!PyArg_UnpackTuple(args, "", 1, 2, &other, &third))
4088 return NULL;
4089 return (*func)(other, self, third);
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00004090}
4091
Tim Peters6d6c1a32001-08-02 04:15:00 +00004092static PyObject *
4093wrap_unaryfunc(PyObject *self, PyObject *args, void *wrapped)
4094{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004095 unaryfunc func = (unaryfunc)wrapped;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004096
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004097 if (!check_num_args(args, 0))
4098 return NULL;
4099 return (*func)(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004100}
4101
Tim Peters6d6c1a32001-08-02 04:15:00 +00004102static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004103wrap_indexargfunc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004104{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004105 ssizeargfunc func = (ssizeargfunc)wrapped;
4106 PyObject* o;
4107 Py_ssize_t i;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004108
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004109 if (!PyArg_UnpackTuple(args, "", 1, 1, &o))
4110 return NULL;
4111 i = PyNumber_AsSsize_t(o, PyExc_OverflowError);
4112 if (i == -1 && PyErr_Occurred())
4113 return NULL;
4114 return (*func)(self, i);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004115}
4116
Martin v. Löwis18e16552006-02-15 17:27:45 +00004117static Py_ssize_t
Guido van Rossum5d815f32001-08-17 21:57:47 +00004118getindex(PyObject *self, PyObject *arg)
4119{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004120 Py_ssize_t i;
Guido van Rossum5d815f32001-08-17 21:57:47 +00004121
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004122 i = PyNumber_AsSsize_t(arg, PyExc_OverflowError);
4123 if (i == -1 && PyErr_Occurred())
4124 return -1;
4125 if (i < 0) {
4126 PySequenceMethods *sq = Py_TYPE(self)->tp_as_sequence;
4127 if (sq && sq->sq_length) {
4128 Py_ssize_t n = (*sq->sq_length)(self);
4129 if (n < 0)
4130 return -1;
4131 i += n;
4132 }
4133 }
4134 return i;
Guido van Rossum5d815f32001-08-17 21:57:47 +00004135}
4136
4137static PyObject *
4138wrap_sq_item(PyObject *self, PyObject *args, void *wrapped)
4139{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004140 ssizeargfunc func = (ssizeargfunc)wrapped;
4141 PyObject *arg;
4142 Py_ssize_t i;
Guido van Rossum5d815f32001-08-17 21:57:47 +00004143
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004144 if (PyTuple_GET_SIZE(args) == 1) {
4145 arg = PyTuple_GET_ITEM(args, 0);
4146 i = getindex(self, arg);
4147 if (i == -1 && PyErr_Occurred())
4148 return NULL;
4149 return (*func)(self, i);
4150 }
4151 check_num_args(args, 1);
4152 assert(PyErr_Occurred());
4153 return NULL;
Guido van Rossum5d815f32001-08-17 21:57:47 +00004154}
4155
Tim Peters6d6c1a32001-08-02 04:15:00 +00004156static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00004157wrap_sq_setitem(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004158{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004159 ssizeobjargproc func = (ssizeobjargproc)wrapped;
4160 Py_ssize_t i;
4161 int res;
4162 PyObject *arg, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004163
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004164 if (!PyArg_UnpackTuple(args, "", 2, 2, &arg, &value))
4165 return NULL;
4166 i = getindex(self, arg);
4167 if (i == -1 && PyErr_Occurred())
4168 return NULL;
4169 res = (*func)(self, i, value);
4170 if (res == -1 && PyErr_Occurred())
4171 return NULL;
4172 Py_INCREF(Py_None);
4173 return Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004174}
4175
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004176static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00004177wrap_sq_delitem(PyObject *self, PyObject *args, void *wrapped)
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004178{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004179 ssizeobjargproc func = (ssizeobjargproc)wrapped;
4180 Py_ssize_t i;
4181 int res;
4182 PyObject *arg;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004183
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004184 if (!check_num_args(args, 1))
4185 return NULL;
4186 arg = PyTuple_GET_ITEM(args, 0);
4187 i = getindex(self, arg);
4188 if (i == -1 && PyErr_Occurred())
4189 return NULL;
4190 res = (*func)(self, i, NULL);
4191 if (res == -1 && PyErr_Occurred())
4192 return NULL;
4193 Py_INCREF(Py_None);
4194 return Py_None;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004195}
4196
Tim Peters6d6c1a32001-08-02 04:15:00 +00004197/* XXX objobjproc is a misnomer; should be objargpred */
4198static PyObject *
4199wrap_objobjproc(PyObject *self, PyObject *args, void *wrapped)
4200{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004201 objobjproc func = (objobjproc)wrapped;
4202 int res;
4203 PyObject *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004204
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004205 if (!check_num_args(args, 1))
4206 return NULL;
4207 value = PyTuple_GET_ITEM(args, 0);
4208 res = (*func)(self, value);
4209 if (res == -1 && PyErr_Occurred())
4210 return NULL;
4211 else
4212 return PyBool_FromLong(res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004213}
4214
Tim Peters6d6c1a32001-08-02 04:15:00 +00004215static PyObject *
4216wrap_objobjargproc(PyObject *self, PyObject *args, void *wrapped)
4217{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004218 objobjargproc func = (objobjargproc)wrapped;
4219 int res;
4220 PyObject *key, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004221
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004222 if (!PyArg_UnpackTuple(args, "", 2, 2, &key, &value))
4223 return NULL;
4224 res = (*func)(self, key, value);
4225 if (res == -1 && PyErr_Occurred())
4226 return NULL;
4227 Py_INCREF(Py_None);
4228 return Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004229}
4230
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004231static PyObject *
4232wrap_delitem(PyObject *self, PyObject *args, void *wrapped)
4233{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004234 objobjargproc func = (objobjargproc)wrapped;
4235 int res;
4236 PyObject *key;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004237
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004238 if (!check_num_args(args, 1))
4239 return NULL;
4240 key = PyTuple_GET_ITEM(args, 0);
4241 res = (*func)(self, key, NULL);
4242 if (res == -1 && PyErr_Occurred())
4243 return NULL;
4244 Py_INCREF(Py_None);
4245 return Py_None;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004246}
4247
Guido van Rossum4dcdb782003-04-14 21:46:03 +00004248/* Helper to check for object.__setattr__ or __delattr__ applied to a type.
Guido van Rossum52b27052003-04-15 20:05:10 +00004249 This is called the Carlo Verre hack after its discoverer. */
Guido van Rossum4dcdb782003-04-14 21:46:03 +00004250static int
4251hackcheck(PyObject *self, setattrofunc func, char *what)
4252{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004253 PyTypeObject *type = Py_TYPE(self);
4254 while (type && type->tp_flags & Py_TPFLAGS_HEAPTYPE)
4255 type = type->tp_base;
4256 /* If type is NULL now, this is a really weird type.
4257 In the spirit of backwards compatibility (?), just shut up. */
4258 if (type && type->tp_setattro != func) {
4259 PyErr_Format(PyExc_TypeError,
4260 "can't apply this %s to %s object",
4261 what,
4262 type->tp_name);
4263 return 0;
4264 }
4265 return 1;
Guido van Rossum4dcdb782003-04-14 21:46:03 +00004266}
4267
Tim Peters6d6c1a32001-08-02 04:15:00 +00004268static PyObject *
4269wrap_setattr(PyObject *self, PyObject *args, void *wrapped)
4270{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004271 setattrofunc func = (setattrofunc)wrapped;
4272 int res;
4273 PyObject *name, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004274
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004275 if (!PyArg_UnpackTuple(args, "", 2, 2, &name, &value))
4276 return NULL;
4277 if (!hackcheck(self, func, "__setattr__"))
4278 return NULL;
4279 res = (*func)(self, name, value);
4280 if (res < 0)
4281 return NULL;
4282 Py_INCREF(Py_None);
4283 return Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004284}
4285
4286static PyObject *
4287wrap_delattr(PyObject *self, PyObject *args, void *wrapped)
4288{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004289 setattrofunc func = (setattrofunc)wrapped;
4290 int res;
4291 PyObject *name;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004292
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004293 if (!check_num_args(args, 1))
4294 return NULL;
4295 name = PyTuple_GET_ITEM(args, 0);
4296 if (!hackcheck(self, func, "__delattr__"))
4297 return NULL;
4298 res = (*func)(self, name, NULL);
4299 if (res < 0)
4300 return NULL;
4301 Py_INCREF(Py_None);
4302 return Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004303}
4304
Tim Peters6d6c1a32001-08-02 04:15:00 +00004305static PyObject *
4306wrap_hashfunc(PyObject *self, PyObject *args, void *wrapped)
4307{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004308 hashfunc func = (hashfunc)wrapped;
4309 long res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004310
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004311 if (!check_num_args(args, 0))
4312 return NULL;
4313 res = (*func)(self);
4314 if (res == -1 && PyErr_Occurred())
4315 return NULL;
4316 return PyLong_FromLong(res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004317}
4318
Tim Peters6d6c1a32001-08-02 04:15:00 +00004319static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00004320wrap_call(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004321{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004322 ternaryfunc func = (ternaryfunc)wrapped;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004323
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004324 return (*func)(self, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004325}
4326
Tim Peters6d6c1a32001-08-02 04:15:00 +00004327static PyObject *
4328wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op)
4329{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004330 richcmpfunc func = (richcmpfunc)wrapped;
4331 PyObject *other;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004332
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004333 if (!check_num_args(args, 1))
4334 return NULL;
4335 other = PyTuple_GET_ITEM(args, 0);
4336 return (*func)(self, other, op);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004337}
4338
4339#undef RICHCMP_WRAPPER
4340#define RICHCMP_WRAPPER(NAME, OP) \
4341static PyObject * \
4342richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \
4343{ \
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004344 return wrap_richcmpfunc(self, args, wrapped, OP); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004345}
4346
Jack Jansen8e938b42001-08-08 15:29:49 +00004347RICHCMP_WRAPPER(lt, Py_LT)
4348RICHCMP_WRAPPER(le, Py_LE)
4349RICHCMP_WRAPPER(eq, Py_EQ)
4350RICHCMP_WRAPPER(ne, Py_NE)
4351RICHCMP_WRAPPER(gt, Py_GT)
4352RICHCMP_WRAPPER(ge, Py_GE)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004353
Tim Peters6d6c1a32001-08-02 04:15:00 +00004354static PyObject *
4355wrap_next(PyObject *self, PyObject *args, void *wrapped)
4356{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004357 unaryfunc func = (unaryfunc)wrapped;
4358 PyObject *res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004359
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004360 if (!check_num_args(args, 0))
4361 return NULL;
4362 res = (*func)(self);
4363 if (res == NULL && !PyErr_Occurred())
4364 PyErr_SetNone(PyExc_StopIteration);
4365 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004366}
4367
Tim Peters6d6c1a32001-08-02 04:15:00 +00004368static PyObject *
4369wrap_descr_get(PyObject *self, PyObject *args, void *wrapped)
4370{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004371 descrgetfunc func = (descrgetfunc)wrapped;
4372 PyObject *obj;
4373 PyObject *type = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004374
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004375 if (!PyArg_UnpackTuple(args, "", 1, 2, &obj, &type))
4376 return NULL;
4377 if (obj == Py_None)
4378 obj = NULL;
4379 if (type == Py_None)
4380 type = NULL;
4381 if (type == NULL &&obj == NULL) {
4382 PyErr_SetString(PyExc_TypeError,
4383 "__get__(None, None) is invalid");
4384 return NULL;
4385 }
4386 return (*func)(self, obj, type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004387}
4388
Tim Peters6d6c1a32001-08-02 04:15:00 +00004389static PyObject *
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004390wrap_descr_set(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004391{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004392 descrsetfunc func = (descrsetfunc)wrapped;
4393 PyObject *obj, *value;
4394 int ret;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004395
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004396 if (!PyArg_UnpackTuple(args, "", 2, 2, &obj, &value))
4397 return NULL;
4398 ret = (*func)(self, obj, value);
4399 if (ret < 0)
4400 return NULL;
4401 Py_INCREF(Py_None);
4402 return Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004403}
Guido van Rossum22b13872002-08-06 21:41:44 +00004404
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00004405static PyObject *
4406wrap_descr_delete(PyObject *self, PyObject *args, void *wrapped)
4407{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004408 descrsetfunc func = (descrsetfunc)wrapped;
4409 PyObject *obj;
4410 int ret;
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00004411
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004412 if (!check_num_args(args, 1))
4413 return NULL;
4414 obj = PyTuple_GET_ITEM(args, 0);
4415 ret = (*func)(self, obj, NULL);
4416 if (ret < 0)
4417 return NULL;
4418 Py_INCREF(Py_None);
4419 return Py_None;
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00004420}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004421
Tim Peters6d6c1a32001-08-02 04:15:00 +00004422static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00004423wrap_init(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004424{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004425 initproc func = (initproc)wrapped;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004426
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004427 if (func(self, args, kwds) < 0)
4428 return NULL;
4429 Py_INCREF(Py_None);
4430 return Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004431}
4432
Tim Peters6d6c1a32001-08-02 04:15:00 +00004433static PyObject *
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004434tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004435{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004436 PyTypeObject *type, *subtype, *staticbase;
4437 PyObject *arg0, *res;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004438
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004439 if (self == NULL || !PyType_Check(self))
4440 Py_FatalError("__new__() called with non-type 'self'");
4441 type = (PyTypeObject *)self;
4442 if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) {
4443 PyErr_Format(PyExc_TypeError,
4444 "%s.__new__(): not enough arguments",
4445 type->tp_name);
4446 return NULL;
4447 }
4448 arg0 = PyTuple_GET_ITEM(args, 0);
4449 if (!PyType_Check(arg0)) {
4450 PyErr_Format(PyExc_TypeError,
4451 "%s.__new__(X): X is not a type object (%s)",
4452 type->tp_name,
4453 Py_TYPE(arg0)->tp_name);
4454 return NULL;
4455 }
4456 subtype = (PyTypeObject *)arg0;
4457 if (!PyType_IsSubtype(subtype, type)) {
4458 PyErr_Format(PyExc_TypeError,
4459 "%s.__new__(%s): %s is not a subtype of %s",
4460 type->tp_name,
4461 subtype->tp_name,
4462 subtype->tp_name,
4463 type->tp_name);
4464 return NULL;
4465 }
Barry Warsaw60f01882001-08-22 19:24:42 +00004466
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004467 /* Check that the use doesn't do something silly and unsafe like
4468 object.__new__(dict). To do this, we check that the
4469 most derived base that's not a heap type is this type. */
4470 staticbase = subtype;
4471 while (staticbase && (staticbase->tp_flags & Py_TPFLAGS_HEAPTYPE))
4472 staticbase = staticbase->tp_base;
4473 /* If staticbase is NULL now, it is a really weird type.
4474 In the spirit of backwards compatibility (?), just shut up. */
4475 if (staticbase && staticbase->tp_new != type->tp_new) {
4476 PyErr_Format(PyExc_TypeError,
4477 "%s.__new__(%s) is not safe, use %s.__new__()",
4478 type->tp_name,
4479 subtype->tp_name,
4480 staticbase == NULL ? "?" : staticbase->tp_name);
4481 return NULL;
4482 }
Barry Warsaw60f01882001-08-22 19:24:42 +00004483
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004484 args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
4485 if (args == NULL)
4486 return NULL;
4487 res = type->tp_new(subtype, args, kwds);
4488 Py_DECREF(args);
4489 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004490}
4491
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004492static struct PyMethodDef tp_new_methoddef[] = {
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004493 {"__new__", (PyCFunction)tp_new_wrapper, METH_VARARGS|METH_KEYWORDS,
4494 PyDoc_STR("T.__new__(S, ...) -> "
4495 "a new object with type S, a subtype of T")},
4496 {0}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004497};
4498
4499static int
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004500add_tp_new_wrapper(PyTypeObject *type)
4501{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004502 PyObject *func;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004503
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004504 if (PyDict_GetItemString(type->tp_dict, "__new__") != NULL)
4505 return 0;
4506 func = PyCFunction_New(tp_new_methoddef, (PyObject *)type);
4507 if (func == NULL)
4508 return -1;
4509 if (PyDict_SetItemString(type->tp_dict, "__new__", func)) {
4510 Py_DECREF(func);
4511 return -1;
4512 }
4513 Py_DECREF(func);
4514 return 0;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004515}
4516
Guido van Rossumf040ede2001-08-07 16:40:56 +00004517/* Slot wrappers that call the corresponding __foo__ slot. See comments
4518 below at override_slots() for more explanation. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004519
Guido van Rossumdc91b992001-08-08 22:26:22 +00004520#define SLOT0(FUNCNAME, OPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004521static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004522FUNCNAME(PyObject *self) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004523{ \
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004524 static PyObject *cache_str; \
4525 return call_method(self, OPSTR, &cache_str, "()"); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004526}
4527
Guido van Rossumdc91b992001-08-08 22:26:22 +00004528#define SLOT1(FUNCNAME, OPSTR, ARG1TYPE, ARGCODES) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004529static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004530FUNCNAME(PyObject *self, ARG1TYPE arg1) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004531{ \
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004532 static PyObject *cache_str; \
4533 return call_method(self, OPSTR, &cache_str, "(" ARGCODES ")", arg1); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004534}
4535
Guido van Rossumcd118802003-01-06 22:57:47 +00004536/* Boolean helper for SLOT1BINFULL().
4537 right.__class__ is a nontrivial subclass of left.__class__. */
4538static int
4539method_is_overloaded(PyObject *left, PyObject *right, char *name)
4540{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004541 PyObject *a, *b;
4542 int ok;
Guido van Rossumcd118802003-01-06 22:57:47 +00004543
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004544 b = PyObject_GetAttrString((PyObject *)(Py_TYPE(right)), name);
4545 if (b == NULL) {
4546 PyErr_Clear();
4547 /* If right doesn't have it, it's not overloaded */
4548 return 0;
4549 }
Guido van Rossumcd118802003-01-06 22:57:47 +00004550
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004551 a = PyObject_GetAttrString((PyObject *)(Py_TYPE(left)), name);
4552 if (a == NULL) {
4553 PyErr_Clear();
4554 Py_DECREF(b);
4555 /* If right has it but left doesn't, it's overloaded */
4556 return 1;
4557 }
Guido van Rossumcd118802003-01-06 22:57:47 +00004558
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004559 ok = PyObject_RichCompareBool(a, b, Py_NE);
4560 Py_DECREF(a);
4561 Py_DECREF(b);
4562 if (ok < 0) {
4563 PyErr_Clear();
4564 return 0;
4565 }
Guido van Rossumcd118802003-01-06 22:57:47 +00004566
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004567 return ok;
Guido van Rossumcd118802003-01-06 22:57:47 +00004568}
4569
Guido van Rossumdc91b992001-08-08 22:26:22 +00004570
4571#define SLOT1BINFULL(FUNCNAME, TESTFUNC, SLOTNAME, OPSTR, ROPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004572static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004573FUNCNAME(PyObject *self, PyObject *other) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004574{ \
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004575 static PyObject *cache_str, *rcache_str; \
4576 int do_other = Py_TYPE(self) != Py_TYPE(other) && \
4577 Py_TYPE(other)->tp_as_number != NULL && \
4578 Py_TYPE(other)->tp_as_number->SLOTNAME == TESTFUNC; \
4579 if (Py_TYPE(self)->tp_as_number != NULL && \
4580 Py_TYPE(self)->tp_as_number->SLOTNAME == TESTFUNC) { \
4581 PyObject *r; \
4582 if (do_other && \
4583 PyType_IsSubtype(Py_TYPE(other), Py_TYPE(self)) && \
4584 method_is_overloaded(self, other, ROPSTR)) { \
4585 r = call_maybe( \
4586 other, ROPSTR, &rcache_str, "(O)", self); \
4587 if (r != Py_NotImplemented) \
4588 return r; \
4589 Py_DECREF(r); \
4590 do_other = 0; \
4591 } \
4592 r = call_maybe( \
4593 self, OPSTR, &cache_str, "(O)", other); \
4594 if (r != Py_NotImplemented || \
4595 Py_TYPE(other) == Py_TYPE(self)) \
4596 return r; \
4597 Py_DECREF(r); \
4598 } \
4599 if (do_other) { \
4600 return call_maybe( \
4601 other, ROPSTR, &rcache_str, "(O)", self); \
4602 } \
4603 Py_INCREF(Py_NotImplemented); \
4604 return Py_NotImplemented; \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004605}
4606
4607#define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) \
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004608 SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR)
Guido van Rossumdc91b992001-08-08 22:26:22 +00004609
4610#define SLOT2(FUNCNAME, OPSTR, ARG1TYPE, ARG2TYPE, ARGCODES) \
4611static PyObject * \
4612FUNCNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \
4613{ \
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004614 static PyObject *cache_str; \
4615 return call_method(self, OPSTR, &cache_str, \
4616 "(" ARGCODES ")", arg1, arg2); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004617}
4618
Martin v. Löwis18e16552006-02-15 17:27:45 +00004619static Py_ssize_t
Tim Peters6d6c1a32001-08-02 04:15:00 +00004620slot_sq_length(PyObject *self)
4621{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004622 static PyObject *len_str;
4623 PyObject *res = call_method(self, "__len__", &len_str, "()");
4624 Py_ssize_t len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004625
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004626 if (res == NULL)
4627 return -1;
4628 len = PyNumber_AsSsize_t(res, PyExc_OverflowError);
4629 Py_DECREF(res);
4630 if (len < 0) {
4631 if (!PyErr_Occurred())
4632 PyErr_SetString(PyExc_ValueError,
4633 "__len__() should return >= 0");
4634 return -1;
4635 }
4636 return len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004637}
4638
Guido van Rossumf4593e02001-10-03 12:09:30 +00004639/* Super-optimized version of slot_sq_item.
4640 Other slots could do the same... */
4641static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00004642slot_sq_item(PyObject *self, Py_ssize_t i)
Guido van Rossumf4593e02001-10-03 12:09:30 +00004643{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004644 static PyObject *getitem_str;
4645 PyObject *func, *args = NULL, *ival = NULL, *retval = NULL;
4646 descrgetfunc f;
Guido van Rossumf4593e02001-10-03 12:09:30 +00004647
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004648 if (getitem_str == NULL) {
4649 getitem_str = PyUnicode_InternFromString("__getitem__");
4650 if (getitem_str == NULL)
4651 return NULL;
4652 }
4653 func = _PyType_Lookup(Py_TYPE(self), getitem_str);
4654 if (func != NULL) {
4655 if ((f = Py_TYPE(func)->tp_descr_get) == NULL)
4656 Py_INCREF(func);
4657 else {
4658 func = f(func, self, (PyObject *)(Py_TYPE(self)));
4659 if (func == NULL) {
4660 return NULL;
4661 }
4662 }
4663 ival = PyLong_FromSsize_t(i);
4664 if (ival != NULL) {
4665 args = PyTuple_New(1);
4666 if (args != NULL) {
4667 PyTuple_SET_ITEM(args, 0, ival);
4668 retval = PyObject_Call(func, args, NULL);
4669 Py_XDECREF(args);
4670 Py_XDECREF(func);
4671 return retval;
4672 }
4673 }
4674 }
4675 else {
4676 PyErr_SetObject(PyExc_AttributeError, getitem_str);
4677 }
4678 Py_XDECREF(args);
4679 Py_XDECREF(ival);
4680 Py_XDECREF(func);
4681 return NULL;
Guido van Rossumf4593e02001-10-03 12:09:30 +00004682}
4683
Tim Peters6d6c1a32001-08-02 04:15:00 +00004684static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00004685slot_sq_ass_item(PyObject *self, Py_ssize_t index, PyObject *value)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004686{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004687 PyObject *res;
4688 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004689
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004690 if (value == NULL)
4691 res = call_method(self, "__delitem__", &delitem_str,
4692 "(n)", index);
4693 else
4694 res = call_method(self, "__setitem__", &setitem_str,
4695 "(nO)", index, value);
4696 if (res == NULL)
4697 return -1;
4698 Py_DECREF(res);
4699 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004700}
4701
4702static int
Tim Peters6d6c1a32001-08-02 04:15:00 +00004703slot_sq_contains(PyObject *self, PyObject *value)
4704{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004705 PyObject *func, *res, *args;
4706 int result = -1;
Tim Petersbf9b2442003-03-23 05:35:36 +00004707
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004708 static PyObject *contains_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004709
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004710 func = lookup_maybe(self, "__contains__", &contains_str);
4711 if (func != NULL) {
4712 args = PyTuple_Pack(1, value);
4713 if (args == NULL)
4714 res = NULL;
4715 else {
4716 res = PyObject_Call(func, args, NULL);
4717 Py_DECREF(args);
4718 }
4719 Py_DECREF(func);
4720 if (res != NULL) {
4721 result = PyObject_IsTrue(res);
4722 Py_DECREF(res);
4723 }
4724 }
4725 else if (! PyErr_Occurred()) {
4726 /* Possible results: -1 and 1 */
4727 result = (int)_PySequence_IterSearch(self, value,
4728 PY_ITERSEARCH_CONTAINS);
4729 }
4730 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004731}
4732
Tim Peters6d6c1a32001-08-02 04:15:00 +00004733#define slot_mp_length slot_sq_length
4734
Guido van Rossumdc91b992001-08-08 22:26:22 +00004735SLOT1(slot_mp_subscript, "__getitem__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004736
4737static int
4738slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value)
4739{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004740 PyObject *res;
4741 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004742
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004743 if (value == NULL)
4744 res = call_method(self, "__delitem__", &delitem_str,
4745 "(O)", key);
4746 else
4747 res = call_method(self, "__setitem__", &setitem_str,
4748 "(OO)", key, value);
4749 if (res == NULL)
4750 return -1;
4751 Py_DECREF(res);
4752 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004753}
4754
Guido van Rossumdc91b992001-08-08 22:26:22 +00004755SLOT1BIN(slot_nb_add, nb_add, "__add__", "__radd__")
4756SLOT1BIN(slot_nb_subtract, nb_subtract, "__sub__", "__rsub__")
4757SLOT1BIN(slot_nb_multiply, nb_multiply, "__mul__", "__rmul__")
Guido van Rossumdc91b992001-08-08 22:26:22 +00004758SLOT1BIN(slot_nb_remainder, nb_remainder, "__mod__", "__rmod__")
4759SLOT1BIN(slot_nb_divmod, nb_divmod, "__divmod__", "__rdivmod__")
4760
Jeremy Hylton938ace62002-07-17 16:30:39 +00004761static PyObject *slot_nb_power(PyObject *, PyObject *, PyObject *);
Guido van Rossumdc91b992001-08-08 22:26:22 +00004762
4763SLOT1BINFULL(slot_nb_power_binary, slot_nb_power,
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004764 nb_power, "__pow__", "__rpow__")
Guido van Rossumdc91b992001-08-08 22:26:22 +00004765
4766static PyObject *
4767slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus)
4768{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004769 static PyObject *pow_str;
Guido van Rossum2730b132001-08-28 18:22:14 +00004770
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004771 if (modulus == Py_None)
4772 return slot_nb_power_binary(self, other);
4773 /* Three-arg power doesn't use __rpow__. But ternary_op
4774 can call this when the second argument's type uses
4775 slot_nb_power, so check before calling self.__pow__. */
4776 if (Py_TYPE(self)->tp_as_number != NULL &&
4777 Py_TYPE(self)->tp_as_number->nb_power == slot_nb_power) {
4778 return call_method(self, "__pow__", &pow_str,
4779 "(OO)", other, modulus);
4780 }
4781 Py_INCREF(Py_NotImplemented);
4782 return Py_NotImplemented;
Guido van Rossumdc91b992001-08-08 22:26:22 +00004783}
4784
4785SLOT0(slot_nb_negative, "__neg__")
4786SLOT0(slot_nb_positive, "__pos__")
4787SLOT0(slot_nb_absolute, "__abs__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004788
4789static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00004790slot_nb_bool(PyObject *self)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004791{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004792 PyObject *func, *args;
4793 static PyObject *bool_str, *len_str;
4794 int result = -1;
4795 int using_len = 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004796
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004797 func = lookup_maybe(self, "__bool__", &bool_str);
4798 if (func == NULL) {
4799 if (PyErr_Occurred())
4800 return -1;
4801 func = lookup_maybe(self, "__len__", &len_str);
4802 if (func == NULL)
4803 return PyErr_Occurred() ? -1 : 1;
4804 using_len = 1;
4805 }
4806 args = PyTuple_New(0);
4807 if (args != NULL) {
4808 PyObject *temp = PyObject_Call(func, args, NULL);
4809 Py_DECREF(args);
4810 if (temp != NULL) {
4811 if (using_len) {
4812 /* enforced by slot_nb_len */
4813 result = PyObject_IsTrue(temp);
4814 }
4815 else if (PyBool_Check(temp)) {
4816 result = PyObject_IsTrue(temp);
4817 }
4818 else {
4819 PyErr_Format(PyExc_TypeError,
4820 "__bool__ should return "
4821 "bool, returned %s",
4822 Py_TYPE(temp)->tp_name);
4823 result = -1;
4824 }
4825 Py_DECREF(temp);
4826 }
4827 }
4828 Py_DECREF(func);
4829 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004830}
4831
Guido van Rossum38fff8c2006-03-07 18:50:55 +00004832
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00004833static PyObject *
Guido van Rossum38fff8c2006-03-07 18:50:55 +00004834slot_nb_index(PyObject *self)
4835{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004836 static PyObject *index_str;
4837 return call_method(self, "__index__", &index_str, "()");
Guido van Rossum38fff8c2006-03-07 18:50:55 +00004838}
4839
4840
Guido van Rossumdc91b992001-08-08 22:26:22 +00004841SLOT0(slot_nb_invert, "__invert__")
4842SLOT1BIN(slot_nb_lshift, nb_lshift, "__lshift__", "__rlshift__")
4843SLOT1BIN(slot_nb_rshift, nb_rshift, "__rshift__", "__rrshift__")
4844SLOT1BIN(slot_nb_and, nb_and, "__and__", "__rand__")
4845SLOT1BIN(slot_nb_xor, nb_xor, "__xor__", "__rxor__")
4846SLOT1BIN(slot_nb_or, nb_or, "__or__", "__ror__")
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004847
Guido van Rossumdc91b992001-08-08 22:26:22 +00004848SLOT0(slot_nb_int, "__int__")
Guido van Rossumdc91b992001-08-08 22:26:22 +00004849SLOT0(slot_nb_float, "__float__")
Guido van Rossumdc91b992001-08-08 22:26:22 +00004850SLOT1(slot_nb_inplace_add, "__iadd__", PyObject *, "O")
4851SLOT1(slot_nb_inplace_subtract, "__isub__", PyObject *, "O")
4852SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *, "O")
Guido van Rossumdc91b992001-08-08 22:26:22 +00004853SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *, "O")
Thomas Wouterscf297e42007-02-23 15:07:44 +00004854/* Can't use SLOT1 here, because nb_inplace_power is ternary */
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004855static PyObject *
4856slot_nb_inplace_power(PyObject *self, PyObject * arg1, PyObject *arg2)
4857{
4858 static PyObject *cache_str;
4859 return call_method(self, "__ipow__", &cache_str, "(" "O" ")", arg1);
Thomas Wouterscf297e42007-02-23 15:07:44 +00004860}
Guido van Rossumdc91b992001-08-08 22:26:22 +00004861SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *, "O")
4862SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *, "O")
4863SLOT1(slot_nb_inplace_and, "__iand__", PyObject *, "O")
4864SLOT1(slot_nb_inplace_xor, "__ixor__", PyObject *, "O")
4865SLOT1(slot_nb_inplace_or, "__ior__", PyObject *, "O")
4866SLOT1BIN(slot_nb_floor_divide, nb_floor_divide,
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004867 "__floordiv__", "__rfloordiv__")
Guido van Rossumdc91b992001-08-08 22:26:22 +00004868SLOT1BIN(slot_nb_true_divide, nb_true_divide, "__truediv__", "__rtruediv__")
4869SLOT1(slot_nb_inplace_floor_divide, "__ifloordiv__", PyObject *, "O")
4870SLOT1(slot_nb_inplace_true_divide, "__itruediv__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004871
Guido van Rossumb8f63662001-08-15 23:57:02 +00004872static PyObject *
4873slot_tp_repr(PyObject *self)
4874{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004875 PyObject *func, *res;
4876 static PyObject *repr_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004877
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004878 func = lookup_method(self, "__repr__", &repr_str);
4879 if (func != NULL) {
4880 res = PyEval_CallObject(func, NULL);
4881 Py_DECREF(func);
4882 return res;
4883 }
4884 PyErr_Clear();
4885 return PyUnicode_FromFormat("<%s object at %p>",
4886 Py_TYPE(self)->tp_name, self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004887}
4888
4889static PyObject *
4890slot_tp_str(PyObject *self)
4891{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004892 PyObject *func, *res;
4893 static PyObject *str_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004894
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004895 func = lookup_method(self, "__str__", &str_str);
4896 if (func != NULL) {
4897 res = PyEval_CallObject(func, NULL);
4898 Py_DECREF(func);
4899 return res;
4900 }
4901 else {
4902 PyObject *ress;
4903 PyErr_Clear();
4904 res = slot_tp_repr(self);
4905 if (!res)
4906 return NULL;
4907 ress = _PyUnicode_AsDefaultEncodedString(res, NULL);
4908 Py_DECREF(res);
4909 return ress;
4910 }
Guido van Rossumb8f63662001-08-15 23:57:02 +00004911}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004912
4913static long
4914slot_tp_hash(PyObject *self)
4915{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004916 PyObject *func, *res;
4917 static PyObject *hash_str;
4918 long h;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004919
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004920 func = lookup_method(self, "__hash__", &hash_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004921
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004922 if (func == Py_None) {
4923 Py_DECREF(func);
4924 func = NULL;
4925 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +00004926
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004927 if (func == NULL) {
4928 return PyObject_HashNotImplemented(self);
4929 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +00004930
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004931 res = PyEval_CallObject(func, NULL);
4932 Py_DECREF(func);
4933 if (res == NULL)
4934 return -1;
4935 if (PyLong_Check(res))
4936 h = PyLong_Type.tp_hash(res);
4937 else
4938 h = PyLong_AsLong(res);
4939 Py_DECREF(res);
4940 if (h == -1 && !PyErr_Occurred())
4941 h = -2;
4942 return h;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004943}
4944
4945static PyObject *
4946slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds)
4947{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004948 static PyObject *call_str;
4949 PyObject *meth = lookup_method(self, "__call__", &call_str);
4950 PyObject *res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004951
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004952 if (meth == NULL)
4953 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004954
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004955 res = PyObject_Call(meth, args, kwds);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004956
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004957 Py_DECREF(meth);
4958 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004959}
4960
Guido van Rossum14a6f832001-10-17 13:59:09 +00004961/* There are two slot dispatch functions for tp_getattro.
4962
4963 - slot_tp_getattro() is used when __getattribute__ is overridden
4964 but no __getattr__ hook is present;
4965
4966 - slot_tp_getattr_hook() is used when a __getattr__ hook is present.
4967
Guido van Rossumc334df52002-04-04 23:44:47 +00004968 The code in update_one_slot() always installs slot_tp_getattr_hook(); this
4969 detects the absence of __getattr__ and then installs the simpler slot if
4970 necessary. */
Guido van Rossum14a6f832001-10-17 13:59:09 +00004971
Tim Peters6d6c1a32001-08-02 04:15:00 +00004972static PyObject *
4973slot_tp_getattro(PyObject *self, PyObject *name)
4974{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004975 static PyObject *getattribute_str = NULL;
4976 return call_method(self, "__getattribute__", &getattribute_str,
4977 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004978}
4979
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004980static PyObject *
Benjamin Peterson9262b842008-11-17 22:45:50 +00004981call_attribute(PyObject *self, PyObject *attr, PyObject *name)
4982{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004983 PyObject *res, *descr = NULL;
4984 descrgetfunc f = Py_TYPE(attr)->tp_descr_get;
Benjamin Peterson9262b842008-11-17 22:45:50 +00004985
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004986 if (f != NULL) {
4987 descr = f(attr, self, (PyObject *)(Py_TYPE(self)));
4988 if (descr == NULL)
4989 return NULL;
4990 else
4991 attr = descr;
4992 }
4993 res = PyObject_CallFunctionObjArgs(attr, name, NULL);
4994 Py_XDECREF(descr);
4995 return res;
Benjamin Peterson9262b842008-11-17 22:45:50 +00004996}
4997
4998static PyObject *
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004999slot_tp_getattr_hook(PyObject *self, PyObject *name)
5000{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00005001 PyTypeObject *tp = Py_TYPE(self);
5002 PyObject *getattr, *getattribute, *res;
5003 static PyObject *getattribute_str = NULL;
5004 static PyObject *getattr_str = NULL;
Guido van Rossum19c1cd52001-09-21 21:24:49 +00005005
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00005006 if (getattr_str == NULL) {
5007 getattr_str = PyUnicode_InternFromString("__getattr__");
5008 if (getattr_str == NULL)
5009 return NULL;
5010 }
5011 if (getattribute_str == NULL) {
5012 getattribute_str =
5013 PyUnicode_InternFromString("__getattribute__");
5014 if (getattribute_str == NULL)
5015 return NULL;
5016 }
5017 /* speed hack: we could use lookup_maybe, but that would resolve the
5018 method fully for each attribute lookup for classes with
5019 __getattr__, even when the attribute is present. So we use
5020 _PyType_Lookup and create the method only when needed, with
5021 call_attribute. */
5022 getattr = _PyType_Lookup(tp, getattr_str);
5023 if (getattr == NULL) {
5024 /* No __getattr__ hook: use a simpler dispatcher */
5025 tp->tp_getattro = slot_tp_getattro;
5026 return slot_tp_getattro(self, name);
5027 }
5028 Py_INCREF(getattr);
5029 /* speed hack: we could use lookup_maybe, but that would resolve the
5030 method fully for each attribute lookup for classes with
5031 __getattr__, even when self has the default __getattribute__
5032 method. So we use _PyType_Lookup and create the method only when
5033 needed, with call_attribute. */
5034 getattribute = _PyType_Lookup(tp, getattribute_str);
5035 if (getattribute == NULL ||
5036 (Py_TYPE(getattribute) == &PyWrapperDescr_Type &&
5037 ((PyWrapperDescrObject *)getattribute)->d_wrapped ==
5038 (void *)PyObject_GenericGetAttr))
5039 res = PyObject_GenericGetAttr(self, name);
5040 else {
5041 Py_INCREF(getattribute);
5042 res = call_attribute(self, getattribute, name);
5043 Py_DECREF(getattribute);
5044 }
5045 if (res == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) {
5046 PyErr_Clear();
5047 res = call_attribute(self, getattr, name);
5048 }
5049 Py_DECREF(getattr);
5050 return res;
Guido van Rossum19c1cd52001-09-21 21:24:49 +00005051}
5052
Tim Peters6d6c1a32001-08-02 04:15:00 +00005053static int
5054slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value)
5055{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00005056 PyObject *res;
5057 static PyObject *delattr_str, *setattr_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005058
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00005059 if (value == NULL)
5060 res = call_method(self, "__delattr__", &delattr_str,
5061 "(O)", name);
5062 else
5063 res = call_method(self, "__setattr__", &setattr_str,
5064 "(OO)", name, value);
5065 if (res == NULL)
5066 return -1;
5067 Py_DECREF(res);
5068 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005069}
5070
Guido van Rossumf5243f02008-01-01 04:06:48 +00005071static char *name_op[] = {
5072 "__lt__",
5073 "__le__",
5074 "__eq__",
5075 "__ne__",
5076 "__gt__",
5077 "__ge__",
5078};
5079
Tim Peters6d6c1a32001-08-02 04:15:00 +00005080static PyObject *
Guido van Rossumb8f63662001-08-15 23:57:02 +00005081half_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005082{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00005083 PyObject *func, *args, *res;
5084 static PyObject *op_str[6];
Tim Peters6d6c1a32001-08-02 04:15:00 +00005085
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00005086 func = lookup_method(self, name_op[op], &op_str[op]);
5087 if (func == NULL) {
5088 PyErr_Clear();
5089 Py_INCREF(Py_NotImplemented);
5090 return Py_NotImplemented;
5091 }
5092 args = PyTuple_Pack(1, other);
5093 if (args == NULL)
5094 res = NULL;
5095 else {
5096 res = PyObject_Call(func, args, NULL);
5097 Py_DECREF(args);
5098 }
5099 Py_DECREF(func);
5100 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005101}
5102
Guido van Rossumb8f63662001-08-15 23:57:02 +00005103static PyObject *
5104slot_tp_richcompare(PyObject *self, PyObject *other, int op)
5105{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00005106 PyObject *res;
Guido van Rossumb8f63662001-08-15 23:57:02 +00005107
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00005108 if (Py_TYPE(self)->tp_richcompare == slot_tp_richcompare) {
5109 res = half_richcompare(self, other, op);
5110 if (res != Py_NotImplemented)
5111 return res;
5112 Py_DECREF(res);
5113 }
5114 if (Py_TYPE(other)->tp_richcompare == slot_tp_richcompare) {
5115 res = half_richcompare(other, self, _Py_SwappedOp[op]);
5116 if (res != Py_NotImplemented) {
5117 return res;
5118 }
5119 Py_DECREF(res);
5120 }
5121 Py_INCREF(Py_NotImplemented);
5122 return Py_NotImplemented;
Guido van Rossumb8f63662001-08-15 23:57:02 +00005123}
5124
5125static PyObject *
5126slot_tp_iter(PyObject *self)
5127{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00005128 PyObject *func, *res;
5129 static PyObject *iter_str, *getitem_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00005130
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00005131 func = lookup_method(self, "__iter__", &iter_str);
5132 if (func != NULL) {
5133 PyObject *args;
5134 args = res = PyTuple_New(0);
5135 if (args != NULL) {
5136 res = PyObject_Call(func, args, NULL);
5137 Py_DECREF(args);
5138 }
5139 Py_DECREF(func);
5140 return res;
5141 }
5142 PyErr_Clear();
5143 func = lookup_method(self, "__getitem__", &getitem_str);
5144 if (func == NULL) {
5145 PyErr_Format(PyExc_TypeError,
5146 "'%.200s' object is not iterable",
5147 Py_TYPE(self)->tp_name);
5148 return NULL;
5149 }
5150 Py_DECREF(func);
5151 return PySeqIter_New(self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005152}
Tim Peters6d6c1a32001-08-02 04:15:00 +00005153
5154static PyObject *
5155slot_tp_iternext(PyObject *self)
5156{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00005157 static PyObject *next_str;
5158 return call_method(self, "__next__", &next_str, "()");
Tim Peters6d6c1a32001-08-02 04:15:00 +00005159}
5160
Guido van Rossum1a493502001-08-17 16:47:50 +00005161static PyObject *
5162slot_tp_descr_get(PyObject *self, PyObject *obj, PyObject *type)
5163{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00005164 PyTypeObject *tp = Py_TYPE(self);
5165 PyObject *get;
5166 static PyObject *get_str = NULL;
Guido van Rossum1a493502001-08-17 16:47:50 +00005167
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00005168 if (get_str == NULL) {
5169 get_str = PyUnicode_InternFromString("__get__");
5170 if (get_str == NULL)
5171 return NULL;
5172 }
5173 get = _PyType_Lookup(tp, get_str);
5174 if (get == NULL) {
5175 /* Avoid further slowdowns */
5176 if (tp->tp_descr_get == slot_tp_descr_get)
5177 tp->tp_descr_get = NULL;
5178 Py_INCREF(self);
5179 return self;
5180 }
5181 if (obj == NULL)
5182 obj = Py_None;
5183 if (type == NULL)
5184 type = Py_None;
5185 return PyObject_CallFunctionObjArgs(get, self, obj, type, NULL);
Guido van Rossum1a493502001-08-17 16:47:50 +00005186}
Tim Peters6d6c1a32001-08-02 04:15:00 +00005187
5188static int
5189slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value)
5190{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00005191 PyObject *res;
5192 static PyObject *del_str, *set_str;
Guido van Rossum2c252392001-08-24 10:13:31 +00005193
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00005194 if (value == NULL)
5195 res = call_method(self, "__delete__", &del_str,
5196 "(O)", target);
5197 else
5198 res = call_method(self, "__set__", &set_str,
5199 "(OO)", target, value);
5200 if (res == NULL)
5201 return -1;
5202 Py_DECREF(res);
5203 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005204}
5205
5206static int
5207slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds)
5208{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00005209 static PyObject *init_str;
5210 PyObject *meth = lookup_method(self, "__init__", &init_str);
5211 PyObject *res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005212
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00005213 if (meth == NULL)
5214 return -1;
5215 res = PyObject_Call(meth, args, kwds);
5216 Py_DECREF(meth);
5217 if (res == NULL)
5218 return -1;
5219 if (res != Py_None) {
5220 PyErr_Format(PyExc_TypeError,
5221 "__init__() should return None, not '%.200s'",
5222 Py_TYPE(res)->tp_name);
5223 Py_DECREF(res);
5224 return -1;
5225 }
5226 Py_DECREF(res);
5227 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005228}
5229
5230static PyObject *
5231slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
5232{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00005233 static PyObject *new_str;
5234 PyObject *func;
5235 PyObject *newargs, *x;
5236 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005237
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00005238 if (new_str == NULL) {
5239 new_str = PyUnicode_InternFromString("__new__");
5240 if (new_str == NULL)
5241 return NULL;
5242 }
5243 func = PyObject_GetAttr((PyObject *)type, new_str);
5244 if (func == NULL)
5245 return NULL;
5246 assert(PyTuple_Check(args));
5247 n = PyTuple_GET_SIZE(args);
5248 newargs = PyTuple_New(n+1);
5249 if (newargs == NULL)
5250 return NULL;
5251 Py_INCREF(type);
5252 PyTuple_SET_ITEM(newargs, 0, (PyObject *)type);
5253 for (i = 0; i < n; i++) {
5254 x = PyTuple_GET_ITEM(args, i);
5255 Py_INCREF(x);
5256 PyTuple_SET_ITEM(newargs, i+1, x);
5257 }
5258 x = PyObject_Call(func, newargs, kwds);
5259 Py_DECREF(newargs);
5260 Py_DECREF(func);
5261 return x;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005262}
5263
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005264static void
5265slot_tp_del(PyObject *self)
5266{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00005267 static PyObject *del_str = NULL;
5268 PyObject *del, *res;
5269 PyObject *error_type, *error_value, *error_traceback;
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005270
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00005271 /* Temporarily resurrect the object. */
5272 assert(self->ob_refcnt == 0);
5273 self->ob_refcnt = 1;
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005274
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00005275 /* Save the current exception, if any. */
5276 PyErr_Fetch(&error_type, &error_value, &error_traceback);
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005277
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00005278 /* Execute __del__ method, if any. */
5279 del = lookup_maybe(self, "__del__", &del_str);
5280 if (del != NULL) {
5281 res = PyEval_CallObject(del, NULL);
5282 if (res == NULL)
5283 PyErr_WriteUnraisable(del);
5284 else
5285 Py_DECREF(res);
5286 Py_DECREF(del);
5287 }
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005288
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00005289 /* Restore the saved exception. */
5290 PyErr_Restore(error_type, error_value, error_traceback);
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005291
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00005292 /* Undo the temporary resurrection; can't use DECREF here, it would
5293 * cause a recursive call.
5294 */
5295 assert(self->ob_refcnt > 0);
5296 if (--self->ob_refcnt == 0)
5297 return; /* this is the normal path out */
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005298
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00005299 /* __del__ resurrected it! Make it look like the original Py_DECREF
5300 * never happened.
5301 */
5302 {
5303 Py_ssize_t refcnt = self->ob_refcnt;
5304 _Py_NewReference(self);
5305 self->ob_refcnt = refcnt;
5306 }
5307 assert(!PyType_IS_GC(Py_TYPE(self)) ||
5308 _Py_AS_GC(self)->gc.gc_refs != _PyGC_REFS_UNTRACKED);
5309 /* If Py_REF_DEBUG, _Py_NewReference bumped _Py_RefTotal, so
5310 * we need to undo that. */
5311 _Py_DEC_REFTOTAL;
5312 /* If Py_TRACE_REFS, _Py_NewReference re-added self to the object
5313 * chain, so no more to do there.
5314 * If COUNT_ALLOCS, the original decref bumped tp_frees, and
5315 * _Py_NewReference bumped tp_allocs: both of those need to be
5316 * undone.
5317 */
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005318#ifdef COUNT_ALLOCS
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00005319 --Py_TYPE(self)->tp_frees;
5320 --Py_TYPE(self)->tp_allocs;
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005321#endif
5322}
5323
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005324
5325/* Table mapping __foo__ names to tp_foo offsets and slot_tp_foo wrapper
Tim Petersbf9b2442003-03-23 05:35:36 +00005326 functions. The offsets here are relative to the 'PyHeapTypeObject'
Guido van Rossume5c691a2003-03-07 15:13:17 +00005327 structure, which incorporates the additional structures used for numbers,
5328 sequences and mappings.
5329 Note that multiple names may map to the same slot (e.g. __eq__,
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005330 __ne__ etc. all map to tp_richcompare) and one name may map to multiple
Guido van Rossumc334df52002-04-04 23:44:47 +00005331 slots (e.g. __str__ affects tp_str as well as tp_repr). The table is
5332 terminated with an all-zero entry. (This table is further initialized and
5333 sorted in init_slotdefs() below.) */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005334
Guido van Rossum6d204072001-10-21 00:44:31 +00005335typedef struct wrapperbase slotdef;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005336
5337#undef TPSLOT
Guido van Rossumc8e56452001-10-22 00:43:43 +00005338#undef FLSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005339#undef ETSLOT
5340#undef SQSLOT
5341#undef MPSLOT
5342#undef NBSLOT
Guido van Rossum6d204072001-10-21 00:44:31 +00005343#undef UNSLOT
5344#undef IBSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005345#undef BINSLOT
5346#undef RBINSLOT
5347
Guido van Rossum6d204072001-10-21 00:44:31 +00005348#define TPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00005349 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
5350 PyDoc_STR(DOC)}
Guido van Rossumc8e56452001-10-22 00:43:43 +00005351#define FLSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC, FLAGS) \
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00005352 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
5353 PyDoc_STR(DOC), FLAGS}
Guido van Rossum6d204072001-10-21 00:44:31 +00005354#define ETSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00005355 {NAME, offsetof(PyHeapTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
5356 PyDoc_STR(DOC)}
Guido van Rossum6d204072001-10-21 00:44:31 +00005357#define SQSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00005358 ETSLOT(NAME, as_sequence.SLOT, FUNCTION, WRAPPER, DOC)
Guido van Rossum6d204072001-10-21 00:44:31 +00005359#define MPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00005360 ETSLOT(NAME, as_mapping.SLOT, FUNCTION, WRAPPER, DOC)
Guido van Rossum6d204072001-10-21 00:44:31 +00005361#define NBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00005362 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, DOC)
Guido van Rossum6d204072001-10-21 00:44:31 +00005363#define UNSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00005364 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
5365 "x." NAME "() <==> " DOC)
Guido van Rossum6d204072001-10-21 00:44:31 +00005366#define IBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00005367 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
5368 "x." NAME "(y) <==> x" DOC "y")
Guido van Rossum6d204072001-10-21 00:44:31 +00005369#define BINSLOT(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) <==> x" DOC "y")
Guido van Rossum6d204072001-10-21 00:44:31 +00005372#define RBINSLOT(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) <==> y" DOC "x")
Anthony Baxter56616992005-06-03 14:12:21 +00005375#define BINSLOTNOTINFIX(NAME, SLOT, FUNCTION, DOC) \
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00005376 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
5377 "x." NAME "(y) <==> " DOC)
Anthony Baxter56616992005-06-03 14:12:21 +00005378#define RBINSLOTNOTINFIX(NAME, SLOT, FUNCTION, DOC) \
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00005379 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
5380 "x." NAME "(y) <==> " DOC)
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005381
5382static slotdef slotdefs[] = {
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00005383 SQSLOT("__len__", sq_length, slot_sq_length, wrap_lenfunc,
5384 "x.__len__() <==> len(x)"),
5385 /* Heap types defining __add__/__mul__ have sq_concat/sq_repeat == NULL.
5386 The logic in abstract.c always falls back to nb_add/nb_multiply in
5387 this case. Defining both the nb_* and the sq_* slots to call the
5388 user-defined methods has unexpected side-effects, as shown by
5389 test_descr.notimplemented() */
5390 SQSLOT("__add__", sq_concat, NULL, wrap_binaryfunc,
5391 "x.__add__(y) <==> x+y"),
5392 SQSLOT("__mul__", sq_repeat, NULL, wrap_indexargfunc,
5393 "x.__mul__(n) <==> x*n"),
5394 SQSLOT("__rmul__", sq_repeat, NULL, wrap_indexargfunc,
5395 "x.__rmul__(n) <==> n*x"),
5396 SQSLOT("__getitem__", sq_item, slot_sq_item, wrap_sq_item,
5397 "x.__getitem__(y) <==> x[y]"),
5398 SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_setitem,
5399 "x.__setitem__(i, y) <==> x[i]=y"),
5400 SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_delitem,
5401 "x.__delitem__(y) <==> del x[y]"),
5402 SQSLOT("__contains__", sq_contains, slot_sq_contains, wrap_objobjproc,
5403 "x.__contains__(y) <==> y in x"),
5404 SQSLOT("__iadd__", sq_inplace_concat, NULL,
5405 wrap_binaryfunc, "x.__iadd__(y) <==> x+=y"),
5406 SQSLOT("__imul__", sq_inplace_repeat, NULL,
5407 wrap_indexargfunc, "x.__imul__(y) <==> x*=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005408
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00005409 MPSLOT("__len__", mp_length, slot_mp_length, wrap_lenfunc,
5410 "x.__len__() <==> len(x)"),
5411 MPSLOT("__getitem__", mp_subscript, slot_mp_subscript,
5412 wrap_binaryfunc,
5413 "x.__getitem__(y) <==> x[y]"),
5414 MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript,
5415 wrap_objobjargproc,
5416 "x.__setitem__(i, y) <==> x[i]=y"),
5417 MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript,
5418 wrap_delitem,
5419 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005420
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00005421 BINSLOT("__add__", nb_add, slot_nb_add,
5422 "+"),
5423 RBINSLOT("__radd__", nb_add, slot_nb_add,
5424 "+"),
5425 BINSLOT("__sub__", nb_subtract, slot_nb_subtract,
5426 "-"),
5427 RBINSLOT("__rsub__", nb_subtract, slot_nb_subtract,
5428 "-"),
5429 BINSLOT("__mul__", nb_multiply, slot_nb_multiply,
5430 "*"),
5431 RBINSLOT("__rmul__", nb_multiply, slot_nb_multiply,
5432 "*"),
5433 BINSLOT("__mod__", nb_remainder, slot_nb_remainder,
5434 "%"),
5435 RBINSLOT("__rmod__", nb_remainder, slot_nb_remainder,
5436 "%"),
5437 BINSLOTNOTINFIX("__divmod__", nb_divmod, slot_nb_divmod,
5438 "divmod(x, y)"),
5439 RBINSLOTNOTINFIX("__rdivmod__", nb_divmod, slot_nb_divmod,
5440 "divmod(y, x)"),
5441 NBSLOT("__pow__", nb_power, slot_nb_power, wrap_ternaryfunc,
5442 "x.__pow__(y[, z]) <==> pow(x, y[, z])"),
5443 NBSLOT("__rpow__", nb_power, slot_nb_power, wrap_ternaryfunc_r,
5444 "y.__rpow__(x[, z]) <==> pow(x, y[, z])"),
5445 UNSLOT("__neg__", nb_negative, slot_nb_negative, wrap_unaryfunc, "-x"),
5446 UNSLOT("__pos__", nb_positive, slot_nb_positive, wrap_unaryfunc, "+x"),
5447 UNSLOT("__abs__", nb_absolute, slot_nb_absolute, wrap_unaryfunc,
5448 "abs(x)"),
5449 UNSLOT("__bool__", nb_bool, slot_nb_bool, wrap_inquirypred,
5450 "x != 0"),
5451 UNSLOT("__invert__", nb_invert, slot_nb_invert, wrap_unaryfunc, "~x"),
5452 BINSLOT("__lshift__", nb_lshift, slot_nb_lshift, "<<"),
5453 RBINSLOT("__rlshift__", nb_lshift, slot_nb_lshift, "<<"),
5454 BINSLOT("__rshift__", nb_rshift, slot_nb_rshift, ">>"),
5455 RBINSLOT("__rrshift__", nb_rshift, slot_nb_rshift, ">>"),
5456 BINSLOT("__and__", nb_and, slot_nb_and, "&"),
5457 RBINSLOT("__rand__", nb_and, slot_nb_and, "&"),
5458 BINSLOT("__xor__", nb_xor, slot_nb_xor, "^"),
5459 RBINSLOT("__rxor__", nb_xor, slot_nb_xor, "^"),
5460 BINSLOT("__or__", nb_or, slot_nb_or, "|"),
5461 RBINSLOT("__ror__", nb_or, slot_nb_or, "|"),
5462 UNSLOT("__int__", nb_int, slot_nb_int, wrap_unaryfunc,
5463 "int(x)"),
5464 UNSLOT("__float__", nb_float, slot_nb_float, wrap_unaryfunc,
5465 "float(x)"),
5466 NBSLOT("__index__", nb_index, slot_nb_index, wrap_unaryfunc,
5467 "x[y:z] <==> x[y.__index__():z.__index__()]"),
5468 IBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add,
5469 wrap_binaryfunc, "+"),
5470 IBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract,
5471 wrap_binaryfunc, "-"),
5472 IBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply,
5473 wrap_binaryfunc, "*"),
5474 IBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder,
5475 wrap_binaryfunc, "%"),
5476 IBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power,
5477 wrap_binaryfunc, "**"),
5478 IBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift,
5479 wrap_binaryfunc, "<<"),
5480 IBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift,
5481 wrap_binaryfunc, ">>"),
5482 IBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and,
5483 wrap_binaryfunc, "&"),
5484 IBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor,
5485 wrap_binaryfunc, "^"),
5486 IBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or,
5487 wrap_binaryfunc, "|"),
5488 BINSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
5489 RBINSLOT("__rfloordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
5490 BINSLOT("__truediv__", nb_true_divide, slot_nb_true_divide, "/"),
5491 RBINSLOT("__rtruediv__", nb_true_divide, slot_nb_true_divide, "/"),
5492 IBSLOT("__ifloordiv__", nb_inplace_floor_divide,
5493 slot_nb_inplace_floor_divide, wrap_binaryfunc, "//"),
5494 IBSLOT("__itruediv__", nb_inplace_true_divide,
5495 slot_nb_inplace_true_divide, wrap_binaryfunc, "/"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005496
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00005497 TPSLOT("__str__", tp_str, slot_tp_str, wrap_unaryfunc,
5498 "x.__str__() <==> str(x)"),
5499 TPSLOT("__repr__", tp_repr, slot_tp_repr, wrap_unaryfunc,
5500 "x.__repr__() <==> repr(x)"),
5501 TPSLOT("__hash__", tp_hash, slot_tp_hash, wrap_hashfunc,
5502 "x.__hash__() <==> hash(x)"),
5503 FLSLOT("__call__", tp_call, slot_tp_call, (wrapperfunc)wrap_call,
5504 "x.__call__(...) <==> x(...)", PyWrapperFlag_KEYWORDS),
5505 TPSLOT("__getattribute__", tp_getattro, slot_tp_getattr_hook,
5506 wrap_binaryfunc, "x.__getattribute__('name') <==> x.name"),
5507 TPSLOT("__getattribute__", tp_getattr, NULL, NULL, ""),
5508 TPSLOT("__getattr__", tp_getattro, slot_tp_getattr_hook, NULL, ""),
5509 TPSLOT("__getattr__", tp_getattr, NULL, NULL, ""),
5510 TPSLOT("__setattr__", tp_setattro, slot_tp_setattro, wrap_setattr,
5511 "x.__setattr__('name', value) <==> x.name = value"),
5512 TPSLOT("__setattr__", tp_setattr, NULL, NULL, ""),
5513 TPSLOT("__delattr__", tp_setattro, slot_tp_setattro, wrap_delattr,
5514 "x.__delattr__('name') <==> del x.name"),
5515 TPSLOT("__delattr__", tp_setattr, NULL, NULL, ""),
5516 TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare, richcmp_lt,
5517 "x.__lt__(y) <==> x<y"),
5518 TPSLOT("__le__", tp_richcompare, slot_tp_richcompare, richcmp_le,
5519 "x.__le__(y) <==> x<=y"),
5520 TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare, richcmp_eq,
5521 "x.__eq__(y) <==> x==y"),
5522 TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare, richcmp_ne,
5523 "x.__ne__(y) <==> x!=y"),
5524 TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare, richcmp_gt,
5525 "x.__gt__(y) <==> x>y"),
5526 TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare, richcmp_ge,
5527 "x.__ge__(y) <==> x>=y"),
5528 TPSLOT("__iter__", tp_iter, slot_tp_iter, wrap_unaryfunc,
5529 "x.__iter__() <==> iter(x)"),
5530 TPSLOT("__next__", tp_iternext, slot_tp_iternext, wrap_next,
5531 "x.__next__() <==> next(x)"),
5532 TPSLOT("__get__", tp_descr_get, slot_tp_descr_get, wrap_descr_get,
5533 "descr.__get__(obj[, type]) -> value"),
5534 TPSLOT("__set__", tp_descr_set, slot_tp_descr_set, wrap_descr_set,
5535 "descr.__set__(obj, value)"),
5536 TPSLOT("__delete__", tp_descr_set, slot_tp_descr_set,
5537 wrap_descr_delete, "descr.__delete__(obj)"),
5538 FLSLOT("__init__", tp_init, slot_tp_init, (wrapperfunc)wrap_init,
5539 "x.__init__(...) initializes x; "
Alexander Belopolsky102594f2010-08-16 20:26:04 +00005540 "see help(type(x)) for signature",
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00005541 PyWrapperFlag_KEYWORDS),
5542 TPSLOT("__new__", tp_new, slot_tp_new, NULL, ""),
5543 TPSLOT("__del__", tp_del, slot_tp_del, NULL, ""),
5544 {NULL}
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005545};
5546
Guido van Rossumc334df52002-04-04 23:44:47 +00005547/* Given a type pointer and an offset gotten from a slotdef entry, return a
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00005548 pointer to the actual slot. This is not quite the same as simply adding
Guido van Rossumc334df52002-04-04 23:44:47 +00005549 the offset to the type pointer, since it takes care to indirect through the
5550 proper indirection pointer (as_buffer, etc.); it returns NULL if the
5551 indirection pointer is NULL. */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005552static void **
Martin v. Löwis18e16552006-02-15 17:27:45 +00005553slotptr(PyTypeObject *type, int ioffset)
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005554{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00005555 char *ptr;
5556 long offset = ioffset;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005557
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00005558 /* Note: this depends on the order of the members of PyHeapTypeObject! */
5559 assert(offset >= 0);
5560 assert((size_t)offset < offsetof(PyHeapTypeObject, as_buffer));
5561 if ((size_t)offset >= offsetof(PyHeapTypeObject, as_sequence)) {
5562 ptr = (char *)type->tp_as_sequence;
5563 offset -= offsetof(PyHeapTypeObject, as_sequence);
5564 }
5565 else if ((size_t)offset >= offsetof(PyHeapTypeObject, as_mapping)) {
5566 ptr = (char *)type->tp_as_mapping;
5567 offset -= offsetof(PyHeapTypeObject, as_mapping);
5568 }
5569 else if ((size_t)offset >= offsetof(PyHeapTypeObject, as_number)) {
5570 ptr = (char *)type->tp_as_number;
5571 offset -= offsetof(PyHeapTypeObject, as_number);
5572 }
5573 else {
5574 ptr = (char *)type;
5575 }
5576 if (ptr != NULL)
5577 ptr += offset;
5578 return (void **)ptr;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005579}
Guido van Rossumf040ede2001-08-07 16:40:56 +00005580
Guido van Rossumc334df52002-04-04 23:44:47 +00005581/* Length of array of slotdef pointers used to store slots with the
5582 same __name__. There should be at most MAX_EQUIV-1 slotdef entries with
5583 the same __name__, for any __name__. Since that's a static property, it is
5584 appropriate to declare fixed-size arrays for this. */
5585#define MAX_EQUIV 10
5586
5587/* Return a slot pointer for a given name, but ONLY if the attribute has
5588 exactly one slot function. The name must be an interned string. */
5589static void **
5590resolve_slotdups(PyTypeObject *type, PyObject *name)
5591{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00005592 /* XXX Maybe this could be optimized more -- but is it worth it? */
Guido van Rossumc334df52002-04-04 23:44:47 +00005593
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00005594 /* pname and ptrs act as a little cache */
5595 static PyObject *pname;
5596 static slotdef *ptrs[MAX_EQUIV];
5597 slotdef *p, **pp;
5598 void **res, **ptr;
Guido van Rossumc334df52002-04-04 23:44:47 +00005599
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00005600 if (pname != name) {
5601 /* Collect all slotdefs that match name into ptrs. */
5602 pname = name;
5603 pp = ptrs;
5604 for (p = slotdefs; p->name_strobj; p++) {
5605 if (p->name_strobj == name)
5606 *pp++ = p;
5607 }
5608 *pp = NULL;
5609 }
Guido van Rossumc334df52002-04-04 23:44:47 +00005610
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00005611 /* Look in all matching slots of the type; if exactly one of these has
5612 a filled-in slot, return its value. Otherwise return NULL. */
5613 res = NULL;
5614 for (pp = ptrs; *pp; pp++) {
5615 ptr = slotptr(type, (*pp)->offset);
5616 if (ptr == NULL || *ptr == NULL)
5617 continue;
5618 if (res != NULL)
5619 return NULL;
5620 res = ptr;
5621 }
5622 return res;
Guido van Rossumc334df52002-04-04 23:44:47 +00005623}
5624
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005625/* Common code for update_slots_callback() and fixup_slot_dispatchers(). This
Guido van Rossumc334df52002-04-04 23:44:47 +00005626 does some incredibly complex thinking and then sticks something into the
5627 slot. (It sees if the adjacent slotdefs for the same slot have conflicting
5628 interests, and then stores a generic wrapper or a specific function into
5629 the slot.) Return a pointer to the next slotdef with a different offset,
5630 because that's convenient for fixup_slot_dispatchers(). */
5631static slotdef *
5632update_one_slot(PyTypeObject *type, slotdef *p)
5633{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00005634 PyObject *descr;
5635 PyWrapperDescrObject *d;
5636 void *generic = NULL, *specific = NULL;
5637 int use_generic = 0;
5638 int offset = p->offset;
5639 void **ptr = slotptr(type, offset);
Guido van Rossumc334df52002-04-04 23:44:47 +00005640
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00005641 if (ptr == NULL) {
5642 do {
5643 ++p;
5644 } while (p->offset == offset);
5645 return p;
5646 }
5647 do {
5648 descr = _PyType_Lookup(type, p->name_strobj);
5649 if (descr == NULL) {
5650 if (ptr == (void**)&type->tp_iternext) {
5651 specific = _PyObject_NextNotImplemented;
5652 }
5653 continue;
5654 }
5655 if (Py_TYPE(descr) == &PyWrapperDescr_Type) {
5656 void **tptr = resolve_slotdups(type, p->name_strobj);
5657 if (tptr == NULL || tptr == ptr)
5658 generic = p->function;
5659 d = (PyWrapperDescrObject *)descr;
5660 if (d->d_base->wrapper == p->wrapper &&
5661 PyType_IsSubtype(type, d->d_type))
5662 {
5663 if (specific == NULL ||
5664 specific == d->d_wrapped)
5665 specific = d->d_wrapped;
5666 else
5667 use_generic = 1;
5668 }
5669 }
5670 else if (Py_TYPE(descr) == &PyCFunction_Type &&
5671 PyCFunction_GET_FUNCTION(descr) ==
5672 (PyCFunction)tp_new_wrapper &&
5673 ptr == (void**)&type->tp_new)
5674 {
5675 /* The __new__ wrapper is not a wrapper descriptor,
5676 so must be special-cased differently.
5677 If we don't do this, creating an instance will
5678 always use slot_tp_new which will look up
5679 __new__ in the MRO which will call tp_new_wrapper
5680 which will look through the base classes looking
5681 for a static base and call its tp_new (usually
5682 PyType_GenericNew), after performing various
5683 sanity checks and constructing a new argument
5684 list. Cut all that nonsense short -- this speeds
5685 up instance creation tremendously. */
5686 specific = (void *)type->tp_new;
5687 /* XXX I'm not 100% sure that there isn't a hole
5688 in this reasoning that requires additional
5689 sanity checks. I'll buy the first person to
5690 point out a bug in this reasoning a beer. */
5691 }
5692 else if (descr == Py_None &&
5693 ptr == (void**)&type->tp_hash) {
5694 /* We specifically allow __hash__ to be set to None
5695 to prevent inheritance of the default
5696 implementation from object.__hash__ */
5697 specific = PyObject_HashNotImplemented;
5698 }
5699 else {
5700 use_generic = 1;
5701 generic = p->function;
5702 }
5703 } while ((++p)->offset == offset);
5704 if (specific && !use_generic)
5705 *ptr = specific;
5706 else
5707 *ptr = generic;
5708 return p;
Guido van Rossumc334df52002-04-04 23:44:47 +00005709}
5710
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005711/* In the type, update the slots whose slotdefs are gathered in the pp array.
5712 This is a callback for update_subclasses(). */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005713static int
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005714update_slots_callback(PyTypeObject *type, void *data)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005715{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00005716 slotdef **pp = (slotdef **)data;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005717
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00005718 for (; *pp; pp++)
5719 update_one_slot(type, *pp);
5720 return 0;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005721}
5722
Guido van Rossumc334df52002-04-04 23:44:47 +00005723/* Comparison function for qsort() to compare slotdefs by their offset, and
5724 for equal offset by their address (to force a stable sort). */
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005725static int
5726slotdef_cmp(const void *aa, const void *bb)
5727{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00005728 const slotdef *a = (const slotdef *)aa, *b = (const slotdef *)bb;
5729 int c = a->offset - b->offset;
5730 if (c != 0)
5731 return c;
5732 else
5733 /* Cannot use a-b, as this gives off_t,
5734 which may lose precision when converted to int. */
5735 return (a > b) ? 1 : (a < b) ? -1 : 0;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005736}
5737
Guido van Rossumc334df52002-04-04 23:44:47 +00005738/* Initialize the slotdefs table by adding interned string objects for the
5739 names and sorting the entries. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005740static void
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005741init_slotdefs(void)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005742{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00005743 slotdef *p;
5744 static int initialized = 0;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005745
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00005746 if (initialized)
5747 return;
5748 for (p = slotdefs; p->name; p++) {
5749 p->name_strobj = PyUnicode_InternFromString(p->name);
5750 if (!p->name_strobj)
5751 Py_FatalError("Out of memory interning slotdef names");
5752 }
5753 qsort((void *)slotdefs, (size_t)(p-slotdefs), sizeof(slotdef),
5754 slotdef_cmp);
5755 initialized = 1;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005756}
5757
Guido van Rossumc334df52002-04-04 23:44:47 +00005758/* Update the slots after assignment to a class (type) attribute. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005759static int
5760update_slot(PyTypeObject *type, PyObject *name)
5761{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00005762 slotdef *ptrs[MAX_EQUIV];
5763 slotdef *p;
5764 slotdef **pp;
5765 int offset;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005766
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00005767 /* Clear the VALID_VERSION flag of 'type' and all its
5768 subclasses. This could possibly be unified with the
5769 update_subclasses() recursion below, but carefully:
5770 they each have their own conditions on which to stop
5771 recursing into subclasses. */
5772 PyType_Modified(type);
Christian Heimesa62da1d2008-01-12 19:39:10 +00005773
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00005774 init_slotdefs();
5775 pp = ptrs;
5776 for (p = slotdefs; p->name; p++) {
5777 /* XXX assume name is interned! */
5778 if (p->name_strobj == name)
5779 *pp++ = p;
5780 }
5781 *pp = NULL;
5782 for (pp = ptrs; *pp; pp++) {
5783 p = *pp;
5784 offset = p->offset;
5785 while (p > slotdefs && (p-1)->offset == offset)
5786 --p;
5787 *pp = p;
5788 }
5789 if (ptrs[0] == NULL)
5790 return 0; /* Not an attribute that affects any slots */
5791 return update_subclasses(type, name,
5792 update_slots_callback, (void *)ptrs);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005793}
5794
Guido van Rossumc334df52002-04-04 23:44:47 +00005795/* Store the proper functions in the slot dispatches at class (type)
5796 definition time, based upon which operations the class overrides in its
5797 dict. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00005798static void
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005799fixup_slot_dispatchers(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005800{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00005801 slotdef *p;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005802
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00005803 init_slotdefs();
5804 for (p = slotdefs; p->name; )
5805 p = update_one_slot(type, p);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005806}
Guido van Rossum705f0f52001-08-24 16:47:00 +00005807
Michael W. Hudson98bbc492002-11-26 14:47:27 +00005808static void
5809update_all_slots(PyTypeObject* type)
5810{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00005811 slotdef *p;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00005812
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00005813 init_slotdefs();
5814 for (p = slotdefs; p->name; p++) {
5815 /* update_slot returns int but can't actually fail */
5816 update_slot(type, p->name_strobj);
5817 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +00005818}
5819
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005820/* recurse_down_subclasses() and update_subclasses() are mutually
5821 recursive functions to call a callback for all subclasses,
5822 but refraining from recursing into subclasses that define 'name'. */
5823
5824static int
5825update_subclasses(PyTypeObject *type, PyObject *name,
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00005826 update_callback callback, void *data)
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005827{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00005828 if (callback(type, data) < 0)
5829 return -1;
5830 return recurse_down_subclasses(type, name, callback, data);
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005831}
5832
5833static int
5834recurse_down_subclasses(PyTypeObject *type, PyObject *name,
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00005835 update_callback callback, void *data)
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005836{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00005837 PyTypeObject *subclass;
5838 PyObject *ref, *subclasses, *dict;
5839 Py_ssize_t i, n;
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005840
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00005841 subclasses = type->tp_subclasses;
5842 if (subclasses == NULL)
5843 return 0;
5844 assert(PyList_Check(subclasses));
5845 n = PyList_GET_SIZE(subclasses);
5846 for (i = 0; i < n; i++) {
5847 ref = PyList_GET_ITEM(subclasses, i);
5848 assert(PyWeakref_CheckRef(ref));
5849 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
5850 assert(subclass != NULL);
5851 if ((PyObject *)subclass == Py_None)
5852 continue;
5853 assert(PyType_Check(subclass));
5854 /* Avoid recursing down into unaffected classes */
5855 dict = subclass->tp_dict;
5856 if (dict != NULL && PyDict_Check(dict) &&
5857 PyDict_GetItem(dict, name) != NULL)
5858 continue;
5859 if (update_subclasses(subclass, name, callback, data) < 0)
5860 return -1;
5861 }
5862 return 0;
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005863}
5864
Guido van Rossum6d204072001-10-21 00:44:31 +00005865/* This function is called by PyType_Ready() to populate the type's
5866 dictionary with method descriptors for function slots. For each
Guido van Rossum09638c12002-06-13 19:17:46 +00005867 function slot (like tp_repr) that's defined in the type, one or more
5868 corresponding descriptors are added in the type's tp_dict dictionary
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00005869 under the appropriate name (like __repr__). Some function slots
Guido van Rossum09638c12002-06-13 19:17:46 +00005870 cause more than one descriptor to be added (for example, the nb_add
5871 slot adds both __add__ and __radd__ descriptors) and some function
5872 slots compete for the same descriptor (for example both sq_item and
5873 mp_subscript generate a __getitem__ descriptor).
5874
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00005875 In the latter case, the first slotdef entry encoutered wins. Since
Tim Petersbf9b2442003-03-23 05:35:36 +00005876 slotdef entries are sorted by the offset of the slot in the
Guido van Rossume5c691a2003-03-07 15:13:17 +00005877 PyHeapTypeObject, this gives us some control over disambiguating
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005878 between competing slots: the members of PyHeapTypeObject are listed
5879 from most general to least general, so the most general slot is
5880 preferred. In particular, because as_mapping comes before as_sequence,
5881 for a type that defines both mp_subscript and sq_item, mp_subscript
5882 wins.
Guido van Rossum09638c12002-06-13 19:17:46 +00005883
5884 This only adds new descriptors and doesn't overwrite entries in
5885 tp_dict that were previously defined. The descriptors contain a
5886 reference to the C function they must call, so that it's safe if they
5887 are copied into a subtype's __dict__ and the subtype has a different
5888 C function in its slot -- calling the method defined by the
5889 descriptor will call the C function that was used to create it,
5890 rather than the C function present in the slot when it is called.
5891 (This is important because a subtype may have a C function in the
5892 slot that calls the method from the dictionary, and we want to avoid
5893 infinite recursion here.) */
Guido van Rossum6d204072001-10-21 00:44:31 +00005894
5895static int
5896add_operators(PyTypeObject *type)
5897{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00005898 PyObject *dict = type->tp_dict;
5899 slotdef *p;
5900 PyObject *descr;
5901 void **ptr;
Guido van Rossum6d204072001-10-21 00:44:31 +00005902
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00005903 init_slotdefs();
5904 for (p = slotdefs; p->name; p++) {
5905 if (p->wrapper == NULL)
5906 continue;
5907 ptr = slotptr(type, p->offset);
5908 if (!ptr || !*ptr)
5909 continue;
5910 if (PyDict_GetItem(dict, p->name_strobj))
5911 continue;
5912 if (*ptr == PyObject_HashNotImplemented) {
5913 /* Classes may prevent the inheritance of the tp_hash
5914 slot by storing PyObject_HashNotImplemented in it. Make it
5915 visible as a None value for the __hash__ attribute. */
5916 if (PyDict_SetItem(dict, p->name_strobj, Py_None) < 0)
5917 return -1;
5918 }
5919 else {
5920 descr = PyDescr_NewWrapper(type, p, *ptr);
5921 if (descr == NULL)
5922 return -1;
5923 if (PyDict_SetItem(dict, p->name_strobj, descr) < 0)
5924 return -1;
5925 Py_DECREF(descr);
5926 }
5927 }
5928 if (type->tp_new != NULL) {
5929 if (add_tp_new_wrapper(type) < 0)
5930 return -1;
5931 }
5932 return 0;
Guido van Rossum6d204072001-10-21 00:44:31 +00005933}
5934
Guido van Rossum705f0f52001-08-24 16:47:00 +00005935
5936/* Cooperative 'super' */
5937
5938typedef struct {
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00005939 PyObject_HEAD
5940 PyTypeObject *type;
5941 PyObject *obj;
5942 PyTypeObject *obj_type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005943} superobject;
5944
Guido van Rossum6f799372001-09-20 20:46:19 +00005945static PyMemberDef super_members[] = {
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00005946 {"__thisclass__", T_OBJECT, offsetof(superobject, type), READONLY,
5947 "the class invoking super()"},
5948 {"__self__", T_OBJECT, offsetof(superobject, obj), READONLY,
5949 "the instance invoking super(); may be None"},
5950 {"__self_class__", T_OBJECT, offsetof(superobject, obj_type), READONLY,
5951 "the type of the instance invoking super(); may be None"},
5952 {0}
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005953};
5954
Guido van Rossum705f0f52001-08-24 16:47:00 +00005955static void
5956super_dealloc(PyObject *self)
5957{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00005958 superobject *su = (superobject *)self;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005959
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00005960 _PyObject_GC_UNTRACK(self);
5961 Py_XDECREF(su->obj);
5962 Py_XDECREF(su->type);
5963 Py_XDECREF(su->obj_type);
5964 Py_TYPE(self)->tp_free(self);
Guido van Rossum705f0f52001-08-24 16:47:00 +00005965}
5966
5967static PyObject *
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005968super_repr(PyObject *self)
5969{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00005970 superobject *su = (superobject *)self;
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005971
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00005972 if (su->obj_type)
5973 return PyUnicode_FromFormat(
5974 "<super: <class '%s'>, <%s object>>",
5975 su->type ? su->type->tp_name : "NULL",
5976 su->obj_type->tp_name);
5977 else
5978 return PyUnicode_FromFormat(
5979 "<super: <class '%s'>, NULL>",
5980 su->type ? su->type->tp_name : "NULL");
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005981}
5982
5983static PyObject *
Guido van Rossum705f0f52001-08-24 16:47:00 +00005984super_getattro(PyObject *self, PyObject *name)
5985{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00005986 superobject *su = (superobject *)self;
5987 int skip = su->obj_type == NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005988
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00005989 if (!skip) {
5990 /* We want __class__ to return the class of the super object
5991 (i.e. super, or a subclass), not the class of su->obj. */
5992 skip = (PyUnicode_Check(name) &&
5993 PyUnicode_GET_SIZE(name) == 9 &&
5994 PyUnicode_CompareWithASCIIString(name, "__class__") == 0);
5995 }
Guido van Rossum76ba09f2003-04-16 19:40:58 +00005996
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00005997 if (!skip) {
5998 PyObject *mro, *res, *tmp, *dict;
5999 PyTypeObject *starttype;
6000 descrgetfunc f;
6001 Py_ssize_t i, n;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006002
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00006003 starttype = su->obj_type;
6004 mro = starttype->tp_mro;
Guido van Rossum155db9a2002-04-02 17:53:47 +00006005
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00006006 if (mro == NULL)
6007 n = 0;
6008 else {
6009 assert(PyTuple_Check(mro));
6010 n = PyTuple_GET_SIZE(mro);
6011 }
6012 for (i = 0; i < n; i++) {
6013 if ((PyObject *)(su->type) == PyTuple_GET_ITEM(mro, i))
6014 break;
6015 }
6016 i++;
6017 res = NULL;
6018 for (; i < n; i++) {
6019 tmp = PyTuple_GET_ITEM(mro, i);
6020 if (PyType_Check(tmp))
6021 dict = ((PyTypeObject *)tmp)->tp_dict;
6022 else
6023 continue;
6024 res = PyDict_GetItem(dict, name);
6025 if (res != NULL) {
6026 Py_INCREF(res);
6027 f = Py_TYPE(res)->tp_descr_get;
6028 if (f != NULL) {
6029 tmp = f(res,
6030 /* Only pass 'obj' param if
6031 this is instance-mode super
6032 (See SF ID #743627)
6033 */
6034 (su->obj == (PyObject *)
6035 su->obj_type
6036 ? (PyObject *)NULL
6037 : su->obj),
6038 (PyObject *)starttype);
6039 Py_DECREF(res);
6040 res = tmp;
6041 }
6042 return res;
6043 }
6044 }
6045 }
6046 return PyObject_GenericGetAttr(self, name);
Guido van Rossum705f0f52001-08-24 16:47:00 +00006047}
6048
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006049static PyTypeObject *
Guido van Rossum5b443c62001-12-03 15:38:28 +00006050supercheck(PyTypeObject *type, PyObject *obj)
6051{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00006052 /* Check that a super() call makes sense. Return a type object.
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006053
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00006054 obj can be a new-style class, or an instance of one:
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006055
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00006056 - If it is a class, it must be a subclass of 'type'. This case is
6057 used for class methods; the return value is obj.
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006058
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00006059 - If it is an instance, it must be an instance of 'type'. This is
6060 the normal case; the return value is obj.__class__.
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006061
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00006062 But... when obj is an instance, we want to allow for the case where
6063 Py_TYPE(obj) is not a subclass of type, but obj.__class__ is!
6064 This will allow using super() with a proxy for obj.
6065 */
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006066
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00006067 /* Check for first bullet above (special case) */
6068 if (PyType_Check(obj) && PyType_IsSubtype((PyTypeObject *)obj, type)) {
6069 Py_INCREF(obj);
6070 return (PyTypeObject *)obj;
6071 }
Guido van Rossum8e80a722003-02-18 19:22:22 +00006072
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00006073 /* Normal case */
6074 if (PyType_IsSubtype(Py_TYPE(obj), type)) {
6075 Py_INCREF(Py_TYPE(obj));
6076 return Py_TYPE(obj);
6077 }
6078 else {
6079 /* Try the slow way */
6080 static PyObject *class_str = NULL;
6081 PyObject *class_attr;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006082
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00006083 if (class_str == NULL) {
6084 class_str = PyUnicode_FromString("__class__");
6085 if (class_str == NULL)
6086 return NULL;
6087 }
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006088
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00006089 class_attr = PyObject_GetAttr(obj, class_str);
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006090
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00006091 if (class_attr != NULL &&
6092 PyType_Check(class_attr) &&
6093 (PyTypeObject *)class_attr != Py_TYPE(obj))
6094 {
6095 int ok = PyType_IsSubtype(
6096 (PyTypeObject *)class_attr, type);
6097 if (ok)
6098 return (PyTypeObject *)class_attr;
6099 }
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006100
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00006101 if (class_attr == NULL)
6102 PyErr_Clear();
6103 else
6104 Py_DECREF(class_attr);
6105 }
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006106
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00006107 PyErr_SetString(PyExc_TypeError,
6108 "super(type, obj): "
6109 "obj must be an instance or subtype of type");
6110 return NULL;
Guido van Rossum5b443c62001-12-03 15:38:28 +00006111}
6112
Guido van Rossum705f0f52001-08-24 16:47:00 +00006113static PyObject *
6114super_descr_get(PyObject *self, PyObject *obj, PyObject *type)
6115{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00006116 superobject *su = (superobject *)self;
6117 superobject *newobj;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006118
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00006119 if (obj == NULL || obj == Py_None || su->obj != NULL) {
6120 /* Not binding to an object, or already bound */
6121 Py_INCREF(self);
6122 return self;
6123 }
6124 if (Py_TYPE(su) != &PySuper_Type)
6125 /* If su is an instance of a (strict) subclass of super,
6126 call its type */
6127 return PyObject_CallFunctionObjArgs((PyObject *)Py_TYPE(su),
6128 su->type, obj, NULL);
6129 else {
6130 /* Inline the common case */
6131 PyTypeObject *obj_type = supercheck(su->type, obj);
6132 if (obj_type == NULL)
6133 return NULL;
6134 newobj = (superobject *)PySuper_Type.tp_new(&PySuper_Type,
6135 NULL, NULL);
6136 if (newobj == NULL)
6137 return NULL;
6138 Py_INCREF(su->type);
6139 Py_INCREF(obj);
6140 newobj->type = su->type;
6141 newobj->obj = obj;
6142 newobj->obj_type = obj_type;
6143 return (PyObject *)newobj;
6144 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00006145}
6146
6147static int
6148super_init(PyObject *self, PyObject *args, PyObject *kwds)
6149{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00006150 superobject *su = (superobject *)self;
6151 PyTypeObject *type = NULL;
6152 PyObject *obj = NULL;
6153 PyTypeObject *obj_type = NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006154
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00006155 if (!_PyArg_NoKeywords("super", kwds))
6156 return -1;
6157 if (!PyArg_ParseTuple(args, "|O!O:super", &PyType_Type, &type, &obj))
6158 return -1;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00006159
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00006160 if (type == NULL) {
6161 /* Call super(), without args -- fill in from __class__
6162 and first local variable on the stack. */
6163 PyFrameObject *f = PyThreadState_GET()->frame;
6164 PyCodeObject *co = f->f_code;
6165 int i, n;
6166 if (co == NULL) {
6167 PyErr_SetString(PyExc_SystemError,
6168 "super(): no code object");
6169 return -1;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00006170 }
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00006171 if (co->co_argcount == 0) {
6172 PyErr_SetString(PyExc_SystemError,
6173 "super(): no arguments");
6174 return -1;
6175 }
6176 obj = f->f_localsplus[0];
6177 if (obj == NULL) {
6178 PyErr_SetString(PyExc_SystemError,
6179 "super(): arg[0] deleted");
6180 return -1;
6181 }
6182 if (co->co_freevars == NULL)
6183 n = 0;
6184 else {
6185 assert(PyTuple_Check(co->co_freevars));
6186 n = PyTuple_GET_SIZE(co->co_freevars);
6187 }
6188 for (i = 0; i < n; i++) {
6189 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
6190 assert(PyUnicode_Check(name));
6191 if (!PyUnicode_CompareWithASCIIString(name,
6192 "__class__")) {
6193 Py_ssize_t index = co->co_nlocals +
6194 PyTuple_GET_SIZE(co->co_cellvars) + i;
6195 PyObject *cell = f->f_localsplus[index];
6196 if (cell == NULL || !PyCell_Check(cell)) {
6197 PyErr_SetString(PyExc_SystemError,
6198 "super(): bad __class__ cell");
6199 return -1;
6200 }
6201 type = (PyTypeObject *) PyCell_GET(cell);
6202 if (type == NULL) {
6203 PyErr_SetString(PyExc_SystemError,
6204 "super(): empty __class__ cell");
6205 return -1;
6206 }
6207 if (!PyType_Check(type)) {
6208 PyErr_Format(PyExc_SystemError,
6209 "super(): __class__ is not a type (%s)",
6210 Py_TYPE(type)->tp_name);
6211 return -1;
6212 }
6213 break;
6214 }
6215 }
6216 if (type == NULL) {
6217 PyErr_SetString(PyExc_SystemError,
6218 "super(): __class__ cell not found");
6219 return -1;
6220 }
6221 }
Guido van Rossumcd16bf62007-06-13 18:07:49 +00006222
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00006223 if (obj == Py_None)
6224 obj = NULL;
6225 if (obj != NULL) {
6226 obj_type = supercheck(type, obj);
6227 if (obj_type == NULL)
6228 return -1;
6229 Py_INCREF(obj);
6230 }
6231 Py_INCREF(type);
6232 su->type = type;
6233 su->obj = obj;
6234 su->obj_type = obj_type;
6235 return 0;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006236}
6237
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00006238PyDoc_STRVAR(super_doc,
Guido van Rossumcd16bf62007-06-13 18:07:49 +00006239"super() -> same as super(__class__, <first argument>)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00006240"super(type) -> unbound super object\n"
6241"super(type, obj) -> bound super object; requires isinstance(obj, type)\n"
Guido van Rossume705ef12001-08-29 15:47:06 +00006242"super(type, type2) -> bound super object; requires issubclass(type2, type)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00006243"Typical use to call a cooperative superclass method:\n"
6244"class C(B):\n"
6245" def meth(self, arg):\n"
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00006246" super().meth(arg)\n"
Guido van Rossumcd16bf62007-06-13 18:07:49 +00006247"This works for class methods too:\n"
6248"class C(B):\n"
6249" @classmethod\n"
6250" def cmeth(cls, arg):\n"
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00006251" super().cmeth(arg)\n");
Guido van Rossum705f0f52001-08-24 16:47:00 +00006252
Guido van Rossum048eb752001-10-02 21:24:57 +00006253static int
6254super_traverse(PyObject *self, visitproc visit, void *arg)
6255{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00006256 superobject *su = (superobject *)self;
Guido van Rossum048eb752001-10-02 21:24:57 +00006257
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00006258 Py_VISIT(su->obj);
6259 Py_VISIT(su->type);
6260 Py_VISIT(su->obj_type);
Guido van Rossum048eb752001-10-02 21:24:57 +00006261
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00006262 return 0;
Guido van Rossum048eb752001-10-02 21:24:57 +00006263}
6264
Guido van Rossum705f0f52001-08-24 16:47:00 +00006265PyTypeObject PySuper_Type = {
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00006266 PyVarObject_HEAD_INIT(&PyType_Type, 0)
6267 "super", /* tp_name */
6268 sizeof(superobject), /* tp_basicsize */
6269 0, /* tp_itemsize */
6270 /* methods */
6271 super_dealloc, /* tp_dealloc */
6272 0, /* tp_print */
6273 0, /* tp_getattr */
6274 0, /* tp_setattr */
6275 0, /* tp_reserved */
6276 super_repr, /* tp_repr */
6277 0, /* tp_as_number */
6278 0, /* tp_as_sequence */
6279 0, /* tp_as_mapping */
6280 0, /* tp_hash */
6281 0, /* tp_call */
6282 0, /* tp_str */
6283 super_getattro, /* tp_getattro */
6284 0, /* tp_setattro */
6285 0, /* tp_as_buffer */
6286 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
6287 Py_TPFLAGS_BASETYPE, /* tp_flags */
6288 super_doc, /* tp_doc */
6289 super_traverse, /* tp_traverse */
6290 0, /* tp_clear */
6291 0, /* tp_richcompare */
6292 0, /* tp_weaklistoffset */
6293 0, /* tp_iter */
6294 0, /* tp_iternext */
6295 0, /* tp_methods */
6296 super_members, /* tp_members */
6297 0, /* tp_getset */
6298 0, /* tp_base */
6299 0, /* tp_dict */
6300 super_descr_get, /* tp_descr_get */
6301 0, /* tp_descr_set */
6302 0, /* tp_dictoffset */
6303 super_init, /* tp_init */
6304 PyType_GenericAlloc, /* tp_alloc */
6305 PyType_GenericNew, /* tp_new */
6306 PyObject_GC_Del, /* tp_free */
Guido van Rossum705f0f52001-08-24 16:47:00 +00006307};