blob: 0c881b7057392b6df674c6e57be8e2d9738956cd [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
Benjamin Peterson2c05a2e2012-10-31 00:01:15 -0400314 if (!check_set_special_type_attr(type, value, "__qualname__"))
315 return -1;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100316 if (!PyUnicode_Check(value)) {
317 PyErr_Format(PyExc_TypeError,
318 "can only assign string to %s.__qualname__, not '%s'",
319 type->tp_name, Py_TYPE(value)->tp_name);
320 return -1;
321 }
322
323 et = (PyHeapTypeObject*)type;
324 Py_INCREF(value);
325 Py_DECREF(et->ht_qualname);
326 et->ht_qualname = value;
327 return 0;
328}
329
Guido van Rossumc3542212001-08-16 09:18:56 +0000330static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000331type_module(PyTypeObject *type, void *context)
Guido van Rossum29ca26e1995-01-07 11:58:15 +0000332{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000333 PyObject *mod;
334 char *s;
Guido van Rossumc3542212001-08-16 09:18:56 +0000335
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000336 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
Victor Stinner3c1e4812012-03-26 22:10:51 +0200337 mod = _PyDict_GetItemId(type->tp_dict, &PyId___module__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000338 if (!mod) {
339 PyErr_Format(PyExc_AttributeError, "__module__");
340 return 0;
341 }
342 Py_XINCREF(mod);
343 return mod;
344 }
345 else {
346 s = strrchr(type->tp_name, '.');
347 if (s != NULL)
348 return PyUnicode_FromStringAndSize(
349 type->tp_name, (Py_ssize_t)(s - type->tp_name));
350 return PyUnicode_FromString("builtins");
351 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000352}
353
Guido van Rossum3926a632001-09-25 16:25:58 +0000354static int
355type_set_module(PyTypeObject *type, PyObject *value, void *context)
356{
Benjamin Petersond9f23d22011-08-17 11:54:03 -0500357 if (!check_set_special_type_attr(type, value, "__module__"))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000358 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000359
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000360 PyType_Modified(type);
Christian Heimesa62da1d2008-01-12 19:39:10 +0000361
Victor Stinner3c1e4812012-03-26 22:10:51 +0200362 return _PyDict_SetItemId(type->tp_dict, &PyId___module__, value);
Guido van Rossum3926a632001-09-25 16:25:58 +0000363}
364
Tim Peters6d6c1a32001-08-02 04:15:00 +0000365static PyObject *
Christian Heimes9e7f1d22008-02-28 12:27:11 +0000366type_abstractmethods(PyTypeObject *type, void *context)
367{
Benjamin Petersonaec5fd12010-10-02 00:03:31 +0000368 PyObject *mod = NULL;
Benjamin Peterson84060b82010-10-03 02:13:39 +0000369 /* type itself has an __abstractmethods__ descriptor (this). Don't return
370 that. */
Benjamin Petersonaec5fd12010-10-02 00:03:31 +0000371 if (type != &PyType_Type)
372 mod = PyDict_GetItemString(type->tp_dict, "__abstractmethods__");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000373 if (!mod) {
Benjamin Peterson23b628e2011-01-12 18:56:07 +0000374 PyErr_SetString(PyExc_AttributeError, "__abstractmethods__");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000375 return NULL;
376 }
377 Py_XINCREF(mod);
378 return mod;
Christian Heimes9e7f1d22008-02-28 12:27:11 +0000379}
380
381static int
382type_set_abstractmethods(PyTypeObject *type, PyObject *value, void *context)
383{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000384 /* __abstractmethods__ should only be set once on a type, in
385 abc.ABCMeta.__new__, so this function doesn't do anything
386 special to update subclasses.
387 */
Antoine Pitrou6f430e42012-08-15 23:18:25 +0200388 int abstract, res;
Benjamin Peterson477ba912011-01-12 15:34:01 +0000389 if (value != NULL) {
Antoine Pitrou6f430e42012-08-15 23:18:25 +0200390 abstract = PyObject_IsTrue(value);
391 if (abstract < 0)
392 return -1;
Benjamin Peterson477ba912011-01-12 15:34:01 +0000393 res = PyDict_SetItemString(type->tp_dict, "__abstractmethods__", value);
394 }
395 else {
Antoine Pitrou6f430e42012-08-15 23:18:25 +0200396 abstract = 0;
Benjamin Peterson477ba912011-01-12 15:34:01 +0000397 res = PyDict_DelItemString(type->tp_dict, "__abstractmethods__");
398 if (res && PyErr_ExceptionMatches(PyExc_KeyError)) {
Benjamin Peterson23b628e2011-01-12 18:56:07 +0000399 PyErr_SetString(PyExc_AttributeError, "__abstractmethods__");
Benjamin Peterson477ba912011-01-12 15:34:01 +0000400 return -1;
401 }
402 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000403 if (res == 0) {
404 PyType_Modified(type);
Antoine Pitrou6f430e42012-08-15 23:18:25 +0200405 if (abstract)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000406 type->tp_flags |= Py_TPFLAGS_IS_ABSTRACT;
Antoine Pitrou6f430e42012-08-15 23:18:25 +0200407 else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000408 type->tp_flags &= ~Py_TPFLAGS_IS_ABSTRACT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000409 }
410 return res;
Christian Heimes9e7f1d22008-02-28 12:27:11 +0000411}
412
413static PyObject *
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000414type_get_bases(PyTypeObject *type, void *context)
415{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000416 Py_INCREF(type->tp_bases);
417 return type->tp_bases;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000418}
419
420static PyTypeObject *best_base(PyObject *);
421static int mro_internal(PyTypeObject *);
422static int compatible_for_assignment(PyTypeObject *, PyTypeObject *, char *);
423static int add_subclass(PyTypeObject*, PyTypeObject*);
424static void remove_subclass(PyTypeObject *, PyTypeObject *);
425static void update_all_slots(PyTypeObject *);
426
Guido van Rossum8d24ee92003-03-24 23:49:49 +0000427typedef int (*update_callback)(PyTypeObject *, void *);
428static int update_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 +0000430static int recurse_down_subclasses(PyTypeObject *type, PyObject *name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000431 update_callback callback, void *data);
Guido van Rossum8d24ee92003-03-24 23:49:49 +0000432
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000433static int
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000434mro_subclasses(PyTypeObject *type, PyObject* temp)
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000435{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000436 PyTypeObject *subclass;
437 PyObject *ref, *subclasses, *old_mro;
438 Py_ssize_t i, n;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000439
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000440 subclasses = type->tp_subclasses;
441 if (subclasses == NULL)
442 return 0;
443 assert(PyList_Check(subclasses));
444 n = PyList_GET_SIZE(subclasses);
445 for (i = 0; i < n; i++) {
446 ref = PyList_GET_ITEM(subclasses, i);
447 assert(PyWeakref_CheckRef(ref));
448 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
449 assert(subclass != NULL);
450 if ((PyObject *)subclass == Py_None)
451 continue;
452 assert(PyType_Check(subclass));
453 old_mro = subclass->tp_mro;
454 if (mro_internal(subclass) < 0) {
455 subclass->tp_mro = old_mro;
456 return -1;
457 }
458 else {
459 PyObject* tuple;
460 tuple = PyTuple_Pack(2, subclass, old_mro);
461 Py_DECREF(old_mro);
462 if (!tuple)
463 return -1;
464 if (PyList_Append(temp, tuple) < 0)
465 return -1;
466 Py_DECREF(tuple);
467 }
468 if (mro_subclasses(subclass, temp) < 0)
469 return -1;
470 }
471 return 0;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000472}
473
474static int
475type_set_bases(PyTypeObject *type, PyObject *value, void *context)
476{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000477 Py_ssize_t i;
478 int r = 0;
479 PyObject *ob, *temp;
480 PyTypeObject *new_base, *old_base;
481 PyObject *old_bases, *old_mro;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000482
Benjamin Petersond9f23d22011-08-17 11:54:03 -0500483 if (!check_set_special_type_attr(type, value, "__bases__"))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000484 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000485 if (!PyTuple_Check(value)) {
486 PyErr_Format(PyExc_TypeError,
487 "can only assign tuple to %s.__bases__, not %s",
488 type->tp_name, Py_TYPE(value)->tp_name);
489 return -1;
490 }
491 if (PyTuple_GET_SIZE(value) == 0) {
492 PyErr_Format(PyExc_TypeError,
493 "can only assign non-empty tuple to %s.__bases__, not ()",
494 type->tp_name);
495 return -1;
496 }
497 for (i = 0; i < PyTuple_GET_SIZE(value); i++) {
498 ob = PyTuple_GET_ITEM(value, i);
499 if (!PyType_Check(ob)) {
Benjamin Petersonb6af60c2012-04-01 18:49:54 -0400500 PyErr_Format(PyExc_TypeError,
Benjamin Peterson9ee601e2012-04-01 18:51:37 -0400501 "%s.__bases__ must be tuple of classes, not '%s'",
Benjamin Petersonb6af60c2012-04-01 18:49:54 -0400502 type->tp_name, Py_TYPE(ob)->tp_name);
503 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000504 }
Benjamin Peterson3471bb62012-04-01 18:48:40 -0400505 if (PyType_IsSubtype((PyTypeObject*)ob, type)) {
506 PyErr_SetString(PyExc_TypeError,
507 "a __bases__ item causes an inheritance cycle");
508 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000509 }
510 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000511
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000512 new_base = best_base(value);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000513
Benjamin Petersonab3c1c12012-04-01 18:48:02 -0400514 if (!new_base)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000515 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000516
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000517 if (!compatible_for_assignment(type->tp_base, new_base, "__bases__"))
518 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000519
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000520 Py_INCREF(new_base);
521 Py_INCREF(value);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000522
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000523 old_bases = type->tp_bases;
524 old_base = type->tp_base;
525 old_mro = type->tp_mro;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000526
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000527 type->tp_bases = value;
528 type->tp_base = new_base;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000529
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000530 if (mro_internal(type) < 0) {
531 goto bail;
532 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000533
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000534 temp = PyList_New(0);
535 if (!temp)
536 goto bail;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000537
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000538 r = mro_subclasses(type, temp);
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000539
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000540 if (r < 0) {
541 for (i = 0; i < PyList_Size(temp); i++) {
542 PyTypeObject* cls;
543 PyObject* mro;
544 PyArg_UnpackTuple(PyList_GET_ITEM(temp, i),
545 "", 2, 2, &cls, &mro);
546 Py_INCREF(mro);
547 ob = cls->tp_mro;
548 cls->tp_mro = mro;
549 Py_DECREF(ob);
550 }
551 Py_DECREF(temp);
552 goto bail;
553 }
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000554
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000555 Py_DECREF(temp);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000556
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000557 /* any base that was in __bases__ but now isn't, we
558 need to remove |type| from its tp_subclasses.
559 conversely, any class now in __bases__ that wasn't
560 needs to have |type| added to its subclasses. */
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000561
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000562 /* for now, sod that: just remove from all old_bases,
563 add to all new_bases */
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000564
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000565 for (i = PyTuple_GET_SIZE(old_bases) - 1; i >= 0; i--) {
566 ob = PyTuple_GET_ITEM(old_bases, i);
567 if (PyType_Check(ob)) {
568 remove_subclass(
569 (PyTypeObject*)ob, type);
570 }
571 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000572
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000573 for (i = PyTuple_GET_SIZE(value) - 1; i >= 0; i--) {
574 ob = PyTuple_GET_ITEM(value, i);
575 if (PyType_Check(ob)) {
576 if (add_subclass((PyTypeObject*)ob, type) < 0)
577 r = -1;
578 }
579 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000580
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000581 update_all_slots(type);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000582
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000583 Py_DECREF(old_bases);
584 Py_DECREF(old_base);
585 Py_DECREF(old_mro);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000586
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000587 return r;
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000588
589 bail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000590 Py_DECREF(type->tp_bases);
591 Py_DECREF(type->tp_base);
592 if (type->tp_mro != old_mro) {
593 Py_DECREF(type->tp_mro);
594 }
Michael W. Hudsone723e452003-08-07 14:58:10 +0000595
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000596 type->tp_bases = old_bases;
597 type->tp_base = old_base;
598 type->tp_mro = old_mro;
Tim Petersea7f75d2002-12-07 21:39:16 +0000599
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000600 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000601}
602
603static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000604type_dict(PyTypeObject *type, void *context)
605{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000606 if (type->tp_dict == NULL) {
607 Py_INCREF(Py_None);
608 return Py_None;
609 }
610 return PyDictProxy_New(type->tp_dict);
Guido van Rossum29ca26e1995-01-07 11:58:15 +0000611}
612
Tim Peters24008312002-03-17 18:56:20 +0000613static PyObject *
614type_get_doc(PyTypeObject *type, void *context)
615{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000616 PyObject *result;
617 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE) && type->tp_doc != NULL)
618 return PyUnicode_FromString(type->tp_doc);
Victor Stinner3c1e4812012-03-26 22:10:51 +0200619 result = _PyDict_GetItemId(type->tp_dict, &PyId___doc__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000620 if (result == NULL) {
621 result = Py_None;
622 Py_INCREF(result);
623 }
624 else if (Py_TYPE(result)->tp_descr_get) {
625 result = Py_TYPE(result)->tp_descr_get(result, NULL,
626 (PyObject *)type);
627 }
628 else {
629 Py_INCREF(result);
630 }
631 return result;
Tim Peters24008312002-03-17 18:56:20 +0000632}
633
Benjamin Peterson01fc6cd2011-08-17 12:03:47 -0500634static int
635type_set_doc(PyTypeObject *type, PyObject *value, void *context)
636{
637 if (!check_set_special_type_attr(type, value, "__doc__"))
638 return -1;
639 PyType_Modified(type);
Victor Stinner3c1e4812012-03-26 22:10:51 +0200640 return _PyDict_SetItemId(type->tp_dict, &PyId___doc__, value);
Benjamin Peterson01fc6cd2011-08-17 12:03:47 -0500641}
642
Antoine Pitrouec569b72008-08-26 22:40:48 +0000643static PyObject *
644type___instancecheck__(PyObject *type, PyObject *inst)
645{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000646 switch (_PyObject_RealIsInstance(inst, type)) {
647 case -1:
648 return NULL;
649 case 0:
650 Py_RETURN_FALSE;
651 default:
652 Py_RETURN_TRUE;
653 }
Antoine Pitrouec569b72008-08-26 22:40:48 +0000654}
655
656
657static PyObject *
Antoine Pitrouec569b72008-08-26 22:40:48 +0000658type___subclasscheck__(PyObject *type, PyObject *inst)
659{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000660 switch (_PyObject_RealIsSubclass(inst, type)) {
661 case -1:
662 return NULL;
663 case 0:
664 Py_RETURN_FALSE;
665 default:
666 Py_RETURN_TRUE;
667 }
Antoine Pitrouec569b72008-08-26 22:40:48 +0000668}
669
Antoine Pitrouec569b72008-08-26 22:40:48 +0000670
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000671static PyGetSetDef type_getsets[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000672 {"__name__", (getter)type_name, (setter)type_set_name, NULL},
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100673 {"__qualname__", (getter)type_qualname, (setter)type_set_qualname, NULL},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000674 {"__bases__", (getter)type_get_bases, (setter)type_set_bases, NULL},
675 {"__module__", (getter)type_module, (setter)type_set_module, NULL},
676 {"__abstractmethods__", (getter)type_abstractmethods,
677 (setter)type_set_abstractmethods, NULL},
678 {"__dict__", (getter)type_dict, NULL, NULL},
Benjamin Peterson01fc6cd2011-08-17 12:03:47 -0500679 {"__doc__", (getter)type_get_doc, (setter)type_set_doc, NULL},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000680 {0}
Tim Peters6d6c1a32001-08-02 04:15:00 +0000681};
682
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000683static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000684type_repr(PyTypeObject *type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000685{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000686 PyObject *mod, *name, *rtn;
Guido van Rossumc3542212001-08-16 09:18:56 +0000687
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000688 mod = type_module(type, NULL);
689 if (mod == NULL)
690 PyErr_Clear();
691 else if (!PyUnicode_Check(mod)) {
692 Py_DECREF(mod);
693 mod = NULL;
694 }
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100695 name = type_qualname(type, NULL);
Christian Heimesa0e7e412012-09-10 03:00:14 +0200696 if (name == NULL) {
697 Py_XDECREF(mod);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000698 return NULL;
Christian Heimesa0e7e412012-09-10 03:00:14 +0200699 }
Barry Warsaw7ce36942001-08-24 18:34:26 +0000700
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000701 if (mod != NULL && PyUnicode_CompareWithASCIIString(mod, "builtins"))
702 rtn = PyUnicode_FromFormat("<class '%U.%U'>", mod, name);
703 else
704 rtn = PyUnicode_FromFormat("<class '%s'>", type->tp_name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000705
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000706 Py_XDECREF(mod);
707 Py_DECREF(name);
708 return rtn;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000709}
710
Tim Peters6d6c1a32001-08-02 04:15:00 +0000711static PyObject *
712type_call(PyTypeObject *type, PyObject *args, PyObject *kwds)
713{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000714 PyObject *obj;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000715
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000716 if (type->tp_new == NULL) {
717 PyErr_Format(PyExc_TypeError,
718 "cannot create '%.100s' instances",
719 type->tp_name);
720 return NULL;
721 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000722
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000723 obj = type->tp_new(type, args, kwds);
724 if (obj != NULL) {
725 /* Ugly exception: when the call was type(something),
726 don't call tp_init on the result. */
727 if (type == &PyType_Type &&
728 PyTuple_Check(args) && PyTuple_GET_SIZE(args) == 1 &&
729 (kwds == NULL ||
730 (PyDict_Check(kwds) && PyDict_Size(kwds) == 0)))
731 return obj;
732 /* If the returned object is not an instance of type,
733 it won't be initialized. */
734 if (!PyType_IsSubtype(Py_TYPE(obj), type))
735 return obj;
736 type = Py_TYPE(obj);
737 if (type->tp_init != NULL &&
738 type->tp_init(obj, args, kwds) < 0) {
739 Py_DECREF(obj);
740 obj = NULL;
741 }
742 }
743 return obj;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000744}
745
746PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000747PyType_GenericAlloc(PyTypeObject *type, Py_ssize_t nitems)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000748{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000749 PyObject *obj;
750 const size_t size = _PyObject_VAR_SIZE(type, nitems+1);
751 /* note that we need to add one, for the sentinel */
Tim Peters406fe3b2001-10-06 19:04:01 +0000752
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000753 if (PyType_IS_GC(type))
754 obj = _PyObject_GC_Malloc(size);
755 else
756 obj = (PyObject *)PyObject_MALLOC(size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000757
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000758 if (obj == NULL)
759 return PyErr_NoMemory();
Tim Peters406fe3b2001-10-06 19:04:01 +0000760
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000761 memset(obj, '\0', size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000762
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000763 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
764 Py_INCREF(type);
Tim Peters406fe3b2001-10-06 19:04:01 +0000765
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000766 if (type->tp_itemsize == 0)
767 PyObject_INIT(obj, type);
768 else
769 (void) PyObject_INIT_VAR((PyVarObject *)obj, type, nitems);
Tim Peters406fe3b2001-10-06 19:04:01 +0000770
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000771 if (PyType_IS_GC(type))
772 _PyObject_GC_TRACK(obj);
773 return obj;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000774}
775
776PyObject *
777PyType_GenericNew(PyTypeObject *type, PyObject *args, PyObject *kwds)
778{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000779 return type->tp_alloc(type, 0);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000780}
781
Guido van Rossum9475a232001-10-05 20:51:39 +0000782/* Helpers for subtyping */
783
784static int
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000785traverse_slots(PyTypeObject *type, PyObject *self, visitproc visit, void *arg)
786{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000787 Py_ssize_t i, n;
788 PyMemberDef *mp;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000789
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000790 n = Py_SIZE(type);
791 mp = PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type);
792 for (i = 0; i < n; i++, mp++) {
793 if (mp->type == T_OBJECT_EX) {
794 char *addr = (char *)self + mp->offset;
795 PyObject *obj = *(PyObject **)addr;
796 if (obj != NULL) {
797 int err = visit(obj, arg);
798 if (err)
799 return err;
800 }
801 }
802 }
803 return 0;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000804}
805
806static int
Guido van Rossum9475a232001-10-05 20:51:39 +0000807subtype_traverse(PyObject *self, visitproc visit, void *arg)
808{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000809 PyTypeObject *type, *base;
810 traverseproc basetraverse;
Guido van Rossum9475a232001-10-05 20:51:39 +0000811
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000812 /* Find the nearest base with a different tp_traverse,
813 and traverse slots while we're at it */
814 type = Py_TYPE(self);
815 base = type;
816 while ((basetraverse = base->tp_traverse) == subtype_traverse) {
817 if (Py_SIZE(base)) {
818 int err = traverse_slots(base, self, visit, arg);
819 if (err)
820 return err;
821 }
822 base = base->tp_base;
823 assert(base);
824 }
Guido van Rossum9475a232001-10-05 20:51:39 +0000825
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000826 if (type->tp_dictoffset != base->tp_dictoffset) {
827 PyObject **dictptr = _PyObject_GetDictPtr(self);
828 if (dictptr && *dictptr)
829 Py_VISIT(*dictptr);
830 }
Guido van Rossum9475a232001-10-05 20:51:39 +0000831
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000832 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
833 /* For a heaptype, the instances count as references
834 to the type. Traverse the type so the collector
835 can find cycles involving this link. */
836 Py_VISIT(type);
Guido van Rossuma3862092002-06-10 15:24:42 +0000837
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000838 if (basetraverse)
839 return basetraverse(self, visit, arg);
840 return 0;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000841}
842
843static void
844clear_slots(PyTypeObject *type, PyObject *self)
845{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000846 Py_ssize_t i, n;
847 PyMemberDef *mp;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000848
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000849 n = Py_SIZE(type);
850 mp = PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type);
851 for (i = 0; i < n; i++, mp++) {
852 if (mp->type == T_OBJECT_EX && !(mp->flags & READONLY)) {
853 char *addr = (char *)self + mp->offset;
854 PyObject *obj = *(PyObject **)addr;
855 if (obj != NULL) {
856 *(PyObject **)addr = NULL;
857 Py_DECREF(obj);
858 }
859 }
860 }
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000861}
862
863static int
864subtype_clear(PyObject *self)
865{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000866 PyTypeObject *type, *base;
867 inquiry baseclear;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000868
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000869 /* Find the nearest base with a different tp_clear
870 and clear slots while we're at it */
871 type = Py_TYPE(self);
872 base = type;
873 while ((baseclear = base->tp_clear) == subtype_clear) {
874 if (Py_SIZE(base))
875 clear_slots(base, self);
876 base = base->tp_base;
877 assert(base);
878 }
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000879
Benjamin Peterson52c42432012-03-07 18:41:11 -0600880 /* Clear the instance dict (if any), to break cycles involving only
881 __dict__ slots (as in the case 'self.__dict__ is self'). */
882 if (type->tp_dictoffset != base->tp_dictoffset) {
883 PyObject **dictptr = _PyObject_GetDictPtr(self);
884 if (dictptr && *dictptr)
885 Py_CLEAR(*dictptr);
886 }
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000887
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000888 if (baseclear)
889 return baseclear(self);
890 return 0;
Guido van Rossum9475a232001-10-05 20:51:39 +0000891}
Tim Peters6d6c1a32001-08-02 04:15:00 +0000892
893static void
894subtype_dealloc(PyObject *self)
895{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000896 PyTypeObject *type, *base;
897 destructor basedealloc;
Antoine Pitrou56cd62c2012-09-06 00:59:49 +0200898 PyThreadState *tstate = PyThreadState_GET();
Tim Peters6d6c1a32001-08-02 04:15:00 +0000899
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000900 /* Extract the type; we expect it to be a heap type */
901 type = Py_TYPE(self);
902 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000903
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000904 /* Test whether the type has GC exactly once */
Guido van Rossum22b13872002-08-06 21:41:44 +0000905
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000906 if (!PyType_IS_GC(type)) {
907 /* It's really rare to find a dynamic type that doesn't have
908 GC; it can only happen when deriving from 'object' and not
909 adding any slots or instance variables. This allows
910 certain simplifications: there's no need to call
911 clear_slots(), or DECREF the dict, or clear weakrefs. */
Guido van Rossum22b13872002-08-06 21:41:44 +0000912
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000913 /* Maybe call finalizer; exit early if resurrected */
914 if (type->tp_del) {
915 type->tp_del(self);
916 if (self->ob_refcnt > 0)
917 return;
918 }
Guido van Rossum22b13872002-08-06 21:41:44 +0000919
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000920 /* Find the nearest base with a different tp_dealloc */
921 base = type;
922 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
923 assert(Py_SIZE(base) == 0);
924 base = base->tp_base;
925 assert(base);
926 }
Guido van Rossum22b13872002-08-06 21:41:44 +0000927
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000928 /* Extract the type again; tp_del may have changed it */
929 type = Py_TYPE(self);
Benjamin Peterson193152c2009-04-25 01:08:45 +0000930
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000931 /* Call the base tp_dealloc() */
932 assert(basedealloc);
933 basedealloc(self);
Guido van Rossum22b13872002-08-06 21:41:44 +0000934
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000935 /* Can't reference self beyond this point */
936 Py_DECREF(type);
Guido van Rossum22b13872002-08-06 21:41:44 +0000937
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000938 /* Done */
939 return;
940 }
Guido van Rossum22b13872002-08-06 21:41:44 +0000941
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000942 /* We get here only if the type has GC */
Guido van Rossum22b13872002-08-06 21:41:44 +0000943
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000944 /* UnTrack and re-Track around the trashcan macro, alas */
945 /* See explanation at end of function for full disclosure */
946 PyObject_GC_UnTrack(self);
947 ++_PyTrash_delete_nesting;
Antoine Pitrou56cd62c2012-09-06 00:59:49 +0200948 ++ tstate->trash_delete_nesting;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000949 Py_TRASHCAN_SAFE_BEGIN(self);
950 --_PyTrash_delete_nesting;
Antoine Pitrou56cd62c2012-09-06 00:59:49 +0200951 -- tstate->trash_delete_nesting;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000952 /* DO NOT restore GC tracking at this point. weakref callbacks
953 * (if any, and whether directly here or indirectly in something we
954 * call) may trigger GC, and if self is tracked at that point, it
955 * will look like trash to GC and GC will try to delete self again.
956 */
Guido van Rossum22b13872002-08-06 21:41:44 +0000957
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000958 /* Find the nearest base with a different tp_dealloc */
959 base = type;
Brett Cannonb94767f2011-02-22 20:15:44 +0000960 while ((/*basedealloc =*/ base->tp_dealloc) == subtype_dealloc) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000961 base = base->tp_base;
962 assert(base);
963 }
Guido van Rossum14227b42001-12-06 02:35:58 +0000964
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000965 /* If we added a weaklist, we clear it. Do this *before* calling
966 the finalizer (__del__), clearing slots, or clearing the instance
967 dict. */
Guido van Rossum59195fd2003-06-13 20:54:40 +0000968
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000969 if (type->tp_weaklistoffset && !base->tp_weaklistoffset)
970 PyObject_ClearWeakRefs(self);
Guido van Rossum1987c662003-05-29 14:29:23 +0000971
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000972 /* Maybe call finalizer; exit early if resurrected */
973 if (type->tp_del) {
974 _PyObject_GC_TRACK(self);
975 type->tp_del(self);
976 if (self->ob_refcnt > 0)
977 goto endlabel; /* resurrected */
978 else
979 _PyObject_GC_UNTRACK(self);
980 /* New weakrefs could be created during the finalizer call.
981 If this occurs, clear them out without calling their
982 finalizers since they might rely on part of the object
983 being finalized that has already been destroyed. */
984 if (type->tp_weaklistoffset && !base->tp_weaklistoffset) {
985 /* Modeled after GET_WEAKREFS_LISTPTR() */
986 PyWeakReference **list = (PyWeakReference **) \
987 PyObject_GET_WEAKREFS_LISTPTR(self);
988 while (*list)
989 _PyWeakref_ClearRef(*list);
990 }
991 }
Guido van Rossum1987c662003-05-29 14:29:23 +0000992
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000993 /* Clear slots up to the nearest base with a different tp_dealloc */
994 base = type;
995 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
996 if (Py_SIZE(base))
997 clear_slots(base, self);
998 base = base->tp_base;
999 assert(base);
1000 }
Guido van Rossum59195fd2003-06-13 20:54:40 +00001001
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001002 /* If we added a dict, DECREF it */
1003 if (type->tp_dictoffset && !base->tp_dictoffset) {
1004 PyObject **dictptr = _PyObject_GetDictPtr(self);
1005 if (dictptr != NULL) {
1006 PyObject *dict = *dictptr;
1007 if (dict != NULL) {
1008 Py_DECREF(dict);
1009 *dictptr = NULL;
1010 }
1011 }
1012 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001013
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001014 /* Extract the type again; tp_del may have changed it */
1015 type = Py_TYPE(self);
Benjamin Peterson193152c2009-04-25 01:08:45 +00001016
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001017 /* Call the base tp_dealloc(); first retrack self if
1018 * basedealloc knows about gc.
1019 */
1020 if (PyType_IS_GC(base))
1021 _PyObject_GC_TRACK(self);
1022 assert(basedealloc);
1023 basedealloc(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001024
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001025 /* Can't reference self beyond this point */
1026 Py_DECREF(type);
Guido van Rossum22b13872002-08-06 21:41:44 +00001027
Guido van Rossum0906e072002-08-07 20:42:09 +00001028 endlabel:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001029 ++_PyTrash_delete_nesting;
Antoine Pitrou56cd62c2012-09-06 00:59:49 +02001030 ++ tstate->trash_delete_nesting;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001031 Py_TRASHCAN_SAFE_END(self);
1032 --_PyTrash_delete_nesting;
Antoine Pitrou56cd62c2012-09-06 00:59:49 +02001033 -- tstate->trash_delete_nesting;
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001034
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001035 /* Explanation of the weirdness around the trashcan macros:
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001036
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001037 Q. What do the trashcan macros do?
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001038
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001039 A. Read the comment titled "Trashcan mechanism" in object.h.
1040 For one, this explains why there must be a call to GC-untrack
1041 before the trashcan begin macro. Without understanding the
1042 trashcan code, the answers to the following questions don't make
1043 sense.
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001044
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001045 Q. Why do we GC-untrack before the trashcan and then immediately
1046 GC-track again afterward?
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001047
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001048 A. In the case that the base class is GC-aware, the base class
1049 probably GC-untracks the object. If it does that using the
1050 UNTRACK macro, this will crash when the object is already
1051 untracked. Because we don't know what the base class does, the
1052 only safe thing is to make sure the object is tracked when we
1053 call the base class dealloc. But... The trashcan begin macro
1054 requires that the object is *untracked* before it is called. So
1055 the dance becomes:
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001056
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001057 GC untrack
1058 trashcan begin
1059 GC track
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001060
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001061 Q. Why did the last question say "immediately GC-track again"?
1062 It's nowhere near immediately.
Tim Petersf7f9e992003-11-13 21:59:32 +00001063
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001064 A. Because the code *used* to re-track immediately. Bad Idea.
1065 self has a refcount of 0, and if gc ever gets its hands on it
1066 (which can happen if any weakref callback gets invoked), it
1067 looks like trash to gc too, and gc also tries to delete self
Ezio Melotti13925002011-03-16 11:05:33 +02001068 then. But we're already deleting self. Double deallocation is
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001069 a subtle disaster.
Tim Petersf7f9e992003-11-13 21:59:32 +00001070
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001071 Q. Why the bizarre (net-zero) manipulation of
1072 _PyTrash_delete_nesting around the trashcan macros?
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001073
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001074 A. Some base classes (e.g. list) also use the trashcan mechanism.
1075 The following scenario used to be possible:
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001076
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001077 - suppose the trashcan level is one below the trashcan limit
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001078
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001079 - subtype_dealloc() is called
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001080
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001081 - the trashcan limit is not yet reached, so the trashcan level
1082 is incremented and the code between trashcan begin and end is
1083 executed
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001084
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001085 - this destroys much of the object's contents, including its
1086 slots and __dict__
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001087
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001088 - basedealloc() is called; this is really list_dealloc(), or
1089 some other type which also uses the trashcan macros
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001090
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001091 - the trashcan limit is now reached, so the object is put on the
1092 trashcan's to-be-deleted-later list
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001093
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001094 - basedealloc() returns
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001095
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001096 - subtype_dealloc() decrefs the object's type
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001097
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001098 - subtype_dealloc() returns
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001099
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001100 - later, the trashcan code starts deleting the objects from its
1101 to-be-deleted-later list
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001102
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001103 - subtype_dealloc() is called *AGAIN* for the same object
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001104
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001105 - at the very least (if the destroyed slots and __dict__ don't
1106 cause problems) the object's type gets decref'ed a second
1107 time, which is *BAD*!!!
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001108
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001109 The remedy is to make sure that if the code between trashcan
1110 begin and end in subtype_dealloc() is called, the code between
1111 trashcan begin and end in basedealloc() will also be called.
1112 This is done by decrementing the level after passing into the
1113 trashcan block, and incrementing it just before leaving the
1114 block.
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001115
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001116 But now it's possible that a chain of objects consisting solely
1117 of objects whose deallocator is subtype_dealloc() will defeat
1118 the trashcan mechanism completely: the decremented level means
1119 that the effective level never reaches the limit. Therefore, we
1120 *increment* the level *before* entering the trashcan block, and
1121 matchingly decrement it after leaving. This means the trashcan
1122 code will trigger a little early, but that's no big deal.
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001123
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001124 Q. Are there any live examples of code in need of all this
1125 complexity?
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001126
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001127 A. Yes. See SF bug 668433 for code that crashed (when Python was
1128 compiled in debug mode) before the trashcan level manipulations
1129 were added. For more discussion, see SF patches 581742, 575073
1130 and bug 574207.
1131 */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001132}
1133
Jeremy Hylton938ace62002-07-17 16:30:39 +00001134static PyTypeObject *solid_base(PyTypeObject *type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001135
Tim Peters6d6c1a32001-08-02 04:15:00 +00001136/* type test with subclassing support */
1137
1138int
1139PyType_IsSubtype(PyTypeObject *a, PyTypeObject *b)
1140{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001141 PyObject *mro;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001142
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001143 mro = a->tp_mro;
1144 if (mro != NULL) {
1145 /* Deal with multiple inheritance without recursion
1146 by walking the MRO tuple */
1147 Py_ssize_t i, n;
1148 assert(PyTuple_Check(mro));
1149 n = PyTuple_GET_SIZE(mro);
1150 for (i = 0; i < n; i++) {
1151 if (PyTuple_GET_ITEM(mro, i) == (PyObject *)b)
1152 return 1;
1153 }
1154 return 0;
1155 }
1156 else {
1157 /* a is not completely initilized yet; follow tp_base */
1158 do {
1159 if (a == b)
1160 return 1;
1161 a = a->tp_base;
1162 } while (a != NULL);
1163 return b == &PyBaseObject_Type;
1164 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001165}
1166
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001167/* Internal routines to do a method lookup in the type
Guido van Rossum60718732001-08-28 17:47:51 +00001168 without looking in the instance dictionary
1169 (so we can't use PyObject_GetAttr) but still binding
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001170 it to the instance. The arguments are the object,
Guido van Rossum60718732001-08-28 17:47:51 +00001171 the method name as a C string, and the address of a
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001172 static variable used to cache the interned Python string.
1173
1174 Two variants:
1175
1176 - lookup_maybe() returns NULL without raising an exception
1177 when the _PyType_Lookup() call fails;
1178
1179 - lookup_method() always raises an exception upon errors.
Benjamin Peterson224205f2009-05-08 03:25:19 +00001180
1181 - _PyObject_LookupSpecial() exported for the benefit of other places.
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001182*/
Guido van Rossum60718732001-08-28 17:47:51 +00001183
1184static PyObject *
Benjamin Petersonce798522012-01-22 11:24:29 -05001185lookup_maybe(PyObject *self, _Py_Identifier *attrid)
Guido van Rossum60718732001-08-28 17:47:51 +00001186{
Victor Stinner3c1e4812012-03-26 22:10:51 +02001187 PyObject *res;
Guido van Rossum60718732001-08-28 17:47:51 +00001188
Victor Stinner3c1e4812012-03-26 22:10:51 +02001189 res = _PyType_LookupId(Py_TYPE(self), attrid);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001190 if (res != NULL) {
1191 descrgetfunc f;
1192 if ((f = Py_TYPE(res)->tp_descr_get) == NULL)
1193 Py_INCREF(res);
1194 else
1195 res = f(res, self, (PyObject *)(Py_TYPE(self)));
1196 }
1197 return res;
Guido van Rossum60718732001-08-28 17:47:51 +00001198}
1199
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001200static PyObject *
Benjamin Petersonce798522012-01-22 11:24:29 -05001201lookup_method(PyObject *self, _Py_Identifier *attrid)
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001202{
Benjamin Petersonce798522012-01-22 11:24:29 -05001203 PyObject *res = lookup_maybe(self, attrid);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001204 if (res == NULL && !PyErr_Occurred())
Benjamin Petersonce798522012-01-22 11:24:29 -05001205 PyErr_SetObject(PyExc_AttributeError, attrid->object);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001206 return res;
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001207}
1208
Benjamin Peterson224205f2009-05-08 03:25:19 +00001209PyObject *
Benjamin Petersonce798522012-01-22 11:24:29 -05001210_PyObject_LookupSpecial(PyObject *self, _Py_Identifier *attrid)
Benjamin Peterson224205f2009-05-08 03:25:19 +00001211{
Benjamin Petersonce798522012-01-22 11:24:29 -05001212 return lookup_maybe(self, attrid);
Benjamin Peterson224205f2009-05-08 03:25:19 +00001213}
1214
Guido van Rossum2730b132001-08-28 18:22:14 +00001215/* A variation of PyObject_CallMethod that uses lookup_method()
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001216 instead of PyObject_GetAttrString(). This uses the same convention
Guido van Rossum2730b132001-08-28 18:22:14 +00001217 as lookup_method to cache the interned name string object. */
1218
Neil Schemenauerf23473f2001-10-21 22:28:58 +00001219static PyObject *
Benjamin Petersonce798522012-01-22 11:24:29 -05001220call_method(PyObject *o, _Py_Identifier *nameid, char *format, ...)
Guido van Rossum2730b132001-08-28 18:22:14 +00001221{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001222 va_list va;
1223 PyObject *args, *func = 0, *retval;
1224 va_start(va, format);
Guido van Rossum2730b132001-08-28 18:22:14 +00001225
Benjamin Petersonce798522012-01-22 11:24:29 -05001226 func = lookup_maybe(o, nameid);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001227 if (func == NULL) {
1228 va_end(va);
1229 if (!PyErr_Occurred())
Benjamin Petersonce798522012-01-22 11:24:29 -05001230 PyErr_SetObject(PyExc_AttributeError, nameid->object);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001231 return NULL;
1232 }
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001233
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001234 if (format && *format)
1235 args = Py_VaBuildValue(format, va);
1236 else
1237 args = PyTuple_New(0);
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001238
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001239 va_end(va);
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001240
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001241 if (args == NULL)
1242 return NULL;
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001243
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001244 assert(PyTuple_Check(args));
1245 retval = PyObject_Call(func, args, NULL);
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001246
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001247 Py_DECREF(args);
1248 Py_DECREF(func);
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001249
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001250 return retval;
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001251}
1252
1253/* Clone of call_method() that returns NotImplemented when the lookup fails. */
1254
Neil Schemenauerf23473f2001-10-21 22:28:58 +00001255static PyObject *
Benjamin Petersonce798522012-01-22 11:24:29 -05001256call_maybe(PyObject *o, _Py_Identifier *nameid, char *format, ...)
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001257{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001258 va_list va;
1259 PyObject *args, *func = 0, *retval;
1260 va_start(va, format);
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001261
Benjamin Petersonce798522012-01-22 11:24:29 -05001262 func = lookup_maybe(o, nameid);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001263 if (func == NULL) {
1264 va_end(va);
Brian Curtindfc80e32011-08-10 20:28:54 -05001265 if (!PyErr_Occurred())
1266 Py_RETURN_NOTIMPLEMENTED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001267 return NULL;
1268 }
Guido van Rossum2730b132001-08-28 18:22:14 +00001269
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001270 if (format && *format)
1271 args = Py_VaBuildValue(format, va);
1272 else
1273 args = PyTuple_New(0);
Guido van Rossum2730b132001-08-28 18:22:14 +00001274
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001275 va_end(va);
Guido van Rossum2730b132001-08-28 18:22:14 +00001276
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001277 if (args == NULL)
1278 return NULL;
Guido van Rossum2730b132001-08-28 18:22:14 +00001279
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001280 assert(PyTuple_Check(args));
1281 retval = PyObject_Call(func, args, NULL);
Guido van Rossum2730b132001-08-28 18:22:14 +00001282
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001283 Py_DECREF(args);
1284 Py_DECREF(func);
Guido van Rossum2730b132001-08-28 18:22:14 +00001285
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001286 return retval;
Guido van Rossum2730b132001-08-28 18:22:14 +00001287}
1288
Tim Petersea7f75d2002-12-07 21:39:16 +00001289/*
Guido van Rossum1f121312002-11-14 19:49:16 +00001290 Method resolution order algorithm C3 described in
1291 "A Monotonic Superclass Linearization for Dylan",
1292 by Kim Barrett, Bob Cassel, Paul Haahr,
Tim Petersea7f75d2002-12-07 21:39:16 +00001293 David A. Moon, Keith Playford, and P. Tucker Withington.
Guido van Rossum1f121312002-11-14 19:49:16 +00001294 (OOPSLA 1996)
1295
Guido van Rossum98f33732002-11-25 21:36:54 +00001296 Some notes about the rules implied by C3:
1297
Tim Petersea7f75d2002-12-07 21:39:16 +00001298 No duplicate bases.
Guido van Rossum98f33732002-11-25 21:36:54 +00001299 It isn't legal to repeat a class in a list of base classes.
1300
1301 The next three properties are the 3 constraints in "C3".
1302
Tim Petersea7f75d2002-12-07 21:39:16 +00001303 Local precendece order.
Guido van Rossum98f33732002-11-25 21:36:54 +00001304 If A precedes B in C's MRO, then A will precede B in the MRO of all
1305 subclasses of C.
1306
1307 Monotonicity.
1308 The MRO of a class must be an extension without reordering of the
1309 MRO of each of its superclasses.
1310
1311 Extended Precedence Graph (EPG).
1312 Linearization is consistent if there is a path in the EPG from
1313 each class to all its successors in the linearization. See
1314 the paper for definition of EPG.
Guido van Rossum1f121312002-11-14 19:49:16 +00001315 */
1316
Tim Petersea7f75d2002-12-07 21:39:16 +00001317static int
Guido van Rossum1f121312002-11-14 19:49:16 +00001318tail_contains(PyObject *list, int whence, PyObject *o) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001319 Py_ssize_t j, size;
1320 size = PyList_GET_SIZE(list);
Guido van Rossum1f121312002-11-14 19:49:16 +00001321
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001322 for (j = whence+1; j < size; j++) {
1323 if (PyList_GET_ITEM(list, j) == o)
1324 return 1;
1325 }
1326 return 0;
Guido van Rossum1f121312002-11-14 19:49:16 +00001327}
1328
Guido van Rossum98f33732002-11-25 21:36:54 +00001329static PyObject *
1330class_name(PyObject *cls)
1331{
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001332 PyObject *name = _PyObject_GetAttrId(cls, &PyId___name__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001333 if (name == NULL) {
1334 PyErr_Clear();
1335 Py_XDECREF(name);
1336 name = PyObject_Repr(cls);
1337 }
1338 if (name == NULL)
1339 return NULL;
1340 if (!PyUnicode_Check(name)) {
1341 Py_DECREF(name);
1342 return NULL;
1343 }
1344 return name;
Guido van Rossum98f33732002-11-25 21:36:54 +00001345}
1346
1347static int
1348check_duplicates(PyObject *list)
1349{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001350 Py_ssize_t i, j, n;
1351 /* Let's use a quadratic time algorithm,
1352 assuming that the bases lists is short.
1353 */
1354 n = PyList_GET_SIZE(list);
1355 for (i = 0; i < n; i++) {
1356 PyObject *o = PyList_GET_ITEM(list, i);
1357 for (j = i + 1; j < n; j++) {
1358 if (PyList_GET_ITEM(list, j) == o) {
1359 o = class_name(o);
1360 if (o != NULL) {
1361 PyErr_Format(PyExc_TypeError,
1362 "duplicate base class %U",
1363 o);
1364 Py_DECREF(o);
1365 } else {
1366 PyErr_SetString(PyExc_TypeError,
1367 "duplicate base class");
1368 }
1369 return -1;
1370 }
1371 }
1372 }
1373 return 0;
Guido van Rossum98f33732002-11-25 21:36:54 +00001374}
1375
1376/* Raise a TypeError for an MRO order disagreement.
1377
1378 It's hard to produce a good error message. In the absence of better
1379 insight into error reporting, report the classes that were candidates
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001380 to be put next into the MRO. There is some conflict between the
Guido van Rossum98f33732002-11-25 21:36:54 +00001381 order in which they should be put in the MRO, but it's hard to
1382 diagnose what constraint can't be satisfied.
1383*/
1384
1385static void
1386set_mro_error(PyObject *to_merge, int *remain)
1387{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001388 Py_ssize_t i, n, off, to_merge_size;
1389 char buf[1000];
1390 PyObject *k, *v;
1391 PyObject *set = PyDict_New();
1392 if (!set) return;
Guido van Rossum98f33732002-11-25 21:36:54 +00001393
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001394 to_merge_size = PyList_GET_SIZE(to_merge);
1395 for (i = 0; i < to_merge_size; i++) {
1396 PyObject *L = PyList_GET_ITEM(to_merge, i);
1397 if (remain[i] < PyList_GET_SIZE(L)) {
1398 PyObject *c = PyList_GET_ITEM(L, remain[i]);
1399 if (PyDict_SetItem(set, c, Py_None) < 0) {
1400 Py_DECREF(set);
1401 return;
1402 }
1403 }
1404 }
1405 n = PyDict_Size(set);
Guido van Rossum98f33732002-11-25 21:36:54 +00001406
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001407 off = PyOS_snprintf(buf, sizeof(buf), "Cannot create a \
Raymond Hettingerf394df42003-04-06 19:13:41 +00001408consistent method resolution\norder (MRO) for bases");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001409 i = 0;
1410 while (PyDict_Next(set, &i, &k, &v) && (size_t)off < sizeof(buf)) {
1411 PyObject *name = class_name(k);
Victor Stinnere5f99f32010-05-19 01:42:46 +00001412 char *name_str;
1413 if (name != NULL) {
1414 name_str = _PyUnicode_AsString(name);
1415 if (name_str == NULL)
Victor Stinnerba644a62010-05-19 01:50:45 +00001416 name_str = "?";
Victor Stinnere5f99f32010-05-19 01:42:46 +00001417 } else
Victor Stinnerba644a62010-05-19 01:50:45 +00001418 name_str = "?";
Victor Stinnere5f99f32010-05-19 01:42:46 +00001419 off += PyOS_snprintf(buf + off, sizeof(buf) - off, " %s", name_str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001420 Py_XDECREF(name);
1421 if (--n && (size_t)(off+1) < sizeof(buf)) {
1422 buf[off++] = ',';
1423 buf[off] = '\0';
1424 }
1425 }
1426 PyErr_SetString(PyExc_TypeError, buf);
1427 Py_DECREF(set);
Guido van Rossum98f33732002-11-25 21:36:54 +00001428}
1429
Tim Petersea7f75d2002-12-07 21:39:16 +00001430static int
Guido van Rossum1f121312002-11-14 19:49:16 +00001431pmerge(PyObject *acc, PyObject* to_merge) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001432 Py_ssize_t i, j, to_merge_size, empty_cnt;
1433 int *remain;
1434 int ok;
Tim Petersea7f75d2002-12-07 21:39:16 +00001435
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001436 to_merge_size = PyList_GET_SIZE(to_merge);
Guido van Rossum1f121312002-11-14 19:49:16 +00001437
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001438 /* remain stores an index into each sublist of to_merge.
1439 remain[i] is the index of the next base in to_merge[i]
1440 that is not included in acc.
1441 */
1442 remain = (int *)PyMem_MALLOC(SIZEOF_INT*to_merge_size);
1443 if (remain == NULL)
1444 return -1;
1445 for (i = 0; i < to_merge_size; i++)
1446 remain[i] = 0;
Guido van Rossum1f121312002-11-14 19:49:16 +00001447
1448 again:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001449 empty_cnt = 0;
1450 for (i = 0; i < to_merge_size; i++) {
1451 PyObject *candidate;
Tim Petersea7f75d2002-12-07 21:39:16 +00001452
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001453 PyObject *cur_list = PyList_GET_ITEM(to_merge, i);
Guido van Rossum1f121312002-11-14 19:49:16 +00001454
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001455 if (remain[i] >= PyList_GET_SIZE(cur_list)) {
1456 empty_cnt++;
1457 continue;
1458 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001459
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001460 /* Choose next candidate for MRO.
Guido van Rossum98f33732002-11-25 21:36:54 +00001461
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001462 The input sequences alone can determine the choice.
1463 If not, choose the class which appears in the MRO
1464 of the earliest direct superclass of the new class.
1465 */
Guido van Rossum98f33732002-11-25 21:36:54 +00001466
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001467 candidate = PyList_GET_ITEM(cur_list, remain[i]);
1468 for (j = 0; j < to_merge_size; j++) {
1469 PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
1470 if (tail_contains(j_lst, remain[j], candidate)) {
1471 goto skip; /* continue outer loop */
1472 }
1473 }
1474 ok = PyList_Append(acc, candidate);
1475 if (ok < 0) {
1476 PyMem_Free(remain);
1477 return -1;
1478 }
1479 for (j = 0; j < to_merge_size; j++) {
1480 PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
1481 if (remain[j] < PyList_GET_SIZE(j_lst) &&
1482 PyList_GET_ITEM(j_lst, remain[j]) == candidate) {
1483 remain[j]++;
1484 }
1485 }
1486 goto again;
1487 skip: ;
1488 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001489
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001490 if (empty_cnt == to_merge_size) {
1491 PyMem_FREE(remain);
1492 return 0;
1493 }
1494 set_mro_error(to_merge, remain);
1495 PyMem_FREE(remain);
1496 return -1;
Guido van Rossum1f121312002-11-14 19:49:16 +00001497}
1498
Tim Peters6d6c1a32001-08-02 04:15:00 +00001499static PyObject *
1500mro_implementation(PyTypeObject *type)
1501{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001502 Py_ssize_t i, n;
1503 int ok;
1504 PyObject *bases, *result;
1505 PyObject *to_merge, *bases_aslist;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001506
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001507 if (type->tp_dict == NULL) {
1508 if (PyType_Ready(type) < 0)
1509 return NULL;
1510 }
Guido van Rossum63517572002-06-18 16:44:57 +00001511
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001512 /* Find a superclass linearization that honors the constraints
1513 of the explicit lists of bases and the constraints implied by
1514 each base class.
Guido van Rossum98f33732002-11-25 21:36:54 +00001515
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001516 to_merge is a list of lists, where each list is a superclass
1517 linearization implied by a base class. The last element of
1518 to_merge is the declared list of bases.
1519 */
Guido van Rossum98f33732002-11-25 21:36:54 +00001520
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001521 bases = type->tp_bases;
1522 n = PyTuple_GET_SIZE(bases);
Guido van Rossum1f121312002-11-14 19:49:16 +00001523
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001524 to_merge = PyList_New(n+1);
1525 if (to_merge == NULL)
1526 return NULL;
Guido van Rossum1f121312002-11-14 19:49:16 +00001527
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001528 for (i = 0; i < n; i++) {
1529 PyObject *base = PyTuple_GET_ITEM(bases, i);
1530 PyObject *parentMRO;
1531 parentMRO = PySequence_List(((PyTypeObject*)base)->tp_mro);
1532 if (parentMRO == NULL) {
1533 Py_DECREF(to_merge);
1534 return NULL;
1535 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001536
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001537 PyList_SET_ITEM(to_merge, i, parentMRO);
1538 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001539
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001540 bases_aslist = PySequence_List(bases);
1541 if (bases_aslist == NULL) {
1542 Py_DECREF(to_merge);
1543 return NULL;
1544 }
1545 /* This is just a basic sanity check. */
1546 if (check_duplicates(bases_aslist) < 0) {
1547 Py_DECREF(to_merge);
1548 Py_DECREF(bases_aslist);
1549 return NULL;
1550 }
1551 PyList_SET_ITEM(to_merge, n, bases_aslist);
Guido van Rossum1f121312002-11-14 19:49:16 +00001552
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001553 result = Py_BuildValue("[O]", (PyObject *)type);
1554 if (result == NULL) {
1555 Py_DECREF(to_merge);
1556 return NULL;
1557 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001558
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001559 ok = pmerge(result, to_merge);
1560 Py_DECREF(to_merge);
1561 if (ok < 0) {
1562 Py_DECREF(result);
1563 return NULL;
1564 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001565
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001566 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001567}
1568
1569static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001570mro_external(PyObject *self)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001571{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001572 PyTypeObject *type = (PyTypeObject *)self;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001573
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001574 return mro_implementation(type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001575}
1576
1577static int
1578mro_internal(PyTypeObject *type)
1579{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001580 PyObject *mro, *result, *tuple;
1581 int checkit = 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001582
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001583 if (Py_TYPE(type) == &PyType_Type) {
1584 result = mro_implementation(type);
1585 }
1586 else {
Benjamin Petersonce798522012-01-22 11:24:29 -05001587 _Py_IDENTIFIER(mro);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001588 checkit = 1;
Benjamin Petersonce798522012-01-22 11:24:29 -05001589 mro = lookup_method((PyObject *)type, &PyId_mro);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001590 if (mro == NULL)
1591 return -1;
1592 result = PyObject_CallObject(mro, NULL);
1593 Py_DECREF(mro);
1594 }
1595 if (result == NULL)
1596 return -1;
1597 tuple = PySequence_Tuple(result);
1598 Py_DECREF(result);
1599 if (tuple == NULL)
1600 return -1;
1601 if (checkit) {
1602 Py_ssize_t i, len;
1603 PyObject *cls;
1604 PyTypeObject *solid;
Armin Rigo037d1e02005-12-29 17:07:39 +00001605
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001606 solid = solid_base(type);
Armin Rigo037d1e02005-12-29 17:07:39 +00001607
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001608 len = PyTuple_GET_SIZE(tuple);
Armin Rigo037d1e02005-12-29 17:07:39 +00001609
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001610 for (i = 0; i < len; i++) {
1611 PyTypeObject *t;
1612 cls = PyTuple_GET_ITEM(tuple, i);
1613 if (!PyType_Check(cls)) {
1614 PyErr_Format(PyExc_TypeError,
1615 "mro() returned a non-class ('%.500s')",
1616 Py_TYPE(cls)->tp_name);
1617 Py_DECREF(tuple);
1618 return -1;
1619 }
1620 t = (PyTypeObject*)cls;
1621 if (!PyType_IsSubtype(solid, solid_base(t))) {
1622 PyErr_Format(PyExc_TypeError,
1623 "mro() returned base with unsuitable layout ('%.500s')",
1624 t->tp_name);
1625 Py_DECREF(tuple);
1626 return -1;
1627 }
1628 }
1629 }
1630 type->tp_mro = tuple;
Christian Heimesa62da1d2008-01-12 19:39:10 +00001631
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001632 type_mro_modified(type, type->tp_mro);
Florent Xiclunaaa6c1d22011-12-12 18:54:29 +01001633 /* corner case: the super class might have been hidden
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001634 from the custom MRO */
1635 type_mro_modified(type, type->tp_bases);
Christian Heimesa62da1d2008-01-12 19:39:10 +00001636
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001637 PyType_Modified(type);
Christian Heimesa62da1d2008-01-12 19:39:10 +00001638
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001639 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001640}
1641
1642
1643/* Calculate the best base amongst multiple base classes.
1644 This is the first one that's on the path to the "solid base". */
1645
1646static PyTypeObject *
1647best_base(PyObject *bases)
1648{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001649 Py_ssize_t i, n;
1650 PyTypeObject *base, *winner, *candidate, *base_i;
1651 PyObject *base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001652
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001653 assert(PyTuple_Check(bases));
1654 n = PyTuple_GET_SIZE(bases);
1655 assert(n > 0);
1656 base = NULL;
1657 winner = NULL;
1658 for (i = 0; i < n; i++) {
1659 base_proto = PyTuple_GET_ITEM(bases, i);
1660 if (!PyType_Check(base_proto)) {
1661 PyErr_SetString(
1662 PyExc_TypeError,
1663 "bases must be types");
1664 return NULL;
1665 }
1666 base_i = (PyTypeObject *)base_proto;
1667 if (base_i->tp_dict == NULL) {
1668 if (PyType_Ready(base_i) < 0)
1669 return NULL;
1670 }
1671 candidate = solid_base(base_i);
1672 if (winner == NULL) {
1673 winner = candidate;
1674 base = base_i;
1675 }
1676 else if (PyType_IsSubtype(winner, candidate))
1677 ;
1678 else if (PyType_IsSubtype(candidate, winner)) {
1679 winner = candidate;
1680 base = base_i;
1681 }
1682 else {
1683 PyErr_SetString(
1684 PyExc_TypeError,
1685 "multiple bases have "
1686 "instance lay-out conflict");
1687 return NULL;
1688 }
1689 }
Florent Xiclunaaa6c1d22011-12-12 18:54:29 +01001690 assert (base != NULL);
1691
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001692 return base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001693}
1694
1695static int
1696extra_ivars(PyTypeObject *type, PyTypeObject *base)
1697{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001698 size_t t_size = type->tp_basicsize;
1699 size_t b_size = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001700
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001701 assert(t_size >= b_size); /* Else type smaller than base! */
1702 if (type->tp_itemsize || base->tp_itemsize) {
1703 /* If itemsize is involved, stricter rules */
1704 return t_size != b_size ||
1705 type->tp_itemsize != base->tp_itemsize;
1706 }
1707 if (type->tp_weaklistoffset && base->tp_weaklistoffset == 0 &&
1708 type->tp_weaklistoffset + sizeof(PyObject *) == t_size &&
1709 type->tp_flags & Py_TPFLAGS_HEAPTYPE)
1710 t_size -= sizeof(PyObject *);
1711 if (type->tp_dictoffset && base->tp_dictoffset == 0 &&
1712 type->tp_dictoffset + sizeof(PyObject *) == t_size &&
1713 type->tp_flags & Py_TPFLAGS_HEAPTYPE)
1714 t_size -= sizeof(PyObject *);
Guido van Rossum9676b222001-08-17 20:32:36 +00001715
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001716 return t_size != b_size;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001717}
1718
1719static PyTypeObject *
1720solid_base(PyTypeObject *type)
1721{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001722 PyTypeObject *base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001723
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001724 if (type->tp_base)
1725 base = solid_base(type->tp_base);
1726 else
1727 base = &PyBaseObject_Type;
1728 if (extra_ivars(type, base))
1729 return type;
1730 else
1731 return base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001732}
1733
Jeremy Hylton938ace62002-07-17 16:30:39 +00001734static void object_dealloc(PyObject *);
1735static int object_init(PyObject *, PyObject *, PyObject *);
1736static int update_slot(PyTypeObject *, PyObject *);
1737static void fixup_slot_dispatchers(PyTypeObject *);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001738
Guido van Rossum360e4b82007-05-14 22:51:27 +00001739/*
1740 * Helpers for __dict__ descriptor. We don't want to expose the dicts
1741 * inherited from various builtin types. The builtin base usually provides
1742 * its own __dict__ descriptor, so we use that when we can.
1743 */
1744static PyTypeObject *
1745get_builtin_base_with_dict(PyTypeObject *type)
1746{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001747 while (type->tp_base != NULL) {
1748 if (type->tp_dictoffset != 0 &&
1749 !(type->tp_flags & Py_TPFLAGS_HEAPTYPE))
1750 return type;
1751 type = type->tp_base;
1752 }
1753 return NULL;
Guido van Rossum360e4b82007-05-14 22:51:27 +00001754}
1755
1756static PyObject *
1757get_dict_descriptor(PyTypeObject *type)
1758{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001759 PyObject *descr;
Guido van Rossum360e4b82007-05-14 22:51:27 +00001760
Victor Stinner3c1e4812012-03-26 22:10:51 +02001761 descr = _PyType_LookupId(type, &PyId___dict__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001762 if (descr == NULL || !PyDescr_IsData(descr))
1763 return NULL;
Guido van Rossum360e4b82007-05-14 22:51:27 +00001764
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001765 return descr;
Guido van Rossum360e4b82007-05-14 22:51:27 +00001766}
1767
1768static void
1769raise_dict_descr_error(PyObject *obj)
1770{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001771 PyErr_Format(PyExc_TypeError,
1772 "this __dict__ descriptor does not support "
1773 "'%.200s' objects", Py_TYPE(obj)->tp_name);
Guido van Rossum360e4b82007-05-14 22:51:27 +00001774}
1775
Tim Peters6d6c1a32001-08-02 04:15:00 +00001776static PyObject *
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001777subtype_dict(PyObject *obj, void *context)
1778{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001779 PyTypeObject *base;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001780
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001781 base = get_builtin_base_with_dict(Py_TYPE(obj));
1782 if (base != NULL) {
1783 descrgetfunc func;
1784 PyObject *descr = get_dict_descriptor(base);
1785 if (descr == NULL) {
1786 raise_dict_descr_error(obj);
1787 return NULL;
1788 }
1789 func = Py_TYPE(descr)->tp_descr_get;
1790 if (func == NULL) {
1791 raise_dict_descr_error(obj);
1792 return NULL;
1793 }
1794 return func(descr, obj, (PyObject *)(Py_TYPE(obj)));
1795 }
Benjamin Peterson8eb12692012-02-19 19:59:10 -05001796 return PyObject_GenericGetDict(obj, context);
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001797}
1798
Guido van Rossum6661be32001-10-26 04:26:12 +00001799static int
1800subtype_setdict(PyObject *obj, PyObject *value, void *context)
1801{
Benjamin Peterson8eb12692012-02-19 19:59:10 -05001802 PyObject *dict, **dictptr;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001803 PyTypeObject *base;
Guido van Rossum6661be32001-10-26 04:26:12 +00001804
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001805 base = get_builtin_base_with_dict(Py_TYPE(obj));
1806 if (base != NULL) {
1807 descrsetfunc func;
1808 PyObject *descr = get_dict_descriptor(base);
1809 if (descr == NULL) {
1810 raise_dict_descr_error(obj);
1811 return -1;
1812 }
1813 func = Py_TYPE(descr)->tp_descr_set;
1814 if (func == NULL) {
1815 raise_dict_descr_error(obj);
1816 return -1;
1817 }
1818 return func(descr, obj, value);
1819 }
Benjamin Peterson8eb12692012-02-19 19:59:10 -05001820 /* Almost like PyObject_GenericSetDict, but allow __dict__ to be deleted. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001821 dictptr = _PyObject_GetDictPtr(obj);
1822 if (dictptr == NULL) {
1823 PyErr_SetString(PyExc_AttributeError,
1824 "This object has no __dict__");
1825 return -1;
1826 }
Benjamin Peterson006c5a22012-02-19 20:36:12 -05001827 if (value != NULL && !PyDict_Check(value)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001828 PyErr_Format(PyExc_TypeError,
1829 "__dict__ must be set to a dictionary, "
1830 "not a '%.200s'", Py_TYPE(value)->tp_name);
1831 return -1;
1832 }
1833 dict = *dictptr;
1834 Py_XINCREF(value);
1835 *dictptr = value;
1836 Py_XDECREF(dict);
1837 return 0;
Guido van Rossum6661be32001-10-26 04:26:12 +00001838}
1839
Guido van Rossumad47da02002-08-12 19:05:44 +00001840static PyObject *
1841subtype_getweakref(PyObject *obj, void *context)
1842{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001843 PyObject **weaklistptr;
1844 PyObject *result;
Guido van Rossumad47da02002-08-12 19:05:44 +00001845
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001846 if (Py_TYPE(obj)->tp_weaklistoffset == 0) {
1847 PyErr_SetString(PyExc_AttributeError,
1848 "This object has no __weakref__");
1849 return NULL;
1850 }
1851 assert(Py_TYPE(obj)->tp_weaklistoffset > 0);
1852 assert(Py_TYPE(obj)->tp_weaklistoffset + sizeof(PyObject *) <=
1853 (size_t)(Py_TYPE(obj)->tp_basicsize));
1854 weaklistptr = (PyObject **)
1855 ((char *)obj + Py_TYPE(obj)->tp_weaklistoffset);
1856 if (*weaklistptr == NULL)
1857 result = Py_None;
1858 else
1859 result = *weaklistptr;
1860 Py_INCREF(result);
1861 return result;
Guido van Rossumad47da02002-08-12 19:05:44 +00001862}
1863
Guido van Rossum373c7412003-01-07 13:41:37 +00001864/* Three variants on the subtype_getsets list. */
1865
1866static PyGetSetDef subtype_getsets_full[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001867 {"__dict__", subtype_dict, subtype_setdict,
1868 PyDoc_STR("dictionary for instance variables (if defined)")},
1869 {"__weakref__", subtype_getweakref, NULL,
1870 PyDoc_STR("list of weak references to the object (if defined)")},
1871 {0}
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001872};
1873
Guido van Rossum373c7412003-01-07 13:41:37 +00001874static PyGetSetDef subtype_getsets_dict_only[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001875 {"__dict__", subtype_dict, subtype_setdict,
1876 PyDoc_STR("dictionary for instance variables (if defined)")},
1877 {0}
Guido van Rossum373c7412003-01-07 13:41:37 +00001878};
1879
1880static PyGetSetDef subtype_getsets_weakref_only[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001881 {"__weakref__", subtype_getweakref, NULL,
1882 PyDoc_STR("list of weak references to the object (if defined)")},
1883 {0}
Guido van Rossum373c7412003-01-07 13:41:37 +00001884};
1885
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001886static int
1887valid_identifier(PyObject *s)
1888{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001889 if (!PyUnicode_Check(s)) {
1890 PyErr_Format(PyExc_TypeError,
1891 "__slots__ items must be strings, not '%.200s'",
1892 Py_TYPE(s)->tp_name);
1893 return 0;
1894 }
1895 if (!PyUnicode_IsIdentifier(s)) {
1896 PyErr_SetString(PyExc_TypeError,
1897 "__slots__ must be identifiers");
1898 return 0;
1899 }
1900 return 1;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001901}
1902
Guido van Rossumd8faa362007-04-27 19:54:29 +00001903/* Forward */
1904static int
1905object_init(PyObject *self, PyObject *args, PyObject *kwds);
1906
1907static int
1908type_init(PyObject *cls, PyObject *args, PyObject *kwds)
1909{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001910 int res;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001911
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001912 assert(args != NULL && PyTuple_Check(args));
1913 assert(kwds == NULL || PyDict_Check(kwds));
Guido van Rossumd8faa362007-04-27 19:54:29 +00001914
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001915 if (kwds != NULL && PyDict_Check(kwds) && PyDict_Size(kwds) != 0) {
1916 PyErr_SetString(PyExc_TypeError,
1917 "type.__init__() takes no keyword arguments");
1918 return -1;
1919 }
Guido van Rossumd8faa362007-04-27 19:54:29 +00001920
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001921 if (args != NULL && PyTuple_Check(args) &&
1922 (PyTuple_GET_SIZE(args) != 1 && PyTuple_GET_SIZE(args) != 3)) {
1923 PyErr_SetString(PyExc_TypeError,
1924 "type.__init__() takes 1 or 3 arguments");
1925 return -1;
1926 }
Guido van Rossumd8faa362007-04-27 19:54:29 +00001927
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001928 /* Call object.__init__(self) now. */
1929 /* XXX Could call super(type, cls).__init__() but what's the point? */
1930 args = PyTuple_GetSlice(args, 0, 0);
1931 res = object_init(cls, args, NULL);
1932 Py_DECREF(args);
1933 return res;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001934}
1935
Victor Stinner4ca1cf32012-10-30 23:40:45 +01001936unsigned long
Martin v. Löwis738236d2011-02-05 20:35:29 +00001937PyType_GetFlags(PyTypeObject *type)
1938{
1939 return type->tp_flags;
1940}
1941
Nick Coghlande31b192011-10-23 22:04:16 +10001942/* Determine the most derived metatype. */
1943PyTypeObject *
1944_PyType_CalculateMetaclass(PyTypeObject *metatype, PyObject *bases)
1945{
1946 Py_ssize_t i, nbases;
1947 PyTypeObject *winner;
1948 PyObject *tmp;
1949 PyTypeObject *tmptype;
1950
1951 /* Determine the proper metatype to deal with this,
1952 and check for metatype conflicts while we're at it.
1953 Note that if some other metatype wins to contract,
1954 it's possible that its instances are not types. */
1955
1956 nbases = PyTuple_GET_SIZE(bases);
1957 winner = metatype;
1958 for (i = 0; i < nbases; i++) {
1959 tmp = PyTuple_GET_ITEM(bases, i);
1960 tmptype = Py_TYPE(tmp);
1961 if (PyType_IsSubtype(winner, tmptype))
1962 continue;
1963 if (PyType_IsSubtype(tmptype, winner)) {
1964 winner = tmptype;
1965 continue;
1966 }
1967 /* else: */
1968 PyErr_SetString(PyExc_TypeError,
1969 "metaclass conflict: "
1970 "the metaclass of a derived class "
1971 "must be a (non-strict) subclass "
1972 "of the metaclasses of all its bases");
1973 return NULL;
1974 }
1975 return winner;
1976}
1977
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001978static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00001979type_new(PyTypeObject *metatype, PyObject *args, PyObject *kwds)
1980{
Victor Stinner6f738742012-02-25 01:22:36 +01001981 PyObject *name, *bases = NULL, *orig_dict, *dict = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001982 static char *kwlist[] = {"name", "bases", "dict", 0};
Victor Stinner6f738742012-02-25 01:22:36 +01001983 PyObject *qualname, *slots = NULL, *tmp, *newslots;
1984 PyTypeObject *type = NULL, *base, *tmptype, *winner;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001985 PyHeapTypeObject *et;
1986 PyMemberDef *mp;
1987 Py_ssize_t i, nbases, nslots, slotoffset, add_dict, add_weak;
1988 int j, may_add_dict, may_add_weak;
Victor Stinner3c1e4812012-03-26 22:10:51 +02001989 _Py_IDENTIFIER(__qualname__);
1990 _Py_IDENTIFIER(__slots__);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001991
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001992 assert(args != NULL && PyTuple_Check(args));
1993 assert(kwds == NULL || PyDict_Check(kwds));
Tim Peters3abca122001-10-27 19:37:48 +00001994
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001995 /* Special case: type(x) should return x->ob_type */
1996 {
1997 const Py_ssize_t nargs = PyTuple_GET_SIZE(args);
1998 const Py_ssize_t nkwds = kwds == NULL ? 0 : PyDict_Size(kwds);
Tim Peters3abca122001-10-27 19:37:48 +00001999
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002000 if (PyType_CheckExact(metatype) && nargs == 1 && nkwds == 0) {
2001 PyObject *x = PyTuple_GET_ITEM(args, 0);
2002 Py_INCREF(Py_TYPE(x));
2003 return (PyObject *) Py_TYPE(x);
2004 }
Tim Peters3abca122001-10-27 19:37:48 +00002005
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002006 /* SF bug 475327 -- if that didn't trigger, we need 3
2007 arguments. but PyArg_ParseTupleAndKeywords below may give
2008 a msg saying type() needs exactly 3. */
2009 if (nargs + nkwds != 3) {
2010 PyErr_SetString(PyExc_TypeError,
2011 "type() takes 1 or 3 arguments");
2012 return NULL;
2013 }
2014 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002015
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002016 /* Check arguments: (name, bases, dict) */
2017 if (!PyArg_ParseTupleAndKeywords(args, kwds, "UO!O!:type", kwlist,
2018 &name,
2019 &PyTuple_Type, &bases,
Victor Stinner6f738742012-02-25 01:22:36 +01002020 &PyDict_Type, &orig_dict))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002021 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002022
Nick Coghlande31b192011-10-23 22:04:16 +10002023 /* Determine the proper metatype to deal with this: */
2024 winner = _PyType_CalculateMetaclass(metatype, bases);
2025 if (winner == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002026 return NULL;
2027 }
Nick Coghlande31b192011-10-23 22:04:16 +10002028
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002029 if (winner != metatype) {
2030 if (winner->tp_new != type_new) /* Pass it to the winner */
2031 return winner->tp_new(winner, args, kwds);
2032 metatype = winner;
2033 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002034
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002035 /* Adjust for empty tuple bases */
Nick Coghlande31b192011-10-23 22:04:16 +10002036 nbases = PyTuple_GET_SIZE(bases);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002037 if (nbases == 0) {
2038 bases = PyTuple_Pack(1, &PyBaseObject_Type);
2039 if (bases == NULL)
Victor Stinner6f738742012-02-25 01:22:36 +01002040 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002041 nbases = 1;
2042 }
2043 else
2044 Py_INCREF(bases);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002045
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002046 /* Calculate best base, and check that all bases are type objects */
2047 base = best_base(bases);
2048 if (base == NULL) {
Victor Stinner6f738742012-02-25 01:22:36 +01002049 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002050 }
2051 if (!PyType_HasFeature(base, Py_TPFLAGS_BASETYPE)) {
2052 PyErr_Format(PyExc_TypeError,
2053 "type '%.100s' is not an acceptable base type",
2054 base->tp_name);
Victor Stinner6f738742012-02-25 01:22:36 +01002055 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002056 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002057
Victor Stinner6f738742012-02-25 01:22:36 +01002058 dict = PyDict_Copy(orig_dict);
2059 if (dict == NULL)
2060 goto error;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002061
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002062 /* Check for a __slots__ sequence variable in dict, and count it */
Victor Stinner3c1e4812012-03-26 22:10:51 +02002063 slots = _PyDict_GetItemId(dict, &PyId___slots__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002064 nslots = 0;
2065 add_dict = 0;
2066 add_weak = 0;
2067 may_add_dict = base->tp_dictoffset == 0;
2068 may_add_weak = base->tp_weaklistoffset == 0 && base->tp_itemsize == 0;
2069 if (slots == NULL) {
2070 if (may_add_dict) {
2071 add_dict++;
2072 }
2073 if (may_add_weak) {
2074 add_weak++;
2075 }
2076 }
2077 else {
2078 /* Have slots */
Guido van Rossumad47da02002-08-12 19:05:44 +00002079
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002080 /* Make it into a tuple */
2081 if (PyUnicode_Check(slots))
2082 slots = PyTuple_Pack(1, slots);
2083 else
2084 slots = PySequence_Tuple(slots);
Victor Stinner6f738742012-02-25 01:22:36 +01002085 if (slots == NULL)
2086 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002087 assert(PyTuple_Check(slots));
Guido van Rossumad47da02002-08-12 19:05:44 +00002088
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002089 /* Are slots allowed? */
2090 nslots = PyTuple_GET_SIZE(slots);
2091 if (nslots > 0 && base->tp_itemsize != 0) {
2092 PyErr_Format(PyExc_TypeError,
2093 "nonempty __slots__ "
2094 "not supported for subtype of '%s'",
2095 base->tp_name);
Victor Stinner6f738742012-02-25 01:22:36 +01002096 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002097 }
Guido van Rossumad47da02002-08-12 19:05:44 +00002098
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002099 /* Check for valid slot names and two special cases */
2100 for (i = 0; i < nslots; i++) {
2101 PyObject *tmp = PyTuple_GET_ITEM(slots, i);
2102 if (!valid_identifier(tmp))
Victor Stinner6f738742012-02-25 01:22:36 +01002103 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002104 assert(PyUnicode_Check(tmp));
2105 if (PyUnicode_CompareWithASCIIString(tmp, "__dict__") == 0) {
2106 if (!may_add_dict || add_dict) {
2107 PyErr_SetString(PyExc_TypeError,
2108 "__dict__ slot disallowed: "
2109 "we already got one");
Victor Stinner6f738742012-02-25 01:22:36 +01002110 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002111 }
2112 add_dict++;
2113 }
2114 if (PyUnicode_CompareWithASCIIString(tmp, "__weakref__") == 0) {
2115 if (!may_add_weak || add_weak) {
2116 PyErr_SetString(PyExc_TypeError,
2117 "__weakref__ slot disallowed: "
2118 "either we already got one, "
2119 "or __itemsize__ != 0");
Victor Stinner6f738742012-02-25 01:22:36 +01002120 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002121 }
2122 add_weak++;
2123 }
2124 }
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00002125
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002126 /* Copy slots into a list, mangle names and sort them.
2127 Sorted names are needed for __class__ assignment.
2128 Convert them back to tuple at the end.
2129 */
2130 newslots = PyList_New(nslots - add_dict - add_weak);
2131 if (newslots == NULL)
Victor Stinner6f738742012-02-25 01:22:36 +01002132 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002133 for (i = j = 0; i < nslots; i++) {
2134 tmp = PyTuple_GET_ITEM(slots, i);
2135 if ((add_dict &&
2136 PyUnicode_CompareWithASCIIString(tmp, "__dict__") == 0) ||
2137 (add_weak &&
2138 PyUnicode_CompareWithASCIIString(tmp, "__weakref__") == 0))
2139 continue;
2140 tmp =_Py_Mangle(name, tmp);
Benjamin Petersonae13c882011-08-16 22:26:48 -05002141 if (!tmp) {
2142 Py_DECREF(newslots);
Victor Stinner6f738742012-02-25 01:22:36 +01002143 goto error;
Benjamin Petersonae13c882011-08-16 22:26:48 -05002144 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002145 PyList_SET_ITEM(newslots, j, tmp);
Benjamin Petersonc4085c82011-08-16 18:53:26 -05002146 if (PyDict_GetItem(dict, tmp)) {
2147 PyErr_Format(PyExc_ValueError,
2148 "%R in __slots__ conflicts with class variable",
2149 tmp);
Benjamin Petersond17cefc2011-08-16 22:28:23 -05002150 Py_DECREF(newslots);
Victor Stinner6f738742012-02-25 01:22:36 +01002151 goto error;
Benjamin Petersonc4085c82011-08-16 18:53:26 -05002152 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002153 j++;
2154 }
2155 assert(j == nslots - add_dict - add_weak);
2156 nslots = j;
Victor Stinner6f738742012-02-25 01:22:36 +01002157 Py_CLEAR(slots);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002158 if (PyList_Sort(newslots) == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002159 Py_DECREF(newslots);
Victor Stinner6f738742012-02-25 01:22:36 +01002160 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002161 }
2162 slots = PyList_AsTuple(newslots);
2163 Py_DECREF(newslots);
Victor Stinner6f738742012-02-25 01:22:36 +01002164 if (slots == NULL)
2165 goto error;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00002166
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002167 /* Secondary bases may provide weakrefs or dict */
2168 if (nbases > 1 &&
2169 ((may_add_dict && !add_dict) ||
2170 (may_add_weak && !add_weak))) {
2171 for (i = 0; i < nbases; i++) {
2172 tmp = PyTuple_GET_ITEM(bases, i);
2173 if (tmp == (PyObject *)base)
2174 continue; /* Skip primary base */
2175 assert(PyType_Check(tmp));
2176 tmptype = (PyTypeObject *)tmp;
2177 if (may_add_dict && !add_dict &&
2178 tmptype->tp_dictoffset != 0)
2179 add_dict++;
2180 if (may_add_weak && !add_weak &&
2181 tmptype->tp_weaklistoffset != 0)
2182 add_weak++;
2183 if (may_add_dict && !add_dict)
2184 continue;
2185 if (may_add_weak && !add_weak)
2186 continue;
2187 /* Nothing more to check */
2188 break;
2189 }
2190 }
2191 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002192
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002193 /* Allocate the type object */
2194 type = (PyTypeObject *)metatype->tp_alloc(metatype, nslots);
Victor Stinner6f738742012-02-25 01:22:36 +01002195 if (type == NULL)
2196 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002197
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002198 /* Keep name and slots alive in the extended type object */
2199 et = (PyHeapTypeObject *)type;
2200 Py_INCREF(name);
2201 et->ht_name = name;
2202 et->ht_slots = slots;
Victor Stinner6f738742012-02-25 01:22:36 +01002203 slots = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002204
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002205 /* Initialize tp_flags */
2206 type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE |
2207 Py_TPFLAGS_BASETYPE;
2208 if (base->tp_flags & Py_TPFLAGS_HAVE_GC)
2209 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossumdc91b992001-08-08 22:26:22 +00002210
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002211 /* Initialize essential fields */
2212 type->tp_as_number = &et->as_number;
2213 type->tp_as_sequence = &et->as_sequence;
2214 type->tp_as_mapping = &et->as_mapping;
2215 type->tp_as_buffer = &et->as_buffer;
2216 type->tp_name = _PyUnicode_AsString(name);
Victor Stinner6f738742012-02-25 01:22:36 +01002217 if (!type->tp_name)
2218 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002219
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002220 /* Set tp_base and tp_bases */
2221 type->tp_bases = bases;
Victor Stinner6f738742012-02-25 01:22:36 +01002222 bases = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002223 Py_INCREF(base);
2224 type->tp_base = base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002225
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002226 /* Initialize tp_dict from passed-in dict */
Victor Stinner6f738742012-02-25 01:22:36 +01002227 Py_INCREF(dict);
2228 type->tp_dict = dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002229
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002230 /* Set __module__ in the dict */
Victor Stinner3c1e4812012-03-26 22:10:51 +02002231 if (_PyDict_GetItemId(dict, &PyId___module__) == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002232 tmp = PyEval_GetGlobals();
2233 if (tmp != NULL) {
Victor Stinner3c1e4812012-03-26 22:10:51 +02002234 tmp = _PyDict_GetItemId(tmp, &PyId___name__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002235 if (tmp != NULL) {
Victor Stinner3c1e4812012-03-26 22:10:51 +02002236 if (_PyDict_SetItemId(dict, &PyId___module__,
2237 tmp) < 0)
Victor Stinner6f738742012-02-25 01:22:36 +01002238 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002239 }
2240 }
2241 }
Guido van Rossumc3542212001-08-16 09:18:56 +00002242
Victor Stinner6f738742012-02-25 01:22:36 +01002243 /* Set ht_qualname to dict['__qualname__'] if available, else to
2244 __name__. The __qualname__ accessor will look for ht_qualname.
2245 */
Victor Stinner3c1e4812012-03-26 22:10:51 +02002246 qualname = _PyDict_GetItemId(dict, &PyId___qualname__);
Victor Stinner6f738742012-02-25 01:22:36 +01002247 if (qualname != NULL) {
2248 if (!PyUnicode_Check(qualname)) {
2249 PyErr_Format(PyExc_TypeError,
2250 "type __qualname__ must be a str, not %s",
2251 Py_TYPE(qualname)->tp_name);
2252 goto error;
2253 }
2254 }
Benjamin Peterson8afa7fa2012-10-30 23:51:03 -04002255 et->ht_qualname = qualname ? qualname : et->ht_name;
2256 Py_INCREF(et->ht_qualname);
2257 if (qualname != NULL && PyDict_DelItem(dict, PyId___qualname__.object) < 0)
2258 goto error;
Victor Stinner6f738742012-02-25 01:22:36 +01002259
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002260 /* Set tp_doc to a copy of dict['__doc__'], if the latter is there
2261 and is a string. The __doc__ accessor will first look for tp_doc;
2262 if that fails, it will still look into __dict__.
2263 */
2264 {
Victor Stinner3c1e4812012-03-26 22:10:51 +02002265 PyObject *doc = _PyDict_GetItemId(dict, &PyId___doc__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002266 if (doc != NULL && PyUnicode_Check(doc)) {
2267 Py_ssize_t len;
2268 char *doc_str;
2269 char *tp_doc;
Alexandre Vassalottia85998a2008-05-03 18:24:43 +00002270
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002271 doc_str = _PyUnicode_AsString(doc);
Victor Stinner6f738742012-02-25 01:22:36 +01002272 if (doc_str == NULL)
2273 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002274 /* Silently truncate the docstring if it contains null bytes. */
2275 len = strlen(doc_str);
2276 tp_doc = (char *)PyObject_MALLOC(len + 1);
Victor Stinner6f738742012-02-25 01:22:36 +01002277 if (tp_doc == NULL)
2278 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002279 memcpy(tp_doc, doc_str, len + 1);
2280 type->tp_doc = tp_doc;
2281 }
2282 }
Tim Peters2f93e282001-10-04 05:27:00 +00002283
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002284 /* Special-case __new__: if it's a plain function,
2285 make it a static function */
Victor Stinner3c1e4812012-03-26 22:10:51 +02002286 tmp = _PyDict_GetItemId(dict, &PyId___new__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002287 if (tmp != NULL && PyFunction_Check(tmp)) {
2288 tmp = PyStaticMethod_New(tmp);
Victor Stinner6f738742012-02-25 01:22:36 +01002289 if (tmp == NULL)
2290 goto error;
Victor Stinner3c1e4812012-03-26 22:10:51 +02002291 if (_PyDict_SetItemId(dict, &PyId___new__, tmp) < 0)
2292 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002293 Py_DECREF(tmp);
2294 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002295
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002296 /* Add descriptors for custom slots from __slots__, or for __dict__ */
2297 mp = PyHeapType_GET_MEMBERS(et);
2298 slotoffset = base->tp_basicsize;
Victor Stinner6f738742012-02-25 01:22:36 +01002299 if (et->ht_slots != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002300 for (i = 0; i < nslots; i++, mp++) {
2301 mp->name = _PyUnicode_AsString(
Victor Stinner6f738742012-02-25 01:22:36 +01002302 PyTuple_GET_ITEM(et->ht_slots, i));
2303 if (mp->name == NULL)
2304 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002305 mp->type = T_OBJECT_EX;
2306 mp->offset = slotoffset;
Guido van Rossumd8faa362007-04-27 19:54:29 +00002307
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002308 /* __dict__ and __weakref__ are already filtered out */
2309 assert(strcmp(mp->name, "__dict__") != 0);
2310 assert(strcmp(mp->name, "__weakref__") != 0);
Guido van Rossumd8faa362007-04-27 19:54:29 +00002311
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002312 slotoffset += sizeof(PyObject *);
2313 }
2314 }
2315 if (add_dict) {
2316 if (base->tp_itemsize)
2317 type->tp_dictoffset = -(long)sizeof(PyObject *);
2318 else
2319 type->tp_dictoffset = slotoffset;
2320 slotoffset += sizeof(PyObject *);
2321 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002322 if (type->tp_dictoffset) {
2323 et->ht_cached_keys = _PyDict_NewKeysForClass();
2324 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002325 if (add_weak) {
2326 assert(!base->tp_itemsize);
2327 type->tp_weaklistoffset = slotoffset;
2328 slotoffset += sizeof(PyObject *);
2329 }
2330 type->tp_basicsize = slotoffset;
2331 type->tp_itemsize = base->tp_itemsize;
2332 type->tp_members = PyHeapType_GET_MEMBERS(et);
Guido van Rossum373c7412003-01-07 13:41:37 +00002333
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002334 if (type->tp_weaklistoffset && type->tp_dictoffset)
2335 type->tp_getset = subtype_getsets_full;
2336 else if (type->tp_weaklistoffset && !type->tp_dictoffset)
2337 type->tp_getset = subtype_getsets_weakref_only;
2338 else if (!type->tp_weaklistoffset && type->tp_dictoffset)
2339 type->tp_getset = subtype_getsets_dict_only;
2340 else
2341 type->tp_getset = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002342
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002343 /* Special case some slots */
2344 if (type->tp_dictoffset != 0 || nslots > 0) {
2345 if (base->tp_getattr == NULL && base->tp_getattro == NULL)
2346 type->tp_getattro = PyObject_GenericGetAttr;
2347 if (base->tp_setattr == NULL && base->tp_setattro == NULL)
2348 type->tp_setattro = PyObject_GenericSetAttr;
2349 }
2350 type->tp_dealloc = subtype_dealloc;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002351
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002352 /* Enable GC unless there are really no instance variables possible */
2353 if (!(type->tp_basicsize == sizeof(PyObject) &&
2354 type->tp_itemsize == 0))
2355 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossum9475a232001-10-05 20:51:39 +00002356
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002357 /* Always override allocation strategy to use regular heap */
2358 type->tp_alloc = PyType_GenericAlloc;
2359 if (type->tp_flags & Py_TPFLAGS_HAVE_GC) {
2360 type->tp_free = PyObject_GC_Del;
2361 type->tp_traverse = subtype_traverse;
2362 type->tp_clear = subtype_clear;
2363 }
2364 else
2365 type->tp_free = PyObject_Del;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002366
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002367 /* Initialize the rest */
Victor Stinner6f738742012-02-25 01:22:36 +01002368 if (PyType_Ready(type) < 0)
2369 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002370
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002371 /* Put the proper slots in place */
2372 fixup_slot_dispatchers(type);
Guido van Rossumf040ede2001-08-07 16:40:56 +00002373
Victor Stinner6f738742012-02-25 01:22:36 +01002374 Py_DECREF(dict);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002375 return (PyObject *)type;
Victor Stinner6f738742012-02-25 01:22:36 +01002376
2377error:
2378 Py_XDECREF(dict);
2379 Py_XDECREF(bases);
2380 Py_XDECREF(slots);
2381 Py_XDECREF(type);
2382 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002383}
2384
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002385static short slotoffsets[] = {
2386 -1, /* invalid slot */
2387#include "typeslots.inc"
2388};
2389
Benjamin Petersone28108c2012-01-29 20:13:18 -05002390PyObject *
Martin v. Löwis9c564092012-06-23 23:20:45 +02002391PyType_FromSpecWithBases(PyType_Spec *spec, PyObject *bases)
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002392{
2393 PyHeapTypeObject *res = (PyHeapTypeObject*)PyType_GenericAlloc(&PyType_Type, 0);
Martin v. Löwis9c564092012-06-23 23:20:45 +02002394 PyTypeObject *type, *base;
2395 char *s;
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002396 char *res_start = (char*)res;
2397 PyType_Slot *slot;
Martin v. Löwis9c564092012-06-23 23:20:45 +02002398
2399 /* Set the type name and qualname */
2400 s = strrchr(spec->name, '.');
2401 if (s == NULL)
2402 s = (char*)spec->name;
2403 else
2404 s++;
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002405
Martin v. Löwis5e06a5d2011-02-21 16:24:00 +00002406 if (res == NULL)
Antoine Pitroubb78f572012-06-24 00:18:27 +02002407 return NULL;
2408 type = &res->ht_type;
Antoine Pitrou66a3a7e2012-06-24 00:42:59 +02002409 /* The flags must be initialized early, before the GC traverses us */
2410 type->tp_flags = spec->flags | Py_TPFLAGS_HEAPTYPE;
Martin v. Löwis9c564092012-06-23 23:20:45 +02002411 res->ht_name = PyUnicode_FromString(s);
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002412 if (!res->ht_name)
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002413 goto fail;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002414 res->ht_qualname = res->ht_name;
2415 Py_INCREF(res->ht_qualname);
Antoine Pitroubb78f572012-06-24 00:18:27 +02002416 type->tp_name = spec->name;
2417 if (!type->tp_name)
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002418 goto fail;
Martin v. Löwis9c564092012-06-23 23:20:45 +02002419
2420 /* Adjust for empty tuple bases */
2421 if (!bases) {
2422 base = &PyBaseObject_Type;
2423 /* See whether Py_tp_base(s) was specified */
2424 for (slot = spec->slots; slot->slot; slot++) {
2425 if (slot->slot == Py_tp_base)
2426 base = slot->pfunc;
2427 else if (slot->slot == Py_tp_bases) {
2428 bases = slot->pfunc;
2429 Py_INCREF(bases);
2430 }
2431 }
2432 if (!bases)
2433 bases = PyTuple_Pack(1, base);
2434 if (!bases)
2435 goto fail;
2436 }
2437 else
2438 Py_INCREF(bases);
2439
2440 /* Calculate best base, and check that all bases are type objects */
2441 base = best_base(bases);
2442 if (base == NULL) {
2443 goto fail;
2444 }
2445 if (!PyType_HasFeature(base, Py_TPFLAGS_BASETYPE)) {
2446 PyErr_Format(PyExc_TypeError,
2447 "type '%.100s' is not an acceptable base type",
2448 base->tp_name);
2449 goto fail;
2450 }
2451
Martin v. Löwis9c564092012-06-23 23:20:45 +02002452 /* Initialize essential fields */
2453 type->tp_as_number = &res->as_number;
2454 type->tp_as_sequence = &res->as_sequence;
2455 type->tp_as_mapping = &res->as_mapping;
2456 type->tp_as_buffer = &res->as_buffer;
2457 /* Set tp_base and tp_bases */
2458 type->tp_bases = bases;
2459 bases = NULL;
2460 Py_INCREF(base);
2461 type->tp_base = base;
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002462
Antoine Pitroubb78f572012-06-24 00:18:27 +02002463 type->tp_basicsize = spec->basicsize;
2464 type->tp_itemsize = spec->itemsize;
Victor Stinner0fcab4a2011-01-04 12:59:15 +00002465
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002466 for (slot = spec->slots; slot->slot; slot++) {
Victor Stinner63941882011-09-29 00:42:28 +02002467 if (slot->slot >= Py_ARRAY_LENGTH(slotoffsets)) {
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002468 PyErr_SetString(PyExc_RuntimeError, "invalid slot offset");
2469 goto fail;
2470 }
Martin v. Löwis9c564092012-06-23 23:20:45 +02002471 if (slot->slot == Py_tp_base || slot->slot == Py_tp_bases)
2472 /* Processed above */
2473 continue;
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002474 *(void**)(res_start + slotoffsets[slot->slot]) = slot->pfunc;
Georg Brandl032400b2011-02-19 21:47:02 +00002475
2476 /* need to make a copy of the docstring slot, which usually
2477 points to a static string literal */
2478 if (slot->slot == Py_tp_doc) {
Antoine Pitrou682d94c2012-05-14 14:43:03 +02002479 size_t len = strlen(slot->pfunc)+1;
Georg Brandl032400b2011-02-19 21:47:02 +00002480 char *tp_doc = PyObject_MALLOC(len);
2481 if (tp_doc == NULL)
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002482 goto fail;
Georg Brandl032400b2011-02-19 21:47:02 +00002483 memcpy(tp_doc, slot->pfunc, len);
Antoine Pitroubb78f572012-06-24 00:18:27 +02002484 type->tp_doc = tp_doc;
Georg Brandl032400b2011-02-19 21:47:02 +00002485 }
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002486 }
Antoine Pitroubb78f572012-06-24 00:18:27 +02002487 if (type->tp_dictoffset) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002488 res->ht_cached_keys = _PyDict_NewKeysForClass();
2489 }
Antoine Pitroubb78f572012-06-24 00:18:27 +02002490 if (type->tp_dealloc == NULL) {
Antoine Pitrou99cc6292012-06-23 14:42:38 +02002491 /* It's a heap type, so needs the heap types' dealloc.
2492 subtype_dealloc will call the base type's tp_dealloc, if
2493 necessary. */
Antoine Pitroubb78f572012-06-24 00:18:27 +02002494 type->tp_dealloc = subtype_dealloc;
Antoine Pitrou99cc6292012-06-23 14:42:38 +02002495 }
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002496
Antoine Pitroubb78f572012-06-24 00:18:27 +02002497 if (PyType_Ready(type) < 0)
Benjamin Peterson2652d252012-01-29 20:16:37 -05002498 goto fail;
2499
Martin v. Löwis9c564092012-06-23 23:20:45 +02002500 /* Set type.__module__ */
2501 s = strrchr(spec->name, '.');
2502 if (s != NULL)
2503 _PyDict_SetItemId(type->tp_dict, &PyId___module__,
2504 PyUnicode_FromStringAndSize(
2505 spec->name, (Py_ssize_t)(s - spec->name)));
2506
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002507 return (PyObject*)res;
Victor Stinner0fcab4a2011-01-04 12:59:15 +00002508
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002509 fail:
2510 Py_DECREF(res);
2511 return NULL;
2512}
2513
Martin v. Löwis9c564092012-06-23 23:20:45 +02002514PyObject *
2515PyType_FromSpec(PyType_Spec *spec)
2516{
2517 return PyType_FromSpecWithBases(spec, NULL);
2518}
2519
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002520
Tim Peters6d6c1a32001-08-02 04:15:00 +00002521/* Internal API to look for a name through the MRO.
2522 This returns a borrowed reference, and doesn't set an exception! */
2523PyObject *
2524_PyType_Lookup(PyTypeObject *type, PyObject *name)
2525{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002526 Py_ssize_t i, n;
2527 PyObject *mro, *res, *base, *dict;
2528 unsigned int h;
Christian Heimesa62da1d2008-01-12 19:39:10 +00002529
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002530 if (MCACHE_CACHEABLE_NAME(name) &&
2531 PyType_HasFeature(type, Py_TPFLAGS_VALID_VERSION_TAG)) {
2532 /* fast path */
2533 h = MCACHE_HASH_METHOD(type, name);
2534 if (method_cache[h].version == type->tp_version_tag &&
2535 method_cache[h].name == name)
2536 return method_cache[h].value;
2537 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002538
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002539 /* Look in tp_dict of types in MRO */
2540 mro = type->tp_mro;
Guido van Rossum23094982002-06-10 14:30:43 +00002541
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002542 /* If mro is NULL, the type is either not yet initialized
2543 by PyType_Ready(), or already cleared by type_clear().
2544 Either way the safest thing to do is to return NULL. */
2545 if (mro == NULL)
2546 return NULL;
Guido van Rossum23094982002-06-10 14:30:43 +00002547
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002548 res = NULL;
Victor Stinnerd74782b2012-03-09 00:39:08 +01002549 /* keep a strong reference to mro because type->tp_mro can be replaced
2550 during PyDict_GetItem(dict, name) */
2551 Py_INCREF(mro);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002552 assert(PyTuple_Check(mro));
2553 n = PyTuple_GET_SIZE(mro);
2554 for (i = 0; i < n; i++) {
2555 base = PyTuple_GET_ITEM(mro, i);
2556 assert(PyType_Check(base));
2557 dict = ((PyTypeObject *)base)->tp_dict;
2558 assert(dict && PyDict_Check(dict));
2559 res = PyDict_GetItem(dict, name);
2560 if (res != NULL)
2561 break;
2562 }
Victor Stinnerd74782b2012-03-09 00:39:08 +01002563 Py_DECREF(mro);
Christian Heimesa62da1d2008-01-12 19:39:10 +00002564
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002565 if (MCACHE_CACHEABLE_NAME(name) && assign_version_tag(type)) {
2566 h = MCACHE_HASH_METHOD(type, name);
2567 method_cache[h].version = type->tp_version_tag;
2568 method_cache[h].value = res; /* borrowed */
2569 Py_INCREF(name);
2570 Py_DECREF(method_cache[h].name);
2571 method_cache[h].name = name;
2572 }
2573 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002574}
2575
Victor Stinner3c1e4812012-03-26 22:10:51 +02002576static PyObject *
2577_PyType_LookupId(PyTypeObject *type, struct _Py_Identifier *name)
2578{
2579 PyObject *oname;
2580 oname = _PyUnicode_FromId(name); /* borrowed */
2581 if (oname == NULL)
2582 return NULL;
2583 return _PyType_Lookup(type, oname);
2584}
2585
Tim Peters6d6c1a32001-08-02 04:15:00 +00002586/* This is similar to PyObject_GenericGetAttr(),
2587 but uses _PyType_Lookup() instead of just looking in type->tp_dict. */
2588static PyObject *
2589type_getattro(PyTypeObject *type, PyObject *name)
2590{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002591 PyTypeObject *metatype = Py_TYPE(type);
2592 PyObject *meta_attribute, *attribute;
2593 descrgetfunc meta_get;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002594
Benjamin Peterson16d84ac2012-03-16 09:32:59 -05002595 if (!PyUnicode_Check(name)) {
2596 PyErr_Format(PyExc_TypeError,
2597 "attribute name must be string, not '%.200s'",
2598 name->ob_type->tp_name);
2599 return NULL;
2600 }
2601
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002602 /* Initialize this type (we'll assume the metatype is initialized) */
2603 if (type->tp_dict == NULL) {
2604 if (PyType_Ready(type) < 0)
2605 return NULL;
2606 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002607
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002608 /* No readable descriptor found yet */
2609 meta_get = NULL;
Tim Peters34592512002-07-11 06:23:50 +00002610
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002611 /* Look for the attribute in the metatype */
2612 meta_attribute = _PyType_Lookup(metatype, name);
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002613
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002614 if (meta_attribute != NULL) {
2615 meta_get = Py_TYPE(meta_attribute)->tp_descr_get;
Tim Peters34592512002-07-11 06:23:50 +00002616
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002617 if (meta_get != NULL && PyDescr_IsData(meta_attribute)) {
2618 /* Data descriptors implement tp_descr_set to intercept
2619 * writes. Assume the attribute is not overridden in
2620 * type's tp_dict (and bases): call the descriptor now.
2621 */
2622 return meta_get(meta_attribute, (PyObject *)type,
2623 (PyObject *)metatype);
2624 }
2625 Py_INCREF(meta_attribute);
2626 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002627
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002628 /* No data descriptor found on metatype. Look in tp_dict of this
2629 * type and its bases */
2630 attribute = _PyType_Lookup(type, name);
2631 if (attribute != NULL) {
2632 /* Implement descriptor functionality, if any */
2633 descrgetfunc local_get = Py_TYPE(attribute)->tp_descr_get;
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00002634
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002635 Py_XDECREF(meta_attribute);
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00002636
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002637 if (local_get != NULL) {
2638 /* NULL 2nd argument indicates the descriptor was
2639 * found on the target object itself (or a base) */
2640 return local_get(attribute, (PyObject *)NULL,
2641 (PyObject *)type);
2642 }
Tim Peters34592512002-07-11 06:23:50 +00002643
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002644 Py_INCREF(attribute);
2645 return attribute;
2646 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002647
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002648 /* No attribute found in local __dict__ (or bases): use the
2649 * descriptor from the metatype, if any */
2650 if (meta_get != NULL) {
2651 PyObject *res;
2652 res = meta_get(meta_attribute, (PyObject *)type,
2653 (PyObject *)metatype);
2654 Py_DECREF(meta_attribute);
2655 return res;
2656 }
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002657
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002658 /* If an ordinary attribute was found on the metatype, return it now */
2659 if (meta_attribute != NULL) {
2660 return meta_attribute;
2661 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002662
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002663 /* Give up */
2664 PyErr_Format(PyExc_AttributeError,
2665 "type object '%.50s' has no attribute '%U'",
2666 type->tp_name, name);
2667 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002668}
2669
2670static int
2671type_setattro(PyTypeObject *type, PyObject *name, PyObject *value)
2672{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002673 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
2674 PyErr_Format(
2675 PyExc_TypeError,
2676 "can't set attributes of built-in/extension type '%s'",
2677 type->tp_name);
2678 return -1;
2679 }
2680 if (PyObject_GenericSetAttr((PyObject *)type, name, value) < 0)
2681 return -1;
2682 return update_slot(type, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002683}
2684
Benjamin Peterson64acccf2012-04-27 15:07:36 -04002685extern void
2686_PyDictKeys_DecRef(PyDictKeysObject *keys);
2687
Tim Peters6d6c1a32001-08-02 04:15:00 +00002688static void
2689type_dealloc(PyTypeObject *type)
2690{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002691 PyHeapTypeObject *et;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002692
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002693 /* Assert this is a heap-allocated type object */
2694 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
2695 _PyObject_GC_UNTRACK(type);
2696 PyObject_ClearWeakRefs((PyObject *)type);
2697 et = (PyHeapTypeObject *)type;
2698 Py_XDECREF(type->tp_base);
2699 Py_XDECREF(type->tp_dict);
2700 Py_XDECREF(type->tp_bases);
2701 Py_XDECREF(type->tp_mro);
2702 Py_XDECREF(type->tp_cache);
2703 Py_XDECREF(type->tp_subclasses);
2704 /* A type's tp_doc is heap allocated, unlike the tp_doc slots
2705 * of most other objects. It's okay to cast it to char *.
2706 */
2707 PyObject_Free((char *)type->tp_doc);
2708 Py_XDECREF(et->ht_name);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002709 Py_XDECREF(et->ht_qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002710 Py_XDECREF(et->ht_slots);
Benjamin Peterson64acccf2012-04-27 15:07:36 -04002711 if (et->ht_cached_keys)
2712 _PyDictKeys_DecRef(et->ht_cached_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002713 Py_TYPE(type)->tp_free((PyObject *)type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002714}
2715
Guido van Rossum1c450732001-10-08 15:18:27 +00002716static PyObject *
2717type_subclasses(PyTypeObject *type, PyObject *args_ignored)
2718{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002719 PyObject *list, *raw, *ref;
2720 Py_ssize_t i, n;
Guido van Rossum1c450732001-10-08 15:18:27 +00002721
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002722 list = PyList_New(0);
2723 if (list == NULL)
2724 return NULL;
2725 raw = type->tp_subclasses;
2726 if (raw == NULL)
2727 return list;
2728 assert(PyList_Check(raw));
2729 n = PyList_GET_SIZE(raw);
2730 for (i = 0; i < n; i++) {
2731 ref = PyList_GET_ITEM(raw, i);
2732 assert(PyWeakref_CheckRef(ref));
2733 ref = PyWeakref_GET_OBJECT(ref);
2734 if (ref != Py_None) {
2735 if (PyList_Append(list, ref) < 0) {
2736 Py_DECREF(list);
2737 return NULL;
2738 }
2739 }
2740 }
2741 return list;
Guido van Rossum1c450732001-10-08 15:18:27 +00002742}
2743
Guido van Rossum47374822007-08-02 16:48:17 +00002744static PyObject *
2745type_prepare(PyObject *self, PyObject *args, PyObject *kwds)
2746{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002747 return PyDict_New();
Guido van Rossum47374822007-08-02 16:48:17 +00002748}
2749
Victor Stinner63941882011-09-29 00:42:28 +02002750/*
Benjamin Peterson82b00c12011-05-24 11:09:06 -05002751 Merge the __dict__ of aclass into dict, and recursively also all
2752 the __dict__s of aclass's base classes. The order of merging isn't
2753 defined, as it's expected that only the final set of dict keys is
2754 interesting.
2755 Return 0 on success, -1 on error.
2756*/
2757
2758static int
2759merge_class_dict(PyObject *dict, PyObject *aclass)
2760{
2761 PyObject *classdict;
2762 PyObject *bases;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02002763 _Py_IDENTIFIER(__bases__);
Benjamin Peterson82b00c12011-05-24 11:09:06 -05002764
2765 assert(PyDict_Check(dict));
2766 assert(aclass);
2767
2768 /* Merge in the type's dict (if any). */
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002769 classdict = _PyObject_GetAttrId(aclass, &PyId___dict__);
Benjamin Peterson82b00c12011-05-24 11:09:06 -05002770 if (classdict == NULL)
2771 PyErr_Clear();
2772 else {
2773 int status = PyDict_Update(dict, classdict);
2774 Py_DECREF(classdict);
2775 if (status < 0)
2776 return -1;
2777 }
2778
2779 /* Recursively merge in the base types' (if any) dicts. */
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002780 bases = _PyObject_GetAttrId(aclass, &PyId___bases__);
Benjamin Peterson82b00c12011-05-24 11:09:06 -05002781 if (bases == NULL)
2782 PyErr_Clear();
2783 else {
2784 /* We have no guarantee that bases is a real tuple */
2785 Py_ssize_t i, n;
2786 n = PySequence_Size(bases); /* This better be right */
2787 if (n < 0)
2788 PyErr_Clear();
2789 else {
2790 for (i = 0; i < n; i++) {
2791 int status;
2792 PyObject *base = PySequence_GetItem(bases, i);
2793 if (base == NULL) {
2794 Py_DECREF(bases);
2795 return -1;
2796 }
2797 status = merge_class_dict(dict, base);
2798 Py_DECREF(base);
2799 if (status < 0) {
2800 Py_DECREF(bases);
2801 return -1;
2802 }
2803 }
2804 }
2805 Py_DECREF(bases);
2806 }
2807 return 0;
2808}
2809
2810/* __dir__ for type objects: returns __dict__ and __bases__.
2811 We deliberately don't suck up its __class__, as methods belonging to the
2812 metaclass would probably be more confusing than helpful.
2813*/
2814static PyObject *
2815type_dir(PyObject *self, PyObject *args)
2816{
2817 PyObject *result = NULL;
2818 PyObject *dict = PyDict_New();
2819
2820 if (dict != NULL && merge_class_dict(dict, self) == 0)
2821 result = PyDict_Keys(dict);
2822
2823 Py_XDECREF(dict);
2824 return result;
2825}
2826
Martin v. Loewis4f2f3b62012-04-24 19:13:57 +02002827static PyObject*
2828type_sizeof(PyObject *self, PyObject *args_unused)
2829{
2830 Py_ssize_t size;
2831 PyTypeObject *type = (PyTypeObject*)self;
2832 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
2833 PyHeapTypeObject* et = (PyHeapTypeObject*)type;
2834 size = sizeof(PyHeapTypeObject);
2835 if (et->ht_cached_keys)
2836 size += _PyDict_KeysSize(et->ht_cached_keys);
2837 }
2838 else
2839 size = sizeof(PyTypeObject);
2840 return PyLong_FromSsize_t(size);
2841}
2842
Tim Peters6d6c1a32001-08-02 04:15:00 +00002843static PyMethodDef type_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002844 {"mro", (PyCFunction)mro_external, METH_NOARGS,
2845 PyDoc_STR("mro() -> list\nreturn a type's method resolution order")},
2846 {"__subclasses__", (PyCFunction)type_subclasses, METH_NOARGS,
2847 PyDoc_STR("__subclasses__() -> list of immediate subclasses")},
2848 {"__prepare__", (PyCFunction)type_prepare,
2849 METH_VARARGS | METH_KEYWORDS | METH_CLASS,
2850 PyDoc_STR("__prepare__() -> dict\n"
2851 "used to create the namespace for the class statement")},
2852 {"__instancecheck__", type___instancecheck__, METH_O,
Benjamin Petersonfbe56bb2011-05-24 12:42:51 -05002853 PyDoc_STR("__instancecheck__() -> bool\ncheck if an object is an instance")},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002854 {"__subclasscheck__", type___subclasscheck__, METH_O,
Benjamin Petersonfbe56bb2011-05-24 12:42:51 -05002855 PyDoc_STR("__subclasscheck__() -> bool\ncheck if a class is a subclass")},
Benjamin Peterson82b00c12011-05-24 11:09:06 -05002856 {"__dir__", type_dir, METH_NOARGS,
Benjamin Petersonc7284122011-05-24 12:46:15 -05002857 PyDoc_STR("__dir__() -> list\nspecialized __dir__ implementation for types")},
Martin v. Loewis4f2f3b62012-04-24 19:13:57 +02002858 {"__sizeof__", type_sizeof, METH_NOARGS,
2859 "__sizeof__() -> int\nreturn memory consumption of the type object"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002860 {0}
Tim Peters6d6c1a32001-08-02 04:15:00 +00002861};
2862
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002863PyDoc_STRVAR(type_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00002864"type(object) -> the object's type\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002865"type(name, bases, dict) -> a new type");
Tim Peters6d6c1a32001-08-02 04:15:00 +00002866
Guido van Rossum048eb752001-10-02 21:24:57 +00002867static int
2868type_traverse(PyTypeObject *type, visitproc visit, void *arg)
2869{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002870 /* Because of type_is_gc(), the collector only calls this
2871 for heaptypes. */
Antoine Pitrou1351ca62012-06-24 00:30:12 +02002872 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
2873 char msg[200];
2874 sprintf(msg, "type_traverse() called for non-heap type '%.100s'",
2875 type->tp_name);
2876 Py_FatalError(msg);
2877 }
Guido van Rossum048eb752001-10-02 21:24:57 +00002878
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002879 Py_VISIT(type->tp_dict);
2880 Py_VISIT(type->tp_cache);
2881 Py_VISIT(type->tp_mro);
2882 Py_VISIT(type->tp_bases);
2883 Py_VISIT(type->tp_base);
Guido van Rossuma3862092002-06-10 15:24:42 +00002884
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002885 /* There's no need to visit type->tp_subclasses or
2886 ((PyHeapTypeObject *)type)->ht_slots, because they can't be involved
2887 in cycles; tp_subclasses is a list of weak references,
2888 and slots is a tuple of strings. */
Guido van Rossum048eb752001-10-02 21:24:57 +00002889
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002890 return 0;
Guido van Rossum048eb752001-10-02 21:24:57 +00002891}
2892
2893static int
2894type_clear(PyTypeObject *type)
2895{
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002896 PyDictKeysObject *cached_keys;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002897 /* Because of type_is_gc(), the collector only calls this
2898 for heaptypes. */
2899 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002900
Antoine Pitrou2e872082011-12-15 14:15:31 +01002901 /* We need to invalidate the method cache carefully before clearing
2902 the dict, so that other objects caught in a reference cycle
2903 don't start calling destroyed methods.
2904
2905 Otherwise, the only field we need to clear is tp_mro, which is
2906 part of a hard cycle (its first element is the class itself) that
2907 won't be broken otherwise (it's a tuple and tuples don't have a
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002908 tp_clear handler). None of the other fields need to be
2909 cleared, and here's why:
Guido van Rossum048eb752001-10-02 21:24:57 +00002910
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002911 tp_cache:
2912 Not used; if it were, it would be a dict.
Guido van Rossuma3862092002-06-10 15:24:42 +00002913
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002914 tp_bases, tp_base:
2915 If these are involved in a cycle, there must be at least
2916 one other, mutable object in the cycle, e.g. a base
2917 class's dict; the cycle will be broken that way.
Guido van Rossuma3862092002-06-10 15:24:42 +00002918
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002919 tp_subclasses:
2920 A list of weak references can't be part of a cycle; and
2921 lists have their own tp_clear.
Guido van Rossuma3862092002-06-10 15:24:42 +00002922
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002923 slots (in PyHeapTypeObject):
2924 A tuple of strings can't be part of a cycle.
2925 */
Guido van Rossuma3862092002-06-10 15:24:42 +00002926
Antoine Pitrou2e872082011-12-15 14:15:31 +01002927 PyType_Modified(type);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002928 cached_keys = ((PyHeapTypeObject *)type)->ht_cached_keys;
2929 if (cached_keys != NULL) {
2930 ((PyHeapTypeObject *)type)->ht_cached_keys = NULL;
2931 _PyDictKeys_DecRef(cached_keys);
2932 }
Antoine Pitrou2e872082011-12-15 14:15:31 +01002933 if (type->tp_dict)
2934 PyDict_Clear(type->tp_dict);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002935 Py_CLEAR(type->tp_mro);
Guido van Rossum048eb752001-10-02 21:24:57 +00002936
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002937 return 0;
Guido van Rossum048eb752001-10-02 21:24:57 +00002938}
2939
2940static int
2941type_is_gc(PyTypeObject *type)
2942{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002943 return type->tp_flags & Py_TPFLAGS_HEAPTYPE;
Guido van Rossum048eb752001-10-02 21:24:57 +00002944}
2945
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002946PyTypeObject PyType_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002947 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2948 "type", /* tp_name */
2949 sizeof(PyHeapTypeObject), /* tp_basicsize */
2950 sizeof(PyMemberDef), /* tp_itemsize */
2951 (destructor)type_dealloc, /* tp_dealloc */
2952 0, /* tp_print */
2953 0, /* tp_getattr */
2954 0, /* tp_setattr */
2955 0, /* tp_reserved */
2956 (reprfunc)type_repr, /* tp_repr */
2957 0, /* tp_as_number */
2958 0, /* tp_as_sequence */
2959 0, /* tp_as_mapping */
2960 0, /* tp_hash */
2961 (ternaryfunc)type_call, /* tp_call */
2962 0, /* tp_str */
2963 (getattrofunc)type_getattro, /* tp_getattro */
2964 (setattrofunc)type_setattro, /* tp_setattro */
2965 0, /* tp_as_buffer */
2966 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
2967 Py_TPFLAGS_BASETYPE | Py_TPFLAGS_TYPE_SUBCLASS, /* tp_flags */
2968 type_doc, /* tp_doc */
2969 (traverseproc)type_traverse, /* tp_traverse */
2970 (inquiry)type_clear, /* tp_clear */
2971 0, /* tp_richcompare */
2972 offsetof(PyTypeObject, tp_weaklist), /* tp_weaklistoffset */
2973 0, /* tp_iter */
2974 0, /* tp_iternext */
2975 type_methods, /* tp_methods */
2976 type_members, /* tp_members */
2977 type_getsets, /* tp_getset */
2978 0, /* tp_base */
2979 0, /* tp_dict */
2980 0, /* tp_descr_get */
2981 0, /* tp_descr_set */
2982 offsetof(PyTypeObject, tp_dict), /* tp_dictoffset */
2983 type_init, /* tp_init */
2984 0, /* tp_alloc */
2985 type_new, /* tp_new */
2986 PyObject_GC_Del, /* tp_free */
2987 (inquiry)type_is_gc, /* tp_is_gc */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002988};
Tim Peters6d6c1a32001-08-02 04:15:00 +00002989
2990
2991/* The base type of all types (eventually)... except itself. */
2992
Guido van Rossumd8faa362007-04-27 19:54:29 +00002993/* You may wonder why object.__new__() only complains about arguments
2994 when object.__init__() is not overridden, and vice versa.
2995
2996 Consider the use cases:
2997
2998 1. When neither is overridden, we want to hear complaints about
2999 excess (i.e., any) arguments, since their presence could
3000 indicate there's a bug.
3001
3002 2. When defining an Immutable type, we are likely to override only
3003 __new__(), since __init__() is called too late to initialize an
3004 Immutable object. Since __new__() defines the signature for the
3005 type, it would be a pain to have to override __init__() just to
3006 stop it from complaining about excess arguments.
3007
3008 3. When defining a Mutable type, we are likely to override only
3009 __init__(). So here the converse reasoning applies: we don't
3010 want to have to override __new__() just to stop it from
3011 complaining.
3012
3013 4. When __init__() is overridden, and the subclass __init__() calls
3014 object.__init__(), the latter should complain about excess
3015 arguments; ditto for __new__().
3016
3017 Use cases 2 and 3 make it unattractive to unconditionally check for
3018 excess arguments. The best solution that addresses all four use
3019 cases is as follows: __init__() complains about excess arguments
3020 unless __new__() is overridden and __init__() is not overridden
3021 (IOW, if __init__() is overridden or __new__() is not overridden);
3022 symmetrically, __new__() complains about excess arguments unless
3023 __init__() is overridden and __new__() is not overridden
3024 (IOW, if __new__() is overridden or __init__() is not overridden).
3025
3026 However, for backwards compatibility, this breaks too much code.
3027 Therefore, in 2.6, we'll *warn* about excess arguments when both
3028 methods are overridden; for all other cases we'll use the above
3029 rules.
3030
3031*/
3032
3033/* Forward */
3034static PyObject *
3035object_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
3036
3037static int
3038excess_args(PyObject *args, PyObject *kwds)
3039{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003040 return PyTuple_GET_SIZE(args) ||
3041 (kwds && PyDict_Check(kwds) && PyDict_Size(kwds));
Guido van Rossumd8faa362007-04-27 19:54:29 +00003042}
3043
Tim Peters6d6c1a32001-08-02 04:15:00 +00003044static int
3045object_init(PyObject *self, PyObject *args, PyObject *kwds)
3046{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003047 int err = 0;
Benjamin Peterson96384b92012-03-17 00:05:44 -05003048 PyTypeObject *type = Py_TYPE(self);
3049 if (excess_args(args, kwds) &&
3050 (type->tp_new == object_new || type->tp_init != object_init)) {
3051 PyErr_SetString(PyExc_TypeError, "object.__init__() takes no parameters");
3052 err = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003053 }
3054 return err;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003055}
3056
Guido van Rossum298e4212003-02-13 16:30:16 +00003057static PyObject *
3058object_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3059{
Benjamin Peterson96384b92012-03-17 00:05:44 -05003060 if (excess_args(args, kwds) &&
3061 (type->tp_init == object_init || type->tp_new != object_new)) {
R David Murray702a5dc2013-02-18 21:39:18 -05003062 PyErr_SetString(PyExc_TypeError, "object() takes no parameters");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003063 return NULL;
Benjamin Peterson96384b92012-03-17 00:05:44 -05003064 }
Victor Stinner3c1e4812012-03-26 22:10:51 +02003065
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003066 if (type->tp_flags & Py_TPFLAGS_IS_ABSTRACT) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003067 PyObject *abstract_methods = NULL;
3068 PyObject *builtins;
3069 PyObject *sorted;
3070 PyObject *sorted_methods = NULL;
3071 PyObject *joined = NULL;
Benjamin Peterson9a03ecf2012-03-16 20:15:54 -05003072 PyObject *comma;
3073 _Py_static_string(comma_id, ", ");
Victor Stinner3c1e4812012-03-26 22:10:51 +02003074 _Py_IDENTIFIER(sorted);
Christian Heimes9e7f1d22008-02-28 12:27:11 +00003075
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003076 /* Compute ", ".join(sorted(type.__abstractmethods__))
3077 into joined. */
3078 abstract_methods = type_abstractmethods(type, NULL);
3079 if (abstract_methods == NULL)
3080 goto error;
3081 builtins = PyEval_GetBuiltins();
3082 if (builtins == NULL)
3083 goto error;
Victor Stinner3c1e4812012-03-26 22:10:51 +02003084 sorted = _PyDict_GetItemId(builtins, &PyId_sorted);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003085 if (sorted == NULL)
3086 goto error;
3087 sorted_methods = PyObject_CallFunctionObjArgs(sorted,
3088 abstract_methods,
3089 NULL);
3090 if (sorted_methods == NULL)
3091 goto error;
Benjamin Peterson9a03ecf2012-03-16 20:15:54 -05003092 comma = _PyUnicode_FromId(&comma_id);
3093 if (comma == NULL)
3094 goto error;
3095 joined = PyUnicode_Join(comma, sorted_methods);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003096 if (joined == NULL)
3097 goto error;
Christian Heimes9e7f1d22008-02-28 12:27:11 +00003098
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003099 PyErr_Format(PyExc_TypeError,
3100 "Can't instantiate abstract class %s "
3101 "with abstract methods %U",
3102 type->tp_name,
3103 joined);
3104 error:
3105 Py_XDECREF(joined);
3106 Py_XDECREF(sorted_methods);
3107 Py_XDECREF(abstract_methods);
3108 return NULL;
3109 }
3110 return type->tp_alloc(type, 0);
Guido van Rossum298e4212003-02-13 16:30:16 +00003111}
3112
Tim Peters6d6c1a32001-08-02 04:15:00 +00003113static void
3114object_dealloc(PyObject *self)
3115{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003116 Py_TYPE(self)->tp_free(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003117}
3118
Guido van Rossum8e248182001-08-12 05:17:56 +00003119static PyObject *
3120object_repr(PyObject *self)
3121{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003122 PyTypeObject *type;
3123 PyObject *mod, *name, *rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00003124
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003125 type = Py_TYPE(self);
3126 mod = type_module(type, NULL);
3127 if (mod == NULL)
3128 PyErr_Clear();
3129 else if (!PyUnicode_Check(mod)) {
3130 Py_DECREF(mod);
3131 mod = NULL;
3132 }
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003133 name = type_qualname(type, NULL);
Christian Heimese81dc292012-09-10 16:57:36 +02003134 if (name == NULL) {
3135 Py_XDECREF(mod);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003136 return NULL;
Christian Heimese81dc292012-09-10 16:57:36 +02003137 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003138 if (mod != NULL && PyUnicode_CompareWithASCIIString(mod, "builtins"))
3139 rtn = PyUnicode_FromFormat("<%U.%U object at %p>", mod, name, self);
3140 else
3141 rtn = PyUnicode_FromFormat("<%s object at %p>",
3142 type->tp_name, self);
3143 Py_XDECREF(mod);
3144 Py_DECREF(name);
3145 return rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00003146}
3147
Guido van Rossumb8f63662001-08-15 23:57:02 +00003148static PyObject *
3149object_str(PyObject *self)
3150{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003151 unaryfunc f;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003152
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003153 f = Py_TYPE(self)->tp_repr;
Benjamin Peterson7b166872012-04-24 11:06:25 -04003154 if (f == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003155 f = object_repr;
3156 return f(self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003157}
3158
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003159static PyObject *
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003160object_richcompare(PyObject *self, PyObject *other, int op)
3161{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003162 PyObject *res;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003163
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003164 switch (op) {
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003165
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003166 case Py_EQ:
3167 /* Return NotImplemented instead of False, so if two
3168 objects are compared, both get a chance at the
3169 comparison. See issue #1393. */
3170 res = (self == other) ? Py_True : Py_NotImplemented;
3171 Py_INCREF(res);
3172 break;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003173
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003174 case Py_NE:
3175 /* By default, != returns the opposite of ==,
3176 unless the latter returns NotImplemented. */
3177 res = PyObject_RichCompare(self, other, Py_EQ);
3178 if (res != NULL && res != Py_NotImplemented) {
3179 int ok = PyObject_IsTrue(res);
3180 Py_DECREF(res);
3181 if (ok < 0)
3182 res = NULL;
3183 else {
3184 if (ok)
3185 res = Py_False;
3186 else
3187 res = Py_True;
3188 Py_INCREF(res);
3189 }
3190 }
3191 break;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003192
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003193 default:
3194 res = Py_NotImplemented;
3195 Py_INCREF(res);
3196 break;
3197 }
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003198
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003199 return res;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003200}
3201
3202static PyObject *
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003203object_get_class(PyObject *self, void *closure)
3204{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003205 Py_INCREF(Py_TYPE(self));
3206 return (PyObject *)(Py_TYPE(self));
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003207}
3208
3209static int
3210equiv_structs(PyTypeObject *a, PyTypeObject *b)
3211{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003212 return a == b ||
3213 (a != NULL &&
3214 b != NULL &&
3215 a->tp_basicsize == b->tp_basicsize &&
3216 a->tp_itemsize == b->tp_itemsize &&
3217 a->tp_dictoffset == b->tp_dictoffset &&
3218 a->tp_weaklistoffset == b->tp_weaklistoffset &&
3219 ((a->tp_flags & Py_TPFLAGS_HAVE_GC) ==
3220 (b->tp_flags & Py_TPFLAGS_HAVE_GC)));
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003221}
3222
3223static int
3224same_slots_added(PyTypeObject *a, PyTypeObject *b)
3225{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003226 PyTypeObject *base = a->tp_base;
3227 Py_ssize_t size;
3228 PyObject *slots_a, *slots_b;
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003229
Benjamin Peterson67641d22011-01-17 19:24:34 +00003230 assert(base == b->tp_base);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003231 size = base->tp_basicsize;
3232 if (a->tp_dictoffset == size && b->tp_dictoffset == size)
3233 size += sizeof(PyObject *);
3234 if (a->tp_weaklistoffset == size && b->tp_weaklistoffset == size)
3235 size += sizeof(PyObject *);
Guido van Rossumd8faa362007-04-27 19:54:29 +00003236
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003237 /* Check slots compliance */
3238 slots_a = ((PyHeapTypeObject *)a)->ht_slots;
3239 slots_b = ((PyHeapTypeObject *)b)->ht_slots;
3240 if (slots_a && slots_b) {
3241 if (PyObject_RichCompareBool(slots_a, slots_b, Py_EQ) != 1)
3242 return 0;
3243 size += sizeof(PyObject *) * PyTuple_GET_SIZE(slots_a);
3244 }
3245 return size == a->tp_basicsize && size == b->tp_basicsize;
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003246}
3247
3248static int
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003249compatible_for_assignment(PyTypeObject* oldto, PyTypeObject* newto, char* attr)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003250{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003251 PyTypeObject *newbase, *oldbase;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003252
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003253 if (newto->tp_dealloc != oldto->tp_dealloc ||
3254 newto->tp_free != oldto->tp_free)
3255 {
3256 PyErr_Format(PyExc_TypeError,
3257 "%s assignment: "
3258 "'%s' deallocator differs from '%s'",
3259 attr,
3260 newto->tp_name,
3261 oldto->tp_name);
3262 return 0;
3263 }
3264 newbase = newto;
3265 oldbase = oldto;
3266 while (equiv_structs(newbase, newbase->tp_base))
3267 newbase = newbase->tp_base;
3268 while (equiv_structs(oldbase, oldbase->tp_base))
3269 oldbase = oldbase->tp_base;
3270 if (newbase != oldbase &&
3271 (newbase->tp_base != oldbase->tp_base ||
3272 !same_slots_added(newbase, oldbase))) {
3273 PyErr_Format(PyExc_TypeError,
3274 "%s assignment: "
3275 "'%s' object layout differs from '%s'",
3276 attr,
3277 newto->tp_name,
3278 oldto->tp_name);
3279 return 0;
3280 }
Tim Petersea7f75d2002-12-07 21:39:16 +00003281
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003282 return 1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003283}
3284
3285static int
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003286object_set_class(PyObject *self, PyObject *value, void *closure)
3287{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003288 PyTypeObject *oldto = Py_TYPE(self);
3289 PyTypeObject *newto;
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003290
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003291 if (value == NULL) {
3292 PyErr_SetString(PyExc_TypeError,
3293 "can't delete __class__ attribute");
3294 return -1;
3295 }
3296 if (!PyType_Check(value)) {
3297 PyErr_Format(PyExc_TypeError,
Florent Xiclunaaa6c1d22011-12-12 18:54:29 +01003298 "__class__ must be set to a class, not '%s' object",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003299 Py_TYPE(value)->tp_name);
3300 return -1;
3301 }
3302 newto = (PyTypeObject *)value;
3303 if (!(newto->tp_flags & Py_TPFLAGS_HEAPTYPE) ||
3304 !(oldto->tp_flags & Py_TPFLAGS_HEAPTYPE))
3305 {
3306 PyErr_Format(PyExc_TypeError,
3307 "__class__ assignment: only for heap types");
3308 return -1;
3309 }
3310 if (compatible_for_assignment(newto, oldto, "__class__")) {
3311 Py_INCREF(newto);
3312 Py_TYPE(self) = newto;
3313 Py_DECREF(oldto);
3314 return 0;
3315 }
3316 else {
3317 return -1;
3318 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003319}
3320
3321static PyGetSetDef object_getsets[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003322 {"__class__", object_get_class, object_set_class,
3323 PyDoc_STR("the object's class")},
3324 {0}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003325};
3326
Guido van Rossumc53f0092003-02-18 22:05:12 +00003327
Guido van Rossum036f9992003-02-21 22:02:54 +00003328/* Stuff to implement __reduce_ex__ for pickle protocols >= 2.
Alexandre Vassalottif7fa63d2008-05-11 08:55:36 +00003329 We fall back to helpers in copyreg for:
Guido van Rossum036f9992003-02-21 22:02:54 +00003330 - pickle protocols < 2
3331 - calculating the list of slot names (done only once per class)
3332 - the __newobj__ function (which is used as a token but never called)
3333*/
3334
3335static PyObject *
Alexandre Vassalottif7fa63d2008-05-11 08:55:36 +00003336import_copyreg(void)
Guido van Rossum036f9992003-02-21 22:02:54 +00003337{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003338 static PyObject *copyreg_str;
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003339 static PyObject *mod_copyreg = NULL;
Guido van Rossum3926a632001-09-25 16:25:58 +00003340
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003341 if (!copyreg_str) {
3342 copyreg_str = PyUnicode_InternFromString("copyreg");
3343 if (copyreg_str == NULL)
3344 return NULL;
3345 }
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003346 if (!mod_copyreg) {
3347 mod_copyreg = PyImport_Import(copyreg_str);
3348 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003349
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003350 Py_XINCREF(mod_copyreg);
3351 return mod_copyreg;
Guido van Rossum036f9992003-02-21 22:02:54 +00003352}
3353
3354static PyObject *
3355slotnames(PyObject *cls)
3356{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003357 PyObject *clsdict;
3358 PyObject *copyreg;
3359 PyObject *slotnames;
Victor Stinner3c1e4812012-03-26 22:10:51 +02003360 _Py_IDENTIFIER(__slotnames__);
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02003361 _Py_IDENTIFIER(_slotnames);
Guido van Rossum036f9992003-02-21 22:02:54 +00003362
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003363 clsdict = ((PyTypeObject *)cls)->tp_dict;
Victor Stinner3c1e4812012-03-26 22:10:51 +02003364 slotnames = _PyDict_GetItemId(clsdict, &PyId___slotnames__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003365 if (slotnames != NULL && PyList_Check(slotnames)) {
3366 Py_INCREF(slotnames);
3367 return slotnames;
3368 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003369
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003370 copyreg = import_copyreg();
3371 if (copyreg == NULL)
3372 return NULL;
Guido van Rossum036f9992003-02-21 22:02:54 +00003373
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02003374 slotnames = _PyObject_CallMethodId(copyreg, &PyId__slotnames, "O", cls);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003375 Py_DECREF(copyreg);
3376 if (slotnames != NULL &&
3377 slotnames != Py_None &&
3378 !PyList_Check(slotnames))
3379 {
3380 PyErr_SetString(PyExc_TypeError,
3381 "copyreg._slotnames didn't return a list or None");
3382 Py_DECREF(slotnames);
3383 slotnames = NULL;
3384 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003385
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003386 return slotnames;
Guido van Rossum036f9992003-02-21 22:02:54 +00003387}
3388
3389static PyObject *
3390reduce_2(PyObject *obj)
3391{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003392 PyObject *cls, *getnewargs;
3393 PyObject *args = NULL, *args2 = NULL;
3394 PyObject *getstate = NULL, *state = NULL, *names = NULL;
3395 PyObject *slots = NULL, *listitems = NULL, *dictitems = NULL;
3396 PyObject *copyreg = NULL, *newobj = NULL, *res = NULL;
3397 Py_ssize_t i, n;
Victor Stinner3c1e4812012-03-26 22:10:51 +02003398 _Py_IDENTIFIER(__getnewargs__);
3399 _Py_IDENTIFIER(__getstate__);
3400 _Py_IDENTIFIER(__newobj__);
Guido van Rossum036f9992003-02-21 22:02:54 +00003401
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003402 cls = (PyObject *) Py_TYPE(obj);
3403
Victor Stinner3c1e4812012-03-26 22:10:51 +02003404 getnewargs = _PyObject_GetAttrId(obj, &PyId___getnewargs__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003405 if (getnewargs != NULL) {
3406 args = PyObject_CallObject(getnewargs, NULL);
3407 Py_DECREF(getnewargs);
3408 if (args != NULL && !PyTuple_Check(args)) {
3409 PyErr_Format(PyExc_TypeError,
3410 "__getnewargs__ should return a tuple, "
3411 "not '%.200s'", Py_TYPE(args)->tp_name);
3412 goto end;
3413 }
3414 }
3415 else {
3416 PyErr_Clear();
3417 args = PyTuple_New(0);
3418 }
3419 if (args == NULL)
3420 goto end;
Guido van Rossum036f9992003-02-21 22:02:54 +00003421
Victor Stinner3c1e4812012-03-26 22:10:51 +02003422 getstate = _PyObject_GetAttrId(obj, &PyId___getstate__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003423 if (getstate != NULL) {
3424 state = PyObject_CallObject(getstate, NULL);
3425 Py_DECREF(getstate);
3426 if (state == NULL)
3427 goto end;
3428 }
3429 else {
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003430 PyObject **dict;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003431 PyErr_Clear();
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003432 dict = _PyObject_GetDictPtr(obj);
3433 if (dict && *dict)
3434 state = *dict;
3435 else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003436 state = Py_None;
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003437 Py_INCREF(state);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003438 names = slotnames(cls);
3439 if (names == NULL)
3440 goto end;
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003441 if (names != Py_None && PyList_GET_SIZE(names) > 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003442 assert(PyList_Check(names));
3443 slots = PyDict_New();
3444 if (slots == NULL)
3445 goto end;
3446 n = 0;
3447 /* Can't pre-compute the list size; the list
3448 is stored on the class so accessible to other
3449 threads, which may be run by DECREF */
3450 for (i = 0; i < PyList_GET_SIZE(names); i++) {
3451 PyObject *name, *value;
3452 name = PyList_GET_ITEM(names, i);
3453 value = PyObject_GetAttr(obj, name);
3454 if (value == NULL)
3455 PyErr_Clear();
3456 else {
3457 int err = PyDict_SetItem(slots, name,
3458 value);
3459 Py_DECREF(value);
3460 if (err)
3461 goto end;
3462 n++;
3463 }
3464 }
3465 if (n) {
3466 state = Py_BuildValue("(NO)", state, slots);
3467 if (state == NULL)
3468 goto end;
3469 }
3470 }
3471 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003472
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003473 if (!PyList_Check(obj)) {
3474 listitems = Py_None;
3475 Py_INCREF(listitems);
3476 }
3477 else {
3478 listitems = PyObject_GetIter(obj);
3479 if (listitems == NULL)
3480 goto end;
3481 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003482
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003483 if (!PyDict_Check(obj)) {
3484 dictitems = Py_None;
3485 Py_INCREF(dictitems);
3486 }
3487 else {
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02003488 _Py_IDENTIFIER(items);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02003489 PyObject *items = _PyObject_CallMethodId(obj, &PyId_items, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003490 if (items == NULL)
3491 goto end;
3492 dictitems = PyObject_GetIter(items);
3493 Py_DECREF(items);
3494 if (dictitems == NULL)
3495 goto end;
3496 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003497
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003498 copyreg = import_copyreg();
3499 if (copyreg == NULL)
3500 goto end;
Victor Stinner3c1e4812012-03-26 22:10:51 +02003501 newobj = _PyObject_GetAttrId(copyreg, &PyId___newobj__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003502 if (newobj == NULL)
3503 goto end;
Guido van Rossum036f9992003-02-21 22:02:54 +00003504
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003505 n = PyTuple_GET_SIZE(args);
3506 args2 = PyTuple_New(n+1);
3507 if (args2 == NULL)
3508 goto end;
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003509 Py_INCREF(cls);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003510 PyTuple_SET_ITEM(args2, 0, cls);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003511 for (i = 0; i < n; i++) {
3512 PyObject *v = PyTuple_GET_ITEM(args, i);
3513 Py_INCREF(v);
3514 PyTuple_SET_ITEM(args2, i+1, v);
3515 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003516
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003517 res = PyTuple_Pack(5, newobj, args2, state, listitems, dictitems);
Guido van Rossum036f9992003-02-21 22:02:54 +00003518
3519 end:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003520 Py_XDECREF(args);
3521 Py_XDECREF(args2);
3522 Py_XDECREF(slots);
3523 Py_XDECREF(state);
3524 Py_XDECREF(names);
3525 Py_XDECREF(listitems);
3526 Py_XDECREF(dictitems);
3527 Py_XDECREF(copyreg);
3528 Py_XDECREF(newobj);
3529 return res;
Guido van Rossum036f9992003-02-21 22:02:54 +00003530}
3531
Guido van Rossumd8faa362007-04-27 19:54:29 +00003532/*
3533 * There were two problems when object.__reduce__ and object.__reduce_ex__
3534 * were implemented in the same function:
3535 * - trying to pickle an object with a custom __reduce__ method that
3536 * fell back to object.__reduce__ in certain circumstances led to
3537 * infinite recursion at Python level and eventual RuntimeError.
3538 * - Pickling objects that lied about their type by overwriting the
3539 * __class__ descriptor could lead to infinite recursion at C level
3540 * and eventual segfault.
3541 *
3542 * Because of backwards compatibility, the two methods still have to
3543 * behave in the same way, even if this is not required by the pickle
3544 * protocol. This common functionality was moved to the _common_reduce
3545 * function.
3546 */
3547static PyObject *
3548_common_reduce(PyObject *self, int proto)
3549{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003550 PyObject *copyreg, *res;
Guido van Rossumd8faa362007-04-27 19:54:29 +00003551
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003552 if (proto >= 2)
3553 return reduce_2(self);
Guido van Rossumd8faa362007-04-27 19:54:29 +00003554
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003555 copyreg = import_copyreg();
3556 if (!copyreg)
3557 return NULL;
Guido van Rossumd8faa362007-04-27 19:54:29 +00003558
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003559 res = PyEval_CallMethod(copyreg, "_reduce_ex", "(Oi)", self, proto);
3560 Py_DECREF(copyreg);
Guido van Rossumd8faa362007-04-27 19:54:29 +00003561
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003562 return res;
Guido van Rossumd8faa362007-04-27 19:54:29 +00003563}
3564
3565static PyObject *
3566object_reduce(PyObject *self, PyObject *args)
3567{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003568 int proto = 0;
Guido van Rossumd8faa362007-04-27 19:54:29 +00003569
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003570 if (!PyArg_ParseTuple(args, "|i:__reduce__", &proto))
3571 return NULL;
Guido van Rossumd8faa362007-04-27 19:54:29 +00003572
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003573 return _common_reduce(self, proto);
Guido van Rossumd8faa362007-04-27 19:54:29 +00003574}
3575
Guido van Rossum036f9992003-02-21 22:02:54 +00003576static PyObject *
3577object_reduce_ex(PyObject *self, PyObject *args)
3578{
Victor Stinner3c1e4812012-03-26 22:10:51 +02003579 static PyObject *objreduce;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003580 PyObject *reduce, *res;
3581 int proto = 0;
Victor Stinner3c1e4812012-03-26 22:10:51 +02003582 _Py_IDENTIFIER(__reduce__);
Guido van Rossum036f9992003-02-21 22:02:54 +00003583
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003584 if (!PyArg_ParseTuple(args, "|i:__reduce_ex__", &proto))
3585 return NULL;
Guido van Rossum036f9992003-02-21 22:02:54 +00003586
Victor Stinner3c1e4812012-03-26 22:10:51 +02003587 if (objreduce == NULL) {
3588 objreduce = _PyDict_GetItemId(PyBaseObject_Type.tp_dict,
3589 &PyId___reduce__);
3590 if (objreduce == NULL)
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003591 return NULL;
3592 }
3593
Victor Stinner3c1e4812012-03-26 22:10:51 +02003594 reduce = _PyObject_GetAttrId(self, &PyId___reduce__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003595 if (reduce == NULL)
3596 PyErr_Clear();
3597 else {
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003598 PyObject *cls, *clsreduce;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003599 int override;
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003600
3601 cls = (PyObject *) Py_TYPE(self);
Victor Stinner3c1e4812012-03-26 22:10:51 +02003602 clsreduce = _PyObject_GetAttrId(cls, &PyId___reduce__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003603 if (clsreduce == NULL) {
3604 Py_DECREF(reduce);
3605 return NULL;
3606 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003607 override = (clsreduce != objreduce);
3608 Py_DECREF(clsreduce);
3609 if (override) {
3610 res = PyObject_CallObject(reduce, NULL);
3611 Py_DECREF(reduce);
3612 return res;
3613 }
3614 else
3615 Py_DECREF(reduce);
3616 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003617
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003618 return _common_reduce(self, proto);
Guido van Rossum3926a632001-09-25 16:25:58 +00003619}
3620
Christian Heimes9e7f1d22008-02-28 12:27:11 +00003621static PyObject *
3622object_subclasshook(PyObject *cls, PyObject *args)
3623{
Brian Curtindfc80e32011-08-10 20:28:54 -05003624 Py_RETURN_NOTIMPLEMENTED;
Christian Heimes9e7f1d22008-02-28 12:27:11 +00003625}
3626
3627PyDoc_STRVAR(object_subclasshook_doc,
3628"Abstract classes can override this to customize issubclass().\n"
3629"\n"
3630"This is invoked early on by abc.ABCMeta.__subclasscheck__().\n"
3631"It should return True, False or NotImplemented. If it returns\n"
3632"NotImplemented, the normal algorithm is used. Otherwise, it\n"
3633"overrides the normal algorithm (and the outcome is cached).\n");
Eric Smith8c663262007-08-25 02:26:07 +00003634
3635/*
3636 from PEP 3101, this code implements:
3637
3638 class object:
3639 def __format__(self, format_spec):
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003640 return format(str(self), format_spec)
Eric Smith8c663262007-08-25 02:26:07 +00003641*/
3642static PyObject *
3643object_format(PyObject *self, PyObject *args)
3644{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003645 PyObject *format_spec;
3646 PyObject *self_as_str = NULL;
3647 PyObject *result = NULL;
Eric Smith8c663262007-08-25 02:26:07 +00003648
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003649 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
3650 return NULL;
Eric Smith8c663262007-08-25 02:26:07 +00003651
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003652 self_as_str = PyObject_Str(self);
Eric Smithe4d63172010-09-13 20:48:43 +00003653 if (self_as_str != NULL) {
3654 /* Issue 7994: If we're converting to a string, we
Eric V. Smithb9cd3532011-03-12 10:08:48 -05003655 should reject format specifications */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003656 if (PyUnicode_GET_LENGTH(format_spec) > 0) {
Andrew Svetlov2cd8ce42012-12-23 14:27:17 +02003657 PyErr_SetString(PyExc_TypeError,
Eric V. Smithb9cd3532011-03-12 10:08:48 -05003658 "non-empty format string passed to object.__format__");
Andrew Svetlov2cd8ce42012-12-23 14:27:17 +02003659 goto done;
Eric V. Smithb9cd3532011-03-12 10:08:48 -05003660 }
Eric Smith8c663262007-08-25 02:26:07 +00003661
Eric V. Smithb9cd3532011-03-12 10:08:48 -05003662 result = PyObject_Format(self_as_str, format_spec);
Eric Smithe4d63172010-09-13 20:48:43 +00003663 }
3664
3665done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003666 Py_XDECREF(self_as_str);
Eric Smith8c663262007-08-25 02:26:07 +00003667
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003668 return result;
Eric Smith8c663262007-08-25 02:26:07 +00003669}
3670
Martin v. Löwis00709aa2008-06-04 14:18:43 +00003671static PyObject *
3672object_sizeof(PyObject *self, PyObject *args)
3673{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003674 Py_ssize_t res, isize;
Martin v. Löwis00709aa2008-06-04 14:18:43 +00003675
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003676 res = 0;
3677 isize = self->ob_type->tp_itemsize;
3678 if (isize > 0)
3679 res = Py_SIZE(self->ob_type) * isize;
3680 res += self->ob_type->tp_basicsize;
Martin v. Löwis00709aa2008-06-04 14:18:43 +00003681
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003682 return PyLong_FromSsize_t(res);
Martin v. Löwis00709aa2008-06-04 14:18:43 +00003683}
3684
Benjamin Peterson82b00c12011-05-24 11:09:06 -05003685/* __dir__ for generic objects: returns __dict__, __class__,
3686 and recursively up the __class__.__bases__ chain.
3687*/
3688static PyObject *
3689object_dir(PyObject *self, PyObject *args)
3690{
3691 PyObject *result = NULL;
3692 PyObject *dict = NULL;
3693 PyObject *itsclass = NULL;
3694
3695 /* Get __dict__ (which may or may not be a real dict...) */
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02003696 dict = _PyObject_GetAttrId(self, &PyId___dict__);
Benjamin Peterson82b00c12011-05-24 11:09:06 -05003697 if (dict == NULL) {
3698 PyErr_Clear();
3699 dict = PyDict_New();
3700 }
3701 else if (!PyDict_Check(dict)) {
3702 Py_DECREF(dict);
3703 dict = PyDict_New();
3704 }
3705 else {
3706 /* Copy __dict__ to avoid mutating it. */
3707 PyObject *temp = PyDict_Copy(dict);
3708 Py_DECREF(dict);
3709 dict = temp;
3710 }
3711
3712 if (dict == NULL)
3713 goto error;
3714
3715 /* Merge in attrs reachable from its class. */
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02003716 itsclass = _PyObject_GetAttrId(self, &PyId___class__);
Benjamin Peterson82b00c12011-05-24 11:09:06 -05003717 if (itsclass == NULL)
3718 /* XXX(tomer): Perhaps fall back to obj->ob_type if no
3719 __class__ exists? */
3720 PyErr_Clear();
3721 else if (merge_class_dict(dict, itsclass) != 0)
3722 goto error;
3723
3724 result = PyDict_Keys(dict);
3725 /* fall through */
3726error:
3727 Py_XDECREF(itsclass);
3728 Py_XDECREF(dict);
3729 return result;
3730}
3731
Guido van Rossum3926a632001-09-25 16:25:58 +00003732static PyMethodDef object_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003733 {"__reduce_ex__", object_reduce_ex, METH_VARARGS,
3734 PyDoc_STR("helper for pickle")},
3735 {"__reduce__", object_reduce, METH_VARARGS,
3736 PyDoc_STR("helper for pickle")},
3737 {"__subclasshook__", object_subclasshook, METH_CLASS | METH_VARARGS,
3738 object_subclasshook_doc},
3739 {"__format__", object_format, METH_VARARGS,
3740 PyDoc_STR("default object formatter")},
3741 {"__sizeof__", object_sizeof, METH_NOARGS,
Benjamin Petersonfbe56bb2011-05-24 12:42:51 -05003742 PyDoc_STR("__sizeof__() -> int\nsize of object in memory, in bytes")},
Benjamin Peterson82b00c12011-05-24 11:09:06 -05003743 {"__dir__", object_dir, METH_NOARGS,
Benjamin Petersonc7284122011-05-24 12:46:15 -05003744 PyDoc_STR("__dir__() -> list\ndefault dir() implementation")},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003745 {0}
Guido van Rossum3926a632001-09-25 16:25:58 +00003746};
3747
Guido van Rossum036f9992003-02-21 22:02:54 +00003748
Tim Peters6d6c1a32001-08-02 04:15:00 +00003749PyTypeObject PyBaseObject_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003750 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3751 "object", /* tp_name */
3752 sizeof(PyObject), /* tp_basicsize */
3753 0, /* tp_itemsize */
3754 object_dealloc, /* tp_dealloc */
3755 0, /* tp_print */
3756 0, /* tp_getattr */
3757 0, /* tp_setattr */
3758 0, /* tp_reserved */
3759 object_repr, /* tp_repr */
3760 0, /* tp_as_number */
3761 0, /* tp_as_sequence */
3762 0, /* tp_as_mapping */
3763 (hashfunc)_Py_HashPointer, /* tp_hash */
3764 0, /* tp_call */
3765 object_str, /* tp_str */
3766 PyObject_GenericGetAttr, /* tp_getattro */
3767 PyObject_GenericSetAttr, /* tp_setattro */
3768 0, /* tp_as_buffer */
3769 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
3770 PyDoc_STR("The most base type"), /* tp_doc */
3771 0, /* tp_traverse */
3772 0, /* tp_clear */
3773 object_richcompare, /* tp_richcompare */
3774 0, /* tp_weaklistoffset */
3775 0, /* tp_iter */
3776 0, /* tp_iternext */
3777 object_methods, /* tp_methods */
3778 0, /* tp_members */
3779 object_getsets, /* tp_getset */
3780 0, /* tp_base */
3781 0, /* tp_dict */
3782 0, /* tp_descr_get */
3783 0, /* tp_descr_set */
3784 0, /* tp_dictoffset */
3785 object_init, /* tp_init */
3786 PyType_GenericAlloc, /* tp_alloc */
3787 object_new, /* tp_new */
3788 PyObject_Del, /* tp_free */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003789};
3790
3791
Guido van Rossum50e9fb92006-08-17 05:42:55 +00003792/* Add the methods from tp_methods to the __dict__ in a type object */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003793
3794static int
3795add_methods(PyTypeObject *type, PyMethodDef *meth)
3796{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003797 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003798
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003799 for (; meth->ml_name != NULL; meth++) {
3800 PyObject *descr;
Benjamin Peterson89a6e9a2012-05-08 09:22:24 -04003801 int err;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003802 if (PyDict_GetItemString(dict, meth->ml_name) &&
3803 !(meth->ml_flags & METH_COEXIST))
3804 continue;
3805 if (meth->ml_flags & METH_CLASS) {
3806 if (meth->ml_flags & METH_STATIC) {
3807 PyErr_SetString(PyExc_ValueError,
3808 "method cannot be both class and static");
3809 return -1;
3810 }
3811 descr = PyDescr_NewClassMethod(type, meth);
3812 }
3813 else if (meth->ml_flags & METH_STATIC) {
Andrew Svetlov3ba3a3e2012-12-25 13:32:35 +02003814 PyObject *cfunc = PyCFunction_NewEx(meth, (PyObject*)type, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003815 if (cfunc == NULL)
3816 return -1;
3817 descr = PyStaticMethod_New(cfunc);
3818 Py_DECREF(cfunc);
3819 }
3820 else {
3821 descr = PyDescr_NewMethod(type, meth);
3822 }
3823 if (descr == NULL)
3824 return -1;
Benjamin Peterson89a6e9a2012-05-08 09:22:24 -04003825 err = PyDict_SetItemString(dict, meth->ml_name, descr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003826 Py_DECREF(descr);
Benjamin Peterson89a6e9a2012-05-08 09:22:24 -04003827 if (err < 0)
3828 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003829 }
3830 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003831}
3832
3833static int
Guido van Rossum6f799372001-09-20 20:46:19 +00003834add_members(PyTypeObject *type, PyMemberDef *memb)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003835{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003836 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003837
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003838 for (; memb->name != NULL; memb++) {
3839 PyObject *descr;
3840 if (PyDict_GetItemString(dict, memb->name))
3841 continue;
3842 descr = PyDescr_NewMember(type, memb);
3843 if (descr == NULL)
3844 return -1;
3845 if (PyDict_SetItemString(dict, memb->name, descr) < 0)
3846 return -1;
3847 Py_DECREF(descr);
3848 }
3849 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003850}
3851
3852static int
Guido van Rossum32d34c82001-09-20 21:45:26 +00003853add_getset(PyTypeObject *type, PyGetSetDef *gsp)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003854{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003855 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003856
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003857 for (; gsp->name != NULL; gsp++) {
3858 PyObject *descr;
3859 if (PyDict_GetItemString(dict, gsp->name))
3860 continue;
3861 descr = PyDescr_NewGetSet(type, gsp);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003862
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003863 if (descr == NULL)
3864 return -1;
3865 if (PyDict_SetItemString(dict, gsp->name, descr) < 0)
3866 return -1;
3867 Py_DECREF(descr);
3868 }
3869 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003870}
3871
Guido van Rossum13d52f02001-08-10 21:24:08 +00003872static void
3873inherit_special(PyTypeObject *type, PyTypeObject *base)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003874{
Tim Peters6d6c1a32001-08-02 04:15:00 +00003875
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003876 /* Copying basicsize is connected to the GC flags */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003877 if (!(type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
3878 (base->tp_flags & Py_TPFLAGS_HAVE_GC) &&
3879 (!type->tp_traverse && !type->tp_clear)) {
3880 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
3881 if (type->tp_traverse == NULL)
3882 type->tp_traverse = base->tp_traverse;
3883 if (type->tp_clear == NULL)
3884 type->tp_clear = base->tp_clear;
3885 }
3886 {
3887 /* The condition below could use some explanation.
3888 It appears that tp_new is not inherited for static types
3889 whose base class is 'object'; this seems to be a precaution
3890 so that old extension types don't suddenly become
3891 callable (object.__new__ wouldn't insure the invariants
3892 that the extension type's own factory function ensures).
3893 Heap types, of course, are under our control, so they do
3894 inherit tp_new; static extension types that specify some
Florent Xiclunaaa6c1d22011-12-12 18:54:29 +01003895 other built-in type as the default also
3896 inherit object.__new__. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003897 if (base != &PyBaseObject_Type ||
3898 (type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
3899 if (type->tp_new == NULL)
3900 type->tp_new = base->tp_new;
3901 }
3902 }
Benjamin Petersona7465e22010-07-05 15:01:22 +00003903 if (type->tp_basicsize == 0)
3904 type->tp_basicsize = base->tp_basicsize;
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00003905
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003906 /* Copy other non-function slots */
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00003907
3908#undef COPYVAL
3909#define COPYVAL(SLOT) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003910 if (type->SLOT == 0) type->SLOT = base->SLOT
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00003911
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003912 COPYVAL(tp_itemsize);
3913 COPYVAL(tp_weaklistoffset);
3914 COPYVAL(tp_dictoffset);
Thomas Wouters27d517b2007-02-25 20:39:11 +00003915
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003916 /* Setup fast subclass flags */
3917 if (PyType_IsSubtype(base, (PyTypeObject*)PyExc_BaseException))
3918 type->tp_flags |= Py_TPFLAGS_BASE_EXC_SUBCLASS;
3919 else if (PyType_IsSubtype(base, &PyType_Type))
3920 type->tp_flags |= Py_TPFLAGS_TYPE_SUBCLASS;
3921 else if (PyType_IsSubtype(base, &PyLong_Type))
3922 type->tp_flags |= Py_TPFLAGS_LONG_SUBCLASS;
3923 else if (PyType_IsSubtype(base, &PyBytes_Type))
3924 type->tp_flags |= Py_TPFLAGS_BYTES_SUBCLASS;
3925 else if (PyType_IsSubtype(base, &PyUnicode_Type))
3926 type->tp_flags |= Py_TPFLAGS_UNICODE_SUBCLASS;
3927 else if (PyType_IsSubtype(base, &PyTuple_Type))
3928 type->tp_flags |= Py_TPFLAGS_TUPLE_SUBCLASS;
3929 else if (PyType_IsSubtype(base, &PyList_Type))
3930 type->tp_flags |= Py_TPFLAGS_LIST_SUBCLASS;
3931 else if (PyType_IsSubtype(base, &PyDict_Type))
3932 type->tp_flags |= Py_TPFLAGS_DICT_SUBCLASS;
Guido van Rossum13d52f02001-08-10 21:24:08 +00003933}
3934
Guido van Rossum38938152006-08-21 23:36:26 +00003935static int
Guido van Rossumf5243f02008-01-01 04:06:48 +00003936overrides_hash(PyTypeObject *type)
Guido van Rossum38938152006-08-21 23:36:26 +00003937{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003938 PyObject *dict = type->tp_dict;
Victor Stinner3c1e4812012-03-26 22:10:51 +02003939 _Py_IDENTIFIER(__eq__);
Guido van Rossum38938152006-08-21 23:36:26 +00003940
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003941 assert(dict != NULL);
Victor Stinner3c1e4812012-03-26 22:10:51 +02003942 if (_PyDict_GetItemId(dict, &PyId___eq__) != NULL)
3943 return 1;
3944 if (_PyDict_GetItemId(dict, &PyId___hash__) != NULL)
3945 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003946 return 0;
Guido van Rossum38938152006-08-21 23:36:26 +00003947}
3948
Guido van Rossum13d52f02001-08-10 21:24:08 +00003949static void
3950inherit_slots(PyTypeObject *type, PyTypeObject *base)
3951{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003952 PyTypeObject *basebase;
Guido van Rossum13d52f02001-08-10 21:24:08 +00003953
3954#undef SLOTDEFINED
Tim Peters6d6c1a32001-08-02 04:15:00 +00003955#undef COPYSLOT
3956#undef COPYNUM
3957#undef COPYSEQ
3958#undef COPYMAP
Guido van Rossum5af588b2001-10-12 14:13:21 +00003959#undef COPYBUF
Guido van Rossum13d52f02001-08-10 21:24:08 +00003960
3961#define SLOTDEFINED(SLOT) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003962 (base->SLOT != 0 && \
3963 (basebase == NULL || base->SLOT != basebase->SLOT))
Guido van Rossum13d52f02001-08-10 21:24:08 +00003964
Tim Peters6d6c1a32001-08-02 04:15:00 +00003965#define COPYSLOT(SLOT) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003966 if (!type->SLOT && SLOTDEFINED(SLOT)) type->SLOT = base->SLOT
Tim Peters6d6c1a32001-08-02 04:15:00 +00003967
3968#define COPYNUM(SLOT) COPYSLOT(tp_as_number->SLOT)
3969#define COPYSEQ(SLOT) COPYSLOT(tp_as_sequence->SLOT)
3970#define COPYMAP(SLOT) COPYSLOT(tp_as_mapping->SLOT)
Tim Petersfc57ccb2001-10-12 02:38:24 +00003971#define COPYBUF(SLOT) COPYSLOT(tp_as_buffer->SLOT)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003972
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003973 /* This won't inherit indirect slots (from tp_as_number etc.)
3974 if type doesn't provide the space. */
Guido van Rossum13d52f02001-08-10 21:24:08 +00003975
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003976 if (type->tp_as_number != NULL && base->tp_as_number != NULL) {
3977 basebase = base->tp_base;
3978 if (basebase->tp_as_number == NULL)
3979 basebase = NULL;
3980 COPYNUM(nb_add);
3981 COPYNUM(nb_subtract);
3982 COPYNUM(nb_multiply);
3983 COPYNUM(nb_remainder);
3984 COPYNUM(nb_divmod);
3985 COPYNUM(nb_power);
3986 COPYNUM(nb_negative);
3987 COPYNUM(nb_positive);
3988 COPYNUM(nb_absolute);
3989 COPYNUM(nb_bool);
3990 COPYNUM(nb_invert);
3991 COPYNUM(nb_lshift);
3992 COPYNUM(nb_rshift);
3993 COPYNUM(nb_and);
3994 COPYNUM(nb_xor);
3995 COPYNUM(nb_or);
3996 COPYNUM(nb_int);
3997 COPYNUM(nb_float);
3998 COPYNUM(nb_inplace_add);
3999 COPYNUM(nb_inplace_subtract);
4000 COPYNUM(nb_inplace_multiply);
4001 COPYNUM(nb_inplace_remainder);
4002 COPYNUM(nb_inplace_power);
4003 COPYNUM(nb_inplace_lshift);
4004 COPYNUM(nb_inplace_rshift);
4005 COPYNUM(nb_inplace_and);
4006 COPYNUM(nb_inplace_xor);
4007 COPYNUM(nb_inplace_or);
4008 COPYNUM(nb_true_divide);
4009 COPYNUM(nb_floor_divide);
4010 COPYNUM(nb_inplace_true_divide);
4011 COPYNUM(nb_inplace_floor_divide);
4012 COPYNUM(nb_index);
4013 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004014
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004015 if (type->tp_as_sequence != NULL && base->tp_as_sequence != NULL) {
4016 basebase = base->tp_base;
4017 if (basebase->tp_as_sequence == NULL)
4018 basebase = NULL;
4019 COPYSEQ(sq_length);
4020 COPYSEQ(sq_concat);
4021 COPYSEQ(sq_repeat);
4022 COPYSEQ(sq_item);
4023 COPYSEQ(sq_ass_item);
4024 COPYSEQ(sq_contains);
4025 COPYSEQ(sq_inplace_concat);
4026 COPYSEQ(sq_inplace_repeat);
4027 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004028
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004029 if (type->tp_as_mapping != NULL && base->tp_as_mapping != NULL) {
4030 basebase = base->tp_base;
4031 if (basebase->tp_as_mapping == NULL)
4032 basebase = NULL;
4033 COPYMAP(mp_length);
4034 COPYMAP(mp_subscript);
4035 COPYMAP(mp_ass_subscript);
4036 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004037
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004038 if (type->tp_as_buffer != NULL && base->tp_as_buffer != NULL) {
4039 basebase = base->tp_base;
4040 if (basebase->tp_as_buffer == NULL)
4041 basebase = NULL;
4042 COPYBUF(bf_getbuffer);
4043 COPYBUF(bf_releasebuffer);
4044 }
Tim Petersfc57ccb2001-10-12 02:38:24 +00004045
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004046 basebase = base->tp_base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004047
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004048 COPYSLOT(tp_dealloc);
4049 if (type->tp_getattr == NULL && type->tp_getattro == NULL) {
4050 type->tp_getattr = base->tp_getattr;
4051 type->tp_getattro = base->tp_getattro;
4052 }
4053 if (type->tp_setattr == NULL && type->tp_setattro == NULL) {
4054 type->tp_setattr = base->tp_setattr;
4055 type->tp_setattro = base->tp_setattro;
4056 }
4057 /* tp_reserved is ignored */
4058 COPYSLOT(tp_repr);
4059 /* tp_hash see tp_richcompare */
4060 COPYSLOT(tp_call);
4061 COPYSLOT(tp_str);
4062 {
4063 /* Copy comparison-related slots only when
4064 not overriding them anywhere */
4065 if (type->tp_richcompare == NULL &&
4066 type->tp_hash == NULL &&
4067 !overrides_hash(type))
4068 {
4069 type->tp_richcompare = base->tp_richcompare;
4070 type->tp_hash = base->tp_hash;
4071 }
4072 }
4073 {
4074 COPYSLOT(tp_iter);
4075 COPYSLOT(tp_iternext);
4076 }
4077 {
4078 COPYSLOT(tp_descr_get);
4079 COPYSLOT(tp_descr_set);
4080 COPYSLOT(tp_dictoffset);
4081 COPYSLOT(tp_init);
4082 COPYSLOT(tp_alloc);
4083 COPYSLOT(tp_is_gc);
4084 if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) ==
4085 (base->tp_flags & Py_TPFLAGS_HAVE_GC)) {
4086 /* They agree about gc. */
4087 COPYSLOT(tp_free);
4088 }
4089 else if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
4090 type->tp_free == NULL &&
4091 base->tp_free == PyObject_Free) {
4092 /* A bit of magic to plug in the correct default
4093 * tp_free function when a derived class adds gc,
4094 * didn't define tp_free, and the base uses the
4095 * default non-gc tp_free.
4096 */
4097 type->tp_free = PyObject_GC_Del;
4098 }
4099 /* else they didn't agree about gc, and there isn't something
4100 * obvious to be done -- the type is on its own.
4101 */
4102 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004103}
4104
Jeremy Hylton938ace62002-07-17 16:30:39 +00004105static int add_operators(PyTypeObject *);
Guido van Rossum13d52f02001-08-10 21:24:08 +00004106
Tim Peters6d6c1a32001-08-02 04:15:00 +00004107int
Guido van Rossum528b7eb2001-08-07 17:24:28 +00004108PyType_Ready(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004109{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004110 PyObject *dict, *bases;
4111 PyTypeObject *base;
4112 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004113
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004114 if (type->tp_flags & Py_TPFLAGS_READY) {
4115 assert(type->tp_dict != NULL);
4116 return 0;
4117 }
4118 assert((type->tp_flags & Py_TPFLAGS_READYING) == 0);
Guido van Rossumd614f972001-08-10 17:39:49 +00004119
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004120 type->tp_flags |= Py_TPFLAGS_READYING;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004121
Tim Peters36eb4df2003-03-23 03:33:13 +00004122#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004123 /* PyType_Ready is the closest thing we have to a choke point
4124 * for type objects, so is the best place I can think of to try
4125 * to get type objects into the doubly-linked list of all objects.
4126 * Still, not all type objects go thru PyType_Ready.
4127 */
4128 _Py_AddToAllObjects((PyObject *)type, 0);
Tim Peters36eb4df2003-03-23 03:33:13 +00004129#endif
4130
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004131 /* Initialize tp_base (defaults to BaseObject unless that's us) */
4132 base = type->tp_base;
4133 if (base == NULL && type != &PyBaseObject_Type) {
4134 base = type->tp_base = &PyBaseObject_Type;
4135 Py_INCREF(base);
4136 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004137
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004138 /* Now the only way base can still be NULL is if type is
4139 * &PyBaseObject_Type.
4140 */
Guido van Rossum692cdbc2006-03-10 02:04:28 +00004141
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004142 /* Initialize the base class */
4143 if (base != NULL && base->tp_dict == NULL) {
4144 if (PyType_Ready(base) < 0)
4145 goto error;
4146 }
Guido van Rossum323a9cf2002-08-14 17:26:30 +00004147
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004148 /* Initialize ob_type if NULL. This means extensions that want to be
4149 compilable separately on Windows can call PyType_Ready() instead of
4150 initializing the ob_type field of their type objects. */
4151 /* The test for base != NULL is really unnecessary, since base is only
4152 NULL when type is &PyBaseObject_Type, and we know its ob_type is
4153 not NULL (it's initialized to &PyType_Type). But coverity doesn't
4154 know that. */
4155 if (Py_TYPE(type) == NULL && base != NULL)
4156 Py_TYPE(type) = Py_TYPE(base);
Guido van Rossum0986d822002-04-08 01:38:42 +00004157
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004158 /* Initialize tp_bases */
4159 bases = type->tp_bases;
4160 if (bases == NULL) {
4161 if (base == NULL)
4162 bases = PyTuple_New(0);
4163 else
4164 bases = PyTuple_Pack(1, base);
4165 if (bases == NULL)
4166 goto error;
4167 type->tp_bases = bases;
4168 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004169
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004170 /* Initialize tp_dict */
4171 dict = type->tp_dict;
4172 if (dict == NULL) {
4173 dict = PyDict_New();
4174 if (dict == NULL)
4175 goto error;
4176 type->tp_dict = dict;
4177 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004178
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004179 /* Add type-specific descriptors to tp_dict */
4180 if (add_operators(type) < 0)
4181 goto error;
4182 if (type->tp_methods != NULL) {
4183 if (add_methods(type, type->tp_methods) < 0)
4184 goto error;
4185 }
4186 if (type->tp_members != NULL) {
4187 if (add_members(type, type->tp_members) < 0)
4188 goto error;
4189 }
4190 if (type->tp_getset != NULL) {
4191 if (add_getset(type, type->tp_getset) < 0)
4192 goto error;
4193 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004194
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004195 /* Calculate method resolution order */
4196 if (mro_internal(type) < 0) {
4197 goto error;
4198 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004199
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004200 /* Inherit special flags from dominant base */
4201 if (type->tp_base != NULL)
4202 inherit_special(type, type->tp_base);
Guido van Rossum13d52f02001-08-10 21:24:08 +00004203
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004204 /* Initialize tp_dict properly */
4205 bases = type->tp_mro;
4206 assert(bases != NULL);
4207 assert(PyTuple_Check(bases));
4208 n = PyTuple_GET_SIZE(bases);
4209 for (i = 1; i < n; i++) {
4210 PyObject *b = PyTuple_GET_ITEM(bases, i);
4211 if (PyType_Check(b))
4212 inherit_slots(type, (PyTypeObject *)b);
4213 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004214
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004215 /* Sanity check for tp_free. */
4216 if (PyType_IS_GC(type) && (type->tp_flags & Py_TPFLAGS_BASETYPE) &&
4217 (type->tp_free == NULL || type->tp_free == PyObject_Del)) {
4218 /* This base class needs to call tp_free, but doesn't have
4219 * one, or its tp_free is for non-gc'ed objects.
4220 */
4221 PyErr_Format(PyExc_TypeError, "type '%.100s' participates in "
4222 "gc and is a base type but has inappropriate "
4223 "tp_free slot",
4224 type->tp_name);
4225 goto error;
4226 }
Tim Peters3cfe7542003-05-21 21:29:48 +00004227
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004228 /* if the type dictionary doesn't contain a __doc__, set it from
4229 the tp_doc slot.
4230 */
Victor Stinner3c1e4812012-03-26 22:10:51 +02004231 if (_PyDict_GetItemId(type->tp_dict, &PyId___doc__) == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004232 if (type->tp_doc != NULL) {
4233 PyObject *doc = PyUnicode_FromString(type->tp_doc);
4234 if (doc == NULL)
4235 goto error;
Victor Stinner3c1e4812012-03-26 22:10:51 +02004236 _PyDict_SetItemId(type->tp_dict, &PyId___doc__, doc);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004237 Py_DECREF(doc);
4238 } else {
Victor Stinner3c1e4812012-03-26 22:10:51 +02004239 _PyDict_SetItemId(type->tp_dict,
4240 &PyId___doc__, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004241 }
4242 }
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00004243
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004244 /* Hack for tp_hash and __hash__.
4245 If after all that, tp_hash is still NULL, and __hash__ is not in
4246 tp_dict, set tp_hash to PyObject_HashNotImplemented and
4247 tp_dict['__hash__'] equal to None.
4248 This signals that __hash__ is not inherited.
4249 */
4250 if (type->tp_hash == NULL) {
Victor Stinner3c1e4812012-03-26 22:10:51 +02004251 if (_PyDict_GetItemId(type->tp_dict, &PyId___hash__) == NULL) {
4252 if (_PyDict_SetItemId(type->tp_dict, &PyId___hash__, Py_None) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004253 goto error;
4254 type->tp_hash = PyObject_HashNotImplemented;
4255 }
4256 }
Guido van Rossum38938152006-08-21 23:36:26 +00004257
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004258 /* Some more special stuff */
4259 base = type->tp_base;
4260 if (base != NULL) {
4261 if (type->tp_as_number == NULL)
4262 type->tp_as_number = base->tp_as_number;
4263 if (type->tp_as_sequence == NULL)
4264 type->tp_as_sequence = base->tp_as_sequence;
4265 if (type->tp_as_mapping == NULL)
4266 type->tp_as_mapping = base->tp_as_mapping;
4267 if (type->tp_as_buffer == NULL)
4268 type->tp_as_buffer = base->tp_as_buffer;
4269 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004270
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004271 /* Link into each base class's list of subclasses */
4272 bases = type->tp_bases;
4273 n = PyTuple_GET_SIZE(bases);
4274 for (i = 0; i < n; i++) {
4275 PyObject *b = PyTuple_GET_ITEM(bases, i);
4276 if (PyType_Check(b) &&
4277 add_subclass((PyTypeObject *)b, type) < 0)
4278 goto error;
4279 }
Guido van Rossum1c450732001-10-08 15:18:27 +00004280
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004281 /* Warn for a type that implements tp_compare (now known as
4282 tp_reserved) but not tp_richcompare. */
4283 if (type->tp_reserved && !type->tp_richcompare) {
Andrew Svetlov2cd8ce42012-12-23 14:27:17 +02004284 PyErr_Format(PyExc_TypeError,
Victor Stinner4a2b7a12010-08-13 14:03:48 +00004285 "Type %.100s defines tp_reserved (formerly tp_compare) "
4286 "but not tp_richcompare. Comparisons may not behave as intended.",
4287 type->tp_name);
Andrew Svetlov2cd8ce42012-12-23 14:27:17 +02004288 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004289 }
Mark Dickinson2a7d45b2009-02-08 11:02:10 +00004290
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004291 /* All done -- set the ready flag */
4292 assert(type->tp_dict != NULL);
4293 type->tp_flags =
4294 (type->tp_flags & ~Py_TPFLAGS_READYING) | Py_TPFLAGS_READY;
4295 return 0;
Guido van Rossumd614f972001-08-10 17:39:49 +00004296
4297 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004298 type->tp_flags &= ~Py_TPFLAGS_READYING;
4299 return -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004300}
4301
Guido van Rossum1c450732001-10-08 15:18:27 +00004302static int
4303add_subclass(PyTypeObject *base, PyTypeObject *type)
4304{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004305 Py_ssize_t i;
4306 int result;
4307 PyObject *list, *ref, *newobj;
Guido van Rossum1c450732001-10-08 15:18:27 +00004308
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004309 list = base->tp_subclasses;
4310 if (list == NULL) {
4311 base->tp_subclasses = list = PyList_New(0);
4312 if (list == NULL)
4313 return -1;
4314 }
4315 assert(PyList_Check(list));
4316 newobj = PyWeakref_NewRef((PyObject *)type, NULL);
4317 i = PyList_GET_SIZE(list);
4318 while (--i >= 0) {
4319 ref = PyList_GET_ITEM(list, i);
4320 assert(PyWeakref_CheckRef(ref));
4321 if (PyWeakref_GET_OBJECT(ref) == Py_None)
4322 return PyList_SetItem(list, i, newobj);
4323 }
4324 result = PyList_Append(list, newobj);
4325 Py_DECREF(newobj);
4326 return result;
Guido van Rossum1c450732001-10-08 15:18:27 +00004327}
4328
Michael W. Hudson98bbc492002-11-26 14:47:27 +00004329static void
4330remove_subclass(PyTypeObject *base, PyTypeObject *type)
4331{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004332 Py_ssize_t i;
4333 PyObject *list, *ref;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00004334
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004335 list = base->tp_subclasses;
4336 if (list == NULL) {
4337 return;
4338 }
4339 assert(PyList_Check(list));
4340 i = PyList_GET_SIZE(list);
4341 while (--i >= 0) {
4342 ref = PyList_GET_ITEM(list, i);
4343 assert(PyWeakref_CheckRef(ref));
4344 if (PyWeakref_GET_OBJECT(ref) == (PyObject*)type) {
4345 /* this can't fail, right? */
4346 PySequence_DelItem(list, i);
4347 return;
4348 }
4349 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +00004350}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004351
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004352static int
4353check_num_args(PyObject *ob, int n)
4354{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004355 if (!PyTuple_CheckExact(ob)) {
4356 PyErr_SetString(PyExc_SystemError,
4357 "PyArg_UnpackTuple() argument list is not a tuple");
4358 return 0;
4359 }
4360 if (n == PyTuple_GET_SIZE(ob))
4361 return 1;
4362 PyErr_Format(
4363 PyExc_TypeError,
4364 "expected %d arguments, got %zd", n, PyTuple_GET_SIZE(ob));
4365 return 0;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004366}
4367
Tim Peters6d6c1a32001-08-02 04:15:00 +00004368/* Generic wrappers for overloadable 'operators' such as __getitem__ */
4369
4370/* There's a wrapper *function* for each distinct function typedef used
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004371 for type object slots (e.g. binaryfunc, ternaryfunc, etc.). There's a
Tim Peters6d6c1a32001-08-02 04:15:00 +00004372 wrapper *table* for each distinct operation (e.g. __len__, __add__).
4373 Most tables have only one entry; the tables for binary operators have two
4374 entries, one regular and one with reversed arguments. */
4375
4376static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00004377wrap_lenfunc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004378{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004379 lenfunc func = (lenfunc)wrapped;
4380 Py_ssize_t res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004381
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004382 if (!check_num_args(args, 0))
4383 return NULL;
4384 res = (*func)(self);
4385 if (res == -1 && PyErr_Occurred())
4386 return NULL;
4387 return PyLong_FromLong((long)res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004388}
4389
Tim Peters6d6c1a32001-08-02 04:15:00 +00004390static PyObject *
Raymond Hettingerf34f2642003-10-11 17:29:04 +00004391wrap_inquirypred(PyObject *self, PyObject *args, void *wrapped)
4392{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004393 inquiry func = (inquiry)wrapped;
4394 int res;
Raymond Hettingerf34f2642003-10-11 17:29:04 +00004395
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004396 if (!check_num_args(args, 0))
4397 return NULL;
4398 res = (*func)(self);
4399 if (res == -1 && PyErr_Occurred())
4400 return NULL;
4401 return PyBool_FromLong((long)res);
Raymond Hettingerf34f2642003-10-11 17:29:04 +00004402}
4403
4404static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00004405wrap_binaryfunc(PyObject *self, PyObject *args, void *wrapped)
4406{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004407 binaryfunc func = (binaryfunc)wrapped;
4408 PyObject *other;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004409
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004410 if (!check_num_args(args, 1))
4411 return NULL;
4412 other = PyTuple_GET_ITEM(args, 0);
4413 return (*func)(self, other);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004414}
4415
4416static PyObject *
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00004417wrap_binaryfunc_l(PyObject *self, PyObject *args, void *wrapped)
4418{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004419 binaryfunc func = (binaryfunc)wrapped;
4420 PyObject *other;
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00004421
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004422 if (!check_num_args(args, 1))
4423 return NULL;
4424 other = PyTuple_GET_ITEM(args, 0);
4425 return (*func)(self, other);
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00004426}
4427
4428static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00004429wrap_binaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
4430{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004431 binaryfunc func = (binaryfunc)wrapped;
4432 PyObject *other;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004433
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004434 if (!check_num_args(args, 1))
4435 return NULL;
4436 other = PyTuple_GET_ITEM(args, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004437 return (*func)(other, self);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004438}
4439
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004440static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00004441wrap_ternaryfunc(PyObject *self, PyObject *args, void *wrapped)
4442{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004443 ternaryfunc func = (ternaryfunc)wrapped;
4444 PyObject *other;
4445 PyObject *third = Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004446
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004447 /* Note: This wrapper only works for __pow__() */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004448
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004449 if (!PyArg_UnpackTuple(args, "", 1, 2, &other, &third))
4450 return NULL;
4451 return (*func)(self, other, third);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004452}
4453
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00004454static PyObject *
4455wrap_ternaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
4456{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004457 ternaryfunc func = (ternaryfunc)wrapped;
4458 PyObject *other;
4459 PyObject *third = Py_None;
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00004460
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004461 /* Note: This wrapper only works for __pow__() */
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00004462
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004463 if (!PyArg_UnpackTuple(args, "", 1, 2, &other, &third))
4464 return NULL;
4465 return (*func)(other, self, third);
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00004466}
4467
Tim Peters6d6c1a32001-08-02 04:15:00 +00004468static PyObject *
4469wrap_unaryfunc(PyObject *self, PyObject *args, void *wrapped)
4470{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004471 unaryfunc func = (unaryfunc)wrapped;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004472
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004473 if (!check_num_args(args, 0))
4474 return NULL;
4475 return (*func)(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004476}
4477
Tim Peters6d6c1a32001-08-02 04:15:00 +00004478static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004479wrap_indexargfunc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004480{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004481 ssizeargfunc func = (ssizeargfunc)wrapped;
4482 PyObject* o;
4483 Py_ssize_t i;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004484
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004485 if (!PyArg_UnpackTuple(args, "", 1, 1, &o))
4486 return NULL;
4487 i = PyNumber_AsSsize_t(o, PyExc_OverflowError);
4488 if (i == -1 && PyErr_Occurred())
4489 return NULL;
4490 return (*func)(self, i);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004491}
4492
Martin v. Löwis18e16552006-02-15 17:27:45 +00004493static Py_ssize_t
Guido van Rossum5d815f32001-08-17 21:57:47 +00004494getindex(PyObject *self, PyObject *arg)
4495{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004496 Py_ssize_t i;
Guido van Rossum5d815f32001-08-17 21:57:47 +00004497
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004498 i = PyNumber_AsSsize_t(arg, PyExc_OverflowError);
4499 if (i == -1 && PyErr_Occurred())
4500 return -1;
4501 if (i < 0) {
4502 PySequenceMethods *sq = Py_TYPE(self)->tp_as_sequence;
4503 if (sq && sq->sq_length) {
4504 Py_ssize_t n = (*sq->sq_length)(self);
4505 if (n < 0)
4506 return -1;
4507 i += n;
4508 }
4509 }
4510 return i;
Guido van Rossum5d815f32001-08-17 21:57:47 +00004511}
4512
4513static PyObject *
4514wrap_sq_item(PyObject *self, PyObject *args, void *wrapped)
4515{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004516 ssizeargfunc func = (ssizeargfunc)wrapped;
4517 PyObject *arg;
4518 Py_ssize_t i;
Guido van Rossum5d815f32001-08-17 21:57:47 +00004519
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004520 if (PyTuple_GET_SIZE(args) == 1) {
4521 arg = PyTuple_GET_ITEM(args, 0);
4522 i = getindex(self, arg);
4523 if (i == -1 && PyErr_Occurred())
4524 return NULL;
4525 return (*func)(self, i);
4526 }
4527 check_num_args(args, 1);
4528 assert(PyErr_Occurred());
4529 return NULL;
Guido van Rossum5d815f32001-08-17 21:57:47 +00004530}
4531
Tim Peters6d6c1a32001-08-02 04:15:00 +00004532static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00004533wrap_sq_setitem(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004534{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004535 ssizeobjargproc func = (ssizeobjargproc)wrapped;
4536 Py_ssize_t i;
4537 int res;
4538 PyObject *arg, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004539
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004540 if (!PyArg_UnpackTuple(args, "", 2, 2, &arg, &value))
4541 return NULL;
4542 i = getindex(self, arg);
4543 if (i == -1 && PyErr_Occurred())
4544 return NULL;
4545 res = (*func)(self, i, value);
4546 if (res == -1 && PyErr_Occurred())
4547 return NULL;
4548 Py_INCREF(Py_None);
4549 return Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004550}
4551
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004552static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00004553wrap_sq_delitem(PyObject *self, PyObject *args, void *wrapped)
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004554{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004555 ssizeobjargproc func = (ssizeobjargproc)wrapped;
4556 Py_ssize_t i;
4557 int res;
4558 PyObject *arg;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004559
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004560 if (!check_num_args(args, 1))
4561 return NULL;
4562 arg = PyTuple_GET_ITEM(args, 0);
4563 i = getindex(self, arg);
4564 if (i == -1 && PyErr_Occurred())
4565 return NULL;
4566 res = (*func)(self, i, NULL);
4567 if (res == -1 && PyErr_Occurred())
4568 return NULL;
4569 Py_INCREF(Py_None);
4570 return Py_None;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004571}
4572
Tim Peters6d6c1a32001-08-02 04:15:00 +00004573/* XXX objobjproc is a misnomer; should be objargpred */
4574static PyObject *
4575wrap_objobjproc(PyObject *self, PyObject *args, void *wrapped)
4576{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004577 objobjproc func = (objobjproc)wrapped;
4578 int res;
4579 PyObject *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004580
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004581 if (!check_num_args(args, 1))
4582 return NULL;
4583 value = PyTuple_GET_ITEM(args, 0);
4584 res = (*func)(self, value);
4585 if (res == -1 && PyErr_Occurred())
4586 return NULL;
4587 else
4588 return PyBool_FromLong(res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004589}
4590
Tim Peters6d6c1a32001-08-02 04:15:00 +00004591static PyObject *
4592wrap_objobjargproc(PyObject *self, PyObject *args, void *wrapped)
4593{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004594 objobjargproc func = (objobjargproc)wrapped;
4595 int res;
4596 PyObject *key, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004597
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004598 if (!PyArg_UnpackTuple(args, "", 2, 2, &key, &value))
4599 return NULL;
4600 res = (*func)(self, key, value);
4601 if (res == -1 && PyErr_Occurred())
4602 return NULL;
4603 Py_INCREF(Py_None);
4604 return Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004605}
4606
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004607static PyObject *
4608wrap_delitem(PyObject *self, PyObject *args, void *wrapped)
4609{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004610 objobjargproc func = (objobjargproc)wrapped;
4611 int res;
4612 PyObject *key;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004613
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004614 if (!check_num_args(args, 1))
4615 return NULL;
4616 key = PyTuple_GET_ITEM(args, 0);
4617 res = (*func)(self, key, NULL);
4618 if (res == -1 && PyErr_Occurred())
4619 return NULL;
4620 Py_INCREF(Py_None);
4621 return Py_None;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004622}
4623
Guido van Rossum4dcdb782003-04-14 21:46:03 +00004624/* Helper to check for object.__setattr__ or __delattr__ applied to a type.
Guido van Rossum52b27052003-04-15 20:05:10 +00004625 This is called the Carlo Verre hack after its discoverer. */
Guido van Rossum4dcdb782003-04-14 21:46:03 +00004626static int
4627hackcheck(PyObject *self, setattrofunc func, char *what)
4628{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004629 PyTypeObject *type = Py_TYPE(self);
4630 while (type && type->tp_flags & Py_TPFLAGS_HEAPTYPE)
4631 type = type->tp_base;
4632 /* If type is NULL now, this is a really weird type.
4633 In the spirit of backwards compatibility (?), just shut up. */
4634 if (type && type->tp_setattro != func) {
4635 PyErr_Format(PyExc_TypeError,
4636 "can't apply this %s to %s object",
4637 what,
4638 type->tp_name);
4639 return 0;
4640 }
4641 return 1;
Guido van Rossum4dcdb782003-04-14 21:46:03 +00004642}
4643
Tim Peters6d6c1a32001-08-02 04:15:00 +00004644static PyObject *
4645wrap_setattr(PyObject *self, PyObject *args, void *wrapped)
4646{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004647 setattrofunc func = (setattrofunc)wrapped;
4648 int res;
4649 PyObject *name, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004650
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004651 if (!PyArg_UnpackTuple(args, "", 2, 2, &name, &value))
4652 return NULL;
4653 if (!hackcheck(self, func, "__setattr__"))
4654 return NULL;
4655 res = (*func)(self, name, value);
4656 if (res < 0)
4657 return NULL;
4658 Py_INCREF(Py_None);
4659 return Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004660}
4661
4662static PyObject *
4663wrap_delattr(PyObject *self, PyObject *args, void *wrapped)
4664{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004665 setattrofunc func = (setattrofunc)wrapped;
4666 int res;
4667 PyObject *name;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004668
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004669 if (!check_num_args(args, 1))
4670 return NULL;
4671 name = PyTuple_GET_ITEM(args, 0);
4672 if (!hackcheck(self, func, "__delattr__"))
4673 return NULL;
4674 res = (*func)(self, name, NULL);
4675 if (res < 0)
4676 return NULL;
4677 Py_INCREF(Py_None);
4678 return Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004679}
4680
Tim Peters6d6c1a32001-08-02 04:15:00 +00004681static PyObject *
4682wrap_hashfunc(PyObject *self, PyObject *args, void *wrapped)
4683{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004684 hashfunc func = (hashfunc)wrapped;
Benjamin Peterson8035bc52010-10-23 16:20:50 +00004685 Py_hash_t res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004686
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004687 if (!check_num_args(args, 0))
4688 return NULL;
4689 res = (*func)(self);
4690 if (res == -1 && PyErr_Occurred())
4691 return NULL;
Benjamin Peterson8035bc52010-10-23 16:20:50 +00004692 return PyLong_FromSsize_t(res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004693}
4694
Tim Peters6d6c1a32001-08-02 04:15:00 +00004695static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00004696wrap_call(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004697{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004698 ternaryfunc func = (ternaryfunc)wrapped;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004699
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004700 return (*func)(self, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004701}
4702
Tim Peters6d6c1a32001-08-02 04:15:00 +00004703static PyObject *
4704wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op)
4705{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004706 richcmpfunc func = (richcmpfunc)wrapped;
4707 PyObject *other;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004708
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004709 if (!check_num_args(args, 1))
4710 return NULL;
4711 other = PyTuple_GET_ITEM(args, 0);
4712 return (*func)(self, other, op);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004713}
4714
4715#undef RICHCMP_WRAPPER
4716#define RICHCMP_WRAPPER(NAME, OP) \
4717static PyObject * \
4718richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \
4719{ \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004720 return wrap_richcmpfunc(self, args, wrapped, OP); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004721}
4722
Jack Jansen8e938b42001-08-08 15:29:49 +00004723RICHCMP_WRAPPER(lt, Py_LT)
4724RICHCMP_WRAPPER(le, Py_LE)
4725RICHCMP_WRAPPER(eq, Py_EQ)
4726RICHCMP_WRAPPER(ne, Py_NE)
4727RICHCMP_WRAPPER(gt, Py_GT)
4728RICHCMP_WRAPPER(ge, Py_GE)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004729
Tim Peters6d6c1a32001-08-02 04:15:00 +00004730static PyObject *
4731wrap_next(PyObject *self, PyObject *args, void *wrapped)
4732{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004733 unaryfunc func = (unaryfunc)wrapped;
4734 PyObject *res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004735
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004736 if (!check_num_args(args, 0))
4737 return NULL;
4738 res = (*func)(self);
4739 if (res == NULL && !PyErr_Occurred())
4740 PyErr_SetNone(PyExc_StopIteration);
4741 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004742}
4743
Tim Peters6d6c1a32001-08-02 04:15:00 +00004744static PyObject *
4745wrap_descr_get(PyObject *self, PyObject *args, void *wrapped)
4746{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004747 descrgetfunc func = (descrgetfunc)wrapped;
4748 PyObject *obj;
4749 PyObject *type = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004750
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004751 if (!PyArg_UnpackTuple(args, "", 1, 2, &obj, &type))
4752 return NULL;
4753 if (obj == Py_None)
4754 obj = NULL;
4755 if (type == Py_None)
4756 type = NULL;
4757 if (type == NULL &&obj == NULL) {
4758 PyErr_SetString(PyExc_TypeError,
4759 "__get__(None, None) is invalid");
4760 return NULL;
4761 }
4762 return (*func)(self, obj, type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004763}
4764
Tim Peters6d6c1a32001-08-02 04:15:00 +00004765static PyObject *
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004766wrap_descr_set(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004767{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004768 descrsetfunc func = (descrsetfunc)wrapped;
4769 PyObject *obj, *value;
4770 int ret;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004771
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004772 if (!PyArg_UnpackTuple(args, "", 2, 2, &obj, &value))
4773 return NULL;
4774 ret = (*func)(self, obj, value);
4775 if (ret < 0)
4776 return NULL;
4777 Py_INCREF(Py_None);
4778 return Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004779}
Guido van Rossum22b13872002-08-06 21:41:44 +00004780
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00004781static PyObject *
4782wrap_descr_delete(PyObject *self, PyObject *args, void *wrapped)
4783{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004784 descrsetfunc func = (descrsetfunc)wrapped;
4785 PyObject *obj;
4786 int ret;
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00004787
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004788 if (!check_num_args(args, 1))
4789 return NULL;
4790 obj = PyTuple_GET_ITEM(args, 0);
4791 ret = (*func)(self, obj, NULL);
4792 if (ret < 0)
4793 return NULL;
4794 Py_INCREF(Py_None);
4795 return Py_None;
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00004796}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004797
Tim Peters6d6c1a32001-08-02 04:15:00 +00004798static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00004799wrap_init(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004800{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004801 initproc func = (initproc)wrapped;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004802
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004803 if (func(self, args, kwds) < 0)
4804 return NULL;
4805 Py_INCREF(Py_None);
4806 return Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004807}
4808
Tim Peters6d6c1a32001-08-02 04:15:00 +00004809static PyObject *
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004810tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004811{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004812 PyTypeObject *type, *subtype, *staticbase;
4813 PyObject *arg0, *res;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004814
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004815 if (self == NULL || !PyType_Check(self))
4816 Py_FatalError("__new__() called with non-type 'self'");
4817 type = (PyTypeObject *)self;
4818 if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) {
4819 PyErr_Format(PyExc_TypeError,
4820 "%s.__new__(): not enough arguments",
4821 type->tp_name);
4822 return NULL;
4823 }
4824 arg0 = PyTuple_GET_ITEM(args, 0);
4825 if (!PyType_Check(arg0)) {
4826 PyErr_Format(PyExc_TypeError,
4827 "%s.__new__(X): X is not a type object (%s)",
4828 type->tp_name,
4829 Py_TYPE(arg0)->tp_name);
4830 return NULL;
4831 }
4832 subtype = (PyTypeObject *)arg0;
4833 if (!PyType_IsSubtype(subtype, type)) {
4834 PyErr_Format(PyExc_TypeError,
4835 "%s.__new__(%s): %s is not a subtype of %s",
4836 type->tp_name,
4837 subtype->tp_name,
4838 subtype->tp_name,
4839 type->tp_name);
4840 return NULL;
4841 }
Barry Warsaw60f01882001-08-22 19:24:42 +00004842
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004843 /* Check that the use doesn't do something silly and unsafe like
4844 object.__new__(dict). To do this, we check that the
4845 most derived base that's not a heap type is this type. */
4846 staticbase = subtype;
Martin v. Löwis9c564092012-06-23 23:20:45 +02004847 while (staticbase && (staticbase->tp_new == slot_tp_new))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004848 staticbase = staticbase->tp_base;
4849 /* If staticbase is NULL now, it is a really weird type.
4850 In the spirit of backwards compatibility (?), just shut up. */
4851 if (staticbase && staticbase->tp_new != type->tp_new) {
4852 PyErr_Format(PyExc_TypeError,
4853 "%s.__new__(%s) is not safe, use %s.__new__()",
4854 type->tp_name,
4855 subtype->tp_name,
4856 staticbase == NULL ? "?" : staticbase->tp_name);
4857 return NULL;
4858 }
Barry Warsaw60f01882001-08-22 19:24:42 +00004859
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004860 args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
4861 if (args == NULL)
4862 return NULL;
4863 res = type->tp_new(subtype, args, kwds);
4864 Py_DECREF(args);
4865 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004866}
4867
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004868static struct PyMethodDef tp_new_methoddef[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004869 {"__new__", (PyCFunction)tp_new_wrapper, METH_VARARGS|METH_KEYWORDS,
4870 PyDoc_STR("T.__new__(S, ...) -> "
4871 "a new object with type S, a subtype of T")},
4872 {0}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004873};
4874
4875static int
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004876add_tp_new_wrapper(PyTypeObject *type)
4877{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004878 PyObject *func;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004879
Victor Stinner3c1e4812012-03-26 22:10:51 +02004880 if (_PyDict_GetItemId(type->tp_dict, &PyId___new__) != NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004881 return 0;
Andrew Svetlov3ba3a3e2012-12-25 13:32:35 +02004882 func = PyCFunction_NewEx(tp_new_methoddef, (PyObject *)type, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004883 if (func == NULL)
4884 return -1;
Victor Stinner3c1e4812012-03-26 22:10:51 +02004885 if (_PyDict_SetItemId(type->tp_dict, &PyId___new__, func)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004886 Py_DECREF(func);
4887 return -1;
4888 }
4889 Py_DECREF(func);
4890 return 0;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004891}
4892
Guido van Rossumf040ede2001-08-07 16:40:56 +00004893/* Slot wrappers that call the corresponding __foo__ slot. See comments
4894 below at override_slots() for more explanation. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004895
Guido van Rossumdc91b992001-08-08 22:26:22 +00004896#define SLOT0(FUNCNAME, OPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004897static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004898FUNCNAME(PyObject *self) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004899{ \
Benjamin Petersonce798522012-01-22 11:24:29 -05004900 _Py_static_string(id, OPSTR); \
4901 return call_method(self, &id, "()"); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004902}
4903
Guido van Rossumdc91b992001-08-08 22:26:22 +00004904#define SLOT1(FUNCNAME, OPSTR, ARG1TYPE, ARGCODES) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004905static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004906FUNCNAME(PyObject *self, ARG1TYPE arg1) \
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, "(" ARGCODES ")", arg1); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004910}
4911
Guido van Rossumcd118802003-01-06 22:57:47 +00004912/* Boolean helper for SLOT1BINFULL().
4913 right.__class__ is a nontrivial subclass of left.__class__. */
4914static int
Victor Stinner3c1e4812012-03-26 22:10:51 +02004915method_is_overloaded(PyObject *left, PyObject *right, struct _Py_Identifier *name)
Guido van Rossumcd118802003-01-06 22:57:47 +00004916{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004917 PyObject *a, *b;
4918 int ok;
Guido van Rossumcd118802003-01-06 22:57:47 +00004919
Victor Stinner3c1e4812012-03-26 22:10:51 +02004920 b = _PyObject_GetAttrId((PyObject *)(Py_TYPE(right)), name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004921 if (b == NULL) {
4922 PyErr_Clear();
4923 /* If right doesn't have it, it's not overloaded */
4924 return 0;
4925 }
Guido van Rossumcd118802003-01-06 22:57:47 +00004926
Victor Stinner3c1e4812012-03-26 22:10:51 +02004927 a = _PyObject_GetAttrId((PyObject *)(Py_TYPE(left)), name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004928 if (a == NULL) {
4929 PyErr_Clear();
4930 Py_DECREF(b);
4931 /* If right has it but left doesn't, it's overloaded */
4932 return 1;
4933 }
Guido van Rossumcd118802003-01-06 22:57:47 +00004934
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004935 ok = PyObject_RichCompareBool(a, b, Py_NE);
4936 Py_DECREF(a);
4937 Py_DECREF(b);
4938 if (ok < 0) {
4939 PyErr_Clear();
4940 return 0;
4941 }
Guido van Rossumcd118802003-01-06 22:57:47 +00004942
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004943 return ok;
Guido van Rossumcd118802003-01-06 22:57:47 +00004944}
4945
Guido van Rossumdc91b992001-08-08 22:26:22 +00004946
4947#define SLOT1BINFULL(FUNCNAME, TESTFUNC, SLOTNAME, OPSTR, ROPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004948static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004949FUNCNAME(PyObject *self, PyObject *other) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004950{ \
Benjamin Petersonce798522012-01-22 11:24:29 -05004951 _Py_static_string(op_id, OPSTR); \
4952 _Py_static_string(rop_id, ROPSTR); \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004953 int do_other = Py_TYPE(self) != Py_TYPE(other) && \
4954 Py_TYPE(other)->tp_as_number != NULL && \
4955 Py_TYPE(other)->tp_as_number->SLOTNAME == TESTFUNC; \
4956 if (Py_TYPE(self)->tp_as_number != NULL && \
4957 Py_TYPE(self)->tp_as_number->SLOTNAME == TESTFUNC) { \
4958 PyObject *r; \
4959 if (do_other && \
4960 PyType_IsSubtype(Py_TYPE(other), Py_TYPE(self)) && \
Victor Stinner3c1e4812012-03-26 22:10:51 +02004961 method_is_overloaded(self, other, &rop_id)) { \
Benjamin Petersonce798522012-01-22 11:24:29 -05004962 r = call_maybe(other, &rop_id, "(O)", self); \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004963 if (r != Py_NotImplemented) \
4964 return r; \
4965 Py_DECREF(r); \
4966 do_other = 0; \
4967 } \
Benjamin Petersonce798522012-01-22 11:24:29 -05004968 r = call_maybe(self, &op_id, "(O)", other); \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004969 if (r != Py_NotImplemented || \
4970 Py_TYPE(other) == Py_TYPE(self)) \
4971 return r; \
4972 Py_DECREF(r); \
4973 } \
4974 if (do_other) { \
Benjamin Petersonce798522012-01-22 11:24:29 -05004975 return call_maybe(other, &rop_id, "(O)", self); \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004976 } \
Brian Curtindfc80e32011-08-10 20:28:54 -05004977 Py_RETURN_NOTIMPLEMENTED; \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004978}
4979
4980#define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004981 SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR)
Guido van Rossumdc91b992001-08-08 22:26:22 +00004982
4983#define SLOT2(FUNCNAME, OPSTR, ARG1TYPE, ARG2TYPE, ARGCODES) \
4984static PyObject * \
4985FUNCNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \
4986{ \
Benjamin Petersonce798522012-01-22 11:24:29 -05004987 _Py_static_string(id, #OPSTR); \
4988 return call_method(self, &id, "(" ARGCODES ")", arg1, arg2); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004989}
4990
Martin v. Löwis18e16552006-02-15 17:27:45 +00004991static Py_ssize_t
Tim Peters6d6c1a32001-08-02 04:15:00 +00004992slot_sq_length(PyObject *self)
4993{
Benjamin Petersonce798522012-01-22 11:24:29 -05004994 _Py_IDENTIFIER(__len__);
4995 PyObject *res = call_method(self, &PyId___len__, "()");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004996 Py_ssize_t len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004997
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004998 if (res == NULL)
4999 return -1;
5000 len = PyNumber_AsSsize_t(res, PyExc_OverflowError);
5001 Py_DECREF(res);
5002 if (len < 0) {
5003 if (!PyErr_Occurred())
5004 PyErr_SetString(PyExc_ValueError,
5005 "__len__() should return >= 0");
5006 return -1;
5007 }
5008 return len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005009}
5010
Guido van Rossumf4593e02001-10-03 12:09:30 +00005011/* Super-optimized version of slot_sq_item.
5012 Other slots could do the same... */
5013static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00005014slot_sq_item(PyObject *self, Py_ssize_t i)
Guido van Rossumf4593e02001-10-03 12:09:30 +00005015{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005016 PyObject *func, *args = NULL, *ival = NULL, *retval = NULL;
5017 descrgetfunc f;
Guido van Rossumf4593e02001-10-03 12:09:30 +00005018
Victor Stinner3c1e4812012-03-26 22:10:51 +02005019 func = _PyType_LookupId(Py_TYPE(self), &PyId___getitem__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005020 if (func != NULL) {
5021 if ((f = Py_TYPE(func)->tp_descr_get) == NULL)
5022 Py_INCREF(func);
5023 else {
5024 func = f(func, self, (PyObject *)(Py_TYPE(self)));
5025 if (func == NULL) {
5026 return NULL;
5027 }
5028 }
5029 ival = PyLong_FromSsize_t(i);
5030 if (ival != NULL) {
5031 args = PyTuple_New(1);
5032 if (args != NULL) {
5033 PyTuple_SET_ITEM(args, 0, ival);
5034 retval = PyObject_Call(func, args, NULL);
5035 Py_XDECREF(args);
5036 Py_XDECREF(func);
5037 return retval;
5038 }
5039 }
5040 }
5041 else {
Victor Stinner3c1e4812012-03-26 22:10:51 +02005042 PyObject *getitem_str = _PyUnicode_FromId(&PyId___getitem__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005043 PyErr_SetObject(PyExc_AttributeError, getitem_str);
5044 }
5045 Py_XDECREF(args);
5046 Py_XDECREF(ival);
5047 Py_XDECREF(func);
5048 return NULL;
Guido van Rossumf4593e02001-10-03 12:09:30 +00005049}
5050
Tim Peters6d6c1a32001-08-02 04:15:00 +00005051static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00005052slot_sq_ass_item(PyObject *self, Py_ssize_t index, PyObject *value)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005053{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005054 PyObject *res;
Benjamin Petersonce798522012-01-22 11:24:29 -05005055 _Py_IDENTIFIER(__delitem__);
5056 _Py_IDENTIFIER(__setitem__);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005057
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005058 if (value == NULL)
Benjamin Petersonce798522012-01-22 11:24:29 -05005059 res = call_method(self, &PyId___delitem__, "(n)", index);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005060 else
Benjamin Petersonce798522012-01-22 11:24:29 -05005061 res = call_method(self, &PyId___setitem__, "(nO)", index, value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005062 if (res == NULL)
5063 return -1;
5064 Py_DECREF(res);
5065 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005066}
5067
5068static int
Tim Peters6d6c1a32001-08-02 04:15:00 +00005069slot_sq_contains(PyObject *self, PyObject *value)
5070{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005071 PyObject *func, *res, *args;
5072 int result = -1;
Benjamin Petersonce798522012-01-22 11:24:29 -05005073 _Py_IDENTIFIER(__contains__);
Tim Petersbf9b2442003-03-23 05:35:36 +00005074
Benjamin Petersonce798522012-01-22 11:24:29 -05005075 func = lookup_maybe(self, &PyId___contains__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005076 if (func != NULL) {
5077 args = PyTuple_Pack(1, value);
5078 if (args == NULL)
5079 res = NULL;
5080 else {
5081 res = PyObject_Call(func, args, NULL);
5082 Py_DECREF(args);
5083 }
5084 Py_DECREF(func);
5085 if (res != NULL) {
5086 result = PyObject_IsTrue(res);
5087 Py_DECREF(res);
5088 }
5089 }
5090 else if (! PyErr_Occurred()) {
5091 /* Possible results: -1 and 1 */
5092 result = (int)_PySequence_IterSearch(self, value,
5093 PY_ITERSEARCH_CONTAINS);
5094 }
5095 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005096}
5097
Tim Peters6d6c1a32001-08-02 04:15:00 +00005098#define slot_mp_length slot_sq_length
5099
Guido van Rossumdc91b992001-08-08 22:26:22 +00005100SLOT1(slot_mp_subscript, "__getitem__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00005101
5102static int
5103slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value)
5104{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005105 PyObject *res;
Benjamin Petersonce798522012-01-22 11:24:29 -05005106 _Py_IDENTIFIER(__delitem__);
5107 _Py_IDENTIFIER(__setitem__);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005108
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005109 if (value == NULL)
Benjamin Petersonce798522012-01-22 11:24:29 -05005110 res = call_method(self, &PyId___delitem__, "(O)", key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005111 else
Benjamin Petersonce798522012-01-22 11:24:29 -05005112 res = call_method(self, &PyId___setitem__, "(OO)", key, value);
5113
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005114 if (res == NULL)
5115 return -1;
5116 Py_DECREF(res);
5117 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005118}
5119
Guido van Rossumdc91b992001-08-08 22:26:22 +00005120SLOT1BIN(slot_nb_add, nb_add, "__add__", "__radd__")
5121SLOT1BIN(slot_nb_subtract, nb_subtract, "__sub__", "__rsub__")
5122SLOT1BIN(slot_nb_multiply, nb_multiply, "__mul__", "__rmul__")
Guido van Rossumdc91b992001-08-08 22:26:22 +00005123SLOT1BIN(slot_nb_remainder, nb_remainder, "__mod__", "__rmod__")
5124SLOT1BIN(slot_nb_divmod, nb_divmod, "__divmod__", "__rdivmod__")
5125
Jeremy Hylton938ace62002-07-17 16:30:39 +00005126static PyObject *slot_nb_power(PyObject *, PyObject *, PyObject *);
Guido van Rossumdc91b992001-08-08 22:26:22 +00005127
5128SLOT1BINFULL(slot_nb_power_binary, slot_nb_power,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005129 nb_power, "__pow__", "__rpow__")
Guido van Rossumdc91b992001-08-08 22:26:22 +00005130
5131static PyObject *
5132slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus)
5133{
Benjamin Petersonce798522012-01-22 11:24:29 -05005134 _Py_IDENTIFIER(__pow__);
Guido van Rossum2730b132001-08-28 18:22:14 +00005135
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005136 if (modulus == Py_None)
5137 return slot_nb_power_binary(self, other);
5138 /* Three-arg power doesn't use __rpow__. But ternary_op
5139 can call this when the second argument's type uses
5140 slot_nb_power, so check before calling self.__pow__. */
5141 if (Py_TYPE(self)->tp_as_number != NULL &&
5142 Py_TYPE(self)->tp_as_number->nb_power == slot_nb_power) {
Benjamin Petersonce798522012-01-22 11:24:29 -05005143 return call_method(self, &PyId___pow__, "(OO)", other, modulus);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005144 }
Brian Curtindfc80e32011-08-10 20:28:54 -05005145 Py_RETURN_NOTIMPLEMENTED;
Guido van Rossumdc91b992001-08-08 22:26:22 +00005146}
5147
5148SLOT0(slot_nb_negative, "__neg__")
5149SLOT0(slot_nb_positive, "__pos__")
5150SLOT0(slot_nb_absolute, "__abs__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00005151
5152static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00005153slot_nb_bool(PyObject *self)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005154{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005155 PyObject *func, *args;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005156 int result = -1;
5157 int using_len = 0;
Benjamin Petersonce798522012-01-22 11:24:29 -05005158 _Py_IDENTIFIER(__len__);
5159 _Py_IDENTIFIER(__bool__);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005160
Benjamin Petersonce798522012-01-22 11:24:29 -05005161 func = lookup_maybe(self, &PyId___bool__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005162 if (func == NULL) {
5163 if (PyErr_Occurred())
5164 return -1;
Benjamin Petersonce798522012-01-22 11:24:29 -05005165 func = lookup_maybe(self, &PyId___len__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005166 if (func == NULL)
5167 return PyErr_Occurred() ? -1 : 1;
5168 using_len = 1;
5169 }
5170 args = PyTuple_New(0);
5171 if (args != NULL) {
5172 PyObject *temp = PyObject_Call(func, args, NULL);
5173 Py_DECREF(args);
5174 if (temp != NULL) {
5175 if (using_len) {
5176 /* enforced by slot_nb_len */
5177 result = PyObject_IsTrue(temp);
5178 }
5179 else if (PyBool_Check(temp)) {
5180 result = PyObject_IsTrue(temp);
5181 }
5182 else {
5183 PyErr_Format(PyExc_TypeError,
5184 "__bool__ should return "
5185 "bool, returned %s",
5186 Py_TYPE(temp)->tp_name);
5187 result = -1;
5188 }
5189 Py_DECREF(temp);
5190 }
5191 }
5192 Py_DECREF(func);
5193 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005194}
5195
Guido van Rossum38fff8c2006-03-07 18:50:55 +00005196
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00005197static PyObject *
Guido van Rossum38fff8c2006-03-07 18:50:55 +00005198slot_nb_index(PyObject *self)
5199{
Benjamin Petersonce798522012-01-22 11:24:29 -05005200 _Py_IDENTIFIER(__index__);
5201 return call_method(self, &PyId___index__, "()");
Guido van Rossum38fff8c2006-03-07 18:50:55 +00005202}
5203
5204
Guido van Rossumdc91b992001-08-08 22:26:22 +00005205SLOT0(slot_nb_invert, "__invert__")
5206SLOT1BIN(slot_nb_lshift, nb_lshift, "__lshift__", "__rlshift__")
5207SLOT1BIN(slot_nb_rshift, nb_rshift, "__rshift__", "__rrshift__")
5208SLOT1BIN(slot_nb_and, nb_and, "__and__", "__rand__")
5209SLOT1BIN(slot_nb_xor, nb_xor, "__xor__", "__rxor__")
5210SLOT1BIN(slot_nb_or, nb_or, "__or__", "__ror__")
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00005211
Guido van Rossumdc91b992001-08-08 22:26:22 +00005212SLOT0(slot_nb_int, "__int__")
Guido van Rossumdc91b992001-08-08 22:26:22 +00005213SLOT0(slot_nb_float, "__float__")
Guido van Rossumdc91b992001-08-08 22:26:22 +00005214SLOT1(slot_nb_inplace_add, "__iadd__", PyObject *, "O")
5215SLOT1(slot_nb_inplace_subtract, "__isub__", PyObject *, "O")
5216SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *, "O")
Guido van Rossumdc91b992001-08-08 22:26:22 +00005217SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *, "O")
Thomas Wouterscf297e42007-02-23 15:07:44 +00005218/* Can't use SLOT1 here, because nb_inplace_power is ternary */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005219static PyObject *
5220slot_nb_inplace_power(PyObject *self, PyObject * arg1, PyObject *arg2)
5221{
Benjamin Petersonce798522012-01-22 11:24:29 -05005222 _Py_IDENTIFIER(__ipow__);
5223 return call_method(self, &PyId___ipow__, "(" "O" ")", arg1);
Thomas Wouterscf297e42007-02-23 15:07:44 +00005224}
Guido van Rossumdc91b992001-08-08 22:26:22 +00005225SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *, "O")
5226SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *, "O")
5227SLOT1(slot_nb_inplace_and, "__iand__", PyObject *, "O")
5228SLOT1(slot_nb_inplace_xor, "__ixor__", PyObject *, "O")
5229SLOT1(slot_nb_inplace_or, "__ior__", PyObject *, "O")
5230SLOT1BIN(slot_nb_floor_divide, nb_floor_divide,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005231 "__floordiv__", "__rfloordiv__")
Guido van Rossumdc91b992001-08-08 22:26:22 +00005232SLOT1BIN(slot_nb_true_divide, nb_true_divide, "__truediv__", "__rtruediv__")
5233SLOT1(slot_nb_inplace_floor_divide, "__ifloordiv__", PyObject *, "O")
5234SLOT1(slot_nb_inplace_true_divide, "__itruediv__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00005235
Guido van Rossumb8f63662001-08-15 23:57:02 +00005236static PyObject *
5237slot_tp_repr(PyObject *self)
5238{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005239 PyObject *func, *res;
Benjamin Petersonce798522012-01-22 11:24:29 -05005240 _Py_IDENTIFIER(__repr__);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005241
Benjamin Petersonce798522012-01-22 11:24:29 -05005242 func = lookup_method(self, &PyId___repr__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005243 if (func != NULL) {
5244 res = PyEval_CallObject(func, NULL);
5245 Py_DECREF(func);
5246 return res;
5247 }
5248 PyErr_Clear();
5249 return PyUnicode_FromFormat("<%s object at %p>",
5250 Py_TYPE(self)->tp_name, self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005251}
5252
5253static PyObject *
5254slot_tp_str(PyObject *self)
5255{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005256 PyObject *func, *res;
Benjamin Petersonce798522012-01-22 11:24:29 -05005257 _Py_IDENTIFIER(__str__);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005258
Benjamin Petersonce798522012-01-22 11:24:29 -05005259 func = lookup_method(self, &PyId___str__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005260 if (func != NULL) {
5261 res = PyEval_CallObject(func, NULL);
5262 Py_DECREF(func);
5263 return res;
5264 }
5265 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005266 /* PyObject *ress; */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005267 PyErr_Clear();
5268 res = slot_tp_repr(self);
5269 if (!res)
5270 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005271 /* XXX this is non-sensical. Why should we return
5272 a bytes object from __str__. Is this code even
5273 used? - mvl */
5274 assert(0);
5275 return res;
5276 /*
Victor Stinnerf3fd7332011-03-02 01:03:11 +00005277 ress = _PyUnicode_AsDefaultEncodedString(res);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005278 Py_DECREF(res);
5279 return ress;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005280 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005281 }
Guido van Rossumb8f63662001-08-15 23:57:02 +00005282}
Tim Peters6d6c1a32001-08-02 04:15:00 +00005283
Benjamin Peterson8f67d082010-10-17 20:54:53 +00005284static Py_hash_t
Tim Peters6d6c1a32001-08-02 04:15:00 +00005285slot_tp_hash(PyObject *self)
5286{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005287 PyObject *func, *res;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00005288 Py_ssize_t h;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005289
Benjamin Petersonce798522012-01-22 11:24:29 -05005290 func = lookup_method(self, &PyId___hash__);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005291
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005292 if (func == Py_None) {
5293 Py_DECREF(func);
5294 func = NULL;
5295 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +00005296
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005297 if (func == NULL) {
5298 return PyObject_HashNotImplemented(self);
5299 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +00005300
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005301 res = PyEval_CallObject(func, NULL);
5302 Py_DECREF(func);
5303 if (res == NULL)
5304 return -1;
Mark Dickinsondc787d22010-05-23 13:33:13 +00005305
5306 if (!PyLong_Check(res)) {
5307 PyErr_SetString(PyExc_TypeError,
5308 "__hash__ method should return an integer");
5309 return -1;
5310 }
Benjamin Peterson8f67d082010-10-17 20:54:53 +00005311 /* Transform the PyLong `res` to a Py_hash_t `h`. For an existing
5312 hashable Python object x, hash(x) will always lie within the range of
5313 Py_hash_t. Therefore our transformation must preserve values that
5314 already lie within this range, to ensure that if x.__hash__() returns
5315 hash(y) then hash(x) == hash(y). */
5316 h = PyLong_AsSsize_t(res);
5317 if (h == -1 && PyErr_Occurred()) {
5318 /* res was not within the range of a Py_hash_t, so we're free to
Mark Dickinsondc787d22010-05-23 13:33:13 +00005319 use any sufficiently bit-mixing transformation;
5320 long.__hash__ will do nicely. */
Benjamin Peterson8f67d082010-10-17 20:54:53 +00005321 PyErr_Clear();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005322 h = PyLong_Type.tp_hash(res);
Benjamin Peterson8f67d082010-10-17 20:54:53 +00005323 }
Benjamin Petersone7dfeeb2010-10-17 21:27:01 +00005324 /* -1 is reserved for errors. */
5325 if (h == -1)
5326 h = -2;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005327 Py_DECREF(res);
Mark Dickinsondc787d22010-05-23 13:33:13 +00005328 return h;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005329}
5330
5331static PyObject *
5332slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds)
5333{
Benjamin Petersonce798522012-01-22 11:24:29 -05005334 _Py_IDENTIFIER(__call__);
5335 PyObject *meth = lookup_method(self, &PyId___call__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005336 PyObject *res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005337
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005338 if (meth == NULL)
5339 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005340
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005341 res = PyObject_Call(meth, args, kwds);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005342
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005343 Py_DECREF(meth);
5344 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005345}
5346
Guido van Rossum14a6f832001-10-17 13:59:09 +00005347/* There are two slot dispatch functions for tp_getattro.
5348
5349 - slot_tp_getattro() is used when __getattribute__ is overridden
5350 but no __getattr__ hook is present;
5351
5352 - slot_tp_getattr_hook() is used when a __getattr__ hook is present.
5353
Guido van Rossumc334df52002-04-04 23:44:47 +00005354 The code in update_one_slot() always installs slot_tp_getattr_hook(); this
5355 detects the absence of __getattr__ and then installs the simpler slot if
5356 necessary. */
Guido van Rossum14a6f832001-10-17 13:59:09 +00005357
Tim Peters6d6c1a32001-08-02 04:15:00 +00005358static PyObject *
5359slot_tp_getattro(PyObject *self, PyObject *name)
5360{
Benjamin Petersonce798522012-01-22 11:24:29 -05005361 return call_method(self, &PyId___getattribute__, "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005362}
5363
Guido van Rossum19c1cd52001-09-21 21:24:49 +00005364static PyObject *
Benjamin Peterson9262b842008-11-17 22:45:50 +00005365call_attribute(PyObject *self, PyObject *attr, PyObject *name)
5366{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005367 PyObject *res, *descr = NULL;
5368 descrgetfunc f = Py_TYPE(attr)->tp_descr_get;
Benjamin Peterson9262b842008-11-17 22:45:50 +00005369
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005370 if (f != NULL) {
5371 descr = f(attr, self, (PyObject *)(Py_TYPE(self)));
5372 if (descr == NULL)
5373 return NULL;
5374 else
5375 attr = descr;
5376 }
5377 res = PyObject_CallFunctionObjArgs(attr, name, NULL);
5378 Py_XDECREF(descr);
5379 return res;
Benjamin Peterson9262b842008-11-17 22:45:50 +00005380}
5381
5382static PyObject *
Guido van Rossum19c1cd52001-09-21 21:24:49 +00005383slot_tp_getattr_hook(PyObject *self, PyObject *name)
5384{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005385 PyTypeObject *tp = Py_TYPE(self);
5386 PyObject *getattr, *getattribute, *res;
Victor Stinner3c1e4812012-03-26 22:10:51 +02005387 _Py_IDENTIFIER(__getattr__);
Guido van Rossum19c1cd52001-09-21 21:24:49 +00005388
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005389 /* speed hack: we could use lookup_maybe, but that would resolve the
5390 method fully for each attribute lookup for classes with
5391 __getattr__, even when the attribute is present. So we use
5392 _PyType_Lookup and create the method only when needed, with
5393 call_attribute. */
Victor Stinner3c1e4812012-03-26 22:10:51 +02005394 getattr = _PyType_LookupId(tp, &PyId___getattr__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005395 if (getattr == NULL) {
5396 /* No __getattr__ hook: use a simpler dispatcher */
5397 tp->tp_getattro = slot_tp_getattro;
5398 return slot_tp_getattro(self, name);
5399 }
5400 Py_INCREF(getattr);
5401 /* speed hack: we could use lookup_maybe, but that would resolve the
5402 method fully for each attribute lookup for classes with
5403 __getattr__, even when self has the default __getattribute__
5404 method. So we use _PyType_Lookup and create the method only when
5405 needed, with call_attribute. */
Victor Stinner3c1e4812012-03-26 22:10:51 +02005406 getattribute = _PyType_LookupId(tp, &PyId___getattribute__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005407 if (getattribute == NULL ||
5408 (Py_TYPE(getattribute) == &PyWrapperDescr_Type &&
5409 ((PyWrapperDescrObject *)getattribute)->d_wrapped ==
5410 (void *)PyObject_GenericGetAttr))
5411 res = PyObject_GenericGetAttr(self, name);
5412 else {
5413 Py_INCREF(getattribute);
5414 res = call_attribute(self, getattribute, name);
5415 Py_DECREF(getattribute);
5416 }
5417 if (res == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) {
5418 PyErr_Clear();
5419 res = call_attribute(self, getattr, name);
5420 }
5421 Py_DECREF(getattr);
5422 return res;
Guido van Rossum19c1cd52001-09-21 21:24:49 +00005423}
5424
Tim Peters6d6c1a32001-08-02 04:15:00 +00005425static int
5426slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value)
5427{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005428 PyObject *res;
Benjamin Petersonce798522012-01-22 11:24:29 -05005429 _Py_IDENTIFIER(__delattr__);
5430 _Py_IDENTIFIER(__setattr__);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005431
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005432 if (value == NULL)
Benjamin Petersonce798522012-01-22 11:24:29 -05005433 res = call_method(self, &PyId___delattr__, "(O)", name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005434 else
Benjamin Petersonce798522012-01-22 11:24:29 -05005435 res = call_method(self, &PyId___setattr__, "(OO)", name, value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005436 if (res == NULL)
5437 return -1;
5438 Py_DECREF(res);
5439 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005440}
5441
Benjamin Petersonce798522012-01-22 11:24:29 -05005442static _Py_Identifier name_op[] = {
5443 {0, "__lt__", 0},
5444 {0, "__le__", 0},
5445 {0, "__eq__", 0},
5446 {0, "__ne__", 0},
5447 {0, "__gt__", 0},
5448 {0, "__ge__", 0}
Guido van Rossumf5243f02008-01-01 04:06:48 +00005449};
5450
Tim Peters6d6c1a32001-08-02 04:15:00 +00005451static PyObject *
Mark Dickinson6f1d0492009-11-15 13:58:49 +00005452slot_tp_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005453{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005454 PyObject *func, *args, *res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005455
Benjamin Petersonce798522012-01-22 11:24:29 -05005456 func = lookup_method(self, &name_op[op]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005457 if (func == NULL) {
5458 PyErr_Clear();
Brian Curtindfc80e32011-08-10 20:28:54 -05005459 Py_RETURN_NOTIMPLEMENTED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005460 }
5461 args = PyTuple_Pack(1, other);
5462 if (args == NULL)
5463 res = NULL;
5464 else {
5465 res = PyObject_Call(func, args, NULL);
5466 Py_DECREF(args);
5467 }
5468 Py_DECREF(func);
5469 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005470}
5471
Guido van Rossumb8f63662001-08-15 23:57:02 +00005472static PyObject *
Guido van Rossumb8f63662001-08-15 23:57:02 +00005473slot_tp_iter(PyObject *self)
5474{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005475 PyObject *func, *res;
Benjamin Petersonce798522012-01-22 11:24:29 -05005476 _Py_IDENTIFIER(__iter__);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005477
Benjamin Petersonce798522012-01-22 11:24:29 -05005478 func = lookup_method(self, &PyId___iter__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005479 if (func != NULL) {
5480 PyObject *args;
5481 args = res = PyTuple_New(0);
5482 if (args != NULL) {
5483 res = PyObject_Call(func, args, NULL);
5484 Py_DECREF(args);
5485 }
5486 Py_DECREF(func);
5487 return res;
5488 }
5489 PyErr_Clear();
Benjamin Petersonce798522012-01-22 11:24:29 -05005490 func = lookup_method(self, &PyId___getitem__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005491 if (func == NULL) {
5492 PyErr_Format(PyExc_TypeError,
5493 "'%.200s' object is not iterable",
5494 Py_TYPE(self)->tp_name);
5495 return NULL;
5496 }
5497 Py_DECREF(func);
5498 return PySeqIter_New(self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005499}
Tim Peters6d6c1a32001-08-02 04:15:00 +00005500
5501static PyObject *
5502slot_tp_iternext(PyObject *self)
5503{
Benjamin Petersonce798522012-01-22 11:24:29 -05005504 _Py_IDENTIFIER(__next__);
5505 return call_method(self, &PyId___next__, "()");
Tim Peters6d6c1a32001-08-02 04:15:00 +00005506}
5507
Guido van Rossum1a493502001-08-17 16:47:50 +00005508static PyObject *
5509slot_tp_descr_get(PyObject *self, PyObject *obj, PyObject *type)
5510{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005511 PyTypeObject *tp = Py_TYPE(self);
5512 PyObject *get;
Victor Stinner3c1e4812012-03-26 22:10:51 +02005513 _Py_IDENTIFIER(__get__);
Guido van Rossum1a493502001-08-17 16:47:50 +00005514
Victor Stinner3c1e4812012-03-26 22:10:51 +02005515 get = _PyType_LookupId(tp, &PyId___get__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005516 if (get == NULL) {
5517 /* Avoid further slowdowns */
5518 if (tp->tp_descr_get == slot_tp_descr_get)
5519 tp->tp_descr_get = NULL;
5520 Py_INCREF(self);
5521 return self;
5522 }
5523 if (obj == NULL)
5524 obj = Py_None;
5525 if (type == NULL)
5526 type = Py_None;
5527 return PyObject_CallFunctionObjArgs(get, self, obj, type, NULL);
Guido van Rossum1a493502001-08-17 16:47:50 +00005528}
Tim Peters6d6c1a32001-08-02 04:15:00 +00005529
5530static int
5531slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value)
5532{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005533 PyObject *res;
Benjamin Petersonce798522012-01-22 11:24:29 -05005534 _Py_IDENTIFIER(__delete__);
5535 _Py_IDENTIFIER(__set__);
Guido van Rossum2c252392001-08-24 10:13:31 +00005536
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005537 if (value == NULL)
Benjamin Petersonce798522012-01-22 11:24:29 -05005538 res = call_method(self, &PyId___delete__, "(O)", target);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005539 else
Benjamin Petersonce798522012-01-22 11:24:29 -05005540 res = call_method(self, &PyId___set__, "(OO)", target, value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005541 if (res == NULL)
5542 return -1;
5543 Py_DECREF(res);
5544 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005545}
5546
5547static int
5548slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds)
5549{
Benjamin Petersonce798522012-01-22 11:24:29 -05005550 _Py_IDENTIFIER(__init__);
5551 PyObject *meth = lookup_method(self, &PyId___init__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005552 PyObject *res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005553
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005554 if (meth == NULL)
5555 return -1;
5556 res = PyObject_Call(meth, args, kwds);
5557 Py_DECREF(meth);
5558 if (res == NULL)
5559 return -1;
5560 if (res != Py_None) {
5561 PyErr_Format(PyExc_TypeError,
5562 "__init__() should return None, not '%.200s'",
5563 Py_TYPE(res)->tp_name);
5564 Py_DECREF(res);
5565 return -1;
5566 }
5567 Py_DECREF(res);
5568 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005569}
5570
5571static PyObject *
5572slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
5573{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005574 PyObject *func;
5575 PyObject *newargs, *x;
5576 Py_ssize_t i, n;
Victor Stinner3c1e4812012-03-26 22:10:51 +02005577 _Py_IDENTIFIER(__new__);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005578
Victor Stinner3c1e4812012-03-26 22:10:51 +02005579 func = _PyObject_GetAttrId((PyObject *)type, &PyId___new__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005580 if (func == NULL)
5581 return NULL;
5582 assert(PyTuple_Check(args));
5583 n = PyTuple_GET_SIZE(args);
5584 newargs = PyTuple_New(n+1);
5585 if (newargs == NULL)
5586 return NULL;
5587 Py_INCREF(type);
5588 PyTuple_SET_ITEM(newargs, 0, (PyObject *)type);
5589 for (i = 0; i < n; i++) {
5590 x = PyTuple_GET_ITEM(args, i);
5591 Py_INCREF(x);
5592 PyTuple_SET_ITEM(newargs, i+1, x);
5593 }
5594 x = PyObject_Call(func, newargs, kwds);
5595 Py_DECREF(newargs);
5596 Py_DECREF(func);
5597 return x;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005598}
5599
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005600static void
5601slot_tp_del(PyObject *self)
5602{
Benjamin Petersonce798522012-01-22 11:24:29 -05005603 _Py_IDENTIFIER(__del__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005604 PyObject *del, *res;
5605 PyObject *error_type, *error_value, *error_traceback;
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005606
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005607 /* Temporarily resurrect the object. */
5608 assert(self->ob_refcnt == 0);
5609 self->ob_refcnt = 1;
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005610
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005611 /* Save the current exception, if any. */
5612 PyErr_Fetch(&error_type, &error_value, &error_traceback);
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005613
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005614 /* Execute __del__ method, if any. */
Benjamin Petersonce798522012-01-22 11:24:29 -05005615 del = lookup_maybe(self, &PyId___del__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005616 if (del != NULL) {
5617 res = PyEval_CallObject(del, NULL);
5618 if (res == NULL)
5619 PyErr_WriteUnraisable(del);
5620 else
5621 Py_DECREF(res);
5622 Py_DECREF(del);
5623 }
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005624
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005625 /* Restore the saved exception. */
5626 PyErr_Restore(error_type, error_value, error_traceback);
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005627
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005628 /* Undo the temporary resurrection; can't use DECREF here, it would
5629 * cause a recursive call.
5630 */
5631 assert(self->ob_refcnt > 0);
5632 if (--self->ob_refcnt == 0)
5633 return; /* this is the normal path out */
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005634
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005635 /* __del__ resurrected it! Make it look like the original Py_DECREF
5636 * never happened.
5637 */
5638 {
5639 Py_ssize_t refcnt = self->ob_refcnt;
5640 _Py_NewReference(self);
5641 self->ob_refcnt = refcnt;
5642 }
5643 assert(!PyType_IS_GC(Py_TYPE(self)) ||
5644 _Py_AS_GC(self)->gc.gc_refs != _PyGC_REFS_UNTRACKED);
5645 /* If Py_REF_DEBUG, _Py_NewReference bumped _Py_RefTotal, so
5646 * we need to undo that. */
5647 _Py_DEC_REFTOTAL;
5648 /* If Py_TRACE_REFS, _Py_NewReference re-added self to the object
5649 * chain, so no more to do there.
5650 * If COUNT_ALLOCS, the original decref bumped tp_frees, and
5651 * _Py_NewReference bumped tp_allocs: both of those need to be
5652 * undone.
5653 */
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005654#ifdef COUNT_ALLOCS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005655 --Py_TYPE(self)->tp_frees;
5656 --Py_TYPE(self)->tp_allocs;
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005657#endif
5658}
5659
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005660
Benjamin Peterson63952412013-04-01 17:41:41 -04005661/*
5662Table mapping __foo__ names to tp_foo offsets and slot_tp_foo wrapper functions.
5663
5664The table is ordered by offsets relative to the 'PyHeapTypeObject' structure,
5665which incorporates the additional structures used for numbers, sequences and
5666mappings. Note that multiple names may map to the same slot (e.g. __eq__,
5667__ne__ etc. all map to tp_richcompare) and one name may map to multiple slots
5668(e.g. __str__ affects tp_str as well as tp_repr). The table is terminated with
5669an all-zero entry. (This table is further initialized in init_slotdefs().)
5670*/
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005671
Guido van Rossum6d204072001-10-21 00:44:31 +00005672typedef struct wrapperbase slotdef;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005673
5674#undef TPSLOT
Guido van Rossumc8e56452001-10-22 00:43:43 +00005675#undef FLSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005676#undef ETSLOT
5677#undef SQSLOT
5678#undef MPSLOT
5679#undef NBSLOT
Guido van Rossum6d204072001-10-21 00:44:31 +00005680#undef UNSLOT
5681#undef IBSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005682#undef BINSLOT
5683#undef RBINSLOT
5684
Guido van Rossum6d204072001-10-21 00:44:31 +00005685#define TPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005686 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
5687 PyDoc_STR(DOC)}
Guido van Rossumc8e56452001-10-22 00:43:43 +00005688#define FLSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC, FLAGS) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005689 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
5690 PyDoc_STR(DOC), FLAGS}
Guido van Rossum6d204072001-10-21 00:44:31 +00005691#define ETSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005692 {NAME, offsetof(PyHeapTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
5693 PyDoc_STR(DOC)}
Guido van Rossum6d204072001-10-21 00:44:31 +00005694#define SQSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005695 ETSLOT(NAME, as_sequence.SLOT, FUNCTION, WRAPPER, DOC)
Guido van Rossum6d204072001-10-21 00:44:31 +00005696#define MPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005697 ETSLOT(NAME, as_mapping.SLOT, FUNCTION, WRAPPER, DOC)
Guido van Rossum6d204072001-10-21 00:44:31 +00005698#define NBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005699 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, DOC)
Guido van Rossum6d204072001-10-21 00:44:31 +00005700#define UNSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005701 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
5702 "x." NAME "() <==> " DOC)
Guido van Rossum6d204072001-10-21 00:44:31 +00005703#define IBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005704 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
5705 "x." NAME "(y) <==> x" DOC "y")
Guido van Rossum6d204072001-10-21 00:44:31 +00005706#define BINSLOT(NAME, SLOT, FUNCTION, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005707 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
5708 "x." NAME "(y) <==> x" DOC "y")
Guido van Rossum6d204072001-10-21 00:44:31 +00005709#define RBINSLOT(NAME, SLOT, FUNCTION, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005710 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
5711 "x." NAME "(y) <==> y" DOC "x")
Anthony Baxter56616992005-06-03 14:12:21 +00005712#define BINSLOTNOTINFIX(NAME, SLOT, FUNCTION, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005713 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
5714 "x." NAME "(y) <==> " DOC)
Anthony Baxter56616992005-06-03 14:12:21 +00005715#define RBINSLOTNOTINFIX(NAME, SLOT, FUNCTION, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005716 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
5717 "x." NAME "(y) <==> " DOC)
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005718
5719static slotdef slotdefs[] = {
Benjamin Peterson63952412013-04-01 17:41:41 -04005720 TPSLOT("__getattribute__", tp_getattr, NULL, NULL, ""),
5721 TPSLOT("__getattr__", tp_getattr, NULL, NULL, ""),
5722 TPSLOT("__setattr__", tp_setattr, NULL, NULL, ""),
5723 TPSLOT("__delattr__", tp_setattr, NULL, NULL, ""),
5724 TPSLOT("__repr__", tp_repr, slot_tp_repr, wrap_unaryfunc,
5725 "x.__repr__() <==> repr(x)"),
5726 TPSLOT("__hash__", tp_hash, slot_tp_hash, wrap_hashfunc,
5727 "x.__hash__() <==> hash(x)"),
5728 FLSLOT("__call__", tp_call, slot_tp_call, (wrapperfunc)wrap_call,
5729 "x.__call__(...) <==> x(...)", PyWrapperFlag_KEYWORDS),
5730 TPSLOT("__str__", tp_str, slot_tp_str, wrap_unaryfunc,
5731 "x.__str__() <==> str(x)"),
5732 TPSLOT("__getattribute__", tp_getattro, slot_tp_getattr_hook,
5733 wrap_binaryfunc, "x.__getattribute__('name') <==> x.name"),
5734 TPSLOT("__getattr__", tp_getattro, slot_tp_getattr_hook, NULL, ""),
5735 TPSLOT("__setattr__", tp_setattro, slot_tp_setattro, wrap_setattr,
5736 "x.__setattr__('name', value) <==> x.name = value"),
5737 TPSLOT("__delattr__", tp_setattro, slot_tp_setattro, wrap_delattr,
5738 "x.__delattr__('name') <==> del x.name"),
5739 TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare, richcmp_lt,
5740 "x.__lt__(y) <==> x<y"),
5741 TPSLOT("__le__", tp_richcompare, slot_tp_richcompare, richcmp_le,
5742 "x.__le__(y) <==> x<=y"),
5743 TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare, richcmp_eq,
5744 "x.__eq__(y) <==> x==y"),
5745 TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare, richcmp_ne,
5746 "x.__ne__(y) <==> x!=y"),
5747 TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare, richcmp_gt,
5748 "x.__gt__(y) <==> x>y"),
5749 TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare, richcmp_ge,
5750 "x.__ge__(y) <==> x>=y"),
5751 TPSLOT("__iter__", tp_iter, slot_tp_iter, wrap_unaryfunc,
5752 "x.__iter__() <==> iter(x)"),
5753 TPSLOT("__next__", tp_iternext, slot_tp_iternext, wrap_next,
5754 "x.__next__() <==> next(x)"),
5755 TPSLOT("__get__", tp_descr_get, slot_tp_descr_get, wrap_descr_get,
5756 "descr.__get__(obj[, type]) -> value"),
5757 TPSLOT("__set__", tp_descr_set, slot_tp_descr_set, wrap_descr_set,
5758 "descr.__set__(obj, value)"),
5759 TPSLOT("__delete__", tp_descr_set, slot_tp_descr_set,
5760 wrap_descr_delete, "descr.__delete__(obj)"),
5761 FLSLOT("__init__", tp_init, slot_tp_init, (wrapperfunc)wrap_init,
5762 "x.__init__(...) initializes x; "
5763 "see help(type(x)) for signature",
5764 PyWrapperFlag_KEYWORDS),
5765 TPSLOT("__new__", tp_new, slot_tp_new, NULL, ""),
5766 TPSLOT("__del__", tp_del, slot_tp_del, NULL, ""),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005767
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005768 BINSLOT("__add__", nb_add, slot_nb_add,
5769 "+"),
5770 RBINSLOT("__radd__", nb_add, slot_nb_add,
5771 "+"),
5772 BINSLOT("__sub__", nb_subtract, slot_nb_subtract,
5773 "-"),
5774 RBINSLOT("__rsub__", nb_subtract, slot_nb_subtract,
5775 "-"),
5776 BINSLOT("__mul__", nb_multiply, slot_nb_multiply,
5777 "*"),
5778 RBINSLOT("__rmul__", nb_multiply, slot_nb_multiply,
5779 "*"),
5780 BINSLOT("__mod__", nb_remainder, slot_nb_remainder,
5781 "%"),
5782 RBINSLOT("__rmod__", nb_remainder, slot_nb_remainder,
5783 "%"),
5784 BINSLOTNOTINFIX("__divmod__", nb_divmod, slot_nb_divmod,
5785 "divmod(x, y)"),
5786 RBINSLOTNOTINFIX("__rdivmod__", nb_divmod, slot_nb_divmod,
5787 "divmod(y, x)"),
5788 NBSLOT("__pow__", nb_power, slot_nb_power, wrap_ternaryfunc,
5789 "x.__pow__(y[, z]) <==> pow(x, y[, z])"),
5790 NBSLOT("__rpow__", nb_power, slot_nb_power, wrap_ternaryfunc_r,
5791 "y.__rpow__(x[, z]) <==> pow(x, y[, z])"),
5792 UNSLOT("__neg__", nb_negative, slot_nb_negative, wrap_unaryfunc, "-x"),
5793 UNSLOT("__pos__", nb_positive, slot_nb_positive, wrap_unaryfunc, "+x"),
5794 UNSLOT("__abs__", nb_absolute, slot_nb_absolute, wrap_unaryfunc,
5795 "abs(x)"),
5796 UNSLOT("__bool__", nb_bool, slot_nb_bool, wrap_inquirypred,
5797 "x != 0"),
5798 UNSLOT("__invert__", nb_invert, slot_nb_invert, wrap_unaryfunc, "~x"),
5799 BINSLOT("__lshift__", nb_lshift, slot_nb_lshift, "<<"),
5800 RBINSLOT("__rlshift__", nb_lshift, slot_nb_lshift, "<<"),
5801 BINSLOT("__rshift__", nb_rshift, slot_nb_rshift, ">>"),
5802 RBINSLOT("__rrshift__", nb_rshift, slot_nb_rshift, ">>"),
5803 BINSLOT("__and__", nb_and, slot_nb_and, "&"),
5804 RBINSLOT("__rand__", nb_and, slot_nb_and, "&"),
5805 BINSLOT("__xor__", nb_xor, slot_nb_xor, "^"),
5806 RBINSLOT("__rxor__", nb_xor, slot_nb_xor, "^"),
5807 BINSLOT("__or__", nb_or, slot_nb_or, "|"),
5808 RBINSLOT("__ror__", nb_or, slot_nb_or, "|"),
5809 UNSLOT("__int__", nb_int, slot_nb_int, wrap_unaryfunc,
5810 "int(x)"),
5811 UNSLOT("__float__", nb_float, slot_nb_float, wrap_unaryfunc,
5812 "float(x)"),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005813 IBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add,
Eli Benderskyd3baae72011-11-11 16:57:05 +02005814 wrap_binaryfunc, "+="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005815 IBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract,
Eli Benderskyd3baae72011-11-11 16:57:05 +02005816 wrap_binaryfunc, "-="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005817 IBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply,
Eli Benderskyd3baae72011-11-11 16:57:05 +02005818 wrap_binaryfunc, "*="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005819 IBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder,
Eli Benderskyd3baae72011-11-11 16:57:05 +02005820 wrap_binaryfunc, "%="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005821 IBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power,
Eli Benderskyd3baae72011-11-11 16:57:05 +02005822 wrap_binaryfunc, "**="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005823 IBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift,
Eli Benderskyd3baae72011-11-11 16:57:05 +02005824 wrap_binaryfunc, "<<="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005825 IBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift,
Eli Benderskyd3baae72011-11-11 16:57:05 +02005826 wrap_binaryfunc, ">>="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005827 IBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and,
Eli Benderskyd3baae72011-11-11 16:57:05 +02005828 wrap_binaryfunc, "&="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005829 IBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor,
Eli Benderskyd3baae72011-11-11 16:57:05 +02005830 wrap_binaryfunc, "^="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005831 IBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or,
Eli Benderskyd3baae72011-11-11 16:57:05 +02005832 wrap_binaryfunc, "|="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005833 BINSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
5834 RBINSLOT("__rfloordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
5835 BINSLOT("__truediv__", nb_true_divide, slot_nb_true_divide, "/"),
5836 RBINSLOT("__rtruediv__", nb_true_divide, slot_nb_true_divide, "/"),
5837 IBSLOT("__ifloordiv__", nb_inplace_floor_divide,
5838 slot_nb_inplace_floor_divide, wrap_binaryfunc, "//"),
5839 IBSLOT("__itruediv__", nb_inplace_true_divide,
5840 slot_nb_inplace_true_divide, wrap_binaryfunc, "/"),
Benjamin Peterson63952412013-04-01 17:41:41 -04005841 NBSLOT("__index__", nb_index, slot_nb_index, wrap_unaryfunc,
5842 "x[y:z] <==> x[y.__index__():z.__index__()]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005843
Benjamin Peterson63952412013-04-01 17:41:41 -04005844 MPSLOT("__len__", mp_length, slot_mp_length, wrap_lenfunc,
5845 "x.__len__() <==> len(x)"),
5846 MPSLOT("__getitem__", mp_subscript, slot_mp_subscript,
5847 wrap_binaryfunc,
5848 "x.__getitem__(y) <==> x[y]"),
5849 MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript,
5850 wrap_objobjargproc,
5851 "x.__setitem__(i, y) <==> x[i]=y"),
5852 MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript,
5853 wrap_delitem,
5854 "x.__delitem__(y) <==> del x[y]"),
5855
5856 SQSLOT("__len__", sq_length, slot_sq_length, wrap_lenfunc,
5857 "x.__len__() <==> len(x)"),
5858 /* Heap types defining __add__/__mul__ have sq_concat/sq_repeat == NULL.
5859 The logic in abstract.c always falls back to nb_add/nb_multiply in
5860 this case. Defining both the nb_* and the sq_* slots to call the
5861 user-defined methods has unexpected side-effects, as shown by
5862 test_descr.notimplemented() */
5863 SQSLOT("__add__", sq_concat, NULL, wrap_binaryfunc,
5864 "x.__add__(y) <==> x+y"),
5865 SQSLOT("__mul__", sq_repeat, NULL, wrap_indexargfunc,
5866 "x.__mul__(n) <==> x*n"),
5867 SQSLOT("__rmul__", sq_repeat, NULL, wrap_indexargfunc,
5868 "x.__rmul__(n) <==> n*x"),
5869 SQSLOT("__getitem__", sq_item, slot_sq_item, wrap_sq_item,
5870 "x.__getitem__(y) <==> x[y]"),
5871 SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_setitem,
5872 "x.__setitem__(i, y) <==> x[i]=y"),
5873 SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_delitem,
5874 "x.__delitem__(y) <==> del x[y]"),
5875 SQSLOT("__contains__", sq_contains, slot_sq_contains, wrap_objobjproc,
5876 "x.__contains__(y) <==> y in x"),
5877 SQSLOT("__iadd__", sq_inplace_concat, NULL,
5878 wrap_binaryfunc, "x.__iadd__(y) <==> x+=y"),
5879 SQSLOT("__imul__", sq_inplace_repeat, NULL,
5880 wrap_indexargfunc, "x.__imul__(y) <==> x*=y"),
5881
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005882 {NULL}
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005883};
5884
Guido van Rossumc334df52002-04-04 23:44:47 +00005885/* Given a type pointer and an offset gotten from a slotdef entry, return a
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005886 pointer to the actual slot. This is not quite the same as simply adding
Guido van Rossumc334df52002-04-04 23:44:47 +00005887 the offset to the type pointer, since it takes care to indirect through the
5888 proper indirection pointer (as_buffer, etc.); it returns NULL if the
5889 indirection pointer is NULL. */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005890static void **
Martin v. Löwis18e16552006-02-15 17:27:45 +00005891slotptr(PyTypeObject *type, int ioffset)
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005892{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005893 char *ptr;
5894 long offset = ioffset;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005895
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005896 /* Note: this depends on the order of the members of PyHeapTypeObject! */
5897 assert(offset >= 0);
5898 assert((size_t)offset < offsetof(PyHeapTypeObject, as_buffer));
5899 if ((size_t)offset >= offsetof(PyHeapTypeObject, as_sequence)) {
5900 ptr = (char *)type->tp_as_sequence;
5901 offset -= offsetof(PyHeapTypeObject, as_sequence);
5902 }
5903 else if ((size_t)offset >= offsetof(PyHeapTypeObject, as_mapping)) {
5904 ptr = (char *)type->tp_as_mapping;
5905 offset -= offsetof(PyHeapTypeObject, as_mapping);
5906 }
5907 else if ((size_t)offset >= offsetof(PyHeapTypeObject, as_number)) {
5908 ptr = (char *)type->tp_as_number;
5909 offset -= offsetof(PyHeapTypeObject, as_number);
5910 }
5911 else {
5912 ptr = (char *)type;
5913 }
5914 if (ptr != NULL)
5915 ptr += offset;
5916 return (void **)ptr;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005917}
Guido van Rossumf040ede2001-08-07 16:40:56 +00005918
Guido van Rossumc334df52002-04-04 23:44:47 +00005919/* Length of array of slotdef pointers used to store slots with the
5920 same __name__. There should be at most MAX_EQUIV-1 slotdef entries with
5921 the same __name__, for any __name__. Since that's a static property, it is
5922 appropriate to declare fixed-size arrays for this. */
5923#define MAX_EQUIV 10
5924
5925/* Return a slot pointer for a given name, but ONLY if the attribute has
5926 exactly one slot function. The name must be an interned string. */
5927static void **
5928resolve_slotdups(PyTypeObject *type, PyObject *name)
5929{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005930 /* XXX Maybe this could be optimized more -- but is it worth it? */
Guido van Rossumc334df52002-04-04 23:44:47 +00005931
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005932 /* pname and ptrs act as a little cache */
5933 static PyObject *pname;
5934 static slotdef *ptrs[MAX_EQUIV];
5935 slotdef *p, **pp;
5936 void **res, **ptr;
Guido van Rossumc334df52002-04-04 23:44:47 +00005937
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005938 if (pname != name) {
5939 /* Collect all slotdefs that match name into ptrs. */
5940 pname = name;
5941 pp = ptrs;
5942 for (p = slotdefs; p->name_strobj; p++) {
5943 if (p->name_strobj == name)
5944 *pp++ = p;
5945 }
5946 *pp = NULL;
5947 }
Guido van Rossumc334df52002-04-04 23:44:47 +00005948
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005949 /* Look in all matching slots of the type; if exactly one of these has
5950 a filled-in slot, return its value. Otherwise return NULL. */
5951 res = NULL;
5952 for (pp = ptrs; *pp; pp++) {
5953 ptr = slotptr(type, (*pp)->offset);
5954 if (ptr == NULL || *ptr == NULL)
5955 continue;
5956 if (res != NULL)
5957 return NULL;
5958 res = ptr;
5959 }
5960 return res;
Guido van Rossumc334df52002-04-04 23:44:47 +00005961}
5962
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005963/* Common code for update_slots_callback() and fixup_slot_dispatchers(). This
Guido van Rossumc334df52002-04-04 23:44:47 +00005964 does some incredibly complex thinking and then sticks something into the
5965 slot. (It sees if the adjacent slotdefs for the same slot have conflicting
5966 interests, and then stores a generic wrapper or a specific function into
5967 the slot.) Return a pointer to the next slotdef with a different offset,
5968 because that's convenient for fixup_slot_dispatchers(). */
5969static slotdef *
5970update_one_slot(PyTypeObject *type, slotdef *p)
5971{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005972 PyObject *descr;
5973 PyWrapperDescrObject *d;
5974 void *generic = NULL, *specific = NULL;
5975 int use_generic = 0;
5976 int offset = p->offset;
5977 void **ptr = slotptr(type, offset);
Guido van Rossumc334df52002-04-04 23:44:47 +00005978
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005979 if (ptr == NULL) {
5980 do {
5981 ++p;
5982 } while (p->offset == offset);
5983 return p;
5984 }
5985 do {
5986 descr = _PyType_Lookup(type, p->name_strobj);
5987 if (descr == NULL) {
5988 if (ptr == (void**)&type->tp_iternext) {
Trent Nelsonab02db22012-09-18 21:58:03 -04005989 specific = (void *)_PyObject_NextNotImplemented;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005990 }
5991 continue;
5992 }
Benjamin Peterson7b166872012-04-24 11:06:25 -04005993 if (Py_TYPE(descr) == &PyWrapperDescr_Type &&
5994 ((PyWrapperDescrObject *)descr)->d_base->name_strobj == p->name_strobj) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005995 void **tptr = resolve_slotdups(type, p->name_strobj);
5996 if (tptr == NULL || tptr == ptr)
5997 generic = p->function;
5998 d = (PyWrapperDescrObject *)descr;
5999 if (d->d_base->wrapper == p->wrapper &&
6000 PyType_IsSubtype(type, PyDescr_TYPE(d)))
6001 {
6002 if (specific == NULL ||
6003 specific == d->d_wrapped)
6004 specific = d->d_wrapped;
6005 else
6006 use_generic = 1;
6007 }
6008 }
6009 else if (Py_TYPE(descr) == &PyCFunction_Type &&
6010 PyCFunction_GET_FUNCTION(descr) ==
6011 (PyCFunction)tp_new_wrapper &&
6012 ptr == (void**)&type->tp_new)
6013 {
6014 /* The __new__ wrapper is not a wrapper descriptor,
6015 so must be special-cased differently.
6016 If we don't do this, creating an instance will
6017 always use slot_tp_new which will look up
6018 __new__ in the MRO which will call tp_new_wrapper
6019 which will look through the base classes looking
6020 for a static base and call its tp_new (usually
6021 PyType_GenericNew), after performing various
6022 sanity checks and constructing a new argument
6023 list. Cut all that nonsense short -- this speeds
6024 up instance creation tremendously. */
6025 specific = (void *)type->tp_new;
6026 /* XXX I'm not 100% sure that there isn't a hole
6027 in this reasoning that requires additional
6028 sanity checks. I'll buy the first person to
6029 point out a bug in this reasoning a beer. */
6030 }
6031 else if (descr == Py_None &&
6032 ptr == (void**)&type->tp_hash) {
6033 /* We specifically allow __hash__ to be set to None
6034 to prevent inheritance of the default
6035 implementation from object.__hash__ */
Trent Nelsonab02db22012-09-18 21:58:03 -04006036 specific = (void *)PyObject_HashNotImplemented;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006037 }
6038 else {
6039 use_generic = 1;
6040 generic = p->function;
6041 }
6042 } while ((++p)->offset == offset);
6043 if (specific && !use_generic)
6044 *ptr = specific;
6045 else
6046 *ptr = generic;
6047 return p;
Guido van Rossumc334df52002-04-04 23:44:47 +00006048}
6049
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006050/* In the type, update the slots whose slotdefs are gathered in the pp array.
6051 This is a callback for update_subclasses(). */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006052static int
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006053update_slots_callback(PyTypeObject *type, void *data)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006054{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006055 slotdef **pp = (slotdef **)data;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006056
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006057 for (; *pp; pp++)
6058 update_one_slot(type, *pp);
6059 return 0;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006060}
6061
Guido van Rossumc334df52002-04-04 23:44:47 +00006062/* Initialize the slotdefs table by adding interned string objects for the
6063 names and sorting the entries. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006064static void
Guido van Rossumd396b9c2001-10-13 20:02:41 +00006065init_slotdefs(void)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006066{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006067 slotdef *p;
6068 static int initialized = 0;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006069
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006070 if (initialized)
6071 return;
6072 for (p = slotdefs; p->name; p++) {
Benjamin Peterson63952412013-04-01 17:41:41 -04006073 /* Slots must be ordered by their offset in the PyHeapTypeObject. */
6074 assert(!p[1].name || p->offset <= p[1].offset);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006075 p->name_strobj = PyUnicode_InternFromString(p->name);
6076 if (!p->name_strobj)
6077 Py_FatalError("Out of memory interning slotdef names");
6078 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006079 initialized = 1;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006080}
6081
Guido van Rossumc334df52002-04-04 23:44:47 +00006082/* Update the slots after assignment to a class (type) attribute. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006083static int
6084update_slot(PyTypeObject *type, PyObject *name)
6085{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006086 slotdef *ptrs[MAX_EQUIV];
6087 slotdef *p;
6088 slotdef **pp;
6089 int offset;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006090
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006091 /* Clear the VALID_VERSION flag of 'type' and all its
6092 subclasses. This could possibly be unified with the
6093 update_subclasses() recursion below, but carefully:
6094 they each have their own conditions on which to stop
6095 recursing into subclasses. */
6096 PyType_Modified(type);
Christian Heimesa62da1d2008-01-12 19:39:10 +00006097
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006098 init_slotdefs();
6099 pp = ptrs;
6100 for (p = slotdefs; p->name; p++) {
6101 /* XXX assume name is interned! */
6102 if (p->name_strobj == name)
6103 *pp++ = p;
6104 }
6105 *pp = NULL;
6106 for (pp = ptrs; *pp; pp++) {
6107 p = *pp;
6108 offset = p->offset;
6109 while (p > slotdefs && (p-1)->offset == offset)
6110 --p;
6111 *pp = p;
6112 }
6113 if (ptrs[0] == NULL)
6114 return 0; /* Not an attribute that affects any slots */
6115 return update_subclasses(type, name,
6116 update_slots_callback, (void *)ptrs);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006117}
6118
Guido van Rossumc334df52002-04-04 23:44:47 +00006119/* Store the proper functions in the slot dispatches at class (type)
6120 definition time, based upon which operations the class overrides in its
6121 dict. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00006122static void
Guido van Rossum7b9144b2001-10-09 19:39:46 +00006123fixup_slot_dispatchers(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00006124{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006125 slotdef *p;
Tim Peters6d6c1a32001-08-02 04:15:00 +00006126
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006127 init_slotdefs();
6128 for (p = slotdefs; p->name; )
6129 p = update_one_slot(type, p);
Tim Peters6d6c1a32001-08-02 04:15:00 +00006130}
Guido van Rossum705f0f52001-08-24 16:47:00 +00006131
Michael W. Hudson98bbc492002-11-26 14:47:27 +00006132static void
6133update_all_slots(PyTypeObject* type)
6134{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006135 slotdef *p;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00006136
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006137 init_slotdefs();
6138 for (p = slotdefs; p->name; p++) {
6139 /* update_slot returns int but can't actually fail */
6140 update_slot(type, p->name_strobj);
6141 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +00006142}
6143
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006144/* recurse_down_subclasses() and update_subclasses() are mutually
6145 recursive functions to call a callback for all subclasses,
6146 but refraining from recursing into subclasses that define 'name'. */
6147
6148static int
6149update_subclasses(PyTypeObject *type, PyObject *name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006150 update_callback callback, void *data)
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006151{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006152 if (callback(type, data) < 0)
6153 return -1;
6154 return recurse_down_subclasses(type, name, callback, data);
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006155}
6156
6157static int
6158recurse_down_subclasses(PyTypeObject *type, PyObject *name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006159 update_callback callback, void *data)
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006160{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006161 PyTypeObject *subclass;
6162 PyObject *ref, *subclasses, *dict;
6163 Py_ssize_t i, n;
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006164
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006165 subclasses = type->tp_subclasses;
6166 if (subclasses == NULL)
6167 return 0;
6168 assert(PyList_Check(subclasses));
6169 n = PyList_GET_SIZE(subclasses);
6170 for (i = 0; i < n; i++) {
6171 ref = PyList_GET_ITEM(subclasses, i);
6172 assert(PyWeakref_CheckRef(ref));
6173 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
6174 assert(subclass != NULL);
6175 if ((PyObject *)subclass == Py_None)
6176 continue;
6177 assert(PyType_Check(subclass));
6178 /* Avoid recursing down into unaffected classes */
6179 dict = subclass->tp_dict;
6180 if (dict != NULL && PyDict_Check(dict) &&
6181 PyDict_GetItem(dict, name) != NULL)
6182 continue;
6183 if (update_subclasses(subclass, name, callback, data) < 0)
6184 return -1;
6185 }
6186 return 0;
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006187}
6188
Guido van Rossum6d204072001-10-21 00:44:31 +00006189/* This function is called by PyType_Ready() to populate the type's
6190 dictionary with method descriptors for function slots. For each
Guido van Rossum09638c12002-06-13 19:17:46 +00006191 function slot (like tp_repr) that's defined in the type, one or more
6192 corresponding descriptors are added in the type's tp_dict dictionary
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006193 under the appropriate name (like __repr__). Some function slots
Guido van Rossum09638c12002-06-13 19:17:46 +00006194 cause more than one descriptor to be added (for example, the nb_add
6195 slot adds both __add__ and __radd__ descriptors) and some function
6196 slots compete for the same descriptor (for example both sq_item and
6197 mp_subscript generate a __getitem__ descriptor).
6198
Ezio Melotti13925002011-03-16 11:05:33 +02006199 In the latter case, the first slotdef entry encountered wins. Since
Tim Petersbf9b2442003-03-23 05:35:36 +00006200 slotdef entries are sorted by the offset of the slot in the
Guido van Rossume5c691a2003-03-07 15:13:17 +00006201 PyHeapTypeObject, this gives us some control over disambiguating
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006202 between competing slots: the members of PyHeapTypeObject are listed
6203 from most general to least general, so the most general slot is
6204 preferred. In particular, because as_mapping comes before as_sequence,
6205 for a type that defines both mp_subscript and sq_item, mp_subscript
6206 wins.
Guido van Rossum09638c12002-06-13 19:17:46 +00006207
6208 This only adds new descriptors and doesn't overwrite entries in
6209 tp_dict that were previously defined. The descriptors contain a
6210 reference to the C function they must call, so that it's safe if they
6211 are copied into a subtype's __dict__ and the subtype has a different
6212 C function in its slot -- calling the method defined by the
6213 descriptor will call the C function that was used to create it,
6214 rather than the C function present in the slot when it is called.
6215 (This is important because a subtype may have a C function in the
6216 slot that calls the method from the dictionary, and we want to avoid
6217 infinite recursion here.) */
Guido van Rossum6d204072001-10-21 00:44:31 +00006218
6219static int
6220add_operators(PyTypeObject *type)
6221{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006222 PyObject *dict = type->tp_dict;
6223 slotdef *p;
6224 PyObject *descr;
6225 void **ptr;
Guido van Rossum6d204072001-10-21 00:44:31 +00006226
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006227 init_slotdefs();
6228 for (p = slotdefs; p->name; p++) {
6229 if (p->wrapper == NULL)
6230 continue;
6231 ptr = slotptr(type, p->offset);
6232 if (!ptr || !*ptr)
6233 continue;
6234 if (PyDict_GetItem(dict, p->name_strobj))
6235 continue;
Trent Nelsonab02db22012-09-18 21:58:03 -04006236 if (*ptr == (void *)PyObject_HashNotImplemented) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006237 /* Classes may prevent the inheritance of the tp_hash
6238 slot by storing PyObject_HashNotImplemented in it. Make it
6239 visible as a None value for the __hash__ attribute. */
6240 if (PyDict_SetItem(dict, p->name_strobj, Py_None) < 0)
6241 return -1;
6242 }
6243 else {
6244 descr = PyDescr_NewWrapper(type, p, *ptr);
6245 if (descr == NULL)
6246 return -1;
6247 if (PyDict_SetItem(dict, p->name_strobj, descr) < 0)
6248 return -1;
6249 Py_DECREF(descr);
6250 }
6251 }
6252 if (type->tp_new != NULL) {
6253 if (add_tp_new_wrapper(type) < 0)
6254 return -1;
6255 }
6256 return 0;
Guido van Rossum6d204072001-10-21 00:44:31 +00006257}
6258
Guido van Rossum705f0f52001-08-24 16:47:00 +00006259
6260/* Cooperative 'super' */
6261
6262typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006263 PyObject_HEAD
6264 PyTypeObject *type;
6265 PyObject *obj;
6266 PyTypeObject *obj_type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006267} superobject;
6268
Guido van Rossum6f799372001-09-20 20:46:19 +00006269static PyMemberDef super_members[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006270 {"__thisclass__", T_OBJECT, offsetof(superobject, type), READONLY,
6271 "the class invoking super()"},
6272 {"__self__", T_OBJECT, offsetof(superobject, obj), READONLY,
6273 "the instance invoking super(); may be None"},
6274 {"__self_class__", T_OBJECT, offsetof(superobject, obj_type), READONLY,
6275 "the type of the instance invoking super(); may be None"},
6276 {0}
Guido van Rossum41eb14d2001-08-30 23:13:11 +00006277};
6278
Guido van Rossum705f0f52001-08-24 16:47:00 +00006279static void
6280super_dealloc(PyObject *self)
6281{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006282 superobject *su = (superobject *)self;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006283
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006284 _PyObject_GC_UNTRACK(self);
6285 Py_XDECREF(su->obj);
6286 Py_XDECREF(su->type);
6287 Py_XDECREF(su->obj_type);
6288 Py_TYPE(self)->tp_free(self);
Guido van Rossum705f0f52001-08-24 16:47:00 +00006289}
6290
6291static PyObject *
Guido van Rossum41eb14d2001-08-30 23:13:11 +00006292super_repr(PyObject *self)
6293{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006294 superobject *su = (superobject *)self;
Guido van Rossum41eb14d2001-08-30 23:13:11 +00006295
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006296 if (su->obj_type)
6297 return PyUnicode_FromFormat(
6298 "<super: <class '%s'>, <%s object>>",
6299 su->type ? su->type->tp_name : "NULL",
6300 su->obj_type->tp_name);
6301 else
6302 return PyUnicode_FromFormat(
6303 "<super: <class '%s'>, NULL>",
6304 su->type ? su->type->tp_name : "NULL");
Guido van Rossum41eb14d2001-08-30 23:13:11 +00006305}
6306
6307static PyObject *
Guido van Rossum705f0f52001-08-24 16:47:00 +00006308super_getattro(PyObject *self, PyObject *name)
6309{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006310 superobject *su = (superobject *)self;
6311 int skip = su->obj_type == NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006312
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006313 if (!skip) {
6314 /* We want __class__ to return the class of the super object
6315 (i.e. super, or a subclass), not the class of su->obj. */
6316 skip = (PyUnicode_Check(name) &&
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006317 PyUnicode_GET_LENGTH(name) == 9 &&
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006318 PyUnicode_CompareWithASCIIString(name, "__class__") == 0);
6319 }
Guido van Rossum76ba09f2003-04-16 19:40:58 +00006320
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006321 if (!skip) {
6322 PyObject *mro, *res, *tmp, *dict;
6323 PyTypeObject *starttype;
6324 descrgetfunc f;
6325 Py_ssize_t i, n;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006326
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006327 starttype = su->obj_type;
6328 mro = starttype->tp_mro;
Guido van Rossum155db9a2002-04-02 17:53:47 +00006329
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006330 if (mro == NULL)
6331 n = 0;
6332 else {
6333 assert(PyTuple_Check(mro));
6334 n = PyTuple_GET_SIZE(mro);
6335 }
6336 for (i = 0; i < n; i++) {
6337 if ((PyObject *)(su->type) == PyTuple_GET_ITEM(mro, i))
6338 break;
6339 }
6340 i++;
6341 res = NULL;
Victor Stinnerd74782b2012-03-09 00:39:08 +01006342 /* keep a strong reference to mro because starttype->tp_mro can be
6343 replaced during PyDict_GetItem(dict, name) */
6344 Py_INCREF(mro);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006345 for (; i < n; i++) {
6346 tmp = PyTuple_GET_ITEM(mro, i);
6347 if (PyType_Check(tmp))
6348 dict = ((PyTypeObject *)tmp)->tp_dict;
6349 else
6350 continue;
6351 res = PyDict_GetItem(dict, name);
6352 if (res != NULL) {
6353 Py_INCREF(res);
6354 f = Py_TYPE(res)->tp_descr_get;
6355 if (f != NULL) {
6356 tmp = f(res,
6357 /* Only pass 'obj' param if
6358 this is instance-mode super
6359 (See SF ID #743627)
6360 */
6361 (su->obj == (PyObject *)
6362 su->obj_type
6363 ? (PyObject *)NULL
6364 : su->obj),
6365 (PyObject *)starttype);
6366 Py_DECREF(res);
6367 res = tmp;
6368 }
Victor Stinnerd74782b2012-03-09 00:39:08 +01006369 Py_DECREF(mro);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006370 return res;
6371 }
6372 }
Victor Stinnerd74782b2012-03-09 00:39:08 +01006373 Py_DECREF(mro);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006374 }
6375 return PyObject_GenericGetAttr(self, name);
Guido van Rossum705f0f52001-08-24 16:47:00 +00006376}
6377
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006378static PyTypeObject *
Guido van Rossum5b443c62001-12-03 15:38:28 +00006379supercheck(PyTypeObject *type, PyObject *obj)
6380{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006381 /* Check that a super() call makes sense. Return a type object.
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006382
Florent Xiclunaaa6c1d22011-12-12 18:54:29 +01006383 obj can be a class, or an instance of one:
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006384
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006385 - If it is a class, it must be a subclass of 'type'. This case is
6386 used for class methods; the return value is obj.
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006387
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006388 - If it is an instance, it must be an instance of 'type'. This is
6389 the normal case; the return value is obj.__class__.
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006390
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006391 But... when obj is an instance, we want to allow for the case where
6392 Py_TYPE(obj) is not a subclass of type, but obj.__class__ is!
6393 This will allow using super() with a proxy for obj.
6394 */
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006395
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006396 /* Check for first bullet above (special case) */
6397 if (PyType_Check(obj) && PyType_IsSubtype((PyTypeObject *)obj, type)) {
6398 Py_INCREF(obj);
6399 return (PyTypeObject *)obj;
6400 }
Guido van Rossum8e80a722003-02-18 19:22:22 +00006401
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006402 /* Normal case */
6403 if (PyType_IsSubtype(Py_TYPE(obj), type)) {
6404 Py_INCREF(Py_TYPE(obj));
6405 return Py_TYPE(obj);
6406 }
6407 else {
6408 /* Try the slow way */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006409 PyObject *class_attr;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006410
Martin v. Löwisbfc6d742011-10-13 20:03:57 +02006411 class_attr = _PyObject_GetAttrId(obj, &PyId___class__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006412 if (class_attr != NULL &&
6413 PyType_Check(class_attr) &&
6414 (PyTypeObject *)class_attr != Py_TYPE(obj))
6415 {
6416 int ok = PyType_IsSubtype(
6417 (PyTypeObject *)class_attr, type);
6418 if (ok)
6419 return (PyTypeObject *)class_attr;
6420 }
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006421
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006422 if (class_attr == NULL)
6423 PyErr_Clear();
6424 else
6425 Py_DECREF(class_attr);
6426 }
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006427
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006428 PyErr_SetString(PyExc_TypeError,
6429 "super(type, obj): "
6430 "obj must be an instance or subtype of type");
6431 return NULL;
Guido van Rossum5b443c62001-12-03 15:38:28 +00006432}
6433
Guido van Rossum705f0f52001-08-24 16:47:00 +00006434static PyObject *
6435super_descr_get(PyObject *self, PyObject *obj, PyObject *type)
6436{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006437 superobject *su = (superobject *)self;
6438 superobject *newobj;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006439
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006440 if (obj == NULL || obj == Py_None || su->obj != NULL) {
6441 /* Not binding to an object, or already bound */
6442 Py_INCREF(self);
6443 return self;
6444 }
6445 if (Py_TYPE(su) != &PySuper_Type)
6446 /* If su is an instance of a (strict) subclass of super,
6447 call its type */
6448 return PyObject_CallFunctionObjArgs((PyObject *)Py_TYPE(su),
6449 su->type, obj, NULL);
6450 else {
6451 /* Inline the common case */
6452 PyTypeObject *obj_type = supercheck(su->type, obj);
6453 if (obj_type == NULL)
6454 return NULL;
6455 newobj = (superobject *)PySuper_Type.tp_new(&PySuper_Type,
6456 NULL, NULL);
6457 if (newobj == NULL)
6458 return NULL;
6459 Py_INCREF(su->type);
6460 Py_INCREF(obj);
6461 newobj->type = su->type;
6462 newobj->obj = obj;
6463 newobj->obj_type = obj_type;
6464 return (PyObject *)newobj;
6465 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00006466}
6467
6468static int
6469super_init(PyObject *self, PyObject *args, PyObject *kwds)
6470{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006471 superobject *su = (superobject *)self;
6472 PyTypeObject *type = NULL;
6473 PyObject *obj = NULL;
6474 PyTypeObject *obj_type = NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006475
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006476 if (!_PyArg_NoKeywords("super", kwds))
6477 return -1;
6478 if (!PyArg_ParseTuple(args, "|O!O:super", &PyType_Type, &type, &obj))
6479 return -1;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00006480
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006481 if (type == NULL) {
6482 /* Call super(), without args -- fill in from __class__
6483 and first local variable on the stack. */
6484 PyFrameObject *f = PyThreadState_GET()->frame;
6485 PyCodeObject *co = f->f_code;
Victor Stinner0fcab4a2011-01-04 12:59:15 +00006486 Py_ssize_t i, n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006487 if (co == NULL) {
Benjamin Peterson6a42bd62012-09-01 23:04:38 -04006488 PyErr_SetString(PyExc_RuntimeError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006489 "super(): no code object");
6490 return -1;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00006491 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006492 if (co->co_argcount == 0) {
Benjamin Peterson6a42bd62012-09-01 23:04:38 -04006493 PyErr_SetString(PyExc_RuntimeError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006494 "super(): no arguments");
6495 return -1;
6496 }
6497 obj = f->f_localsplus[0];
6498 if (obj == NULL) {
Benjamin Peterson6a42bd62012-09-01 23:04:38 -04006499 PyErr_SetString(PyExc_RuntimeError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006500 "super(): arg[0] deleted");
6501 return -1;
6502 }
6503 if (co->co_freevars == NULL)
6504 n = 0;
6505 else {
6506 assert(PyTuple_Check(co->co_freevars));
6507 n = PyTuple_GET_SIZE(co->co_freevars);
6508 }
6509 for (i = 0; i < n; i++) {
6510 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
6511 assert(PyUnicode_Check(name));
6512 if (!PyUnicode_CompareWithASCIIString(name,
Nick Coghlan0b43bcf2012-05-27 18:17:07 +10006513 "__class__")) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006514 Py_ssize_t index = co->co_nlocals +
6515 PyTuple_GET_SIZE(co->co_cellvars) + i;
6516 PyObject *cell = f->f_localsplus[index];
6517 if (cell == NULL || !PyCell_Check(cell)) {
Benjamin Peterson6a42bd62012-09-01 23:04:38 -04006518 PyErr_SetString(PyExc_RuntimeError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006519 "super(): bad __class__ cell");
6520 return -1;
6521 }
6522 type = (PyTypeObject *) PyCell_GET(cell);
6523 if (type == NULL) {
Benjamin Peterson6a42bd62012-09-01 23:04:38 -04006524 PyErr_SetString(PyExc_RuntimeError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006525 "super(): empty __class__ cell");
6526 return -1;
6527 }
6528 if (!PyType_Check(type)) {
Benjamin Peterson6a42bd62012-09-01 23:04:38 -04006529 PyErr_Format(PyExc_RuntimeError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006530 "super(): __class__ is not a type (%s)",
6531 Py_TYPE(type)->tp_name);
6532 return -1;
6533 }
6534 break;
6535 }
6536 }
6537 if (type == NULL) {
Benjamin Peterson6a42bd62012-09-01 23:04:38 -04006538 PyErr_SetString(PyExc_RuntimeError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006539 "super(): __class__ cell not found");
6540 return -1;
6541 }
6542 }
Guido van Rossumcd16bf62007-06-13 18:07:49 +00006543
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006544 if (obj == Py_None)
6545 obj = NULL;
6546 if (obj != NULL) {
6547 obj_type = supercheck(type, obj);
6548 if (obj_type == NULL)
6549 return -1;
6550 Py_INCREF(obj);
6551 }
6552 Py_INCREF(type);
6553 su->type = type;
6554 su->obj = obj;
6555 su->obj_type = obj_type;
6556 return 0;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006557}
6558
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00006559PyDoc_STRVAR(super_doc,
Guido van Rossumcd16bf62007-06-13 18:07:49 +00006560"super() -> same as super(__class__, <first argument>)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00006561"super(type) -> unbound super object\n"
6562"super(type, obj) -> bound super object; requires isinstance(obj, type)\n"
Guido van Rossume705ef12001-08-29 15:47:06 +00006563"super(type, type2) -> bound super object; requires issubclass(type2, type)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00006564"Typical use to call a cooperative superclass method:\n"
6565"class C(B):\n"
6566" def meth(self, arg):\n"
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006567" super().meth(arg)\n"
Guido van Rossumcd16bf62007-06-13 18:07:49 +00006568"This works for class methods too:\n"
6569"class C(B):\n"
6570" @classmethod\n"
6571" def cmeth(cls, arg):\n"
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006572" super().cmeth(arg)\n");
Guido van Rossum705f0f52001-08-24 16:47:00 +00006573
Guido van Rossum048eb752001-10-02 21:24:57 +00006574static int
6575super_traverse(PyObject *self, visitproc visit, void *arg)
6576{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006577 superobject *su = (superobject *)self;
Guido van Rossum048eb752001-10-02 21:24:57 +00006578
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006579 Py_VISIT(su->obj);
6580 Py_VISIT(su->type);
6581 Py_VISIT(su->obj_type);
Guido van Rossum048eb752001-10-02 21:24:57 +00006582
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006583 return 0;
Guido van Rossum048eb752001-10-02 21:24:57 +00006584}
6585
Guido van Rossum705f0f52001-08-24 16:47:00 +00006586PyTypeObject PySuper_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006587 PyVarObject_HEAD_INIT(&PyType_Type, 0)
6588 "super", /* tp_name */
6589 sizeof(superobject), /* tp_basicsize */
6590 0, /* tp_itemsize */
6591 /* methods */
6592 super_dealloc, /* tp_dealloc */
6593 0, /* tp_print */
6594 0, /* tp_getattr */
6595 0, /* tp_setattr */
6596 0, /* tp_reserved */
6597 super_repr, /* tp_repr */
6598 0, /* tp_as_number */
6599 0, /* tp_as_sequence */
6600 0, /* tp_as_mapping */
6601 0, /* tp_hash */
6602 0, /* tp_call */
6603 0, /* tp_str */
6604 super_getattro, /* tp_getattro */
6605 0, /* tp_setattro */
6606 0, /* tp_as_buffer */
6607 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
6608 Py_TPFLAGS_BASETYPE, /* tp_flags */
6609 super_doc, /* tp_doc */
6610 super_traverse, /* tp_traverse */
6611 0, /* tp_clear */
6612 0, /* tp_richcompare */
6613 0, /* tp_weaklistoffset */
6614 0, /* tp_iter */
6615 0, /* tp_iternext */
6616 0, /* tp_methods */
6617 super_members, /* tp_members */
6618 0, /* tp_getset */
6619 0, /* tp_base */
6620 0, /* tp_dict */
6621 super_descr_get, /* tp_descr_get */
6622 0, /* tp_descr_set */
6623 0, /* tp_dictoffset */
6624 super_init, /* tp_init */
6625 PyType_GenericAlloc, /* tp_alloc */
6626 PyType_GenericNew, /* tp_new */
6627 PyObject_GC_Del, /* tp_free */
Guido van Rossum705f0f52001-08-24 16:47:00 +00006628};