blob: 6ece741833a03459e543c18d0453ed45eeb2ba5e [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
Mark Dickinson64aafeb2013-04-13 15:26:58 +0100301 /* Wait until et is a sane state before Py_DECREF'ing the old et->ht_name
302 value. (Bug #16447.) */
303 tmp = et->ht_name;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000304 et->ht_name = value;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000305
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000306 type->tp_name = tp_name;
Mark Dickinson64aafeb2013-04-13 15:26:58 +0100307 Py_DECREF(tmp);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000308
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000309 return 0;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000310}
311
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100312static int
313type_set_qualname(PyTypeObject *type, PyObject *value, void *context)
314{
315 PyHeapTypeObject* et;
316
Benjamin Peterson2c05a2e2012-10-31 00:01:15 -0400317 if (!check_set_special_type_attr(type, value, "__qualname__"))
318 return -1;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100319 if (!PyUnicode_Check(value)) {
320 PyErr_Format(PyExc_TypeError,
321 "can only assign string to %s.__qualname__, not '%s'",
322 type->tp_name, Py_TYPE(value)->tp_name);
323 return -1;
324 }
325
326 et = (PyHeapTypeObject*)type;
327 Py_INCREF(value);
328 Py_DECREF(et->ht_qualname);
329 et->ht_qualname = value;
330 return 0;
331}
332
Guido van Rossumc3542212001-08-16 09:18:56 +0000333static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000334type_module(PyTypeObject *type, void *context)
Guido van Rossum29ca26e1995-01-07 11:58:15 +0000335{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000336 PyObject *mod;
337 char *s;
Guido van Rossumc3542212001-08-16 09:18:56 +0000338
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000339 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
Victor Stinner3c1e4812012-03-26 22:10:51 +0200340 mod = _PyDict_GetItemId(type->tp_dict, &PyId___module__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000341 if (!mod) {
342 PyErr_Format(PyExc_AttributeError, "__module__");
343 return 0;
344 }
345 Py_XINCREF(mod);
346 return mod;
347 }
348 else {
349 s = strrchr(type->tp_name, '.');
350 if (s != NULL)
351 return PyUnicode_FromStringAndSize(
352 type->tp_name, (Py_ssize_t)(s - type->tp_name));
353 return PyUnicode_FromString("builtins");
354 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000355}
356
Guido van Rossum3926a632001-09-25 16:25:58 +0000357static int
358type_set_module(PyTypeObject *type, PyObject *value, void *context)
359{
Benjamin Petersond9f23d22011-08-17 11:54:03 -0500360 if (!check_set_special_type_attr(type, value, "__module__"))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000361 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000362
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000363 PyType_Modified(type);
Christian Heimesa62da1d2008-01-12 19:39:10 +0000364
Victor Stinner3c1e4812012-03-26 22:10:51 +0200365 return _PyDict_SetItemId(type->tp_dict, &PyId___module__, value);
Guido van Rossum3926a632001-09-25 16:25:58 +0000366}
367
Tim Peters6d6c1a32001-08-02 04:15:00 +0000368static PyObject *
Christian Heimes9e7f1d22008-02-28 12:27:11 +0000369type_abstractmethods(PyTypeObject *type, void *context)
370{
Benjamin Petersonaec5fd12010-10-02 00:03:31 +0000371 PyObject *mod = NULL;
Benjamin Peterson84060b82010-10-03 02:13:39 +0000372 /* type itself has an __abstractmethods__ descriptor (this). Don't return
373 that. */
Benjamin Petersonaec5fd12010-10-02 00:03:31 +0000374 if (type != &PyType_Type)
375 mod = PyDict_GetItemString(type->tp_dict, "__abstractmethods__");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000376 if (!mod) {
Benjamin Peterson23b628e2011-01-12 18:56:07 +0000377 PyErr_SetString(PyExc_AttributeError, "__abstractmethods__");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000378 return NULL;
379 }
380 Py_XINCREF(mod);
381 return mod;
Christian Heimes9e7f1d22008-02-28 12:27:11 +0000382}
383
384static int
385type_set_abstractmethods(PyTypeObject *type, PyObject *value, void *context)
386{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000387 /* __abstractmethods__ should only be set once on a type, in
388 abc.ABCMeta.__new__, so this function doesn't do anything
389 special to update subclasses.
390 */
Antoine Pitrou6f430e42012-08-15 23:18:25 +0200391 int abstract, res;
Benjamin Peterson477ba912011-01-12 15:34:01 +0000392 if (value != NULL) {
Antoine Pitrou6f430e42012-08-15 23:18:25 +0200393 abstract = PyObject_IsTrue(value);
394 if (abstract < 0)
395 return -1;
Benjamin Peterson477ba912011-01-12 15:34:01 +0000396 res = PyDict_SetItemString(type->tp_dict, "__abstractmethods__", value);
397 }
398 else {
Antoine Pitrou6f430e42012-08-15 23:18:25 +0200399 abstract = 0;
Benjamin Peterson477ba912011-01-12 15:34:01 +0000400 res = PyDict_DelItemString(type->tp_dict, "__abstractmethods__");
401 if (res && PyErr_ExceptionMatches(PyExc_KeyError)) {
Benjamin Peterson23b628e2011-01-12 18:56:07 +0000402 PyErr_SetString(PyExc_AttributeError, "__abstractmethods__");
Benjamin Peterson477ba912011-01-12 15:34:01 +0000403 return -1;
404 }
405 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000406 if (res == 0) {
407 PyType_Modified(type);
Antoine Pitrou6f430e42012-08-15 23:18:25 +0200408 if (abstract)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000409 type->tp_flags |= Py_TPFLAGS_IS_ABSTRACT;
Antoine Pitrou6f430e42012-08-15 23:18:25 +0200410 else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000411 type->tp_flags &= ~Py_TPFLAGS_IS_ABSTRACT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000412 }
413 return res;
Christian Heimes9e7f1d22008-02-28 12:27:11 +0000414}
415
416static PyObject *
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000417type_get_bases(PyTypeObject *type, void *context)
418{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000419 Py_INCREF(type->tp_bases);
420 return type->tp_bases;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000421}
422
423static PyTypeObject *best_base(PyObject *);
424static int mro_internal(PyTypeObject *);
425static int compatible_for_assignment(PyTypeObject *, PyTypeObject *, char *);
426static int add_subclass(PyTypeObject*, PyTypeObject*);
427static void remove_subclass(PyTypeObject *, PyTypeObject *);
428static void update_all_slots(PyTypeObject *);
429
Guido van Rossum8d24ee92003-03-24 23:49:49 +0000430typedef int (*update_callback)(PyTypeObject *, void *);
431static int update_subclasses(PyTypeObject *type, PyObject *name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000432 update_callback callback, void *data);
Guido van Rossum8d24ee92003-03-24 23:49:49 +0000433static int recurse_down_subclasses(PyTypeObject *type, PyObject *name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000434 update_callback callback, void *data);
Guido van Rossum8d24ee92003-03-24 23:49:49 +0000435
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000436static int
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000437mro_subclasses(PyTypeObject *type, PyObject* temp)
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000438{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000439 PyTypeObject *subclass;
440 PyObject *ref, *subclasses, *old_mro;
441 Py_ssize_t i, n;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000442
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000443 subclasses = type->tp_subclasses;
444 if (subclasses == NULL)
445 return 0;
446 assert(PyList_Check(subclasses));
447 n = PyList_GET_SIZE(subclasses);
448 for (i = 0; i < n; i++) {
449 ref = PyList_GET_ITEM(subclasses, i);
450 assert(PyWeakref_CheckRef(ref));
451 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
452 assert(subclass != NULL);
453 if ((PyObject *)subclass == Py_None)
454 continue;
455 assert(PyType_Check(subclass));
456 old_mro = subclass->tp_mro;
457 if (mro_internal(subclass) < 0) {
458 subclass->tp_mro = old_mro;
459 return -1;
460 }
461 else {
462 PyObject* tuple;
463 tuple = PyTuple_Pack(2, subclass, old_mro);
464 Py_DECREF(old_mro);
465 if (!tuple)
466 return -1;
467 if (PyList_Append(temp, tuple) < 0)
468 return -1;
469 Py_DECREF(tuple);
470 }
471 if (mro_subclasses(subclass, temp) < 0)
472 return -1;
473 }
474 return 0;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000475}
476
477static int
478type_set_bases(PyTypeObject *type, PyObject *value, void *context)
479{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000480 Py_ssize_t i;
481 int r = 0;
482 PyObject *ob, *temp;
483 PyTypeObject *new_base, *old_base;
484 PyObject *old_bases, *old_mro;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000485
Benjamin Petersond9f23d22011-08-17 11:54:03 -0500486 if (!check_set_special_type_attr(type, value, "__bases__"))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000487 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000488 if (!PyTuple_Check(value)) {
489 PyErr_Format(PyExc_TypeError,
490 "can only assign tuple to %s.__bases__, not %s",
491 type->tp_name, Py_TYPE(value)->tp_name);
492 return -1;
493 }
494 if (PyTuple_GET_SIZE(value) == 0) {
495 PyErr_Format(PyExc_TypeError,
496 "can only assign non-empty tuple to %s.__bases__, not ()",
497 type->tp_name);
498 return -1;
499 }
500 for (i = 0; i < PyTuple_GET_SIZE(value); i++) {
501 ob = PyTuple_GET_ITEM(value, i);
502 if (!PyType_Check(ob)) {
Benjamin Petersonb6af60c2012-04-01 18:49:54 -0400503 PyErr_Format(PyExc_TypeError,
Benjamin Peterson9ee601e2012-04-01 18:51:37 -0400504 "%s.__bases__ must be tuple of classes, not '%s'",
Benjamin Petersonb6af60c2012-04-01 18:49:54 -0400505 type->tp_name, Py_TYPE(ob)->tp_name);
506 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000507 }
Benjamin Peterson3471bb62012-04-01 18:48:40 -0400508 if (PyType_IsSubtype((PyTypeObject*)ob, type)) {
509 PyErr_SetString(PyExc_TypeError,
510 "a __bases__ item causes an inheritance cycle");
511 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000512 }
513 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000514
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000515 new_base = best_base(value);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000516
Benjamin Petersonab3c1c12012-04-01 18:48:02 -0400517 if (!new_base)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000518 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000519
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000520 if (!compatible_for_assignment(type->tp_base, new_base, "__bases__"))
521 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000522
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000523 Py_INCREF(new_base);
524 Py_INCREF(value);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000525
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000526 old_bases = type->tp_bases;
527 old_base = type->tp_base;
528 old_mro = type->tp_mro;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000529
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000530 type->tp_bases = value;
531 type->tp_base = new_base;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000532
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000533 if (mro_internal(type) < 0) {
534 goto bail;
535 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000536
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000537 temp = PyList_New(0);
538 if (!temp)
539 goto bail;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000540
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000541 r = mro_subclasses(type, temp);
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000542
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000543 if (r < 0) {
544 for (i = 0; i < PyList_Size(temp); i++) {
545 PyTypeObject* cls;
546 PyObject* mro;
547 PyArg_UnpackTuple(PyList_GET_ITEM(temp, i),
548 "", 2, 2, &cls, &mro);
549 Py_INCREF(mro);
550 ob = cls->tp_mro;
551 cls->tp_mro = mro;
552 Py_DECREF(ob);
553 }
554 Py_DECREF(temp);
555 goto bail;
556 }
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000557
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000558 Py_DECREF(temp);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000559
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000560 /* any base that was in __bases__ but now isn't, we
561 need to remove |type| from its tp_subclasses.
562 conversely, any class now in __bases__ that wasn't
563 needs to have |type| added to its subclasses. */
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000564
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000565 /* for now, sod that: just remove from all old_bases,
566 add to all new_bases */
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000567
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000568 for (i = PyTuple_GET_SIZE(old_bases) - 1; i >= 0; i--) {
569 ob = PyTuple_GET_ITEM(old_bases, i);
570 if (PyType_Check(ob)) {
571 remove_subclass(
572 (PyTypeObject*)ob, type);
573 }
574 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000575
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000576 for (i = PyTuple_GET_SIZE(value) - 1; i >= 0; i--) {
577 ob = PyTuple_GET_ITEM(value, i);
578 if (PyType_Check(ob)) {
579 if (add_subclass((PyTypeObject*)ob, type) < 0)
580 r = -1;
581 }
582 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000583
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000584 update_all_slots(type);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000585
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000586 Py_DECREF(old_bases);
587 Py_DECREF(old_base);
588 Py_DECREF(old_mro);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000589
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000590 return r;
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000591
592 bail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000593 Py_DECREF(type->tp_bases);
594 Py_DECREF(type->tp_base);
595 if (type->tp_mro != old_mro) {
596 Py_DECREF(type->tp_mro);
597 }
Michael W. Hudsone723e452003-08-07 14:58:10 +0000598
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000599 type->tp_bases = old_bases;
600 type->tp_base = old_base;
601 type->tp_mro = old_mro;
Tim Petersea7f75d2002-12-07 21:39:16 +0000602
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000603 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000604}
605
606static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000607type_dict(PyTypeObject *type, void *context)
608{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000609 if (type->tp_dict == NULL) {
610 Py_INCREF(Py_None);
611 return Py_None;
612 }
613 return PyDictProxy_New(type->tp_dict);
Guido van Rossum29ca26e1995-01-07 11:58:15 +0000614}
615
Tim Peters24008312002-03-17 18:56:20 +0000616static PyObject *
617type_get_doc(PyTypeObject *type, void *context)
618{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000619 PyObject *result;
620 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE) && type->tp_doc != NULL)
621 return PyUnicode_FromString(type->tp_doc);
Victor Stinner3c1e4812012-03-26 22:10:51 +0200622 result = _PyDict_GetItemId(type->tp_dict, &PyId___doc__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000623 if (result == NULL) {
624 result = Py_None;
625 Py_INCREF(result);
626 }
627 else if (Py_TYPE(result)->tp_descr_get) {
628 result = Py_TYPE(result)->tp_descr_get(result, NULL,
629 (PyObject *)type);
630 }
631 else {
632 Py_INCREF(result);
633 }
634 return result;
Tim Peters24008312002-03-17 18:56:20 +0000635}
636
Benjamin Peterson01fc6cd2011-08-17 12:03:47 -0500637static int
638type_set_doc(PyTypeObject *type, PyObject *value, void *context)
639{
640 if (!check_set_special_type_attr(type, value, "__doc__"))
641 return -1;
642 PyType_Modified(type);
Victor Stinner3c1e4812012-03-26 22:10:51 +0200643 return _PyDict_SetItemId(type->tp_dict, &PyId___doc__, value);
Benjamin Peterson01fc6cd2011-08-17 12:03:47 -0500644}
645
Antoine Pitrouec569b72008-08-26 22:40:48 +0000646static PyObject *
647type___instancecheck__(PyObject *type, PyObject *inst)
648{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000649 switch (_PyObject_RealIsInstance(inst, type)) {
650 case -1:
651 return NULL;
652 case 0:
653 Py_RETURN_FALSE;
654 default:
655 Py_RETURN_TRUE;
656 }
Antoine Pitrouec569b72008-08-26 22:40:48 +0000657}
658
659
660static PyObject *
Antoine Pitrouec569b72008-08-26 22:40:48 +0000661type___subclasscheck__(PyObject *type, PyObject *inst)
662{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000663 switch (_PyObject_RealIsSubclass(inst, type)) {
664 case -1:
665 return NULL;
666 case 0:
667 Py_RETURN_FALSE;
668 default:
669 Py_RETURN_TRUE;
670 }
Antoine Pitrouec569b72008-08-26 22:40:48 +0000671}
672
Antoine Pitrouec569b72008-08-26 22:40:48 +0000673
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000674static PyGetSetDef type_getsets[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000675 {"__name__", (getter)type_name, (setter)type_set_name, NULL},
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100676 {"__qualname__", (getter)type_qualname, (setter)type_set_qualname, NULL},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000677 {"__bases__", (getter)type_get_bases, (setter)type_set_bases, NULL},
678 {"__module__", (getter)type_module, (setter)type_set_module, NULL},
679 {"__abstractmethods__", (getter)type_abstractmethods,
680 (setter)type_set_abstractmethods, NULL},
681 {"__dict__", (getter)type_dict, NULL, NULL},
Benjamin Peterson01fc6cd2011-08-17 12:03:47 -0500682 {"__doc__", (getter)type_get_doc, (setter)type_set_doc, NULL},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000683 {0}
Tim Peters6d6c1a32001-08-02 04:15:00 +0000684};
685
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000686static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000687type_repr(PyTypeObject *type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000688{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000689 PyObject *mod, *name, *rtn;
Guido van Rossumc3542212001-08-16 09:18:56 +0000690
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000691 mod = type_module(type, NULL);
692 if (mod == NULL)
693 PyErr_Clear();
694 else if (!PyUnicode_Check(mod)) {
695 Py_DECREF(mod);
696 mod = NULL;
697 }
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100698 name = type_qualname(type, NULL);
Christian Heimesa0e7e412012-09-10 03:00:14 +0200699 if (name == NULL) {
700 Py_XDECREF(mod);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000701 return NULL;
Christian Heimesa0e7e412012-09-10 03:00:14 +0200702 }
Barry Warsaw7ce36942001-08-24 18:34:26 +0000703
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000704 if (mod != NULL && PyUnicode_CompareWithASCIIString(mod, "builtins"))
705 rtn = PyUnicode_FromFormat("<class '%U.%U'>", mod, name);
706 else
707 rtn = PyUnicode_FromFormat("<class '%s'>", type->tp_name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000708
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000709 Py_XDECREF(mod);
710 Py_DECREF(name);
711 return rtn;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000712}
713
Tim Peters6d6c1a32001-08-02 04:15:00 +0000714static PyObject *
715type_call(PyTypeObject *type, PyObject *args, PyObject *kwds)
716{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000717 PyObject *obj;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000718
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000719 if (type->tp_new == NULL) {
720 PyErr_Format(PyExc_TypeError,
721 "cannot create '%.100s' instances",
722 type->tp_name);
723 return NULL;
724 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000725
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000726 obj = type->tp_new(type, args, kwds);
727 if (obj != NULL) {
728 /* Ugly exception: when the call was type(something),
729 don't call tp_init on the result. */
730 if (type == &PyType_Type &&
731 PyTuple_Check(args) && PyTuple_GET_SIZE(args) == 1 &&
732 (kwds == NULL ||
733 (PyDict_Check(kwds) && PyDict_Size(kwds) == 0)))
734 return obj;
735 /* If the returned object is not an instance of type,
736 it won't be initialized. */
737 if (!PyType_IsSubtype(Py_TYPE(obj), type))
738 return obj;
739 type = Py_TYPE(obj);
740 if (type->tp_init != NULL &&
741 type->tp_init(obj, args, kwds) < 0) {
742 Py_DECREF(obj);
743 obj = NULL;
744 }
745 }
746 return obj;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000747}
748
749PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000750PyType_GenericAlloc(PyTypeObject *type, Py_ssize_t nitems)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000751{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000752 PyObject *obj;
753 const size_t size = _PyObject_VAR_SIZE(type, nitems+1);
754 /* note that we need to add one, for the sentinel */
Tim Peters406fe3b2001-10-06 19:04:01 +0000755
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000756 if (PyType_IS_GC(type))
757 obj = _PyObject_GC_Malloc(size);
758 else
759 obj = (PyObject *)PyObject_MALLOC(size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000760
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000761 if (obj == NULL)
762 return PyErr_NoMemory();
Tim Peters406fe3b2001-10-06 19:04:01 +0000763
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000764 memset(obj, '\0', size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000765
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000766 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
767 Py_INCREF(type);
Tim Peters406fe3b2001-10-06 19:04:01 +0000768
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000769 if (type->tp_itemsize == 0)
770 PyObject_INIT(obj, type);
771 else
772 (void) PyObject_INIT_VAR((PyVarObject *)obj, type, nitems);
Tim Peters406fe3b2001-10-06 19:04:01 +0000773
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000774 if (PyType_IS_GC(type))
775 _PyObject_GC_TRACK(obj);
776 return obj;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000777}
778
779PyObject *
780PyType_GenericNew(PyTypeObject *type, PyObject *args, PyObject *kwds)
781{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000782 return type->tp_alloc(type, 0);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000783}
784
Guido van Rossum9475a232001-10-05 20:51:39 +0000785/* Helpers for subtyping */
786
787static int
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000788traverse_slots(PyTypeObject *type, PyObject *self, visitproc visit, void *arg)
789{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000790 Py_ssize_t i, n;
791 PyMemberDef *mp;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000792
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000793 n = Py_SIZE(type);
794 mp = PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type);
795 for (i = 0; i < n; i++, mp++) {
796 if (mp->type == T_OBJECT_EX) {
797 char *addr = (char *)self + mp->offset;
798 PyObject *obj = *(PyObject **)addr;
799 if (obj != NULL) {
800 int err = visit(obj, arg);
801 if (err)
802 return err;
803 }
804 }
805 }
806 return 0;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000807}
808
809static int
Guido van Rossum9475a232001-10-05 20:51:39 +0000810subtype_traverse(PyObject *self, visitproc visit, void *arg)
811{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000812 PyTypeObject *type, *base;
813 traverseproc basetraverse;
Guido van Rossum9475a232001-10-05 20:51:39 +0000814
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000815 /* Find the nearest base with a different tp_traverse,
816 and traverse slots while we're at it */
817 type = Py_TYPE(self);
818 base = type;
819 while ((basetraverse = base->tp_traverse) == subtype_traverse) {
820 if (Py_SIZE(base)) {
821 int err = traverse_slots(base, self, visit, arg);
822 if (err)
823 return err;
824 }
825 base = base->tp_base;
826 assert(base);
827 }
Guido van Rossum9475a232001-10-05 20:51:39 +0000828
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000829 if (type->tp_dictoffset != base->tp_dictoffset) {
830 PyObject **dictptr = _PyObject_GetDictPtr(self);
831 if (dictptr && *dictptr)
832 Py_VISIT(*dictptr);
833 }
Guido van Rossum9475a232001-10-05 20:51:39 +0000834
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000835 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
836 /* For a heaptype, the instances count as references
837 to the type. Traverse the type so the collector
838 can find cycles involving this link. */
839 Py_VISIT(type);
Guido van Rossuma3862092002-06-10 15:24:42 +0000840
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000841 if (basetraverse)
842 return basetraverse(self, visit, arg);
843 return 0;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000844}
845
846static void
847clear_slots(PyTypeObject *type, PyObject *self)
848{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000849 Py_ssize_t i, n;
850 PyMemberDef *mp;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000851
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000852 n = Py_SIZE(type);
853 mp = PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type);
854 for (i = 0; i < n; i++, mp++) {
855 if (mp->type == T_OBJECT_EX && !(mp->flags & READONLY)) {
856 char *addr = (char *)self + mp->offset;
857 PyObject *obj = *(PyObject **)addr;
858 if (obj != NULL) {
859 *(PyObject **)addr = NULL;
860 Py_DECREF(obj);
861 }
862 }
863 }
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000864}
865
866static int
867subtype_clear(PyObject *self)
868{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000869 PyTypeObject *type, *base;
870 inquiry baseclear;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000871
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000872 /* Find the nearest base with a different tp_clear
873 and clear slots while we're at it */
874 type = Py_TYPE(self);
875 base = type;
876 while ((baseclear = base->tp_clear) == subtype_clear) {
877 if (Py_SIZE(base))
878 clear_slots(base, self);
879 base = base->tp_base;
880 assert(base);
881 }
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000882
Benjamin Peterson52c42432012-03-07 18:41:11 -0600883 /* Clear the instance dict (if any), to break cycles involving only
884 __dict__ slots (as in the case 'self.__dict__ is self'). */
885 if (type->tp_dictoffset != base->tp_dictoffset) {
886 PyObject **dictptr = _PyObject_GetDictPtr(self);
887 if (dictptr && *dictptr)
888 Py_CLEAR(*dictptr);
889 }
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000890
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000891 if (baseclear)
892 return baseclear(self);
893 return 0;
Guido van Rossum9475a232001-10-05 20:51:39 +0000894}
Tim Peters6d6c1a32001-08-02 04:15:00 +0000895
896static void
897subtype_dealloc(PyObject *self)
898{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000899 PyTypeObject *type, *base;
900 destructor basedealloc;
Antoine Pitrou56cd62c2012-09-06 00:59:49 +0200901 PyThreadState *tstate = PyThreadState_GET();
Tim Peters6d6c1a32001-08-02 04:15:00 +0000902
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000903 /* Extract the type; we expect it to be a heap type */
904 type = Py_TYPE(self);
905 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000906
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000907 /* Test whether the type has GC exactly once */
Guido van Rossum22b13872002-08-06 21:41:44 +0000908
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000909 if (!PyType_IS_GC(type)) {
910 /* It's really rare to find a dynamic type that doesn't have
911 GC; it can only happen when deriving from 'object' and not
912 adding any slots or instance variables. This allows
913 certain simplifications: there's no need to call
914 clear_slots(), or DECREF the dict, or clear weakrefs. */
Guido van Rossum22b13872002-08-06 21:41:44 +0000915
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000916 /* Maybe call finalizer; exit early if resurrected */
917 if (type->tp_del) {
918 type->tp_del(self);
919 if (self->ob_refcnt > 0)
920 return;
921 }
Guido van Rossum22b13872002-08-06 21:41:44 +0000922
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000923 /* Find the nearest base with a different tp_dealloc */
924 base = type;
925 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
926 assert(Py_SIZE(base) == 0);
927 base = base->tp_base;
928 assert(base);
929 }
Guido van Rossum22b13872002-08-06 21:41:44 +0000930
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000931 /* Extract the type again; tp_del may have changed it */
932 type = Py_TYPE(self);
Benjamin Peterson193152c2009-04-25 01:08:45 +0000933
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000934 /* Call the base tp_dealloc() */
935 assert(basedealloc);
936 basedealloc(self);
Guido van Rossum22b13872002-08-06 21:41:44 +0000937
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000938 /* Can't reference self beyond this point */
939 Py_DECREF(type);
Guido van Rossum22b13872002-08-06 21:41:44 +0000940
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000941 /* Done */
942 return;
943 }
Guido van Rossum22b13872002-08-06 21:41:44 +0000944
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000945 /* We get here only if the type has GC */
Guido van Rossum22b13872002-08-06 21:41:44 +0000946
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000947 /* UnTrack and re-Track around the trashcan macro, alas */
948 /* See explanation at end of function for full disclosure */
949 PyObject_GC_UnTrack(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 Py_TRASHCAN_SAFE_BEGIN(self);
953 --_PyTrash_delete_nesting;
Antoine Pitrou56cd62c2012-09-06 00:59:49 +0200954 -- tstate->trash_delete_nesting;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000955 /* DO NOT restore GC tracking at this point. weakref callbacks
956 * (if any, and whether directly here or indirectly in something we
957 * call) may trigger GC, and if self is tracked at that point, it
958 * will look like trash to GC and GC will try to delete self again.
959 */
Guido van Rossum22b13872002-08-06 21:41:44 +0000960
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000961 /* Find the nearest base with a different tp_dealloc */
962 base = type;
Brett Cannonb94767f2011-02-22 20:15:44 +0000963 while ((/*basedealloc =*/ base->tp_dealloc) == subtype_dealloc) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000964 base = base->tp_base;
965 assert(base);
966 }
Guido van Rossum14227b42001-12-06 02:35:58 +0000967
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000968 /* If we added a weaklist, we clear it. Do this *before* calling
969 the finalizer (__del__), clearing slots, or clearing the instance
970 dict. */
Guido van Rossum59195fd2003-06-13 20:54:40 +0000971
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000972 if (type->tp_weaklistoffset && !base->tp_weaklistoffset)
973 PyObject_ClearWeakRefs(self);
Guido van Rossum1987c662003-05-29 14:29:23 +0000974
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000975 /* Maybe call finalizer; exit early if resurrected */
976 if (type->tp_del) {
977 _PyObject_GC_TRACK(self);
978 type->tp_del(self);
979 if (self->ob_refcnt > 0)
980 goto endlabel; /* resurrected */
981 else
982 _PyObject_GC_UNTRACK(self);
983 /* New weakrefs could be created during the finalizer call.
984 If this occurs, clear them out without calling their
985 finalizers since they might rely on part of the object
986 being finalized that has already been destroyed. */
987 if (type->tp_weaklistoffset && !base->tp_weaklistoffset) {
988 /* Modeled after GET_WEAKREFS_LISTPTR() */
989 PyWeakReference **list = (PyWeakReference **) \
990 PyObject_GET_WEAKREFS_LISTPTR(self);
991 while (*list)
992 _PyWeakref_ClearRef(*list);
993 }
994 }
Guido van Rossum1987c662003-05-29 14:29:23 +0000995
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000996 /* Clear slots up to the nearest base with a different tp_dealloc */
997 base = type;
998 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
999 if (Py_SIZE(base))
1000 clear_slots(base, self);
1001 base = base->tp_base;
1002 assert(base);
1003 }
Guido van Rossum59195fd2003-06-13 20:54:40 +00001004
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001005 /* If we added a dict, DECREF it */
1006 if (type->tp_dictoffset && !base->tp_dictoffset) {
1007 PyObject **dictptr = _PyObject_GetDictPtr(self);
1008 if (dictptr != NULL) {
1009 PyObject *dict = *dictptr;
1010 if (dict != NULL) {
1011 Py_DECREF(dict);
1012 *dictptr = NULL;
1013 }
1014 }
1015 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001016
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001017 /* Extract the type again; tp_del may have changed it */
1018 type = Py_TYPE(self);
Benjamin Peterson193152c2009-04-25 01:08:45 +00001019
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001020 /* Call the base tp_dealloc(); first retrack self if
1021 * basedealloc knows about gc.
1022 */
1023 if (PyType_IS_GC(base))
1024 _PyObject_GC_TRACK(self);
1025 assert(basedealloc);
1026 basedealloc(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001027
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001028 /* Can't reference self beyond this point */
1029 Py_DECREF(type);
Guido van Rossum22b13872002-08-06 21:41:44 +00001030
Guido van Rossum0906e072002-08-07 20:42:09 +00001031 endlabel:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001032 ++_PyTrash_delete_nesting;
Antoine Pitrou56cd62c2012-09-06 00:59:49 +02001033 ++ tstate->trash_delete_nesting;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001034 Py_TRASHCAN_SAFE_END(self);
1035 --_PyTrash_delete_nesting;
Antoine Pitrou56cd62c2012-09-06 00:59:49 +02001036 -- tstate->trash_delete_nesting;
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001037
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001038 /* Explanation of the weirdness around the trashcan macros:
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001039
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001040 Q. What do the trashcan macros do?
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001041
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001042 A. Read the comment titled "Trashcan mechanism" in object.h.
1043 For one, this explains why there must be a call to GC-untrack
1044 before the trashcan begin macro. Without understanding the
1045 trashcan code, the answers to the following questions don't make
1046 sense.
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001047
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001048 Q. Why do we GC-untrack before the trashcan and then immediately
1049 GC-track again afterward?
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001050
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001051 A. In the case that the base class is GC-aware, the base class
1052 probably GC-untracks the object. If it does that using the
1053 UNTRACK macro, this will crash when the object is already
1054 untracked. Because we don't know what the base class does, the
1055 only safe thing is to make sure the object is tracked when we
1056 call the base class dealloc. But... The trashcan begin macro
1057 requires that the object is *untracked* before it is called. So
1058 the dance becomes:
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001059
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001060 GC untrack
1061 trashcan begin
1062 GC track
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001063
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001064 Q. Why did the last question say "immediately GC-track again"?
1065 It's nowhere near immediately.
Tim Petersf7f9e992003-11-13 21:59:32 +00001066
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001067 A. Because the code *used* to re-track immediately. Bad Idea.
1068 self has a refcount of 0, and if gc ever gets its hands on it
1069 (which can happen if any weakref callback gets invoked), it
1070 looks like trash to gc too, and gc also tries to delete self
Ezio Melotti13925002011-03-16 11:05:33 +02001071 then. But we're already deleting self. Double deallocation is
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001072 a subtle disaster.
Tim Petersf7f9e992003-11-13 21:59:32 +00001073
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001074 Q. Why the bizarre (net-zero) manipulation of
1075 _PyTrash_delete_nesting around the trashcan macros?
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001076
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001077 A. Some base classes (e.g. list) also use the trashcan mechanism.
1078 The following scenario used to be possible:
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001079
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001080 - suppose the trashcan level is one below the trashcan limit
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001081
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001082 - subtype_dealloc() is called
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001083
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001084 - the trashcan limit is not yet reached, so the trashcan level
1085 is incremented and the code between trashcan begin and end is
1086 executed
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001087
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001088 - this destroys much of the object's contents, including its
1089 slots and __dict__
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001090
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001091 - basedealloc() is called; this is really list_dealloc(), or
1092 some other type which also uses the trashcan macros
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001093
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001094 - the trashcan limit is now reached, so the object is put on the
1095 trashcan's to-be-deleted-later list
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001096
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001097 - basedealloc() returns
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001098
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001099 - subtype_dealloc() decrefs the object's type
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001100
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001101 - subtype_dealloc() returns
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001102
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001103 - later, the trashcan code starts deleting the objects from its
1104 to-be-deleted-later list
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001105
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001106 - subtype_dealloc() is called *AGAIN* for the same object
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001107
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001108 - at the very least (if the destroyed slots and __dict__ don't
1109 cause problems) the object's type gets decref'ed a second
1110 time, which is *BAD*!!!
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001111
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001112 The remedy is to make sure that if the code between trashcan
1113 begin and end in subtype_dealloc() is called, the code between
1114 trashcan begin and end in basedealloc() will also be called.
1115 This is done by decrementing the level after passing into the
1116 trashcan block, and incrementing it just before leaving the
1117 block.
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001118
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001119 But now it's possible that a chain of objects consisting solely
1120 of objects whose deallocator is subtype_dealloc() will defeat
1121 the trashcan mechanism completely: the decremented level means
1122 that the effective level never reaches the limit. Therefore, we
1123 *increment* the level *before* entering the trashcan block, and
1124 matchingly decrement it after leaving. This means the trashcan
1125 code will trigger a little early, but that's no big deal.
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001126
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001127 Q. Are there any live examples of code in need of all this
1128 complexity?
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001129
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001130 A. Yes. See SF bug 668433 for code that crashed (when Python was
1131 compiled in debug mode) before the trashcan level manipulations
1132 were added. For more discussion, see SF patches 581742, 575073
1133 and bug 574207.
1134 */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001135}
1136
Jeremy Hylton938ace62002-07-17 16:30:39 +00001137static PyTypeObject *solid_base(PyTypeObject *type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001138
Tim Peters6d6c1a32001-08-02 04:15:00 +00001139/* type test with subclassing support */
1140
1141int
1142PyType_IsSubtype(PyTypeObject *a, PyTypeObject *b)
1143{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001144 PyObject *mro;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001145
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001146 mro = a->tp_mro;
1147 if (mro != NULL) {
1148 /* Deal with multiple inheritance without recursion
1149 by walking the MRO tuple */
1150 Py_ssize_t i, n;
1151 assert(PyTuple_Check(mro));
1152 n = PyTuple_GET_SIZE(mro);
1153 for (i = 0; i < n; i++) {
1154 if (PyTuple_GET_ITEM(mro, i) == (PyObject *)b)
1155 return 1;
1156 }
1157 return 0;
1158 }
1159 else {
1160 /* a is not completely initilized yet; follow tp_base */
1161 do {
1162 if (a == b)
1163 return 1;
1164 a = a->tp_base;
1165 } while (a != NULL);
1166 return b == &PyBaseObject_Type;
1167 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001168}
1169
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001170/* Internal routines to do a method lookup in the type
Guido van Rossum60718732001-08-28 17:47:51 +00001171 without looking in the instance dictionary
1172 (so we can't use PyObject_GetAttr) but still binding
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001173 it to the instance. The arguments are the object,
Guido van Rossum60718732001-08-28 17:47:51 +00001174 the method name as a C string, and the address of a
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001175 static variable used to cache the interned Python string.
1176
1177 Two variants:
1178
1179 - lookup_maybe() returns NULL without raising an exception
1180 when the _PyType_Lookup() call fails;
1181
1182 - lookup_method() always raises an exception upon errors.
Benjamin Peterson224205f2009-05-08 03:25:19 +00001183
1184 - _PyObject_LookupSpecial() exported for the benefit of other places.
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001185*/
Guido van Rossum60718732001-08-28 17:47:51 +00001186
1187static PyObject *
Benjamin Petersonce798522012-01-22 11:24:29 -05001188lookup_maybe(PyObject *self, _Py_Identifier *attrid)
Guido van Rossum60718732001-08-28 17:47:51 +00001189{
Victor Stinner3c1e4812012-03-26 22:10:51 +02001190 PyObject *res;
Guido van Rossum60718732001-08-28 17:47:51 +00001191
Victor Stinner3c1e4812012-03-26 22:10:51 +02001192 res = _PyType_LookupId(Py_TYPE(self), attrid);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001193 if (res != NULL) {
1194 descrgetfunc f;
1195 if ((f = Py_TYPE(res)->tp_descr_get) == NULL)
1196 Py_INCREF(res);
1197 else
1198 res = f(res, self, (PyObject *)(Py_TYPE(self)));
1199 }
1200 return res;
Guido van Rossum60718732001-08-28 17:47:51 +00001201}
1202
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001203static PyObject *
Benjamin Petersonce798522012-01-22 11:24:29 -05001204lookup_method(PyObject *self, _Py_Identifier *attrid)
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001205{
Benjamin Petersonce798522012-01-22 11:24:29 -05001206 PyObject *res = lookup_maybe(self, attrid);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001207 if (res == NULL && !PyErr_Occurred())
Benjamin Petersonce798522012-01-22 11:24:29 -05001208 PyErr_SetObject(PyExc_AttributeError, attrid->object);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001209 return res;
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001210}
1211
Benjamin Peterson224205f2009-05-08 03:25:19 +00001212PyObject *
Benjamin Petersonce798522012-01-22 11:24:29 -05001213_PyObject_LookupSpecial(PyObject *self, _Py_Identifier *attrid)
Benjamin Peterson224205f2009-05-08 03:25:19 +00001214{
Benjamin Petersonce798522012-01-22 11:24:29 -05001215 return lookup_maybe(self, attrid);
Benjamin Peterson224205f2009-05-08 03:25:19 +00001216}
1217
Guido van Rossum2730b132001-08-28 18:22:14 +00001218/* A variation of PyObject_CallMethod that uses lookup_method()
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001219 instead of PyObject_GetAttrString(). This uses the same convention
Guido van Rossum2730b132001-08-28 18:22:14 +00001220 as lookup_method to cache the interned name string object. */
1221
Neil Schemenauerf23473f2001-10-21 22:28:58 +00001222static PyObject *
Benjamin Petersonce798522012-01-22 11:24:29 -05001223call_method(PyObject *o, _Py_Identifier *nameid, char *format, ...)
Guido van Rossum2730b132001-08-28 18:22:14 +00001224{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001225 va_list va;
1226 PyObject *args, *func = 0, *retval;
1227 va_start(va, format);
Guido van Rossum2730b132001-08-28 18:22:14 +00001228
Benjamin Petersonce798522012-01-22 11:24:29 -05001229 func = lookup_maybe(o, nameid);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001230 if (func == NULL) {
1231 va_end(va);
1232 if (!PyErr_Occurred())
Benjamin Petersonce798522012-01-22 11:24:29 -05001233 PyErr_SetObject(PyExc_AttributeError, nameid->object);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001234 return NULL;
1235 }
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001236
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001237 if (format && *format)
1238 args = Py_VaBuildValue(format, va);
1239 else
1240 args = PyTuple_New(0);
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001241
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001242 va_end(va);
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001243
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001244 if (args == NULL)
1245 return NULL;
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001246
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001247 assert(PyTuple_Check(args));
1248 retval = PyObject_Call(func, args, NULL);
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001249
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001250 Py_DECREF(args);
1251 Py_DECREF(func);
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001252
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001253 return retval;
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001254}
1255
1256/* Clone of call_method() that returns NotImplemented when the lookup fails. */
1257
Neil Schemenauerf23473f2001-10-21 22:28:58 +00001258static PyObject *
Benjamin Petersonce798522012-01-22 11:24:29 -05001259call_maybe(PyObject *o, _Py_Identifier *nameid, char *format, ...)
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001260{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001261 va_list va;
1262 PyObject *args, *func = 0, *retval;
1263 va_start(va, format);
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001264
Benjamin Petersonce798522012-01-22 11:24:29 -05001265 func = lookup_maybe(o, nameid);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001266 if (func == NULL) {
1267 va_end(va);
Brian Curtindfc80e32011-08-10 20:28:54 -05001268 if (!PyErr_Occurred())
1269 Py_RETURN_NOTIMPLEMENTED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001270 return NULL;
1271 }
Guido van Rossum2730b132001-08-28 18:22:14 +00001272
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001273 if (format && *format)
1274 args = Py_VaBuildValue(format, va);
1275 else
1276 args = PyTuple_New(0);
Guido van Rossum2730b132001-08-28 18:22:14 +00001277
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001278 va_end(va);
Guido van Rossum2730b132001-08-28 18:22:14 +00001279
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001280 if (args == NULL)
1281 return NULL;
Guido van Rossum2730b132001-08-28 18:22:14 +00001282
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001283 assert(PyTuple_Check(args));
1284 retval = PyObject_Call(func, args, NULL);
Guido van Rossum2730b132001-08-28 18:22:14 +00001285
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001286 Py_DECREF(args);
1287 Py_DECREF(func);
Guido van Rossum2730b132001-08-28 18:22:14 +00001288
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001289 return retval;
Guido van Rossum2730b132001-08-28 18:22:14 +00001290}
1291
Tim Petersea7f75d2002-12-07 21:39:16 +00001292/*
Guido van Rossum1f121312002-11-14 19:49:16 +00001293 Method resolution order algorithm C3 described in
1294 "A Monotonic Superclass Linearization for Dylan",
1295 by Kim Barrett, Bob Cassel, Paul Haahr,
Tim Petersea7f75d2002-12-07 21:39:16 +00001296 David A. Moon, Keith Playford, and P. Tucker Withington.
Guido van Rossum1f121312002-11-14 19:49:16 +00001297 (OOPSLA 1996)
1298
Guido van Rossum98f33732002-11-25 21:36:54 +00001299 Some notes about the rules implied by C3:
1300
Tim Petersea7f75d2002-12-07 21:39:16 +00001301 No duplicate bases.
Guido van Rossum98f33732002-11-25 21:36:54 +00001302 It isn't legal to repeat a class in a list of base classes.
1303
1304 The next three properties are the 3 constraints in "C3".
1305
Tim Petersea7f75d2002-12-07 21:39:16 +00001306 Local precendece order.
Guido van Rossum98f33732002-11-25 21:36:54 +00001307 If A precedes B in C's MRO, then A will precede B in the MRO of all
1308 subclasses of C.
1309
1310 Monotonicity.
1311 The MRO of a class must be an extension without reordering of the
1312 MRO of each of its superclasses.
1313
1314 Extended Precedence Graph (EPG).
1315 Linearization is consistent if there is a path in the EPG from
1316 each class to all its successors in the linearization. See
1317 the paper for definition of EPG.
Guido van Rossum1f121312002-11-14 19:49:16 +00001318 */
1319
Tim Petersea7f75d2002-12-07 21:39:16 +00001320static int
Guido van Rossum1f121312002-11-14 19:49:16 +00001321tail_contains(PyObject *list, int whence, PyObject *o) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001322 Py_ssize_t j, size;
1323 size = PyList_GET_SIZE(list);
Guido van Rossum1f121312002-11-14 19:49:16 +00001324
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001325 for (j = whence+1; j < size; j++) {
1326 if (PyList_GET_ITEM(list, j) == o)
1327 return 1;
1328 }
1329 return 0;
Guido van Rossum1f121312002-11-14 19:49:16 +00001330}
1331
Guido van Rossum98f33732002-11-25 21:36:54 +00001332static PyObject *
1333class_name(PyObject *cls)
1334{
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001335 PyObject *name = _PyObject_GetAttrId(cls, &PyId___name__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001336 if (name == NULL) {
1337 PyErr_Clear();
1338 Py_XDECREF(name);
1339 name = PyObject_Repr(cls);
1340 }
1341 if (name == NULL)
1342 return NULL;
1343 if (!PyUnicode_Check(name)) {
1344 Py_DECREF(name);
1345 return NULL;
1346 }
1347 return name;
Guido van Rossum98f33732002-11-25 21:36:54 +00001348}
1349
1350static int
1351check_duplicates(PyObject *list)
1352{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001353 Py_ssize_t i, j, n;
1354 /* Let's use a quadratic time algorithm,
1355 assuming that the bases lists is short.
1356 */
1357 n = PyList_GET_SIZE(list);
1358 for (i = 0; i < n; i++) {
1359 PyObject *o = PyList_GET_ITEM(list, i);
1360 for (j = i + 1; j < n; j++) {
1361 if (PyList_GET_ITEM(list, j) == o) {
1362 o = class_name(o);
1363 if (o != NULL) {
1364 PyErr_Format(PyExc_TypeError,
1365 "duplicate base class %U",
1366 o);
1367 Py_DECREF(o);
1368 } else {
1369 PyErr_SetString(PyExc_TypeError,
1370 "duplicate base class");
1371 }
1372 return -1;
1373 }
1374 }
1375 }
1376 return 0;
Guido van Rossum98f33732002-11-25 21:36:54 +00001377}
1378
1379/* Raise a TypeError for an MRO order disagreement.
1380
1381 It's hard to produce a good error message. In the absence of better
1382 insight into error reporting, report the classes that were candidates
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001383 to be put next into the MRO. There is some conflict between the
Guido van Rossum98f33732002-11-25 21:36:54 +00001384 order in which they should be put in the MRO, but it's hard to
1385 diagnose what constraint can't be satisfied.
1386*/
1387
1388static void
1389set_mro_error(PyObject *to_merge, int *remain)
1390{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001391 Py_ssize_t i, n, off, to_merge_size;
1392 char buf[1000];
1393 PyObject *k, *v;
1394 PyObject *set = PyDict_New();
1395 if (!set) return;
Guido van Rossum98f33732002-11-25 21:36:54 +00001396
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001397 to_merge_size = PyList_GET_SIZE(to_merge);
1398 for (i = 0; i < to_merge_size; i++) {
1399 PyObject *L = PyList_GET_ITEM(to_merge, i);
1400 if (remain[i] < PyList_GET_SIZE(L)) {
1401 PyObject *c = PyList_GET_ITEM(L, remain[i]);
1402 if (PyDict_SetItem(set, c, Py_None) < 0) {
1403 Py_DECREF(set);
1404 return;
1405 }
1406 }
1407 }
1408 n = PyDict_Size(set);
Guido van Rossum98f33732002-11-25 21:36:54 +00001409
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001410 off = PyOS_snprintf(buf, sizeof(buf), "Cannot create a \
Raymond Hettingerf394df42003-04-06 19:13:41 +00001411consistent method resolution\norder (MRO) for bases");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001412 i = 0;
1413 while (PyDict_Next(set, &i, &k, &v) && (size_t)off < sizeof(buf)) {
1414 PyObject *name = class_name(k);
Victor Stinnere5f99f32010-05-19 01:42:46 +00001415 char *name_str;
1416 if (name != NULL) {
1417 name_str = _PyUnicode_AsString(name);
1418 if (name_str == NULL)
Victor Stinnerba644a62010-05-19 01:50:45 +00001419 name_str = "?";
Victor Stinnere5f99f32010-05-19 01:42:46 +00001420 } else
Victor Stinnerba644a62010-05-19 01:50:45 +00001421 name_str = "?";
Victor Stinnere5f99f32010-05-19 01:42:46 +00001422 off += PyOS_snprintf(buf + off, sizeof(buf) - off, " %s", name_str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001423 Py_XDECREF(name);
1424 if (--n && (size_t)(off+1) < sizeof(buf)) {
1425 buf[off++] = ',';
1426 buf[off] = '\0';
1427 }
1428 }
1429 PyErr_SetString(PyExc_TypeError, buf);
1430 Py_DECREF(set);
Guido van Rossum98f33732002-11-25 21:36:54 +00001431}
1432
Tim Petersea7f75d2002-12-07 21:39:16 +00001433static int
Guido van Rossum1f121312002-11-14 19:49:16 +00001434pmerge(PyObject *acc, PyObject* to_merge) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001435 Py_ssize_t i, j, to_merge_size, empty_cnt;
1436 int *remain;
1437 int ok;
Tim Petersea7f75d2002-12-07 21:39:16 +00001438
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001439 to_merge_size = PyList_GET_SIZE(to_merge);
Guido van Rossum1f121312002-11-14 19:49:16 +00001440
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001441 /* remain stores an index into each sublist of to_merge.
1442 remain[i] is the index of the next base in to_merge[i]
1443 that is not included in acc.
1444 */
1445 remain = (int *)PyMem_MALLOC(SIZEOF_INT*to_merge_size);
1446 if (remain == NULL)
1447 return -1;
1448 for (i = 0; i < to_merge_size; i++)
1449 remain[i] = 0;
Guido van Rossum1f121312002-11-14 19:49:16 +00001450
1451 again:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001452 empty_cnt = 0;
1453 for (i = 0; i < to_merge_size; i++) {
1454 PyObject *candidate;
Tim Petersea7f75d2002-12-07 21:39:16 +00001455
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001456 PyObject *cur_list = PyList_GET_ITEM(to_merge, i);
Guido van Rossum1f121312002-11-14 19:49:16 +00001457
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001458 if (remain[i] >= PyList_GET_SIZE(cur_list)) {
1459 empty_cnt++;
1460 continue;
1461 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001462
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001463 /* Choose next candidate for MRO.
Guido van Rossum98f33732002-11-25 21:36:54 +00001464
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001465 The input sequences alone can determine the choice.
1466 If not, choose the class which appears in the MRO
1467 of the earliest direct superclass of the new class.
1468 */
Guido van Rossum98f33732002-11-25 21:36:54 +00001469
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001470 candidate = PyList_GET_ITEM(cur_list, remain[i]);
1471 for (j = 0; j < to_merge_size; j++) {
1472 PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
1473 if (tail_contains(j_lst, remain[j], candidate)) {
1474 goto skip; /* continue outer loop */
1475 }
1476 }
1477 ok = PyList_Append(acc, candidate);
1478 if (ok < 0) {
1479 PyMem_Free(remain);
1480 return -1;
1481 }
1482 for (j = 0; j < to_merge_size; j++) {
1483 PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
1484 if (remain[j] < PyList_GET_SIZE(j_lst) &&
1485 PyList_GET_ITEM(j_lst, remain[j]) == candidate) {
1486 remain[j]++;
1487 }
1488 }
1489 goto again;
1490 skip: ;
1491 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001492
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001493 if (empty_cnt == to_merge_size) {
1494 PyMem_FREE(remain);
1495 return 0;
1496 }
1497 set_mro_error(to_merge, remain);
1498 PyMem_FREE(remain);
1499 return -1;
Guido van Rossum1f121312002-11-14 19:49:16 +00001500}
1501
Tim Peters6d6c1a32001-08-02 04:15:00 +00001502static PyObject *
1503mro_implementation(PyTypeObject *type)
1504{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001505 Py_ssize_t i, n;
1506 int ok;
1507 PyObject *bases, *result;
1508 PyObject *to_merge, *bases_aslist;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001509
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001510 if (type->tp_dict == NULL) {
1511 if (PyType_Ready(type) < 0)
1512 return NULL;
1513 }
Guido van Rossum63517572002-06-18 16:44:57 +00001514
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001515 /* Find a superclass linearization that honors the constraints
1516 of the explicit lists of bases and the constraints implied by
1517 each base class.
Guido van Rossum98f33732002-11-25 21:36:54 +00001518
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001519 to_merge is a list of lists, where each list is a superclass
1520 linearization implied by a base class. The last element of
1521 to_merge is the declared list of bases.
1522 */
Guido van Rossum98f33732002-11-25 21:36:54 +00001523
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001524 bases = type->tp_bases;
1525 n = PyTuple_GET_SIZE(bases);
Guido van Rossum1f121312002-11-14 19:49:16 +00001526
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001527 to_merge = PyList_New(n+1);
1528 if (to_merge == NULL)
1529 return NULL;
Guido van Rossum1f121312002-11-14 19:49:16 +00001530
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001531 for (i = 0; i < n; i++) {
1532 PyObject *base = PyTuple_GET_ITEM(bases, i);
1533 PyObject *parentMRO;
1534 parentMRO = PySequence_List(((PyTypeObject*)base)->tp_mro);
1535 if (parentMRO == NULL) {
1536 Py_DECREF(to_merge);
1537 return NULL;
1538 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001539
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001540 PyList_SET_ITEM(to_merge, i, parentMRO);
1541 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001542
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001543 bases_aslist = PySequence_List(bases);
1544 if (bases_aslist == NULL) {
1545 Py_DECREF(to_merge);
1546 return NULL;
1547 }
1548 /* This is just a basic sanity check. */
1549 if (check_duplicates(bases_aslist) < 0) {
1550 Py_DECREF(to_merge);
1551 Py_DECREF(bases_aslist);
1552 return NULL;
1553 }
1554 PyList_SET_ITEM(to_merge, n, bases_aslist);
Guido van Rossum1f121312002-11-14 19:49:16 +00001555
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001556 result = Py_BuildValue("[O]", (PyObject *)type);
1557 if (result == NULL) {
1558 Py_DECREF(to_merge);
1559 return NULL;
1560 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001561
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001562 ok = pmerge(result, to_merge);
1563 Py_DECREF(to_merge);
1564 if (ok < 0) {
1565 Py_DECREF(result);
1566 return NULL;
1567 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001568
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001569 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001570}
1571
1572static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001573mro_external(PyObject *self)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001574{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001575 PyTypeObject *type = (PyTypeObject *)self;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001576
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001577 return mro_implementation(type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001578}
1579
1580static int
1581mro_internal(PyTypeObject *type)
1582{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001583 PyObject *mro, *result, *tuple;
1584 int checkit = 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001585
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001586 if (Py_TYPE(type) == &PyType_Type) {
1587 result = mro_implementation(type);
1588 }
1589 else {
Benjamin Petersonce798522012-01-22 11:24:29 -05001590 _Py_IDENTIFIER(mro);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001591 checkit = 1;
Benjamin Petersonce798522012-01-22 11:24:29 -05001592 mro = lookup_method((PyObject *)type, &PyId_mro);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001593 if (mro == NULL)
1594 return -1;
1595 result = PyObject_CallObject(mro, NULL);
1596 Py_DECREF(mro);
1597 }
1598 if (result == NULL)
1599 return -1;
1600 tuple = PySequence_Tuple(result);
1601 Py_DECREF(result);
1602 if (tuple == NULL)
1603 return -1;
1604 if (checkit) {
1605 Py_ssize_t i, len;
1606 PyObject *cls;
1607 PyTypeObject *solid;
Armin Rigo037d1e02005-12-29 17:07:39 +00001608
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001609 solid = solid_base(type);
Armin Rigo037d1e02005-12-29 17:07:39 +00001610
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001611 len = PyTuple_GET_SIZE(tuple);
Armin Rigo037d1e02005-12-29 17:07:39 +00001612
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001613 for (i = 0; i < len; i++) {
1614 PyTypeObject *t;
1615 cls = PyTuple_GET_ITEM(tuple, i);
1616 if (!PyType_Check(cls)) {
1617 PyErr_Format(PyExc_TypeError,
1618 "mro() returned a non-class ('%.500s')",
1619 Py_TYPE(cls)->tp_name);
1620 Py_DECREF(tuple);
1621 return -1;
1622 }
1623 t = (PyTypeObject*)cls;
1624 if (!PyType_IsSubtype(solid, solid_base(t))) {
1625 PyErr_Format(PyExc_TypeError,
1626 "mro() returned base with unsuitable layout ('%.500s')",
1627 t->tp_name);
1628 Py_DECREF(tuple);
1629 return -1;
1630 }
1631 }
1632 }
1633 type->tp_mro = tuple;
Christian Heimesa62da1d2008-01-12 19:39:10 +00001634
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001635 type_mro_modified(type, type->tp_mro);
Florent Xiclunaaa6c1d22011-12-12 18:54:29 +01001636 /* corner case: the super class might have been hidden
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001637 from the custom MRO */
1638 type_mro_modified(type, type->tp_bases);
Christian Heimesa62da1d2008-01-12 19:39:10 +00001639
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001640 PyType_Modified(type);
Christian Heimesa62da1d2008-01-12 19:39:10 +00001641
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001642 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001643}
1644
1645
1646/* Calculate the best base amongst multiple base classes.
1647 This is the first one that's on the path to the "solid base". */
1648
1649static PyTypeObject *
1650best_base(PyObject *bases)
1651{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001652 Py_ssize_t i, n;
1653 PyTypeObject *base, *winner, *candidate, *base_i;
1654 PyObject *base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001655
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001656 assert(PyTuple_Check(bases));
1657 n = PyTuple_GET_SIZE(bases);
1658 assert(n > 0);
1659 base = NULL;
1660 winner = NULL;
1661 for (i = 0; i < n; i++) {
1662 base_proto = PyTuple_GET_ITEM(bases, i);
1663 if (!PyType_Check(base_proto)) {
1664 PyErr_SetString(
1665 PyExc_TypeError,
1666 "bases must be types");
1667 return NULL;
1668 }
1669 base_i = (PyTypeObject *)base_proto;
1670 if (base_i->tp_dict == NULL) {
1671 if (PyType_Ready(base_i) < 0)
1672 return NULL;
1673 }
1674 candidate = solid_base(base_i);
1675 if (winner == NULL) {
1676 winner = candidate;
1677 base = base_i;
1678 }
1679 else if (PyType_IsSubtype(winner, candidate))
1680 ;
1681 else if (PyType_IsSubtype(candidate, winner)) {
1682 winner = candidate;
1683 base = base_i;
1684 }
1685 else {
1686 PyErr_SetString(
1687 PyExc_TypeError,
1688 "multiple bases have "
1689 "instance lay-out conflict");
1690 return NULL;
1691 }
1692 }
Florent Xiclunaaa6c1d22011-12-12 18:54:29 +01001693 assert (base != NULL);
1694
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001695 return base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001696}
1697
1698static int
1699extra_ivars(PyTypeObject *type, PyTypeObject *base)
1700{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001701 size_t t_size = type->tp_basicsize;
1702 size_t b_size = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001703
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001704 assert(t_size >= b_size); /* Else type smaller than base! */
1705 if (type->tp_itemsize || base->tp_itemsize) {
1706 /* If itemsize is involved, stricter rules */
1707 return t_size != b_size ||
1708 type->tp_itemsize != base->tp_itemsize;
1709 }
1710 if (type->tp_weaklistoffset && base->tp_weaklistoffset == 0 &&
1711 type->tp_weaklistoffset + sizeof(PyObject *) == t_size &&
1712 type->tp_flags & Py_TPFLAGS_HEAPTYPE)
1713 t_size -= sizeof(PyObject *);
1714 if (type->tp_dictoffset && base->tp_dictoffset == 0 &&
1715 type->tp_dictoffset + sizeof(PyObject *) == t_size &&
1716 type->tp_flags & Py_TPFLAGS_HEAPTYPE)
1717 t_size -= sizeof(PyObject *);
Guido van Rossum9676b222001-08-17 20:32:36 +00001718
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001719 return t_size != b_size;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001720}
1721
1722static PyTypeObject *
1723solid_base(PyTypeObject *type)
1724{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001725 PyTypeObject *base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001726
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001727 if (type->tp_base)
1728 base = solid_base(type->tp_base);
1729 else
1730 base = &PyBaseObject_Type;
1731 if (extra_ivars(type, base))
1732 return type;
1733 else
1734 return base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001735}
1736
Jeremy Hylton938ace62002-07-17 16:30:39 +00001737static void object_dealloc(PyObject *);
1738static int object_init(PyObject *, PyObject *, PyObject *);
1739static int update_slot(PyTypeObject *, PyObject *);
1740static void fixup_slot_dispatchers(PyTypeObject *);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001741
Guido van Rossum360e4b82007-05-14 22:51:27 +00001742/*
1743 * Helpers for __dict__ descriptor. We don't want to expose the dicts
1744 * inherited from various builtin types. The builtin base usually provides
1745 * its own __dict__ descriptor, so we use that when we can.
1746 */
1747static PyTypeObject *
1748get_builtin_base_with_dict(PyTypeObject *type)
1749{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001750 while (type->tp_base != NULL) {
1751 if (type->tp_dictoffset != 0 &&
1752 !(type->tp_flags & Py_TPFLAGS_HEAPTYPE))
1753 return type;
1754 type = type->tp_base;
1755 }
1756 return NULL;
Guido van Rossum360e4b82007-05-14 22:51:27 +00001757}
1758
1759static PyObject *
1760get_dict_descriptor(PyTypeObject *type)
1761{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001762 PyObject *descr;
Guido van Rossum360e4b82007-05-14 22:51:27 +00001763
Victor Stinner3c1e4812012-03-26 22:10:51 +02001764 descr = _PyType_LookupId(type, &PyId___dict__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001765 if (descr == NULL || !PyDescr_IsData(descr))
1766 return NULL;
Guido van Rossum360e4b82007-05-14 22:51:27 +00001767
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001768 return descr;
Guido van Rossum360e4b82007-05-14 22:51:27 +00001769}
1770
1771static void
1772raise_dict_descr_error(PyObject *obj)
1773{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001774 PyErr_Format(PyExc_TypeError,
1775 "this __dict__ descriptor does not support "
1776 "'%.200s' objects", Py_TYPE(obj)->tp_name);
Guido van Rossum360e4b82007-05-14 22:51:27 +00001777}
1778
Tim Peters6d6c1a32001-08-02 04:15:00 +00001779static PyObject *
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001780subtype_dict(PyObject *obj, void *context)
1781{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001782 PyTypeObject *base;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001783
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001784 base = get_builtin_base_with_dict(Py_TYPE(obj));
1785 if (base != NULL) {
1786 descrgetfunc func;
1787 PyObject *descr = get_dict_descriptor(base);
1788 if (descr == NULL) {
1789 raise_dict_descr_error(obj);
1790 return NULL;
1791 }
1792 func = Py_TYPE(descr)->tp_descr_get;
1793 if (func == NULL) {
1794 raise_dict_descr_error(obj);
1795 return NULL;
1796 }
1797 return func(descr, obj, (PyObject *)(Py_TYPE(obj)));
1798 }
Benjamin Peterson8eb12692012-02-19 19:59:10 -05001799 return PyObject_GenericGetDict(obj, context);
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001800}
1801
Guido van Rossum6661be32001-10-26 04:26:12 +00001802static int
1803subtype_setdict(PyObject *obj, PyObject *value, void *context)
1804{
Benjamin Peterson8eb12692012-02-19 19:59:10 -05001805 PyObject *dict, **dictptr;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001806 PyTypeObject *base;
Guido van Rossum6661be32001-10-26 04:26:12 +00001807
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001808 base = get_builtin_base_with_dict(Py_TYPE(obj));
1809 if (base != NULL) {
1810 descrsetfunc func;
1811 PyObject *descr = get_dict_descriptor(base);
1812 if (descr == NULL) {
1813 raise_dict_descr_error(obj);
1814 return -1;
1815 }
1816 func = Py_TYPE(descr)->tp_descr_set;
1817 if (func == NULL) {
1818 raise_dict_descr_error(obj);
1819 return -1;
1820 }
1821 return func(descr, obj, value);
1822 }
Benjamin Peterson8eb12692012-02-19 19:59:10 -05001823 /* Almost like PyObject_GenericSetDict, but allow __dict__ to be deleted. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001824 dictptr = _PyObject_GetDictPtr(obj);
1825 if (dictptr == NULL) {
1826 PyErr_SetString(PyExc_AttributeError,
1827 "This object has no __dict__");
1828 return -1;
1829 }
Benjamin Peterson006c5a22012-02-19 20:36:12 -05001830 if (value != NULL && !PyDict_Check(value)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001831 PyErr_Format(PyExc_TypeError,
1832 "__dict__ must be set to a dictionary, "
1833 "not a '%.200s'", Py_TYPE(value)->tp_name);
1834 return -1;
1835 }
1836 dict = *dictptr;
1837 Py_XINCREF(value);
1838 *dictptr = value;
1839 Py_XDECREF(dict);
1840 return 0;
Guido van Rossum6661be32001-10-26 04:26:12 +00001841}
1842
Guido van Rossumad47da02002-08-12 19:05:44 +00001843static PyObject *
1844subtype_getweakref(PyObject *obj, void *context)
1845{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001846 PyObject **weaklistptr;
1847 PyObject *result;
Guido van Rossumad47da02002-08-12 19:05:44 +00001848
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001849 if (Py_TYPE(obj)->tp_weaklistoffset == 0) {
1850 PyErr_SetString(PyExc_AttributeError,
1851 "This object has no __weakref__");
1852 return NULL;
1853 }
1854 assert(Py_TYPE(obj)->tp_weaklistoffset > 0);
1855 assert(Py_TYPE(obj)->tp_weaklistoffset + sizeof(PyObject *) <=
1856 (size_t)(Py_TYPE(obj)->tp_basicsize));
1857 weaklistptr = (PyObject **)
1858 ((char *)obj + Py_TYPE(obj)->tp_weaklistoffset);
1859 if (*weaklistptr == NULL)
1860 result = Py_None;
1861 else
1862 result = *weaklistptr;
1863 Py_INCREF(result);
1864 return result;
Guido van Rossumad47da02002-08-12 19:05:44 +00001865}
1866
Guido van Rossum373c7412003-01-07 13:41:37 +00001867/* Three variants on the subtype_getsets list. */
1868
1869static PyGetSetDef subtype_getsets_full[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001870 {"__dict__", subtype_dict, subtype_setdict,
1871 PyDoc_STR("dictionary for instance variables (if defined)")},
1872 {"__weakref__", subtype_getweakref, NULL,
1873 PyDoc_STR("list of weak references to the object (if defined)")},
1874 {0}
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001875};
1876
Guido van Rossum373c7412003-01-07 13:41:37 +00001877static PyGetSetDef subtype_getsets_dict_only[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001878 {"__dict__", subtype_dict, subtype_setdict,
1879 PyDoc_STR("dictionary for instance variables (if defined)")},
1880 {0}
Guido van Rossum373c7412003-01-07 13:41:37 +00001881};
1882
1883static PyGetSetDef subtype_getsets_weakref_only[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001884 {"__weakref__", subtype_getweakref, NULL,
1885 PyDoc_STR("list of weak references to the object (if defined)")},
1886 {0}
Guido van Rossum373c7412003-01-07 13:41:37 +00001887};
1888
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001889static int
1890valid_identifier(PyObject *s)
1891{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001892 if (!PyUnicode_Check(s)) {
1893 PyErr_Format(PyExc_TypeError,
1894 "__slots__ items must be strings, not '%.200s'",
1895 Py_TYPE(s)->tp_name);
1896 return 0;
1897 }
1898 if (!PyUnicode_IsIdentifier(s)) {
1899 PyErr_SetString(PyExc_TypeError,
1900 "__slots__ must be identifiers");
1901 return 0;
1902 }
1903 return 1;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001904}
1905
Guido van Rossumd8faa362007-04-27 19:54:29 +00001906/* Forward */
1907static int
1908object_init(PyObject *self, PyObject *args, PyObject *kwds);
1909
1910static int
1911type_init(PyObject *cls, PyObject *args, PyObject *kwds)
1912{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001913 int res;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001914
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001915 assert(args != NULL && PyTuple_Check(args));
1916 assert(kwds == NULL || PyDict_Check(kwds));
Guido van Rossumd8faa362007-04-27 19:54:29 +00001917
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001918 if (kwds != NULL && PyDict_Check(kwds) && PyDict_Size(kwds) != 0) {
1919 PyErr_SetString(PyExc_TypeError,
1920 "type.__init__() takes no keyword arguments");
1921 return -1;
1922 }
Guido van Rossumd8faa362007-04-27 19:54:29 +00001923
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001924 if (args != NULL && PyTuple_Check(args) &&
1925 (PyTuple_GET_SIZE(args) != 1 && PyTuple_GET_SIZE(args) != 3)) {
1926 PyErr_SetString(PyExc_TypeError,
1927 "type.__init__() takes 1 or 3 arguments");
1928 return -1;
1929 }
Guido van Rossumd8faa362007-04-27 19:54:29 +00001930
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001931 /* Call object.__init__(self) now. */
1932 /* XXX Could call super(type, cls).__init__() but what's the point? */
1933 args = PyTuple_GetSlice(args, 0, 0);
1934 res = object_init(cls, args, NULL);
1935 Py_DECREF(args);
1936 return res;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001937}
1938
Martin v. Löwis738236d2011-02-05 20:35:29 +00001939long
1940PyType_GetFlags(PyTypeObject *type)
1941{
1942 return type->tp_flags;
1943}
1944
Nick Coghlande31b192011-10-23 22:04:16 +10001945/* Determine the most derived metatype. */
1946PyTypeObject *
1947_PyType_CalculateMetaclass(PyTypeObject *metatype, PyObject *bases)
1948{
1949 Py_ssize_t i, nbases;
1950 PyTypeObject *winner;
1951 PyObject *tmp;
1952 PyTypeObject *tmptype;
1953
1954 /* Determine the proper metatype to deal with this,
1955 and check for metatype conflicts while we're at it.
1956 Note that if some other metatype wins to contract,
1957 it's possible that its instances are not types. */
1958
1959 nbases = PyTuple_GET_SIZE(bases);
1960 winner = metatype;
1961 for (i = 0; i < nbases; i++) {
1962 tmp = PyTuple_GET_ITEM(bases, i);
1963 tmptype = Py_TYPE(tmp);
1964 if (PyType_IsSubtype(winner, tmptype))
1965 continue;
1966 if (PyType_IsSubtype(tmptype, winner)) {
1967 winner = tmptype;
1968 continue;
1969 }
1970 /* else: */
1971 PyErr_SetString(PyExc_TypeError,
1972 "metaclass conflict: "
1973 "the metaclass of a derived class "
1974 "must be a (non-strict) subclass "
1975 "of the metaclasses of all its bases");
1976 return NULL;
1977 }
1978 return winner;
1979}
1980
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001981static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00001982type_new(PyTypeObject *metatype, PyObject *args, PyObject *kwds)
1983{
Victor Stinner6f738742012-02-25 01:22:36 +01001984 PyObject *name, *bases = NULL, *orig_dict, *dict = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001985 static char *kwlist[] = {"name", "bases", "dict", 0};
Victor Stinner6f738742012-02-25 01:22:36 +01001986 PyObject *qualname, *slots = NULL, *tmp, *newslots;
1987 PyTypeObject *type = NULL, *base, *tmptype, *winner;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001988 PyHeapTypeObject *et;
1989 PyMemberDef *mp;
1990 Py_ssize_t i, nbases, nslots, slotoffset, add_dict, add_weak;
1991 int j, may_add_dict, may_add_weak;
Victor Stinner3c1e4812012-03-26 22:10:51 +02001992 _Py_IDENTIFIER(__qualname__);
1993 _Py_IDENTIFIER(__slots__);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001994
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001995 assert(args != NULL && PyTuple_Check(args));
1996 assert(kwds == NULL || PyDict_Check(kwds));
Tim Peters3abca122001-10-27 19:37:48 +00001997
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001998 /* Special case: type(x) should return x->ob_type */
1999 {
2000 const Py_ssize_t nargs = PyTuple_GET_SIZE(args);
2001 const Py_ssize_t nkwds = kwds == NULL ? 0 : PyDict_Size(kwds);
Tim Peters3abca122001-10-27 19:37:48 +00002002
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002003 if (PyType_CheckExact(metatype) && nargs == 1 && nkwds == 0) {
2004 PyObject *x = PyTuple_GET_ITEM(args, 0);
2005 Py_INCREF(Py_TYPE(x));
2006 return (PyObject *) Py_TYPE(x);
2007 }
Tim Peters3abca122001-10-27 19:37:48 +00002008
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002009 /* SF bug 475327 -- if that didn't trigger, we need 3
2010 arguments. but PyArg_ParseTupleAndKeywords below may give
2011 a msg saying type() needs exactly 3. */
2012 if (nargs + nkwds != 3) {
2013 PyErr_SetString(PyExc_TypeError,
2014 "type() takes 1 or 3 arguments");
2015 return NULL;
2016 }
2017 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002018
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002019 /* Check arguments: (name, bases, dict) */
2020 if (!PyArg_ParseTupleAndKeywords(args, kwds, "UO!O!:type", kwlist,
2021 &name,
2022 &PyTuple_Type, &bases,
Victor Stinner6f738742012-02-25 01:22:36 +01002023 &PyDict_Type, &orig_dict))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002024 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002025
Nick Coghlande31b192011-10-23 22:04:16 +10002026 /* Determine the proper metatype to deal with this: */
2027 winner = _PyType_CalculateMetaclass(metatype, bases);
2028 if (winner == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002029 return NULL;
2030 }
Nick Coghlande31b192011-10-23 22:04:16 +10002031
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002032 if (winner != metatype) {
2033 if (winner->tp_new != type_new) /* Pass it to the winner */
2034 return winner->tp_new(winner, args, kwds);
2035 metatype = winner;
2036 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002037
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002038 /* Adjust for empty tuple bases */
Nick Coghlande31b192011-10-23 22:04:16 +10002039 nbases = PyTuple_GET_SIZE(bases);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002040 if (nbases == 0) {
2041 bases = PyTuple_Pack(1, &PyBaseObject_Type);
2042 if (bases == NULL)
Victor Stinner6f738742012-02-25 01:22:36 +01002043 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002044 nbases = 1;
2045 }
2046 else
2047 Py_INCREF(bases);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002048
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002049 /* Calculate best base, and check that all bases are type objects */
2050 base = best_base(bases);
2051 if (base == NULL) {
Victor Stinner6f738742012-02-25 01:22:36 +01002052 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002053 }
2054 if (!PyType_HasFeature(base, Py_TPFLAGS_BASETYPE)) {
2055 PyErr_Format(PyExc_TypeError,
2056 "type '%.100s' is not an acceptable base type",
2057 base->tp_name);
Victor Stinner6f738742012-02-25 01:22:36 +01002058 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002059 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002060
Victor Stinner6f738742012-02-25 01:22:36 +01002061 dict = PyDict_Copy(orig_dict);
2062 if (dict == NULL)
2063 goto error;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002064
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002065 /* Check for a __slots__ sequence variable in dict, and count it */
Victor Stinner3c1e4812012-03-26 22:10:51 +02002066 slots = _PyDict_GetItemId(dict, &PyId___slots__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002067 nslots = 0;
2068 add_dict = 0;
2069 add_weak = 0;
2070 may_add_dict = base->tp_dictoffset == 0;
2071 may_add_weak = base->tp_weaklistoffset == 0 && base->tp_itemsize == 0;
2072 if (slots == NULL) {
2073 if (may_add_dict) {
2074 add_dict++;
2075 }
2076 if (may_add_weak) {
2077 add_weak++;
2078 }
2079 }
2080 else {
2081 /* Have slots */
Guido van Rossumad47da02002-08-12 19:05:44 +00002082
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002083 /* Make it into a tuple */
2084 if (PyUnicode_Check(slots))
2085 slots = PyTuple_Pack(1, slots);
2086 else
2087 slots = PySequence_Tuple(slots);
Victor Stinner6f738742012-02-25 01:22:36 +01002088 if (slots == NULL)
2089 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002090 assert(PyTuple_Check(slots));
Guido van Rossumad47da02002-08-12 19:05:44 +00002091
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002092 /* Are slots allowed? */
2093 nslots = PyTuple_GET_SIZE(slots);
2094 if (nslots > 0 && base->tp_itemsize != 0) {
2095 PyErr_Format(PyExc_TypeError,
2096 "nonempty __slots__ "
2097 "not supported for subtype of '%s'",
2098 base->tp_name);
Victor Stinner6f738742012-02-25 01:22:36 +01002099 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002100 }
Guido van Rossumad47da02002-08-12 19:05:44 +00002101
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002102 /* Check for valid slot names and two special cases */
2103 for (i = 0; i < nslots; i++) {
2104 PyObject *tmp = PyTuple_GET_ITEM(slots, i);
2105 if (!valid_identifier(tmp))
Victor Stinner6f738742012-02-25 01:22:36 +01002106 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002107 assert(PyUnicode_Check(tmp));
2108 if (PyUnicode_CompareWithASCIIString(tmp, "__dict__") == 0) {
2109 if (!may_add_dict || add_dict) {
2110 PyErr_SetString(PyExc_TypeError,
2111 "__dict__ slot disallowed: "
2112 "we already got one");
Victor Stinner6f738742012-02-25 01:22:36 +01002113 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002114 }
2115 add_dict++;
2116 }
2117 if (PyUnicode_CompareWithASCIIString(tmp, "__weakref__") == 0) {
2118 if (!may_add_weak || add_weak) {
2119 PyErr_SetString(PyExc_TypeError,
2120 "__weakref__ slot disallowed: "
2121 "either we already got one, "
2122 "or __itemsize__ != 0");
Victor Stinner6f738742012-02-25 01:22:36 +01002123 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002124 }
2125 add_weak++;
2126 }
2127 }
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00002128
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002129 /* Copy slots into a list, mangle names and sort them.
2130 Sorted names are needed for __class__ assignment.
2131 Convert them back to tuple at the end.
2132 */
2133 newslots = PyList_New(nslots - add_dict - add_weak);
2134 if (newslots == NULL)
Victor Stinner6f738742012-02-25 01:22:36 +01002135 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002136 for (i = j = 0; i < nslots; i++) {
2137 tmp = PyTuple_GET_ITEM(slots, i);
2138 if ((add_dict &&
2139 PyUnicode_CompareWithASCIIString(tmp, "__dict__") == 0) ||
2140 (add_weak &&
2141 PyUnicode_CompareWithASCIIString(tmp, "__weakref__") == 0))
2142 continue;
2143 tmp =_Py_Mangle(name, tmp);
Benjamin Petersonae13c882011-08-16 22:26:48 -05002144 if (!tmp) {
2145 Py_DECREF(newslots);
Victor Stinner6f738742012-02-25 01:22:36 +01002146 goto error;
Benjamin Petersonae13c882011-08-16 22:26:48 -05002147 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002148 PyList_SET_ITEM(newslots, j, tmp);
Benjamin Petersonc4085c82011-08-16 18:53:26 -05002149 if (PyDict_GetItem(dict, tmp)) {
2150 PyErr_Format(PyExc_ValueError,
2151 "%R in __slots__ conflicts with class variable",
2152 tmp);
Benjamin Petersond17cefc2011-08-16 22:28:23 -05002153 Py_DECREF(newslots);
Victor Stinner6f738742012-02-25 01:22:36 +01002154 goto error;
Benjamin Petersonc4085c82011-08-16 18:53:26 -05002155 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002156 j++;
2157 }
2158 assert(j == nslots - add_dict - add_weak);
2159 nslots = j;
Victor Stinner6f738742012-02-25 01:22:36 +01002160 Py_CLEAR(slots);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002161 if (PyList_Sort(newslots) == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002162 Py_DECREF(newslots);
Victor Stinner6f738742012-02-25 01:22:36 +01002163 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002164 }
2165 slots = PyList_AsTuple(newslots);
2166 Py_DECREF(newslots);
Victor Stinner6f738742012-02-25 01:22:36 +01002167 if (slots == NULL)
2168 goto error;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00002169
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002170 /* Secondary bases may provide weakrefs or dict */
2171 if (nbases > 1 &&
2172 ((may_add_dict && !add_dict) ||
2173 (may_add_weak && !add_weak))) {
2174 for (i = 0; i < nbases; i++) {
2175 tmp = PyTuple_GET_ITEM(bases, i);
2176 if (tmp == (PyObject *)base)
2177 continue; /* Skip primary base */
2178 assert(PyType_Check(tmp));
2179 tmptype = (PyTypeObject *)tmp;
2180 if (may_add_dict && !add_dict &&
2181 tmptype->tp_dictoffset != 0)
2182 add_dict++;
2183 if (may_add_weak && !add_weak &&
2184 tmptype->tp_weaklistoffset != 0)
2185 add_weak++;
2186 if (may_add_dict && !add_dict)
2187 continue;
2188 if (may_add_weak && !add_weak)
2189 continue;
2190 /* Nothing more to check */
2191 break;
2192 }
2193 }
2194 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002195
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002196 /* Allocate the type object */
2197 type = (PyTypeObject *)metatype->tp_alloc(metatype, nslots);
Victor Stinner6f738742012-02-25 01:22:36 +01002198 if (type == NULL)
2199 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002200
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002201 /* Keep name and slots alive in the extended type object */
2202 et = (PyHeapTypeObject *)type;
2203 Py_INCREF(name);
2204 et->ht_name = name;
2205 et->ht_slots = slots;
Victor Stinner6f738742012-02-25 01:22:36 +01002206 slots = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002207
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002208 /* Initialize tp_flags */
2209 type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE |
2210 Py_TPFLAGS_BASETYPE;
2211 if (base->tp_flags & Py_TPFLAGS_HAVE_GC)
2212 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossumdc91b992001-08-08 22:26:22 +00002213
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002214 /* Initialize essential fields */
2215 type->tp_as_number = &et->as_number;
2216 type->tp_as_sequence = &et->as_sequence;
2217 type->tp_as_mapping = &et->as_mapping;
2218 type->tp_as_buffer = &et->as_buffer;
2219 type->tp_name = _PyUnicode_AsString(name);
Victor Stinner6f738742012-02-25 01:22:36 +01002220 if (!type->tp_name)
2221 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002222
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002223 /* Set tp_base and tp_bases */
2224 type->tp_bases = bases;
Victor Stinner6f738742012-02-25 01:22:36 +01002225 bases = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002226 Py_INCREF(base);
2227 type->tp_base = base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002228
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002229 /* Initialize tp_dict from passed-in dict */
Victor Stinner6f738742012-02-25 01:22:36 +01002230 Py_INCREF(dict);
2231 type->tp_dict = dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002232
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002233 /* Set __module__ in the dict */
Victor Stinner3c1e4812012-03-26 22:10:51 +02002234 if (_PyDict_GetItemId(dict, &PyId___module__) == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002235 tmp = PyEval_GetGlobals();
2236 if (tmp != NULL) {
Victor Stinner3c1e4812012-03-26 22:10:51 +02002237 tmp = _PyDict_GetItemId(tmp, &PyId___name__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002238 if (tmp != NULL) {
Victor Stinner3c1e4812012-03-26 22:10:51 +02002239 if (_PyDict_SetItemId(dict, &PyId___module__,
2240 tmp) < 0)
Victor Stinner6f738742012-02-25 01:22:36 +01002241 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002242 }
2243 }
2244 }
Guido van Rossumc3542212001-08-16 09:18:56 +00002245
Victor Stinner6f738742012-02-25 01:22:36 +01002246 /* Set ht_qualname to dict['__qualname__'] if available, else to
2247 __name__. The __qualname__ accessor will look for ht_qualname.
2248 */
Victor Stinner3c1e4812012-03-26 22:10:51 +02002249 qualname = _PyDict_GetItemId(dict, &PyId___qualname__);
Victor Stinner6f738742012-02-25 01:22:36 +01002250 if (qualname != NULL) {
2251 if (!PyUnicode_Check(qualname)) {
2252 PyErr_Format(PyExc_TypeError,
2253 "type __qualname__ must be a str, not %s",
2254 Py_TYPE(qualname)->tp_name);
2255 goto error;
2256 }
2257 }
Benjamin Peterson8afa7fa2012-10-30 23:51:03 -04002258 et->ht_qualname = qualname ? qualname : et->ht_name;
2259 Py_INCREF(et->ht_qualname);
2260 if (qualname != NULL && PyDict_DelItem(dict, PyId___qualname__.object) < 0)
2261 goto error;
Victor Stinner6f738742012-02-25 01:22:36 +01002262
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002263 /* Set tp_doc to a copy of dict['__doc__'], if the latter is there
2264 and is a string. The __doc__ accessor will first look for tp_doc;
2265 if that fails, it will still look into __dict__.
2266 */
2267 {
Victor Stinner3c1e4812012-03-26 22:10:51 +02002268 PyObject *doc = _PyDict_GetItemId(dict, &PyId___doc__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002269 if (doc != NULL && PyUnicode_Check(doc)) {
2270 Py_ssize_t len;
2271 char *doc_str;
2272 char *tp_doc;
Alexandre Vassalottia85998a2008-05-03 18:24:43 +00002273
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002274 doc_str = _PyUnicode_AsString(doc);
Victor Stinner6f738742012-02-25 01:22:36 +01002275 if (doc_str == NULL)
2276 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002277 /* Silently truncate the docstring if it contains null bytes. */
2278 len = strlen(doc_str);
2279 tp_doc = (char *)PyObject_MALLOC(len + 1);
Victor Stinner6f738742012-02-25 01:22:36 +01002280 if (tp_doc == NULL)
2281 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002282 memcpy(tp_doc, doc_str, len + 1);
2283 type->tp_doc = tp_doc;
2284 }
2285 }
Tim Peters2f93e282001-10-04 05:27:00 +00002286
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002287 /* Special-case __new__: if it's a plain function,
2288 make it a static function */
Victor Stinner3c1e4812012-03-26 22:10:51 +02002289 tmp = _PyDict_GetItemId(dict, &PyId___new__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002290 if (tmp != NULL && PyFunction_Check(tmp)) {
2291 tmp = PyStaticMethod_New(tmp);
Victor Stinner6f738742012-02-25 01:22:36 +01002292 if (tmp == NULL)
2293 goto error;
Victor Stinner3c1e4812012-03-26 22:10:51 +02002294 if (_PyDict_SetItemId(dict, &PyId___new__, tmp) < 0)
2295 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002296 Py_DECREF(tmp);
2297 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002298
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002299 /* Add descriptors for custom slots from __slots__, or for __dict__ */
2300 mp = PyHeapType_GET_MEMBERS(et);
2301 slotoffset = base->tp_basicsize;
Victor Stinner6f738742012-02-25 01:22:36 +01002302 if (et->ht_slots != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002303 for (i = 0; i < nslots; i++, mp++) {
2304 mp->name = _PyUnicode_AsString(
Victor Stinner6f738742012-02-25 01:22:36 +01002305 PyTuple_GET_ITEM(et->ht_slots, i));
2306 if (mp->name == NULL)
2307 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002308 mp->type = T_OBJECT_EX;
2309 mp->offset = slotoffset;
Guido van Rossumd8faa362007-04-27 19:54:29 +00002310
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002311 /* __dict__ and __weakref__ are already filtered out */
2312 assert(strcmp(mp->name, "__dict__") != 0);
2313 assert(strcmp(mp->name, "__weakref__") != 0);
Guido van Rossumd8faa362007-04-27 19:54:29 +00002314
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002315 slotoffset += sizeof(PyObject *);
2316 }
2317 }
2318 if (add_dict) {
2319 if (base->tp_itemsize)
2320 type->tp_dictoffset = -(long)sizeof(PyObject *);
2321 else
2322 type->tp_dictoffset = slotoffset;
2323 slotoffset += sizeof(PyObject *);
2324 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002325 if (type->tp_dictoffset) {
2326 et->ht_cached_keys = _PyDict_NewKeysForClass();
2327 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002328 if (add_weak) {
2329 assert(!base->tp_itemsize);
2330 type->tp_weaklistoffset = slotoffset;
2331 slotoffset += sizeof(PyObject *);
2332 }
2333 type->tp_basicsize = slotoffset;
2334 type->tp_itemsize = base->tp_itemsize;
2335 type->tp_members = PyHeapType_GET_MEMBERS(et);
Guido van Rossum373c7412003-01-07 13:41:37 +00002336
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002337 if (type->tp_weaklistoffset && type->tp_dictoffset)
2338 type->tp_getset = subtype_getsets_full;
2339 else if (type->tp_weaklistoffset && !type->tp_dictoffset)
2340 type->tp_getset = subtype_getsets_weakref_only;
2341 else if (!type->tp_weaklistoffset && type->tp_dictoffset)
2342 type->tp_getset = subtype_getsets_dict_only;
2343 else
2344 type->tp_getset = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002345
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002346 /* Special case some slots */
2347 if (type->tp_dictoffset != 0 || nslots > 0) {
2348 if (base->tp_getattr == NULL && base->tp_getattro == NULL)
2349 type->tp_getattro = PyObject_GenericGetAttr;
2350 if (base->tp_setattr == NULL && base->tp_setattro == NULL)
2351 type->tp_setattro = PyObject_GenericSetAttr;
2352 }
2353 type->tp_dealloc = subtype_dealloc;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002354
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002355 /* Enable GC unless there are really no instance variables possible */
2356 if (!(type->tp_basicsize == sizeof(PyObject) &&
2357 type->tp_itemsize == 0))
2358 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossum9475a232001-10-05 20:51:39 +00002359
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002360 /* Always override allocation strategy to use regular heap */
2361 type->tp_alloc = PyType_GenericAlloc;
2362 if (type->tp_flags & Py_TPFLAGS_HAVE_GC) {
2363 type->tp_free = PyObject_GC_Del;
2364 type->tp_traverse = subtype_traverse;
2365 type->tp_clear = subtype_clear;
2366 }
2367 else
2368 type->tp_free = PyObject_Del;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002369
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002370 /* Initialize the rest */
Victor Stinner6f738742012-02-25 01:22:36 +01002371 if (PyType_Ready(type) < 0)
2372 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002373
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002374 /* Put the proper slots in place */
2375 fixup_slot_dispatchers(type);
Guido van Rossumf040ede2001-08-07 16:40:56 +00002376
Victor Stinner6f738742012-02-25 01:22:36 +01002377 Py_DECREF(dict);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002378 return (PyObject *)type;
Victor Stinner6f738742012-02-25 01:22:36 +01002379
2380error:
2381 Py_XDECREF(dict);
2382 Py_XDECREF(bases);
2383 Py_XDECREF(slots);
2384 Py_XDECREF(type);
2385 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002386}
2387
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002388static short slotoffsets[] = {
2389 -1, /* invalid slot */
2390#include "typeslots.inc"
2391};
2392
Benjamin Petersone28108c2012-01-29 20:13:18 -05002393PyObject *
Martin v. Löwis9c564092012-06-23 23:20:45 +02002394PyType_FromSpecWithBases(PyType_Spec *spec, PyObject *bases)
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002395{
2396 PyHeapTypeObject *res = (PyHeapTypeObject*)PyType_GenericAlloc(&PyType_Type, 0);
Martin v. Löwis9c564092012-06-23 23:20:45 +02002397 PyTypeObject *type, *base;
2398 char *s;
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002399 char *res_start = (char*)res;
2400 PyType_Slot *slot;
Martin v. Löwis9c564092012-06-23 23:20:45 +02002401
2402 /* Set the type name and qualname */
2403 s = strrchr(spec->name, '.');
2404 if (s == NULL)
2405 s = (char*)spec->name;
2406 else
2407 s++;
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002408
Martin v. Löwis5e06a5d2011-02-21 16:24:00 +00002409 if (res == NULL)
Antoine Pitroubb78f572012-06-24 00:18:27 +02002410 return NULL;
2411 type = &res->ht_type;
Antoine Pitrou66a3a7e2012-06-24 00:42:59 +02002412 /* The flags must be initialized early, before the GC traverses us */
2413 type->tp_flags = spec->flags | Py_TPFLAGS_HEAPTYPE;
Martin v. Löwis9c564092012-06-23 23:20:45 +02002414 res->ht_name = PyUnicode_FromString(s);
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002415 if (!res->ht_name)
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002416 goto fail;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002417 res->ht_qualname = res->ht_name;
2418 Py_INCREF(res->ht_qualname);
Antoine Pitroubb78f572012-06-24 00:18:27 +02002419 type->tp_name = spec->name;
2420 if (!type->tp_name)
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002421 goto fail;
Martin v. Löwis9c564092012-06-23 23:20:45 +02002422
2423 /* Adjust for empty tuple bases */
2424 if (!bases) {
2425 base = &PyBaseObject_Type;
2426 /* See whether Py_tp_base(s) was specified */
2427 for (slot = spec->slots; slot->slot; slot++) {
2428 if (slot->slot == Py_tp_base)
2429 base = slot->pfunc;
2430 else if (slot->slot == Py_tp_bases) {
2431 bases = slot->pfunc;
2432 Py_INCREF(bases);
2433 }
2434 }
2435 if (!bases)
2436 bases = PyTuple_Pack(1, base);
2437 if (!bases)
2438 goto fail;
2439 }
2440 else
2441 Py_INCREF(bases);
2442
2443 /* Calculate best base, and check that all bases are type objects */
2444 base = best_base(bases);
2445 if (base == NULL) {
2446 goto fail;
2447 }
2448 if (!PyType_HasFeature(base, Py_TPFLAGS_BASETYPE)) {
2449 PyErr_Format(PyExc_TypeError,
2450 "type '%.100s' is not an acceptable base type",
2451 base->tp_name);
2452 goto fail;
2453 }
2454
Martin v. Löwis9c564092012-06-23 23:20:45 +02002455 /* Initialize essential fields */
2456 type->tp_as_number = &res->as_number;
2457 type->tp_as_sequence = &res->as_sequence;
2458 type->tp_as_mapping = &res->as_mapping;
2459 type->tp_as_buffer = &res->as_buffer;
2460 /* Set tp_base and tp_bases */
2461 type->tp_bases = bases;
2462 bases = NULL;
2463 Py_INCREF(base);
2464 type->tp_base = base;
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002465
Antoine Pitroubb78f572012-06-24 00:18:27 +02002466 type->tp_basicsize = spec->basicsize;
2467 type->tp_itemsize = spec->itemsize;
Victor Stinner0fcab4a2011-01-04 12:59:15 +00002468
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002469 for (slot = spec->slots; slot->slot; slot++) {
Victor Stinner63941882011-09-29 00:42:28 +02002470 if (slot->slot >= Py_ARRAY_LENGTH(slotoffsets)) {
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002471 PyErr_SetString(PyExc_RuntimeError, "invalid slot offset");
2472 goto fail;
2473 }
Martin v. Löwis9c564092012-06-23 23:20:45 +02002474 if (slot->slot == Py_tp_base || slot->slot == Py_tp_bases)
2475 /* Processed above */
2476 continue;
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002477 *(void**)(res_start + slotoffsets[slot->slot]) = slot->pfunc;
Georg Brandl032400b2011-02-19 21:47:02 +00002478
2479 /* need to make a copy of the docstring slot, which usually
2480 points to a static string literal */
2481 if (slot->slot == Py_tp_doc) {
Antoine Pitrou682d94c2012-05-14 14:43:03 +02002482 size_t len = strlen(slot->pfunc)+1;
Georg Brandl032400b2011-02-19 21:47:02 +00002483 char *tp_doc = PyObject_MALLOC(len);
2484 if (tp_doc == NULL)
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002485 goto fail;
Georg Brandl032400b2011-02-19 21:47:02 +00002486 memcpy(tp_doc, slot->pfunc, len);
Antoine Pitroubb78f572012-06-24 00:18:27 +02002487 type->tp_doc = tp_doc;
Georg Brandl032400b2011-02-19 21:47:02 +00002488 }
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002489 }
Antoine Pitroubb78f572012-06-24 00:18:27 +02002490 if (type->tp_dictoffset) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002491 res->ht_cached_keys = _PyDict_NewKeysForClass();
2492 }
Antoine Pitroubb78f572012-06-24 00:18:27 +02002493 if (type->tp_dealloc == NULL) {
Antoine Pitrou99cc6292012-06-23 14:42:38 +02002494 /* It's a heap type, so needs the heap types' dealloc.
2495 subtype_dealloc will call the base type's tp_dealloc, if
2496 necessary. */
Antoine Pitroubb78f572012-06-24 00:18:27 +02002497 type->tp_dealloc = subtype_dealloc;
Antoine Pitrou99cc6292012-06-23 14:42:38 +02002498 }
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002499
Antoine Pitroubb78f572012-06-24 00:18:27 +02002500 if (PyType_Ready(type) < 0)
Benjamin Peterson2652d252012-01-29 20:16:37 -05002501 goto fail;
2502
Martin v. Löwis9c564092012-06-23 23:20:45 +02002503 /* Set type.__module__ */
2504 s = strrchr(spec->name, '.');
2505 if (s != NULL)
2506 _PyDict_SetItemId(type->tp_dict, &PyId___module__,
2507 PyUnicode_FromStringAndSize(
2508 spec->name, (Py_ssize_t)(s - spec->name)));
2509
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002510 return (PyObject*)res;
Victor Stinner0fcab4a2011-01-04 12:59:15 +00002511
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002512 fail:
2513 Py_DECREF(res);
2514 return NULL;
2515}
2516
Martin v. Löwis9c564092012-06-23 23:20:45 +02002517PyObject *
2518PyType_FromSpec(PyType_Spec *spec)
2519{
2520 return PyType_FromSpecWithBases(spec, NULL);
2521}
2522
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002523
Tim Peters6d6c1a32001-08-02 04:15:00 +00002524/* Internal API to look for a name through the MRO.
2525 This returns a borrowed reference, and doesn't set an exception! */
2526PyObject *
2527_PyType_Lookup(PyTypeObject *type, PyObject *name)
2528{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002529 Py_ssize_t i, n;
2530 PyObject *mro, *res, *base, *dict;
2531 unsigned int h;
Christian Heimesa62da1d2008-01-12 19:39:10 +00002532
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002533 if (MCACHE_CACHEABLE_NAME(name) &&
2534 PyType_HasFeature(type, Py_TPFLAGS_VALID_VERSION_TAG)) {
2535 /* fast path */
2536 h = MCACHE_HASH_METHOD(type, name);
2537 if (method_cache[h].version == type->tp_version_tag &&
2538 method_cache[h].name == name)
2539 return method_cache[h].value;
2540 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002541
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002542 /* Look in tp_dict of types in MRO */
2543 mro = type->tp_mro;
Guido van Rossum23094982002-06-10 14:30:43 +00002544
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002545 /* If mro is NULL, the type is either not yet initialized
2546 by PyType_Ready(), or already cleared by type_clear().
2547 Either way the safest thing to do is to return NULL. */
2548 if (mro == NULL)
2549 return NULL;
Guido van Rossum23094982002-06-10 14:30:43 +00002550
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002551 res = NULL;
Victor Stinnerd74782b2012-03-09 00:39:08 +01002552 /* keep a strong reference to mro because type->tp_mro can be replaced
2553 during PyDict_GetItem(dict, name) */
2554 Py_INCREF(mro);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002555 assert(PyTuple_Check(mro));
2556 n = PyTuple_GET_SIZE(mro);
2557 for (i = 0; i < n; i++) {
2558 base = PyTuple_GET_ITEM(mro, i);
2559 assert(PyType_Check(base));
2560 dict = ((PyTypeObject *)base)->tp_dict;
2561 assert(dict && PyDict_Check(dict));
2562 res = PyDict_GetItem(dict, name);
2563 if (res != NULL)
2564 break;
2565 }
Victor Stinnerd74782b2012-03-09 00:39:08 +01002566 Py_DECREF(mro);
Christian Heimesa62da1d2008-01-12 19:39:10 +00002567
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002568 if (MCACHE_CACHEABLE_NAME(name) && assign_version_tag(type)) {
2569 h = MCACHE_HASH_METHOD(type, name);
2570 method_cache[h].version = type->tp_version_tag;
2571 method_cache[h].value = res; /* borrowed */
2572 Py_INCREF(name);
2573 Py_DECREF(method_cache[h].name);
2574 method_cache[h].name = name;
2575 }
2576 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002577}
2578
Victor Stinner3c1e4812012-03-26 22:10:51 +02002579static PyObject *
2580_PyType_LookupId(PyTypeObject *type, struct _Py_Identifier *name)
2581{
2582 PyObject *oname;
2583 oname = _PyUnicode_FromId(name); /* borrowed */
2584 if (oname == NULL)
2585 return NULL;
2586 return _PyType_Lookup(type, oname);
2587}
2588
Tim Peters6d6c1a32001-08-02 04:15:00 +00002589/* This is similar to PyObject_GenericGetAttr(),
2590 but uses _PyType_Lookup() instead of just looking in type->tp_dict. */
2591static PyObject *
2592type_getattro(PyTypeObject *type, PyObject *name)
2593{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002594 PyTypeObject *metatype = Py_TYPE(type);
2595 PyObject *meta_attribute, *attribute;
2596 descrgetfunc meta_get;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002597
Benjamin Peterson16d84ac2012-03-16 09:32:59 -05002598 if (!PyUnicode_Check(name)) {
2599 PyErr_Format(PyExc_TypeError,
2600 "attribute name must be string, not '%.200s'",
2601 name->ob_type->tp_name);
2602 return NULL;
2603 }
2604
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002605 /* Initialize this type (we'll assume the metatype is initialized) */
2606 if (type->tp_dict == NULL) {
2607 if (PyType_Ready(type) < 0)
2608 return NULL;
2609 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002610
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002611 /* No readable descriptor found yet */
2612 meta_get = NULL;
Tim Peters34592512002-07-11 06:23:50 +00002613
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002614 /* Look for the attribute in the metatype */
2615 meta_attribute = _PyType_Lookup(metatype, name);
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002616
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002617 if (meta_attribute != NULL) {
2618 meta_get = Py_TYPE(meta_attribute)->tp_descr_get;
Tim Peters34592512002-07-11 06:23:50 +00002619
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002620 if (meta_get != NULL && PyDescr_IsData(meta_attribute)) {
2621 /* Data descriptors implement tp_descr_set to intercept
2622 * writes. Assume the attribute is not overridden in
2623 * type's tp_dict (and bases): call the descriptor now.
2624 */
2625 return meta_get(meta_attribute, (PyObject *)type,
2626 (PyObject *)metatype);
2627 }
2628 Py_INCREF(meta_attribute);
2629 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002630
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002631 /* No data descriptor found on metatype. Look in tp_dict of this
2632 * type and its bases */
2633 attribute = _PyType_Lookup(type, name);
2634 if (attribute != NULL) {
2635 /* Implement descriptor functionality, if any */
2636 descrgetfunc local_get = Py_TYPE(attribute)->tp_descr_get;
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00002637
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002638 Py_XDECREF(meta_attribute);
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00002639
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002640 if (local_get != NULL) {
2641 /* NULL 2nd argument indicates the descriptor was
2642 * found on the target object itself (or a base) */
2643 return local_get(attribute, (PyObject *)NULL,
2644 (PyObject *)type);
2645 }
Tim Peters34592512002-07-11 06:23:50 +00002646
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002647 Py_INCREF(attribute);
2648 return attribute;
2649 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002650
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002651 /* No attribute found in local __dict__ (or bases): use the
2652 * descriptor from the metatype, if any */
2653 if (meta_get != NULL) {
2654 PyObject *res;
2655 res = meta_get(meta_attribute, (PyObject *)type,
2656 (PyObject *)metatype);
2657 Py_DECREF(meta_attribute);
2658 return res;
2659 }
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002660
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002661 /* If an ordinary attribute was found on the metatype, return it now */
2662 if (meta_attribute != NULL) {
2663 return meta_attribute;
2664 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002665
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002666 /* Give up */
2667 PyErr_Format(PyExc_AttributeError,
2668 "type object '%.50s' has no attribute '%U'",
2669 type->tp_name, name);
2670 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002671}
2672
2673static int
2674type_setattro(PyTypeObject *type, PyObject *name, PyObject *value)
2675{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002676 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
2677 PyErr_Format(
2678 PyExc_TypeError,
2679 "can't set attributes of built-in/extension type '%s'",
2680 type->tp_name);
2681 return -1;
2682 }
2683 if (PyObject_GenericSetAttr((PyObject *)type, name, value) < 0)
2684 return -1;
2685 return update_slot(type, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002686}
2687
Benjamin Peterson64acccf2012-04-27 15:07:36 -04002688extern void
2689_PyDictKeys_DecRef(PyDictKeysObject *keys);
2690
Tim Peters6d6c1a32001-08-02 04:15:00 +00002691static void
2692type_dealloc(PyTypeObject *type)
2693{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002694 PyHeapTypeObject *et;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002695
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002696 /* Assert this is a heap-allocated type object */
2697 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
2698 _PyObject_GC_UNTRACK(type);
2699 PyObject_ClearWeakRefs((PyObject *)type);
2700 et = (PyHeapTypeObject *)type;
2701 Py_XDECREF(type->tp_base);
2702 Py_XDECREF(type->tp_dict);
2703 Py_XDECREF(type->tp_bases);
2704 Py_XDECREF(type->tp_mro);
2705 Py_XDECREF(type->tp_cache);
2706 Py_XDECREF(type->tp_subclasses);
2707 /* A type's tp_doc is heap allocated, unlike the tp_doc slots
2708 * of most other objects. It's okay to cast it to char *.
2709 */
2710 PyObject_Free((char *)type->tp_doc);
2711 Py_XDECREF(et->ht_name);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002712 Py_XDECREF(et->ht_qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002713 Py_XDECREF(et->ht_slots);
Benjamin Peterson64acccf2012-04-27 15:07:36 -04002714 if (et->ht_cached_keys)
2715 _PyDictKeys_DecRef(et->ht_cached_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002716 Py_TYPE(type)->tp_free((PyObject *)type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002717}
2718
Guido van Rossum1c450732001-10-08 15:18:27 +00002719static PyObject *
2720type_subclasses(PyTypeObject *type, PyObject *args_ignored)
2721{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002722 PyObject *list, *raw, *ref;
2723 Py_ssize_t i, n;
Guido van Rossum1c450732001-10-08 15:18:27 +00002724
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002725 list = PyList_New(0);
2726 if (list == NULL)
2727 return NULL;
2728 raw = type->tp_subclasses;
2729 if (raw == NULL)
2730 return list;
2731 assert(PyList_Check(raw));
2732 n = PyList_GET_SIZE(raw);
2733 for (i = 0; i < n; i++) {
2734 ref = PyList_GET_ITEM(raw, i);
2735 assert(PyWeakref_CheckRef(ref));
2736 ref = PyWeakref_GET_OBJECT(ref);
2737 if (ref != Py_None) {
2738 if (PyList_Append(list, ref) < 0) {
2739 Py_DECREF(list);
2740 return NULL;
2741 }
2742 }
2743 }
2744 return list;
Guido van Rossum1c450732001-10-08 15:18:27 +00002745}
2746
Guido van Rossum47374822007-08-02 16:48:17 +00002747static PyObject *
2748type_prepare(PyObject *self, PyObject *args, PyObject *kwds)
2749{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002750 return PyDict_New();
Guido van Rossum47374822007-08-02 16:48:17 +00002751}
2752
Victor Stinner63941882011-09-29 00:42:28 +02002753/*
Benjamin Peterson82b00c12011-05-24 11:09:06 -05002754 Merge the __dict__ of aclass into dict, and recursively also all
2755 the __dict__s of aclass's base classes. The order of merging isn't
2756 defined, as it's expected that only the final set of dict keys is
2757 interesting.
2758 Return 0 on success, -1 on error.
2759*/
2760
2761static int
2762merge_class_dict(PyObject *dict, PyObject *aclass)
2763{
2764 PyObject *classdict;
2765 PyObject *bases;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02002766 _Py_IDENTIFIER(__bases__);
Benjamin Peterson82b00c12011-05-24 11:09:06 -05002767
2768 assert(PyDict_Check(dict));
2769 assert(aclass);
2770
2771 /* Merge in the type's dict (if any). */
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002772 classdict = _PyObject_GetAttrId(aclass, &PyId___dict__);
Benjamin Peterson82b00c12011-05-24 11:09:06 -05002773 if (classdict == NULL)
2774 PyErr_Clear();
2775 else {
2776 int status = PyDict_Update(dict, classdict);
2777 Py_DECREF(classdict);
2778 if (status < 0)
2779 return -1;
2780 }
2781
2782 /* Recursively merge in the base types' (if any) dicts. */
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002783 bases = _PyObject_GetAttrId(aclass, &PyId___bases__);
Benjamin Peterson82b00c12011-05-24 11:09:06 -05002784 if (bases == NULL)
2785 PyErr_Clear();
2786 else {
2787 /* We have no guarantee that bases is a real tuple */
2788 Py_ssize_t i, n;
2789 n = PySequence_Size(bases); /* This better be right */
2790 if (n < 0)
2791 PyErr_Clear();
2792 else {
2793 for (i = 0; i < n; i++) {
2794 int status;
2795 PyObject *base = PySequence_GetItem(bases, i);
2796 if (base == NULL) {
2797 Py_DECREF(bases);
2798 return -1;
2799 }
2800 status = merge_class_dict(dict, base);
2801 Py_DECREF(base);
2802 if (status < 0) {
2803 Py_DECREF(bases);
2804 return -1;
2805 }
2806 }
2807 }
2808 Py_DECREF(bases);
2809 }
2810 return 0;
2811}
2812
2813/* __dir__ for type objects: returns __dict__ and __bases__.
2814 We deliberately don't suck up its __class__, as methods belonging to the
2815 metaclass would probably be more confusing than helpful.
2816*/
2817static PyObject *
2818type_dir(PyObject *self, PyObject *args)
2819{
2820 PyObject *result = NULL;
2821 PyObject *dict = PyDict_New();
2822
2823 if (dict != NULL && merge_class_dict(dict, self) == 0)
2824 result = PyDict_Keys(dict);
2825
2826 Py_XDECREF(dict);
2827 return result;
2828}
2829
Martin v. Loewis4f2f3b62012-04-24 19:13:57 +02002830static PyObject*
2831type_sizeof(PyObject *self, PyObject *args_unused)
2832{
2833 Py_ssize_t size;
2834 PyTypeObject *type = (PyTypeObject*)self;
2835 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
2836 PyHeapTypeObject* et = (PyHeapTypeObject*)type;
2837 size = sizeof(PyHeapTypeObject);
2838 if (et->ht_cached_keys)
2839 size += _PyDict_KeysSize(et->ht_cached_keys);
2840 }
2841 else
2842 size = sizeof(PyTypeObject);
2843 return PyLong_FromSsize_t(size);
2844}
2845
Tim Peters6d6c1a32001-08-02 04:15:00 +00002846static PyMethodDef type_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002847 {"mro", (PyCFunction)mro_external, METH_NOARGS,
2848 PyDoc_STR("mro() -> list\nreturn a type's method resolution order")},
2849 {"__subclasses__", (PyCFunction)type_subclasses, METH_NOARGS,
2850 PyDoc_STR("__subclasses__() -> list of immediate subclasses")},
2851 {"__prepare__", (PyCFunction)type_prepare,
2852 METH_VARARGS | METH_KEYWORDS | METH_CLASS,
2853 PyDoc_STR("__prepare__() -> dict\n"
2854 "used to create the namespace for the class statement")},
2855 {"__instancecheck__", type___instancecheck__, METH_O,
Benjamin Petersonfbe56bb2011-05-24 12:42:51 -05002856 PyDoc_STR("__instancecheck__() -> bool\ncheck if an object is an instance")},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002857 {"__subclasscheck__", type___subclasscheck__, METH_O,
Benjamin Petersonfbe56bb2011-05-24 12:42:51 -05002858 PyDoc_STR("__subclasscheck__() -> bool\ncheck if a class is a subclass")},
Benjamin Peterson82b00c12011-05-24 11:09:06 -05002859 {"__dir__", type_dir, METH_NOARGS,
Benjamin Petersonc7284122011-05-24 12:46:15 -05002860 PyDoc_STR("__dir__() -> list\nspecialized __dir__ implementation for types")},
Martin v. Loewis4f2f3b62012-04-24 19:13:57 +02002861 {"__sizeof__", type_sizeof, METH_NOARGS,
2862 "__sizeof__() -> int\nreturn memory consumption of the type object"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002863 {0}
Tim Peters6d6c1a32001-08-02 04:15:00 +00002864};
2865
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002866PyDoc_STRVAR(type_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00002867"type(object) -> the object's type\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002868"type(name, bases, dict) -> a new type");
Tim Peters6d6c1a32001-08-02 04:15:00 +00002869
Guido van Rossum048eb752001-10-02 21:24:57 +00002870static int
2871type_traverse(PyTypeObject *type, visitproc visit, void *arg)
2872{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002873 /* Because of type_is_gc(), the collector only calls this
2874 for heaptypes. */
Antoine Pitrou1351ca62012-06-24 00:30:12 +02002875 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
2876 char msg[200];
2877 sprintf(msg, "type_traverse() called for non-heap type '%.100s'",
2878 type->tp_name);
2879 Py_FatalError(msg);
2880 }
Guido van Rossum048eb752001-10-02 21:24:57 +00002881
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002882 Py_VISIT(type->tp_dict);
2883 Py_VISIT(type->tp_cache);
2884 Py_VISIT(type->tp_mro);
2885 Py_VISIT(type->tp_bases);
2886 Py_VISIT(type->tp_base);
Guido van Rossuma3862092002-06-10 15:24:42 +00002887
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002888 /* There's no need to visit type->tp_subclasses or
2889 ((PyHeapTypeObject *)type)->ht_slots, because they can't be involved
2890 in cycles; tp_subclasses is a list of weak references,
2891 and slots is a tuple of strings. */
Guido van Rossum048eb752001-10-02 21:24:57 +00002892
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002893 return 0;
Guido van Rossum048eb752001-10-02 21:24:57 +00002894}
2895
2896static int
2897type_clear(PyTypeObject *type)
2898{
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002899 PyDictKeysObject *cached_keys;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002900 /* Because of type_is_gc(), the collector only calls this
2901 for heaptypes. */
2902 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002903
Antoine Pitrou2e872082011-12-15 14:15:31 +01002904 /* We need to invalidate the method cache carefully before clearing
2905 the dict, so that other objects caught in a reference cycle
2906 don't start calling destroyed methods.
2907
2908 Otherwise, the only field we need to clear is tp_mro, which is
2909 part of a hard cycle (its first element is the class itself) that
2910 won't be broken otherwise (it's a tuple and tuples don't have a
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002911 tp_clear handler). None of the other fields need to be
2912 cleared, and here's why:
Guido van Rossum048eb752001-10-02 21:24:57 +00002913
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002914 tp_cache:
2915 Not used; if it were, it would be a dict.
Guido van Rossuma3862092002-06-10 15:24:42 +00002916
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002917 tp_bases, tp_base:
2918 If these are involved in a cycle, there must be at least
2919 one other, mutable object in the cycle, e.g. a base
2920 class's dict; the cycle will be broken that way.
Guido van Rossuma3862092002-06-10 15:24:42 +00002921
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002922 tp_subclasses:
2923 A list of weak references can't be part of a cycle; and
2924 lists have their own tp_clear.
Guido van Rossuma3862092002-06-10 15:24:42 +00002925
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002926 slots (in PyHeapTypeObject):
2927 A tuple of strings can't be part of a cycle.
2928 */
Guido van Rossuma3862092002-06-10 15:24:42 +00002929
Antoine Pitrou2e872082011-12-15 14:15:31 +01002930 PyType_Modified(type);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002931 cached_keys = ((PyHeapTypeObject *)type)->ht_cached_keys;
2932 if (cached_keys != NULL) {
2933 ((PyHeapTypeObject *)type)->ht_cached_keys = NULL;
2934 _PyDictKeys_DecRef(cached_keys);
2935 }
Antoine Pitrou2e872082011-12-15 14:15:31 +01002936 if (type->tp_dict)
2937 PyDict_Clear(type->tp_dict);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002938 Py_CLEAR(type->tp_mro);
Guido van Rossum048eb752001-10-02 21:24:57 +00002939
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002940 return 0;
Guido van Rossum048eb752001-10-02 21:24:57 +00002941}
2942
2943static int
2944type_is_gc(PyTypeObject *type)
2945{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002946 return type->tp_flags & Py_TPFLAGS_HEAPTYPE;
Guido van Rossum048eb752001-10-02 21:24:57 +00002947}
2948
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002949PyTypeObject PyType_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002950 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2951 "type", /* tp_name */
2952 sizeof(PyHeapTypeObject), /* tp_basicsize */
2953 sizeof(PyMemberDef), /* tp_itemsize */
2954 (destructor)type_dealloc, /* tp_dealloc */
2955 0, /* tp_print */
2956 0, /* tp_getattr */
2957 0, /* tp_setattr */
2958 0, /* tp_reserved */
2959 (reprfunc)type_repr, /* tp_repr */
2960 0, /* tp_as_number */
2961 0, /* tp_as_sequence */
2962 0, /* tp_as_mapping */
2963 0, /* tp_hash */
2964 (ternaryfunc)type_call, /* tp_call */
2965 0, /* tp_str */
2966 (getattrofunc)type_getattro, /* tp_getattro */
2967 (setattrofunc)type_setattro, /* tp_setattro */
2968 0, /* tp_as_buffer */
2969 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
2970 Py_TPFLAGS_BASETYPE | Py_TPFLAGS_TYPE_SUBCLASS, /* tp_flags */
2971 type_doc, /* tp_doc */
2972 (traverseproc)type_traverse, /* tp_traverse */
2973 (inquiry)type_clear, /* tp_clear */
2974 0, /* tp_richcompare */
2975 offsetof(PyTypeObject, tp_weaklist), /* tp_weaklistoffset */
2976 0, /* tp_iter */
2977 0, /* tp_iternext */
2978 type_methods, /* tp_methods */
2979 type_members, /* tp_members */
2980 type_getsets, /* tp_getset */
2981 0, /* tp_base */
2982 0, /* tp_dict */
2983 0, /* tp_descr_get */
2984 0, /* tp_descr_set */
2985 offsetof(PyTypeObject, tp_dict), /* tp_dictoffset */
2986 type_init, /* tp_init */
2987 0, /* tp_alloc */
2988 type_new, /* tp_new */
2989 PyObject_GC_Del, /* tp_free */
2990 (inquiry)type_is_gc, /* tp_is_gc */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002991};
Tim Peters6d6c1a32001-08-02 04:15:00 +00002992
2993
2994/* The base type of all types (eventually)... except itself. */
2995
Guido van Rossumd8faa362007-04-27 19:54:29 +00002996/* You may wonder why object.__new__() only complains about arguments
2997 when object.__init__() is not overridden, and vice versa.
2998
2999 Consider the use cases:
3000
3001 1. When neither is overridden, we want to hear complaints about
3002 excess (i.e., any) arguments, since their presence could
3003 indicate there's a bug.
3004
3005 2. When defining an Immutable type, we are likely to override only
3006 __new__(), since __init__() is called too late to initialize an
3007 Immutable object. Since __new__() defines the signature for the
3008 type, it would be a pain to have to override __init__() just to
3009 stop it from complaining about excess arguments.
3010
3011 3. When defining a Mutable type, we are likely to override only
3012 __init__(). So here the converse reasoning applies: we don't
3013 want to have to override __new__() just to stop it from
3014 complaining.
3015
3016 4. When __init__() is overridden, and the subclass __init__() calls
3017 object.__init__(), the latter should complain about excess
3018 arguments; ditto for __new__().
3019
3020 Use cases 2 and 3 make it unattractive to unconditionally check for
3021 excess arguments. The best solution that addresses all four use
3022 cases is as follows: __init__() complains about excess arguments
3023 unless __new__() is overridden and __init__() is not overridden
3024 (IOW, if __init__() is overridden or __new__() is not overridden);
3025 symmetrically, __new__() complains about excess arguments unless
3026 __init__() is overridden and __new__() is not overridden
3027 (IOW, if __new__() is overridden or __init__() is not overridden).
3028
3029 However, for backwards compatibility, this breaks too much code.
3030 Therefore, in 2.6, we'll *warn* about excess arguments when both
3031 methods are overridden; for all other cases we'll use the above
3032 rules.
3033
3034*/
3035
3036/* Forward */
3037static PyObject *
3038object_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
3039
3040static int
3041excess_args(PyObject *args, PyObject *kwds)
3042{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003043 return PyTuple_GET_SIZE(args) ||
3044 (kwds && PyDict_Check(kwds) && PyDict_Size(kwds));
Guido van Rossumd8faa362007-04-27 19:54:29 +00003045}
3046
Tim Peters6d6c1a32001-08-02 04:15:00 +00003047static int
3048object_init(PyObject *self, PyObject *args, PyObject *kwds)
3049{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003050 int err = 0;
Benjamin Peterson96384b92012-03-17 00:05:44 -05003051 PyTypeObject *type = Py_TYPE(self);
3052 if (excess_args(args, kwds) &&
3053 (type->tp_new == object_new || type->tp_init != object_init)) {
3054 PyErr_SetString(PyExc_TypeError, "object.__init__() takes no parameters");
3055 err = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003056 }
3057 return err;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003058}
3059
Guido van Rossum298e4212003-02-13 16:30:16 +00003060static PyObject *
3061object_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3062{
Benjamin Peterson96384b92012-03-17 00:05:44 -05003063 if (excess_args(args, kwds) &&
3064 (type->tp_init == object_init || type->tp_new != object_new)) {
R David Murray702a5dc2013-02-18 21:39:18 -05003065 PyErr_SetString(PyExc_TypeError, "object() takes no parameters");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003066 return NULL;
Benjamin Peterson96384b92012-03-17 00:05:44 -05003067 }
Victor Stinner3c1e4812012-03-26 22:10:51 +02003068
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003069 if (type->tp_flags & Py_TPFLAGS_IS_ABSTRACT) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003070 PyObject *abstract_methods = NULL;
3071 PyObject *builtins;
3072 PyObject *sorted;
3073 PyObject *sorted_methods = NULL;
3074 PyObject *joined = NULL;
Benjamin Peterson9a03ecf2012-03-16 20:15:54 -05003075 PyObject *comma;
3076 _Py_static_string(comma_id, ", ");
Victor Stinner3c1e4812012-03-26 22:10:51 +02003077 _Py_IDENTIFIER(sorted);
Christian Heimes9e7f1d22008-02-28 12:27:11 +00003078
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003079 /* Compute ", ".join(sorted(type.__abstractmethods__))
3080 into joined. */
3081 abstract_methods = type_abstractmethods(type, NULL);
3082 if (abstract_methods == NULL)
3083 goto error;
3084 builtins = PyEval_GetBuiltins();
3085 if (builtins == NULL)
3086 goto error;
Victor Stinner3c1e4812012-03-26 22:10:51 +02003087 sorted = _PyDict_GetItemId(builtins, &PyId_sorted);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003088 if (sorted == NULL)
3089 goto error;
3090 sorted_methods = PyObject_CallFunctionObjArgs(sorted,
3091 abstract_methods,
3092 NULL);
3093 if (sorted_methods == NULL)
3094 goto error;
Benjamin Peterson9a03ecf2012-03-16 20:15:54 -05003095 comma = _PyUnicode_FromId(&comma_id);
3096 if (comma == NULL)
3097 goto error;
3098 joined = PyUnicode_Join(comma, sorted_methods);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003099 if (joined == NULL)
3100 goto error;
Christian Heimes9e7f1d22008-02-28 12:27:11 +00003101
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003102 PyErr_Format(PyExc_TypeError,
3103 "Can't instantiate abstract class %s "
3104 "with abstract methods %U",
3105 type->tp_name,
3106 joined);
3107 error:
3108 Py_XDECREF(joined);
3109 Py_XDECREF(sorted_methods);
3110 Py_XDECREF(abstract_methods);
3111 return NULL;
3112 }
3113 return type->tp_alloc(type, 0);
Guido van Rossum298e4212003-02-13 16:30:16 +00003114}
3115
Tim Peters6d6c1a32001-08-02 04:15:00 +00003116static void
3117object_dealloc(PyObject *self)
3118{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003119 Py_TYPE(self)->tp_free(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003120}
3121
Guido van Rossum8e248182001-08-12 05:17:56 +00003122static PyObject *
3123object_repr(PyObject *self)
3124{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003125 PyTypeObject *type;
3126 PyObject *mod, *name, *rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00003127
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003128 type = Py_TYPE(self);
3129 mod = type_module(type, NULL);
3130 if (mod == NULL)
3131 PyErr_Clear();
3132 else if (!PyUnicode_Check(mod)) {
3133 Py_DECREF(mod);
3134 mod = NULL;
3135 }
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003136 name = type_qualname(type, NULL);
Christian Heimese81dc292012-09-10 16:57:36 +02003137 if (name == NULL) {
3138 Py_XDECREF(mod);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003139 return NULL;
Christian Heimese81dc292012-09-10 16:57:36 +02003140 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003141 if (mod != NULL && PyUnicode_CompareWithASCIIString(mod, "builtins"))
3142 rtn = PyUnicode_FromFormat("<%U.%U object at %p>", mod, name, self);
3143 else
3144 rtn = PyUnicode_FromFormat("<%s object at %p>",
3145 type->tp_name, self);
3146 Py_XDECREF(mod);
3147 Py_DECREF(name);
3148 return rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00003149}
3150
Guido van Rossumb8f63662001-08-15 23:57:02 +00003151static PyObject *
3152object_str(PyObject *self)
3153{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003154 unaryfunc f;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003155
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003156 f = Py_TYPE(self)->tp_repr;
Benjamin Peterson7b166872012-04-24 11:06:25 -04003157 if (f == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003158 f = object_repr;
3159 return f(self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003160}
3161
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003162static PyObject *
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003163object_richcompare(PyObject *self, PyObject *other, int op)
3164{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003165 PyObject *res;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003166
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003167 switch (op) {
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003168
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003169 case Py_EQ:
3170 /* Return NotImplemented instead of False, so if two
3171 objects are compared, both get a chance at the
3172 comparison. See issue #1393. */
3173 res = (self == other) ? Py_True : Py_NotImplemented;
3174 Py_INCREF(res);
3175 break;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003176
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003177 case Py_NE:
3178 /* By default, != returns the opposite of ==,
3179 unless the latter returns NotImplemented. */
3180 res = PyObject_RichCompare(self, other, Py_EQ);
3181 if (res != NULL && res != Py_NotImplemented) {
3182 int ok = PyObject_IsTrue(res);
3183 Py_DECREF(res);
3184 if (ok < 0)
3185 res = NULL;
3186 else {
3187 if (ok)
3188 res = Py_False;
3189 else
3190 res = Py_True;
3191 Py_INCREF(res);
3192 }
3193 }
3194 break;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003195
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003196 default:
3197 res = Py_NotImplemented;
3198 Py_INCREF(res);
3199 break;
3200 }
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003201
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003202 return res;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003203}
3204
3205static PyObject *
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003206object_get_class(PyObject *self, void *closure)
3207{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003208 Py_INCREF(Py_TYPE(self));
3209 return (PyObject *)(Py_TYPE(self));
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003210}
3211
3212static int
3213equiv_structs(PyTypeObject *a, PyTypeObject *b)
3214{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003215 return a == b ||
3216 (a != NULL &&
3217 b != NULL &&
3218 a->tp_basicsize == b->tp_basicsize &&
3219 a->tp_itemsize == b->tp_itemsize &&
3220 a->tp_dictoffset == b->tp_dictoffset &&
3221 a->tp_weaklistoffset == b->tp_weaklistoffset &&
3222 ((a->tp_flags & Py_TPFLAGS_HAVE_GC) ==
3223 (b->tp_flags & Py_TPFLAGS_HAVE_GC)));
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003224}
3225
3226static int
3227same_slots_added(PyTypeObject *a, PyTypeObject *b)
3228{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003229 PyTypeObject *base = a->tp_base;
3230 Py_ssize_t size;
3231 PyObject *slots_a, *slots_b;
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003232
Benjamin Peterson67641d22011-01-17 19:24:34 +00003233 assert(base == b->tp_base);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003234 size = base->tp_basicsize;
3235 if (a->tp_dictoffset == size && b->tp_dictoffset == size)
3236 size += sizeof(PyObject *);
3237 if (a->tp_weaklistoffset == size && b->tp_weaklistoffset == size)
3238 size += sizeof(PyObject *);
Guido van Rossumd8faa362007-04-27 19:54:29 +00003239
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003240 /* Check slots compliance */
3241 slots_a = ((PyHeapTypeObject *)a)->ht_slots;
3242 slots_b = ((PyHeapTypeObject *)b)->ht_slots;
3243 if (slots_a && slots_b) {
3244 if (PyObject_RichCompareBool(slots_a, slots_b, Py_EQ) != 1)
3245 return 0;
3246 size += sizeof(PyObject *) * PyTuple_GET_SIZE(slots_a);
3247 }
3248 return size == a->tp_basicsize && size == b->tp_basicsize;
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003249}
3250
3251static int
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003252compatible_for_assignment(PyTypeObject* oldto, PyTypeObject* newto, char* attr)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003253{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003254 PyTypeObject *newbase, *oldbase;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003255
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003256 if (newto->tp_dealloc != oldto->tp_dealloc ||
3257 newto->tp_free != oldto->tp_free)
3258 {
3259 PyErr_Format(PyExc_TypeError,
3260 "%s assignment: "
3261 "'%s' deallocator differs from '%s'",
3262 attr,
3263 newto->tp_name,
3264 oldto->tp_name);
3265 return 0;
3266 }
3267 newbase = newto;
3268 oldbase = oldto;
3269 while (equiv_structs(newbase, newbase->tp_base))
3270 newbase = newbase->tp_base;
3271 while (equiv_structs(oldbase, oldbase->tp_base))
3272 oldbase = oldbase->tp_base;
3273 if (newbase != oldbase &&
3274 (newbase->tp_base != oldbase->tp_base ||
3275 !same_slots_added(newbase, oldbase))) {
3276 PyErr_Format(PyExc_TypeError,
3277 "%s assignment: "
3278 "'%s' object layout differs from '%s'",
3279 attr,
3280 newto->tp_name,
3281 oldto->tp_name);
3282 return 0;
3283 }
Tim Petersea7f75d2002-12-07 21:39:16 +00003284
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003285 return 1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003286}
3287
3288static int
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003289object_set_class(PyObject *self, PyObject *value, void *closure)
3290{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003291 PyTypeObject *oldto = Py_TYPE(self);
3292 PyTypeObject *newto;
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003293
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003294 if (value == NULL) {
3295 PyErr_SetString(PyExc_TypeError,
3296 "can't delete __class__ attribute");
3297 return -1;
3298 }
3299 if (!PyType_Check(value)) {
3300 PyErr_Format(PyExc_TypeError,
Florent Xiclunaaa6c1d22011-12-12 18:54:29 +01003301 "__class__ must be set to a class, not '%s' object",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003302 Py_TYPE(value)->tp_name);
3303 return -1;
3304 }
3305 newto = (PyTypeObject *)value;
3306 if (!(newto->tp_flags & Py_TPFLAGS_HEAPTYPE) ||
3307 !(oldto->tp_flags & Py_TPFLAGS_HEAPTYPE))
3308 {
3309 PyErr_Format(PyExc_TypeError,
3310 "__class__ assignment: only for heap types");
3311 return -1;
3312 }
3313 if (compatible_for_assignment(newto, oldto, "__class__")) {
3314 Py_INCREF(newto);
3315 Py_TYPE(self) = newto;
3316 Py_DECREF(oldto);
3317 return 0;
3318 }
3319 else {
3320 return -1;
3321 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003322}
3323
3324static PyGetSetDef object_getsets[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003325 {"__class__", object_get_class, object_set_class,
3326 PyDoc_STR("the object's class")},
3327 {0}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003328};
3329
Guido van Rossumc53f0092003-02-18 22:05:12 +00003330
Guido van Rossum036f9992003-02-21 22:02:54 +00003331/* Stuff to implement __reduce_ex__ for pickle protocols >= 2.
Alexandre Vassalottif7fa63d2008-05-11 08:55:36 +00003332 We fall back to helpers in copyreg for:
Guido van Rossum036f9992003-02-21 22:02:54 +00003333 - pickle protocols < 2
3334 - calculating the list of slot names (done only once per class)
3335 - the __newobj__ function (which is used as a token but never called)
3336*/
3337
3338static PyObject *
Alexandre Vassalottif7fa63d2008-05-11 08:55:36 +00003339import_copyreg(void)
Guido van Rossum036f9992003-02-21 22:02:54 +00003340{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003341 static PyObject *copyreg_str;
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003342 static PyObject *mod_copyreg = NULL;
Guido van Rossum3926a632001-09-25 16:25:58 +00003343
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003344 if (!copyreg_str) {
3345 copyreg_str = PyUnicode_InternFromString("copyreg");
3346 if (copyreg_str == NULL)
3347 return NULL;
3348 }
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003349 if (!mod_copyreg) {
3350 mod_copyreg = PyImport_Import(copyreg_str);
3351 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003352
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003353 Py_XINCREF(mod_copyreg);
3354 return mod_copyreg;
Guido van Rossum036f9992003-02-21 22:02:54 +00003355}
3356
3357static PyObject *
3358slotnames(PyObject *cls)
3359{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003360 PyObject *clsdict;
3361 PyObject *copyreg;
3362 PyObject *slotnames;
Victor Stinner3c1e4812012-03-26 22:10:51 +02003363 _Py_IDENTIFIER(__slotnames__);
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02003364 _Py_IDENTIFIER(_slotnames);
Guido van Rossum036f9992003-02-21 22:02:54 +00003365
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003366 clsdict = ((PyTypeObject *)cls)->tp_dict;
Victor Stinner3c1e4812012-03-26 22:10:51 +02003367 slotnames = _PyDict_GetItemId(clsdict, &PyId___slotnames__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003368 if (slotnames != NULL && PyList_Check(slotnames)) {
3369 Py_INCREF(slotnames);
3370 return slotnames;
3371 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003372
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003373 copyreg = import_copyreg();
3374 if (copyreg == NULL)
3375 return NULL;
Guido van Rossum036f9992003-02-21 22:02:54 +00003376
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02003377 slotnames = _PyObject_CallMethodId(copyreg, &PyId__slotnames, "O", cls);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003378 Py_DECREF(copyreg);
3379 if (slotnames != NULL &&
3380 slotnames != Py_None &&
3381 !PyList_Check(slotnames))
3382 {
3383 PyErr_SetString(PyExc_TypeError,
3384 "copyreg._slotnames didn't return a list or None");
3385 Py_DECREF(slotnames);
3386 slotnames = NULL;
3387 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003388
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003389 return slotnames;
Guido van Rossum036f9992003-02-21 22:02:54 +00003390}
3391
3392static PyObject *
3393reduce_2(PyObject *obj)
3394{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003395 PyObject *cls, *getnewargs;
3396 PyObject *args = NULL, *args2 = NULL;
3397 PyObject *getstate = NULL, *state = NULL, *names = NULL;
3398 PyObject *slots = NULL, *listitems = NULL, *dictitems = NULL;
3399 PyObject *copyreg = NULL, *newobj = NULL, *res = NULL;
3400 Py_ssize_t i, n;
Victor Stinner3c1e4812012-03-26 22:10:51 +02003401 _Py_IDENTIFIER(__getnewargs__);
3402 _Py_IDENTIFIER(__getstate__);
3403 _Py_IDENTIFIER(__newobj__);
Guido van Rossum036f9992003-02-21 22:02:54 +00003404
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003405 cls = (PyObject *) Py_TYPE(obj);
3406
Victor Stinner3c1e4812012-03-26 22:10:51 +02003407 getnewargs = _PyObject_GetAttrId(obj, &PyId___getnewargs__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003408 if (getnewargs != NULL) {
3409 args = PyObject_CallObject(getnewargs, NULL);
3410 Py_DECREF(getnewargs);
3411 if (args != NULL && !PyTuple_Check(args)) {
3412 PyErr_Format(PyExc_TypeError,
3413 "__getnewargs__ should return a tuple, "
3414 "not '%.200s'", Py_TYPE(args)->tp_name);
3415 goto end;
3416 }
3417 }
3418 else {
3419 PyErr_Clear();
3420 args = PyTuple_New(0);
3421 }
3422 if (args == NULL)
3423 goto end;
Guido van Rossum036f9992003-02-21 22:02:54 +00003424
Victor Stinner3c1e4812012-03-26 22:10:51 +02003425 getstate = _PyObject_GetAttrId(obj, &PyId___getstate__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003426 if (getstate != NULL) {
3427 state = PyObject_CallObject(getstate, NULL);
3428 Py_DECREF(getstate);
3429 if (state == NULL)
3430 goto end;
3431 }
3432 else {
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003433 PyObject **dict;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003434 PyErr_Clear();
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003435 dict = _PyObject_GetDictPtr(obj);
3436 if (dict && *dict)
3437 state = *dict;
3438 else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003439 state = Py_None;
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003440 Py_INCREF(state);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003441 names = slotnames(cls);
3442 if (names == NULL)
3443 goto end;
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003444 if (names != Py_None && PyList_GET_SIZE(names) > 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003445 assert(PyList_Check(names));
3446 slots = PyDict_New();
3447 if (slots == NULL)
3448 goto end;
3449 n = 0;
3450 /* Can't pre-compute the list size; the list
3451 is stored on the class so accessible to other
3452 threads, which may be run by DECREF */
3453 for (i = 0; i < PyList_GET_SIZE(names); i++) {
3454 PyObject *name, *value;
3455 name = PyList_GET_ITEM(names, i);
3456 value = PyObject_GetAttr(obj, name);
3457 if (value == NULL)
3458 PyErr_Clear();
3459 else {
3460 int err = PyDict_SetItem(slots, name,
3461 value);
3462 Py_DECREF(value);
3463 if (err)
3464 goto end;
3465 n++;
3466 }
3467 }
3468 if (n) {
3469 state = Py_BuildValue("(NO)", state, slots);
3470 if (state == NULL)
3471 goto end;
3472 }
3473 }
3474 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003475
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003476 if (!PyList_Check(obj)) {
3477 listitems = Py_None;
3478 Py_INCREF(listitems);
3479 }
3480 else {
3481 listitems = PyObject_GetIter(obj);
3482 if (listitems == NULL)
3483 goto end;
3484 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003485
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003486 if (!PyDict_Check(obj)) {
3487 dictitems = Py_None;
3488 Py_INCREF(dictitems);
3489 }
3490 else {
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02003491 _Py_IDENTIFIER(items);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02003492 PyObject *items = _PyObject_CallMethodId(obj, &PyId_items, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003493 if (items == NULL)
3494 goto end;
3495 dictitems = PyObject_GetIter(items);
3496 Py_DECREF(items);
3497 if (dictitems == NULL)
3498 goto end;
3499 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003500
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003501 copyreg = import_copyreg();
3502 if (copyreg == NULL)
3503 goto end;
Victor Stinner3c1e4812012-03-26 22:10:51 +02003504 newobj = _PyObject_GetAttrId(copyreg, &PyId___newobj__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003505 if (newobj == NULL)
3506 goto end;
Guido van Rossum036f9992003-02-21 22:02:54 +00003507
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003508 n = PyTuple_GET_SIZE(args);
3509 args2 = PyTuple_New(n+1);
3510 if (args2 == NULL)
3511 goto end;
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003512 Py_INCREF(cls);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003513 PyTuple_SET_ITEM(args2, 0, cls);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003514 for (i = 0; i < n; i++) {
3515 PyObject *v = PyTuple_GET_ITEM(args, i);
3516 Py_INCREF(v);
3517 PyTuple_SET_ITEM(args2, i+1, v);
3518 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003519
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003520 res = PyTuple_Pack(5, newobj, args2, state, listitems, dictitems);
Guido van Rossum036f9992003-02-21 22:02:54 +00003521
3522 end:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003523 Py_XDECREF(args);
3524 Py_XDECREF(args2);
3525 Py_XDECREF(slots);
3526 Py_XDECREF(state);
3527 Py_XDECREF(names);
3528 Py_XDECREF(listitems);
3529 Py_XDECREF(dictitems);
3530 Py_XDECREF(copyreg);
3531 Py_XDECREF(newobj);
3532 return res;
Guido van Rossum036f9992003-02-21 22:02:54 +00003533}
3534
Guido van Rossumd8faa362007-04-27 19:54:29 +00003535/*
3536 * There were two problems when object.__reduce__ and object.__reduce_ex__
3537 * were implemented in the same function:
3538 * - trying to pickle an object with a custom __reduce__ method that
3539 * fell back to object.__reduce__ in certain circumstances led to
3540 * infinite recursion at Python level and eventual RuntimeError.
3541 * - Pickling objects that lied about their type by overwriting the
3542 * __class__ descriptor could lead to infinite recursion at C level
3543 * and eventual segfault.
3544 *
3545 * Because of backwards compatibility, the two methods still have to
3546 * behave in the same way, even if this is not required by the pickle
3547 * protocol. This common functionality was moved to the _common_reduce
3548 * function.
3549 */
3550static PyObject *
3551_common_reduce(PyObject *self, int proto)
3552{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003553 PyObject *copyreg, *res;
Guido van Rossumd8faa362007-04-27 19:54:29 +00003554
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003555 if (proto >= 2)
3556 return reduce_2(self);
Guido van Rossumd8faa362007-04-27 19:54:29 +00003557
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003558 copyreg = import_copyreg();
3559 if (!copyreg)
3560 return NULL;
Guido van Rossumd8faa362007-04-27 19:54:29 +00003561
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003562 res = PyEval_CallMethod(copyreg, "_reduce_ex", "(Oi)", self, proto);
3563 Py_DECREF(copyreg);
Guido van Rossumd8faa362007-04-27 19:54:29 +00003564
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003565 return res;
Guido van Rossumd8faa362007-04-27 19:54:29 +00003566}
3567
3568static PyObject *
3569object_reduce(PyObject *self, PyObject *args)
3570{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003571 int proto = 0;
Guido van Rossumd8faa362007-04-27 19:54:29 +00003572
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003573 if (!PyArg_ParseTuple(args, "|i:__reduce__", &proto))
3574 return NULL;
Guido van Rossumd8faa362007-04-27 19:54:29 +00003575
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003576 return _common_reduce(self, proto);
Guido van Rossumd8faa362007-04-27 19:54:29 +00003577}
3578
Guido van Rossum036f9992003-02-21 22:02:54 +00003579static PyObject *
3580object_reduce_ex(PyObject *self, PyObject *args)
3581{
Victor Stinner3c1e4812012-03-26 22:10:51 +02003582 static PyObject *objreduce;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003583 PyObject *reduce, *res;
3584 int proto = 0;
Victor Stinner3c1e4812012-03-26 22:10:51 +02003585 _Py_IDENTIFIER(__reduce__);
Guido van Rossum036f9992003-02-21 22:02:54 +00003586
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003587 if (!PyArg_ParseTuple(args, "|i:__reduce_ex__", &proto))
3588 return NULL;
Guido van Rossum036f9992003-02-21 22:02:54 +00003589
Victor Stinner3c1e4812012-03-26 22:10:51 +02003590 if (objreduce == NULL) {
3591 objreduce = _PyDict_GetItemId(PyBaseObject_Type.tp_dict,
3592 &PyId___reduce__);
3593 if (objreduce == NULL)
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003594 return NULL;
3595 }
3596
Victor Stinner3c1e4812012-03-26 22:10:51 +02003597 reduce = _PyObject_GetAttrId(self, &PyId___reduce__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003598 if (reduce == NULL)
3599 PyErr_Clear();
3600 else {
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003601 PyObject *cls, *clsreduce;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003602 int override;
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003603
3604 cls = (PyObject *) Py_TYPE(self);
Victor Stinner3c1e4812012-03-26 22:10:51 +02003605 clsreduce = _PyObject_GetAttrId(cls, &PyId___reduce__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003606 if (clsreduce == NULL) {
3607 Py_DECREF(reduce);
3608 return NULL;
3609 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003610 override = (clsreduce != objreduce);
3611 Py_DECREF(clsreduce);
3612 if (override) {
3613 res = PyObject_CallObject(reduce, NULL);
3614 Py_DECREF(reduce);
3615 return res;
3616 }
3617 else
3618 Py_DECREF(reduce);
3619 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003620
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003621 return _common_reduce(self, proto);
Guido van Rossum3926a632001-09-25 16:25:58 +00003622}
3623
Christian Heimes9e7f1d22008-02-28 12:27:11 +00003624static PyObject *
3625object_subclasshook(PyObject *cls, PyObject *args)
3626{
Brian Curtindfc80e32011-08-10 20:28:54 -05003627 Py_RETURN_NOTIMPLEMENTED;
Christian Heimes9e7f1d22008-02-28 12:27:11 +00003628}
3629
3630PyDoc_STRVAR(object_subclasshook_doc,
3631"Abstract classes can override this to customize issubclass().\n"
3632"\n"
3633"This is invoked early on by abc.ABCMeta.__subclasscheck__().\n"
3634"It should return True, False or NotImplemented. If it returns\n"
3635"NotImplemented, the normal algorithm is used. Otherwise, it\n"
3636"overrides the normal algorithm (and the outcome is cached).\n");
Eric Smith8c663262007-08-25 02:26:07 +00003637
3638/*
3639 from PEP 3101, this code implements:
3640
3641 class object:
3642 def __format__(self, format_spec):
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003643 return format(str(self), format_spec)
Eric Smith8c663262007-08-25 02:26:07 +00003644*/
3645static PyObject *
3646object_format(PyObject *self, PyObject *args)
3647{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003648 PyObject *format_spec;
3649 PyObject *self_as_str = NULL;
3650 PyObject *result = NULL;
Eric Smith8c663262007-08-25 02:26:07 +00003651
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003652 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
3653 return NULL;
Eric Smith8c663262007-08-25 02:26:07 +00003654
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003655 self_as_str = PyObject_Str(self);
Eric Smithe4d63172010-09-13 20:48:43 +00003656 if (self_as_str != NULL) {
3657 /* Issue 7994: If we're converting to a string, we
Eric V. Smithb9cd3532011-03-12 10:08:48 -05003658 should reject format specifications */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003659 if (PyUnicode_GET_LENGTH(format_spec) > 0) {
Eric V. Smithb9cd3532011-03-12 10:08:48 -05003660 if (PyErr_WarnEx(PyExc_DeprecationWarning,
3661 "object.__format__ with a non-empty format "
3662 "string is deprecated", 1) < 0) {
3663 goto done;
3664 }
3665 /* Eventually this will become an error:
3666 PyErr_Format(PyExc_TypeError,
3667 "non-empty format string passed to object.__format__");
3668 goto done;
3669 */
3670 }
Eric Smith8c663262007-08-25 02:26:07 +00003671
Eric V. Smithb9cd3532011-03-12 10:08:48 -05003672 result = PyObject_Format(self_as_str, format_spec);
Eric Smithe4d63172010-09-13 20:48:43 +00003673 }
3674
3675done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003676 Py_XDECREF(self_as_str);
Eric Smith8c663262007-08-25 02:26:07 +00003677
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003678 return result;
Eric Smith8c663262007-08-25 02:26:07 +00003679}
3680
Martin v. Löwis00709aa2008-06-04 14:18:43 +00003681static PyObject *
3682object_sizeof(PyObject *self, PyObject *args)
3683{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003684 Py_ssize_t res, isize;
Martin v. Löwis00709aa2008-06-04 14:18:43 +00003685
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003686 res = 0;
3687 isize = self->ob_type->tp_itemsize;
3688 if (isize > 0)
3689 res = Py_SIZE(self->ob_type) * isize;
3690 res += self->ob_type->tp_basicsize;
Martin v. Löwis00709aa2008-06-04 14:18:43 +00003691
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003692 return PyLong_FromSsize_t(res);
Martin v. Löwis00709aa2008-06-04 14:18:43 +00003693}
3694
Benjamin Peterson82b00c12011-05-24 11:09:06 -05003695/* __dir__ for generic objects: returns __dict__, __class__,
3696 and recursively up the __class__.__bases__ chain.
3697*/
3698static PyObject *
3699object_dir(PyObject *self, PyObject *args)
3700{
3701 PyObject *result = NULL;
3702 PyObject *dict = NULL;
3703 PyObject *itsclass = NULL;
3704
3705 /* Get __dict__ (which may or may not be a real dict...) */
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02003706 dict = _PyObject_GetAttrId(self, &PyId___dict__);
Benjamin Peterson82b00c12011-05-24 11:09:06 -05003707 if (dict == NULL) {
3708 PyErr_Clear();
3709 dict = PyDict_New();
3710 }
3711 else if (!PyDict_Check(dict)) {
3712 Py_DECREF(dict);
3713 dict = PyDict_New();
3714 }
3715 else {
3716 /* Copy __dict__ to avoid mutating it. */
3717 PyObject *temp = PyDict_Copy(dict);
3718 Py_DECREF(dict);
3719 dict = temp;
3720 }
3721
3722 if (dict == NULL)
3723 goto error;
3724
3725 /* Merge in attrs reachable from its class. */
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02003726 itsclass = _PyObject_GetAttrId(self, &PyId___class__);
Benjamin Peterson82b00c12011-05-24 11:09:06 -05003727 if (itsclass == NULL)
3728 /* XXX(tomer): Perhaps fall back to obj->ob_type if no
3729 __class__ exists? */
3730 PyErr_Clear();
3731 else if (merge_class_dict(dict, itsclass) != 0)
3732 goto error;
3733
3734 result = PyDict_Keys(dict);
3735 /* fall through */
3736error:
3737 Py_XDECREF(itsclass);
3738 Py_XDECREF(dict);
3739 return result;
3740}
3741
Guido van Rossum3926a632001-09-25 16:25:58 +00003742static PyMethodDef object_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003743 {"__reduce_ex__", object_reduce_ex, METH_VARARGS,
3744 PyDoc_STR("helper for pickle")},
3745 {"__reduce__", object_reduce, METH_VARARGS,
3746 PyDoc_STR("helper for pickle")},
3747 {"__subclasshook__", object_subclasshook, METH_CLASS | METH_VARARGS,
3748 object_subclasshook_doc},
3749 {"__format__", object_format, METH_VARARGS,
3750 PyDoc_STR("default object formatter")},
3751 {"__sizeof__", object_sizeof, METH_NOARGS,
Benjamin Petersonfbe56bb2011-05-24 12:42:51 -05003752 PyDoc_STR("__sizeof__() -> int\nsize of object in memory, in bytes")},
Benjamin Peterson82b00c12011-05-24 11:09:06 -05003753 {"__dir__", object_dir, METH_NOARGS,
Benjamin Petersonc7284122011-05-24 12:46:15 -05003754 PyDoc_STR("__dir__() -> list\ndefault dir() implementation")},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003755 {0}
Guido van Rossum3926a632001-09-25 16:25:58 +00003756};
3757
Guido van Rossum036f9992003-02-21 22:02:54 +00003758
Tim Peters6d6c1a32001-08-02 04:15:00 +00003759PyTypeObject PyBaseObject_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003760 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3761 "object", /* tp_name */
3762 sizeof(PyObject), /* tp_basicsize */
3763 0, /* tp_itemsize */
3764 object_dealloc, /* tp_dealloc */
3765 0, /* tp_print */
3766 0, /* tp_getattr */
3767 0, /* tp_setattr */
3768 0, /* tp_reserved */
3769 object_repr, /* tp_repr */
3770 0, /* tp_as_number */
3771 0, /* tp_as_sequence */
3772 0, /* tp_as_mapping */
3773 (hashfunc)_Py_HashPointer, /* tp_hash */
3774 0, /* tp_call */
3775 object_str, /* tp_str */
3776 PyObject_GenericGetAttr, /* tp_getattro */
3777 PyObject_GenericSetAttr, /* tp_setattro */
3778 0, /* tp_as_buffer */
3779 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
3780 PyDoc_STR("The most base type"), /* tp_doc */
3781 0, /* tp_traverse */
3782 0, /* tp_clear */
3783 object_richcompare, /* tp_richcompare */
3784 0, /* tp_weaklistoffset */
3785 0, /* tp_iter */
3786 0, /* tp_iternext */
3787 object_methods, /* tp_methods */
3788 0, /* tp_members */
3789 object_getsets, /* tp_getset */
3790 0, /* tp_base */
3791 0, /* tp_dict */
3792 0, /* tp_descr_get */
3793 0, /* tp_descr_set */
3794 0, /* tp_dictoffset */
3795 object_init, /* tp_init */
3796 PyType_GenericAlloc, /* tp_alloc */
3797 object_new, /* tp_new */
3798 PyObject_Del, /* tp_free */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003799};
3800
3801
Guido van Rossum50e9fb92006-08-17 05:42:55 +00003802/* Add the methods from tp_methods to the __dict__ in a type object */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003803
3804static int
3805add_methods(PyTypeObject *type, PyMethodDef *meth)
3806{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003807 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003808
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003809 for (; meth->ml_name != NULL; meth++) {
3810 PyObject *descr;
Benjamin Peterson89a6e9a2012-05-08 09:22:24 -04003811 int err;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003812 if (PyDict_GetItemString(dict, meth->ml_name) &&
3813 !(meth->ml_flags & METH_COEXIST))
3814 continue;
3815 if (meth->ml_flags & METH_CLASS) {
3816 if (meth->ml_flags & METH_STATIC) {
3817 PyErr_SetString(PyExc_ValueError,
3818 "method cannot be both class and static");
3819 return -1;
3820 }
3821 descr = PyDescr_NewClassMethod(type, meth);
3822 }
3823 else if (meth->ml_flags & METH_STATIC) {
Antoine Pitrou5b629422011-12-23 12:40:16 +01003824 PyObject *cfunc = PyCFunction_New(meth, (PyObject*)type);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003825 if (cfunc == NULL)
3826 return -1;
3827 descr = PyStaticMethod_New(cfunc);
3828 Py_DECREF(cfunc);
3829 }
3830 else {
3831 descr = PyDescr_NewMethod(type, meth);
3832 }
3833 if (descr == NULL)
3834 return -1;
Benjamin Peterson89a6e9a2012-05-08 09:22:24 -04003835 err = PyDict_SetItemString(dict, meth->ml_name, descr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003836 Py_DECREF(descr);
Benjamin Peterson89a6e9a2012-05-08 09:22:24 -04003837 if (err < 0)
3838 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003839 }
3840 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003841}
3842
3843static int
Guido van Rossum6f799372001-09-20 20:46:19 +00003844add_members(PyTypeObject *type, PyMemberDef *memb)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003845{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003846 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003847
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003848 for (; memb->name != NULL; memb++) {
3849 PyObject *descr;
3850 if (PyDict_GetItemString(dict, memb->name))
3851 continue;
3852 descr = PyDescr_NewMember(type, memb);
3853 if (descr == NULL)
3854 return -1;
3855 if (PyDict_SetItemString(dict, memb->name, descr) < 0)
3856 return -1;
3857 Py_DECREF(descr);
3858 }
3859 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003860}
3861
3862static int
Guido van Rossum32d34c82001-09-20 21:45:26 +00003863add_getset(PyTypeObject *type, PyGetSetDef *gsp)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003864{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003865 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003866
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003867 for (; gsp->name != NULL; gsp++) {
3868 PyObject *descr;
3869 if (PyDict_GetItemString(dict, gsp->name))
3870 continue;
3871 descr = PyDescr_NewGetSet(type, gsp);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003872
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003873 if (descr == NULL)
3874 return -1;
3875 if (PyDict_SetItemString(dict, gsp->name, descr) < 0)
3876 return -1;
3877 Py_DECREF(descr);
3878 }
3879 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003880}
3881
Guido van Rossum13d52f02001-08-10 21:24:08 +00003882static void
3883inherit_special(PyTypeObject *type, PyTypeObject *base)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003884{
Tim Peters6d6c1a32001-08-02 04:15:00 +00003885
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003886 /* Copying basicsize is connected to the GC flags */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003887 if (!(type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
3888 (base->tp_flags & Py_TPFLAGS_HAVE_GC) &&
3889 (!type->tp_traverse && !type->tp_clear)) {
3890 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
3891 if (type->tp_traverse == NULL)
3892 type->tp_traverse = base->tp_traverse;
3893 if (type->tp_clear == NULL)
3894 type->tp_clear = base->tp_clear;
3895 }
3896 {
3897 /* The condition below could use some explanation.
3898 It appears that tp_new is not inherited for static types
3899 whose base class is 'object'; this seems to be a precaution
3900 so that old extension types don't suddenly become
3901 callable (object.__new__ wouldn't insure the invariants
3902 that the extension type's own factory function ensures).
3903 Heap types, of course, are under our control, so they do
3904 inherit tp_new; static extension types that specify some
Florent Xiclunaaa6c1d22011-12-12 18:54:29 +01003905 other built-in type as the default also
3906 inherit object.__new__. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003907 if (base != &PyBaseObject_Type ||
3908 (type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
3909 if (type->tp_new == NULL)
3910 type->tp_new = base->tp_new;
3911 }
3912 }
Benjamin Petersona7465e22010-07-05 15:01:22 +00003913 if (type->tp_basicsize == 0)
3914 type->tp_basicsize = base->tp_basicsize;
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00003915
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003916 /* Copy other non-function slots */
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00003917
3918#undef COPYVAL
3919#define COPYVAL(SLOT) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003920 if (type->SLOT == 0) type->SLOT = base->SLOT
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00003921
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003922 COPYVAL(tp_itemsize);
3923 COPYVAL(tp_weaklistoffset);
3924 COPYVAL(tp_dictoffset);
Thomas Wouters27d517b2007-02-25 20:39:11 +00003925
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003926 /* Setup fast subclass flags */
3927 if (PyType_IsSubtype(base, (PyTypeObject*)PyExc_BaseException))
3928 type->tp_flags |= Py_TPFLAGS_BASE_EXC_SUBCLASS;
3929 else if (PyType_IsSubtype(base, &PyType_Type))
3930 type->tp_flags |= Py_TPFLAGS_TYPE_SUBCLASS;
3931 else if (PyType_IsSubtype(base, &PyLong_Type))
3932 type->tp_flags |= Py_TPFLAGS_LONG_SUBCLASS;
3933 else if (PyType_IsSubtype(base, &PyBytes_Type))
3934 type->tp_flags |= Py_TPFLAGS_BYTES_SUBCLASS;
3935 else if (PyType_IsSubtype(base, &PyUnicode_Type))
3936 type->tp_flags |= Py_TPFLAGS_UNICODE_SUBCLASS;
3937 else if (PyType_IsSubtype(base, &PyTuple_Type))
3938 type->tp_flags |= Py_TPFLAGS_TUPLE_SUBCLASS;
3939 else if (PyType_IsSubtype(base, &PyList_Type))
3940 type->tp_flags |= Py_TPFLAGS_LIST_SUBCLASS;
3941 else if (PyType_IsSubtype(base, &PyDict_Type))
3942 type->tp_flags |= Py_TPFLAGS_DICT_SUBCLASS;
Guido van Rossum13d52f02001-08-10 21:24:08 +00003943}
3944
Guido van Rossum38938152006-08-21 23:36:26 +00003945static int
Guido van Rossumf5243f02008-01-01 04:06:48 +00003946overrides_hash(PyTypeObject *type)
Guido van Rossum38938152006-08-21 23:36:26 +00003947{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003948 PyObject *dict = type->tp_dict;
Victor Stinner3c1e4812012-03-26 22:10:51 +02003949 _Py_IDENTIFIER(__eq__);
Guido van Rossum38938152006-08-21 23:36:26 +00003950
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003951 assert(dict != NULL);
Victor Stinner3c1e4812012-03-26 22:10:51 +02003952 if (_PyDict_GetItemId(dict, &PyId___eq__) != NULL)
3953 return 1;
3954 if (_PyDict_GetItemId(dict, &PyId___hash__) != NULL)
3955 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003956 return 0;
Guido van Rossum38938152006-08-21 23:36:26 +00003957}
3958
Guido van Rossum13d52f02001-08-10 21:24:08 +00003959static void
3960inherit_slots(PyTypeObject *type, PyTypeObject *base)
3961{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003962 PyTypeObject *basebase;
Guido van Rossum13d52f02001-08-10 21:24:08 +00003963
3964#undef SLOTDEFINED
Tim Peters6d6c1a32001-08-02 04:15:00 +00003965#undef COPYSLOT
3966#undef COPYNUM
3967#undef COPYSEQ
3968#undef COPYMAP
Guido van Rossum5af588b2001-10-12 14:13:21 +00003969#undef COPYBUF
Guido van Rossum13d52f02001-08-10 21:24:08 +00003970
3971#define SLOTDEFINED(SLOT) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003972 (base->SLOT != 0 && \
3973 (basebase == NULL || base->SLOT != basebase->SLOT))
Guido van Rossum13d52f02001-08-10 21:24:08 +00003974
Tim Peters6d6c1a32001-08-02 04:15:00 +00003975#define COPYSLOT(SLOT) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003976 if (!type->SLOT && SLOTDEFINED(SLOT)) type->SLOT = base->SLOT
Tim Peters6d6c1a32001-08-02 04:15:00 +00003977
3978#define COPYNUM(SLOT) COPYSLOT(tp_as_number->SLOT)
3979#define COPYSEQ(SLOT) COPYSLOT(tp_as_sequence->SLOT)
3980#define COPYMAP(SLOT) COPYSLOT(tp_as_mapping->SLOT)
Tim Petersfc57ccb2001-10-12 02:38:24 +00003981#define COPYBUF(SLOT) COPYSLOT(tp_as_buffer->SLOT)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003982
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003983 /* This won't inherit indirect slots (from tp_as_number etc.)
3984 if type doesn't provide the space. */
Guido van Rossum13d52f02001-08-10 21:24:08 +00003985
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003986 if (type->tp_as_number != NULL && base->tp_as_number != NULL) {
3987 basebase = base->tp_base;
3988 if (basebase->tp_as_number == NULL)
3989 basebase = NULL;
3990 COPYNUM(nb_add);
3991 COPYNUM(nb_subtract);
3992 COPYNUM(nb_multiply);
3993 COPYNUM(nb_remainder);
3994 COPYNUM(nb_divmod);
3995 COPYNUM(nb_power);
3996 COPYNUM(nb_negative);
3997 COPYNUM(nb_positive);
3998 COPYNUM(nb_absolute);
3999 COPYNUM(nb_bool);
4000 COPYNUM(nb_invert);
4001 COPYNUM(nb_lshift);
4002 COPYNUM(nb_rshift);
4003 COPYNUM(nb_and);
4004 COPYNUM(nb_xor);
4005 COPYNUM(nb_or);
4006 COPYNUM(nb_int);
4007 COPYNUM(nb_float);
4008 COPYNUM(nb_inplace_add);
4009 COPYNUM(nb_inplace_subtract);
4010 COPYNUM(nb_inplace_multiply);
4011 COPYNUM(nb_inplace_remainder);
4012 COPYNUM(nb_inplace_power);
4013 COPYNUM(nb_inplace_lshift);
4014 COPYNUM(nb_inplace_rshift);
4015 COPYNUM(nb_inplace_and);
4016 COPYNUM(nb_inplace_xor);
4017 COPYNUM(nb_inplace_or);
4018 COPYNUM(nb_true_divide);
4019 COPYNUM(nb_floor_divide);
4020 COPYNUM(nb_inplace_true_divide);
4021 COPYNUM(nb_inplace_floor_divide);
4022 COPYNUM(nb_index);
4023 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004024
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004025 if (type->tp_as_sequence != NULL && base->tp_as_sequence != NULL) {
4026 basebase = base->tp_base;
4027 if (basebase->tp_as_sequence == NULL)
4028 basebase = NULL;
4029 COPYSEQ(sq_length);
4030 COPYSEQ(sq_concat);
4031 COPYSEQ(sq_repeat);
4032 COPYSEQ(sq_item);
4033 COPYSEQ(sq_ass_item);
4034 COPYSEQ(sq_contains);
4035 COPYSEQ(sq_inplace_concat);
4036 COPYSEQ(sq_inplace_repeat);
4037 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004038
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004039 if (type->tp_as_mapping != NULL && base->tp_as_mapping != NULL) {
4040 basebase = base->tp_base;
4041 if (basebase->tp_as_mapping == NULL)
4042 basebase = NULL;
4043 COPYMAP(mp_length);
4044 COPYMAP(mp_subscript);
4045 COPYMAP(mp_ass_subscript);
4046 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004047
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004048 if (type->tp_as_buffer != NULL && base->tp_as_buffer != NULL) {
4049 basebase = base->tp_base;
4050 if (basebase->tp_as_buffer == NULL)
4051 basebase = NULL;
4052 COPYBUF(bf_getbuffer);
4053 COPYBUF(bf_releasebuffer);
4054 }
Tim Petersfc57ccb2001-10-12 02:38:24 +00004055
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004056 basebase = base->tp_base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004057
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004058 COPYSLOT(tp_dealloc);
4059 if (type->tp_getattr == NULL && type->tp_getattro == NULL) {
4060 type->tp_getattr = base->tp_getattr;
4061 type->tp_getattro = base->tp_getattro;
4062 }
4063 if (type->tp_setattr == NULL && type->tp_setattro == NULL) {
4064 type->tp_setattr = base->tp_setattr;
4065 type->tp_setattro = base->tp_setattro;
4066 }
4067 /* tp_reserved is ignored */
4068 COPYSLOT(tp_repr);
4069 /* tp_hash see tp_richcompare */
4070 COPYSLOT(tp_call);
4071 COPYSLOT(tp_str);
4072 {
4073 /* Copy comparison-related slots only when
4074 not overriding them anywhere */
4075 if (type->tp_richcompare == NULL &&
4076 type->tp_hash == NULL &&
4077 !overrides_hash(type))
4078 {
4079 type->tp_richcompare = base->tp_richcompare;
4080 type->tp_hash = base->tp_hash;
4081 }
4082 }
4083 {
4084 COPYSLOT(tp_iter);
4085 COPYSLOT(tp_iternext);
4086 }
4087 {
4088 COPYSLOT(tp_descr_get);
4089 COPYSLOT(tp_descr_set);
4090 COPYSLOT(tp_dictoffset);
4091 COPYSLOT(tp_init);
4092 COPYSLOT(tp_alloc);
4093 COPYSLOT(tp_is_gc);
4094 if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) ==
4095 (base->tp_flags & Py_TPFLAGS_HAVE_GC)) {
4096 /* They agree about gc. */
4097 COPYSLOT(tp_free);
4098 }
4099 else if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
4100 type->tp_free == NULL &&
4101 base->tp_free == PyObject_Free) {
4102 /* A bit of magic to plug in the correct default
4103 * tp_free function when a derived class adds gc,
4104 * didn't define tp_free, and the base uses the
4105 * default non-gc tp_free.
4106 */
4107 type->tp_free = PyObject_GC_Del;
4108 }
4109 /* else they didn't agree about gc, and there isn't something
4110 * obvious to be done -- the type is on its own.
4111 */
4112 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004113}
4114
Jeremy Hylton938ace62002-07-17 16:30:39 +00004115static int add_operators(PyTypeObject *);
Guido van Rossum13d52f02001-08-10 21:24:08 +00004116
Tim Peters6d6c1a32001-08-02 04:15:00 +00004117int
Guido van Rossum528b7eb2001-08-07 17:24:28 +00004118PyType_Ready(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004119{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004120 PyObject *dict, *bases;
4121 PyTypeObject *base;
4122 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004123
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004124 if (type->tp_flags & Py_TPFLAGS_READY) {
4125 assert(type->tp_dict != NULL);
4126 return 0;
4127 }
4128 assert((type->tp_flags & Py_TPFLAGS_READYING) == 0);
Guido van Rossumd614f972001-08-10 17:39:49 +00004129
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004130 type->tp_flags |= Py_TPFLAGS_READYING;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004131
Tim Peters36eb4df2003-03-23 03:33:13 +00004132#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004133 /* PyType_Ready is the closest thing we have to a choke point
4134 * for type objects, so is the best place I can think of to try
4135 * to get type objects into the doubly-linked list of all objects.
4136 * Still, not all type objects go thru PyType_Ready.
4137 */
4138 _Py_AddToAllObjects((PyObject *)type, 0);
Tim Peters36eb4df2003-03-23 03:33:13 +00004139#endif
4140
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004141 /* Initialize tp_base (defaults to BaseObject unless that's us) */
4142 base = type->tp_base;
4143 if (base == NULL && type != &PyBaseObject_Type) {
4144 base = type->tp_base = &PyBaseObject_Type;
4145 Py_INCREF(base);
4146 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004147
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004148 /* Now the only way base can still be NULL is if type is
4149 * &PyBaseObject_Type.
4150 */
Guido van Rossum692cdbc2006-03-10 02:04:28 +00004151
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004152 /* Initialize the base class */
4153 if (base != NULL && base->tp_dict == NULL) {
4154 if (PyType_Ready(base) < 0)
4155 goto error;
4156 }
Guido van Rossum323a9cf2002-08-14 17:26:30 +00004157
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004158 /* Initialize ob_type if NULL. This means extensions that want to be
4159 compilable separately on Windows can call PyType_Ready() instead of
4160 initializing the ob_type field of their type objects. */
4161 /* The test for base != NULL is really unnecessary, since base is only
4162 NULL when type is &PyBaseObject_Type, and we know its ob_type is
4163 not NULL (it's initialized to &PyType_Type). But coverity doesn't
4164 know that. */
4165 if (Py_TYPE(type) == NULL && base != NULL)
4166 Py_TYPE(type) = Py_TYPE(base);
Guido van Rossum0986d822002-04-08 01:38:42 +00004167
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004168 /* Initialize tp_bases */
4169 bases = type->tp_bases;
4170 if (bases == NULL) {
4171 if (base == NULL)
4172 bases = PyTuple_New(0);
4173 else
4174 bases = PyTuple_Pack(1, base);
4175 if (bases == NULL)
4176 goto error;
4177 type->tp_bases = bases;
4178 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004179
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004180 /* Initialize tp_dict */
4181 dict = type->tp_dict;
4182 if (dict == NULL) {
4183 dict = PyDict_New();
4184 if (dict == NULL)
4185 goto error;
4186 type->tp_dict = dict;
4187 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004188
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004189 /* Add type-specific descriptors to tp_dict */
4190 if (add_operators(type) < 0)
4191 goto error;
4192 if (type->tp_methods != NULL) {
4193 if (add_methods(type, type->tp_methods) < 0)
4194 goto error;
4195 }
4196 if (type->tp_members != NULL) {
4197 if (add_members(type, type->tp_members) < 0)
4198 goto error;
4199 }
4200 if (type->tp_getset != NULL) {
4201 if (add_getset(type, type->tp_getset) < 0)
4202 goto error;
4203 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004204
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004205 /* Calculate method resolution order */
4206 if (mro_internal(type) < 0) {
4207 goto error;
4208 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004209
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004210 /* Inherit special flags from dominant base */
4211 if (type->tp_base != NULL)
4212 inherit_special(type, type->tp_base);
Guido van Rossum13d52f02001-08-10 21:24:08 +00004213
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004214 /* Initialize tp_dict properly */
4215 bases = type->tp_mro;
4216 assert(bases != NULL);
4217 assert(PyTuple_Check(bases));
4218 n = PyTuple_GET_SIZE(bases);
4219 for (i = 1; i < n; i++) {
4220 PyObject *b = PyTuple_GET_ITEM(bases, i);
4221 if (PyType_Check(b))
4222 inherit_slots(type, (PyTypeObject *)b);
4223 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004224
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004225 /* Sanity check for tp_free. */
4226 if (PyType_IS_GC(type) && (type->tp_flags & Py_TPFLAGS_BASETYPE) &&
4227 (type->tp_free == NULL || type->tp_free == PyObject_Del)) {
4228 /* This base class needs to call tp_free, but doesn't have
4229 * one, or its tp_free is for non-gc'ed objects.
4230 */
4231 PyErr_Format(PyExc_TypeError, "type '%.100s' participates in "
4232 "gc and is a base type but has inappropriate "
4233 "tp_free slot",
4234 type->tp_name);
4235 goto error;
4236 }
Tim Peters3cfe7542003-05-21 21:29:48 +00004237
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004238 /* if the type dictionary doesn't contain a __doc__, set it from
4239 the tp_doc slot.
4240 */
Victor Stinner3c1e4812012-03-26 22:10:51 +02004241 if (_PyDict_GetItemId(type->tp_dict, &PyId___doc__) == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004242 if (type->tp_doc != NULL) {
4243 PyObject *doc = PyUnicode_FromString(type->tp_doc);
4244 if (doc == NULL)
4245 goto error;
Victor Stinner3c1e4812012-03-26 22:10:51 +02004246 _PyDict_SetItemId(type->tp_dict, &PyId___doc__, doc);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004247 Py_DECREF(doc);
4248 } else {
Victor Stinner3c1e4812012-03-26 22:10:51 +02004249 _PyDict_SetItemId(type->tp_dict,
4250 &PyId___doc__, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004251 }
4252 }
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00004253
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004254 /* Hack for tp_hash and __hash__.
4255 If after all that, tp_hash is still NULL, and __hash__ is not in
4256 tp_dict, set tp_hash to PyObject_HashNotImplemented and
4257 tp_dict['__hash__'] equal to None.
4258 This signals that __hash__ is not inherited.
4259 */
4260 if (type->tp_hash == NULL) {
Victor Stinner3c1e4812012-03-26 22:10:51 +02004261 if (_PyDict_GetItemId(type->tp_dict, &PyId___hash__) == NULL) {
4262 if (_PyDict_SetItemId(type->tp_dict, &PyId___hash__, Py_None) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004263 goto error;
4264 type->tp_hash = PyObject_HashNotImplemented;
4265 }
4266 }
Guido van Rossum38938152006-08-21 23:36:26 +00004267
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004268 /* Some more special stuff */
4269 base = type->tp_base;
4270 if (base != NULL) {
4271 if (type->tp_as_number == NULL)
4272 type->tp_as_number = base->tp_as_number;
4273 if (type->tp_as_sequence == NULL)
4274 type->tp_as_sequence = base->tp_as_sequence;
4275 if (type->tp_as_mapping == NULL)
4276 type->tp_as_mapping = base->tp_as_mapping;
4277 if (type->tp_as_buffer == NULL)
4278 type->tp_as_buffer = base->tp_as_buffer;
4279 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004280
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004281 /* Link into each base class's list of subclasses */
4282 bases = type->tp_bases;
4283 n = PyTuple_GET_SIZE(bases);
4284 for (i = 0; i < n; i++) {
4285 PyObject *b = PyTuple_GET_ITEM(bases, i);
4286 if (PyType_Check(b) &&
4287 add_subclass((PyTypeObject *)b, type) < 0)
4288 goto error;
4289 }
Guido van Rossum1c450732001-10-08 15:18:27 +00004290
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004291 /* Warn for a type that implements tp_compare (now known as
4292 tp_reserved) but not tp_richcompare. */
4293 if (type->tp_reserved && !type->tp_richcompare) {
4294 int error;
Victor Stinner4a2b7a12010-08-13 14:03:48 +00004295 error = PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
4296 "Type %.100s defines tp_reserved (formerly tp_compare) "
4297 "but not tp_richcompare. Comparisons may not behave as intended.",
4298 type->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004299 if (error == -1)
4300 goto error;
4301 }
Mark Dickinson2a7d45b2009-02-08 11:02:10 +00004302
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004303 /* All done -- set the ready flag */
4304 assert(type->tp_dict != NULL);
4305 type->tp_flags =
4306 (type->tp_flags & ~Py_TPFLAGS_READYING) | Py_TPFLAGS_READY;
4307 return 0;
Guido van Rossumd614f972001-08-10 17:39:49 +00004308
4309 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004310 type->tp_flags &= ~Py_TPFLAGS_READYING;
4311 return -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004312}
4313
Guido van Rossum1c450732001-10-08 15:18:27 +00004314static int
4315add_subclass(PyTypeObject *base, PyTypeObject *type)
4316{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004317 Py_ssize_t i;
4318 int result;
4319 PyObject *list, *ref, *newobj;
Guido van Rossum1c450732001-10-08 15:18:27 +00004320
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004321 list = base->tp_subclasses;
4322 if (list == NULL) {
4323 base->tp_subclasses = list = PyList_New(0);
4324 if (list == NULL)
4325 return -1;
4326 }
4327 assert(PyList_Check(list));
4328 newobj = PyWeakref_NewRef((PyObject *)type, NULL);
4329 i = PyList_GET_SIZE(list);
4330 while (--i >= 0) {
4331 ref = PyList_GET_ITEM(list, i);
4332 assert(PyWeakref_CheckRef(ref));
4333 if (PyWeakref_GET_OBJECT(ref) == Py_None)
4334 return PyList_SetItem(list, i, newobj);
4335 }
4336 result = PyList_Append(list, newobj);
4337 Py_DECREF(newobj);
4338 return result;
Guido van Rossum1c450732001-10-08 15:18:27 +00004339}
4340
Michael W. Hudson98bbc492002-11-26 14:47:27 +00004341static void
4342remove_subclass(PyTypeObject *base, PyTypeObject *type)
4343{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004344 Py_ssize_t i;
4345 PyObject *list, *ref;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00004346
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004347 list = base->tp_subclasses;
4348 if (list == NULL) {
4349 return;
4350 }
4351 assert(PyList_Check(list));
4352 i = PyList_GET_SIZE(list);
4353 while (--i >= 0) {
4354 ref = PyList_GET_ITEM(list, i);
4355 assert(PyWeakref_CheckRef(ref));
4356 if (PyWeakref_GET_OBJECT(ref) == (PyObject*)type) {
4357 /* this can't fail, right? */
4358 PySequence_DelItem(list, i);
4359 return;
4360 }
4361 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +00004362}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004363
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004364static int
4365check_num_args(PyObject *ob, int n)
4366{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004367 if (!PyTuple_CheckExact(ob)) {
4368 PyErr_SetString(PyExc_SystemError,
4369 "PyArg_UnpackTuple() argument list is not a tuple");
4370 return 0;
4371 }
4372 if (n == PyTuple_GET_SIZE(ob))
4373 return 1;
4374 PyErr_Format(
4375 PyExc_TypeError,
4376 "expected %d arguments, got %zd", n, PyTuple_GET_SIZE(ob));
4377 return 0;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004378}
4379
Tim Peters6d6c1a32001-08-02 04:15:00 +00004380/* Generic wrappers for overloadable 'operators' such as __getitem__ */
4381
4382/* There's a wrapper *function* for each distinct function typedef used
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004383 for type object slots (e.g. binaryfunc, ternaryfunc, etc.). There's a
Tim Peters6d6c1a32001-08-02 04:15:00 +00004384 wrapper *table* for each distinct operation (e.g. __len__, __add__).
4385 Most tables have only one entry; the tables for binary operators have two
4386 entries, one regular and one with reversed arguments. */
4387
4388static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00004389wrap_lenfunc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004390{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004391 lenfunc func = (lenfunc)wrapped;
4392 Py_ssize_t res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004393
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004394 if (!check_num_args(args, 0))
4395 return NULL;
4396 res = (*func)(self);
4397 if (res == -1 && PyErr_Occurred())
4398 return NULL;
4399 return PyLong_FromLong((long)res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004400}
4401
Tim Peters6d6c1a32001-08-02 04:15:00 +00004402static PyObject *
Raymond Hettingerf34f2642003-10-11 17:29:04 +00004403wrap_inquirypred(PyObject *self, PyObject *args, void *wrapped)
4404{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004405 inquiry func = (inquiry)wrapped;
4406 int res;
Raymond Hettingerf34f2642003-10-11 17:29:04 +00004407
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004408 if (!check_num_args(args, 0))
4409 return NULL;
4410 res = (*func)(self);
4411 if (res == -1 && PyErr_Occurred())
4412 return NULL;
4413 return PyBool_FromLong((long)res);
Raymond Hettingerf34f2642003-10-11 17:29:04 +00004414}
4415
4416static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00004417wrap_binaryfunc(PyObject *self, PyObject *args, void *wrapped)
4418{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004419 binaryfunc func = (binaryfunc)wrapped;
4420 PyObject *other;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004421
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004422 if (!check_num_args(args, 1))
4423 return NULL;
4424 other = PyTuple_GET_ITEM(args, 0);
4425 return (*func)(self, other);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004426}
4427
4428static PyObject *
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00004429wrap_binaryfunc_l(PyObject *self, PyObject *args, void *wrapped)
4430{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004431 binaryfunc func = (binaryfunc)wrapped;
4432 PyObject *other;
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00004433
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004434 if (!check_num_args(args, 1))
4435 return NULL;
4436 other = PyTuple_GET_ITEM(args, 0);
4437 return (*func)(self, other);
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00004438}
4439
4440static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00004441wrap_binaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
4442{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004443 binaryfunc func = (binaryfunc)wrapped;
4444 PyObject *other;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004445
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004446 if (!check_num_args(args, 1))
4447 return NULL;
4448 other = PyTuple_GET_ITEM(args, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004449 return (*func)(other, self);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004450}
4451
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004452static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00004453wrap_ternaryfunc(PyObject *self, PyObject *args, void *wrapped)
4454{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004455 ternaryfunc func = (ternaryfunc)wrapped;
4456 PyObject *other;
4457 PyObject *third = Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004458
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004459 /* Note: This wrapper only works for __pow__() */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004460
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004461 if (!PyArg_UnpackTuple(args, "", 1, 2, &other, &third))
4462 return NULL;
4463 return (*func)(self, other, third);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004464}
4465
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00004466static PyObject *
4467wrap_ternaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
4468{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004469 ternaryfunc func = (ternaryfunc)wrapped;
4470 PyObject *other;
4471 PyObject *third = Py_None;
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00004472
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004473 /* Note: This wrapper only works for __pow__() */
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00004474
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004475 if (!PyArg_UnpackTuple(args, "", 1, 2, &other, &third))
4476 return NULL;
4477 return (*func)(other, self, third);
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00004478}
4479
Tim Peters6d6c1a32001-08-02 04:15:00 +00004480static PyObject *
4481wrap_unaryfunc(PyObject *self, PyObject *args, void *wrapped)
4482{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004483 unaryfunc func = (unaryfunc)wrapped;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004484
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004485 if (!check_num_args(args, 0))
4486 return NULL;
4487 return (*func)(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004488}
4489
Tim Peters6d6c1a32001-08-02 04:15:00 +00004490static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004491wrap_indexargfunc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004492{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004493 ssizeargfunc func = (ssizeargfunc)wrapped;
4494 PyObject* o;
4495 Py_ssize_t i;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004496
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004497 if (!PyArg_UnpackTuple(args, "", 1, 1, &o))
4498 return NULL;
4499 i = PyNumber_AsSsize_t(o, PyExc_OverflowError);
4500 if (i == -1 && PyErr_Occurred())
4501 return NULL;
4502 return (*func)(self, i);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004503}
4504
Martin v. Löwis18e16552006-02-15 17:27:45 +00004505static Py_ssize_t
Guido van Rossum5d815f32001-08-17 21:57:47 +00004506getindex(PyObject *self, PyObject *arg)
4507{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004508 Py_ssize_t i;
Guido van Rossum5d815f32001-08-17 21:57:47 +00004509
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004510 i = PyNumber_AsSsize_t(arg, PyExc_OverflowError);
4511 if (i == -1 && PyErr_Occurred())
4512 return -1;
4513 if (i < 0) {
4514 PySequenceMethods *sq = Py_TYPE(self)->tp_as_sequence;
4515 if (sq && sq->sq_length) {
4516 Py_ssize_t n = (*sq->sq_length)(self);
4517 if (n < 0)
4518 return -1;
4519 i += n;
4520 }
4521 }
4522 return i;
Guido van Rossum5d815f32001-08-17 21:57:47 +00004523}
4524
4525static PyObject *
4526wrap_sq_item(PyObject *self, PyObject *args, void *wrapped)
4527{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004528 ssizeargfunc func = (ssizeargfunc)wrapped;
4529 PyObject *arg;
4530 Py_ssize_t i;
Guido van Rossum5d815f32001-08-17 21:57:47 +00004531
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004532 if (PyTuple_GET_SIZE(args) == 1) {
4533 arg = PyTuple_GET_ITEM(args, 0);
4534 i = getindex(self, arg);
4535 if (i == -1 && PyErr_Occurred())
4536 return NULL;
4537 return (*func)(self, i);
4538 }
4539 check_num_args(args, 1);
4540 assert(PyErr_Occurred());
4541 return NULL;
Guido van Rossum5d815f32001-08-17 21:57:47 +00004542}
4543
Tim Peters6d6c1a32001-08-02 04:15:00 +00004544static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00004545wrap_sq_setitem(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004546{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004547 ssizeobjargproc func = (ssizeobjargproc)wrapped;
4548 Py_ssize_t i;
4549 int res;
4550 PyObject *arg, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004551
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004552 if (!PyArg_UnpackTuple(args, "", 2, 2, &arg, &value))
4553 return NULL;
4554 i = getindex(self, arg);
4555 if (i == -1 && PyErr_Occurred())
4556 return NULL;
4557 res = (*func)(self, i, value);
4558 if (res == -1 && PyErr_Occurred())
4559 return NULL;
4560 Py_INCREF(Py_None);
4561 return Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004562}
4563
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004564static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00004565wrap_sq_delitem(PyObject *self, PyObject *args, void *wrapped)
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004566{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004567 ssizeobjargproc func = (ssizeobjargproc)wrapped;
4568 Py_ssize_t i;
4569 int res;
4570 PyObject *arg;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004571
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004572 if (!check_num_args(args, 1))
4573 return NULL;
4574 arg = PyTuple_GET_ITEM(args, 0);
4575 i = getindex(self, arg);
4576 if (i == -1 && PyErr_Occurred())
4577 return NULL;
4578 res = (*func)(self, i, NULL);
4579 if (res == -1 && PyErr_Occurred())
4580 return NULL;
4581 Py_INCREF(Py_None);
4582 return Py_None;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004583}
4584
Tim Peters6d6c1a32001-08-02 04:15:00 +00004585/* XXX objobjproc is a misnomer; should be objargpred */
4586static PyObject *
4587wrap_objobjproc(PyObject *self, PyObject *args, void *wrapped)
4588{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004589 objobjproc func = (objobjproc)wrapped;
4590 int res;
4591 PyObject *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004592
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004593 if (!check_num_args(args, 1))
4594 return NULL;
4595 value = PyTuple_GET_ITEM(args, 0);
4596 res = (*func)(self, value);
4597 if (res == -1 && PyErr_Occurred())
4598 return NULL;
4599 else
4600 return PyBool_FromLong(res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004601}
4602
Tim Peters6d6c1a32001-08-02 04:15:00 +00004603static PyObject *
4604wrap_objobjargproc(PyObject *self, PyObject *args, void *wrapped)
4605{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004606 objobjargproc func = (objobjargproc)wrapped;
4607 int res;
4608 PyObject *key, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004609
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004610 if (!PyArg_UnpackTuple(args, "", 2, 2, &key, &value))
4611 return NULL;
4612 res = (*func)(self, key, value);
4613 if (res == -1 && PyErr_Occurred())
4614 return NULL;
4615 Py_INCREF(Py_None);
4616 return Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004617}
4618
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004619static PyObject *
4620wrap_delitem(PyObject *self, PyObject *args, void *wrapped)
4621{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004622 objobjargproc func = (objobjargproc)wrapped;
4623 int res;
4624 PyObject *key;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004625
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004626 if (!check_num_args(args, 1))
4627 return NULL;
4628 key = PyTuple_GET_ITEM(args, 0);
4629 res = (*func)(self, key, NULL);
4630 if (res == -1 && PyErr_Occurred())
4631 return NULL;
4632 Py_INCREF(Py_None);
4633 return Py_None;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004634}
4635
Guido van Rossum4dcdb782003-04-14 21:46:03 +00004636/* Helper to check for object.__setattr__ or __delattr__ applied to a type.
Guido van Rossum52b27052003-04-15 20:05:10 +00004637 This is called the Carlo Verre hack after its discoverer. */
Guido van Rossum4dcdb782003-04-14 21:46:03 +00004638static int
4639hackcheck(PyObject *self, setattrofunc func, char *what)
4640{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004641 PyTypeObject *type = Py_TYPE(self);
4642 while (type && type->tp_flags & Py_TPFLAGS_HEAPTYPE)
4643 type = type->tp_base;
4644 /* If type is NULL now, this is a really weird type.
4645 In the spirit of backwards compatibility (?), just shut up. */
4646 if (type && type->tp_setattro != func) {
4647 PyErr_Format(PyExc_TypeError,
4648 "can't apply this %s to %s object",
4649 what,
4650 type->tp_name);
4651 return 0;
4652 }
4653 return 1;
Guido van Rossum4dcdb782003-04-14 21:46:03 +00004654}
4655
Tim Peters6d6c1a32001-08-02 04:15:00 +00004656static PyObject *
4657wrap_setattr(PyObject *self, PyObject *args, void *wrapped)
4658{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004659 setattrofunc func = (setattrofunc)wrapped;
4660 int res;
4661 PyObject *name, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004662
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004663 if (!PyArg_UnpackTuple(args, "", 2, 2, &name, &value))
4664 return NULL;
4665 if (!hackcheck(self, func, "__setattr__"))
4666 return NULL;
4667 res = (*func)(self, name, value);
4668 if (res < 0)
4669 return NULL;
4670 Py_INCREF(Py_None);
4671 return Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004672}
4673
4674static PyObject *
4675wrap_delattr(PyObject *self, PyObject *args, void *wrapped)
4676{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004677 setattrofunc func = (setattrofunc)wrapped;
4678 int res;
4679 PyObject *name;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004680
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004681 if (!check_num_args(args, 1))
4682 return NULL;
4683 name = PyTuple_GET_ITEM(args, 0);
4684 if (!hackcheck(self, func, "__delattr__"))
4685 return NULL;
4686 res = (*func)(self, name, NULL);
4687 if (res < 0)
4688 return NULL;
4689 Py_INCREF(Py_None);
4690 return Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004691}
4692
Tim Peters6d6c1a32001-08-02 04:15:00 +00004693static PyObject *
4694wrap_hashfunc(PyObject *self, PyObject *args, void *wrapped)
4695{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004696 hashfunc func = (hashfunc)wrapped;
Benjamin Peterson8035bc52010-10-23 16:20:50 +00004697 Py_hash_t res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004698
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004699 if (!check_num_args(args, 0))
4700 return NULL;
4701 res = (*func)(self);
4702 if (res == -1 && PyErr_Occurred())
4703 return NULL;
Benjamin Peterson8035bc52010-10-23 16:20:50 +00004704 return PyLong_FromSsize_t(res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004705}
4706
Tim Peters6d6c1a32001-08-02 04:15:00 +00004707static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00004708wrap_call(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004709{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004710 ternaryfunc func = (ternaryfunc)wrapped;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004711
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004712 return (*func)(self, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004713}
4714
Tim Peters6d6c1a32001-08-02 04:15:00 +00004715static PyObject *
4716wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op)
4717{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004718 richcmpfunc func = (richcmpfunc)wrapped;
4719 PyObject *other;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004720
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004721 if (!check_num_args(args, 1))
4722 return NULL;
4723 other = PyTuple_GET_ITEM(args, 0);
4724 return (*func)(self, other, op);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004725}
4726
4727#undef RICHCMP_WRAPPER
4728#define RICHCMP_WRAPPER(NAME, OP) \
4729static PyObject * \
4730richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \
4731{ \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004732 return wrap_richcmpfunc(self, args, wrapped, OP); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004733}
4734
Jack Jansen8e938b42001-08-08 15:29:49 +00004735RICHCMP_WRAPPER(lt, Py_LT)
4736RICHCMP_WRAPPER(le, Py_LE)
4737RICHCMP_WRAPPER(eq, Py_EQ)
4738RICHCMP_WRAPPER(ne, Py_NE)
4739RICHCMP_WRAPPER(gt, Py_GT)
4740RICHCMP_WRAPPER(ge, Py_GE)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004741
Tim Peters6d6c1a32001-08-02 04:15:00 +00004742static PyObject *
4743wrap_next(PyObject *self, PyObject *args, void *wrapped)
4744{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004745 unaryfunc func = (unaryfunc)wrapped;
4746 PyObject *res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004747
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004748 if (!check_num_args(args, 0))
4749 return NULL;
4750 res = (*func)(self);
4751 if (res == NULL && !PyErr_Occurred())
4752 PyErr_SetNone(PyExc_StopIteration);
4753 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004754}
4755
Tim Peters6d6c1a32001-08-02 04:15:00 +00004756static PyObject *
4757wrap_descr_get(PyObject *self, PyObject *args, void *wrapped)
4758{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004759 descrgetfunc func = (descrgetfunc)wrapped;
4760 PyObject *obj;
4761 PyObject *type = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004762
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004763 if (!PyArg_UnpackTuple(args, "", 1, 2, &obj, &type))
4764 return NULL;
4765 if (obj == Py_None)
4766 obj = NULL;
4767 if (type == Py_None)
4768 type = NULL;
4769 if (type == NULL &&obj == NULL) {
4770 PyErr_SetString(PyExc_TypeError,
4771 "__get__(None, None) is invalid");
4772 return NULL;
4773 }
4774 return (*func)(self, obj, type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004775}
4776
Tim Peters6d6c1a32001-08-02 04:15:00 +00004777static PyObject *
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004778wrap_descr_set(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004779{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004780 descrsetfunc func = (descrsetfunc)wrapped;
4781 PyObject *obj, *value;
4782 int ret;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004783
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004784 if (!PyArg_UnpackTuple(args, "", 2, 2, &obj, &value))
4785 return NULL;
4786 ret = (*func)(self, obj, value);
4787 if (ret < 0)
4788 return NULL;
4789 Py_INCREF(Py_None);
4790 return Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004791}
Guido van Rossum22b13872002-08-06 21:41:44 +00004792
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00004793static PyObject *
4794wrap_descr_delete(PyObject *self, PyObject *args, void *wrapped)
4795{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004796 descrsetfunc func = (descrsetfunc)wrapped;
4797 PyObject *obj;
4798 int ret;
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00004799
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004800 if (!check_num_args(args, 1))
4801 return NULL;
4802 obj = PyTuple_GET_ITEM(args, 0);
4803 ret = (*func)(self, obj, NULL);
4804 if (ret < 0)
4805 return NULL;
4806 Py_INCREF(Py_None);
4807 return Py_None;
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00004808}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004809
Tim Peters6d6c1a32001-08-02 04:15:00 +00004810static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00004811wrap_init(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004812{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004813 initproc func = (initproc)wrapped;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004814
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004815 if (func(self, args, kwds) < 0)
4816 return NULL;
4817 Py_INCREF(Py_None);
4818 return Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004819}
4820
Tim Peters6d6c1a32001-08-02 04:15:00 +00004821static PyObject *
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004822tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004823{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004824 PyTypeObject *type, *subtype, *staticbase;
4825 PyObject *arg0, *res;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004826
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004827 if (self == NULL || !PyType_Check(self))
4828 Py_FatalError("__new__() called with non-type 'self'");
4829 type = (PyTypeObject *)self;
4830 if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) {
4831 PyErr_Format(PyExc_TypeError,
4832 "%s.__new__(): not enough arguments",
4833 type->tp_name);
4834 return NULL;
4835 }
4836 arg0 = PyTuple_GET_ITEM(args, 0);
4837 if (!PyType_Check(arg0)) {
4838 PyErr_Format(PyExc_TypeError,
4839 "%s.__new__(X): X is not a type object (%s)",
4840 type->tp_name,
4841 Py_TYPE(arg0)->tp_name);
4842 return NULL;
4843 }
4844 subtype = (PyTypeObject *)arg0;
4845 if (!PyType_IsSubtype(subtype, type)) {
4846 PyErr_Format(PyExc_TypeError,
4847 "%s.__new__(%s): %s is not a subtype of %s",
4848 type->tp_name,
4849 subtype->tp_name,
4850 subtype->tp_name,
4851 type->tp_name);
4852 return NULL;
4853 }
Barry Warsaw60f01882001-08-22 19:24:42 +00004854
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004855 /* Check that the use doesn't do something silly and unsafe like
4856 object.__new__(dict). To do this, we check that the
4857 most derived base that's not a heap type is this type. */
4858 staticbase = subtype;
Martin v. Löwis9c564092012-06-23 23:20:45 +02004859 while (staticbase && (staticbase->tp_new == slot_tp_new))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004860 staticbase = staticbase->tp_base;
4861 /* If staticbase is NULL now, it is a really weird type.
4862 In the spirit of backwards compatibility (?), just shut up. */
4863 if (staticbase && staticbase->tp_new != type->tp_new) {
4864 PyErr_Format(PyExc_TypeError,
4865 "%s.__new__(%s) is not safe, use %s.__new__()",
4866 type->tp_name,
4867 subtype->tp_name,
4868 staticbase == NULL ? "?" : staticbase->tp_name);
4869 return NULL;
4870 }
Barry Warsaw60f01882001-08-22 19:24:42 +00004871
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004872 args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
4873 if (args == NULL)
4874 return NULL;
4875 res = type->tp_new(subtype, args, kwds);
4876 Py_DECREF(args);
4877 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004878}
4879
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004880static struct PyMethodDef tp_new_methoddef[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004881 {"__new__", (PyCFunction)tp_new_wrapper, METH_VARARGS|METH_KEYWORDS,
4882 PyDoc_STR("T.__new__(S, ...) -> "
4883 "a new object with type S, a subtype of T")},
4884 {0}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004885};
4886
4887static int
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004888add_tp_new_wrapper(PyTypeObject *type)
4889{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004890 PyObject *func;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004891
Victor Stinner3c1e4812012-03-26 22:10:51 +02004892 if (_PyDict_GetItemId(type->tp_dict, &PyId___new__) != NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004893 return 0;
4894 func = PyCFunction_New(tp_new_methoddef, (PyObject *)type);
4895 if (func == NULL)
4896 return -1;
Victor Stinner3c1e4812012-03-26 22:10:51 +02004897 if (_PyDict_SetItemId(type->tp_dict, &PyId___new__, func)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004898 Py_DECREF(func);
4899 return -1;
4900 }
4901 Py_DECREF(func);
4902 return 0;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004903}
4904
Guido van Rossumf040ede2001-08-07 16:40:56 +00004905/* Slot wrappers that call the corresponding __foo__ slot. See comments
4906 below at override_slots() for more explanation. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004907
Guido van Rossumdc91b992001-08-08 22:26:22 +00004908#define SLOT0(FUNCNAME, OPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004909static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004910FUNCNAME(PyObject *self) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004911{ \
Benjamin Petersonce798522012-01-22 11:24:29 -05004912 _Py_static_string(id, OPSTR); \
4913 return call_method(self, &id, "()"); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004914}
4915
Guido van Rossumdc91b992001-08-08 22:26:22 +00004916#define SLOT1(FUNCNAME, OPSTR, ARG1TYPE, ARGCODES) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004917static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004918FUNCNAME(PyObject *self, ARG1TYPE arg1) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004919{ \
Benjamin Petersonce798522012-01-22 11:24:29 -05004920 _Py_static_string(id, OPSTR); \
4921 return call_method(self, &id, "(" ARGCODES ")", arg1); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004922}
4923
Guido van Rossumcd118802003-01-06 22:57:47 +00004924/* Boolean helper for SLOT1BINFULL().
4925 right.__class__ is a nontrivial subclass of left.__class__. */
4926static int
Victor Stinner3c1e4812012-03-26 22:10:51 +02004927method_is_overloaded(PyObject *left, PyObject *right, struct _Py_Identifier *name)
Guido van Rossumcd118802003-01-06 22:57:47 +00004928{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004929 PyObject *a, *b;
4930 int ok;
Guido van Rossumcd118802003-01-06 22:57:47 +00004931
Victor Stinner3c1e4812012-03-26 22:10:51 +02004932 b = _PyObject_GetAttrId((PyObject *)(Py_TYPE(right)), name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004933 if (b == NULL) {
4934 PyErr_Clear();
4935 /* If right doesn't have it, it's not overloaded */
4936 return 0;
4937 }
Guido van Rossumcd118802003-01-06 22:57:47 +00004938
Victor Stinner3c1e4812012-03-26 22:10:51 +02004939 a = _PyObject_GetAttrId((PyObject *)(Py_TYPE(left)), name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004940 if (a == NULL) {
4941 PyErr_Clear();
4942 Py_DECREF(b);
4943 /* If right has it but left doesn't, it's overloaded */
4944 return 1;
4945 }
Guido van Rossumcd118802003-01-06 22:57:47 +00004946
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004947 ok = PyObject_RichCompareBool(a, b, Py_NE);
4948 Py_DECREF(a);
4949 Py_DECREF(b);
4950 if (ok < 0) {
4951 PyErr_Clear();
4952 return 0;
4953 }
Guido van Rossumcd118802003-01-06 22:57:47 +00004954
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004955 return ok;
Guido van Rossumcd118802003-01-06 22:57:47 +00004956}
4957
Guido van Rossumdc91b992001-08-08 22:26:22 +00004958
4959#define SLOT1BINFULL(FUNCNAME, TESTFUNC, SLOTNAME, OPSTR, ROPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004960static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004961FUNCNAME(PyObject *self, PyObject *other) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004962{ \
Benjamin Petersonce798522012-01-22 11:24:29 -05004963 _Py_static_string(op_id, OPSTR); \
4964 _Py_static_string(rop_id, ROPSTR); \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004965 int do_other = Py_TYPE(self) != Py_TYPE(other) && \
4966 Py_TYPE(other)->tp_as_number != NULL && \
4967 Py_TYPE(other)->tp_as_number->SLOTNAME == TESTFUNC; \
4968 if (Py_TYPE(self)->tp_as_number != NULL && \
4969 Py_TYPE(self)->tp_as_number->SLOTNAME == TESTFUNC) { \
4970 PyObject *r; \
4971 if (do_other && \
4972 PyType_IsSubtype(Py_TYPE(other), Py_TYPE(self)) && \
Victor Stinner3c1e4812012-03-26 22:10:51 +02004973 method_is_overloaded(self, other, &rop_id)) { \
Benjamin Petersonce798522012-01-22 11:24:29 -05004974 r = call_maybe(other, &rop_id, "(O)", self); \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004975 if (r != Py_NotImplemented) \
4976 return r; \
4977 Py_DECREF(r); \
4978 do_other = 0; \
4979 } \
Benjamin Petersonce798522012-01-22 11:24:29 -05004980 r = call_maybe(self, &op_id, "(O)", other); \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004981 if (r != Py_NotImplemented || \
4982 Py_TYPE(other) == Py_TYPE(self)) \
4983 return r; \
4984 Py_DECREF(r); \
4985 } \
4986 if (do_other) { \
Benjamin Petersonce798522012-01-22 11:24:29 -05004987 return call_maybe(other, &rop_id, "(O)", self); \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004988 } \
Brian Curtindfc80e32011-08-10 20:28:54 -05004989 Py_RETURN_NOTIMPLEMENTED; \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004990}
4991
4992#define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004993 SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR)
Guido van Rossumdc91b992001-08-08 22:26:22 +00004994
4995#define SLOT2(FUNCNAME, OPSTR, ARG1TYPE, ARG2TYPE, ARGCODES) \
4996static PyObject * \
4997FUNCNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \
4998{ \
Benjamin Petersonce798522012-01-22 11:24:29 -05004999 _Py_static_string(id, #OPSTR); \
5000 return call_method(self, &id, "(" ARGCODES ")", arg1, arg2); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00005001}
5002
Martin v. Löwis18e16552006-02-15 17:27:45 +00005003static Py_ssize_t
Tim Peters6d6c1a32001-08-02 04:15:00 +00005004slot_sq_length(PyObject *self)
5005{
Benjamin Petersonce798522012-01-22 11:24:29 -05005006 _Py_IDENTIFIER(__len__);
5007 PyObject *res = call_method(self, &PyId___len__, "()");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005008 Py_ssize_t len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005009
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005010 if (res == NULL)
5011 return -1;
5012 len = PyNumber_AsSsize_t(res, PyExc_OverflowError);
5013 Py_DECREF(res);
5014 if (len < 0) {
5015 if (!PyErr_Occurred())
5016 PyErr_SetString(PyExc_ValueError,
5017 "__len__() should return >= 0");
5018 return -1;
5019 }
5020 return len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005021}
5022
Guido van Rossumf4593e02001-10-03 12:09:30 +00005023/* Super-optimized version of slot_sq_item.
5024 Other slots could do the same... */
5025static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00005026slot_sq_item(PyObject *self, Py_ssize_t i)
Guido van Rossumf4593e02001-10-03 12:09:30 +00005027{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005028 PyObject *func, *args = NULL, *ival = NULL, *retval = NULL;
5029 descrgetfunc f;
Guido van Rossumf4593e02001-10-03 12:09:30 +00005030
Victor Stinner3c1e4812012-03-26 22:10:51 +02005031 func = _PyType_LookupId(Py_TYPE(self), &PyId___getitem__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005032 if (func != NULL) {
5033 if ((f = Py_TYPE(func)->tp_descr_get) == NULL)
5034 Py_INCREF(func);
5035 else {
5036 func = f(func, self, (PyObject *)(Py_TYPE(self)));
5037 if (func == NULL) {
5038 return NULL;
5039 }
5040 }
5041 ival = PyLong_FromSsize_t(i);
5042 if (ival != NULL) {
5043 args = PyTuple_New(1);
5044 if (args != NULL) {
5045 PyTuple_SET_ITEM(args, 0, ival);
5046 retval = PyObject_Call(func, args, NULL);
5047 Py_XDECREF(args);
5048 Py_XDECREF(func);
5049 return retval;
5050 }
5051 }
5052 }
5053 else {
Victor Stinner3c1e4812012-03-26 22:10:51 +02005054 PyObject *getitem_str = _PyUnicode_FromId(&PyId___getitem__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005055 PyErr_SetObject(PyExc_AttributeError, getitem_str);
5056 }
5057 Py_XDECREF(args);
5058 Py_XDECREF(ival);
5059 Py_XDECREF(func);
5060 return NULL;
Guido van Rossumf4593e02001-10-03 12:09:30 +00005061}
5062
Tim Peters6d6c1a32001-08-02 04:15:00 +00005063static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00005064slot_sq_ass_item(PyObject *self, Py_ssize_t index, PyObject *value)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005065{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005066 PyObject *res;
Benjamin Petersonce798522012-01-22 11:24:29 -05005067 _Py_IDENTIFIER(__delitem__);
5068 _Py_IDENTIFIER(__setitem__);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005069
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005070 if (value == NULL)
Benjamin Petersonce798522012-01-22 11:24:29 -05005071 res = call_method(self, &PyId___delitem__, "(n)", index);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005072 else
Benjamin Petersonce798522012-01-22 11:24:29 -05005073 res = call_method(self, &PyId___setitem__, "(nO)", index, value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005074 if (res == NULL)
5075 return -1;
5076 Py_DECREF(res);
5077 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005078}
5079
5080static int
Tim Peters6d6c1a32001-08-02 04:15:00 +00005081slot_sq_contains(PyObject *self, PyObject *value)
5082{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005083 PyObject *func, *res, *args;
5084 int result = -1;
Benjamin Petersonce798522012-01-22 11:24:29 -05005085 _Py_IDENTIFIER(__contains__);
Tim Petersbf9b2442003-03-23 05:35:36 +00005086
Benjamin Petersonce798522012-01-22 11:24:29 -05005087 func = lookup_maybe(self, &PyId___contains__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005088 if (func != NULL) {
5089 args = PyTuple_Pack(1, value);
5090 if (args == NULL)
5091 res = NULL;
5092 else {
5093 res = PyObject_Call(func, args, NULL);
5094 Py_DECREF(args);
5095 }
5096 Py_DECREF(func);
5097 if (res != NULL) {
5098 result = PyObject_IsTrue(res);
5099 Py_DECREF(res);
5100 }
5101 }
5102 else if (! PyErr_Occurred()) {
5103 /* Possible results: -1 and 1 */
5104 result = (int)_PySequence_IterSearch(self, value,
5105 PY_ITERSEARCH_CONTAINS);
5106 }
5107 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005108}
5109
Tim Peters6d6c1a32001-08-02 04:15:00 +00005110#define slot_mp_length slot_sq_length
5111
Guido van Rossumdc91b992001-08-08 22:26:22 +00005112SLOT1(slot_mp_subscript, "__getitem__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00005113
5114static int
5115slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value)
5116{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005117 PyObject *res;
Benjamin Petersonce798522012-01-22 11:24:29 -05005118 _Py_IDENTIFIER(__delitem__);
5119 _Py_IDENTIFIER(__setitem__);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005120
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005121 if (value == NULL)
Benjamin Petersonce798522012-01-22 11:24:29 -05005122 res = call_method(self, &PyId___delitem__, "(O)", key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005123 else
Benjamin Petersonce798522012-01-22 11:24:29 -05005124 res = call_method(self, &PyId___setitem__, "(OO)", key, value);
5125
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005126 if (res == NULL)
5127 return -1;
5128 Py_DECREF(res);
5129 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005130}
5131
Guido van Rossumdc91b992001-08-08 22:26:22 +00005132SLOT1BIN(slot_nb_add, nb_add, "__add__", "__radd__")
5133SLOT1BIN(slot_nb_subtract, nb_subtract, "__sub__", "__rsub__")
5134SLOT1BIN(slot_nb_multiply, nb_multiply, "__mul__", "__rmul__")
Guido van Rossumdc91b992001-08-08 22:26:22 +00005135SLOT1BIN(slot_nb_remainder, nb_remainder, "__mod__", "__rmod__")
5136SLOT1BIN(slot_nb_divmod, nb_divmod, "__divmod__", "__rdivmod__")
5137
Jeremy Hylton938ace62002-07-17 16:30:39 +00005138static PyObject *slot_nb_power(PyObject *, PyObject *, PyObject *);
Guido van Rossumdc91b992001-08-08 22:26:22 +00005139
5140SLOT1BINFULL(slot_nb_power_binary, slot_nb_power,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005141 nb_power, "__pow__", "__rpow__")
Guido van Rossumdc91b992001-08-08 22:26:22 +00005142
5143static PyObject *
5144slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus)
5145{
Benjamin Petersonce798522012-01-22 11:24:29 -05005146 _Py_IDENTIFIER(__pow__);
Guido van Rossum2730b132001-08-28 18:22:14 +00005147
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005148 if (modulus == Py_None)
5149 return slot_nb_power_binary(self, other);
5150 /* Three-arg power doesn't use __rpow__. But ternary_op
5151 can call this when the second argument's type uses
5152 slot_nb_power, so check before calling self.__pow__. */
5153 if (Py_TYPE(self)->tp_as_number != NULL &&
5154 Py_TYPE(self)->tp_as_number->nb_power == slot_nb_power) {
Benjamin Petersonce798522012-01-22 11:24:29 -05005155 return call_method(self, &PyId___pow__, "(OO)", other, modulus);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005156 }
Brian Curtindfc80e32011-08-10 20:28:54 -05005157 Py_RETURN_NOTIMPLEMENTED;
Guido van Rossumdc91b992001-08-08 22:26:22 +00005158}
5159
5160SLOT0(slot_nb_negative, "__neg__")
5161SLOT0(slot_nb_positive, "__pos__")
5162SLOT0(slot_nb_absolute, "__abs__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00005163
5164static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00005165slot_nb_bool(PyObject *self)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005166{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005167 PyObject *func, *args;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005168 int result = -1;
5169 int using_len = 0;
Benjamin Petersonce798522012-01-22 11:24:29 -05005170 _Py_IDENTIFIER(__len__);
5171 _Py_IDENTIFIER(__bool__);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005172
Benjamin Petersonce798522012-01-22 11:24:29 -05005173 func = lookup_maybe(self, &PyId___bool__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005174 if (func == NULL) {
5175 if (PyErr_Occurred())
5176 return -1;
Benjamin Petersonce798522012-01-22 11:24:29 -05005177 func = lookup_maybe(self, &PyId___len__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005178 if (func == NULL)
5179 return PyErr_Occurred() ? -1 : 1;
5180 using_len = 1;
5181 }
5182 args = PyTuple_New(0);
5183 if (args != NULL) {
5184 PyObject *temp = PyObject_Call(func, args, NULL);
5185 Py_DECREF(args);
5186 if (temp != NULL) {
5187 if (using_len) {
5188 /* enforced by slot_nb_len */
5189 result = PyObject_IsTrue(temp);
5190 }
5191 else if (PyBool_Check(temp)) {
5192 result = PyObject_IsTrue(temp);
5193 }
5194 else {
5195 PyErr_Format(PyExc_TypeError,
5196 "__bool__ should return "
5197 "bool, returned %s",
5198 Py_TYPE(temp)->tp_name);
5199 result = -1;
5200 }
5201 Py_DECREF(temp);
5202 }
5203 }
5204 Py_DECREF(func);
5205 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005206}
5207
Guido van Rossum38fff8c2006-03-07 18:50:55 +00005208
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00005209static PyObject *
Guido van Rossum38fff8c2006-03-07 18:50:55 +00005210slot_nb_index(PyObject *self)
5211{
Benjamin Petersonce798522012-01-22 11:24:29 -05005212 _Py_IDENTIFIER(__index__);
5213 return call_method(self, &PyId___index__, "()");
Guido van Rossum38fff8c2006-03-07 18:50:55 +00005214}
5215
5216
Guido van Rossumdc91b992001-08-08 22:26:22 +00005217SLOT0(slot_nb_invert, "__invert__")
5218SLOT1BIN(slot_nb_lshift, nb_lshift, "__lshift__", "__rlshift__")
5219SLOT1BIN(slot_nb_rshift, nb_rshift, "__rshift__", "__rrshift__")
5220SLOT1BIN(slot_nb_and, nb_and, "__and__", "__rand__")
5221SLOT1BIN(slot_nb_xor, nb_xor, "__xor__", "__rxor__")
5222SLOT1BIN(slot_nb_or, nb_or, "__or__", "__ror__")
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00005223
Guido van Rossumdc91b992001-08-08 22:26:22 +00005224SLOT0(slot_nb_int, "__int__")
Guido van Rossumdc91b992001-08-08 22:26:22 +00005225SLOT0(slot_nb_float, "__float__")
Guido van Rossumdc91b992001-08-08 22:26:22 +00005226SLOT1(slot_nb_inplace_add, "__iadd__", PyObject *, "O")
5227SLOT1(slot_nb_inplace_subtract, "__isub__", PyObject *, "O")
5228SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *, "O")
Guido van Rossumdc91b992001-08-08 22:26:22 +00005229SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *, "O")
Thomas Wouterscf297e42007-02-23 15:07:44 +00005230/* Can't use SLOT1 here, because nb_inplace_power is ternary */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005231static PyObject *
5232slot_nb_inplace_power(PyObject *self, PyObject * arg1, PyObject *arg2)
5233{
Benjamin Petersonce798522012-01-22 11:24:29 -05005234 _Py_IDENTIFIER(__ipow__);
5235 return call_method(self, &PyId___ipow__, "(" "O" ")", arg1);
Thomas Wouterscf297e42007-02-23 15:07:44 +00005236}
Guido van Rossumdc91b992001-08-08 22:26:22 +00005237SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *, "O")
5238SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *, "O")
5239SLOT1(slot_nb_inplace_and, "__iand__", PyObject *, "O")
5240SLOT1(slot_nb_inplace_xor, "__ixor__", PyObject *, "O")
5241SLOT1(slot_nb_inplace_or, "__ior__", PyObject *, "O")
5242SLOT1BIN(slot_nb_floor_divide, nb_floor_divide,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005243 "__floordiv__", "__rfloordiv__")
Guido van Rossumdc91b992001-08-08 22:26:22 +00005244SLOT1BIN(slot_nb_true_divide, nb_true_divide, "__truediv__", "__rtruediv__")
5245SLOT1(slot_nb_inplace_floor_divide, "__ifloordiv__", PyObject *, "O")
5246SLOT1(slot_nb_inplace_true_divide, "__itruediv__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00005247
Guido van Rossumb8f63662001-08-15 23:57:02 +00005248static PyObject *
5249slot_tp_repr(PyObject *self)
5250{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005251 PyObject *func, *res;
Benjamin Petersonce798522012-01-22 11:24:29 -05005252 _Py_IDENTIFIER(__repr__);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005253
Benjamin Petersonce798522012-01-22 11:24:29 -05005254 func = lookup_method(self, &PyId___repr__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005255 if (func != NULL) {
5256 res = PyEval_CallObject(func, NULL);
5257 Py_DECREF(func);
5258 return res;
5259 }
5260 PyErr_Clear();
5261 return PyUnicode_FromFormat("<%s object at %p>",
5262 Py_TYPE(self)->tp_name, self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005263}
5264
5265static PyObject *
5266slot_tp_str(PyObject *self)
5267{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005268 PyObject *func, *res;
Benjamin Petersonce798522012-01-22 11:24:29 -05005269 _Py_IDENTIFIER(__str__);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005270
Benjamin Petersonce798522012-01-22 11:24:29 -05005271 func = lookup_method(self, &PyId___str__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005272 if (func != NULL) {
5273 res = PyEval_CallObject(func, NULL);
5274 Py_DECREF(func);
5275 return res;
5276 }
5277 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005278 /* PyObject *ress; */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005279 PyErr_Clear();
5280 res = slot_tp_repr(self);
5281 if (!res)
5282 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005283 /* XXX this is non-sensical. Why should we return
5284 a bytes object from __str__. Is this code even
5285 used? - mvl */
5286 assert(0);
5287 return res;
5288 /*
Victor Stinnerf3fd7332011-03-02 01:03:11 +00005289 ress = _PyUnicode_AsDefaultEncodedString(res);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005290 Py_DECREF(res);
5291 return ress;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005292 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005293 }
Guido van Rossumb8f63662001-08-15 23:57:02 +00005294}
Tim Peters6d6c1a32001-08-02 04:15:00 +00005295
Benjamin Peterson8f67d082010-10-17 20:54:53 +00005296static Py_hash_t
Tim Peters6d6c1a32001-08-02 04:15:00 +00005297slot_tp_hash(PyObject *self)
5298{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005299 PyObject *func, *res;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00005300 Py_ssize_t h;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005301
Benjamin Petersonce798522012-01-22 11:24:29 -05005302 func = lookup_method(self, &PyId___hash__);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005303
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005304 if (func == Py_None) {
5305 Py_DECREF(func);
5306 func = NULL;
5307 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +00005308
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005309 if (func == NULL) {
5310 return PyObject_HashNotImplemented(self);
5311 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +00005312
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005313 res = PyEval_CallObject(func, NULL);
5314 Py_DECREF(func);
5315 if (res == NULL)
5316 return -1;
Mark Dickinsondc787d22010-05-23 13:33:13 +00005317
5318 if (!PyLong_Check(res)) {
5319 PyErr_SetString(PyExc_TypeError,
5320 "__hash__ method should return an integer");
5321 return -1;
5322 }
Benjamin Peterson8f67d082010-10-17 20:54:53 +00005323 /* Transform the PyLong `res` to a Py_hash_t `h`. For an existing
5324 hashable Python object x, hash(x) will always lie within the range of
5325 Py_hash_t. Therefore our transformation must preserve values that
5326 already lie within this range, to ensure that if x.__hash__() returns
5327 hash(y) then hash(x) == hash(y). */
5328 h = PyLong_AsSsize_t(res);
5329 if (h == -1 && PyErr_Occurred()) {
5330 /* res was not within the range of a Py_hash_t, so we're free to
Mark Dickinsondc787d22010-05-23 13:33:13 +00005331 use any sufficiently bit-mixing transformation;
5332 long.__hash__ will do nicely. */
Benjamin Peterson8f67d082010-10-17 20:54:53 +00005333 PyErr_Clear();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005334 h = PyLong_Type.tp_hash(res);
Benjamin Peterson8f67d082010-10-17 20:54:53 +00005335 }
Benjamin Petersone7dfeeb2010-10-17 21:27:01 +00005336 /* -1 is reserved for errors. */
5337 if (h == -1)
5338 h = -2;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005339 Py_DECREF(res);
Mark Dickinsondc787d22010-05-23 13:33:13 +00005340 return h;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005341}
5342
5343static PyObject *
5344slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds)
5345{
Benjamin Petersonce798522012-01-22 11:24:29 -05005346 _Py_IDENTIFIER(__call__);
5347 PyObject *meth = lookup_method(self, &PyId___call__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005348 PyObject *res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005349
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005350 if (meth == NULL)
5351 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005352
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005353 res = PyObject_Call(meth, args, kwds);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005354
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005355 Py_DECREF(meth);
5356 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005357}
5358
Guido van Rossum14a6f832001-10-17 13:59:09 +00005359/* There are two slot dispatch functions for tp_getattro.
5360
5361 - slot_tp_getattro() is used when __getattribute__ is overridden
5362 but no __getattr__ hook is present;
5363
5364 - slot_tp_getattr_hook() is used when a __getattr__ hook is present.
5365
Guido van Rossumc334df52002-04-04 23:44:47 +00005366 The code in update_one_slot() always installs slot_tp_getattr_hook(); this
5367 detects the absence of __getattr__ and then installs the simpler slot if
5368 necessary. */
Guido van Rossum14a6f832001-10-17 13:59:09 +00005369
Tim Peters6d6c1a32001-08-02 04:15:00 +00005370static PyObject *
5371slot_tp_getattro(PyObject *self, PyObject *name)
5372{
Benjamin Petersonce798522012-01-22 11:24:29 -05005373 return call_method(self, &PyId___getattribute__, "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005374}
5375
Guido van Rossum19c1cd52001-09-21 21:24:49 +00005376static PyObject *
Benjamin Peterson9262b842008-11-17 22:45:50 +00005377call_attribute(PyObject *self, PyObject *attr, PyObject *name)
5378{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005379 PyObject *res, *descr = NULL;
5380 descrgetfunc f = Py_TYPE(attr)->tp_descr_get;
Benjamin Peterson9262b842008-11-17 22:45:50 +00005381
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005382 if (f != NULL) {
5383 descr = f(attr, self, (PyObject *)(Py_TYPE(self)));
5384 if (descr == NULL)
5385 return NULL;
5386 else
5387 attr = descr;
5388 }
5389 res = PyObject_CallFunctionObjArgs(attr, name, NULL);
5390 Py_XDECREF(descr);
5391 return res;
Benjamin Peterson9262b842008-11-17 22:45:50 +00005392}
5393
5394static PyObject *
Guido van Rossum19c1cd52001-09-21 21:24:49 +00005395slot_tp_getattr_hook(PyObject *self, PyObject *name)
5396{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005397 PyTypeObject *tp = Py_TYPE(self);
5398 PyObject *getattr, *getattribute, *res;
Victor Stinner3c1e4812012-03-26 22:10:51 +02005399 _Py_IDENTIFIER(__getattr__);
Guido van Rossum19c1cd52001-09-21 21:24:49 +00005400
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005401 /* speed hack: we could use lookup_maybe, but that would resolve the
5402 method fully for each attribute lookup for classes with
5403 __getattr__, even when the attribute is present. So we use
5404 _PyType_Lookup and create the method only when needed, with
5405 call_attribute. */
Victor Stinner3c1e4812012-03-26 22:10:51 +02005406 getattr = _PyType_LookupId(tp, &PyId___getattr__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005407 if (getattr == NULL) {
5408 /* No __getattr__ hook: use a simpler dispatcher */
5409 tp->tp_getattro = slot_tp_getattro;
5410 return slot_tp_getattro(self, name);
5411 }
5412 Py_INCREF(getattr);
5413 /* speed hack: we could use lookup_maybe, but that would resolve the
5414 method fully for each attribute lookup for classes with
5415 __getattr__, even when self has the default __getattribute__
5416 method. So we use _PyType_Lookup and create the method only when
5417 needed, with call_attribute. */
Victor Stinner3c1e4812012-03-26 22:10:51 +02005418 getattribute = _PyType_LookupId(tp, &PyId___getattribute__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005419 if (getattribute == NULL ||
5420 (Py_TYPE(getattribute) == &PyWrapperDescr_Type &&
5421 ((PyWrapperDescrObject *)getattribute)->d_wrapped ==
5422 (void *)PyObject_GenericGetAttr))
5423 res = PyObject_GenericGetAttr(self, name);
5424 else {
5425 Py_INCREF(getattribute);
5426 res = call_attribute(self, getattribute, name);
5427 Py_DECREF(getattribute);
5428 }
5429 if (res == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) {
5430 PyErr_Clear();
5431 res = call_attribute(self, getattr, name);
5432 }
5433 Py_DECREF(getattr);
5434 return res;
Guido van Rossum19c1cd52001-09-21 21:24:49 +00005435}
5436
Tim Peters6d6c1a32001-08-02 04:15:00 +00005437static int
5438slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value)
5439{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005440 PyObject *res;
Benjamin Petersonce798522012-01-22 11:24:29 -05005441 _Py_IDENTIFIER(__delattr__);
5442 _Py_IDENTIFIER(__setattr__);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005443
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005444 if (value == NULL)
Benjamin Petersonce798522012-01-22 11:24:29 -05005445 res = call_method(self, &PyId___delattr__, "(O)", name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005446 else
Benjamin Petersonce798522012-01-22 11:24:29 -05005447 res = call_method(self, &PyId___setattr__, "(OO)", name, value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005448 if (res == NULL)
5449 return -1;
5450 Py_DECREF(res);
5451 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005452}
5453
Benjamin Petersonce798522012-01-22 11:24:29 -05005454static _Py_Identifier name_op[] = {
5455 {0, "__lt__", 0},
5456 {0, "__le__", 0},
5457 {0, "__eq__", 0},
5458 {0, "__ne__", 0},
5459 {0, "__gt__", 0},
5460 {0, "__ge__", 0}
Guido van Rossumf5243f02008-01-01 04:06:48 +00005461};
5462
Tim Peters6d6c1a32001-08-02 04:15:00 +00005463static PyObject *
Mark Dickinson6f1d0492009-11-15 13:58:49 +00005464slot_tp_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005465{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005466 PyObject *func, *args, *res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005467
Benjamin Petersonce798522012-01-22 11:24:29 -05005468 func = lookup_method(self, &name_op[op]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005469 if (func == NULL) {
5470 PyErr_Clear();
Brian Curtindfc80e32011-08-10 20:28:54 -05005471 Py_RETURN_NOTIMPLEMENTED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005472 }
5473 args = PyTuple_Pack(1, other);
5474 if (args == NULL)
5475 res = NULL;
5476 else {
5477 res = PyObject_Call(func, args, NULL);
5478 Py_DECREF(args);
5479 }
5480 Py_DECREF(func);
5481 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005482}
5483
Guido van Rossumb8f63662001-08-15 23:57:02 +00005484static PyObject *
Guido van Rossumb8f63662001-08-15 23:57:02 +00005485slot_tp_iter(PyObject *self)
5486{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005487 PyObject *func, *res;
Benjamin Petersonce798522012-01-22 11:24:29 -05005488 _Py_IDENTIFIER(__iter__);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005489
Benjamin Petersonce798522012-01-22 11:24:29 -05005490 func = lookup_method(self, &PyId___iter__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005491 if (func != NULL) {
5492 PyObject *args;
5493 args = res = PyTuple_New(0);
5494 if (args != NULL) {
5495 res = PyObject_Call(func, args, NULL);
5496 Py_DECREF(args);
5497 }
5498 Py_DECREF(func);
5499 return res;
5500 }
5501 PyErr_Clear();
Benjamin Petersonce798522012-01-22 11:24:29 -05005502 func = lookup_method(self, &PyId___getitem__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005503 if (func == NULL) {
5504 PyErr_Format(PyExc_TypeError,
5505 "'%.200s' object is not iterable",
5506 Py_TYPE(self)->tp_name);
5507 return NULL;
5508 }
5509 Py_DECREF(func);
5510 return PySeqIter_New(self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005511}
Tim Peters6d6c1a32001-08-02 04:15:00 +00005512
5513static PyObject *
5514slot_tp_iternext(PyObject *self)
5515{
Benjamin Petersonce798522012-01-22 11:24:29 -05005516 _Py_IDENTIFIER(__next__);
5517 return call_method(self, &PyId___next__, "()");
Tim Peters6d6c1a32001-08-02 04:15:00 +00005518}
5519
Guido van Rossum1a493502001-08-17 16:47:50 +00005520static PyObject *
5521slot_tp_descr_get(PyObject *self, PyObject *obj, PyObject *type)
5522{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005523 PyTypeObject *tp = Py_TYPE(self);
5524 PyObject *get;
Victor Stinner3c1e4812012-03-26 22:10:51 +02005525 _Py_IDENTIFIER(__get__);
Guido van Rossum1a493502001-08-17 16:47:50 +00005526
Victor Stinner3c1e4812012-03-26 22:10:51 +02005527 get = _PyType_LookupId(tp, &PyId___get__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005528 if (get == NULL) {
5529 /* Avoid further slowdowns */
5530 if (tp->tp_descr_get == slot_tp_descr_get)
5531 tp->tp_descr_get = NULL;
5532 Py_INCREF(self);
5533 return self;
5534 }
5535 if (obj == NULL)
5536 obj = Py_None;
5537 if (type == NULL)
5538 type = Py_None;
5539 return PyObject_CallFunctionObjArgs(get, self, obj, type, NULL);
Guido van Rossum1a493502001-08-17 16:47:50 +00005540}
Tim Peters6d6c1a32001-08-02 04:15:00 +00005541
5542static int
5543slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value)
5544{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005545 PyObject *res;
Benjamin Petersonce798522012-01-22 11:24:29 -05005546 _Py_IDENTIFIER(__delete__);
5547 _Py_IDENTIFIER(__set__);
Guido van Rossum2c252392001-08-24 10:13:31 +00005548
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005549 if (value == NULL)
Benjamin Petersonce798522012-01-22 11:24:29 -05005550 res = call_method(self, &PyId___delete__, "(O)", target);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005551 else
Benjamin Petersonce798522012-01-22 11:24:29 -05005552 res = call_method(self, &PyId___set__, "(OO)", target, value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005553 if (res == NULL)
5554 return -1;
5555 Py_DECREF(res);
5556 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005557}
5558
5559static int
5560slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds)
5561{
Benjamin Petersonce798522012-01-22 11:24:29 -05005562 _Py_IDENTIFIER(__init__);
5563 PyObject *meth = lookup_method(self, &PyId___init__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005564 PyObject *res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005565
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005566 if (meth == NULL)
5567 return -1;
5568 res = PyObject_Call(meth, args, kwds);
5569 Py_DECREF(meth);
5570 if (res == NULL)
5571 return -1;
5572 if (res != Py_None) {
5573 PyErr_Format(PyExc_TypeError,
5574 "__init__() should return None, not '%.200s'",
5575 Py_TYPE(res)->tp_name);
5576 Py_DECREF(res);
5577 return -1;
5578 }
5579 Py_DECREF(res);
5580 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005581}
5582
5583static PyObject *
5584slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
5585{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005586 PyObject *func;
5587 PyObject *newargs, *x;
5588 Py_ssize_t i, n;
Victor Stinner3c1e4812012-03-26 22:10:51 +02005589 _Py_IDENTIFIER(__new__);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005590
Victor Stinner3c1e4812012-03-26 22:10:51 +02005591 func = _PyObject_GetAttrId((PyObject *)type, &PyId___new__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005592 if (func == NULL)
5593 return NULL;
5594 assert(PyTuple_Check(args));
5595 n = PyTuple_GET_SIZE(args);
5596 newargs = PyTuple_New(n+1);
5597 if (newargs == NULL)
5598 return NULL;
5599 Py_INCREF(type);
5600 PyTuple_SET_ITEM(newargs, 0, (PyObject *)type);
5601 for (i = 0; i < n; i++) {
5602 x = PyTuple_GET_ITEM(args, i);
5603 Py_INCREF(x);
5604 PyTuple_SET_ITEM(newargs, i+1, x);
5605 }
5606 x = PyObject_Call(func, newargs, kwds);
5607 Py_DECREF(newargs);
5608 Py_DECREF(func);
5609 return x;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005610}
5611
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005612static void
5613slot_tp_del(PyObject *self)
5614{
Benjamin Petersonce798522012-01-22 11:24:29 -05005615 _Py_IDENTIFIER(__del__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005616 PyObject *del, *res;
5617 PyObject *error_type, *error_value, *error_traceback;
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005618
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005619 /* Temporarily resurrect the object. */
5620 assert(self->ob_refcnt == 0);
5621 self->ob_refcnt = 1;
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005622
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005623 /* Save the current exception, if any. */
5624 PyErr_Fetch(&error_type, &error_value, &error_traceback);
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005625
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005626 /* Execute __del__ method, if any. */
Benjamin Petersonce798522012-01-22 11:24:29 -05005627 del = lookup_maybe(self, &PyId___del__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005628 if (del != NULL) {
5629 res = PyEval_CallObject(del, NULL);
5630 if (res == NULL)
5631 PyErr_WriteUnraisable(del);
5632 else
5633 Py_DECREF(res);
5634 Py_DECREF(del);
5635 }
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005636
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005637 /* Restore the saved exception. */
5638 PyErr_Restore(error_type, error_value, error_traceback);
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005639
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005640 /* Undo the temporary resurrection; can't use DECREF here, it would
5641 * cause a recursive call.
5642 */
5643 assert(self->ob_refcnt > 0);
5644 if (--self->ob_refcnt == 0)
5645 return; /* this is the normal path out */
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005646
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005647 /* __del__ resurrected it! Make it look like the original Py_DECREF
5648 * never happened.
5649 */
5650 {
5651 Py_ssize_t refcnt = self->ob_refcnt;
5652 _Py_NewReference(self);
5653 self->ob_refcnt = refcnt;
5654 }
5655 assert(!PyType_IS_GC(Py_TYPE(self)) ||
5656 _Py_AS_GC(self)->gc.gc_refs != _PyGC_REFS_UNTRACKED);
5657 /* If Py_REF_DEBUG, _Py_NewReference bumped _Py_RefTotal, so
5658 * we need to undo that. */
5659 _Py_DEC_REFTOTAL;
5660 /* If Py_TRACE_REFS, _Py_NewReference re-added self to the object
5661 * chain, so no more to do there.
5662 * If COUNT_ALLOCS, the original decref bumped tp_frees, and
5663 * _Py_NewReference bumped tp_allocs: both of those need to be
5664 * undone.
5665 */
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005666#ifdef COUNT_ALLOCS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005667 --Py_TYPE(self)->tp_frees;
5668 --Py_TYPE(self)->tp_allocs;
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005669#endif
5670}
5671
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005672
Benjamin Peterson63952412013-04-01 17:41:41 -04005673/*
5674Table mapping __foo__ names to tp_foo offsets and slot_tp_foo wrapper functions.
5675
5676The table is ordered by offsets relative to the 'PyHeapTypeObject' structure,
5677which incorporates the additional structures used for numbers, sequences and
5678mappings. Note that multiple names may map to the same slot (e.g. __eq__,
5679__ne__ etc. all map to tp_richcompare) and one name may map to multiple slots
5680(e.g. __str__ affects tp_str as well as tp_repr). The table is terminated with
5681an all-zero entry. (This table is further initialized in init_slotdefs().)
5682*/
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005683
Guido van Rossum6d204072001-10-21 00:44:31 +00005684typedef struct wrapperbase slotdef;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005685
5686#undef TPSLOT
Guido van Rossumc8e56452001-10-22 00:43:43 +00005687#undef FLSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005688#undef ETSLOT
5689#undef SQSLOT
5690#undef MPSLOT
5691#undef NBSLOT
Guido van Rossum6d204072001-10-21 00:44:31 +00005692#undef UNSLOT
5693#undef IBSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005694#undef BINSLOT
5695#undef RBINSLOT
5696
Guido van Rossum6d204072001-10-21 00:44:31 +00005697#define TPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005698 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
5699 PyDoc_STR(DOC)}
Guido van Rossumc8e56452001-10-22 00:43:43 +00005700#define FLSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC, FLAGS) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005701 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
5702 PyDoc_STR(DOC), FLAGS}
Guido van Rossum6d204072001-10-21 00:44:31 +00005703#define ETSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005704 {NAME, offsetof(PyHeapTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
5705 PyDoc_STR(DOC)}
Guido van Rossum6d204072001-10-21 00:44:31 +00005706#define SQSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005707 ETSLOT(NAME, as_sequence.SLOT, FUNCTION, WRAPPER, DOC)
Guido van Rossum6d204072001-10-21 00:44:31 +00005708#define MPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005709 ETSLOT(NAME, as_mapping.SLOT, FUNCTION, WRAPPER, DOC)
Guido van Rossum6d204072001-10-21 00:44:31 +00005710#define NBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005711 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, DOC)
Guido van Rossum6d204072001-10-21 00:44:31 +00005712#define UNSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005713 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
5714 "x." NAME "() <==> " DOC)
Guido van Rossum6d204072001-10-21 00:44:31 +00005715#define IBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005716 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
5717 "x." NAME "(y) <==> x" DOC "y")
Guido van Rossum6d204072001-10-21 00:44:31 +00005718#define BINSLOT(NAME, SLOT, FUNCTION, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005719 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
5720 "x." NAME "(y) <==> x" DOC "y")
Guido van Rossum6d204072001-10-21 00:44:31 +00005721#define RBINSLOT(NAME, SLOT, FUNCTION, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005722 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
5723 "x." NAME "(y) <==> y" DOC "x")
Anthony Baxter56616992005-06-03 14:12:21 +00005724#define BINSLOTNOTINFIX(NAME, SLOT, FUNCTION, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005725 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
5726 "x." NAME "(y) <==> " DOC)
Anthony Baxter56616992005-06-03 14:12:21 +00005727#define RBINSLOTNOTINFIX(NAME, SLOT, FUNCTION, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005728 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
5729 "x." NAME "(y) <==> " DOC)
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005730
5731static slotdef slotdefs[] = {
Benjamin Peterson63952412013-04-01 17:41:41 -04005732 TPSLOT("__getattribute__", tp_getattr, NULL, NULL, ""),
5733 TPSLOT("__getattr__", tp_getattr, NULL, NULL, ""),
5734 TPSLOT("__setattr__", tp_setattr, NULL, NULL, ""),
5735 TPSLOT("__delattr__", tp_setattr, NULL, NULL, ""),
5736 TPSLOT("__repr__", tp_repr, slot_tp_repr, wrap_unaryfunc,
5737 "x.__repr__() <==> repr(x)"),
5738 TPSLOT("__hash__", tp_hash, slot_tp_hash, wrap_hashfunc,
5739 "x.__hash__() <==> hash(x)"),
5740 FLSLOT("__call__", tp_call, slot_tp_call, (wrapperfunc)wrap_call,
5741 "x.__call__(...) <==> x(...)", PyWrapperFlag_KEYWORDS),
5742 TPSLOT("__str__", tp_str, slot_tp_str, wrap_unaryfunc,
5743 "x.__str__() <==> str(x)"),
5744 TPSLOT("__getattribute__", tp_getattro, slot_tp_getattr_hook,
5745 wrap_binaryfunc, "x.__getattribute__('name') <==> x.name"),
5746 TPSLOT("__getattr__", tp_getattro, slot_tp_getattr_hook, NULL, ""),
5747 TPSLOT("__setattr__", tp_setattro, slot_tp_setattro, wrap_setattr,
5748 "x.__setattr__('name', value) <==> x.name = value"),
5749 TPSLOT("__delattr__", tp_setattro, slot_tp_setattro, wrap_delattr,
5750 "x.__delattr__('name') <==> del x.name"),
5751 TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare, richcmp_lt,
5752 "x.__lt__(y) <==> x<y"),
5753 TPSLOT("__le__", tp_richcompare, slot_tp_richcompare, richcmp_le,
5754 "x.__le__(y) <==> x<=y"),
5755 TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare, richcmp_eq,
5756 "x.__eq__(y) <==> x==y"),
5757 TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare, richcmp_ne,
5758 "x.__ne__(y) <==> x!=y"),
5759 TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare, richcmp_gt,
5760 "x.__gt__(y) <==> x>y"),
5761 TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare, richcmp_ge,
5762 "x.__ge__(y) <==> x>=y"),
5763 TPSLOT("__iter__", tp_iter, slot_tp_iter, wrap_unaryfunc,
5764 "x.__iter__() <==> iter(x)"),
5765 TPSLOT("__next__", tp_iternext, slot_tp_iternext, wrap_next,
5766 "x.__next__() <==> next(x)"),
5767 TPSLOT("__get__", tp_descr_get, slot_tp_descr_get, wrap_descr_get,
5768 "descr.__get__(obj[, type]) -> value"),
5769 TPSLOT("__set__", tp_descr_set, slot_tp_descr_set, wrap_descr_set,
5770 "descr.__set__(obj, value)"),
5771 TPSLOT("__delete__", tp_descr_set, slot_tp_descr_set,
5772 wrap_descr_delete, "descr.__delete__(obj)"),
5773 FLSLOT("__init__", tp_init, slot_tp_init, (wrapperfunc)wrap_init,
5774 "x.__init__(...) initializes x; "
5775 "see help(type(x)) for signature",
5776 PyWrapperFlag_KEYWORDS),
5777 TPSLOT("__new__", tp_new, slot_tp_new, NULL, ""),
5778 TPSLOT("__del__", tp_del, slot_tp_del, NULL, ""),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005779
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005780 BINSLOT("__add__", nb_add, slot_nb_add,
5781 "+"),
5782 RBINSLOT("__radd__", nb_add, slot_nb_add,
5783 "+"),
5784 BINSLOT("__sub__", nb_subtract, slot_nb_subtract,
5785 "-"),
5786 RBINSLOT("__rsub__", nb_subtract, slot_nb_subtract,
5787 "-"),
5788 BINSLOT("__mul__", nb_multiply, slot_nb_multiply,
5789 "*"),
5790 RBINSLOT("__rmul__", nb_multiply, slot_nb_multiply,
5791 "*"),
5792 BINSLOT("__mod__", nb_remainder, slot_nb_remainder,
5793 "%"),
5794 RBINSLOT("__rmod__", nb_remainder, slot_nb_remainder,
5795 "%"),
5796 BINSLOTNOTINFIX("__divmod__", nb_divmod, slot_nb_divmod,
5797 "divmod(x, y)"),
5798 RBINSLOTNOTINFIX("__rdivmod__", nb_divmod, slot_nb_divmod,
5799 "divmod(y, x)"),
5800 NBSLOT("__pow__", nb_power, slot_nb_power, wrap_ternaryfunc,
5801 "x.__pow__(y[, z]) <==> pow(x, y[, z])"),
5802 NBSLOT("__rpow__", nb_power, slot_nb_power, wrap_ternaryfunc_r,
5803 "y.__rpow__(x[, z]) <==> pow(x, y[, z])"),
5804 UNSLOT("__neg__", nb_negative, slot_nb_negative, wrap_unaryfunc, "-x"),
5805 UNSLOT("__pos__", nb_positive, slot_nb_positive, wrap_unaryfunc, "+x"),
5806 UNSLOT("__abs__", nb_absolute, slot_nb_absolute, wrap_unaryfunc,
5807 "abs(x)"),
5808 UNSLOT("__bool__", nb_bool, slot_nb_bool, wrap_inquirypred,
5809 "x != 0"),
5810 UNSLOT("__invert__", nb_invert, slot_nb_invert, wrap_unaryfunc, "~x"),
5811 BINSLOT("__lshift__", nb_lshift, slot_nb_lshift, "<<"),
5812 RBINSLOT("__rlshift__", nb_lshift, slot_nb_lshift, "<<"),
5813 BINSLOT("__rshift__", nb_rshift, slot_nb_rshift, ">>"),
5814 RBINSLOT("__rrshift__", nb_rshift, slot_nb_rshift, ">>"),
5815 BINSLOT("__and__", nb_and, slot_nb_and, "&"),
5816 RBINSLOT("__rand__", nb_and, slot_nb_and, "&"),
5817 BINSLOT("__xor__", nb_xor, slot_nb_xor, "^"),
5818 RBINSLOT("__rxor__", nb_xor, slot_nb_xor, "^"),
5819 BINSLOT("__or__", nb_or, slot_nb_or, "|"),
5820 RBINSLOT("__ror__", nb_or, slot_nb_or, "|"),
5821 UNSLOT("__int__", nb_int, slot_nb_int, wrap_unaryfunc,
5822 "int(x)"),
5823 UNSLOT("__float__", nb_float, slot_nb_float, wrap_unaryfunc,
5824 "float(x)"),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005825 IBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add,
Eli Benderskyd3baae72011-11-11 16:57:05 +02005826 wrap_binaryfunc, "+="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005827 IBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract,
Eli Benderskyd3baae72011-11-11 16:57:05 +02005828 wrap_binaryfunc, "-="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005829 IBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply,
Eli Benderskyd3baae72011-11-11 16:57:05 +02005830 wrap_binaryfunc, "*="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005831 IBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder,
Eli Benderskyd3baae72011-11-11 16:57:05 +02005832 wrap_binaryfunc, "%="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005833 IBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power,
Eli Benderskyd3baae72011-11-11 16:57:05 +02005834 wrap_binaryfunc, "**="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005835 IBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift,
Eli Benderskyd3baae72011-11-11 16:57:05 +02005836 wrap_binaryfunc, "<<="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005837 IBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift,
Eli Benderskyd3baae72011-11-11 16:57:05 +02005838 wrap_binaryfunc, ">>="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005839 IBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and,
Eli Benderskyd3baae72011-11-11 16:57:05 +02005840 wrap_binaryfunc, "&="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005841 IBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor,
Eli Benderskyd3baae72011-11-11 16:57:05 +02005842 wrap_binaryfunc, "^="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005843 IBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or,
Eli Benderskyd3baae72011-11-11 16:57:05 +02005844 wrap_binaryfunc, "|="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005845 BINSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
5846 RBINSLOT("__rfloordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
5847 BINSLOT("__truediv__", nb_true_divide, slot_nb_true_divide, "/"),
5848 RBINSLOT("__rtruediv__", nb_true_divide, slot_nb_true_divide, "/"),
5849 IBSLOT("__ifloordiv__", nb_inplace_floor_divide,
5850 slot_nb_inplace_floor_divide, wrap_binaryfunc, "//"),
5851 IBSLOT("__itruediv__", nb_inplace_true_divide,
5852 slot_nb_inplace_true_divide, wrap_binaryfunc, "/"),
Benjamin Peterson63952412013-04-01 17:41:41 -04005853 NBSLOT("__index__", nb_index, slot_nb_index, wrap_unaryfunc,
5854 "x[y:z] <==> x[y.__index__():z.__index__()]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005855
Benjamin Peterson63952412013-04-01 17:41:41 -04005856 MPSLOT("__len__", mp_length, slot_mp_length, wrap_lenfunc,
5857 "x.__len__() <==> len(x)"),
5858 MPSLOT("__getitem__", mp_subscript, slot_mp_subscript,
5859 wrap_binaryfunc,
5860 "x.__getitem__(y) <==> x[y]"),
5861 MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript,
5862 wrap_objobjargproc,
5863 "x.__setitem__(i, y) <==> x[i]=y"),
5864 MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript,
5865 wrap_delitem,
5866 "x.__delitem__(y) <==> del x[y]"),
5867
5868 SQSLOT("__len__", sq_length, slot_sq_length, wrap_lenfunc,
5869 "x.__len__() <==> len(x)"),
5870 /* Heap types defining __add__/__mul__ have sq_concat/sq_repeat == NULL.
5871 The logic in abstract.c always falls back to nb_add/nb_multiply in
5872 this case. Defining both the nb_* and the sq_* slots to call the
5873 user-defined methods has unexpected side-effects, as shown by
5874 test_descr.notimplemented() */
5875 SQSLOT("__add__", sq_concat, NULL, wrap_binaryfunc,
5876 "x.__add__(y) <==> x+y"),
5877 SQSLOT("__mul__", sq_repeat, NULL, wrap_indexargfunc,
5878 "x.__mul__(n) <==> x*n"),
5879 SQSLOT("__rmul__", sq_repeat, NULL, wrap_indexargfunc,
5880 "x.__rmul__(n) <==> n*x"),
5881 SQSLOT("__getitem__", sq_item, slot_sq_item, wrap_sq_item,
5882 "x.__getitem__(y) <==> x[y]"),
5883 SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_setitem,
5884 "x.__setitem__(i, y) <==> x[i]=y"),
5885 SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_delitem,
5886 "x.__delitem__(y) <==> del x[y]"),
5887 SQSLOT("__contains__", sq_contains, slot_sq_contains, wrap_objobjproc,
5888 "x.__contains__(y) <==> y in x"),
5889 SQSLOT("__iadd__", sq_inplace_concat, NULL,
5890 wrap_binaryfunc, "x.__iadd__(y) <==> x+=y"),
5891 SQSLOT("__imul__", sq_inplace_repeat, NULL,
5892 wrap_indexargfunc, "x.__imul__(y) <==> x*=y"),
5893
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005894 {NULL}
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005895};
5896
Guido van Rossumc334df52002-04-04 23:44:47 +00005897/* Given a type pointer and an offset gotten from a slotdef entry, return a
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005898 pointer to the actual slot. This is not quite the same as simply adding
Guido van Rossumc334df52002-04-04 23:44:47 +00005899 the offset to the type pointer, since it takes care to indirect through the
5900 proper indirection pointer (as_buffer, etc.); it returns NULL if the
5901 indirection pointer is NULL. */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005902static void **
Martin v. Löwis18e16552006-02-15 17:27:45 +00005903slotptr(PyTypeObject *type, int ioffset)
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005904{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005905 char *ptr;
5906 long offset = ioffset;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005907
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005908 /* Note: this depends on the order of the members of PyHeapTypeObject! */
5909 assert(offset >= 0);
5910 assert((size_t)offset < offsetof(PyHeapTypeObject, as_buffer));
5911 if ((size_t)offset >= offsetof(PyHeapTypeObject, as_sequence)) {
5912 ptr = (char *)type->tp_as_sequence;
5913 offset -= offsetof(PyHeapTypeObject, as_sequence);
5914 }
5915 else if ((size_t)offset >= offsetof(PyHeapTypeObject, as_mapping)) {
5916 ptr = (char *)type->tp_as_mapping;
5917 offset -= offsetof(PyHeapTypeObject, as_mapping);
5918 }
5919 else if ((size_t)offset >= offsetof(PyHeapTypeObject, as_number)) {
5920 ptr = (char *)type->tp_as_number;
5921 offset -= offsetof(PyHeapTypeObject, as_number);
5922 }
5923 else {
5924 ptr = (char *)type;
5925 }
5926 if (ptr != NULL)
5927 ptr += offset;
5928 return (void **)ptr;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005929}
Guido van Rossumf040ede2001-08-07 16:40:56 +00005930
Guido van Rossumc334df52002-04-04 23:44:47 +00005931/* Length of array of slotdef pointers used to store slots with the
5932 same __name__. There should be at most MAX_EQUIV-1 slotdef entries with
5933 the same __name__, for any __name__. Since that's a static property, it is
5934 appropriate to declare fixed-size arrays for this. */
5935#define MAX_EQUIV 10
5936
5937/* Return a slot pointer for a given name, but ONLY if the attribute has
5938 exactly one slot function. The name must be an interned string. */
5939static void **
5940resolve_slotdups(PyTypeObject *type, PyObject *name)
5941{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005942 /* XXX Maybe this could be optimized more -- but is it worth it? */
Guido van Rossumc334df52002-04-04 23:44:47 +00005943
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005944 /* pname and ptrs act as a little cache */
5945 static PyObject *pname;
5946 static slotdef *ptrs[MAX_EQUIV];
5947 slotdef *p, **pp;
5948 void **res, **ptr;
Guido van Rossumc334df52002-04-04 23:44:47 +00005949
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005950 if (pname != name) {
5951 /* Collect all slotdefs that match name into ptrs. */
5952 pname = name;
5953 pp = ptrs;
5954 for (p = slotdefs; p->name_strobj; p++) {
5955 if (p->name_strobj == name)
5956 *pp++ = p;
5957 }
5958 *pp = NULL;
5959 }
Guido van Rossumc334df52002-04-04 23:44:47 +00005960
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005961 /* Look in all matching slots of the type; if exactly one of these has
5962 a filled-in slot, return its value. Otherwise return NULL. */
5963 res = NULL;
5964 for (pp = ptrs; *pp; pp++) {
5965 ptr = slotptr(type, (*pp)->offset);
5966 if (ptr == NULL || *ptr == NULL)
5967 continue;
5968 if (res != NULL)
5969 return NULL;
5970 res = ptr;
5971 }
5972 return res;
Guido van Rossumc334df52002-04-04 23:44:47 +00005973}
5974
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005975/* Common code for update_slots_callback() and fixup_slot_dispatchers(). This
Guido van Rossumc334df52002-04-04 23:44:47 +00005976 does some incredibly complex thinking and then sticks something into the
5977 slot. (It sees if the adjacent slotdefs for the same slot have conflicting
5978 interests, and then stores a generic wrapper or a specific function into
5979 the slot.) Return a pointer to the next slotdef with a different offset,
5980 because that's convenient for fixup_slot_dispatchers(). */
5981static slotdef *
5982update_one_slot(PyTypeObject *type, slotdef *p)
5983{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005984 PyObject *descr;
5985 PyWrapperDescrObject *d;
5986 void *generic = NULL, *specific = NULL;
5987 int use_generic = 0;
5988 int offset = p->offset;
5989 void **ptr = slotptr(type, offset);
Guido van Rossumc334df52002-04-04 23:44:47 +00005990
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005991 if (ptr == NULL) {
5992 do {
5993 ++p;
5994 } while (p->offset == offset);
5995 return p;
5996 }
5997 do {
5998 descr = _PyType_Lookup(type, p->name_strobj);
5999 if (descr == NULL) {
6000 if (ptr == (void**)&type->tp_iternext) {
Trent Nelsonab02db22012-09-18 21:58:03 -04006001 specific = (void *)_PyObject_NextNotImplemented;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006002 }
6003 continue;
6004 }
Benjamin Peterson7b166872012-04-24 11:06:25 -04006005 if (Py_TYPE(descr) == &PyWrapperDescr_Type &&
6006 ((PyWrapperDescrObject *)descr)->d_base->name_strobj == p->name_strobj) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006007 void **tptr = resolve_slotdups(type, p->name_strobj);
6008 if (tptr == NULL || tptr == ptr)
6009 generic = p->function;
6010 d = (PyWrapperDescrObject *)descr;
6011 if (d->d_base->wrapper == p->wrapper &&
6012 PyType_IsSubtype(type, PyDescr_TYPE(d)))
6013 {
6014 if (specific == NULL ||
6015 specific == d->d_wrapped)
6016 specific = d->d_wrapped;
6017 else
6018 use_generic = 1;
6019 }
6020 }
6021 else if (Py_TYPE(descr) == &PyCFunction_Type &&
6022 PyCFunction_GET_FUNCTION(descr) ==
6023 (PyCFunction)tp_new_wrapper &&
6024 ptr == (void**)&type->tp_new)
6025 {
6026 /* The __new__ wrapper is not a wrapper descriptor,
6027 so must be special-cased differently.
6028 If we don't do this, creating an instance will
6029 always use slot_tp_new which will look up
6030 __new__ in the MRO which will call tp_new_wrapper
6031 which will look through the base classes looking
6032 for a static base and call its tp_new (usually
6033 PyType_GenericNew), after performing various
6034 sanity checks and constructing a new argument
6035 list. Cut all that nonsense short -- this speeds
6036 up instance creation tremendously. */
6037 specific = (void *)type->tp_new;
6038 /* XXX I'm not 100% sure that there isn't a hole
6039 in this reasoning that requires additional
6040 sanity checks. I'll buy the first person to
6041 point out a bug in this reasoning a beer. */
6042 }
6043 else if (descr == Py_None &&
6044 ptr == (void**)&type->tp_hash) {
6045 /* We specifically allow __hash__ to be set to None
6046 to prevent inheritance of the default
6047 implementation from object.__hash__ */
Trent Nelsonab02db22012-09-18 21:58:03 -04006048 specific = (void *)PyObject_HashNotImplemented;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006049 }
6050 else {
6051 use_generic = 1;
6052 generic = p->function;
6053 }
6054 } while ((++p)->offset == offset);
6055 if (specific && !use_generic)
6056 *ptr = specific;
6057 else
6058 *ptr = generic;
6059 return p;
Guido van Rossumc334df52002-04-04 23:44:47 +00006060}
6061
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006062/* In the type, update the slots whose slotdefs are gathered in the pp array.
6063 This is a callback for update_subclasses(). */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006064static int
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006065update_slots_callback(PyTypeObject *type, void *data)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006066{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006067 slotdef **pp = (slotdef **)data;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006068
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006069 for (; *pp; pp++)
6070 update_one_slot(type, *pp);
6071 return 0;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006072}
6073
Guido van Rossumc334df52002-04-04 23:44:47 +00006074/* Initialize the slotdefs table by adding interned string objects for the
6075 names and sorting the entries. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006076static void
Guido van Rossumd396b9c2001-10-13 20:02:41 +00006077init_slotdefs(void)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006078{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006079 slotdef *p;
6080 static int initialized = 0;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006081
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006082 if (initialized)
6083 return;
6084 for (p = slotdefs; p->name; p++) {
Benjamin Peterson63952412013-04-01 17:41:41 -04006085 /* Slots must be ordered by their offset in the PyHeapTypeObject. */
6086 assert(!p[1].name || p->offset <= p[1].offset);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006087 p->name_strobj = PyUnicode_InternFromString(p->name);
6088 if (!p->name_strobj)
6089 Py_FatalError("Out of memory interning slotdef names");
6090 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006091 initialized = 1;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006092}
6093
Guido van Rossumc334df52002-04-04 23:44:47 +00006094/* Update the slots after assignment to a class (type) attribute. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006095static int
6096update_slot(PyTypeObject *type, PyObject *name)
6097{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006098 slotdef *ptrs[MAX_EQUIV];
6099 slotdef *p;
6100 slotdef **pp;
6101 int offset;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006102
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006103 /* Clear the VALID_VERSION flag of 'type' and all its
6104 subclasses. This could possibly be unified with the
6105 update_subclasses() recursion below, but carefully:
6106 they each have their own conditions on which to stop
6107 recursing into subclasses. */
6108 PyType_Modified(type);
Christian Heimesa62da1d2008-01-12 19:39:10 +00006109
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006110 init_slotdefs();
6111 pp = ptrs;
6112 for (p = slotdefs; p->name; p++) {
6113 /* XXX assume name is interned! */
6114 if (p->name_strobj == name)
6115 *pp++ = p;
6116 }
6117 *pp = NULL;
6118 for (pp = ptrs; *pp; pp++) {
6119 p = *pp;
6120 offset = p->offset;
6121 while (p > slotdefs && (p-1)->offset == offset)
6122 --p;
6123 *pp = p;
6124 }
6125 if (ptrs[0] == NULL)
6126 return 0; /* Not an attribute that affects any slots */
6127 return update_subclasses(type, name,
6128 update_slots_callback, (void *)ptrs);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006129}
6130
Guido van Rossumc334df52002-04-04 23:44:47 +00006131/* Store the proper functions in the slot dispatches at class (type)
6132 definition time, based upon which operations the class overrides in its
6133 dict. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00006134static void
Guido van Rossum7b9144b2001-10-09 19:39:46 +00006135fixup_slot_dispatchers(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00006136{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006137 slotdef *p;
Tim Peters6d6c1a32001-08-02 04:15:00 +00006138
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006139 init_slotdefs();
6140 for (p = slotdefs; p->name; )
6141 p = update_one_slot(type, p);
Tim Peters6d6c1a32001-08-02 04:15:00 +00006142}
Guido van Rossum705f0f52001-08-24 16:47:00 +00006143
Michael W. Hudson98bbc492002-11-26 14:47:27 +00006144static void
6145update_all_slots(PyTypeObject* type)
6146{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006147 slotdef *p;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00006148
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006149 init_slotdefs();
6150 for (p = slotdefs; p->name; p++) {
6151 /* update_slot returns int but can't actually fail */
6152 update_slot(type, p->name_strobj);
6153 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +00006154}
6155
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006156/* recurse_down_subclasses() and update_subclasses() are mutually
6157 recursive functions to call a callback for all subclasses,
6158 but refraining from recursing into subclasses that define 'name'. */
6159
6160static int
6161update_subclasses(PyTypeObject *type, PyObject *name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006162 update_callback callback, void *data)
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006163{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006164 if (callback(type, data) < 0)
6165 return -1;
6166 return recurse_down_subclasses(type, name, callback, data);
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006167}
6168
6169static int
6170recurse_down_subclasses(PyTypeObject *type, PyObject *name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006171 update_callback callback, void *data)
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006172{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006173 PyTypeObject *subclass;
6174 PyObject *ref, *subclasses, *dict;
6175 Py_ssize_t i, n;
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006176
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006177 subclasses = type->tp_subclasses;
6178 if (subclasses == NULL)
6179 return 0;
6180 assert(PyList_Check(subclasses));
6181 n = PyList_GET_SIZE(subclasses);
6182 for (i = 0; i < n; i++) {
6183 ref = PyList_GET_ITEM(subclasses, i);
6184 assert(PyWeakref_CheckRef(ref));
6185 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
6186 assert(subclass != NULL);
6187 if ((PyObject *)subclass == Py_None)
6188 continue;
6189 assert(PyType_Check(subclass));
6190 /* Avoid recursing down into unaffected classes */
6191 dict = subclass->tp_dict;
6192 if (dict != NULL && PyDict_Check(dict) &&
6193 PyDict_GetItem(dict, name) != NULL)
6194 continue;
6195 if (update_subclasses(subclass, name, callback, data) < 0)
6196 return -1;
6197 }
6198 return 0;
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006199}
6200
Guido van Rossum6d204072001-10-21 00:44:31 +00006201/* This function is called by PyType_Ready() to populate the type's
6202 dictionary with method descriptors for function slots. For each
Guido van Rossum09638c12002-06-13 19:17:46 +00006203 function slot (like tp_repr) that's defined in the type, one or more
6204 corresponding descriptors are added in the type's tp_dict dictionary
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006205 under the appropriate name (like __repr__). Some function slots
Guido van Rossum09638c12002-06-13 19:17:46 +00006206 cause more than one descriptor to be added (for example, the nb_add
6207 slot adds both __add__ and __radd__ descriptors) and some function
6208 slots compete for the same descriptor (for example both sq_item and
6209 mp_subscript generate a __getitem__ descriptor).
6210
Ezio Melotti13925002011-03-16 11:05:33 +02006211 In the latter case, the first slotdef entry encountered wins. Since
Tim Petersbf9b2442003-03-23 05:35:36 +00006212 slotdef entries are sorted by the offset of the slot in the
Guido van Rossume5c691a2003-03-07 15:13:17 +00006213 PyHeapTypeObject, this gives us some control over disambiguating
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006214 between competing slots: the members of PyHeapTypeObject are listed
6215 from most general to least general, so the most general slot is
6216 preferred. In particular, because as_mapping comes before as_sequence,
6217 for a type that defines both mp_subscript and sq_item, mp_subscript
6218 wins.
Guido van Rossum09638c12002-06-13 19:17:46 +00006219
6220 This only adds new descriptors and doesn't overwrite entries in
6221 tp_dict that were previously defined. The descriptors contain a
6222 reference to the C function they must call, so that it's safe if they
6223 are copied into a subtype's __dict__ and the subtype has a different
6224 C function in its slot -- calling the method defined by the
6225 descriptor will call the C function that was used to create it,
6226 rather than the C function present in the slot when it is called.
6227 (This is important because a subtype may have a C function in the
6228 slot that calls the method from the dictionary, and we want to avoid
6229 infinite recursion here.) */
Guido van Rossum6d204072001-10-21 00:44:31 +00006230
6231static int
6232add_operators(PyTypeObject *type)
6233{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006234 PyObject *dict = type->tp_dict;
6235 slotdef *p;
6236 PyObject *descr;
6237 void **ptr;
Guido van Rossum6d204072001-10-21 00:44:31 +00006238
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006239 init_slotdefs();
6240 for (p = slotdefs; p->name; p++) {
6241 if (p->wrapper == NULL)
6242 continue;
6243 ptr = slotptr(type, p->offset);
6244 if (!ptr || !*ptr)
6245 continue;
6246 if (PyDict_GetItem(dict, p->name_strobj))
6247 continue;
Trent Nelsonab02db22012-09-18 21:58:03 -04006248 if (*ptr == (void *)PyObject_HashNotImplemented) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006249 /* Classes may prevent the inheritance of the tp_hash
6250 slot by storing PyObject_HashNotImplemented in it. Make it
6251 visible as a None value for the __hash__ attribute. */
6252 if (PyDict_SetItem(dict, p->name_strobj, Py_None) < 0)
6253 return -1;
6254 }
6255 else {
6256 descr = PyDescr_NewWrapper(type, p, *ptr);
6257 if (descr == NULL)
6258 return -1;
6259 if (PyDict_SetItem(dict, p->name_strobj, descr) < 0)
6260 return -1;
6261 Py_DECREF(descr);
6262 }
6263 }
6264 if (type->tp_new != NULL) {
6265 if (add_tp_new_wrapper(type) < 0)
6266 return -1;
6267 }
6268 return 0;
Guido van Rossum6d204072001-10-21 00:44:31 +00006269}
6270
Guido van Rossum705f0f52001-08-24 16:47:00 +00006271
6272/* Cooperative 'super' */
6273
6274typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006275 PyObject_HEAD
6276 PyTypeObject *type;
6277 PyObject *obj;
6278 PyTypeObject *obj_type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006279} superobject;
6280
Guido van Rossum6f799372001-09-20 20:46:19 +00006281static PyMemberDef super_members[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006282 {"__thisclass__", T_OBJECT, offsetof(superobject, type), READONLY,
6283 "the class invoking super()"},
6284 {"__self__", T_OBJECT, offsetof(superobject, obj), READONLY,
6285 "the instance invoking super(); may be None"},
6286 {"__self_class__", T_OBJECT, offsetof(superobject, obj_type), READONLY,
6287 "the type of the instance invoking super(); may be None"},
6288 {0}
Guido van Rossum41eb14d2001-08-30 23:13:11 +00006289};
6290
Guido van Rossum705f0f52001-08-24 16:47:00 +00006291static void
6292super_dealloc(PyObject *self)
6293{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006294 superobject *su = (superobject *)self;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006295
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006296 _PyObject_GC_UNTRACK(self);
6297 Py_XDECREF(su->obj);
6298 Py_XDECREF(su->type);
6299 Py_XDECREF(su->obj_type);
6300 Py_TYPE(self)->tp_free(self);
Guido van Rossum705f0f52001-08-24 16:47:00 +00006301}
6302
6303static PyObject *
Guido van Rossum41eb14d2001-08-30 23:13:11 +00006304super_repr(PyObject *self)
6305{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006306 superobject *su = (superobject *)self;
Guido van Rossum41eb14d2001-08-30 23:13:11 +00006307
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006308 if (su->obj_type)
6309 return PyUnicode_FromFormat(
6310 "<super: <class '%s'>, <%s object>>",
6311 su->type ? su->type->tp_name : "NULL",
6312 su->obj_type->tp_name);
6313 else
6314 return PyUnicode_FromFormat(
6315 "<super: <class '%s'>, NULL>",
6316 su->type ? su->type->tp_name : "NULL");
Guido van Rossum41eb14d2001-08-30 23:13:11 +00006317}
6318
6319static PyObject *
Guido van Rossum705f0f52001-08-24 16:47:00 +00006320super_getattro(PyObject *self, PyObject *name)
6321{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006322 superobject *su = (superobject *)self;
6323 int skip = su->obj_type == NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006324
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006325 if (!skip) {
6326 /* We want __class__ to return the class of the super object
6327 (i.e. super, or a subclass), not the class of su->obj. */
6328 skip = (PyUnicode_Check(name) &&
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006329 PyUnicode_GET_LENGTH(name) == 9 &&
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006330 PyUnicode_CompareWithASCIIString(name, "__class__") == 0);
6331 }
Guido van Rossum76ba09f2003-04-16 19:40:58 +00006332
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006333 if (!skip) {
6334 PyObject *mro, *res, *tmp, *dict;
6335 PyTypeObject *starttype;
6336 descrgetfunc f;
6337 Py_ssize_t i, n;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006338
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006339 starttype = su->obj_type;
6340 mro = starttype->tp_mro;
Guido van Rossum155db9a2002-04-02 17:53:47 +00006341
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006342 if (mro == NULL)
6343 n = 0;
6344 else {
6345 assert(PyTuple_Check(mro));
6346 n = PyTuple_GET_SIZE(mro);
6347 }
6348 for (i = 0; i < n; i++) {
6349 if ((PyObject *)(su->type) == PyTuple_GET_ITEM(mro, i))
6350 break;
6351 }
6352 i++;
6353 res = NULL;
Victor Stinnerd74782b2012-03-09 00:39:08 +01006354 /* keep a strong reference to mro because starttype->tp_mro can be
6355 replaced during PyDict_GetItem(dict, name) */
6356 Py_INCREF(mro);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006357 for (; i < n; i++) {
6358 tmp = PyTuple_GET_ITEM(mro, i);
6359 if (PyType_Check(tmp))
6360 dict = ((PyTypeObject *)tmp)->tp_dict;
6361 else
6362 continue;
6363 res = PyDict_GetItem(dict, name);
6364 if (res != NULL) {
6365 Py_INCREF(res);
6366 f = Py_TYPE(res)->tp_descr_get;
6367 if (f != NULL) {
6368 tmp = f(res,
6369 /* Only pass 'obj' param if
6370 this is instance-mode super
6371 (See SF ID #743627)
6372 */
6373 (su->obj == (PyObject *)
6374 su->obj_type
6375 ? (PyObject *)NULL
6376 : su->obj),
6377 (PyObject *)starttype);
6378 Py_DECREF(res);
6379 res = tmp;
6380 }
Victor Stinnerd74782b2012-03-09 00:39:08 +01006381 Py_DECREF(mro);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006382 return res;
6383 }
6384 }
Victor Stinnerd74782b2012-03-09 00:39:08 +01006385 Py_DECREF(mro);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006386 }
6387 return PyObject_GenericGetAttr(self, name);
Guido van Rossum705f0f52001-08-24 16:47:00 +00006388}
6389
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006390static PyTypeObject *
Guido van Rossum5b443c62001-12-03 15:38:28 +00006391supercheck(PyTypeObject *type, PyObject *obj)
6392{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006393 /* Check that a super() call makes sense. Return a type object.
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006394
Florent Xiclunaaa6c1d22011-12-12 18:54:29 +01006395 obj can be a class, or an instance of one:
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006396
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006397 - If it is a class, it must be a subclass of 'type'. This case is
6398 used for class methods; the return value is obj.
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006399
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006400 - If it is an instance, it must be an instance of 'type'. This is
6401 the normal case; the return value is obj.__class__.
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006402
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006403 But... when obj is an instance, we want to allow for the case where
6404 Py_TYPE(obj) is not a subclass of type, but obj.__class__ is!
6405 This will allow using super() with a proxy for obj.
6406 */
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006407
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006408 /* Check for first bullet above (special case) */
6409 if (PyType_Check(obj) && PyType_IsSubtype((PyTypeObject *)obj, type)) {
6410 Py_INCREF(obj);
6411 return (PyTypeObject *)obj;
6412 }
Guido van Rossum8e80a722003-02-18 19:22:22 +00006413
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006414 /* Normal case */
6415 if (PyType_IsSubtype(Py_TYPE(obj), type)) {
6416 Py_INCREF(Py_TYPE(obj));
6417 return Py_TYPE(obj);
6418 }
6419 else {
6420 /* Try the slow way */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006421 PyObject *class_attr;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006422
Martin v. Löwisbfc6d742011-10-13 20:03:57 +02006423 class_attr = _PyObject_GetAttrId(obj, &PyId___class__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006424 if (class_attr != NULL &&
6425 PyType_Check(class_attr) &&
6426 (PyTypeObject *)class_attr != Py_TYPE(obj))
6427 {
6428 int ok = PyType_IsSubtype(
6429 (PyTypeObject *)class_attr, type);
6430 if (ok)
6431 return (PyTypeObject *)class_attr;
6432 }
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006433
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006434 if (class_attr == NULL)
6435 PyErr_Clear();
6436 else
6437 Py_DECREF(class_attr);
6438 }
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006439
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006440 PyErr_SetString(PyExc_TypeError,
6441 "super(type, obj): "
6442 "obj must be an instance or subtype of type");
6443 return NULL;
Guido van Rossum5b443c62001-12-03 15:38:28 +00006444}
6445
Guido van Rossum705f0f52001-08-24 16:47:00 +00006446static PyObject *
6447super_descr_get(PyObject *self, PyObject *obj, PyObject *type)
6448{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006449 superobject *su = (superobject *)self;
6450 superobject *newobj;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006451
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006452 if (obj == NULL || obj == Py_None || su->obj != NULL) {
6453 /* Not binding to an object, or already bound */
6454 Py_INCREF(self);
6455 return self;
6456 }
6457 if (Py_TYPE(su) != &PySuper_Type)
6458 /* If su is an instance of a (strict) subclass of super,
6459 call its type */
6460 return PyObject_CallFunctionObjArgs((PyObject *)Py_TYPE(su),
6461 su->type, obj, NULL);
6462 else {
6463 /* Inline the common case */
6464 PyTypeObject *obj_type = supercheck(su->type, obj);
6465 if (obj_type == NULL)
6466 return NULL;
6467 newobj = (superobject *)PySuper_Type.tp_new(&PySuper_Type,
6468 NULL, NULL);
6469 if (newobj == NULL)
6470 return NULL;
6471 Py_INCREF(su->type);
6472 Py_INCREF(obj);
6473 newobj->type = su->type;
6474 newobj->obj = obj;
6475 newobj->obj_type = obj_type;
6476 return (PyObject *)newobj;
6477 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00006478}
6479
6480static int
6481super_init(PyObject *self, PyObject *args, PyObject *kwds)
6482{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006483 superobject *su = (superobject *)self;
6484 PyTypeObject *type = NULL;
6485 PyObject *obj = NULL;
6486 PyTypeObject *obj_type = NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006487
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006488 if (!_PyArg_NoKeywords("super", kwds))
6489 return -1;
6490 if (!PyArg_ParseTuple(args, "|O!O:super", &PyType_Type, &type, &obj))
6491 return -1;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00006492
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006493 if (type == NULL) {
6494 /* Call super(), without args -- fill in from __class__
6495 and first local variable on the stack. */
6496 PyFrameObject *f = PyThreadState_GET()->frame;
6497 PyCodeObject *co = f->f_code;
Victor Stinner0fcab4a2011-01-04 12:59:15 +00006498 Py_ssize_t i, n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006499 if (co == NULL) {
Benjamin Peterson6a42bd62012-09-01 23:04:38 -04006500 PyErr_SetString(PyExc_RuntimeError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006501 "super(): no code object");
6502 return -1;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00006503 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006504 if (co->co_argcount == 0) {
Benjamin Peterson6a42bd62012-09-01 23:04:38 -04006505 PyErr_SetString(PyExc_RuntimeError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006506 "super(): no arguments");
6507 return -1;
6508 }
6509 obj = f->f_localsplus[0];
6510 if (obj == NULL) {
Benjamin Peterson6a42bd62012-09-01 23:04:38 -04006511 PyErr_SetString(PyExc_RuntimeError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006512 "super(): arg[0] deleted");
6513 return -1;
6514 }
6515 if (co->co_freevars == NULL)
6516 n = 0;
6517 else {
6518 assert(PyTuple_Check(co->co_freevars));
6519 n = PyTuple_GET_SIZE(co->co_freevars);
6520 }
6521 for (i = 0; i < n; i++) {
6522 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
6523 assert(PyUnicode_Check(name));
6524 if (!PyUnicode_CompareWithASCIIString(name,
Nick Coghlan0b43bcf2012-05-27 18:17:07 +10006525 "__class__")) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006526 Py_ssize_t index = co->co_nlocals +
6527 PyTuple_GET_SIZE(co->co_cellvars) + i;
6528 PyObject *cell = f->f_localsplus[index];
6529 if (cell == NULL || !PyCell_Check(cell)) {
Benjamin Peterson6a42bd62012-09-01 23:04:38 -04006530 PyErr_SetString(PyExc_RuntimeError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006531 "super(): bad __class__ cell");
6532 return -1;
6533 }
6534 type = (PyTypeObject *) PyCell_GET(cell);
6535 if (type == NULL) {
Benjamin Peterson6a42bd62012-09-01 23:04:38 -04006536 PyErr_SetString(PyExc_RuntimeError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006537 "super(): empty __class__ cell");
6538 return -1;
6539 }
6540 if (!PyType_Check(type)) {
Benjamin Peterson6a42bd62012-09-01 23:04:38 -04006541 PyErr_Format(PyExc_RuntimeError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006542 "super(): __class__ is not a type (%s)",
6543 Py_TYPE(type)->tp_name);
6544 return -1;
6545 }
6546 break;
6547 }
6548 }
6549 if (type == NULL) {
Benjamin Peterson6a42bd62012-09-01 23:04:38 -04006550 PyErr_SetString(PyExc_RuntimeError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006551 "super(): __class__ cell not found");
6552 return -1;
6553 }
6554 }
Guido van Rossumcd16bf62007-06-13 18:07:49 +00006555
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006556 if (obj == Py_None)
6557 obj = NULL;
6558 if (obj != NULL) {
6559 obj_type = supercheck(type, obj);
6560 if (obj_type == NULL)
6561 return -1;
6562 Py_INCREF(obj);
6563 }
6564 Py_INCREF(type);
6565 su->type = type;
6566 su->obj = obj;
6567 su->obj_type = obj_type;
6568 return 0;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006569}
6570
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00006571PyDoc_STRVAR(super_doc,
Guido van Rossumcd16bf62007-06-13 18:07:49 +00006572"super() -> same as super(__class__, <first argument>)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00006573"super(type) -> unbound super object\n"
6574"super(type, obj) -> bound super object; requires isinstance(obj, type)\n"
Guido van Rossume705ef12001-08-29 15:47:06 +00006575"super(type, type2) -> bound super object; requires issubclass(type2, type)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00006576"Typical use to call a cooperative superclass method:\n"
6577"class C(B):\n"
6578" def meth(self, arg):\n"
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006579" super().meth(arg)\n"
Guido van Rossumcd16bf62007-06-13 18:07:49 +00006580"This works for class methods too:\n"
6581"class C(B):\n"
6582" @classmethod\n"
6583" def cmeth(cls, arg):\n"
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006584" super().cmeth(arg)\n");
Guido van Rossum705f0f52001-08-24 16:47:00 +00006585
Guido van Rossum048eb752001-10-02 21:24:57 +00006586static int
6587super_traverse(PyObject *self, visitproc visit, void *arg)
6588{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006589 superobject *su = (superobject *)self;
Guido van Rossum048eb752001-10-02 21:24:57 +00006590
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006591 Py_VISIT(su->obj);
6592 Py_VISIT(su->type);
6593 Py_VISIT(su->obj_type);
Guido van Rossum048eb752001-10-02 21:24:57 +00006594
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006595 return 0;
Guido van Rossum048eb752001-10-02 21:24:57 +00006596}
6597
Guido van Rossum705f0f52001-08-24 16:47:00 +00006598PyTypeObject PySuper_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006599 PyVarObject_HEAD_INIT(&PyType_Type, 0)
6600 "super", /* tp_name */
6601 sizeof(superobject), /* tp_basicsize */
6602 0, /* tp_itemsize */
6603 /* methods */
6604 super_dealloc, /* tp_dealloc */
6605 0, /* tp_print */
6606 0, /* tp_getattr */
6607 0, /* tp_setattr */
6608 0, /* tp_reserved */
6609 super_repr, /* tp_repr */
6610 0, /* tp_as_number */
6611 0, /* tp_as_sequence */
6612 0, /* tp_as_mapping */
6613 0, /* tp_hash */
6614 0, /* tp_call */
6615 0, /* tp_str */
6616 super_getattro, /* tp_getattro */
6617 0, /* tp_setattro */
6618 0, /* tp_as_buffer */
6619 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
6620 Py_TPFLAGS_BASETYPE, /* tp_flags */
6621 super_doc, /* tp_doc */
6622 super_traverse, /* tp_traverse */
6623 0, /* tp_clear */
6624 0, /* tp_richcompare */
6625 0, /* tp_weaklistoffset */
6626 0, /* tp_iter */
6627 0, /* tp_iternext */
6628 0, /* tp_methods */
6629 super_members, /* tp_members */
6630 0, /* tp_getset */
6631 0, /* tp_base */
6632 0, /* tp_dict */
6633 super_descr_get, /* tp_descr_get */
6634 0, /* tp_descr_set */
6635 0, /* tp_dictoffset */
6636 super_init, /* tp_init */
6637 PyType_GenericAlloc, /* tp_alloc */
6638 PyType_GenericNew, /* tp_new */
6639 PyObject_GC_Del, /* tp_free */
Guido van Rossum705f0f52001-08-24 16:47:00 +00006640};