blob: 9f89972594208338231ab365e029468444678ca3 [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
Martin v. Löwis738236d2011-02-05 20:35:29 +00001936long
1937PyType_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) {
Eric V. Smithb9cd3532011-03-12 10:08:48 -05003657 if (PyErr_WarnEx(PyExc_DeprecationWarning,
3658 "object.__format__ with a non-empty format "
3659 "string is deprecated", 1) < 0) {
3660 goto done;
3661 }
3662 /* Eventually this will become an error:
3663 PyErr_Format(PyExc_TypeError,
3664 "non-empty format string passed to object.__format__");
3665 goto done;
3666 */
3667 }
Eric Smith8c663262007-08-25 02:26:07 +00003668
Eric V. Smithb9cd3532011-03-12 10:08:48 -05003669 result = PyObject_Format(self_as_str, format_spec);
Eric Smithe4d63172010-09-13 20:48:43 +00003670 }
3671
3672done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003673 Py_XDECREF(self_as_str);
Eric Smith8c663262007-08-25 02:26:07 +00003674
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003675 return result;
Eric Smith8c663262007-08-25 02:26:07 +00003676}
3677
Martin v. Löwis00709aa2008-06-04 14:18:43 +00003678static PyObject *
3679object_sizeof(PyObject *self, PyObject *args)
3680{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003681 Py_ssize_t res, isize;
Martin v. Löwis00709aa2008-06-04 14:18:43 +00003682
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003683 res = 0;
3684 isize = self->ob_type->tp_itemsize;
3685 if (isize > 0)
3686 res = Py_SIZE(self->ob_type) * isize;
3687 res += self->ob_type->tp_basicsize;
Martin v. Löwis00709aa2008-06-04 14:18:43 +00003688
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003689 return PyLong_FromSsize_t(res);
Martin v. Löwis00709aa2008-06-04 14:18:43 +00003690}
3691
Benjamin Peterson82b00c12011-05-24 11:09:06 -05003692/* __dir__ for generic objects: returns __dict__, __class__,
3693 and recursively up the __class__.__bases__ chain.
3694*/
3695static PyObject *
3696object_dir(PyObject *self, PyObject *args)
3697{
3698 PyObject *result = NULL;
3699 PyObject *dict = NULL;
3700 PyObject *itsclass = NULL;
3701
3702 /* Get __dict__ (which may or may not be a real dict...) */
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02003703 dict = _PyObject_GetAttrId(self, &PyId___dict__);
Benjamin Peterson82b00c12011-05-24 11:09:06 -05003704 if (dict == NULL) {
3705 PyErr_Clear();
3706 dict = PyDict_New();
3707 }
3708 else if (!PyDict_Check(dict)) {
3709 Py_DECREF(dict);
3710 dict = PyDict_New();
3711 }
3712 else {
3713 /* Copy __dict__ to avoid mutating it. */
3714 PyObject *temp = PyDict_Copy(dict);
3715 Py_DECREF(dict);
3716 dict = temp;
3717 }
3718
3719 if (dict == NULL)
3720 goto error;
3721
3722 /* Merge in attrs reachable from its class. */
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02003723 itsclass = _PyObject_GetAttrId(self, &PyId___class__);
Benjamin Peterson82b00c12011-05-24 11:09:06 -05003724 if (itsclass == NULL)
3725 /* XXX(tomer): Perhaps fall back to obj->ob_type if no
3726 __class__ exists? */
3727 PyErr_Clear();
3728 else if (merge_class_dict(dict, itsclass) != 0)
3729 goto error;
3730
3731 result = PyDict_Keys(dict);
3732 /* fall through */
3733error:
3734 Py_XDECREF(itsclass);
3735 Py_XDECREF(dict);
3736 return result;
3737}
3738
Guido van Rossum3926a632001-09-25 16:25:58 +00003739static PyMethodDef object_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003740 {"__reduce_ex__", object_reduce_ex, METH_VARARGS,
3741 PyDoc_STR("helper for pickle")},
3742 {"__reduce__", object_reduce, METH_VARARGS,
3743 PyDoc_STR("helper for pickle")},
3744 {"__subclasshook__", object_subclasshook, METH_CLASS | METH_VARARGS,
3745 object_subclasshook_doc},
3746 {"__format__", object_format, METH_VARARGS,
3747 PyDoc_STR("default object formatter")},
3748 {"__sizeof__", object_sizeof, METH_NOARGS,
Benjamin Petersonfbe56bb2011-05-24 12:42:51 -05003749 PyDoc_STR("__sizeof__() -> int\nsize of object in memory, in bytes")},
Benjamin Peterson82b00c12011-05-24 11:09:06 -05003750 {"__dir__", object_dir, METH_NOARGS,
Benjamin Petersonc7284122011-05-24 12:46:15 -05003751 PyDoc_STR("__dir__() -> list\ndefault dir() implementation")},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003752 {0}
Guido van Rossum3926a632001-09-25 16:25:58 +00003753};
3754
Guido van Rossum036f9992003-02-21 22:02:54 +00003755
Tim Peters6d6c1a32001-08-02 04:15:00 +00003756PyTypeObject PyBaseObject_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003757 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3758 "object", /* tp_name */
3759 sizeof(PyObject), /* tp_basicsize */
3760 0, /* tp_itemsize */
3761 object_dealloc, /* tp_dealloc */
3762 0, /* tp_print */
3763 0, /* tp_getattr */
3764 0, /* tp_setattr */
3765 0, /* tp_reserved */
3766 object_repr, /* tp_repr */
3767 0, /* tp_as_number */
3768 0, /* tp_as_sequence */
3769 0, /* tp_as_mapping */
3770 (hashfunc)_Py_HashPointer, /* tp_hash */
3771 0, /* tp_call */
3772 object_str, /* tp_str */
3773 PyObject_GenericGetAttr, /* tp_getattro */
3774 PyObject_GenericSetAttr, /* tp_setattro */
3775 0, /* tp_as_buffer */
3776 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
3777 PyDoc_STR("The most base type"), /* tp_doc */
3778 0, /* tp_traverse */
3779 0, /* tp_clear */
3780 object_richcompare, /* tp_richcompare */
3781 0, /* tp_weaklistoffset */
3782 0, /* tp_iter */
3783 0, /* tp_iternext */
3784 object_methods, /* tp_methods */
3785 0, /* tp_members */
3786 object_getsets, /* tp_getset */
3787 0, /* tp_base */
3788 0, /* tp_dict */
3789 0, /* tp_descr_get */
3790 0, /* tp_descr_set */
3791 0, /* tp_dictoffset */
3792 object_init, /* tp_init */
3793 PyType_GenericAlloc, /* tp_alloc */
3794 object_new, /* tp_new */
3795 PyObject_Del, /* tp_free */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003796};
3797
3798
Guido van Rossum50e9fb92006-08-17 05:42:55 +00003799/* Add the methods from tp_methods to the __dict__ in a type object */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003800
3801static int
3802add_methods(PyTypeObject *type, PyMethodDef *meth)
3803{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003804 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003805
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003806 for (; meth->ml_name != NULL; meth++) {
3807 PyObject *descr;
Benjamin Peterson89a6e9a2012-05-08 09:22:24 -04003808 int err;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003809 if (PyDict_GetItemString(dict, meth->ml_name) &&
3810 !(meth->ml_flags & METH_COEXIST))
3811 continue;
3812 if (meth->ml_flags & METH_CLASS) {
3813 if (meth->ml_flags & METH_STATIC) {
3814 PyErr_SetString(PyExc_ValueError,
3815 "method cannot be both class and static");
3816 return -1;
3817 }
3818 descr = PyDescr_NewClassMethod(type, meth);
3819 }
3820 else if (meth->ml_flags & METH_STATIC) {
Antoine Pitrou5b629422011-12-23 12:40:16 +01003821 PyObject *cfunc = PyCFunction_New(meth, (PyObject*)type);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003822 if (cfunc == NULL)
3823 return -1;
3824 descr = PyStaticMethod_New(cfunc);
3825 Py_DECREF(cfunc);
3826 }
3827 else {
3828 descr = PyDescr_NewMethod(type, meth);
3829 }
3830 if (descr == NULL)
3831 return -1;
Benjamin Peterson89a6e9a2012-05-08 09:22:24 -04003832 err = PyDict_SetItemString(dict, meth->ml_name, descr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003833 Py_DECREF(descr);
Benjamin Peterson89a6e9a2012-05-08 09:22:24 -04003834 if (err < 0)
3835 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003836 }
3837 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003838}
3839
3840static int
Guido van Rossum6f799372001-09-20 20:46:19 +00003841add_members(PyTypeObject *type, PyMemberDef *memb)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003842{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003843 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003844
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003845 for (; memb->name != NULL; memb++) {
3846 PyObject *descr;
3847 if (PyDict_GetItemString(dict, memb->name))
3848 continue;
3849 descr = PyDescr_NewMember(type, memb);
3850 if (descr == NULL)
3851 return -1;
3852 if (PyDict_SetItemString(dict, memb->name, descr) < 0)
3853 return -1;
3854 Py_DECREF(descr);
3855 }
3856 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003857}
3858
3859static int
Guido van Rossum32d34c82001-09-20 21:45:26 +00003860add_getset(PyTypeObject *type, PyGetSetDef *gsp)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003861{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003862 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003863
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003864 for (; gsp->name != NULL; gsp++) {
3865 PyObject *descr;
3866 if (PyDict_GetItemString(dict, gsp->name))
3867 continue;
3868 descr = PyDescr_NewGetSet(type, gsp);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003869
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003870 if (descr == NULL)
3871 return -1;
3872 if (PyDict_SetItemString(dict, gsp->name, descr) < 0)
3873 return -1;
3874 Py_DECREF(descr);
3875 }
3876 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003877}
3878
Guido van Rossum13d52f02001-08-10 21:24:08 +00003879static void
3880inherit_special(PyTypeObject *type, PyTypeObject *base)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003881{
Tim Peters6d6c1a32001-08-02 04:15:00 +00003882
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003883 /* Copying basicsize is connected to the GC flags */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003884 if (!(type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
3885 (base->tp_flags & Py_TPFLAGS_HAVE_GC) &&
3886 (!type->tp_traverse && !type->tp_clear)) {
3887 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
3888 if (type->tp_traverse == NULL)
3889 type->tp_traverse = base->tp_traverse;
3890 if (type->tp_clear == NULL)
3891 type->tp_clear = base->tp_clear;
3892 }
3893 {
3894 /* The condition below could use some explanation.
3895 It appears that tp_new is not inherited for static types
3896 whose base class is 'object'; this seems to be a precaution
3897 so that old extension types don't suddenly become
3898 callable (object.__new__ wouldn't insure the invariants
3899 that the extension type's own factory function ensures).
3900 Heap types, of course, are under our control, so they do
3901 inherit tp_new; static extension types that specify some
Florent Xiclunaaa6c1d22011-12-12 18:54:29 +01003902 other built-in type as the default also
3903 inherit object.__new__. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003904 if (base != &PyBaseObject_Type ||
3905 (type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
3906 if (type->tp_new == NULL)
3907 type->tp_new = base->tp_new;
3908 }
3909 }
Benjamin Petersona7465e22010-07-05 15:01:22 +00003910 if (type->tp_basicsize == 0)
3911 type->tp_basicsize = base->tp_basicsize;
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00003912
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003913 /* Copy other non-function slots */
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00003914
3915#undef COPYVAL
3916#define COPYVAL(SLOT) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003917 if (type->SLOT == 0) type->SLOT = base->SLOT
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00003918
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003919 COPYVAL(tp_itemsize);
3920 COPYVAL(tp_weaklistoffset);
3921 COPYVAL(tp_dictoffset);
Thomas Wouters27d517b2007-02-25 20:39:11 +00003922
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003923 /* Setup fast subclass flags */
3924 if (PyType_IsSubtype(base, (PyTypeObject*)PyExc_BaseException))
3925 type->tp_flags |= Py_TPFLAGS_BASE_EXC_SUBCLASS;
3926 else if (PyType_IsSubtype(base, &PyType_Type))
3927 type->tp_flags |= Py_TPFLAGS_TYPE_SUBCLASS;
3928 else if (PyType_IsSubtype(base, &PyLong_Type))
3929 type->tp_flags |= Py_TPFLAGS_LONG_SUBCLASS;
3930 else if (PyType_IsSubtype(base, &PyBytes_Type))
3931 type->tp_flags |= Py_TPFLAGS_BYTES_SUBCLASS;
3932 else if (PyType_IsSubtype(base, &PyUnicode_Type))
3933 type->tp_flags |= Py_TPFLAGS_UNICODE_SUBCLASS;
3934 else if (PyType_IsSubtype(base, &PyTuple_Type))
3935 type->tp_flags |= Py_TPFLAGS_TUPLE_SUBCLASS;
3936 else if (PyType_IsSubtype(base, &PyList_Type))
3937 type->tp_flags |= Py_TPFLAGS_LIST_SUBCLASS;
3938 else if (PyType_IsSubtype(base, &PyDict_Type))
3939 type->tp_flags |= Py_TPFLAGS_DICT_SUBCLASS;
Guido van Rossum13d52f02001-08-10 21:24:08 +00003940}
3941
Guido van Rossum38938152006-08-21 23:36:26 +00003942static int
Guido van Rossumf5243f02008-01-01 04:06:48 +00003943overrides_hash(PyTypeObject *type)
Guido van Rossum38938152006-08-21 23:36:26 +00003944{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003945 PyObject *dict = type->tp_dict;
Victor Stinner3c1e4812012-03-26 22:10:51 +02003946 _Py_IDENTIFIER(__eq__);
Guido van Rossum38938152006-08-21 23:36:26 +00003947
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003948 assert(dict != NULL);
Victor Stinner3c1e4812012-03-26 22:10:51 +02003949 if (_PyDict_GetItemId(dict, &PyId___eq__) != NULL)
3950 return 1;
3951 if (_PyDict_GetItemId(dict, &PyId___hash__) != NULL)
3952 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003953 return 0;
Guido van Rossum38938152006-08-21 23:36:26 +00003954}
3955
Guido van Rossum13d52f02001-08-10 21:24:08 +00003956static void
3957inherit_slots(PyTypeObject *type, PyTypeObject *base)
3958{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003959 PyTypeObject *basebase;
Guido van Rossum13d52f02001-08-10 21:24:08 +00003960
3961#undef SLOTDEFINED
Tim Peters6d6c1a32001-08-02 04:15:00 +00003962#undef COPYSLOT
3963#undef COPYNUM
3964#undef COPYSEQ
3965#undef COPYMAP
Guido van Rossum5af588b2001-10-12 14:13:21 +00003966#undef COPYBUF
Guido van Rossum13d52f02001-08-10 21:24:08 +00003967
3968#define SLOTDEFINED(SLOT) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003969 (base->SLOT != 0 && \
3970 (basebase == NULL || base->SLOT != basebase->SLOT))
Guido van Rossum13d52f02001-08-10 21:24:08 +00003971
Tim Peters6d6c1a32001-08-02 04:15:00 +00003972#define COPYSLOT(SLOT) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003973 if (!type->SLOT && SLOTDEFINED(SLOT)) type->SLOT = base->SLOT
Tim Peters6d6c1a32001-08-02 04:15:00 +00003974
3975#define COPYNUM(SLOT) COPYSLOT(tp_as_number->SLOT)
3976#define COPYSEQ(SLOT) COPYSLOT(tp_as_sequence->SLOT)
3977#define COPYMAP(SLOT) COPYSLOT(tp_as_mapping->SLOT)
Tim Petersfc57ccb2001-10-12 02:38:24 +00003978#define COPYBUF(SLOT) COPYSLOT(tp_as_buffer->SLOT)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003979
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003980 /* This won't inherit indirect slots (from tp_as_number etc.)
3981 if type doesn't provide the space. */
Guido van Rossum13d52f02001-08-10 21:24:08 +00003982
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003983 if (type->tp_as_number != NULL && base->tp_as_number != NULL) {
3984 basebase = base->tp_base;
3985 if (basebase->tp_as_number == NULL)
3986 basebase = NULL;
3987 COPYNUM(nb_add);
3988 COPYNUM(nb_subtract);
3989 COPYNUM(nb_multiply);
3990 COPYNUM(nb_remainder);
3991 COPYNUM(nb_divmod);
3992 COPYNUM(nb_power);
3993 COPYNUM(nb_negative);
3994 COPYNUM(nb_positive);
3995 COPYNUM(nb_absolute);
3996 COPYNUM(nb_bool);
3997 COPYNUM(nb_invert);
3998 COPYNUM(nb_lshift);
3999 COPYNUM(nb_rshift);
4000 COPYNUM(nb_and);
4001 COPYNUM(nb_xor);
4002 COPYNUM(nb_or);
4003 COPYNUM(nb_int);
4004 COPYNUM(nb_float);
4005 COPYNUM(nb_inplace_add);
4006 COPYNUM(nb_inplace_subtract);
4007 COPYNUM(nb_inplace_multiply);
4008 COPYNUM(nb_inplace_remainder);
4009 COPYNUM(nb_inplace_power);
4010 COPYNUM(nb_inplace_lshift);
4011 COPYNUM(nb_inplace_rshift);
4012 COPYNUM(nb_inplace_and);
4013 COPYNUM(nb_inplace_xor);
4014 COPYNUM(nb_inplace_or);
4015 COPYNUM(nb_true_divide);
4016 COPYNUM(nb_floor_divide);
4017 COPYNUM(nb_inplace_true_divide);
4018 COPYNUM(nb_inplace_floor_divide);
4019 COPYNUM(nb_index);
4020 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004021
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004022 if (type->tp_as_sequence != NULL && base->tp_as_sequence != NULL) {
4023 basebase = base->tp_base;
4024 if (basebase->tp_as_sequence == NULL)
4025 basebase = NULL;
4026 COPYSEQ(sq_length);
4027 COPYSEQ(sq_concat);
4028 COPYSEQ(sq_repeat);
4029 COPYSEQ(sq_item);
4030 COPYSEQ(sq_ass_item);
4031 COPYSEQ(sq_contains);
4032 COPYSEQ(sq_inplace_concat);
4033 COPYSEQ(sq_inplace_repeat);
4034 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004035
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004036 if (type->tp_as_mapping != NULL && base->tp_as_mapping != NULL) {
4037 basebase = base->tp_base;
4038 if (basebase->tp_as_mapping == NULL)
4039 basebase = NULL;
4040 COPYMAP(mp_length);
4041 COPYMAP(mp_subscript);
4042 COPYMAP(mp_ass_subscript);
4043 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004044
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004045 if (type->tp_as_buffer != NULL && base->tp_as_buffer != NULL) {
4046 basebase = base->tp_base;
4047 if (basebase->tp_as_buffer == NULL)
4048 basebase = NULL;
4049 COPYBUF(bf_getbuffer);
4050 COPYBUF(bf_releasebuffer);
4051 }
Tim Petersfc57ccb2001-10-12 02:38:24 +00004052
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004053 basebase = base->tp_base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004054
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004055 COPYSLOT(tp_dealloc);
4056 if (type->tp_getattr == NULL && type->tp_getattro == NULL) {
4057 type->tp_getattr = base->tp_getattr;
4058 type->tp_getattro = base->tp_getattro;
4059 }
4060 if (type->tp_setattr == NULL && type->tp_setattro == NULL) {
4061 type->tp_setattr = base->tp_setattr;
4062 type->tp_setattro = base->tp_setattro;
4063 }
4064 /* tp_reserved is ignored */
4065 COPYSLOT(tp_repr);
4066 /* tp_hash see tp_richcompare */
4067 COPYSLOT(tp_call);
4068 COPYSLOT(tp_str);
4069 {
4070 /* Copy comparison-related slots only when
4071 not overriding them anywhere */
4072 if (type->tp_richcompare == NULL &&
4073 type->tp_hash == NULL &&
4074 !overrides_hash(type))
4075 {
4076 type->tp_richcompare = base->tp_richcompare;
4077 type->tp_hash = base->tp_hash;
4078 }
4079 }
4080 {
4081 COPYSLOT(tp_iter);
4082 COPYSLOT(tp_iternext);
4083 }
4084 {
4085 COPYSLOT(tp_descr_get);
4086 COPYSLOT(tp_descr_set);
4087 COPYSLOT(tp_dictoffset);
4088 COPYSLOT(tp_init);
4089 COPYSLOT(tp_alloc);
4090 COPYSLOT(tp_is_gc);
4091 if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) ==
4092 (base->tp_flags & Py_TPFLAGS_HAVE_GC)) {
4093 /* They agree about gc. */
4094 COPYSLOT(tp_free);
4095 }
4096 else if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
4097 type->tp_free == NULL &&
4098 base->tp_free == PyObject_Free) {
4099 /* A bit of magic to plug in the correct default
4100 * tp_free function when a derived class adds gc,
4101 * didn't define tp_free, and the base uses the
4102 * default non-gc tp_free.
4103 */
4104 type->tp_free = PyObject_GC_Del;
4105 }
4106 /* else they didn't agree about gc, and there isn't something
4107 * obvious to be done -- the type is on its own.
4108 */
4109 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004110}
4111
Jeremy Hylton938ace62002-07-17 16:30:39 +00004112static int add_operators(PyTypeObject *);
Guido van Rossum13d52f02001-08-10 21:24:08 +00004113
Tim Peters6d6c1a32001-08-02 04:15:00 +00004114int
Guido van Rossum528b7eb2001-08-07 17:24:28 +00004115PyType_Ready(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004116{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004117 PyObject *dict, *bases;
4118 PyTypeObject *base;
4119 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004120
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004121 if (type->tp_flags & Py_TPFLAGS_READY) {
4122 assert(type->tp_dict != NULL);
4123 return 0;
4124 }
4125 assert((type->tp_flags & Py_TPFLAGS_READYING) == 0);
Guido van Rossumd614f972001-08-10 17:39:49 +00004126
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004127 type->tp_flags |= Py_TPFLAGS_READYING;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004128
Tim Peters36eb4df2003-03-23 03:33:13 +00004129#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004130 /* PyType_Ready is the closest thing we have to a choke point
4131 * for type objects, so is the best place I can think of to try
4132 * to get type objects into the doubly-linked list of all objects.
4133 * Still, not all type objects go thru PyType_Ready.
4134 */
4135 _Py_AddToAllObjects((PyObject *)type, 0);
Tim Peters36eb4df2003-03-23 03:33:13 +00004136#endif
4137
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004138 /* Initialize tp_base (defaults to BaseObject unless that's us) */
4139 base = type->tp_base;
4140 if (base == NULL && type != &PyBaseObject_Type) {
4141 base = type->tp_base = &PyBaseObject_Type;
4142 Py_INCREF(base);
4143 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004144
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004145 /* Now the only way base can still be NULL is if type is
4146 * &PyBaseObject_Type.
4147 */
Guido van Rossum692cdbc2006-03-10 02:04:28 +00004148
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004149 /* Initialize the base class */
4150 if (base != NULL && base->tp_dict == NULL) {
4151 if (PyType_Ready(base) < 0)
4152 goto error;
4153 }
Guido van Rossum323a9cf2002-08-14 17:26:30 +00004154
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004155 /* Initialize ob_type if NULL. This means extensions that want to be
4156 compilable separately on Windows can call PyType_Ready() instead of
4157 initializing the ob_type field of their type objects. */
4158 /* The test for base != NULL is really unnecessary, since base is only
4159 NULL when type is &PyBaseObject_Type, and we know its ob_type is
4160 not NULL (it's initialized to &PyType_Type). But coverity doesn't
4161 know that. */
4162 if (Py_TYPE(type) == NULL && base != NULL)
4163 Py_TYPE(type) = Py_TYPE(base);
Guido van Rossum0986d822002-04-08 01:38:42 +00004164
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004165 /* Initialize tp_bases */
4166 bases = type->tp_bases;
4167 if (bases == NULL) {
4168 if (base == NULL)
4169 bases = PyTuple_New(0);
4170 else
4171 bases = PyTuple_Pack(1, base);
4172 if (bases == NULL)
4173 goto error;
4174 type->tp_bases = bases;
4175 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004176
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004177 /* Initialize tp_dict */
4178 dict = type->tp_dict;
4179 if (dict == NULL) {
4180 dict = PyDict_New();
4181 if (dict == NULL)
4182 goto error;
4183 type->tp_dict = dict;
4184 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004185
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004186 /* Add type-specific descriptors to tp_dict */
4187 if (add_operators(type) < 0)
4188 goto error;
4189 if (type->tp_methods != NULL) {
4190 if (add_methods(type, type->tp_methods) < 0)
4191 goto error;
4192 }
4193 if (type->tp_members != NULL) {
4194 if (add_members(type, type->tp_members) < 0)
4195 goto error;
4196 }
4197 if (type->tp_getset != NULL) {
4198 if (add_getset(type, type->tp_getset) < 0)
4199 goto error;
4200 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004201
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004202 /* Calculate method resolution order */
4203 if (mro_internal(type) < 0) {
4204 goto error;
4205 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004206
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004207 /* Inherit special flags from dominant base */
4208 if (type->tp_base != NULL)
4209 inherit_special(type, type->tp_base);
Guido van Rossum13d52f02001-08-10 21:24:08 +00004210
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004211 /* Initialize tp_dict properly */
4212 bases = type->tp_mro;
4213 assert(bases != NULL);
4214 assert(PyTuple_Check(bases));
4215 n = PyTuple_GET_SIZE(bases);
4216 for (i = 1; i < n; i++) {
4217 PyObject *b = PyTuple_GET_ITEM(bases, i);
4218 if (PyType_Check(b))
4219 inherit_slots(type, (PyTypeObject *)b);
4220 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004221
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004222 /* Sanity check for tp_free. */
4223 if (PyType_IS_GC(type) && (type->tp_flags & Py_TPFLAGS_BASETYPE) &&
4224 (type->tp_free == NULL || type->tp_free == PyObject_Del)) {
4225 /* This base class needs to call tp_free, but doesn't have
4226 * one, or its tp_free is for non-gc'ed objects.
4227 */
4228 PyErr_Format(PyExc_TypeError, "type '%.100s' participates in "
4229 "gc and is a base type but has inappropriate "
4230 "tp_free slot",
4231 type->tp_name);
4232 goto error;
4233 }
Tim Peters3cfe7542003-05-21 21:29:48 +00004234
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004235 /* if the type dictionary doesn't contain a __doc__, set it from
4236 the tp_doc slot.
4237 */
Victor Stinner3c1e4812012-03-26 22:10:51 +02004238 if (_PyDict_GetItemId(type->tp_dict, &PyId___doc__) == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004239 if (type->tp_doc != NULL) {
4240 PyObject *doc = PyUnicode_FromString(type->tp_doc);
4241 if (doc == NULL)
4242 goto error;
Victor Stinner3c1e4812012-03-26 22:10:51 +02004243 _PyDict_SetItemId(type->tp_dict, &PyId___doc__, doc);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004244 Py_DECREF(doc);
4245 } else {
Victor Stinner3c1e4812012-03-26 22:10:51 +02004246 _PyDict_SetItemId(type->tp_dict,
4247 &PyId___doc__, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004248 }
4249 }
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00004250
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004251 /* Hack for tp_hash and __hash__.
4252 If after all that, tp_hash is still NULL, and __hash__ is not in
4253 tp_dict, set tp_hash to PyObject_HashNotImplemented and
4254 tp_dict['__hash__'] equal to None.
4255 This signals that __hash__ is not inherited.
4256 */
4257 if (type->tp_hash == NULL) {
Victor Stinner3c1e4812012-03-26 22:10:51 +02004258 if (_PyDict_GetItemId(type->tp_dict, &PyId___hash__) == NULL) {
4259 if (_PyDict_SetItemId(type->tp_dict, &PyId___hash__, Py_None) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004260 goto error;
4261 type->tp_hash = PyObject_HashNotImplemented;
4262 }
4263 }
Guido van Rossum38938152006-08-21 23:36:26 +00004264
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004265 /* Some more special stuff */
4266 base = type->tp_base;
4267 if (base != NULL) {
4268 if (type->tp_as_number == NULL)
4269 type->tp_as_number = base->tp_as_number;
4270 if (type->tp_as_sequence == NULL)
4271 type->tp_as_sequence = base->tp_as_sequence;
4272 if (type->tp_as_mapping == NULL)
4273 type->tp_as_mapping = base->tp_as_mapping;
4274 if (type->tp_as_buffer == NULL)
4275 type->tp_as_buffer = base->tp_as_buffer;
4276 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004277
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004278 /* Link into each base class's list of subclasses */
4279 bases = type->tp_bases;
4280 n = PyTuple_GET_SIZE(bases);
4281 for (i = 0; i < n; i++) {
4282 PyObject *b = PyTuple_GET_ITEM(bases, i);
4283 if (PyType_Check(b) &&
4284 add_subclass((PyTypeObject *)b, type) < 0)
4285 goto error;
4286 }
Guido van Rossum1c450732001-10-08 15:18:27 +00004287
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004288 /* Warn for a type that implements tp_compare (now known as
4289 tp_reserved) but not tp_richcompare. */
4290 if (type->tp_reserved && !type->tp_richcompare) {
4291 int error;
Victor Stinner4a2b7a12010-08-13 14:03:48 +00004292 error = PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
4293 "Type %.100s defines tp_reserved (formerly tp_compare) "
4294 "but not tp_richcompare. Comparisons may not behave as intended.",
4295 type->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004296 if (error == -1)
4297 goto error;
4298 }
Mark Dickinson2a7d45b2009-02-08 11:02:10 +00004299
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004300 /* All done -- set the ready flag */
4301 assert(type->tp_dict != NULL);
4302 type->tp_flags =
4303 (type->tp_flags & ~Py_TPFLAGS_READYING) | Py_TPFLAGS_READY;
4304 return 0;
Guido van Rossumd614f972001-08-10 17:39:49 +00004305
4306 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004307 type->tp_flags &= ~Py_TPFLAGS_READYING;
4308 return -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004309}
4310
Guido van Rossum1c450732001-10-08 15:18:27 +00004311static int
4312add_subclass(PyTypeObject *base, PyTypeObject *type)
4313{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004314 Py_ssize_t i;
4315 int result;
4316 PyObject *list, *ref, *newobj;
Guido van Rossum1c450732001-10-08 15:18:27 +00004317
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004318 list = base->tp_subclasses;
4319 if (list == NULL) {
4320 base->tp_subclasses = list = PyList_New(0);
4321 if (list == NULL)
4322 return -1;
4323 }
4324 assert(PyList_Check(list));
4325 newobj = PyWeakref_NewRef((PyObject *)type, NULL);
4326 i = PyList_GET_SIZE(list);
4327 while (--i >= 0) {
4328 ref = PyList_GET_ITEM(list, i);
4329 assert(PyWeakref_CheckRef(ref));
4330 if (PyWeakref_GET_OBJECT(ref) == Py_None)
4331 return PyList_SetItem(list, i, newobj);
4332 }
4333 result = PyList_Append(list, newobj);
4334 Py_DECREF(newobj);
4335 return result;
Guido van Rossum1c450732001-10-08 15:18:27 +00004336}
4337
Michael W. Hudson98bbc492002-11-26 14:47:27 +00004338static void
4339remove_subclass(PyTypeObject *base, PyTypeObject *type)
4340{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004341 Py_ssize_t i;
4342 PyObject *list, *ref;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00004343
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004344 list = base->tp_subclasses;
4345 if (list == NULL) {
4346 return;
4347 }
4348 assert(PyList_Check(list));
4349 i = PyList_GET_SIZE(list);
4350 while (--i >= 0) {
4351 ref = PyList_GET_ITEM(list, i);
4352 assert(PyWeakref_CheckRef(ref));
4353 if (PyWeakref_GET_OBJECT(ref) == (PyObject*)type) {
4354 /* this can't fail, right? */
4355 PySequence_DelItem(list, i);
4356 return;
4357 }
4358 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +00004359}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004360
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004361static int
4362check_num_args(PyObject *ob, int n)
4363{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004364 if (!PyTuple_CheckExact(ob)) {
4365 PyErr_SetString(PyExc_SystemError,
4366 "PyArg_UnpackTuple() argument list is not a tuple");
4367 return 0;
4368 }
4369 if (n == PyTuple_GET_SIZE(ob))
4370 return 1;
4371 PyErr_Format(
4372 PyExc_TypeError,
4373 "expected %d arguments, got %zd", n, PyTuple_GET_SIZE(ob));
4374 return 0;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004375}
4376
Tim Peters6d6c1a32001-08-02 04:15:00 +00004377/* Generic wrappers for overloadable 'operators' such as __getitem__ */
4378
4379/* There's a wrapper *function* for each distinct function typedef used
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004380 for type object slots (e.g. binaryfunc, ternaryfunc, etc.). There's a
Tim Peters6d6c1a32001-08-02 04:15:00 +00004381 wrapper *table* for each distinct operation (e.g. __len__, __add__).
4382 Most tables have only one entry; the tables for binary operators have two
4383 entries, one regular and one with reversed arguments. */
4384
4385static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00004386wrap_lenfunc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004387{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004388 lenfunc func = (lenfunc)wrapped;
4389 Py_ssize_t res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004390
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004391 if (!check_num_args(args, 0))
4392 return NULL;
4393 res = (*func)(self);
4394 if (res == -1 && PyErr_Occurred())
4395 return NULL;
4396 return PyLong_FromLong((long)res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004397}
4398
Tim Peters6d6c1a32001-08-02 04:15:00 +00004399static PyObject *
Raymond Hettingerf34f2642003-10-11 17:29:04 +00004400wrap_inquirypred(PyObject *self, PyObject *args, void *wrapped)
4401{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004402 inquiry func = (inquiry)wrapped;
4403 int res;
Raymond Hettingerf34f2642003-10-11 17:29:04 +00004404
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004405 if (!check_num_args(args, 0))
4406 return NULL;
4407 res = (*func)(self);
4408 if (res == -1 && PyErr_Occurred())
4409 return NULL;
4410 return PyBool_FromLong((long)res);
Raymond Hettingerf34f2642003-10-11 17:29:04 +00004411}
4412
4413static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00004414wrap_binaryfunc(PyObject *self, PyObject *args, void *wrapped)
4415{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004416 binaryfunc func = (binaryfunc)wrapped;
4417 PyObject *other;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004418
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004419 if (!check_num_args(args, 1))
4420 return NULL;
4421 other = PyTuple_GET_ITEM(args, 0);
4422 return (*func)(self, other);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004423}
4424
4425static PyObject *
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00004426wrap_binaryfunc_l(PyObject *self, PyObject *args, void *wrapped)
4427{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004428 binaryfunc func = (binaryfunc)wrapped;
4429 PyObject *other;
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00004430
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004431 if (!check_num_args(args, 1))
4432 return NULL;
4433 other = PyTuple_GET_ITEM(args, 0);
4434 return (*func)(self, other);
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00004435}
4436
4437static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00004438wrap_binaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
4439{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004440 binaryfunc func = (binaryfunc)wrapped;
4441 PyObject *other;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004442
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004443 if (!check_num_args(args, 1))
4444 return NULL;
4445 other = PyTuple_GET_ITEM(args, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004446 return (*func)(other, self);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004447}
4448
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004449static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00004450wrap_ternaryfunc(PyObject *self, PyObject *args, void *wrapped)
4451{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004452 ternaryfunc func = (ternaryfunc)wrapped;
4453 PyObject *other;
4454 PyObject *third = Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004455
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004456 /* Note: This wrapper only works for __pow__() */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004457
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004458 if (!PyArg_UnpackTuple(args, "", 1, 2, &other, &third))
4459 return NULL;
4460 return (*func)(self, other, third);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004461}
4462
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00004463static PyObject *
4464wrap_ternaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
4465{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004466 ternaryfunc func = (ternaryfunc)wrapped;
4467 PyObject *other;
4468 PyObject *third = Py_None;
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00004469
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004470 /* Note: This wrapper only works for __pow__() */
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00004471
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004472 if (!PyArg_UnpackTuple(args, "", 1, 2, &other, &third))
4473 return NULL;
4474 return (*func)(other, self, third);
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00004475}
4476
Tim Peters6d6c1a32001-08-02 04:15:00 +00004477static PyObject *
4478wrap_unaryfunc(PyObject *self, PyObject *args, void *wrapped)
4479{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004480 unaryfunc func = (unaryfunc)wrapped;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004481
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004482 if (!check_num_args(args, 0))
4483 return NULL;
4484 return (*func)(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004485}
4486
Tim Peters6d6c1a32001-08-02 04:15:00 +00004487static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004488wrap_indexargfunc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004489{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004490 ssizeargfunc func = (ssizeargfunc)wrapped;
4491 PyObject* o;
4492 Py_ssize_t i;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004493
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004494 if (!PyArg_UnpackTuple(args, "", 1, 1, &o))
4495 return NULL;
4496 i = PyNumber_AsSsize_t(o, PyExc_OverflowError);
4497 if (i == -1 && PyErr_Occurred())
4498 return NULL;
4499 return (*func)(self, i);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004500}
4501
Martin v. Löwis18e16552006-02-15 17:27:45 +00004502static Py_ssize_t
Guido van Rossum5d815f32001-08-17 21:57:47 +00004503getindex(PyObject *self, PyObject *arg)
4504{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004505 Py_ssize_t i;
Guido van Rossum5d815f32001-08-17 21:57:47 +00004506
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004507 i = PyNumber_AsSsize_t(arg, PyExc_OverflowError);
4508 if (i == -1 && PyErr_Occurred())
4509 return -1;
4510 if (i < 0) {
4511 PySequenceMethods *sq = Py_TYPE(self)->tp_as_sequence;
4512 if (sq && sq->sq_length) {
4513 Py_ssize_t n = (*sq->sq_length)(self);
4514 if (n < 0)
4515 return -1;
4516 i += n;
4517 }
4518 }
4519 return i;
Guido van Rossum5d815f32001-08-17 21:57:47 +00004520}
4521
4522static PyObject *
4523wrap_sq_item(PyObject *self, PyObject *args, void *wrapped)
4524{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004525 ssizeargfunc func = (ssizeargfunc)wrapped;
4526 PyObject *arg;
4527 Py_ssize_t i;
Guido van Rossum5d815f32001-08-17 21:57:47 +00004528
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004529 if (PyTuple_GET_SIZE(args) == 1) {
4530 arg = PyTuple_GET_ITEM(args, 0);
4531 i = getindex(self, arg);
4532 if (i == -1 && PyErr_Occurred())
4533 return NULL;
4534 return (*func)(self, i);
4535 }
4536 check_num_args(args, 1);
4537 assert(PyErr_Occurred());
4538 return NULL;
Guido van Rossum5d815f32001-08-17 21:57:47 +00004539}
4540
Tim Peters6d6c1a32001-08-02 04:15:00 +00004541static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00004542wrap_sq_setitem(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004543{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004544 ssizeobjargproc func = (ssizeobjargproc)wrapped;
4545 Py_ssize_t i;
4546 int res;
4547 PyObject *arg, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004548
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004549 if (!PyArg_UnpackTuple(args, "", 2, 2, &arg, &value))
4550 return NULL;
4551 i = getindex(self, arg);
4552 if (i == -1 && PyErr_Occurred())
4553 return NULL;
4554 res = (*func)(self, i, value);
4555 if (res == -1 && PyErr_Occurred())
4556 return NULL;
4557 Py_INCREF(Py_None);
4558 return Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004559}
4560
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004561static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00004562wrap_sq_delitem(PyObject *self, PyObject *args, void *wrapped)
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004563{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004564 ssizeobjargproc func = (ssizeobjargproc)wrapped;
4565 Py_ssize_t i;
4566 int res;
4567 PyObject *arg;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004568
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004569 if (!check_num_args(args, 1))
4570 return NULL;
4571 arg = PyTuple_GET_ITEM(args, 0);
4572 i = getindex(self, arg);
4573 if (i == -1 && PyErr_Occurred())
4574 return NULL;
4575 res = (*func)(self, i, NULL);
4576 if (res == -1 && PyErr_Occurred())
4577 return NULL;
4578 Py_INCREF(Py_None);
4579 return Py_None;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004580}
4581
Tim Peters6d6c1a32001-08-02 04:15:00 +00004582/* XXX objobjproc is a misnomer; should be objargpred */
4583static PyObject *
4584wrap_objobjproc(PyObject *self, PyObject *args, void *wrapped)
4585{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004586 objobjproc func = (objobjproc)wrapped;
4587 int res;
4588 PyObject *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004589
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004590 if (!check_num_args(args, 1))
4591 return NULL;
4592 value = PyTuple_GET_ITEM(args, 0);
4593 res = (*func)(self, value);
4594 if (res == -1 && PyErr_Occurred())
4595 return NULL;
4596 else
4597 return PyBool_FromLong(res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004598}
4599
Tim Peters6d6c1a32001-08-02 04:15:00 +00004600static PyObject *
4601wrap_objobjargproc(PyObject *self, PyObject *args, void *wrapped)
4602{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004603 objobjargproc func = (objobjargproc)wrapped;
4604 int res;
4605 PyObject *key, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004606
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004607 if (!PyArg_UnpackTuple(args, "", 2, 2, &key, &value))
4608 return NULL;
4609 res = (*func)(self, key, value);
4610 if (res == -1 && PyErr_Occurred())
4611 return NULL;
4612 Py_INCREF(Py_None);
4613 return Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004614}
4615
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004616static PyObject *
4617wrap_delitem(PyObject *self, PyObject *args, void *wrapped)
4618{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004619 objobjargproc func = (objobjargproc)wrapped;
4620 int res;
4621 PyObject *key;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004622
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004623 if (!check_num_args(args, 1))
4624 return NULL;
4625 key = PyTuple_GET_ITEM(args, 0);
4626 res = (*func)(self, key, NULL);
4627 if (res == -1 && PyErr_Occurred())
4628 return NULL;
4629 Py_INCREF(Py_None);
4630 return Py_None;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004631}
4632
Guido van Rossum4dcdb782003-04-14 21:46:03 +00004633/* Helper to check for object.__setattr__ or __delattr__ applied to a type.
Guido van Rossum52b27052003-04-15 20:05:10 +00004634 This is called the Carlo Verre hack after its discoverer. */
Guido van Rossum4dcdb782003-04-14 21:46:03 +00004635static int
4636hackcheck(PyObject *self, setattrofunc func, char *what)
4637{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004638 PyTypeObject *type = Py_TYPE(self);
4639 while (type && type->tp_flags & Py_TPFLAGS_HEAPTYPE)
4640 type = type->tp_base;
4641 /* If type is NULL now, this is a really weird type.
4642 In the spirit of backwards compatibility (?), just shut up. */
4643 if (type && type->tp_setattro != func) {
4644 PyErr_Format(PyExc_TypeError,
4645 "can't apply this %s to %s object",
4646 what,
4647 type->tp_name);
4648 return 0;
4649 }
4650 return 1;
Guido van Rossum4dcdb782003-04-14 21:46:03 +00004651}
4652
Tim Peters6d6c1a32001-08-02 04:15:00 +00004653static PyObject *
4654wrap_setattr(PyObject *self, PyObject *args, void *wrapped)
4655{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004656 setattrofunc func = (setattrofunc)wrapped;
4657 int res;
4658 PyObject *name, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004659
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004660 if (!PyArg_UnpackTuple(args, "", 2, 2, &name, &value))
4661 return NULL;
4662 if (!hackcheck(self, func, "__setattr__"))
4663 return NULL;
4664 res = (*func)(self, name, value);
4665 if (res < 0)
4666 return NULL;
4667 Py_INCREF(Py_None);
4668 return Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004669}
4670
4671static PyObject *
4672wrap_delattr(PyObject *self, PyObject *args, void *wrapped)
4673{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004674 setattrofunc func = (setattrofunc)wrapped;
4675 int res;
4676 PyObject *name;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004677
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004678 if (!check_num_args(args, 1))
4679 return NULL;
4680 name = PyTuple_GET_ITEM(args, 0);
4681 if (!hackcheck(self, func, "__delattr__"))
4682 return NULL;
4683 res = (*func)(self, name, NULL);
4684 if (res < 0)
4685 return NULL;
4686 Py_INCREF(Py_None);
4687 return Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004688}
4689
Tim Peters6d6c1a32001-08-02 04:15:00 +00004690static PyObject *
4691wrap_hashfunc(PyObject *self, PyObject *args, void *wrapped)
4692{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004693 hashfunc func = (hashfunc)wrapped;
Benjamin Peterson8035bc52010-10-23 16:20:50 +00004694 Py_hash_t res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004695
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004696 if (!check_num_args(args, 0))
4697 return NULL;
4698 res = (*func)(self);
4699 if (res == -1 && PyErr_Occurred())
4700 return NULL;
Benjamin Peterson8035bc52010-10-23 16:20:50 +00004701 return PyLong_FromSsize_t(res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004702}
4703
Tim Peters6d6c1a32001-08-02 04:15:00 +00004704static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00004705wrap_call(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004706{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004707 ternaryfunc func = (ternaryfunc)wrapped;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004708
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004709 return (*func)(self, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004710}
4711
Tim Peters6d6c1a32001-08-02 04:15:00 +00004712static PyObject *
4713wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op)
4714{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004715 richcmpfunc func = (richcmpfunc)wrapped;
4716 PyObject *other;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004717
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004718 if (!check_num_args(args, 1))
4719 return NULL;
4720 other = PyTuple_GET_ITEM(args, 0);
4721 return (*func)(self, other, op);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004722}
4723
4724#undef RICHCMP_WRAPPER
4725#define RICHCMP_WRAPPER(NAME, OP) \
4726static PyObject * \
4727richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \
4728{ \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004729 return wrap_richcmpfunc(self, args, wrapped, OP); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004730}
4731
Jack Jansen8e938b42001-08-08 15:29:49 +00004732RICHCMP_WRAPPER(lt, Py_LT)
4733RICHCMP_WRAPPER(le, Py_LE)
4734RICHCMP_WRAPPER(eq, Py_EQ)
4735RICHCMP_WRAPPER(ne, Py_NE)
4736RICHCMP_WRAPPER(gt, Py_GT)
4737RICHCMP_WRAPPER(ge, Py_GE)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004738
Tim Peters6d6c1a32001-08-02 04:15:00 +00004739static PyObject *
4740wrap_next(PyObject *self, PyObject *args, void *wrapped)
4741{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004742 unaryfunc func = (unaryfunc)wrapped;
4743 PyObject *res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004744
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004745 if (!check_num_args(args, 0))
4746 return NULL;
4747 res = (*func)(self);
4748 if (res == NULL && !PyErr_Occurred())
4749 PyErr_SetNone(PyExc_StopIteration);
4750 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004751}
4752
Tim Peters6d6c1a32001-08-02 04:15:00 +00004753static PyObject *
4754wrap_descr_get(PyObject *self, PyObject *args, void *wrapped)
4755{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004756 descrgetfunc func = (descrgetfunc)wrapped;
4757 PyObject *obj;
4758 PyObject *type = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004759
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004760 if (!PyArg_UnpackTuple(args, "", 1, 2, &obj, &type))
4761 return NULL;
4762 if (obj == Py_None)
4763 obj = NULL;
4764 if (type == Py_None)
4765 type = NULL;
4766 if (type == NULL &&obj == NULL) {
4767 PyErr_SetString(PyExc_TypeError,
4768 "__get__(None, None) is invalid");
4769 return NULL;
4770 }
4771 return (*func)(self, obj, type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004772}
4773
Tim Peters6d6c1a32001-08-02 04:15:00 +00004774static PyObject *
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004775wrap_descr_set(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004776{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004777 descrsetfunc func = (descrsetfunc)wrapped;
4778 PyObject *obj, *value;
4779 int ret;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004780
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004781 if (!PyArg_UnpackTuple(args, "", 2, 2, &obj, &value))
4782 return NULL;
4783 ret = (*func)(self, obj, value);
4784 if (ret < 0)
4785 return NULL;
4786 Py_INCREF(Py_None);
4787 return Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004788}
Guido van Rossum22b13872002-08-06 21:41:44 +00004789
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00004790static PyObject *
4791wrap_descr_delete(PyObject *self, PyObject *args, void *wrapped)
4792{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004793 descrsetfunc func = (descrsetfunc)wrapped;
4794 PyObject *obj;
4795 int ret;
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00004796
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004797 if (!check_num_args(args, 1))
4798 return NULL;
4799 obj = PyTuple_GET_ITEM(args, 0);
4800 ret = (*func)(self, obj, NULL);
4801 if (ret < 0)
4802 return NULL;
4803 Py_INCREF(Py_None);
4804 return Py_None;
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00004805}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004806
Tim Peters6d6c1a32001-08-02 04:15:00 +00004807static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00004808wrap_init(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004809{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004810 initproc func = (initproc)wrapped;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004811
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004812 if (func(self, args, kwds) < 0)
4813 return NULL;
4814 Py_INCREF(Py_None);
4815 return Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004816}
4817
Tim Peters6d6c1a32001-08-02 04:15:00 +00004818static PyObject *
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004819tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004820{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004821 PyTypeObject *type, *subtype, *staticbase;
4822 PyObject *arg0, *res;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004823
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004824 if (self == NULL || !PyType_Check(self))
4825 Py_FatalError("__new__() called with non-type 'self'");
4826 type = (PyTypeObject *)self;
4827 if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) {
4828 PyErr_Format(PyExc_TypeError,
4829 "%s.__new__(): not enough arguments",
4830 type->tp_name);
4831 return NULL;
4832 }
4833 arg0 = PyTuple_GET_ITEM(args, 0);
4834 if (!PyType_Check(arg0)) {
4835 PyErr_Format(PyExc_TypeError,
4836 "%s.__new__(X): X is not a type object (%s)",
4837 type->tp_name,
4838 Py_TYPE(arg0)->tp_name);
4839 return NULL;
4840 }
4841 subtype = (PyTypeObject *)arg0;
4842 if (!PyType_IsSubtype(subtype, type)) {
4843 PyErr_Format(PyExc_TypeError,
4844 "%s.__new__(%s): %s is not a subtype of %s",
4845 type->tp_name,
4846 subtype->tp_name,
4847 subtype->tp_name,
4848 type->tp_name);
4849 return NULL;
4850 }
Barry Warsaw60f01882001-08-22 19:24:42 +00004851
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004852 /* Check that the use doesn't do something silly and unsafe like
4853 object.__new__(dict). To do this, we check that the
4854 most derived base that's not a heap type is this type. */
4855 staticbase = subtype;
Martin v. Löwis9c564092012-06-23 23:20:45 +02004856 while (staticbase && (staticbase->tp_new == slot_tp_new))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004857 staticbase = staticbase->tp_base;
4858 /* If staticbase is NULL now, it is a really weird type.
4859 In the spirit of backwards compatibility (?), just shut up. */
4860 if (staticbase && staticbase->tp_new != type->tp_new) {
4861 PyErr_Format(PyExc_TypeError,
4862 "%s.__new__(%s) is not safe, use %s.__new__()",
4863 type->tp_name,
4864 subtype->tp_name,
4865 staticbase == NULL ? "?" : staticbase->tp_name);
4866 return NULL;
4867 }
Barry Warsaw60f01882001-08-22 19:24:42 +00004868
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004869 args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
4870 if (args == NULL)
4871 return NULL;
4872 res = type->tp_new(subtype, args, kwds);
4873 Py_DECREF(args);
4874 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004875}
4876
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004877static struct PyMethodDef tp_new_methoddef[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004878 {"__new__", (PyCFunction)tp_new_wrapper, METH_VARARGS|METH_KEYWORDS,
4879 PyDoc_STR("T.__new__(S, ...) -> "
4880 "a new object with type S, a subtype of T")},
4881 {0}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004882};
4883
4884static int
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004885add_tp_new_wrapper(PyTypeObject *type)
4886{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004887 PyObject *func;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004888
Victor Stinner3c1e4812012-03-26 22:10:51 +02004889 if (_PyDict_GetItemId(type->tp_dict, &PyId___new__) != NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004890 return 0;
4891 func = PyCFunction_New(tp_new_methoddef, (PyObject *)type);
4892 if (func == NULL)
4893 return -1;
Victor Stinner3c1e4812012-03-26 22:10:51 +02004894 if (_PyDict_SetItemId(type->tp_dict, &PyId___new__, func)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004895 Py_DECREF(func);
4896 return -1;
4897 }
4898 Py_DECREF(func);
4899 return 0;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004900}
4901
Guido van Rossumf040ede2001-08-07 16:40:56 +00004902/* Slot wrappers that call the corresponding __foo__ slot. See comments
4903 below at override_slots() for more explanation. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004904
Guido van Rossumdc91b992001-08-08 22:26:22 +00004905#define SLOT0(FUNCNAME, OPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004906static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004907FUNCNAME(PyObject *self) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004908{ \
Benjamin Petersonce798522012-01-22 11:24:29 -05004909 _Py_static_string(id, OPSTR); \
4910 return call_method(self, &id, "()"); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004911}
4912
Guido van Rossumdc91b992001-08-08 22:26:22 +00004913#define SLOT1(FUNCNAME, OPSTR, ARG1TYPE, ARGCODES) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004914static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004915FUNCNAME(PyObject *self, ARG1TYPE arg1) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004916{ \
Benjamin Petersonce798522012-01-22 11:24:29 -05004917 _Py_static_string(id, OPSTR); \
4918 return call_method(self, &id, "(" ARGCODES ")", arg1); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004919}
4920
Guido van Rossumcd118802003-01-06 22:57:47 +00004921/* Boolean helper for SLOT1BINFULL().
4922 right.__class__ is a nontrivial subclass of left.__class__. */
4923static int
Victor Stinner3c1e4812012-03-26 22:10:51 +02004924method_is_overloaded(PyObject *left, PyObject *right, struct _Py_Identifier *name)
Guido van Rossumcd118802003-01-06 22:57:47 +00004925{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004926 PyObject *a, *b;
4927 int ok;
Guido van Rossumcd118802003-01-06 22:57:47 +00004928
Victor Stinner3c1e4812012-03-26 22:10:51 +02004929 b = _PyObject_GetAttrId((PyObject *)(Py_TYPE(right)), name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004930 if (b == NULL) {
4931 PyErr_Clear();
4932 /* If right doesn't have it, it's not overloaded */
4933 return 0;
4934 }
Guido van Rossumcd118802003-01-06 22:57:47 +00004935
Victor Stinner3c1e4812012-03-26 22:10:51 +02004936 a = _PyObject_GetAttrId((PyObject *)(Py_TYPE(left)), name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004937 if (a == NULL) {
4938 PyErr_Clear();
4939 Py_DECREF(b);
4940 /* If right has it but left doesn't, it's overloaded */
4941 return 1;
4942 }
Guido van Rossumcd118802003-01-06 22:57:47 +00004943
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004944 ok = PyObject_RichCompareBool(a, b, Py_NE);
4945 Py_DECREF(a);
4946 Py_DECREF(b);
4947 if (ok < 0) {
4948 PyErr_Clear();
4949 return 0;
4950 }
Guido van Rossumcd118802003-01-06 22:57:47 +00004951
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004952 return ok;
Guido van Rossumcd118802003-01-06 22:57:47 +00004953}
4954
Guido van Rossumdc91b992001-08-08 22:26:22 +00004955
4956#define SLOT1BINFULL(FUNCNAME, TESTFUNC, SLOTNAME, OPSTR, ROPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004957static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004958FUNCNAME(PyObject *self, PyObject *other) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004959{ \
Benjamin Petersonce798522012-01-22 11:24:29 -05004960 _Py_static_string(op_id, OPSTR); \
4961 _Py_static_string(rop_id, ROPSTR); \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004962 int do_other = Py_TYPE(self) != Py_TYPE(other) && \
4963 Py_TYPE(other)->tp_as_number != NULL && \
4964 Py_TYPE(other)->tp_as_number->SLOTNAME == TESTFUNC; \
4965 if (Py_TYPE(self)->tp_as_number != NULL && \
4966 Py_TYPE(self)->tp_as_number->SLOTNAME == TESTFUNC) { \
4967 PyObject *r; \
4968 if (do_other && \
4969 PyType_IsSubtype(Py_TYPE(other), Py_TYPE(self)) && \
Victor Stinner3c1e4812012-03-26 22:10:51 +02004970 method_is_overloaded(self, other, &rop_id)) { \
Benjamin Petersonce798522012-01-22 11:24:29 -05004971 r = call_maybe(other, &rop_id, "(O)", self); \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004972 if (r != Py_NotImplemented) \
4973 return r; \
4974 Py_DECREF(r); \
4975 do_other = 0; \
4976 } \
Benjamin Petersonce798522012-01-22 11:24:29 -05004977 r = call_maybe(self, &op_id, "(O)", other); \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004978 if (r != Py_NotImplemented || \
4979 Py_TYPE(other) == Py_TYPE(self)) \
4980 return r; \
4981 Py_DECREF(r); \
4982 } \
4983 if (do_other) { \
Benjamin Petersonce798522012-01-22 11:24:29 -05004984 return call_maybe(other, &rop_id, "(O)", self); \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004985 } \
Brian Curtindfc80e32011-08-10 20:28:54 -05004986 Py_RETURN_NOTIMPLEMENTED; \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004987}
4988
4989#define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004990 SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR)
Guido van Rossumdc91b992001-08-08 22:26:22 +00004991
4992#define SLOT2(FUNCNAME, OPSTR, ARG1TYPE, ARG2TYPE, ARGCODES) \
4993static PyObject * \
4994FUNCNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \
4995{ \
Benjamin Petersonce798522012-01-22 11:24:29 -05004996 _Py_static_string(id, #OPSTR); \
4997 return call_method(self, &id, "(" ARGCODES ")", arg1, arg2); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004998}
4999
Martin v. Löwis18e16552006-02-15 17:27:45 +00005000static Py_ssize_t
Tim Peters6d6c1a32001-08-02 04:15:00 +00005001slot_sq_length(PyObject *self)
5002{
Benjamin Petersonce798522012-01-22 11:24:29 -05005003 _Py_IDENTIFIER(__len__);
5004 PyObject *res = call_method(self, &PyId___len__, "()");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005005 Py_ssize_t len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005006
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005007 if (res == NULL)
5008 return -1;
5009 len = PyNumber_AsSsize_t(res, PyExc_OverflowError);
5010 Py_DECREF(res);
5011 if (len < 0) {
5012 if (!PyErr_Occurred())
5013 PyErr_SetString(PyExc_ValueError,
5014 "__len__() should return >= 0");
5015 return -1;
5016 }
5017 return len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005018}
5019
Guido van Rossumf4593e02001-10-03 12:09:30 +00005020/* Super-optimized version of slot_sq_item.
5021 Other slots could do the same... */
5022static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00005023slot_sq_item(PyObject *self, Py_ssize_t i)
Guido van Rossumf4593e02001-10-03 12:09:30 +00005024{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005025 PyObject *func, *args = NULL, *ival = NULL, *retval = NULL;
5026 descrgetfunc f;
Guido van Rossumf4593e02001-10-03 12:09:30 +00005027
Victor Stinner3c1e4812012-03-26 22:10:51 +02005028 func = _PyType_LookupId(Py_TYPE(self), &PyId___getitem__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005029 if (func != NULL) {
5030 if ((f = Py_TYPE(func)->tp_descr_get) == NULL)
5031 Py_INCREF(func);
5032 else {
5033 func = f(func, self, (PyObject *)(Py_TYPE(self)));
5034 if (func == NULL) {
5035 return NULL;
5036 }
5037 }
5038 ival = PyLong_FromSsize_t(i);
5039 if (ival != NULL) {
5040 args = PyTuple_New(1);
5041 if (args != NULL) {
5042 PyTuple_SET_ITEM(args, 0, ival);
5043 retval = PyObject_Call(func, args, NULL);
5044 Py_XDECREF(args);
5045 Py_XDECREF(func);
5046 return retval;
5047 }
5048 }
5049 }
5050 else {
Victor Stinner3c1e4812012-03-26 22:10:51 +02005051 PyObject *getitem_str = _PyUnicode_FromId(&PyId___getitem__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005052 PyErr_SetObject(PyExc_AttributeError, getitem_str);
5053 }
5054 Py_XDECREF(args);
5055 Py_XDECREF(ival);
5056 Py_XDECREF(func);
5057 return NULL;
Guido van Rossumf4593e02001-10-03 12:09:30 +00005058}
5059
Tim Peters6d6c1a32001-08-02 04:15:00 +00005060static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00005061slot_sq_ass_item(PyObject *self, Py_ssize_t index, PyObject *value)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005062{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005063 PyObject *res;
Benjamin Petersonce798522012-01-22 11:24:29 -05005064 _Py_IDENTIFIER(__delitem__);
5065 _Py_IDENTIFIER(__setitem__);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005066
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005067 if (value == NULL)
Benjamin Petersonce798522012-01-22 11:24:29 -05005068 res = call_method(self, &PyId___delitem__, "(n)", index);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005069 else
Benjamin Petersonce798522012-01-22 11:24:29 -05005070 res = call_method(self, &PyId___setitem__, "(nO)", index, value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005071 if (res == NULL)
5072 return -1;
5073 Py_DECREF(res);
5074 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005075}
5076
5077static int
Tim Peters6d6c1a32001-08-02 04:15:00 +00005078slot_sq_contains(PyObject *self, PyObject *value)
5079{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005080 PyObject *func, *res, *args;
5081 int result = -1;
Benjamin Petersonce798522012-01-22 11:24:29 -05005082 _Py_IDENTIFIER(__contains__);
Tim Petersbf9b2442003-03-23 05:35:36 +00005083
Benjamin Petersonce798522012-01-22 11:24:29 -05005084 func = lookup_maybe(self, &PyId___contains__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005085 if (func != NULL) {
5086 args = PyTuple_Pack(1, value);
5087 if (args == NULL)
5088 res = NULL;
5089 else {
5090 res = PyObject_Call(func, args, NULL);
5091 Py_DECREF(args);
5092 }
5093 Py_DECREF(func);
5094 if (res != NULL) {
5095 result = PyObject_IsTrue(res);
5096 Py_DECREF(res);
5097 }
5098 }
5099 else if (! PyErr_Occurred()) {
5100 /* Possible results: -1 and 1 */
5101 result = (int)_PySequence_IterSearch(self, value,
5102 PY_ITERSEARCH_CONTAINS);
5103 }
5104 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005105}
5106
Tim Peters6d6c1a32001-08-02 04:15:00 +00005107#define slot_mp_length slot_sq_length
5108
Guido van Rossumdc91b992001-08-08 22:26:22 +00005109SLOT1(slot_mp_subscript, "__getitem__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00005110
5111static int
5112slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value)
5113{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005114 PyObject *res;
Benjamin Petersonce798522012-01-22 11:24:29 -05005115 _Py_IDENTIFIER(__delitem__);
5116 _Py_IDENTIFIER(__setitem__);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005117
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005118 if (value == NULL)
Benjamin Petersonce798522012-01-22 11:24:29 -05005119 res = call_method(self, &PyId___delitem__, "(O)", key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005120 else
Benjamin Petersonce798522012-01-22 11:24:29 -05005121 res = call_method(self, &PyId___setitem__, "(OO)", key, value);
5122
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005123 if (res == NULL)
5124 return -1;
5125 Py_DECREF(res);
5126 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005127}
5128
Guido van Rossumdc91b992001-08-08 22:26:22 +00005129SLOT1BIN(slot_nb_add, nb_add, "__add__", "__radd__")
5130SLOT1BIN(slot_nb_subtract, nb_subtract, "__sub__", "__rsub__")
5131SLOT1BIN(slot_nb_multiply, nb_multiply, "__mul__", "__rmul__")
Guido van Rossumdc91b992001-08-08 22:26:22 +00005132SLOT1BIN(slot_nb_remainder, nb_remainder, "__mod__", "__rmod__")
5133SLOT1BIN(slot_nb_divmod, nb_divmod, "__divmod__", "__rdivmod__")
5134
Jeremy Hylton938ace62002-07-17 16:30:39 +00005135static PyObject *slot_nb_power(PyObject *, PyObject *, PyObject *);
Guido van Rossumdc91b992001-08-08 22:26:22 +00005136
5137SLOT1BINFULL(slot_nb_power_binary, slot_nb_power,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005138 nb_power, "__pow__", "__rpow__")
Guido van Rossumdc91b992001-08-08 22:26:22 +00005139
5140static PyObject *
5141slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus)
5142{
Benjamin Petersonce798522012-01-22 11:24:29 -05005143 _Py_IDENTIFIER(__pow__);
Guido van Rossum2730b132001-08-28 18:22:14 +00005144
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005145 if (modulus == Py_None)
5146 return slot_nb_power_binary(self, other);
5147 /* Three-arg power doesn't use __rpow__. But ternary_op
5148 can call this when the second argument's type uses
5149 slot_nb_power, so check before calling self.__pow__. */
5150 if (Py_TYPE(self)->tp_as_number != NULL &&
5151 Py_TYPE(self)->tp_as_number->nb_power == slot_nb_power) {
Benjamin Petersonce798522012-01-22 11:24:29 -05005152 return call_method(self, &PyId___pow__, "(OO)", other, modulus);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005153 }
Brian Curtindfc80e32011-08-10 20:28:54 -05005154 Py_RETURN_NOTIMPLEMENTED;
Guido van Rossumdc91b992001-08-08 22:26:22 +00005155}
5156
5157SLOT0(slot_nb_negative, "__neg__")
5158SLOT0(slot_nb_positive, "__pos__")
5159SLOT0(slot_nb_absolute, "__abs__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00005160
5161static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00005162slot_nb_bool(PyObject *self)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005163{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005164 PyObject *func, *args;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005165 int result = -1;
5166 int using_len = 0;
Benjamin Petersonce798522012-01-22 11:24:29 -05005167 _Py_IDENTIFIER(__len__);
5168 _Py_IDENTIFIER(__bool__);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005169
Benjamin Petersonce798522012-01-22 11:24:29 -05005170 func = lookup_maybe(self, &PyId___bool__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005171 if (func == NULL) {
5172 if (PyErr_Occurred())
5173 return -1;
Benjamin Petersonce798522012-01-22 11:24:29 -05005174 func = lookup_maybe(self, &PyId___len__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005175 if (func == NULL)
5176 return PyErr_Occurred() ? -1 : 1;
5177 using_len = 1;
5178 }
5179 args = PyTuple_New(0);
5180 if (args != NULL) {
5181 PyObject *temp = PyObject_Call(func, args, NULL);
5182 Py_DECREF(args);
5183 if (temp != NULL) {
5184 if (using_len) {
5185 /* enforced by slot_nb_len */
5186 result = PyObject_IsTrue(temp);
5187 }
5188 else if (PyBool_Check(temp)) {
5189 result = PyObject_IsTrue(temp);
5190 }
5191 else {
5192 PyErr_Format(PyExc_TypeError,
5193 "__bool__ should return "
5194 "bool, returned %s",
5195 Py_TYPE(temp)->tp_name);
5196 result = -1;
5197 }
5198 Py_DECREF(temp);
5199 }
5200 }
5201 Py_DECREF(func);
5202 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005203}
5204
Guido van Rossum38fff8c2006-03-07 18:50:55 +00005205
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00005206static PyObject *
Guido van Rossum38fff8c2006-03-07 18:50:55 +00005207slot_nb_index(PyObject *self)
5208{
Benjamin Petersonce798522012-01-22 11:24:29 -05005209 _Py_IDENTIFIER(__index__);
5210 return call_method(self, &PyId___index__, "()");
Guido van Rossum38fff8c2006-03-07 18:50:55 +00005211}
5212
5213
Guido van Rossumdc91b992001-08-08 22:26:22 +00005214SLOT0(slot_nb_invert, "__invert__")
5215SLOT1BIN(slot_nb_lshift, nb_lshift, "__lshift__", "__rlshift__")
5216SLOT1BIN(slot_nb_rshift, nb_rshift, "__rshift__", "__rrshift__")
5217SLOT1BIN(slot_nb_and, nb_and, "__and__", "__rand__")
5218SLOT1BIN(slot_nb_xor, nb_xor, "__xor__", "__rxor__")
5219SLOT1BIN(slot_nb_or, nb_or, "__or__", "__ror__")
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00005220
Guido van Rossumdc91b992001-08-08 22:26:22 +00005221SLOT0(slot_nb_int, "__int__")
Guido van Rossumdc91b992001-08-08 22:26:22 +00005222SLOT0(slot_nb_float, "__float__")
Guido van Rossumdc91b992001-08-08 22:26:22 +00005223SLOT1(slot_nb_inplace_add, "__iadd__", PyObject *, "O")
5224SLOT1(slot_nb_inplace_subtract, "__isub__", PyObject *, "O")
5225SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *, "O")
Guido van Rossumdc91b992001-08-08 22:26:22 +00005226SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *, "O")
Thomas Wouterscf297e42007-02-23 15:07:44 +00005227/* Can't use SLOT1 here, because nb_inplace_power is ternary */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005228static PyObject *
5229slot_nb_inplace_power(PyObject *self, PyObject * arg1, PyObject *arg2)
5230{
Benjamin Petersonce798522012-01-22 11:24:29 -05005231 _Py_IDENTIFIER(__ipow__);
5232 return call_method(self, &PyId___ipow__, "(" "O" ")", arg1);
Thomas Wouterscf297e42007-02-23 15:07:44 +00005233}
Guido van Rossumdc91b992001-08-08 22:26:22 +00005234SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *, "O")
5235SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *, "O")
5236SLOT1(slot_nb_inplace_and, "__iand__", PyObject *, "O")
5237SLOT1(slot_nb_inplace_xor, "__ixor__", PyObject *, "O")
5238SLOT1(slot_nb_inplace_or, "__ior__", PyObject *, "O")
5239SLOT1BIN(slot_nb_floor_divide, nb_floor_divide,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005240 "__floordiv__", "__rfloordiv__")
Guido van Rossumdc91b992001-08-08 22:26:22 +00005241SLOT1BIN(slot_nb_true_divide, nb_true_divide, "__truediv__", "__rtruediv__")
5242SLOT1(slot_nb_inplace_floor_divide, "__ifloordiv__", PyObject *, "O")
5243SLOT1(slot_nb_inplace_true_divide, "__itruediv__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00005244
Guido van Rossumb8f63662001-08-15 23:57:02 +00005245static PyObject *
5246slot_tp_repr(PyObject *self)
5247{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005248 PyObject *func, *res;
Benjamin Petersonce798522012-01-22 11:24:29 -05005249 _Py_IDENTIFIER(__repr__);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005250
Benjamin Petersonce798522012-01-22 11:24:29 -05005251 func = lookup_method(self, &PyId___repr__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005252 if (func != NULL) {
5253 res = PyEval_CallObject(func, NULL);
5254 Py_DECREF(func);
5255 return res;
5256 }
5257 PyErr_Clear();
5258 return PyUnicode_FromFormat("<%s object at %p>",
5259 Py_TYPE(self)->tp_name, self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005260}
5261
5262static PyObject *
5263slot_tp_str(PyObject *self)
5264{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005265 PyObject *func, *res;
Benjamin Petersonce798522012-01-22 11:24:29 -05005266 _Py_IDENTIFIER(__str__);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005267
Benjamin Petersonce798522012-01-22 11:24:29 -05005268 func = lookup_method(self, &PyId___str__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005269 if (func != NULL) {
5270 res = PyEval_CallObject(func, NULL);
5271 Py_DECREF(func);
5272 return res;
5273 }
5274 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005275 /* PyObject *ress; */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005276 PyErr_Clear();
5277 res = slot_tp_repr(self);
5278 if (!res)
5279 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005280 /* XXX this is non-sensical. Why should we return
5281 a bytes object from __str__. Is this code even
5282 used? - mvl */
5283 assert(0);
5284 return res;
5285 /*
Victor Stinnerf3fd7332011-03-02 01:03:11 +00005286 ress = _PyUnicode_AsDefaultEncodedString(res);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005287 Py_DECREF(res);
5288 return ress;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005289 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005290 }
Guido van Rossumb8f63662001-08-15 23:57:02 +00005291}
Tim Peters6d6c1a32001-08-02 04:15:00 +00005292
Benjamin Peterson8f67d082010-10-17 20:54:53 +00005293static Py_hash_t
Tim Peters6d6c1a32001-08-02 04:15:00 +00005294slot_tp_hash(PyObject *self)
5295{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005296 PyObject *func, *res;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00005297 Py_ssize_t h;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005298
Benjamin Petersonce798522012-01-22 11:24:29 -05005299 func = lookup_method(self, &PyId___hash__);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005300
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005301 if (func == Py_None) {
5302 Py_DECREF(func);
5303 func = NULL;
5304 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +00005305
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005306 if (func == NULL) {
5307 return PyObject_HashNotImplemented(self);
5308 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +00005309
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005310 res = PyEval_CallObject(func, NULL);
5311 Py_DECREF(func);
5312 if (res == NULL)
5313 return -1;
Mark Dickinsondc787d22010-05-23 13:33:13 +00005314
5315 if (!PyLong_Check(res)) {
5316 PyErr_SetString(PyExc_TypeError,
5317 "__hash__ method should return an integer");
5318 return -1;
5319 }
Benjamin Peterson8f67d082010-10-17 20:54:53 +00005320 /* Transform the PyLong `res` to a Py_hash_t `h`. For an existing
5321 hashable Python object x, hash(x) will always lie within the range of
5322 Py_hash_t. Therefore our transformation must preserve values that
5323 already lie within this range, to ensure that if x.__hash__() returns
5324 hash(y) then hash(x) == hash(y). */
5325 h = PyLong_AsSsize_t(res);
5326 if (h == -1 && PyErr_Occurred()) {
5327 /* res was not within the range of a Py_hash_t, so we're free to
Mark Dickinsondc787d22010-05-23 13:33:13 +00005328 use any sufficiently bit-mixing transformation;
5329 long.__hash__ will do nicely. */
Benjamin Peterson8f67d082010-10-17 20:54:53 +00005330 PyErr_Clear();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005331 h = PyLong_Type.tp_hash(res);
Benjamin Peterson8f67d082010-10-17 20:54:53 +00005332 }
Benjamin Petersone7dfeeb2010-10-17 21:27:01 +00005333 /* -1 is reserved for errors. */
5334 if (h == -1)
5335 h = -2;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005336 Py_DECREF(res);
Mark Dickinsondc787d22010-05-23 13:33:13 +00005337 return h;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005338}
5339
5340static PyObject *
5341slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds)
5342{
Benjamin Petersonce798522012-01-22 11:24:29 -05005343 _Py_IDENTIFIER(__call__);
5344 PyObject *meth = lookup_method(self, &PyId___call__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005345 PyObject *res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005346
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005347 if (meth == NULL)
5348 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005349
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005350 res = PyObject_Call(meth, args, kwds);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005351
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005352 Py_DECREF(meth);
5353 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005354}
5355
Guido van Rossum14a6f832001-10-17 13:59:09 +00005356/* There are two slot dispatch functions for tp_getattro.
5357
5358 - slot_tp_getattro() is used when __getattribute__ is overridden
5359 but no __getattr__ hook is present;
5360
5361 - slot_tp_getattr_hook() is used when a __getattr__ hook is present.
5362
Guido van Rossumc334df52002-04-04 23:44:47 +00005363 The code in update_one_slot() always installs slot_tp_getattr_hook(); this
5364 detects the absence of __getattr__ and then installs the simpler slot if
5365 necessary. */
Guido van Rossum14a6f832001-10-17 13:59:09 +00005366
Tim Peters6d6c1a32001-08-02 04:15:00 +00005367static PyObject *
5368slot_tp_getattro(PyObject *self, PyObject *name)
5369{
Benjamin Petersonce798522012-01-22 11:24:29 -05005370 return call_method(self, &PyId___getattribute__, "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005371}
5372
Guido van Rossum19c1cd52001-09-21 21:24:49 +00005373static PyObject *
Benjamin Peterson9262b842008-11-17 22:45:50 +00005374call_attribute(PyObject *self, PyObject *attr, PyObject *name)
5375{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005376 PyObject *res, *descr = NULL;
5377 descrgetfunc f = Py_TYPE(attr)->tp_descr_get;
Benjamin Peterson9262b842008-11-17 22:45:50 +00005378
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005379 if (f != NULL) {
5380 descr = f(attr, self, (PyObject *)(Py_TYPE(self)));
5381 if (descr == NULL)
5382 return NULL;
5383 else
5384 attr = descr;
5385 }
5386 res = PyObject_CallFunctionObjArgs(attr, name, NULL);
5387 Py_XDECREF(descr);
5388 return res;
Benjamin Peterson9262b842008-11-17 22:45:50 +00005389}
5390
5391static PyObject *
Guido van Rossum19c1cd52001-09-21 21:24:49 +00005392slot_tp_getattr_hook(PyObject *self, PyObject *name)
5393{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005394 PyTypeObject *tp = Py_TYPE(self);
5395 PyObject *getattr, *getattribute, *res;
Victor Stinner3c1e4812012-03-26 22:10:51 +02005396 _Py_IDENTIFIER(__getattr__);
Guido van Rossum19c1cd52001-09-21 21:24:49 +00005397
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005398 /* speed hack: we could use lookup_maybe, but that would resolve the
5399 method fully for each attribute lookup for classes with
5400 __getattr__, even when the attribute is present. So we use
5401 _PyType_Lookup and create the method only when needed, with
5402 call_attribute. */
Victor Stinner3c1e4812012-03-26 22:10:51 +02005403 getattr = _PyType_LookupId(tp, &PyId___getattr__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005404 if (getattr == NULL) {
5405 /* No __getattr__ hook: use a simpler dispatcher */
5406 tp->tp_getattro = slot_tp_getattro;
5407 return slot_tp_getattro(self, name);
5408 }
5409 Py_INCREF(getattr);
5410 /* speed hack: we could use lookup_maybe, but that would resolve the
5411 method fully for each attribute lookup for classes with
5412 __getattr__, even when self has the default __getattribute__
5413 method. So we use _PyType_Lookup and create the method only when
5414 needed, with call_attribute. */
Victor Stinner3c1e4812012-03-26 22:10:51 +02005415 getattribute = _PyType_LookupId(tp, &PyId___getattribute__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005416 if (getattribute == NULL ||
5417 (Py_TYPE(getattribute) == &PyWrapperDescr_Type &&
5418 ((PyWrapperDescrObject *)getattribute)->d_wrapped ==
5419 (void *)PyObject_GenericGetAttr))
5420 res = PyObject_GenericGetAttr(self, name);
5421 else {
5422 Py_INCREF(getattribute);
5423 res = call_attribute(self, getattribute, name);
5424 Py_DECREF(getattribute);
5425 }
5426 if (res == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) {
5427 PyErr_Clear();
5428 res = call_attribute(self, getattr, name);
5429 }
5430 Py_DECREF(getattr);
5431 return res;
Guido van Rossum19c1cd52001-09-21 21:24:49 +00005432}
5433
Tim Peters6d6c1a32001-08-02 04:15:00 +00005434static int
5435slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value)
5436{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005437 PyObject *res;
Benjamin Petersonce798522012-01-22 11:24:29 -05005438 _Py_IDENTIFIER(__delattr__);
5439 _Py_IDENTIFIER(__setattr__);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005440
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005441 if (value == NULL)
Benjamin Petersonce798522012-01-22 11:24:29 -05005442 res = call_method(self, &PyId___delattr__, "(O)", name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005443 else
Benjamin Petersonce798522012-01-22 11:24:29 -05005444 res = call_method(self, &PyId___setattr__, "(OO)", name, value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005445 if (res == NULL)
5446 return -1;
5447 Py_DECREF(res);
5448 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005449}
5450
Benjamin Petersonce798522012-01-22 11:24:29 -05005451static _Py_Identifier name_op[] = {
5452 {0, "__lt__", 0},
5453 {0, "__le__", 0},
5454 {0, "__eq__", 0},
5455 {0, "__ne__", 0},
5456 {0, "__gt__", 0},
5457 {0, "__ge__", 0}
Guido van Rossumf5243f02008-01-01 04:06:48 +00005458};
5459
Tim Peters6d6c1a32001-08-02 04:15:00 +00005460static PyObject *
Mark Dickinson6f1d0492009-11-15 13:58:49 +00005461slot_tp_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005462{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005463 PyObject *func, *args, *res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005464
Benjamin Petersonce798522012-01-22 11:24:29 -05005465 func = lookup_method(self, &name_op[op]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005466 if (func == NULL) {
5467 PyErr_Clear();
Brian Curtindfc80e32011-08-10 20:28:54 -05005468 Py_RETURN_NOTIMPLEMENTED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005469 }
5470 args = PyTuple_Pack(1, other);
5471 if (args == NULL)
5472 res = NULL;
5473 else {
5474 res = PyObject_Call(func, args, NULL);
5475 Py_DECREF(args);
5476 }
5477 Py_DECREF(func);
5478 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005479}
5480
Guido van Rossumb8f63662001-08-15 23:57:02 +00005481static PyObject *
Guido van Rossumb8f63662001-08-15 23:57:02 +00005482slot_tp_iter(PyObject *self)
5483{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005484 PyObject *func, *res;
Benjamin Petersonce798522012-01-22 11:24:29 -05005485 _Py_IDENTIFIER(__iter__);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005486
Benjamin Petersonce798522012-01-22 11:24:29 -05005487 func = lookup_method(self, &PyId___iter__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005488 if (func != NULL) {
5489 PyObject *args;
5490 args = res = PyTuple_New(0);
5491 if (args != NULL) {
5492 res = PyObject_Call(func, args, NULL);
5493 Py_DECREF(args);
5494 }
5495 Py_DECREF(func);
5496 return res;
5497 }
5498 PyErr_Clear();
Benjamin Petersonce798522012-01-22 11:24:29 -05005499 func = lookup_method(self, &PyId___getitem__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005500 if (func == NULL) {
5501 PyErr_Format(PyExc_TypeError,
5502 "'%.200s' object is not iterable",
5503 Py_TYPE(self)->tp_name);
5504 return NULL;
5505 }
5506 Py_DECREF(func);
5507 return PySeqIter_New(self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005508}
Tim Peters6d6c1a32001-08-02 04:15:00 +00005509
5510static PyObject *
5511slot_tp_iternext(PyObject *self)
5512{
Benjamin Petersonce798522012-01-22 11:24:29 -05005513 _Py_IDENTIFIER(__next__);
5514 return call_method(self, &PyId___next__, "()");
Tim Peters6d6c1a32001-08-02 04:15:00 +00005515}
5516
Guido van Rossum1a493502001-08-17 16:47:50 +00005517static PyObject *
5518slot_tp_descr_get(PyObject *self, PyObject *obj, PyObject *type)
5519{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005520 PyTypeObject *tp = Py_TYPE(self);
5521 PyObject *get;
Victor Stinner3c1e4812012-03-26 22:10:51 +02005522 _Py_IDENTIFIER(__get__);
Guido van Rossum1a493502001-08-17 16:47:50 +00005523
Victor Stinner3c1e4812012-03-26 22:10:51 +02005524 get = _PyType_LookupId(tp, &PyId___get__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005525 if (get == NULL) {
5526 /* Avoid further slowdowns */
5527 if (tp->tp_descr_get == slot_tp_descr_get)
5528 tp->tp_descr_get = NULL;
5529 Py_INCREF(self);
5530 return self;
5531 }
5532 if (obj == NULL)
5533 obj = Py_None;
5534 if (type == NULL)
5535 type = Py_None;
5536 return PyObject_CallFunctionObjArgs(get, self, obj, type, NULL);
Guido van Rossum1a493502001-08-17 16:47:50 +00005537}
Tim Peters6d6c1a32001-08-02 04:15:00 +00005538
5539static int
5540slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value)
5541{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005542 PyObject *res;
Benjamin Petersonce798522012-01-22 11:24:29 -05005543 _Py_IDENTIFIER(__delete__);
5544 _Py_IDENTIFIER(__set__);
Guido van Rossum2c252392001-08-24 10:13:31 +00005545
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005546 if (value == NULL)
Benjamin Petersonce798522012-01-22 11:24:29 -05005547 res = call_method(self, &PyId___delete__, "(O)", target);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005548 else
Benjamin Petersonce798522012-01-22 11:24:29 -05005549 res = call_method(self, &PyId___set__, "(OO)", target, value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005550 if (res == NULL)
5551 return -1;
5552 Py_DECREF(res);
5553 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005554}
5555
5556static int
5557slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds)
5558{
Benjamin Petersonce798522012-01-22 11:24:29 -05005559 _Py_IDENTIFIER(__init__);
5560 PyObject *meth = lookup_method(self, &PyId___init__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005561 PyObject *res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005562
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005563 if (meth == NULL)
5564 return -1;
5565 res = PyObject_Call(meth, args, kwds);
5566 Py_DECREF(meth);
5567 if (res == NULL)
5568 return -1;
5569 if (res != Py_None) {
5570 PyErr_Format(PyExc_TypeError,
5571 "__init__() should return None, not '%.200s'",
5572 Py_TYPE(res)->tp_name);
5573 Py_DECREF(res);
5574 return -1;
5575 }
5576 Py_DECREF(res);
5577 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005578}
5579
5580static PyObject *
5581slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
5582{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005583 PyObject *func;
5584 PyObject *newargs, *x;
5585 Py_ssize_t i, n;
Victor Stinner3c1e4812012-03-26 22:10:51 +02005586 _Py_IDENTIFIER(__new__);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005587
Victor Stinner3c1e4812012-03-26 22:10:51 +02005588 func = _PyObject_GetAttrId((PyObject *)type, &PyId___new__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005589 if (func == NULL)
5590 return NULL;
5591 assert(PyTuple_Check(args));
5592 n = PyTuple_GET_SIZE(args);
5593 newargs = PyTuple_New(n+1);
5594 if (newargs == NULL)
5595 return NULL;
5596 Py_INCREF(type);
5597 PyTuple_SET_ITEM(newargs, 0, (PyObject *)type);
5598 for (i = 0; i < n; i++) {
5599 x = PyTuple_GET_ITEM(args, i);
5600 Py_INCREF(x);
5601 PyTuple_SET_ITEM(newargs, i+1, x);
5602 }
5603 x = PyObject_Call(func, newargs, kwds);
5604 Py_DECREF(newargs);
5605 Py_DECREF(func);
5606 return x;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005607}
5608
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005609static void
5610slot_tp_del(PyObject *self)
5611{
Benjamin Petersonce798522012-01-22 11:24:29 -05005612 _Py_IDENTIFIER(__del__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005613 PyObject *del, *res;
5614 PyObject *error_type, *error_value, *error_traceback;
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005615
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005616 /* Temporarily resurrect the object. */
5617 assert(self->ob_refcnt == 0);
5618 self->ob_refcnt = 1;
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005619
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005620 /* Save the current exception, if any. */
5621 PyErr_Fetch(&error_type, &error_value, &error_traceback);
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005622
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005623 /* Execute __del__ method, if any. */
Benjamin Petersonce798522012-01-22 11:24:29 -05005624 del = lookup_maybe(self, &PyId___del__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005625 if (del != NULL) {
5626 res = PyEval_CallObject(del, NULL);
5627 if (res == NULL)
5628 PyErr_WriteUnraisable(del);
5629 else
5630 Py_DECREF(res);
5631 Py_DECREF(del);
5632 }
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005633
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005634 /* Restore the saved exception. */
5635 PyErr_Restore(error_type, error_value, error_traceback);
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005636
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005637 /* Undo the temporary resurrection; can't use DECREF here, it would
5638 * cause a recursive call.
5639 */
5640 assert(self->ob_refcnt > 0);
5641 if (--self->ob_refcnt == 0)
5642 return; /* this is the normal path out */
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005643
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005644 /* __del__ resurrected it! Make it look like the original Py_DECREF
5645 * never happened.
5646 */
5647 {
5648 Py_ssize_t refcnt = self->ob_refcnt;
5649 _Py_NewReference(self);
5650 self->ob_refcnt = refcnt;
5651 }
5652 assert(!PyType_IS_GC(Py_TYPE(self)) ||
5653 _Py_AS_GC(self)->gc.gc_refs != _PyGC_REFS_UNTRACKED);
5654 /* If Py_REF_DEBUG, _Py_NewReference bumped _Py_RefTotal, so
5655 * we need to undo that. */
5656 _Py_DEC_REFTOTAL;
5657 /* If Py_TRACE_REFS, _Py_NewReference re-added self to the object
5658 * chain, so no more to do there.
5659 * If COUNT_ALLOCS, the original decref bumped tp_frees, and
5660 * _Py_NewReference bumped tp_allocs: both of those need to be
5661 * undone.
5662 */
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005663#ifdef COUNT_ALLOCS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005664 --Py_TYPE(self)->tp_frees;
5665 --Py_TYPE(self)->tp_allocs;
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005666#endif
5667}
5668
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005669
Benjamin Peterson63952412013-04-01 17:41:41 -04005670/*
5671Table mapping __foo__ names to tp_foo offsets and slot_tp_foo wrapper functions.
5672
5673The table is ordered by offsets relative to the 'PyHeapTypeObject' structure,
5674which incorporates the additional structures used for numbers, sequences and
5675mappings. Note that multiple names may map to the same slot (e.g. __eq__,
5676__ne__ etc. all map to tp_richcompare) and one name may map to multiple slots
5677(e.g. __str__ affects tp_str as well as tp_repr). The table is terminated with
5678an all-zero entry. (This table is further initialized in init_slotdefs().)
5679*/
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005680
Guido van Rossum6d204072001-10-21 00:44:31 +00005681typedef struct wrapperbase slotdef;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005682
5683#undef TPSLOT
Guido van Rossumc8e56452001-10-22 00:43:43 +00005684#undef FLSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005685#undef ETSLOT
5686#undef SQSLOT
5687#undef MPSLOT
5688#undef NBSLOT
Guido van Rossum6d204072001-10-21 00:44:31 +00005689#undef UNSLOT
5690#undef IBSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005691#undef BINSLOT
5692#undef RBINSLOT
5693
Guido van Rossum6d204072001-10-21 00:44:31 +00005694#define TPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005695 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
5696 PyDoc_STR(DOC)}
Guido van Rossumc8e56452001-10-22 00:43:43 +00005697#define FLSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC, FLAGS) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005698 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
5699 PyDoc_STR(DOC), FLAGS}
Guido van Rossum6d204072001-10-21 00:44:31 +00005700#define ETSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005701 {NAME, offsetof(PyHeapTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
5702 PyDoc_STR(DOC)}
Guido van Rossum6d204072001-10-21 00:44:31 +00005703#define SQSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005704 ETSLOT(NAME, as_sequence.SLOT, FUNCTION, WRAPPER, DOC)
Guido van Rossum6d204072001-10-21 00:44:31 +00005705#define MPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005706 ETSLOT(NAME, as_mapping.SLOT, FUNCTION, WRAPPER, DOC)
Guido van Rossum6d204072001-10-21 00:44:31 +00005707#define NBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005708 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, DOC)
Guido van Rossum6d204072001-10-21 00:44:31 +00005709#define UNSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005710 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
5711 "x." NAME "() <==> " DOC)
Guido van Rossum6d204072001-10-21 00:44:31 +00005712#define IBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005713 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
5714 "x." NAME "(y) <==> x" DOC "y")
Guido van Rossum6d204072001-10-21 00:44:31 +00005715#define BINSLOT(NAME, SLOT, FUNCTION, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005716 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
5717 "x." NAME "(y) <==> x" DOC "y")
Guido van Rossum6d204072001-10-21 00:44:31 +00005718#define RBINSLOT(NAME, SLOT, FUNCTION, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005719 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
5720 "x." NAME "(y) <==> y" DOC "x")
Anthony Baxter56616992005-06-03 14:12:21 +00005721#define BINSLOTNOTINFIX(NAME, SLOT, FUNCTION, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005722 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
5723 "x." NAME "(y) <==> " DOC)
Anthony Baxter56616992005-06-03 14:12:21 +00005724#define RBINSLOTNOTINFIX(NAME, SLOT, FUNCTION, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005725 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
5726 "x." NAME "(y) <==> " DOC)
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005727
5728static slotdef slotdefs[] = {
Benjamin Peterson63952412013-04-01 17:41:41 -04005729 TPSLOT("__getattribute__", tp_getattr, NULL, NULL, ""),
5730 TPSLOT("__getattr__", tp_getattr, NULL, NULL, ""),
5731 TPSLOT("__setattr__", tp_setattr, NULL, NULL, ""),
5732 TPSLOT("__delattr__", tp_setattr, NULL, NULL, ""),
5733 TPSLOT("__repr__", tp_repr, slot_tp_repr, wrap_unaryfunc,
5734 "x.__repr__() <==> repr(x)"),
5735 TPSLOT("__hash__", tp_hash, slot_tp_hash, wrap_hashfunc,
5736 "x.__hash__() <==> hash(x)"),
5737 FLSLOT("__call__", tp_call, slot_tp_call, (wrapperfunc)wrap_call,
5738 "x.__call__(...) <==> x(...)", PyWrapperFlag_KEYWORDS),
5739 TPSLOT("__str__", tp_str, slot_tp_str, wrap_unaryfunc,
5740 "x.__str__() <==> str(x)"),
5741 TPSLOT("__getattribute__", tp_getattro, slot_tp_getattr_hook,
5742 wrap_binaryfunc, "x.__getattribute__('name') <==> x.name"),
5743 TPSLOT("__getattr__", tp_getattro, slot_tp_getattr_hook, NULL, ""),
5744 TPSLOT("__setattr__", tp_setattro, slot_tp_setattro, wrap_setattr,
5745 "x.__setattr__('name', value) <==> x.name = value"),
5746 TPSLOT("__delattr__", tp_setattro, slot_tp_setattro, wrap_delattr,
5747 "x.__delattr__('name') <==> del x.name"),
5748 TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare, richcmp_lt,
5749 "x.__lt__(y) <==> x<y"),
5750 TPSLOT("__le__", tp_richcompare, slot_tp_richcompare, richcmp_le,
5751 "x.__le__(y) <==> x<=y"),
5752 TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare, richcmp_eq,
5753 "x.__eq__(y) <==> x==y"),
5754 TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare, richcmp_ne,
5755 "x.__ne__(y) <==> x!=y"),
5756 TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare, richcmp_gt,
5757 "x.__gt__(y) <==> x>y"),
5758 TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare, richcmp_ge,
5759 "x.__ge__(y) <==> x>=y"),
5760 TPSLOT("__iter__", tp_iter, slot_tp_iter, wrap_unaryfunc,
5761 "x.__iter__() <==> iter(x)"),
5762 TPSLOT("__next__", tp_iternext, slot_tp_iternext, wrap_next,
5763 "x.__next__() <==> next(x)"),
5764 TPSLOT("__get__", tp_descr_get, slot_tp_descr_get, wrap_descr_get,
5765 "descr.__get__(obj[, type]) -> value"),
5766 TPSLOT("__set__", tp_descr_set, slot_tp_descr_set, wrap_descr_set,
5767 "descr.__set__(obj, value)"),
5768 TPSLOT("__delete__", tp_descr_set, slot_tp_descr_set,
5769 wrap_descr_delete, "descr.__delete__(obj)"),
5770 FLSLOT("__init__", tp_init, slot_tp_init, (wrapperfunc)wrap_init,
5771 "x.__init__(...) initializes x; "
5772 "see help(type(x)) for signature",
5773 PyWrapperFlag_KEYWORDS),
5774 TPSLOT("__new__", tp_new, slot_tp_new, NULL, ""),
5775 TPSLOT("__del__", tp_del, slot_tp_del, NULL, ""),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005776
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005777 BINSLOT("__add__", nb_add, slot_nb_add,
5778 "+"),
5779 RBINSLOT("__radd__", nb_add, slot_nb_add,
5780 "+"),
5781 BINSLOT("__sub__", nb_subtract, slot_nb_subtract,
5782 "-"),
5783 RBINSLOT("__rsub__", nb_subtract, slot_nb_subtract,
5784 "-"),
5785 BINSLOT("__mul__", nb_multiply, slot_nb_multiply,
5786 "*"),
5787 RBINSLOT("__rmul__", nb_multiply, slot_nb_multiply,
5788 "*"),
5789 BINSLOT("__mod__", nb_remainder, slot_nb_remainder,
5790 "%"),
5791 RBINSLOT("__rmod__", nb_remainder, slot_nb_remainder,
5792 "%"),
5793 BINSLOTNOTINFIX("__divmod__", nb_divmod, slot_nb_divmod,
5794 "divmod(x, y)"),
5795 RBINSLOTNOTINFIX("__rdivmod__", nb_divmod, slot_nb_divmod,
5796 "divmod(y, x)"),
5797 NBSLOT("__pow__", nb_power, slot_nb_power, wrap_ternaryfunc,
5798 "x.__pow__(y[, z]) <==> pow(x, y[, z])"),
5799 NBSLOT("__rpow__", nb_power, slot_nb_power, wrap_ternaryfunc_r,
5800 "y.__rpow__(x[, z]) <==> pow(x, y[, z])"),
5801 UNSLOT("__neg__", nb_negative, slot_nb_negative, wrap_unaryfunc, "-x"),
5802 UNSLOT("__pos__", nb_positive, slot_nb_positive, wrap_unaryfunc, "+x"),
5803 UNSLOT("__abs__", nb_absolute, slot_nb_absolute, wrap_unaryfunc,
5804 "abs(x)"),
5805 UNSLOT("__bool__", nb_bool, slot_nb_bool, wrap_inquirypred,
5806 "x != 0"),
5807 UNSLOT("__invert__", nb_invert, slot_nb_invert, wrap_unaryfunc, "~x"),
5808 BINSLOT("__lshift__", nb_lshift, slot_nb_lshift, "<<"),
5809 RBINSLOT("__rlshift__", nb_lshift, slot_nb_lshift, "<<"),
5810 BINSLOT("__rshift__", nb_rshift, slot_nb_rshift, ">>"),
5811 RBINSLOT("__rrshift__", nb_rshift, slot_nb_rshift, ">>"),
5812 BINSLOT("__and__", nb_and, slot_nb_and, "&"),
5813 RBINSLOT("__rand__", nb_and, slot_nb_and, "&"),
5814 BINSLOT("__xor__", nb_xor, slot_nb_xor, "^"),
5815 RBINSLOT("__rxor__", nb_xor, slot_nb_xor, "^"),
5816 BINSLOT("__or__", nb_or, slot_nb_or, "|"),
5817 RBINSLOT("__ror__", nb_or, slot_nb_or, "|"),
5818 UNSLOT("__int__", nb_int, slot_nb_int, wrap_unaryfunc,
5819 "int(x)"),
5820 UNSLOT("__float__", nb_float, slot_nb_float, wrap_unaryfunc,
5821 "float(x)"),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005822 IBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add,
Eli Benderskyd3baae72011-11-11 16:57:05 +02005823 wrap_binaryfunc, "+="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005824 IBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract,
Eli Benderskyd3baae72011-11-11 16:57:05 +02005825 wrap_binaryfunc, "-="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005826 IBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply,
Eli Benderskyd3baae72011-11-11 16:57:05 +02005827 wrap_binaryfunc, "*="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005828 IBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder,
Eli Benderskyd3baae72011-11-11 16:57:05 +02005829 wrap_binaryfunc, "%="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005830 IBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power,
Eli Benderskyd3baae72011-11-11 16:57:05 +02005831 wrap_binaryfunc, "**="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005832 IBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift,
Eli Benderskyd3baae72011-11-11 16:57:05 +02005833 wrap_binaryfunc, "<<="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005834 IBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift,
Eli Benderskyd3baae72011-11-11 16:57:05 +02005835 wrap_binaryfunc, ">>="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005836 IBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and,
Eli Benderskyd3baae72011-11-11 16:57:05 +02005837 wrap_binaryfunc, "&="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005838 IBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor,
Eli Benderskyd3baae72011-11-11 16:57:05 +02005839 wrap_binaryfunc, "^="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005840 IBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or,
Eli Benderskyd3baae72011-11-11 16:57:05 +02005841 wrap_binaryfunc, "|="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005842 BINSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
5843 RBINSLOT("__rfloordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
5844 BINSLOT("__truediv__", nb_true_divide, slot_nb_true_divide, "/"),
5845 RBINSLOT("__rtruediv__", nb_true_divide, slot_nb_true_divide, "/"),
5846 IBSLOT("__ifloordiv__", nb_inplace_floor_divide,
5847 slot_nb_inplace_floor_divide, wrap_binaryfunc, "//"),
5848 IBSLOT("__itruediv__", nb_inplace_true_divide,
5849 slot_nb_inplace_true_divide, wrap_binaryfunc, "/"),
Benjamin Peterson63952412013-04-01 17:41:41 -04005850 NBSLOT("__index__", nb_index, slot_nb_index, wrap_unaryfunc,
5851 "x[y:z] <==> x[y.__index__():z.__index__()]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005852
Benjamin Peterson63952412013-04-01 17:41:41 -04005853 MPSLOT("__len__", mp_length, slot_mp_length, wrap_lenfunc,
5854 "x.__len__() <==> len(x)"),
5855 MPSLOT("__getitem__", mp_subscript, slot_mp_subscript,
5856 wrap_binaryfunc,
5857 "x.__getitem__(y) <==> x[y]"),
5858 MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript,
5859 wrap_objobjargproc,
5860 "x.__setitem__(i, y) <==> x[i]=y"),
5861 MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript,
5862 wrap_delitem,
5863 "x.__delitem__(y) <==> del x[y]"),
5864
5865 SQSLOT("__len__", sq_length, slot_sq_length, wrap_lenfunc,
5866 "x.__len__() <==> len(x)"),
5867 /* Heap types defining __add__/__mul__ have sq_concat/sq_repeat == NULL.
5868 The logic in abstract.c always falls back to nb_add/nb_multiply in
5869 this case. Defining both the nb_* and the sq_* slots to call the
5870 user-defined methods has unexpected side-effects, as shown by
5871 test_descr.notimplemented() */
5872 SQSLOT("__add__", sq_concat, NULL, wrap_binaryfunc,
5873 "x.__add__(y) <==> x+y"),
5874 SQSLOT("__mul__", sq_repeat, NULL, wrap_indexargfunc,
5875 "x.__mul__(n) <==> x*n"),
5876 SQSLOT("__rmul__", sq_repeat, NULL, wrap_indexargfunc,
5877 "x.__rmul__(n) <==> n*x"),
5878 SQSLOT("__getitem__", sq_item, slot_sq_item, wrap_sq_item,
5879 "x.__getitem__(y) <==> x[y]"),
5880 SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_setitem,
5881 "x.__setitem__(i, y) <==> x[i]=y"),
5882 SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_delitem,
5883 "x.__delitem__(y) <==> del x[y]"),
5884 SQSLOT("__contains__", sq_contains, slot_sq_contains, wrap_objobjproc,
5885 "x.__contains__(y) <==> y in x"),
5886 SQSLOT("__iadd__", sq_inplace_concat, NULL,
5887 wrap_binaryfunc, "x.__iadd__(y) <==> x+=y"),
5888 SQSLOT("__imul__", sq_inplace_repeat, NULL,
5889 wrap_indexargfunc, "x.__imul__(y) <==> x*=y"),
5890
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005891 {NULL}
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005892};
5893
Guido van Rossumc334df52002-04-04 23:44:47 +00005894/* Given a type pointer and an offset gotten from a slotdef entry, return a
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005895 pointer to the actual slot. This is not quite the same as simply adding
Guido van Rossumc334df52002-04-04 23:44:47 +00005896 the offset to the type pointer, since it takes care to indirect through the
5897 proper indirection pointer (as_buffer, etc.); it returns NULL if the
5898 indirection pointer is NULL. */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005899static void **
Martin v. Löwis18e16552006-02-15 17:27:45 +00005900slotptr(PyTypeObject *type, int ioffset)
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005901{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005902 char *ptr;
5903 long offset = ioffset;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005904
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005905 /* Note: this depends on the order of the members of PyHeapTypeObject! */
5906 assert(offset >= 0);
5907 assert((size_t)offset < offsetof(PyHeapTypeObject, as_buffer));
5908 if ((size_t)offset >= offsetof(PyHeapTypeObject, as_sequence)) {
5909 ptr = (char *)type->tp_as_sequence;
5910 offset -= offsetof(PyHeapTypeObject, as_sequence);
5911 }
5912 else if ((size_t)offset >= offsetof(PyHeapTypeObject, as_mapping)) {
5913 ptr = (char *)type->tp_as_mapping;
5914 offset -= offsetof(PyHeapTypeObject, as_mapping);
5915 }
5916 else if ((size_t)offset >= offsetof(PyHeapTypeObject, as_number)) {
5917 ptr = (char *)type->tp_as_number;
5918 offset -= offsetof(PyHeapTypeObject, as_number);
5919 }
5920 else {
5921 ptr = (char *)type;
5922 }
5923 if (ptr != NULL)
5924 ptr += offset;
5925 return (void **)ptr;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005926}
Guido van Rossumf040ede2001-08-07 16:40:56 +00005927
Guido van Rossumc334df52002-04-04 23:44:47 +00005928/* Length of array of slotdef pointers used to store slots with the
5929 same __name__. There should be at most MAX_EQUIV-1 slotdef entries with
5930 the same __name__, for any __name__. Since that's a static property, it is
5931 appropriate to declare fixed-size arrays for this. */
5932#define MAX_EQUIV 10
5933
5934/* Return a slot pointer for a given name, but ONLY if the attribute has
5935 exactly one slot function. The name must be an interned string. */
5936static void **
5937resolve_slotdups(PyTypeObject *type, PyObject *name)
5938{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005939 /* XXX Maybe this could be optimized more -- but is it worth it? */
Guido van Rossumc334df52002-04-04 23:44:47 +00005940
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005941 /* pname and ptrs act as a little cache */
5942 static PyObject *pname;
5943 static slotdef *ptrs[MAX_EQUIV];
5944 slotdef *p, **pp;
5945 void **res, **ptr;
Guido van Rossumc334df52002-04-04 23:44:47 +00005946
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005947 if (pname != name) {
5948 /* Collect all slotdefs that match name into ptrs. */
5949 pname = name;
5950 pp = ptrs;
5951 for (p = slotdefs; p->name_strobj; p++) {
5952 if (p->name_strobj == name)
5953 *pp++ = p;
5954 }
5955 *pp = NULL;
5956 }
Guido van Rossumc334df52002-04-04 23:44:47 +00005957
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005958 /* Look in all matching slots of the type; if exactly one of these has
5959 a filled-in slot, return its value. Otherwise return NULL. */
5960 res = NULL;
5961 for (pp = ptrs; *pp; pp++) {
5962 ptr = slotptr(type, (*pp)->offset);
5963 if (ptr == NULL || *ptr == NULL)
5964 continue;
5965 if (res != NULL)
5966 return NULL;
5967 res = ptr;
5968 }
5969 return res;
Guido van Rossumc334df52002-04-04 23:44:47 +00005970}
5971
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005972/* Common code for update_slots_callback() and fixup_slot_dispatchers(). This
Guido van Rossumc334df52002-04-04 23:44:47 +00005973 does some incredibly complex thinking and then sticks something into the
5974 slot. (It sees if the adjacent slotdefs for the same slot have conflicting
5975 interests, and then stores a generic wrapper or a specific function into
5976 the slot.) Return a pointer to the next slotdef with a different offset,
5977 because that's convenient for fixup_slot_dispatchers(). */
5978static slotdef *
5979update_one_slot(PyTypeObject *type, slotdef *p)
5980{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005981 PyObject *descr;
5982 PyWrapperDescrObject *d;
5983 void *generic = NULL, *specific = NULL;
5984 int use_generic = 0;
5985 int offset = p->offset;
5986 void **ptr = slotptr(type, offset);
Guido van Rossumc334df52002-04-04 23:44:47 +00005987
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005988 if (ptr == NULL) {
5989 do {
5990 ++p;
5991 } while (p->offset == offset);
5992 return p;
5993 }
5994 do {
5995 descr = _PyType_Lookup(type, p->name_strobj);
5996 if (descr == NULL) {
5997 if (ptr == (void**)&type->tp_iternext) {
Trent Nelsonab02db22012-09-18 21:58:03 -04005998 specific = (void *)_PyObject_NextNotImplemented;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005999 }
6000 continue;
6001 }
Benjamin Peterson7b166872012-04-24 11:06:25 -04006002 if (Py_TYPE(descr) == &PyWrapperDescr_Type &&
6003 ((PyWrapperDescrObject *)descr)->d_base->name_strobj == p->name_strobj) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006004 void **tptr = resolve_slotdups(type, p->name_strobj);
6005 if (tptr == NULL || tptr == ptr)
6006 generic = p->function;
6007 d = (PyWrapperDescrObject *)descr;
6008 if (d->d_base->wrapper == p->wrapper &&
6009 PyType_IsSubtype(type, PyDescr_TYPE(d)))
6010 {
6011 if (specific == NULL ||
6012 specific == d->d_wrapped)
6013 specific = d->d_wrapped;
6014 else
6015 use_generic = 1;
6016 }
6017 }
6018 else if (Py_TYPE(descr) == &PyCFunction_Type &&
6019 PyCFunction_GET_FUNCTION(descr) ==
6020 (PyCFunction)tp_new_wrapper &&
6021 ptr == (void**)&type->tp_new)
6022 {
6023 /* The __new__ wrapper is not a wrapper descriptor,
6024 so must be special-cased differently.
6025 If we don't do this, creating an instance will
6026 always use slot_tp_new which will look up
6027 __new__ in the MRO which will call tp_new_wrapper
6028 which will look through the base classes looking
6029 for a static base and call its tp_new (usually
6030 PyType_GenericNew), after performing various
6031 sanity checks and constructing a new argument
6032 list. Cut all that nonsense short -- this speeds
6033 up instance creation tremendously. */
6034 specific = (void *)type->tp_new;
6035 /* XXX I'm not 100% sure that there isn't a hole
6036 in this reasoning that requires additional
6037 sanity checks. I'll buy the first person to
6038 point out a bug in this reasoning a beer. */
6039 }
6040 else if (descr == Py_None &&
6041 ptr == (void**)&type->tp_hash) {
6042 /* We specifically allow __hash__ to be set to None
6043 to prevent inheritance of the default
6044 implementation from object.__hash__ */
Trent Nelsonab02db22012-09-18 21:58:03 -04006045 specific = (void *)PyObject_HashNotImplemented;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006046 }
6047 else {
6048 use_generic = 1;
6049 generic = p->function;
6050 }
6051 } while ((++p)->offset == offset);
6052 if (specific && !use_generic)
6053 *ptr = specific;
6054 else
6055 *ptr = generic;
6056 return p;
Guido van Rossumc334df52002-04-04 23:44:47 +00006057}
6058
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006059/* In the type, update the slots whose slotdefs are gathered in the pp array.
6060 This is a callback for update_subclasses(). */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006061static int
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006062update_slots_callback(PyTypeObject *type, void *data)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006063{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006064 slotdef **pp = (slotdef **)data;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006065
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006066 for (; *pp; pp++)
6067 update_one_slot(type, *pp);
6068 return 0;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006069}
6070
Guido van Rossumc334df52002-04-04 23:44:47 +00006071/* Initialize the slotdefs table by adding interned string objects for the
6072 names and sorting the entries. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006073static void
Guido van Rossumd396b9c2001-10-13 20:02:41 +00006074init_slotdefs(void)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006075{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006076 slotdef *p;
6077 static int initialized = 0;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006078
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006079 if (initialized)
6080 return;
6081 for (p = slotdefs; p->name; p++) {
Benjamin Peterson63952412013-04-01 17:41:41 -04006082 /* Slots must be ordered by their offset in the PyHeapTypeObject. */
6083 assert(!p[1].name || p->offset <= p[1].offset);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006084 p->name_strobj = PyUnicode_InternFromString(p->name);
6085 if (!p->name_strobj)
6086 Py_FatalError("Out of memory interning slotdef names");
6087 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006088 initialized = 1;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006089}
6090
Guido van Rossumc334df52002-04-04 23:44:47 +00006091/* Update the slots after assignment to a class (type) attribute. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006092static int
6093update_slot(PyTypeObject *type, PyObject *name)
6094{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006095 slotdef *ptrs[MAX_EQUIV];
6096 slotdef *p;
6097 slotdef **pp;
6098 int offset;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006099
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006100 /* Clear the VALID_VERSION flag of 'type' and all its
6101 subclasses. This could possibly be unified with the
6102 update_subclasses() recursion below, but carefully:
6103 they each have their own conditions on which to stop
6104 recursing into subclasses. */
6105 PyType_Modified(type);
Christian Heimesa62da1d2008-01-12 19:39:10 +00006106
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006107 init_slotdefs();
6108 pp = ptrs;
6109 for (p = slotdefs; p->name; p++) {
6110 /* XXX assume name is interned! */
6111 if (p->name_strobj == name)
6112 *pp++ = p;
6113 }
6114 *pp = NULL;
6115 for (pp = ptrs; *pp; pp++) {
6116 p = *pp;
6117 offset = p->offset;
6118 while (p > slotdefs && (p-1)->offset == offset)
6119 --p;
6120 *pp = p;
6121 }
6122 if (ptrs[0] == NULL)
6123 return 0; /* Not an attribute that affects any slots */
6124 return update_subclasses(type, name,
6125 update_slots_callback, (void *)ptrs);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006126}
6127
Guido van Rossumc334df52002-04-04 23:44:47 +00006128/* Store the proper functions in the slot dispatches at class (type)
6129 definition time, based upon which operations the class overrides in its
6130 dict. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00006131static void
Guido van Rossum7b9144b2001-10-09 19:39:46 +00006132fixup_slot_dispatchers(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00006133{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006134 slotdef *p;
Tim Peters6d6c1a32001-08-02 04:15:00 +00006135
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006136 init_slotdefs();
6137 for (p = slotdefs; p->name; )
6138 p = update_one_slot(type, p);
Tim Peters6d6c1a32001-08-02 04:15:00 +00006139}
Guido van Rossum705f0f52001-08-24 16:47:00 +00006140
Michael W. Hudson98bbc492002-11-26 14:47:27 +00006141static void
6142update_all_slots(PyTypeObject* type)
6143{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006144 slotdef *p;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00006145
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006146 init_slotdefs();
6147 for (p = slotdefs; p->name; p++) {
6148 /* update_slot returns int but can't actually fail */
6149 update_slot(type, p->name_strobj);
6150 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +00006151}
6152
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006153/* recurse_down_subclasses() and update_subclasses() are mutually
6154 recursive functions to call a callback for all subclasses,
6155 but refraining from recursing into subclasses that define 'name'. */
6156
6157static int
6158update_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 if (callback(type, data) < 0)
6162 return -1;
6163 return recurse_down_subclasses(type, name, callback, data);
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006164}
6165
6166static int
6167recurse_down_subclasses(PyTypeObject *type, PyObject *name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006168 update_callback callback, void *data)
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006169{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006170 PyTypeObject *subclass;
6171 PyObject *ref, *subclasses, *dict;
6172 Py_ssize_t i, n;
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006173
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006174 subclasses = type->tp_subclasses;
6175 if (subclasses == NULL)
6176 return 0;
6177 assert(PyList_Check(subclasses));
6178 n = PyList_GET_SIZE(subclasses);
6179 for (i = 0; i < n; i++) {
6180 ref = PyList_GET_ITEM(subclasses, i);
6181 assert(PyWeakref_CheckRef(ref));
6182 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
6183 assert(subclass != NULL);
6184 if ((PyObject *)subclass == Py_None)
6185 continue;
6186 assert(PyType_Check(subclass));
6187 /* Avoid recursing down into unaffected classes */
6188 dict = subclass->tp_dict;
6189 if (dict != NULL && PyDict_Check(dict) &&
6190 PyDict_GetItem(dict, name) != NULL)
6191 continue;
6192 if (update_subclasses(subclass, name, callback, data) < 0)
6193 return -1;
6194 }
6195 return 0;
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006196}
6197
Guido van Rossum6d204072001-10-21 00:44:31 +00006198/* This function is called by PyType_Ready() to populate the type's
6199 dictionary with method descriptors for function slots. For each
Guido van Rossum09638c12002-06-13 19:17:46 +00006200 function slot (like tp_repr) that's defined in the type, one or more
6201 corresponding descriptors are added in the type's tp_dict dictionary
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006202 under the appropriate name (like __repr__). Some function slots
Guido van Rossum09638c12002-06-13 19:17:46 +00006203 cause more than one descriptor to be added (for example, the nb_add
6204 slot adds both __add__ and __radd__ descriptors) and some function
6205 slots compete for the same descriptor (for example both sq_item and
6206 mp_subscript generate a __getitem__ descriptor).
6207
Ezio Melotti13925002011-03-16 11:05:33 +02006208 In the latter case, the first slotdef entry encountered wins. Since
Tim Petersbf9b2442003-03-23 05:35:36 +00006209 slotdef entries are sorted by the offset of the slot in the
Guido van Rossume5c691a2003-03-07 15:13:17 +00006210 PyHeapTypeObject, this gives us some control over disambiguating
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006211 between competing slots: the members of PyHeapTypeObject are listed
6212 from most general to least general, so the most general slot is
6213 preferred. In particular, because as_mapping comes before as_sequence,
6214 for a type that defines both mp_subscript and sq_item, mp_subscript
6215 wins.
Guido van Rossum09638c12002-06-13 19:17:46 +00006216
6217 This only adds new descriptors and doesn't overwrite entries in
6218 tp_dict that were previously defined. The descriptors contain a
6219 reference to the C function they must call, so that it's safe if they
6220 are copied into a subtype's __dict__ and the subtype has a different
6221 C function in its slot -- calling the method defined by the
6222 descriptor will call the C function that was used to create it,
6223 rather than the C function present in the slot when it is called.
6224 (This is important because a subtype may have a C function in the
6225 slot that calls the method from the dictionary, and we want to avoid
6226 infinite recursion here.) */
Guido van Rossum6d204072001-10-21 00:44:31 +00006227
6228static int
6229add_operators(PyTypeObject *type)
6230{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006231 PyObject *dict = type->tp_dict;
6232 slotdef *p;
6233 PyObject *descr;
6234 void **ptr;
Guido van Rossum6d204072001-10-21 00:44:31 +00006235
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006236 init_slotdefs();
6237 for (p = slotdefs; p->name; p++) {
6238 if (p->wrapper == NULL)
6239 continue;
6240 ptr = slotptr(type, p->offset);
6241 if (!ptr || !*ptr)
6242 continue;
6243 if (PyDict_GetItem(dict, p->name_strobj))
6244 continue;
Trent Nelsonab02db22012-09-18 21:58:03 -04006245 if (*ptr == (void *)PyObject_HashNotImplemented) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006246 /* Classes may prevent the inheritance of the tp_hash
6247 slot by storing PyObject_HashNotImplemented in it. Make it
6248 visible as a None value for the __hash__ attribute. */
6249 if (PyDict_SetItem(dict, p->name_strobj, Py_None) < 0)
6250 return -1;
6251 }
6252 else {
6253 descr = PyDescr_NewWrapper(type, p, *ptr);
6254 if (descr == NULL)
6255 return -1;
6256 if (PyDict_SetItem(dict, p->name_strobj, descr) < 0)
6257 return -1;
6258 Py_DECREF(descr);
6259 }
6260 }
6261 if (type->tp_new != NULL) {
6262 if (add_tp_new_wrapper(type) < 0)
6263 return -1;
6264 }
6265 return 0;
Guido van Rossum6d204072001-10-21 00:44:31 +00006266}
6267
Guido van Rossum705f0f52001-08-24 16:47:00 +00006268
6269/* Cooperative 'super' */
6270
6271typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006272 PyObject_HEAD
6273 PyTypeObject *type;
6274 PyObject *obj;
6275 PyTypeObject *obj_type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006276} superobject;
6277
Guido van Rossum6f799372001-09-20 20:46:19 +00006278static PyMemberDef super_members[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006279 {"__thisclass__", T_OBJECT, offsetof(superobject, type), READONLY,
6280 "the class invoking super()"},
6281 {"__self__", T_OBJECT, offsetof(superobject, obj), READONLY,
6282 "the instance invoking super(); may be None"},
6283 {"__self_class__", T_OBJECT, offsetof(superobject, obj_type), READONLY,
6284 "the type of the instance invoking super(); may be None"},
6285 {0}
Guido van Rossum41eb14d2001-08-30 23:13:11 +00006286};
6287
Guido van Rossum705f0f52001-08-24 16:47:00 +00006288static void
6289super_dealloc(PyObject *self)
6290{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006291 superobject *su = (superobject *)self;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006292
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006293 _PyObject_GC_UNTRACK(self);
6294 Py_XDECREF(su->obj);
6295 Py_XDECREF(su->type);
6296 Py_XDECREF(su->obj_type);
6297 Py_TYPE(self)->tp_free(self);
Guido van Rossum705f0f52001-08-24 16:47:00 +00006298}
6299
6300static PyObject *
Guido van Rossum41eb14d2001-08-30 23:13:11 +00006301super_repr(PyObject *self)
6302{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006303 superobject *su = (superobject *)self;
Guido van Rossum41eb14d2001-08-30 23:13:11 +00006304
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006305 if (su->obj_type)
6306 return PyUnicode_FromFormat(
6307 "<super: <class '%s'>, <%s object>>",
6308 su->type ? su->type->tp_name : "NULL",
6309 su->obj_type->tp_name);
6310 else
6311 return PyUnicode_FromFormat(
6312 "<super: <class '%s'>, NULL>",
6313 su->type ? su->type->tp_name : "NULL");
Guido van Rossum41eb14d2001-08-30 23:13:11 +00006314}
6315
6316static PyObject *
Guido van Rossum705f0f52001-08-24 16:47:00 +00006317super_getattro(PyObject *self, PyObject *name)
6318{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006319 superobject *su = (superobject *)self;
6320 int skip = su->obj_type == NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006321
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006322 if (!skip) {
6323 /* We want __class__ to return the class of the super object
6324 (i.e. super, or a subclass), not the class of su->obj. */
6325 skip = (PyUnicode_Check(name) &&
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006326 PyUnicode_GET_LENGTH(name) == 9 &&
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006327 PyUnicode_CompareWithASCIIString(name, "__class__") == 0);
6328 }
Guido van Rossum76ba09f2003-04-16 19:40:58 +00006329
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006330 if (!skip) {
6331 PyObject *mro, *res, *tmp, *dict;
6332 PyTypeObject *starttype;
6333 descrgetfunc f;
6334 Py_ssize_t i, n;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006335
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006336 starttype = su->obj_type;
6337 mro = starttype->tp_mro;
Guido van Rossum155db9a2002-04-02 17:53:47 +00006338
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006339 if (mro == NULL)
6340 n = 0;
6341 else {
6342 assert(PyTuple_Check(mro));
6343 n = PyTuple_GET_SIZE(mro);
6344 }
6345 for (i = 0; i < n; i++) {
6346 if ((PyObject *)(su->type) == PyTuple_GET_ITEM(mro, i))
6347 break;
6348 }
6349 i++;
6350 res = NULL;
Victor Stinnerd74782b2012-03-09 00:39:08 +01006351 /* keep a strong reference to mro because starttype->tp_mro can be
6352 replaced during PyDict_GetItem(dict, name) */
6353 Py_INCREF(mro);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006354 for (; i < n; i++) {
6355 tmp = PyTuple_GET_ITEM(mro, i);
6356 if (PyType_Check(tmp))
6357 dict = ((PyTypeObject *)tmp)->tp_dict;
6358 else
6359 continue;
6360 res = PyDict_GetItem(dict, name);
6361 if (res != NULL) {
6362 Py_INCREF(res);
6363 f = Py_TYPE(res)->tp_descr_get;
6364 if (f != NULL) {
6365 tmp = f(res,
6366 /* Only pass 'obj' param if
6367 this is instance-mode super
6368 (See SF ID #743627)
6369 */
6370 (su->obj == (PyObject *)
6371 su->obj_type
6372 ? (PyObject *)NULL
6373 : su->obj),
6374 (PyObject *)starttype);
6375 Py_DECREF(res);
6376 res = tmp;
6377 }
Victor Stinnerd74782b2012-03-09 00:39:08 +01006378 Py_DECREF(mro);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006379 return res;
6380 }
6381 }
Victor Stinnerd74782b2012-03-09 00:39:08 +01006382 Py_DECREF(mro);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006383 }
6384 return PyObject_GenericGetAttr(self, name);
Guido van Rossum705f0f52001-08-24 16:47:00 +00006385}
6386
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006387static PyTypeObject *
Guido van Rossum5b443c62001-12-03 15:38:28 +00006388supercheck(PyTypeObject *type, PyObject *obj)
6389{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006390 /* Check that a super() call makes sense. Return a type object.
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006391
Florent Xiclunaaa6c1d22011-12-12 18:54:29 +01006392 obj can be a class, or an instance of one:
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006393
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006394 - If it is a class, it must be a subclass of 'type'. This case is
6395 used for class methods; the return value is obj.
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006396
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006397 - If it is an instance, it must be an instance of 'type'. This is
6398 the normal case; the return value is obj.__class__.
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006399
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006400 But... when obj is an instance, we want to allow for the case where
6401 Py_TYPE(obj) is not a subclass of type, but obj.__class__ is!
6402 This will allow using super() with a proxy for obj.
6403 */
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006404
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006405 /* Check for first bullet above (special case) */
6406 if (PyType_Check(obj) && PyType_IsSubtype((PyTypeObject *)obj, type)) {
6407 Py_INCREF(obj);
6408 return (PyTypeObject *)obj;
6409 }
Guido van Rossum8e80a722003-02-18 19:22:22 +00006410
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006411 /* Normal case */
6412 if (PyType_IsSubtype(Py_TYPE(obj), type)) {
6413 Py_INCREF(Py_TYPE(obj));
6414 return Py_TYPE(obj);
6415 }
6416 else {
6417 /* Try the slow way */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006418 PyObject *class_attr;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006419
Martin v. Löwisbfc6d742011-10-13 20:03:57 +02006420 class_attr = _PyObject_GetAttrId(obj, &PyId___class__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006421 if (class_attr != NULL &&
6422 PyType_Check(class_attr) &&
6423 (PyTypeObject *)class_attr != Py_TYPE(obj))
6424 {
6425 int ok = PyType_IsSubtype(
6426 (PyTypeObject *)class_attr, type);
6427 if (ok)
6428 return (PyTypeObject *)class_attr;
6429 }
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006430
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006431 if (class_attr == NULL)
6432 PyErr_Clear();
6433 else
6434 Py_DECREF(class_attr);
6435 }
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006436
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006437 PyErr_SetString(PyExc_TypeError,
6438 "super(type, obj): "
6439 "obj must be an instance or subtype of type");
6440 return NULL;
Guido van Rossum5b443c62001-12-03 15:38:28 +00006441}
6442
Guido van Rossum705f0f52001-08-24 16:47:00 +00006443static PyObject *
6444super_descr_get(PyObject *self, PyObject *obj, PyObject *type)
6445{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006446 superobject *su = (superobject *)self;
6447 superobject *newobj;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006448
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006449 if (obj == NULL || obj == Py_None || su->obj != NULL) {
6450 /* Not binding to an object, or already bound */
6451 Py_INCREF(self);
6452 return self;
6453 }
6454 if (Py_TYPE(su) != &PySuper_Type)
6455 /* If su is an instance of a (strict) subclass of super,
6456 call its type */
6457 return PyObject_CallFunctionObjArgs((PyObject *)Py_TYPE(su),
6458 su->type, obj, NULL);
6459 else {
6460 /* Inline the common case */
6461 PyTypeObject *obj_type = supercheck(su->type, obj);
6462 if (obj_type == NULL)
6463 return NULL;
6464 newobj = (superobject *)PySuper_Type.tp_new(&PySuper_Type,
6465 NULL, NULL);
6466 if (newobj == NULL)
6467 return NULL;
6468 Py_INCREF(su->type);
6469 Py_INCREF(obj);
6470 newobj->type = su->type;
6471 newobj->obj = obj;
6472 newobj->obj_type = obj_type;
6473 return (PyObject *)newobj;
6474 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00006475}
6476
6477static int
6478super_init(PyObject *self, PyObject *args, PyObject *kwds)
6479{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006480 superobject *su = (superobject *)self;
6481 PyTypeObject *type = NULL;
6482 PyObject *obj = NULL;
6483 PyTypeObject *obj_type = NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006484
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006485 if (!_PyArg_NoKeywords("super", kwds))
6486 return -1;
6487 if (!PyArg_ParseTuple(args, "|O!O:super", &PyType_Type, &type, &obj))
6488 return -1;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00006489
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006490 if (type == NULL) {
6491 /* Call super(), without args -- fill in from __class__
6492 and first local variable on the stack. */
6493 PyFrameObject *f = PyThreadState_GET()->frame;
6494 PyCodeObject *co = f->f_code;
Victor Stinner0fcab4a2011-01-04 12:59:15 +00006495 Py_ssize_t i, n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006496 if (co == NULL) {
Benjamin Peterson6a42bd62012-09-01 23:04:38 -04006497 PyErr_SetString(PyExc_RuntimeError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006498 "super(): no code object");
6499 return -1;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00006500 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006501 if (co->co_argcount == 0) {
Benjamin Peterson6a42bd62012-09-01 23:04:38 -04006502 PyErr_SetString(PyExc_RuntimeError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006503 "super(): no arguments");
6504 return -1;
6505 }
6506 obj = f->f_localsplus[0];
6507 if (obj == NULL) {
Benjamin Peterson6a42bd62012-09-01 23:04:38 -04006508 PyErr_SetString(PyExc_RuntimeError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006509 "super(): arg[0] deleted");
6510 return -1;
6511 }
6512 if (co->co_freevars == NULL)
6513 n = 0;
6514 else {
6515 assert(PyTuple_Check(co->co_freevars));
6516 n = PyTuple_GET_SIZE(co->co_freevars);
6517 }
6518 for (i = 0; i < n; i++) {
6519 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
6520 assert(PyUnicode_Check(name));
6521 if (!PyUnicode_CompareWithASCIIString(name,
Nick Coghlan0b43bcf2012-05-27 18:17:07 +10006522 "__class__")) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006523 Py_ssize_t index = co->co_nlocals +
6524 PyTuple_GET_SIZE(co->co_cellvars) + i;
6525 PyObject *cell = f->f_localsplus[index];
6526 if (cell == NULL || !PyCell_Check(cell)) {
Benjamin Peterson6a42bd62012-09-01 23:04:38 -04006527 PyErr_SetString(PyExc_RuntimeError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006528 "super(): bad __class__ cell");
6529 return -1;
6530 }
6531 type = (PyTypeObject *) PyCell_GET(cell);
6532 if (type == NULL) {
Benjamin Peterson6a42bd62012-09-01 23:04:38 -04006533 PyErr_SetString(PyExc_RuntimeError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006534 "super(): empty __class__ cell");
6535 return -1;
6536 }
6537 if (!PyType_Check(type)) {
Benjamin Peterson6a42bd62012-09-01 23:04:38 -04006538 PyErr_Format(PyExc_RuntimeError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006539 "super(): __class__ is not a type (%s)",
6540 Py_TYPE(type)->tp_name);
6541 return -1;
6542 }
6543 break;
6544 }
6545 }
6546 if (type == NULL) {
Benjamin Peterson6a42bd62012-09-01 23:04:38 -04006547 PyErr_SetString(PyExc_RuntimeError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006548 "super(): __class__ cell not found");
6549 return -1;
6550 }
6551 }
Guido van Rossumcd16bf62007-06-13 18:07:49 +00006552
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006553 if (obj == Py_None)
6554 obj = NULL;
6555 if (obj != NULL) {
6556 obj_type = supercheck(type, obj);
6557 if (obj_type == NULL)
6558 return -1;
6559 Py_INCREF(obj);
6560 }
6561 Py_INCREF(type);
6562 su->type = type;
6563 su->obj = obj;
6564 su->obj_type = obj_type;
6565 return 0;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006566}
6567
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00006568PyDoc_STRVAR(super_doc,
Guido van Rossumcd16bf62007-06-13 18:07:49 +00006569"super() -> same as super(__class__, <first argument>)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00006570"super(type) -> unbound super object\n"
6571"super(type, obj) -> bound super object; requires isinstance(obj, type)\n"
Guido van Rossume705ef12001-08-29 15:47:06 +00006572"super(type, type2) -> bound super object; requires issubclass(type2, type)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00006573"Typical use to call a cooperative superclass method:\n"
6574"class C(B):\n"
6575" def meth(self, arg):\n"
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006576" super().meth(arg)\n"
Guido van Rossumcd16bf62007-06-13 18:07:49 +00006577"This works for class methods too:\n"
6578"class C(B):\n"
6579" @classmethod\n"
6580" def cmeth(cls, arg):\n"
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006581" super().cmeth(arg)\n");
Guido van Rossum705f0f52001-08-24 16:47:00 +00006582
Guido van Rossum048eb752001-10-02 21:24:57 +00006583static int
6584super_traverse(PyObject *self, visitproc visit, void *arg)
6585{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006586 superobject *su = (superobject *)self;
Guido van Rossum048eb752001-10-02 21:24:57 +00006587
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006588 Py_VISIT(su->obj);
6589 Py_VISIT(su->type);
6590 Py_VISIT(su->obj_type);
Guido van Rossum048eb752001-10-02 21:24:57 +00006591
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006592 return 0;
Guido van Rossum048eb752001-10-02 21:24:57 +00006593}
6594
Guido van Rossum705f0f52001-08-24 16:47:00 +00006595PyTypeObject PySuper_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006596 PyVarObject_HEAD_INIT(&PyType_Type, 0)
6597 "super", /* tp_name */
6598 sizeof(superobject), /* tp_basicsize */
6599 0, /* tp_itemsize */
6600 /* methods */
6601 super_dealloc, /* tp_dealloc */
6602 0, /* tp_print */
6603 0, /* tp_getattr */
6604 0, /* tp_setattr */
6605 0, /* tp_reserved */
6606 super_repr, /* tp_repr */
6607 0, /* tp_as_number */
6608 0, /* tp_as_sequence */
6609 0, /* tp_as_mapping */
6610 0, /* tp_hash */
6611 0, /* tp_call */
6612 0, /* tp_str */
6613 super_getattro, /* tp_getattro */
6614 0, /* tp_setattro */
6615 0, /* tp_as_buffer */
6616 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
6617 Py_TPFLAGS_BASETYPE, /* tp_flags */
6618 super_doc, /* tp_doc */
6619 super_traverse, /* tp_traverse */
6620 0, /* tp_clear */
6621 0, /* tp_richcompare */
6622 0, /* tp_weaklistoffset */
6623 0, /* tp_iter */
6624 0, /* tp_iternext */
6625 0, /* tp_methods */
6626 super_members, /* tp_members */
6627 0, /* tp_getset */
6628 0, /* tp_base */
6629 0, /* tp_dict */
6630 super_descr_get, /* tp_descr_get */
6631 0, /* tp_descr_set */
6632 0, /* tp_dictoffset */
6633 super_init, /* tp_init */
6634 PyType_GenericAlloc, /* tp_alloc */
6635 PyType_GenericNew, /* tp_new */
6636 PyObject_GC_Del, /* tp_free */
Guido van Rossum705f0f52001-08-24 16:47:00 +00006637};