blob: 5d625a21eac35471306f38d72e4d666da55c35eb [file] [log] [blame]
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001/* Type object implementation */
2
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003#include "Python.h"
Guido van Rossumcd16bf62007-06-13 18:07:49 +00004#include "frameobject.h"
Tim Peters6d6c1a32001-08-02 04:15:00 +00005#include "structmember.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00006
Guido van Rossum9923ffe2002-06-04 19:52:53 +00007#include <ctype.h>
8
Christian Heimesa62da1d2008-01-12 19:39:10 +00009
10/* Support type attribute cache */
11
12/* The cache can keep references to the names alive for longer than
13 they normally would. This is why the maximum size is limited to
14 MCACHE_MAX_ATTR_SIZE, since it might be a problem if very large
15 strings are used as attribute names. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000016#define MCACHE_MAX_ATTR_SIZE 100
Benjamin Peterson7d95e402012-04-23 11:24:50 -040017#define MCACHE_SIZE_EXP 9
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000018#define MCACHE_HASH(version, name_hash) \
19 (((unsigned int)(version) * (unsigned int)(name_hash)) \
20 >> (8*sizeof(unsigned int) - MCACHE_SIZE_EXP))
Christian Heimesa62da1d2008-01-12 19:39:10 +000021#define MCACHE_HASH_METHOD(type, name) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000022 MCACHE_HASH((type)->tp_version_tag, \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020023 ((PyASCIIObject *)(name))->hash)
Christian Heimesa62da1d2008-01-12 19:39:10 +000024#define MCACHE_CACHEABLE_NAME(name) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000025 PyUnicode_CheckExact(name) && \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020026 PyUnicode_READY(name) != -1 && \
27 PyUnicode_GET_LENGTH(name) <= MCACHE_MAX_ATTR_SIZE
Christian Heimesa62da1d2008-01-12 19:39:10 +000028
29struct method_cache_entry {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000030 unsigned int version;
31 PyObject *name; /* reference to exactly a str or None */
32 PyObject *value; /* borrowed */
Christian Heimesa62da1d2008-01-12 19:39:10 +000033};
34
35static struct method_cache_entry method_cache[1 << MCACHE_SIZE_EXP];
36static unsigned int next_version_tag = 0;
Christian Heimes26855632008-01-27 23:50:43 +000037
Martin v. Löwisbd928fe2011-10-14 10:20:37 +020038_Py_IDENTIFIER(__class__);
Victor Stinner3c1e4812012-03-26 22:10:51 +020039_Py_IDENTIFIER(__dict__);
40_Py_IDENTIFIER(__doc__);
41_Py_IDENTIFIER(__getitem__);
42_Py_IDENTIFIER(__getattribute__);
43_Py_IDENTIFIER(__hash__);
44_Py_IDENTIFIER(__module__);
45_Py_IDENTIFIER(__name__);
46_Py_IDENTIFIER(__new__);
47
48static PyObject *
49_PyType_LookupId(PyTypeObject *type, struct _Py_Identifier *name);
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +020050
Martin v. Löwis9c564092012-06-23 23:20:45 +020051static PyObject *
52slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
53
Christian Heimes26855632008-01-27 23:50:43 +000054unsigned int
55PyType_ClearCache(void)
56{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000057 Py_ssize_t i;
58 unsigned int cur_version_tag = next_version_tag - 1;
59
60 for (i = 0; i < (1 << MCACHE_SIZE_EXP); i++) {
61 method_cache[i].version = 0;
62 Py_CLEAR(method_cache[i].name);
63 method_cache[i].value = NULL;
64 }
65 next_version_tag = 0;
66 /* mark all version tags as invalid */
67 PyType_Modified(&PyBaseObject_Type);
68 return cur_version_tag;
Christian Heimes26855632008-01-27 23:50:43 +000069}
Christian Heimesa62da1d2008-01-12 19:39:10 +000070
Georg Brandlf08a9dd2008-06-10 16:57:31 +000071void
72PyType_Modified(PyTypeObject *type)
Christian Heimesa62da1d2008-01-12 19:39:10 +000073{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000074 /* Invalidate any cached data for the specified type and all
75 subclasses. This function is called after the base
76 classes, mro, or attributes of the type are altered.
Christian Heimesa62da1d2008-01-12 19:39:10 +000077
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000078 Invariants:
Christian Heimesa62da1d2008-01-12 19:39:10 +000079
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000080 - Py_TPFLAGS_VALID_VERSION_TAG is never set if
81 Py_TPFLAGS_HAVE_VERSION_TAG is not set (e.g. on type
82 objects coming from non-recompiled extension modules)
Christian Heimesa62da1d2008-01-12 19:39:10 +000083
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000084 - before Py_TPFLAGS_VALID_VERSION_TAG can be set on a type,
85 it must first be set on all super types.
Christian Heimesa62da1d2008-01-12 19:39:10 +000086
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000087 This function clears the Py_TPFLAGS_VALID_VERSION_TAG of a
88 type (so it must first clear it on all subclasses). The
89 tp_version_tag value is meaningless unless this flag is set.
90 We don't assign new version tags eagerly, but only as
91 needed.
92 */
93 PyObject *raw, *ref;
94 Py_ssize_t i, n;
Christian Heimesa62da1d2008-01-12 19:39:10 +000095
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000096 if (!PyType_HasFeature(type, Py_TPFLAGS_VALID_VERSION_TAG))
97 return;
Christian Heimesa62da1d2008-01-12 19:39:10 +000098
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000099 raw = type->tp_subclasses;
100 if (raw != NULL) {
101 n = PyList_GET_SIZE(raw);
102 for (i = 0; i < n; i++) {
103 ref = PyList_GET_ITEM(raw, i);
104 ref = PyWeakref_GET_OBJECT(ref);
105 if (ref != Py_None) {
106 PyType_Modified((PyTypeObject *)ref);
107 }
108 }
109 }
110 type->tp_flags &= ~Py_TPFLAGS_VALID_VERSION_TAG;
Christian Heimesa62da1d2008-01-12 19:39:10 +0000111}
112
113static void
114type_mro_modified(PyTypeObject *type, PyObject *bases) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000115 /*
Florent Xiclunaaa6c1d22011-12-12 18:54:29 +0100116 Check that all base classes or elements of the MRO of type are
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000117 able to be cached. This function is called after the base
118 classes or mro of the type are altered.
Christian Heimesa62da1d2008-01-12 19:39:10 +0000119
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000120 Unset HAVE_VERSION_TAG and VALID_VERSION_TAG if the type
Florent Xiclunaaa6c1d22011-12-12 18:54:29 +0100121 has a custom MRO that includes a type which is not officially
122 super type.
Christian Heimesa62da1d2008-01-12 19:39:10 +0000123
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000124 Called from mro_internal, which will subsequently be called on
125 each subclass when their mro is recursively updated.
126 */
127 Py_ssize_t i, n;
128 int clear = 0;
Christian Heimesa62da1d2008-01-12 19:39:10 +0000129
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000130 if (!PyType_HasFeature(type, Py_TPFLAGS_HAVE_VERSION_TAG))
131 return;
Christian Heimesa62da1d2008-01-12 19:39:10 +0000132
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000133 n = PyTuple_GET_SIZE(bases);
134 for (i = 0; i < n; i++) {
135 PyObject *b = PyTuple_GET_ITEM(bases, i);
136 PyTypeObject *cls;
Christian Heimesa62da1d2008-01-12 19:39:10 +0000137
Florent Xiclunaaa6c1d22011-12-12 18:54:29 +0100138 assert(PyType_Check(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000139 cls = (PyTypeObject *)b;
Christian Heimesa62da1d2008-01-12 19:39:10 +0000140
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000141 if (!PyType_HasFeature(cls, Py_TPFLAGS_HAVE_VERSION_TAG) ||
142 !PyType_IsSubtype(type, cls)) {
143 clear = 1;
144 break;
145 }
146 }
Christian Heimesa62da1d2008-01-12 19:39:10 +0000147
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000148 if (clear)
149 type->tp_flags &= ~(Py_TPFLAGS_HAVE_VERSION_TAG|
150 Py_TPFLAGS_VALID_VERSION_TAG);
Christian Heimesa62da1d2008-01-12 19:39:10 +0000151}
152
153static int
154assign_version_tag(PyTypeObject *type)
155{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000156 /* Ensure that the tp_version_tag is valid and set
157 Py_TPFLAGS_VALID_VERSION_TAG. To respect the invariant, this
158 must first be done on all super classes. Return 0 if this
159 cannot be done, 1 if Py_TPFLAGS_VALID_VERSION_TAG.
160 */
161 Py_ssize_t i, n;
162 PyObject *bases;
Christian Heimesa62da1d2008-01-12 19:39:10 +0000163
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000164 if (PyType_HasFeature(type, Py_TPFLAGS_VALID_VERSION_TAG))
165 return 1;
166 if (!PyType_HasFeature(type, Py_TPFLAGS_HAVE_VERSION_TAG))
167 return 0;
168 if (!PyType_HasFeature(type, Py_TPFLAGS_READY))
169 return 0;
Christian Heimesa62da1d2008-01-12 19:39:10 +0000170
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000171 type->tp_version_tag = next_version_tag++;
172 /* for stress-testing: next_version_tag &= 0xFF; */
Christian Heimesa62da1d2008-01-12 19:39:10 +0000173
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000174 if (type->tp_version_tag == 0) {
175 /* wrap-around or just starting Python - clear the whole
176 cache by filling names with references to Py_None.
177 Values are also set to NULL for added protection, as they
178 are borrowed reference */
179 for (i = 0; i < (1 << MCACHE_SIZE_EXP); i++) {
180 method_cache[i].value = NULL;
181 Py_XDECREF(method_cache[i].name);
182 method_cache[i].name = Py_None;
183 Py_INCREF(Py_None);
184 }
185 /* mark all version tags as invalid */
186 PyType_Modified(&PyBaseObject_Type);
187 return 1;
188 }
189 bases = type->tp_bases;
190 n = PyTuple_GET_SIZE(bases);
191 for (i = 0; i < n; i++) {
192 PyObject *b = PyTuple_GET_ITEM(bases, i);
193 assert(PyType_Check(b));
194 if (!assign_version_tag((PyTypeObject *)b))
195 return 0;
196 }
197 type->tp_flags |= Py_TPFLAGS_VALID_VERSION_TAG;
198 return 1;
Christian Heimesa62da1d2008-01-12 19:39:10 +0000199}
200
201
Guido van Rossum6f799372001-09-20 20:46:19 +0000202static PyMemberDef type_members[] = {
Benjamin Peterson0e102062010-08-25 23:13:17 +0000203 {"__basicsize__", T_PYSSIZET, offsetof(PyTypeObject,tp_basicsize),READONLY},
204 {"__itemsize__", T_PYSSIZET, offsetof(PyTypeObject, tp_itemsize), READONLY},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000205 {"__flags__", T_LONG, offsetof(PyTypeObject, tp_flags), READONLY},
206 {"__weakrefoffset__", T_LONG,
207 offsetof(PyTypeObject, tp_weaklistoffset), READONLY},
208 {"__base__", T_OBJECT, offsetof(PyTypeObject, tp_base), READONLY},
209 {"__dictoffset__", T_LONG,
210 offsetof(PyTypeObject, tp_dictoffset), READONLY},
211 {"__mro__", T_OBJECT, offsetof(PyTypeObject, tp_mro), READONLY},
212 {0}
Tim Peters6d6c1a32001-08-02 04:15:00 +0000213};
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000214
Benjamin Petersond9f23d22011-08-17 11:54:03 -0500215static int
216check_set_special_type_attr(PyTypeObject *type, PyObject *value, const char *name)
217{
218 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
219 PyErr_Format(PyExc_TypeError,
220 "can't set %s.%s", type->tp_name, name);
221 return 0;
222 }
223 if (!value) {
224 PyErr_Format(PyExc_TypeError,
225 "can't delete %s.%s", type->tp_name, name);
226 return 0;
227 }
228 return 1;
229}
230
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000231static PyObject *
Guido van Rossumc3542212001-08-16 09:18:56 +0000232type_name(PyTypeObject *type, void *context)
233{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000234 const char *s;
Guido van Rossumc3542212001-08-16 09:18:56 +0000235
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000236 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
237 PyHeapTypeObject* et = (PyHeapTypeObject*)type;
Tim Petersea7f75d2002-12-07 21:39:16 +0000238
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000239 Py_INCREF(et->ht_name);
240 return et->ht_name;
241 }
242 else {
243 s = strrchr(type->tp_name, '.');
244 if (s == NULL)
245 s = type->tp_name;
246 else
247 s++;
248 return PyUnicode_FromString(s);
249 }
Guido van Rossumc3542212001-08-16 09:18:56 +0000250}
251
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100252static PyObject *
253type_qualname(PyTypeObject *type, void *context)
254{
255 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
256 PyHeapTypeObject* et = (PyHeapTypeObject*)type;
257 Py_INCREF(et->ht_qualname);
258 return et->ht_qualname;
259 }
260 else {
261 return type_name(type, context);
262 }
263}
264
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000265static int
266type_set_name(PyTypeObject *type, PyObject *value, void *context)
267{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000268 PyHeapTypeObject* et;
269 char *tp_name;
270 PyObject *tmp;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000271
Benjamin Petersond9f23d22011-08-17 11:54:03 -0500272 if (!check_set_special_type_attr(type, value, "__name__"))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000273 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000274 if (!PyUnicode_Check(value)) {
275 PyErr_Format(PyExc_TypeError,
276 "can only assign string to %s.__name__, not '%s'",
277 type->tp_name, Py_TYPE(value)->tp_name);
278 return -1;
279 }
Guido van Rossume845c0f2007-11-02 23:07:07 +0000280
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000281 /* Check absence of null characters */
282 tmp = PyUnicode_FromStringAndSize("\0", 1);
283 if (tmp == NULL)
284 return -1;
285 if (PyUnicode_Contains(value, tmp) != 0) {
286 Py_DECREF(tmp);
287 PyErr_Format(PyExc_ValueError,
288 "__name__ must not contain null bytes");
289 return -1;
290 }
291 Py_DECREF(tmp);
Guido van Rossume845c0f2007-11-02 23:07:07 +0000292
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000293 tp_name = _PyUnicode_AsString(value);
294 if (tp_name == NULL)
295 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000296
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000297 et = (PyHeapTypeObject*)type;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000298
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000299 Py_INCREF(value);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000300
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000301 Py_DECREF(et->ht_name);
302 et->ht_name = value;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000303
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000304 type->tp_name = tp_name;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000305
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000306 return 0;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000307}
308
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100309static int
310type_set_qualname(PyTypeObject *type, PyObject *value, void *context)
311{
312 PyHeapTypeObject* et;
313
314 if (!PyUnicode_Check(value)) {
315 PyErr_Format(PyExc_TypeError,
316 "can only assign string to %s.__qualname__, not '%s'",
317 type->tp_name, Py_TYPE(value)->tp_name);
318 return -1;
319 }
320
321 et = (PyHeapTypeObject*)type;
322 Py_INCREF(value);
323 Py_DECREF(et->ht_qualname);
324 et->ht_qualname = value;
325 return 0;
326}
327
Guido van Rossumc3542212001-08-16 09:18:56 +0000328static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000329type_module(PyTypeObject *type, void *context)
Guido van Rossum29ca26e1995-01-07 11:58:15 +0000330{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000331 PyObject *mod;
332 char *s;
Guido van Rossumc3542212001-08-16 09:18:56 +0000333
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000334 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
Victor Stinner3c1e4812012-03-26 22:10:51 +0200335 mod = _PyDict_GetItemId(type->tp_dict, &PyId___module__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000336 if (!mod) {
337 PyErr_Format(PyExc_AttributeError, "__module__");
338 return 0;
339 }
340 Py_XINCREF(mod);
341 return mod;
342 }
343 else {
344 s = strrchr(type->tp_name, '.');
345 if (s != NULL)
346 return PyUnicode_FromStringAndSize(
347 type->tp_name, (Py_ssize_t)(s - type->tp_name));
348 return PyUnicode_FromString("builtins");
349 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000350}
351
Guido van Rossum3926a632001-09-25 16:25:58 +0000352static int
353type_set_module(PyTypeObject *type, PyObject *value, void *context)
354{
Benjamin Petersond9f23d22011-08-17 11:54:03 -0500355 if (!check_set_special_type_attr(type, value, "__module__"))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000356 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000357
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000358 PyType_Modified(type);
Christian Heimesa62da1d2008-01-12 19:39:10 +0000359
Victor Stinner3c1e4812012-03-26 22:10:51 +0200360 return _PyDict_SetItemId(type->tp_dict, &PyId___module__, value);
Guido van Rossum3926a632001-09-25 16:25:58 +0000361}
362
Tim Peters6d6c1a32001-08-02 04:15:00 +0000363static PyObject *
Christian Heimes9e7f1d22008-02-28 12:27:11 +0000364type_abstractmethods(PyTypeObject *type, void *context)
365{
Benjamin Petersonaec5fd12010-10-02 00:03:31 +0000366 PyObject *mod = NULL;
Benjamin Peterson84060b82010-10-03 02:13:39 +0000367 /* type itself has an __abstractmethods__ descriptor (this). Don't return
368 that. */
Benjamin Petersonaec5fd12010-10-02 00:03:31 +0000369 if (type != &PyType_Type)
370 mod = PyDict_GetItemString(type->tp_dict, "__abstractmethods__");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000371 if (!mod) {
Benjamin Peterson23b628e2011-01-12 18:56:07 +0000372 PyErr_SetString(PyExc_AttributeError, "__abstractmethods__");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000373 return NULL;
374 }
375 Py_XINCREF(mod);
376 return mod;
Christian Heimes9e7f1d22008-02-28 12:27:11 +0000377}
378
379static int
380type_set_abstractmethods(PyTypeObject *type, PyObject *value, void *context)
381{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000382 /* __abstractmethods__ should only be set once on a type, in
383 abc.ABCMeta.__new__, so this function doesn't do anything
384 special to update subclasses.
385 */
Antoine Pitrou6f430e42012-08-15 23:18:25 +0200386 int abstract, res;
Benjamin Peterson477ba912011-01-12 15:34:01 +0000387 if (value != NULL) {
Antoine Pitrou6f430e42012-08-15 23:18:25 +0200388 abstract = PyObject_IsTrue(value);
389 if (abstract < 0)
390 return -1;
Benjamin Peterson477ba912011-01-12 15:34:01 +0000391 res = PyDict_SetItemString(type->tp_dict, "__abstractmethods__", value);
392 }
393 else {
Antoine Pitrou6f430e42012-08-15 23:18:25 +0200394 abstract = 0;
Benjamin Peterson477ba912011-01-12 15:34:01 +0000395 res = PyDict_DelItemString(type->tp_dict, "__abstractmethods__");
396 if (res && PyErr_ExceptionMatches(PyExc_KeyError)) {
Benjamin Peterson23b628e2011-01-12 18:56:07 +0000397 PyErr_SetString(PyExc_AttributeError, "__abstractmethods__");
Benjamin Peterson477ba912011-01-12 15:34:01 +0000398 return -1;
399 }
400 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000401 if (res == 0) {
402 PyType_Modified(type);
Antoine Pitrou6f430e42012-08-15 23:18:25 +0200403 if (abstract)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000404 type->tp_flags |= Py_TPFLAGS_IS_ABSTRACT;
Antoine Pitrou6f430e42012-08-15 23:18:25 +0200405 else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000406 type->tp_flags &= ~Py_TPFLAGS_IS_ABSTRACT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000407 }
408 return res;
Christian Heimes9e7f1d22008-02-28 12:27:11 +0000409}
410
411static PyObject *
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000412type_get_bases(PyTypeObject *type, void *context)
413{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000414 Py_INCREF(type->tp_bases);
415 return type->tp_bases;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000416}
417
418static PyTypeObject *best_base(PyObject *);
419static int mro_internal(PyTypeObject *);
420static int compatible_for_assignment(PyTypeObject *, PyTypeObject *, char *);
421static int add_subclass(PyTypeObject*, PyTypeObject*);
422static void remove_subclass(PyTypeObject *, PyTypeObject *);
423static void update_all_slots(PyTypeObject *);
424
Guido van Rossum8d24ee92003-03-24 23:49:49 +0000425typedef int (*update_callback)(PyTypeObject *, void *);
426static int update_subclasses(PyTypeObject *type, PyObject *name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000427 update_callback callback, void *data);
Guido van Rossum8d24ee92003-03-24 23:49:49 +0000428static int recurse_down_subclasses(PyTypeObject *type, PyObject *name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000429 update_callback callback, void *data);
Guido van Rossum8d24ee92003-03-24 23:49:49 +0000430
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000431static int
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000432mro_subclasses(PyTypeObject *type, PyObject* temp)
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000433{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000434 PyTypeObject *subclass;
435 PyObject *ref, *subclasses, *old_mro;
436 Py_ssize_t i, n;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000437
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000438 subclasses = type->tp_subclasses;
439 if (subclasses == NULL)
440 return 0;
441 assert(PyList_Check(subclasses));
442 n = PyList_GET_SIZE(subclasses);
443 for (i = 0; i < n; i++) {
444 ref = PyList_GET_ITEM(subclasses, i);
445 assert(PyWeakref_CheckRef(ref));
446 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
447 assert(subclass != NULL);
448 if ((PyObject *)subclass == Py_None)
449 continue;
450 assert(PyType_Check(subclass));
451 old_mro = subclass->tp_mro;
452 if (mro_internal(subclass) < 0) {
453 subclass->tp_mro = old_mro;
454 return -1;
455 }
456 else {
457 PyObject* tuple;
458 tuple = PyTuple_Pack(2, subclass, old_mro);
459 Py_DECREF(old_mro);
460 if (!tuple)
461 return -1;
462 if (PyList_Append(temp, tuple) < 0)
463 return -1;
464 Py_DECREF(tuple);
465 }
466 if (mro_subclasses(subclass, temp) < 0)
467 return -1;
468 }
469 return 0;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000470}
471
472static int
473type_set_bases(PyTypeObject *type, PyObject *value, void *context)
474{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000475 Py_ssize_t i;
476 int r = 0;
477 PyObject *ob, *temp;
478 PyTypeObject *new_base, *old_base;
479 PyObject *old_bases, *old_mro;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000480
Benjamin Petersond9f23d22011-08-17 11:54:03 -0500481 if (!check_set_special_type_attr(type, value, "__bases__"))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000482 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000483 if (!PyTuple_Check(value)) {
484 PyErr_Format(PyExc_TypeError,
485 "can only assign tuple to %s.__bases__, not %s",
486 type->tp_name, Py_TYPE(value)->tp_name);
487 return -1;
488 }
489 if (PyTuple_GET_SIZE(value) == 0) {
490 PyErr_Format(PyExc_TypeError,
491 "can only assign non-empty tuple to %s.__bases__, not ()",
492 type->tp_name);
493 return -1;
494 }
495 for (i = 0; i < PyTuple_GET_SIZE(value); i++) {
496 ob = PyTuple_GET_ITEM(value, i);
497 if (!PyType_Check(ob)) {
Benjamin Petersonb6af60c2012-04-01 18:49:54 -0400498 PyErr_Format(PyExc_TypeError,
Benjamin Peterson9ee601e2012-04-01 18:51:37 -0400499 "%s.__bases__ must be tuple of classes, not '%s'",
Benjamin Petersonb6af60c2012-04-01 18:49:54 -0400500 type->tp_name, Py_TYPE(ob)->tp_name);
501 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000502 }
Benjamin Peterson3471bb62012-04-01 18:48:40 -0400503 if (PyType_IsSubtype((PyTypeObject*)ob, type)) {
504 PyErr_SetString(PyExc_TypeError,
505 "a __bases__ item causes an inheritance cycle");
506 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000507 }
508 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000509
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000510 new_base = best_base(value);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000511
Benjamin Petersonab3c1c12012-04-01 18:48:02 -0400512 if (!new_base)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000513 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000514
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000515 if (!compatible_for_assignment(type->tp_base, new_base, "__bases__"))
516 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000517
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000518 Py_INCREF(new_base);
519 Py_INCREF(value);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000520
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000521 old_bases = type->tp_bases;
522 old_base = type->tp_base;
523 old_mro = type->tp_mro;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000524
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000525 type->tp_bases = value;
526 type->tp_base = new_base;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000527
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000528 if (mro_internal(type) < 0) {
529 goto bail;
530 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000531
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000532 temp = PyList_New(0);
533 if (!temp)
534 goto bail;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000535
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000536 r = mro_subclasses(type, temp);
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000537
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000538 if (r < 0) {
539 for (i = 0; i < PyList_Size(temp); i++) {
540 PyTypeObject* cls;
541 PyObject* mro;
542 PyArg_UnpackTuple(PyList_GET_ITEM(temp, i),
543 "", 2, 2, &cls, &mro);
544 Py_INCREF(mro);
545 ob = cls->tp_mro;
546 cls->tp_mro = mro;
547 Py_DECREF(ob);
548 }
549 Py_DECREF(temp);
550 goto bail;
551 }
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000552
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000553 Py_DECREF(temp);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000554
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000555 /* any base that was in __bases__ but now isn't, we
556 need to remove |type| from its tp_subclasses.
557 conversely, any class now in __bases__ that wasn't
558 needs to have |type| added to its subclasses. */
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000559
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000560 /* for now, sod that: just remove from all old_bases,
561 add to all new_bases */
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000562
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000563 for (i = PyTuple_GET_SIZE(old_bases) - 1; i >= 0; i--) {
564 ob = PyTuple_GET_ITEM(old_bases, i);
565 if (PyType_Check(ob)) {
566 remove_subclass(
567 (PyTypeObject*)ob, type);
568 }
569 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000570
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000571 for (i = PyTuple_GET_SIZE(value) - 1; i >= 0; i--) {
572 ob = PyTuple_GET_ITEM(value, i);
573 if (PyType_Check(ob)) {
574 if (add_subclass((PyTypeObject*)ob, type) < 0)
575 r = -1;
576 }
577 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000578
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000579 update_all_slots(type);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000580
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000581 Py_DECREF(old_bases);
582 Py_DECREF(old_base);
583 Py_DECREF(old_mro);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000584
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000585 return r;
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000586
587 bail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000588 Py_DECREF(type->tp_bases);
589 Py_DECREF(type->tp_base);
590 if (type->tp_mro != old_mro) {
591 Py_DECREF(type->tp_mro);
592 }
Michael W. Hudsone723e452003-08-07 14:58:10 +0000593
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000594 type->tp_bases = old_bases;
595 type->tp_base = old_base;
596 type->tp_mro = old_mro;
Tim Petersea7f75d2002-12-07 21:39:16 +0000597
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000598 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000599}
600
601static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000602type_dict(PyTypeObject *type, void *context)
603{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000604 if (type->tp_dict == NULL) {
605 Py_INCREF(Py_None);
606 return Py_None;
607 }
608 return PyDictProxy_New(type->tp_dict);
Guido van Rossum29ca26e1995-01-07 11:58:15 +0000609}
610
Tim Peters24008312002-03-17 18:56:20 +0000611static PyObject *
612type_get_doc(PyTypeObject *type, void *context)
613{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000614 PyObject *result;
615 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE) && type->tp_doc != NULL)
616 return PyUnicode_FromString(type->tp_doc);
Victor Stinner3c1e4812012-03-26 22:10:51 +0200617 result = _PyDict_GetItemId(type->tp_dict, &PyId___doc__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000618 if (result == NULL) {
619 result = Py_None;
620 Py_INCREF(result);
621 }
622 else if (Py_TYPE(result)->tp_descr_get) {
623 result = Py_TYPE(result)->tp_descr_get(result, NULL,
624 (PyObject *)type);
625 }
626 else {
627 Py_INCREF(result);
628 }
629 return result;
Tim Peters24008312002-03-17 18:56:20 +0000630}
631
Benjamin Peterson01fc6cd2011-08-17 12:03:47 -0500632static int
633type_set_doc(PyTypeObject *type, PyObject *value, void *context)
634{
635 if (!check_set_special_type_attr(type, value, "__doc__"))
636 return -1;
637 PyType_Modified(type);
Victor Stinner3c1e4812012-03-26 22:10:51 +0200638 return _PyDict_SetItemId(type->tp_dict, &PyId___doc__, value);
Benjamin Peterson01fc6cd2011-08-17 12:03:47 -0500639}
640
Antoine Pitrouec569b72008-08-26 22:40:48 +0000641static PyObject *
642type___instancecheck__(PyObject *type, PyObject *inst)
643{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000644 switch (_PyObject_RealIsInstance(inst, type)) {
645 case -1:
646 return NULL;
647 case 0:
648 Py_RETURN_FALSE;
649 default:
650 Py_RETURN_TRUE;
651 }
Antoine Pitrouec569b72008-08-26 22:40:48 +0000652}
653
654
655static PyObject *
Antoine Pitrouec569b72008-08-26 22:40:48 +0000656type___subclasscheck__(PyObject *type, PyObject *inst)
657{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000658 switch (_PyObject_RealIsSubclass(inst, type)) {
659 case -1:
660 return NULL;
661 case 0:
662 Py_RETURN_FALSE;
663 default:
664 Py_RETURN_TRUE;
665 }
Antoine Pitrouec569b72008-08-26 22:40:48 +0000666}
667
Antoine Pitrouec569b72008-08-26 22:40:48 +0000668
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000669static PyGetSetDef type_getsets[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000670 {"__name__", (getter)type_name, (setter)type_set_name, NULL},
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100671 {"__qualname__", (getter)type_qualname, (setter)type_set_qualname, NULL},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000672 {"__bases__", (getter)type_get_bases, (setter)type_set_bases, NULL},
673 {"__module__", (getter)type_module, (setter)type_set_module, NULL},
674 {"__abstractmethods__", (getter)type_abstractmethods,
675 (setter)type_set_abstractmethods, NULL},
676 {"__dict__", (getter)type_dict, NULL, NULL},
Benjamin Peterson01fc6cd2011-08-17 12:03:47 -0500677 {"__doc__", (getter)type_get_doc, (setter)type_set_doc, NULL},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000678 {0}
Tim Peters6d6c1a32001-08-02 04:15:00 +0000679};
680
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000681static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000682type_repr(PyTypeObject *type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000683{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000684 PyObject *mod, *name, *rtn;
Guido van Rossumc3542212001-08-16 09:18:56 +0000685
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000686 mod = type_module(type, NULL);
687 if (mod == NULL)
688 PyErr_Clear();
689 else if (!PyUnicode_Check(mod)) {
690 Py_DECREF(mod);
691 mod = NULL;
692 }
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100693 name = type_qualname(type, NULL);
Christian Heimesa0e7e412012-09-10 03:00:14 +0200694 if (name == NULL) {
695 Py_XDECREF(mod);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000696 return NULL;
Christian Heimesa0e7e412012-09-10 03:00:14 +0200697 }
Barry Warsaw7ce36942001-08-24 18:34:26 +0000698
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000699 if (mod != NULL && PyUnicode_CompareWithASCIIString(mod, "builtins"))
700 rtn = PyUnicode_FromFormat("<class '%U.%U'>", mod, name);
701 else
702 rtn = PyUnicode_FromFormat("<class '%s'>", type->tp_name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000703
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000704 Py_XDECREF(mod);
705 Py_DECREF(name);
706 return rtn;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000707}
708
Tim Peters6d6c1a32001-08-02 04:15:00 +0000709static PyObject *
710type_call(PyTypeObject *type, PyObject *args, PyObject *kwds)
711{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000712 PyObject *obj;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000713
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000714 if (type->tp_new == NULL) {
715 PyErr_Format(PyExc_TypeError,
716 "cannot create '%.100s' instances",
717 type->tp_name);
718 return NULL;
719 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000720
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000721 obj = type->tp_new(type, args, kwds);
722 if (obj != NULL) {
723 /* Ugly exception: when the call was type(something),
724 don't call tp_init on the result. */
725 if (type == &PyType_Type &&
726 PyTuple_Check(args) && PyTuple_GET_SIZE(args) == 1 &&
727 (kwds == NULL ||
728 (PyDict_Check(kwds) && PyDict_Size(kwds) == 0)))
729 return obj;
730 /* If the returned object is not an instance of type,
731 it won't be initialized. */
732 if (!PyType_IsSubtype(Py_TYPE(obj), type))
733 return obj;
734 type = Py_TYPE(obj);
735 if (type->tp_init != NULL &&
736 type->tp_init(obj, args, kwds) < 0) {
737 Py_DECREF(obj);
738 obj = NULL;
739 }
740 }
741 return obj;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000742}
743
744PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000745PyType_GenericAlloc(PyTypeObject *type, Py_ssize_t nitems)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000746{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000747 PyObject *obj;
748 const size_t size = _PyObject_VAR_SIZE(type, nitems+1);
749 /* note that we need to add one, for the sentinel */
Tim Peters406fe3b2001-10-06 19:04:01 +0000750
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000751 if (PyType_IS_GC(type))
752 obj = _PyObject_GC_Malloc(size);
753 else
754 obj = (PyObject *)PyObject_MALLOC(size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000755
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000756 if (obj == NULL)
757 return PyErr_NoMemory();
Tim Peters406fe3b2001-10-06 19:04:01 +0000758
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000759 memset(obj, '\0', size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000760
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000761 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
762 Py_INCREF(type);
Tim Peters406fe3b2001-10-06 19:04:01 +0000763
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000764 if (type->tp_itemsize == 0)
765 PyObject_INIT(obj, type);
766 else
767 (void) PyObject_INIT_VAR((PyVarObject *)obj, type, nitems);
Tim Peters406fe3b2001-10-06 19:04:01 +0000768
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000769 if (PyType_IS_GC(type))
770 _PyObject_GC_TRACK(obj);
771 return obj;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000772}
773
774PyObject *
775PyType_GenericNew(PyTypeObject *type, PyObject *args, PyObject *kwds)
776{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000777 return type->tp_alloc(type, 0);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000778}
779
Guido van Rossum9475a232001-10-05 20:51:39 +0000780/* Helpers for subtyping */
781
782static int
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000783traverse_slots(PyTypeObject *type, PyObject *self, visitproc visit, void *arg)
784{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000785 Py_ssize_t i, n;
786 PyMemberDef *mp;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000787
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000788 n = Py_SIZE(type);
789 mp = PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type);
790 for (i = 0; i < n; i++, mp++) {
791 if (mp->type == T_OBJECT_EX) {
792 char *addr = (char *)self + mp->offset;
793 PyObject *obj = *(PyObject **)addr;
794 if (obj != NULL) {
795 int err = visit(obj, arg);
796 if (err)
797 return err;
798 }
799 }
800 }
801 return 0;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000802}
803
804static int
Guido van Rossum9475a232001-10-05 20:51:39 +0000805subtype_traverse(PyObject *self, visitproc visit, void *arg)
806{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000807 PyTypeObject *type, *base;
808 traverseproc basetraverse;
Guido van Rossum9475a232001-10-05 20:51:39 +0000809
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000810 /* Find the nearest base with a different tp_traverse,
811 and traverse slots while we're at it */
812 type = Py_TYPE(self);
813 base = type;
814 while ((basetraverse = base->tp_traverse) == subtype_traverse) {
815 if (Py_SIZE(base)) {
816 int err = traverse_slots(base, self, visit, arg);
817 if (err)
818 return err;
819 }
820 base = base->tp_base;
821 assert(base);
822 }
Guido van Rossum9475a232001-10-05 20:51:39 +0000823
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000824 if (type->tp_dictoffset != base->tp_dictoffset) {
825 PyObject **dictptr = _PyObject_GetDictPtr(self);
826 if (dictptr && *dictptr)
827 Py_VISIT(*dictptr);
828 }
Guido van Rossum9475a232001-10-05 20:51:39 +0000829
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000830 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
831 /* For a heaptype, the instances count as references
832 to the type. Traverse the type so the collector
833 can find cycles involving this link. */
834 Py_VISIT(type);
Guido van Rossuma3862092002-06-10 15:24:42 +0000835
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000836 if (basetraverse)
837 return basetraverse(self, visit, arg);
838 return 0;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000839}
840
841static void
842clear_slots(PyTypeObject *type, PyObject *self)
843{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000844 Py_ssize_t i, n;
845 PyMemberDef *mp;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000846
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000847 n = Py_SIZE(type);
848 mp = PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type);
849 for (i = 0; i < n; i++, mp++) {
850 if (mp->type == T_OBJECT_EX && !(mp->flags & READONLY)) {
851 char *addr = (char *)self + mp->offset;
852 PyObject *obj = *(PyObject **)addr;
853 if (obj != NULL) {
854 *(PyObject **)addr = NULL;
855 Py_DECREF(obj);
856 }
857 }
858 }
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000859}
860
861static int
862subtype_clear(PyObject *self)
863{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000864 PyTypeObject *type, *base;
865 inquiry baseclear;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000866
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000867 /* Find the nearest base with a different tp_clear
868 and clear slots while we're at it */
869 type = Py_TYPE(self);
870 base = type;
871 while ((baseclear = base->tp_clear) == subtype_clear) {
872 if (Py_SIZE(base))
873 clear_slots(base, self);
874 base = base->tp_base;
875 assert(base);
876 }
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000877
Benjamin Peterson52c42432012-03-07 18:41:11 -0600878 /* Clear the instance dict (if any), to break cycles involving only
879 __dict__ slots (as in the case 'self.__dict__ is self'). */
880 if (type->tp_dictoffset != base->tp_dictoffset) {
881 PyObject **dictptr = _PyObject_GetDictPtr(self);
882 if (dictptr && *dictptr)
883 Py_CLEAR(*dictptr);
884 }
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000885
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000886 if (baseclear)
887 return baseclear(self);
888 return 0;
Guido van Rossum9475a232001-10-05 20:51:39 +0000889}
Tim Peters6d6c1a32001-08-02 04:15:00 +0000890
891static void
892subtype_dealloc(PyObject *self)
893{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000894 PyTypeObject *type, *base;
895 destructor basedealloc;
Antoine Pitrou56cd62c2012-09-06 00:59:49 +0200896 PyThreadState *tstate = PyThreadState_GET();
Tim Peters6d6c1a32001-08-02 04:15:00 +0000897
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000898 /* Extract the type; we expect it to be a heap type */
899 type = Py_TYPE(self);
900 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000901
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000902 /* Test whether the type has GC exactly once */
Guido van Rossum22b13872002-08-06 21:41:44 +0000903
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000904 if (!PyType_IS_GC(type)) {
905 /* It's really rare to find a dynamic type that doesn't have
906 GC; it can only happen when deriving from 'object' and not
907 adding any slots or instance variables. This allows
908 certain simplifications: there's no need to call
909 clear_slots(), or DECREF the dict, or clear weakrefs. */
Guido van Rossum22b13872002-08-06 21:41:44 +0000910
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000911 /* Maybe call finalizer; exit early if resurrected */
912 if (type->tp_del) {
913 type->tp_del(self);
914 if (self->ob_refcnt > 0)
915 return;
916 }
Guido van Rossum22b13872002-08-06 21:41:44 +0000917
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000918 /* Find the nearest base with a different tp_dealloc */
919 base = type;
920 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
921 assert(Py_SIZE(base) == 0);
922 base = base->tp_base;
923 assert(base);
924 }
Guido van Rossum22b13872002-08-06 21:41:44 +0000925
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000926 /* Extract the type again; tp_del may have changed it */
927 type = Py_TYPE(self);
Benjamin Peterson193152c2009-04-25 01:08:45 +0000928
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000929 /* Call the base tp_dealloc() */
930 assert(basedealloc);
931 basedealloc(self);
Guido van Rossum22b13872002-08-06 21:41:44 +0000932
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000933 /* Can't reference self beyond this point */
934 Py_DECREF(type);
Guido van Rossum22b13872002-08-06 21:41:44 +0000935
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000936 /* Done */
937 return;
938 }
Guido van Rossum22b13872002-08-06 21:41:44 +0000939
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000940 /* We get here only if the type has GC */
Guido van Rossum22b13872002-08-06 21:41:44 +0000941
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000942 /* UnTrack and re-Track around the trashcan macro, alas */
943 /* See explanation at end of function for full disclosure */
944 PyObject_GC_UnTrack(self);
945 ++_PyTrash_delete_nesting;
Antoine Pitrou56cd62c2012-09-06 00:59:49 +0200946 ++ tstate->trash_delete_nesting;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000947 Py_TRASHCAN_SAFE_BEGIN(self);
948 --_PyTrash_delete_nesting;
Antoine Pitrou56cd62c2012-09-06 00:59:49 +0200949 -- tstate->trash_delete_nesting;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000950 /* DO NOT restore GC tracking at this point. weakref callbacks
951 * (if any, and whether directly here or indirectly in something we
952 * call) may trigger GC, and if self is tracked at that point, it
953 * will look like trash to GC and GC will try to delete self again.
954 */
Guido van Rossum22b13872002-08-06 21:41:44 +0000955
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000956 /* Find the nearest base with a different tp_dealloc */
957 base = type;
Brett Cannonb94767f2011-02-22 20:15:44 +0000958 while ((/*basedealloc =*/ base->tp_dealloc) == subtype_dealloc) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000959 base = base->tp_base;
960 assert(base);
961 }
Guido van Rossum14227b42001-12-06 02:35:58 +0000962
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000963 /* If we added a weaklist, we clear it. Do this *before* calling
964 the finalizer (__del__), clearing slots, or clearing the instance
965 dict. */
Guido van Rossum59195fd2003-06-13 20:54:40 +0000966
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000967 if (type->tp_weaklistoffset && !base->tp_weaklistoffset)
968 PyObject_ClearWeakRefs(self);
Guido van Rossum1987c662003-05-29 14:29:23 +0000969
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000970 /* Maybe call finalizer; exit early if resurrected */
971 if (type->tp_del) {
972 _PyObject_GC_TRACK(self);
973 type->tp_del(self);
974 if (self->ob_refcnt > 0)
975 goto endlabel; /* resurrected */
976 else
977 _PyObject_GC_UNTRACK(self);
978 /* New weakrefs could be created during the finalizer call.
979 If this occurs, clear them out without calling their
980 finalizers since they might rely on part of the object
981 being finalized that has already been destroyed. */
982 if (type->tp_weaklistoffset && !base->tp_weaklistoffset) {
983 /* Modeled after GET_WEAKREFS_LISTPTR() */
984 PyWeakReference **list = (PyWeakReference **) \
985 PyObject_GET_WEAKREFS_LISTPTR(self);
986 while (*list)
987 _PyWeakref_ClearRef(*list);
988 }
989 }
Guido van Rossum1987c662003-05-29 14:29:23 +0000990
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000991 /* Clear slots up to the nearest base with a different tp_dealloc */
992 base = type;
993 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
994 if (Py_SIZE(base))
995 clear_slots(base, self);
996 base = base->tp_base;
997 assert(base);
998 }
Guido van Rossum59195fd2003-06-13 20:54:40 +0000999
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001000 /* If we added a dict, DECREF it */
1001 if (type->tp_dictoffset && !base->tp_dictoffset) {
1002 PyObject **dictptr = _PyObject_GetDictPtr(self);
1003 if (dictptr != NULL) {
1004 PyObject *dict = *dictptr;
1005 if (dict != NULL) {
1006 Py_DECREF(dict);
1007 *dictptr = NULL;
1008 }
1009 }
1010 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001011
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001012 /* Extract the type again; tp_del may have changed it */
1013 type = Py_TYPE(self);
Benjamin Peterson193152c2009-04-25 01:08:45 +00001014
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001015 /* Call the base tp_dealloc(); first retrack self if
1016 * basedealloc knows about gc.
1017 */
1018 if (PyType_IS_GC(base))
1019 _PyObject_GC_TRACK(self);
1020 assert(basedealloc);
1021 basedealloc(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001022
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001023 /* Can't reference self beyond this point */
1024 Py_DECREF(type);
Guido van Rossum22b13872002-08-06 21:41:44 +00001025
Guido van Rossum0906e072002-08-07 20:42:09 +00001026 endlabel:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001027 ++_PyTrash_delete_nesting;
Antoine Pitrou56cd62c2012-09-06 00:59:49 +02001028 ++ tstate->trash_delete_nesting;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001029 Py_TRASHCAN_SAFE_END(self);
1030 --_PyTrash_delete_nesting;
Antoine Pitrou56cd62c2012-09-06 00:59:49 +02001031 -- tstate->trash_delete_nesting;
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001032
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001033 /* Explanation of the weirdness around the trashcan macros:
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001034
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001035 Q. What do the trashcan macros do?
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001036
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001037 A. Read the comment titled "Trashcan mechanism" in object.h.
1038 For one, this explains why there must be a call to GC-untrack
1039 before the trashcan begin macro. Without understanding the
1040 trashcan code, the answers to the following questions don't make
1041 sense.
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001042
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001043 Q. Why do we GC-untrack before the trashcan and then immediately
1044 GC-track again afterward?
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001045
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001046 A. In the case that the base class is GC-aware, the base class
1047 probably GC-untracks the object. If it does that using the
1048 UNTRACK macro, this will crash when the object is already
1049 untracked. Because we don't know what the base class does, the
1050 only safe thing is to make sure the object is tracked when we
1051 call the base class dealloc. But... The trashcan begin macro
1052 requires that the object is *untracked* before it is called. So
1053 the dance becomes:
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001054
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001055 GC untrack
1056 trashcan begin
1057 GC track
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001058
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001059 Q. Why did the last question say "immediately GC-track again"?
1060 It's nowhere near immediately.
Tim Petersf7f9e992003-11-13 21:59:32 +00001061
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001062 A. Because the code *used* to re-track immediately. Bad Idea.
1063 self has a refcount of 0, and if gc ever gets its hands on it
1064 (which can happen if any weakref callback gets invoked), it
1065 looks like trash to gc too, and gc also tries to delete self
Ezio Melotti13925002011-03-16 11:05:33 +02001066 then. But we're already deleting self. Double deallocation is
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001067 a subtle disaster.
Tim Petersf7f9e992003-11-13 21:59:32 +00001068
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001069 Q. Why the bizarre (net-zero) manipulation of
1070 _PyTrash_delete_nesting around the trashcan macros?
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001071
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001072 A. Some base classes (e.g. list) also use the trashcan mechanism.
1073 The following scenario used to be possible:
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001074
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001075 - suppose the trashcan level is one below the trashcan limit
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001076
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001077 - subtype_dealloc() is called
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001078
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001079 - the trashcan limit is not yet reached, so the trashcan level
1080 is incremented and the code between trashcan begin and end is
1081 executed
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001082
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001083 - this destroys much of the object's contents, including its
1084 slots and __dict__
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001085
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001086 - basedealloc() is called; this is really list_dealloc(), or
1087 some other type which also uses the trashcan macros
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001088
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001089 - the trashcan limit is now reached, so the object is put on the
1090 trashcan's to-be-deleted-later list
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001091
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001092 - basedealloc() returns
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001093
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001094 - subtype_dealloc() decrefs the object's type
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001095
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001096 - subtype_dealloc() returns
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001097
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001098 - later, the trashcan code starts deleting the objects from its
1099 to-be-deleted-later list
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001100
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001101 - subtype_dealloc() is called *AGAIN* for the same object
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001102
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001103 - at the very least (if the destroyed slots and __dict__ don't
1104 cause problems) the object's type gets decref'ed a second
1105 time, which is *BAD*!!!
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001106
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001107 The remedy is to make sure that if the code between trashcan
1108 begin and end in subtype_dealloc() is called, the code between
1109 trashcan begin and end in basedealloc() will also be called.
1110 This is done by decrementing the level after passing into the
1111 trashcan block, and incrementing it just before leaving the
1112 block.
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001113
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001114 But now it's possible that a chain of objects consisting solely
1115 of objects whose deallocator is subtype_dealloc() will defeat
1116 the trashcan mechanism completely: the decremented level means
1117 that the effective level never reaches the limit. Therefore, we
1118 *increment* the level *before* entering the trashcan block, and
1119 matchingly decrement it after leaving. This means the trashcan
1120 code will trigger a little early, but that's no big deal.
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001121
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001122 Q. Are there any live examples of code in need of all this
1123 complexity?
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001124
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001125 A. Yes. See SF bug 668433 for code that crashed (when Python was
1126 compiled in debug mode) before the trashcan level manipulations
1127 were added. For more discussion, see SF patches 581742, 575073
1128 and bug 574207.
1129 */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001130}
1131
Jeremy Hylton938ace62002-07-17 16:30:39 +00001132static PyTypeObject *solid_base(PyTypeObject *type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001133
Tim Peters6d6c1a32001-08-02 04:15:00 +00001134/* type test with subclassing support */
1135
1136int
1137PyType_IsSubtype(PyTypeObject *a, PyTypeObject *b)
1138{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001139 PyObject *mro;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001140
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001141 mro = a->tp_mro;
1142 if (mro != NULL) {
1143 /* Deal with multiple inheritance without recursion
1144 by walking the MRO tuple */
1145 Py_ssize_t i, n;
1146 assert(PyTuple_Check(mro));
1147 n = PyTuple_GET_SIZE(mro);
1148 for (i = 0; i < n; i++) {
1149 if (PyTuple_GET_ITEM(mro, i) == (PyObject *)b)
1150 return 1;
1151 }
1152 return 0;
1153 }
1154 else {
1155 /* a is not completely initilized yet; follow tp_base */
1156 do {
1157 if (a == b)
1158 return 1;
1159 a = a->tp_base;
1160 } while (a != NULL);
1161 return b == &PyBaseObject_Type;
1162 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001163}
1164
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001165/* Internal routines to do a method lookup in the type
Guido van Rossum60718732001-08-28 17:47:51 +00001166 without looking in the instance dictionary
1167 (so we can't use PyObject_GetAttr) but still binding
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001168 it to the instance. The arguments are the object,
Guido van Rossum60718732001-08-28 17:47:51 +00001169 the method name as a C string, and the address of a
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001170 static variable used to cache the interned Python string.
1171
1172 Two variants:
1173
1174 - lookup_maybe() returns NULL without raising an exception
1175 when the _PyType_Lookup() call fails;
1176
1177 - lookup_method() always raises an exception upon errors.
Benjamin Peterson224205f2009-05-08 03:25:19 +00001178
1179 - _PyObject_LookupSpecial() exported for the benefit of other places.
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001180*/
Guido van Rossum60718732001-08-28 17:47:51 +00001181
1182static PyObject *
Benjamin Petersonce798522012-01-22 11:24:29 -05001183lookup_maybe(PyObject *self, _Py_Identifier *attrid)
Guido van Rossum60718732001-08-28 17:47:51 +00001184{
Victor Stinner3c1e4812012-03-26 22:10:51 +02001185 PyObject *res;
Guido van Rossum60718732001-08-28 17:47:51 +00001186
Victor Stinner3c1e4812012-03-26 22:10:51 +02001187 res = _PyType_LookupId(Py_TYPE(self), attrid);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001188 if (res != NULL) {
1189 descrgetfunc f;
1190 if ((f = Py_TYPE(res)->tp_descr_get) == NULL)
1191 Py_INCREF(res);
1192 else
1193 res = f(res, self, (PyObject *)(Py_TYPE(self)));
1194 }
1195 return res;
Guido van Rossum60718732001-08-28 17:47:51 +00001196}
1197
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001198static PyObject *
Benjamin Petersonce798522012-01-22 11:24:29 -05001199lookup_method(PyObject *self, _Py_Identifier *attrid)
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001200{
Benjamin Petersonce798522012-01-22 11:24:29 -05001201 PyObject *res = lookup_maybe(self, attrid);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001202 if (res == NULL && !PyErr_Occurred())
Benjamin Petersonce798522012-01-22 11:24:29 -05001203 PyErr_SetObject(PyExc_AttributeError, attrid->object);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001204 return res;
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001205}
1206
Benjamin Peterson224205f2009-05-08 03:25:19 +00001207PyObject *
Benjamin Petersonce798522012-01-22 11:24:29 -05001208_PyObject_LookupSpecial(PyObject *self, _Py_Identifier *attrid)
Benjamin Peterson224205f2009-05-08 03:25:19 +00001209{
Benjamin Petersonce798522012-01-22 11:24:29 -05001210 return lookup_maybe(self, attrid);
Benjamin Peterson224205f2009-05-08 03:25:19 +00001211}
1212
Guido van Rossum2730b132001-08-28 18:22:14 +00001213/* A variation of PyObject_CallMethod that uses lookup_method()
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001214 instead of PyObject_GetAttrString(). This uses the same convention
Guido van Rossum2730b132001-08-28 18:22:14 +00001215 as lookup_method to cache the interned name string object. */
1216
Neil Schemenauerf23473f2001-10-21 22:28:58 +00001217static PyObject *
Benjamin Petersonce798522012-01-22 11:24:29 -05001218call_method(PyObject *o, _Py_Identifier *nameid, char *format, ...)
Guido van Rossum2730b132001-08-28 18:22:14 +00001219{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001220 va_list va;
1221 PyObject *args, *func = 0, *retval;
1222 va_start(va, format);
Guido van Rossum2730b132001-08-28 18:22:14 +00001223
Benjamin Petersonce798522012-01-22 11:24:29 -05001224 func = lookup_maybe(o, nameid);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001225 if (func == NULL) {
1226 va_end(va);
1227 if (!PyErr_Occurred())
Benjamin Petersonce798522012-01-22 11:24:29 -05001228 PyErr_SetObject(PyExc_AttributeError, nameid->object);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001229 return NULL;
1230 }
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001231
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001232 if (format && *format)
1233 args = Py_VaBuildValue(format, va);
1234 else
1235 args = PyTuple_New(0);
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001236
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001237 va_end(va);
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001238
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001239 if (args == NULL)
1240 return NULL;
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001241
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001242 assert(PyTuple_Check(args));
1243 retval = PyObject_Call(func, args, NULL);
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001244
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001245 Py_DECREF(args);
1246 Py_DECREF(func);
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001247
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001248 return retval;
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001249}
1250
1251/* Clone of call_method() that returns NotImplemented when the lookup fails. */
1252
Neil Schemenauerf23473f2001-10-21 22:28:58 +00001253static PyObject *
Benjamin Petersonce798522012-01-22 11:24:29 -05001254call_maybe(PyObject *o, _Py_Identifier *nameid, char *format, ...)
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001255{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001256 va_list va;
1257 PyObject *args, *func = 0, *retval;
1258 va_start(va, format);
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001259
Benjamin Petersonce798522012-01-22 11:24:29 -05001260 func = lookup_maybe(o, nameid);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001261 if (func == NULL) {
1262 va_end(va);
Brian Curtindfc80e32011-08-10 20:28:54 -05001263 if (!PyErr_Occurred())
1264 Py_RETURN_NOTIMPLEMENTED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001265 return NULL;
1266 }
Guido van Rossum2730b132001-08-28 18:22:14 +00001267
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001268 if (format && *format)
1269 args = Py_VaBuildValue(format, va);
1270 else
1271 args = PyTuple_New(0);
Guido van Rossum2730b132001-08-28 18:22:14 +00001272
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001273 va_end(va);
Guido van Rossum2730b132001-08-28 18:22:14 +00001274
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001275 if (args == NULL)
1276 return NULL;
Guido van Rossum2730b132001-08-28 18:22:14 +00001277
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001278 assert(PyTuple_Check(args));
1279 retval = PyObject_Call(func, args, NULL);
Guido van Rossum2730b132001-08-28 18:22:14 +00001280
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001281 Py_DECREF(args);
1282 Py_DECREF(func);
Guido van Rossum2730b132001-08-28 18:22:14 +00001283
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001284 return retval;
Guido van Rossum2730b132001-08-28 18:22:14 +00001285}
1286
Tim Petersea7f75d2002-12-07 21:39:16 +00001287/*
Guido van Rossum1f121312002-11-14 19:49:16 +00001288 Method resolution order algorithm C3 described in
1289 "A Monotonic Superclass Linearization for Dylan",
1290 by Kim Barrett, Bob Cassel, Paul Haahr,
Tim Petersea7f75d2002-12-07 21:39:16 +00001291 David A. Moon, Keith Playford, and P. Tucker Withington.
Guido van Rossum1f121312002-11-14 19:49:16 +00001292 (OOPSLA 1996)
1293
Guido van Rossum98f33732002-11-25 21:36:54 +00001294 Some notes about the rules implied by C3:
1295
Tim Petersea7f75d2002-12-07 21:39:16 +00001296 No duplicate bases.
Guido van Rossum98f33732002-11-25 21:36:54 +00001297 It isn't legal to repeat a class in a list of base classes.
1298
1299 The next three properties are the 3 constraints in "C3".
1300
Tim Petersea7f75d2002-12-07 21:39:16 +00001301 Local precendece order.
Guido van Rossum98f33732002-11-25 21:36:54 +00001302 If A precedes B in C's MRO, then A will precede B in the MRO of all
1303 subclasses of C.
1304
1305 Monotonicity.
1306 The MRO of a class must be an extension without reordering of the
1307 MRO of each of its superclasses.
1308
1309 Extended Precedence Graph (EPG).
1310 Linearization is consistent if there is a path in the EPG from
1311 each class to all its successors in the linearization. See
1312 the paper for definition of EPG.
Guido van Rossum1f121312002-11-14 19:49:16 +00001313 */
1314
Tim Petersea7f75d2002-12-07 21:39:16 +00001315static int
Guido van Rossum1f121312002-11-14 19:49:16 +00001316tail_contains(PyObject *list, int whence, PyObject *o) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001317 Py_ssize_t j, size;
1318 size = PyList_GET_SIZE(list);
Guido van Rossum1f121312002-11-14 19:49:16 +00001319
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001320 for (j = whence+1; j < size; j++) {
1321 if (PyList_GET_ITEM(list, j) == o)
1322 return 1;
1323 }
1324 return 0;
Guido van Rossum1f121312002-11-14 19:49:16 +00001325}
1326
Guido van Rossum98f33732002-11-25 21:36:54 +00001327static PyObject *
1328class_name(PyObject *cls)
1329{
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001330 PyObject *name = _PyObject_GetAttrId(cls, &PyId___name__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001331 if (name == NULL) {
1332 PyErr_Clear();
1333 Py_XDECREF(name);
1334 name = PyObject_Repr(cls);
1335 }
1336 if (name == NULL)
1337 return NULL;
1338 if (!PyUnicode_Check(name)) {
1339 Py_DECREF(name);
1340 return NULL;
1341 }
1342 return name;
Guido van Rossum98f33732002-11-25 21:36:54 +00001343}
1344
1345static int
1346check_duplicates(PyObject *list)
1347{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001348 Py_ssize_t i, j, n;
1349 /* Let's use a quadratic time algorithm,
1350 assuming that the bases lists is short.
1351 */
1352 n = PyList_GET_SIZE(list);
1353 for (i = 0; i < n; i++) {
1354 PyObject *o = PyList_GET_ITEM(list, i);
1355 for (j = i + 1; j < n; j++) {
1356 if (PyList_GET_ITEM(list, j) == o) {
1357 o = class_name(o);
1358 if (o != NULL) {
1359 PyErr_Format(PyExc_TypeError,
1360 "duplicate base class %U",
1361 o);
1362 Py_DECREF(o);
1363 } else {
1364 PyErr_SetString(PyExc_TypeError,
1365 "duplicate base class");
1366 }
1367 return -1;
1368 }
1369 }
1370 }
1371 return 0;
Guido van Rossum98f33732002-11-25 21:36:54 +00001372}
1373
1374/* Raise a TypeError for an MRO order disagreement.
1375
1376 It's hard to produce a good error message. In the absence of better
1377 insight into error reporting, report the classes that were candidates
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001378 to be put next into the MRO. There is some conflict between the
Guido van Rossum98f33732002-11-25 21:36:54 +00001379 order in which they should be put in the MRO, but it's hard to
1380 diagnose what constraint can't be satisfied.
1381*/
1382
1383static void
1384set_mro_error(PyObject *to_merge, int *remain)
1385{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001386 Py_ssize_t i, n, off, to_merge_size;
1387 char buf[1000];
1388 PyObject *k, *v;
1389 PyObject *set = PyDict_New();
1390 if (!set) return;
Guido van Rossum98f33732002-11-25 21:36:54 +00001391
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001392 to_merge_size = PyList_GET_SIZE(to_merge);
1393 for (i = 0; i < to_merge_size; i++) {
1394 PyObject *L = PyList_GET_ITEM(to_merge, i);
1395 if (remain[i] < PyList_GET_SIZE(L)) {
1396 PyObject *c = PyList_GET_ITEM(L, remain[i]);
1397 if (PyDict_SetItem(set, c, Py_None) < 0) {
1398 Py_DECREF(set);
1399 return;
1400 }
1401 }
1402 }
1403 n = PyDict_Size(set);
Guido van Rossum98f33732002-11-25 21:36:54 +00001404
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001405 off = PyOS_snprintf(buf, sizeof(buf), "Cannot create a \
Raymond Hettingerf394df42003-04-06 19:13:41 +00001406consistent method resolution\norder (MRO) for bases");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001407 i = 0;
1408 while (PyDict_Next(set, &i, &k, &v) && (size_t)off < sizeof(buf)) {
1409 PyObject *name = class_name(k);
Victor Stinnere5f99f32010-05-19 01:42:46 +00001410 char *name_str;
1411 if (name != NULL) {
1412 name_str = _PyUnicode_AsString(name);
1413 if (name_str == NULL)
Victor Stinnerba644a62010-05-19 01:50:45 +00001414 name_str = "?";
Victor Stinnere5f99f32010-05-19 01:42:46 +00001415 } else
Victor Stinnerba644a62010-05-19 01:50:45 +00001416 name_str = "?";
Victor Stinnere5f99f32010-05-19 01:42:46 +00001417 off += PyOS_snprintf(buf + off, sizeof(buf) - off, " %s", name_str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001418 Py_XDECREF(name);
1419 if (--n && (size_t)(off+1) < sizeof(buf)) {
1420 buf[off++] = ',';
1421 buf[off] = '\0';
1422 }
1423 }
1424 PyErr_SetString(PyExc_TypeError, buf);
1425 Py_DECREF(set);
Guido van Rossum98f33732002-11-25 21:36:54 +00001426}
1427
Tim Petersea7f75d2002-12-07 21:39:16 +00001428static int
Guido van Rossum1f121312002-11-14 19:49:16 +00001429pmerge(PyObject *acc, PyObject* to_merge) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001430 Py_ssize_t i, j, to_merge_size, empty_cnt;
1431 int *remain;
1432 int ok;
Tim Petersea7f75d2002-12-07 21:39:16 +00001433
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001434 to_merge_size = PyList_GET_SIZE(to_merge);
Guido van Rossum1f121312002-11-14 19:49:16 +00001435
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001436 /* remain stores an index into each sublist of to_merge.
1437 remain[i] is the index of the next base in to_merge[i]
1438 that is not included in acc.
1439 */
1440 remain = (int *)PyMem_MALLOC(SIZEOF_INT*to_merge_size);
1441 if (remain == NULL)
1442 return -1;
1443 for (i = 0; i < to_merge_size; i++)
1444 remain[i] = 0;
Guido van Rossum1f121312002-11-14 19:49:16 +00001445
1446 again:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001447 empty_cnt = 0;
1448 for (i = 0; i < to_merge_size; i++) {
1449 PyObject *candidate;
Tim Petersea7f75d2002-12-07 21:39:16 +00001450
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001451 PyObject *cur_list = PyList_GET_ITEM(to_merge, i);
Guido van Rossum1f121312002-11-14 19:49:16 +00001452
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001453 if (remain[i] >= PyList_GET_SIZE(cur_list)) {
1454 empty_cnt++;
1455 continue;
1456 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001457
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001458 /* Choose next candidate for MRO.
Guido van Rossum98f33732002-11-25 21:36:54 +00001459
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001460 The input sequences alone can determine the choice.
1461 If not, choose the class which appears in the MRO
1462 of the earliest direct superclass of the new class.
1463 */
Guido van Rossum98f33732002-11-25 21:36:54 +00001464
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001465 candidate = PyList_GET_ITEM(cur_list, remain[i]);
1466 for (j = 0; j < to_merge_size; j++) {
1467 PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
1468 if (tail_contains(j_lst, remain[j], candidate)) {
1469 goto skip; /* continue outer loop */
1470 }
1471 }
1472 ok = PyList_Append(acc, candidate);
1473 if (ok < 0) {
1474 PyMem_Free(remain);
1475 return -1;
1476 }
1477 for (j = 0; j < to_merge_size; j++) {
1478 PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
1479 if (remain[j] < PyList_GET_SIZE(j_lst) &&
1480 PyList_GET_ITEM(j_lst, remain[j]) == candidate) {
1481 remain[j]++;
1482 }
1483 }
1484 goto again;
1485 skip: ;
1486 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001487
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001488 if (empty_cnt == to_merge_size) {
1489 PyMem_FREE(remain);
1490 return 0;
1491 }
1492 set_mro_error(to_merge, remain);
1493 PyMem_FREE(remain);
1494 return -1;
Guido van Rossum1f121312002-11-14 19:49:16 +00001495}
1496
Tim Peters6d6c1a32001-08-02 04:15:00 +00001497static PyObject *
1498mro_implementation(PyTypeObject *type)
1499{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001500 Py_ssize_t i, n;
1501 int ok;
1502 PyObject *bases, *result;
1503 PyObject *to_merge, *bases_aslist;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001504
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001505 if (type->tp_dict == NULL) {
1506 if (PyType_Ready(type) < 0)
1507 return NULL;
1508 }
Guido van Rossum63517572002-06-18 16:44:57 +00001509
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001510 /* Find a superclass linearization that honors the constraints
1511 of the explicit lists of bases and the constraints implied by
1512 each base class.
Guido van Rossum98f33732002-11-25 21:36:54 +00001513
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001514 to_merge is a list of lists, where each list is a superclass
1515 linearization implied by a base class. The last element of
1516 to_merge is the declared list of bases.
1517 */
Guido van Rossum98f33732002-11-25 21:36:54 +00001518
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001519 bases = type->tp_bases;
1520 n = PyTuple_GET_SIZE(bases);
Guido van Rossum1f121312002-11-14 19:49:16 +00001521
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001522 to_merge = PyList_New(n+1);
1523 if (to_merge == NULL)
1524 return NULL;
Guido van Rossum1f121312002-11-14 19:49:16 +00001525
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001526 for (i = 0; i < n; i++) {
1527 PyObject *base = PyTuple_GET_ITEM(bases, i);
1528 PyObject *parentMRO;
1529 parentMRO = PySequence_List(((PyTypeObject*)base)->tp_mro);
1530 if (parentMRO == NULL) {
1531 Py_DECREF(to_merge);
1532 return NULL;
1533 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001534
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001535 PyList_SET_ITEM(to_merge, i, parentMRO);
1536 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001537
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001538 bases_aslist = PySequence_List(bases);
1539 if (bases_aslist == NULL) {
1540 Py_DECREF(to_merge);
1541 return NULL;
1542 }
1543 /* This is just a basic sanity check. */
1544 if (check_duplicates(bases_aslist) < 0) {
1545 Py_DECREF(to_merge);
1546 Py_DECREF(bases_aslist);
1547 return NULL;
1548 }
1549 PyList_SET_ITEM(to_merge, n, bases_aslist);
Guido van Rossum1f121312002-11-14 19:49:16 +00001550
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001551 result = Py_BuildValue("[O]", (PyObject *)type);
1552 if (result == 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 ok = pmerge(result, to_merge);
1558 Py_DECREF(to_merge);
1559 if (ok < 0) {
1560 Py_DECREF(result);
1561 return NULL;
1562 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001563
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001564 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001565}
1566
1567static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001568mro_external(PyObject *self)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001569{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001570 PyTypeObject *type = (PyTypeObject *)self;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001571
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001572 return mro_implementation(type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001573}
1574
1575static int
1576mro_internal(PyTypeObject *type)
1577{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001578 PyObject *mro, *result, *tuple;
1579 int checkit = 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001580
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001581 if (Py_TYPE(type) == &PyType_Type) {
1582 result = mro_implementation(type);
1583 }
1584 else {
Benjamin Petersonce798522012-01-22 11:24:29 -05001585 _Py_IDENTIFIER(mro);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001586 checkit = 1;
Benjamin Petersonce798522012-01-22 11:24:29 -05001587 mro = lookup_method((PyObject *)type, &PyId_mro);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001588 if (mro == NULL)
1589 return -1;
1590 result = PyObject_CallObject(mro, NULL);
1591 Py_DECREF(mro);
1592 }
1593 if (result == NULL)
1594 return -1;
1595 tuple = PySequence_Tuple(result);
1596 Py_DECREF(result);
1597 if (tuple == NULL)
1598 return -1;
1599 if (checkit) {
1600 Py_ssize_t i, len;
1601 PyObject *cls;
1602 PyTypeObject *solid;
Armin Rigo037d1e02005-12-29 17:07:39 +00001603
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001604 solid = solid_base(type);
Armin Rigo037d1e02005-12-29 17:07:39 +00001605
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001606 len = PyTuple_GET_SIZE(tuple);
Armin Rigo037d1e02005-12-29 17:07:39 +00001607
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001608 for (i = 0; i < len; i++) {
1609 PyTypeObject *t;
1610 cls = PyTuple_GET_ITEM(tuple, i);
1611 if (!PyType_Check(cls)) {
1612 PyErr_Format(PyExc_TypeError,
1613 "mro() returned a non-class ('%.500s')",
1614 Py_TYPE(cls)->tp_name);
1615 Py_DECREF(tuple);
1616 return -1;
1617 }
1618 t = (PyTypeObject*)cls;
1619 if (!PyType_IsSubtype(solid, solid_base(t))) {
1620 PyErr_Format(PyExc_TypeError,
1621 "mro() returned base with unsuitable layout ('%.500s')",
1622 t->tp_name);
1623 Py_DECREF(tuple);
1624 return -1;
1625 }
1626 }
1627 }
1628 type->tp_mro = tuple;
Christian Heimesa62da1d2008-01-12 19:39:10 +00001629
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001630 type_mro_modified(type, type->tp_mro);
Florent Xiclunaaa6c1d22011-12-12 18:54:29 +01001631 /* corner case: the super class might have been hidden
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001632 from the custom MRO */
1633 type_mro_modified(type, type->tp_bases);
Christian Heimesa62da1d2008-01-12 19:39:10 +00001634
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001635 PyType_Modified(type);
Christian Heimesa62da1d2008-01-12 19:39:10 +00001636
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001637 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001638}
1639
1640
1641/* Calculate the best base amongst multiple base classes.
1642 This is the first one that's on the path to the "solid base". */
1643
1644static PyTypeObject *
1645best_base(PyObject *bases)
1646{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001647 Py_ssize_t i, n;
1648 PyTypeObject *base, *winner, *candidate, *base_i;
1649 PyObject *base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001650
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001651 assert(PyTuple_Check(bases));
1652 n = PyTuple_GET_SIZE(bases);
1653 assert(n > 0);
1654 base = NULL;
1655 winner = NULL;
1656 for (i = 0; i < n; i++) {
1657 base_proto = PyTuple_GET_ITEM(bases, i);
1658 if (!PyType_Check(base_proto)) {
1659 PyErr_SetString(
1660 PyExc_TypeError,
1661 "bases must be types");
1662 return NULL;
1663 }
1664 base_i = (PyTypeObject *)base_proto;
1665 if (base_i->tp_dict == NULL) {
1666 if (PyType_Ready(base_i) < 0)
1667 return NULL;
1668 }
1669 candidate = solid_base(base_i);
1670 if (winner == NULL) {
1671 winner = candidate;
1672 base = base_i;
1673 }
1674 else if (PyType_IsSubtype(winner, candidate))
1675 ;
1676 else if (PyType_IsSubtype(candidate, winner)) {
1677 winner = candidate;
1678 base = base_i;
1679 }
1680 else {
1681 PyErr_SetString(
1682 PyExc_TypeError,
1683 "multiple bases have "
1684 "instance lay-out conflict");
1685 return NULL;
1686 }
1687 }
Florent Xiclunaaa6c1d22011-12-12 18:54:29 +01001688 assert (base != NULL);
1689
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001690 return base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001691}
1692
1693static int
1694extra_ivars(PyTypeObject *type, PyTypeObject *base)
1695{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001696 size_t t_size = type->tp_basicsize;
1697 size_t b_size = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001698
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001699 assert(t_size >= b_size); /* Else type smaller than base! */
1700 if (type->tp_itemsize || base->tp_itemsize) {
1701 /* If itemsize is involved, stricter rules */
1702 return t_size != b_size ||
1703 type->tp_itemsize != base->tp_itemsize;
1704 }
1705 if (type->tp_weaklistoffset && base->tp_weaklistoffset == 0 &&
1706 type->tp_weaklistoffset + sizeof(PyObject *) == t_size &&
1707 type->tp_flags & Py_TPFLAGS_HEAPTYPE)
1708 t_size -= sizeof(PyObject *);
1709 if (type->tp_dictoffset && base->tp_dictoffset == 0 &&
1710 type->tp_dictoffset + sizeof(PyObject *) == t_size &&
1711 type->tp_flags & Py_TPFLAGS_HEAPTYPE)
1712 t_size -= sizeof(PyObject *);
Guido van Rossum9676b222001-08-17 20:32:36 +00001713
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001714 return t_size != b_size;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001715}
1716
1717static PyTypeObject *
1718solid_base(PyTypeObject *type)
1719{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001720 PyTypeObject *base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001721
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001722 if (type->tp_base)
1723 base = solid_base(type->tp_base);
1724 else
1725 base = &PyBaseObject_Type;
1726 if (extra_ivars(type, base))
1727 return type;
1728 else
1729 return base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001730}
1731
Jeremy Hylton938ace62002-07-17 16:30:39 +00001732static void object_dealloc(PyObject *);
1733static int object_init(PyObject *, PyObject *, PyObject *);
1734static int update_slot(PyTypeObject *, PyObject *);
1735static void fixup_slot_dispatchers(PyTypeObject *);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001736
Guido van Rossum360e4b82007-05-14 22:51:27 +00001737/*
1738 * Helpers for __dict__ descriptor. We don't want to expose the dicts
1739 * inherited from various builtin types. The builtin base usually provides
1740 * its own __dict__ descriptor, so we use that when we can.
1741 */
1742static PyTypeObject *
1743get_builtin_base_with_dict(PyTypeObject *type)
1744{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001745 while (type->tp_base != NULL) {
1746 if (type->tp_dictoffset != 0 &&
1747 !(type->tp_flags & Py_TPFLAGS_HEAPTYPE))
1748 return type;
1749 type = type->tp_base;
1750 }
1751 return NULL;
Guido van Rossum360e4b82007-05-14 22:51:27 +00001752}
1753
1754static PyObject *
1755get_dict_descriptor(PyTypeObject *type)
1756{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001757 PyObject *descr;
Guido van Rossum360e4b82007-05-14 22:51:27 +00001758
Victor Stinner3c1e4812012-03-26 22:10:51 +02001759 descr = _PyType_LookupId(type, &PyId___dict__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001760 if (descr == NULL || !PyDescr_IsData(descr))
1761 return NULL;
Guido van Rossum360e4b82007-05-14 22:51:27 +00001762
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001763 return descr;
Guido van Rossum360e4b82007-05-14 22:51:27 +00001764}
1765
1766static void
1767raise_dict_descr_error(PyObject *obj)
1768{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001769 PyErr_Format(PyExc_TypeError,
1770 "this __dict__ descriptor does not support "
1771 "'%.200s' objects", Py_TYPE(obj)->tp_name);
Guido van Rossum360e4b82007-05-14 22:51:27 +00001772}
1773
Tim Peters6d6c1a32001-08-02 04:15:00 +00001774static PyObject *
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001775subtype_dict(PyObject *obj, void *context)
1776{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001777 PyTypeObject *base;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001778
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001779 base = get_builtin_base_with_dict(Py_TYPE(obj));
1780 if (base != NULL) {
1781 descrgetfunc func;
1782 PyObject *descr = get_dict_descriptor(base);
1783 if (descr == NULL) {
1784 raise_dict_descr_error(obj);
1785 return NULL;
1786 }
1787 func = Py_TYPE(descr)->tp_descr_get;
1788 if (func == NULL) {
1789 raise_dict_descr_error(obj);
1790 return NULL;
1791 }
1792 return func(descr, obj, (PyObject *)(Py_TYPE(obj)));
1793 }
Benjamin Peterson8eb12692012-02-19 19:59:10 -05001794 return PyObject_GenericGetDict(obj, context);
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001795}
1796
Guido van Rossum6661be32001-10-26 04:26:12 +00001797static int
1798subtype_setdict(PyObject *obj, PyObject *value, void *context)
1799{
Benjamin Peterson8eb12692012-02-19 19:59:10 -05001800 PyObject *dict, **dictptr;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001801 PyTypeObject *base;
Guido van Rossum6661be32001-10-26 04:26:12 +00001802
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001803 base = get_builtin_base_with_dict(Py_TYPE(obj));
1804 if (base != NULL) {
1805 descrsetfunc func;
1806 PyObject *descr = get_dict_descriptor(base);
1807 if (descr == NULL) {
1808 raise_dict_descr_error(obj);
1809 return -1;
1810 }
1811 func = Py_TYPE(descr)->tp_descr_set;
1812 if (func == NULL) {
1813 raise_dict_descr_error(obj);
1814 return -1;
1815 }
1816 return func(descr, obj, value);
1817 }
Benjamin Peterson8eb12692012-02-19 19:59:10 -05001818 /* Almost like PyObject_GenericSetDict, but allow __dict__ to be deleted. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001819 dictptr = _PyObject_GetDictPtr(obj);
1820 if (dictptr == NULL) {
1821 PyErr_SetString(PyExc_AttributeError,
1822 "This object has no __dict__");
1823 return -1;
1824 }
Benjamin Peterson006c5a22012-02-19 20:36:12 -05001825 if (value != NULL && !PyDict_Check(value)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001826 PyErr_Format(PyExc_TypeError,
1827 "__dict__ must be set to a dictionary, "
1828 "not a '%.200s'", Py_TYPE(value)->tp_name);
1829 return -1;
1830 }
1831 dict = *dictptr;
1832 Py_XINCREF(value);
1833 *dictptr = value;
1834 Py_XDECREF(dict);
1835 return 0;
Guido van Rossum6661be32001-10-26 04:26:12 +00001836}
1837
Guido van Rossumad47da02002-08-12 19:05:44 +00001838static PyObject *
1839subtype_getweakref(PyObject *obj, void *context)
1840{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001841 PyObject **weaklistptr;
1842 PyObject *result;
Guido van Rossumad47da02002-08-12 19:05:44 +00001843
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001844 if (Py_TYPE(obj)->tp_weaklistoffset == 0) {
1845 PyErr_SetString(PyExc_AttributeError,
1846 "This object has no __weakref__");
1847 return NULL;
1848 }
1849 assert(Py_TYPE(obj)->tp_weaklistoffset > 0);
1850 assert(Py_TYPE(obj)->tp_weaklistoffset + sizeof(PyObject *) <=
1851 (size_t)(Py_TYPE(obj)->tp_basicsize));
1852 weaklistptr = (PyObject **)
1853 ((char *)obj + Py_TYPE(obj)->tp_weaklistoffset);
1854 if (*weaklistptr == NULL)
1855 result = Py_None;
1856 else
1857 result = *weaklistptr;
1858 Py_INCREF(result);
1859 return result;
Guido van Rossumad47da02002-08-12 19:05:44 +00001860}
1861
Guido van Rossum373c7412003-01-07 13:41:37 +00001862/* Three variants on the subtype_getsets list. */
1863
1864static PyGetSetDef subtype_getsets_full[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001865 {"__dict__", subtype_dict, subtype_setdict,
1866 PyDoc_STR("dictionary for instance variables (if defined)")},
1867 {"__weakref__", subtype_getweakref, NULL,
1868 PyDoc_STR("list of weak references to the object (if defined)")},
1869 {0}
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001870};
1871
Guido van Rossum373c7412003-01-07 13:41:37 +00001872static PyGetSetDef subtype_getsets_dict_only[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001873 {"__dict__", subtype_dict, subtype_setdict,
1874 PyDoc_STR("dictionary for instance variables (if defined)")},
1875 {0}
Guido van Rossum373c7412003-01-07 13:41:37 +00001876};
1877
1878static PyGetSetDef subtype_getsets_weakref_only[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001879 {"__weakref__", subtype_getweakref, NULL,
1880 PyDoc_STR("list of weak references to the object (if defined)")},
1881 {0}
Guido van Rossum373c7412003-01-07 13:41:37 +00001882};
1883
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001884static int
1885valid_identifier(PyObject *s)
1886{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001887 if (!PyUnicode_Check(s)) {
1888 PyErr_Format(PyExc_TypeError,
1889 "__slots__ items must be strings, not '%.200s'",
1890 Py_TYPE(s)->tp_name);
1891 return 0;
1892 }
1893 if (!PyUnicode_IsIdentifier(s)) {
1894 PyErr_SetString(PyExc_TypeError,
1895 "__slots__ must be identifiers");
1896 return 0;
1897 }
1898 return 1;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001899}
1900
Guido van Rossumd8faa362007-04-27 19:54:29 +00001901/* Forward */
1902static int
1903object_init(PyObject *self, PyObject *args, PyObject *kwds);
1904
1905static int
1906type_init(PyObject *cls, PyObject *args, PyObject *kwds)
1907{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001908 int res;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001909
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001910 assert(args != NULL && PyTuple_Check(args));
1911 assert(kwds == NULL || PyDict_Check(kwds));
Guido van Rossumd8faa362007-04-27 19:54:29 +00001912
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001913 if (kwds != NULL && PyDict_Check(kwds) && PyDict_Size(kwds) != 0) {
1914 PyErr_SetString(PyExc_TypeError,
1915 "type.__init__() takes no keyword arguments");
1916 return -1;
1917 }
Guido van Rossumd8faa362007-04-27 19:54:29 +00001918
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001919 if (args != NULL && PyTuple_Check(args) &&
1920 (PyTuple_GET_SIZE(args) != 1 && PyTuple_GET_SIZE(args) != 3)) {
1921 PyErr_SetString(PyExc_TypeError,
1922 "type.__init__() takes 1 or 3 arguments");
1923 return -1;
1924 }
Guido van Rossumd8faa362007-04-27 19:54:29 +00001925
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001926 /* Call object.__init__(self) now. */
1927 /* XXX Could call super(type, cls).__init__() but what's the point? */
1928 args = PyTuple_GetSlice(args, 0, 0);
1929 res = object_init(cls, args, NULL);
1930 Py_DECREF(args);
1931 return res;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001932}
1933
Martin v. Löwis738236d2011-02-05 20:35:29 +00001934long
1935PyType_GetFlags(PyTypeObject *type)
1936{
1937 return type->tp_flags;
1938}
1939
Nick Coghlande31b192011-10-23 22:04:16 +10001940/* Determine the most derived metatype. */
1941PyTypeObject *
1942_PyType_CalculateMetaclass(PyTypeObject *metatype, PyObject *bases)
1943{
1944 Py_ssize_t i, nbases;
1945 PyTypeObject *winner;
1946 PyObject *tmp;
1947 PyTypeObject *tmptype;
1948
1949 /* Determine the proper metatype to deal with this,
1950 and check for metatype conflicts while we're at it.
1951 Note that if some other metatype wins to contract,
1952 it's possible that its instances are not types. */
1953
1954 nbases = PyTuple_GET_SIZE(bases);
1955 winner = metatype;
1956 for (i = 0; i < nbases; i++) {
1957 tmp = PyTuple_GET_ITEM(bases, i);
1958 tmptype = Py_TYPE(tmp);
1959 if (PyType_IsSubtype(winner, tmptype))
1960 continue;
1961 if (PyType_IsSubtype(tmptype, winner)) {
1962 winner = tmptype;
1963 continue;
1964 }
1965 /* else: */
1966 PyErr_SetString(PyExc_TypeError,
1967 "metaclass conflict: "
1968 "the metaclass of a derived class "
1969 "must be a (non-strict) subclass "
1970 "of the metaclasses of all its bases");
1971 return NULL;
1972 }
1973 return winner;
1974}
1975
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001976static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00001977type_new(PyTypeObject *metatype, PyObject *args, PyObject *kwds)
1978{
Victor Stinner6f738742012-02-25 01:22:36 +01001979 PyObject *name, *bases = NULL, *orig_dict, *dict = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001980 static char *kwlist[] = {"name", "bases", "dict", 0};
Victor Stinner6f738742012-02-25 01:22:36 +01001981 PyObject *qualname, *slots = NULL, *tmp, *newslots;
1982 PyTypeObject *type = NULL, *base, *tmptype, *winner;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001983 PyHeapTypeObject *et;
1984 PyMemberDef *mp;
1985 Py_ssize_t i, nbases, nslots, slotoffset, add_dict, add_weak;
1986 int j, may_add_dict, may_add_weak;
Victor Stinner3c1e4812012-03-26 22:10:51 +02001987 _Py_IDENTIFIER(__qualname__);
1988 _Py_IDENTIFIER(__slots__);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001989
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001990 assert(args != NULL && PyTuple_Check(args));
1991 assert(kwds == NULL || PyDict_Check(kwds));
Tim Peters3abca122001-10-27 19:37:48 +00001992
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001993 /* Special case: type(x) should return x->ob_type */
1994 {
1995 const Py_ssize_t nargs = PyTuple_GET_SIZE(args);
1996 const Py_ssize_t nkwds = kwds == NULL ? 0 : PyDict_Size(kwds);
Tim Peters3abca122001-10-27 19:37:48 +00001997
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001998 if (PyType_CheckExact(metatype) && nargs == 1 && nkwds == 0) {
1999 PyObject *x = PyTuple_GET_ITEM(args, 0);
2000 Py_INCREF(Py_TYPE(x));
2001 return (PyObject *) Py_TYPE(x);
2002 }
Tim Peters3abca122001-10-27 19:37:48 +00002003
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002004 /* SF bug 475327 -- if that didn't trigger, we need 3
2005 arguments. but PyArg_ParseTupleAndKeywords below may give
2006 a msg saying type() needs exactly 3. */
2007 if (nargs + nkwds != 3) {
2008 PyErr_SetString(PyExc_TypeError,
2009 "type() takes 1 or 3 arguments");
2010 return NULL;
2011 }
2012 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002013
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002014 /* Check arguments: (name, bases, dict) */
2015 if (!PyArg_ParseTupleAndKeywords(args, kwds, "UO!O!:type", kwlist,
2016 &name,
2017 &PyTuple_Type, &bases,
Victor Stinner6f738742012-02-25 01:22:36 +01002018 &PyDict_Type, &orig_dict))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002019 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002020
Nick Coghlande31b192011-10-23 22:04:16 +10002021 /* Determine the proper metatype to deal with this: */
2022 winner = _PyType_CalculateMetaclass(metatype, bases);
2023 if (winner == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002024 return NULL;
2025 }
Nick Coghlande31b192011-10-23 22:04:16 +10002026
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002027 if (winner != metatype) {
2028 if (winner->tp_new != type_new) /* Pass it to the winner */
2029 return winner->tp_new(winner, args, kwds);
2030 metatype = winner;
2031 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002032
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002033 /* Adjust for empty tuple bases */
Nick Coghlande31b192011-10-23 22:04:16 +10002034 nbases = PyTuple_GET_SIZE(bases);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002035 if (nbases == 0) {
2036 bases = PyTuple_Pack(1, &PyBaseObject_Type);
2037 if (bases == NULL)
Victor Stinner6f738742012-02-25 01:22:36 +01002038 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002039 nbases = 1;
2040 }
2041 else
2042 Py_INCREF(bases);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002043
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002044 /* Calculate best base, and check that all bases are type objects */
2045 base = best_base(bases);
2046 if (base == NULL) {
Victor Stinner6f738742012-02-25 01:22:36 +01002047 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002048 }
2049 if (!PyType_HasFeature(base, Py_TPFLAGS_BASETYPE)) {
2050 PyErr_Format(PyExc_TypeError,
2051 "type '%.100s' is not an acceptable base type",
2052 base->tp_name);
Victor Stinner6f738742012-02-25 01:22:36 +01002053 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002054 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002055
Victor Stinner6f738742012-02-25 01:22:36 +01002056 dict = PyDict_Copy(orig_dict);
2057 if (dict == NULL)
2058 goto error;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002059
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002060 /* Check for a __slots__ sequence variable in dict, and count it */
Victor Stinner3c1e4812012-03-26 22:10:51 +02002061 slots = _PyDict_GetItemId(dict, &PyId___slots__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002062 nslots = 0;
2063 add_dict = 0;
2064 add_weak = 0;
2065 may_add_dict = base->tp_dictoffset == 0;
2066 may_add_weak = base->tp_weaklistoffset == 0 && base->tp_itemsize == 0;
2067 if (slots == NULL) {
2068 if (may_add_dict) {
2069 add_dict++;
2070 }
2071 if (may_add_weak) {
2072 add_weak++;
2073 }
2074 }
2075 else {
2076 /* Have slots */
Guido van Rossumad47da02002-08-12 19:05:44 +00002077
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002078 /* Make it into a tuple */
2079 if (PyUnicode_Check(slots))
2080 slots = PyTuple_Pack(1, slots);
2081 else
2082 slots = PySequence_Tuple(slots);
Victor Stinner6f738742012-02-25 01:22:36 +01002083 if (slots == NULL)
2084 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002085 assert(PyTuple_Check(slots));
Guido van Rossumad47da02002-08-12 19:05:44 +00002086
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002087 /* Are slots allowed? */
2088 nslots = PyTuple_GET_SIZE(slots);
2089 if (nslots > 0 && base->tp_itemsize != 0) {
2090 PyErr_Format(PyExc_TypeError,
2091 "nonempty __slots__ "
2092 "not supported for subtype of '%s'",
2093 base->tp_name);
Victor Stinner6f738742012-02-25 01:22:36 +01002094 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002095 }
Guido van Rossumad47da02002-08-12 19:05:44 +00002096
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002097 /* Check for valid slot names and two special cases */
2098 for (i = 0; i < nslots; i++) {
2099 PyObject *tmp = PyTuple_GET_ITEM(slots, i);
2100 if (!valid_identifier(tmp))
Victor Stinner6f738742012-02-25 01:22:36 +01002101 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002102 assert(PyUnicode_Check(tmp));
2103 if (PyUnicode_CompareWithASCIIString(tmp, "__dict__") == 0) {
2104 if (!may_add_dict || add_dict) {
2105 PyErr_SetString(PyExc_TypeError,
2106 "__dict__ slot disallowed: "
2107 "we already got one");
Victor Stinner6f738742012-02-25 01:22:36 +01002108 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002109 }
2110 add_dict++;
2111 }
2112 if (PyUnicode_CompareWithASCIIString(tmp, "__weakref__") == 0) {
2113 if (!may_add_weak || add_weak) {
2114 PyErr_SetString(PyExc_TypeError,
2115 "__weakref__ slot disallowed: "
2116 "either we already got one, "
2117 "or __itemsize__ != 0");
Victor Stinner6f738742012-02-25 01:22:36 +01002118 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002119 }
2120 add_weak++;
2121 }
2122 }
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00002123
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002124 /* Copy slots into a list, mangle names and sort them.
2125 Sorted names are needed for __class__ assignment.
2126 Convert them back to tuple at the end.
2127 */
2128 newslots = PyList_New(nslots - add_dict - add_weak);
2129 if (newslots == NULL)
Victor Stinner6f738742012-02-25 01:22:36 +01002130 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002131 for (i = j = 0; i < nslots; i++) {
2132 tmp = PyTuple_GET_ITEM(slots, i);
2133 if ((add_dict &&
2134 PyUnicode_CompareWithASCIIString(tmp, "__dict__") == 0) ||
2135 (add_weak &&
2136 PyUnicode_CompareWithASCIIString(tmp, "__weakref__") == 0))
2137 continue;
2138 tmp =_Py_Mangle(name, tmp);
Benjamin Petersonae13c882011-08-16 22:26:48 -05002139 if (!tmp) {
2140 Py_DECREF(newslots);
Victor Stinner6f738742012-02-25 01:22:36 +01002141 goto error;
Benjamin Petersonae13c882011-08-16 22:26:48 -05002142 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002143 PyList_SET_ITEM(newslots, j, tmp);
Benjamin Petersonc4085c82011-08-16 18:53:26 -05002144 if (PyDict_GetItem(dict, tmp)) {
2145 PyErr_Format(PyExc_ValueError,
2146 "%R in __slots__ conflicts with class variable",
2147 tmp);
Benjamin Petersond17cefc2011-08-16 22:28:23 -05002148 Py_DECREF(newslots);
Victor Stinner6f738742012-02-25 01:22:36 +01002149 goto error;
Benjamin Petersonc4085c82011-08-16 18:53:26 -05002150 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002151 j++;
2152 }
2153 assert(j == nslots - add_dict - add_weak);
2154 nslots = j;
Victor Stinner6f738742012-02-25 01:22:36 +01002155 Py_CLEAR(slots);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002156 if (PyList_Sort(newslots) == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002157 Py_DECREF(newslots);
Victor Stinner6f738742012-02-25 01:22:36 +01002158 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002159 }
2160 slots = PyList_AsTuple(newslots);
2161 Py_DECREF(newslots);
Victor Stinner6f738742012-02-25 01:22:36 +01002162 if (slots == NULL)
2163 goto error;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00002164
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002165 /* Secondary bases may provide weakrefs or dict */
2166 if (nbases > 1 &&
2167 ((may_add_dict && !add_dict) ||
2168 (may_add_weak && !add_weak))) {
2169 for (i = 0; i < nbases; i++) {
2170 tmp = PyTuple_GET_ITEM(bases, i);
2171 if (tmp == (PyObject *)base)
2172 continue; /* Skip primary base */
2173 assert(PyType_Check(tmp));
2174 tmptype = (PyTypeObject *)tmp;
2175 if (may_add_dict && !add_dict &&
2176 tmptype->tp_dictoffset != 0)
2177 add_dict++;
2178 if (may_add_weak && !add_weak &&
2179 tmptype->tp_weaklistoffset != 0)
2180 add_weak++;
2181 if (may_add_dict && !add_dict)
2182 continue;
2183 if (may_add_weak && !add_weak)
2184 continue;
2185 /* Nothing more to check */
2186 break;
2187 }
2188 }
2189 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002190
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002191 /* Allocate the type object */
2192 type = (PyTypeObject *)metatype->tp_alloc(metatype, nslots);
Victor Stinner6f738742012-02-25 01:22:36 +01002193 if (type == NULL)
2194 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002195
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002196 /* Keep name and slots alive in the extended type object */
2197 et = (PyHeapTypeObject *)type;
2198 Py_INCREF(name);
2199 et->ht_name = name;
2200 et->ht_slots = slots;
Victor Stinner6f738742012-02-25 01:22:36 +01002201 slots = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002202
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002203 /* Initialize tp_flags */
2204 type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE |
2205 Py_TPFLAGS_BASETYPE;
2206 if (base->tp_flags & Py_TPFLAGS_HAVE_GC)
2207 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossumdc91b992001-08-08 22:26:22 +00002208
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002209 /* Initialize essential fields */
2210 type->tp_as_number = &et->as_number;
2211 type->tp_as_sequence = &et->as_sequence;
2212 type->tp_as_mapping = &et->as_mapping;
2213 type->tp_as_buffer = &et->as_buffer;
2214 type->tp_name = _PyUnicode_AsString(name);
Victor Stinner6f738742012-02-25 01:22:36 +01002215 if (!type->tp_name)
2216 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002217
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002218 /* Set tp_base and tp_bases */
2219 type->tp_bases = bases;
Victor Stinner6f738742012-02-25 01:22:36 +01002220 bases = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002221 Py_INCREF(base);
2222 type->tp_base = base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002223
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002224 /* Initialize tp_dict from passed-in dict */
Victor Stinner6f738742012-02-25 01:22:36 +01002225 Py_INCREF(dict);
2226 type->tp_dict = dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002227
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002228 /* Set __module__ in the dict */
Victor Stinner3c1e4812012-03-26 22:10:51 +02002229 if (_PyDict_GetItemId(dict, &PyId___module__) == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002230 tmp = PyEval_GetGlobals();
2231 if (tmp != NULL) {
Victor Stinner3c1e4812012-03-26 22:10:51 +02002232 tmp = _PyDict_GetItemId(tmp, &PyId___name__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002233 if (tmp != NULL) {
Victor Stinner3c1e4812012-03-26 22:10:51 +02002234 if (_PyDict_SetItemId(dict, &PyId___module__,
2235 tmp) < 0)
Victor Stinner6f738742012-02-25 01:22:36 +01002236 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002237 }
2238 }
2239 }
Guido van Rossumc3542212001-08-16 09:18:56 +00002240
Victor Stinner6f738742012-02-25 01:22:36 +01002241 /* Set ht_qualname to dict['__qualname__'] if available, else to
2242 __name__. The __qualname__ accessor will look for ht_qualname.
2243 */
Victor Stinner3c1e4812012-03-26 22:10:51 +02002244 qualname = _PyDict_GetItemId(dict, &PyId___qualname__);
Victor Stinner6f738742012-02-25 01:22:36 +01002245 if (qualname != NULL) {
2246 if (!PyUnicode_Check(qualname)) {
2247 PyErr_Format(PyExc_TypeError,
2248 "type __qualname__ must be a str, not %s",
2249 Py_TYPE(qualname)->tp_name);
2250 goto error;
2251 }
2252 }
2253 else {
2254 qualname = et->ht_name;
2255 }
2256 Py_INCREF(qualname);
2257 et->ht_qualname = qualname;
2258
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002259 /* Set tp_doc to a copy of dict['__doc__'], if the latter is there
2260 and is a string. The __doc__ accessor will first look for tp_doc;
2261 if that fails, it will still look into __dict__.
2262 */
2263 {
Victor Stinner3c1e4812012-03-26 22:10:51 +02002264 PyObject *doc = _PyDict_GetItemId(dict, &PyId___doc__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002265 if (doc != NULL && PyUnicode_Check(doc)) {
2266 Py_ssize_t len;
2267 char *doc_str;
2268 char *tp_doc;
Alexandre Vassalottia85998a2008-05-03 18:24:43 +00002269
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002270 doc_str = _PyUnicode_AsString(doc);
Victor Stinner6f738742012-02-25 01:22:36 +01002271 if (doc_str == NULL)
2272 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002273 /* Silently truncate the docstring if it contains null bytes. */
2274 len = strlen(doc_str);
2275 tp_doc = (char *)PyObject_MALLOC(len + 1);
Victor Stinner6f738742012-02-25 01:22:36 +01002276 if (tp_doc == NULL)
2277 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002278 memcpy(tp_doc, doc_str, len + 1);
2279 type->tp_doc = tp_doc;
2280 }
2281 }
Tim Peters2f93e282001-10-04 05:27:00 +00002282
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002283 /* Special-case __new__: if it's a plain function,
2284 make it a static function */
Victor Stinner3c1e4812012-03-26 22:10:51 +02002285 tmp = _PyDict_GetItemId(dict, &PyId___new__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002286 if (tmp != NULL && PyFunction_Check(tmp)) {
2287 tmp = PyStaticMethod_New(tmp);
Victor Stinner6f738742012-02-25 01:22:36 +01002288 if (tmp == NULL)
2289 goto error;
Victor Stinner3c1e4812012-03-26 22:10:51 +02002290 if (_PyDict_SetItemId(dict, &PyId___new__, tmp) < 0)
2291 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002292 Py_DECREF(tmp);
2293 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002294
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002295 /* Add descriptors for custom slots from __slots__, or for __dict__ */
2296 mp = PyHeapType_GET_MEMBERS(et);
2297 slotoffset = base->tp_basicsize;
Victor Stinner6f738742012-02-25 01:22:36 +01002298 if (et->ht_slots != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002299 for (i = 0; i < nslots; i++, mp++) {
2300 mp->name = _PyUnicode_AsString(
Victor Stinner6f738742012-02-25 01:22:36 +01002301 PyTuple_GET_ITEM(et->ht_slots, i));
2302 if (mp->name == NULL)
2303 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002304 mp->type = T_OBJECT_EX;
2305 mp->offset = slotoffset;
Guido van Rossumd8faa362007-04-27 19:54:29 +00002306
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002307 /* __dict__ and __weakref__ are already filtered out */
2308 assert(strcmp(mp->name, "__dict__") != 0);
2309 assert(strcmp(mp->name, "__weakref__") != 0);
Guido van Rossumd8faa362007-04-27 19:54:29 +00002310
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002311 slotoffset += sizeof(PyObject *);
2312 }
2313 }
2314 if (add_dict) {
2315 if (base->tp_itemsize)
2316 type->tp_dictoffset = -(long)sizeof(PyObject *);
2317 else
2318 type->tp_dictoffset = slotoffset;
2319 slotoffset += sizeof(PyObject *);
2320 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002321 if (type->tp_dictoffset) {
2322 et->ht_cached_keys = _PyDict_NewKeysForClass();
2323 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002324 if (add_weak) {
2325 assert(!base->tp_itemsize);
2326 type->tp_weaklistoffset = slotoffset;
2327 slotoffset += sizeof(PyObject *);
2328 }
2329 type->tp_basicsize = slotoffset;
2330 type->tp_itemsize = base->tp_itemsize;
2331 type->tp_members = PyHeapType_GET_MEMBERS(et);
Guido van Rossum373c7412003-01-07 13:41:37 +00002332
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002333 if (type->tp_weaklistoffset && type->tp_dictoffset)
2334 type->tp_getset = subtype_getsets_full;
2335 else if (type->tp_weaklistoffset && !type->tp_dictoffset)
2336 type->tp_getset = subtype_getsets_weakref_only;
2337 else if (!type->tp_weaklistoffset && type->tp_dictoffset)
2338 type->tp_getset = subtype_getsets_dict_only;
2339 else
2340 type->tp_getset = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002341
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002342 /* Special case some slots */
2343 if (type->tp_dictoffset != 0 || nslots > 0) {
2344 if (base->tp_getattr == NULL && base->tp_getattro == NULL)
2345 type->tp_getattro = PyObject_GenericGetAttr;
2346 if (base->tp_setattr == NULL && base->tp_setattro == NULL)
2347 type->tp_setattro = PyObject_GenericSetAttr;
2348 }
2349 type->tp_dealloc = subtype_dealloc;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002350
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002351 /* Enable GC unless there are really no instance variables possible */
2352 if (!(type->tp_basicsize == sizeof(PyObject) &&
2353 type->tp_itemsize == 0))
2354 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossum9475a232001-10-05 20:51:39 +00002355
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002356 /* Always override allocation strategy to use regular heap */
2357 type->tp_alloc = PyType_GenericAlloc;
2358 if (type->tp_flags & Py_TPFLAGS_HAVE_GC) {
2359 type->tp_free = PyObject_GC_Del;
2360 type->tp_traverse = subtype_traverse;
2361 type->tp_clear = subtype_clear;
2362 }
2363 else
2364 type->tp_free = PyObject_Del;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002365
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002366 /* Initialize the rest */
Victor Stinner6f738742012-02-25 01:22:36 +01002367 if (PyType_Ready(type) < 0)
2368 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002369
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002370 /* Put the proper slots in place */
2371 fixup_slot_dispatchers(type);
Guido van Rossumf040ede2001-08-07 16:40:56 +00002372
Victor Stinner6f738742012-02-25 01:22:36 +01002373 Py_DECREF(dict);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002374 return (PyObject *)type;
Victor Stinner6f738742012-02-25 01:22:36 +01002375
2376error:
2377 Py_XDECREF(dict);
2378 Py_XDECREF(bases);
2379 Py_XDECREF(slots);
2380 Py_XDECREF(type);
2381 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002382}
2383
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002384static short slotoffsets[] = {
2385 -1, /* invalid slot */
2386#include "typeslots.inc"
2387};
2388
Benjamin Petersone28108c2012-01-29 20:13:18 -05002389PyObject *
Martin v. Löwis9c564092012-06-23 23:20:45 +02002390PyType_FromSpecWithBases(PyType_Spec *spec, PyObject *bases)
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002391{
2392 PyHeapTypeObject *res = (PyHeapTypeObject*)PyType_GenericAlloc(&PyType_Type, 0);
Martin v. Löwis9c564092012-06-23 23:20:45 +02002393 PyTypeObject *type, *base;
2394 char *s;
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002395 char *res_start = (char*)res;
2396 PyType_Slot *slot;
Martin v. Löwis9c564092012-06-23 23:20:45 +02002397
2398 /* Set the type name and qualname */
2399 s = strrchr(spec->name, '.');
2400 if (s == NULL)
2401 s = (char*)spec->name;
2402 else
2403 s++;
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002404
Martin v. Löwis5e06a5d2011-02-21 16:24:00 +00002405 if (res == NULL)
Antoine Pitroubb78f572012-06-24 00:18:27 +02002406 return NULL;
2407 type = &res->ht_type;
Antoine Pitrou66a3a7e2012-06-24 00:42:59 +02002408 /* The flags must be initialized early, before the GC traverses us */
2409 type->tp_flags = spec->flags | Py_TPFLAGS_HEAPTYPE;
Martin v. Löwis9c564092012-06-23 23:20:45 +02002410 res->ht_name = PyUnicode_FromString(s);
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002411 if (!res->ht_name)
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002412 goto fail;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002413 res->ht_qualname = res->ht_name;
2414 Py_INCREF(res->ht_qualname);
Antoine Pitroubb78f572012-06-24 00:18:27 +02002415 type->tp_name = spec->name;
2416 if (!type->tp_name)
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002417 goto fail;
Martin v. Löwis9c564092012-06-23 23:20:45 +02002418
2419 /* Adjust for empty tuple bases */
2420 if (!bases) {
2421 base = &PyBaseObject_Type;
2422 /* See whether Py_tp_base(s) was specified */
2423 for (slot = spec->slots; slot->slot; slot++) {
2424 if (slot->slot == Py_tp_base)
2425 base = slot->pfunc;
2426 else if (slot->slot == Py_tp_bases) {
2427 bases = slot->pfunc;
2428 Py_INCREF(bases);
2429 }
2430 }
2431 if (!bases)
2432 bases = PyTuple_Pack(1, base);
2433 if (!bases)
2434 goto fail;
2435 }
2436 else
2437 Py_INCREF(bases);
2438
2439 /* Calculate best base, and check that all bases are type objects */
2440 base = best_base(bases);
2441 if (base == NULL) {
2442 goto fail;
2443 }
2444 if (!PyType_HasFeature(base, Py_TPFLAGS_BASETYPE)) {
2445 PyErr_Format(PyExc_TypeError,
2446 "type '%.100s' is not an acceptable base type",
2447 base->tp_name);
2448 goto fail;
2449 }
2450
Martin v. Löwis9c564092012-06-23 23:20:45 +02002451 /* Initialize essential fields */
2452 type->tp_as_number = &res->as_number;
2453 type->tp_as_sequence = &res->as_sequence;
2454 type->tp_as_mapping = &res->as_mapping;
2455 type->tp_as_buffer = &res->as_buffer;
2456 /* Set tp_base and tp_bases */
2457 type->tp_bases = bases;
2458 bases = NULL;
2459 Py_INCREF(base);
2460 type->tp_base = base;
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002461
Antoine Pitroubb78f572012-06-24 00:18:27 +02002462 type->tp_basicsize = spec->basicsize;
2463 type->tp_itemsize = spec->itemsize;
Victor Stinner0fcab4a2011-01-04 12:59:15 +00002464
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002465 for (slot = spec->slots; slot->slot; slot++) {
Victor Stinner63941882011-09-29 00:42:28 +02002466 if (slot->slot >= Py_ARRAY_LENGTH(slotoffsets)) {
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002467 PyErr_SetString(PyExc_RuntimeError, "invalid slot offset");
2468 goto fail;
2469 }
Martin v. Löwis9c564092012-06-23 23:20:45 +02002470 if (slot->slot == Py_tp_base || slot->slot == Py_tp_bases)
2471 /* Processed above */
2472 continue;
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002473 *(void**)(res_start + slotoffsets[slot->slot]) = slot->pfunc;
Georg Brandl032400b2011-02-19 21:47:02 +00002474
2475 /* need to make a copy of the docstring slot, which usually
2476 points to a static string literal */
2477 if (slot->slot == Py_tp_doc) {
Antoine Pitrou682d94c2012-05-14 14:43:03 +02002478 size_t len = strlen(slot->pfunc)+1;
Georg Brandl032400b2011-02-19 21:47:02 +00002479 char *tp_doc = PyObject_MALLOC(len);
2480 if (tp_doc == NULL)
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002481 goto fail;
Georg Brandl032400b2011-02-19 21:47:02 +00002482 memcpy(tp_doc, slot->pfunc, len);
Antoine Pitroubb78f572012-06-24 00:18:27 +02002483 type->tp_doc = tp_doc;
Georg Brandl032400b2011-02-19 21:47:02 +00002484 }
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002485 }
Antoine Pitroubb78f572012-06-24 00:18:27 +02002486 if (type->tp_dictoffset) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002487 res->ht_cached_keys = _PyDict_NewKeysForClass();
2488 }
Antoine Pitroubb78f572012-06-24 00:18:27 +02002489 if (type->tp_dealloc == NULL) {
Antoine Pitrou99cc6292012-06-23 14:42:38 +02002490 /* It's a heap type, so needs the heap types' dealloc.
2491 subtype_dealloc will call the base type's tp_dealloc, if
2492 necessary. */
Antoine Pitroubb78f572012-06-24 00:18:27 +02002493 type->tp_dealloc = subtype_dealloc;
Antoine Pitrou99cc6292012-06-23 14:42:38 +02002494 }
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002495
Antoine Pitroubb78f572012-06-24 00:18:27 +02002496 if (PyType_Ready(type) < 0)
Benjamin Peterson2652d252012-01-29 20:16:37 -05002497 goto fail;
2498
Martin v. Löwis9c564092012-06-23 23:20:45 +02002499 /* Set type.__module__ */
2500 s = strrchr(spec->name, '.');
2501 if (s != NULL)
2502 _PyDict_SetItemId(type->tp_dict, &PyId___module__,
2503 PyUnicode_FromStringAndSize(
2504 spec->name, (Py_ssize_t)(s - spec->name)));
2505
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002506 return (PyObject*)res;
Victor Stinner0fcab4a2011-01-04 12:59:15 +00002507
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002508 fail:
2509 Py_DECREF(res);
2510 return NULL;
2511}
2512
Martin v. Löwis9c564092012-06-23 23:20:45 +02002513PyObject *
2514PyType_FromSpec(PyType_Spec *spec)
2515{
2516 return PyType_FromSpecWithBases(spec, NULL);
2517}
2518
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002519
Tim Peters6d6c1a32001-08-02 04:15:00 +00002520/* Internal API to look for a name through the MRO.
2521 This returns a borrowed reference, and doesn't set an exception! */
2522PyObject *
2523_PyType_Lookup(PyTypeObject *type, PyObject *name)
2524{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002525 Py_ssize_t i, n;
2526 PyObject *mro, *res, *base, *dict;
2527 unsigned int h;
Christian Heimesa62da1d2008-01-12 19:39:10 +00002528
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002529 if (MCACHE_CACHEABLE_NAME(name) &&
2530 PyType_HasFeature(type, Py_TPFLAGS_VALID_VERSION_TAG)) {
2531 /* fast path */
2532 h = MCACHE_HASH_METHOD(type, name);
2533 if (method_cache[h].version == type->tp_version_tag &&
2534 method_cache[h].name == name)
2535 return method_cache[h].value;
2536 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002537
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002538 /* Look in tp_dict of types in MRO */
2539 mro = type->tp_mro;
Guido van Rossum23094982002-06-10 14:30:43 +00002540
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002541 /* If mro is NULL, the type is either not yet initialized
2542 by PyType_Ready(), or already cleared by type_clear().
2543 Either way the safest thing to do is to return NULL. */
2544 if (mro == NULL)
2545 return NULL;
Guido van Rossum23094982002-06-10 14:30:43 +00002546
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002547 res = NULL;
Victor Stinnerd74782b2012-03-09 00:39:08 +01002548 /* keep a strong reference to mro because type->tp_mro can be replaced
2549 during PyDict_GetItem(dict, name) */
2550 Py_INCREF(mro);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002551 assert(PyTuple_Check(mro));
2552 n = PyTuple_GET_SIZE(mro);
2553 for (i = 0; i < n; i++) {
2554 base = PyTuple_GET_ITEM(mro, i);
2555 assert(PyType_Check(base));
2556 dict = ((PyTypeObject *)base)->tp_dict;
2557 assert(dict && PyDict_Check(dict));
2558 res = PyDict_GetItem(dict, name);
2559 if (res != NULL)
2560 break;
2561 }
Victor Stinnerd74782b2012-03-09 00:39:08 +01002562 Py_DECREF(mro);
Christian Heimesa62da1d2008-01-12 19:39:10 +00002563
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002564 if (MCACHE_CACHEABLE_NAME(name) && assign_version_tag(type)) {
2565 h = MCACHE_HASH_METHOD(type, name);
2566 method_cache[h].version = type->tp_version_tag;
2567 method_cache[h].value = res; /* borrowed */
2568 Py_INCREF(name);
2569 Py_DECREF(method_cache[h].name);
2570 method_cache[h].name = name;
2571 }
2572 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002573}
2574
Victor Stinner3c1e4812012-03-26 22:10:51 +02002575static PyObject *
2576_PyType_LookupId(PyTypeObject *type, struct _Py_Identifier *name)
2577{
2578 PyObject *oname;
2579 oname = _PyUnicode_FromId(name); /* borrowed */
2580 if (oname == NULL)
2581 return NULL;
2582 return _PyType_Lookup(type, oname);
2583}
2584
Tim Peters6d6c1a32001-08-02 04:15:00 +00002585/* This is similar to PyObject_GenericGetAttr(),
2586 but uses _PyType_Lookup() instead of just looking in type->tp_dict. */
2587static PyObject *
2588type_getattro(PyTypeObject *type, PyObject *name)
2589{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002590 PyTypeObject *metatype = Py_TYPE(type);
2591 PyObject *meta_attribute, *attribute;
2592 descrgetfunc meta_get;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002593
Benjamin Peterson16d84ac2012-03-16 09:32:59 -05002594 if (!PyUnicode_Check(name)) {
2595 PyErr_Format(PyExc_TypeError,
2596 "attribute name must be string, not '%.200s'",
2597 name->ob_type->tp_name);
2598 return NULL;
2599 }
2600
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002601 /* Initialize this type (we'll assume the metatype is initialized) */
2602 if (type->tp_dict == NULL) {
2603 if (PyType_Ready(type) < 0)
2604 return NULL;
2605 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002606
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002607 /* No readable descriptor found yet */
2608 meta_get = NULL;
Tim Peters34592512002-07-11 06:23:50 +00002609
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002610 /* Look for the attribute in the metatype */
2611 meta_attribute = _PyType_Lookup(metatype, name);
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002612
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002613 if (meta_attribute != NULL) {
2614 meta_get = Py_TYPE(meta_attribute)->tp_descr_get;
Tim Peters34592512002-07-11 06:23:50 +00002615
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002616 if (meta_get != NULL && PyDescr_IsData(meta_attribute)) {
2617 /* Data descriptors implement tp_descr_set to intercept
2618 * writes. Assume the attribute is not overridden in
2619 * type's tp_dict (and bases): call the descriptor now.
2620 */
2621 return meta_get(meta_attribute, (PyObject *)type,
2622 (PyObject *)metatype);
2623 }
2624 Py_INCREF(meta_attribute);
2625 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002626
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002627 /* No data descriptor found on metatype. Look in tp_dict of this
2628 * type and its bases */
2629 attribute = _PyType_Lookup(type, name);
2630 if (attribute != NULL) {
2631 /* Implement descriptor functionality, if any */
2632 descrgetfunc local_get = Py_TYPE(attribute)->tp_descr_get;
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00002633
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002634 Py_XDECREF(meta_attribute);
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00002635
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002636 if (local_get != NULL) {
2637 /* NULL 2nd argument indicates the descriptor was
2638 * found on the target object itself (or a base) */
2639 return local_get(attribute, (PyObject *)NULL,
2640 (PyObject *)type);
2641 }
Tim Peters34592512002-07-11 06:23:50 +00002642
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002643 Py_INCREF(attribute);
2644 return attribute;
2645 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002646
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002647 /* No attribute found in local __dict__ (or bases): use the
2648 * descriptor from the metatype, if any */
2649 if (meta_get != NULL) {
2650 PyObject *res;
2651 res = meta_get(meta_attribute, (PyObject *)type,
2652 (PyObject *)metatype);
2653 Py_DECREF(meta_attribute);
2654 return res;
2655 }
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002656
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002657 /* If an ordinary attribute was found on the metatype, return it now */
2658 if (meta_attribute != NULL) {
2659 return meta_attribute;
2660 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002661
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002662 /* Give up */
2663 PyErr_Format(PyExc_AttributeError,
2664 "type object '%.50s' has no attribute '%U'",
2665 type->tp_name, name);
2666 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002667}
2668
2669static int
2670type_setattro(PyTypeObject *type, PyObject *name, PyObject *value)
2671{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002672 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
2673 PyErr_Format(
2674 PyExc_TypeError,
2675 "can't set attributes of built-in/extension type '%s'",
2676 type->tp_name);
2677 return -1;
2678 }
2679 if (PyObject_GenericSetAttr((PyObject *)type, name, value) < 0)
2680 return -1;
2681 return update_slot(type, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002682}
2683
Benjamin Peterson64acccf2012-04-27 15:07:36 -04002684extern void
2685_PyDictKeys_DecRef(PyDictKeysObject *keys);
2686
Tim Peters6d6c1a32001-08-02 04:15:00 +00002687static void
2688type_dealloc(PyTypeObject *type)
2689{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002690 PyHeapTypeObject *et;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002691
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002692 /* Assert this is a heap-allocated type object */
2693 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
2694 _PyObject_GC_UNTRACK(type);
2695 PyObject_ClearWeakRefs((PyObject *)type);
2696 et = (PyHeapTypeObject *)type;
2697 Py_XDECREF(type->tp_base);
2698 Py_XDECREF(type->tp_dict);
2699 Py_XDECREF(type->tp_bases);
2700 Py_XDECREF(type->tp_mro);
2701 Py_XDECREF(type->tp_cache);
2702 Py_XDECREF(type->tp_subclasses);
2703 /* A type's tp_doc is heap allocated, unlike the tp_doc slots
2704 * of most other objects. It's okay to cast it to char *.
2705 */
2706 PyObject_Free((char *)type->tp_doc);
2707 Py_XDECREF(et->ht_name);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002708 Py_XDECREF(et->ht_qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002709 Py_XDECREF(et->ht_slots);
Benjamin Peterson64acccf2012-04-27 15:07:36 -04002710 if (et->ht_cached_keys)
2711 _PyDictKeys_DecRef(et->ht_cached_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002712 Py_TYPE(type)->tp_free((PyObject *)type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002713}
2714
Guido van Rossum1c450732001-10-08 15:18:27 +00002715static PyObject *
2716type_subclasses(PyTypeObject *type, PyObject *args_ignored)
2717{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002718 PyObject *list, *raw, *ref;
2719 Py_ssize_t i, n;
Guido van Rossum1c450732001-10-08 15:18:27 +00002720
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002721 list = PyList_New(0);
2722 if (list == NULL)
2723 return NULL;
2724 raw = type->tp_subclasses;
2725 if (raw == NULL)
2726 return list;
2727 assert(PyList_Check(raw));
2728 n = PyList_GET_SIZE(raw);
2729 for (i = 0; i < n; i++) {
2730 ref = PyList_GET_ITEM(raw, i);
2731 assert(PyWeakref_CheckRef(ref));
2732 ref = PyWeakref_GET_OBJECT(ref);
2733 if (ref != Py_None) {
2734 if (PyList_Append(list, ref) < 0) {
2735 Py_DECREF(list);
2736 return NULL;
2737 }
2738 }
2739 }
2740 return list;
Guido van Rossum1c450732001-10-08 15:18:27 +00002741}
2742
Guido van Rossum47374822007-08-02 16:48:17 +00002743static PyObject *
2744type_prepare(PyObject *self, PyObject *args, PyObject *kwds)
2745{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002746 return PyDict_New();
Guido van Rossum47374822007-08-02 16:48:17 +00002747}
2748
Victor Stinner63941882011-09-29 00:42:28 +02002749/*
Benjamin Peterson82b00c12011-05-24 11:09:06 -05002750 Merge the __dict__ of aclass into dict, and recursively also all
2751 the __dict__s of aclass's base classes. The order of merging isn't
2752 defined, as it's expected that only the final set of dict keys is
2753 interesting.
2754 Return 0 on success, -1 on error.
2755*/
2756
2757static int
2758merge_class_dict(PyObject *dict, PyObject *aclass)
2759{
2760 PyObject *classdict;
2761 PyObject *bases;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02002762 _Py_IDENTIFIER(__bases__);
Benjamin Peterson82b00c12011-05-24 11:09:06 -05002763
2764 assert(PyDict_Check(dict));
2765 assert(aclass);
2766
2767 /* Merge in the type's dict (if any). */
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002768 classdict = _PyObject_GetAttrId(aclass, &PyId___dict__);
Benjamin Peterson82b00c12011-05-24 11:09:06 -05002769 if (classdict == NULL)
2770 PyErr_Clear();
2771 else {
2772 int status = PyDict_Update(dict, classdict);
2773 Py_DECREF(classdict);
2774 if (status < 0)
2775 return -1;
2776 }
2777
2778 /* Recursively merge in the base types' (if any) dicts. */
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002779 bases = _PyObject_GetAttrId(aclass, &PyId___bases__);
Benjamin Peterson82b00c12011-05-24 11:09:06 -05002780 if (bases == NULL)
2781 PyErr_Clear();
2782 else {
2783 /* We have no guarantee that bases is a real tuple */
2784 Py_ssize_t i, n;
2785 n = PySequence_Size(bases); /* This better be right */
2786 if (n < 0)
2787 PyErr_Clear();
2788 else {
2789 for (i = 0; i < n; i++) {
2790 int status;
2791 PyObject *base = PySequence_GetItem(bases, i);
2792 if (base == NULL) {
2793 Py_DECREF(bases);
2794 return -1;
2795 }
2796 status = merge_class_dict(dict, base);
2797 Py_DECREF(base);
2798 if (status < 0) {
2799 Py_DECREF(bases);
2800 return -1;
2801 }
2802 }
2803 }
2804 Py_DECREF(bases);
2805 }
2806 return 0;
2807}
2808
2809/* __dir__ for type objects: returns __dict__ and __bases__.
2810 We deliberately don't suck up its __class__, as methods belonging to the
2811 metaclass would probably be more confusing than helpful.
2812*/
2813static PyObject *
2814type_dir(PyObject *self, PyObject *args)
2815{
2816 PyObject *result = NULL;
2817 PyObject *dict = PyDict_New();
2818
2819 if (dict != NULL && merge_class_dict(dict, self) == 0)
2820 result = PyDict_Keys(dict);
2821
2822 Py_XDECREF(dict);
2823 return result;
2824}
2825
Martin v. Loewis4f2f3b62012-04-24 19:13:57 +02002826static PyObject*
2827type_sizeof(PyObject *self, PyObject *args_unused)
2828{
2829 Py_ssize_t size;
2830 PyTypeObject *type = (PyTypeObject*)self;
2831 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
2832 PyHeapTypeObject* et = (PyHeapTypeObject*)type;
2833 size = sizeof(PyHeapTypeObject);
2834 if (et->ht_cached_keys)
2835 size += _PyDict_KeysSize(et->ht_cached_keys);
2836 }
2837 else
2838 size = sizeof(PyTypeObject);
2839 return PyLong_FromSsize_t(size);
2840}
2841
Tim Peters6d6c1a32001-08-02 04:15:00 +00002842static PyMethodDef type_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002843 {"mro", (PyCFunction)mro_external, METH_NOARGS,
2844 PyDoc_STR("mro() -> list\nreturn a type's method resolution order")},
2845 {"__subclasses__", (PyCFunction)type_subclasses, METH_NOARGS,
2846 PyDoc_STR("__subclasses__() -> list of immediate subclasses")},
2847 {"__prepare__", (PyCFunction)type_prepare,
2848 METH_VARARGS | METH_KEYWORDS | METH_CLASS,
2849 PyDoc_STR("__prepare__() -> dict\n"
2850 "used to create the namespace for the class statement")},
2851 {"__instancecheck__", type___instancecheck__, METH_O,
Benjamin Petersonfbe56bb2011-05-24 12:42:51 -05002852 PyDoc_STR("__instancecheck__() -> bool\ncheck if an object is an instance")},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002853 {"__subclasscheck__", type___subclasscheck__, METH_O,
Benjamin Petersonfbe56bb2011-05-24 12:42:51 -05002854 PyDoc_STR("__subclasscheck__() -> bool\ncheck if a class is a subclass")},
Benjamin Peterson82b00c12011-05-24 11:09:06 -05002855 {"__dir__", type_dir, METH_NOARGS,
Benjamin Petersonc7284122011-05-24 12:46:15 -05002856 PyDoc_STR("__dir__() -> list\nspecialized __dir__ implementation for types")},
Martin v. Loewis4f2f3b62012-04-24 19:13:57 +02002857 {"__sizeof__", type_sizeof, METH_NOARGS,
2858 "__sizeof__() -> int\nreturn memory consumption of the type object"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002859 {0}
Tim Peters6d6c1a32001-08-02 04:15:00 +00002860};
2861
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002862PyDoc_STRVAR(type_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00002863"type(object) -> the object's type\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002864"type(name, bases, dict) -> a new type");
Tim Peters6d6c1a32001-08-02 04:15:00 +00002865
Guido van Rossum048eb752001-10-02 21:24:57 +00002866static int
2867type_traverse(PyTypeObject *type, visitproc visit, void *arg)
2868{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002869 /* Because of type_is_gc(), the collector only calls this
2870 for heaptypes. */
Antoine Pitrou1351ca62012-06-24 00:30:12 +02002871 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
2872 char msg[200];
2873 sprintf(msg, "type_traverse() called for non-heap type '%.100s'",
2874 type->tp_name);
2875 Py_FatalError(msg);
2876 }
Guido van Rossum048eb752001-10-02 21:24:57 +00002877
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002878 Py_VISIT(type->tp_dict);
2879 Py_VISIT(type->tp_cache);
2880 Py_VISIT(type->tp_mro);
2881 Py_VISIT(type->tp_bases);
2882 Py_VISIT(type->tp_base);
Guido van Rossuma3862092002-06-10 15:24:42 +00002883
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002884 /* There's no need to visit type->tp_subclasses or
2885 ((PyHeapTypeObject *)type)->ht_slots, because they can't be involved
2886 in cycles; tp_subclasses is a list of weak references,
2887 and slots is a tuple of strings. */
Guido van Rossum048eb752001-10-02 21:24:57 +00002888
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002889 return 0;
Guido van Rossum048eb752001-10-02 21:24:57 +00002890}
2891
2892static int
2893type_clear(PyTypeObject *type)
2894{
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002895 PyDictKeysObject *cached_keys;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002896 /* Because of type_is_gc(), the collector only calls this
2897 for heaptypes. */
2898 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002899
Antoine Pitrou2e872082011-12-15 14:15:31 +01002900 /* We need to invalidate the method cache carefully before clearing
2901 the dict, so that other objects caught in a reference cycle
2902 don't start calling destroyed methods.
2903
2904 Otherwise, the only field we need to clear is tp_mro, which is
2905 part of a hard cycle (its first element is the class itself) that
2906 won't be broken otherwise (it's a tuple and tuples don't have a
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002907 tp_clear handler). None of the other fields need to be
2908 cleared, and here's why:
Guido van Rossum048eb752001-10-02 21:24:57 +00002909
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002910 tp_cache:
2911 Not used; if it were, it would be a dict.
Guido van Rossuma3862092002-06-10 15:24:42 +00002912
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002913 tp_bases, tp_base:
2914 If these are involved in a cycle, there must be at least
2915 one other, mutable object in the cycle, e.g. a base
2916 class's dict; the cycle will be broken that way.
Guido van Rossuma3862092002-06-10 15:24:42 +00002917
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002918 tp_subclasses:
2919 A list of weak references can't be part of a cycle; and
2920 lists have their own tp_clear.
Guido van Rossuma3862092002-06-10 15:24:42 +00002921
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002922 slots (in PyHeapTypeObject):
2923 A tuple of strings can't be part of a cycle.
2924 */
Guido van Rossuma3862092002-06-10 15:24:42 +00002925
Antoine Pitrou2e872082011-12-15 14:15:31 +01002926 PyType_Modified(type);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002927 cached_keys = ((PyHeapTypeObject *)type)->ht_cached_keys;
2928 if (cached_keys != NULL) {
2929 ((PyHeapTypeObject *)type)->ht_cached_keys = NULL;
2930 _PyDictKeys_DecRef(cached_keys);
2931 }
Antoine Pitrou2e872082011-12-15 14:15:31 +01002932 if (type->tp_dict)
2933 PyDict_Clear(type->tp_dict);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002934 Py_CLEAR(type->tp_mro);
Guido van Rossum048eb752001-10-02 21:24:57 +00002935
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002936 return 0;
Guido van Rossum048eb752001-10-02 21:24:57 +00002937}
2938
2939static int
2940type_is_gc(PyTypeObject *type)
2941{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002942 return type->tp_flags & Py_TPFLAGS_HEAPTYPE;
Guido van Rossum048eb752001-10-02 21:24:57 +00002943}
2944
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002945PyTypeObject PyType_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002946 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2947 "type", /* tp_name */
2948 sizeof(PyHeapTypeObject), /* tp_basicsize */
2949 sizeof(PyMemberDef), /* tp_itemsize */
2950 (destructor)type_dealloc, /* tp_dealloc */
2951 0, /* tp_print */
2952 0, /* tp_getattr */
2953 0, /* tp_setattr */
2954 0, /* tp_reserved */
2955 (reprfunc)type_repr, /* tp_repr */
2956 0, /* tp_as_number */
2957 0, /* tp_as_sequence */
2958 0, /* tp_as_mapping */
2959 0, /* tp_hash */
2960 (ternaryfunc)type_call, /* tp_call */
2961 0, /* tp_str */
2962 (getattrofunc)type_getattro, /* tp_getattro */
2963 (setattrofunc)type_setattro, /* tp_setattro */
2964 0, /* tp_as_buffer */
2965 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
2966 Py_TPFLAGS_BASETYPE | Py_TPFLAGS_TYPE_SUBCLASS, /* tp_flags */
2967 type_doc, /* tp_doc */
2968 (traverseproc)type_traverse, /* tp_traverse */
2969 (inquiry)type_clear, /* tp_clear */
2970 0, /* tp_richcompare */
2971 offsetof(PyTypeObject, tp_weaklist), /* tp_weaklistoffset */
2972 0, /* tp_iter */
2973 0, /* tp_iternext */
2974 type_methods, /* tp_methods */
2975 type_members, /* tp_members */
2976 type_getsets, /* tp_getset */
2977 0, /* tp_base */
2978 0, /* tp_dict */
2979 0, /* tp_descr_get */
2980 0, /* tp_descr_set */
2981 offsetof(PyTypeObject, tp_dict), /* tp_dictoffset */
2982 type_init, /* tp_init */
2983 0, /* tp_alloc */
2984 type_new, /* tp_new */
2985 PyObject_GC_Del, /* tp_free */
2986 (inquiry)type_is_gc, /* tp_is_gc */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002987};
Tim Peters6d6c1a32001-08-02 04:15:00 +00002988
2989
2990/* The base type of all types (eventually)... except itself. */
2991
Guido van Rossumd8faa362007-04-27 19:54:29 +00002992/* You may wonder why object.__new__() only complains about arguments
2993 when object.__init__() is not overridden, and vice versa.
2994
2995 Consider the use cases:
2996
2997 1. When neither is overridden, we want to hear complaints about
2998 excess (i.e., any) arguments, since their presence could
2999 indicate there's a bug.
3000
3001 2. When defining an Immutable type, we are likely to override only
3002 __new__(), since __init__() is called too late to initialize an
3003 Immutable object. Since __new__() defines the signature for the
3004 type, it would be a pain to have to override __init__() just to
3005 stop it from complaining about excess arguments.
3006
3007 3. When defining a Mutable type, we are likely to override only
3008 __init__(). So here the converse reasoning applies: we don't
3009 want to have to override __new__() just to stop it from
3010 complaining.
3011
3012 4. When __init__() is overridden, and the subclass __init__() calls
3013 object.__init__(), the latter should complain about excess
3014 arguments; ditto for __new__().
3015
3016 Use cases 2 and 3 make it unattractive to unconditionally check for
3017 excess arguments. The best solution that addresses all four use
3018 cases is as follows: __init__() complains about excess arguments
3019 unless __new__() is overridden and __init__() is not overridden
3020 (IOW, if __init__() is overridden or __new__() is not overridden);
3021 symmetrically, __new__() complains about excess arguments unless
3022 __init__() is overridden and __new__() is not overridden
3023 (IOW, if __new__() is overridden or __init__() is not overridden).
3024
3025 However, for backwards compatibility, this breaks too much code.
3026 Therefore, in 2.6, we'll *warn* about excess arguments when both
3027 methods are overridden; for all other cases we'll use the above
3028 rules.
3029
3030*/
3031
3032/* Forward */
3033static PyObject *
3034object_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
3035
3036static int
3037excess_args(PyObject *args, PyObject *kwds)
3038{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003039 return PyTuple_GET_SIZE(args) ||
3040 (kwds && PyDict_Check(kwds) && PyDict_Size(kwds));
Guido van Rossumd8faa362007-04-27 19:54:29 +00003041}
3042
Tim Peters6d6c1a32001-08-02 04:15:00 +00003043static int
3044object_init(PyObject *self, PyObject *args, PyObject *kwds)
3045{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003046 int err = 0;
Benjamin Peterson96384b92012-03-17 00:05:44 -05003047 PyTypeObject *type = Py_TYPE(self);
3048 if (excess_args(args, kwds) &&
3049 (type->tp_new == object_new || type->tp_init != object_init)) {
3050 PyErr_SetString(PyExc_TypeError, "object.__init__() takes no parameters");
3051 err = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003052 }
3053 return err;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003054}
3055
Guido van Rossum298e4212003-02-13 16:30:16 +00003056static PyObject *
3057object_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3058{
Benjamin Peterson96384b92012-03-17 00:05:44 -05003059 if (excess_args(args, kwds) &&
3060 (type->tp_init == object_init || type->tp_new != object_new)) {
3061 PyErr_SetString(PyExc_TypeError, "object.__new__() takes no parameters");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003062 return NULL;
Benjamin Peterson96384b92012-03-17 00:05:44 -05003063 }
Victor Stinner3c1e4812012-03-26 22:10:51 +02003064
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003065 if (type->tp_flags & Py_TPFLAGS_IS_ABSTRACT) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003066 PyObject *abstract_methods = NULL;
3067 PyObject *builtins;
3068 PyObject *sorted;
3069 PyObject *sorted_methods = NULL;
3070 PyObject *joined = NULL;
Benjamin Peterson9a03ecf2012-03-16 20:15:54 -05003071 PyObject *comma;
3072 _Py_static_string(comma_id, ", ");
Victor Stinner3c1e4812012-03-26 22:10:51 +02003073 _Py_IDENTIFIER(sorted);
Christian Heimes9e7f1d22008-02-28 12:27:11 +00003074
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003075 /* Compute ", ".join(sorted(type.__abstractmethods__))
3076 into joined. */
3077 abstract_methods = type_abstractmethods(type, NULL);
3078 if (abstract_methods == NULL)
3079 goto error;
3080 builtins = PyEval_GetBuiltins();
3081 if (builtins == NULL)
3082 goto error;
Victor Stinner3c1e4812012-03-26 22:10:51 +02003083 sorted = _PyDict_GetItemId(builtins, &PyId_sorted);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003084 if (sorted == NULL)
3085 goto error;
3086 sorted_methods = PyObject_CallFunctionObjArgs(sorted,
3087 abstract_methods,
3088 NULL);
3089 if (sorted_methods == NULL)
3090 goto error;
Benjamin Peterson9a03ecf2012-03-16 20:15:54 -05003091 comma = _PyUnicode_FromId(&comma_id);
3092 if (comma == NULL)
3093 goto error;
3094 joined = PyUnicode_Join(comma, sorted_methods);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003095 if (joined == NULL)
3096 goto error;
Christian Heimes9e7f1d22008-02-28 12:27:11 +00003097
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003098 PyErr_Format(PyExc_TypeError,
3099 "Can't instantiate abstract class %s "
3100 "with abstract methods %U",
3101 type->tp_name,
3102 joined);
3103 error:
3104 Py_XDECREF(joined);
3105 Py_XDECREF(sorted_methods);
3106 Py_XDECREF(abstract_methods);
3107 return NULL;
3108 }
3109 return type->tp_alloc(type, 0);
Guido van Rossum298e4212003-02-13 16:30:16 +00003110}
3111
Tim Peters6d6c1a32001-08-02 04:15:00 +00003112static void
3113object_dealloc(PyObject *self)
3114{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003115 Py_TYPE(self)->tp_free(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003116}
3117
Guido van Rossum8e248182001-08-12 05:17:56 +00003118static PyObject *
3119object_repr(PyObject *self)
3120{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003121 PyTypeObject *type;
3122 PyObject *mod, *name, *rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00003123
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003124 type = Py_TYPE(self);
3125 mod = type_module(type, NULL);
3126 if (mod == NULL)
3127 PyErr_Clear();
3128 else if (!PyUnicode_Check(mod)) {
3129 Py_DECREF(mod);
3130 mod = NULL;
3131 }
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003132 name = type_qualname(type, NULL);
Christian Heimese81dc292012-09-10 16:57:36 +02003133 if (name == NULL) {
3134 Py_XDECREF(mod);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003135 return NULL;
Christian Heimese81dc292012-09-10 16:57:36 +02003136 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003137 if (mod != NULL && PyUnicode_CompareWithASCIIString(mod, "builtins"))
3138 rtn = PyUnicode_FromFormat("<%U.%U object at %p>", mod, name, self);
3139 else
3140 rtn = PyUnicode_FromFormat("<%s object at %p>",
3141 type->tp_name, self);
3142 Py_XDECREF(mod);
3143 Py_DECREF(name);
3144 return rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00003145}
3146
Guido van Rossumb8f63662001-08-15 23:57:02 +00003147static PyObject *
3148object_str(PyObject *self)
3149{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003150 unaryfunc f;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003151
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003152 f = Py_TYPE(self)->tp_repr;
Benjamin Peterson7b166872012-04-24 11:06:25 -04003153 if (f == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003154 f = object_repr;
3155 return f(self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003156}
3157
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003158static PyObject *
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003159object_richcompare(PyObject *self, PyObject *other, int op)
3160{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003161 PyObject *res;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003162
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003163 switch (op) {
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003164
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003165 case Py_EQ:
3166 /* Return NotImplemented instead of False, so if two
3167 objects are compared, both get a chance at the
3168 comparison. See issue #1393. */
3169 res = (self == other) ? Py_True : Py_NotImplemented;
3170 Py_INCREF(res);
3171 break;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003172
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003173 case Py_NE:
3174 /* By default, != returns the opposite of ==,
3175 unless the latter returns NotImplemented. */
3176 res = PyObject_RichCompare(self, other, Py_EQ);
3177 if (res != NULL && res != Py_NotImplemented) {
3178 int ok = PyObject_IsTrue(res);
3179 Py_DECREF(res);
3180 if (ok < 0)
3181 res = NULL;
3182 else {
3183 if (ok)
3184 res = Py_False;
3185 else
3186 res = Py_True;
3187 Py_INCREF(res);
3188 }
3189 }
3190 break;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003191
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003192 default:
3193 res = Py_NotImplemented;
3194 Py_INCREF(res);
3195 break;
3196 }
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003197
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003198 return res;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003199}
3200
3201static PyObject *
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003202object_get_class(PyObject *self, void *closure)
3203{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003204 Py_INCREF(Py_TYPE(self));
3205 return (PyObject *)(Py_TYPE(self));
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003206}
3207
3208static int
3209equiv_structs(PyTypeObject *a, PyTypeObject *b)
3210{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003211 return a == b ||
3212 (a != NULL &&
3213 b != NULL &&
3214 a->tp_basicsize == b->tp_basicsize &&
3215 a->tp_itemsize == b->tp_itemsize &&
3216 a->tp_dictoffset == b->tp_dictoffset &&
3217 a->tp_weaklistoffset == b->tp_weaklistoffset &&
3218 ((a->tp_flags & Py_TPFLAGS_HAVE_GC) ==
3219 (b->tp_flags & Py_TPFLAGS_HAVE_GC)));
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003220}
3221
3222static int
3223same_slots_added(PyTypeObject *a, PyTypeObject *b)
3224{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003225 PyTypeObject *base = a->tp_base;
3226 Py_ssize_t size;
3227 PyObject *slots_a, *slots_b;
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003228
Benjamin Peterson67641d22011-01-17 19:24:34 +00003229 assert(base == b->tp_base);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003230 size = base->tp_basicsize;
3231 if (a->tp_dictoffset == size && b->tp_dictoffset == size)
3232 size += sizeof(PyObject *);
3233 if (a->tp_weaklistoffset == size && b->tp_weaklistoffset == size)
3234 size += sizeof(PyObject *);
Guido van Rossumd8faa362007-04-27 19:54:29 +00003235
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003236 /* Check slots compliance */
3237 slots_a = ((PyHeapTypeObject *)a)->ht_slots;
3238 slots_b = ((PyHeapTypeObject *)b)->ht_slots;
3239 if (slots_a && slots_b) {
3240 if (PyObject_RichCompareBool(slots_a, slots_b, Py_EQ) != 1)
3241 return 0;
3242 size += sizeof(PyObject *) * PyTuple_GET_SIZE(slots_a);
3243 }
3244 return size == a->tp_basicsize && size == b->tp_basicsize;
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003245}
3246
3247static int
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003248compatible_for_assignment(PyTypeObject* oldto, PyTypeObject* newto, char* attr)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003249{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003250 PyTypeObject *newbase, *oldbase;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003251
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003252 if (newto->tp_dealloc != oldto->tp_dealloc ||
3253 newto->tp_free != oldto->tp_free)
3254 {
3255 PyErr_Format(PyExc_TypeError,
3256 "%s assignment: "
3257 "'%s' deallocator differs from '%s'",
3258 attr,
3259 newto->tp_name,
3260 oldto->tp_name);
3261 return 0;
3262 }
3263 newbase = newto;
3264 oldbase = oldto;
3265 while (equiv_structs(newbase, newbase->tp_base))
3266 newbase = newbase->tp_base;
3267 while (equiv_structs(oldbase, oldbase->tp_base))
3268 oldbase = oldbase->tp_base;
3269 if (newbase != oldbase &&
3270 (newbase->tp_base != oldbase->tp_base ||
3271 !same_slots_added(newbase, oldbase))) {
3272 PyErr_Format(PyExc_TypeError,
3273 "%s assignment: "
3274 "'%s' object layout differs from '%s'",
3275 attr,
3276 newto->tp_name,
3277 oldto->tp_name);
3278 return 0;
3279 }
Tim Petersea7f75d2002-12-07 21:39:16 +00003280
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003281 return 1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003282}
3283
3284static int
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003285object_set_class(PyObject *self, PyObject *value, void *closure)
3286{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003287 PyTypeObject *oldto = Py_TYPE(self);
3288 PyTypeObject *newto;
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003289
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003290 if (value == NULL) {
3291 PyErr_SetString(PyExc_TypeError,
3292 "can't delete __class__ attribute");
3293 return -1;
3294 }
3295 if (!PyType_Check(value)) {
3296 PyErr_Format(PyExc_TypeError,
Florent Xiclunaaa6c1d22011-12-12 18:54:29 +01003297 "__class__ must be set to a class, not '%s' object",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003298 Py_TYPE(value)->tp_name);
3299 return -1;
3300 }
3301 newto = (PyTypeObject *)value;
3302 if (!(newto->tp_flags & Py_TPFLAGS_HEAPTYPE) ||
3303 !(oldto->tp_flags & Py_TPFLAGS_HEAPTYPE))
3304 {
3305 PyErr_Format(PyExc_TypeError,
3306 "__class__ assignment: only for heap types");
3307 return -1;
3308 }
3309 if (compatible_for_assignment(newto, oldto, "__class__")) {
3310 Py_INCREF(newto);
3311 Py_TYPE(self) = newto;
3312 Py_DECREF(oldto);
3313 return 0;
3314 }
3315 else {
3316 return -1;
3317 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003318}
3319
3320static PyGetSetDef object_getsets[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003321 {"__class__", object_get_class, object_set_class,
3322 PyDoc_STR("the object's class")},
3323 {0}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003324};
3325
Guido van Rossumc53f0092003-02-18 22:05:12 +00003326
Guido van Rossum036f9992003-02-21 22:02:54 +00003327/* Stuff to implement __reduce_ex__ for pickle protocols >= 2.
Alexandre Vassalottif7fa63d2008-05-11 08:55:36 +00003328 We fall back to helpers in copyreg for:
Guido van Rossum036f9992003-02-21 22:02:54 +00003329 - pickle protocols < 2
3330 - calculating the list of slot names (done only once per class)
3331 - the __newobj__ function (which is used as a token but never called)
3332*/
3333
3334static PyObject *
Alexandre Vassalottif7fa63d2008-05-11 08:55:36 +00003335import_copyreg(void)
Guido van Rossum036f9992003-02-21 22:02:54 +00003336{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003337 static PyObject *copyreg_str;
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003338 static PyObject *mod_copyreg = NULL;
Guido van Rossum3926a632001-09-25 16:25:58 +00003339
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003340 if (!copyreg_str) {
3341 copyreg_str = PyUnicode_InternFromString("copyreg");
3342 if (copyreg_str == NULL)
3343 return NULL;
3344 }
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003345 if (!mod_copyreg) {
3346 mod_copyreg = PyImport_Import(copyreg_str);
3347 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003348
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003349 Py_XINCREF(mod_copyreg);
3350 return mod_copyreg;
Guido van Rossum036f9992003-02-21 22:02:54 +00003351}
3352
3353static PyObject *
3354slotnames(PyObject *cls)
3355{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003356 PyObject *clsdict;
3357 PyObject *copyreg;
3358 PyObject *slotnames;
Victor Stinner3c1e4812012-03-26 22:10:51 +02003359 _Py_IDENTIFIER(__slotnames__);
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02003360 _Py_IDENTIFIER(_slotnames);
Guido van Rossum036f9992003-02-21 22:02:54 +00003361
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003362 clsdict = ((PyTypeObject *)cls)->tp_dict;
Victor Stinner3c1e4812012-03-26 22:10:51 +02003363 slotnames = _PyDict_GetItemId(clsdict, &PyId___slotnames__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003364 if (slotnames != NULL && PyList_Check(slotnames)) {
3365 Py_INCREF(slotnames);
3366 return slotnames;
3367 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003368
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003369 copyreg = import_copyreg();
3370 if (copyreg == NULL)
3371 return NULL;
Guido van Rossum036f9992003-02-21 22:02:54 +00003372
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02003373 slotnames = _PyObject_CallMethodId(copyreg, &PyId__slotnames, "O", cls);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003374 Py_DECREF(copyreg);
3375 if (slotnames != NULL &&
3376 slotnames != Py_None &&
3377 !PyList_Check(slotnames))
3378 {
3379 PyErr_SetString(PyExc_TypeError,
3380 "copyreg._slotnames didn't return a list or None");
3381 Py_DECREF(slotnames);
3382 slotnames = NULL;
3383 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003384
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003385 return slotnames;
Guido van Rossum036f9992003-02-21 22:02:54 +00003386}
3387
3388static PyObject *
3389reduce_2(PyObject *obj)
3390{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003391 PyObject *cls, *getnewargs;
3392 PyObject *args = NULL, *args2 = NULL;
3393 PyObject *getstate = NULL, *state = NULL, *names = NULL;
3394 PyObject *slots = NULL, *listitems = NULL, *dictitems = NULL;
3395 PyObject *copyreg = NULL, *newobj = NULL, *res = NULL;
3396 Py_ssize_t i, n;
Victor Stinner3c1e4812012-03-26 22:10:51 +02003397 _Py_IDENTIFIER(__getnewargs__);
3398 _Py_IDENTIFIER(__getstate__);
3399 _Py_IDENTIFIER(__newobj__);
Guido van Rossum036f9992003-02-21 22:02:54 +00003400
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003401 cls = (PyObject *) Py_TYPE(obj);
3402
Victor Stinner3c1e4812012-03-26 22:10:51 +02003403 getnewargs = _PyObject_GetAttrId(obj, &PyId___getnewargs__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003404 if (getnewargs != NULL) {
3405 args = PyObject_CallObject(getnewargs, NULL);
3406 Py_DECREF(getnewargs);
3407 if (args != NULL && !PyTuple_Check(args)) {
3408 PyErr_Format(PyExc_TypeError,
3409 "__getnewargs__ should return a tuple, "
3410 "not '%.200s'", Py_TYPE(args)->tp_name);
3411 goto end;
3412 }
3413 }
3414 else {
3415 PyErr_Clear();
3416 args = PyTuple_New(0);
3417 }
3418 if (args == NULL)
3419 goto end;
Guido van Rossum036f9992003-02-21 22:02:54 +00003420
Victor Stinner3c1e4812012-03-26 22:10:51 +02003421 getstate = _PyObject_GetAttrId(obj, &PyId___getstate__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003422 if (getstate != NULL) {
3423 state = PyObject_CallObject(getstate, NULL);
3424 Py_DECREF(getstate);
3425 if (state == NULL)
3426 goto end;
3427 }
3428 else {
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003429 PyObject **dict;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003430 PyErr_Clear();
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003431 dict = _PyObject_GetDictPtr(obj);
3432 if (dict && *dict)
3433 state = *dict;
3434 else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003435 state = Py_None;
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003436 Py_INCREF(state);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003437 names = slotnames(cls);
3438 if (names == NULL)
3439 goto end;
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003440 if (names != Py_None && PyList_GET_SIZE(names) > 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003441 assert(PyList_Check(names));
3442 slots = PyDict_New();
3443 if (slots == NULL)
3444 goto end;
3445 n = 0;
3446 /* Can't pre-compute the list size; the list
3447 is stored on the class so accessible to other
3448 threads, which may be run by DECREF */
3449 for (i = 0; i < PyList_GET_SIZE(names); i++) {
3450 PyObject *name, *value;
3451 name = PyList_GET_ITEM(names, i);
3452 value = PyObject_GetAttr(obj, name);
3453 if (value == NULL)
3454 PyErr_Clear();
3455 else {
3456 int err = PyDict_SetItem(slots, name,
3457 value);
3458 Py_DECREF(value);
3459 if (err)
3460 goto end;
3461 n++;
3462 }
3463 }
3464 if (n) {
3465 state = Py_BuildValue("(NO)", state, slots);
3466 if (state == NULL)
3467 goto end;
3468 }
3469 }
3470 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003471
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003472 if (!PyList_Check(obj)) {
3473 listitems = Py_None;
3474 Py_INCREF(listitems);
3475 }
3476 else {
3477 listitems = PyObject_GetIter(obj);
3478 if (listitems == NULL)
3479 goto end;
3480 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003481
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003482 if (!PyDict_Check(obj)) {
3483 dictitems = Py_None;
3484 Py_INCREF(dictitems);
3485 }
3486 else {
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02003487 _Py_IDENTIFIER(items);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02003488 PyObject *items = _PyObject_CallMethodId(obj, &PyId_items, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003489 if (items == NULL)
3490 goto end;
3491 dictitems = PyObject_GetIter(items);
3492 Py_DECREF(items);
3493 if (dictitems == NULL)
3494 goto end;
3495 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003496
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003497 copyreg = import_copyreg();
3498 if (copyreg == NULL)
3499 goto end;
Victor Stinner3c1e4812012-03-26 22:10:51 +02003500 newobj = _PyObject_GetAttrId(copyreg, &PyId___newobj__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003501 if (newobj == NULL)
3502 goto end;
Guido van Rossum036f9992003-02-21 22:02:54 +00003503
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003504 n = PyTuple_GET_SIZE(args);
3505 args2 = PyTuple_New(n+1);
3506 if (args2 == NULL)
3507 goto end;
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003508 Py_INCREF(cls);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003509 PyTuple_SET_ITEM(args2, 0, cls);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003510 for (i = 0; i < n; i++) {
3511 PyObject *v = PyTuple_GET_ITEM(args, i);
3512 Py_INCREF(v);
3513 PyTuple_SET_ITEM(args2, i+1, v);
3514 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003515
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003516 res = PyTuple_Pack(5, newobj, args2, state, listitems, dictitems);
Guido van Rossum036f9992003-02-21 22:02:54 +00003517
3518 end:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003519 Py_XDECREF(args);
3520 Py_XDECREF(args2);
3521 Py_XDECREF(slots);
3522 Py_XDECREF(state);
3523 Py_XDECREF(names);
3524 Py_XDECREF(listitems);
3525 Py_XDECREF(dictitems);
3526 Py_XDECREF(copyreg);
3527 Py_XDECREF(newobj);
3528 return res;
Guido van Rossum036f9992003-02-21 22:02:54 +00003529}
3530
Guido van Rossumd8faa362007-04-27 19:54:29 +00003531/*
3532 * There were two problems when object.__reduce__ and object.__reduce_ex__
3533 * were implemented in the same function:
3534 * - trying to pickle an object with a custom __reduce__ method that
3535 * fell back to object.__reduce__ in certain circumstances led to
3536 * infinite recursion at Python level and eventual RuntimeError.
3537 * - Pickling objects that lied about their type by overwriting the
3538 * __class__ descriptor could lead to infinite recursion at C level
3539 * and eventual segfault.
3540 *
3541 * Because of backwards compatibility, the two methods still have to
3542 * behave in the same way, even if this is not required by the pickle
3543 * protocol. This common functionality was moved to the _common_reduce
3544 * function.
3545 */
3546static PyObject *
3547_common_reduce(PyObject *self, int proto)
3548{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003549 PyObject *copyreg, *res;
Guido van Rossumd8faa362007-04-27 19:54:29 +00003550
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003551 if (proto >= 2)
3552 return reduce_2(self);
Guido van Rossumd8faa362007-04-27 19:54:29 +00003553
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003554 copyreg = import_copyreg();
3555 if (!copyreg)
3556 return NULL;
Guido van Rossumd8faa362007-04-27 19:54:29 +00003557
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003558 res = PyEval_CallMethod(copyreg, "_reduce_ex", "(Oi)", self, proto);
3559 Py_DECREF(copyreg);
Guido van Rossumd8faa362007-04-27 19:54:29 +00003560
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003561 return res;
Guido van Rossumd8faa362007-04-27 19:54:29 +00003562}
3563
3564static PyObject *
3565object_reduce(PyObject *self, PyObject *args)
3566{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003567 int proto = 0;
Guido van Rossumd8faa362007-04-27 19:54:29 +00003568
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003569 if (!PyArg_ParseTuple(args, "|i:__reduce__", &proto))
3570 return NULL;
Guido van Rossumd8faa362007-04-27 19:54:29 +00003571
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003572 return _common_reduce(self, proto);
Guido van Rossumd8faa362007-04-27 19:54:29 +00003573}
3574
Guido van Rossum036f9992003-02-21 22:02:54 +00003575static PyObject *
3576object_reduce_ex(PyObject *self, PyObject *args)
3577{
Victor Stinner3c1e4812012-03-26 22:10:51 +02003578 static PyObject *objreduce;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003579 PyObject *reduce, *res;
3580 int proto = 0;
Victor Stinner3c1e4812012-03-26 22:10:51 +02003581 _Py_IDENTIFIER(__reduce__);
Guido van Rossum036f9992003-02-21 22:02:54 +00003582
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003583 if (!PyArg_ParseTuple(args, "|i:__reduce_ex__", &proto))
3584 return NULL;
Guido van Rossum036f9992003-02-21 22:02:54 +00003585
Victor Stinner3c1e4812012-03-26 22:10:51 +02003586 if (objreduce == NULL) {
3587 objreduce = _PyDict_GetItemId(PyBaseObject_Type.tp_dict,
3588 &PyId___reduce__);
3589 if (objreduce == NULL)
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003590 return NULL;
3591 }
3592
Victor Stinner3c1e4812012-03-26 22:10:51 +02003593 reduce = _PyObject_GetAttrId(self, &PyId___reduce__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003594 if (reduce == NULL)
3595 PyErr_Clear();
3596 else {
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003597 PyObject *cls, *clsreduce;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003598 int override;
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003599
3600 cls = (PyObject *) Py_TYPE(self);
Victor Stinner3c1e4812012-03-26 22:10:51 +02003601 clsreduce = _PyObject_GetAttrId(cls, &PyId___reduce__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003602 if (clsreduce == NULL) {
3603 Py_DECREF(reduce);
3604 return NULL;
3605 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003606 override = (clsreduce != objreduce);
3607 Py_DECREF(clsreduce);
3608 if (override) {
3609 res = PyObject_CallObject(reduce, NULL);
3610 Py_DECREF(reduce);
3611 return res;
3612 }
3613 else
3614 Py_DECREF(reduce);
3615 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003616
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003617 return _common_reduce(self, proto);
Guido van Rossum3926a632001-09-25 16:25:58 +00003618}
3619
Christian Heimes9e7f1d22008-02-28 12:27:11 +00003620static PyObject *
3621object_subclasshook(PyObject *cls, PyObject *args)
3622{
Brian Curtindfc80e32011-08-10 20:28:54 -05003623 Py_RETURN_NOTIMPLEMENTED;
Christian Heimes9e7f1d22008-02-28 12:27:11 +00003624}
3625
3626PyDoc_STRVAR(object_subclasshook_doc,
3627"Abstract classes can override this to customize issubclass().\n"
3628"\n"
3629"This is invoked early on by abc.ABCMeta.__subclasscheck__().\n"
3630"It should return True, False or NotImplemented. If it returns\n"
3631"NotImplemented, the normal algorithm is used. Otherwise, it\n"
3632"overrides the normal algorithm (and the outcome is cached).\n");
Eric Smith8c663262007-08-25 02:26:07 +00003633
3634/*
3635 from PEP 3101, this code implements:
3636
3637 class object:
3638 def __format__(self, format_spec):
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003639 return format(str(self), format_spec)
Eric Smith8c663262007-08-25 02:26:07 +00003640*/
3641static PyObject *
3642object_format(PyObject *self, PyObject *args)
3643{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003644 PyObject *format_spec;
3645 PyObject *self_as_str = NULL;
3646 PyObject *result = NULL;
Eric Smith8c663262007-08-25 02:26:07 +00003647
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003648 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
3649 return NULL;
Eric Smith8c663262007-08-25 02:26:07 +00003650
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003651 self_as_str = PyObject_Str(self);
Eric Smithe4d63172010-09-13 20:48:43 +00003652 if (self_as_str != NULL) {
3653 /* Issue 7994: If we're converting to a string, we
Eric V. Smithb9cd3532011-03-12 10:08:48 -05003654 should reject format specifications */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003655 if (PyUnicode_GET_LENGTH(format_spec) > 0) {
Eric V. Smithb9cd3532011-03-12 10:08:48 -05003656 if (PyErr_WarnEx(PyExc_DeprecationWarning,
3657 "object.__format__ with a non-empty format "
3658 "string is deprecated", 1) < 0) {
3659 goto done;
3660 }
3661 /* Eventually this will become an error:
3662 PyErr_Format(PyExc_TypeError,
3663 "non-empty format string passed to object.__format__");
3664 goto done;
3665 */
3666 }
Eric Smith8c663262007-08-25 02:26:07 +00003667
Eric V. Smithb9cd3532011-03-12 10:08:48 -05003668 result = PyObject_Format(self_as_str, format_spec);
Eric Smithe4d63172010-09-13 20:48:43 +00003669 }
3670
3671done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003672 Py_XDECREF(self_as_str);
Eric Smith8c663262007-08-25 02:26:07 +00003673
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003674 return result;
Eric Smith8c663262007-08-25 02:26:07 +00003675}
3676
Martin v. Löwis00709aa2008-06-04 14:18:43 +00003677static PyObject *
3678object_sizeof(PyObject *self, PyObject *args)
3679{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003680 Py_ssize_t res, isize;
Martin v. Löwis00709aa2008-06-04 14:18:43 +00003681
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003682 res = 0;
3683 isize = self->ob_type->tp_itemsize;
3684 if (isize > 0)
3685 res = Py_SIZE(self->ob_type) * isize;
3686 res += self->ob_type->tp_basicsize;
Martin v. Löwis00709aa2008-06-04 14:18:43 +00003687
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003688 return PyLong_FromSsize_t(res);
Martin v. Löwis00709aa2008-06-04 14:18:43 +00003689}
3690
Benjamin Peterson82b00c12011-05-24 11:09:06 -05003691/* __dir__ for generic objects: returns __dict__, __class__,
3692 and recursively up the __class__.__bases__ chain.
3693*/
3694static PyObject *
3695object_dir(PyObject *self, PyObject *args)
3696{
3697 PyObject *result = NULL;
3698 PyObject *dict = NULL;
3699 PyObject *itsclass = NULL;
3700
3701 /* Get __dict__ (which may or may not be a real dict...) */
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02003702 dict = _PyObject_GetAttrId(self, &PyId___dict__);
Benjamin Peterson82b00c12011-05-24 11:09:06 -05003703 if (dict == NULL) {
3704 PyErr_Clear();
3705 dict = PyDict_New();
3706 }
3707 else if (!PyDict_Check(dict)) {
3708 Py_DECREF(dict);
3709 dict = PyDict_New();
3710 }
3711 else {
3712 /* Copy __dict__ to avoid mutating it. */
3713 PyObject *temp = PyDict_Copy(dict);
3714 Py_DECREF(dict);
3715 dict = temp;
3716 }
3717
3718 if (dict == NULL)
3719 goto error;
3720
3721 /* Merge in attrs reachable from its class. */
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02003722 itsclass = _PyObject_GetAttrId(self, &PyId___class__);
Benjamin Peterson82b00c12011-05-24 11:09:06 -05003723 if (itsclass == NULL)
3724 /* XXX(tomer): Perhaps fall back to obj->ob_type if no
3725 __class__ exists? */
3726 PyErr_Clear();
3727 else if (merge_class_dict(dict, itsclass) != 0)
3728 goto error;
3729
3730 result = PyDict_Keys(dict);
3731 /* fall through */
3732error:
3733 Py_XDECREF(itsclass);
3734 Py_XDECREF(dict);
3735 return result;
3736}
3737
Guido van Rossum3926a632001-09-25 16:25:58 +00003738static PyMethodDef object_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003739 {"__reduce_ex__", object_reduce_ex, METH_VARARGS,
3740 PyDoc_STR("helper for pickle")},
3741 {"__reduce__", object_reduce, METH_VARARGS,
3742 PyDoc_STR("helper for pickle")},
3743 {"__subclasshook__", object_subclasshook, METH_CLASS | METH_VARARGS,
3744 object_subclasshook_doc},
3745 {"__format__", object_format, METH_VARARGS,
3746 PyDoc_STR("default object formatter")},
3747 {"__sizeof__", object_sizeof, METH_NOARGS,
Benjamin Petersonfbe56bb2011-05-24 12:42:51 -05003748 PyDoc_STR("__sizeof__() -> int\nsize of object in memory, in bytes")},
Benjamin Peterson82b00c12011-05-24 11:09:06 -05003749 {"__dir__", object_dir, METH_NOARGS,
Benjamin Petersonc7284122011-05-24 12:46:15 -05003750 PyDoc_STR("__dir__() -> list\ndefault dir() implementation")},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003751 {0}
Guido van Rossum3926a632001-09-25 16:25:58 +00003752};
3753
Guido van Rossum036f9992003-02-21 22:02:54 +00003754
Tim Peters6d6c1a32001-08-02 04:15:00 +00003755PyTypeObject PyBaseObject_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003756 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3757 "object", /* tp_name */
3758 sizeof(PyObject), /* tp_basicsize */
3759 0, /* tp_itemsize */
3760 object_dealloc, /* tp_dealloc */
3761 0, /* tp_print */
3762 0, /* tp_getattr */
3763 0, /* tp_setattr */
3764 0, /* tp_reserved */
3765 object_repr, /* tp_repr */
3766 0, /* tp_as_number */
3767 0, /* tp_as_sequence */
3768 0, /* tp_as_mapping */
3769 (hashfunc)_Py_HashPointer, /* tp_hash */
3770 0, /* tp_call */
3771 object_str, /* tp_str */
3772 PyObject_GenericGetAttr, /* tp_getattro */
3773 PyObject_GenericSetAttr, /* tp_setattro */
3774 0, /* tp_as_buffer */
3775 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
3776 PyDoc_STR("The most base type"), /* tp_doc */
3777 0, /* tp_traverse */
3778 0, /* tp_clear */
3779 object_richcompare, /* tp_richcompare */
3780 0, /* tp_weaklistoffset */
3781 0, /* tp_iter */
3782 0, /* tp_iternext */
3783 object_methods, /* tp_methods */
3784 0, /* tp_members */
3785 object_getsets, /* tp_getset */
3786 0, /* tp_base */
3787 0, /* tp_dict */
3788 0, /* tp_descr_get */
3789 0, /* tp_descr_set */
3790 0, /* tp_dictoffset */
3791 object_init, /* tp_init */
3792 PyType_GenericAlloc, /* tp_alloc */
3793 object_new, /* tp_new */
3794 PyObject_Del, /* tp_free */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003795};
3796
3797
Guido van Rossum50e9fb92006-08-17 05:42:55 +00003798/* Add the methods from tp_methods to the __dict__ in a type object */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003799
3800static int
3801add_methods(PyTypeObject *type, PyMethodDef *meth)
3802{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003803 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003804
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003805 for (; meth->ml_name != NULL; meth++) {
3806 PyObject *descr;
Benjamin Peterson89a6e9a2012-05-08 09:22:24 -04003807 int err;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003808 if (PyDict_GetItemString(dict, meth->ml_name) &&
3809 !(meth->ml_flags & METH_COEXIST))
3810 continue;
3811 if (meth->ml_flags & METH_CLASS) {
3812 if (meth->ml_flags & METH_STATIC) {
3813 PyErr_SetString(PyExc_ValueError,
3814 "method cannot be both class and static");
3815 return -1;
3816 }
3817 descr = PyDescr_NewClassMethod(type, meth);
3818 }
3819 else if (meth->ml_flags & METH_STATIC) {
Antoine Pitrou5b629422011-12-23 12:40:16 +01003820 PyObject *cfunc = PyCFunction_New(meth, (PyObject*)type);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003821 if (cfunc == NULL)
3822 return -1;
3823 descr = PyStaticMethod_New(cfunc);
3824 Py_DECREF(cfunc);
3825 }
3826 else {
3827 descr = PyDescr_NewMethod(type, meth);
3828 }
3829 if (descr == NULL)
3830 return -1;
Benjamin Peterson89a6e9a2012-05-08 09:22:24 -04003831 err = PyDict_SetItemString(dict, meth->ml_name, descr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003832 Py_DECREF(descr);
Benjamin Peterson89a6e9a2012-05-08 09:22:24 -04003833 if (err < 0)
3834 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003835 }
3836 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003837}
3838
3839static int
Guido van Rossum6f799372001-09-20 20:46:19 +00003840add_members(PyTypeObject *type, PyMemberDef *memb)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003841{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003842 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003843
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003844 for (; memb->name != NULL; memb++) {
3845 PyObject *descr;
3846 if (PyDict_GetItemString(dict, memb->name))
3847 continue;
3848 descr = PyDescr_NewMember(type, memb);
3849 if (descr == NULL)
3850 return -1;
3851 if (PyDict_SetItemString(dict, memb->name, descr) < 0)
3852 return -1;
3853 Py_DECREF(descr);
3854 }
3855 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003856}
3857
3858static int
Guido van Rossum32d34c82001-09-20 21:45:26 +00003859add_getset(PyTypeObject *type, PyGetSetDef *gsp)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003860{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003861 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003862
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003863 for (; gsp->name != NULL; gsp++) {
3864 PyObject *descr;
3865 if (PyDict_GetItemString(dict, gsp->name))
3866 continue;
3867 descr = PyDescr_NewGetSet(type, gsp);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003868
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003869 if (descr == NULL)
3870 return -1;
3871 if (PyDict_SetItemString(dict, gsp->name, descr) < 0)
3872 return -1;
3873 Py_DECREF(descr);
3874 }
3875 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003876}
3877
Guido van Rossum13d52f02001-08-10 21:24:08 +00003878static void
3879inherit_special(PyTypeObject *type, PyTypeObject *base)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003880{
Tim Peters6d6c1a32001-08-02 04:15:00 +00003881
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003882 /* Copying basicsize is connected to the GC flags */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003883 if (!(type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
3884 (base->tp_flags & Py_TPFLAGS_HAVE_GC) &&
3885 (!type->tp_traverse && !type->tp_clear)) {
3886 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
3887 if (type->tp_traverse == NULL)
3888 type->tp_traverse = base->tp_traverse;
3889 if (type->tp_clear == NULL)
3890 type->tp_clear = base->tp_clear;
3891 }
3892 {
3893 /* The condition below could use some explanation.
3894 It appears that tp_new is not inherited for static types
3895 whose base class is 'object'; this seems to be a precaution
3896 so that old extension types don't suddenly become
3897 callable (object.__new__ wouldn't insure the invariants
3898 that the extension type's own factory function ensures).
3899 Heap types, of course, are under our control, so they do
3900 inherit tp_new; static extension types that specify some
Florent Xiclunaaa6c1d22011-12-12 18:54:29 +01003901 other built-in type as the default also
3902 inherit object.__new__. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003903 if (base != &PyBaseObject_Type ||
3904 (type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
3905 if (type->tp_new == NULL)
3906 type->tp_new = base->tp_new;
3907 }
3908 }
Benjamin Petersona7465e22010-07-05 15:01:22 +00003909 if (type->tp_basicsize == 0)
3910 type->tp_basicsize = base->tp_basicsize;
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00003911
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003912 /* Copy other non-function slots */
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00003913
3914#undef COPYVAL
3915#define COPYVAL(SLOT) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003916 if (type->SLOT == 0) type->SLOT = base->SLOT
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00003917
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003918 COPYVAL(tp_itemsize);
3919 COPYVAL(tp_weaklistoffset);
3920 COPYVAL(tp_dictoffset);
Thomas Wouters27d517b2007-02-25 20:39:11 +00003921
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003922 /* Setup fast subclass flags */
3923 if (PyType_IsSubtype(base, (PyTypeObject*)PyExc_BaseException))
3924 type->tp_flags |= Py_TPFLAGS_BASE_EXC_SUBCLASS;
3925 else if (PyType_IsSubtype(base, &PyType_Type))
3926 type->tp_flags |= Py_TPFLAGS_TYPE_SUBCLASS;
3927 else if (PyType_IsSubtype(base, &PyLong_Type))
3928 type->tp_flags |= Py_TPFLAGS_LONG_SUBCLASS;
3929 else if (PyType_IsSubtype(base, &PyBytes_Type))
3930 type->tp_flags |= Py_TPFLAGS_BYTES_SUBCLASS;
3931 else if (PyType_IsSubtype(base, &PyUnicode_Type))
3932 type->tp_flags |= Py_TPFLAGS_UNICODE_SUBCLASS;
3933 else if (PyType_IsSubtype(base, &PyTuple_Type))
3934 type->tp_flags |= Py_TPFLAGS_TUPLE_SUBCLASS;
3935 else if (PyType_IsSubtype(base, &PyList_Type))
3936 type->tp_flags |= Py_TPFLAGS_LIST_SUBCLASS;
3937 else if (PyType_IsSubtype(base, &PyDict_Type))
3938 type->tp_flags |= Py_TPFLAGS_DICT_SUBCLASS;
Guido van Rossum13d52f02001-08-10 21:24:08 +00003939}
3940
Guido van Rossum38938152006-08-21 23:36:26 +00003941static int
Guido van Rossumf5243f02008-01-01 04:06:48 +00003942overrides_hash(PyTypeObject *type)
Guido van Rossum38938152006-08-21 23:36:26 +00003943{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003944 PyObject *dict = type->tp_dict;
Victor Stinner3c1e4812012-03-26 22:10:51 +02003945 _Py_IDENTIFIER(__eq__);
Guido van Rossum38938152006-08-21 23:36:26 +00003946
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003947 assert(dict != NULL);
Victor Stinner3c1e4812012-03-26 22:10:51 +02003948 if (_PyDict_GetItemId(dict, &PyId___eq__) != NULL)
3949 return 1;
3950 if (_PyDict_GetItemId(dict, &PyId___hash__) != NULL)
3951 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003952 return 0;
Guido van Rossum38938152006-08-21 23:36:26 +00003953}
3954
Guido van Rossum13d52f02001-08-10 21:24:08 +00003955static void
3956inherit_slots(PyTypeObject *type, PyTypeObject *base)
3957{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003958 PyTypeObject *basebase;
Guido van Rossum13d52f02001-08-10 21:24:08 +00003959
3960#undef SLOTDEFINED
Tim Peters6d6c1a32001-08-02 04:15:00 +00003961#undef COPYSLOT
3962#undef COPYNUM
3963#undef COPYSEQ
3964#undef COPYMAP
Guido van Rossum5af588b2001-10-12 14:13:21 +00003965#undef COPYBUF
Guido van Rossum13d52f02001-08-10 21:24:08 +00003966
3967#define SLOTDEFINED(SLOT) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003968 (base->SLOT != 0 && \
3969 (basebase == NULL || base->SLOT != basebase->SLOT))
Guido van Rossum13d52f02001-08-10 21:24:08 +00003970
Tim Peters6d6c1a32001-08-02 04:15:00 +00003971#define COPYSLOT(SLOT) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003972 if (!type->SLOT && SLOTDEFINED(SLOT)) type->SLOT = base->SLOT
Tim Peters6d6c1a32001-08-02 04:15:00 +00003973
3974#define COPYNUM(SLOT) COPYSLOT(tp_as_number->SLOT)
3975#define COPYSEQ(SLOT) COPYSLOT(tp_as_sequence->SLOT)
3976#define COPYMAP(SLOT) COPYSLOT(tp_as_mapping->SLOT)
Tim Petersfc57ccb2001-10-12 02:38:24 +00003977#define COPYBUF(SLOT) COPYSLOT(tp_as_buffer->SLOT)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003978
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003979 /* This won't inherit indirect slots (from tp_as_number etc.)
3980 if type doesn't provide the space. */
Guido van Rossum13d52f02001-08-10 21:24:08 +00003981
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003982 if (type->tp_as_number != NULL && base->tp_as_number != NULL) {
3983 basebase = base->tp_base;
3984 if (basebase->tp_as_number == NULL)
3985 basebase = NULL;
3986 COPYNUM(nb_add);
3987 COPYNUM(nb_subtract);
3988 COPYNUM(nb_multiply);
3989 COPYNUM(nb_remainder);
3990 COPYNUM(nb_divmod);
3991 COPYNUM(nb_power);
3992 COPYNUM(nb_negative);
3993 COPYNUM(nb_positive);
3994 COPYNUM(nb_absolute);
3995 COPYNUM(nb_bool);
3996 COPYNUM(nb_invert);
3997 COPYNUM(nb_lshift);
3998 COPYNUM(nb_rshift);
3999 COPYNUM(nb_and);
4000 COPYNUM(nb_xor);
4001 COPYNUM(nb_or);
4002 COPYNUM(nb_int);
4003 COPYNUM(nb_float);
4004 COPYNUM(nb_inplace_add);
4005 COPYNUM(nb_inplace_subtract);
4006 COPYNUM(nb_inplace_multiply);
4007 COPYNUM(nb_inplace_remainder);
4008 COPYNUM(nb_inplace_power);
4009 COPYNUM(nb_inplace_lshift);
4010 COPYNUM(nb_inplace_rshift);
4011 COPYNUM(nb_inplace_and);
4012 COPYNUM(nb_inplace_xor);
4013 COPYNUM(nb_inplace_or);
4014 COPYNUM(nb_true_divide);
4015 COPYNUM(nb_floor_divide);
4016 COPYNUM(nb_inplace_true_divide);
4017 COPYNUM(nb_inplace_floor_divide);
4018 COPYNUM(nb_index);
4019 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004020
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004021 if (type->tp_as_sequence != NULL && base->tp_as_sequence != NULL) {
4022 basebase = base->tp_base;
4023 if (basebase->tp_as_sequence == NULL)
4024 basebase = NULL;
4025 COPYSEQ(sq_length);
4026 COPYSEQ(sq_concat);
4027 COPYSEQ(sq_repeat);
4028 COPYSEQ(sq_item);
4029 COPYSEQ(sq_ass_item);
4030 COPYSEQ(sq_contains);
4031 COPYSEQ(sq_inplace_concat);
4032 COPYSEQ(sq_inplace_repeat);
4033 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004034
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004035 if (type->tp_as_mapping != NULL && base->tp_as_mapping != NULL) {
4036 basebase = base->tp_base;
4037 if (basebase->tp_as_mapping == NULL)
4038 basebase = NULL;
4039 COPYMAP(mp_length);
4040 COPYMAP(mp_subscript);
4041 COPYMAP(mp_ass_subscript);
4042 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004043
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004044 if (type->tp_as_buffer != NULL && base->tp_as_buffer != NULL) {
4045 basebase = base->tp_base;
4046 if (basebase->tp_as_buffer == NULL)
4047 basebase = NULL;
4048 COPYBUF(bf_getbuffer);
4049 COPYBUF(bf_releasebuffer);
4050 }
Tim Petersfc57ccb2001-10-12 02:38:24 +00004051
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004052 basebase = base->tp_base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004053
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004054 COPYSLOT(tp_dealloc);
4055 if (type->tp_getattr == NULL && type->tp_getattro == NULL) {
4056 type->tp_getattr = base->tp_getattr;
4057 type->tp_getattro = base->tp_getattro;
4058 }
4059 if (type->tp_setattr == NULL && type->tp_setattro == NULL) {
4060 type->tp_setattr = base->tp_setattr;
4061 type->tp_setattro = base->tp_setattro;
4062 }
4063 /* tp_reserved is ignored */
4064 COPYSLOT(tp_repr);
4065 /* tp_hash see tp_richcompare */
4066 COPYSLOT(tp_call);
4067 COPYSLOT(tp_str);
4068 {
4069 /* Copy comparison-related slots only when
4070 not overriding them anywhere */
4071 if (type->tp_richcompare == NULL &&
4072 type->tp_hash == NULL &&
4073 !overrides_hash(type))
4074 {
4075 type->tp_richcompare = base->tp_richcompare;
4076 type->tp_hash = base->tp_hash;
4077 }
4078 }
4079 {
4080 COPYSLOT(tp_iter);
4081 COPYSLOT(tp_iternext);
4082 }
4083 {
4084 COPYSLOT(tp_descr_get);
4085 COPYSLOT(tp_descr_set);
4086 COPYSLOT(tp_dictoffset);
4087 COPYSLOT(tp_init);
4088 COPYSLOT(tp_alloc);
4089 COPYSLOT(tp_is_gc);
4090 if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) ==
4091 (base->tp_flags & Py_TPFLAGS_HAVE_GC)) {
4092 /* They agree about gc. */
4093 COPYSLOT(tp_free);
4094 }
4095 else if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
4096 type->tp_free == NULL &&
4097 base->tp_free == PyObject_Free) {
4098 /* A bit of magic to plug in the correct default
4099 * tp_free function when a derived class adds gc,
4100 * didn't define tp_free, and the base uses the
4101 * default non-gc tp_free.
4102 */
4103 type->tp_free = PyObject_GC_Del;
4104 }
4105 /* else they didn't agree about gc, and there isn't something
4106 * obvious to be done -- the type is on its own.
4107 */
4108 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004109}
4110
Jeremy Hylton938ace62002-07-17 16:30:39 +00004111static int add_operators(PyTypeObject *);
Guido van Rossum13d52f02001-08-10 21:24:08 +00004112
Tim Peters6d6c1a32001-08-02 04:15:00 +00004113int
Guido van Rossum528b7eb2001-08-07 17:24:28 +00004114PyType_Ready(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004115{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004116 PyObject *dict, *bases;
4117 PyTypeObject *base;
4118 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004119
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004120 if (type->tp_flags & Py_TPFLAGS_READY) {
4121 assert(type->tp_dict != NULL);
4122 return 0;
4123 }
4124 assert((type->tp_flags & Py_TPFLAGS_READYING) == 0);
Guido van Rossumd614f972001-08-10 17:39:49 +00004125
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004126 type->tp_flags |= Py_TPFLAGS_READYING;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004127
Tim Peters36eb4df2003-03-23 03:33:13 +00004128#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004129 /* PyType_Ready is the closest thing we have to a choke point
4130 * for type objects, so is the best place I can think of to try
4131 * to get type objects into the doubly-linked list of all objects.
4132 * Still, not all type objects go thru PyType_Ready.
4133 */
4134 _Py_AddToAllObjects((PyObject *)type, 0);
Tim Peters36eb4df2003-03-23 03:33:13 +00004135#endif
4136
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004137 /* Initialize tp_base (defaults to BaseObject unless that's us) */
4138 base = type->tp_base;
4139 if (base == NULL && type != &PyBaseObject_Type) {
4140 base = type->tp_base = &PyBaseObject_Type;
4141 Py_INCREF(base);
4142 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004143
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004144 /* Now the only way base can still be NULL is if type is
4145 * &PyBaseObject_Type.
4146 */
Guido van Rossum692cdbc2006-03-10 02:04:28 +00004147
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004148 /* Initialize the base class */
4149 if (base != NULL && base->tp_dict == NULL) {
4150 if (PyType_Ready(base) < 0)
4151 goto error;
4152 }
Guido van Rossum323a9cf2002-08-14 17:26:30 +00004153
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004154 /* Initialize ob_type if NULL. This means extensions that want to be
4155 compilable separately on Windows can call PyType_Ready() instead of
4156 initializing the ob_type field of their type objects. */
4157 /* The test for base != NULL is really unnecessary, since base is only
4158 NULL when type is &PyBaseObject_Type, and we know its ob_type is
4159 not NULL (it's initialized to &PyType_Type). But coverity doesn't
4160 know that. */
4161 if (Py_TYPE(type) == NULL && base != NULL)
4162 Py_TYPE(type) = Py_TYPE(base);
Guido van Rossum0986d822002-04-08 01:38:42 +00004163
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004164 /* Initialize tp_bases */
4165 bases = type->tp_bases;
4166 if (bases == NULL) {
4167 if (base == NULL)
4168 bases = PyTuple_New(0);
4169 else
4170 bases = PyTuple_Pack(1, base);
4171 if (bases == NULL)
4172 goto error;
4173 type->tp_bases = bases;
4174 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004175
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004176 /* Initialize tp_dict */
4177 dict = type->tp_dict;
4178 if (dict == NULL) {
4179 dict = PyDict_New();
4180 if (dict == NULL)
4181 goto error;
4182 type->tp_dict = dict;
4183 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004184
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004185 /* Add type-specific descriptors to tp_dict */
4186 if (add_operators(type) < 0)
4187 goto error;
4188 if (type->tp_methods != NULL) {
4189 if (add_methods(type, type->tp_methods) < 0)
4190 goto error;
4191 }
4192 if (type->tp_members != NULL) {
4193 if (add_members(type, type->tp_members) < 0)
4194 goto error;
4195 }
4196 if (type->tp_getset != NULL) {
4197 if (add_getset(type, type->tp_getset) < 0)
4198 goto error;
4199 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004200
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004201 /* Calculate method resolution order */
4202 if (mro_internal(type) < 0) {
4203 goto error;
4204 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004205
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004206 /* Inherit special flags from dominant base */
4207 if (type->tp_base != NULL)
4208 inherit_special(type, type->tp_base);
Guido van Rossum13d52f02001-08-10 21:24:08 +00004209
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004210 /* Initialize tp_dict properly */
4211 bases = type->tp_mro;
4212 assert(bases != NULL);
4213 assert(PyTuple_Check(bases));
4214 n = PyTuple_GET_SIZE(bases);
4215 for (i = 1; i < n; i++) {
4216 PyObject *b = PyTuple_GET_ITEM(bases, i);
4217 if (PyType_Check(b))
4218 inherit_slots(type, (PyTypeObject *)b);
4219 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004220
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004221 /* Sanity check for tp_free. */
4222 if (PyType_IS_GC(type) && (type->tp_flags & Py_TPFLAGS_BASETYPE) &&
4223 (type->tp_free == NULL || type->tp_free == PyObject_Del)) {
4224 /* This base class needs to call tp_free, but doesn't have
4225 * one, or its tp_free is for non-gc'ed objects.
4226 */
4227 PyErr_Format(PyExc_TypeError, "type '%.100s' participates in "
4228 "gc and is a base type but has inappropriate "
4229 "tp_free slot",
4230 type->tp_name);
4231 goto error;
4232 }
Tim Peters3cfe7542003-05-21 21:29:48 +00004233
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004234 /* if the type dictionary doesn't contain a __doc__, set it from
4235 the tp_doc slot.
4236 */
Victor Stinner3c1e4812012-03-26 22:10:51 +02004237 if (_PyDict_GetItemId(type->tp_dict, &PyId___doc__) == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004238 if (type->tp_doc != NULL) {
4239 PyObject *doc = PyUnicode_FromString(type->tp_doc);
4240 if (doc == NULL)
4241 goto error;
Victor Stinner3c1e4812012-03-26 22:10:51 +02004242 _PyDict_SetItemId(type->tp_dict, &PyId___doc__, doc);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004243 Py_DECREF(doc);
4244 } else {
Victor Stinner3c1e4812012-03-26 22:10:51 +02004245 _PyDict_SetItemId(type->tp_dict,
4246 &PyId___doc__, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004247 }
4248 }
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00004249
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004250 /* Hack for tp_hash and __hash__.
4251 If after all that, tp_hash is still NULL, and __hash__ is not in
4252 tp_dict, set tp_hash to PyObject_HashNotImplemented and
4253 tp_dict['__hash__'] equal to None.
4254 This signals that __hash__ is not inherited.
4255 */
4256 if (type->tp_hash == NULL) {
Victor Stinner3c1e4812012-03-26 22:10:51 +02004257 if (_PyDict_GetItemId(type->tp_dict, &PyId___hash__) == NULL) {
4258 if (_PyDict_SetItemId(type->tp_dict, &PyId___hash__, Py_None) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004259 goto error;
4260 type->tp_hash = PyObject_HashNotImplemented;
4261 }
4262 }
Guido van Rossum38938152006-08-21 23:36:26 +00004263
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004264 /* Some more special stuff */
4265 base = type->tp_base;
4266 if (base != NULL) {
4267 if (type->tp_as_number == NULL)
4268 type->tp_as_number = base->tp_as_number;
4269 if (type->tp_as_sequence == NULL)
4270 type->tp_as_sequence = base->tp_as_sequence;
4271 if (type->tp_as_mapping == NULL)
4272 type->tp_as_mapping = base->tp_as_mapping;
4273 if (type->tp_as_buffer == NULL)
4274 type->tp_as_buffer = base->tp_as_buffer;
4275 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004276
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004277 /* Link into each base class's list of subclasses */
4278 bases = type->tp_bases;
4279 n = PyTuple_GET_SIZE(bases);
4280 for (i = 0; i < n; i++) {
4281 PyObject *b = PyTuple_GET_ITEM(bases, i);
4282 if (PyType_Check(b) &&
4283 add_subclass((PyTypeObject *)b, type) < 0)
4284 goto error;
4285 }
Guido van Rossum1c450732001-10-08 15:18:27 +00004286
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004287 /* Warn for a type that implements tp_compare (now known as
4288 tp_reserved) but not tp_richcompare. */
4289 if (type->tp_reserved && !type->tp_richcompare) {
4290 int error;
Victor Stinner4a2b7a12010-08-13 14:03:48 +00004291 error = PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
4292 "Type %.100s defines tp_reserved (formerly tp_compare) "
4293 "but not tp_richcompare. Comparisons may not behave as intended.",
4294 type->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004295 if (error == -1)
4296 goto error;
4297 }
Mark Dickinson2a7d45b2009-02-08 11:02:10 +00004298
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004299 /* All done -- set the ready flag */
4300 assert(type->tp_dict != NULL);
4301 type->tp_flags =
4302 (type->tp_flags & ~Py_TPFLAGS_READYING) | Py_TPFLAGS_READY;
4303 return 0;
Guido van Rossumd614f972001-08-10 17:39:49 +00004304
4305 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004306 type->tp_flags &= ~Py_TPFLAGS_READYING;
4307 return -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004308}
4309
Guido van Rossum1c450732001-10-08 15:18:27 +00004310static int
4311add_subclass(PyTypeObject *base, PyTypeObject *type)
4312{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004313 Py_ssize_t i;
4314 int result;
4315 PyObject *list, *ref, *newobj;
Guido van Rossum1c450732001-10-08 15:18:27 +00004316
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004317 list = base->tp_subclasses;
4318 if (list == NULL) {
4319 base->tp_subclasses = list = PyList_New(0);
4320 if (list == NULL)
4321 return -1;
4322 }
4323 assert(PyList_Check(list));
4324 newobj = PyWeakref_NewRef((PyObject *)type, NULL);
4325 i = PyList_GET_SIZE(list);
4326 while (--i >= 0) {
4327 ref = PyList_GET_ITEM(list, i);
4328 assert(PyWeakref_CheckRef(ref));
4329 if (PyWeakref_GET_OBJECT(ref) == Py_None)
4330 return PyList_SetItem(list, i, newobj);
4331 }
4332 result = PyList_Append(list, newobj);
4333 Py_DECREF(newobj);
4334 return result;
Guido van Rossum1c450732001-10-08 15:18:27 +00004335}
4336
Michael W. Hudson98bbc492002-11-26 14:47:27 +00004337static void
4338remove_subclass(PyTypeObject *base, PyTypeObject *type)
4339{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004340 Py_ssize_t i;
4341 PyObject *list, *ref;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00004342
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004343 list = base->tp_subclasses;
4344 if (list == NULL) {
4345 return;
4346 }
4347 assert(PyList_Check(list));
4348 i = PyList_GET_SIZE(list);
4349 while (--i >= 0) {
4350 ref = PyList_GET_ITEM(list, i);
4351 assert(PyWeakref_CheckRef(ref));
4352 if (PyWeakref_GET_OBJECT(ref) == (PyObject*)type) {
4353 /* this can't fail, right? */
4354 PySequence_DelItem(list, i);
4355 return;
4356 }
4357 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +00004358}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004359
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004360static int
4361check_num_args(PyObject *ob, int n)
4362{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004363 if (!PyTuple_CheckExact(ob)) {
4364 PyErr_SetString(PyExc_SystemError,
4365 "PyArg_UnpackTuple() argument list is not a tuple");
4366 return 0;
4367 }
4368 if (n == PyTuple_GET_SIZE(ob))
4369 return 1;
4370 PyErr_Format(
4371 PyExc_TypeError,
4372 "expected %d arguments, got %zd", n, PyTuple_GET_SIZE(ob));
4373 return 0;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004374}
4375
Tim Peters6d6c1a32001-08-02 04:15:00 +00004376/* Generic wrappers for overloadable 'operators' such as __getitem__ */
4377
4378/* There's a wrapper *function* for each distinct function typedef used
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004379 for type object slots (e.g. binaryfunc, ternaryfunc, etc.). There's a
Tim Peters6d6c1a32001-08-02 04:15:00 +00004380 wrapper *table* for each distinct operation (e.g. __len__, __add__).
4381 Most tables have only one entry; the tables for binary operators have two
4382 entries, one regular and one with reversed arguments. */
4383
4384static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00004385wrap_lenfunc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004386{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004387 lenfunc func = (lenfunc)wrapped;
4388 Py_ssize_t res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004389
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004390 if (!check_num_args(args, 0))
4391 return NULL;
4392 res = (*func)(self);
4393 if (res == -1 && PyErr_Occurred())
4394 return NULL;
4395 return PyLong_FromLong((long)res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004396}
4397
Tim Peters6d6c1a32001-08-02 04:15:00 +00004398static PyObject *
Raymond Hettingerf34f2642003-10-11 17:29:04 +00004399wrap_inquirypred(PyObject *self, PyObject *args, void *wrapped)
4400{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004401 inquiry func = (inquiry)wrapped;
4402 int res;
Raymond Hettingerf34f2642003-10-11 17:29:04 +00004403
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004404 if (!check_num_args(args, 0))
4405 return NULL;
4406 res = (*func)(self);
4407 if (res == -1 && PyErr_Occurred())
4408 return NULL;
4409 return PyBool_FromLong((long)res);
Raymond Hettingerf34f2642003-10-11 17:29:04 +00004410}
4411
4412static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00004413wrap_binaryfunc(PyObject *self, PyObject *args, void *wrapped)
4414{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004415 binaryfunc func = (binaryfunc)wrapped;
4416 PyObject *other;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004417
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004418 if (!check_num_args(args, 1))
4419 return NULL;
4420 other = PyTuple_GET_ITEM(args, 0);
4421 return (*func)(self, other);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004422}
4423
4424static PyObject *
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00004425wrap_binaryfunc_l(PyObject *self, PyObject *args, void *wrapped)
4426{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004427 binaryfunc func = (binaryfunc)wrapped;
4428 PyObject *other;
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00004429
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004430 if (!check_num_args(args, 1))
4431 return NULL;
4432 other = PyTuple_GET_ITEM(args, 0);
4433 return (*func)(self, other);
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00004434}
4435
4436static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00004437wrap_binaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
4438{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004439 binaryfunc func = (binaryfunc)wrapped;
4440 PyObject *other;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004441
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004442 if (!check_num_args(args, 1))
4443 return NULL;
4444 other = PyTuple_GET_ITEM(args, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004445 return (*func)(other, self);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004446}
4447
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004448static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00004449wrap_ternaryfunc(PyObject *self, PyObject *args, void *wrapped)
4450{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004451 ternaryfunc func = (ternaryfunc)wrapped;
4452 PyObject *other;
4453 PyObject *third = Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004454
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004455 /* Note: This wrapper only works for __pow__() */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004456
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004457 if (!PyArg_UnpackTuple(args, "", 1, 2, &other, &third))
4458 return NULL;
4459 return (*func)(self, other, third);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004460}
4461
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00004462static PyObject *
4463wrap_ternaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
4464{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004465 ternaryfunc func = (ternaryfunc)wrapped;
4466 PyObject *other;
4467 PyObject *third = Py_None;
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00004468
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004469 /* Note: This wrapper only works for __pow__() */
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00004470
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004471 if (!PyArg_UnpackTuple(args, "", 1, 2, &other, &third))
4472 return NULL;
4473 return (*func)(other, self, third);
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00004474}
4475
Tim Peters6d6c1a32001-08-02 04:15:00 +00004476static PyObject *
4477wrap_unaryfunc(PyObject *self, PyObject *args, void *wrapped)
4478{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004479 unaryfunc func = (unaryfunc)wrapped;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004480
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004481 if (!check_num_args(args, 0))
4482 return NULL;
4483 return (*func)(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004484}
4485
Tim Peters6d6c1a32001-08-02 04:15:00 +00004486static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004487wrap_indexargfunc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004488{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004489 ssizeargfunc func = (ssizeargfunc)wrapped;
4490 PyObject* o;
4491 Py_ssize_t i;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004492
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004493 if (!PyArg_UnpackTuple(args, "", 1, 1, &o))
4494 return NULL;
4495 i = PyNumber_AsSsize_t(o, PyExc_OverflowError);
4496 if (i == -1 && PyErr_Occurred())
4497 return NULL;
4498 return (*func)(self, i);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004499}
4500
Martin v. Löwis18e16552006-02-15 17:27:45 +00004501static Py_ssize_t
Guido van Rossum5d815f32001-08-17 21:57:47 +00004502getindex(PyObject *self, PyObject *arg)
4503{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004504 Py_ssize_t i;
Guido van Rossum5d815f32001-08-17 21:57:47 +00004505
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004506 i = PyNumber_AsSsize_t(arg, PyExc_OverflowError);
4507 if (i == -1 && PyErr_Occurred())
4508 return -1;
4509 if (i < 0) {
4510 PySequenceMethods *sq = Py_TYPE(self)->tp_as_sequence;
4511 if (sq && sq->sq_length) {
4512 Py_ssize_t n = (*sq->sq_length)(self);
4513 if (n < 0)
4514 return -1;
4515 i += n;
4516 }
4517 }
4518 return i;
Guido van Rossum5d815f32001-08-17 21:57:47 +00004519}
4520
4521static PyObject *
4522wrap_sq_item(PyObject *self, PyObject *args, void *wrapped)
4523{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004524 ssizeargfunc func = (ssizeargfunc)wrapped;
4525 PyObject *arg;
4526 Py_ssize_t i;
Guido van Rossum5d815f32001-08-17 21:57:47 +00004527
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004528 if (PyTuple_GET_SIZE(args) == 1) {
4529 arg = PyTuple_GET_ITEM(args, 0);
4530 i = getindex(self, arg);
4531 if (i == -1 && PyErr_Occurred())
4532 return NULL;
4533 return (*func)(self, i);
4534 }
4535 check_num_args(args, 1);
4536 assert(PyErr_Occurred());
4537 return NULL;
Guido van Rossum5d815f32001-08-17 21:57:47 +00004538}
4539
Tim Peters6d6c1a32001-08-02 04:15:00 +00004540static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00004541wrap_sq_setitem(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004542{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004543 ssizeobjargproc func = (ssizeobjargproc)wrapped;
4544 Py_ssize_t i;
4545 int res;
4546 PyObject *arg, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004547
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004548 if (!PyArg_UnpackTuple(args, "", 2, 2, &arg, &value))
4549 return NULL;
4550 i = getindex(self, arg);
4551 if (i == -1 && PyErr_Occurred())
4552 return NULL;
4553 res = (*func)(self, i, value);
4554 if (res == -1 && PyErr_Occurred())
4555 return NULL;
4556 Py_INCREF(Py_None);
4557 return Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004558}
4559
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004560static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00004561wrap_sq_delitem(PyObject *self, PyObject *args, void *wrapped)
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004562{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004563 ssizeobjargproc func = (ssizeobjargproc)wrapped;
4564 Py_ssize_t i;
4565 int res;
4566 PyObject *arg;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004567
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004568 if (!check_num_args(args, 1))
4569 return NULL;
4570 arg = PyTuple_GET_ITEM(args, 0);
4571 i = getindex(self, arg);
4572 if (i == -1 && PyErr_Occurred())
4573 return NULL;
4574 res = (*func)(self, i, NULL);
4575 if (res == -1 && PyErr_Occurred())
4576 return NULL;
4577 Py_INCREF(Py_None);
4578 return Py_None;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004579}
4580
Tim Peters6d6c1a32001-08-02 04:15:00 +00004581/* XXX objobjproc is a misnomer; should be objargpred */
4582static PyObject *
4583wrap_objobjproc(PyObject *self, PyObject *args, void *wrapped)
4584{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004585 objobjproc func = (objobjproc)wrapped;
4586 int res;
4587 PyObject *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004588
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004589 if (!check_num_args(args, 1))
4590 return NULL;
4591 value = PyTuple_GET_ITEM(args, 0);
4592 res = (*func)(self, value);
4593 if (res == -1 && PyErr_Occurred())
4594 return NULL;
4595 else
4596 return PyBool_FromLong(res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004597}
4598
Tim Peters6d6c1a32001-08-02 04:15:00 +00004599static PyObject *
4600wrap_objobjargproc(PyObject *self, PyObject *args, void *wrapped)
4601{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004602 objobjargproc func = (objobjargproc)wrapped;
4603 int res;
4604 PyObject *key, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004605
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004606 if (!PyArg_UnpackTuple(args, "", 2, 2, &key, &value))
4607 return NULL;
4608 res = (*func)(self, key, value);
4609 if (res == -1 && PyErr_Occurred())
4610 return NULL;
4611 Py_INCREF(Py_None);
4612 return Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004613}
4614
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004615static PyObject *
4616wrap_delitem(PyObject *self, PyObject *args, void *wrapped)
4617{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004618 objobjargproc func = (objobjargproc)wrapped;
4619 int res;
4620 PyObject *key;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004621
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004622 if (!check_num_args(args, 1))
4623 return NULL;
4624 key = PyTuple_GET_ITEM(args, 0);
4625 res = (*func)(self, key, NULL);
4626 if (res == -1 && PyErr_Occurred())
4627 return NULL;
4628 Py_INCREF(Py_None);
4629 return Py_None;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004630}
4631
Guido van Rossum4dcdb782003-04-14 21:46:03 +00004632/* Helper to check for object.__setattr__ or __delattr__ applied to a type.
Guido van Rossum52b27052003-04-15 20:05:10 +00004633 This is called the Carlo Verre hack after its discoverer. */
Guido van Rossum4dcdb782003-04-14 21:46:03 +00004634static int
4635hackcheck(PyObject *self, setattrofunc func, char *what)
4636{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004637 PyTypeObject *type = Py_TYPE(self);
4638 while (type && type->tp_flags & Py_TPFLAGS_HEAPTYPE)
4639 type = type->tp_base;
4640 /* If type is NULL now, this is a really weird type.
4641 In the spirit of backwards compatibility (?), just shut up. */
4642 if (type && type->tp_setattro != func) {
4643 PyErr_Format(PyExc_TypeError,
4644 "can't apply this %s to %s object",
4645 what,
4646 type->tp_name);
4647 return 0;
4648 }
4649 return 1;
Guido van Rossum4dcdb782003-04-14 21:46:03 +00004650}
4651
Tim Peters6d6c1a32001-08-02 04:15:00 +00004652static PyObject *
4653wrap_setattr(PyObject *self, PyObject *args, void *wrapped)
4654{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004655 setattrofunc func = (setattrofunc)wrapped;
4656 int res;
4657 PyObject *name, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004658
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004659 if (!PyArg_UnpackTuple(args, "", 2, 2, &name, &value))
4660 return NULL;
4661 if (!hackcheck(self, func, "__setattr__"))
4662 return NULL;
4663 res = (*func)(self, name, value);
4664 if (res < 0)
4665 return NULL;
4666 Py_INCREF(Py_None);
4667 return Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004668}
4669
4670static PyObject *
4671wrap_delattr(PyObject *self, PyObject *args, void *wrapped)
4672{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004673 setattrofunc func = (setattrofunc)wrapped;
4674 int res;
4675 PyObject *name;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004676
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004677 if (!check_num_args(args, 1))
4678 return NULL;
4679 name = PyTuple_GET_ITEM(args, 0);
4680 if (!hackcheck(self, func, "__delattr__"))
4681 return NULL;
4682 res = (*func)(self, name, NULL);
4683 if (res < 0)
4684 return NULL;
4685 Py_INCREF(Py_None);
4686 return Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004687}
4688
Tim Peters6d6c1a32001-08-02 04:15:00 +00004689static PyObject *
4690wrap_hashfunc(PyObject *self, PyObject *args, void *wrapped)
4691{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004692 hashfunc func = (hashfunc)wrapped;
Benjamin Peterson8035bc52010-10-23 16:20:50 +00004693 Py_hash_t res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004694
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004695 if (!check_num_args(args, 0))
4696 return NULL;
4697 res = (*func)(self);
4698 if (res == -1 && PyErr_Occurred())
4699 return NULL;
Benjamin Peterson8035bc52010-10-23 16:20:50 +00004700 return PyLong_FromSsize_t(res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004701}
4702
Tim Peters6d6c1a32001-08-02 04:15:00 +00004703static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00004704wrap_call(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004705{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004706 ternaryfunc func = (ternaryfunc)wrapped;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004707
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004708 return (*func)(self, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004709}
4710
Tim Peters6d6c1a32001-08-02 04:15:00 +00004711static PyObject *
4712wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op)
4713{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004714 richcmpfunc func = (richcmpfunc)wrapped;
4715 PyObject *other;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004716
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004717 if (!check_num_args(args, 1))
4718 return NULL;
4719 other = PyTuple_GET_ITEM(args, 0);
4720 return (*func)(self, other, op);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004721}
4722
4723#undef RICHCMP_WRAPPER
4724#define RICHCMP_WRAPPER(NAME, OP) \
4725static PyObject * \
4726richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \
4727{ \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004728 return wrap_richcmpfunc(self, args, wrapped, OP); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004729}
4730
Jack Jansen8e938b42001-08-08 15:29:49 +00004731RICHCMP_WRAPPER(lt, Py_LT)
4732RICHCMP_WRAPPER(le, Py_LE)
4733RICHCMP_WRAPPER(eq, Py_EQ)
4734RICHCMP_WRAPPER(ne, Py_NE)
4735RICHCMP_WRAPPER(gt, Py_GT)
4736RICHCMP_WRAPPER(ge, Py_GE)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004737
Tim Peters6d6c1a32001-08-02 04:15:00 +00004738static PyObject *
4739wrap_next(PyObject *self, PyObject *args, void *wrapped)
4740{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004741 unaryfunc func = (unaryfunc)wrapped;
4742 PyObject *res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004743
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004744 if (!check_num_args(args, 0))
4745 return NULL;
4746 res = (*func)(self);
4747 if (res == NULL && !PyErr_Occurred())
4748 PyErr_SetNone(PyExc_StopIteration);
4749 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004750}
4751
Tim Peters6d6c1a32001-08-02 04:15:00 +00004752static PyObject *
4753wrap_descr_get(PyObject *self, PyObject *args, void *wrapped)
4754{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004755 descrgetfunc func = (descrgetfunc)wrapped;
4756 PyObject *obj;
4757 PyObject *type = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004758
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004759 if (!PyArg_UnpackTuple(args, "", 1, 2, &obj, &type))
4760 return NULL;
4761 if (obj == Py_None)
4762 obj = NULL;
4763 if (type == Py_None)
4764 type = NULL;
4765 if (type == NULL &&obj == NULL) {
4766 PyErr_SetString(PyExc_TypeError,
4767 "__get__(None, None) is invalid");
4768 return NULL;
4769 }
4770 return (*func)(self, obj, type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004771}
4772
Tim Peters6d6c1a32001-08-02 04:15:00 +00004773static PyObject *
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004774wrap_descr_set(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004775{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004776 descrsetfunc func = (descrsetfunc)wrapped;
4777 PyObject *obj, *value;
4778 int ret;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004779
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004780 if (!PyArg_UnpackTuple(args, "", 2, 2, &obj, &value))
4781 return NULL;
4782 ret = (*func)(self, obj, value);
4783 if (ret < 0)
4784 return NULL;
4785 Py_INCREF(Py_None);
4786 return Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004787}
Guido van Rossum22b13872002-08-06 21:41:44 +00004788
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00004789static PyObject *
4790wrap_descr_delete(PyObject *self, PyObject *args, void *wrapped)
4791{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004792 descrsetfunc func = (descrsetfunc)wrapped;
4793 PyObject *obj;
4794 int ret;
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00004795
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004796 if (!check_num_args(args, 1))
4797 return NULL;
4798 obj = PyTuple_GET_ITEM(args, 0);
4799 ret = (*func)(self, obj, NULL);
4800 if (ret < 0)
4801 return NULL;
4802 Py_INCREF(Py_None);
4803 return Py_None;
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00004804}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004805
Tim Peters6d6c1a32001-08-02 04:15:00 +00004806static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00004807wrap_init(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004808{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004809 initproc func = (initproc)wrapped;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004810
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004811 if (func(self, args, kwds) < 0)
4812 return NULL;
4813 Py_INCREF(Py_None);
4814 return Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004815}
4816
Tim Peters6d6c1a32001-08-02 04:15:00 +00004817static PyObject *
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004818tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004819{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004820 PyTypeObject *type, *subtype, *staticbase;
4821 PyObject *arg0, *res;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004822
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004823 if (self == NULL || !PyType_Check(self))
4824 Py_FatalError("__new__() called with non-type 'self'");
4825 type = (PyTypeObject *)self;
4826 if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) {
4827 PyErr_Format(PyExc_TypeError,
4828 "%s.__new__(): not enough arguments",
4829 type->tp_name);
4830 return NULL;
4831 }
4832 arg0 = PyTuple_GET_ITEM(args, 0);
4833 if (!PyType_Check(arg0)) {
4834 PyErr_Format(PyExc_TypeError,
4835 "%s.__new__(X): X is not a type object (%s)",
4836 type->tp_name,
4837 Py_TYPE(arg0)->tp_name);
4838 return NULL;
4839 }
4840 subtype = (PyTypeObject *)arg0;
4841 if (!PyType_IsSubtype(subtype, type)) {
4842 PyErr_Format(PyExc_TypeError,
4843 "%s.__new__(%s): %s is not a subtype of %s",
4844 type->tp_name,
4845 subtype->tp_name,
4846 subtype->tp_name,
4847 type->tp_name);
4848 return NULL;
4849 }
Barry Warsaw60f01882001-08-22 19:24:42 +00004850
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004851 /* Check that the use doesn't do something silly and unsafe like
4852 object.__new__(dict). To do this, we check that the
4853 most derived base that's not a heap type is this type. */
4854 staticbase = subtype;
Martin v. Löwis9c564092012-06-23 23:20:45 +02004855 while (staticbase && (staticbase->tp_new == slot_tp_new))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004856 staticbase = staticbase->tp_base;
4857 /* If staticbase is NULL now, it is a really weird type.
4858 In the spirit of backwards compatibility (?), just shut up. */
4859 if (staticbase && staticbase->tp_new != type->tp_new) {
4860 PyErr_Format(PyExc_TypeError,
4861 "%s.__new__(%s) is not safe, use %s.__new__()",
4862 type->tp_name,
4863 subtype->tp_name,
4864 staticbase == NULL ? "?" : staticbase->tp_name);
4865 return NULL;
4866 }
Barry Warsaw60f01882001-08-22 19:24:42 +00004867
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004868 args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
4869 if (args == NULL)
4870 return NULL;
4871 res = type->tp_new(subtype, args, kwds);
4872 Py_DECREF(args);
4873 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004874}
4875
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004876static struct PyMethodDef tp_new_methoddef[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004877 {"__new__", (PyCFunction)tp_new_wrapper, METH_VARARGS|METH_KEYWORDS,
4878 PyDoc_STR("T.__new__(S, ...) -> "
4879 "a new object with type S, a subtype of T")},
4880 {0}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004881};
4882
4883static int
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004884add_tp_new_wrapper(PyTypeObject *type)
4885{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004886 PyObject *func;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004887
Victor Stinner3c1e4812012-03-26 22:10:51 +02004888 if (_PyDict_GetItemId(type->tp_dict, &PyId___new__) != NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004889 return 0;
4890 func = PyCFunction_New(tp_new_methoddef, (PyObject *)type);
4891 if (func == NULL)
4892 return -1;
Victor Stinner3c1e4812012-03-26 22:10:51 +02004893 if (_PyDict_SetItemId(type->tp_dict, &PyId___new__, func)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004894 Py_DECREF(func);
4895 return -1;
4896 }
4897 Py_DECREF(func);
4898 return 0;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004899}
4900
Guido van Rossumf040ede2001-08-07 16:40:56 +00004901/* Slot wrappers that call the corresponding __foo__ slot. See comments
4902 below at override_slots() for more explanation. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004903
Guido van Rossumdc91b992001-08-08 22:26:22 +00004904#define SLOT0(FUNCNAME, OPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004905static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004906FUNCNAME(PyObject *self) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004907{ \
Benjamin Petersonce798522012-01-22 11:24:29 -05004908 _Py_static_string(id, OPSTR); \
4909 return call_method(self, &id, "()"); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004910}
4911
Guido van Rossumdc91b992001-08-08 22:26:22 +00004912#define SLOT1(FUNCNAME, OPSTR, ARG1TYPE, ARGCODES) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004913static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004914FUNCNAME(PyObject *self, ARG1TYPE arg1) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004915{ \
Benjamin Petersonce798522012-01-22 11:24:29 -05004916 _Py_static_string(id, OPSTR); \
4917 return call_method(self, &id, "(" ARGCODES ")", arg1); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004918}
4919
Guido van Rossumcd118802003-01-06 22:57:47 +00004920/* Boolean helper for SLOT1BINFULL().
4921 right.__class__ is a nontrivial subclass of left.__class__. */
4922static int
Victor Stinner3c1e4812012-03-26 22:10:51 +02004923method_is_overloaded(PyObject *left, PyObject *right, struct _Py_Identifier *name)
Guido van Rossumcd118802003-01-06 22:57:47 +00004924{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004925 PyObject *a, *b;
4926 int ok;
Guido van Rossumcd118802003-01-06 22:57:47 +00004927
Victor Stinner3c1e4812012-03-26 22:10:51 +02004928 b = _PyObject_GetAttrId((PyObject *)(Py_TYPE(right)), name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004929 if (b == NULL) {
4930 PyErr_Clear();
4931 /* If right doesn't have it, it's not overloaded */
4932 return 0;
4933 }
Guido van Rossumcd118802003-01-06 22:57:47 +00004934
Victor Stinner3c1e4812012-03-26 22:10:51 +02004935 a = _PyObject_GetAttrId((PyObject *)(Py_TYPE(left)), name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004936 if (a == NULL) {
4937 PyErr_Clear();
4938 Py_DECREF(b);
4939 /* If right has it but left doesn't, it's overloaded */
4940 return 1;
4941 }
Guido van Rossumcd118802003-01-06 22:57:47 +00004942
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004943 ok = PyObject_RichCompareBool(a, b, Py_NE);
4944 Py_DECREF(a);
4945 Py_DECREF(b);
4946 if (ok < 0) {
4947 PyErr_Clear();
4948 return 0;
4949 }
Guido van Rossumcd118802003-01-06 22:57:47 +00004950
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004951 return ok;
Guido van Rossumcd118802003-01-06 22:57:47 +00004952}
4953
Guido van Rossumdc91b992001-08-08 22:26:22 +00004954
4955#define SLOT1BINFULL(FUNCNAME, TESTFUNC, SLOTNAME, OPSTR, ROPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004956static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004957FUNCNAME(PyObject *self, PyObject *other) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004958{ \
Benjamin Petersonce798522012-01-22 11:24:29 -05004959 _Py_static_string(op_id, OPSTR); \
4960 _Py_static_string(rop_id, ROPSTR); \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004961 int do_other = Py_TYPE(self) != Py_TYPE(other) && \
4962 Py_TYPE(other)->tp_as_number != NULL && \
4963 Py_TYPE(other)->tp_as_number->SLOTNAME == TESTFUNC; \
4964 if (Py_TYPE(self)->tp_as_number != NULL && \
4965 Py_TYPE(self)->tp_as_number->SLOTNAME == TESTFUNC) { \
4966 PyObject *r; \
4967 if (do_other && \
4968 PyType_IsSubtype(Py_TYPE(other), Py_TYPE(self)) && \
Victor Stinner3c1e4812012-03-26 22:10:51 +02004969 method_is_overloaded(self, other, &rop_id)) { \
Benjamin Petersonce798522012-01-22 11:24:29 -05004970 r = call_maybe(other, &rop_id, "(O)", self); \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004971 if (r != Py_NotImplemented) \
4972 return r; \
4973 Py_DECREF(r); \
4974 do_other = 0; \
4975 } \
Benjamin Petersonce798522012-01-22 11:24:29 -05004976 r = call_maybe(self, &op_id, "(O)", other); \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004977 if (r != Py_NotImplemented || \
4978 Py_TYPE(other) == Py_TYPE(self)) \
4979 return r; \
4980 Py_DECREF(r); \
4981 } \
4982 if (do_other) { \
Benjamin Petersonce798522012-01-22 11:24:29 -05004983 return call_maybe(other, &rop_id, "(O)", self); \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004984 } \
Brian Curtindfc80e32011-08-10 20:28:54 -05004985 Py_RETURN_NOTIMPLEMENTED; \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004986}
4987
4988#define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004989 SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR)
Guido van Rossumdc91b992001-08-08 22:26:22 +00004990
4991#define SLOT2(FUNCNAME, OPSTR, ARG1TYPE, ARG2TYPE, ARGCODES) \
4992static PyObject * \
4993FUNCNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \
4994{ \
Benjamin Petersonce798522012-01-22 11:24:29 -05004995 _Py_static_string(id, #OPSTR); \
4996 return call_method(self, &id, "(" ARGCODES ")", arg1, arg2); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004997}
4998
Martin v. Löwis18e16552006-02-15 17:27:45 +00004999static Py_ssize_t
Tim Peters6d6c1a32001-08-02 04:15:00 +00005000slot_sq_length(PyObject *self)
5001{
Benjamin Petersonce798522012-01-22 11:24:29 -05005002 _Py_IDENTIFIER(__len__);
5003 PyObject *res = call_method(self, &PyId___len__, "()");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005004 Py_ssize_t len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005005
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005006 if (res == NULL)
5007 return -1;
5008 len = PyNumber_AsSsize_t(res, PyExc_OverflowError);
5009 Py_DECREF(res);
5010 if (len < 0) {
5011 if (!PyErr_Occurred())
5012 PyErr_SetString(PyExc_ValueError,
5013 "__len__() should return >= 0");
5014 return -1;
5015 }
5016 return len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005017}
5018
Guido van Rossumf4593e02001-10-03 12:09:30 +00005019/* Super-optimized version of slot_sq_item.
5020 Other slots could do the same... */
5021static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00005022slot_sq_item(PyObject *self, Py_ssize_t i)
Guido van Rossumf4593e02001-10-03 12:09:30 +00005023{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005024 PyObject *func, *args = NULL, *ival = NULL, *retval = NULL;
5025 descrgetfunc f;
Guido van Rossumf4593e02001-10-03 12:09:30 +00005026
Victor Stinner3c1e4812012-03-26 22:10:51 +02005027 func = _PyType_LookupId(Py_TYPE(self), &PyId___getitem__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005028 if (func != NULL) {
5029 if ((f = Py_TYPE(func)->tp_descr_get) == NULL)
5030 Py_INCREF(func);
5031 else {
5032 func = f(func, self, (PyObject *)(Py_TYPE(self)));
5033 if (func == NULL) {
5034 return NULL;
5035 }
5036 }
5037 ival = PyLong_FromSsize_t(i);
5038 if (ival != NULL) {
5039 args = PyTuple_New(1);
5040 if (args != NULL) {
5041 PyTuple_SET_ITEM(args, 0, ival);
5042 retval = PyObject_Call(func, args, NULL);
5043 Py_XDECREF(args);
5044 Py_XDECREF(func);
5045 return retval;
5046 }
5047 }
5048 }
5049 else {
Victor Stinner3c1e4812012-03-26 22:10:51 +02005050 PyObject *getitem_str = _PyUnicode_FromId(&PyId___getitem__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005051 PyErr_SetObject(PyExc_AttributeError, getitem_str);
5052 }
5053 Py_XDECREF(args);
5054 Py_XDECREF(ival);
5055 Py_XDECREF(func);
5056 return NULL;
Guido van Rossumf4593e02001-10-03 12:09:30 +00005057}
5058
Tim Peters6d6c1a32001-08-02 04:15:00 +00005059static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00005060slot_sq_ass_item(PyObject *self, Py_ssize_t index, PyObject *value)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005061{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005062 PyObject *res;
Benjamin Petersonce798522012-01-22 11:24:29 -05005063 _Py_IDENTIFIER(__delitem__);
5064 _Py_IDENTIFIER(__setitem__);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005065
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005066 if (value == NULL)
Benjamin Petersonce798522012-01-22 11:24:29 -05005067 res = call_method(self, &PyId___delitem__, "(n)", index);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005068 else
Benjamin Petersonce798522012-01-22 11:24:29 -05005069 res = call_method(self, &PyId___setitem__, "(nO)", index, value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005070 if (res == NULL)
5071 return -1;
5072 Py_DECREF(res);
5073 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005074}
5075
5076static int
Tim Peters6d6c1a32001-08-02 04:15:00 +00005077slot_sq_contains(PyObject *self, PyObject *value)
5078{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005079 PyObject *func, *res, *args;
5080 int result = -1;
Benjamin Petersonce798522012-01-22 11:24:29 -05005081 _Py_IDENTIFIER(__contains__);
Tim Petersbf9b2442003-03-23 05:35:36 +00005082
Benjamin Petersonce798522012-01-22 11:24:29 -05005083 func = lookup_maybe(self, &PyId___contains__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005084 if (func != NULL) {
5085 args = PyTuple_Pack(1, value);
5086 if (args == NULL)
5087 res = NULL;
5088 else {
5089 res = PyObject_Call(func, args, NULL);
5090 Py_DECREF(args);
5091 }
5092 Py_DECREF(func);
5093 if (res != NULL) {
5094 result = PyObject_IsTrue(res);
5095 Py_DECREF(res);
5096 }
5097 }
5098 else if (! PyErr_Occurred()) {
5099 /* Possible results: -1 and 1 */
5100 result = (int)_PySequence_IterSearch(self, value,
5101 PY_ITERSEARCH_CONTAINS);
5102 }
5103 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005104}
5105
Tim Peters6d6c1a32001-08-02 04:15:00 +00005106#define slot_mp_length slot_sq_length
5107
Guido van Rossumdc91b992001-08-08 22:26:22 +00005108SLOT1(slot_mp_subscript, "__getitem__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00005109
5110static int
5111slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value)
5112{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005113 PyObject *res;
Benjamin Petersonce798522012-01-22 11:24:29 -05005114 _Py_IDENTIFIER(__delitem__);
5115 _Py_IDENTIFIER(__setitem__);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005116
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005117 if (value == NULL)
Benjamin Petersonce798522012-01-22 11:24:29 -05005118 res = call_method(self, &PyId___delitem__, "(O)", key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005119 else
Benjamin Petersonce798522012-01-22 11:24:29 -05005120 res = call_method(self, &PyId___setitem__, "(OO)", key, value);
5121
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005122 if (res == NULL)
5123 return -1;
5124 Py_DECREF(res);
5125 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005126}
5127
Guido van Rossumdc91b992001-08-08 22:26:22 +00005128SLOT1BIN(slot_nb_add, nb_add, "__add__", "__radd__")
5129SLOT1BIN(slot_nb_subtract, nb_subtract, "__sub__", "__rsub__")
5130SLOT1BIN(slot_nb_multiply, nb_multiply, "__mul__", "__rmul__")
Guido van Rossumdc91b992001-08-08 22:26:22 +00005131SLOT1BIN(slot_nb_remainder, nb_remainder, "__mod__", "__rmod__")
5132SLOT1BIN(slot_nb_divmod, nb_divmod, "__divmod__", "__rdivmod__")
5133
Jeremy Hylton938ace62002-07-17 16:30:39 +00005134static PyObject *slot_nb_power(PyObject *, PyObject *, PyObject *);
Guido van Rossumdc91b992001-08-08 22:26:22 +00005135
5136SLOT1BINFULL(slot_nb_power_binary, slot_nb_power,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005137 nb_power, "__pow__", "__rpow__")
Guido van Rossumdc91b992001-08-08 22:26:22 +00005138
5139static PyObject *
5140slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus)
5141{
Benjamin Petersonce798522012-01-22 11:24:29 -05005142 _Py_IDENTIFIER(__pow__);
Guido van Rossum2730b132001-08-28 18:22:14 +00005143
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005144 if (modulus == Py_None)
5145 return slot_nb_power_binary(self, other);
5146 /* Three-arg power doesn't use __rpow__. But ternary_op
5147 can call this when the second argument's type uses
5148 slot_nb_power, so check before calling self.__pow__. */
5149 if (Py_TYPE(self)->tp_as_number != NULL &&
5150 Py_TYPE(self)->tp_as_number->nb_power == slot_nb_power) {
Benjamin Petersonce798522012-01-22 11:24:29 -05005151 return call_method(self, &PyId___pow__, "(OO)", other, modulus);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005152 }
Brian Curtindfc80e32011-08-10 20:28:54 -05005153 Py_RETURN_NOTIMPLEMENTED;
Guido van Rossumdc91b992001-08-08 22:26:22 +00005154}
5155
5156SLOT0(slot_nb_negative, "__neg__")
5157SLOT0(slot_nb_positive, "__pos__")
5158SLOT0(slot_nb_absolute, "__abs__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00005159
5160static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00005161slot_nb_bool(PyObject *self)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005162{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005163 PyObject *func, *args;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005164 int result = -1;
5165 int using_len = 0;
Benjamin Petersonce798522012-01-22 11:24:29 -05005166 _Py_IDENTIFIER(__len__);
5167 _Py_IDENTIFIER(__bool__);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005168
Benjamin Petersonce798522012-01-22 11:24:29 -05005169 func = lookup_maybe(self, &PyId___bool__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005170 if (func == NULL) {
5171 if (PyErr_Occurred())
5172 return -1;
Benjamin Petersonce798522012-01-22 11:24:29 -05005173 func = lookup_maybe(self, &PyId___len__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005174 if (func == NULL)
5175 return PyErr_Occurred() ? -1 : 1;
5176 using_len = 1;
5177 }
5178 args = PyTuple_New(0);
5179 if (args != NULL) {
5180 PyObject *temp = PyObject_Call(func, args, NULL);
5181 Py_DECREF(args);
5182 if (temp != NULL) {
5183 if (using_len) {
5184 /* enforced by slot_nb_len */
5185 result = PyObject_IsTrue(temp);
5186 }
5187 else if (PyBool_Check(temp)) {
5188 result = PyObject_IsTrue(temp);
5189 }
5190 else {
5191 PyErr_Format(PyExc_TypeError,
5192 "__bool__ should return "
5193 "bool, returned %s",
5194 Py_TYPE(temp)->tp_name);
5195 result = -1;
5196 }
5197 Py_DECREF(temp);
5198 }
5199 }
5200 Py_DECREF(func);
5201 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005202}
5203
Guido van Rossum38fff8c2006-03-07 18:50:55 +00005204
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00005205static PyObject *
Guido van Rossum38fff8c2006-03-07 18:50:55 +00005206slot_nb_index(PyObject *self)
5207{
Benjamin Petersonce798522012-01-22 11:24:29 -05005208 _Py_IDENTIFIER(__index__);
5209 return call_method(self, &PyId___index__, "()");
Guido van Rossum38fff8c2006-03-07 18:50:55 +00005210}
5211
5212
Guido van Rossumdc91b992001-08-08 22:26:22 +00005213SLOT0(slot_nb_invert, "__invert__")
5214SLOT1BIN(slot_nb_lshift, nb_lshift, "__lshift__", "__rlshift__")
5215SLOT1BIN(slot_nb_rshift, nb_rshift, "__rshift__", "__rrshift__")
5216SLOT1BIN(slot_nb_and, nb_and, "__and__", "__rand__")
5217SLOT1BIN(slot_nb_xor, nb_xor, "__xor__", "__rxor__")
5218SLOT1BIN(slot_nb_or, nb_or, "__or__", "__ror__")
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00005219
Guido van Rossumdc91b992001-08-08 22:26:22 +00005220SLOT0(slot_nb_int, "__int__")
Guido van Rossumdc91b992001-08-08 22:26:22 +00005221SLOT0(slot_nb_float, "__float__")
Guido van Rossumdc91b992001-08-08 22:26:22 +00005222SLOT1(slot_nb_inplace_add, "__iadd__", PyObject *, "O")
5223SLOT1(slot_nb_inplace_subtract, "__isub__", PyObject *, "O")
5224SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *, "O")
Guido van Rossumdc91b992001-08-08 22:26:22 +00005225SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *, "O")
Thomas Wouterscf297e42007-02-23 15:07:44 +00005226/* Can't use SLOT1 here, because nb_inplace_power is ternary */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005227static PyObject *
5228slot_nb_inplace_power(PyObject *self, PyObject * arg1, PyObject *arg2)
5229{
Benjamin Petersonce798522012-01-22 11:24:29 -05005230 _Py_IDENTIFIER(__ipow__);
5231 return call_method(self, &PyId___ipow__, "(" "O" ")", arg1);
Thomas Wouterscf297e42007-02-23 15:07:44 +00005232}
Guido van Rossumdc91b992001-08-08 22:26:22 +00005233SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *, "O")
5234SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *, "O")
5235SLOT1(slot_nb_inplace_and, "__iand__", PyObject *, "O")
5236SLOT1(slot_nb_inplace_xor, "__ixor__", PyObject *, "O")
5237SLOT1(slot_nb_inplace_or, "__ior__", PyObject *, "O")
5238SLOT1BIN(slot_nb_floor_divide, nb_floor_divide,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005239 "__floordiv__", "__rfloordiv__")
Guido van Rossumdc91b992001-08-08 22:26:22 +00005240SLOT1BIN(slot_nb_true_divide, nb_true_divide, "__truediv__", "__rtruediv__")
5241SLOT1(slot_nb_inplace_floor_divide, "__ifloordiv__", PyObject *, "O")
5242SLOT1(slot_nb_inplace_true_divide, "__itruediv__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00005243
Guido van Rossumb8f63662001-08-15 23:57:02 +00005244static PyObject *
5245slot_tp_repr(PyObject *self)
5246{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005247 PyObject *func, *res;
Benjamin Petersonce798522012-01-22 11:24:29 -05005248 _Py_IDENTIFIER(__repr__);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005249
Benjamin Petersonce798522012-01-22 11:24:29 -05005250 func = lookup_method(self, &PyId___repr__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005251 if (func != NULL) {
5252 res = PyEval_CallObject(func, NULL);
5253 Py_DECREF(func);
5254 return res;
5255 }
5256 PyErr_Clear();
5257 return PyUnicode_FromFormat("<%s object at %p>",
5258 Py_TYPE(self)->tp_name, self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005259}
5260
5261static PyObject *
5262slot_tp_str(PyObject *self)
5263{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005264 PyObject *func, *res;
Benjamin Petersonce798522012-01-22 11:24:29 -05005265 _Py_IDENTIFIER(__str__);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005266
Benjamin Petersonce798522012-01-22 11:24:29 -05005267 func = lookup_method(self, &PyId___str__);
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 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005274 /* PyObject *ress; */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005275 PyErr_Clear();
5276 res = slot_tp_repr(self);
5277 if (!res)
5278 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005279 /* XXX this is non-sensical. Why should we return
5280 a bytes object from __str__. Is this code even
5281 used? - mvl */
5282 assert(0);
5283 return res;
5284 /*
Victor Stinnerf3fd7332011-03-02 01:03:11 +00005285 ress = _PyUnicode_AsDefaultEncodedString(res);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005286 Py_DECREF(res);
5287 return ress;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005288 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005289 }
Guido van Rossumb8f63662001-08-15 23:57:02 +00005290}
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
5669/* Table mapping __foo__ names to tp_foo offsets and slot_tp_foo wrapper
Tim Petersbf9b2442003-03-23 05:35:36 +00005670 functions. The offsets here are relative to the 'PyHeapTypeObject'
Guido van Rossume5c691a2003-03-07 15:13:17 +00005671 structure, which incorporates the additional structures used for numbers,
5672 sequences and mappings.
5673 Note that multiple names may map to the same slot (e.g. __eq__,
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005674 __ne__ etc. all map to tp_richcompare) and one name may map to multiple
Guido van Rossumc334df52002-04-04 23:44:47 +00005675 slots (e.g. __str__ affects tp_str as well as tp_repr). The table is
5676 terminated with an all-zero entry. (This table is further initialized and
5677 sorted in init_slotdefs() below.) */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005678
Guido van Rossum6d204072001-10-21 00:44:31 +00005679typedef struct wrapperbase slotdef;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005680
5681#undef TPSLOT
Guido van Rossumc8e56452001-10-22 00:43:43 +00005682#undef FLSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005683#undef ETSLOT
5684#undef SQSLOT
5685#undef MPSLOT
5686#undef NBSLOT
Guido van Rossum6d204072001-10-21 00:44:31 +00005687#undef UNSLOT
5688#undef IBSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005689#undef BINSLOT
5690#undef RBINSLOT
5691
Guido van Rossum6d204072001-10-21 00:44:31 +00005692#define TPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005693 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
5694 PyDoc_STR(DOC)}
Guido van Rossumc8e56452001-10-22 00:43:43 +00005695#define FLSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC, FLAGS) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005696 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
5697 PyDoc_STR(DOC), FLAGS}
Guido van Rossum6d204072001-10-21 00:44:31 +00005698#define ETSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005699 {NAME, offsetof(PyHeapTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
5700 PyDoc_STR(DOC)}
Guido van Rossum6d204072001-10-21 00:44:31 +00005701#define SQSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005702 ETSLOT(NAME, as_sequence.SLOT, FUNCTION, WRAPPER, DOC)
Guido van Rossum6d204072001-10-21 00:44:31 +00005703#define MPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005704 ETSLOT(NAME, as_mapping.SLOT, FUNCTION, WRAPPER, DOC)
Guido van Rossum6d204072001-10-21 00:44:31 +00005705#define NBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005706 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, DOC)
Guido van Rossum6d204072001-10-21 00:44:31 +00005707#define UNSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005708 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
5709 "x." NAME "() <==> " DOC)
Guido van Rossum6d204072001-10-21 00:44:31 +00005710#define IBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005711 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
5712 "x." NAME "(y) <==> x" DOC "y")
Guido van Rossum6d204072001-10-21 00:44:31 +00005713#define BINSLOT(NAME, SLOT, FUNCTION, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005714 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
5715 "x." NAME "(y) <==> x" DOC "y")
Guido van Rossum6d204072001-10-21 00:44:31 +00005716#define RBINSLOT(NAME, SLOT, FUNCTION, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005717 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
5718 "x." NAME "(y) <==> y" DOC "x")
Anthony Baxter56616992005-06-03 14:12:21 +00005719#define BINSLOTNOTINFIX(NAME, SLOT, FUNCTION, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005720 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
5721 "x." NAME "(y) <==> " DOC)
Anthony Baxter56616992005-06-03 14:12:21 +00005722#define RBINSLOTNOTINFIX(NAME, SLOT, FUNCTION, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005723 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
5724 "x." NAME "(y) <==> " DOC)
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005725
5726static slotdef slotdefs[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005727 SQSLOT("__len__", sq_length, slot_sq_length, wrap_lenfunc,
5728 "x.__len__() <==> len(x)"),
5729 /* Heap types defining __add__/__mul__ have sq_concat/sq_repeat == NULL.
5730 The logic in abstract.c always falls back to nb_add/nb_multiply in
5731 this case. Defining both the nb_* and the sq_* slots to call the
5732 user-defined methods has unexpected side-effects, as shown by
5733 test_descr.notimplemented() */
5734 SQSLOT("__add__", sq_concat, NULL, wrap_binaryfunc,
5735 "x.__add__(y) <==> x+y"),
5736 SQSLOT("__mul__", sq_repeat, NULL, wrap_indexargfunc,
5737 "x.__mul__(n) <==> x*n"),
5738 SQSLOT("__rmul__", sq_repeat, NULL, wrap_indexargfunc,
5739 "x.__rmul__(n) <==> n*x"),
5740 SQSLOT("__getitem__", sq_item, slot_sq_item, wrap_sq_item,
5741 "x.__getitem__(y) <==> x[y]"),
5742 SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_setitem,
5743 "x.__setitem__(i, y) <==> x[i]=y"),
5744 SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_delitem,
5745 "x.__delitem__(y) <==> del x[y]"),
5746 SQSLOT("__contains__", sq_contains, slot_sq_contains, wrap_objobjproc,
5747 "x.__contains__(y) <==> y in x"),
5748 SQSLOT("__iadd__", sq_inplace_concat, NULL,
5749 wrap_binaryfunc, "x.__iadd__(y) <==> x+=y"),
5750 SQSLOT("__imul__", sq_inplace_repeat, NULL,
5751 wrap_indexargfunc, "x.__imul__(y) <==> x*=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005752
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005753 MPSLOT("__len__", mp_length, slot_mp_length, wrap_lenfunc,
5754 "x.__len__() <==> len(x)"),
5755 MPSLOT("__getitem__", mp_subscript, slot_mp_subscript,
5756 wrap_binaryfunc,
5757 "x.__getitem__(y) <==> x[y]"),
5758 MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript,
5759 wrap_objobjargproc,
5760 "x.__setitem__(i, y) <==> x[i]=y"),
5761 MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript,
5762 wrap_delitem,
5763 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005764
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005765 BINSLOT("__add__", nb_add, slot_nb_add,
5766 "+"),
5767 RBINSLOT("__radd__", nb_add, slot_nb_add,
5768 "+"),
5769 BINSLOT("__sub__", nb_subtract, slot_nb_subtract,
5770 "-"),
5771 RBINSLOT("__rsub__", nb_subtract, slot_nb_subtract,
5772 "-"),
5773 BINSLOT("__mul__", nb_multiply, slot_nb_multiply,
5774 "*"),
5775 RBINSLOT("__rmul__", nb_multiply, slot_nb_multiply,
5776 "*"),
5777 BINSLOT("__mod__", nb_remainder, slot_nb_remainder,
5778 "%"),
5779 RBINSLOT("__rmod__", nb_remainder, slot_nb_remainder,
5780 "%"),
5781 BINSLOTNOTINFIX("__divmod__", nb_divmod, slot_nb_divmod,
5782 "divmod(x, y)"),
5783 RBINSLOTNOTINFIX("__rdivmod__", nb_divmod, slot_nb_divmod,
5784 "divmod(y, x)"),
5785 NBSLOT("__pow__", nb_power, slot_nb_power, wrap_ternaryfunc,
5786 "x.__pow__(y[, z]) <==> pow(x, y[, z])"),
5787 NBSLOT("__rpow__", nb_power, slot_nb_power, wrap_ternaryfunc_r,
5788 "y.__rpow__(x[, z]) <==> pow(x, y[, z])"),
5789 UNSLOT("__neg__", nb_negative, slot_nb_negative, wrap_unaryfunc, "-x"),
5790 UNSLOT("__pos__", nb_positive, slot_nb_positive, wrap_unaryfunc, "+x"),
5791 UNSLOT("__abs__", nb_absolute, slot_nb_absolute, wrap_unaryfunc,
5792 "abs(x)"),
5793 UNSLOT("__bool__", nb_bool, slot_nb_bool, wrap_inquirypred,
5794 "x != 0"),
5795 UNSLOT("__invert__", nb_invert, slot_nb_invert, wrap_unaryfunc, "~x"),
5796 BINSLOT("__lshift__", nb_lshift, slot_nb_lshift, "<<"),
5797 RBINSLOT("__rlshift__", nb_lshift, slot_nb_lshift, "<<"),
5798 BINSLOT("__rshift__", nb_rshift, slot_nb_rshift, ">>"),
5799 RBINSLOT("__rrshift__", nb_rshift, slot_nb_rshift, ">>"),
5800 BINSLOT("__and__", nb_and, slot_nb_and, "&"),
5801 RBINSLOT("__rand__", nb_and, slot_nb_and, "&"),
5802 BINSLOT("__xor__", nb_xor, slot_nb_xor, "^"),
5803 RBINSLOT("__rxor__", nb_xor, slot_nb_xor, "^"),
5804 BINSLOT("__or__", nb_or, slot_nb_or, "|"),
5805 RBINSLOT("__ror__", nb_or, slot_nb_or, "|"),
5806 UNSLOT("__int__", nb_int, slot_nb_int, wrap_unaryfunc,
5807 "int(x)"),
5808 UNSLOT("__float__", nb_float, slot_nb_float, wrap_unaryfunc,
5809 "float(x)"),
5810 NBSLOT("__index__", nb_index, slot_nb_index, wrap_unaryfunc,
5811 "x[y:z] <==> x[y.__index__():z.__index__()]"),
5812 IBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add,
Eli Benderskyd3baae72011-11-11 16:57:05 +02005813 wrap_binaryfunc, "+="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005814 IBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract,
Eli Benderskyd3baae72011-11-11 16:57:05 +02005815 wrap_binaryfunc, "-="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005816 IBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply,
Eli Benderskyd3baae72011-11-11 16:57:05 +02005817 wrap_binaryfunc, "*="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005818 IBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder,
Eli Benderskyd3baae72011-11-11 16:57:05 +02005819 wrap_binaryfunc, "%="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005820 IBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power,
Eli Benderskyd3baae72011-11-11 16:57:05 +02005821 wrap_binaryfunc, "**="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005822 IBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift,
Eli Benderskyd3baae72011-11-11 16:57:05 +02005823 wrap_binaryfunc, "<<="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005824 IBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift,
Eli Benderskyd3baae72011-11-11 16:57:05 +02005825 wrap_binaryfunc, ">>="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005826 IBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and,
Eli Benderskyd3baae72011-11-11 16:57:05 +02005827 wrap_binaryfunc, "&="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005828 IBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor,
Eli Benderskyd3baae72011-11-11 16:57:05 +02005829 wrap_binaryfunc, "^="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005830 IBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or,
Eli Benderskyd3baae72011-11-11 16:57:05 +02005831 wrap_binaryfunc, "|="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005832 BINSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
5833 RBINSLOT("__rfloordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
5834 BINSLOT("__truediv__", nb_true_divide, slot_nb_true_divide, "/"),
5835 RBINSLOT("__rtruediv__", nb_true_divide, slot_nb_true_divide, "/"),
5836 IBSLOT("__ifloordiv__", nb_inplace_floor_divide,
5837 slot_nb_inplace_floor_divide, wrap_binaryfunc, "//"),
5838 IBSLOT("__itruediv__", nb_inplace_true_divide,
5839 slot_nb_inplace_true_divide, wrap_binaryfunc, "/"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005840
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005841 TPSLOT("__str__", tp_str, slot_tp_str, wrap_unaryfunc,
5842 "x.__str__() <==> str(x)"),
5843 TPSLOT("__repr__", tp_repr, slot_tp_repr, wrap_unaryfunc,
5844 "x.__repr__() <==> repr(x)"),
5845 TPSLOT("__hash__", tp_hash, slot_tp_hash, wrap_hashfunc,
5846 "x.__hash__() <==> hash(x)"),
5847 FLSLOT("__call__", tp_call, slot_tp_call, (wrapperfunc)wrap_call,
5848 "x.__call__(...) <==> x(...)", PyWrapperFlag_KEYWORDS),
5849 TPSLOT("__getattribute__", tp_getattro, slot_tp_getattr_hook,
5850 wrap_binaryfunc, "x.__getattribute__('name') <==> x.name"),
5851 TPSLOT("__getattribute__", tp_getattr, NULL, NULL, ""),
5852 TPSLOT("__getattr__", tp_getattro, slot_tp_getattr_hook, NULL, ""),
5853 TPSLOT("__getattr__", tp_getattr, NULL, NULL, ""),
5854 TPSLOT("__setattr__", tp_setattro, slot_tp_setattro, wrap_setattr,
5855 "x.__setattr__('name', value) <==> x.name = value"),
5856 TPSLOT("__setattr__", tp_setattr, NULL, NULL, ""),
5857 TPSLOT("__delattr__", tp_setattro, slot_tp_setattro, wrap_delattr,
5858 "x.__delattr__('name') <==> del x.name"),
5859 TPSLOT("__delattr__", tp_setattr, NULL, NULL, ""),
5860 TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare, richcmp_lt,
5861 "x.__lt__(y) <==> x<y"),
5862 TPSLOT("__le__", tp_richcompare, slot_tp_richcompare, richcmp_le,
5863 "x.__le__(y) <==> x<=y"),
5864 TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare, richcmp_eq,
5865 "x.__eq__(y) <==> x==y"),
5866 TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare, richcmp_ne,
5867 "x.__ne__(y) <==> x!=y"),
5868 TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare, richcmp_gt,
5869 "x.__gt__(y) <==> x>y"),
5870 TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare, richcmp_ge,
5871 "x.__ge__(y) <==> x>=y"),
5872 TPSLOT("__iter__", tp_iter, slot_tp_iter, wrap_unaryfunc,
5873 "x.__iter__() <==> iter(x)"),
5874 TPSLOT("__next__", tp_iternext, slot_tp_iternext, wrap_next,
5875 "x.__next__() <==> next(x)"),
5876 TPSLOT("__get__", tp_descr_get, slot_tp_descr_get, wrap_descr_get,
5877 "descr.__get__(obj[, type]) -> value"),
5878 TPSLOT("__set__", tp_descr_set, slot_tp_descr_set, wrap_descr_set,
5879 "descr.__set__(obj, value)"),
5880 TPSLOT("__delete__", tp_descr_set, slot_tp_descr_set,
5881 wrap_descr_delete, "descr.__delete__(obj)"),
5882 FLSLOT("__init__", tp_init, slot_tp_init, (wrapperfunc)wrap_init,
5883 "x.__init__(...) initializes x; "
Alexander Belopolsky977a6842010-08-16 20:17:07 +00005884 "see help(type(x)) for signature",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005885 PyWrapperFlag_KEYWORDS),
5886 TPSLOT("__new__", tp_new, slot_tp_new, NULL, ""),
5887 TPSLOT("__del__", tp_del, slot_tp_del, NULL, ""),
5888 {NULL}
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005889};
5890
Guido van Rossumc334df52002-04-04 23:44:47 +00005891/* Given a type pointer and an offset gotten from a slotdef entry, return a
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005892 pointer to the actual slot. This is not quite the same as simply adding
Guido van Rossumc334df52002-04-04 23:44:47 +00005893 the offset to the type pointer, since it takes care to indirect through the
5894 proper indirection pointer (as_buffer, etc.); it returns NULL if the
5895 indirection pointer is NULL. */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005896static void **
Martin v. Löwis18e16552006-02-15 17:27:45 +00005897slotptr(PyTypeObject *type, int ioffset)
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005898{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005899 char *ptr;
5900 long offset = ioffset;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005901
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005902 /* Note: this depends on the order of the members of PyHeapTypeObject! */
5903 assert(offset >= 0);
5904 assert((size_t)offset < offsetof(PyHeapTypeObject, as_buffer));
5905 if ((size_t)offset >= offsetof(PyHeapTypeObject, as_sequence)) {
5906 ptr = (char *)type->tp_as_sequence;
5907 offset -= offsetof(PyHeapTypeObject, as_sequence);
5908 }
5909 else if ((size_t)offset >= offsetof(PyHeapTypeObject, as_mapping)) {
5910 ptr = (char *)type->tp_as_mapping;
5911 offset -= offsetof(PyHeapTypeObject, as_mapping);
5912 }
5913 else if ((size_t)offset >= offsetof(PyHeapTypeObject, as_number)) {
5914 ptr = (char *)type->tp_as_number;
5915 offset -= offsetof(PyHeapTypeObject, as_number);
5916 }
5917 else {
5918 ptr = (char *)type;
5919 }
5920 if (ptr != NULL)
5921 ptr += offset;
5922 return (void **)ptr;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005923}
Guido van Rossumf040ede2001-08-07 16:40:56 +00005924
Guido van Rossumc334df52002-04-04 23:44:47 +00005925/* Length of array of slotdef pointers used to store slots with the
5926 same __name__. There should be at most MAX_EQUIV-1 slotdef entries with
5927 the same __name__, for any __name__. Since that's a static property, it is
5928 appropriate to declare fixed-size arrays for this. */
5929#define MAX_EQUIV 10
5930
5931/* Return a slot pointer for a given name, but ONLY if the attribute has
5932 exactly one slot function. The name must be an interned string. */
5933static void **
5934resolve_slotdups(PyTypeObject *type, PyObject *name)
5935{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005936 /* XXX Maybe this could be optimized more -- but is it worth it? */
Guido van Rossumc334df52002-04-04 23:44:47 +00005937
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005938 /* pname and ptrs act as a little cache */
5939 static PyObject *pname;
5940 static slotdef *ptrs[MAX_EQUIV];
5941 slotdef *p, **pp;
5942 void **res, **ptr;
Guido van Rossumc334df52002-04-04 23:44:47 +00005943
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005944 if (pname != name) {
5945 /* Collect all slotdefs that match name into ptrs. */
5946 pname = name;
5947 pp = ptrs;
5948 for (p = slotdefs; p->name_strobj; p++) {
5949 if (p->name_strobj == name)
5950 *pp++ = p;
5951 }
5952 *pp = NULL;
5953 }
Guido van Rossumc334df52002-04-04 23:44:47 +00005954
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005955 /* Look in all matching slots of the type; if exactly one of these has
5956 a filled-in slot, return its value. Otherwise return NULL. */
5957 res = NULL;
5958 for (pp = ptrs; *pp; pp++) {
5959 ptr = slotptr(type, (*pp)->offset);
5960 if (ptr == NULL || *ptr == NULL)
5961 continue;
5962 if (res != NULL)
5963 return NULL;
5964 res = ptr;
5965 }
5966 return res;
Guido van Rossumc334df52002-04-04 23:44:47 +00005967}
5968
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005969/* Common code for update_slots_callback() and fixup_slot_dispatchers(). This
Guido van Rossumc334df52002-04-04 23:44:47 +00005970 does some incredibly complex thinking and then sticks something into the
5971 slot. (It sees if the adjacent slotdefs for the same slot have conflicting
5972 interests, and then stores a generic wrapper or a specific function into
5973 the slot.) Return a pointer to the next slotdef with a different offset,
5974 because that's convenient for fixup_slot_dispatchers(). */
5975static slotdef *
5976update_one_slot(PyTypeObject *type, slotdef *p)
5977{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005978 PyObject *descr;
5979 PyWrapperDescrObject *d;
5980 void *generic = NULL, *specific = NULL;
5981 int use_generic = 0;
5982 int offset = p->offset;
5983 void **ptr = slotptr(type, offset);
Guido van Rossumc334df52002-04-04 23:44:47 +00005984
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005985 if (ptr == NULL) {
5986 do {
5987 ++p;
5988 } while (p->offset == offset);
5989 return p;
5990 }
5991 do {
5992 descr = _PyType_Lookup(type, p->name_strobj);
5993 if (descr == NULL) {
5994 if (ptr == (void**)&type->tp_iternext) {
Trent Nelsonab02db22012-09-18 21:58:03 -04005995 specific = (void *)_PyObject_NextNotImplemented;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005996 }
5997 continue;
5998 }
Benjamin Peterson7b166872012-04-24 11:06:25 -04005999 if (Py_TYPE(descr) == &PyWrapperDescr_Type &&
6000 ((PyWrapperDescrObject *)descr)->d_base->name_strobj == p->name_strobj) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006001 void **tptr = resolve_slotdups(type, p->name_strobj);
6002 if (tptr == NULL || tptr == ptr)
6003 generic = p->function;
6004 d = (PyWrapperDescrObject *)descr;
6005 if (d->d_base->wrapper == p->wrapper &&
6006 PyType_IsSubtype(type, PyDescr_TYPE(d)))
6007 {
6008 if (specific == NULL ||
6009 specific == d->d_wrapped)
6010 specific = d->d_wrapped;
6011 else
6012 use_generic = 1;
6013 }
6014 }
6015 else if (Py_TYPE(descr) == &PyCFunction_Type &&
6016 PyCFunction_GET_FUNCTION(descr) ==
6017 (PyCFunction)tp_new_wrapper &&
6018 ptr == (void**)&type->tp_new)
6019 {
6020 /* The __new__ wrapper is not a wrapper descriptor,
6021 so must be special-cased differently.
6022 If we don't do this, creating an instance will
6023 always use slot_tp_new which will look up
6024 __new__ in the MRO which will call tp_new_wrapper
6025 which will look through the base classes looking
6026 for a static base and call its tp_new (usually
6027 PyType_GenericNew), after performing various
6028 sanity checks and constructing a new argument
6029 list. Cut all that nonsense short -- this speeds
6030 up instance creation tremendously. */
6031 specific = (void *)type->tp_new;
6032 /* XXX I'm not 100% sure that there isn't a hole
6033 in this reasoning that requires additional
6034 sanity checks. I'll buy the first person to
6035 point out a bug in this reasoning a beer. */
6036 }
6037 else if (descr == Py_None &&
6038 ptr == (void**)&type->tp_hash) {
6039 /* We specifically allow __hash__ to be set to None
6040 to prevent inheritance of the default
6041 implementation from object.__hash__ */
Trent Nelsonab02db22012-09-18 21:58:03 -04006042 specific = (void *)PyObject_HashNotImplemented;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006043 }
6044 else {
6045 use_generic = 1;
6046 generic = p->function;
6047 }
6048 } while ((++p)->offset == offset);
6049 if (specific && !use_generic)
6050 *ptr = specific;
6051 else
6052 *ptr = generic;
6053 return p;
Guido van Rossumc334df52002-04-04 23:44:47 +00006054}
6055
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006056/* In the type, update the slots whose slotdefs are gathered in the pp array.
6057 This is a callback for update_subclasses(). */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006058static int
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006059update_slots_callback(PyTypeObject *type, void *data)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006060{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006061 slotdef **pp = (slotdef **)data;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006062
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006063 for (; *pp; pp++)
6064 update_one_slot(type, *pp);
6065 return 0;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006066}
6067
Guido van Rossumc334df52002-04-04 23:44:47 +00006068/* Comparison function for qsort() to compare slotdefs by their offset, and
6069 for equal offset by their address (to force a stable sort). */
Guido van Rossumd396b9c2001-10-13 20:02:41 +00006070static int
6071slotdef_cmp(const void *aa, const void *bb)
6072{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006073 const slotdef *a = (const slotdef *)aa, *b = (const slotdef *)bb;
6074 int c = a->offset - b->offset;
6075 if (c != 0)
6076 return c;
6077 else
6078 /* Cannot use a-b, as this gives off_t,
6079 which may lose precision when converted to int. */
6080 return (a > b) ? 1 : (a < b) ? -1 : 0;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00006081}
6082
Guido van Rossumc334df52002-04-04 23:44:47 +00006083/* Initialize the slotdefs table by adding interned string objects for the
6084 names and sorting the entries. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006085static void
Guido van Rossumd396b9c2001-10-13 20:02:41 +00006086init_slotdefs(void)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006087{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006088 slotdef *p;
6089 static int initialized = 0;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006090
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006091 if (initialized)
6092 return;
6093 for (p = slotdefs; p->name; p++) {
6094 p->name_strobj = PyUnicode_InternFromString(p->name);
6095 if (!p->name_strobj)
6096 Py_FatalError("Out of memory interning slotdef names");
6097 }
6098 qsort((void *)slotdefs, (size_t)(p-slotdefs), sizeof(slotdef),
6099 slotdef_cmp);
6100 initialized = 1;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006101}
6102
Guido van Rossumc334df52002-04-04 23:44:47 +00006103/* Update the slots after assignment to a class (type) attribute. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006104static int
6105update_slot(PyTypeObject *type, PyObject *name)
6106{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006107 slotdef *ptrs[MAX_EQUIV];
6108 slotdef *p;
6109 slotdef **pp;
6110 int offset;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006111
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006112 /* Clear the VALID_VERSION flag of 'type' and all its
6113 subclasses. This could possibly be unified with the
6114 update_subclasses() recursion below, but carefully:
6115 they each have their own conditions on which to stop
6116 recursing into subclasses. */
6117 PyType_Modified(type);
Christian Heimesa62da1d2008-01-12 19:39:10 +00006118
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006119 init_slotdefs();
6120 pp = ptrs;
6121 for (p = slotdefs; p->name; p++) {
6122 /* XXX assume name is interned! */
6123 if (p->name_strobj == name)
6124 *pp++ = p;
6125 }
6126 *pp = NULL;
6127 for (pp = ptrs; *pp; pp++) {
6128 p = *pp;
6129 offset = p->offset;
6130 while (p > slotdefs && (p-1)->offset == offset)
6131 --p;
6132 *pp = p;
6133 }
6134 if (ptrs[0] == NULL)
6135 return 0; /* Not an attribute that affects any slots */
6136 return update_subclasses(type, name,
6137 update_slots_callback, (void *)ptrs);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006138}
6139
Guido van Rossumc334df52002-04-04 23:44:47 +00006140/* Store the proper functions in the slot dispatches at class (type)
6141 definition time, based upon which operations the class overrides in its
6142 dict. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00006143static void
Guido van Rossum7b9144b2001-10-09 19:39:46 +00006144fixup_slot_dispatchers(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00006145{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006146 slotdef *p;
Tim Peters6d6c1a32001-08-02 04:15:00 +00006147
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006148 init_slotdefs();
6149 for (p = slotdefs; p->name; )
6150 p = update_one_slot(type, p);
Tim Peters6d6c1a32001-08-02 04:15:00 +00006151}
Guido van Rossum705f0f52001-08-24 16:47:00 +00006152
Michael W. Hudson98bbc492002-11-26 14:47:27 +00006153static void
6154update_all_slots(PyTypeObject* type)
6155{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006156 slotdef *p;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00006157
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006158 init_slotdefs();
6159 for (p = slotdefs; p->name; p++) {
6160 /* update_slot returns int but can't actually fail */
6161 update_slot(type, p->name_strobj);
6162 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +00006163}
6164
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006165/* recurse_down_subclasses() and update_subclasses() are mutually
6166 recursive functions to call a callback for all subclasses,
6167 but refraining from recursing into subclasses that define 'name'. */
6168
6169static int
6170update_subclasses(PyTypeObject *type, PyObject *name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006171 update_callback callback, void *data)
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006172{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006173 if (callback(type, data) < 0)
6174 return -1;
6175 return recurse_down_subclasses(type, name, callback, data);
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006176}
6177
6178static int
6179recurse_down_subclasses(PyTypeObject *type, PyObject *name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006180 update_callback callback, void *data)
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006181{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006182 PyTypeObject *subclass;
6183 PyObject *ref, *subclasses, *dict;
6184 Py_ssize_t i, n;
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006185
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006186 subclasses = type->tp_subclasses;
6187 if (subclasses == NULL)
6188 return 0;
6189 assert(PyList_Check(subclasses));
6190 n = PyList_GET_SIZE(subclasses);
6191 for (i = 0; i < n; i++) {
6192 ref = PyList_GET_ITEM(subclasses, i);
6193 assert(PyWeakref_CheckRef(ref));
6194 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
6195 assert(subclass != NULL);
6196 if ((PyObject *)subclass == Py_None)
6197 continue;
6198 assert(PyType_Check(subclass));
6199 /* Avoid recursing down into unaffected classes */
6200 dict = subclass->tp_dict;
6201 if (dict != NULL && PyDict_Check(dict) &&
6202 PyDict_GetItem(dict, name) != NULL)
6203 continue;
6204 if (update_subclasses(subclass, name, callback, data) < 0)
6205 return -1;
6206 }
6207 return 0;
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006208}
6209
Guido van Rossum6d204072001-10-21 00:44:31 +00006210/* This function is called by PyType_Ready() to populate the type's
6211 dictionary with method descriptors for function slots. For each
Guido van Rossum09638c12002-06-13 19:17:46 +00006212 function slot (like tp_repr) that's defined in the type, one or more
6213 corresponding descriptors are added in the type's tp_dict dictionary
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006214 under the appropriate name (like __repr__). Some function slots
Guido van Rossum09638c12002-06-13 19:17:46 +00006215 cause more than one descriptor to be added (for example, the nb_add
6216 slot adds both __add__ and __radd__ descriptors) and some function
6217 slots compete for the same descriptor (for example both sq_item and
6218 mp_subscript generate a __getitem__ descriptor).
6219
Ezio Melotti13925002011-03-16 11:05:33 +02006220 In the latter case, the first slotdef entry encountered wins. Since
Tim Petersbf9b2442003-03-23 05:35:36 +00006221 slotdef entries are sorted by the offset of the slot in the
Guido van Rossume5c691a2003-03-07 15:13:17 +00006222 PyHeapTypeObject, this gives us some control over disambiguating
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006223 between competing slots: the members of PyHeapTypeObject are listed
6224 from most general to least general, so the most general slot is
6225 preferred. In particular, because as_mapping comes before as_sequence,
6226 for a type that defines both mp_subscript and sq_item, mp_subscript
6227 wins.
Guido van Rossum09638c12002-06-13 19:17:46 +00006228
6229 This only adds new descriptors and doesn't overwrite entries in
6230 tp_dict that were previously defined. The descriptors contain a
6231 reference to the C function they must call, so that it's safe if they
6232 are copied into a subtype's __dict__ and the subtype has a different
6233 C function in its slot -- calling the method defined by the
6234 descriptor will call the C function that was used to create it,
6235 rather than the C function present in the slot when it is called.
6236 (This is important because a subtype may have a C function in the
6237 slot that calls the method from the dictionary, and we want to avoid
6238 infinite recursion here.) */
Guido van Rossum6d204072001-10-21 00:44:31 +00006239
6240static int
6241add_operators(PyTypeObject *type)
6242{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006243 PyObject *dict = type->tp_dict;
6244 slotdef *p;
6245 PyObject *descr;
6246 void **ptr;
Guido van Rossum6d204072001-10-21 00:44:31 +00006247
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006248 init_slotdefs();
6249 for (p = slotdefs; p->name; p++) {
6250 if (p->wrapper == NULL)
6251 continue;
6252 ptr = slotptr(type, p->offset);
6253 if (!ptr || !*ptr)
6254 continue;
6255 if (PyDict_GetItem(dict, p->name_strobj))
6256 continue;
Trent Nelsonab02db22012-09-18 21:58:03 -04006257 if (*ptr == (void *)PyObject_HashNotImplemented) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006258 /* Classes may prevent the inheritance of the tp_hash
6259 slot by storing PyObject_HashNotImplemented in it. Make it
6260 visible as a None value for the __hash__ attribute. */
6261 if (PyDict_SetItem(dict, p->name_strobj, Py_None) < 0)
6262 return -1;
6263 }
6264 else {
6265 descr = PyDescr_NewWrapper(type, p, *ptr);
6266 if (descr == NULL)
6267 return -1;
6268 if (PyDict_SetItem(dict, p->name_strobj, descr) < 0)
6269 return -1;
6270 Py_DECREF(descr);
6271 }
6272 }
6273 if (type->tp_new != NULL) {
6274 if (add_tp_new_wrapper(type) < 0)
6275 return -1;
6276 }
6277 return 0;
Guido van Rossum6d204072001-10-21 00:44:31 +00006278}
6279
Guido van Rossum705f0f52001-08-24 16:47:00 +00006280
6281/* Cooperative 'super' */
6282
6283typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006284 PyObject_HEAD
6285 PyTypeObject *type;
6286 PyObject *obj;
6287 PyTypeObject *obj_type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006288} superobject;
6289
Guido van Rossum6f799372001-09-20 20:46:19 +00006290static PyMemberDef super_members[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006291 {"__thisclass__", T_OBJECT, offsetof(superobject, type), READONLY,
6292 "the class invoking super()"},
6293 {"__self__", T_OBJECT, offsetof(superobject, obj), READONLY,
6294 "the instance invoking super(); may be None"},
6295 {"__self_class__", T_OBJECT, offsetof(superobject, obj_type), READONLY,
6296 "the type of the instance invoking super(); may be None"},
6297 {0}
Guido van Rossum41eb14d2001-08-30 23:13:11 +00006298};
6299
Guido van Rossum705f0f52001-08-24 16:47:00 +00006300static void
6301super_dealloc(PyObject *self)
6302{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006303 superobject *su = (superobject *)self;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006304
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006305 _PyObject_GC_UNTRACK(self);
6306 Py_XDECREF(su->obj);
6307 Py_XDECREF(su->type);
6308 Py_XDECREF(su->obj_type);
6309 Py_TYPE(self)->tp_free(self);
Guido van Rossum705f0f52001-08-24 16:47:00 +00006310}
6311
6312static PyObject *
Guido van Rossum41eb14d2001-08-30 23:13:11 +00006313super_repr(PyObject *self)
6314{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006315 superobject *su = (superobject *)self;
Guido van Rossum41eb14d2001-08-30 23:13:11 +00006316
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006317 if (su->obj_type)
6318 return PyUnicode_FromFormat(
6319 "<super: <class '%s'>, <%s object>>",
6320 su->type ? su->type->tp_name : "NULL",
6321 su->obj_type->tp_name);
6322 else
6323 return PyUnicode_FromFormat(
6324 "<super: <class '%s'>, NULL>",
6325 su->type ? su->type->tp_name : "NULL");
Guido van Rossum41eb14d2001-08-30 23:13:11 +00006326}
6327
6328static PyObject *
Guido van Rossum705f0f52001-08-24 16:47:00 +00006329super_getattro(PyObject *self, PyObject *name)
6330{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006331 superobject *su = (superobject *)self;
6332 int skip = su->obj_type == NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006333
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006334 if (!skip) {
6335 /* We want __class__ to return the class of the super object
6336 (i.e. super, or a subclass), not the class of su->obj. */
6337 skip = (PyUnicode_Check(name) &&
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006338 PyUnicode_GET_LENGTH(name) == 9 &&
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006339 PyUnicode_CompareWithASCIIString(name, "__class__") == 0);
6340 }
Guido van Rossum76ba09f2003-04-16 19:40:58 +00006341
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006342 if (!skip) {
6343 PyObject *mro, *res, *tmp, *dict;
6344 PyTypeObject *starttype;
6345 descrgetfunc f;
6346 Py_ssize_t i, n;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006347
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006348 starttype = su->obj_type;
6349 mro = starttype->tp_mro;
Guido van Rossum155db9a2002-04-02 17:53:47 +00006350
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006351 if (mro == NULL)
6352 n = 0;
6353 else {
6354 assert(PyTuple_Check(mro));
6355 n = PyTuple_GET_SIZE(mro);
6356 }
6357 for (i = 0; i < n; i++) {
6358 if ((PyObject *)(su->type) == PyTuple_GET_ITEM(mro, i))
6359 break;
6360 }
6361 i++;
6362 res = NULL;
Victor Stinnerd74782b2012-03-09 00:39:08 +01006363 /* keep a strong reference to mro because starttype->tp_mro can be
6364 replaced during PyDict_GetItem(dict, name) */
6365 Py_INCREF(mro);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006366 for (; i < n; i++) {
6367 tmp = PyTuple_GET_ITEM(mro, i);
6368 if (PyType_Check(tmp))
6369 dict = ((PyTypeObject *)tmp)->tp_dict;
6370 else
6371 continue;
6372 res = PyDict_GetItem(dict, name);
6373 if (res != NULL) {
6374 Py_INCREF(res);
6375 f = Py_TYPE(res)->tp_descr_get;
6376 if (f != NULL) {
6377 tmp = f(res,
6378 /* Only pass 'obj' param if
6379 this is instance-mode super
6380 (See SF ID #743627)
6381 */
6382 (su->obj == (PyObject *)
6383 su->obj_type
6384 ? (PyObject *)NULL
6385 : su->obj),
6386 (PyObject *)starttype);
6387 Py_DECREF(res);
6388 res = tmp;
6389 }
Victor Stinnerd74782b2012-03-09 00:39:08 +01006390 Py_DECREF(mro);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006391 return res;
6392 }
6393 }
Victor Stinnerd74782b2012-03-09 00:39:08 +01006394 Py_DECREF(mro);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006395 }
6396 return PyObject_GenericGetAttr(self, name);
Guido van Rossum705f0f52001-08-24 16:47:00 +00006397}
6398
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006399static PyTypeObject *
Guido van Rossum5b443c62001-12-03 15:38:28 +00006400supercheck(PyTypeObject *type, PyObject *obj)
6401{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006402 /* Check that a super() call makes sense. Return a type object.
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006403
Florent Xiclunaaa6c1d22011-12-12 18:54:29 +01006404 obj can be a class, or an instance of one:
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006405
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006406 - If it is a class, it must be a subclass of 'type'. This case is
6407 used for class methods; the return value is obj.
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006408
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006409 - If it is an instance, it must be an instance of 'type'. This is
6410 the normal case; the return value is obj.__class__.
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006411
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006412 But... when obj is an instance, we want to allow for the case where
6413 Py_TYPE(obj) is not a subclass of type, but obj.__class__ is!
6414 This will allow using super() with a proxy for obj.
6415 */
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006416
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006417 /* Check for first bullet above (special case) */
6418 if (PyType_Check(obj) && PyType_IsSubtype((PyTypeObject *)obj, type)) {
6419 Py_INCREF(obj);
6420 return (PyTypeObject *)obj;
6421 }
Guido van Rossum8e80a722003-02-18 19:22:22 +00006422
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006423 /* Normal case */
6424 if (PyType_IsSubtype(Py_TYPE(obj), type)) {
6425 Py_INCREF(Py_TYPE(obj));
6426 return Py_TYPE(obj);
6427 }
6428 else {
6429 /* Try the slow way */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006430 PyObject *class_attr;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006431
Martin v. Löwisbfc6d742011-10-13 20:03:57 +02006432 class_attr = _PyObject_GetAttrId(obj, &PyId___class__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006433 if (class_attr != NULL &&
6434 PyType_Check(class_attr) &&
6435 (PyTypeObject *)class_attr != Py_TYPE(obj))
6436 {
6437 int ok = PyType_IsSubtype(
6438 (PyTypeObject *)class_attr, type);
6439 if (ok)
6440 return (PyTypeObject *)class_attr;
6441 }
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006442
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006443 if (class_attr == NULL)
6444 PyErr_Clear();
6445 else
6446 Py_DECREF(class_attr);
6447 }
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006448
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006449 PyErr_SetString(PyExc_TypeError,
6450 "super(type, obj): "
6451 "obj must be an instance or subtype of type");
6452 return NULL;
Guido van Rossum5b443c62001-12-03 15:38:28 +00006453}
6454
Guido van Rossum705f0f52001-08-24 16:47:00 +00006455static PyObject *
6456super_descr_get(PyObject *self, PyObject *obj, PyObject *type)
6457{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006458 superobject *su = (superobject *)self;
6459 superobject *newobj;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006460
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006461 if (obj == NULL || obj == Py_None || su->obj != NULL) {
6462 /* Not binding to an object, or already bound */
6463 Py_INCREF(self);
6464 return self;
6465 }
6466 if (Py_TYPE(su) != &PySuper_Type)
6467 /* If su is an instance of a (strict) subclass of super,
6468 call its type */
6469 return PyObject_CallFunctionObjArgs((PyObject *)Py_TYPE(su),
6470 su->type, obj, NULL);
6471 else {
6472 /* Inline the common case */
6473 PyTypeObject *obj_type = supercheck(su->type, obj);
6474 if (obj_type == NULL)
6475 return NULL;
6476 newobj = (superobject *)PySuper_Type.tp_new(&PySuper_Type,
6477 NULL, NULL);
6478 if (newobj == NULL)
6479 return NULL;
6480 Py_INCREF(su->type);
6481 Py_INCREF(obj);
6482 newobj->type = su->type;
6483 newobj->obj = obj;
6484 newobj->obj_type = obj_type;
6485 return (PyObject *)newobj;
6486 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00006487}
6488
6489static int
6490super_init(PyObject *self, PyObject *args, PyObject *kwds)
6491{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006492 superobject *su = (superobject *)self;
6493 PyTypeObject *type = NULL;
6494 PyObject *obj = NULL;
6495 PyTypeObject *obj_type = NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006496
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006497 if (!_PyArg_NoKeywords("super", kwds))
6498 return -1;
6499 if (!PyArg_ParseTuple(args, "|O!O:super", &PyType_Type, &type, &obj))
6500 return -1;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00006501
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006502 if (type == NULL) {
6503 /* Call super(), without args -- fill in from __class__
6504 and first local variable on the stack. */
6505 PyFrameObject *f = PyThreadState_GET()->frame;
6506 PyCodeObject *co = f->f_code;
Victor Stinner0fcab4a2011-01-04 12:59:15 +00006507 Py_ssize_t i, n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006508 if (co == NULL) {
Benjamin Peterson6a42bd62012-09-01 23:04:38 -04006509 PyErr_SetString(PyExc_RuntimeError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006510 "super(): no code object");
6511 return -1;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00006512 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006513 if (co->co_argcount == 0) {
Benjamin Peterson6a42bd62012-09-01 23:04:38 -04006514 PyErr_SetString(PyExc_RuntimeError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006515 "super(): no arguments");
6516 return -1;
6517 }
6518 obj = f->f_localsplus[0];
6519 if (obj == NULL) {
Benjamin Peterson6a42bd62012-09-01 23:04:38 -04006520 PyErr_SetString(PyExc_RuntimeError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006521 "super(): arg[0] deleted");
6522 return -1;
6523 }
6524 if (co->co_freevars == NULL)
6525 n = 0;
6526 else {
6527 assert(PyTuple_Check(co->co_freevars));
6528 n = PyTuple_GET_SIZE(co->co_freevars);
6529 }
6530 for (i = 0; i < n; i++) {
6531 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
6532 assert(PyUnicode_Check(name));
6533 if (!PyUnicode_CompareWithASCIIString(name,
Nick Coghlan0b43bcf2012-05-27 18:17:07 +10006534 "__class__")) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006535 Py_ssize_t index = co->co_nlocals +
6536 PyTuple_GET_SIZE(co->co_cellvars) + i;
6537 PyObject *cell = f->f_localsplus[index];
6538 if (cell == NULL || !PyCell_Check(cell)) {
Benjamin Peterson6a42bd62012-09-01 23:04:38 -04006539 PyErr_SetString(PyExc_RuntimeError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006540 "super(): bad __class__ cell");
6541 return -1;
6542 }
6543 type = (PyTypeObject *) PyCell_GET(cell);
6544 if (type == NULL) {
Benjamin Peterson6a42bd62012-09-01 23:04:38 -04006545 PyErr_SetString(PyExc_RuntimeError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006546 "super(): empty __class__ cell");
6547 return -1;
6548 }
6549 if (!PyType_Check(type)) {
Benjamin Peterson6a42bd62012-09-01 23:04:38 -04006550 PyErr_Format(PyExc_RuntimeError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006551 "super(): __class__ is not a type (%s)",
6552 Py_TYPE(type)->tp_name);
6553 return -1;
6554 }
6555 break;
6556 }
6557 }
6558 if (type == NULL) {
Benjamin Peterson6a42bd62012-09-01 23:04:38 -04006559 PyErr_SetString(PyExc_RuntimeError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006560 "super(): __class__ cell not found");
6561 return -1;
6562 }
6563 }
Guido van Rossumcd16bf62007-06-13 18:07:49 +00006564
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006565 if (obj == Py_None)
6566 obj = NULL;
6567 if (obj != NULL) {
6568 obj_type = supercheck(type, obj);
6569 if (obj_type == NULL)
6570 return -1;
6571 Py_INCREF(obj);
6572 }
6573 Py_INCREF(type);
6574 su->type = type;
6575 su->obj = obj;
6576 su->obj_type = obj_type;
6577 return 0;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006578}
6579
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00006580PyDoc_STRVAR(super_doc,
Guido van Rossumcd16bf62007-06-13 18:07:49 +00006581"super() -> same as super(__class__, <first argument>)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00006582"super(type) -> unbound super object\n"
6583"super(type, obj) -> bound super object; requires isinstance(obj, type)\n"
Guido van Rossume705ef12001-08-29 15:47:06 +00006584"super(type, type2) -> bound super object; requires issubclass(type2, type)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00006585"Typical use to call a cooperative superclass method:\n"
6586"class C(B):\n"
6587" def meth(self, arg):\n"
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006588" super().meth(arg)\n"
Guido van Rossumcd16bf62007-06-13 18:07:49 +00006589"This works for class methods too:\n"
6590"class C(B):\n"
6591" @classmethod\n"
6592" def cmeth(cls, arg):\n"
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006593" super().cmeth(arg)\n");
Guido van Rossum705f0f52001-08-24 16:47:00 +00006594
Guido van Rossum048eb752001-10-02 21:24:57 +00006595static int
6596super_traverse(PyObject *self, visitproc visit, void *arg)
6597{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006598 superobject *su = (superobject *)self;
Guido van Rossum048eb752001-10-02 21:24:57 +00006599
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006600 Py_VISIT(su->obj);
6601 Py_VISIT(su->type);
6602 Py_VISIT(su->obj_type);
Guido van Rossum048eb752001-10-02 21:24:57 +00006603
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006604 return 0;
Guido van Rossum048eb752001-10-02 21:24:57 +00006605}
6606
Guido van Rossum705f0f52001-08-24 16:47:00 +00006607PyTypeObject PySuper_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006608 PyVarObject_HEAD_INIT(&PyType_Type, 0)
6609 "super", /* tp_name */
6610 sizeof(superobject), /* tp_basicsize */
6611 0, /* tp_itemsize */
6612 /* methods */
6613 super_dealloc, /* tp_dealloc */
6614 0, /* tp_print */
6615 0, /* tp_getattr */
6616 0, /* tp_setattr */
6617 0, /* tp_reserved */
6618 super_repr, /* tp_repr */
6619 0, /* tp_as_number */
6620 0, /* tp_as_sequence */
6621 0, /* tp_as_mapping */
6622 0, /* tp_hash */
6623 0, /* tp_call */
6624 0, /* tp_str */
6625 super_getattro, /* tp_getattro */
6626 0, /* tp_setattro */
6627 0, /* tp_as_buffer */
6628 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
6629 Py_TPFLAGS_BASETYPE, /* tp_flags */
6630 super_doc, /* tp_doc */
6631 super_traverse, /* tp_traverse */
6632 0, /* tp_clear */
6633 0, /* tp_richcompare */
6634 0, /* tp_weaklistoffset */
6635 0, /* tp_iter */
6636 0, /* tp_iternext */
6637 0, /* tp_methods */
6638 super_members, /* tp_members */
6639 0, /* tp_getset */
6640 0, /* tp_base */
6641 0, /* tp_dict */
6642 super_descr_get, /* tp_descr_get */
6643 0, /* tp_descr_set */
6644 0, /* tp_dictoffset */
6645 super_init, /* tp_init */
6646 PyType_GenericAlloc, /* tp_alloc */
6647 PyType_GenericNew, /* tp_new */
6648 PyObject_GC_Del, /* tp_free */
Guido van Rossum705f0f52001-08-24 16:47:00 +00006649};