blob: f311af8f25bb93ea8276344c5b6806fa6aa2d077 [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
Antoine Pitrou957a23b2013-05-04 20:45:02 +020010/* Cached lookup of the copyreg module, for faster __reduce__ calls */
11
12static PyObject *cached_copyreg_module = NULL;
13
Christian Heimesa62da1d2008-01-12 19:39:10 +000014/* Support type attribute cache */
15
16/* The cache can keep references to the names alive for longer than
17 they normally would. This is why the maximum size is limited to
18 MCACHE_MAX_ATTR_SIZE, since it might be a problem if very large
19 strings are used as attribute names. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000020#define MCACHE_MAX_ATTR_SIZE 100
Benjamin Peterson7d95e402012-04-23 11:24:50 -040021#define MCACHE_SIZE_EXP 9
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000022#define MCACHE_HASH(version, name_hash) \
23 (((unsigned int)(version) * (unsigned int)(name_hash)) \
24 >> (8*sizeof(unsigned int) - MCACHE_SIZE_EXP))
Christian Heimesa62da1d2008-01-12 19:39:10 +000025#define MCACHE_HASH_METHOD(type, name) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000026 MCACHE_HASH((type)->tp_version_tag, \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020027 ((PyASCIIObject *)(name))->hash)
Christian Heimesa62da1d2008-01-12 19:39:10 +000028#define MCACHE_CACHEABLE_NAME(name) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000029 PyUnicode_CheckExact(name) && \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020030 PyUnicode_READY(name) != -1 && \
31 PyUnicode_GET_LENGTH(name) <= MCACHE_MAX_ATTR_SIZE
Christian Heimesa62da1d2008-01-12 19:39:10 +000032
33struct method_cache_entry {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000034 unsigned int version;
35 PyObject *name; /* reference to exactly a str or None */
36 PyObject *value; /* borrowed */
Christian Heimesa62da1d2008-01-12 19:39:10 +000037};
38
39static struct method_cache_entry method_cache[1 << MCACHE_SIZE_EXP];
40static unsigned int next_version_tag = 0;
Christian Heimes26855632008-01-27 23:50:43 +000041
Martin v. Löwisbd928fe2011-10-14 10:20:37 +020042_Py_IDENTIFIER(__class__);
Victor Stinner3c1e4812012-03-26 22:10:51 +020043_Py_IDENTIFIER(__dict__);
44_Py_IDENTIFIER(__doc__);
45_Py_IDENTIFIER(__getitem__);
46_Py_IDENTIFIER(__getattribute__);
47_Py_IDENTIFIER(__hash__);
48_Py_IDENTIFIER(__module__);
49_Py_IDENTIFIER(__name__);
50_Py_IDENTIFIER(__new__);
51
52static PyObject *
53_PyType_LookupId(PyTypeObject *type, struct _Py_Identifier *name);
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +020054
Martin v. Löwis9c564092012-06-23 23:20:45 +020055static PyObject *
56slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
57
Christian Heimes26855632008-01-27 23:50:43 +000058unsigned int
59PyType_ClearCache(void)
60{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000061 Py_ssize_t i;
62 unsigned int cur_version_tag = next_version_tag - 1;
63
64 for (i = 0; i < (1 << MCACHE_SIZE_EXP); i++) {
65 method_cache[i].version = 0;
66 Py_CLEAR(method_cache[i].name);
67 method_cache[i].value = NULL;
68 }
69 next_version_tag = 0;
70 /* mark all version tags as invalid */
71 PyType_Modified(&PyBaseObject_Type);
72 return cur_version_tag;
Christian Heimes26855632008-01-27 23:50:43 +000073}
Christian Heimesa62da1d2008-01-12 19:39:10 +000074
Georg Brandlf08a9dd2008-06-10 16:57:31 +000075void
Antoine Pitrou957a23b2013-05-04 20:45:02 +020076_PyType_Fini(void)
77{
78 PyType_ClearCache();
79 /* Need to forget our obsolete instance of the copyreg module at
80 * interpreter shutdown (issue #17408). */
81 Py_CLEAR(cached_copyreg_module);
82}
83
84void
Georg Brandlf08a9dd2008-06-10 16:57:31 +000085PyType_Modified(PyTypeObject *type)
Christian Heimesa62da1d2008-01-12 19:39:10 +000086{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000087 /* Invalidate any cached data for the specified type and all
88 subclasses. This function is called after the base
89 classes, mro, or attributes of the type are altered.
Christian Heimesa62da1d2008-01-12 19:39:10 +000090
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000091 Invariants:
Christian Heimesa62da1d2008-01-12 19:39:10 +000092
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000093 - Py_TPFLAGS_VALID_VERSION_TAG is never set if
94 Py_TPFLAGS_HAVE_VERSION_TAG is not set (e.g. on type
95 objects coming from non-recompiled extension modules)
Christian Heimesa62da1d2008-01-12 19:39:10 +000096
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000097 - before Py_TPFLAGS_VALID_VERSION_TAG can be set on a type,
98 it must first be set on all super types.
Christian Heimesa62da1d2008-01-12 19:39:10 +000099
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000100 This function clears the Py_TPFLAGS_VALID_VERSION_TAG of a
101 type (so it must first clear it on all subclasses). The
102 tp_version_tag value is meaningless unless this flag is set.
103 We don't assign new version tags eagerly, but only as
104 needed.
105 */
106 PyObject *raw, *ref;
107 Py_ssize_t i, n;
Christian Heimesa62da1d2008-01-12 19:39:10 +0000108
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000109 if (!PyType_HasFeature(type, Py_TPFLAGS_VALID_VERSION_TAG))
110 return;
Christian Heimesa62da1d2008-01-12 19:39:10 +0000111
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000112 raw = type->tp_subclasses;
113 if (raw != NULL) {
114 n = PyList_GET_SIZE(raw);
115 for (i = 0; i < n; i++) {
116 ref = PyList_GET_ITEM(raw, i);
117 ref = PyWeakref_GET_OBJECT(ref);
118 if (ref != Py_None) {
119 PyType_Modified((PyTypeObject *)ref);
120 }
121 }
122 }
123 type->tp_flags &= ~Py_TPFLAGS_VALID_VERSION_TAG;
Christian Heimesa62da1d2008-01-12 19:39:10 +0000124}
125
126static void
127type_mro_modified(PyTypeObject *type, PyObject *bases) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000128 /*
Florent Xiclunaaa6c1d22011-12-12 18:54:29 +0100129 Check that all base classes or elements of the MRO of type are
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000130 able to be cached. This function is called after the base
131 classes or mro of the type are altered.
Christian Heimesa62da1d2008-01-12 19:39:10 +0000132
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000133 Unset HAVE_VERSION_TAG and VALID_VERSION_TAG if the type
Florent Xiclunaaa6c1d22011-12-12 18:54:29 +0100134 has a custom MRO that includes a type which is not officially
135 super type.
Christian Heimesa62da1d2008-01-12 19:39:10 +0000136
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000137 Called from mro_internal, which will subsequently be called on
138 each subclass when their mro is recursively updated.
139 */
140 Py_ssize_t i, n;
141 int clear = 0;
Christian Heimesa62da1d2008-01-12 19:39:10 +0000142
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000143 if (!PyType_HasFeature(type, Py_TPFLAGS_HAVE_VERSION_TAG))
144 return;
Christian Heimesa62da1d2008-01-12 19:39:10 +0000145
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000146 n = PyTuple_GET_SIZE(bases);
147 for (i = 0; i < n; i++) {
148 PyObject *b = PyTuple_GET_ITEM(bases, i);
149 PyTypeObject *cls;
Christian Heimesa62da1d2008-01-12 19:39:10 +0000150
Florent Xiclunaaa6c1d22011-12-12 18:54:29 +0100151 assert(PyType_Check(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000152 cls = (PyTypeObject *)b;
Christian Heimesa62da1d2008-01-12 19:39:10 +0000153
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000154 if (!PyType_HasFeature(cls, Py_TPFLAGS_HAVE_VERSION_TAG) ||
155 !PyType_IsSubtype(type, cls)) {
156 clear = 1;
157 break;
158 }
159 }
Christian Heimesa62da1d2008-01-12 19:39:10 +0000160
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000161 if (clear)
162 type->tp_flags &= ~(Py_TPFLAGS_HAVE_VERSION_TAG|
163 Py_TPFLAGS_VALID_VERSION_TAG);
Christian Heimesa62da1d2008-01-12 19:39:10 +0000164}
165
166static int
167assign_version_tag(PyTypeObject *type)
168{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000169 /* Ensure that the tp_version_tag is valid and set
170 Py_TPFLAGS_VALID_VERSION_TAG. To respect the invariant, this
171 must first be done on all super classes. Return 0 if this
172 cannot be done, 1 if Py_TPFLAGS_VALID_VERSION_TAG.
173 */
174 Py_ssize_t i, n;
175 PyObject *bases;
Christian Heimesa62da1d2008-01-12 19:39:10 +0000176
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000177 if (PyType_HasFeature(type, Py_TPFLAGS_VALID_VERSION_TAG))
178 return 1;
179 if (!PyType_HasFeature(type, Py_TPFLAGS_HAVE_VERSION_TAG))
180 return 0;
181 if (!PyType_HasFeature(type, Py_TPFLAGS_READY))
182 return 0;
Christian Heimesa62da1d2008-01-12 19:39:10 +0000183
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000184 type->tp_version_tag = next_version_tag++;
185 /* for stress-testing: next_version_tag &= 0xFF; */
Christian Heimesa62da1d2008-01-12 19:39:10 +0000186
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000187 if (type->tp_version_tag == 0) {
188 /* wrap-around or just starting Python - clear the whole
189 cache by filling names with references to Py_None.
190 Values are also set to NULL for added protection, as they
191 are borrowed reference */
192 for (i = 0; i < (1 << MCACHE_SIZE_EXP); i++) {
193 method_cache[i].value = NULL;
194 Py_XDECREF(method_cache[i].name);
195 method_cache[i].name = Py_None;
196 Py_INCREF(Py_None);
197 }
198 /* mark all version tags as invalid */
199 PyType_Modified(&PyBaseObject_Type);
200 return 1;
201 }
202 bases = type->tp_bases;
203 n = PyTuple_GET_SIZE(bases);
204 for (i = 0; i < n; i++) {
205 PyObject *b = PyTuple_GET_ITEM(bases, i);
206 assert(PyType_Check(b));
207 if (!assign_version_tag((PyTypeObject *)b))
208 return 0;
209 }
210 type->tp_flags |= Py_TPFLAGS_VALID_VERSION_TAG;
211 return 1;
Christian Heimesa62da1d2008-01-12 19:39:10 +0000212}
213
214
Guido van Rossum6f799372001-09-20 20:46:19 +0000215static PyMemberDef type_members[] = {
Benjamin Peterson0e102062010-08-25 23:13:17 +0000216 {"__basicsize__", T_PYSSIZET, offsetof(PyTypeObject,tp_basicsize),READONLY},
217 {"__itemsize__", T_PYSSIZET, offsetof(PyTypeObject, tp_itemsize), READONLY},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000218 {"__flags__", T_LONG, offsetof(PyTypeObject, tp_flags), READONLY},
219 {"__weakrefoffset__", T_LONG,
220 offsetof(PyTypeObject, tp_weaklistoffset), READONLY},
221 {"__base__", T_OBJECT, offsetof(PyTypeObject, tp_base), READONLY},
222 {"__dictoffset__", T_LONG,
223 offsetof(PyTypeObject, tp_dictoffset), READONLY},
224 {"__mro__", T_OBJECT, offsetof(PyTypeObject, tp_mro), READONLY},
225 {0}
Tim Peters6d6c1a32001-08-02 04:15:00 +0000226};
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000227
Benjamin Petersond9f23d22011-08-17 11:54:03 -0500228static int
229check_set_special_type_attr(PyTypeObject *type, PyObject *value, const char *name)
230{
231 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
232 PyErr_Format(PyExc_TypeError,
233 "can't set %s.%s", type->tp_name, name);
234 return 0;
235 }
236 if (!value) {
237 PyErr_Format(PyExc_TypeError,
238 "can't delete %s.%s", type->tp_name, name);
239 return 0;
240 }
241 return 1;
242}
243
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000244static PyObject *
Guido van Rossumc3542212001-08-16 09:18:56 +0000245type_name(PyTypeObject *type, void *context)
246{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000247 const char *s;
Guido van Rossumc3542212001-08-16 09:18:56 +0000248
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000249 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
250 PyHeapTypeObject* et = (PyHeapTypeObject*)type;
Tim Petersea7f75d2002-12-07 21:39:16 +0000251
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000252 Py_INCREF(et->ht_name);
253 return et->ht_name;
254 }
255 else {
256 s = strrchr(type->tp_name, '.');
257 if (s == NULL)
258 s = type->tp_name;
259 else
260 s++;
261 return PyUnicode_FromString(s);
262 }
Guido van Rossumc3542212001-08-16 09:18:56 +0000263}
264
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100265static PyObject *
266type_qualname(PyTypeObject *type, void *context)
267{
268 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
269 PyHeapTypeObject* et = (PyHeapTypeObject*)type;
270 Py_INCREF(et->ht_qualname);
271 return et->ht_qualname;
272 }
273 else {
274 return type_name(type, context);
275 }
276}
277
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000278static int
279type_set_name(PyTypeObject *type, PyObject *value, void *context)
280{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000281 PyHeapTypeObject* et;
282 char *tp_name;
283 PyObject *tmp;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000284
Benjamin Petersond9f23d22011-08-17 11:54:03 -0500285 if (!check_set_special_type_attr(type, value, "__name__"))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000286 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000287 if (!PyUnicode_Check(value)) {
288 PyErr_Format(PyExc_TypeError,
289 "can only assign string to %s.__name__, not '%s'",
290 type->tp_name, Py_TYPE(value)->tp_name);
291 return -1;
292 }
Guido van Rossume845c0f2007-11-02 23:07:07 +0000293
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000294 /* Check absence of null characters */
295 tmp = PyUnicode_FromStringAndSize("\0", 1);
296 if (tmp == NULL)
297 return -1;
298 if (PyUnicode_Contains(value, tmp) != 0) {
299 Py_DECREF(tmp);
300 PyErr_Format(PyExc_ValueError,
301 "__name__ must not contain null bytes");
302 return -1;
303 }
304 Py_DECREF(tmp);
Guido van Rossume845c0f2007-11-02 23:07:07 +0000305
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000306 tp_name = _PyUnicode_AsString(value);
307 if (tp_name == NULL)
308 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000309
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000310 et = (PyHeapTypeObject*)type;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000311
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000312 Py_INCREF(value);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000313
Mark Dickinson64aafeb2013-04-13 15:26:58 +0100314 /* Wait until et is a sane state before Py_DECREF'ing the old et->ht_name
315 value. (Bug #16447.) */
316 tmp = et->ht_name;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000317 et->ht_name = value;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000318
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000319 type->tp_name = tp_name;
Mark Dickinson64aafeb2013-04-13 15:26:58 +0100320 Py_DECREF(tmp);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000321
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000322 return 0;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000323}
324
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100325static int
326type_set_qualname(PyTypeObject *type, PyObject *value, void *context)
327{
328 PyHeapTypeObject* et;
329
Benjamin Peterson2c05a2e2012-10-31 00:01:15 -0400330 if (!check_set_special_type_attr(type, value, "__qualname__"))
331 return -1;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100332 if (!PyUnicode_Check(value)) {
333 PyErr_Format(PyExc_TypeError,
334 "can only assign string to %s.__qualname__, not '%s'",
335 type->tp_name, Py_TYPE(value)->tp_name);
336 return -1;
337 }
338
339 et = (PyHeapTypeObject*)type;
340 Py_INCREF(value);
341 Py_DECREF(et->ht_qualname);
342 et->ht_qualname = value;
343 return 0;
344}
345
Guido van Rossumc3542212001-08-16 09:18:56 +0000346static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000347type_module(PyTypeObject *type, void *context)
Guido van Rossum29ca26e1995-01-07 11:58:15 +0000348{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000349 PyObject *mod;
350 char *s;
Guido van Rossumc3542212001-08-16 09:18:56 +0000351
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000352 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
Victor Stinner3c1e4812012-03-26 22:10:51 +0200353 mod = _PyDict_GetItemId(type->tp_dict, &PyId___module__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000354 if (!mod) {
355 PyErr_Format(PyExc_AttributeError, "__module__");
356 return 0;
357 }
358 Py_XINCREF(mod);
359 return mod;
360 }
361 else {
362 s = strrchr(type->tp_name, '.');
363 if (s != NULL)
364 return PyUnicode_FromStringAndSize(
365 type->tp_name, (Py_ssize_t)(s - type->tp_name));
366 return PyUnicode_FromString("builtins");
367 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000368}
369
Guido van Rossum3926a632001-09-25 16:25:58 +0000370static int
371type_set_module(PyTypeObject *type, PyObject *value, void *context)
372{
Benjamin Petersond9f23d22011-08-17 11:54:03 -0500373 if (!check_set_special_type_attr(type, value, "__module__"))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000374 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000375
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000376 PyType_Modified(type);
Christian Heimesa62da1d2008-01-12 19:39:10 +0000377
Victor Stinner3c1e4812012-03-26 22:10:51 +0200378 return _PyDict_SetItemId(type->tp_dict, &PyId___module__, value);
Guido van Rossum3926a632001-09-25 16:25:58 +0000379}
380
Tim Peters6d6c1a32001-08-02 04:15:00 +0000381static PyObject *
Christian Heimes9e7f1d22008-02-28 12:27:11 +0000382type_abstractmethods(PyTypeObject *type, void *context)
383{
Benjamin Petersonaec5fd12010-10-02 00:03:31 +0000384 PyObject *mod = NULL;
Benjamin Peterson84060b82010-10-03 02:13:39 +0000385 /* type itself has an __abstractmethods__ descriptor (this). Don't return
386 that. */
Benjamin Petersonaec5fd12010-10-02 00:03:31 +0000387 if (type != &PyType_Type)
388 mod = PyDict_GetItemString(type->tp_dict, "__abstractmethods__");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000389 if (!mod) {
Benjamin Peterson23b628e2011-01-12 18:56:07 +0000390 PyErr_SetString(PyExc_AttributeError, "__abstractmethods__");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000391 return NULL;
392 }
393 Py_XINCREF(mod);
394 return mod;
Christian Heimes9e7f1d22008-02-28 12:27:11 +0000395}
396
397static int
398type_set_abstractmethods(PyTypeObject *type, PyObject *value, void *context)
399{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000400 /* __abstractmethods__ should only be set once on a type, in
401 abc.ABCMeta.__new__, so this function doesn't do anything
402 special to update subclasses.
403 */
Antoine Pitrou6f430e42012-08-15 23:18:25 +0200404 int abstract, res;
Benjamin Peterson477ba912011-01-12 15:34:01 +0000405 if (value != NULL) {
Antoine Pitrou6f430e42012-08-15 23:18:25 +0200406 abstract = PyObject_IsTrue(value);
407 if (abstract < 0)
408 return -1;
Benjamin Peterson477ba912011-01-12 15:34:01 +0000409 res = PyDict_SetItemString(type->tp_dict, "__abstractmethods__", value);
410 }
411 else {
Antoine Pitrou6f430e42012-08-15 23:18:25 +0200412 abstract = 0;
Benjamin Peterson477ba912011-01-12 15:34:01 +0000413 res = PyDict_DelItemString(type->tp_dict, "__abstractmethods__");
414 if (res && PyErr_ExceptionMatches(PyExc_KeyError)) {
Benjamin Peterson23b628e2011-01-12 18:56:07 +0000415 PyErr_SetString(PyExc_AttributeError, "__abstractmethods__");
Benjamin Peterson477ba912011-01-12 15:34:01 +0000416 return -1;
417 }
418 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000419 if (res == 0) {
420 PyType_Modified(type);
Antoine Pitrou6f430e42012-08-15 23:18:25 +0200421 if (abstract)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000422 type->tp_flags |= Py_TPFLAGS_IS_ABSTRACT;
Antoine Pitrou6f430e42012-08-15 23:18:25 +0200423 else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000424 type->tp_flags &= ~Py_TPFLAGS_IS_ABSTRACT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000425 }
426 return res;
Christian Heimes9e7f1d22008-02-28 12:27:11 +0000427}
428
429static PyObject *
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000430type_get_bases(PyTypeObject *type, void *context)
431{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000432 Py_INCREF(type->tp_bases);
433 return type->tp_bases;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000434}
435
436static PyTypeObject *best_base(PyObject *);
437static int mro_internal(PyTypeObject *);
438static int compatible_for_assignment(PyTypeObject *, PyTypeObject *, char *);
439static int add_subclass(PyTypeObject*, PyTypeObject*);
440static void remove_subclass(PyTypeObject *, PyTypeObject *);
441static void update_all_slots(PyTypeObject *);
442
Guido van Rossum8d24ee92003-03-24 23:49:49 +0000443typedef int (*update_callback)(PyTypeObject *, void *);
444static int update_subclasses(PyTypeObject *type, PyObject *name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000445 update_callback callback, void *data);
Guido van Rossum8d24ee92003-03-24 23:49:49 +0000446static int recurse_down_subclasses(PyTypeObject *type, PyObject *name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000447 update_callback callback, void *data);
Guido van Rossum8d24ee92003-03-24 23:49:49 +0000448
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000449static int
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000450mro_subclasses(PyTypeObject *type, PyObject* temp)
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000451{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000452 PyTypeObject *subclass;
453 PyObject *ref, *subclasses, *old_mro;
454 Py_ssize_t i, n;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000455
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000456 subclasses = type->tp_subclasses;
457 if (subclasses == NULL)
458 return 0;
459 assert(PyList_Check(subclasses));
460 n = PyList_GET_SIZE(subclasses);
461 for (i = 0; i < n; i++) {
462 ref = PyList_GET_ITEM(subclasses, i);
463 assert(PyWeakref_CheckRef(ref));
464 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
465 assert(subclass != NULL);
466 if ((PyObject *)subclass == Py_None)
467 continue;
468 assert(PyType_Check(subclass));
469 old_mro = subclass->tp_mro;
470 if (mro_internal(subclass) < 0) {
471 subclass->tp_mro = old_mro;
472 return -1;
473 }
474 else {
475 PyObject* tuple;
476 tuple = PyTuple_Pack(2, subclass, old_mro);
477 Py_DECREF(old_mro);
478 if (!tuple)
479 return -1;
480 if (PyList_Append(temp, tuple) < 0)
481 return -1;
482 Py_DECREF(tuple);
483 }
484 if (mro_subclasses(subclass, temp) < 0)
485 return -1;
486 }
487 return 0;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000488}
489
490static int
491type_set_bases(PyTypeObject *type, PyObject *value, void *context)
492{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000493 Py_ssize_t i;
494 int r = 0;
495 PyObject *ob, *temp;
496 PyTypeObject *new_base, *old_base;
497 PyObject *old_bases, *old_mro;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000498
Benjamin Petersond9f23d22011-08-17 11:54:03 -0500499 if (!check_set_special_type_attr(type, value, "__bases__"))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000500 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000501 if (!PyTuple_Check(value)) {
502 PyErr_Format(PyExc_TypeError,
503 "can only assign tuple to %s.__bases__, not %s",
504 type->tp_name, Py_TYPE(value)->tp_name);
505 return -1;
506 }
507 if (PyTuple_GET_SIZE(value) == 0) {
508 PyErr_Format(PyExc_TypeError,
509 "can only assign non-empty tuple to %s.__bases__, not ()",
510 type->tp_name);
511 return -1;
512 }
513 for (i = 0; i < PyTuple_GET_SIZE(value); i++) {
514 ob = PyTuple_GET_ITEM(value, i);
515 if (!PyType_Check(ob)) {
Benjamin Petersonb6af60c2012-04-01 18:49:54 -0400516 PyErr_Format(PyExc_TypeError,
Benjamin Peterson9ee601e2012-04-01 18:51:37 -0400517 "%s.__bases__ must be tuple of classes, not '%s'",
Benjamin Petersonb6af60c2012-04-01 18:49:54 -0400518 type->tp_name, Py_TYPE(ob)->tp_name);
519 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000520 }
Benjamin Peterson3471bb62012-04-01 18:48:40 -0400521 if (PyType_IsSubtype((PyTypeObject*)ob, type)) {
522 PyErr_SetString(PyExc_TypeError,
523 "a __bases__ item causes an inheritance cycle");
524 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000525 }
526 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000527
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000528 new_base = best_base(value);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000529
Benjamin Petersonab3c1c12012-04-01 18:48:02 -0400530 if (!new_base)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000531 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000532
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000533 if (!compatible_for_assignment(type->tp_base, new_base, "__bases__"))
534 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000535
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000536 Py_INCREF(new_base);
537 Py_INCREF(value);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000538
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000539 old_bases = type->tp_bases;
540 old_base = type->tp_base;
541 old_mro = type->tp_mro;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000542
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000543 type->tp_bases = value;
544 type->tp_base = new_base;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000545
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000546 if (mro_internal(type) < 0) {
547 goto bail;
548 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000549
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000550 temp = PyList_New(0);
551 if (!temp)
552 goto bail;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000553
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000554 r = mro_subclasses(type, temp);
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000555
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000556 if (r < 0) {
557 for (i = 0; i < PyList_Size(temp); i++) {
558 PyTypeObject* cls;
559 PyObject* mro;
560 PyArg_UnpackTuple(PyList_GET_ITEM(temp, i),
561 "", 2, 2, &cls, &mro);
562 Py_INCREF(mro);
563 ob = cls->tp_mro;
564 cls->tp_mro = mro;
565 Py_DECREF(ob);
566 }
567 Py_DECREF(temp);
568 goto bail;
569 }
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000570
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000571 Py_DECREF(temp);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000572
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000573 /* any base that was in __bases__ but now isn't, we
574 need to remove |type| from its tp_subclasses.
575 conversely, any class now in __bases__ that wasn't
576 needs to have |type| added to its subclasses. */
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000577
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000578 /* for now, sod that: just remove from all old_bases,
579 add to all new_bases */
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000580
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000581 for (i = PyTuple_GET_SIZE(old_bases) - 1; i >= 0; i--) {
582 ob = PyTuple_GET_ITEM(old_bases, i);
583 if (PyType_Check(ob)) {
584 remove_subclass(
585 (PyTypeObject*)ob, type);
586 }
587 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000588
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000589 for (i = PyTuple_GET_SIZE(value) - 1; i >= 0; i--) {
590 ob = PyTuple_GET_ITEM(value, i);
591 if (PyType_Check(ob)) {
592 if (add_subclass((PyTypeObject*)ob, type) < 0)
593 r = -1;
594 }
595 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000596
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000597 update_all_slots(type);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000598
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000599 Py_DECREF(old_bases);
600 Py_DECREF(old_base);
601 Py_DECREF(old_mro);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000602
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000603 return r;
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000604
605 bail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000606 Py_DECREF(type->tp_bases);
607 Py_DECREF(type->tp_base);
608 if (type->tp_mro != old_mro) {
609 Py_DECREF(type->tp_mro);
610 }
Michael W. Hudsone723e452003-08-07 14:58:10 +0000611
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000612 type->tp_bases = old_bases;
613 type->tp_base = old_base;
614 type->tp_mro = old_mro;
Tim Petersea7f75d2002-12-07 21:39:16 +0000615
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000616 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000617}
618
619static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000620type_dict(PyTypeObject *type, void *context)
621{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000622 if (type->tp_dict == NULL) {
623 Py_INCREF(Py_None);
624 return Py_None;
625 }
626 return PyDictProxy_New(type->tp_dict);
Guido van Rossum29ca26e1995-01-07 11:58:15 +0000627}
628
Tim Peters24008312002-03-17 18:56:20 +0000629static PyObject *
630type_get_doc(PyTypeObject *type, void *context)
631{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000632 PyObject *result;
633 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE) && type->tp_doc != NULL)
634 return PyUnicode_FromString(type->tp_doc);
Victor Stinner3c1e4812012-03-26 22:10:51 +0200635 result = _PyDict_GetItemId(type->tp_dict, &PyId___doc__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000636 if (result == NULL) {
637 result = Py_None;
638 Py_INCREF(result);
639 }
640 else if (Py_TYPE(result)->tp_descr_get) {
641 result = Py_TYPE(result)->tp_descr_get(result, NULL,
642 (PyObject *)type);
643 }
644 else {
645 Py_INCREF(result);
646 }
647 return result;
Tim Peters24008312002-03-17 18:56:20 +0000648}
649
Benjamin Peterson01fc6cd2011-08-17 12:03:47 -0500650static int
651type_set_doc(PyTypeObject *type, PyObject *value, void *context)
652{
653 if (!check_set_special_type_attr(type, value, "__doc__"))
654 return -1;
655 PyType_Modified(type);
Victor Stinner3c1e4812012-03-26 22:10:51 +0200656 return _PyDict_SetItemId(type->tp_dict, &PyId___doc__, value);
Benjamin Peterson01fc6cd2011-08-17 12:03:47 -0500657}
658
Antoine Pitrouec569b72008-08-26 22:40:48 +0000659static PyObject *
660type___instancecheck__(PyObject *type, PyObject *inst)
661{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000662 switch (_PyObject_RealIsInstance(inst, type)) {
663 case -1:
664 return NULL;
665 case 0:
666 Py_RETURN_FALSE;
667 default:
668 Py_RETURN_TRUE;
669 }
Antoine Pitrouec569b72008-08-26 22:40:48 +0000670}
671
672
673static PyObject *
Antoine Pitrouec569b72008-08-26 22:40:48 +0000674type___subclasscheck__(PyObject *type, PyObject *inst)
675{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000676 switch (_PyObject_RealIsSubclass(inst, type)) {
677 case -1:
678 return NULL;
679 case 0:
680 Py_RETURN_FALSE;
681 default:
682 Py_RETURN_TRUE;
683 }
Antoine Pitrouec569b72008-08-26 22:40:48 +0000684}
685
Antoine Pitrouec569b72008-08-26 22:40:48 +0000686
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000687static PyGetSetDef type_getsets[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000688 {"__name__", (getter)type_name, (setter)type_set_name, NULL},
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100689 {"__qualname__", (getter)type_qualname, (setter)type_set_qualname, NULL},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000690 {"__bases__", (getter)type_get_bases, (setter)type_set_bases, NULL},
691 {"__module__", (getter)type_module, (setter)type_set_module, NULL},
692 {"__abstractmethods__", (getter)type_abstractmethods,
693 (setter)type_set_abstractmethods, NULL},
694 {"__dict__", (getter)type_dict, NULL, NULL},
Benjamin Peterson01fc6cd2011-08-17 12:03:47 -0500695 {"__doc__", (getter)type_get_doc, (setter)type_set_doc, NULL},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000696 {0}
Tim Peters6d6c1a32001-08-02 04:15:00 +0000697};
698
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000699static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000700type_repr(PyTypeObject *type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000701{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000702 PyObject *mod, *name, *rtn;
Guido van Rossumc3542212001-08-16 09:18:56 +0000703
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000704 mod = type_module(type, NULL);
705 if (mod == NULL)
706 PyErr_Clear();
707 else if (!PyUnicode_Check(mod)) {
708 Py_DECREF(mod);
709 mod = NULL;
710 }
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100711 name = type_qualname(type, NULL);
Christian Heimesa0e7e412012-09-10 03:00:14 +0200712 if (name == NULL) {
713 Py_XDECREF(mod);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000714 return NULL;
Christian Heimesa0e7e412012-09-10 03:00:14 +0200715 }
Barry Warsaw7ce36942001-08-24 18:34:26 +0000716
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000717 if (mod != NULL && PyUnicode_CompareWithASCIIString(mod, "builtins"))
718 rtn = PyUnicode_FromFormat("<class '%U.%U'>", mod, name);
719 else
720 rtn = PyUnicode_FromFormat("<class '%s'>", type->tp_name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000721
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000722 Py_XDECREF(mod);
723 Py_DECREF(name);
724 return rtn;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000725}
726
Tim Peters6d6c1a32001-08-02 04:15:00 +0000727static PyObject *
728type_call(PyTypeObject *type, PyObject *args, PyObject *kwds)
729{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000730 PyObject *obj;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000731
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000732 if (type->tp_new == NULL) {
733 PyErr_Format(PyExc_TypeError,
734 "cannot create '%.100s' instances",
735 type->tp_name);
736 return NULL;
737 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000738
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000739 obj = type->tp_new(type, args, kwds);
740 if (obj != NULL) {
741 /* Ugly exception: when the call was type(something),
742 don't call tp_init on the result. */
743 if (type == &PyType_Type &&
744 PyTuple_Check(args) && PyTuple_GET_SIZE(args) == 1 &&
745 (kwds == NULL ||
746 (PyDict_Check(kwds) && PyDict_Size(kwds) == 0)))
747 return obj;
748 /* If the returned object is not an instance of type,
749 it won't be initialized. */
750 if (!PyType_IsSubtype(Py_TYPE(obj), type))
751 return obj;
752 type = Py_TYPE(obj);
Victor Stinner3997cfd2013-07-16 22:51:21 +0200753 if (type->tp_init != NULL) {
754 int res = type->tp_init(obj, args, kwds);
755 if (res < 0) {
756 Py_DECREF(obj);
757 obj = NULL;
758 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000759 }
760 }
761 return obj;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000762}
763
764PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000765PyType_GenericAlloc(PyTypeObject *type, Py_ssize_t nitems)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000766{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000767 PyObject *obj;
768 const size_t size = _PyObject_VAR_SIZE(type, nitems+1);
769 /* note that we need to add one, for the sentinel */
Tim Peters406fe3b2001-10-06 19:04:01 +0000770
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000771 if (PyType_IS_GC(type))
772 obj = _PyObject_GC_Malloc(size);
773 else
774 obj = (PyObject *)PyObject_MALLOC(size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000775
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000776 if (obj == NULL)
777 return PyErr_NoMemory();
Tim Peters406fe3b2001-10-06 19:04:01 +0000778
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000779 memset(obj, '\0', size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000780
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000781 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
782 Py_INCREF(type);
Tim Peters406fe3b2001-10-06 19:04:01 +0000783
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000784 if (type->tp_itemsize == 0)
785 PyObject_INIT(obj, type);
786 else
787 (void) PyObject_INIT_VAR((PyVarObject *)obj, type, nitems);
Tim Peters406fe3b2001-10-06 19:04:01 +0000788
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000789 if (PyType_IS_GC(type))
790 _PyObject_GC_TRACK(obj);
791 return obj;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000792}
793
794PyObject *
795PyType_GenericNew(PyTypeObject *type, PyObject *args, PyObject *kwds)
796{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000797 return type->tp_alloc(type, 0);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000798}
799
Guido van Rossum9475a232001-10-05 20:51:39 +0000800/* Helpers for subtyping */
801
802static int
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000803traverse_slots(PyTypeObject *type, PyObject *self, visitproc visit, void *arg)
804{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000805 Py_ssize_t i, n;
806 PyMemberDef *mp;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000807
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000808 n = Py_SIZE(type);
809 mp = PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type);
810 for (i = 0; i < n; i++, mp++) {
811 if (mp->type == T_OBJECT_EX) {
812 char *addr = (char *)self + mp->offset;
813 PyObject *obj = *(PyObject **)addr;
814 if (obj != NULL) {
815 int err = visit(obj, arg);
816 if (err)
817 return err;
818 }
819 }
820 }
821 return 0;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000822}
823
824static int
Guido van Rossum9475a232001-10-05 20:51:39 +0000825subtype_traverse(PyObject *self, visitproc visit, void *arg)
826{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000827 PyTypeObject *type, *base;
828 traverseproc basetraverse;
Guido van Rossum9475a232001-10-05 20:51:39 +0000829
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000830 /* Find the nearest base with a different tp_traverse,
831 and traverse slots while we're at it */
832 type = Py_TYPE(self);
833 base = type;
834 while ((basetraverse = base->tp_traverse) == subtype_traverse) {
835 if (Py_SIZE(base)) {
836 int err = traverse_slots(base, self, visit, arg);
837 if (err)
838 return err;
839 }
840 base = base->tp_base;
841 assert(base);
842 }
Guido van Rossum9475a232001-10-05 20:51:39 +0000843
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000844 if (type->tp_dictoffset != base->tp_dictoffset) {
845 PyObject **dictptr = _PyObject_GetDictPtr(self);
846 if (dictptr && *dictptr)
847 Py_VISIT(*dictptr);
848 }
Guido van Rossum9475a232001-10-05 20:51:39 +0000849
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000850 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
851 /* For a heaptype, the instances count as references
852 to the type. Traverse the type so the collector
853 can find cycles involving this link. */
854 Py_VISIT(type);
Guido van Rossuma3862092002-06-10 15:24:42 +0000855
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000856 if (basetraverse)
857 return basetraverse(self, visit, arg);
858 return 0;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000859}
860
861static void
862clear_slots(PyTypeObject *type, PyObject *self)
863{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000864 Py_ssize_t i, n;
865 PyMemberDef *mp;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000866
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000867 n = Py_SIZE(type);
868 mp = PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type);
869 for (i = 0; i < n; i++, mp++) {
870 if (mp->type == T_OBJECT_EX && !(mp->flags & READONLY)) {
871 char *addr = (char *)self + mp->offset;
872 PyObject *obj = *(PyObject **)addr;
873 if (obj != NULL) {
874 *(PyObject **)addr = NULL;
875 Py_DECREF(obj);
876 }
877 }
878 }
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000879}
880
881static int
882subtype_clear(PyObject *self)
883{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000884 PyTypeObject *type, *base;
885 inquiry baseclear;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000886
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000887 /* Find the nearest base with a different tp_clear
888 and clear slots while we're at it */
889 type = Py_TYPE(self);
890 base = type;
891 while ((baseclear = base->tp_clear) == subtype_clear) {
892 if (Py_SIZE(base))
893 clear_slots(base, self);
894 base = base->tp_base;
895 assert(base);
896 }
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000897
Benjamin Peterson52c42432012-03-07 18:41:11 -0600898 /* Clear the instance dict (if any), to break cycles involving only
899 __dict__ slots (as in the case 'self.__dict__ is self'). */
900 if (type->tp_dictoffset != base->tp_dictoffset) {
901 PyObject **dictptr = _PyObject_GetDictPtr(self);
902 if (dictptr && *dictptr)
903 Py_CLEAR(*dictptr);
904 }
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000905
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000906 if (baseclear)
907 return baseclear(self);
908 return 0;
Guido van Rossum9475a232001-10-05 20:51:39 +0000909}
Tim Peters6d6c1a32001-08-02 04:15:00 +0000910
911static void
912subtype_dealloc(PyObject *self)
913{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000914 PyTypeObject *type, *base;
915 destructor basedealloc;
Antoine Pitrou56cd62c2012-09-06 00:59:49 +0200916 PyThreadState *tstate = PyThreadState_GET();
Tim Peters6d6c1a32001-08-02 04:15:00 +0000917
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000918 /* Extract the type; we expect it to be a heap type */
919 type = Py_TYPE(self);
920 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000921
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000922 /* Test whether the type has GC exactly once */
Guido van Rossum22b13872002-08-06 21:41:44 +0000923
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000924 if (!PyType_IS_GC(type)) {
925 /* It's really rare to find a dynamic type that doesn't have
926 GC; it can only happen when deriving from 'object' and not
927 adding any slots or instance variables. This allows
928 certain simplifications: there's no need to call
929 clear_slots(), or DECREF the dict, or clear weakrefs. */
Guido van Rossum22b13872002-08-06 21:41:44 +0000930
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000931 /* Maybe call finalizer; exit early if resurrected */
932 if (type->tp_del) {
933 type->tp_del(self);
934 if (self->ob_refcnt > 0)
935 return;
936 }
Guido van Rossum22b13872002-08-06 21:41:44 +0000937
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000938 /* Find the nearest base with a different tp_dealloc */
939 base = type;
940 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
941 assert(Py_SIZE(base) == 0);
942 base = base->tp_base;
943 assert(base);
944 }
Guido van Rossum22b13872002-08-06 21:41:44 +0000945
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000946 /* Extract the type again; tp_del may have changed it */
947 type = Py_TYPE(self);
Benjamin Peterson193152c2009-04-25 01:08:45 +0000948
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000949 /* Call the base tp_dealloc() */
950 assert(basedealloc);
951 basedealloc(self);
Guido van Rossum22b13872002-08-06 21:41:44 +0000952
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000953 /* Can't reference self beyond this point */
954 Py_DECREF(type);
Guido van Rossum22b13872002-08-06 21:41:44 +0000955
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000956 /* Done */
957 return;
958 }
Guido van Rossum22b13872002-08-06 21:41:44 +0000959
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000960 /* We get here only if the type has GC */
Guido van Rossum22b13872002-08-06 21:41:44 +0000961
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000962 /* UnTrack and re-Track around the trashcan macro, alas */
963 /* See explanation at end of function for full disclosure */
964 PyObject_GC_UnTrack(self);
965 ++_PyTrash_delete_nesting;
Antoine Pitrou56cd62c2012-09-06 00:59:49 +0200966 ++ tstate->trash_delete_nesting;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000967 Py_TRASHCAN_SAFE_BEGIN(self);
968 --_PyTrash_delete_nesting;
Antoine Pitrou56cd62c2012-09-06 00:59:49 +0200969 -- tstate->trash_delete_nesting;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000970 /* DO NOT restore GC tracking at this point. weakref callbacks
971 * (if any, and whether directly here or indirectly in something we
972 * call) may trigger GC, and if self is tracked at that point, it
973 * will look like trash to GC and GC will try to delete self again.
974 */
Guido van Rossum22b13872002-08-06 21:41:44 +0000975
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000976 /* Find the nearest base with a different tp_dealloc */
977 base = type;
Brett Cannonb94767f2011-02-22 20:15:44 +0000978 while ((/*basedealloc =*/ base->tp_dealloc) == subtype_dealloc) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000979 base = base->tp_base;
980 assert(base);
981 }
Guido van Rossum14227b42001-12-06 02:35:58 +0000982
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000983 /* If we added a weaklist, we clear it. Do this *before* calling
984 the finalizer (__del__), clearing slots, or clearing the instance
985 dict. */
Guido van Rossum59195fd2003-06-13 20:54:40 +0000986
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000987 if (type->tp_weaklistoffset && !base->tp_weaklistoffset)
988 PyObject_ClearWeakRefs(self);
Guido van Rossum1987c662003-05-29 14:29:23 +0000989
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000990 /* Maybe call finalizer; exit early if resurrected */
991 if (type->tp_del) {
992 _PyObject_GC_TRACK(self);
993 type->tp_del(self);
994 if (self->ob_refcnt > 0)
995 goto endlabel; /* resurrected */
996 else
997 _PyObject_GC_UNTRACK(self);
998 /* New weakrefs could be created during the finalizer call.
999 If this occurs, clear them out without calling their
1000 finalizers since they might rely on part of the object
1001 being finalized that has already been destroyed. */
1002 if (type->tp_weaklistoffset && !base->tp_weaklistoffset) {
1003 /* Modeled after GET_WEAKREFS_LISTPTR() */
1004 PyWeakReference **list = (PyWeakReference **) \
1005 PyObject_GET_WEAKREFS_LISTPTR(self);
1006 while (*list)
1007 _PyWeakref_ClearRef(*list);
1008 }
1009 }
Guido van Rossum1987c662003-05-29 14:29:23 +00001010
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001011 /* Clear slots up to the nearest base with a different tp_dealloc */
1012 base = type;
1013 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
1014 if (Py_SIZE(base))
1015 clear_slots(base, self);
1016 base = base->tp_base;
1017 assert(base);
1018 }
Guido van Rossum59195fd2003-06-13 20:54:40 +00001019
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001020 /* If we added a dict, DECREF it */
1021 if (type->tp_dictoffset && !base->tp_dictoffset) {
1022 PyObject **dictptr = _PyObject_GetDictPtr(self);
1023 if (dictptr != NULL) {
1024 PyObject *dict = *dictptr;
1025 if (dict != NULL) {
1026 Py_DECREF(dict);
1027 *dictptr = NULL;
1028 }
1029 }
1030 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001031
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001032 /* Extract the type again; tp_del may have changed it */
1033 type = Py_TYPE(self);
Benjamin Peterson193152c2009-04-25 01:08:45 +00001034
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001035 /* Call the base tp_dealloc(); first retrack self if
1036 * basedealloc knows about gc.
1037 */
1038 if (PyType_IS_GC(base))
1039 _PyObject_GC_TRACK(self);
1040 assert(basedealloc);
1041 basedealloc(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001042
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001043 /* Can't reference self beyond this point */
1044 Py_DECREF(type);
Guido van Rossum22b13872002-08-06 21:41:44 +00001045
Guido van Rossum0906e072002-08-07 20:42:09 +00001046 endlabel:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001047 ++_PyTrash_delete_nesting;
Antoine Pitrou56cd62c2012-09-06 00:59:49 +02001048 ++ tstate->trash_delete_nesting;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001049 Py_TRASHCAN_SAFE_END(self);
1050 --_PyTrash_delete_nesting;
Antoine Pitrou56cd62c2012-09-06 00:59:49 +02001051 -- tstate->trash_delete_nesting;
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001052
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001053 /* Explanation of the weirdness around the trashcan macros:
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001054
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001055 Q. What do the trashcan macros do?
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001056
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001057 A. Read the comment titled "Trashcan mechanism" in object.h.
1058 For one, this explains why there must be a call to GC-untrack
1059 before the trashcan begin macro. Without understanding the
1060 trashcan code, the answers to the following questions don't make
1061 sense.
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001062
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001063 Q. Why do we GC-untrack before the trashcan and then immediately
1064 GC-track again afterward?
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001065
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001066 A. In the case that the base class is GC-aware, the base class
1067 probably GC-untracks the object. If it does that using the
1068 UNTRACK macro, this will crash when the object is already
1069 untracked. Because we don't know what the base class does, the
1070 only safe thing is to make sure the object is tracked when we
1071 call the base class dealloc. But... The trashcan begin macro
1072 requires that the object is *untracked* before it is called. So
1073 the dance becomes:
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001074
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001075 GC untrack
1076 trashcan begin
1077 GC track
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001078
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001079 Q. Why did the last question say "immediately GC-track again"?
1080 It's nowhere near immediately.
Tim Petersf7f9e992003-11-13 21:59:32 +00001081
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001082 A. Because the code *used* to re-track immediately. Bad Idea.
1083 self has a refcount of 0, and if gc ever gets its hands on it
1084 (which can happen if any weakref callback gets invoked), it
1085 looks like trash to gc too, and gc also tries to delete self
Ezio Melotti13925002011-03-16 11:05:33 +02001086 then. But we're already deleting self. Double deallocation is
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001087 a subtle disaster.
Tim Petersf7f9e992003-11-13 21:59:32 +00001088
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001089 Q. Why the bizarre (net-zero) manipulation of
1090 _PyTrash_delete_nesting around the trashcan macros?
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001091
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001092 A. Some base classes (e.g. list) also use the trashcan mechanism.
1093 The following scenario used to be possible:
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001094
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001095 - suppose the trashcan level is one below the trashcan limit
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001096
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001097 - subtype_dealloc() is called
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001098
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001099 - the trashcan limit is not yet reached, so the trashcan level
1100 is incremented and the code between trashcan begin and end is
1101 executed
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001102
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001103 - this destroys much of the object's contents, including its
1104 slots and __dict__
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001105
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001106 - basedealloc() is called; this is really list_dealloc(), or
1107 some other type which also uses the trashcan macros
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001108
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001109 - the trashcan limit is now reached, so the object is put on the
1110 trashcan's to-be-deleted-later list
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001111
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001112 - basedealloc() returns
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001113
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001114 - subtype_dealloc() decrefs the object's type
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001115
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001116 - subtype_dealloc() returns
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001117
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001118 - later, the trashcan code starts deleting the objects from its
1119 to-be-deleted-later list
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001120
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001121 - subtype_dealloc() is called *AGAIN* for the same object
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001122
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001123 - at the very least (if the destroyed slots and __dict__ don't
1124 cause problems) the object's type gets decref'ed a second
1125 time, which is *BAD*!!!
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001126
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001127 The remedy is to make sure that if the code between trashcan
1128 begin and end in subtype_dealloc() is called, the code between
1129 trashcan begin and end in basedealloc() will also be called.
1130 This is done by decrementing the level after passing into the
1131 trashcan block, and incrementing it just before leaving the
1132 block.
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001133
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001134 But now it's possible that a chain of objects consisting solely
1135 of objects whose deallocator is subtype_dealloc() will defeat
1136 the trashcan mechanism completely: the decremented level means
1137 that the effective level never reaches the limit. Therefore, we
1138 *increment* the level *before* entering the trashcan block, and
1139 matchingly decrement it after leaving. This means the trashcan
1140 code will trigger a little early, but that's no big deal.
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001141
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001142 Q. Are there any live examples of code in need of all this
1143 complexity?
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001144
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001145 A. Yes. See SF bug 668433 for code that crashed (when Python was
1146 compiled in debug mode) before the trashcan level manipulations
1147 were added. For more discussion, see SF patches 581742, 575073
1148 and bug 574207.
1149 */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001150}
1151
Jeremy Hylton938ace62002-07-17 16:30:39 +00001152static PyTypeObject *solid_base(PyTypeObject *type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001153
Tim Peters6d6c1a32001-08-02 04:15:00 +00001154/* type test with subclassing support */
1155
1156int
1157PyType_IsSubtype(PyTypeObject *a, PyTypeObject *b)
1158{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001159 PyObject *mro;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001160
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001161 mro = a->tp_mro;
1162 if (mro != NULL) {
1163 /* Deal with multiple inheritance without recursion
1164 by walking the MRO tuple */
1165 Py_ssize_t i, n;
1166 assert(PyTuple_Check(mro));
1167 n = PyTuple_GET_SIZE(mro);
1168 for (i = 0; i < n; i++) {
1169 if (PyTuple_GET_ITEM(mro, i) == (PyObject *)b)
1170 return 1;
1171 }
1172 return 0;
1173 }
1174 else {
1175 /* a is not completely initilized yet; follow tp_base */
1176 do {
1177 if (a == b)
1178 return 1;
1179 a = a->tp_base;
1180 } while (a != NULL);
1181 return b == &PyBaseObject_Type;
1182 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001183}
1184
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001185/* Internal routines to do a method lookup in the type
Guido van Rossum60718732001-08-28 17:47:51 +00001186 without looking in the instance dictionary
1187 (so we can't use PyObject_GetAttr) but still binding
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001188 it to the instance. The arguments are the object,
Guido van Rossum60718732001-08-28 17:47:51 +00001189 the method name as a C string, and the address of a
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001190 static variable used to cache the interned Python string.
1191
1192 Two variants:
1193
1194 - lookup_maybe() returns NULL without raising an exception
1195 when the _PyType_Lookup() call fails;
1196
1197 - lookup_method() always raises an exception upon errors.
Benjamin Peterson224205f2009-05-08 03:25:19 +00001198
1199 - _PyObject_LookupSpecial() exported for the benefit of other places.
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001200*/
Guido van Rossum60718732001-08-28 17:47:51 +00001201
1202static PyObject *
Benjamin Petersonce798522012-01-22 11:24:29 -05001203lookup_maybe(PyObject *self, _Py_Identifier *attrid)
Guido van Rossum60718732001-08-28 17:47:51 +00001204{
Victor Stinner3c1e4812012-03-26 22:10:51 +02001205 PyObject *res;
Guido van Rossum60718732001-08-28 17:47:51 +00001206
Victor Stinner3c1e4812012-03-26 22:10:51 +02001207 res = _PyType_LookupId(Py_TYPE(self), attrid);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001208 if (res != NULL) {
1209 descrgetfunc f;
1210 if ((f = Py_TYPE(res)->tp_descr_get) == NULL)
1211 Py_INCREF(res);
1212 else
1213 res = f(res, self, (PyObject *)(Py_TYPE(self)));
1214 }
1215 return res;
Guido van Rossum60718732001-08-28 17:47:51 +00001216}
1217
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001218static PyObject *
Benjamin Petersonce798522012-01-22 11:24:29 -05001219lookup_method(PyObject *self, _Py_Identifier *attrid)
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001220{
Benjamin Petersonce798522012-01-22 11:24:29 -05001221 PyObject *res = lookup_maybe(self, attrid);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001222 if (res == NULL && !PyErr_Occurred())
Benjamin Petersonce798522012-01-22 11:24:29 -05001223 PyErr_SetObject(PyExc_AttributeError, attrid->object);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001224 return res;
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001225}
1226
Benjamin Peterson224205f2009-05-08 03:25:19 +00001227PyObject *
Benjamin Petersonce798522012-01-22 11:24:29 -05001228_PyObject_LookupSpecial(PyObject *self, _Py_Identifier *attrid)
Benjamin Peterson224205f2009-05-08 03:25:19 +00001229{
Benjamin Petersonce798522012-01-22 11:24:29 -05001230 return lookup_maybe(self, attrid);
Benjamin Peterson224205f2009-05-08 03:25:19 +00001231}
1232
Guido van Rossum2730b132001-08-28 18:22:14 +00001233/* A variation of PyObject_CallMethod that uses lookup_method()
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001234 instead of PyObject_GetAttrString(). This uses the same convention
Guido van Rossum2730b132001-08-28 18:22:14 +00001235 as lookup_method to cache the interned name string object. */
1236
Neil Schemenauerf23473f2001-10-21 22:28:58 +00001237static PyObject *
Benjamin Petersonce798522012-01-22 11:24:29 -05001238call_method(PyObject *o, _Py_Identifier *nameid, char *format, ...)
Guido van Rossum2730b132001-08-28 18:22:14 +00001239{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001240 va_list va;
1241 PyObject *args, *func = 0, *retval;
1242 va_start(va, format);
Guido van Rossum2730b132001-08-28 18:22:14 +00001243
Benjamin Petersonce798522012-01-22 11:24:29 -05001244 func = lookup_maybe(o, nameid);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001245 if (func == NULL) {
1246 va_end(va);
1247 if (!PyErr_Occurred())
Benjamin Petersonce798522012-01-22 11:24:29 -05001248 PyErr_SetObject(PyExc_AttributeError, nameid->object);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001249 return NULL;
1250 }
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001251
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001252 if (format && *format)
1253 args = Py_VaBuildValue(format, va);
1254 else
1255 args = PyTuple_New(0);
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001256
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001257 va_end(va);
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001258
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001259 if (args == NULL)
1260 return NULL;
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001261
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001262 assert(PyTuple_Check(args));
1263 retval = PyObject_Call(func, args, NULL);
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001264
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001265 Py_DECREF(args);
1266 Py_DECREF(func);
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001267
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001268 return retval;
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001269}
1270
1271/* Clone of call_method() that returns NotImplemented when the lookup fails. */
1272
Neil Schemenauerf23473f2001-10-21 22:28:58 +00001273static PyObject *
Benjamin Petersonce798522012-01-22 11:24:29 -05001274call_maybe(PyObject *o, _Py_Identifier *nameid, char *format, ...)
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001275{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001276 va_list va;
1277 PyObject *args, *func = 0, *retval;
1278 va_start(va, format);
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001279
Benjamin Petersonce798522012-01-22 11:24:29 -05001280 func = lookup_maybe(o, nameid);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001281 if (func == NULL) {
1282 va_end(va);
Brian Curtindfc80e32011-08-10 20:28:54 -05001283 if (!PyErr_Occurred())
1284 Py_RETURN_NOTIMPLEMENTED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001285 return NULL;
1286 }
Guido van Rossum2730b132001-08-28 18:22:14 +00001287
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001288 if (format && *format)
1289 args = Py_VaBuildValue(format, va);
1290 else
1291 args = PyTuple_New(0);
Guido van Rossum2730b132001-08-28 18:22:14 +00001292
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001293 va_end(va);
Guido van Rossum2730b132001-08-28 18:22:14 +00001294
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001295 if (args == NULL)
1296 return NULL;
Guido van Rossum2730b132001-08-28 18:22:14 +00001297
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001298 assert(PyTuple_Check(args));
1299 retval = PyObject_Call(func, args, NULL);
Guido van Rossum2730b132001-08-28 18:22:14 +00001300
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001301 Py_DECREF(args);
1302 Py_DECREF(func);
Guido van Rossum2730b132001-08-28 18:22:14 +00001303
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001304 return retval;
Guido van Rossum2730b132001-08-28 18:22:14 +00001305}
1306
Tim Petersea7f75d2002-12-07 21:39:16 +00001307/*
Guido van Rossum1f121312002-11-14 19:49:16 +00001308 Method resolution order algorithm C3 described in
1309 "A Monotonic Superclass Linearization for Dylan",
1310 by Kim Barrett, Bob Cassel, Paul Haahr,
Tim Petersea7f75d2002-12-07 21:39:16 +00001311 David A. Moon, Keith Playford, and P. Tucker Withington.
Guido van Rossum1f121312002-11-14 19:49:16 +00001312 (OOPSLA 1996)
1313
Guido van Rossum98f33732002-11-25 21:36:54 +00001314 Some notes about the rules implied by C3:
1315
Tim Petersea7f75d2002-12-07 21:39:16 +00001316 No duplicate bases.
Guido van Rossum98f33732002-11-25 21:36:54 +00001317 It isn't legal to repeat a class in a list of base classes.
1318
1319 The next three properties are the 3 constraints in "C3".
1320
Tim Petersea7f75d2002-12-07 21:39:16 +00001321 Local precendece order.
Guido van Rossum98f33732002-11-25 21:36:54 +00001322 If A precedes B in C's MRO, then A will precede B in the MRO of all
1323 subclasses of C.
1324
1325 Monotonicity.
1326 The MRO of a class must be an extension without reordering of the
1327 MRO of each of its superclasses.
1328
1329 Extended Precedence Graph (EPG).
1330 Linearization is consistent if there is a path in the EPG from
1331 each class to all its successors in the linearization. See
1332 the paper for definition of EPG.
Guido van Rossum1f121312002-11-14 19:49:16 +00001333 */
1334
Tim Petersea7f75d2002-12-07 21:39:16 +00001335static int
Guido van Rossum1f121312002-11-14 19:49:16 +00001336tail_contains(PyObject *list, int whence, PyObject *o) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001337 Py_ssize_t j, size;
1338 size = PyList_GET_SIZE(list);
Guido van Rossum1f121312002-11-14 19:49:16 +00001339
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001340 for (j = whence+1; j < size; j++) {
1341 if (PyList_GET_ITEM(list, j) == o)
1342 return 1;
1343 }
1344 return 0;
Guido van Rossum1f121312002-11-14 19:49:16 +00001345}
1346
Guido van Rossum98f33732002-11-25 21:36:54 +00001347static PyObject *
1348class_name(PyObject *cls)
1349{
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001350 PyObject *name = _PyObject_GetAttrId(cls, &PyId___name__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001351 if (name == NULL) {
1352 PyErr_Clear();
1353 Py_XDECREF(name);
1354 name = PyObject_Repr(cls);
1355 }
1356 if (name == NULL)
1357 return NULL;
1358 if (!PyUnicode_Check(name)) {
1359 Py_DECREF(name);
1360 return NULL;
1361 }
1362 return name;
Guido van Rossum98f33732002-11-25 21:36:54 +00001363}
1364
1365static int
1366check_duplicates(PyObject *list)
1367{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001368 Py_ssize_t i, j, n;
1369 /* Let's use a quadratic time algorithm,
1370 assuming that the bases lists is short.
1371 */
1372 n = PyList_GET_SIZE(list);
1373 for (i = 0; i < n; i++) {
1374 PyObject *o = PyList_GET_ITEM(list, i);
1375 for (j = i + 1; j < n; j++) {
1376 if (PyList_GET_ITEM(list, j) == o) {
1377 o = class_name(o);
1378 if (o != NULL) {
1379 PyErr_Format(PyExc_TypeError,
1380 "duplicate base class %U",
1381 o);
1382 Py_DECREF(o);
1383 } else {
1384 PyErr_SetString(PyExc_TypeError,
1385 "duplicate base class");
1386 }
1387 return -1;
1388 }
1389 }
1390 }
1391 return 0;
Guido van Rossum98f33732002-11-25 21:36:54 +00001392}
1393
1394/* Raise a TypeError for an MRO order disagreement.
1395
1396 It's hard to produce a good error message. In the absence of better
1397 insight into error reporting, report the classes that were candidates
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001398 to be put next into the MRO. There is some conflict between the
Guido van Rossum98f33732002-11-25 21:36:54 +00001399 order in which they should be put in the MRO, but it's hard to
1400 diagnose what constraint can't be satisfied.
1401*/
1402
1403static void
1404set_mro_error(PyObject *to_merge, int *remain)
1405{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001406 Py_ssize_t i, n, off, to_merge_size;
1407 char buf[1000];
1408 PyObject *k, *v;
1409 PyObject *set = PyDict_New();
1410 if (!set) return;
Guido van Rossum98f33732002-11-25 21:36:54 +00001411
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001412 to_merge_size = PyList_GET_SIZE(to_merge);
1413 for (i = 0; i < to_merge_size; i++) {
1414 PyObject *L = PyList_GET_ITEM(to_merge, i);
1415 if (remain[i] < PyList_GET_SIZE(L)) {
1416 PyObject *c = PyList_GET_ITEM(L, remain[i]);
1417 if (PyDict_SetItem(set, c, Py_None) < 0) {
1418 Py_DECREF(set);
1419 return;
1420 }
1421 }
1422 }
1423 n = PyDict_Size(set);
Guido van Rossum98f33732002-11-25 21:36:54 +00001424
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001425 off = PyOS_snprintf(buf, sizeof(buf), "Cannot create a \
Raymond Hettingerf394df42003-04-06 19:13:41 +00001426consistent method resolution\norder (MRO) for bases");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001427 i = 0;
1428 while (PyDict_Next(set, &i, &k, &v) && (size_t)off < sizeof(buf)) {
1429 PyObject *name = class_name(k);
Victor Stinnere5f99f32010-05-19 01:42:46 +00001430 char *name_str;
1431 if (name != NULL) {
1432 name_str = _PyUnicode_AsString(name);
1433 if (name_str == NULL)
Victor Stinnerba644a62010-05-19 01:50:45 +00001434 name_str = "?";
Victor Stinnere5f99f32010-05-19 01:42:46 +00001435 } else
Victor Stinnerba644a62010-05-19 01:50:45 +00001436 name_str = "?";
Victor Stinnere5f99f32010-05-19 01:42:46 +00001437 off += PyOS_snprintf(buf + off, sizeof(buf) - off, " %s", name_str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001438 Py_XDECREF(name);
1439 if (--n && (size_t)(off+1) < sizeof(buf)) {
1440 buf[off++] = ',';
1441 buf[off] = '\0';
1442 }
1443 }
1444 PyErr_SetString(PyExc_TypeError, buf);
1445 Py_DECREF(set);
Guido van Rossum98f33732002-11-25 21:36:54 +00001446}
1447
Tim Petersea7f75d2002-12-07 21:39:16 +00001448static int
Guido van Rossum1f121312002-11-14 19:49:16 +00001449pmerge(PyObject *acc, PyObject* to_merge) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001450 Py_ssize_t i, j, to_merge_size, empty_cnt;
1451 int *remain;
1452 int ok;
Tim Petersea7f75d2002-12-07 21:39:16 +00001453
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001454 to_merge_size = PyList_GET_SIZE(to_merge);
Guido van Rossum1f121312002-11-14 19:49:16 +00001455
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001456 /* remain stores an index into each sublist of to_merge.
1457 remain[i] is the index of the next base in to_merge[i]
1458 that is not included in acc.
1459 */
1460 remain = (int *)PyMem_MALLOC(SIZEOF_INT*to_merge_size);
Victor Stinnera41f0852013-07-12 00:42:14 +02001461 if (remain == NULL) {
1462 PyErr_NoMemory();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001463 return -1;
Victor Stinnera41f0852013-07-12 00:42:14 +02001464 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001465 for (i = 0; i < to_merge_size; i++)
1466 remain[i] = 0;
Guido van Rossum1f121312002-11-14 19:49:16 +00001467
1468 again:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001469 empty_cnt = 0;
1470 for (i = 0; i < to_merge_size; i++) {
1471 PyObject *candidate;
Tim Petersea7f75d2002-12-07 21:39:16 +00001472
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001473 PyObject *cur_list = PyList_GET_ITEM(to_merge, i);
Guido van Rossum1f121312002-11-14 19:49:16 +00001474
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001475 if (remain[i] >= PyList_GET_SIZE(cur_list)) {
1476 empty_cnt++;
1477 continue;
1478 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001479
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001480 /* Choose next candidate for MRO.
Guido van Rossum98f33732002-11-25 21:36:54 +00001481
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001482 The input sequences alone can determine the choice.
1483 If not, choose the class which appears in the MRO
1484 of the earliest direct superclass of the new class.
1485 */
Guido van Rossum98f33732002-11-25 21:36:54 +00001486
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001487 candidate = PyList_GET_ITEM(cur_list, remain[i]);
1488 for (j = 0; j < to_merge_size; j++) {
1489 PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
1490 if (tail_contains(j_lst, remain[j], candidate)) {
1491 goto skip; /* continue outer loop */
1492 }
1493 }
1494 ok = PyList_Append(acc, candidate);
1495 if (ok < 0) {
Victor Stinnera41f0852013-07-12 00:42:14 +02001496 PyMem_FREE(remain);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001497 return -1;
1498 }
1499 for (j = 0; j < to_merge_size; j++) {
1500 PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
1501 if (remain[j] < PyList_GET_SIZE(j_lst) &&
1502 PyList_GET_ITEM(j_lst, remain[j]) == candidate) {
1503 remain[j]++;
1504 }
1505 }
1506 goto again;
1507 skip: ;
1508 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001509
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001510 if (empty_cnt == to_merge_size) {
1511 PyMem_FREE(remain);
1512 return 0;
1513 }
1514 set_mro_error(to_merge, remain);
1515 PyMem_FREE(remain);
1516 return -1;
Guido van Rossum1f121312002-11-14 19:49:16 +00001517}
1518
Tim Peters6d6c1a32001-08-02 04:15:00 +00001519static PyObject *
1520mro_implementation(PyTypeObject *type)
1521{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001522 Py_ssize_t i, n;
1523 int ok;
1524 PyObject *bases, *result;
1525 PyObject *to_merge, *bases_aslist;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001526
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001527 if (type->tp_dict == NULL) {
1528 if (PyType_Ready(type) < 0)
1529 return NULL;
1530 }
Guido van Rossum63517572002-06-18 16:44:57 +00001531
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001532 /* Find a superclass linearization that honors the constraints
1533 of the explicit lists of bases and the constraints implied by
1534 each base class.
Guido van Rossum98f33732002-11-25 21:36:54 +00001535
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001536 to_merge is a list of lists, where each list is a superclass
1537 linearization implied by a base class. The last element of
1538 to_merge is the declared list of bases.
1539 */
Guido van Rossum98f33732002-11-25 21:36:54 +00001540
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001541 bases = type->tp_bases;
1542 n = PyTuple_GET_SIZE(bases);
Guido van Rossum1f121312002-11-14 19:49:16 +00001543
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001544 to_merge = PyList_New(n+1);
1545 if (to_merge == NULL)
1546 return NULL;
Guido van Rossum1f121312002-11-14 19:49:16 +00001547
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001548 for (i = 0; i < n; i++) {
1549 PyObject *base = PyTuple_GET_ITEM(bases, i);
1550 PyObject *parentMRO;
1551 parentMRO = PySequence_List(((PyTypeObject*)base)->tp_mro);
1552 if (parentMRO == NULL) {
1553 Py_DECREF(to_merge);
1554 return NULL;
1555 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001556
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001557 PyList_SET_ITEM(to_merge, i, parentMRO);
1558 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001559
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001560 bases_aslist = PySequence_List(bases);
1561 if (bases_aslist == NULL) {
1562 Py_DECREF(to_merge);
1563 return NULL;
1564 }
1565 /* This is just a basic sanity check. */
1566 if (check_duplicates(bases_aslist) < 0) {
1567 Py_DECREF(to_merge);
1568 Py_DECREF(bases_aslist);
1569 return NULL;
1570 }
1571 PyList_SET_ITEM(to_merge, n, bases_aslist);
Guido van Rossum1f121312002-11-14 19:49:16 +00001572
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001573 result = Py_BuildValue("[O]", (PyObject *)type);
1574 if (result == NULL) {
1575 Py_DECREF(to_merge);
1576 return NULL;
1577 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001578
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001579 ok = pmerge(result, to_merge);
1580 Py_DECREF(to_merge);
1581 if (ok < 0) {
1582 Py_DECREF(result);
1583 return NULL;
1584 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001585
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001586 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001587}
1588
1589static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001590mro_external(PyObject *self)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001591{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001592 PyTypeObject *type = (PyTypeObject *)self;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001593
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001594 return mro_implementation(type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001595}
1596
1597static int
1598mro_internal(PyTypeObject *type)
1599{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001600 PyObject *mro, *result, *tuple;
1601 int checkit = 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001602
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001603 if (Py_TYPE(type) == &PyType_Type) {
1604 result = mro_implementation(type);
1605 }
1606 else {
Benjamin Petersonce798522012-01-22 11:24:29 -05001607 _Py_IDENTIFIER(mro);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001608 checkit = 1;
Benjamin Petersonce798522012-01-22 11:24:29 -05001609 mro = lookup_method((PyObject *)type, &PyId_mro);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001610 if (mro == NULL)
1611 return -1;
1612 result = PyObject_CallObject(mro, NULL);
1613 Py_DECREF(mro);
1614 }
1615 if (result == NULL)
1616 return -1;
1617 tuple = PySequence_Tuple(result);
1618 Py_DECREF(result);
1619 if (tuple == NULL)
1620 return -1;
1621 if (checkit) {
1622 Py_ssize_t i, len;
1623 PyObject *cls;
1624 PyTypeObject *solid;
Armin Rigo037d1e02005-12-29 17:07:39 +00001625
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001626 solid = solid_base(type);
Armin Rigo037d1e02005-12-29 17:07:39 +00001627
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001628 len = PyTuple_GET_SIZE(tuple);
Armin Rigo037d1e02005-12-29 17:07:39 +00001629
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001630 for (i = 0; i < len; i++) {
1631 PyTypeObject *t;
1632 cls = PyTuple_GET_ITEM(tuple, i);
1633 if (!PyType_Check(cls)) {
1634 PyErr_Format(PyExc_TypeError,
1635 "mro() returned a non-class ('%.500s')",
1636 Py_TYPE(cls)->tp_name);
1637 Py_DECREF(tuple);
1638 return -1;
1639 }
1640 t = (PyTypeObject*)cls;
1641 if (!PyType_IsSubtype(solid, solid_base(t))) {
1642 PyErr_Format(PyExc_TypeError,
1643 "mro() returned base with unsuitable layout ('%.500s')",
1644 t->tp_name);
1645 Py_DECREF(tuple);
1646 return -1;
1647 }
1648 }
1649 }
1650 type->tp_mro = tuple;
Christian Heimesa62da1d2008-01-12 19:39:10 +00001651
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001652 type_mro_modified(type, type->tp_mro);
Florent Xiclunaaa6c1d22011-12-12 18:54:29 +01001653 /* corner case: the super class might have been hidden
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001654 from the custom MRO */
1655 type_mro_modified(type, type->tp_bases);
Christian Heimesa62da1d2008-01-12 19:39:10 +00001656
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001657 PyType_Modified(type);
Christian Heimesa62da1d2008-01-12 19:39:10 +00001658
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001659 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001660}
1661
1662
1663/* Calculate the best base amongst multiple base classes.
1664 This is the first one that's on the path to the "solid base". */
1665
1666static PyTypeObject *
1667best_base(PyObject *bases)
1668{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001669 Py_ssize_t i, n;
1670 PyTypeObject *base, *winner, *candidate, *base_i;
1671 PyObject *base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001672
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001673 assert(PyTuple_Check(bases));
1674 n = PyTuple_GET_SIZE(bases);
1675 assert(n > 0);
1676 base = NULL;
1677 winner = NULL;
1678 for (i = 0; i < n; i++) {
1679 base_proto = PyTuple_GET_ITEM(bases, i);
1680 if (!PyType_Check(base_proto)) {
1681 PyErr_SetString(
1682 PyExc_TypeError,
1683 "bases must be types");
1684 return NULL;
1685 }
1686 base_i = (PyTypeObject *)base_proto;
1687 if (base_i->tp_dict == NULL) {
1688 if (PyType_Ready(base_i) < 0)
1689 return NULL;
1690 }
1691 candidate = solid_base(base_i);
1692 if (winner == NULL) {
1693 winner = candidate;
1694 base = base_i;
1695 }
1696 else if (PyType_IsSubtype(winner, candidate))
1697 ;
1698 else if (PyType_IsSubtype(candidate, winner)) {
1699 winner = candidate;
1700 base = base_i;
1701 }
1702 else {
1703 PyErr_SetString(
1704 PyExc_TypeError,
1705 "multiple bases have "
1706 "instance lay-out conflict");
1707 return NULL;
1708 }
1709 }
Florent Xiclunaaa6c1d22011-12-12 18:54:29 +01001710 assert (base != NULL);
1711
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001712 return base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001713}
1714
1715static int
1716extra_ivars(PyTypeObject *type, PyTypeObject *base)
1717{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001718 size_t t_size = type->tp_basicsize;
1719 size_t b_size = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001720
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001721 assert(t_size >= b_size); /* Else type smaller than base! */
1722 if (type->tp_itemsize || base->tp_itemsize) {
1723 /* If itemsize is involved, stricter rules */
1724 return t_size != b_size ||
1725 type->tp_itemsize != base->tp_itemsize;
1726 }
1727 if (type->tp_weaklistoffset && base->tp_weaklistoffset == 0 &&
1728 type->tp_weaklistoffset + sizeof(PyObject *) == t_size &&
1729 type->tp_flags & Py_TPFLAGS_HEAPTYPE)
1730 t_size -= sizeof(PyObject *);
1731 if (type->tp_dictoffset && base->tp_dictoffset == 0 &&
1732 type->tp_dictoffset + sizeof(PyObject *) == t_size &&
1733 type->tp_flags & Py_TPFLAGS_HEAPTYPE)
1734 t_size -= sizeof(PyObject *);
Guido van Rossum9676b222001-08-17 20:32:36 +00001735
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001736 return t_size != b_size;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001737}
1738
1739static PyTypeObject *
1740solid_base(PyTypeObject *type)
1741{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001742 PyTypeObject *base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001743
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001744 if (type->tp_base)
1745 base = solid_base(type->tp_base);
1746 else
1747 base = &PyBaseObject_Type;
1748 if (extra_ivars(type, base))
1749 return type;
1750 else
1751 return base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001752}
1753
Jeremy Hylton938ace62002-07-17 16:30:39 +00001754static void object_dealloc(PyObject *);
1755static int object_init(PyObject *, PyObject *, PyObject *);
1756static int update_slot(PyTypeObject *, PyObject *);
1757static void fixup_slot_dispatchers(PyTypeObject *);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001758
Guido van Rossum360e4b82007-05-14 22:51:27 +00001759/*
1760 * Helpers for __dict__ descriptor. We don't want to expose the dicts
1761 * inherited from various builtin types. The builtin base usually provides
1762 * its own __dict__ descriptor, so we use that when we can.
1763 */
1764static PyTypeObject *
1765get_builtin_base_with_dict(PyTypeObject *type)
1766{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001767 while (type->tp_base != NULL) {
1768 if (type->tp_dictoffset != 0 &&
1769 !(type->tp_flags & Py_TPFLAGS_HEAPTYPE))
1770 return type;
1771 type = type->tp_base;
1772 }
1773 return NULL;
Guido van Rossum360e4b82007-05-14 22:51:27 +00001774}
1775
1776static PyObject *
1777get_dict_descriptor(PyTypeObject *type)
1778{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001779 PyObject *descr;
Guido van Rossum360e4b82007-05-14 22:51:27 +00001780
Victor Stinner3c1e4812012-03-26 22:10:51 +02001781 descr = _PyType_LookupId(type, &PyId___dict__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001782 if (descr == NULL || !PyDescr_IsData(descr))
1783 return NULL;
Guido van Rossum360e4b82007-05-14 22:51:27 +00001784
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001785 return descr;
Guido van Rossum360e4b82007-05-14 22:51:27 +00001786}
1787
1788static void
1789raise_dict_descr_error(PyObject *obj)
1790{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001791 PyErr_Format(PyExc_TypeError,
1792 "this __dict__ descriptor does not support "
1793 "'%.200s' objects", Py_TYPE(obj)->tp_name);
Guido van Rossum360e4b82007-05-14 22:51:27 +00001794}
1795
Tim Peters6d6c1a32001-08-02 04:15:00 +00001796static PyObject *
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001797subtype_dict(PyObject *obj, void *context)
1798{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001799 PyTypeObject *base;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001800
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001801 base = get_builtin_base_with_dict(Py_TYPE(obj));
1802 if (base != NULL) {
1803 descrgetfunc func;
1804 PyObject *descr = get_dict_descriptor(base);
1805 if (descr == NULL) {
1806 raise_dict_descr_error(obj);
1807 return NULL;
1808 }
1809 func = Py_TYPE(descr)->tp_descr_get;
1810 if (func == NULL) {
1811 raise_dict_descr_error(obj);
1812 return NULL;
1813 }
1814 return func(descr, obj, (PyObject *)(Py_TYPE(obj)));
1815 }
Benjamin Peterson8eb12692012-02-19 19:59:10 -05001816 return PyObject_GenericGetDict(obj, context);
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001817}
1818
Guido van Rossum6661be32001-10-26 04:26:12 +00001819static int
1820subtype_setdict(PyObject *obj, PyObject *value, void *context)
1821{
Benjamin Peterson8eb12692012-02-19 19:59:10 -05001822 PyObject *dict, **dictptr;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001823 PyTypeObject *base;
Guido van Rossum6661be32001-10-26 04:26:12 +00001824
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001825 base = get_builtin_base_with_dict(Py_TYPE(obj));
1826 if (base != NULL) {
1827 descrsetfunc func;
1828 PyObject *descr = get_dict_descriptor(base);
1829 if (descr == NULL) {
1830 raise_dict_descr_error(obj);
1831 return -1;
1832 }
1833 func = Py_TYPE(descr)->tp_descr_set;
1834 if (func == NULL) {
1835 raise_dict_descr_error(obj);
1836 return -1;
1837 }
1838 return func(descr, obj, value);
1839 }
Benjamin Peterson8eb12692012-02-19 19:59:10 -05001840 /* Almost like PyObject_GenericSetDict, but allow __dict__ to be deleted. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001841 dictptr = _PyObject_GetDictPtr(obj);
1842 if (dictptr == NULL) {
1843 PyErr_SetString(PyExc_AttributeError,
1844 "This object has no __dict__");
1845 return -1;
1846 }
Benjamin Peterson006c5a22012-02-19 20:36:12 -05001847 if (value != NULL && !PyDict_Check(value)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001848 PyErr_Format(PyExc_TypeError,
1849 "__dict__ must be set to a dictionary, "
1850 "not a '%.200s'", Py_TYPE(value)->tp_name);
1851 return -1;
1852 }
1853 dict = *dictptr;
1854 Py_XINCREF(value);
1855 *dictptr = value;
1856 Py_XDECREF(dict);
1857 return 0;
Guido van Rossum6661be32001-10-26 04:26:12 +00001858}
1859
Guido van Rossumad47da02002-08-12 19:05:44 +00001860static PyObject *
1861subtype_getweakref(PyObject *obj, void *context)
1862{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001863 PyObject **weaklistptr;
1864 PyObject *result;
Guido van Rossumad47da02002-08-12 19:05:44 +00001865
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001866 if (Py_TYPE(obj)->tp_weaklistoffset == 0) {
1867 PyErr_SetString(PyExc_AttributeError,
1868 "This object has no __weakref__");
1869 return NULL;
1870 }
1871 assert(Py_TYPE(obj)->tp_weaklistoffset > 0);
1872 assert(Py_TYPE(obj)->tp_weaklistoffset + sizeof(PyObject *) <=
1873 (size_t)(Py_TYPE(obj)->tp_basicsize));
1874 weaklistptr = (PyObject **)
1875 ((char *)obj + Py_TYPE(obj)->tp_weaklistoffset);
1876 if (*weaklistptr == NULL)
1877 result = Py_None;
1878 else
1879 result = *weaklistptr;
1880 Py_INCREF(result);
1881 return result;
Guido van Rossumad47da02002-08-12 19:05:44 +00001882}
1883
Guido van Rossum373c7412003-01-07 13:41:37 +00001884/* Three variants on the subtype_getsets list. */
1885
1886static PyGetSetDef subtype_getsets_full[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001887 {"__dict__", subtype_dict, subtype_setdict,
1888 PyDoc_STR("dictionary for instance variables (if defined)")},
1889 {"__weakref__", subtype_getweakref, NULL,
1890 PyDoc_STR("list of weak references to the object (if defined)")},
1891 {0}
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001892};
1893
Guido van Rossum373c7412003-01-07 13:41:37 +00001894static PyGetSetDef subtype_getsets_dict_only[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001895 {"__dict__", subtype_dict, subtype_setdict,
1896 PyDoc_STR("dictionary for instance variables (if defined)")},
1897 {0}
Guido van Rossum373c7412003-01-07 13:41:37 +00001898};
1899
1900static PyGetSetDef subtype_getsets_weakref_only[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001901 {"__weakref__", subtype_getweakref, NULL,
1902 PyDoc_STR("list of weak references to the object (if defined)")},
1903 {0}
Guido van Rossum373c7412003-01-07 13:41:37 +00001904};
1905
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001906static int
1907valid_identifier(PyObject *s)
1908{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001909 if (!PyUnicode_Check(s)) {
1910 PyErr_Format(PyExc_TypeError,
1911 "__slots__ items must be strings, not '%.200s'",
1912 Py_TYPE(s)->tp_name);
1913 return 0;
1914 }
1915 if (!PyUnicode_IsIdentifier(s)) {
1916 PyErr_SetString(PyExc_TypeError,
1917 "__slots__ must be identifiers");
1918 return 0;
1919 }
1920 return 1;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001921}
1922
Guido van Rossumd8faa362007-04-27 19:54:29 +00001923/* Forward */
1924static int
1925object_init(PyObject *self, PyObject *args, PyObject *kwds);
1926
1927static int
1928type_init(PyObject *cls, PyObject *args, PyObject *kwds)
1929{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001930 int res;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001931
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001932 assert(args != NULL && PyTuple_Check(args));
1933 assert(kwds == NULL || PyDict_Check(kwds));
Guido van Rossumd8faa362007-04-27 19:54:29 +00001934
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001935 if (kwds != NULL && PyDict_Check(kwds) && PyDict_Size(kwds) != 0) {
1936 PyErr_SetString(PyExc_TypeError,
1937 "type.__init__() takes no keyword arguments");
1938 return -1;
1939 }
Guido van Rossumd8faa362007-04-27 19:54:29 +00001940
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001941 if (args != NULL && PyTuple_Check(args) &&
1942 (PyTuple_GET_SIZE(args) != 1 && PyTuple_GET_SIZE(args) != 3)) {
1943 PyErr_SetString(PyExc_TypeError,
1944 "type.__init__() takes 1 or 3 arguments");
1945 return -1;
1946 }
Guido van Rossumd8faa362007-04-27 19:54:29 +00001947
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001948 /* Call object.__init__(self) now. */
1949 /* XXX Could call super(type, cls).__init__() but what's the point? */
1950 args = PyTuple_GetSlice(args, 0, 0);
1951 res = object_init(cls, args, NULL);
1952 Py_DECREF(args);
1953 return res;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001954}
1955
Victor Stinner4ca1cf32012-10-30 23:40:45 +01001956unsigned long
Martin v. Löwis738236d2011-02-05 20:35:29 +00001957PyType_GetFlags(PyTypeObject *type)
1958{
1959 return type->tp_flags;
1960}
1961
Nick Coghlande31b192011-10-23 22:04:16 +10001962/* Determine the most derived metatype. */
1963PyTypeObject *
1964_PyType_CalculateMetaclass(PyTypeObject *metatype, PyObject *bases)
1965{
1966 Py_ssize_t i, nbases;
1967 PyTypeObject *winner;
1968 PyObject *tmp;
1969 PyTypeObject *tmptype;
1970
1971 /* Determine the proper metatype to deal with this,
1972 and check for metatype conflicts while we're at it.
1973 Note that if some other metatype wins to contract,
1974 it's possible that its instances are not types. */
1975
1976 nbases = PyTuple_GET_SIZE(bases);
1977 winner = metatype;
1978 for (i = 0; i < nbases; i++) {
1979 tmp = PyTuple_GET_ITEM(bases, i);
1980 tmptype = Py_TYPE(tmp);
1981 if (PyType_IsSubtype(winner, tmptype))
1982 continue;
1983 if (PyType_IsSubtype(tmptype, winner)) {
1984 winner = tmptype;
1985 continue;
1986 }
1987 /* else: */
1988 PyErr_SetString(PyExc_TypeError,
1989 "metaclass conflict: "
1990 "the metaclass of a derived class "
1991 "must be a (non-strict) subclass "
1992 "of the metaclasses of all its bases");
1993 return NULL;
1994 }
1995 return winner;
1996}
1997
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001998static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00001999type_new(PyTypeObject *metatype, PyObject *args, PyObject *kwds)
2000{
Victor Stinner6f738742012-02-25 01:22:36 +01002001 PyObject *name, *bases = NULL, *orig_dict, *dict = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002002 static char *kwlist[] = {"name", "bases", "dict", 0};
Victor Stinner6f738742012-02-25 01:22:36 +01002003 PyObject *qualname, *slots = NULL, *tmp, *newslots;
2004 PyTypeObject *type = NULL, *base, *tmptype, *winner;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002005 PyHeapTypeObject *et;
2006 PyMemberDef *mp;
2007 Py_ssize_t i, nbases, nslots, slotoffset, add_dict, add_weak;
2008 int j, may_add_dict, may_add_weak;
Victor Stinner3c1e4812012-03-26 22:10:51 +02002009 _Py_IDENTIFIER(__qualname__);
2010 _Py_IDENTIFIER(__slots__);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002011
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002012 assert(args != NULL && PyTuple_Check(args));
2013 assert(kwds == NULL || PyDict_Check(kwds));
Tim Peters3abca122001-10-27 19:37:48 +00002014
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002015 /* Special case: type(x) should return x->ob_type */
2016 {
2017 const Py_ssize_t nargs = PyTuple_GET_SIZE(args);
2018 const Py_ssize_t nkwds = kwds == NULL ? 0 : PyDict_Size(kwds);
Tim Peters3abca122001-10-27 19:37:48 +00002019
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002020 if (PyType_CheckExact(metatype) && nargs == 1 && nkwds == 0) {
2021 PyObject *x = PyTuple_GET_ITEM(args, 0);
2022 Py_INCREF(Py_TYPE(x));
2023 return (PyObject *) Py_TYPE(x);
2024 }
Tim Peters3abca122001-10-27 19:37:48 +00002025
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002026 /* SF bug 475327 -- if that didn't trigger, we need 3
2027 arguments. but PyArg_ParseTupleAndKeywords below may give
2028 a msg saying type() needs exactly 3. */
2029 if (nargs + nkwds != 3) {
2030 PyErr_SetString(PyExc_TypeError,
2031 "type() takes 1 or 3 arguments");
2032 return NULL;
2033 }
2034 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002035
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002036 /* Check arguments: (name, bases, dict) */
2037 if (!PyArg_ParseTupleAndKeywords(args, kwds, "UO!O!:type", kwlist,
2038 &name,
2039 &PyTuple_Type, &bases,
Victor Stinner6f738742012-02-25 01:22:36 +01002040 &PyDict_Type, &orig_dict))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002041 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002042
Nick Coghlande31b192011-10-23 22:04:16 +10002043 /* Determine the proper metatype to deal with this: */
2044 winner = _PyType_CalculateMetaclass(metatype, bases);
2045 if (winner == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002046 return NULL;
2047 }
Nick Coghlande31b192011-10-23 22:04:16 +10002048
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002049 if (winner != metatype) {
2050 if (winner->tp_new != type_new) /* Pass it to the winner */
2051 return winner->tp_new(winner, args, kwds);
2052 metatype = winner;
2053 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002054
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002055 /* Adjust for empty tuple bases */
Nick Coghlande31b192011-10-23 22:04:16 +10002056 nbases = PyTuple_GET_SIZE(bases);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002057 if (nbases == 0) {
2058 bases = PyTuple_Pack(1, &PyBaseObject_Type);
2059 if (bases == NULL)
Victor Stinner6f738742012-02-25 01:22:36 +01002060 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002061 nbases = 1;
2062 }
2063 else
2064 Py_INCREF(bases);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002065
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002066 /* Calculate best base, and check that all bases are type objects */
2067 base = best_base(bases);
2068 if (base == NULL) {
Victor Stinner6f738742012-02-25 01:22:36 +01002069 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002070 }
2071 if (!PyType_HasFeature(base, Py_TPFLAGS_BASETYPE)) {
2072 PyErr_Format(PyExc_TypeError,
2073 "type '%.100s' is not an acceptable base type",
2074 base->tp_name);
Victor Stinner6f738742012-02-25 01:22:36 +01002075 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002076 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002077
Victor Stinner6f738742012-02-25 01:22:36 +01002078 dict = PyDict_Copy(orig_dict);
2079 if (dict == NULL)
2080 goto error;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002081
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002082 /* Check for a __slots__ sequence variable in dict, and count it */
Victor Stinner3c1e4812012-03-26 22:10:51 +02002083 slots = _PyDict_GetItemId(dict, &PyId___slots__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002084 nslots = 0;
2085 add_dict = 0;
2086 add_weak = 0;
2087 may_add_dict = base->tp_dictoffset == 0;
2088 may_add_weak = base->tp_weaklistoffset == 0 && base->tp_itemsize == 0;
2089 if (slots == NULL) {
2090 if (may_add_dict) {
2091 add_dict++;
2092 }
2093 if (may_add_weak) {
2094 add_weak++;
2095 }
2096 }
2097 else {
2098 /* Have slots */
Guido van Rossumad47da02002-08-12 19:05:44 +00002099
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002100 /* Make it into a tuple */
2101 if (PyUnicode_Check(slots))
2102 slots = PyTuple_Pack(1, slots);
2103 else
2104 slots = PySequence_Tuple(slots);
Victor Stinner6f738742012-02-25 01:22:36 +01002105 if (slots == NULL)
2106 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002107 assert(PyTuple_Check(slots));
Guido van Rossumad47da02002-08-12 19:05:44 +00002108
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002109 /* Are slots allowed? */
2110 nslots = PyTuple_GET_SIZE(slots);
2111 if (nslots > 0 && base->tp_itemsize != 0) {
2112 PyErr_Format(PyExc_TypeError,
2113 "nonempty __slots__ "
2114 "not supported for subtype of '%s'",
2115 base->tp_name);
Victor Stinner6f738742012-02-25 01:22:36 +01002116 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002117 }
Guido van Rossumad47da02002-08-12 19:05:44 +00002118
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002119 /* Check for valid slot names and two special cases */
2120 for (i = 0; i < nslots; i++) {
2121 PyObject *tmp = PyTuple_GET_ITEM(slots, i);
2122 if (!valid_identifier(tmp))
Victor Stinner6f738742012-02-25 01:22:36 +01002123 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002124 assert(PyUnicode_Check(tmp));
2125 if (PyUnicode_CompareWithASCIIString(tmp, "__dict__") == 0) {
2126 if (!may_add_dict || add_dict) {
2127 PyErr_SetString(PyExc_TypeError,
2128 "__dict__ slot disallowed: "
2129 "we already got one");
Victor Stinner6f738742012-02-25 01:22:36 +01002130 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002131 }
2132 add_dict++;
2133 }
2134 if (PyUnicode_CompareWithASCIIString(tmp, "__weakref__") == 0) {
2135 if (!may_add_weak || add_weak) {
2136 PyErr_SetString(PyExc_TypeError,
2137 "__weakref__ slot disallowed: "
2138 "either we already got one, "
2139 "or __itemsize__ != 0");
Victor Stinner6f738742012-02-25 01:22:36 +01002140 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002141 }
2142 add_weak++;
2143 }
2144 }
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00002145
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002146 /* Copy slots into a list, mangle names and sort them.
2147 Sorted names are needed for __class__ assignment.
2148 Convert them back to tuple at the end.
2149 */
2150 newslots = PyList_New(nslots - add_dict - add_weak);
2151 if (newslots == NULL)
Victor Stinner6f738742012-02-25 01:22:36 +01002152 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002153 for (i = j = 0; i < nslots; i++) {
2154 tmp = PyTuple_GET_ITEM(slots, i);
2155 if ((add_dict &&
2156 PyUnicode_CompareWithASCIIString(tmp, "__dict__") == 0) ||
2157 (add_weak &&
2158 PyUnicode_CompareWithASCIIString(tmp, "__weakref__") == 0))
2159 continue;
2160 tmp =_Py_Mangle(name, tmp);
Benjamin Petersonae13c882011-08-16 22:26:48 -05002161 if (!tmp) {
2162 Py_DECREF(newslots);
Victor Stinner6f738742012-02-25 01:22:36 +01002163 goto error;
Benjamin Petersonae13c882011-08-16 22:26:48 -05002164 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002165 PyList_SET_ITEM(newslots, j, tmp);
Benjamin Petersonc4085c82011-08-16 18:53:26 -05002166 if (PyDict_GetItem(dict, tmp)) {
2167 PyErr_Format(PyExc_ValueError,
2168 "%R in __slots__ conflicts with class variable",
2169 tmp);
Benjamin Petersond17cefc2011-08-16 22:28:23 -05002170 Py_DECREF(newslots);
Victor Stinner6f738742012-02-25 01:22:36 +01002171 goto error;
Benjamin Petersonc4085c82011-08-16 18:53:26 -05002172 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002173 j++;
2174 }
2175 assert(j == nslots - add_dict - add_weak);
2176 nslots = j;
Victor Stinner6f738742012-02-25 01:22:36 +01002177 Py_CLEAR(slots);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002178 if (PyList_Sort(newslots) == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002179 Py_DECREF(newslots);
Victor Stinner6f738742012-02-25 01:22:36 +01002180 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002181 }
2182 slots = PyList_AsTuple(newslots);
2183 Py_DECREF(newslots);
Victor Stinner6f738742012-02-25 01:22:36 +01002184 if (slots == NULL)
2185 goto error;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00002186
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002187 /* Secondary bases may provide weakrefs or dict */
2188 if (nbases > 1 &&
2189 ((may_add_dict && !add_dict) ||
2190 (may_add_weak && !add_weak))) {
2191 for (i = 0; i < nbases; i++) {
2192 tmp = PyTuple_GET_ITEM(bases, i);
2193 if (tmp == (PyObject *)base)
2194 continue; /* Skip primary base */
2195 assert(PyType_Check(tmp));
2196 tmptype = (PyTypeObject *)tmp;
2197 if (may_add_dict && !add_dict &&
2198 tmptype->tp_dictoffset != 0)
2199 add_dict++;
2200 if (may_add_weak && !add_weak &&
2201 tmptype->tp_weaklistoffset != 0)
2202 add_weak++;
2203 if (may_add_dict && !add_dict)
2204 continue;
2205 if (may_add_weak && !add_weak)
2206 continue;
2207 /* Nothing more to check */
2208 break;
2209 }
2210 }
2211 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002212
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002213 /* Allocate the type object */
2214 type = (PyTypeObject *)metatype->tp_alloc(metatype, nslots);
Victor Stinner6f738742012-02-25 01:22:36 +01002215 if (type == NULL)
2216 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002217
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002218 /* Keep name and slots alive in the extended type object */
2219 et = (PyHeapTypeObject *)type;
2220 Py_INCREF(name);
2221 et->ht_name = name;
2222 et->ht_slots = slots;
Victor Stinner6f738742012-02-25 01:22:36 +01002223 slots = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002224
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002225 /* Initialize tp_flags */
2226 type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE |
2227 Py_TPFLAGS_BASETYPE;
2228 if (base->tp_flags & Py_TPFLAGS_HAVE_GC)
2229 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossumdc91b992001-08-08 22:26:22 +00002230
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002231 /* Initialize essential fields */
2232 type->tp_as_number = &et->as_number;
2233 type->tp_as_sequence = &et->as_sequence;
2234 type->tp_as_mapping = &et->as_mapping;
2235 type->tp_as_buffer = &et->as_buffer;
2236 type->tp_name = _PyUnicode_AsString(name);
Victor Stinner6f738742012-02-25 01:22:36 +01002237 if (!type->tp_name)
2238 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002239
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002240 /* Set tp_base and tp_bases */
2241 type->tp_bases = bases;
Victor Stinner6f738742012-02-25 01:22:36 +01002242 bases = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002243 Py_INCREF(base);
2244 type->tp_base = base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002245
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002246 /* Initialize tp_dict from passed-in dict */
Victor Stinner6f738742012-02-25 01:22:36 +01002247 Py_INCREF(dict);
2248 type->tp_dict = dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002249
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002250 /* Set __module__ in the dict */
Victor Stinner3c1e4812012-03-26 22:10:51 +02002251 if (_PyDict_GetItemId(dict, &PyId___module__) == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002252 tmp = PyEval_GetGlobals();
2253 if (tmp != NULL) {
Victor Stinner3c1e4812012-03-26 22:10:51 +02002254 tmp = _PyDict_GetItemId(tmp, &PyId___name__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002255 if (tmp != NULL) {
Victor Stinner3c1e4812012-03-26 22:10:51 +02002256 if (_PyDict_SetItemId(dict, &PyId___module__,
2257 tmp) < 0)
Victor Stinner6f738742012-02-25 01:22:36 +01002258 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002259 }
2260 }
2261 }
Guido van Rossumc3542212001-08-16 09:18:56 +00002262
Victor Stinner6f738742012-02-25 01:22:36 +01002263 /* Set ht_qualname to dict['__qualname__'] if available, else to
2264 __name__. The __qualname__ accessor will look for ht_qualname.
2265 */
Victor Stinner3c1e4812012-03-26 22:10:51 +02002266 qualname = _PyDict_GetItemId(dict, &PyId___qualname__);
Victor Stinner6f738742012-02-25 01:22:36 +01002267 if (qualname != NULL) {
2268 if (!PyUnicode_Check(qualname)) {
2269 PyErr_Format(PyExc_TypeError,
2270 "type __qualname__ must be a str, not %s",
2271 Py_TYPE(qualname)->tp_name);
2272 goto error;
2273 }
2274 }
Benjamin Peterson8afa7fa2012-10-30 23:51:03 -04002275 et->ht_qualname = qualname ? qualname : et->ht_name;
2276 Py_INCREF(et->ht_qualname);
2277 if (qualname != NULL && PyDict_DelItem(dict, PyId___qualname__.object) < 0)
2278 goto error;
Victor Stinner6f738742012-02-25 01:22:36 +01002279
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002280 /* Set tp_doc to a copy of dict['__doc__'], if the latter is there
2281 and is a string. The __doc__ accessor will first look for tp_doc;
2282 if that fails, it will still look into __dict__.
2283 */
2284 {
Victor Stinner3c1e4812012-03-26 22:10:51 +02002285 PyObject *doc = _PyDict_GetItemId(dict, &PyId___doc__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002286 if (doc != NULL && PyUnicode_Check(doc)) {
2287 Py_ssize_t len;
2288 char *doc_str;
2289 char *tp_doc;
Alexandre Vassalottia85998a2008-05-03 18:24:43 +00002290
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002291 doc_str = _PyUnicode_AsString(doc);
Victor Stinner6f738742012-02-25 01:22:36 +01002292 if (doc_str == NULL)
2293 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002294 /* Silently truncate the docstring if it contains null bytes. */
2295 len = strlen(doc_str);
2296 tp_doc = (char *)PyObject_MALLOC(len + 1);
Victor Stinner53510cd2013-07-15 19:34:20 +02002297 if (tp_doc == NULL) {
2298 PyErr_NoMemory();
Victor Stinner6f738742012-02-25 01:22:36 +01002299 goto error;
Victor Stinner53510cd2013-07-15 19:34:20 +02002300 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002301 memcpy(tp_doc, doc_str, len + 1);
2302 type->tp_doc = tp_doc;
2303 }
2304 }
Tim Peters2f93e282001-10-04 05:27:00 +00002305
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002306 /* Special-case __new__: if it's a plain function,
2307 make it a static function */
Victor Stinner3c1e4812012-03-26 22:10:51 +02002308 tmp = _PyDict_GetItemId(dict, &PyId___new__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002309 if (tmp != NULL && PyFunction_Check(tmp)) {
2310 tmp = PyStaticMethod_New(tmp);
Victor Stinner6f738742012-02-25 01:22:36 +01002311 if (tmp == NULL)
2312 goto error;
Victor Stinner3c1e4812012-03-26 22:10:51 +02002313 if (_PyDict_SetItemId(dict, &PyId___new__, tmp) < 0)
2314 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002315 Py_DECREF(tmp);
2316 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002317
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002318 /* Add descriptors for custom slots from __slots__, or for __dict__ */
2319 mp = PyHeapType_GET_MEMBERS(et);
2320 slotoffset = base->tp_basicsize;
Victor Stinner6f738742012-02-25 01:22:36 +01002321 if (et->ht_slots != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002322 for (i = 0; i < nslots; i++, mp++) {
2323 mp->name = _PyUnicode_AsString(
Victor Stinner6f738742012-02-25 01:22:36 +01002324 PyTuple_GET_ITEM(et->ht_slots, i));
2325 if (mp->name == NULL)
2326 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002327 mp->type = T_OBJECT_EX;
2328 mp->offset = slotoffset;
Guido van Rossumd8faa362007-04-27 19:54:29 +00002329
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002330 /* __dict__ and __weakref__ are already filtered out */
2331 assert(strcmp(mp->name, "__dict__") != 0);
2332 assert(strcmp(mp->name, "__weakref__") != 0);
Guido van Rossumd8faa362007-04-27 19:54:29 +00002333
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002334 slotoffset += sizeof(PyObject *);
2335 }
2336 }
2337 if (add_dict) {
2338 if (base->tp_itemsize)
2339 type->tp_dictoffset = -(long)sizeof(PyObject *);
2340 else
2341 type->tp_dictoffset = slotoffset;
2342 slotoffset += sizeof(PyObject *);
2343 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002344 if (type->tp_dictoffset) {
2345 et->ht_cached_keys = _PyDict_NewKeysForClass();
2346 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002347 if (add_weak) {
2348 assert(!base->tp_itemsize);
2349 type->tp_weaklistoffset = slotoffset;
2350 slotoffset += sizeof(PyObject *);
2351 }
2352 type->tp_basicsize = slotoffset;
2353 type->tp_itemsize = base->tp_itemsize;
2354 type->tp_members = PyHeapType_GET_MEMBERS(et);
Guido van Rossum373c7412003-01-07 13:41:37 +00002355
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002356 if (type->tp_weaklistoffset && type->tp_dictoffset)
2357 type->tp_getset = subtype_getsets_full;
2358 else if (type->tp_weaklistoffset && !type->tp_dictoffset)
2359 type->tp_getset = subtype_getsets_weakref_only;
2360 else if (!type->tp_weaklistoffset && type->tp_dictoffset)
2361 type->tp_getset = subtype_getsets_dict_only;
2362 else
2363 type->tp_getset = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002364
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002365 /* Special case some slots */
2366 if (type->tp_dictoffset != 0 || nslots > 0) {
2367 if (base->tp_getattr == NULL && base->tp_getattro == NULL)
2368 type->tp_getattro = PyObject_GenericGetAttr;
2369 if (base->tp_setattr == NULL && base->tp_setattro == NULL)
2370 type->tp_setattro = PyObject_GenericSetAttr;
2371 }
2372 type->tp_dealloc = subtype_dealloc;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002373
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002374 /* Enable GC unless there are really no instance variables possible */
2375 if (!(type->tp_basicsize == sizeof(PyObject) &&
2376 type->tp_itemsize == 0))
2377 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossum9475a232001-10-05 20:51:39 +00002378
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002379 /* Always override allocation strategy to use regular heap */
2380 type->tp_alloc = PyType_GenericAlloc;
2381 if (type->tp_flags & Py_TPFLAGS_HAVE_GC) {
2382 type->tp_free = PyObject_GC_Del;
2383 type->tp_traverse = subtype_traverse;
2384 type->tp_clear = subtype_clear;
2385 }
2386 else
2387 type->tp_free = PyObject_Del;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002388
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002389 /* Initialize the rest */
Victor Stinner6f738742012-02-25 01:22:36 +01002390 if (PyType_Ready(type) < 0)
2391 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002392
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002393 /* Put the proper slots in place */
2394 fixup_slot_dispatchers(type);
Guido van Rossumf040ede2001-08-07 16:40:56 +00002395
Victor Stinner6f738742012-02-25 01:22:36 +01002396 Py_DECREF(dict);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002397 return (PyObject *)type;
Victor Stinner6f738742012-02-25 01:22:36 +01002398
2399error:
2400 Py_XDECREF(dict);
2401 Py_XDECREF(bases);
2402 Py_XDECREF(slots);
2403 Py_XDECREF(type);
2404 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002405}
2406
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002407static short slotoffsets[] = {
2408 -1, /* invalid slot */
2409#include "typeslots.inc"
2410};
2411
Benjamin Petersone28108c2012-01-29 20:13:18 -05002412PyObject *
Martin v. Löwis9c564092012-06-23 23:20:45 +02002413PyType_FromSpecWithBases(PyType_Spec *spec, PyObject *bases)
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002414{
2415 PyHeapTypeObject *res = (PyHeapTypeObject*)PyType_GenericAlloc(&PyType_Type, 0);
Martin v. Löwis9c564092012-06-23 23:20:45 +02002416 PyTypeObject *type, *base;
2417 char *s;
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002418 char *res_start = (char*)res;
2419 PyType_Slot *slot;
Victor Stinner54e4ca72013-07-11 22:42:25 +02002420
Martin v. Löwis9c564092012-06-23 23:20:45 +02002421 /* Set the type name and qualname */
2422 s = strrchr(spec->name, '.');
2423 if (s == NULL)
2424 s = (char*)spec->name;
2425 else
2426 s++;
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002427
Martin v. Löwis5e06a5d2011-02-21 16:24:00 +00002428 if (res == NULL)
Antoine Pitroubb78f572012-06-24 00:18:27 +02002429 return NULL;
2430 type = &res->ht_type;
Antoine Pitrou66a3a7e2012-06-24 00:42:59 +02002431 /* The flags must be initialized early, before the GC traverses us */
2432 type->tp_flags = spec->flags | Py_TPFLAGS_HEAPTYPE;
Martin v. Löwis9c564092012-06-23 23:20:45 +02002433 res->ht_name = PyUnicode_FromString(s);
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002434 if (!res->ht_name)
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002435 goto fail;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002436 res->ht_qualname = res->ht_name;
2437 Py_INCREF(res->ht_qualname);
Antoine Pitroubb78f572012-06-24 00:18:27 +02002438 type->tp_name = spec->name;
2439 if (!type->tp_name)
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002440 goto fail;
Victor Stinner54e4ca72013-07-11 22:42:25 +02002441
Martin v. Löwis9c564092012-06-23 23:20:45 +02002442 /* Adjust for empty tuple bases */
2443 if (!bases) {
2444 base = &PyBaseObject_Type;
2445 /* See whether Py_tp_base(s) was specified */
2446 for (slot = spec->slots; slot->slot; slot++) {
2447 if (slot->slot == Py_tp_base)
2448 base = slot->pfunc;
2449 else if (slot->slot == Py_tp_bases) {
2450 bases = slot->pfunc;
2451 Py_INCREF(bases);
2452 }
2453 }
2454 if (!bases)
2455 bases = PyTuple_Pack(1, base);
2456 if (!bases)
2457 goto fail;
2458 }
2459 else
2460 Py_INCREF(bases);
2461
2462 /* Calculate best base, and check that all bases are type objects */
2463 base = best_base(bases);
2464 if (base == NULL) {
2465 goto fail;
2466 }
2467 if (!PyType_HasFeature(base, Py_TPFLAGS_BASETYPE)) {
2468 PyErr_Format(PyExc_TypeError,
2469 "type '%.100s' is not an acceptable base type",
2470 base->tp_name);
2471 goto fail;
2472 }
2473
Martin v. Löwis9c564092012-06-23 23:20:45 +02002474 /* Initialize essential fields */
2475 type->tp_as_number = &res->as_number;
2476 type->tp_as_sequence = &res->as_sequence;
2477 type->tp_as_mapping = &res->as_mapping;
2478 type->tp_as_buffer = &res->as_buffer;
2479 /* Set tp_base and tp_bases */
2480 type->tp_bases = bases;
2481 bases = NULL;
2482 Py_INCREF(base);
2483 type->tp_base = base;
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002484
Antoine Pitroubb78f572012-06-24 00:18:27 +02002485 type->tp_basicsize = spec->basicsize;
2486 type->tp_itemsize = spec->itemsize;
Victor Stinner0fcab4a2011-01-04 12:59:15 +00002487
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002488 for (slot = spec->slots; slot->slot; slot++) {
Victor Stinner63941882011-09-29 00:42:28 +02002489 if (slot->slot >= Py_ARRAY_LENGTH(slotoffsets)) {
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002490 PyErr_SetString(PyExc_RuntimeError, "invalid slot offset");
2491 goto fail;
2492 }
Martin v. Löwis9c564092012-06-23 23:20:45 +02002493 if (slot->slot == Py_tp_base || slot->slot == Py_tp_bases)
2494 /* Processed above */
2495 continue;
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002496 *(void**)(res_start + slotoffsets[slot->slot]) = slot->pfunc;
Georg Brandl032400b2011-02-19 21:47:02 +00002497
2498 /* need to make a copy of the docstring slot, which usually
2499 points to a static string literal */
2500 if (slot->slot == Py_tp_doc) {
Antoine Pitrou682d94c2012-05-14 14:43:03 +02002501 size_t len = strlen(slot->pfunc)+1;
Georg Brandl032400b2011-02-19 21:47:02 +00002502 char *tp_doc = PyObject_MALLOC(len);
Victor Stinner53510cd2013-07-15 19:34:20 +02002503 if (tp_doc == NULL) {
2504 PyErr_NoMemory();
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002505 goto fail;
Victor Stinner53510cd2013-07-15 19:34:20 +02002506 }
Georg Brandl032400b2011-02-19 21:47:02 +00002507 memcpy(tp_doc, slot->pfunc, len);
Antoine Pitroubb78f572012-06-24 00:18:27 +02002508 type->tp_doc = tp_doc;
Georg Brandl032400b2011-02-19 21:47:02 +00002509 }
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002510 }
Antoine Pitroubb78f572012-06-24 00:18:27 +02002511 if (type->tp_dictoffset) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002512 res->ht_cached_keys = _PyDict_NewKeysForClass();
2513 }
Antoine Pitroubb78f572012-06-24 00:18:27 +02002514 if (type->tp_dealloc == NULL) {
Antoine Pitrou99cc6292012-06-23 14:42:38 +02002515 /* It's a heap type, so needs the heap types' dealloc.
2516 subtype_dealloc will call the base type's tp_dealloc, if
2517 necessary. */
Antoine Pitroubb78f572012-06-24 00:18:27 +02002518 type->tp_dealloc = subtype_dealloc;
Antoine Pitrou99cc6292012-06-23 14:42:38 +02002519 }
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002520
Antoine Pitroubb78f572012-06-24 00:18:27 +02002521 if (PyType_Ready(type) < 0)
Benjamin Peterson2652d252012-01-29 20:16:37 -05002522 goto fail;
2523
Martin v. Löwis9c564092012-06-23 23:20:45 +02002524 /* Set type.__module__ */
2525 s = strrchr(spec->name, '.');
2526 if (s != NULL)
Victor Stinner54e4ca72013-07-11 22:42:25 +02002527 _PyDict_SetItemId(type->tp_dict, &PyId___module__,
Martin v. Löwis9c564092012-06-23 23:20:45 +02002528 PyUnicode_FromStringAndSize(
2529 spec->name, (Py_ssize_t)(s - spec->name)));
2530
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002531 return (PyObject*)res;
Victor Stinner0fcab4a2011-01-04 12:59:15 +00002532
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002533 fail:
2534 Py_DECREF(res);
2535 return NULL;
2536}
2537
Martin v. Löwis9c564092012-06-23 23:20:45 +02002538PyObject *
2539PyType_FromSpec(PyType_Spec *spec)
2540{
2541 return PyType_FromSpecWithBases(spec, NULL);
2542}
2543
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002544
Tim Peters6d6c1a32001-08-02 04:15:00 +00002545/* Internal API to look for a name through the MRO.
2546 This returns a borrowed reference, and doesn't set an exception! */
2547PyObject *
2548_PyType_Lookup(PyTypeObject *type, PyObject *name)
2549{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002550 Py_ssize_t i, n;
2551 PyObject *mro, *res, *base, *dict;
2552 unsigned int h;
Christian Heimesa62da1d2008-01-12 19:39:10 +00002553
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002554 if (MCACHE_CACHEABLE_NAME(name) &&
2555 PyType_HasFeature(type, Py_TPFLAGS_VALID_VERSION_TAG)) {
2556 /* fast path */
2557 h = MCACHE_HASH_METHOD(type, name);
2558 if (method_cache[h].version == type->tp_version_tag &&
2559 method_cache[h].name == name)
2560 return method_cache[h].value;
2561 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002562
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002563 /* Look in tp_dict of types in MRO */
2564 mro = type->tp_mro;
Guido van Rossum23094982002-06-10 14:30:43 +00002565
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002566 /* If mro is NULL, the type is either not yet initialized
2567 by PyType_Ready(), or already cleared by type_clear().
2568 Either way the safest thing to do is to return NULL. */
2569 if (mro == NULL)
2570 return NULL;
Guido van Rossum23094982002-06-10 14:30:43 +00002571
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002572 res = NULL;
Victor Stinnerd74782b2012-03-09 00:39:08 +01002573 /* keep a strong reference to mro because type->tp_mro can be replaced
2574 during PyDict_GetItem(dict, name) */
2575 Py_INCREF(mro);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002576 assert(PyTuple_Check(mro));
2577 n = PyTuple_GET_SIZE(mro);
2578 for (i = 0; i < n; i++) {
2579 base = PyTuple_GET_ITEM(mro, i);
2580 assert(PyType_Check(base));
2581 dict = ((PyTypeObject *)base)->tp_dict;
2582 assert(dict && PyDict_Check(dict));
2583 res = PyDict_GetItem(dict, name);
2584 if (res != NULL)
2585 break;
2586 }
Victor Stinnerd74782b2012-03-09 00:39:08 +01002587 Py_DECREF(mro);
Christian Heimesa62da1d2008-01-12 19:39:10 +00002588
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002589 if (MCACHE_CACHEABLE_NAME(name) && assign_version_tag(type)) {
2590 h = MCACHE_HASH_METHOD(type, name);
2591 method_cache[h].version = type->tp_version_tag;
2592 method_cache[h].value = res; /* borrowed */
2593 Py_INCREF(name);
2594 Py_DECREF(method_cache[h].name);
2595 method_cache[h].name = name;
2596 }
2597 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002598}
2599
Victor Stinner3c1e4812012-03-26 22:10:51 +02002600static PyObject *
2601_PyType_LookupId(PyTypeObject *type, struct _Py_Identifier *name)
2602{
2603 PyObject *oname;
2604 oname = _PyUnicode_FromId(name); /* borrowed */
2605 if (oname == NULL)
2606 return NULL;
2607 return _PyType_Lookup(type, oname);
2608}
2609
Tim Peters6d6c1a32001-08-02 04:15:00 +00002610/* This is similar to PyObject_GenericGetAttr(),
2611 but uses _PyType_Lookup() instead of just looking in type->tp_dict. */
2612static PyObject *
2613type_getattro(PyTypeObject *type, PyObject *name)
2614{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002615 PyTypeObject *metatype = Py_TYPE(type);
2616 PyObject *meta_attribute, *attribute;
2617 descrgetfunc meta_get;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002618
Benjamin Peterson16d84ac2012-03-16 09:32:59 -05002619 if (!PyUnicode_Check(name)) {
2620 PyErr_Format(PyExc_TypeError,
2621 "attribute name must be string, not '%.200s'",
2622 name->ob_type->tp_name);
2623 return NULL;
2624 }
2625
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002626 /* Initialize this type (we'll assume the metatype is initialized) */
2627 if (type->tp_dict == NULL) {
2628 if (PyType_Ready(type) < 0)
2629 return NULL;
2630 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002631
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002632 /* No readable descriptor found yet */
2633 meta_get = NULL;
Tim Peters34592512002-07-11 06:23:50 +00002634
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002635 /* Look for the attribute in the metatype */
2636 meta_attribute = _PyType_Lookup(metatype, name);
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002637
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002638 if (meta_attribute != NULL) {
2639 meta_get = Py_TYPE(meta_attribute)->tp_descr_get;
Tim Peters34592512002-07-11 06:23:50 +00002640
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002641 if (meta_get != NULL && PyDescr_IsData(meta_attribute)) {
2642 /* Data descriptors implement tp_descr_set to intercept
2643 * writes. Assume the attribute is not overridden in
2644 * type's tp_dict (and bases): call the descriptor now.
2645 */
2646 return meta_get(meta_attribute, (PyObject *)type,
2647 (PyObject *)metatype);
2648 }
2649 Py_INCREF(meta_attribute);
2650 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002651
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002652 /* No data descriptor found on metatype. Look in tp_dict of this
2653 * type and its bases */
2654 attribute = _PyType_Lookup(type, name);
2655 if (attribute != NULL) {
2656 /* Implement descriptor functionality, if any */
2657 descrgetfunc local_get = Py_TYPE(attribute)->tp_descr_get;
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00002658
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002659 Py_XDECREF(meta_attribute);
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00002660
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002661 if (local_get != NULL) {
2662 /* NULL 2nd argument indicates the descriptor was
2663 * found on the target object itself (or a base) */
2664 return local_get(attribute, (PyObject *)NULL,
2665 (PyObject *)type);
2666 }
Tim Peters34592512002-07-11 06:23:50 +00002667
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002668 Py_INCREF(attribute);
2669 return attribute;
2670 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002671
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002672 /* No attribute found in local __dict__ (or bases): use the
2673 * descriptor from the metatype, if any */
2674 if (meta_get != NULL) {
2675 PyObject *res;
2676 res = meta_get(meta_attribute, (PyObject *)type,
2677 (PyObject *)metatype);
2678 Py_DECREF(meta_attribute);
2679 return res;
2680 }
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002681
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002682 /* If an ordinary attribute was found on the metatype, return it now */
2683 if (meta_attribute != NULL) {
2684 return meta_attribute;
2685 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002686
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002687 /* Give up */
2688 PyErr_Format(PyExc_AttributeError,
2689 "type object '%.50s' has no attribute '%U'",
2690 type->tp_name, name);
2691 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002692}
2693
2694static int
2695type_setattro(PyTypeObject *type, PyObject *name, PyObject *value)
2696{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002697 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
2698 PyErr_Format(
2699 PyExc_TypeError,
2700 "can't set attributes of built-in/extension type '%s'",
2701 type->tp_name);
2702 return -1;
2703 }
2704 if (PyObject_GenericSetAttr((PyObject *)type, name, value) < 0)
2705 return -1;
2706 return update_slot(type, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002707}
2708
Benjamin Peterson64acccf2012-04-27 15:07:36 -04002709extern void
2710_PyDictKeys_DecRef(PyDictKeysObject *keys);
2711
Tim Peters6d6c1a32001-08-02 04:15:00 +00002712static void
2713type_dealloc(PyTypeObject *type)
2714{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002715 PyHeapTypeObject *et;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002716
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002717 /* Assert this is a heap-allocated type object */
2718 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
2719 _PyObject_GC_UNTRACK(type);
2720 PyObject_ClearWeakRefs((PyObject *)type);
2721 et = (PyHeapTypeObject *)type;
2722 Py_XDECREF(type->tp_base);
2723 Py_XDECREF(type->tp_dict);
2724 Py_XDECREF(type->tp_bases);
2725 Py_XDECREF(type->tp_mro);
2726 Py_XDECREF(type->tp_cache);
2727 Py_XDECREF(type->tp_subclasses);
2728 /* A type's tp_doc is heap allocated, unlike the tp_doc slots
2729 * of most other objects. It's okay to cast it to char *.
2730 */
2731 PyObject_Free((char *)type->tp_doc);
2732 Py_XDECREF(et->ht_name);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002733 Py_XDECREF(et->ht_qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002734 Py_XDECREF(et->ht_slots);
Benjamin Peterson64acccf2012-04-27 15:07:36 -04002735 if (et->ht_cached_keys)
2736 _PyDictKeys_DecRef(et->ht_cached_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002737 Py_TYPE(type)->tp_free((PyObject *)type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002738}
2739
Guido van Rossum1c450732001-10-08 15:18:27 +00002740static PyObject *
2741type_subclasses(PyTypeObject *type, PyObject *args_ignored)
2742{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002743 PyObject *list, *raw, *ref;
2744 Py_ssize_t i, n;
Guido van Rossum1c450732001-10-08 15:18:27 +00002745
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002746 list = PyList_New(0);
2747 if (list == NULL)
2748 return NULL;
2749 raw = type->tp_subclasses;
2750 if (raw == NULL)
2751 return list;
2752 assert(PyList_Check(raw));
2753 n = PyList_GET_SIZE(raw);
2754 for (i = 0; i < n; i++) {
2755 ref = PyList_GET_ITEM(raw, i);
2756 assert(PyWeakref_CheckRef(ref));
2757 ref = PyWeakref_GET_OBJECT(ref);
2758 if (ref != Py_None) {
2759 if (PyList_Append(list, ref) < 0) {
2760 Py_DECREF(list);
2761 return NULL;
2762 }
2763 }
2764 }
2765 return list;
Guido van Rossum1c450732001-10-08 15:18:27 +00002766}
2767
Guido van Rossum47374822007-08-02 16:48:17 +00002768static PyObject *
2769type_prepare(PyObject *self, PyObject *args, PyObject *kwds)
2770{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002771 return PyDict_New();
Guido van Rossum47374822007-08-02 16:48:17 +00002772}
2773
Victor Stinner63941882011-09-29 00:42:28 +02002774/*
Benjamin Peterson82b00c12011-05-24 11:09:06 -05002775 Merge the __dict__ of aclass into dict, and recursively also all
2776 the __dict__s of aclass's base classes. The order of merging isn't
2777 defined, as it's expected that only the final set of dict keys is
2778 interesting.
2779 Return 0 on success, -1 on error.
2780*/
2781
2782static int
2783merge_class_dict(PyObject *dict, PyObject *aclass)
2784{
2785 PyObject *classdict;
2786 PyObject *bases;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02002787 _Py_IDENTIFIER(__bases__);
Benjamin Peterson82b00c12011-05-24 11:09:06 -05002788
2789 assert(PyDict_Check(dict));
2790 assert(aclass);
2791
2792 /* Merge in the type's dict (if any). */
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002793 classdict = _PyObject_GetAttrId(aclass, &PyId___dict__);
Benjamin Peterson82b00c12011-05-24 11:09:06 -05002794 if (classdict == NULL)
2795 PyErr_Clear();
2796 else {
2797 int status = PyDict_Update(dict, classdict);
2798 Py_DECREF(classdict);
2799 if (status < 0)
2800 return -1;
2801 }
2802
2803 /* Recursively merge in the base types' (if any) dicts. */
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002804 bases = _PyObject_GetAttrId(aclass, &PyId___bases__);
Benjamin Peterson82b00c12011-05-24 11:09:06 -05002805 if (bases == NULL)
2806 PyErr_Clear();
2807 else {
2808 /* We have no guarantee that bases is a real tuple */
2809 Py_ssize_t i, n;
2810 n = PySequence_Size(bases); /* This better be right */
2811 if (n < 0)
2812 PyErr_Clear();
2813 else {
2814 for (i = 0; i < n; i++) {
2815 int status;
2816 PyObject *base = PySequence_GetItem(bases, i);
2817 if (base == NULL) {
2818 Py_DECREF(bases);
2819 return -1;
2820 }
2821 status = merge_class_dict(dict, base);
2822 Py_DECREF(base);
2823 if (status < 0) {
2824 Py_DECREF(bases);
2825 return -1;
2826 }
2827 }
2828 }
2829 Py_DECREF(bases);
2830 }
2831 return 0;
2832}
2833
2834/* __dir__ for type objects: returns __dict__ and __bases__.
2835 We deliberately don't suck up its __class__, as methods belonging to the
2836 metaclass would probably be more confusing than helpful.
2837*/
2838static PyObject *
2839type_dir(PyObject *self, PyObject *args)
2840{
2841 PyObject *result = NULL;
2842 PyObject *dict = PyDict_New();
2843
2844 if (dict != NULL && merge_class_dict(dict, self) == 0)
2845 result = PyDict_Keys(dict);
2846
2847 Py_XDECREF(dict);
2848 return result;
2849}
2850
Martin v. Loewis4f2f3b62012-04-24 19:13:57 +02002851static PyObject*
2852type_sizeof(PyObject *self, PyObject *args_unused)
2853{
2854 Py_ssize_t size;
2855 PyTypeObject *type = (PyTypeObject*)self;
2856 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
2857 PyHeapTypeObject* et = (PyHeapTypeObject*)type;
2858 size = sizeof(PyHeapTypeObject);
2859 if (et->ht_cached_keys)
2860 size += _PyDict_KeysSize(et->ht_cached_keys);
2861 }
2862 else
2863 size = sizeof(PyTypeObject);
2864 return PyLong_FromSsize_t(size);
2865}
2866
Tim Peters6d6c1a32001-08-02 04:15:00 +00002867static PyMethodDef type_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002868 {"mro", (PyCFunction)mro_external, METH_NOARGS,
2869 PyDoc_STR("mro() -> list\nreturn a type's method resolution order")},
2870 {"__subclasses__", (PyCFunction)type_subclasses, METH_NOARGS,
2871 PyDoc_STR("__subclasses__() -> list of immediate subclasses")},
2872 {"__prepare__", (PyCFunction)type_prepare,
2873 METH_VARARGS | METH_KEYWORDS | METH_CLASS,
2874 PyDoc_STR("__prepare__() -> dict\n"
2875 "used to create the namespace for the class statement")},
2876 {"__instancecheck__", type___instancecheck__, METH_O,
Benjamin Petersonfbe56bb2011-05-24 12:42:51 -05002877 PyDoc_STR("__instancecheck__() -> bool\ncheck if an object is an instance")},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002878 {"__subclasscheck__", type___subclasscheck__, METH_O,
Benjamin Petersonfbe56bb2011-05-24 12:42:51 -05002879 PyDoc_STR("__subclasscheck__() -> bool\ncheck if a class is a subclass")},
Benjamin Peterson82b00c12011-05-24 11:09:06 -05002880 {"__dir__", type_dir, METH_NOARGS,
Benjamin Petersonc7284122011-05-24 12:46:15 -05002881 PyDoc_STR("__dir__() -> list\nspecialized __dir__ implementation for types")},
Martin v. Loewis4f2f3b62012-04-24 19:13:57 +02002882 {"__sizeof__", type_sizeof, METH_NOARGS,
2883 "__sizeof__() -> int\nreturn memory consumption of the type object"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002884 {0}
Tim Peters6d6c1a32001-08-02 04:15:00 +00002885};
2886
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002887PyDoc_STRVAR(type_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00002888"type(object) -> the object's type\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002889"type(name, bases, dict) -> a new type");
Tim Peters6d6c1a32001-08-02 04:15:00 +00002890
Guido van Rossum048eb752001-10-02 21:24:57 +00002891static int
2892type_traverse(PyTypeObject *type, visitproc visit, void *arg)
2893{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002894 /* Because of type_is_gc(), the collector only calls this
2895 for heaptypes. */
Antoine Pitrou1351ca62012-06-24 00:30:12 +02002896 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
2897 char msg[200];
2898 sprintf(msg, "type_traverse() called for non-heap type '%.100s'",
2899 type->tp_name);
2900 Py_FatalError(msg);
2901 }
Guido van Rossum048eb752001-10-02 21:24:57 +00002902
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002903 Py_VISIT(type->tp_dict);
2904 Py_VISIT(type->tp_cache);
2905 Py_VISIT(type->tp_mro);
2906 Py_VISIT(type->tp_bases);
2907 Py_VISIT(type->tp_base);
Guido van Rossuma3862092002-06-10 15:24:42 +00002908
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002909 /* There's no need to visit type->tp_subclasses or
2910 ((PyHeapTypeObject *)type)->ht_slots, because they can't be involved
2911 in cycles; tp_subclasses is a list of weak references,
2912 and slots is a tuple of strings. */
Guido van Rossum048eb752001-10-02 21:24:57 +00002913
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002914 return 0;
Guido van Rossum048eb752001-10-02 21:24:57 +00002915}
2916
2917static int
2918type_clear(PyTypeObject *type)
2919{
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002920 PyDictKeysObject *cached_keys;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002921 /* Because of type_is_gc(), the collector only calls this
2922 for heaptypes. */
2923 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002924
Antoine Pitrou2e872082011-12-15 14:15:31 +01002925 /* We need to invalidate the method cache carefully before clearing
2926 the dict, so that other objects caught in a reference cycle
2927 don't start calling destroyed methods.
2928
2929 Otherwise, the only field we need to clear is tp_mro, which is
2930 part of a hard cycle (its first element is the class itself) that
2931 won't be broken otherwise (it's a tuple and tuples don't have a
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002932 tp_clear handler). None of the other fields need to be
2933 cleared, and here's why:
Guido van Rossum048eb752001-10-02 21:24:57 +00002934
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002935 tp_cache:
2936 Not used; if it were, it would be a dict.
Guido van Rossuma3862092002-06-10 15:24:42 +00002937
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002938 tp_bases, tp_base:
2939 If these are involved in a cycle, there must be at least
2940 one other, mutable object in the cycle, e.g. a base
2941 class's dict; the cycle will be broken that way.
Guido van Rossuma3862092002-06-10 15:24:42 +00002942
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002943 tp_subclasses:
2944 A list of weak references can't be part of a cycle; and
2945 lists have their own tp_clear.
Guido van Rossuma3862092002-06-10 15:24:42 +00002946
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002947 slots (in PyHeapTypeObject):
2948 A tuple of strings can't be part of a cycle.
2949 */
Guido van Rossuma3862092002-06-10 15:24:42 +00002950
Antoine Pitrou2e872082011-12-15 14:15:31 +01002951 PyType_Modified(type);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002952 cached_keys = ((PyHeapTypeObject *)type)->ht_cached_keys;
2953 if (cached_keys != NULL) {
2954 ((PyHeapTypeObject *)type)->ht_cached_keys = NULL;
2955 _PyDictKeys_DecRef(cached_keys);
2956 }
Antoine Pitrou2e872082011-12-15 14:15:31 +01002957 if (type->tp_dict)
2958 PyDict_Clear(type->tp_dict);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002959 Py_CLEAR(type->tp_mro);
Guido van Rossum048eb752001-10-02 21:24:57 +00002960
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002961 return 0;
Guido van Rossum048eb752001-10-02 21:24:57 +00002962}
2963
2964static int
2965type_is_gc(PyTypeObject *type)
2966{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002967 return type->tp_flags & Py_TPFLAGS_HEAPTYPE;
Guido van Rossum048eb752001-10-02 21:24:57 +00002968}
2969
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002970PyTypeObject PyType_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002971 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2972 "type", /* tp_name */
2973 sizeof(PyHeapTypeObject), /* tp_basicsize */
2974 sizeof(PyMemberDef), /* tp_itemsize */
2975 (destructor)type_dealloc, /* tp_dealloc */
2976 0, /* tp_print */
2977 0, /* tp_getattr */
2978 0, /* tp_setattr */
2979 0, /* tp_reserved */
2980 (reprfunc)type_repr, /* tp_repr */
2981 0, /* tp_as_number */
2982 0, /* tp_as_sequence */
2983 0, /* tp_as_mapping */
2984 0, /* tp_hash */
2985 (ternaryfunc)type_call, /* tp_call */
2986 0, /* tp_str */
2987 (getattrofunc)type_getattro, /* tp_getattro */
2988 (setattrofunc)type_setattro, /* tp_setattro */
2989 0, /* tp_as_buffer */
2990 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
2991 Py_TPFLAGS_BASETYPE | Py_TPFLAGS_TYPE_SUBCLASS, /* tp_flags */
2992 type_doc, /* tp_doc */
2993 (traverseproc)type_traverse, /* tp_traverse */
2994 (inquiry)type_clear, /* tp_clear */
2995 0, /* tp_richcompare */
2996 offsetof(PyTypeObject, tp_weaklist), /* tp_weaklistoffset */
2997 0, /* tp_iter */
2998 0, /* tp_iternext */
2999 type_methods, /* tp_methods */
3000 type_members, /* tp_members */
3001 type_getsets, /* tp_getset */
3002 0, /* tp_base */
3003 0, /* tp_dict */
3004 0, /* tp_descr_get */
3005 0, /* tp_descr_set */
3006 offsetof(PyTypeObject, tp_dict), /* tp_dictoffset */
3007 type_init, /* tp_init */
3008 0, /* tp_alloc */
3009 type_new, /* tp_new */
3010 PyObject_GC_Del, /* tp_free */
3011 (inquiry)type_is_gc, /* tp_is_gc */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003012};
Tim Peters6d6c1a32001-08-02 04:15:00 +00003013
3014
3015/* The base type of all types (eventually)... except itself. */
3016
Guido van Rossumd8faa362007-04-27 19:54:29 +00003017/* You may wonder why object.__new__() only complains about arguments
3018 when object.__init__() is not overridden, and vice versa.
3019
3020 Consider the use cases:
3021
3022 1. When neither is overridden, we want to hear complaints about
3023 excess (i.e., any) arguments, since their presence could
3024 indicate there's a bug.
3025
3026 2. When defining an Immutable type, we are likely to override only
3027 __new__(), since __init__() is called too late to initialize an
3028 Immutable object. Since __new__() defines the signature for the
3029 type, it would be a pain to have to override __init__() just to
3030 stop it from complaining about excess arguments.
3031
3032 3. When defining a Mutable type, we are likely to override only
3033 __init__(). So here the converse reasoning applies: we don't
3034 want to have to override __new__() just to stop it from
3035 complaining.
3036
3037 4. When __init__() is overridden, and the subclass __init__() calls
3038 object.__init__(), the latter should complain about excess
3039 arguments; ditto for __new__().
3040
3041 Use cases 2 and 3 make it unattractive to unconditionally check for
3042 excess arguments. The best solution that addresses all four use
3043 cases is as follows: __init__() complains about excess arguments
3044 unless __new__() is overridden and __init__() is not overridden
3045 (IOW, if __init__() is overridden or __new__() is not overridden);
3046 symmetrically, __new__() complains about excess arguments unless
3047 __init__() is overridden and __new__() is not overridden
3048 (IOW, if __new__() is overridden or __init__() is not overridden).
3049
3050 However, for backwards compatibility, this breaks too much code.
3051 Therefore, in 2.6, we'll *warn* about excess arguments when both
3052 methods are overridden; for all other cases we'll use the above
3053 rules.
3054
3055*/
3056
3057/* Forward */
3058static PyObject *
3059object_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
3060
3061static int
3062excess_args(PyObject *args, PyObject *kwds)
3063{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003064 return PyTuple_GET_SIZE(args) ||
3065 (kwds && PyDict_Check(kwds) && PyDict_Size(kwds));
Guido van Rossumd8faa362007-04-27 19:54:29 +00003066}
3067
Tim Peters6d6c1a32001-08-02 04:15:00 +00003068static int
3069object_init(PyObject *self, PyObject *args, PyObject *kwds)
3070{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003071 int err = 0;
Benjamin Peterson96384b92012-03-17 00:05:44 -05003072 PyTypeObject *type = Py_TYPE(self);
3073 if (excess_args(args, kwds) &&
3074 (type->tp_new == object_new || type->tp_init != object_init)) {
3075 PyErr_SetString(PyExc_TypeError, "object.__init__() takes no parameters");
3076 err = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003077 }
3078 return err;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003079}
3080
Guido van Rossum298e4212003-02-13 16:30:16 +00003081static PyObject *
3082object_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3083{
Benjamin Peterson96384b92012-03-17 00:05:44 -05003084 if (excess_args(args, kwds) &&
3085 (type->tp_init == object_init || type->tp_new != object_new)) {
R David Murray702a5dc2013-02-18 21:39:18 -05003086 PyErr_SetString(PyExc_TypeError, "object() takes no parameters");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003087 return NULL;
Benjamin Peterson96384b92012-03-17 00:05:44 -05003088 }
Victor Stinner3c1e4812012-03-26 22:10:51 +02003089
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003090 if (type->tp_flags & Py_TPFLAGS_IS_ABSTRACT) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003091 PyObject *abstract_methods = NULL;
3092 PyObject *builtins;
3093 PyObject *sorted;
3094 PyObject *sorted_methods = NULL;
3095 PyObject *joined = NULL;
Benjamin Peterson9a03ecf2012-03-16 20:15:54 -05003096 PyObject *comma;
3097 _Py_static_string(comma_id, ", ");
Victor Stinner3c1e4812012-03-26 22:10:51 +02003098 _Py_IDENTIFIER(sorted);
Christian Heimes9e7f1d22008-02-28 12:27:11 +00003099
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003100 /* Compute ", ".join(sorted(type.__abstractmethods__))
3101 into joined. */
3102 abstract_methods = type_abstractmethods(type, NULL);
3103 if (abstract_methods == NULL)
3104 goto error;
3105 builtins = PyEval_GetBuiltins();
3106 if (builtins == NULL)
3107 goto error;
Victor Stinner3c1e4812012-03-26 22:10:51 +02003108 sorted = _PyDict_GetItemId(builtins, &PyId_sorted);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003109 if (sorted == NULL)
3110 goto error;
3111 sorted_methods = PyObject_CallFunctionObjArgs(sorted,
3112 abstract_methods,
3113 NULL);
3114 if (sorted_methods == NULL)
3115 goto error;
Benjamin Peterson9a03ecf2012-03-16 20:15:54 -05003116 comma = _PyUnicode_FromId(&comma_id);
3117 if (comma == NULL)
3118 goto error;
3119 joined = PyUnicode_Join(comma, sorted_methods);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003120 if (joined == NULL)
3121 goto error;
Christian Heimes9e7f1d22008-02-28 12:27:11 +00003122
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003123 PyErr_Format(PyExc_TypeError,
3124 "Can't instantiate abstract class %s "
3125 "with abstract methods %U",
3126 type->tp_name,
3127 joined);
3128 error:
3129 Py_XDECREF(joined);
3130 Py_XDECREF(sorted_methods);
3131 Py_XDECREF(abstract_methods);
3132 return NULL;
3133 }
3134 return type->tp_alloc(type, 0);
Guido van Rossum298e4212003-02-13 16:30:16 +00003135}
3136
Tim Peters6d6c1a32001-08-02 04:15:00 +00003137static void
3138object_dealloc(PyObject *self)
3139{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003140 Py_TYPE(self)->tp_free(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003141}
3142
Guido van Rossum8e248182001-08-12 05:17:56 +00003143static PyObject *
3144object_repr(PyObject *self)
3145{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003146 PyTypeObject *type;
3147 PyObject *mod, *name, *rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00003148
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003149 type = Py_TYPE(self);
3150 mod = type_module(type, NULL);
3151 if (mod == NULL)
3152 PyErr_Clear();
3153 else if (!PyUnicode_Check(mod)) {
3154 Py_DECREF(mod);
3155 mod = NULL;
3156 }
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003157 name = type_qualname(type, NULL);
Christian Heimese81dc292012-09-10 16:57:36 +02003158 if (name == NULL) {
3159 Py_XDECREF(mod);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003160 return NULL;
Christian Heimese81dc292012-09-10 16:57:36 +02003161 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003162 if (mod != NULL && PyUnicode_CompareWithASCIIString(mod, "builtins"))
3163 rtn = PyUnicode_FromFormat("<%U.%U object at %p>", mod, name, self);
3164 else
3165 rtn = PyUnicode_FromFormat("<%s object at %p>",
3166 type->tp_name, self);
3167 Py_XDECREF(mod);
3168 Py_DECREF(name);
3169 return rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00003170}
3171
Guido van Rossumb8f63662001-08-15 23:57:02 +00003172static PyObject *
3173object_str(PyObject *self)
3174{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003175 unaryfunc f;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003176
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003177 f = Py_TYPE(self)->tp_repr;
Benjamin Peterson7b166872012-04-24 11:06:25 -04003178 if (f == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003179 f = object_repr;
3180 return f(self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003181}
3182
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003183static PyObject *
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003184object_richcompare(PyObject *self, PyObject *other, int op)
3185{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003186 PyObject *res;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003187
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003188 switch (op) {
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003189
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003190 case Py_EQ:
3191 /* Return NotImplemented instead of False, so if two
3192 objects are compared, both get a chance at the
3193 comparison. See issue #1393. */
3194 res = (self == other) ? Py_True : Py_NotImplemented;
3195 Py_INCREF(res);
3196 break;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003197
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003198 case Py_NE:
3199 /* By default, != returns the opposite of ==,
3200 unless the latter returns NotImplemented. */
3201 res = PyObject_RichCompare(self, other, Py_EQ);
3202 if (res != NULL && res != Py_NotImplemented) {
3203 int ok = PyObject_IsTrue(res);
3204 Py_DECREF(res);
3205 if (ok < 0)
3206 res = NULL;
3207 else {
3208 if (ok)
3209 res = Py_False;
3210 else
3211 res = Py_True;
3212 Py_INCREF(res);
3213 }
3214 }
3215 break;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003216
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003217 default:
3218 res = Py_NotImplemented;
3219 Py_INCREF(res);
3220 break;
3221 }
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003222
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003223 return res;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003224}
3225
3226static PyObject *
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003227object_get_class(PyObject *self, void *closure)
3228{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003229 Py_INCREF(Py_TYPE(self));
3230 return (PyObject *)(Py_TYPE(self));
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003231}
3232
3233static int
3234equiv_structs(PyTypeObject *a, PyTypeObject *b)
3235{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003236 return a == b ||
3237 (a != NULL &&
3238 b != NULL &&
3239 a->tp_basicsize == b->tp_basicsize &&
3240 a->tp_itemsize == b->tp_itemsize &&
3241 a->tp_dictoffset == b->tp_dictoffset &&
3242 a->tp_weaklistoffset == b->tp_weaklistoffset &&
3243 ((a->tp_flags & Py_TPFLAGS_HAVE_GC) ==
3244 (b->tp_flags & Py_TPFLAGS_HAVE_GC)));
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003245}
3246
3247static int
3248same_slots_added(PyTypeObject *a, PyTypeObject *b)
3249{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003250 PyTypeObject *base = a->tp_base;
3251 Py_ssize_t size;
3252 PyObject *slots_a, *slots_b;
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003253
Benjamin Peterson67641d22011-01-17 19:24:34 +00003254 assert(base == b->tp_base);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003255 size = base->tp_basicsize;
3256 if (a->tp_dictoffset == size && b->tp_dictoffset == size)
3257 size += sizeof(PyObject *);
3258 if (a->tp_weaklistoffset == size && b->tp_weaklistoffset == size)
3259 size += sizeof(PyObject *);
Guido van Rossumd8faa362007-04-27 19:54:29 +00003260
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003261 /* Check slots compliance */
3262 slots_a = ((PyHeapTypeObject *)a)->ht_slots;
3263 slots_b = ((PyHeapTypeObject *)b)->ht_slots;
3264 if (slots_a && slots_b) {
3265 if (PyObject_RichCompareBool(slots_a, slots_b, Py_EQ) != 1)
3266 return 0;
3267 size += sizeof(PyObject *) * PyTuple_GET_SIZE(slots_a);
3268 }
3269 return size == a->tp_basicsize && size == b->tp_basicsize;
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003270}
3271
3272static int
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003273compatible_for_assignment(PyTypeObject* oldto, PyTypeObject* newto, char* attr)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003274{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003275 PyTypeObject *newbase, *oldbase;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003276
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003277 if (newto->tp_dealloc != oldto->tp_dealloc ||
3278 newto->tp_free != oldto->tp_free)
3279 {
3280 PyErr_Format(PyExc_TypeError,
3281 "%s assignment: "
3282 "'%s' deallocator differs from '%s'",
3283 attr,
3284 newto->tp_name,
3285 oldto->tp_name);
3286 return 0;
3287 }
3288 newbase = newto;
3289 oldbase = oldto;
3290 while (equiv_structs(newbase, newbase->tp_base))
3291 newbase = newbase->tp_base;
3292 while (equiv_structs(oldbase, oldbase->tp_base))
3293 oldbase = oldbase->tp_base;
3294 if (newbase != oldbase &&
3295 (newbase->tp_base != oldbase->tp_base ||
3296 !same_slots_added(newbase, oldbase))) {
3297 PyErr_Format(PyExc_TypeError,
3298 "%s assignment: "
3299 "'%s' object layout differs from '%s'",
3300 attr,
3301 newto->tp_name,
3302 oldto->tp_name);
3303 return 0;
3304 }
Tim Petersea7f75d2002-12-07 21:39:16 +00003305
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003306 return 1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003307}
3308
3309static int
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003310object_set_class(PyObject *self, PyObject *value, void *closure)
3311{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003312 PyTypeObject *oldto = Py_TYPE(self);
3313 PyTypeObject *newto;
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003314
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003315 if (value == NULL) {
3316 PyErr_SetString(PyExc_TypeError,
3317 "can't delete __class__ attribute");
3318 return -1;
3319 }
3320 if (!PyType_Check(value)) {
3321 PyErr_Format(PyExc_TypeError,
Florent Xiclunaaa6c1d22011-12-12 18:54:29 +01003322 "__class__ must be set to a class, not '%s' object",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003323 Py_TYPE(value)->tp_name);
3324 return -1;
3325 }
3326 newto = (PyTypeObject *)value;
3327 if (!(newto->tp_flags & Py_TPFLAGS_HEAPTYPE) ||
3328 !(oldto->tp_flags & Py_TPFLAGS_HEAPTYPE))
3329 {
3330 PyErr_Format(PyExc_TypeError,
3331 "__class__ assignment: only for heap types");
3332 return -1;
3333 }
3334 if (compatible_for_assignment(newto, oldto, "__class__")) {
3335 Py_INCREF(newto);
3336 Py_TYPE(self) = newto;
3337 Py_DECREF(oldto);
3338 return 0;
3339 }
3340 else {
3341 return -1;
3342 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003343}
3344
3345static PyGetSetDef object_getsets[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003346 {"__class__", object_get_class, object_set_class,
3347 PyDoc_STR("the object's class")},
3348 {0}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003349};
3350
Guido van Rossumc53f0092003-02-18 22:05:12 +00003351
Guido van Rossum036f9992003-02-21 22:02:54 +00003352/* Stuff to implement __reduce_ex__ for pickle protocols >= 2.
Alexandre Vassalottif7fa63d2008-05-11 08:55:36 +00003353 We fall back to helpers in copyreg for:
Guido van Rossum036f9992003-02-21 22:02:54 +00003354 - pickle protocols < 2
3355 - calculating the list of slot names (done only once per class)
3356 - the __newobj__ function (which is used as a token but never called)
3357*/
3358
3359static PyObject *
Alexandre Vassalottif7fa63d2008-05-11 08:55:36 +00003360import_copyreg(void)
Guido van Rossum036f9992003-02-21 22:02:54 +00003361{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003362 static PyObject *copyreg_str;
Guido van Rossum3926a632001-09-25 16:25:58 +00003363
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003364 if (!copyreg_str) {
3365 copyreg_str = PyUnicode_InternFromString("copyreg");
3366 if (copyreg_str == NULL)
3367 return NULL;
3368 }
Antoine Pitrou957a23b2013-05-04 20:45:02 +02003369 if (!cached_copyreg_module) {
3370 cached_copyreg_module = PyImport_Import(copyreg_str);
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003371 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003372
Antoine Pitrou957a23b2013-05-04 20:45:02 +02003373 Py_XINCREF(cached_copyreg_module);
3374 return cached_copyreg_module;
Guido van Rossum036f9992003-02-21 22:02:54 +00003375}
3376
3377static PyObject *
3378slotnames(PyObject *cls)
3379{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003380 PyObject *clsdict;
3381 PyObject *copyreg;
3382 PyObject *slotnames;
Victor Stinner3c1e4812012-03-26 22:10:51 +02003383 _Py_IDENTIFIER(__slotnames__);
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02003384 _Py_IDENTIFIER(_slotnames);
Guido van Rossum036f9992003-02-21 22:02:54 +00003385
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003386 clsdict = ((PyTypeObject *)cls)->tp_dict;
Victor Stinner3c1e4812012-03-26 22:10:51 +02003387 slotnames = _PyDict_GetItemId(clsdict, &PyId___slotnames__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003388 if (slotnames != NULL && PyList_Check(slotnames)) {
3389 Py_INCREF(slotnames);
3390 return slotnames;
3391 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003392
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003393 copyreg = import_copyreg();
3394 if (copyreg == NULL)
3395 return NULL;
Guido van Rossum036f9992003-02-21 22:02:54 +00003396
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02003397 slotnames = _PyObject_CallMethodId(copyreg, &PyId__slotnames, "O", cls);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003398 Py_DECREF(copyreg);
3399 if (slotnames != NULL &&
3400 slotnames != Py_None &&
3401 !PyList_Check(slotnames))
3402 {
3403 PyErr_SetString(PyExc_TypeError,
3404 "copyreg._slotnames didn't return a list or None");
3405 Py_DECREF(slotnames);
3406 slotnames = NULL;
3407 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003408
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003409 return slotnames;
Guido van Rossum036f9992003-02-21 22:02:54 +00003410}
3411
3412static PyObject *
3413reduce_2(PyObject *obj)
3414{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003415 PyObject *cls, *getnewargs;
3416 PyObject *args = NULL, *args2 = NULL;
3417 PyObject *getstate = NULL, *state = NULL, *names = NULL;
3418 PyObject *slots = NULL, *listitems = NULL, *dictitems = NULL;
3419 PyObject *copyreg = NULL, *newobj = NULL, *res = NULL;
3420 Py_ssize_t i, n;
Victor Stinner3c1e4812012-03-26 22:10:51 +02003421 _Py_IDENTIFIER(__getnewargs__);
3422 _Py_IDENTIFIER(__getstate__);
3423 _Py_IDENTIFIER(__newobj__);
Guido van Rossum036f9992003-02-21 22:02:54 +00003424
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003425 cls = (PyObject *) Py_TYPE(obj);
3426
Victor Stinner3c1e4812012-03-26 22:10:51 +02003427 getnewargs = _PyObject_GetAttrId(obj, &PyId___getnewargs__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003428 if (getnewargs != NULL) {
3429 args = PyObject_CallObject(getnewargs, NULL);
3430 Py_DECREF(getnewargs);
3431 if (args != NULL && !PyTuple_Check(args)) {
3432 PyErr_Format(PyExc_TypeError,
3433 "__getnewargs__ should return a tuple, "
3434 "not '%.200s'", Py_TYPE(args)->tp_name);
3435 goto end;
3436 }
3437 }
3438 else {
3439 PyErr_Clear();
3440 args = PyTuple_New(0);
3441 }
3442 if (args == NULL)
3443 goto end;
Guido van Rossum036f9992003-02-21 22:02:54 +00003444
Victor Stinner3c1e4812012-03-26 22:10:51 +02003445 getstate = _PyObject_GetAttrId(obj, &PyId___getstate__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003446 if (getstate != NULL) {
3447 state = PyObject_CallObject(getstate, NULL);
3448 Py_DECREF(getstate);
3449 if (state == NULL)
3450 goto end;
3451 }
3452 else {
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003453 PyObject **dict;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003454 PyErr_Clear();
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003455 dict = _PyObject_GetDictPtr(obj);
3456 if (dict && *dict)
3457 state = *dict;
3458 else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003459 state = Py_None;
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003460 Py_INCREF(state);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003461 names = slotnames(cls);
3462 if (names == NULL)
3463 goto end;
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003464 if (names != Py_None && PyList_GET_SIZE(names) > 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003465 assert(PyList_Check(names));
3466 slots = PyDict_New();
3467 if (slots == NULL)
3468 goto end;
3469 n = 0;
3470 /* Can't pre-compute the list size; the list
3471 is stored on the class so accessible to other
3472 threads, which may be run by DECREF */
3473 for (i = 0; i < PyList_GET_SIZE(names); i++) {
3474 PyObject *name, *value;
3475 name = PyList_GET_ITEM(names, i);
3476 value = PyObject_GetAttr(obj, name);
3477 if (value == NULL)
3478 PyErr_Clear();
3479 else {
3480 int err = PyDict_SetItem(slots, name,
3481 value);
3482 Py_DECREF(value);
3483 if (err)
3484 goto end;
3485 n++;
3486 }
3487 }
3488 if (n) {
3489 state = Py_BuildValue("(NO)", state, slots);
3490 if (state == NULL)
3491 goto end;
3492 }
3493 }
3494 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003495
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003496 if (!PyList_Check(obj)) {
3497 listitems = Py_None;
3498 Py_INCREF(listitems);
3499 }
3500 else {
3501 listitems = PyObject_GetIter(obj);
3502 if (listitems == NULL)
3503 goto end;
3504 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003505
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003506 if (!PyDict_Check(obj)) {
3507 dictitems = Py_None;
3508 Py_INCREF(dictitems);
3509 }
3510 else {
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02003511 _Py_IDENTIFIER(items);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02003512 PyObject *items = _PyObject_CallMethodId(obj, &PyId_items, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003513 if (items == NULL)
3514 goto end;
3515 dictitems = PyObject_GetIter(items);
3516 Py_DECREF(items);
3517 if (dictitems == NULL)
3518 goto end;
3519 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003520
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003521 copyreg = import_copyreg();
3522 if (copyreg == NULL)
3523 goto end;
Victor Stinner3c1e4812012-03-26 22:10:51 +02003524 newobj = _PyObject_GetAttrId(copyreg, &PyId___newobj__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003525 if (newobj == NULL)
3526 goto end;
Guido van Rossum036f9992003-02-21 22:02:54 +00003527
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003528 n = PyTuple_GET_SIZE(args);
3529 args2 = PyTuple_New(n+1);
3530 if (args2 == NULL)
3531 goto end;
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003532 Py_INCREF(cls);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003533 PyTuple_SET_ITEM(args2, 0, cls);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003534 for (i = 0; i < n; i++) {
3535 PyObject *v = PyTuple_GET_ITEM(args, i);
3536 Py_INCREF(v);
3537 PyTuple_SET_ITEM(args2, i+1, v);
3538 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003539
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003540 res = PyTuple_Pack(5, newobj, args2, state, listitems, dictitems);
Guido van Rossum036f9992003-02-21 22:02:54 +00003541
3542 end:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003543 Py_XDECREF(args);
3544 Py_XDECREF(args2);
3545 Py_XDECREF(slots);
3546 Py_XDECREF(state);
3547 Py_XDECREF(names);
3548 Py_XDECREF(listitems);
3549 Py_XDECREF(dictitems);
3550 Py_XDECREF(copyreg);
3551 Py_XDECREF(newobj);
3552 return res;
Guido van Rossum036f9992003-02-21 22:02:54 +00003553}
3554
Guido van Rossumd8faa362007-04-27 19:54:29 +00003555/*
3556 * There were two problems when object.__reduce__ and object.__reduce_ex__
3557 * were implemented in the same function:
3558 * - trying to pickle an object with a custom __reduce__ method that
3559 * fell back to object.__reduce__ in certain circumstances led to
3560 * infinite recursion at Python level and eventual RuntimeError.
3561 * - Pickling objects that lied about their type by overwriting the
3562 * __class__ descriptor could lead to infinite recursion at C level
3563 * and eventual segfault.
3564 *
3565 * Because of backwards compatibility, the two methods still have to
3566 * behave in the same way, even if this is not required by the pickle
3567 * protocol. This common functionality was moved to the _common_reduce
3568 * function.
3569 */
3570static PyObject *
3571_common_reduce(PyObject *self, int proto)
3572{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003573 PyObject *copyreg, *res;
Guido van Rossumd8faa362007-04-27 19:54:29 +00003574
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003575 if (proto >= 2)
3576 return reduce_2(self);
Guido van Rossumd8faa362007-04-27 19:54:29 +00003577
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003578 copyreg = import_copyreg();
3579 if (!copyreg)
3580 return NULL;
Guido van Rossumd8faa362007-04-27 19:54:29 +00003581
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003582 res = PyEval_CallMethod(copyreg, "_reduce_ex", "(Oi)", self, proto);
3583 Py_DECREF(copyreg);
Guido van Rossumd8faa362007-04-27 19:54:29 +00003584
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003585 return res;
Guido van Rossumd8faa362007-04-27 19:54:29 +00003586}
3587
3588static PyObject *
3589object_reduce(PyObject *self, PyObject *args)
3590{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003591 int proto = 0;
Guido van Rossumd8faa362007-04-27 19:54:29 +00003592
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003593 if (!PyArg_ParseTuple(args, "|i:__reduce__", &proto))
3594 return NULL;
Guido van Rossumd8faa362007-04-27 19:54:29 +00003595
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003596 return _common_reduce(self, proto);
Guido van Rossumd8faa362007-04-27 19:54:29 +00003597}
3598
Guido van Rossum036f9992003-02-21 22:02:54 +00003599static PyObject *
3600object_reduce_ex(PyObject *self, PyObject *args)
3601{
Victor Stinner3c1e4812012-03-26 22:10:51 +02003602 static PyObject *objreduce;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003603 PyObject *reduce, *res;
3604 int proto = 0;
Victor Stinner3c1e4812012-03-26 22:10:51 +02003605 _Py_IDENTIFIER(__reduce__);
Guido van Rossum036f9992003-02-21 22:02:54 +00003606
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003607 if (!PyArg_ParseTuple(args, "|i:__reduce_ex__", &proto))
3608 return NULL;
Guido van Rossum036f9992003-02-21 22:02:54 +00003609
Victor Stinner3c1e4812012-03-26 22:10:51 +02003610 if (objreduce == NULL) {
3611 objreduce = _PyDict_GetItemId(PyBaseObject_Type.tp_dict,
3612 &PyId___reduce__);
3613 if (objreduce == NULL)
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003614 return NULL;
3615 }
3616
Victor Stinner3c1e4812012-03-26 22:10:51 +02003617 reduce = _PyObject_GetAttrId(self, &PyId___reduce__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003618 if (reduce == NULL)
3619 PyErr_Clear();
3620 else {
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003621 PyObject *cls, *clsreduce;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003622 int override;
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003623
3624 cls = (PyObject *) Py_TYPE(self);
Victor Stinner3c1e4812012-03-26 22:10:51 +02003625 clsreduce = _PyObject_GetAttrId(cls, &PyId___reduce__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003626 if (clsreduce == NULL) {
3627 Py_DECREF(reduce);
3628 return NULL;
3629 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003630 override = (clsreduce != objreduce);
3631 Py_DECREF(clsreduce);
3632 if (override) {
3633 res = PyObject_CallObject(reduce, NULL);
3634 Py_DECREF(reduce);
3635 return res;
3636 }
3637 else
3638 Py_DECREF(reduce);
3639 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003640
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003641 return _common_reduce(self, proto);
Guido van Rossum3926a632001-09-25 16:25:58 +00003642}
3643
Christian Heimes9e7f1d22008-02-28 12:27:11 +00003644static PyObject *
3645object_subclasshook(PyObject *cls, PyObject *args)
3646{
Brian Curtindfc80e32011-08-10 20:28:54 -05003647 Py_RETURN_NOTIMPLEMENTED;
Christian Heimes9e7f1d22008-02-28 12:27:11 +00003648}
3649
3650PyDoc_STRVAR(object_subclasshook_doc,
3651"Abstract classes can override this to customize issubclass().\n"
3652"\n"
3653"This is invoked early on by abc.ABCMeta.__subclasscheck__().\n"
3654"It should return True, False or NotImplemented. If it returns\n"
3655"NotImplemented, the normal algorithm is used. Otherwise, it\n"
3656"overrides the normal algorithm (and the outcome is cached).\n");
Eric Smith8c663262007-08-25 02:26:07 +00003657
3658/*
3659 from PEP 3101, this code implements:
3660
3661 class object:
3662 def __format__(self, format_spec):
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003663 return format(str(self), format_spec)
Eric Smith8c663262007-08-25 02:26:07 +00003664*/
3665static PyObject *
3666object_format(PyObject *self, PyObject *args)
3667{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003668 PyObject *format_spec;
3669 PyObject *self_as_str = NULL;
3670 PyObject *result = NULL;
Eric Smith8c663262007-08-25 02:26:07 +00003671
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003672 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
3673 return NULL;
Eric Smith8c663262007-08-25 02:26:07 +00003674
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003675 self_as_str = PyObject_Str(self);
Eric Smithe4d63172010-09-13 20:48:43 +00003676 if (self_as_str != NULL) {
3677 /* Issue 7994: If we're converting to a string, we
Eric V. Smithb9cd3532011-03-12 10:08:48 -05003678 should reject format specifications */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003679 if (PyUnicode_GET_LENGTH(format_spec) > 0) {
Andrew Svetlov2cd8ce42012-12-23 14:27:17 +02003680 PyErr_SetString(PyExc_TypeError,
Eric V. Smithb9cd3532011-03-12 10:08:48 -05003681 "non-empty format string passed to object.__format__");
Andrew Svetlov2cd8ce42012-12-23 14:27:17 +02003682 goto done;
Eric V. Smithb9cd3532011-03-12 10:08:48 -05003683 }
Eric Smith8c663262007-08-25 02:26:07 +00003684
Eric V. Smithb9cd3532011-03-12 10:08:48 -05003685 result = PyObject_Format(self_as_str, format_spec);
Eric Smithe4d63172010-09-13 20:48:43 +00003686 }
3687
3688done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003689 Py_XDECREF(self_as_str);
Eric Smith8c663262007-08-25 02:26:07 +00003690
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003691 return result;
Eric Smith8c663262007-08-25 02:26:07 +00003692}
3693
Martin v. Löwis00709aa2008-06-04 14:18:43 +00003694static PyObject *
3695object_sizeof(PyObject *self, PyObject *args)
3696{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003697 Py_ssize_t res, isize;
Martin v. Löwis00709aa2008-06-04 14:18:43 +00003698
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003699 res = 0;
3700 isize = self->ob_type->tp_itemsize;
3701 if (isize > 0)
3702 res = Py_SIZE(self->ob_type) * isize;
3703 res += self->ob_type->tp_basicsize;
Martin v. Löwis00709aa2008-06-04 14:18:43 +00003704
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003705 return PyLong_FromSsize_t(res);
Martin v. Löwis00709aa2008-06-04 14:18:43 +00003706}
3707
Benjamin Peterson82b00c12011-05-24 11:09:06 -05003708/* __dir__ for generic objects: returns __dict__, __class__,
3709 and recursively up the __class__.__bases__ chain.
3710*/
3711static PyObject *
3712object_dir(PyObject *self, PyObject *args)
3713{
3714 PyObject *result = NULL;
3715 PyObject *dict = NULL;
3716 PyObject *itsclass = NULL;
3717
3718 /* Get __dict__ (which may or may not be a real dict...) */
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02003719 dict = _PyObject_GetAttrId(self, &PyId___dict__);
Benjamin Peterson82b00c12011-05-24 11:09:06 -05003720 if (dict == NULL) {
3721 PyErr_Clear();
3722 dict = PyDict_New();
3723 }
3724 else if (!PyDict_Check(dict)) {
3725 Py_DECREF(dict);
3726 dict = PyDict_New();
3727 }
3728 else {
3729 /* Copy __dict__ to avoid mutating it. */
3730 PyObject *temp = PyDict_Copy(dict);
3731 Py_DECREF(dict);
3732 dict = temp;
3733 }
3734
3735 if (dict == NULL)
3736 goto error;
3737
3738 /* Merge in attrs reachable from its class. */
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02003739 itsclass = _PyObject_GetAttrId(self, &PyId___class__);
Benjamin Peterson82b00c12011-05-24 11:09:06 -05003740 if (itsclass == NULL)
3741 /* XXX(tomer): Perhaps fall back to obj->ob_type if no
3742 __class__ exists? */
3743 PyErr_Clear();
3744 else if (merge_class_dict(dict, itsclass) != 0)
3745 goto error;
3746
3747 result = PyDict_Keys(dict);
3748 /* fall through */
3749error:
3750 Py_XDECREF(itsclass);
3751 Py_XDECREF(dict);
3752 return result;
3753}
3754
Guido van Rossum3926a632001-09-25 16:25:58 +00003755static PyMethodDef object_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003756 {"__reduce_ex__", object_reduce_ex, METH_VARARGS,
3757 PyDoc_STR("helper for pickle")},
3758 {"__reduce__", object_reduce, METH_VARARGS,
3759 PyDoc_STR("helper for pickle")},
3760 {"__subclasshook__", object_subclasshook, METH_CLASS | METH_VARARGS,
3761 object_subclasshook_doc},
3762 {"__format__", object_format, METH_VARARGS,
3763 PyDoc_STR("default object formatter")},
3764 {"__sizeof__", object_sizeof, METH_NOARGS,
Benjamin Petersonfbe56bb2011-05-24 12:42:51 -05003765 PyDoc_STR("__sizeof__() -> int\nsize of object in memory, in bytes")},
Benjamin Peterson82b00c12011-05-24 11:09:06 -05003766 {"__dir__", object_dir, METH_NOARGS,
Benjamin Petersonc7284122011-05-24 12:46:15 -05003767 PyDoc_STR("__dir__() -> list\ndefault dir() implementation")},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003768 {0}
Guido van Rossum3926a632001-09-25 16:25:58 +00003769};
3770
Guido van Rossum036f9992003-02-21 22:02:54 +00003771
Tim Peters6d6c1a32001-08-02 04:15:00 +00003772PyTypeObject PyBaseObject_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003773 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3774 "object", /* tp_name */
3775 sizeof(PyObject), /* tp_basicsize */
3776 0, /* tp_itemsize */
3777 object_dealloc, /* tp_dealloc */
3778 0, /* tp_print */
3779 0, /* tp_getattr */
3780 0, /* tp_setattr */
3781 0, /* tp_reserved */
3782 object_repr, /* tp_repr */
3783 0, /* tp_as_number */
3784 0, /* tp_as_sequence */
3785 0, /* tp_as_mapping */
3786 (hashfunc)_Py_HashPointer, /* tp_hash */
3787 0, /* tp_call */
3788 object_str, /* tp_str */
3789 PyObject_GenericGetAttr, /* tp_getattro */
3790 PyObject_GenericSetAttr, /* tp_setattro */
3791 0, /* tp_as_buffer */
3792 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
3793 PyDoc_STR("The most base type"), /* tp_doc */
3794 0, /* tp_traverse */
3795 0, /* tp_clear */
3796 object_richcompare, /* tp_richcompare */
3797 0, /* tp_weaklistoffset */
3798 0, /* tp_iter */
3799 0, /* tp_iternext */
3800 object_methods, /* tp_methods */
3801 0, /* tp_members */
3802 object_getsets, /* tp_getset */
3803 0, /* tp_base */
3804 0, /* tp_dict */
3805 0, /* tp_descr_get */
3806 0, /* tp_descr_set */
3807 0, /* tp_dictoffset */
3808 object_init, /* tp_init */
3809 PyType_GenericAlloc, /* tp_alloc */
3810 object_new, /* tp_new */
3811 PyObject_Del, /* tp_free */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003812};
3813
3814
Guido van Rossum50e9fb92006-08-17 05:42:55 +00003815/* Add the methods from tp_methods to the __dict__ in a type object */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003816
3817static int
3818add_methods(PyTypeObject *type, PyMethodDef *meth)
3819{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003820 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003821
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003822 for (; meth->ml_name != NULL; meth++) {
3823 PyObject *descr;
Benjamin Peterson89a6e9a2012-05-08 09:22:24 -04003824 int err;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003825 if (PyDict_GetItemString(dict, meth->ml_name) &&
3826 !(meth->ml_flags & METH_COEXIST))
3827 continue;
3828 if (meth->ml_flags & METH_CLASS) {
3829 if (meth->ml_flags & METH_STATIC) {
3830 PyErr_SetString(PyExc_ValueError,
3831 "method cannot be both class and static");
3832 return -1;
3833 }
3834 descr = PyDescr_NewClassMethod(type, meth);
3835 }
3836 else if (meth->ml_flags & METH_STATIC) {
Andrew Svetlov3ba3a3e2012-12-25 13:32:35 +02003837 PyObject *cfunc = PyCFunction_NewEx(meth, (PyObject*)type, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003838 if (cfunc == NULL)
3839 return -1;
3840 descr = PyStaticMethod_New(cfunc);
3841 Py_DECREF(cfunc);
3842 }
3843 else {
3844 descr = PyDescr_NewMethod(type, meth);
3845 }
3846 if (descr == NULL)
3847 return -1;
Benjamin Peterson89a6e9a2012-05-08 09:22:24 -04003848 err = PyDict_SetItemString(dict, meth->ml_name, descr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003849 Py_DECREF(descr);
Benjamin Peterson89a6e9a2012-05-08 09:22:24 -04003850 if (err < 0)
3851 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003852 }
3853 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003854}
3855
3856static int
Guido van Rossum6f799372001-09-20 20:46:19 +00003857add_members(PyTypeObject *type, PyMemberDef *memb)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003858{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003859 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003860
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003861 for (; memb->name != NULL; memb++) {
3862 PyObject *descr;
3863 if (PyDict_GetItemString(dict, memb->name))
3864 continue;
3865 descr = PyDescr_NewMember(type, memb);
3866 if (descr == NULL)
3867 return -1;
3868 if (PyDict_SetItemString(dict, memb->name, descr) < 0)
3869 return -1;
3870 Py_DECREF(descr);
3871 }
3872 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003873}
3874
3875static int
Guido van Rossum32d34c82001-09-20 21:45:26 +00003876add_getset(PyTypeObject *type, PyGetSetDef *gsp)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003877{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003878 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003879
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003880 for (; gsp->name != NULL; gsp++) {
3881 PyObject *descr;
3882 if (PyDict_GetItemString(dict, gsp->name))
3883 continue;
3884 descr = PyDescr_NewGetSet(type, gsp);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003885
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003886 if (descr == NULL)
3887 return -1;
3888 if (PyDict_SetItemString(dict, gsp->name, descr) < 0)
3889 return -1;
3890 Py_DECREF(descr);
3891 }
3892 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003893}
3894
Guido van Rossum13d52f02001-08-10 21:24:08 +00003895static void
3896inherit_special(PyTypeObject *type, PyTypeObject *base)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003897{
Tim Peters6d6c1a32001-08-02 04:15:00 +00003898
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003899 /* Copying basicsize is connected to the GC flags */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003900 if (!(type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
3901 (base->tp_flags & Py_TPFLAGS_HAVE_GC) &&
3902 (!type->tp_traverse && !type->tp_clear)) {
3903 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
3904 if (type->tp_traverse == NULL)
3905 type->tp_traverse = base->tp_traverse;
3906 if (type->tp_clear == NULL)
3907 type->tp_clear = base->tp_clear;
3908 }
3909 {
3910 /* The condition below could use some explanation.
3911 It appears that tp_new is not inherited for static types
3912 whose base class is 'object'; this seems to be a precaution
3913 so that old extension types don't suddenly become
3914 callable (object.__new__ wouldn't insure the invariants
3915 that the extension type's own factory function ensures).
3916 Heap types, of course, are under our control, so they do
3917 inherit tp_new; static extension types that specify some
Florent Xiclunaaa6c1d22011-12-12 18:54:29 +01003918 other built-in type as the default also
3919 inherit object.__new__. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003920 if (base != &PyBaseObject_Type ||
3921 (type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
3922 if (type->tp_new == NULL)
3923 type->tp_new = base->tp_new;
3924 }
3925 }
Benjamin Petersona7465e22010-07-05 15:01:22 +00003926 if (type->tp_basicsize == 0)
3927 type->tp_basicsize = base->tp_basicsize;
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00003928
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003929 /* Copy other non-function slots */
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00003930
3931#undef COPYVAL
3932#define COPYVAL(SLOT) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003933 if (type->SLOT == 0) type->SLOT = base->SLOT
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00003934
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003935 COPYVAL(tp_itemsize);
3936 COPYVAL(tp_weaklistoffset);
3937 COPYVAL(tp_dictoffset);
Thomas Wouters27d517b2007-02-25 20:39:11 +00003938
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003939 /* Setup fast subclass flags */
3940 if (PyType_IsSubtype(base, (PyTypeObject*)PyExc_BaseException))
3941 type->tp_flags |= Py_TPFLAGS_BASE_EXC_SUBCLASS;
3942 else if (PyType_IsSubtype(base, &PyType_Type))
3943 type->tp_flags |= Py_TPFLAGS_TYPE_SUBCLASS;
3944 else if (PyType_IsSubtype(base, &PyLong_Type))
3945 type->tp_flags |= Py_TPFLAGS_LONG_SUBCLASS;
3946 else if (PyType_IsSubtype(base, &PyBytes_Type))
3947 type->tp_flags |= Py_TPFLAGS_BYTES_SUBCLASS;
3948 else if (PyType_IsSubtype(base, &PyUnicode_Type))
3949 type->tp_flags |= Py_TPFLAGS_UNICODE_SUBCLASS;
3950 else if (PyType_IsSubtype(base, &PyTuple_Type))
3951 type->tp_flags |= Py_TPFLAGS_TUPLE_SUBCLASS;
3952 else if (PyType_IsSubtype(base, &PyList_Type))
3953 type->tp_flags |= Py_TPFLAGS_LIST_SUBCLASS;
3954 else if (PyType_IsSubtype(base, &PyDict_Type))
3955 type->tp_flags |= Py_TPFLAGS_DICT_SUBCLASS;
Guido van Rossum13d52f02001-08-10 21:24:08 +00003956}
3957
Guido van Rossum38938152006-08-21 23:36:26 +00003958static int
Guido van Rossumf5243f02008-01-01 04:06:48 +00003959overrides_hash(PyTypeObject *type)
Guido van Rossum38938152006-08-21 23:36:26 +00003960{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003961 PyObject *dict = type->tp_dict;
Victor Stinner3c1e4812012-03-26 22:10:51 +02003962 _Py_IDENTIFIER(__eq__);
Guido van Rossum38938152006-08-21 23:36:26 +00003963
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003964 assert(dict != NULL);
Victor Stinner3c1e4812012-03-26 22:10:51 +02003965 if (_PyDict_GetItemId(dict, &PyId___eq__) != NULL)
3966 return 1;
3967 if (_PyDict_GetItemId(dict, &PyId___hash__) != NULL)
3968 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003969 return 0;
Guido van Rossum38938152006-08-21 23:36:26 +00003970}
3971
Guido van Rossum13d52f02001-08-10 21:24:08 +00003972static void
3973inherit_slots(PyTypeObject *type, PyTypeObject *base)
3974{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003975 PyTypeObject *basebase;
Guido van Rossum13d52f02001-08-10 21:24:08 +00003976
3977#undef SLOTDEFINED
Tim Peters6d6c1a32001-08-02 04:15:00 +00003978#undef COPYSLOT
3979#undef COPYNUM
3980#undef COPYSEQ
3981#undef COPYMAP
Guido van Rossum5af588b2001-10-12 14:13:21 +00003982#undef COPYBUF
Guido van Rossum13d52f02001-08-10 21:24:08 +00003983
3984#define SLOTDEFINED(SLOT) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003985 (base->SLOT != 0 && \
3986 (basebase == NULL || base->SLOT != basebase->SLOT))
Guido van Rossum13d52f02001-08-10 21:24:08 +00003987
Tim Peters6d6c1a32001-08-02 04:15:00 +00003988#define COPYSLOT(SLOT) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003989 if (!type->SLOT && SLOTDEFINED(SLOT)) type->SLOT = base->SLOT
Tim Peters6d6c1a32001-08-02 04:15:00 +00003990
3991#define COPYNUM(SLOT) COPYSLOT(tp_as_number->SLOT)
3992#define COPYSEQ(SLOT) COPYSLOT(tp_as_sequence->SLOT)
3993#define COPYMAP(SLOT) COPYSLOT(tp_as_mapping->SLOT)
Tim Petersfc57ccb2001-10-12 02:38:24 +00003994#define COPYBUF(SLOT) COPYSLOT(tp_as_buffer->SLOT)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003995
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003996 /* This won't inherit indirect slots (from tp_as_number etc.)
3997 if type doesn't provide the space. */
Guido van Rossum13d52f02001-08-10 21:24:08 +00003998
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003999 if (type->tp_as_number != NULL && base->tp_as_number != NULL) {
4000 basebase = base->tp_base;
4001 if (basebase->tp_as_number == NULL)
4002 basebase = NULL;
4003 COPYNUM(nb_add);
4004 COPYNUM(nb_subtract);
4005 COPYNUM(nb_multiply);
4006 COPYNUM(nb_remainder);
4007 COPYNUM(nb_divmod);
4008 COPYNUM(nb_power);
4009 COPYNUM(nb_negative);
4010 COPYNUM(nb_positive);
4011 COPYNUM(nb_absolute);
4012 COPYNUM(nb_bool);
4013 COPYNUM(nb_invert);
4014 COPYNUM(nb_lshift);
4015 COPYNUM(nb_rshift);
4016 COPYNUM(nb_and);
4017 COPYNUM(nb_xor);
4018 COPYNUM(nb_or);
4019 COPYNUM(nb_int);
4020 COPYNUM(nb_float);
4021 COPYNUM(nb_inplace_add);
4022 COPYNUM(nb_inplace_subtract);
4023 COPYNUM(nb_inplace_multiply);
4024 COPYNUM(nb_inplace_remainder);
4025 COPYNUM(nb_inplace_power);
4026 COPYNUM(nb_inplace_lshift);
4027 COPYNUM(nb_inplace_rshift);
4028 COPYNUM(nb_inplace_and);
4029 COPYNUM(nb_inplace_xor);
4030 COPYNUM(nb_inplace_or);
4031 COPYNUM(nb_true_divide);
4032 COPYNUM(nb_floor_divide);
4033 COPYNUM(nb_inplace_true_divide);
4034 COPYNUM(nb_inplace_floor_divide);
4035 COPYNUM(nb_index);
4036 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004037
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004038 if (type->tp_as_sequence != NULL && base->tp_as_sequence != NULL) {
4039 basebase = base->tp_base;
4040 if (basebase->tp_as_sequence == NULL)
4041 basebase = NULL;
4042 COPYSEQ(sq_length);
4043 COPYSEQ(sq_concat);
4044 COPYSEQ(sq_repeat);
4045 COPYSEQ(sq_item);
4046 COPYSEQ(sq_ass_item);
4047 COPYSEQ(sq_contains);
4048 COPYSEQ(sq_inplace_concat);
4049 COPYSEQ(sq_inplace_repeat);
4050 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004051
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004052 if (type->tp_as_mapping != NULL && base->tp_as_mapping != NULL) {
4053 basebase = base->tp_base;
4054 if (basebase->tp_as_mapping == NULL)
4055 basebase = NULL;
4056 COPYMAP(mp_length);
4057 COPYMAP(mp_subscript);
4058 COPYMAP(mp_ass_subscript);
4059 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004060
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004061 if (type->tp_as_buffer != NULL && base->tp_as_buffer != NULL) {
4062 basebase = base->tp_base;
4063 if (basebase->tp_as_buffer == NULL)
4064 basebase = NULL;
4065 COPYBUF(bf_getbuffer);
4066 COPYBUF(bf_releasebuffer);
4067 }
Tim Petersfc57ccb2001-10-12 02:38:24 +00004068
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004069 basebase = base->tp_base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004070
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004071 COPYSLOT(tp_dealloc);
4072 if (type->tp_getattr == NULL && type->tp_getattro == NULL) {
4073 type->tp_getattr = base->tp_getattr;
4074 type->tp_getattro = base->tp_getattro;
4075 }
4076 if (type->tp_setattr == NULL && type->tp_setattro == NULL) {
4077 type->tp_setattr = base->tp_setattr;
4078 type->tp_setattro = base->tp_setattro;
4079 }
4080 /* tp_reserved is ignored */
4081 COPYSLOT(tp_repr);
4082 /* tp_hash see tp_richcompare */
4083 COPYSLOT(tp_call);
4084 COPYSLOT(tp_str);
4085 {
4086 /* Copy comparison-related slots only when
4087 not overriding them anywhere */
4088 if (type->tp_richcompare == NULL &&
4089 type->tp_hash == NULL &&
4090 !overrides_hash(type))
4091 {
4092 type->tp_richcompare = base->tp_richcompare;
4093 type->tp_hash = base->tp_hash;
4094 }
4095 }
4096 {
4097 COPYSLOT(tp_iter);
4098 COPYSLOT(tp_iternext);
4099 }
4100 {
4101 COPYSLOT(tp_descr_get);
4102 COPYSLOT(tp_descr_set);
4103 COPYSLOT(tp_dictoffset);
4104 COPYSLOT(tp_init);
4105 COPYSLOT(tp_alloc);
4106 COPYSLOT(tp_is_gc);
4107 if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) ==
4108 (base->tp_flags & Py_TPFLAGS_HAVE_GC)) {
4109 /* They agree about gc. */
4110 COPYSLOT(tp_free);
4111 }
4112 else if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
4113 type->tp_free == NULL &&
4114 base->tp_free == PyObject_Free) {
4115 /* A bit of magic to plug in the correct default
4116 * tp_free function when a derived class adds gc,
4117 * didn't define tp_free, and the base uses the
4118 * default non-gc tp_free.
4119 */
4120 type->tp_free = PyObject_GC_Del;
4121 }
4122 /* else they didn't agree about gc, and there isn't something
4123 * obvious to be done -- the type is on its own.
4124 */
4125 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004126}
4127
Jeremy Hylton938ace62002-07-17 16:30:39 +00004128static int add_operators(PyTypeObject *);
Guido van Rossum13d52f02001-08-10 21:24:08 +00004129
Tim Peters6d6c1a32001-08-02 04:15:00 +00004130int
Guido van Rossum528b7eb2001-08-07 17:24:28 +00004131PyType_Ready(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004132{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004133 PyObject *dict, *bases;
4134 PyTypeObject *base;
4135 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004136
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004137 if (type->tp_flags & Py_TPFLAGS_READY) {
4138 assert(type->tp_dict != NULL);
4139 return 0;
4140 }
4141 assert((type->tp_flags & Py_TPFLAGS_READYING) == 0);
Guido van Rossumd614f972001-08-10 17:39:49 +00004142
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004143 type->tp_flags |= Py_TPFLAGS_READYING;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004144
Tim Peters36eb4df2003-03-23 03:33:13 +00004145#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004146 /* PyType_Ready is the closest thing we have to a choke point
4147 * for type objects, so is the best place I can think of to try
4148 * to get type objects into the doubly-linked list of all objects.
4149 * Still, not all type objects go thru PyType_Ready.
4150 */
4151 _Py_AddToAllObjects((PyObject *)type, 0);
Tim Peters36eb4df2003-03-23 03:33:13 +00004152#endif
4153
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004154 /* Initialize tp_base (defaults to BaseObject unless that's us) */
4155 base = type->tp_base;
4156 if (base == NULL && type != &PyBaseObject_Type) {
4157 base = type->tp_base = &PyBaseObject_Type;
4158 Py_INCREF(base);
4159 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004160
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004161 /* Now the only way base can still be NULL is if type is
4162 * &PyBaseObject_Type.
4163 */
Guido van Rossum692cdbc2006-03-10 02:04:28 +00004164
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004165 /* Initialize the base class */
4166 if (base != NULL && base->tp_dict == NULL) {
4167 if (PyType_Ready(base) < 0)
4168 goto error;
4169 }
Guido van Rossum323a9cf2002-08-14 17:26:30 +00004170
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004171 /* Initialize ob_type if NULL. This means extensions that want to be
4172 compilable separately on Windows can call PyType_Ready() instead of
4173 initializing the ob_type field of their type objects. */
4174 /* The test for base != NULL is really unnecessary, since base is only
4175 NULL when type is &PyBaseObject_Type, and we know its ob_type is
4176 not NULL (it's initialized to &PyType_Type). But coverity doesn't
4177 know that. */
4178 if (Py_TYPE(type) == NULL && base != NULL)
4179 Py_TYPE(type) = Py_TYPE(base);
Guido van Rossum0986d822002-04-08 01:38:42 +00004180
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004181 /* Initialize tp_bases */
4182 bases = type->tp_bases;
4183 if (bases == NULL) {
4184 if (base == NULL)
4185 bases = PyTuple_New(0);
4186 else
4187 bases = PyTuple_Pack(1, base);
4188 if (bases == NULL)
4189 goto error;
4190 type->tp_bases = bases;
4191 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004192
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004193 /* Initialize tp_dict */
4194 dict = type->tp_dict;
4195 if (dict == NULL) {
4196 dict = PyDict_New();
4197 if (dict == NULL)
4198 goto error;
4199 type->tp_dict = dict;
4200 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004201
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004202 /* Add type-specific descriptors to tp_dict */
4203 if (add_operators(type) < 0)
4204 goto error;
4205 if (type->tp_methods != NULL) {
4206 if (add_methods(type, type->tp_methods) < 0)
4207 goto error;
4208 }
4209 if (type->tp_members != NULL) {
4210 if (add_members(type, type->tp_members) < 0)
4211 goto error;
4212 }
4213 if (type->tp_getset != NULL) {
4214 if (add_getset(type, type->tp_getset) < 0)
4215 goto error;
4216 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004217
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004218 /* Calculate method resolution order */
4219 if (mro_internal(type) < 0) {
4220 goto error;
4221 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004222
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004223 /* Inherit special flags from dominant base */
4224 if (type->tp_base != NULL)
4225 inherit_special(type, type->tp_base);
Guido van Rossum13d52f02001-08-10 21:24:08 +00004226
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004227 /* Initialize tp_dict properly */
4228 bases = type->tp_mro;
4229 assert(bases != NULL);
4230 assert(PyTuple_Check(bases));
4231 n = PyTuple_GET_SIZE(bases);
4232 for (i = 1; i < n; i++) {
4233 PyObject *b = PyTuple_GET_ITEM(bases, i);
4234 if (PyType_Check(b))
4235 inherit_slots(type, (PyTypeObject *)b);
4236 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004237
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004238 /* Sanity check for tp_free. */
4239 if (PyType_IS_GC(type) && (type->tp_flags & Py_TPFLAGS_BASETYPE) &&
4240 (type->tp_free == NULL || type->tp_free == PyObject_Del)) {
4241 /* This base class needs to call tp_free, but doesn't have
4242 * one, or its tp_free is for non-gc'ed objects.
4243 */
4244 PyErr_Format(PyExc_TypeError, "type '%.100s' participates in "
4245 "gc and is a base type but has inappropriate "
4246 "tp_free slot",
4247 type->tp_name);
4248 goto error;
4249 }
Tim Peters3cfe7542003-05-21 21:29:48 +00004250
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004251 /* if the type dictionary doesn't contain a __doc__, set it from
4252 the tp_doc slot.
4253 */
Victor Stinner3c1e4812012-03-26 22:10:51 +02004254 if (_PyDict_GetItemId(type->tp_dict, &PyId___doc__) == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004255 if (type->tp_doc != NULL) {
4256 PyObject *doc = PyUnicode_FromString(type->tp_doc);
4257 if (doc == NULL)
4258 goto error;
Victor Stinner3c1e4812012-03-26 22:10:51 +02004259 _PyDict_SetItemId(type->tp_dict, &PyId___doc__, doc);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004260 Py_DECREF(doc);
4261 } else {
Victor Stinner3c1e4812012-03-26 22:10:51 +02004262 _PyDict_SetItemId(type->tp_dict,
4263 &PyId___doc__, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004264 }
4265 }
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00004266
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004267 /* Hack for tp_hash and __hash__.
4268 If after all that, tp_hash is still NULL, and __hash__ is not in
4269 tp_dict, set tp_hash to PyObject_HashNotImplemented and
4270 tp_dict['__hash__'] equal to None.
4271 This signals that __hash__ is not inherited.
4272 */
4273 if (type->tp_hash == NULL) {
Victor Stinner3c1e4812012-03-26 22:10:51 +02004274 if (_PyDict_GetItemId(type->tp_dict, &PyId___hash__) == NULL) {
4275 if (_PyDict_SetItemId(type->tp_dict, &PyId___hash__, Py_None) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004276 goto error;
4277 type->tp_hash = PyObject_HashNotImplemented;
4278 }
4279 }
Guido van Rossum38938152006-08-21 23:36:26 +00004280
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004281 /* Some more special stuff */
4282 base = type->tp_base;
4283 if (base != NULL) {
4284 if (type->tp_as_number == NULL)
4285 type->tp_as_number = base->tp_as_number;
4286 if (type->tp_as_sequence == NULL)
4287 type->tp_as_sequence = base->tp_as_sequence;
4288 if (type->tp_as_mapping == NULL)
4289 type->tp_as_mapping = base->tp_as_mapping;
4290 if (type->tp_as_buffer == NULL)
4291 type->tp_as_buffer = base->tp_as_buffer;
4292 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004293
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004294 /* Link into each base class's list of subclasses */
4295 bases = type->tp_bases;
4296 n = PyTuple_GET_SIZE(bases);
4297 for (i = 0; i < n; i++) {
4298 PyObject *b = PyTuple_GET_ITEM(bases, i);
4299 if (PyType_Check(b) &&
4300 add_subclass((PyTypeObject *)b, type) < 0)
4301 goto error;
4302 }
Guido van Rossum1c450732001-10-08 15:18:27 +00004303
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004304 /* Warn for a type that implements tp_compare (now known as
4305 tp_reserved) but not tp_richcompare. */
4306 if (type->tp_reserved && !type->tp_richcompare) {
Andrew Svetlov2cd8ce42012-12-23 14:27:17 +02004307 PyErr_Format(PyExc_TypeError,
Victor Stinner4a2b7a12010-08-13 14:03:48 +00004308 "Type %.100s defines tp_reserved (formerly tp_compare) "
4309 "but not tp_richcompare. Comparisons may not behave as intended.",
4310 type->tp_name);
Andrew Svetlov2cd8ce42012-12-23 14:27:17 +02004311 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004312 }
Mark Dickinson2a7d45b2009-02-08 11:02:10 +00004313
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004314 /* All done -- set the ready flag */
4315 assert(type->tp_dict != NULL);
4316 type->tp_flags =
4317 (type->tp_flags & ~Py_TPFLAGS_READYING) | Py_TPFLAGS_READY;
4318 return 0;
Guido van Rossumd614f972001-08-10 17:39:49 +00004319
4320 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004321 type->tp_flags &= ~Py_TPFLAGS_READYING;
4322 return -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004323}
4324
Guido van Rossum1c450732001-10-08 15:18:27 +00004325static int
4326add_subclass(PyTypeObject *base, PyTypeObject *type)
4327{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004328 Py_ssize_t i;
4329 int result;
4330 PyObject *list, *ref, *newobj;
Guido van Rossum1c450732001-10-08 15:18:27 +00004331
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004332 list = base->tp_subclasses;
4333 if (list == NULL) {
4334 base->tp_subclasses = list = PyList_New(0);
4335 if (list == NULL)
4336 return -1;
4337 }
4338 assert(PyList_Check(list));
4339 newobj = PyWeakref_NewRef((PyObject *)type, NULL);
Victor Stinner9812af82013-07-08 22:25:48 +02004340 if (newobj == NULL)
4341 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004342 i = PyList_GET_SIZE(list);
4343 while (--i >= 0) {
4344 ref = PyList_GET_ITEM(list, i);
4345 assert(PyWeakref_CheckRef(ref));
4346 if (PyWeakref_GET_OBJECT(ref) == Py_None)
4347 return PyList_SetItem(list, i, newobj);
4348 }
4349 result = PyList_Append(list, newobj);
4350 Py_DECREF(newobj);
4351 return result;
Guido van Rossum1c450732001-10-08 15:18:27 +00004352}
4353
Michael W. Hudson98bbc492002-11-26 14:47:27 +00004354static void
4355remove_subclass(PyTypeObject *base, PyTypeObject *type)
4356{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004357 Py_ssize_t i;
4358 PyObject *list, *ref;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00004359
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004360 list = base->tp_subclasses;
4361 if (list == NULL) {
4362 return;
4363 }
4364 assert(PyList_Check(list));
4365 i = PyList_GET_SIZE(list);
4366 while (--i >= 0) {
4367 ref = PyList_GET_ITEM(list, i);
4368 assert(PyWeakref_CheckRef(ref));
4369 if (PyWeakref_GET_OBJECT(ref) == (PyObject*)type) {
4370 /* this can't fail, right? */
4371 PySequence_DelItem(list, i);
4372 return;
4373 }
4374 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +00004375}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004376
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004377static int
4378check_num_args(PyObject *ob, int n)
4379{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004380 if (!PyTuple_CheckExact(ob)) {
4381 PyErr_SetString(PyExc_SystemError,
4382 "PyArg_UnpackTuple() argument list is not a tuple");
4383 return 0;
4384 }
4385 if (n == PyTuple_GET_SIZE(ob))
4386 return 1;
4387 PyErr_Format(
4388 PyExc_TypeError,
4389 "expected %d arguments, got %zd", n, PyTuple_GET_SIZE(ob));
4390 return 0;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004391}
4392
Tim Peters6d6c1a32001-08-02 04:15:00 +00004393/* Generic wrappers for overloadable 'operators' such as __getitem__ */
4394
4395/* There's a wrapper *function* for each distinct function typedef used
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004396 for type object slots (e.g. binaryfunc, ternaryfunc, etc.). There's a
Tim Peters6d6c1a32001-08-02 04:15:00 +00004397 wrapper *table* for each distinct operation (e.g. __len__, __add__).
4398 Most tables have only one entry; the tables for binary operators have two
4399 entries, one regular and one with reversed arguments. */
4400
4401static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00004402wrap_lenfunc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004403{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004404 lenfunc func = (lenfunc)wrapped;
4405 Py_ssize_t res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004406
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004407 if (!check_num_args(args, 0))
4408 return NULL;
4409 res = (*func)(self);
4410 if (res == -1 && PyErr_Occurred())
4411 return NULL;
4412 return PyLong_FromLong((long)res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004413}
4414
Tim Peters6d6c1a32001-08-02 04:15:00 +00004415static PyObject *
Raymond Hettingerf34f2642003-10-11 17:29:04 +00004416wrap_inquirypred(PyObject *self, PyObject *args, void *wrapped)
4417{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004418 inquiry func = (inquiry)wrapped;
4419 int res;
Raymond Hettingerf34f2642003-10-11 17:29:04 +00004420
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004421 if (!check_num_args(args, 0))
4422 return NULL;
4423 res = (*func)(self);
4424 if (res == -1 && PyErr_Occurred())
4425 return NULL;
4426 return PyBool_FromLong((long)res);
Raymond Hettingerf34f2642003-10-11 17:29:04 +00004427}
4428
4429static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00004430wrap_binaryfunc(PyObject *self, PyObject *args, void *wrapped)
4431{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004432 binaryfunc func = (binaryfunc)wrapped;
4433 PyObject *other;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004434
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004435 if (!check_num_args(args, 1))
4436 return NULL;
4437 other = PyTuple_GET_ITEM(args, 0);
4438 return (*func)(self, other);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004439}
4440
4441static PyObject *
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00004442wrap_binaryfunc_l(PyObject *self, PyObject *args, void *wrapped)
4443{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004444 binaryfunc func = (binaryfunc)wrapped;
4445 PyObject *other;
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00004446
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004447 if (!check_num_args(args, 1))
4448 return NULL;
4449 other = PyTuple_GET_ITEM(args, 0);
4450 return (*func)(self, other);
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00004451}
4452
4453static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00004454wrap_binaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
4455{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004456 binaryfunc func = (binaryfunc)wrapped;
4457 PyObject *other;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004458
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004459 if (!check_num_args(args, 1))
4460 return NULL;
4461 other = PyTuple_GET_ITEM(args, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004462 return (*func)(other, self);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004463}
4464
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004465static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00004466wrap_ternaryfunc(PyObject *self, PyObject *args, void *wrapped)
4467{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004468 ternaryfunc func = (ternaryfunc)wrapped;
4469 PyObject *other;
4470 PyObject *third = Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004471
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004472 /* Note: This wrapper only works for __pow__() */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004473
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004474 if (!PyArg_UnpackTuple(args, "", 1, 2, &other, &third))
4475 return NULL;
4476 return (*func)(self, other, third);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004477}
4478
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00004479static PyObject *
4480wrap_ternaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
4481{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004482 ternaryfunc func = (ternaryfunc)wrapped;
4483 PyObject *other;
4484 PyObject *third = Py_None;
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00004485
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004486 /* Note: This wrapper only works for __pow__() */
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00004487
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004488 if (!PyArg_UnpackTuple(args, "", 1, 2, &other, &third))
4489 return NULL;
4490 return (*func)(other, self, third);
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00004491}
4492
Tim Peters6d6c1a32001-08-02 04:15:00 +00004493static PyObject *
4494wrap_unaryfunc(PyObject *self, PyObject *args, void *wrapped)
4495{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004496 unaryfunc func = (unaryfunc)wrapped;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004497
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004498 if (!check_num_args(args, 0))
4499 return NULL;
4500 return (*func)(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004501}
4502
Tim Peters6d6c1a32001-08-02 04:15:00 +00004503static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004504wrap_indexargfunc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004505{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004506 ssizeargfunc func = (ssizeargfunc)wrapped;
4507 PyObject* o;
4508 Py_ssize_t i;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004509
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004510 if (!PyArg_UnpackTuple(args, "", 1, 1, &o))
4511 return NULL;
4512 i = PyNumber_AsSsize_t(o, PyExc_OverflowError);
4513 if (i == -1 && PyErr_Occurred())
4514 return NULL;
4515 return (*func)(self, i);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004516}
4517
Martin v. Löwis18e16552006-02-15 17:27:45 +00004518static Py_ssize_t
Guido van Rossum5d815f32001-08-17 21:57:47 +00004519getindex(PyObject *self, PyObject *arg)
4520{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004521 Py_ssize_t i;
Guido van Rossum5d815f32001-08-17 21:57:47 +00004522
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004523 i = PyNumber_AsSsize_t(arg, PyExc_OverflowError);
4524 if (i == -1 && PyErr_Occurred())
4525 return -1;
4526 if (i < 0) {
4527 PySequenceMethods *sq = Py_TYPE(self)->tp_as_sequence;
4528 if (sq && sq->sq_length) {
4529 Py_ssize_t n = (*sq->sq_length)(self);
4530 if (n < 0)
4531 return -1;
4532 i += n;
4533 }
4534 }
4535 return i;
Guido van Rossum5d815f32001-08-17 21:57:47 +00004536}
4537
4538static PyObject *
4539wrap_sq_item(PyObject *self, PyObject *args, void *wrapped)
4540{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004541 ssizeargfunc func = (ssizeargfunc)wrapped;
4542 PyObject *arg;
4543 Py_ssize_t i;
Guido van Rossum5d815f32001-08-17 21:57:47 +00004544
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004545 if (PyTuple_GET_SIZE(args) == 1) {
4546 arg = PyTuple_GET_ITEM(args, 0);
4547 i = getindex(self, arg);
4548 if (i == -1 && PyErr_Occurred())
4549 return NULL;
4550 return (*func)(self, i);
4551 }
4552 check_num_args(args, 1);
4553 assert(PyErr_Occurred());
4554 return NULL;
Guido van Rossum5d815f32001-08-17 21:57:47 +00004555}
4556
Tim Peters6d6c1a32001-08-02 04:15:00 +00004557static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00004558wrap_sq_setitem(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004559{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004560 ssizeobjargproc func = (ssizeobjargproc)wrapped;
4561 Py_ssize_t i;
4562 int res;
4563 PyObject *arg, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004564
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004565 if (!PyArg_UnpackTuple(args, "", 2, 2, &arg, &value))
4566 return NULL;
4567 i = getindex(self, arg);
4568 if (i == -1 && PyErr_Occurred())
4569 return NULL;
4570 res = (*func)(self, i, value);
4571 if (res == -1 && PyErr_Occurred())
4572 return NULL;
4573 Py_INCREF(Py_None);
4574 return Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004575}
4576
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004577static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00004578wrap_sq_delitem(PyObject *self, PyObject *args, void *wrapped)
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004579{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004580 ssizeobjargproc func = (ssizeobjargproc)wrapped;
4581 Py_ssize_t i;
4582 int res;
4583 PyObject *arg;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004584
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004585 if (!check_num_args(args, 1))
4586 return NULL;
4587 arg = PyTuple_GET_ITEM(args, 0);
4588 i = getindex(self, arg);
4589 if (i == -1 && PyErr_Occurred())
4590 return NULL;
4591 res = (*func)(self, i, NULL);
4592 if (res == -1 && PyErr_Occurred())
4593 return NULL;
4594 Py_INCREF(Py_None);
4595 return Py_None;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004596}
4597
Tim Peters6d6c1a32001-08-02 04:15:00 +00004598/* XXX objobjproc is a misnomer; should be objargpred */
4599static PyObject *
4600wrap_objobjproc(PyObject *self, PyObject *args, void *wrapped)
4601{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004602 objobjproc func = (objobjproc)wrapped;
4603 int res;
4604 PyObject *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004605
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004606 if (!check_num_args(args, 1))
4607 return NULL;
4608 value = PyTuple_GET_ITEM(args, 0);
4609 res = (*func)(self, value);
4610 if (res == -1 && PyErr_Occurred())
4611 return NULL;
4612 else
4613 return PyBool_FromLong(res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004614}
4615
Tim Peters6d6c1a32001-08-02 04:15:00 +00004616static PyObject *
4617wrap_objobjargproc(PyObject *self, PyObject *args, void *wrapped)
4618{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004619 objobjargproc func = (objobjargproc)wrapped;
4620 int res;
4621 PyObject *key, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004622
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004623 if (!PyArg_UnpackTuple(args, "", 2, 2, &key, &value))
4624 return NULL;
4625 res = (*func)(self, key, value);
4626 if (res == -1 && PyErr_Occurred())
4627 return NULL;
4628 Py_INCREF(Py_None);
4629 return Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004630}
4631
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004632static PyObject *
4633wrap_delitem(PyObject *self, PyObject *args, void *wrapped)
4634{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004635 objobjargproc func = (objobjargproc)wrapped;
4636 int res;
4637 PyObject *key;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004638
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004639 if (!check_num_args(args, 1))
4640 return NULL;
4641 key = PyTuple_GET_ITEM(args, 0);
4642 res = (*func)(self, key, NULL);
4643 if (res == -1 && PyErr_Occurred())
4644 return NULL;
4645 Py_INCREF(Py_None);
4646 return Py_None;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004647}
4648
Guido van Rossum4dcdb782003-04-14 21:46:03 +00004649/* Helper to check for object.__setattr__ or __delattr__ applied to a type.
Guido van Rossum52b27052003-04-15 20:05:10 +00004650 This is called the Carlo Verre hack after its discoverer. */
Guido van Rossum4dcdb782003-04-14 21:46:03 +00004651static int
4652hackcheck(PyObject *self, setattrofunc func, char *what)
4653{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004654 PyTypeObject *type = Py_TYPE(self);
4655 while (type && type->tp_flags & Py_TPFLAGS_HEAPTYPE)
4656 type = type->tp_base;
4657 /* If type is NULL now, this is a really weird type.
4658 In the spirit of backwards compatibility (?), just shut up. */
4659 if (type && type->tp_setattro != func) {
4660 PyErr_Format(PyExc_TypeError,
4661 "can't apply this %s to %s object",
4662 what,
4663 type->tp_name);
4664 return 0;
4665 }
4666 return 1;
Guido van Rossum4dcdb782003-04-14 21:46:03 +00004667}
4668
Tim Peters6d6c1a32001-08-02 04:15:00 +00004669static PyObject *
4670wrap_setattr(PyObject *self, PyObject *args, void *wrapped)
4671{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004672 setattrofunc func = (setattrofunc)wrapped;
4673 int res;
4674 PyObject *name, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004675
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004676 if (!PyArg_UnpackTuple(args, "", 2, 2, &name, &value))
4677 return NULL;
4678 if (!hackcheck(self, func, "__setattr__"))
4679 return NULL;
4680 res = (*func)(self, name, value);
4681 if (res < 0)
4682 return NULL;
4683 Py_INCREF(Py_None);
4684 return Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004685}
4686
4687static PyObject *
4688wrap_delattr(PyObject *self, PyObject *args, void *wrapped)
4689{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004690 setattrofunc func = (setattrofunc)wrapped;
4691 int res;
4692 PyObject *name;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004693
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004694 if (!check_num_args(args, 1))
4695 return NULL;
4696 name = PyTuple_GET_ITEM(args, 0);
4697 if (!hackcheck(self, func, "__delattr__"))
4698 return NULL;
4699 res = (*func)(self, name, NULL);
4700 if (res < 0)
4701 return NULL;
4702 Py_INCREF(Py_None);
4703 return Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004704}
4705
Tim Peters6d6c1a32001-08-02 04:15:00 +00004706static PyObject *
4707wrap_hashfunc(PyObject *self, PyObject *args, void *wrapped)
4708{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004709 hashfunc func = (hashfunc)wrapped;
Benjamin Peterson8035bc52010-10-23 16:20:50 +00004710 Py_hash_t res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004711
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004712 if (!check_num_args(args, 0))
4713 return NULL;
4714 res = (*func)(self);
4715 if (res == -1 && PyErr_Occurred())
4716 return NULL;
Benjamin Peterson8035bc52010-10-23 16:20:50 +00004717 return PyLong_FromSsize_t(res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004718}
4719
Tim Peters6d6c1a32001-08-02 04:15:00 +00004720static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00004721wrap_call(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004722{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004723 ternaryfunc func = (ternaryfunc)wrapped;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004724
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004725 return (*func)(self, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004726}
4727
Tim Peters6d6c1a32001-08-02 04:15:00 +00004728static PyObject *
4729wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op)
4730{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004731 richcmpfunc func = (richcmpfunc)wrapped;
4732 PyObject *other;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004733
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004734 if (!check_num_args(args, 1))
4735 return NULL;
4736 other = PyTuple_GET_ITEM(args, 0);
4737 return (*func)(self, other, op);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004738}
4739
4740#undef RICHCMP_WRAPPER
4741#define RICHCMP_WRAPPER(NAME, OP) \
4742static PyObject * \
4743richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \
4744{ \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004745 return wrap_richcmpfunc(self, args, wrapped, OP); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004746}
4747
Jack Jansen8e938b42001-08-08 15:29:49 +00004748RICHCMP_WRAPPER(lt, Py_LT)
4749RICHCMP_WRAPPER(le, Py_LE)
4750RICHCMP_WRAPPER(eq, Py_EQ)
4751RICHCMP_WRAPPER(ne, Py_NE)
4752RICHCMP_WRAPPER(gt, Py_GT)
4753RICHCMP_WRAPPER(ge, Py_GE)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004754
Tim Peters6d6c1a32001-08-02 04:15:00 +00004755static PyObject *
4756wrap_next(PyObject *self, PyObject *args, void *wrapped)
4757{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004758 unaryfunc func = (unaryfunc)wrapped;
4759 PyObject *res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004760
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004761 if (!check_num_args(args, 0))
4762 return NULL;
4763 res = (*func)(self);
4764 if (res == NULL && !PyErr_Occurred())
4765 PyErr_SetNone(PyExc_StopIteration);
4766 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004767}
4768
Tim Peters6d6c1a32001-08-02 04:15:00 +00004769static PyObject *
4770wrap_descr_get(PyObject *self, PyObject *args, void *wrapped)
4771{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004772 descrgetfunc func = (descrgetfunc)wrapped;
4773 PyObject *obj;
4774 PyObject *type = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004775
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004776 if (!PyArg_UnpackTuple(args, "", 1, 2, &obj, &type))
4777 return NULL;
4778 if (obj == Py_None)
4779 obj = NULL;
4780 if (type == Py_None)
4781 type = NULL;
4782 if (type == NULL &&obj == NULL) {
4783 PyErr_SetString(PyExc_TypeError,
4784 "__get__(None, None) is invalid");
4785 return NULL;
4786 }
4787 return (*func)(self, obj, type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004788}
4789
Tim Peters6d6c1a32001-08-02 04:15:00 +00004790static PyObject *
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004791wrap_descr_set(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004792{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004793 descrsetfunc func = (descrsetfunc)wrapped;
4794 PyObject *obj, *value;
4795 int ret;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004796
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004797 if (!PyArg_UnpackTuple(args, "", 2, 2, &obj, &value))
4798 return NULL;
4799 ret = (*func)(self, obj, value);
4800 if (ret < 0)
4801 return NULL;
4802 Py_INCREF(Py_None);
4803 return Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004804}
Guido van Rossum22b13872002-08-06 21:41:44 +00004805
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00004806static PyObject *
4807wrap_descr_delete(PyObject *self, PyObject *args, void *wrapped)
4808{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004809 descrsetfunc func = (descrsetfunc)wrapped;
4810 PyObject *obj;
4811 int ret;
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00004812
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004813 if (!check_num_args(args, 1))
4814 return NULL;
4815 obj = PyTuple_GET_ITEM(args, 0);
4816 ret = (*func)(self, obj, NULL);
4817 if (ret < 0)
4818 return NULL;
4819 Py_INCREF(Py_None);
4820 return Py_None;
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00004821}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004822
Tim Peters6d6c1a32001-08-02 04:15:00 +00004823static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00004824wrap_init(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004825{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004826 initproc func = (initproc)wrapped;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004827
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004828 if (func(self, args, kwds) < 0)
4829 return NULL;
4830 Py_INCREF(Py_None);
4831 return Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004832}
4833
Tim Peters6d6c1a32001-08-02 04:15:00 +00004834static PyObject *
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004835tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004836{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004837 PyTypeObject *type, *subtype, *staticbase;
4838 PyObject *arg0, *res;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004839
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004840 if (self == NULL || !PyType_Check(self))
4841 Py_FatalError("__new__() called with non-type 'self'");
4842 type = (PyTypeObject *)self;
4843 if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) {
4844 PyErr_Format(PyExc_TypeError,
4845 "%s.__new__(): not enough arguments",
4846 type->tp_name);
4847 return NULL;
4848 }
4849 arg0 = PyTuple_GET_ITEM(args, 0);
4850 if (!PyType_Check(arg0)) {
4851 PyErr_Format(PyExc_TypeError,
4852 "%s.__new__(X): X is not a type object (%s)",
4853 type->tp_name,
4854 Py_TYPE(arg0)->tp_name);
4855 return NULL;
4856 }
4857 subtype = (PyTypeObject *)arg0;
4858 if (!PyType_IsSubtype(subtype, type)) {
4859 PyErr_Format(PyExc_TypeError,
4860 "%s.__new__(%s): %s is not a subtype of %s",
4861 type->tp_name,
4862 subtype->tp_name,
4863 subtype->tp_name,
4864 type->tp_name);
4865 return NULL;
4866 }
Barry Warsaw60f01882001-08-22 19:24:42 +00004867
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004868 /* Check that the use doesn't do something silly and unsafe like
4869 object.__new__(dict). To do this, we check that the
4870 most derived base that's not a heap type is this type. */
4871 staticbase = subtype;
Martin v. Löwis9c564092012-06-23 23:20:45 +02004872 while (staticbase && (staticbase->tp_new == slot_tp_new))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004873 staticbase = staticbase->tp_base;
4874 /* If staticbase is NULL now, it is a really weird type.
4875 In the spirit of backwards compatibility (?), just shut up. */
4876 if (staticbase && staticbase->tp_new != type->tp_new) {
4877 PyErr_Format(PyExc_TypeError,
4878 "%s.__new__(%s) is not safe, use %s.__new__()",
4879 type->tp_name,
4880 subtype->tp_name,
4881 staticbase == NULL ? "?" : staticbase->tp_name);
4882 return NULL;
4883 }
Barry Warsaw60f01882001-08-22 19:24:42 +00004884
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004885 args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
4886 if (args == NULL)
4887 return NULL;
4888 res = type->tp_new(subtype, args, kwds);
4889 Py_DECREF(args);
4890 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004891}
4892
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004893static struct PyMethodDef tp_new_methoddef[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004894 {"__new__", (PyCFunction)tp_new_wrapper, METH_VARARGS|METH_KEYWORDS,
4895 PyDoc_STR("T.__new__(S, ...) -> "
4896 "a new object with type S, a subtype of T")},
4897 {0}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004898};
4899
4900static int
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004901add_tp_new_wrapper(PyTypeObject *type)
4902{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004903 PyObject *func;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004904
Victor Stinner3c1e4812012-03-26 22:10:51 +02004905 if (_PyDict_GetItemId(type->tp_dict, &PyId___new__) != NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004906 return 0;
Andrew Svetlov3ba3a3e2012-12-25 13:32:35 +02004907 func = PyCFunction_NewEx(tp_new_methoddef, (PyObject *)type, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004908 if (func == NULL)
4909 return -1;
Victor Stinner3c1e4812012-03-26 22:10:51 +02004910 if (_PyDict_SetItemId(type->tp_dict, &PyId___new__, func)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004911 Py_DECREF(func);
4912 return -1;
4913 }
4914 Py_DECREF(func);
4915 return 0;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004916}
4917
Guido van Rossumf040ede2001-08-07 16:40:56 +00004918/* Slot wrappers that call the corresponding __foo__ slot. See comments
4919 below at override_slots() for more explanation. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004920
Guido van Rossumdc91b992001-08-08 22:26:22 +00004921#define SLOT0(FUNCNAME, OPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004922static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004923FUNCNAME(PyObject *self) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004924{ \
Benjamin Petersonce798522012-01-22 11:24:29 -05004925 _Py_static_string(id, OPSTR); \
4926 return call_method(self, &id, "()"); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004927}
4928
Guido van Rossumdc91b992001-08-08 22:26:22 +00004929#define SLOT1(FUNCNAME, OPSTR, ARG1TYPE, ARGCODES) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004930static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004931FUNCNAME(PyObject *self, ARG1TYPE arg1) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004932{ \
Benjamin Petersonce798522012-01-22 11:24:29 -05004933 _Py_static_string(id, OPSTR); \
4934 return call_method(self, &id, "(" ARGCODES ")", arg1); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004935}
4936
Guido van Rossumcd118802003-01-06 22:57:47 +00004937/* Boolean helper for SLOT1BINFULL().
4938 right.__class__ is a nontrivial subclass of left.__class__. */
4939static int
Victor Stinner3c1e4812012-03-26 22:10:51 +02004940method_is_overloaded(PyObject *left, PyObject *right, struct _Py_Identifier *name)
Guido van Rossumcd118802003-01-06 22:57:47 +00004941{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004942 PyObject *a, *b;
4943 int ok;
Guido van Rossumcd118802003-01-06 22:57:47 +00004944
Victor Stinner3c1e4812012-03-26 22:10:51 +02004945 b = _PyObject_GetAttrId((PyObject *)(Py_TYPE(right)), name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004946 if (b == NULL) {
4947 PyErr_Clear();
4948 /* If right doesn't have it, it's not overloaded */
4949 return 0;
4950 }
Guido van Rossumcd118802003-01-06 22:57:47 +00004951
Victor Stinner3c1e4812012-03-26 22:10:51 +02004952 a = _PyObject_GetAttrId((PyObject *)(Py_TYPE(left)), name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004953 if (a == NULL) {
4954 PyErr_Clear();
4955 Py_DECREF(b);
4956 /* If right has it but left doesn't, it's overloaded */
4957 return 1;
4958 }
Guido van Rossumcd118802003-01-06 22:57:47 +00004959
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004960 ok = PyObject_RichCompareBool(a, b, Py_NE);
4961 Py_DECREF(a);
4962 Py_DECREF(b);
4963 if (ok < 0) {
4964 PyErr_Clear();
4965 return 0;
4966 }
Guido van Rossumcd118802003-01-06 22:57:47 +00004967
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004968 return ok;
Guido van Rossumcd118802003-01-06 22:57:47 +00004969}
4970
Guido van Rossumdc91b992001-08-08 22:26:22 +00004971
4972#define SLOT1BINFULL(FUNCNAME, TESTFUNC, SLOTNAME, OPSTR, ROPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004973static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004974FUNCNAME(PyObject *self, PyObject *other) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004975{ \
Benjamin Petersonce798522012-01-22 11:24:29 -05004976 _Py_static_string(op_id, OPSTR); \
4977 _Py_static_string(rop_id, ROPSTR); \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004978 int do_other = Py_TYPE(self) != Py_TYPE(other) && \
4979 Py_TYPE(other)->tp_as_number != NULL && \
4980 Py_TYPE(other)->tp_as_number->SLOTNAME == TESTFUNC; \
4981 if (Py_TYPE(self)->tp_as_number != NULL && \
4982 Py_TYPE(self)->tp_as_number->SLOTNAME == TESTFUNC) { \
4983 PyObject *r; \
4984 if (do_other && \
4985 PyType_IsSubtype(Py_TYPE(other), Py_TYPE(self)) && \
Victor Stinner3c1e4812012-03-26 22:10:51 +02004986 method_is_overloaded(self, other, &rop_id)) { \
Benjamin Petersonce798522012-01-22 11:24:29 -05004987 r = call_maybe(other, &rop_id, "(O)", self); \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004988 if (r != Py_NotImplemented) \
4989 return r; \
4990 Py_DECREF(r); \
4991 do_other = 0; \
4992 } \
Benjamin Petersonce798522012-01-22 11:24:29 -05004993 r = call_maybe(self, &op_id, "(O)", other); \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004994 if (r != Py_NotImplemented || \
4995 Py_TYPE(other) == Py_TYPE(self)) \
4996 return r; \
4997 Py_DECREF(r); \
4998 } \
4999 if (do_other) { \
Benjamin Petersonce798522012-01-22 11:24:29 -05005000 return call_maybe(other, &rop_id, "(O)", self); \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005001 } \
Brian Curtindfc80e32011-08-10 20:28:54 -05005002 Py_RETURN_NOTIMPLEMENTED; \
Guido van Rossumdc91b992001-08-08 22:26:22 +00005003}
5004
5005#define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005006 SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR)
Guido van Rossumdc91b992001-08-08 22:26:22 +00005007
5008#define SLOT2(FUNCNAME, OPSTR, ARG1TYPE, ARG2TYPE, ARGCODES) \
5009static PyObject * \
5010FUNCNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \
5011{ \
Benjamin Petersonce798522012-01-22 11:24:29 -05005012 _Py_static_string(id, #OPSTR); \
5013 return call_method(self, &id, "(" ARGCODES ")", arg1, arg2); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00005014}
5015
Martin v. Löwis18e16552006-02-15 17:27:45 +00005016static Py_ssize_t
Tim Peters6d6c1a32001-08-02 04:15:00 +00005017slot_sq_length(PyObject *self)
5018{
Benjamin Petersonce798522012-01-22 11:24:29 -05005019 _Py_IDENTIFIER(__len__);
5020 PyObject *res = call_method(self, &PyId___len__, "()");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005021 Py_ssize_t len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005022
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005023 if (res == NULL)
5024 return -1;
5025 len = PyNumber_AsSsize_t(res, PyExc_OverflowError);
5026 Py_DECREF(res);
5027 if (len < 0) {
5028 if (!PyErr_Occurred())
5029 PyErr_SetString(PyExc_ValueError,
5030 "__len__() should return >= 0");
5031 return -1;
5032 }
5033 return len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005034}
5035
Guido van Rossumf4593e02001-10-03 12:09:30 +00005036/* Super-optimized version of slot_sq_item.
5037 Other slots could do the same... */
5038static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00005039slot_sq_item(PyObject *self, Py_ssize_t i)
Guido van Rossumf4593e02001-10-03 12:09:30 +00005040{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005041 PyObject *func, *args = NULL, *ival = NULL, *retval = NULL;
5042 descrgetfunc f;
Guido van Rossumf4593e02001-10-03 12:09:30 +00005043
Victor Stinner3c1e4812012-03-26 22:10:51 +02005044 func = _PyType_LookupId(Py_TYPE(self), &PyId___getitem__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005045 if (func != NULL) {
5046 if ((f = Py_TYPE(func)->tp_descr_get) == NULL)
5047 Py_INCREF(func);
5048 else {
5049 func = f(func, self, (PyObject *)(Py_TYPE(self)));
5050 if (func == NULL) {
5051 return NULL;
5052 }
5053 }
5054 ival = PyLong_FromSsize_t(i);
5055 if (ival != NULL) {
5056 args = PyTuple_New(1);
5057 if (args != NULL) {
5058 PyTuple_SET_ITEM(args, 0, ival);
5059 retval = PyObject_Call(func, args, NULL);
5060 Py_XDECREF(args);
5061 Py_XDECREF(func);
5062 return retval;
5063 }
5064 }
5065 }
5066 else {
Victor Stinner3c1e4812012-03-26 22:10:51 +02005067 PyObject *getitem_str = _PyUnicode_FromId(&PyId___getitem__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005068 PyErr_SetObject(PyExc_AttributeError, getitem_str);
5069 }
5070 Py_XDECREF(args);
5071 Py_XDECREF(ival);
5072 Py_XDECREF(func);
5073 return NULL;
Guido van Rossumf4593e02001-10-03 12:09:30 +00005074}
5075
Tim Peters6d6c1a32001-08-02 04:15:00 +00005076static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00005077slot_sq_ass_item(PyObject *self, Py_ssize_t index, PyObject *value)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005078{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005079 PyObject *res;
Benjamin Petersonce798522012-01-22 11:24:29 -05005080 _Py_IDENTIFIER(__delitem__);
5081 _Py_IDENTIFIER(__setitem__);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005082
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005083 if (value == NULL)
Benjamin Petersonce798522012-01-22 11:24:29 -05005084 res = call_method(self, &PyId___delitem__, "(n)", index);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005085 else
Benjamin Petersonce798522012-01-22 11:24:29 -05005086 res = call_method(self, &PyId___setitem__, "(nO)", index, value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005087 if (res == NULL)
5088 return -1;
5089 Py_DECREF(res);
5090 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005091}
5092
5093static int
Tim Peters6d6c1a32001-08-02 04:15:00 +00005094slot_sq_contains(PyObject *self, PyObject *value)
5095{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005096 PyObject *func, *res, *args;
5097 int result = -1;
Benjamin Petersonce798522012-01-22 11:24:29 -05005098 _Py_IDENTIFIER(__contains__);
Tim Petersbf9b2442003-03-23 05:35:36 +00005099
Benjamin Petersonce798522012-01-22 11:24:29 -05005100 func = lookup_maybe(self, &PyId___contains__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005101 if (func != NULL) {
5102 args = PyTuple_Pack(1, value);
5103 if (args == NULL)
5104 res = NULL;
5105 else {
5106 res = PyObject_Call(func, args, NULL);
5107 Py_DECREF(args);
5108 }
5109 Py_DECREF(func);
5110 if (res != NULL) {
5111 result = PyObject_IsTrue(res);
5112 Py_DECREF(res);
5113 }
5114 }
5115 else if (! PyErr_Occurred()) {
5116 /* Possible results: -1 and 1 */
5117 result = (int)_PySequence_IterSearch(self, value,
5118 PY_ITERSEARCH_CONTAINS);
5119 }
5120 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005121}
5122
Tim Peters6d6c1a32001-08-02 04:15:00 +00005123#define slot_mp_length slot_sq_length
5124
Guido van Rossumdc91b992001-08-08 22:26:22 +00005125SLOT1(slot_mp_subscript, "__getitem__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00005126
5127static int
5128slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value)
5129{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005130 PyObject *res;
Benjamin Petersonce798522012-01-22 11:24:29 -05005131 _Py_IDENTIFIER(__delitem__);
5132 _Py_IDENTIFIER(__setitem__);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005133
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005134 if (value == NULL)
Benjamin Petersonce798522012-01-22 11:24:29 -05005135 res = call_method(self, &PyId___delitem__, "(O)", key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005136 else
Benjamin Petersonce798522012-01-22 11:24:29 -05005137 res = call_method(self, &PyId___setitem__, "(OO)", key, value);
5138
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005139 if (res == NULL)
5140 return -1;
5141 Py_DECREF(res);
5142 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005143}
5144
Guido van Rossumdc91b992001-08-08 22:26:22 +00005145SLOT1BIN(slot_nb_add, nb_add, "__add__", "__radd__")
5146SLOT1BIN(slot_nb_subtract, nb_subtract, "__sub__", "__rsub__")
5147SLOT1BIN(slot_nb_multiply, nb_multiply, "__mul__", "__rmul__")
Guido van Rossumdc91b992001-08-08 22:26:22 +00005148SLOT1BIN(slot_nb_remainder, nb_remainder, "__mod__", "__rmod__")
5149SLOT1BIN(slot_nb_divmod, nb_divmod, "__divmod__", "__rdivmod__")
5150
Jeremy Hylton938ace62002-07-17 16:30:39 +00005151static PyObject *slot_nb_power(PyObject *, PyObject *, PyObject *);
Guido van Rossumdc91b992001-08-08 22:26:22 +00005152
5153SLOT1BINFULL(slot_nb_power_binary, slot_nb_power,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005154 nb_power, "__pow__", "__rpow__")
Guido van Rossumdc91b992001-08-08 22:26:22 +00005155
5156static PyObject *
5157slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus)
5158{
Benjamin Petersonce798522012-01-22 11:24:29 -05005159 _Py_IDENTIFIER(__pow__);
Guido van Rossum2730b132001-08-28 18:22:14 +00005160
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005161 if (modulus == Py_None)
5162 return slot_nb_power_binary(self, other);
5163 /* Three-arg power doesn't use __rpow__. But ternary_op
5164 can call this when the second argument's type uses
5165 slot_nb_power, so check before calling self.__pow__. */
5166 if (Py_TYPE(self)->tp_as_number != NULL &&
5167 Py_TYPE(self)->tp_as_number->nb_power == slot_nb_power) {
Benjamin Petersonce798522012-01-22 11:24:29 -05005168 return call_method(self, &PyId___pow__, "(OO)", other, modulus);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005169 }
Brian Curtindfc80e32011-08-10 20:28:54 -05005170 Py_RETURN_NOTIMPLEMENTED;
Guido van Rossumdc91b992001-08-08 22:26:22 +00005171}
5172
5173SLOT0(slot_nb_negative, "__neg__")
5174SLOT0(slot_nb_positive, "__pos__")
5175SLOT0(slot_nb_absolute, "__abs__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00005176
5177static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00005178slot_nb_bool(PyObject *self)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005179{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005180 PyObject *func, *args;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005181 int result = -1;
5182 int using_len = 0;
Benjamin Petersonce798522012-01-22 11:24:29 -05005183 _Py_IDENTIFIER(__len__);
5184 _Py_IDENTIFIER(__bool__);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005185
Benjamin Petersonce798522012-01-22 11:24:29 -05005186 func = lookup_maybe(self, &PyId___bool__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005187 if (func == NULL) {
5188 if (PyErr_Occurred())
5189 return -1;
Benjamin Petersonce798522012-01-22 11:24:29 -05005190 func = lookup_maybe(self, &PyId___len__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005191 if (func == NULL)
5192 return PyErr_Occurred() ? -1 : 1;
5193 using_len = 1;
5194 }
5195 args = PyTuple_New(0);
5196 if (args != NULL) {
5197 PyObject *temp = PyObject_Call(func, args, NULL);
5198 Py_DECREF(args);
5199 if (temp != NULL) {
5200 if (using_len) {
5201 /* enforced by slot_nb_len */
5202 result = PyObject_IsTrue(temp);
5203 }
5204 else if (PyBool_Check(temp)) {
5205 result = PyObject_IsTrue(temp);
5206 }
5207 else {
5208 PyErr_Format(PyExc_TypeError,
5209 "__bool__ should return "
5210 "bool, returned %s",
5211 Py_TYPE(temp)->tp_name);
5212 result = -1;
5213 }
5214 Py_DECREF(temp);
5215 }
5216 }
5217 Py_DECREF(func);
5218 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005219}
5220
Guido van Rossum38fff8c2006-03-07 18:50:55 +00005221
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00005222static PyObject *
Guido van Rossum38fff8c2006-03-07 18:50:55 +00005223slot_nb_index(PyObject *self)
5224{
Benjamin Petersonce798522012-01-22 11:24:29 -05005225 _Py_IDENTIFIER(__index__);
5226 return call_method(self, &PyId___index__, "()");
Guido van Rossum38fff8c2006-03-07 18:50:55 +00005227}
5228
5229
Guido van Rossumdc91b992001-08-08 22:26:22 +00005230SLOT0(slot_nb_invert, "__invert__")
5231SLOT1BIN(slot_nb_lshift, nb_lshift, "__lshift__", "__rlshift__")
5232SLOT1BIN(slot_nb_rshift, nb_rshift, "__rshift__", "__rrshift__")
5233SLOT1BIN(slot_nb_and, nb_and, "__and__", "__rand__")
5234SLOT1BIN(slot_nb_xor, nb_xor, "__xor__", "__rxor__")
5235SLOT1BIN(slot_nb_or, nb_or, "__or__", "__ror__")
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00005236
Guido van Rossumdc91b992001-08-08 22:26:22 +00005237SLOT0(slot_nb_int, "__int__")
Guido van Rossumdc91b992001-08-08 22:26:22 +00005238SLOT0(slot_nb_float, "__float__")
Guido van Rossumdc91b992001-08-08 22:26:22 +00005239SLOT1(slot_nb_inplace_add, "__iadd__", PyObject *, "O")
5240SLOT1(slot_nb_inplace_subtract, "__isub__", PyObject *, "O")
5241SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *, "O")
Guido van Rossumdc91b992001-08-08 22:26:22 +00005242SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *, "O")
Thomas Wouterscf297e42007-02-23 15:07:44 +00005243/* Can't use SLOT1 here, because nb_inplace_power is ternary */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005244static PyObject *
5245slot_nb_inplace_power(PyObject *self, PyObject * arg1, PyObject *arg2)
5246{
Benjamin Petersonce798522012-01-22 11:24:29 -05005247 _Py_IDENTIFIER(__ipow__);
5248 return call_method(self, &PyId___ipow__, "(" "O" ")", arg1);
Thomas Wouterscf297e42007-02-23 15:07:44 +00005249}
Guido van Rossumdc91b992001-08-08 22:26:22 +00005250SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *, "O")
5251SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *, "O")
5252SLOT1(slot_nb_inplace_and, "__iand__", PyObject *, "O")
5253SLOT1(slot_nb_inplace_xor, "__ixor__", PyObject *, "O")
5254SLOT1(slot_nb_inplace_or, "__ior__", PyObject *, "O")
5255SLOT1BIN(slot_nb_floor_divide, nb_floor_divide,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005256 "__floordiv__", "__rfloordiv__")
Guido van Rossumdc91b992001-08-08 22:26:22 +00005257SLOT1BIN(slot_nb_true_divide, nb_true_divide, "__truediv__", "__rtruediv__")
5258SLOT1(slot_nb_inplace_floor_divide, "__ifloordiv__", PyObject *, "O")
5259SLOT1(slot_nb_inplace_true_divide, "__itruediv__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00005260
Guido van Rossumb8f63662001-08-15 23:57:02 +00005261static PyObject *
5262slot_tp_repr(PyObject *self)
5263{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005264 PyObject *func, *res;
Benjamin Petersonce798522012-01-22 11:24:29 -05005265 _Py_IDENTIFIER(__repr__);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005266
Benjamin Petersonce798522012-01-22 11:24:29 -05005267 func = lookup_method(self, &PyId___repr__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005268 if (func != NULL) {
5269 res = PyEval_CallObject(func, NULL);
5270 Py_DECREF(func);
5271 return res;
5272 }
5273 PyErr_Clear();
5274 return PyUnicode_FromFormat("<%s object at %p>",
5275 Py_TYPE(self)->tp_name, self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005276}
5277
5278static PyObject *
5279slot_tp_str(PyObject *self)
5280{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005281 PyObject *func, *res;
Benjamin Petersonce798522012-01-22 11:24:29 -05005282 _Py_IDENTIFIER(__str__);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005283
Benjamin Petersonce798522012-01-22 11:24:29 -05005284 func = lookup_method(self, &PyId___str__);
Victor Stinner2e8474d2013-07-11 22:46:11 +02005285 if (func == NULL)
5286 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005287 res = PyEval_CallObject(func, NULL);
5288 Py_DECREF(func);
5289 return res;
5290 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00005291
Benjamin Peterson8f67d082010-10-17 20:54:53 +00005292static Py_hash_t
Tim Peters6d6c1a32001-08-02 04:15:00 +00005293slot_tp_hash(PyObject *self)
5294{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005295 PyObject *func, *res;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00005296 Py_ssize_t h;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005297
Benjamin Petersonce798522012-01-22 11:24:29 -05005298 func = lookup_method(self, &PyId___hash__);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005299
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005300 if (func == Py_None) {
5301 Py_DECREF(func);
5302 func = NULL;
5303 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +00005304
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005305 if (func == NULL) {
5306 return PyObject_HashNotImplemented(self);
5307 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +00005308
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005309 res = PyEval_CallObject(func, NULL);
5310 Py_DECREF(func);
5311 if (res == NULL)
5312 return -1;
Mark Dickinsondc787d22010-05-23 13:33:13 +00005313
5314 if (!PyLong_Check(res)) {
5315 PyErr_SetString(PyExc_TypeError,
5316 "__hash__ method should return an integer");
5317 return -1;
5318 }
Benjamin Peterson8f67d082010-10-17 20:54:53 +00005319 /* Transform the PyLong `res` to a Py_hash_t `h`. For an existing
5320 hashable Python object x, hash(x) will always lie within the range of
5321 Py_hash_t. Therefore our transformation must preserve values that
5322 already lie within this range, to ensure that if x.__hash__() returns
5323 hash(y) then hash(x) == hash(y). */
5324 h = PyLong_AsSsize_t(res);
5325 if (h == -1 && PyErr_Occurred()) {
5326 /* res was not within the range of a Py_hash_t, so we're free to
Mark Dickinsondc787d22010-05-23 13:33:13 +00005327 use any sufficiently bit-mixing transformation;
5328 long.__hash__ will do nicely. */
Benjamin Peterson8f67d082010-10-17 20:54:53 +00005329 PyErr_Clear();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005330 h = PyLong_Type.tp_hash(res);
Benjamin Peterson8f67d082010-10-17 20:54:53 +00005331 }
Benjamin Petersone7dfeeb2010-10-17 21:27:01 +00005332 /* -1 is reserved for errors. */
5333 if (h == -1)
5334 h = -2;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005335 Py_DECREF(res);
Mark Dickinsondc787d22010-05-23 13:33:13 +00005336 return h;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005337}
5338
5339static PyObject *
5340slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds)
5341{
Benjamin Petersonce798522012-01-22 11:24:29 -05005342 _Py_IDENTIFIER(__call__);
5343 PyObject *meth = lookup_method(self, &PyId___call__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005344 PyObject *res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005345
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005346 if (meth == NULL)
5347 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005348
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005349 res = PyObject_Call(meth, args, kwds);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005350
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005351 Py_DECREF(meth);
5352 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005353}
5354
Guido van Rossum14a6f832001-10-17 13:59:09 +00005355/* There are two slot dispatch functions for tp_getattro.
5356
5357 - slot_tp_getattro() is used when __getattribute__ is overridden
5358 but no __getattr__ hook is present;
5359
5360 - slot_tp_getattr_hook() is used when a __getattr__ hook is present.
5361
Guido van Rossumc334df52002-04-04 23:44:47 +00005362 The code in update_one_slot() always installs slot_tp_getattr_hook(); this
5363 detects the absence of __getattr__ and then installs the simpler slot if
5364 necessary. */
Guido van Rossum14a6f832001-10-17 13:59:09 +00005365
Tim Peters6d6c1a32001-08-02 04:15:00 +00005366static PyObject *
5367slot_tp_getattro(PyObject *self, PyObject *name)
5368{
Benjamin Petersonce798522012-01-22 11:24:29 -05005369 return call_method(self, &PyId___getattribute__, "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005370}
5371
Guido van Rossum19c1cd52001-09-21 21:24:49 +00005372static PyObject *
Benjamin Peterson9262b842008-11-17 22:45:50 +00005373call_attribute(PyObject *self, PyObject *attr, PyObject *name)
5374{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005375 PyObject *res, *descr = NULL;
5376 descrgetfunc f = Py_TYPE(attr)->tp_descr_get;
Benjamin Peterson9262b842008-11-17 22:45:50 +00005377
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005378 if (f != NULL) {
5379 descr = f(attr, self, (PyObject *)(Py_TYPE(self)));
5380 if (descr == NULL)
5381 return NULL;
5382 else
5383 attr = descr;
5384 }
5385 res = PyObject_CallFunctionObjArgs(attr, name, NULL);
5386 Py_XDECREF(descr);
5387 return res;
Benjamin Peterson9262b842008-11-17 22:45:50 +00005388}
5389
5390static PyObject *
Guido van Rossum19c1cd52001-09-21 21:24:49 +00005391slot_tp_getattr_hook(PyObject *self, PyObject *name)
5392{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005393 PyTypeObject *tp = Py_TYPE(self);
5394 PyObject *getattr, *getattribute, *res;
Victor Stinner3c1e4812012-03-26 22:10:51 +02005395 _Py_IDENTIFIER(__getattr__);
Guido van Rossum19c1cd52001-09-21 21:24:49 +00005396
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005397 /* speed hack: we could use lookup_maybe, but that would resolve the
5398 method fully for each attribute lookup for classes with
5399 __getattr__, even when the attribute is present. So we use
5400 _PyType_Lookup and create the method only when needed, with
5401 call_attribute. */
Victor Stinner3c1e4812012-03-26 22:10:51 +02005402 getattr = _PyType_LookupId(tp, &PyId___getattr__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005403 if (getattr == NULL) {
5404 /* No __getattr__ hook: use a simpler dispatcher */
5405 tp->tp_getattro = slot_tp_getattro;
5406 return slot_tp_getattro(self, name);
5407 }
5408 Py_INCREF(getattr);
5409 /* speed hack: we could use lookup_maybe, but that would resolve the
5410 method fully for each attribute lookup for classes with
5411 __getattr__, even when self has the default __getattribute__
5412 method. So we use _PyType_Lookup and create the method only when
5413 needed, with call_attribute. */
Victor Stinner3c1e4812012-03-26 22:10:51 +02005414 getattribute = _PyType_LookupId(tp, &PyId___getattribute__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005415 if (getattribute == NULL ||
5416 (Py_TYPE(getattribute) == &PyWrapperDescr_Type &&
5417 ((PyWrapperDescrObject *)getattribute)->d_wrapped ==
5418 (void *)PyObject_GenericGetAttr))
5419 res = PyObject_GenericGetAttr(self, name);
5420 else {
5421 Py_INCREF(getattribute);
5422 res = call_attribute(self, getattribute, name);
5423 Py_DECREF(getattribute);
5424 }
5425 if (res == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) {
5426 PyErr_Clear();
5427 res = call_attribute(self, getattr, name);
5428 }
5429 Py_DECREF(getattr);
5430 return res;
Guido van Rossum19c1cd52001-09-21 21:24:49 +00005431}
5432
Tim Peters6d6c1a32001-08-02 04:15:00 +00005433static int
5434slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value)
5435{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005436 PyObject *res;
Benjamin Petersonce798522012-01-22 11:24:29 -05005437 _Py_IDENTIFIER(__delattr__);
5438 _Py_IDENTIFIER(__setattr__);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005439
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005440 if (value == NULL)
Benjamin Petersonce798522012-01-22 11:24:29 -05005441 res = call_method(self, &PyId___delattr__, "(O)", name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005442 else
Benjamin Petersonce798522012-01-22 11:24:29 -05005443 res = call_method(self, &PyId___setattr__, "(OO)", name, value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005444 if (res == NULL)
5445 return -1;
5446 Py_DECREF(res);
5447 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005448}
5449
Benjamin Petersonce798522012-01-22 11:24:29 -05005450static _Py_Identifier name_op[] = {
5451 {0, "__lt__", 0},
5452 {0, "__le__", 0},
5453 {0, "__eq__", 0},
5454 {0, "__ne__", 0},
5455 {0, "__gt__", 0},
5456 {0, "__ge__", 0}
Guido van Rossumf5243f02008-01-01 04:06:48 +00005457};
5458
Tim Peters6d6c1a32001-08-02 04:15:00 +00005459static PyObject *
Mark Dickinson6f1d0492009-11-15 13:58:49 +00005460slot_tp_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005461{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005462 PyObject *func, *args, *res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005463
Benjamin Petersonce798522012-01-22 11:24:29 -05005464 func = lookup_method(self, &name_op[op]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005465 if (func == NULL) {
5466 PyErr_Clear();
Brian Curtindfc80e32011-08-10 20:28:54 -05005467 Py_RETURN_NOTIMPLEMENTED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005468 }
5469 args = PyTuple_Pack(1, other);
5470 if (args == NULL)
5471 res = NULL;
5472 else {
5473 res = PyObject_Call(func, args, NULL);
5474 Py_DECREF(args);
5475 }
5476 Py_DECREF(func);
5477 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005478}
5479
Guido van Rossumb8f63662001-08-15 23:57:02 +00005480static PyObject *
Guido van Rossumb8f63662001-08-15 23:57:02 +00005481slot_tp_iter(PyObject *self)
5482{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005483 PyObject *func, *res;
Benjamin Petersonce798522012-01-22 11:24:29 -05005484 _Py_IDENTIFIER(__iter__);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005485
Benjamin Petersonce798522012-01-22 11:24:29 -05005486 func = lookup_method(self, &PyId___iter__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005487 if (func != NULL) {
5488 PyObject *args;
5489 args = res = PyTuple_New(0);
5490 if (args != NULL) {
5491 res = PyObject_Call(func, args, NULL);
5492 Py_DECREF(args);
5493 }
5494 Py_DECREF(func);
5495 return res;
5496 }
5497 PyErr_Clear();
Benjamin Petersonce798522012-01-22 11:24:29 -05005498 func = lookup_method(self, &PyId___getitem__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005499 if (func == NULL) {
5500 PyErr_Format(PyExc_TypeError,
5501 "'%.200s' object is not iterable",
5502 Py_TYPE(self)->tp_name);
5503 return NULL;
5504 }
5505 Py_DECREF(func);
5506 return PySeqIter_New(self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005507}
Tim Peters6d6c1a32001-08-02 04:15:00 +00005508
5509static PyObject *
5510slot_tp_iternext(PyObject *self)
5511{
Benjamin Petersonce798522012-01-22 11:24:29 -05005512 _Py_IDENTIFIER(__next__);
5513 return call_method(self, &PyId___next__, "()");
Tim Peters6d6c1a32001-08-02 04:15:00 +00005514}
5515
Guido van Rossum1a493502001-08-17 16:47:50 +00005516static PyObject *
5517slot_tp_descr_get(PyObject *self, PyObject *obj, PyObject *type)
5518{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005519 PyTypeObject *tp = Py_TYPE(self);
5520 PyObject *get;
Victor Stinner3c1e4812012-03-26 22:10:51 +02005521 _Py_IDENTIFIER(__get__);
Guido van Rossum1a493502001-08-17 16:47:50 +00005522
Victor Stinner3c1e4812012-03-26 22:10:51 +02005523 get = _PyType_LookupId(tp, &PyId___get__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005524 if (get == NULL) {
5525 /* Avoid further slowdowns */
5526 if (tp->tp_descr_get == slot_tp_descr_get)
5527 tp->tp_descr_get = NULL;
5528 Py_INCREF(self);
5529 return self;
5530 }
5531 if (obj == NULL)
5532 obj = Py_None;
5533 if (type == NULL)
5534 type = Py_None;
5535 return PyObject_CallFunctionObjArgs(get, self, obj, type, NULL);
Guido van Rossum1a493502001-08-17 16:47:50 +00005536}
Tim Peters6d6c1a32001-08-02 04:15:00 +00005537
5538static int
5539slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value)
5540{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005541 PyObject *res;
Benjamin Petersonce798522012-01-22 11:24:29 -05005542 _Py_IDENTIFIER(__delete__);
5543 _Py_IDENTIFIER(__set__);
Guido van Rossum2c252392001-08-24 10:13:31 +00005544
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005545 if (value == NULL)
Benjamin Petersonce798522012-01-22 11:24:29 -05005546 res = call_method(self, &PyId___delete__, "(O)", target);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005547 else
Benjamin Petersonce798522012-01-22 11:24:29 -05005548 res = call_method(self, &PyId___set__, "(OO)", target, value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005549 if (res == NULL)
5550 return -1;
5551 Py_DECREF(res);
5552 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005553}
5554
5555static int
5556slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds)
5557{
Benjamin Petersonce798522012-01-22 11:24:29 -05005558 _Py_IDENTIFIER(__init__);
5559 PyObject *meth = lookup_method(self, &PyId___init__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005560 PyObject *res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005561
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005562 if (meth == NULL)
5563 return -1;
5564 res = PyObject_Call(meth, args, kwds);
5565 Py_DECREF(meth);
5566 if (res == NULL)
5567 return -1;
5568 if (res != Py_None) {
5569 PyErr_Format(PyExc_TypeError,
5570 "__init__() should return None, not '%.200s'",
5571 Py_TYPE(res)->tp_name);
5572 Py_DECREF(res);
5573 return -1;
5574 }
5575 Py_DECREF(res);
5576 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005577}
5578
5579static PyObject *
5580slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
5581{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005582 PyObject *func;
5583 PyObject *newargs, *x;
5584 Py_ssize_t i, n;
Victor Stinner3c1e4812012-03-26 22:10:51 +02005585 _Py_IDENTIFIER(__new__);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005586
Victor Stinner3c1e4812012-03-26 22:10:51 +02005587 func = _PyObject_GetAttrId((PyObject *)type, &PyId___new__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005588 if (func == NULL)
5589 return NULL;
5590 assert(PyTuple_Check(args));
5591 n = PyTuple_GET_SIZE(args);
5592 newargs = PyTuple_New(n+1);
5593 if (newargs == NULL)
5594 return NULL;
5595 Py_INCREF(type);
5596 PyTuple_SET_ITEM(newargs, 0, (PyObject *)type);
5597 for (i = 0; i < n; i++) {
5598 x = PyTuple_GET_ITEM(args, i);
5599 Py_INCREF(x);
5600 PyTuple_SET_ITEM(newargs, i+1, x);
5601 }
5602 x = PyObject_Call(func, newargs, kwds);
5603 Py_DECREF(newargs);
5604 Py_DECREF(func);
5605 return x;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005606}
5607
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005608static void
5609slot_tp_del(PyObject *self)
5610{
Benjamin Petersonce798522012-01-22 11:24:29 -05005611 _Py_IDENTIFIER(__del__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005612 PyObject *del, *res;
5613 PyObject *error_type, *error_value, *error_traceback;
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005614
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005615 /* Temporarily resurrect the object. */
5616 assert(self->ob_refcnt == 0);
5617 self->ob_refcnt = 1;
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005618
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005619 /* Save the current exception, if any. */
5620 PyErr_Fetch(&error_type, &error_value, &error_traceback);
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005621
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005622 /* Execute __del__ method, if any. */
Benjamin Petersonce798522012-01-22 11:24:29 -05005623 del = lookup_maybe(self, &PyId___del__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005624 if (del != NULL) {
5625 res = PyEval_CallObject(del, NULL);
5626 if (res == NULL)
5627 PyErr_WriteUnraisable(del);
5628 else
5629 Py_DECREF(res);
5630 Py_DECREF(del);
5631 }
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005632
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005633 /* Restore the saved exception. */
5634 PyErr_Restore(error_type, error_value, error_traceback);
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005635
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005636 /* Undo the temporary resurrection; can't use DECREF here, it would
5637 * cause a recursive call.
5638 */
5639 assert(self->ob_refcnt > 0);
5640 if (--self->ob_refcnt == 0)
5641 return; /* this is the normal path out */
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005642
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005643 /* __del__ resurrected it! Make it look like the original Py_DECREF
5644 * never happened.
5645 */
5646 {
5647 Py_ssize_t refcnt = self->ob_refcnt;
5648 _Py_NewReference(self);
5649 self->ob_refcnt = refcnt;
5650 }
5651 assert(!PyType_IS_GC(Py_TYPE(self)) ||
5652 _Py_AS_GC(self)->gc.gc_refs != _PyGC_REFS_UNTRACKED);
5653 /* If Py_REF_DEBUG, _Py_NewReference bumped _Py_RefTotal, so
5654 * we need to undo that. */
5655 _Py_DEC_REFTOTAL;
5656 /* If Py_TRACE_REFS, _Py_NewReference re-added self to the object
5657 * chain, so no more to do there.
5658 * If COUNT_ALLOCS, the original decref bumped tp_frees, and
5659 * _Py_NewReference bumped tp_allocs: both of those need to be
5660 * undone.
5661 */
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005662#ifdef COUNT_ALLOCS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005663 --Py_TYPE(self)->tp_frees;
5664 --Py_TYPE(self)->tp_allocs;
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005665#endif
5666}
5667
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005668
Benjamin Peterson63952412013-04-01 17:41:41 -04005669/*
5670Table mapping __foo__ names to tp_foo offsets and slot_tp_foo wrapper functions.
5671
5672The table is ordered by offsets relative to the 'PyHeapTypeObject' structure,
5673which incorporates the additional structures used for numbers, sequences and
5674mappings. Note that multiple names may map to the same slot (e.g. __eq__,
5675__ne__ etc. all map to tp_richcompare) and one name may map to multiple slots
5676(e.g. __str__ affects tp_str as well as tp_repr). The table is terminated with
5677an all-zero entry. (This table is further initialized in init_slotdefs().)
5678*/
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005679
Guido van Rossum6d204072001-10-21 00:44:31 +00005680typedef struct wrapperbase slotdef;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005681
5682#undef TPSLOT
Guido van Rossumc8e56452001-10-22 00:43:43 +00005683#undef FLSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005684#undef ETSLOT
5685#undef SQSLOT
5686#undef MPSLOT
5687#undef NBSLOT
Guido van Rossum6d204072001-10-21 00:44:31 +00005688#undef UNSLOT
5689#undef IBSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005690#undef BINSLOT
5691#undef RBINSLOT
5692
Guido van Rossum6d204072001-10-21 00:44:31 +00005693#define TPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005694 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
5695 PyDoc_STR(DOC)}
Guido van Rossumc8e56452001-10-22 00:43:43 +00005696#define FLSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC, FLAGS) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005697 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
5698 PyDoc_STR(DOC), FLAGS}
Guido van Rossum6d204072001-10-21 00:44:31 +00005699#define ETSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005700 {NAME, offsetof(PyHeapTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
5701 PyDoc_STR(DOC)}
Guido van Rossum6d204072001-10-21 00:44:31 +00005702#define SQSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005703 ETSLOT(NAME, as_sequence.SLOT, FUNCTION, WRAPPER, DOC)
Guido van Rossum6d204072001-10-21 00:44:31 +00005704#define MPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005705 ETSLOT(NAME, as_mapping.SLOT, FUNCTION, WRAPPER, DOC)
Guido van Rossum6d204072001-10-21 00:44:31 +00005706#define NBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005707 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, DOC)
Guido van Rossum6d204072001-10-21 00:44:31 +00005708#define UNSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005709 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
5710 "x." NAME "() <==> " DOC)
Guido van Rossum6d204072001-10-21 00:44:31 +00005711#define IBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005712 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
5713 "x." NAME "(y) <==> x" DOC "y")
Guido van Rossum6d204072001-10-21 00:44:31 +00005714#define BINSLOT(NAME, SLOT, FUNCTION, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005715 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
5716 "x." NAME "(y) <==> x" DOC "y")
Guido van Rossum6d204072001-10-21 00:44:31 +00005717#define RBINSLOT(NAME, SLOT, FUNCTION, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005718 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
5719 "x." NAME "(y) <==> y" DOC "x")
Anthony Baxter56616992005-06-03 14:12:21 +00005720#define BINSLOTNOTINFIX(NAME, SLOT, FUNCTION, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005721 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
5722 "x." NAME "(y) <==> " DOC)
Anthony Baxter56616992005-06-03 14:12:21 +00005723#define RBINSLOTNOTINFIX(NAME, SLOT, FUNCTION, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005724 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
5725 "x." NAME "(y) <==> " DOC)
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005726
5727static slotdef slotdefs[] = {
Benjamin Peterson63952412013-04-01 17:41:41 -04005728 TPSLOT("__getattribute__", tp_getattr, NULL, NULL, ""),
5729 TPSLOT("__getattr__", tp_getattr, NULL, NULL, ""),
5730 TPSLOT("__setattr__", tp_setattr, NULL, NULL, ""),
5731 TPSLOT("__delattr__", tp_setattr, NULL, NULL, ""),
5732 TPSLOT("__repr__", tp_repr, slot_tp_repr, wrap_unaryfunc,
5733 "x.__repr__() <==> repr(x)"),
5734 TPSLOT("__hash__", tp_hash, slot_tp_hash, wrap_hashfunc,
5735 "x.__hash__() <==> hash(x)"),
5736 FLSLOT("__call__", tp_call, slot_tp_call, (wrapperfunc)wrap_call,
5737 "x.__call__(...) <==> x(...)", PyWrapperFlag_KEYWORDS),
5738 TPSLOT("__str__", tp_str, slot_tp_str, wrap_unaryfunc,
5739 "x.__str__() <==> str(x)"),
5740 TPSLOT("__getattribute__", tp_getattro, slot_tp_getattr_hook,
5741 wrap_binaryfunc, "x.__getattribute__('name') <==> x.name"),
5742 TPSLOT("__getattr__", tp_getattro, slot_tp_getattr_hook, NULL, ""),
5743 TPSLOT("__setattr__", tp_setattro, slot_tp_setattro, wrap_setattr,
5744 "x.__setattr__('name', value) <==> x.name = value"),
5745 TPSLOT("__delattr__", tp_setattro, slot_tp_setattro, wrap_delattr,
5746 "x.__delattr__('name') <==> del x.name"),
5747 TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare, richcmp_lt,
5748 "x.__lt__(y) <==> x<y"),
5749 TPSLOT("__le__", tp_richcompare, slot_tp_richcompare, richcmp_le,
5750 "x.__le__(y) <==> x<=y"),
5751 TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare, richcmp_eq,
5752 "x.__eq__(y) <==> x==y"),
5753 TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare, richcmp_ne,
5754 "x.__ne__(y) <==> x!=y"),
5755 TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare, richcmp_gt,
5756 "x.__gt__(y) <==> x>y"),
5757 TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare, richcmp_ge,
5758 "x.__ge__(y) <==> x>=y"),
5759 TPSLOT("__iter__", tp_iter, slot_tp_iter, wrap_unaryfunc,
5760 "x.__iter__() <==> iter(x)"),
5761 TPSLOT("__next__", tp_iternext, slot_tp_iternext, wrap_next,
5762 "x.__next__() <==> next(x)"),
5763 TPSLOT("__get__", tp_descr_get, slot_tp_descr_get, wrap_descr_get,
5764 "descr.__get__(obj[, type]) -> value"),
5765 TPSLOT("__set__", tp_descr_set, slot_tp_descr_set, wrap_descr_set,
5766 "descr.__set__(obj, value)"),
5767 TPSLOT("__delete__", tp_descr_set, slot_tp_descr_set,
5768 wrap_descr_delete, "descr.__delete__(obj)"),
5769 FLSLOT("__init__", tp_init, slot_tp_init, (wrapperfunc)wrap_init,
5770 "x.__init__(...) initializes x; "
5771 "see help(type(x)) for signature",
5772 PyWrapperFlag_KEYWORDS),
5773 TPSLOT("__new__", tp_new, slot_tp_new, NULL, ""),
5774 TPSLOT("__del__", tp_del, slot_tp_del, NULL, ""),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005775
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005776 BINSLOT("__add__", nb_add, slot_nb_add,
5777 "+"),
5778 RBINSLOT("__radd__", nb_add, slot_nb_add,
5779 "+"),
5780 BINSLOT("__sub__", nb_subtract, slot_nb_subtract,
5781 "-"),
5782 RBINSLOT("__rsub__", nb_subtract, slot_nb_subtract,
5783 "-"),
5784 BINSLOT("__mul__", nb_multiply, slot_nb_multiply,
5785 "*"),
5786 RBINSLOT("__rmul__", nb_multiply, slot_nb_multiply,
5787 "*"),
5788 BINSLOT("__mod__", nb_remainder, slot_nb_remainder,
5789 "%"),
5790 RBINSLOT("__rmod__", nb_remainder, slot_nb_remainder,
5791 "%"),
5792 BINSLOTNOTINFIX("__divmod__", nb_divmod, slot_nb_divmod,
5793 "divmod(x, y)"),
5794 RBINSLOTNOTINFIX("__rdivmod__", nb_divmod, slot_nb_divmod,
5795 "divmod(y, x)"),
5796 NBSLOT("__pow__", nb_power, slot_nb_power, wrap_ternaryfunc,
5797 "x.__pow__(y[, z]) <==> pow(x, y[, z])"),
5798 NBSLOT("__rpow__", nb_power, slot_nb_power, wrap_ternaryfunc_r,
5799 "y.__rpow__(x[, z]) <==> pow(x, y[, z])"),
5800 UNSLOT("__neg__", nb_negative, slot_nb_negative, wrap_unaryfunc, "-x"),
5801 UNSLOT("__pos__", nb_positive, slot_nb_positive, wrap_unaryfunc, "+x"),
5802 UNSLOT("__abs__", nb_absolute, slot_nb_absolute, wrap_unaryfunc,
5803 "abs(x)"),
5804 UNSLOT("__bool__", nb_bool, slot_nb_bool, wrap_inquirypred,
5805 "x != 0"),
5806 UNSLOT("__invert__", nb_invert, slot_nb_invert, wrap_unaryfunc, "~x"),
5807 BINSLOT("__lshift__", nb_lshift, slot_nb_lshift, "<<"),
5808 RBINSLOT("__rlshift__", nb_lshift, slot_nb_lshift, "<<"),
5809 BINSLOT("__rshift__", nb_rshift, slot_nb_rshift, ">>"),
5810 RBINSLOT("__rrshift__", nb_rshift, slot_nb_rshift, ">>"),
5811 BINSLOT("__and__", nb_and, slot_nb_and, "&"),
5812 RBINSLOT("__rand__", nb_and, slot_nb_and, "&"),
5813 BINSLOT("__xor__", nb_xor, slot_nb_xor, "^"),
5814 RBINSLOT("__rxor__", nb_xor, slot_nb_xor, "^"),
5815 BINSLOT("__or__", nb_or, slot_nb_or, "|"),
5816 RBINSLOT("__ror__", nb_or, slot_nb_or, "|"),
5817 UNSLOT("__int__", nb_int, slot_nb_int, wrap_unaryfunc,
5818 "int(x)"),
5819 UNSLOT("__float__", nb_float, slot_nb_float, wrap_unaryfunc,
5820 "float(x)"),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005821 IBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add,
Eli Benderskyd3baae72011-11-11 16:57:05 +02005822 wrap_binaryfunc, "+="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005823 IBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract,
Eli Benderskyd3baae72011-11-11 16:57:05 +02005824 wrap_binaryfunc, "-="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005825 IBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply,
Eli Benderskyd3baae72011-11-11 16:57:05 +02005826 wrap_binaryfunc, "*="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005827 IBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder,
Eli Benderskyd3baae72011-11-11 16:57:05 +02005828 wrap_binaryfunc, "%="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005829 IBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power,
Eli Benderskyd3baae72011-11-11 16:57:05 +02005830 wrap_binaryfunc, "**="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005831 IBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift,
Eli Benderskyd3baae72011-11-11 16:57:05 +02005832 wrap_binaryfunc, "<<="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005833 IBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift,
Eli Benderskyd3baae72011-11-11 16:57:05 +02005834 wrap_binaryfunc, ">>="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005835 IBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and,
Eli Benderskyd3baae72011-11-11 16:57:05 +02005836 wrap_binaryfunc, "&="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005837 IBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor,
Eli Benderskyd3baae72011-11-11 16:57:05 +02005838 wrap_binaryfunc, "^="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005839 IBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or,
Eli Benderskyd3baae72011-11-11 16:57:05 +02005840 wrap_binaryfunc, "|="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005841 BINSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
5842 RBINSLOT("__rfloordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
5843 BINSLOT("__truediv__", nb_true_divide, slot_nb_true_divide, "/"),
5844 RBINSLOT("__rtruediv__", nb_true_divide, slot_nb_true_divide, "/"),
5845 IBSLOT("__ifloordiv__", nb_inplace_floor_divide,
5846 slot_nb_inplace_floor_divide, wrap_binaryfunc, "//"),
5847 IBSLOT("__itruediv__", nb_inplace_true_divide,
5848 slot_nb_inplace_true_divide, wrap_binaryfunc, "/"),
Benjamin Peterson63952412013-04-01 17:41:41 -04005849 NBSLOT("__index__", nb_index, slot_nb_index, wrap_unaryfunc,
5850 "x[y:z] <==> x[y.__index__():z.__index__()]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005851
Benjamin Peterson63952412013-04-01 17:41:41 -04005852 MPSLOT("__len__", mp_length, slot_mp_length, wrap_lenfunc,
5853 "x.__len__() <==> len(x)"),
5854 MPSLOT("__getitem__", mp_subscript, slot_mp_subscript,
5855 wrap_binaryfunc,
5856 "x.__getitem__(y) <==> x[y]"),
5857 MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript,
5858 wrap_objobjargproc,
5859 "x.__setitem__(i, y) <==> x[i]=y"),
5860 MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript,
5861 wrap_delitem,
5862 "x.__delitem__(y) <==> del x[y]"),
5863
5864 SQSLOT("__len__", sq_length, slot_sq_length, wrap_lenfunc,
5865 "x.__len__() <==> len(x)"),
5866 /* Heap types defining __add__/__mul__ have sq_concat/sq_repeat == NULL.
5867 The logic in abstract.c always falls back to nb_add/nb_multiply in
5868 this case. Defining both the nb_* and the sq_* slots to call the
5869 user-defined methods has unexpected side-effects, as shown by
5870 test_descr.notimplemented() */
5871 SQSLOT("__add__", sq_concat, NULL, wrap_binaryfunc,
5872 "x.__add__(y) <==> x+y"),
5873 SQSLOT("__mul__", sq_repeat, NULL, wrap_indexargfunc,
5874 "x.__mul__(n) <==> x*n"),
5875 SQSLOT("__rmul__", sq_repeat, NULL, wrap_indexargfunc,
5876 "x.__rmul__(n) <==> n*x"),
5877 SQSLOT("__getitem__", sq_item, slot_sq_item, wrap_sq_item,
5878 "x.__getitem__(y) <==> x[y]"),
5879 SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_setitem,
5880 "x.__setitem__(i, y) <==> x[i]=y"),
5881 SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_delitem,
5882 "x.__delitem__(y) <==> del x[y]"),
5883 SQSLOT("__contains__", sq_contains, slot_sq_contains, wrap_objobjproc,
5884 "x.__contains__(y) <==> y in x"),
5885 SQSLOT("__iadd__", sq_inplace_concat, NULL,
5886 wrap_binaryfunc, "x.__iadd__(y) <==> x+=y"),
5887 SQSLOT("__imul__", sq_inplace_repeat, NULL,
5888 wrap_indexargfunc, "x.__imul__(y) <==> x*=y"),
5889
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005890 {NULL}
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005891};
5892
Guido van Rossumc334df52002-04-04 23:44:47 +00005893/* Given a type pointer and an offset gotten from a slotdef entry, return a
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005894 pointer to the actual slot. This is not quite the same as simply adding
Guido van Rossumc334df52002-04-04 23:44:47 +00005895 the offset to the type pointer, since it takes care to indirect through the
5896 proper indirection pointer (as_buffer, etc.); it returns NULL if the
5897 indirection pointer is NULL. */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005898static void **
Martin v. Löwis18e16552006-02-15 17:27:45 +00005899slotptr(PyTypeObject *type, int ioffset)
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005900{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005901 char *ptr;
5902 long offset = ioffset;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005903
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005904 /* Note: this depends on the order of the members of PyHeapTypeObject! */
5905 assert(offset >= 0);
5906 assert((size_t)offset < offsetof(PyHeapTypeObject, as_buffer));
5907 if ((size_t)offset >= offsetof(PyHeapTypeObject, as_sequence)) {
5908 ptr = (char *)type->tp_as_sequence;
5909 offset -= offsetof(PyHeapTypeObject, as_sequence);
5910 }
5911 else if ((size_t)offset >= offsetof(PyHeapTypeObject, as_mapping)) {
5912 ptr = (char *)type->tp_as_mapping;
5913 offset -= offsetof(PyHeapTypeObject, as_mapping);
5914 }
5915 else if ((size_t)offset >= offsetof(PyHeapTypeObject, as_number)) {
5916 ptr = (char *)type->tp_as_number;
5917 offset -= offsetof(PyHeapTypeObject, as_number);
5918 }
5919 else {
5920 ptr = (char *)type;
5921 }
5922 if (ptr != NULL)
5923 ptr += offset;
5924 return (void **)ptr;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005925}
Guido van Rossumf040ede2001-08-07 16:40:56 +00005926
Guido van Rossumc334df52002-04-04 23:44:47 +00005927/* Length of array of slotdef pointers used to store slots with the
5928 same __name__. There should be at most MAX_EQUIV-1 slotdef entries with
5929 the same __name__, for any __name__. Since that's a static property, it is
5930 appropriate to declare fixed-size arrays for this. */
5931#define MAX_EQUIV 10
5932
5933/* Return a slot pointer for a given name, but ONLY if the attribute has
5934 exactly one slot function. The name must be an interned string. */
5935static void **
5936resolve_slotdups(PyTypeObject *type, PyObject *name)
5937{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005938 /* XXX Maybe this could be optimized more -- but is it worth it? */
Guido van Rossumc334df52002-04-04 23:44:47 +00005939
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005940 /* pname and ptrs act as a little cache */
5941 static PyObject *pname;
5942 static slotdef *ptrs[MAX_EQUIV];
5943 slotdef *p, **pp;
5944 void **res, **ptr;
Guido van Rossumc334df52002-04-04 23:44:47 +00005945
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005946 if (pname != name) {
5947 /* Collect all slotdefs that match name into ptrs. */
5948 pname = name;
5949 pp = ptrs;
5950 for (p = slotdefs; p->name_strobj; p++) {
5951 if (p->name_strobj == name)
5952 *pp++ = p;
5953 }
5954 *pp = NULL;
5955 }
Guido van Rossumc334df52002-04-04 23:44:47 +00005956
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005957 /* Look in all matching slots of the type; if exactly one of these has
5958 a filled-in slot, return its value. Otherwise return NULL. */
5959 res = NULL;
5960 for (pp = ptrs; *pp; pp++) {
5961 ptr = slotptr(type, (*pp)->offset);
5962 if (ptr == NULL || *ptr == NULL)
5963 continue;
5964 if (res != NULL)
5965 return NULL;
5966 res = ptr;
5967 }
5968 return res;
Guido van Rossumc334df52002-04-04 23:44:47 +00005969}
5970
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005971/* Common code for update_slots_callback() and fixup_slot_dispatchers(). This
Guido van Rossumc334df52002-04-04 23:44:47 +00005972 does some incredibly complex thinking and then sticks something into the
5973 slot. (It sees if the adjacent slotdefs for the same slot have conflicting
5974 interests, and then stores a generic wrapper or a specific function into
5975 the slot.) Return a pointer to the next slotdef with a different offset,
5976 because that's convenient for fixup_slot_dispatchers(). */
5977static slotdef *
5978update_one_slot(PyTypeObject *type, slotdef *p)
5979{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005980 PyObject *descr;
5981 PyWrapperDescrObject *d;
5982 void *generic = NULL, *specific = NULL;
5983 int use_generic = 0;
5984 int offset = p->offset;
5985 void **ptr = slotptr(type, offset);
Guido van Rossumc334df52002-04-04 23:44:47 +00005986
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005987 if (ptr == NULL) {
5988 do {
5989 ++p;
5990 } while (p->offset == offset);
5991 return p;
5992 }
5993 do {
5994 descr = _PyType_Lookup(type, p->name_strobj);
5995 if (descr == NULL) {
5996 if (ptr == (void**)&type->tp_iternext) {
Trent Nelsonab02db22012-09-18 21:58:03 -04005997 specific = (void *)_PyObject_NextNotImplemented;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005998 }
5999 continue;
6000 }
Benjamin Peterson7b166872012-04-24 11:06:25 -04006001 if (Py_TYPE(descr) == &PyWrapperDescr_Type &&
6002 ((PyWrapperDescrObject *)descr)->d_base->name_strobj == p->name_strobj) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006003 void **tptr = resolve_slotdups(type, p->name_strobj);
6004 if (tptr == NULL || tptr == ptr)
6005 generic = p->function;
6006 d = (PyWrapperDescrObject *)descr;
6007 if (d->d_base->wrapper == p->wrapper &&
6008 PyType_IsSubtype(type, PyDescr_TYPE(d)))
6009 {
6010 if (specific == NULL ||
6011 specific == d->d_wrapped)
6012 specific = d->d_wrapped;
6013 else
6014 use_generic = 1;
6015 }
6016 }
6017 else if (Py_TYPE(descr) == &PyCFunction_Type &&
6018 PyCFunction_GET_FUNCTION(descr) ==
6019 (PyCFunction)tp_new_wrapper &&
6020 ptr == (void**)&type->tp_new)
6021 {
6022 /* The __new__ wrapper is not a wrapper descriptor,
6023 so must be special-cased differently.
6024 If we don't do this, creating an instance will
6025 always use slot_tp_new which will look up
6026 __new__ in the MRO which will call tp_new_wrapper
6027 which will look through the base classes looking
6028 for a static base and call its tp_new (usually
6029 PyType_GenericNew), after performing various
6030 sanity checks and constructing a new argument
6031 list. Cut all that nonsense short -- this speeds
6032 up instance creation tremendously. */
6033 specific = (void *)type->tp_new;
6034 /* XXX I'm not 100% sure that there isn't a hole
6035 in this reasoning that requires additional
6036 sanity checks. I'll buy the first person to
6037 point out a bug in this reasoning a beer. */
6038 }
6039 else if (descr == Py_None &&
6040 ptr == (void**)&type->tp_hash) {
6041 /* We specifically allow __hash__ to be set to None
6042 to prevent inheritance of the default
6043 implementation from object.__hash__ */
Trent Nelsonab02db22012-09-18 21:58:03 -04006044 specific = (void *)PyObject_HashNotImplemented;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006045 }
6046 else {
6047 use_generic = 1;
6048 generic = p->function;
6049 }
6050 } while ((++p)->offset == offset);
6051 if (specific && !use_generic)
6052 *ptr = specific;
6053 else
6054 *ptr = generic;
6055 return p;
Guido van Rossumc334df52002-04-04 23:44:47 +00006056}
6057
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006058/* In the type, update the slots whose slotdefs are gathered in the pp array.
6059 This is a callback for update_subclasses(). */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006060static int
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006061update_slots_callback(PyTypeObject *type, void *data)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006062{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006063 slotdef **pp = (slotdef **)data;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006064
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006065 for (; *pp; pp++)
6066 update_one_slot(type, *pp);
6067 return 0;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006068}
6069
Guido van Rossumc334df52002-04-04 23:44:47 +00006070/* Initialize the slotdefs table by adding interned string objects for the
6071 names and sorting the entries. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006072static void
Guido van Rossumd396b9c2001-10-13 20:02:41 +00006073init_slotdefs(void)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006074{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006075 slotdef *p;
6076 static int initialized = 0;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006077
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006078 if (initialized)
6079 return;
6080 for (p = slotdefs; p->name; p++) {
Benjamin Peterson63952412013-04-01 17:41:41 -04006081 /* Slots must be ordered by their offset in the PyHeapTypeObject. */
6082 assert(!p[1].name || p->offset <= p[1].offset);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006083 p->name_strobj = PyUnicode_InternFromString(p->name);
6084 if (!p->name_strobj)
6085 Py_FatalError("Out of memory interning slotdef names");
6086 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006087 initialized = 1;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006088}
6089
Guido van Rossumc334df52002-04-04 23:44:47 +00006090/* Update the slots after assignment to a class (type) attribute. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006091static int
6092update_slot(PyTypeObject *type, PyObject *name)
6093{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006094 slotdef *ptrs[MAX_EQUIV];
6095 slotdef *p;
6096 slotdef **pp;
6097 int offset;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006098
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006099 /* Clear the VALID_VERSION flag of 'type' and all its
6100 subclasses. This could possibly be unified with the
6101 update_subclasses() recursion below, but carefully:
6102 they each have their own conditions on which to stop
6103 recursing into subclasses. */
6104 PyType_Modified(type);
Christian Heimesa62da1d2008-01-12 19:39:10 +00006105
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006106 init_slotdefs();
6107 pp = ptrs;
6108 for (p = slotdefs; p->name; p++) {
6109 /* XXX assume name is interned! */
6110 if (p->name_strobj == name)
6111 *pp++ = p;
6112 }
6113 *pp = NULL;
6114 for (pp = ptrs; *pp; pp++) {
6115 p = *pp;
6116 offset = p->offset;
6117 while (p > slotdefs && (p-1)->offset == offset)
6118 --p;
6119 *pp = p;
6120 }
6121 if (ptrs[0] == NULL)
6122 return 0; /* Not an attribute that affects any slots */
6123 return update_subclasses(type, name,
6124 update_slots_callback, (void *)ptrs);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006125}
6126
Guido van Rossumc334df52002-04-04 23:44:47 +00006127/* Store the proper functions in the slot dispatches at class (type)
6128 definition time, based upon which operations the class overrides in its
6129 dict. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00006130static void
Guido van Rossum7b9144b2001-10-09 19:39:46 +00006131fixup_slot_dispatchers(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00006132{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006133 slotdef *p;
Tim Peters6d6c1a32001-08-02 04:15:00 +00006134
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006135 init_slotdefs();
6136 for (p = slotdefs; p->name; )
6137 p = update_one_slot(type, p);
Tim Peters6d6c1a32001-08-02 04:15:00 +00006138}
Guido van Rossum705f0f52001-08-24 16:47:00 +00006139
Michael W. Hudson98bbc492002-11-26 14:47:27 +00006140static void
6141update_all_slots(PyTypeObject* type)
6142{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006143 slotdef *p;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00006144
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006145 init_slotdefs();
6146 for (p = slotdefs; p->name; p++) {
6147 /* update_slot returns int but can't actually fail */
6148 update_slot(type, p->name_strobj);
6149 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +00006150}
6151
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006152/* recurse_down_subclasses() and update_subclasses() are mutually
6153 recursive functions to call a callback for all subclasses,
6154 but refraining from recursing into subclasses that define 'name'. */
6155
6156static int
6157update_subclasses(PyTypeObject *type, PyObject *name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006158 update_callback callback, void *data)
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006159{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006160 if (callback(type, data) < 0)
6161 return -1;
6162 return recurse_down_subclasses(type, name, callback, data);
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006163}
6164
6165static int
6166recurse_down_subclasses(PyTypeObject *type, PyObject *name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006167 update_callback callback, void *data)
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006168{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006169 PyTypeObject *subclass;
6170 PyObject *ref, *subclasses, *dict;
6171 Py_ssize_t i, n;
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006172
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006173 subclasses = type->tp_subclasses;
6174 if (subclasses == NULL)
6175 return 0;
6176 assert(PyList_Check(subclasses));
6177 n = PyList_GET_SIZE(subclasses);
6178 for (i = 0; i < n; i++) {
6179 ref = PyList_GET_ITEM(subclasses, i);
6180 assert(PyWeakref_CheckRef(ref));
6181 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
6182 assert(subclass != NULL);
6183 if ((PyObject *)subclass == Py_None)
6184 continue;
6185 assert(PyType_Check(subclass));
6186 /* Avoid recursing down into unaffected classes */
6187 dict = subclass->tp_dict;
6188 if (dict != NULL && PyDict_Check(dict) &&
6189 PyDict_GetItem(dict, name) != NULL)
6190 continue;
6191 if (update_subclasses(subclass, name, callback, data) < 0)
6192 return -1;
6193 }
6194 return 0;
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006195}
6196
Guido van Rossum6d204072001-10-21 00:44:31 +00006197/* This function is called by PyType_Ready() to populate the type's
6198 dictionary with method descriptors for function slots. For each
Guido van Rossum09638c12002-06-13 19:17:46 +00006199 function slot (like tp_repr) that's defined in the type, one or more
6200 corresponding descriptors are added in the type's tp_dict dictionary
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006201 under the appropriate name (like __repr__). Some function slots
Guido van Rossum09638c12002-06-13 19:17:46 +00006202 cause more than one descriptor to be added (for example, the nb_add
6203 slot adds both __add__ and __radd__ descriptors) and some function
6204 slots compete for the same descriptor (for example both sq_item and
6205 mp_subscript generate a __getitem__ descriptor).
6206
Ezio Melotti13925002011-03-16 11:05:33 +02006207 In the latter case, the first slotdef entry encountered wins. Since
Tim Petersbf9b2442003-03-23 05:35:36 +00006208 slotdef entries are sorted by the offset of the slot in the
Guido van Rossume5c691a2003-03-07 15:13:17 +00006209 PyHeapTypeObject, this gives us some control over disambiguating
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006210 between competing slots: the members of PyHeapTypeObject are listed
6211 from most general to least general, so the most general slot is
6212 preferred. In particular, because as_mapping comes before as_sequence,
6213 for a type that defines both mp_subscript and sq_item, mp_subscript
6214 wins.
Guido van Rossum09638c12002-06-13 19:17:46 +00006215
6216 This only adds new descriptors and doesn't overwrite entries in
6217 tp_dict that were previously defined. The descriptors contain a
6218 reference to the C function they must call, so that it's safe if they
6219 are copied into a subtype's __dict__ and the subtype has a different
6220 C function in its slot -- calling the method defined by the
6221 descriptor will call the C function that was used to create it,
6222 rather than the C function present in the slot when it is called.
6223 (This is important because a subtype may have a C function in the
6224 slot that calls the method from the dictionary, and we want to avoid
6225 infinite recursion here.) */
Guido van Rossum6d204072001-10-21 00:44:31 +00006226
6227static int
6228add_operators(PyTypeObject *type)
6229{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006230 PyObject *dict = type->tp_dict;
6231 slotdef *p;
6232 PyObject *descr;
6233 void **ptr;
Guido van Rossum6d204072001-10-21 00:44:31 +00006234
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006235 init_slotdefs();
6236 for (p = slotdefs; p->name; p++) {
6237 if (p->wrapper == NULL)
6238 continue;
6239 ptr = slotptr(type, p->offset);
6240 if (!ptr || !*ptr)
6241 continue;
6242 if (PyDict_GetItem(dict, p->name_strobj))
6243 continue;
Trent Nelsonab02db22012-09-18 21:58:03 -04006244 if (*ptr == (void *)PyObject_HashNotImplemented) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006245 /* Classes may prevent the inheritance of the tp_hash
6246 slot by storing PyObject_HashNotImplemented in it. Make it
6247 visible as a None value for the __hash__ attribute. */
6248 if (PyDict_SetItem(dict, p->name_strobj, Py_None) < 0)
6249 return -1;
6250 }
6251 else {
6252 descr = PyDescr_NewWrapper(type, p, *ptr);
6253 if (descr == NULL)
6254 return -1;
6255 if (PyDict_SetItem(dict, p->name_strobj, descr) < 0)
6256 return -1;
6257 Py_DECREF(descr);
6258 }
6259 }
6260 if (type->tp_new != NULL) {
6261 if (add_tp_new_wrapper(type) < 0)
6262 return -1;
6263 }
6264 return 0;
Guido van Rossum6d204072001-10-21 00:44:31 +00006265}
6266
Guido van Rossum705f0f52001-08-24 16:47:00 +00006267
6268/* Cooperative 'super' */
6269
6270typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006271 PyObject_HEAD
6272 PyTypeObject *type;
6273 PyObject *obj;
6274 PyTypeObject *obj_type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006275} superobject;
6276
Guido van Rossum6f799372001-09-20 20:46:19 +00006277static PyMemberDef super_members[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006278 {"__thisclass__", T_OBJECT, offsetof(superobject, type), READONLY,
6279 "the class invoking super()"},
6280 {"__self__", T_OBJECT, offsetof(superobject, obj), READONLY,
6281 "the instance invoking super(); may be None"},
6282 {"__self_class__", T_OBJECT, offsetof(superobject, obj_type), READONLY,
6283 "the type of the instance invoking super(); may be None"},
6284 {0}
Guido van Rossum41eb14d2001-08-30 23:13:11 +00006285};
6286
Guido van Rossum705f0f52001-08-24 16:47:00 +00006287static void
6288super_dealloc(PyObject *self)
6289{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006290 superobject *su = (superobject *)self;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006291
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006292 _PyObject_GC_UNTRACK(self);
6293 Py_XDECREF(su->obj);
6294 Py_XDECREF(su->type);
6295 Py_XDECREF(su->obj_type);
6296 Py_TYPE(self)->tp_free(self);
Guido van Rossum705f0f52001-08-24 16:47:00 +00006297}
6298
6299static PyObject *
Guido van Rossum41eb14d2001-08-30 23:13:11 +00006300super_repr(PyObject *self)
6301{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006302 superobject *su = (superobject *)self;
Guido van Rossum41eb14d2001-08-30 23:13:11 +00006303
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006304 if (su->obj_type)
6305 return PyUnicode_FromFormat(
6306 "<super: <class '%s'>, <%s object>>",
6307 su->type ? su->type->tp_name : "NULL",
6308 su->obj_type->tp_name);
6309 else
6310 return PyUnicode_FromFormat(
6311 "<super: <class '%s'>, NULL>",
6312 su->type ? su->type->tp_name : "NULL");
Guido van Rossum41eb14d2001-08-30 23:13:11 +00006313}
6314
6315static PyObject *
Guido van Rossum705f0f52001-08-24 16:47:00 +00006316super_getattro(PyObject *self, PyObject *name)
6317{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006318 superobject *su = (superobject *)self;
6319 int skip = su->obj_type == NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006320
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006321 if (!skip) {
6322 /* We want __class__ to return the class of the super object
6323 (i.e. super, or a subclass), not the class of su->obj. */
6324 skip = (PyUnicode_Check(name) &&
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006325 PyUnicode_GET_LENGTH(name) == 9 &&
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006326 PyUnicode_CompareWithASCIIString(name, "__class__") == 0);
6327 }
Guido van Rossum76ba09f2003-04-16 19:40:58 +00006328
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006329 if (!skip) {
6330 PyObject *mro, *res, *tmp, *dict;
6331 PyTypeObject *starttype;
6332 descrgetfunc f;
6333 Py_ssize_t i, n;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006334
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006335 starttype = su->obj_type;
6336 mro = starttype->tp_mro;
Guido van Rossum155db9a2002-04-02 17:53:47 +00006337
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006338 if (mro == NULL)
6339 n = 0;
6340 else {
6341 assert(PyTuple_Check(mro));
6342 n = PyTuple_GET_SIZE(mro);
6343 }
6344 for (i = 0; i < n; i++) {
6345 if ((PyObject *)(su->type) == PyTuple_GET_ITEM(mro, i))
6346 break;
6347 }
6348 i++;
6349 res = NULL;
Victor Stinnerd74782b2012-03-09 00:39:08 +01006350 /* keep a strong reference to mro because starttype->tp_mro can be
6351 replaced during PyDict_GetItem(dict, name) */
6352 Py_INCREF(mro);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006353 for (; i < n; i++) {
6354 tmp = PyTuple_GET_ITEM(mro, i);
6355 if (PyType_Check(tmp))
6356 dict = ((PyTypeObject *)tmp)->tp_dict;
6357 else
6358 continue;
6359 res = PyDict_GetItem(dict, name);
6360 if (res != NULL) {
6361 Py_INCREF(res);
6362 f = Py_TYPE(res)->tp_descr_get;
6363 if (f != NULL) {
6364 tmp = f(res,
6365 /* Only pass 'obj' param if
6366 this is instance-mode super
6367 (See SF ID #743627)
6368 */
6369 (su->obj == (PyObject *)
6370 su->obj_type
6371 ? (PyObject *)NULL
6372 : su->obj),
6373 (PyObject *)starttype);
6374 Py_DECREF(res);
6375 res = tmp;
6376 }
Victor Stinnerd74782b2012-03-09 00:39:08 +01006377 Py_DECREF(mro);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006378 return res;
6379 }
6380 }
Victor Stinnerd74782b2012-03-09 00:39:08 +01006381 Py_DECREF(mro);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006382 }
6383 return PyObject_GenericGetAttr(self, name);
Guido van Rossum705f0f52001-08-24 16:47:00 +00006384}
6385
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006386static PyTypeObject *
Guido van Rossum5b443c62001-12-03 15:38:28 +00006387supercheck(PyTypeObject *type, PyObject *obj)
6388{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006389 /* Check that a super() call makes sense. Return a type object.
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006390
Florent Xiclunaaa6c1d22011-12-12 18:54:29 +01006391 obj can be a class, or an instance of one:
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006392
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006393 - If it is a class, it must be a subclass of 'type'. This case is
6394 used for class methods; the return value is obj.
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006395
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006396 - If it is an instance, it must be an instance of 'type'. This is
6397 the normal case; the return value is obj.__class__.
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006398
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006399 But... when obj is an instance, we want to allow for the case where
6400 Py_TYPE(obj) is not a subclass of type, but obj.__class__ is!
6401 This will allow using super() with a proxy for obj.
6402 */
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006403
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006404 /* Check for first bullet above (special case) */
6405 if (PyType_Check(obj) && PyType_IsSubtype((PyTypeObject *)obj, type)) {
6406 Py_INCREF(obj);
6407 return (PyTypeObject *)obj;
6408 }
Guido van Rossum8e80a722003-02-18 19:22:22 +00006409
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006410 /* Normal case */
6411 if (PyType_IsSubtype(Py_TYPE(obj), type)) {
6412 Py_INCREF(Py_TYPE(obj));
6413 return Py_TYPE(obj);
6414 }
6415 else {
6416 /* Try the slow way */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006417 PyObject *class_attr;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006418
Martin v. Löwisbfc6d742011-10-13 20:03:57 +02006419 class_attr = _PyObject_GetAttrId(obj, &PyId___class__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006420 if (class_attr != NULL &&
6421 PyType_Check(class_attr) &&
6422 (PyTypeObject *)class_attr != Py_TYPE(obj))
6423 {
6424 int ok = PyType_IsSubtype(
6425 (PyTypeObject *)class_attr, type);
6426 if (ok)
6427 return (PyTypeObject *)class_attr;
6428 }
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006429
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006430 if (class_attr == NULL)
6431 PyErr_Clear();
6432 else
6433 Py_DECREF(class_attr);
6434 }
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006435
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006436 PyErr_SetString(PyExc_TypeError,
6437 "super(type, obj): "
6438 "obj must be an instance or subtype of type");
6439 return NULL;
Guido van Rossum5b443c62001-12-03 15:38:28 +00006440}
6441
Guido van Rossum705f0f52001-08-24 16:47:00 +00006442static PyObject *
6443super_descr_get(PyObject *self, PyObject *obj, PyObject *type)
6444{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006445 superobject *su = (superobject *)self;
6446 superobject *newobj;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006447
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006448 if (obj == NULL || obj == Py_None || su->obj != NULL) {
6449 /* Not binding to an object, or already bound */
6450 Py_INCREF(self);
6451 return self;
6452 }
6453 if (Py_TYPE(su) != &PySuper_Type)
6454 /* If su is an instance of a (strict) subclass of super,
6455 call its type */
6456 return PyObject_CallFunctionObjArgs((PyObject *)Py_TYPE(su),
6457 su->type, obj, NULL);
6458 else {
6459 /* Inline the common case */
6460 PyTypeObject *obj_type = supercheck(su->type, obj);
6461 if (obj_type == NULL)
6462 return NULL;
6463 newobj = (superobject *)PySuper_Type.tp_new(&PySuper_Type,
6464 NULL, NULL);
6465 if (newobj == NULL)
6466 return NULL;
6467 Py_INCREF(su->type);
6468 Py_INCREF(obj);
6469 newobj->type = su->type;
6470 newobj->obj = obj;
6471 newobj->obj_type = obj_type;
6472 return (PyObject *)newobj;
6473 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00006474}
6475
6476static int
6477super_init(PyObject *self, PyObject *args, PyObject *kwds)
6478{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006479 superobject *su = (superobject *)self;
6480 PyTypeObject *type = NULL;
6481 PyObject *obj = NULL;
6482 PyTypeObject *obj_type = NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006483
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006484 if (!_PyArg_NoKeywords("super", kwds))
6485 return -1;
6486 if (!PyArg_ParseTuple(args, "|O!O:super", &PyType_Type, &type, &obj))
6487 return -1;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00006488
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006489 if (type == NULL) {
6490 /* Call super(), without args -- fill in from __class__
6491 and first local variable on the stack. */
6492 PyFrameObject *f = PyThreadState_GET()->frame;
6493 PyCodeObject *co = f->f_code;
Victor Stinner0fcab4a2011-01-04 12:59:15 +00006494 Py_ssize_t i, n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006495 if (co == NULL) {
Benjamin Peterson6a42bd62012-09-01 23:04:38 -04006496 PyErr_SetString(PyExc_RuntimeError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006497 "super(): no code object");
6498 return -1;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00006499 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006500 if (co->co_argcount == 0) {
Benjamin Peterson6a42bd62012-09-01 23:04:38 -04006501 PyErr_SetString(PyExc_RuntimeError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006502 "super(): no arguments");
6503 return -1;
6504 }
6505 obj = f->f_localsplus[0];
Benjamin Peterson159ae412013-05-12 18:16:06 -05006506 if (obj == NULL && co->co_cell2arg) {
6507 /* The first argument might be a cell. */
6508 n = PyTuple_GET_SIZE(co->co_cellvars);
6509 for (i = 0; i < n; i++) {
6510 if (co->co_cell2arg[i] == 0) {
6511 PyObject *cell = f->f_localsplus[co->co_nlocals + i];
6512 assert(PyCell_Check(cell));
6513 obj = PyCell_GET(cell);
6514 break;
6515 }
6516 }
Guido van Rossum6832c812013-05-10 08:47:42 -07006517 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006518 if (obj == NULL) {
Benjamin Peterson6a42bd62012-09-01 23:04:38 -04006519 PyErr_SetString(PyExc_RuntimeError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006520 "super(): arg[0] deleted");
6521 return -1;
6522 }
6523 if (co->co_freevars == NULL)
6524 n = 0;
6525 else {
6526 assert(PyTuple_Check(co->co_freevars));
6527 n = PyTuple_GET_SIZE(co->co_freevars);
6528 }
6529 for (i = 0; i < n; i++) {
6530 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
6531 assert(PyUnicode_Check(name));
6532 if (!PyUnicode_CompareWithASCIIString(name,
Nick Coghlan0b43bcf2012-05-27 18:17:07 +10006533 "__class__")) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006534 Py_ssize_t index = co->co_nlocals +
6535 PyTuple_GET_SIZE(co->co_cellvars) + i;
6536 PyObject *cell = f->f_localsplus[index];
6537 if (cell == NULL || !PyCell_Check(cell)) {
Benjamin Peterson6a42bd62012-09-01 23:04:38 -04006538 PyErr_SetString(PyExc_RuntimeError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006539 "super(): bad __class__ cell");
6540 return -1;
6541 }
6542 type = (PyTypeObject *) PyCell_GET(cell);
6543 if (type == NULL) {
Benjamin Peterson6a42bd62012-09-01 23:04:38 -04006544 PyErr_SetString(PyExc_RuntimeError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006545 "super(): empty __class__ cell");
6546 return -1;
6547 }
6548 if (!PyType_Check(type)) {
Benjamin Peterson6a42bd62012-09-01 23:04:38 -04006549 PyErr_Format(PyExc_RuntimeError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006550 "super(): __class__ is not a type (%s)",
6551 Py_TYPE(type)->tp_name);
6552 return -1;
6553 }
6554 break;
6555 }
6556 }
6557 if (type == NULL) {
Benjamin Peterson6a42bd62012-09-01 23:04:38 -04006558 PyErr_SetString(PyExc_RuntimeError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006559 "super(): __class__ cell not found");
6560 return -1;
6561 }
6562 }
Guido van Rossumcd16bf62007-06-13 18:07:49 +00006563
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006564 if (obj == Py_None)
6565 obj = NULL;
6566 if (obj != NULL) {
6567 obj_type = supercheck(type, obj);
6568 if (obj_type == NULL)
6569 return -1;
6570 Py_INCREF(obj);
6571 }
6572 Py_INCREF(type);
6573 su->type = type;
6574 su->obj = obj;
6575 su->obj_type = obj_type;
6576 return 0;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006577}
6578
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00006579PyDoc_STRVAR(super_doc,
Guido van Rossumcd16bf62007-06-13 18:07:49 +00006580"super() -> same as super(__class__, <first argument>)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00006581"super(type) -> unbound super object\n"
6582"super(type, obj) -> bound super object; requires isinstance(obj, type)\n"
Guido van Rossume705ef12001-08-29 15:47:06 +00006583"super(type, type2) -> bound super object; requires issubclass(type2, type)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00006584"Typical use to call a cooperative superclass method:\n"
6585"class C(B):\n"
6586" def meth(self, arg):\n"
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006587" super().meth(arg)\n"
Guido van Rossumcd16bf62007-06-13 18:07:49 +00006588"This works for class methods too:\n"
6589"class C(B):\n"
6590" @classmethod\n"
6591" def cmeth(cls, arg):\n"
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006592" super().cmeth(arg)\n");
Guido van Rossum705f0f52001-08-24 16:47:00 +00006593
Guido van Rossum048eb752001-10-02 21:24:57 +00006594static int
6595super_traverse(PyObject *self, visitproc visit, void *arg)
6596{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006597 superobject *su = (superobject *)self;
Guido van Rossum048eb752001-10-02 21:24:57 +00006598
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006599 Py_VISIT(su->obj);
6600 Py_VISIT(su->type);
6601 Py_VISIT(su->obj_type);
Guido van Rossum048eb752001-10-02 21:24:57 +00006602
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006603 return 0;
Guido van Rossum048eb752001-10-02 21:24:57 +00006604}
6605
Guido van Rossum705f0f52001-08-24 16:47:00 +00006606PyTypeObject PySuper_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006607 PyVarObject_HEAD_INIT(&PyType_Type, 0)
6608 "super", /* tp_name */
6609 sizeof(superobject), /* tp_basicsize */
6610 0, /* tp_itemsize */
6611 /* methods */
6612 super_dealloc, /* tp_dealloc */
6613 0, /* tp_print */
6614 0, /* tp_getattr */
6615 0, /* tp_setattr */
6616 0, /* tp_reserved */
6617 super_repr, /* tp_repr */
6618 0, /* tp_as_number */
6619 0, /* tp_as_sequence */
6620 0, /* tp_as_mapping */
6621 0, /* tp_hash */
6622 0, /* tp_call */
6623 0, /* tp_str */
6624 super_getattro, /* tp_getattro */
6625 0, /* tp_setattro */
6626 0, /* tp_as_buffer */
6627 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
6628 Py_TPFLAGS_BASETYPE, /* tp_flags */
6629 super_doc, /* tp_doc */
6630 super_traverse, /* tp_traverse */
6631 0, /* tp_clear */
6632 0, /* tp_richcompare */
6633 0, /* tp_weaklistoffset */
6634 0, /* tp_iter */
6635 0, /* tp_iternext */
6636 0, /* tp_methods */
6637 super_members, /* tp_members */
6638 0, /* tp_getset */
6639 0, /* tp_base */
6640 0, /* tp_dict */
6641 super_descr_get, /* tp_descr_get */
6642 0, /* tp_descr_set */
6643 0, /* tp_dictoffset */
6644 super_init, /* tp_init */
6645 PyType_GenericAlloc, /* tp_alloc */
6646 PyType_GenericNew, /* tp_new */
6647 PyObject_GC_Del, /* tp_free */
Guido van Rossum705f0f52001-08-24 16:47:00 +00006648};