blob: 4b3c63cce76d1c091c4026d29c64b78346f1f79c [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
17#define MCACHE_SIZE_EXP 10
18#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
Christian Heimes26855632008-01-27 23:50:43 +000051unsigned int
52PyType_ClearCache(void)
53{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000054 Py_ssize_t i;
55 unsigned int cur_version_tag = next_version_tag - 1;
56
57 for (i = 0; i < (1 << MCACHE_SIZE_EXP); i++) {
58 method_cache[i].version = 0;
59 Py_CLEAR(method_cache[i].name);
60 method_cache[i].value = NULL;
61 }
62 next_version_tag = 0;
63 /* mark all version tags as invalid */
64 PyType_Modified(&PyBaseObject_Type);
65 return cur_version_tag;
Christian Heimes26855632008-01-27 23:50:43 +000066}
Christian Heimesa62da1d2008-01-12 19:39:10 +000067
Georg Brandlf08a9dd2008-06-10 16:57:31 +000068void
69PyType_Modified(PyTypeObject *type)
Christian Heimesa62da1d2008-01-12 19:39:10 +000070{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000071 /* Invalidate any cached data for the specified type and all
72 subclasses. This function is called after the base
73 classes, mro, or attributes of the type are altered.
Christian Heimesa62da1d2008-01-12 19:39:10 +000074
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000075 Invariants:
Christian Heimesa62da1d2008-01-12 19:39:10 +000076
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000077 - Py_TPFLAGS_VALID_VERSION_TAG is never set if
78 Py_TPFLAGS_HAVE_VERSION_TAG is not set (e.g. on type
79 objects coming from non-recompiled extension modules)
Christian Heimesa62da1d2008-01-12 19:39:10 +000080
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000081 - before Py_TPFLAGS_VALID_VERSION_TAG can be set on a type,
82 it must first be set on all super types.
Christian Heimesa62da1d2008-01-12 19:39:10 +000083
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000084 This function clears the Py_TPFLAGS_VALID_VERSION_TAG of a
85 type (so it must first clear it on all subclasses). The
86 tp_version_tag value is meaningless unless this flag is set.
87 We don't assign new version tags eagerly, but only as
88 needed.
89 */
90 PyObject *raw, *ref;
91 Py_ssize_t i, n;
Christian Heimesa62da1d2008-01-12 19:39:10 +000092
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000093 if (!PyType_HasFeature(type, Py_TPFLAGS_VALID_VERSION_TAG))
94 return;
Christian Heimesa62da1d2008-01-12 19:39:10 +000095
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000096 raw = type->tp_subclasses;
97 if (raw != NULL) {
98 n = PyList_GET_SIZE(raw);
99 for (i = 0; i < n; i++) {
100 ref = PyList_GET_ITEM(raw, i);
101 ref = PyWeakref_GET_OBJECT(ref);
102 if (ref != Py_None) {
103 PyType_Modified((PyTypeObject *)ref);
104 }
105 }
106 }
107 type->tp_flags &= ~Py_TPFLAGS_VALID_VERSION_TAG;
Christian Heimesa62da1d2008-01-12 19:39:10 +0000108}
109
110static void
111type_mro_modified(PyTypeObject *type, PyObject *bases) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000112 /*
Florent Xiclunaaa6c1d22011-12-12 18:54:29 +0100113 Check that all base classes or elements of the MRO of type are
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000114 able to be cached. This function is called after the base
115 classes or mro of the type are altered.
Christian Heimesa62da1d2008-01-12 19:39:10 +0000116
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000117 Unset HAVE_VERSION_TAG and VALID_VERSION_TAG if the type
Florent Xiclunaaa6c1d22011-12-12 18:54:29 +0100118 has a custom MRO that includes a type which is not officially
119 super type.
Christian Heimesa62da1d2008-01-12 19:39:10 +0000120
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000121 Called from mro_internal, which will subsequently be called on
122 each subclass when their mro is recursively updated.
123 */
124 Py_ssize_t i, n;
125 int clear = 0;
Christian Heimesa62da1d2008-01-12 19:39:10 +0000126
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000127 if (!PyType_HasFeature(type, Py_TPFLAGS_HAVE_VERSION_TAG))
128 return;
Christian Heimesa62da1d2008-01-12 19:39:10 +0000129
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000130 n = PyTuple_GET_SIZE(bases);
131 for (i = 0; i < n; i++) {
132 PyObject *b = PyTuple_GET_ITEM(bases, i);
133 PyTypeObject *cls;
Christian Heimesa62da1d2008-01-12 19:39:10 +0000134
Florent Xiclunaaa6c1d22011-12-12 18:54:29 +0100135 assert(PyType_Check(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000136 cls = (PyTypeObject *)b;
Christian Heimesa62da1d2008-01-12 19:39:10 +0000137
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000138 if (!PyType_HasFeature(cls, Py_TPFLAGS_HAVE_VERSION_TAG) ||
139 !PyType_IsSubtype(type, cls)) {
140 clear = 1;
141 break;
142 }
143 }
Christian Heimesa62da1d2008-01-12 19:39:10 +0000144
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000145 if (clear)
146 type->tp_flags &= ~(Py_TPFLAGS_HAVE_VERSION_TAG|
147 Py_TPFLAGS_VALID_VERSION_TAG);
Christian Heimesa62da1d2008-01-12 19:39:10 +0000148}
149
150static int
151assign_version_tag(PyTypeObject *type)
152{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000153 /* Ensure that the tp_version_tag is valid and set
154 Py_TPFLAGS_VALID_VERSION_TAG. To respect the invariant, this
155 must first be done on all super classes. Return 0 if this
156 cannot be done, 1 if Py_TPFLAGS_VALID_VERSION_TAG.
157 */
158 Py_ssize_t i, n;
159 PyObject *bases;
Christian Heimesa62da1d2008-01-12 19:39:10 +0000160
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000161 if (PyType_HasFeature(type, Py_TPFLAGS_VALID_VERSION_TAG))
162 return 1;
163 if (!PyType_HasFeature(type, Py_TPFLAGS_HAVE_VERSION_TAG))
164 return 0;
165 if (!PyType_HasFeature(type, Py_TPFLAGS_READY))
166 return 0;
Christian Heimesa62da1d2008-01-12 19:39:10 +0000167
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000168 type->tp_version_tag = next_version_tag++;
169 /* for stress-testing: next_version_tag &= 0xFF; */
Christian Heimesa62da1d2008-01-12 19:39:10 +0000170
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000171 if (type->tp_version_tag == 0) {
172 /* wrap-around or just starting Python - clear the whole
173 cache by filling names with references to Py_None.
174 Values are also set to NULL for added protection, as they
175 are borrowed reference */
176 for (i = 0; i < (1 << MCACHE_SIZE_EXP); i++) {
177 method_cache[i].value = NULL;
178 Py_XDECREF(method_cache[i].name);
179 method_cache[i].name = Py_None;
180 Py_INCREF(Py_None);
181 }
182 /* mark all version tags as invalid */
183 PyType_Modified(&PyBaseObject_Type);
184 return 1;
185 }
186 bases = type->tp_bases;
187 n = PyTuple_GET_SIZE(bases);
188 for (i = 0; i < n; i++) {
189 PyObject *b = PyTuple_GET_ITEM(bases, i);
190 assert(PyType_Check(b));
191 if (!assign_version_tag((PyTypeObject *)b))
192 return 0;
193 }
194 type->tp_flags |= Py_TPFLAGS_VALID_VERSION_TAG;
195 return 1;
Christian Heimesa62da1d2008-01-12 19:39:10 +0000196}
197
198
Guido van Rossum6f799372001-09-20 20:46:19 +0000199static PyMemberDef type_members[] = {
Benjamin Peterson0e102062010-08-25 23:13:17 +0000200 {"__basicsize__", T_PYSSIZET, offsetof(PyTypeObject,tp_basicsize),READONLY},
201 {"__itemsize__", T_PYSSIZET, offsetof(PyTypeObject, tp_itemsize), READONLY},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000202 {"__flags__", T_LONG, offsetof(PyTypeObject, tp_flags), READONLY},
203 {"__weakrefoffset__", T_LONG,
204 offsetof(PyTypeObject, tp_weaklistoffset), READONLY},
205 {"__base__", T_OBJECT, offsetof(PyTypeObject, tp_base), READONLY},
206 {"__dictoffset__", T_LONG,
207 offsetof(PyTypeObject, tp_dictoffset), READONLY},
208 {"__mro__", T_OBJECT, offsetof(PyTypeObject, tp_mro), READONLY},
209 {0}
Tim Peters6d6c1a32001-08-02 04:15:00 +0000210};
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000211
Benjamin Petersond9f23d22011-08-17 11:54:03 -0500212static int
213check_set_special_type_attr(PyTypeObject *type, PyObject *value, const char *name)
214{
215 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
216 PyErr_Format(PyExc_TypeError,
217 "can't set %s.%s", type->tp_name, name);
218 return 0;
219 }
220 if (!value) {
221 PyErr_Format(PyExc_TypeError,
222 "can't delete %s.%s", type->tp_name, name);
223 return 0;
224 }
225 return 1;
226}
227
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000228static PyObject *
Guido van Rossumc3542212001-08-16 09:18:56 +0000229type_name(PyTypeObject *type, void *context)
230{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000231 const char *s;
Guido van Rossumc3542212001-08-16 09:18:56 +0000232
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000233 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
234 PyHeapTypeObject* et = (PyHeapTypeObject*)type;
Tim Petersea7f75d2002-12-07 21:39:16 +0000235
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000236 Py_INCREF(et->ht_name);
237 return et->ht_name;
238 }
239 else {
240 s = strrchr(type->tp_name, '.');
241 if (s == NULL)
242 s = type->tp_name;
243 else
244 s++;
245 return PyUnicode_FromString(s);
246 }
Guido van Rossumc3542212001-08-16 09:18:56 +0000247}
248
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100249static PyObject *
250type_qualname(PyTypeObject *type, void *context)
251{
252 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
253 PyHeapTypeObject* et = (PyHeapTypeObject*)type;
254 Py_INCREF(et->ht_qualname);
255 return et->ht_qualname;
256 }
257 else {
258 return type_name(type, context);
259 }
260}
261
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000262static int
263type_set_name(PyTypeObject *type, PyObject *value, void *context)
264{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000265 PyHeapTypeObject* et;
266 char *tp_name;
267 PyObject *tmp;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000268
Benjamin Petersond9f23d22011-08-17 11:54:03 -0500269 if (!check_set_special_type_attr(type, value, "__name__"))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000270 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000271 if (!PyUnicode_Check(value)) {
272 PyErr_Format(PyExc_TypeError,
273 "can only assign string to %s.__name__, not '%s'",
274 type->tp_name, Py_TYPE(value)->tp_name);
275 return -1;
276 }
Guido van Rossume845c0f2007-11-02 23:07:07 +0000277
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000278 /* Check absence of null characters */
279 tmp = PyUnicode_FromStringAndSize("\0", 1);
280 if (tmp == NULL)
281 return -1;
282 if (PyUnicode_Contains(value, tmp) != 0) {
283 Py_DECREF(tmp);
284 PyErr_Format(PyExc_ValueError,
285 "__name__ must not contain null bytes");
286 return -1;
287 }
288 Py_DECREF(tmp);
Guido van Rossume845c0f2007-11-02 23:07:07 +0000289
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000290 tp_name = _PyUnicode_AsString(value);
291 if (tp_name == NULL)
292 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000293
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000294 et = (PyHeapTypeObject*)type;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000295
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000296 Py_INCREF(value);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000297
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000298 Py_DECREF(et->ht_name);
299 et->ht_name = value;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000300
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000301 type->tp_name = tp_name;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000302
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000303 return 0;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000304}
305
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100306static int
307type_set_qualname(PyTypeObject *type, PyObject *value, void *context)
308{
309 PyHeapTypeObject* et;
310
311 if (!PyUnicode_Check(value)) {
312 PyErr_Format(PyExc_TypeError,
313 "can only assign string to %s.__qualname__, not '%s'",
314 type->tp_name, Py_TYPE(value)->tp_name);
315 return -1;
316 }
317
318 et = (PyHeapTypeObject*)type;
319 Py_INCREF(value);
320 Py_DECREF(et->ht_qualname);
321 et->ht_qualname = value;
322 return 0;
323}
324
Guido van Rossumc3542212001-08-16 09:18:56 +0000325static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000326type_module(PyTypeObject *type, void *context)
Guido van Rossum29ca26e1995-01-07 11:58:15 +0000327{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000328 PyObject *mod;
329 char *s;
Guido van Rossumc3542212001-08-16 09:18:56 +0000330
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000331 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
Victor Stinner3c1e4812012-03-26 22:10:51 +0200332 mod = _PyDict_GetItemId(type->tp_dict, &PyId___module__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000333 if (!mod) {
334 PyErr_Format(PyExc_AttributeError, "__module__");
335 return 0;
336 }
337 Py_XINCREF(mod);
338 return mod;
339 }
340 else {
341 s = strrchr(type->tp_name, '.');
342 if (s != NULL)
343 return PyUnicode_FromStringAndSize(
344 type->tp_name, (Py_ssize_t)(s - type->tp_name));
345 return PyUnicode_FromString("builtins");
346 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000347}
348
Guido van Rossum3926a632001-09-25 16:25:58 +0000349static int
350type_set_module(PyTypeObject *type, PyObject *value, void *context)
351{
Benjamin Petersond9f23d22011-08-17 11:54:03 -0500352 if (!check_set_special_type_attr(type, value, "__module__"))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000353 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000354
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000355 PyType_Modified(type);
Christian Heimesa62da1d2008-01-12 19:39:10 +0000356
Victor Stinner3c1e4812012-03-26 22:10:51 +0200357 return _PyDict_SetItemId(type->tp_dict, &PyId___module__, value);
Guido van Rossum3926a632001-09-25 16:25:58 +0000358}
359
Tim Peters6d6c1a32001-08-02 04:15:00 +0000360static PyObject *
Christian Heimes9e7f1d22008-02-28 12:27:11 +0000361type_abstractmethods(PyTypeObject *type, void *context)
362{
Benjamin Petersonaec5fd12010-10-02 00:03:31 +0000363 PyObject *mod = NULL;
Benjamin Peterson84060b82010-10-03 02:13:39 +0000364 /* type itself has an __abstractmethods__ descriptor (this). Don't return
365 that. */
Benjamin Petersonaec5fd12010-10-02 00:03:31 +0000366 if (type != &PyType_Type)
367 mod = PyDict_GetItemString(type->tp_dict, "__abstractmethods__");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000368 if (!mod) {
Benjamin Peterson23b628e2011-01-12 18:56:07 +0000369 PyErr_SetString(PyExc_AttributeError, "__abstractmethods__");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000370 return NULL;
371 }
372 Py_XINCREF(mod);
373 return mod;
Christian Heimes9e7f1d22008-02-28 12:27:11 +0000374}
375
376static int
377type_set_abstractmethods(PyTypeObject *type, PyObject *value, void *context)
378{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000379 /* __abstractmethods__ should only be set once on a type, in
380 abc.ABCMeta.__new__, so this function doesn't do anything
381 special to update subclasses.
382 */
Benjamin Peterson477ba912011-01-12 15:34:01 +0000383 int res;
384 if (value != NULL) {
385 res = PyDict_SetItemString(type->tp_dict, "__abstractmethods__", value);
386 }
387 else {
388 res = PyDict_DelItemString(type->tp_dict, "__abstractmethods__");
389 if (res && PyErr_ExceptionMatches(PyExc_KeyError)) {
Benjamin Peterson23b628e2011-01-12 18:56:07 +0000390 PyErr_SetString(PyExc_AttributeError, "__abstractmethods__");
Benjamin Peterson477ba912011-01-12 15:34:01 +0000391 return -1;
392 }
393 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000394 if (res == 0) {
395 PyType_Modified(type);
396 if (value && PyObject_IsTrue(value)) {
397 type->tp_flags |= Py_TPFLAGS_IS_ABSTRACT;
398 }
399 else {
400 type->tp_flags &= ~Py_TPFLAGS_IS_ABSTRACT;
401 }
402 }
403 return res;
Christian Heimes9e7f1d22008-02-28 12:27:11 +0000404}
405
406static PyObject *
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000407type_get_bases(PyTypeObject *type, void *context)
408{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000409 Py_INCREF(type->tp_bases);
410 return type->tp_bases;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000411}
412
413static PyTypeObject *best_base(PyObject *);
414static int mro_internal(PyTypeObject *);
415static int compatible_for_assignment(PyTypeObject *, PyTypeObject *, char *);
416static int add_subclass(PyTypeObject*, PyTypeObject*);
417static void remove_subclass(PyTypeObject *, PyTypeObject *);
418static void update_all_slots(PyTypeObject *);
419
Guido van Rossum8d24ee92003-03-24 23:49:49 +0000420typedef int (*update_callback)(PyTypeObject *, void *);
421static int update_subclasses(PyTypeObject *type, PyObject *name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000422 update_callback callback, void *data);
Guido van Rossum8d24ee92003-03-24 23:49:49 +0000423static int recurse_down_subclasses(PyTypeObject *type, PyObject *name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000424 update_callback callback, void *data);
Guido van Rossum8d24ee92003-03-24 23:49:49 +0000425
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000426static int
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000427mro_subclasses(PyTypeObject *type, PyObject* temp)
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000428{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000429 PyTypeObject *subclass;
430 PyObject *ref, *subclasses, *old_mro;
431 Py_ssize_t i, n;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000432
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000433 subclasses = type->tp_subclasses;
434 if (subclasses == NULL)
435 return 0;
436 assert(PyList_Check(subclasses));
437 n = PyList_GET_SIZE(subclasses);
438 for (i = 0; i < n; i++) {
439 ref = PyList_GET_ITEM(subclasses, i);
440 assert(PyWeakref_CheckRef(ref));
441 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
442 assert(subclass != NULL);
443 if ((PyObject *)subclass == Py_None)
444 continue;
445 assert(PyType_Check(subclass));
446 old_mro = subclass->tp_mro;
447 if (mro_internal(subclass) < 0) {
448 subclass->tp_mro = old_mro;
449 return -1;
450 }
451 else {
452 PyObject* tuple;
453 tuple = PyTuple_Pack(2, subclass, old_mro);
454 Py_DECREF(old_mro);
455 if (!tuple)
456 return -1;
457 if (PyList_Append(temp, tuple) < 0)
458 return -1;
459 Py_DECREF(tuple);
460 }
461 if (mro_subclasses(subclass, temp) < 0)
462 return -1;
463 }
464 return 0;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000465}
466
467static int
468type_set_bases(PyTypeObject *type, PyObject *value, void *context)
469{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000470 Py_ssize_t i;
471 int r = 0;
472 PyObject *ob, *temp;
473 PyTypeObject *new_base, *old_base;
474 PyObject *old_bases, *old_mro;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000475
Benjamin Petersond9f23d22011-08-17 11:54:03 -0500476 if (!check_set_special_type_attr(type, value, "__bases__"))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000477 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000478 if (!PyTuple_Check(value)) {
479 PyErr_Format(PyExc_TypeError,
480 "can only assign tuple to %s.__bases__, not %s",
481 type->tp_name, Py_TYPE(value)->tp_name);
482 return -1;
483 }
484 if (PyTuple_GET_SIZE(value) == 0) {
485 PyErr_Format(PyExc_TypeError,
486 "can only assign non-empty tuple to %s.__bases__, not ()",
487 type->tp_name);
488 return -1;
489 }
490 for (i = 0; i < PyTuple_GET_SIZE(value); i++) {
491 ob = PyTuple_GET_ITEM(value, i);
492 if (!PyType_Check(ob)) {
Benjamin Petersonb6af60c2012-04-01 18:49:54 -0400493 PyErr_Format(PyExc_TypeError,
Benjamin Peterson9ee601e2012-04-01 18:51:37 -0400494 "%s.__bases__ must be tuple of classes, not '%s'",
Benjamin Petersonb6af60c2012-04-01 18:49:54 -0400495 type->tp_name, Py_TYPE(ob)->tp_name);
496 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000497 }
Benjamin Peterson3471bb62012-04-01 18:48:40 -0400498 if (PyType_IsSubtype((PyTypeObject*)ob, type)) {
499 PyErr_SetString(PyExc_TypeError,
500 "a __bases__ item causes an inheritance cycle");
501 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000502 }
503 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000504
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000505 new_base = best_base(value);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000506
Benjamin Petersonab3c1c12012-04-01 18:48:02 -0400507 if (!new_base)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000508 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000509
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000510 if (!compatible_for_assignment(type->tp_base, new_base, "__bases__"))
511 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000512
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000513 Py_INCREF(new_base);
514 Py_INCREF(value);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000515
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000516 old_bases = type->tp_bases;
517 old_base = type->tp_base;
518 old_mro = type->tp_mro;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000519
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000520 type->tp_bases = value;
521 type->tp_base = new_base;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000522
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000523 if (mro_internal(type) < 0) {
524 goto bail;
525 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000526
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000527 temp = PyList_New(0);
528 if (!temp)
529 goto bail;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000530
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000531 r = mro_subclasses(type, temp);
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000532
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000533 if (r < 0) {
534 for (i = 0; i < PyList_Size(temp); i++) {
535 PyTypeObject* cls;
536 PyObject* mro;
537 PyArg_UnpackTuple(PyList_GET_ITEM(temp, i),
538 "", 2, 2, &cls, &mro);
539 Py_INCREF(mro);
540 ob = cls->tp_mro;
541 cls->tp_mro = mro;
542 Py_DECREF(ob);
543 }
544 Py_DECREF(temp);
545 goto bail;
546 }
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000547
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000548 Py_DECREF(temp);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000549
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000550 /* any base that was in __bases__ but now isn't, we
551 need to remove |type| from its tp_subclasses.
552 conversely, any class now in __bases__ that wasn't
553 needs to have |type| added to its subclasses. */
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000554
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000555 /* for now, sod that: just remove from all old_bases,
556 add to all new_bases */
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000557
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000558 for (i = PyTuple_GET_SIZE(old_bases) - 1; i >= 0; i--) {
559 ob = PyTuple_GET_ITEM(old_bases, i);
560 if (PyType_Check(ob)) {
561 remove_subclass(
562 (PyTypeObject*)ob, type);
563 }
564 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000565
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000566 for (i = PyTuple_GET_SIZE(value) - 1; i >= 0; i--) {
567 ob = PyTuple_GET_ITEM(value, i);
568 if (PyType_Check(ob)) {
569 if (add_subclass((PyTypeObject*)ob, type) < 0)
570 r = -1;
571 }
572 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000573
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000574 update_all_slots(type);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000575
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000576 Py_DECREF(old_bases);
577 Py_DECREF(old_base);
578 Py_DECREF(old_mro);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000579
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000580 return r;
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000581
582 bail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000583 Py_DECREF(type->tp_bases);
584 Py_DECREF(type->tp_base);
585 if (type->tp_mro != old_mro) {
586 Py_DECREF(type->tp_mro);
587 }
Michael W. Hudsone723e452003-08-07 14:58:10 +0000588
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000589 type->tp_bases = old_bases;
590 type->tp_base = old_base;
591 type->tp_mro = old_mro;
Tim Petersea7f75d2002-12-07 21:39:16 +0000592
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000593 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000594}
595
596static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000597type_dict(PyTypeObject *type, void *context)
598{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000599 if (type->tp_dict == NULL) {
600 Py_INCREF(Py_None);
601 return Py_None;
602 }
603 return PyDictProxy_New(type->tp_dict);
Guido van Rossum29ca26e1995-01-07 11:58:15 +0000604}
605
Tim Peters24008312002-03-17 18:56:20 +0000606static PyObject *
607type_get_doc(PyTypeObject *type, void *context)
608{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000609 PyObject *result;
610 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE) && type->tp_doc != NULL)
611 return PyUnicode_FromString(type->tp_doc);
Victor Stinner3c1e4812012-03-26 22:10:51 +0200612 result = _PyDict_GetItemId(type->tp_dict, &PyId___doc__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000613 if (result == NULL) {
614 result = Py_None;
615 Py_INCREF(result);
616 }
617 else if (Py_TYPE(result)->tp_descr_get) {
618 result = Py_TYPE(result)->tp_descr_get(result, NULL,
619 (PyObject *)type);
620 }
621 else {
622 Py_INCREF(result);
623 }
624 return result;
Tim Peters24008312002-03-17 18:56:20 +0000625}
626
Benjamin Peterson01fc6cd2011-08-17 12:03:47 -0500627static int
628type_set_doc(PyTypeObject *type, PyObject *value, void *context)
629{
630 if (!check_set_special_type_attr(type, value, "__doc__"))
631 return -1;
632 PyType_Modified(type);
Victor Stinner3c1e4812012-03-26 22:10:51 +0200633 return _PyDict_SetItemId(type->tp_dict, &PyId___doc__, value);
Benjamin Peterson01fc6cd2011-08-17 12:03:47 -0500634}
635
Antoine Pitrouec569b72008-08-26 22:40:48 +0000636static PyObject *
637type___instancecheck__(PyObject *type, PyObject *inst)
638{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000639 switch (_PyObject_RealIsInstance(inst, type)) {
640 case -1:
641 return NULL;
642 case 0:
643 Py_RETURN_FALSE;
644 default:
645 Py_RETURN_TRUE;
646 }
Antoine Pitrouec569b72008-08-26 22:40:48 +0000647}
648
649
650static PyObject *
Antoine Pitrouec569b72008-08-26 22:40:48 +0000651type___subclasscheck__(PyObject *type, PyObject *inst)
652{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000653 switch (_PyObject_RealIsSubclass(inst, type)) {
654 case -1:
655 return NULL;
656 case 0:
657 Py_RETURN_FALSE;
658 default:
659 Py_RETURN_TRUE;
660 }
Antoine Pitrouec569b72008-08-26 22:40:48 +0000661}
662
Antoine Pitrouec569b72008-08-26 22:40:48 +0000663
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000664static PyGetSetDef type_getsets[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000665 {"__name__", (getter)type_name, (setter)type_set_name, NULL},
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100666 {"__qualname__", (getter)type_qualname, (setter)type_set_qualname, NULL},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000667 {"__bases__", (getter)type_get_bases, (setter)type_set_bases, NULL},
668 {"__module__", (getter)type_module, (setter)type_set_module, NULL},
669 {"__abstractmethods__", (getter)type_abstractmethods,
670 (setter)type_set_abstractmethods, NULL},
671 {"__dict__", (getter)type_dict, NULL, NULL},
Benjamin Peterson01fc6cd2011-08-17 12:03:47 -0500672 {"__doc__", (getter)type_get_doc, (setter)type_set_doc, NULL},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000673 {0}
Tim Peters6d6c1a32001-08-02 04:15:00 +0000674};
675
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000676static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000677type_repr(PyTypeObject *type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000678{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000679 PyObject *mod, *name, *rtn;
Guido van Rossumc3542212001-08-16 09:18:56 +0000680
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000681 mod = type_module(type, NULL);
682 if (mod == NULL)
683 PyErr_Clear();
684 else if (!PyUnicode_Check(mod)) {
685 Py_DECREF(mod);
686 mod = NULL;
687 }
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100688 name = type_qualname(type, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000689 if (name == NULL)
690 return NULL;
Barry Warsaw7ce36942001-08-24 18:34:26 +0000691
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000692 if (mod != NULL && PyUnicode_CompareWithASCIIString(mod, "builtins"))
693 rtn = PyUnicode_FromFormat("<class '%U.%U'>", mod, name);
694 else
695 rtn = PyUnicode_FromFormat("<class '%s'>", type->tp_name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000696
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000697 Py_XDECREF(mod);
698 Py_DECREF(name);
699 return rtn;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000700}
701
Tim Peters6d6c1a32001-08-02 04:15:00 +0000702static PyObject *
703type_call(PyTypeObject *type, PyObject *args, PyObject *kwds)
704{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000705 PyObject *obj;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000706
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000707 if (type->tp_new == NULL) {
708 PyErr_Format(PyExc_TypeError,
709 "cannot create '%.100s' instances",
710 type->tp_name);
711 return NULL;
712 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000713
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000714 obj = type->tp_new(type, args, kwds);
715 if (obj != NULL) {
716 /* Ugly exception: when the call was type(something),
717 don't call tp_init on the result. */
718 if (type == &PyType_Type &&
719 PyTuple_Check(args) && PyTuple_GET_SIZE(args) == 1 &&
720 (kwds == NULL ||
721 (PyDict_Check(kwds) && PyDict_Size(kwds) == 0)))
722 return obj;
723 /* If the returned object is not an instance of type,
724 it won't be initialized. */
725 if (!PyType_IsSubtype(Py_TYPE(obj), type))
726 return obj;
727 type = Py_TYPE(obj);
728 if (type->tp_init != NULL &&
729 type->tp_init(obj, args, kwds) < 0) {
730 Py_DECREF(obj);
731 obj = NULL;
732 }
733 }
734 return obj;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000735}
736
737PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000738PyType_GenericAlloc(PyTypeObject *type, Py_ssize_t nitems)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000739{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000740 PyObject *obj;
741 const size_t size = _PyObject_VAR_SIZE(type, nitems+1);
742 /* note that we need to add one, for the sentinel */
Tim Peters406fe3b2001-10-06 19:04:01 +0000743
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000744 if (PyType_IS_GC(type))
745 obj = _PyObject_GC_Malloc(size);
746 else
747 obj = (PyObject *)PyObject_MALLOC(size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000748
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000749 if (obj == NULL)
750 return PyErr_NoMemory();
Tim Peters406fe3b2001-10-06 19:04:01 +0000751
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000752 memset(obj, '\0', size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000753
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000754 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
755 Py_INCREF(type);
Tim Peters406fe3b2001-10-06 19:04:01 +0000756
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000757 if (type->tp_itemsize == 0)
758 PyObject_INIT(obj, type);
759 else
760 (void) PyObject_INIT_VAR((PyVarObject *)obj, type, nitems);
Tim Peters406fe3b2001-10-06 19:04:01 +0000761
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000762 if (PyType_IS_GC(type))
763 _PyObject_GC_TRACK(obj);
764 return obj;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000765}
766
767PyObject *
768PyType_GenericNew(PyTypeObject *type, PyObject *args, PyObject *kwds)
769{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000770 return type->tp_alloc(type, 0);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000771}
772
Guido van Rossum9475a232001-10-05 20:51:39 +0000773/* Helpers for subtyping */
774
775static int
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000776traverse_slots(PyTypeObject *type, PyObject *self, visitproc visit, void *arg)
777{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000778 Py_ssize_t i, n;
779 PyMemberDef *mp;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000780
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000781 n = Py_SIZE(type);
782 mp = PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type);
783 for (i = 0; i < n; i++, mp++) {
784 if (mp->type == T_OBJECT_EX) {
785 char *addr = (char *)self + mp->offset;
786 PyObject *obj = *(PyObject **)addr;
787 if (obj != NULL) {
788 int err = visit(obj, arg);
789 if (err)
790 return err;
791 }
792 }
793 }
794 return 0;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000795}
796
797static int
Guido van Rossum9475a232001-10-05 20:51:39 +0000798subtype_traverse(PyObject *self, visitproc visit, void *arg)
799{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000800 PyTypeObject *type, *base;
801 traverseproc basetraverse;
Guido van Rossum9475a232001-10-05 20:51:39 +0000802
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000803 /* Find the nearest base with a different tp_traverse,
804 and traverse slots while we're at it */
805 type = Py_TYPE(self);
806 base = type;
807 while ((basetraverse = base->tp_traverse) == subtype_traverse) {
808 if (Py_SIZE(base)) {
809 int err = traverse_slots(base, self, visit, arg);
810 if (err)
811 return err;
812 }
813 base = base->tp_base;
814 assert(base);
815 }
Guido van Rossum9475a232001-10-05 20:51:39 +0000816
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000817 if (type->tp_dictoffset != base->tp_dictoffset) {
818 PyObject **dictptr = _PyObject_GetDictPtr(self);
819 if (dictptr && *dictptr)
820 Py_VISIT(*dictptr);
821 }
Guido van Rossum9475a232001-10-05 20:51:39 +0000822
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000823 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
824 /* For a heaptype, the instances count as references
825 to the type. Traverse the type so the collector
826 can find cycles involving this link. */
827 Py_VISIT(type);
Guido van Rossuma3862092002-06-10 15:24:42 +0000828
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000829 if (basetraverse)
830 return basetraverse(self, visit, arg);
831 return 0;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000832}
833
834static void
835clear_slots(PyTypeObject *type, PyObject *self)
836{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000837 Py_ssize_t i, n;
838 PyMemberDef *mp;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000839
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000840 n = Py_SIZE(type);
841 mp = PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type);
842 for (i = 0; i < n; i++, mp++) {
843 if (mp->type == T_OBJECT_EX && !(mp->flags & READONLY)) {
844 char *addr = (char *)self + mp->offset;
845 PyObject *obj = *(PyObject **)addr;
846 if (obj != NULL) {
847 *(PyObject **)addr = NULL;
848 Py_DECREF(obj);
849 }
850 }
851 }
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000852}
853
854static int
855subtype_clear(PyObject *self)
856{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000857 PyTypeObject *type, *base;
858 inquiry baseclear;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000859
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000860 /* Find the nearest base with a different tp_clear
861 and clear slots while we're at it */
862 type = Py_TYPE(self);
863 base = type;
864 while ((baseclear = base->tp_clear) == subtype_clear) {
865 if (Py_SIZE(base))
866 clear_slots(base, self);
867 base = base->tp_base;
868 assert(base);
869 }
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000870
Benjamin Peterson52c42432012-03-07 18:41:11 -0600871 /* Clear the instance dict (if any), to break cycles involving only
872 __dict__ slots (as in the case 'self.__dict__ is self'). */
873 if (type->tp_dictoffset != base->tp_dictoffset) {
874 PyObject **dictptr = _PyObject_GetDictPtr(self);
875 if (dictptr && *dictptr)
876 Py_CLEAR(*dictptr);
877 }
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000878
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000879 if (baseclear)
880 return baseclear(self);
881 return 0;
Guido van Rossum9475a232001-10-05 20:51:39 +0000882}
Tim Peters6d6c1a32001-08-02 04:15:00 +0000883
884static void
885subtype_dealloc(PyObject *self)
886{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000887 PyTypeObject *type, *base;
888 destructor basedealloc;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000889
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000890 /* Extract the type; we expect it to be a heap type */
891 type = Py_TYPE(self);
892 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000893
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000894 /* Test whether the type has GC exactly once */
Guido van Rossum22b13872002-08-06 21:41:44 +0000895
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000896 if (!PyType_IS_GC(type)) {
897 /* It's really rare to find a dynamic type that doesn't have
898 GC; it can only happen when deriving from 'object' and not
899 adding any slots or instance variables. This allows
900 certain simplifications: there's no need to call
901 clear_slots(), or DECREF the dict, or clear weakrefs. */
Guido van Rossum22b13872002-08-06 21:41:44 +0000902
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000903 /* Maybe call finalizer; exit early if resurrected */
904 if (type->tp_del) {
905 type->tp_del(self);
906 if (self->ob_refcnt > 0)
907 return;
908 }
Guido van Rossum22b13872002-08-06 21:41:44 +0000909
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000910 /* Find the nearest base with a different tp_dealloc */
911 base = type;
912 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
913 assert(Py_SIZE(base) == 0);
914 base = base->tp_base;
915 assert(base);
916 }
Guido van Rossum22b13872002-08-06 21:41:44 +0000917
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000918 /* Extract the type again; tp_del may have changed it */
919 type = Py_TYPE(self);
Benjamin Peterson193152c2009-04-25 01:08:45 +0000920
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000921 /* Call the base tp_dealloc() */
922 assert(basedealloc);
923 basedealloc(self);
Guido van Rossum22b13872002-08-06 21:41:44 +0000924
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000925 /* Can't reference self beyond this point */
926 Py_DECREF(type);
Guido van Rossum22b13872002-08-06 21:41:44 +0000927
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000928 /* Done */
929 return;
930 }
Guido van Rossum22b13872002-08-06 21:41:44 +0000931
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000932 /* We get here only if the type has GC */
Guido van Rossum22b13872002-08-06 21:41:44 +0000933
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000934 /* UnTrack and re-Track around the trashcan macro, alas */
935 /* See explanation at end of function for full disclosure */
936 PyObject_GC_UnTrack(self);
937 ++_PyTrash_delete_nesting;
938 Py_TRASHCAN_SAFE_BEGIN(self);
939 --_PyTrash_delete_nesting;
940 /* DO NOT restore GC tracking at this point. weakref callbacks
941 * (if any, and whether directly here or indirectly in something we
942 * call) may trigger GC, and if self is tracked at that point, it
943 * will look like trash to GC and GC will try to delete self again.
944 */
Guido van Rossum22b13872002-08-06 21:41:44 +0000945
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000946 /* Find the nearest base with a different tp_dealloc */
947 base = type;
Brett Cannonb94767f2011-02-22 20:15:44 +0000948 while ((/*basedealloc =*/ base->tp_dealloc) == subtype_dealloc) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000949 base = base->tp_base;
950 assert(base);
951 }
Guido van Rossum14227b42001-12-06 02:35:58 +0000952
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000953 /* If we added a weaklist, we clear it. Do this *before* calling
954 the finalizer (__del__), clearing slots, or clearing the instance
955 dict. */
Guido van Rossum59195fd2003-06-13 20:54:40 +0000956
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000957 if (type->tp_weaklistoffset && !base->tp_weaklistoffset)
958 PyObject_ClearWeakRefs(self);
Guido van Rossum1987c662003-05-29 14:29:23 +0000959
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000960 /* Maybe call finalizer; exit early if resurrected */
961 if (type->tp_del) {
962 _PyObject_GC_TRACK(self);
963 type->tp_del(self);
964 if (self->ob_refcnt > 0)
965 goto endlabel; /* resurrected */
966 else
967 _PyObject_GC_UNTRACK(self);
968 /* New weakrefs could be created during the finalizer call.
969 If this occurs, clear them out without calling their
970 finalizers since they might rely on part of the object
971 being finalized that has already been destroyed. */
972 if (type->tp_weaklistoffset && !base->tp_weaklistoffset) {
973 /* Modeled after GET_WEAKREFS_LISTPTR() */
974 PyWeakReference **list = (PyWeakReference **) \
975 PyObject_GET_WEAKREFS_LISTPTR(self);
976 while (*list)
977 _PyWeakref_ClearRef(*list);
978 }
979 }
Guido van Rossum1987c662003-05-29 14:29:23 +0000980
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000981 /* Clear slots up to the nearest base with a different tp_dealloc */
982 base = type;
983 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
984 if (Py_SIZE(base))
985 clear_slots(base, self);
986 base = base->tp_base;
987 assert(base);
988 }
Guido van Rossum59195fd2003-06-13 20:54:40 +0000989
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000990 /* If we added a dict, DECREF it */
991 if (type->tp_dictoffset && !base->tp_dictoffset) {
992 PyObject **dictptr = _PyObject_GetDictPtr(self);
993 if (dictptr != NULL) {
994 PyObject *dict = *dictptr;
995 if (dict != NULL) {
996 Py_DECREF(dict);
997 *dictptr = NULL;
998 }
999 }
1000 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001001
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001002 /* Extract the type again; tp_del may have changed it */
1003 type = Py_TYPE(self);
Benjamin Peterson193152c2009-04-25 01:08:45 +00001004
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001005 /* Call the base tp_dealloc(); first retrack self if
1006 * basedealloc knows about gc.
1007 */
1008 if (PyType_IS_GC(base))
1009 _PyObject_GC_TRACK(self);
1010 assert(basedealloc);
1011 basedealloc(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001012
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001013 /* Can't reference self beyond this point */
1014 Py_DECREF(type);
Guido van Rossum22b13872002-08-06 21:41:44 +00001015
Guido van Rossum0906e072002-08-07 20:42:09 +00001016 endlabel:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001017 ++_PyTrash_delete_nesting;
1018 Py_TRASHCAN_SAFE_END(self);
1019 --_PyTrash_delete_nesting;
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001020
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001021 /* Explanation of the weirdness around the trashcan macros:
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001022
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001023 Q. What do the trashcan macros do?
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001024
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001025 A. Read the comment titled "Trashcan mechanism" in object.h.
1026 For one, this explains why there must be a call to GC-untrack
1027 before the trashcan begin macro. Without understanding the
1028 trashcan code, the answers to the following questions don't make
1029 sense.
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001030
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001031 Q. Why do we GC-untrack before the trashcan and then immediately
1032 GC-track again afterward?
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001033
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001034 A. In the case that the base class is GC-aware, the base class
1035 probably GC-untracks the object. If it does that using the
1036 UNTRACK macro, this will crash when the object is already
1037 untracked. Because we don't know what the base class does, the
1038 only safe thing is to make sure the object is tracked when we
1039 call the base class dealloc. But... The trashcan begin macro
1040 requires that the object is *untracked* before it is called. So
1041 the dance becomes:
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001042
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001043 GC untrack
1044 trashcan begin
1045 GC track
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001046
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001047 Q. Why did the last question say "immediately GC-track again"?
1048 It's nowhere near immediately.
Tim Petersf7f9e992003-11-13 21:59:32 +00001049
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001050 A. Because the code *used* to re-track immediately. Bad Idea.
1051 self has a refcount of 0, and if gc ever gets its hands on it
1052 (which can happen if any weakref callback gets invoked), it
1053 looks like trash to gc too, and gc also tries to delete self
Ezio Melotti13925002011-03-16 11:05:33 +02001054 then. But we're already deleting self. Double deallocation is
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001055 a subtle disaster.
Tim Petersf7f9e992003-11-13 21:59:32 +00001056
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001057 Q. Why the bizarre (net-zero) manipulation of
1058 _PyTrash_delete_nesting around the trashcan macros?
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001059
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001060 A. Some base classes (e.g. list) also use the trashcan mechanism.
1061 The following scenario used to be possible:
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001062
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001063 - suppose the trashcan level is one below the trashcan limit
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001064
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001065 - subtype_dealloc() is called
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001066
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001067 - the trashcan limit is not yet reached, so the trashcan level
1068 is incremented and the code between trashcan begin and end is
1069 executed
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001070
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001071 - this destroys much of the object's contents, including its
1072 slots and __dict__
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001073
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001074 - basedealloc() is called; this is really list_dealloc(), or
1075 some other type which also uses the trashcan macros
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001076
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001077 - the trashcan limit is now reached, so the object is put on the
1078 trashcan's to-be-deleted-later list
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001079
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001080 - basedealloc() returns
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001081
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001082 - subtype_dealloc() decrefs the object's type
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001083
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001084 - subtype_dealloc() returns
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001085
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001086 - later, the trashcan code starts deleting the objects from its
1087 to-be-deleted-later list
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001088
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001089 - subtype_dealloc() is called *AGAIN* for the same object
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001090
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001091 - at the very least (if the destroyed slots and __dict__ don't
1092 cause problems) the object's type gets decref'ed a second
1093 time, which is *BAD*!!!
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001094
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001095 The remedy is to make sure that if the code between trashcan
1096 begin and end in subtype_dealloc() is called, the code between
1097 trashcan begin and end in basedealloc() will also be called.
1098 This is done by decrementing the level after passing into the
1099 trashcan block, and incrementing it just before leaving the
1100 block.
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001101
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001102 But now it's possible that a chain of objects consisting solely
1103 of objects whose deallocator is subtype_dealloc() will defeat
1104 the trashcan mechanism completely: the decremented level means
1105 that the effective level never reaches the limit. Therefore, we
1106 *increment* the level *before* entering the trashcan block, and
1107 matchingly decrement it after leaving. This means the trashcan
1108 code will trigger a little early, but that's no big deal.
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001109
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001110 Q. Are there any live examples of code in need of all this
1111 complexity?
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001112
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001113 A. Yes. See SF bug 668433 for code that crashed (when Python was
1114 compiled in debug mode) before the trashcan level manipulations
1115 were added. For more discussion, see SF patches 581742, 575073
1116 and bug 574207.
1117 */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001118}
1119
Jeremy Hylton938ace62002-07-17 16:30:39 +00001120static PyTypeObject *solid_base(PyTypeObject *type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001121
Tim Peters6d6c1a32001-08-02 04:15:00 +00001122/* type test with subclassing support */
1123
1124int
1125PyType_IsSubtype(PyTypeObject *a, PyTypeObject *b)
1126{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001127 PyObject *mro;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001128
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001129 mro = a->tp_mro;
1130 if (mro != NULL) {
1131 /* Deal with multiple inheritance without recursion
1132 by walking the MRO tuple */
1133 Py_ssize_t i, n;
1134 assert(PyTuple_Check(mro));
1135 n = PyTuple_GET_SIZE(mro);
1136 for (i = 0; i < n; i++) {
1137 if (PyTuple_GET_ITEM(mro, i) == (PyObject *)b)
1138 return 1;
1139 }
1140 return 0;
1141 }
1142 else {
1143 /* a is not completely initilized yet; follow tp_base */
1144 do {
1145 if (a == b)
1146 return 1;
1147 a = a->tp_base;
1148 } while (a != NULL);
1149 return b == &PyBaseObject_Type;
1150 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001151}
1152
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001153/* Internal routines to do a method lookup in the type
Guido van Rossum60718732001-08-28 17:47:51 +00001154 without looking in the instance dictionary
1155 (so we can't use PyObject_GetAttr) but still binding
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001156 it to the instance. The arguments are the object,
Guido van Rossum60718732001-08-28 17:47:51 +00001157 the method name as a C string, and the address of a
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001158 static variable used to cache the interned Python string.
1159
1160 Two variants:
1161
1162 - lookup_maybe() returns NULL without raising an exception
1163 when the _PyType_Lookup() call fails;
1164
1165 - lookup_method() always raises an exception upon errors.
Benjamin Peterson224205f2009-05-08 03:25:19 +00001166
1167 - _PyObject_LookupSpecial() exported for the benefit of other places.
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001168*/
Guido van Rossum60718732001-08-28 17:47:51 +00001169
1170static PyObject *
Benjamin Petersonce798522012-01-22 11:24:29 -05001171lookup_maybe(PyObject *self, _Py_Identifier *attrid)
Guido van Rossum60718732001-08-28 17:47:51 +00001172{
Victor Stinner3c1e4812012-03-26 22:10:51 +02001173 PyObject *res;
Guido van Rossum60718732001-08-28 17:47:51 +00001174
Victor Stinner3c1e4812012-03-26 22:10:51 +02001175 res = _PyType_LookupId(Py_TYPE(self), attrid);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001176 if (res != NULL) {
1177 descrgetfunc f;
1178 if ((f = Py_TYPE(res)->tp_descr_get) == NULL)
1179 Py_INCREF(res);
1180 else
1181 res = f(res, self, (PyObject *)(Py_TYPE(self)));
1182 }
1183 return res;
Guido van Rossum60718732001-08-28 17:47:51 +00001184}
1185
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001186static PyObject *
Benjamin Petersonce798522012-01-22 11:24:29 -05001187lookup_method(PyObject *self, _Py_Identifier *attrid)
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001188{
Benjamin Petersonce798522012-01-22 11:24:29 -05001189 PyObject *res = lookup_maybe(self, attrid);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001190 if (res == NULL && !PyErr_Occurred())
Benjamin Petersonce798522012-01-22 11:24:29 -05001191 PyErr_SetObject(PyExc_AttributeError, attrid->object);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001192 return res;
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001193}
1194
Benjamin Peterson224205f2009-05-08 03:25:19 +00001195PyObject *
Benjamin Petersonce798522012-01-22 11:24:29 -05001196_PyObject_LookupSpecial(PyObject *self, _Py_Identifier *attrid)
Benjamin Peterson224205f2009-05-08 03:25:19 +00001197{
Benjamin Petersonce798522012-01-22 11:24:29 -05001198 return lookup_maybe(self, attrid);
Benjamin Peterson224205f2009-05-08 03:25:19 +00001199}
1200
Guido van Rossum2730b132001-08-28 18:22:14 +00001201/* A variation of PyObject_CallMethod that uses lookup_method()
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001202 instead of PyObject_GetAttrString(). This uses the same convention
Guido van Rossum2730b132001-08-28 18:22:14 +00001203 as lookup_method to cache the interned name string object. */
1204
Neil Schemenauerf23473f2001-10-21 22:28:58 +00001205static PyObject *
Benjamin Petersonce798522012-01-22 11:24:29 -05001206call_method(PyObject *o, _Py_Identifier *nameid, char *format, ...)
Guido van Rossum2730b132001-08-28 18:22:14 +00001207{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001208 va_list va;
1209 PyObject *args, *func = 0, *retval;
1210 va_start(va, format);
Guido van Rossum2730b132001-08-28 18:22:14 +00001211
Benjamin Petersonce798522012-01-22 11:24:29 -05001212 func = lookup_maybe(o, nameid);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001213 if (func == NULL) {
1214 va_end(va);
1215 if (!PyErr_Occurred())
Benjamin Petersonce798522012-01-22 11:24:29 -05001216 PyErr_SetObject(PyExc_AttributeError, nameid->object);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001217 return NULL;
1218 }
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001219
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001220 if (format && *format)
1221 args = Py_VaBuildValue(format, va);
1222 else
1223 args = PyTuple_New(0);
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001224
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001225 va_end(va);
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001226
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001227 if (args == NULL)
1228 return NULL;
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001229
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001230 assert(PyTuple_Check(args));
1231 retval = PyObject_Call(func, args, NULL);
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001232
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001233 Py_DECREF(args);
1234 Py_DECREF(func);
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001235
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001236 return retval;
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001237}
1238
1239/* Clone of call_method() that returns NotImplemented when the lookup fails. */
1240
Neil Schemenauerf23473f2001-10-21 22:28:58 +00001241static PyObject *
Benjamin Petersonce798522012-01-22 11:24:29 -05001242call_maybe(PyObject *o, _Py_Identifier *nameid, char *format, ...)
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001243{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001244 va_list va;
1245 PyObject *args, *func = 0, *retval;
1246 va_start(va, format);
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001247
Benjamin Petersonce798522012-01-22 11:24:29 -05001248 func = lookup_maybe(o, nameid);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001249 if (func == NULL) {
1250 va_end(va);
Brian Curtindfc80e32011-08-10 20:28:54 -05001251 if (!PyErr_Occurred())
1252 Py_RETURN_NOTIMPLEMENTED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001253 return NULL;
1254 }
Guido van Rossum2730b132001-08-28 18:22:14 +00001255
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001256 if (format && *format)
1257 args = Py_VaBuildValue(format, va);
1258 else
1259 args = PyTuple_New(0);
Guido van Rossum2730b132001-08-28 18:22:14 +00001260
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001261 va_end(va);
Guido van Rossum2730b132001-08-28 18:22:14 +00001262
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001263 if (args == NULL)
1264 return NULL;
Guido van Rossum2730b132001-08-28 18:22:14 +00001265
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001266 assert(PyTuple_Check(args));
1267 retval = PyObject_Call(func, args, NULL);
Guido van Rossum2730b132001-08-28 18:22:14 +00001268
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001269 Py_DECREF(args);
1270 Py_DECREF(func);
Guido van Rossum2730b132001-08-28 18:22:14 +00001271
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001272 return retval;
Guido van Rossum2730b132001-08-28 18:22:14 +00001273}
1274
Tim Petersea7f75d2002-12-07 21:39:16 +00001275/*
Guido van Rossum1f121312002-11-14 19:49:16 +00001276 Method resolution order algorithm C3 described in
1277 "A Monotonic Superclass Linearization for Dylan",
1278 by Kim Barrett, Bob Cassel, Paul Haahr,
Tim Petersea7f75d2002-12-07 21:39:16 +00001279 David A. Moon, Keith Playford, and P. Tucker Withington.
Guido van Rossum1f121312002-11-14 19:49:16 +00001280 (OOPSLA 1996)
1281
Guido van Rossum98f33732002-11-25 21:36:54 +00001282 Some notes about the rules implied by C3:
1283
Tim Petersea7f75d2002-12-07 21:39:16 +00001284 No duplicate bases.
Guido van Rossum98f33732002-11-25 21:36:54 +00001285 It isn't legal to repeat a class in a list of base classes.
1286
1287 The next three properties are the 3 constraints in "C3".
1288
Tim Petersea7f75d2002-12-07 21:39:16 +00001289 Local precendece order.
Guido van Rossum98f33732002-11-25 21:36:54 +00001290 If A precedes B in C's MRO, then A will precede B in the MRO of all
1291 subclasses of C.
1292
1293 Monotonicity.
1294 The MRO of a class must be an extension without reordering of the
1295 MRO of each of its superclasses.
1296
1297 Extended Precedence Graph (EPG).
1298 Linearization is consistent if there is a path in the EPG from
1299 each class to all its successors in the linearization. See
1300 the paper for definition of EPG.
Guido van Rossum1f121312002-11-14 19:49:16 +00001301 */
1302
Tim Petersea7f75d2002-12-07 21:39:16 +00001303static int
Guido van Rossum1f121312002-11-14 19:49:16 +00001304tail_contains(PyObject *list, int whence, PyObject *o) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001305 Py_ssize_t j, size;
1306 size = PyList_GET_SIZE(list);
Guido van Rossum1f121312002-11-14 19:49:16 +00001307
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001308 for (j = whence+1; j < size; j++) {
1309 if (PyList_GET_ITEM(list, j) == o)
1310 return 1;
1311 }
1312 return 0;
Guido van Rossum1f121312002-11-14 19:49:16 +00001313}
1314
Guido van Rossum98f33732002-11-25 21:36:54 +00001315static PyObject *
1316class_name(PyObject *cls)
1317{
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001318 PyObject *name = _PyObject_GetAttrId(cls, &PyId___name__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001319 if (name == NULL) {
1320 PyErr_Clear();
1321 Py_XDECREF(name);
1322 name = PyObject_Repr(cls);
1323 }
1324 if (name == NULL)
1325 return NULL;
1326 if (!PyUnicode_Check(name)) {
1327 Py_DECREF(name);
1328 return NULL;
1329 }
1330 return name;
Guido van Rossum98f33732002-11-25 21:36:54 +00001331}
1332
1333static int
1334check_duplicates(PyObject *list)
1335{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001336 Py_ssize_t i, j, n;
1337 /* Let's use a quadratic time algorithm,
1338 assuming that the bases lists is short.
1339 */
1340 n = PyList_GET_SIZE(list);
1341 for (i = 0; i < n; i++) {
1342 PyObject *o = PyList_GET_ITEM(list, i);
1343 for (j = i + 1; j < n; j++) {
1344 if (PyList_GET_ITEM(list, j) == o) {
1345 o = class_name(o);
1346 if (o != NULL) {
1347 PyErr_Format(PyExc_TypeError,
1348 "duplicate base class %U",
1349 o);
1350 Py_DECREF(o);
1351 } else {
1352 PyErr_SetString(PyExc_TypeError,
1353 "duplicate base class");
1354 }
1355 return -1;
1356 }
1357 }
1358 }
1359 return 0;
Guido van Rossum98f33732002-11-25 21:36:54 +00001360}
1361
1362/* Raise a TypeError for an MRO order disagreement.
1363
1364 It's hard to produce a good error message. In the absence of better
1365 insight into error reporting, report the classes that were candidates
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001366 to be put next into the MRO. There is some conflict between the
Guido van Rossum98f33732002-11-25 21:36:54 +00001367 order in which they should be put in the MRO, but it's hard to
1368 diagnose what constraint can't be satisfied.
1369*/
1370
1371static void
1372set_mro_error(PyObject *to_merge, int *remain)
1373{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001374 Py_ssize_t i, n, off, to_merge_size;
1375 char buf[1000];
1376 PyObject *k, *v;
1377 PyObject *set = PyDict_New();
1378 if (!set) return;
Guido van Rossum98f33732002-11-25 21:36:54 +00001379
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001380 to_merge_size = PyList_GET_SIZE(to_merge);
1381 for (i = 0; i < to_merge_size; i++) {
1382 PyObject *L = PyList_GET_ITEM(to_merge, i);
1383 if (remain[i] < PyList_GET_SIZE(L)) {
1384 PyObject *c = PyList_GET_ITEM(L, remain[i]);
1385 if (PyDict_SetItem(set, c, Py_None) < 0) {
1386 Py_DECREF(set);
1387 return;
1388 }
1389 }
1390 }
1391 n = PyDict_Size(set);
Guido van Rossum98f33732002-11-25 21:36:54 +00001392
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001393 off = PyOS_snprintf(buf, sizeof(buf), "Cannot create a \
Raymond Hettingerf394df42003-04-06 19:13:41 +00001394consistent method resolution\norder (MRO) for bases");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001395 i = 0;
1396 while (PyDict_Next(set, &i, &k, &v) && (size_t)off < sizeof(buf)) {
1397 PyObject *name = class_name(k);
Victor Stinnere5f99f32010-05-19 01:42:46 +00001398 char *name_str;
1399 if (name != NULL) {
1400 name_str = _PyUnicode_AsString(name);
1401 if (name_str == NULL)
Victor Stinnerba644a62010-05-19 01:50:45 +00001402 name_str = "?";
Victor Stinnere5f99f32010-05-19 01:42:46 +00001403 } else
Victor Stinnerba644a62010-05-19 01:50:45 +00001404 name_str = "?";
Victor Stinnere5f99f32010-05-19 01:42:46 +00001405 off += PyOS_snprintf(buf + off, sizeof(buf) - off, " %s", name_str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001406 Py_XDECREF(name);
1407 if (--n && (size_t)(off+1) < sizeof(buf)) {
1408 buf[off++] = ',';
1409 buf[off] = '\0';
1410 }
1411 }
1412 PyErr_SetString(PyExc_TypeError, buf);
1413 Py_DECREF(set);
Guido van Rossum98f33732002-11-25 21:36:54 +00001414}
1415
Tim Petersea7f75d2002-12-07 21:39:16 +00001416static int
Guido van Rossum1f121312002-11-14 19:49:16 +00001417pmerge(PyObject *acc, PyObject* to_merge) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001418 Py_ssize_t i, j, to_merge_size, empty_cnt;
1419 int *remain;
1420 int ok;
Tim Petersea7f75d2002-12-07 21:39:16 +00001421
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001422 to_merge_size = PyList_GET_SIZE(to_merge);
Guido van Rossum1f121312002-11-14 19:49:16 +00001423
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001424 /* remain stores an index into each sublist of to_merge.
1425 remain[i] is the index of the next base in to_merge[i]
1426 that is not included in acc.
1427 */
1428 remain = (int *)PyMem_MALLOC(SIZEOF_INT*to_merge_size);
1429 if (remain == NULL)
1430 return -1;
1431 for (i = 0; i < to_merge_size; i++)
1432 remain[i] = 0;
Guido van Rossum1f121312002-11-14 19:49:16 +00001433
1434 again:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001435 empty_cnt = 0;
1436 for (i = 0; i < to_merge_size; i++) {
1437 PyObject *candidate;
Tim Petersea7f75d2002-12-07 21:39:16 +00001438
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001439 PyObject *cur_list = PyList_GET_ITEM(to_merge, i);
Guido van Rossum1f121312002-11-14 19:49:16 +00001440
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001441 if (remain[i] >= PyList_GET_SIZE(cur_list)) {
1442 empty_cnt++;
1443 continue;
1444 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001445
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001446 /* Choose next candidate for MRO.
Guido van Rossum98f33732002-11-25 21:36:54 +00001447
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001448 The input sequences alone can determine the choice.
1449 If not, choose the class which appears in the MRO
1450 of the earliest direct superclass of the new class.
1451 */
Guido van Rossum98f33732002-11-25 21:36:54 +00001452
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001453 candidate = PyList_GET_ITEM(cur_list, remain[i]);
1454 for (j = 0; j < to_merge_size; j++) {
1455 PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
1456 if (tail_contains(j_lst, remain[j], candidate)) {
1457 goto skip; /* continue outer loop */
1458 }
1459 }
1460 ok = PyList_Append(acc, candidate);
1461 if (ok < 0) {
1462 PyMem_Free(remain);
1463 return -1;
1464 }
1465 for (j = 0; j < to_merge_size; j++) {
1466 PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
1467 if (remain[j] < PyList_GET_SIZE(j_lst) &&
1468 PyList_GET_ITEM(j_lst, remain[j]) == candidate) {
1469 remain[j]++;
1470 }
1471 }
1472 goto again;
1473 skip: ;
1474 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001475
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001476 if (empty_cnt == to_merge_size) {
1477 PyMem_FREE(remain);
1478 return 0;
1479 }
1480 set_mro_error(to_merge, remain);
1481 PyMem_FREE(remain);
1482 return -1;
Guido van Rossum1f121312002-11-14 19:49:16 +00001483}
1484
Tim Peters6d6c1a32001-08-02 04:15:00 +00001485static PyObject *
1486mro_implementation(PyTypeObject *type)
1487{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001488 Py_ssize_t i, n;
1489 int ok;
1490 PyObject *bases, *result;
1491 PyObject *to_merge, *bases_aslist;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001492
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001493 if (type->tp_dict == NULL) {
1494 if (PyType_Ready(type) < 0)
1495 return NULL;
1496 }
Guido van Rossum63517572002-06-18 16:44:57 +00001497
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001498 /* Find a superclass linearization that honors the constraints
1499 of the explicit lists of bases and the constraints implied by
1500 each base class.
Guido van Rossum98f33732002-11-25 21:36:54 +00001501
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001502 to_merge is a list of lists, where each list is a superclass
1503 linearization implied by a base class. The last element of
1504 to_merge is the declared list of bases.
1505 */
Guido van Rossum98f33732002-11-25 21:36:54 +00001506
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001507 bases = type->tp_bases;
1508 n = PyTuple_GET_SIZE(bases);
Guido van Rossum1f121312002-11-14 19:49:16 +00001509
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001510 to_merge = PyList_New(n+1);
1511 if (to_merge == NULL)
1512 return NULL;
Guido van Rossum1f121312002-11-14 19:49:16 +00001513
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001514 for (i = 0; i < n; i++) {
1515 PyObject *base = PyTuple_GET_ITEM(bases, i);
1516 PyObject *parentMRO;
1517 parentMRO = PySequence_List(((PyTypeObject*)base)->tp_mro);
1518 if (parentMRO == NULL) {
1519 Py_DECREF(to_merge);
1520 return NULL;
1521 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001522
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001523 PyList_SET_ITEM(to_merge, i, parentMRO);
1524 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001525
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001526 bases_aslist = PySequence_List(bases);
1527 if (bases_aslist == NULL) {
1528 Py_DECREF(to_merge);
1529 return NULL;
1530 }
1531 /* This is just a basic sanity check. */
1532 if (check_duplicates(bases_aslist) < 0) {
1533 Py_DECREF(to_merge);
1534 Py_DECREF(bases_aslist);
1535 return NULL;
1536 }
1537 PyList_SET_ITEM(to_merge, n, bases_aslist);
Guido van Rossum1f121312002-11-14 19:49:16 +00001538
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001539 result = Py_BuildValue("[O]", (PyObject *)type);
1540 if (result == NULL) {
1541 Py_DECREF(to_merge);
1542 return NULL;
1543 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001544
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001545 ok = pmerge(result, to_merge);
1546 Py_DECREF(to_merge);
1547 if (ok < 0) {
1548 Py_DECREF(result);
1549 return NULL;
1550 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001551
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001552 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001553}
1554
1555static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001556mro_external(PyObject *self)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001557{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001558 PyTypeObject *type = (PyTypeObject *)self;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001559
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001560 return mro_implementation(type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001561}
1562
1563static int
1564mro_internal(PyTypeObject *type)
1565{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001566 PyObject *mro, *result, *tuple;
1567 int checkit = 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001568
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001569 if (Py_TYPE(type) == &PyType_Type) {
1570 result = mro_implementation(type);
1571 }
1572 else {
Benjamin Petersonce798522012-01-22 11:24:29 -05001573 _Py_IDENTIFIER(mro);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001574 checkit = 1;
Benjamin Petersonce798522012-01-22 11:24:29 -05001575 mro = lookup_method((PyObject *)type, &PyId_mro);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001576 if (mro == NULL)
1577 return -1;
1578 result = PyObject_CallObject(mro, NULL);
1579 Py_DECREF(mro);
1580 }
1581 if (result == NULL)
1582 return -1;
1583 tuple = PySequence_Tuple(result);
1584 Py_DECREF(result);
1585 if (tuple == NULL)
1586 return -1;
1587 if (checkit) {
1588 Py_ssize_t i, len;
1589 PyObject *cls;
1590 PyTypeObject *solid;
Armin Rigo037d1e02005-12-29 17:07:39 +00001591
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001592 solid = solid_base(type);
Armin Rigo037d1e02005-12-29 17:07:39 +00001593
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001594 len = PyTuple_GET_SIZE(tuple);
Armin Rigo037d1e02005-12-29 17:07:39 +00001595
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001596 for (i = 0; i < len; i++) {
1597 PyTypeObject *t;
1598 cls = PyTuple_GET_ITEM(tuple, i);
1599 if (!PyType_Check(cls)) {
1600 PyErr_Format(PyExc_TypeError,
1601 "mro() returned a non-class ('%.500s')",
1602 Py_TYPE(cls)->tp_name);
1603 Py_DECREF(tuple);
1604 return -1;
1605 }
1606 t = (PyTypeObject*)cls;
1607 if (!PyType_IsSubtype(solid, solid_base(t))) {
1608 PyErr_Format(PyExc_TypeError,
1609 "mro() returned base with unsuitable layout ('%.500s')",
1610 t->tp_name);
1611 Py_DECREF(tuple);
1612 return -1;
1613 }
1614 }
1615 }
1616 type->tp_mro = tuple;
Christian Heimesa62da1d2008-01-12 19:39:10 +00001617
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001618 type_mro_modified(type, type->tp_mro);
Florent Xiclunaaa6c1d22011-12-12 18:54:29 +01001619 /* corner case: the super class might have been hidden
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001620 from the custom MRO */
1621 type_mro_modified(type, type->tp_bases);
Christian Heimesa62da1d2008-01-12 19:39:10 +00001622
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001623 PyType_Modified(type);
Christian Heimesa62da1d2008-01-12 19:39:10 +00001624
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001625 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001626}
1627
1628
1629/* Calculate the best base amongst multiple base classes.
1630 This is the first one that's on the path to the "solid base". */
1631
1632static PyTypeObject *
1633best_base(PyObject *bases)
1634{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001635 Py_ssize_t i, n;
1636 PyTypeObject *base, *winner, *candidate, *base_i;
1637 PyObject *base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001638
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001639 assert(PyTuple_Check(bases));
1640 n = PyTuple_GET_SIZE(bases);
1641 assert(n > 0);
1642 base = NULL;
1643 winner = NULL;
1644 for (i = 0; i < n; i++) {
1645 base_proto = PyTuple_GET_ITEM(bases, i);
1646 if (!PyType_Check(base_proto)) {
1647 PyErr_SetString(
1648 PyExc_TypeError,
1649 "bases must be types");
1650 return NULL;
1651 }
1652 base_i = (PyTypeObject *)base_proto;
1653 if (base_i->tp_dict == NULL) {
1654 if (PyType_Ready(base_i) < 0)
1655 return NULL;
1656 }
1657 candidate = solid_base(base_i);
1658 if (winner == NULL) {
1659 winner = candidate;
1660 base = base_i;
1661 }
1662 else if (PyType_IsSubtype(winner, candidate))
1663 ;
1664 else if (PyType_IsSubtype(candidate, winner)) {
1665 winner = candidate;
1666 base = base_i;
1667 }
1668 else {
1669 PyErr_SetString(
1670 PyExc_TypeError,
1671 "multiple bases have "
1672 "instance lay-out conflict");
1673 return NULL;
1674 }
1675 }
Florent Xiclunaaa6c1d22011-12-12 18:54:29 +01001676 assert (base != NULL);
1677
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001678 return base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001679}
1680
1681static int
1682extra_ivars(PyTypeObject *type, PyTypeObject *base)
1683{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001684 size_t t_size = type->tp_basicsize;
1685 size_t b_size = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001686
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001687 assert(t_size >= b_size); /* Else type smaller than base! */
1688 if (type->tp_itemsize || base->tp_itemsize) {
1689 /* If itemsize is involved, stricter rules */
1690 return t_size != b_size ||
1691 type->tp_itemsize != base->tp_itemsize;
1692 }
1693 if (type->tp_weaklistoffset && base->tp_weaklistoffset == 0 &&
1694 type->tp_weaklistoffset + sizeof(PyObject *) == t_size &&
1695 type->tp_flags & Py_TPFLAGS_HEAPTYPE)
1696 t_size -= sizeof(PyObject *);
1697 if (type->tp_dictoffset && base->tp_dictoffset == 0 &&
1698 type->tp_dictoffset + sizeof(PyObject *) == t_size &&
1699 type->tp_flags & Py_TPFLAGS_HEAPTYPE)
1700 t_size -= sizeof(PyObject *);
Guido van Rossum9676b222001-08-17 20:32:36 +00001701
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001702 return t_size != b_size;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001703}
1704
1705static PyTypeObject *
1706solid_base(PyTypeObject *type)
1707{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001708 PyTypeObject *base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001709
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001710 if (type->tp_base)
1711 base = solid_base(type->tp_base);
1712 else
1713 base = &PyBaseObject_Type;
1714 if (extra_ivars(type, base))
1715 return type;
1716 else
1717 return base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001718}
1719
Jeremy Hylton938ace62002-07-17 16:30:39 +00001720static void object_dealloc(PyObject *);
1721static int object_init(PyObject *, PyObject *, PyObject *);
1722static int update_slot(PyTypeObject *, PyObject *);
1723static void fixup_slot_dispatchers(PyTypeObject *);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001724
Guido van Rossum360e4b82007-05-14 22:51:27 +00001725/*
1726 * Helpers for __dict__ descriptor. We don't want to expose the dicts
1727 * inherited from various builtin types. The builtin base usually provides
1728 * its own __dict__ descriptor, so we use that when we can.
1729 */
1730static PyTypeObject *
1731get_builtin_base_with_dict(PyTypeObject *type)
1732{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001733 while (type->tp_base != NULL) {
1734 if (type->tp_dictoffset != 0 &&
1735 !(type->tp_flags & Py_TPFLAGS_HEAPTYPE))
1736 return type;
1737 type = type->tp_base;
1738 }
1739 return NULL;
Guido van Rossum360e4b82007-05-14 22:51:27 +00001740}
1741
1742static PyObject *
1743get_dict_descriptor(PyTypeObject *type)
1744{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001745 PyObject *descr;
Guido van Rossum360e4b82007-05-14 22:51:27 +00001746
Victor Stinner3c1e4812012-03-26 22:10:51 +02001747 descr = _PyType_LookupId(type, &PyId___dict__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001748 if (descr == NULL || !PyDescr_IsData(descr))
1749 return NULL;
Guido van Rossum360e4b82007-05-14 22:51:27 +00001750
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001751 return descr;
Guido van Rossum360e4b82007-05-14 22:51:27 +00001752}
1753
1754static void
1755raise_dict_descr_error(PyObject *obj)
1756{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001757 PyErr_Format(PyExc_TypeError,
1758 "this __dict__ descriptor does not support "
1759 "'%.200s' objects", Py_TYPE(obj)->tp_name);
Guido van Rossum360e4b82007-05-14 22:51:27 +00001760}
1761
Tim Peters6d6c1a32001-08-02 04:15:00 +00001762static PyObject *
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001763subtype_dict(PyObject *obj, void *context)
1764{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001765 PyTypeObject *base;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001766
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001767 base = get_builtin_base_with_dict(Py_TYPE(obj));
1768 if (base != NULL) {
1769 descrgetfunc func;
1770 PyObject *descr = get_dict_descriptor(base);
1771 if (descr == NULL) {
1772 raise_dict_descr_error(obj);
1773 return NULL;
1774 }
1775 func = Py_TYPE(descr)->tp_descr_get;
1776 if (func == NULL) {
1777 raise_dict_descr_error(obj);
1778 return NULL;
1779 }
1780 return func(descr, obj, (PyObject *)(Py_TYPE(obj)));
1781 }
Benjamin Peterson8eb12692012-02-19 19:59:10 -05001782 return PyObject_GenericGetDict(obj, context);
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001783}
1784
Guido van Rossum6661be32001-10-26 04:26:12 +00001785static int
1786subtype_setdict(PyObject *obj, PyObject *value, void *context)
1787{
Benjamin Peterson8eb12692012-02-19 19:59:10 -05001788 PyObject *dict, **dictptr;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001789 PyTypeObject *base;
Guido van Rossum6661be32001-10-26 04:26:12 +00001790
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001791 base = get_builtin_base_with_dict(Py_TYPE(obj));
1792 if (base != NULL) {
1793 descrsetfunc func;
1794 PyObject *descr = get_dict_descriptor(base);
1795 if (descr == NULL) {
1796 raise_dict_descr_error(obj);
1797 return -1;
1798 }
1799 func = Py_TYPE(descr)->tp_descr_set;
1800 if (func == NULL) {
1801 raise_dict_descr_error(obj);
1802 return -1;
1803 }
1804 return func(descr, obj, value);
1805 }
Benjamin Peterson8eb12692012-02-19 19:59:10 -05001806 /* Almost like PyObject_GenericSetDict, but allow __dict__ to be deleted. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001807 dictptr = _PyObject_GetDictPtr(obj);
1808 if (dictptr == NULL) {
1809 PyErr_SetString(PyExc_AttributeError,
1810 "This object has no __dict__");
1811 return -1;
1812 }
Benjamin Peterson006c5a22012-02-19 20:36:12 -05001813 if (value != NULL && !PyDict_Check(value)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001814 PyErr_Format(PyExc_TypeError,
1815 "__dict__ must be set to a dictionary, "
1816 "not a '%.200s'", Py_TYPE(value)->tp_name);
1817 return -1;
1818 }
1819 dict = *dictptr;
1820 Py_XINCREF(value);
1821 *dictptr = value;
1822 Py_XDECREF(dict);
1823 return 0;
Guido van Rossum6661be32001-10-26 04:26:12 +00001824}
1825
Guido van Rossumad47da02002-08-12 19:05:44 +00001826static PyObject *
1827subtype_getweakref(PyObject *obj, void *context)
1828{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001829 PyObject **weaklistptr;
1830 PyObject *result;
Guido van Rossumad47da02002-08-12 19:05:44 +00001831
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001832 if (Py_TYPE(obj)->tp_weaklistoffset == 0) {
1833 PyErr_SetString(PyExc_AttributeError,
1834 "This object has no __weakref__");
1835 return NULL;
1836 }
1837 assert(Py_TYPE(obj)->tp_weaklistoffset > 0);
1838 assert(Py_TYPE(obj)->tp_weaklistoffset + sizeof(PyObject *) <=
1839 (size_t)(Py_TYPE(obj)->tp_basicsize));
1840 weaklistptr = (PyObject **)
1841 ((char *)obj + Py_TYPE(obj)->tp_weaklistoffset);
1842 if (*weaklistptr == NULL)
1843 result = Py_None;
1844 else
1845 result = *weaklistptr;
1846 Py_INCREF(result);
1847 return result;
Guido van Rossumad47da02002-08-12 19:05:44 +00001848}
1849
Guido van Rossum373c7412003-01-07 13:41:37 +00001850/* Three variants on the subtype_getsets list. */
1851
1852static PyGetSetDef subtype_getsets_full[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001853 {"__dict__", subtype_dict, subtype_setdict,
1854 PyDoc_STR("dictionary for instance variables (if defined)")},
1855 {"__weakref__", subtype_getweakref, NULL,
1856 PyDoc_STR("list of weak references to the object (if defined)")},
1857 {0}
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001858};
1859
Guido van Rossum373c7412003-01-07 13:41:37 +00001860static PyGetSetDef subtype_getsets_dict_only[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001861 {"__dict__", subtype_dict, subtype_setdict,
1862 PyDoc_STR("dictionary for instance variables (if defined)")},
1863 {0}
Guido van Rossum373c7412003-01-07 13:41:37 +00001864};
1865
1866static PyGetSetDef subtype_getsets_weakref_only[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001867 {"__weakref__", subtype_getweakref, NULL,
1868 PyDoc_STR("list of weak references to the object (if defined)")},
1869 {0}
Guido van Rossum373c7412003-01-07 13:41:37 +00001870};
1871
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001872static int
1873valid_identifier(PyObject *s)
1874{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001875 if (!PyUnicode_Check(s)) {
1876 PyErr_Format(PyExc_TypeError,
1877 "__slots__ items must be strings, not '%.200s'",
1878 Py_TYPE(s)->tp_name);
1879 return 0;
1880 }
1881 if (!PyUnicode_IsIdentifier(s)) {
1882 PyErr_SetString(PyExc_TypeError,
1883 "__slots__ must be identifiers");
1884 return 0;
1885 }
1886 return 1;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001887}
1888
Guido van Rossumd8faa362007-04-27 19:54:29 +00001889/* Forward */
1890static int
1891object_init(PyObject *self, PyObject *args, PyObject *kwds);
1892
1893static int
1894type_init(PyObject *cls, PyObject *args, PyObject *kwds)
1895{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001896 int res;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001897
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001898 assert(args != NULL && PyTuple_Check(args));
1899 assert(kwds == NULL || PyDict_Check(kwds));
Guido van Rossumd8faa362007-04-27 19:54:29 +00001900
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001901 if (kwds != NULL && PyDict_Check(kwds) && PyDict_Size(kwds) != 0) {
1902 PyErr_SetString(PyExc_TypeError,
1903 "type.__init__() takes no keyword arguments");
1904 return -1;
1905 }
Guido van Rossumd8faa362007-04-27 19:54:29 +00001906
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001907 if (args != NULL && PyTuple_Check(args) &&
1908 (PyTuple_GET_SIZE(args) != 1 && PyTuple_GET_SIZE(args) != 3)) {
1909 PyErr_SetString(PyExc_TypeError,
1910 "type.__init__() takes 1 or 3 arguments");
1911 return -1;
1912 }
Guido van Rossumd8faa362007-04-27 19:54:29 +00001913
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001914 /* Call object.__init__(self) now. */
1915 /* XXX Could call super(type, cls).__init__() but what's the point? */
1916 args = PyTuple_GetSlice(args, 0, 0);
1917 res = object_init(cls, args, NULL);
1918 Py_DECREF(args);
1919 return res;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001920}
1921
Martin v. Löwis738236d2011-02-05 20:35:29 +00001922long
1923PyType_GetFlags(PyTypeObject *type)
1924{
1925 return type->tp_flags;
1926}
1927
Nick Coghlande31b192011-10-23 22:04:16 +10001928/* Determine the most derived metatype. */
1929PyTypeObject *
1930_PyType_CalculateMetaclass(PyTypeObject *metatype, PyObject *bases)
1931{
1932 Py_ssize_t i, nbases;
1933 PyTypeObject *winner;
1934 PyObject *tmp;
1935 PyTypeObject *tmptype;
1936
1937 /* Determine the proper metatype to deal with this,
1938 and check for metatype conflicts while we're at it.
1939 Note that if some other metatype wins to contract,
1940 it's possible that its instances are not types. */
1941
1942 nbases = PyTuple_GET_SIZE(bases);
1943 winner = metatype;
1944 for (i = 0; i < nbases; i++) {
1945 tmp = PyTuple_GET_ITEM(bases, i);
1946 tmptype = Py_TYPE(tmp);
1947 if (PyType_IsSubtype(winner, tmptype))
1948 continue;
1949 if (PyType_IsSubtype(tmptype, winner)) {
1950 winner = tmptype;
1951 continue;
1952 }
1953 /* else: */
1954 PyErr_SetString(PyExc_TypeError,
1955 "metaclass conflict: "
1956 "the metaclass of a derived class "
1957 "must be a (non-strict) subclass "
1958 "of the metaclasses of all its bases");
1959 return NULL;
1960 }
1961 return winner;
1962}
1963
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001964static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00001965type_new(PyTypeObject *metatype, PyObject *args, PyObject *kwds)
1966{
Victor Stinner6f738742012-02-25 01:22:36 +01001967 PyObject *name, *bases = NULL, *orig_dict, *dict = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001968 static char *kwlist[] = {"name", "bases", "dict", 0};
Victor Stinner6f738742012-02-25 01:22:36 +01001969 PyObject *qualname, *slots = NULL, *tmp, *newslots;
1970 PyTypeObject *type = NULL, *base, *tmptype, *winner;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001971 PyHeapTypeObject *et;
1972 PyMemberDef *mp;
1973 Py_ssize_t i, nbases, nslots, slotoffset, add_dict, add_weak;
1974 int j, may_add_dict, may_add_weak;
Victor Stinner3c1e4812012-03-26 22:10:51 +02001975 _Py_IDENTIFIER(__qualname__);
1976 _Py_IDENTIFIER(__slots__);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001977
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001978 assert(args != NULL && PyTuple_Check(args));
1979 assert(kwds == NULL || PyDict_Check(kwds));
Tim Peters3abca122001-10-27 19:37:48 +00001980
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001981 /* Special case: type(x) should return x->ob_type */
1982 {
1983 const Py_ssize_t nargs = PyTuple_GET_SIZE(args);
1984 const Py_ssize_t nkwds = kwds == NULL ? 0 : PyDict_Size(kwds);
Tim Peters3abca122001-10-27 19:37:48 +00001985
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001986 if (PyType_CheckExact(metatype) && nargs == 1 && nkwds == 0) {
1987 PyObject *x = PyTuple_GET_ITEM(args, 0);
1988 Py_INCREF(Py_TYPE(x));
1989 return (PyObject *) Py_TYPE(x);
1990 }
Tim Peters3abca122001-10-27 19:37:48 +00001991
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001992 /* SF bug 475327 -- if that didn't trigger, we need 3
1993 arguments. but PyArg_ParseTupleAndKeywords below may give
1994 a msg saying type() needs exactly 3. */
1995 if (nargs + nkwds != 3) {
1996 PyErr_SetString(PyExc_TypeError,
1997 "type() takes 1 or 3 arguments");
1998 return NULL;
1999 }
2000 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002001
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002002 /* Check arguments: (name, bases, dict) */
2003 if (!PyArg_ParseTupleAndKeywords(args, kwds, "UO!O!:type", kwlist,
2004 &name,
2005 &PyTuple_Type, &bases,
Victor Stinner6f738742012-02-25 01:22:36 +01002006 &PyDict_Type, &orig_dict))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002007 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002008
Nick Coghlande31b192011-10-23 22:04:16 +10002009 /* Determine the proper metatype to deal with this: */
2010 winner = _PyType_CalculateMetaclass(metatype, bases);
2011 if (winner == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002012 return NULL;
2013 }
Nick Coghlande31b192011-10-23 22:04:16 +10002014
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002015 if (winner != metatype) {
2016 if (winner->tp_new != type_new) /* Pass it to the winner */
2017 return winner->tp_new(winner, args, kwds);
2018 metatype = winner;
2019 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002020
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002021 /* Adjust for empty tuple bases */
Nick Coghlande31b192011-10-23 22:04:16 +10002022 nbases = PyTuple_GET_SIZE(bases);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002023 if (nbases == 0) {
2024 bases = PyTuple_Pack(1, &PyBaseObject_Type);
2025 if (bases == NULL)
Victor Stinner6f738742012-02-25 01:22:36 +01002026 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002027 nbases = 1;
2028 }
2029 else
2030 Py_INCREF(bases);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002031
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002032 /* Calculate best base, and check that all bases are type objects */
2033 base = best_base(bases);
2034 if (base == NULL) {
Victor Stinner6f738742012-02-25 01:22:36 +01002035 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002036 }
2037 if (!PyType_HasFeature(base, Py_TPFLAGS_BASETYPE)) {
2038 PyErr_Format(PyExc_TypeError,
2039 "type '%.100s' is not an acceptable base type",
2040 base->tp_name);
Victor Stinner6f738742012-02-25 01:22:36 +01002041 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002042 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002043
Victor Stinner6f738742012-02-25 01:22:36 +01002044 dict = PyDict_Copy(orig_dict);
2045 if (dict == NULL)
2046 goto error;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002047
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002048 /* Check for a __slots__ sequence variable in dict, and count it */
Victor Stinner3c1e4812012-03-26 22:10:51 +02002049 slots = _PyDict_GetItemId(dict, &PyId___slots__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002050 nslots = 0;
2051 add_dict = 0;
2052 add_weak = 0;
2053 may_add_dict = base->tp_dictoffset == 0;
2054 may_add_weak = base->tp_weaklistoffset == 0 && base->tp_itemsize == 0;
2055 if (slots == NULL) {
2056 if (may_add_dict) {
2057 add_dict++;
2058 }
2059 if (may_add_weak) {
2060 add_weak++;
2061 }
2062 }
2063 else {
2064 /* Have slots */
Guido van Rossumad47da02002-08-12 19:05:44 +00002065
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002066 /* Make it into a tuple */
2067 if (PyUnicode_Check(slots))
2068 slots = PyTuple_Pack(1, slots);
2069 else
2070 slots = PySequence_Tuple(slots);
Victor Stinner6f738742012-02-25 01:22:36 +01002071 if (slots == NULL)
2072 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002073 assert(PyTuple_Check(slots));
Guido van Rossumad47da02002-08-12 19:05:44 +00002074
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002075 /* Are slots allowed? */
2076 nslots = PyTuple_GET_SIZE(slots);
2077 if (nslots > 0 && base->tp_itemsize != 0) {
2078 PyErr_Format(PyExc_TypeError,
2079 "nonempty __slots__ "
2080 "not supported for subtype of '%s'",
2081 base->tp_name);
Victor Stinner6f738742012-02-25 01:22:36 +01002082 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002083 }
Guido van Rossumad47da02002-08-12 19:05:44 +00002084
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002085 /* Check for valid slot names and two special cases */
2086 for (i = 0; i < nslots; i++) {
2087 PyObject *tmp = PyTuple_GET_ITEM(slots, i);
2088 if (!valid_identifier(tmp))
Victor Stinner6f738742012-02-25 01:22:36 +01002089 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002090 assert(PyUnicode_Check(tmp));
2091 if (PyUnicode_CompareWithASCIIString(tmp, "__dict__") == 0) {
2092 if (!may_add_dict || add_dict) {
2093 PyErr_SetString(PyExc_TypeError,
2094 "__dict__ slot disallowed: "
2095 "we already got one");
Victor Stinner6f738742012-02-25 01:22:36 +01002096 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002097 }
2098 add_dict++;
2099 }
2100 if (PyUnicode_CompareWithASCIIString(tmp, "__weakref__") == 0) {
2101 if (!may_add_weak || add_weak) {
2102 PyErr_SetString(PyExc_TypeError,
2103 "__weakref__ slot disallowed: "
2104 "either we already got one, "
2105 "or __itemsize__ != 0");
Victor Stinner6f738742012-02-25 01:22:36 +01002106 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002107 }
2108 add_weak++;
2109 }
2110 }
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00002111
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002112 /* Copy slots into a list, mangle names and sort them.
2113 Sorted names are needed for __class__ assignment.
2114 Convert them back to tuple at the end.
2115 */
2116 newslots = PyList_New(nslots - add_dict - add_weak);
2117 if (newslots == NULL)
Victor Stinner6f738742012-02-25 01:22:36 +01002118 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002119 for (i = j = 0; i < nslots; i++) {
2120 tmp = PyTuple_GET_ITEM(slots, i);
2121 if ((add_dict &&
2122 PyUnicode_CompareWithASCIIString(tmp, "__dict__") == 0) ||
2123 (add_weak &&
2124 PyUnicode_CompareWithASCIIString(tmp, "__weakref__") == 0))
2125 continue;
2126 tmp =_Py_Mangle(name, tmp);
Benjamin Petersonae13c882011-08-16 22:26:48 -05002127 if (!tmp) {
2128 Py_DECREF(newslots);
Victor Stinner6f738742012-02-25 01:22:36 +01002129 goto error;
Benjamin Petersonae13c882011-08-16 22:26:48 -05002130 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002131 PyList_SET_ITEM(newslots, j, tmp);
Benjamin Petersonc4085c82011-08-16 18:53:26 -05002132 if (PyDict_GetItem(dict, tmp)) {
2133 PyErr_Format(PyExc_ValueError,
2134 "%R in __slots__ conflicts with class variable",
2135 tmp);
Benjamin Petersond17cefc2011-08-16 22:28:23 -05002136 Py_DECREF(newslots);
Victor Stinner6f738742012-02-25 01:22:36 +01002137 goto error;
Benjamin Petersonc4085c82011-08-16 18:53:26 -05002138 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002139 j++;
2140 }
2141 assert(j == nslots - add_dict - add_weak);
2142 nslots = j;
Victor Stinner6f738742012-02-25 01:22:36 +01002143 Py_CLEAR(slots);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002144 if (PyList_Sort(newslots) == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002145 Py_DECREF(newslots);
Victor Stinner6f738742012-02-25 01:22:36 +01002146 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002147 }
2148 slots = PyList_AsTuple(newslots);
2149 Py_DECREF(newslots);
Victor Stinner6f738742012-02-25 01:22:36 +01002150 if (slots == NULL)
2151 goto error;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00002152
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002153 /* Secondary bases may provide weakrefs or dict */
2154 if (nbases > 1 &&
2155 ((may_add_dict && !add_dict) ||
2156 (may_add_weak && !add_weak))) {
2157 for (i = 0; i < nbases; i++) {
2158 tmp = PyTuple_GET_ITEM(bases, i);
2159 if (tmp == (PyObject *)base)
2160 continue; /* Skip primary base */
2161 assert(PyType_Check(tmp));
2162 tmptype = (PyTypeObject *)tmp;
2163 if (may_add_dict && !add_dict &&
2164 tmptype->tp_dictoffset != 0)
2165 add_dict++;
2166 if (may_add_weak && !add_weak &&
2167 tmptype->tp_weaklistoffset != 0)
2168 add_weak++;
2169 if (may_add_dict && !add_dict)
2170 continue;
2171 if (may_add_weak && !add_weak)
2172 continue;
2173 /* Nothing more to check */
2174 break;
2175 }
2176 }
2177 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002178
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002179 /* Allocate the type object */
2180 type = (PyTypeObject *)metatype->tp_alloc(metatype, nslots);
Victor Stinner6f738742012-02-25 01:22:36 +01002181 if (type == NULL)
2182 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002183
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002184 /* Keep name and slots alive in the extended type object */
2185 et = (PyHeapTypeObject *)type;
2186 Py_INCREF(name);
2187 et->ht_name = name;
2188 et->ht_slots = slots;
Victor Stinner6f738742012-02-25 01:22:36 +01002189 slots = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002190
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002191 /* Initialize tp_flags */
2192 type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE |
2193 Py_TPFLAGS_BASETYPE;
2194 if (base->tp_flags & Py_TPFLAGS_HAVE_GC)
2195 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossumdc91b992001-08-08 22:26:22 +00002196
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002197 /* Initialize essential fields */
2198 type->tp_as_number = &et->as_number;
2199 type->tp_as_sequence = &et->as_sequence;
2200 type->tp_as_mapping = &et->as_mapping;
2201 type->tp_as_buffer = &et->as_buffer;
2202 type->tp_name = _PyUnicode_AsString(name);
Victor Stinner6f738742012-02-25 01:22:36 +01002203 if (!type->tp_name)
2204 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002205
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002206 /* Set tp_base and tp_bases */
2207 type->tp_bases = bases;
Victor Stinner6f738742012-02-25 01:22:36 +01002208 bases = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002209 Py_INCREF(base);
2210 type->tp_base = base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002211
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002212 /* Initialize tp_dict from passed-in dict */
Victor Stinner6f738742012-02-25 01:22:36 +01002213 Py_INCREF(dict);
2214 type->tp_dict = dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002215
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002216 /* Set __module__ in the dict */
Victor Stinner3c1e4812012-03-26 22:10:51 +02002217 if (_PyDict_GetItemId(dict, &PyId___module__) == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002218 tmp = PyEval_GetGlobals();
2219 if (tmp != NULL) {
Victor Stinner3c1e4812012-03-26 22:10:51 +02002220 tmp = _PyDict_GetItemId(tmp, &PyId___name__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002221 if (tmp != NULL) {
Victor Stinner3c1e4812012-03-26 22:10:51 +02002222 if (_PyDict_SetItemId(dict, &PyId___module__,
2223 tmp) < 0)
Victor Stinner6f738742012-02-25 01:22:36 +01002224 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002225 }
2226 }
2227 }
Guido van Rossumc3542212001-08-16 09:18:56 +00002228
Victor Stinner6f738742012-02-25 01:22:36 +01002229 /* Set ht_qualname to dict['__qualname__'] if available, else to
2230 __name__. The __qualname__ accessor will look for ht_qualname.
2231 */
Victor Stinner3c1e4812012-03-26 22:10:51 +02002232 qualname = _PyDict_GetItemId(dict, &PyId___qualname__);
Victor Stinner6f738742012-02-25 01:22:36 +01002233 if (qualname != NULL) {
2234 if (!PyUnicode_Check(qualname)) {
2235 PyErr_Format(PyExc_TypeError,
2236 "type __qualname__ must be a str, not %s",
2237 Py_TYPE(qualname)->tp_name);
2238 goto error;
2239 }
2240 }
2241 else {
2242 qualname = et->ht_name;
2243 }
2244 Py_INCREF(qualname);
2245 et->ht_qualname = qualname;
2246
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002247 /* Set tp_doc to a copy of dict['__doc__'], if the latter is there
2248 and is a string. The __doc__ accessor will first look for tp_doc;
2249 if that fails, it will still look into __dict__.
2250 */
2251 {
Victor Stinner3c1e4812012-03-26 22:10:51 +02002252 PyObject *doc = _PyDict_GetItemId(dict, &PyId___doc__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002253 if (doc != NULL && PyUnicode_Check(doc)) {
2254 Py_ssize_t len;
2255 char *doc_str;
2256 char *tp_doc;
Alexandre Vassalottia85998a2008-05-03 18:24:43 +00002257
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002258 doc_str = _PyUnicode_AsString(doc);
Victor Stinner6f738742012-02-25 01:22:36 +01002259 if (doc_str == NULL)
2260 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002261 /* Silently truncate the docstring if it contains null bytes. */
2262 len = strlen(doc_str);
2263 tp_doc = (char *)PyObject_MALLOC(len + 1);
Victor Stinner6f738742012-02-25 01:22:36 +01002264 if (tp_doc == NULL)
2265 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002266 memcpy(tp_doc, doc_str, len + 1);
2267 type->tp_doc = tp_doc;
2268 }
2269 }
Tim Peters2f93e282001-10-04 05:27:00 +00002270
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002271 /* Special-case __new__: if it's a plain function,
2272 make it a static function */
Victor Stinner3c1e4812012-03-26 22:10:51 +02002273 tmp = _PyDict_GetItemId(dict, &PyId___new__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002274 if (tmp != NULL && PyFunction_Check(tmp)) {
2275 tmp = PyStaticMethod_New(tmp);
Victor Stinner6f738742012-02-25 01:22:36 +01002276 if (tmp == NULL)
2277 goto error;
Victor Stinner3c1e4812012-03-26 22:10:51 +02002278 if (_PyDict_SetItemId(dict, &PyId___new__, tmp) < 0)
2279 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002280 Py_DECREF(tmp);
2281 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002282
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002283 /* Add descriptors for custom slots from __slots__, or for __dict__ */
2284 mp = PyHeapType_GET_MEMBERS(et);
2285 slotoffset = base->tp_basicsize;
Victor Stinner6f738742012-02-25 01:22:36 +01002286 if (et->ht_slots != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002287 for (i = 0; i < nslots; i++, mp++) {
2288 mp->name = _PyUnicode_AsString(
Victor Stinner6f738742012-02-25 01:22:36 +01002289 PyTuple_GET_ITEM(et->ht_slots, i));
2290 if (mp->name == NULL)
2291 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002292 mp->type = T_OBJECT_EX;
2293 mp->offset = slotoffset;
Guido van Rossumd8faa362007-04-27 19:54:29 +00002294
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002295 /* __dict__ and __weakref__ are already filtered out */
2296 assert(strcmp(mp->name, "__dict__") != 0);
2297 assert(strcmp(mp->name, "__weakref__") != 0);
Guido van Rossumd8faa362007-04-27 19:54:29 +00002298
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002299 slotoffset += sizeof(PyObject *);
2300 }
2301 }
2302 if (add_dict) {
2303 if (base->tp_itemsize)
2304 type->tp_dictoffset = -(long)sizeof(PyObject *);
2305 else
2306 type->tp_dictoffset = slotoffset;
2307 slotoffset += sizeof(PyObject *);
2308 }
2309 if (add_weak) {
2310 assert(!base->tp_itemsize);
2311 type->tp_weaklistoffset = slotoffset;
2312 slotoffset += sizeof(PyObject *);
2313 }
2314 type->tp_basicsize = slotoffset;
2315 type->tp_itemsize = base->tp_itemsize;
2316 type->tp_members = PyHeapType_GET_MEMBERS(et);
Guido van Rossum373c7412003-01-07 13:41:37 +00002317
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002318 if (type->tp_weaklistoffset && type->tp_dictoffset)
2319 type->tp_getset = subtype_getsets_full;
2320 else if (type->tp_weaklistoffset && !type->tp_dictoffset)
2321 type->tp_getset = subtype_getsets_weakref_only;
2322 else if (!type->tp_weaklistoffset && type->tp_dictoffset)
2323 type->tp_getset = subtype_getsets_dict_only;
2324 else
2325 type->tp_getset = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002326
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002327 /* Special case some slots */
2328 if (type->tp_dictoffset != 0 || nslots > 0) {
2329 if (base->tp_getattr == NULL && base->tp_getattro == NULL)
2330 type->tp_getattro = PyObject_GenericGetAttr;
2331 if (base->tp_setattr == NULL && base->tp_setattro == NULL)
2332 type->tp_setattro = PyObject_GenericSetAttr;
2333 }
2334 type->tp_dealloc = subtype_dealloc;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002335
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002336 /* Enable GC unless there are really no instance variables possible */
2337 if (!(type->tp_basicsize == sizeof(PyObject) &&
2338 type->tp_itemsize == 0))
2339 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossum9475a232001-10-05 20:51:39 +00002340
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002341 /* Always override allocation strategy to use regular heap */
2342 type->tp_alloc = PyType_GenericAlloc;
2343 if (type->tp_flags & Py_TPFLAGS_HAVE_GC) {
2344 type->tp_free = PyObject_GC_Del;
2345 type->tp_traverse = subtype_traverse;
2346 type->tp_clear = subtype_clear;
2347 }
2348 else
2349 type->tp_free = PyObject_Del;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002350
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002351 /* Initialize the rest */
Victor Stinner6f738742012-02-25 01:22:36 +01002352 if (PyType_Ready(type) < 0)
2353 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002354
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002355 /* Put the proper slots in place */
2356 fixup_slot_dispatchers(type);
Guido van Rossumf040ede2001-08-07 16:40:56 +00002357
Victor Stinner6f738742012-02-25 01:22:36 +01002358 Py_DECREF(dict);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002359 return (PyObject *)type;
Victor Stinner6f738742012-02-25 01:22:36 +01002360
2361error:
2362 Py_XDECREF(dict);
2363 Py_XDECREF(bases);
2364 Py_XDECREF(slots);
2365 Py_XDECREF(type);
2366 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002367}
2368
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002369static short slotoffsets[] = {
2370 -1, /* invalid slot */
2371#include "typeslots.inc"
2372};
2373
Benjamin Petersone28108c2012-01-29 20:13:18 -05002374PyObject *
2375PyType_FromSpec(PyType_Spec *spec)
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002376{
2377 PyHeapTypeObject *res = (PyHeapTypeObject*)PyType_GenericAlloc(&PyType_Type, 0);
2378 char *res_start = (char*)res;
2379 PyType_Slot *slot;
2380
Martin v. Löwis5e06a5d2011-02-21 16:24:00 +00002381 if (res == NULL)
2382 return NULL;
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002383 res->ht_name = PyUnicode_FromString(spec->name);
2384 if (!res->ht_name)
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002385 goto fail;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002386 res->ht_qualname = res->ht_name;
2387 Py_INCREF(res->ht_qualname);
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002388 res->ht_type.tp_name = _PyUnicode_AsString(res->ht_name);
2389 if (!res->ht_type.tp_name)
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002390 goto fail;
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002391
2392 res->ht_type.tp_basicsize = spec->basicsize;
2393 res->ht_type.tp_itemsize = spec->itemsize;
2394 res->ht_type.tp_flags = spec->flags | Py_TPFLAGS_HEAPTYPE;
Victor Stinner0fcab4a2011-01-04 12:59:15 +00002395
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002396 for (slot = spec->slots; slot->slot; slot++) {
Victor Stinner63941882011-09-29 00:42:28 +02002397 if (slot->slot >= Py_ARRAY_LENGTH(slotoffsets)) {
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002398 PyErr_SetString(PyExc_RuntimeError, "invalid slot offset");
2399 goto fail;
2400 }
2401 *(void**)(res_start + slotoffsets[slot->slot]) = slot->pfunc;
Georg Brandl032400b2011-02-19 21:47:02 +00002402
2403 /* need to make a copy of the docstring slot, which usually
2404 points to a static string literal */
2405 if (slot->slot == Py_tp_doc) {
2406 ssize_t len = strlen(slot->pfunc)+1;
2407 char *tp_doc = PyObject_MALLOC(len);
2408 if (tp_doc == NULL)
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002409 goto fail;
Georg Brandl032400b2011-02-19 21:47:02 +00002410 memcpy(tp_doc, slot->pfunc, len);
2411 res->ht_type.tp_doc = tp_doc;
2412 }
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002413 }
2414
Benjamin Peterson2652d252012-01-29 20:16:37 -05002415 if (PyType_Ready(&res->ht_type) < 0)
2416 goto fail;
2417
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002418 return (PyObject*)res;
Victor Stinner0fcab4a2011-01-04 12:59:15 +00002419
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002420 fail:
2421 Py_DECREF(res);
2422 return NULL;
2423}
2424
2425
Tim Peters6d6c1a32001-08-02 04:15:00 +00002426/* Internal API to look for a name through the MRO.
2427 This returns a borrowed reference, and doesn't set an exception! */
2428PyObject *
2429_PyType_Lookup(PyTypeObject *type, PyObject *name)
2430{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002431 Py_ssize_t i, n;
2432 PyObject *mro, *res, *base, *dict;
2433 unsigned int h;
Christian Heimesa62da1d2008-01-12 19:39:10 +00002434
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002435 if (MCACHE_CACHEABLE_NAME(name) &&
2436 PyType_HasFeature(type, Py_TPFLAGS_VALID_VERSION_TAG)) {
2437 /* fast path */
2438 h = MCACHE_HASH_METHOD(type, name);
2439 if (method_cache[h].version == type->tp_version_tag &&
2440 method_cache[h].name == name)
2441 return method_cache[h].value;
2442 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002443
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002444 /* Look in tp_dict of types in MRO */
2445 mro = type->tp_mro;
Guido van Rossum23094982002-06-10 14:30:43 +00002446
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002447 /* If mro is NULL, the type is either not yet initialized
2448 by PyType_Ready(), or already cleared by type_clear().
2449 Either way the safest thing to do is to return NULL. */
2450 if (mro == NULL)
2451 return NULL;
Guido van Rossum23094982002-06-10 14:30:43 +00002452
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002453 res = NULL;
Victor Stinnerd74782b2012-03-09 00:39:08 +01002454 /* keep a strong reference to mro because type->tp_mro can be replaced
2455 during PyDict_GetItem(dict, name) */
2456 Py_INCREF(mro);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002457 assert(PyTuple_Check(mro));
2458 n = PyTuple_GET_SIZE(mro);
2459 for (i = 0; i < n; i++) {
2460 base = PyTuple_GET_ITEM(mro, i);
2461 assert(PyType_Check(base));
2462 dict = ((PyTypeObject *)base)->tp_dict;
2463 assert(dict && PyDict_Check(dict));
2464 res = PyDict_GetItem(dict, name);
2465 if (res != NULL)
2466 break;
2467 }
Victor Stinnerd74782b2012-03-09 00:39:08 +01002468 Py_DECREF(mro);
Christian Heimesa62da1d2008-01-12 19:39:10 +00002469
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002470 if (MCACHE_CACHEABLE_NAME(name) && assign_version_tag(type)) {
2471 h = MCACHE_HASH_METHOD(type, name);
2472 method_cache[h].version = type->tp_version_tag;
2473 method_cache[h].value = res; /* borrowed */
2474 Py_INCREF(name);
2475 Py_DECREF(method_cache[h].name);
2476 method_cache[h].name = name;
2477 }
2478 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002479}
2480
Victor Stinner3c1e4812012-03-26 22:10:51 +02002481static PyObject *
2482_PyType_LookupId(PyTypeObject *type, struct _Py_Identifier *name)
2483{
2484 PyObject *oname;
2485 oname = _PyUnicode_FromId(name); /* borrowed */
2486 if (oname == NULL)
2487 return NULL;
2488 return _PyType_Lookup(type, oname);
2489}
2490
Tim Peters6d6c1a32001-08-02 04:15:00 +00002491/* This is similar to PyObject_GenericGetAttr(),
2492 but uses _PyType_Lookup() instead of just looking in type->tp_dict. */
2493static PyObject *
2494type_getattro(PyTypeObject *type, PyObject *name)
2495{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002496 PyTypeObject *metatype = Py_TYPE(type);
2497 PyObject *meta_attribute, *attribute;
2498 descrgetfunc meta_get;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002499
Benjamin Peterson16d84ac2012-03-16 09:32:59 -05002500 if (!PyUnicode_Check(name)) {
2501 PyErr_Format(PyExc_TypeError,
2502 "attribute name must be string, not '%.200s'",
2503 name->ob_type->tp_name);
2504 return NULL;
2505 }
2506
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002507 /* Initialize this type (we'll assume the metatype is initialized) */
2508 if (type->tp_dict == NULL) {
2509 if (PyType_Ready(type) < 0)
2510 return NULL;
2511 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002512
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002513 /* No readable descriptor found yet */
2514 meta_get = NULL;
Tim Peters34592512002-07-11 06:23:50 +00002515
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002516 /* Look for the attribute in the metatype */
2517 meta_attribute = _PyType_Lookup(metatype, name);
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002518
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002519 if (meta_attribute != NULL) {
2520 meta_get = Py_TYPE(meta_attribute)->tp_descr_get;
Tim Peters34592512002-07-11 06:23:50 +00002521
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002522 if (meta_get != NULL && PyDescr_IsData(meta_attribute)) {
2523 /* Data descriptors implement tp_descr_set to intercept
2524 * writes. Assume the attribute is not overridden in
2525 * type's tp_dict (and bases): call the descriptor now.
2526 */
2527 return meta_get(meta_attribute, (PyObject *)type,
2528 (PyObject *)metatype);
2529 }
2530 Py_INCREF(meta_attribute);
2531 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002532
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002533 /* No data descriptor found on metatype. Look in tp_dict of this
2534 * type and its bases */
2535 attribute = _PyType_Lookup(type, name);
2536 if (attribute != NULL) {
2537 /* Implement descriptor functionality, if any */
2538 descrgetfunc local_get = Py_TYPE(attribute)->tp_descr_get;
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00002539
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002540 Py_XDECREF(meta_attribute);
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00002541
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002542 if (local_get != NULL) {
2543 /* NULL 2nd argument indicates the descriptor was
2544 * found on the target object itself (or a base) */
2545 return local_get(attribute, (PyObject *)NULL,
2546 (PyObject *)type);
2547 }
Tim Peters34592512002-07-11 06:23:50 +00002548
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002549 Py_INCREF(attribute);
2550 return attribute;
2551 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002552
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002553 /* No attribute found in local __dict__ (or bases): use the
2554 * descriptor from the metatype, if any */
2555 if (meta_get != NULL) {
2556 PyObject *res;
2557 res = meta_get(meta_attribute, (PyObject *)type,
2558 (PyObject *)metatype);
2559 Py_DECREF(meta_attribute);
2560 return res;
2561 }
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002562
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002563 /* If an ordinary attribute was found on the metatype, return it now */
2564 if (meta_attribute != NULL) {
2565 return meta_attribute;
2566 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002567
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002568 /* Give up */
2569 PyErr_Format(PyExc_AttributeError,
2570 "type object '%.50s' has no attribute '%U'",
2571 type->tp_name, name);
2572 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002573}
2574
2575static int
2576type_setattro(PyTypeObject *type, PyObject *name, PyObject *value)
2577{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002578 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
2579 PyErr_Format(
2580 PyExc_TypeError,
2581 "can't set attributes of built-in/extension type '%s'",
2582 type->tp_name);
2583 return -1;
2584 }
2585 if (PyObject_GenericSetAttr((PyObject *)type, name, value) < 0)
2586 return -1;
2587 return update_slot(type, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002588}
2589
2590static void
2591type_dealloc(PyTypeObject *type)
2592{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002593 PyHeapTypeObject *et;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002594
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002595 /* Assert this is a heap-allocated type object */
2596 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
2597 _PyObject_GC_UNTRACK(type);
2598 PyObject_ClearWeakRefs((PyObject *)type);
2599 et = (PyHeapTypeObject *)type;
2600 Py_XDECREF(type->tp_base);
2601 Py_XDECREF(type->tp_dict);
2602 Py_XDECREF(type->tp_bases);
2603 Py_XDECREF(type->tp_mro);
2604 Py_XDECREF(type->tp_cache);
2605 Py_XDECREF(type->tp_subclasses);
2606 /* A type's tp_doc is heap allocated, unlike the tp_doc slots
2607 * of most other objects. It's okay to cast it to char *.
2608 */
2609 PyObject_Free((char *)type->tp_doc);
2610 Py_XDECREF(et->ht_name);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002611 Py_XDECREF(et->ht_qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002612 Py_XDECREF(et->ht_slots);
2613 Py_TYPE(type)->tp_free((PyObject *)type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002614}
2615
Guido van Rossum1c450732001-10-08 15:18:27 +00002616static PyObject *
2617type_subclasses(PyTypeObject *type, PyObject *args_ignored)
2618{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002619 PyObject *list, *raw, *ref;
2620 Py_ssize_t i, n;
Guido van Rossum1c450732001-10-08 15:18:27 +00002621
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002622 list = PyList_New(0);
2623 if (list == NULL)
2624 return NULL;
2625 raw = type->tp_subclasses;
2626 if (raw == NULL)
2627 return list;
2628 assert(PyList_Check(raw));
2629 n = PyList_GET_SIZE(raw);
2630 for (i = 0; i < n; i++) {
2631 ref = PyList_GET_ITEM(raw, i);
2632 assert(PyWeakref_CheckRef(ref));
2633 ref = PyWeakref_GET_OBJECT(ref);
2634 if (ref != Py_None) {
2635 if (PyList_Append(list, ref) < 0) {
2636 Py_DECREF(list);
2637 return NULL;
2638 }
2639 }
2640 }
2641 return list;
Guido van Rossum1c450732001-10-08 15:18:27 +00002642}
2643
Guido van Rossum47374822007-08-02 16:48:17 +00002644static PyObject *
2645type_prepare(PyObject *self, PyObject *args, PyObject *kwds)
2646{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002647 return PyDict_New();
Guido van Rossum47374822007-08-02 16:48:17 +00002648}
2649
Victor Stinner63941882011-09-29 00:42:28 +02002650/*
Benjamin Peterson82b00c12011-05-24 11:09:06 -05002651 Merge the __dict__ of aclass into dict, and recursively also all
2652 the __dict__s of aclass's base classes. The order of merging isn't
2653 defined, as it's expected that only the final set of dict keys is
2654 interesting.
2655 Return 0 on success, -1 on error.
2656*/
2657
2658static int
2659merge_class_dict(PyObject *dict, PyObject *aclass)
2660{
2661 PyObject *classdict;
2662 PyObject *bases;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02002663 _Py_IDENTIFIER(__bases__);
Benjamin Peterson82b00c12011-05-24 11:09:06 -05002664
2665 assert(PyDict_Check(dict));
2666 assert(aclass);
2667
2668 /* Merge in the type's dict (if any). */
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002669 classdict = _PyObject_GetAttrId(aclass, &PyId___dict__);
Benjamin Peterson82b00c12011-05-24 11:09:06 -05002670 if (classdict == NULL)
2671 PyErr_Clear();
2672 else {
2673 int status = PyDict_Update(dict, classdict);
2674 Py_DECREF(classdict);
2675 if (status < 0)
2676 return -1;
2677 }
2678
2679 /* Recursively merge in the base types' (if any) dicts. */
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002680 bases = _PyObject_GetAttrId(aclass, &PyId___bases__);
Benjamin Peterson82b00c12011-05-24 11:09:06 -05002681 if (bases == NULL)
2682 PyErr_Clear();
2683 else {
2684 /* We have no guarantee that bases is a real tuple */
2685 Py_ssize_t i, n;
2686 n = PySequence_Size(bases); /* This better be right */
2687 if (n < 0)
2688 PyErr_Clear();
2689 else {
2690 for (i = 0; i < n; i++) {
2691 int status;
2692 PyObject *base = PySequence_GetItem(bases, i);
2693 if (base == NULL) {
2694 Py_DECREF(bases);
2695 return -1;
2696 }
2697 status = merge_class_dict(dict, base);
2698 Py_DECREF(base);
2699 if (status < 0) {
2700 Py_DECREF(bases);
2701 return -1;
2702 }
2703 }
2704 }
2705 Py_DECREF(bases);
2706 }
2707 return 0;
2708}
2709
2710/* __dir__ for type objects: returns __dict__ and __bases__.
2711 We deliberately don't suck up its __class__, as methods belonging to the
2712 metaclass would probably be more confusing than helpful.
2713*/
2714static PyObject *
2715type_dir(PyObject *self, PyObject *args)
2716{
2717 PyObject *result = NULL;
2718 PyObject *dict = PyDict_New();
2719
2720 if (dict != NULL && merge_class_dict(dict, self) == 0)
2721 result = PyDict_Keys(dict);
2722
2723 Py_XDECREF(dict);
2724 return result;
2725}
2726
Tim Peters6d6c1a32001-08-02 04:15:00 +00002727static PyMethodDef type_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002728 {"mro", (PyCFunction)mro_external, METH_NOARGS,
2729 PyDoc_STR("mro() -> list\nreturn a type's method resolution order")},
2730 {"__subclasses__", (PyCFunction)type_subclasses, METH_NOARGS,
2731 PyDoc_STR("__subclasses__() -> list of immediate subclasses")},
2732 {"__prepare__", (PyCFunction)type_prepare,
2733 METH_VARARGS | METH_KEYWORDS | METH_CLASS,
2734 PyDoc_STR("__prepare__() -> dict\n"
2735 "used to create the namespace for the class statement")},
2736 {"__instancecheck__", type___instancecheck__, METH_O,
Benjamin Petersonfbe56bb2011-05-24 12:42:51 -05002737 PyDoc_STR("__instancecheck__() -> bool\ncheck if an object is an instance")},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002738 {"__subclasscheck__", type___subclasscheck__, METH_O,
Benjamin Petersonfbe56bb2011-05-24 12:42:51 -05002739 PyDoc_STR("__subclasscheck__() -> bool\ncheck if a class is a subclass")},
Benjamin Peterson82b00c12011-05-24 11:09:06 -05002740 {"__dir__", type_dir, METH_NOARGS,
Benjamin Petersonc7284122011-05-24 12:46:15 -05002741 PyDoc_STR("__dir__() -> list\nspecialized __dir__ implementation for types")},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002742 {0}
Tim Peters6d6c1a32001-08-02 04:15:00 +00002743};
2744
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002745PyDoc_STRVAR(type_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00002746"type(object) -> the object's type\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002747"type(name, bases, dict) -> a new type");
Tim Peters6d6c1a32001-08-02 04:15:00 +00002748
Guido van Rossum048eb752001-10-02 21:24:57 +00002749static int
2750type_traverse(PyTypeObject *type, visitproc visit, void *arg)
2751{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002752 /* Because of type_is_gc(), the collector only calls this
2753 for heaptypes. */
2754 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002755
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002756 Py_VISIT(type->tp_dict);
2757 Py_VISIT(type->tp_cache);
2758 Py_VISIT(type->tp_mro);
2759 Py_VISIT(type->tp_bases);
2760 Py_VISIT(type->tp_base);
Guido van Rossuma3862092002-06-10 15:24:42 +00002761
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002762 /* There's no need to visit type->tp_subclasses or
2763 ((PyHeapTypeObject *)type)->ht_slots, because they can't be involved
2764 in cycles; tp_subclasses is a list of weak references,
2765 and slots is a tuple of strings. */
Guido van Rossum048eb752001-10-02 21:24:57 +00002766
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002767 return 0;
Guido van Rossum048eb752001-10-02 21:24:57 +00002768}
2769
2770static int
2771type_clear(PyTypeObject *type)
2772{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002773 /* Because of type_is_gc(), the collector only calls this
2774 for heaptypes. */
2775 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002776
Antoine Pitrou2e872082011-12-15 14:15:31 +01002777 /* We need to invalidate the method cache carefully before clearing
2778 the dict, so that other objects caught in a reference cycle
2779 don't start calling destroyed methods.
2780
2781 Otherwise, the only field we need to clear is tp_mro, which is
2782 part of a hard cycle (its first element is the class itself) that
2783 won't be broken otherwise (it's a tuple and tuples don't have a
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002784 tp_clear handler). None of the other fields need to be
2785 cleared, and here's why:
Guido van Rossum048eb752001-10-02 21:24:57 +00002786
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002787 tp_cache:
2788 Not used; if it were, it would be a dict.
Guido van Rossuma3862092002-06-10 15:24:42 +00002789
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002790 tp_bases, tp_base:
2791 If these are involved in a cycle, there must be at least
2792 one other, mutable object in the cycle, e.g. a base
2793 class's dict; the cycle will be broken that way.
Guido van Rossuma3862092002-06-10 15:24:42 +00002794
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002795 tp_subclasses:
2796 A list of weak references can't be part of a cycle; and
2797 lists have their own tp_clear.
Guido van Rossuma3862092002-06-10 15:24:42 +00002798
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002799 slots (in PyHeapTypeObject):
2800 A tuple of strings can't be part of a cycle.
2801 */
Guido van Rossuma3862092002-06-10 15:24:42 +00002802
Antoine Pitrou2e872082011-12-15 14:15:31 +01002803 PyType_Modified(type);
2804 if (type->tp_dict)
2805 PyDict_Clear(type->tp_dict);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002806 Py_CLEAR(type->tp_mro);
Guido van Rossum048eb752001-10-02 21:24:57 +00002807
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002808 return 0;
Guido van Rossum048eb752001-10-02 21:24:57 +00002809}
2810
2811static int
2812type_is_gc(PyTypeObject *type)
2813{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002814 return type->tp_flags & Py_TPFLAGS_HEAPTYPE;
Guido van Rossum048eb752001-10-02 21:24:57 +00002815}
2816
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002817PyTypeObject PyType_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002818 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2819 "type", /* tp_name */
2820 sizeof(PyHeapTypeObject), /* tp_basicsize */
2821 sizeof(PyMemberDef), /* tp_itemsize */
2822 (destructor)type_dealloc, /* tp_dealloc */
2823 0, /* tp_print */
2824 0, /* tp_getattr */
2825 0, /* tp_setattr */
2826 0, /* tp_reserved */
2827 (reprfunc)type_repr, /* tp_repr */
2828 0, /* tp_as_number */
2829 0, /* tp_as_sequence */
2830 0, /* tp_as_mapping */
2831 0, /* tp_hash */
2832 (ternaryfunc)type_call, /* tp_call */
2833 0, /* tp_str */
2834 (getattrofunc)type_getattro, /* tp_getattro */
2835 (setattrofunc)type_setattro, /* tp_setattro */
2836 0, /* tp_as_buffer */
2837 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
2838 Py_TPFLAGS_BASETYPE | Py_TPFLAGS_TYPE_SUBCLASS, /* tp_flags */
2839 type_doc, /* tp_doc */
2840 (traverseproc)type_traverse, /* tp_traverse */
2841 (inquiry)type_clear, /* tp_clear */
2842 0, /* tp_richcompare */
2843 offsetof(PyTypeObject, tp_weaklist), /* tp_weaklistoffset */
2844 0, /* tp_iter */
2845 0, /* tp_iternext */
2846 type_methods, /* tp_methods */
2847 type_members, /* tp_members */
2848 type_getsets, /* tp_getset */
2849 0, /* tp_base */
2850 0, /* tp_dict */
2851 0, /* tp_descr_get */
2852 0, /* tp_descr_set */
2853 offsetof(PyTypeObject, tp_dict), /* tp_dictoffset */
2854 type_init, /* tp_init */
2855 0, /* tp_alloc */
2856 type_new, /* tp_new */
2857 PyObject_GC_Del, /* tp_free */
2858 (inquiry)type_is_gc, /* tp_is_gc */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002859};
Tim Peters6d6c1a32001-08-02 04:15:00 +00002860
2861
2862/* The base type of all types (eventually)... except itself. */
2863
Guido van Rossumd8faa362007-04-27 19:54:29 +00002864/* You may wonder why object.__new__() only complains about arguments
2865 when object.__init__() is not overridden, and vice versa.
2866
2867 Consider the use cases:
2868
2869 1. When neither is overridden, we want to hear complaints about
2870 excess (i.e., any) arguments, since their presence could
2871 indicate there's a bug.
2872
2873 2. When defining an Immutable type, we are likely to override only
2874 __new__(), since __init__() is called too late to initialize an
2875 Immutable object. Since __new__() defines the signature for the
2876 type, it would be a pain to have to override __init__() just to
2877 stop it from complaining about excess arguments.
2878
2879 3. When defining a Mutable type, we are likely to override only
2880 __init__(). So here the converse reasoning applies: we don't
2881 want to have to override __new__() just to stop it from
2882 complaining.
2883
2884 4. When __init__() is overridden, and the subclass __init__() calls
2885 object.__init__(), the latter should complain about excess
2886 arguments; ditto for __new__().
2887
2888 Use cases 2 and 3 make it unattractive to unconditionally check for
2889 excess arguments. The best solution that addresses all four use
2890 cases is as follows: __init__() complains about excess arguments
2891 unless __new__() is overridden and __init__() is not overridden
2892 (IOW, if __init__() is overridden or __new__() is not overridden);
2893 symmetrically, __new__() complains about excess arguments unless
2894 __init__() is overridden and __new__() is not overridden
2895 (IOW, if __new__() is overridden or __init__() is not overridden).
2896
2897 However, for backwards compatibility, this breaks too much code.
2898 Therefore, in 2.6, we'll *warn* about excess arguments when both
2899 methods are overridden; for all other cases we'll use the above
2900 rules.
2901
2902*/
2903
2904/* Forward */
2905static PyObject *
2906object_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
2907
2908static int
2909excess_args(PyObject *args, PyObject *kwds)
2910{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002911 return PyTuple_GET_SIZE(args) ||
2912 (kwds && PyDict_Check(kwds) && PyDict_Size(kwds));
Guido van Rossumd8faa362007-04-27 19:54:29 +00002913}
2914
Tim Peters6d6c1a32001-08-02 04:15:00 +00002915static int
2916object_init(PyObject *self, PyObject *args, PyObject *kwds)
2917{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002918 int err = 0;
Benjamin Peterson96384b92012-03-17 00:05:44 -05002919 PyTypeObject *type = Py_TYPE(self);
2920 if (excess_args(args, kwds) &&
2921 (type->tp_new == object_new || type->tp_init != object_init)) {
2922 PyErr_SetString(PyExc_TypeError, "object.__init__() takes no parameters");
2923 err = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002924 }
2925 return err;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002926}
2927
Guido van Rossum298e4212003-02-13 16:30:16 +00002928static PyObject *
2929object_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2930{
Benjamin Peterson96384b92012-03-17 00:05:44 -05002931 if (excess_args(args, kwds) &&
2932 (type->tp_init == object_init || type->tp_new != object_new)) {
2933 PyErr_SetString(PyExc_TypeError, "object.__new__() takes no parameters");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002934 return NULL;
Benjamin Peterson96384b92012-03-17 00:05:44 -05002935 }
Victor Stinner3c1e4812012-03-26 22:10:51 +02002936
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002937 if (type->tp_flags & Py_TPFLAGS_IS_ABSTRACT) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002938 PyObject *abstract_methods = NULL;
2939 PyObject *builtins;
2940 PyObject *sorted;
2941 PyObject *sorted_methods = NULL;
2942 PyObject *joined = NULL;
Benjamin Peterson9a03ecf2012-03-16 20:15:54 -05002943 PyObject *comma;
2944 _Py_static_string(comma_id, ", ");
Victor Stinner3c1e4812012-03-26 22:10:51 +02002945 _Py_IDENTIFIER(sorted);
Christian Heimes9e7f1d22008-02-28 12:27:11 +00002946
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002947 /* Compute ", ".join(sorted(type.__abstractmethods__))
2948 into joined. */
2949 abstract_methods = type_abstractmethods(type, NULL);
2950 if (abstract_methods == NULL)
2951 goto error;
2952 builtins = PyEval_GetBuiltins();
2953 if (builtins == NULL)
2954 goto error;
Victor Stinner3c1e4812012-03-26 22:10:51 +02002955 sorted = _PyDict_GetItemId(builtins, &PyId_sorted);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002956 if (sorted == NULL)
2957 goto error;
2958 sorted_methods = PyObject_CallFunctionObjArgs(sorted,
2959 abstract_methods,
2960 NULL);
2961 if (sorted_methods == NULL)
2962 goto error;
Benjamin Peterson9a03ecf2012-03-16 20:15:54 -05002963 comma = _PyUnicode_FromId(&comma_id);
2964 if (comma == NULL)
2965 goto error;
2966 joined = PyUnicode_Join(comma, sorted_methods);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002967 if (joined == NULL)
2968 goto error;
Christian Heimes9e7f1d22008-02-28 12:27:11 +00002969
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002970 PyErr_Format(PyExc_TypeError,
2971 "Can't instantiate abstract class %s "
2972 "with abstract methods %U",
2973 type->tp_name,
2974 joined);
2975 error:
2976 Py_XDECREF(joined);
2977 Py_XDECREF(sorted_methods);
2978 Py_XDECREF(abstract_methods);
2979 return NULL;
2980 }
2981 return type->tp_alloc(type, 0);
Guido van Rossum298e4212003-02-13 16:30:16 +00002982}
2983
Tim Peters6d6c1a32001-08-02 04:15:00 +00002984static void
2985object_dealloc(PyObject *self)
2986{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002987 Py_TYPE(self)->tp_free(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002988}
2989
Guido van Rossum8e248182001-08-12 05:17:56 +00002990static PyObject *
2991object_repr(PyObject *self)
2992{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002993 PyTypeObject *type;
2994 PyObject *mod, *name, *rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00002995
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002996 type = Py_TYPE(self);
2997 mod = type_module(type, NULL);
2998 if (mod == NULL)
2999 PyErr_Clear();
3000 else if (!PyUnicode_Check(mod)) {
3001 Py_DECREF(mod);
3002 mod = NULL;
3003 }
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003004 name = type_qualname(type, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003005 if (name == NULL)
3006 return NULL;
3007 if (mod != NULL && PyUnicode_CompareWithASCIIString(mod, "builtins"))
3008 rtn = PyUnicode_FromFormat("<%U.%U object at %p>", mod, name, self);
3009 else
3010 rtn = PyUnicode_FromFormat("<%s object at %p>",
3011 type->tp_name, self);
3012 Py_XDECREF(mod);
3013 Py_DECREF(name);
3014 return rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00003015}
3016
Guido van Rossumb8f63662001-08-15 23:57:02 +00003017static PyObject *
3018object_str(PyObject *self)
3019{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003020 unaryfunc f;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003021
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003022 f = Py_TYPE(self)->tp_repr;
Antoine Pitrou8cdc40e2011-07-15 21:15:07 +02003023 if (f == NULL || f == object_str)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003024 f = object_repr;
3025 return f(self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003026}
3027
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003028static PyObject *
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003029object_richcompare(PyObject *self, PyObject *other, int op)
3030{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003031 PyObject *res;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003032
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003033 switch (op) {
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003034
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003035 case Py_EQ:
3036 /* Return NotImplemented instead of False, so if two
3037 objects are compared, both get a chance at the
3038 comparison. See issue #1393. */
3039 res = (self == other) ? Py_True : Py_NotImplemented;
3040 Py_INCREF(res);
3041 break;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003042
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003043 case Py_NE:
3044 /* By default, != returns the opposite of ==,
3045 unless the latter returns NotImplemented. */
3046 res = PyObject_RichCompare(self, other, Py_EQ);
3047 if (res != NULL && res != Py_NotImplemented) {
3048 int ok = PyObject_IsTrue(res);
3049 Py_DECREF(res);
3050 if (ok < 0)
3051 res = NULL;
3052 else {
3053 if (ok)
3054 res = Py_False;
3055 else
3056 res = Py_True;
3057 Py_INCREF(res);
3058 }
3059 }
3060 break;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003061
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003062 default:
3063 res = Py_NotImplemented;
3064 Py_INCREF(res);
3065 break;
3066 }
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003067
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003068 return res;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003069}
3070
3071static PyObject *
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003072object_get_class(PyObject *self, void *closure)
3073{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003074 Py_INCREF(Py_TYPE(self));
3075 return (PyObject *)(Py_TYPE(self));
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003076}
3077
3078static int
3079equiv_structs(PyTypeObject *a, PyTypeObject *b)
3080{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003081 return a == b ||
3082 (a != NULL &&
3083 b != NULL &&
3084 a->tp_basicsize == b->tp_basicsize &&
3085 a->tp_itemsize == b->tp_itemsize &&
3086 a->tp_dictoffset == b->tp_dictoffset &&
3087 a->tp_weaklistoffset == b->tp_weaklistoffset &&
3088 ((a->tp_flags & Py_TPFLAGS_HAVE_GC) ==
3089 (b->tp_flags & Py_TPFLAGS_HAVE_GC)));
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003090}
3091
3092static int
3093same_slots_added(PyTypeObject *a, PyTypeObject *b)
3094{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003095 PyTypeObject *base = a->tp_base;
3096 Py_ssize_t size;
3097 PyObject *slots_a, *slots_b;
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003098
Benjamin Peterson67641d22011-01-17 19:24:34 +00003099 assert(base == b->tp_base);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003100 size = base->tp_basicsize;
3101 if (a->tp_dictoffset == size && b->tp_dictoffset == size)
3102 size += sizeof(PyObject *);
3103 if (a->tp_weaklistoffset == size && b->tp_weaklistoffset == size)
3104 size += sizeof(PyObject *);
Guido van Rossumd8faa362007-04-27 19:54:29 +00003105
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003106 /* Check slots compliance */
3107 slots_a = ((PyHeapTypeObject *)a)->ht_slots;
3108 slots_b = ((PyHeapTypeObject *)b)->ht_slots;
3109 if (slots_a && slots_b) {
3110 if (PyObject_RichCompareBool(slots_a, slots_b, Py_EQ) != 1)
3111 return 0;
3112 size += sizeof(PyObject *) * PyTuple_GET_SIZE(slots_a);
3113 }
3114 return size == a->tp_basicsize && size == b->tp_basicsize;
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003115}
3116
3117static int
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003118compatible_for_assignment(PyTypeObject* oldto, PyTypeObject* newto, char* attr)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003119{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003120 PyTypeObject *newbase, *oldbase;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003121
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003122 if (newto->tp_dealloc != oldto->tp_dealloc ||
3123 newto->tp_free != oldto->tp_free)
3124 {
3125 PyErr_Format(PyExc_TypeError,
3126 "%s assignment: "
3127 "'%s' deallocator differs from '%s'",
3128 attr,
3129 newto->tp_name,
3130 oldto->tp_name);
3131 return 0;
3132 }
3133 newbase = newto;
3134 oldbase = oldto;
3135 while (equiv_structs(newbase, newbase->tp_base))
3136 newbase = newbase->tp_base;
3137 while (equiv_structs(oldbase, oldbase->tp_base))
3138 oldbase = oldbase->tp_base;
3139 if (newbase != oldbase &&
3140 (newbase->tp_base != oldbase->tp_base ||
3141 !same_slots_added(newbase, oldbase))) {
3142 PyErr_Format(PyExc_TypeError,
3143 "%s assignment: "
3144 "'%s' object layout differs from '%s'",
3145 attr,
3146 newto->tp_name,
3147 oldto->tp_name);
3148 return 0;
3149 }
Tim Petersea7f75d2002-12-07 21:39:16 +00003150
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003151 return 1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003152}
3153
3154static int
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003155object_set_class(PyObject *self, PyObject *value, void *closure)
3156{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003157 PyTypeObject *oldto = Py_TYPE(self);
3158 PyTypeObject *newto;
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003159
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003160 if (value == NULL) {
3161 PyErr_SetString(PyExc_TypeError,
3162 "can't delete __class__ attribute");
3163 return -1;
3164 }
3165 if (!PyType_Check(value)) {
3166 PyErr_Format(PyExc_TypeError,
Florent Xiclunaaa6c1d22011-12-12 18:54:29 +01003167 "__class__ must be set to a class, not '%s' object",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003168 Py_TYPE(value)->tp_name);
3169 return -1;
3170 }
3171 newto = (PyTypeObject *)value;
3172 if (!(newto->tp_flags & Py_TPFLAGS_HEAPTYPE) ||
3173 !(oldto->tp_flags & Py_TPFLAGS_HEAPTYPE))
3174 {
3175 PyErr_Format(PyExc_TypeError,
3176 "__class__ assignment: only for heap types");
3177 return -1;
3178 }
3179 if (compatible_for_assignment(newto, oldto, "__class__")) {
3180 Py_INCREF(newto);
3181 Py_TYPE(self) = newto;
3182 Py_DECREF(oldto);
3183 return 0;
3184 }
3185 else {
3186 return -1;
3187 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003188}
3189
3190static PyGetSetDef object_getsets[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003191 {"__class__", object_get_class, object_set_class,
3192 PyDoc_STR("the object's class")},
3193 {0}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003194};
3195
Guido van Rossumc53f0092003-02-18 22:05:12 +00003196
Guido van Rossum036f9992003-02-21 22:02:54 +00003197/* Stuff to implement __reduce_ex__ for pickle protocols >= 2.
Alexandre Vassalottif7fa63d2008-05-11 08:55:36 +00003198 We fall back to helpers in copyreg for:
Guido van Rossum036f9992003-02-21 22:02:54 +00003199 - pickle protocols < 2
3200 - calculating the list of slot names (done only once per class)
3201 - the __newobj__ function (which is used as a token but never called)
3202*/
3203
3204static PyObject *
Alexandre Vassalottif7fa63d2008-05-11 08:55:36 +00003205import_copyreg(void)
Guido van Rossum036f9992003-02-21 22:02:54 +00003206{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003207 static PyObject *copyreg_str;
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003208 static PyObject *mod_copyreg = NULL;
Guido van Rossum3926a632001-09-25 16:25:58 +00003209
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003210 if (!copyreg_str) {
3211 copyreg_str = PyUnicode_InternFromString("copyreg");
3212 if (copyreg_str == NULL)
3213 return NULL;
3214 }
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003215 if (!mod_copyreg) {
3216 mod_copyreg = PyImport_Import(copyreg_str);
3217 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003218
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003219 Py_XINCREF(mod_copyreg);
3220 return mod_copyreg;
Guido van Rossum036f9992003-02-21 22:02:54 +00003221}
3222
3223static PyObject *
3224slotnames(PyObject *cls)
3225{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003226 PyObject *clsdict;
3227 PyObject *copyreg;
3228 PyObject *slotnames;
Victor Stinner3c1e4812012-03-26 22:10:51 +02003229 _Py_IDENTIFIER(__slotnames__);
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02003230 _Py_IDENTIFIER(_slotnames);
Guido van Rossum036f9992003-02-21 22:02:54 +00003231
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003232 clsdict = ((PyTypeObject *)cls)->tp_dict;
Victor Stinner3c1e4812012-03-26 22:10:51 +02003233 slotnames = _PyDict_GetItemId(clsdict, &PyId___slotnames__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003234 if (slotnames != NULL && PyList_Check(slotnames)) {
3235 Py_INCREF(slotnames);
3236 return slotnames;
3237 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003238
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003239 copyreg = import_copyreg();
3240 if (copyreg == NULL)
3241 return NULL;
Guido van Rossum036f9992003-02-21 22:02:54 +00003242
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02003243 slotnames = _PyObject_CallMethodId(copyreg, &PyId__slotnames, "O", cls);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003244 Py_DECREF(copyreg);
3245 if (slotnames != NULL &&
3246 slotnames != Py_None &&
3247 !PyList_Check(slotnames))
3248 {
3249 PyErr_SetString(PyExc_TypeError,
3250 "copyreg._slotnames didn't return a list or None");
3251 Py_DECREF(slotnames);
3252 slotnames = NULL;
3253 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003254
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003255 return slotnames;
Guido van Rossum036f9992003-02-21 22:02:54 +00003256}
3257
3258static PyObject *
3259reduce_2(PyObject *obj)
3260{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003261 PyObject *cls, *getnewargs;
3262 PyObject *args = NULL, *args2 = NULL;
3263 PyObject *getstate = NULL, *state = NULL, *names = NULL;
3264 PyObject *slots = NULL, *listitems = NULL, *dictitems = NULL;
3265 PyObject *copyreg = NULL, *newobj = NULL, *res = NULL;
3266 Py_ssize_t i, n;
Victor Stinner3c1e4812012-03-26 22:10:51 +02003267 _Py_IDENTIFIER(__getnewargs__);
3268 _Py_IDENTIFIER(__getstate__);
3269 _Py_IDENTIFIER(__newobj__);
Guido van Rossum036f9992003-02-21 22:02:54 +00003270
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003271 cls = (PyObject *) Py_TYPE(obj);
3272
Victor Stinner3c1e4812012-03-26 22:10:51 +02003273 getnewargs = _PyObject_GetAttrId(obj, &PyId___getnewargs__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003274 if (getnewargs != NULL) {
3275 args = PyObject_CallObject(getnewargs, NULL);
3276 Py_DECREF(getnewargs);
3277 if (args != NULL && !PyTuple_Check(args)) {
3278 PyErr_Format(PyExc_TypeError,
3279 "__getnewargs__ should return a tuple, "
3280 "not '%.200s'", Py_TYPE(args)->tp_name);
3281 goto end;
3282 }
3283 }
3284 else {
3285 PyErr_Clear();
3286 args = PyTuple_New(0);
3287 }
3288 if (args == NULL)
3289 goto end;
Guido van Rossum036f9992003-02-21 22:02:54 +00003290
Victor Stinner3c1e4812012-03-26 22:10:51 +02003291 getstate = _PyObject_GetAttrId(obj, &PyId___getstate__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003292 if (getstate != NULL) {
3293 state = PyObject_CallObject(getstate, NULL);
3294 Py_DECREF(getstate);
3295 if (state == NULL)
3296 goto end;
3297 }
3298 else {
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003299 PyObject **dict;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003300 PyErr_Clear();
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003301 dict = _PyObject_GetDictPtr(obj);
3302 if (dict && *dict)
3303 state = *dict;
3304 else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003305 state = Py_None;
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003306 Py_INCREF(state);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003307 names = slotnames(cls);
3308 if (names == NULL)
3309 goto end;
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003310 if (names != Py_None && PyList_GET_SIZE(names) > 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003311 assert(PyList_Check(names));
3312 slots = PyDict_New();
3313 if (slots == NULL)
3314 goto end;
3315 n = 0;
3316 /* Can't pre-compute the list size; the list
3317 is stored on the class so accessible to other
3318 threads, which may be run by DECREF */
3319 for (i = 0; i < PyList_GET_SIZE(names); i++) {
3320 PyObject *name, *value;
3321 name = PyList_GET_ITEM(names, i);
3322 value = PyObject_GetAttr(obj, name);
3323 if (value == NULL)
3324 PyErr_Clear();
3325 else {
3326 int err = PyDict_SetItem(slots, name,
3327 value);
3328 Py_DECREF(value);
3329 if (err)
3330 goto end;
3331 n++;
3332 }
3333 }
3334 if (n) {
3335 state = Py_BuildValue("(NO)", state, slots);
3336 if (state == NULL)
3337 goto end;
3338 }
3339 }
3340 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003341
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003342 if (!PyList_Check(obj)) {
3343 listitems = Py_None;
3344 Py_INCREF(listitems);
3345 }
3346 else {
3347 listitems = PyObject_GetIter(obj);
3348 if (listitems == NULL)
3349 goto end;
3350 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003351
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003352 if (!PyDict_Check(obj)) {
3353 dictitems = Py_None;
3354 Py_INCREF(dictitems);
3355 }
3356 else {
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02003357 _Py_IDENTIFIER(items);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02003358 PyObject *items = _PyObject_CallMethodId(obj, &PyId_items, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003359 if (items == NULL)
3360 goto end;
3361 dictitems = PyObject_GetIter(items);
3362 Py_DECREF(items);
3363 if (dictitems == NULL)
3364 goto end;
3365 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003366
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003367 copyreg = import_copyreg();
3368 if (copyreg == NULL)
3369 goto end;
Victor Stinner3c1e4812012-03-26 22:10:51 +02003370 newobj = _PyObject_GetAttrId(copyreg, &PyId___newobj__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003371 if (newobj == NULL)
3372 goto end;
Guido van Rossum036f9992003-02-21 22:02:54 +00003373
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003374 n = PyTuple_GET_SIZE(args);
3375 args2 = PyTuple_New(n+1);
3376 if (args2 == NULL)
3377 goto end;
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003378 Py_INCREF(cls);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003379 PyTuple_SET_ITEM(args2, 0, cls);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003380 for (i = 0; i < n; i++) {
3381 PyObject *v = PyTuple_GET_ITEM(args, i);
3382 Py_INCREF(v);
3383 PyTuple_SET_ITEM(args2, i+1, v);
3384 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003385
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003386 res = PyTuple_Pack(5, newobj, args2, state, listitems, dictitems);
Guido van Rossum036f9992003-02-21 22:02:54 +00003387
3388 end:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003389 Py_XDECREF(args);
3390 Py_XDECREF(args2);
3391 Py_XDECREF(slots);
3392 Py_XDECREF(state);
3393 Py_XDECREF(names);
3394 Py_XDECREF(listitems);
3395 Py_XDECREF(dictitems);
3396 Py_XDECREF(copyreg);
3397 Py_XDECREF(newobj);
3398 return res;
Guido van Rossum036f9992003-02-21 22:02:54 +00003399}
3400
Guido van Rossumd8faa362007-04-27 19:54:29 +00003401/*
3402 * There were two problems when object.__reduce__ and object.__reduce_ex__
3403 * were implemented in the same function:
3404 * - trying to pickle an object with a custom __reduce__ method that
3405 * fell back to object.__reduce__ in certain circumstances led to
3406 * infinite recursion at Python level and eventual RuntimeError.
3407 * - Pickling objects that lied about their type by overwriting the
3408 * __class__ descriptor could lead to infinite recursion at C level
3409 * and eventual segfault.
3410 *
3411 * Because of backwards compatibility, the two methods still have to
3412 * behave in the same way, even if this is not required by the pickle
3413 * protocol. This common functionality was moved to the _common_reduce
3414 * function.
3415 */
3416static PyObject *
3417_common_reduce(PyObject *self, int proto)
3418{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003419 PyObject *copyreg, *res;
Guido van Rossumd8faa362007-04-27 19:54:29 +00003420
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003421 if (proto >= 2)
3422 return reduce_2(self);
Guido van Rossumd8faa362007-04-27 19:54:29 +00003423
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003424 copyreg = import_copyreg();
3425 if (!copyreg)
3426 return NULL;
Guido van Rossumd8faa362007-04-27 19:54:29 +00003427
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003428 res = PyEval_CallMethod(copyreg, "_reduce_ex", "(Oi)", self, proto);
3429 Py_DECREF(copyreg);
Guido van Rossumd8faa362007-04-27 19:54:29 +00003430
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003431 return res;
Guido van Rossumd8faa362007-04-27 19:54:29 +00003432}
3433
3434static PyObject *
3435object_reduce(PyObject *self, PyObject *args)
3436{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003437 int proto = 0;
Guido van Rossumd8faa362007-04-27 19:54:29 +00003438
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003439 if (!PyArg_ParseTuple(args, "|i:__reduce__", &proto))
3440 return NULL;
Guido van Rossumd8faa362007-04-27 19:54:29 +00003441
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003442 return _common_reduce(self, proto);
Guido van Rossumd8faa362007-04-27 19:54:29 +00003443}
3444
Guido van Rossum036f9992003-02-21 22:02:54 +00003445static PyObject *
3446object_reduce_ex(PyObject *self, PyObject *args)
3447{
Victor Stinner3c1e4812012-03-26 22:10:51 +02003448 static PyObject *objreduce;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003449 PyObject *reduce, *res;
3450 int proto = 0;
Victor Stinner3c1e4812012-03-26 22:10:51 +02003451 _Py_IDENTIFIER(__reduce__);
Guido van Rossum036f9992003-02-21 22:02:54 +00003452
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003453 if (!PyArg_ParseTuple(args, "|i:__reduce_ex__", &proto))
3454 return NULL;
Guido van Rossum036f9992003-02-21 22:02:54 +00003455
Victor Stinner3c1e4812012-03-26 22:10:51 +02003456 if (objreduce == NULL) {
3457 objreduce = _PyDict_GetItemId(PyBaseObject_Type.tp_dict,
3458 &PyId___reduce__);
3459 if (objreduce == NULL)
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003460 return NULL;
3461 }
3462
Victor Stinner3c1e4812012-03-26 22:10:51 +02003463 reduce = _PyObject_GetAttrId(self, &PyId___reduce__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003464 if (reduce == NULL)
3465 PyErr_Clear();
3466 else {
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003467 PyObject *cls, *clsreduce;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003468 int override;
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003469
3470 cls = (PyObject *) Py_TYPE(self);
Victor Stinner3c1e4812012-03-26 22:10:51 +02003471 clsreduce = _PyObject_GetAttrId(cls, &PyId___reduce__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003472 if (clsreduce == NULL) {
3473 Py_DECREF(reduce);
3474 return NULL;
3475 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003476 override = (clsreduce != objreduce);
3477 Py_DECREF(clsreduce);
3478 if (override) {
3479 res = PyObject_CallObject(reduce, NULL);
3480 Py_DECREF(reduce);
3481 return res;
3482 }
3483 else
3484 Py_DECREF(reduce);
3485 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003486
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003487 return _common_reduce(self, proto);
Guido van Rossum3926a632001-09-25 16:25:58 +00003488}
3489
Christian Heimes9e7f1d22008-02-28 12:27:11 +00003490static PyObject *
3491object_subclasshook(PyObject *cls, PyObject *args)
3492{
Brian Curtindfc80e32011-08-10 20:28:54 -05003493 Py_RETURN_NOTIMPLEMENTED;
Christian Heimes9e7f1d22008-02-28 12:27:11 +00003494}
3495
3496PyDoc_STRVAR(object_subclasshook_doc,
3497"Abstract classes can override this to customize issubclass().\n"
3498"\n"
3499"This is invoked early on by abc.ABCMeta.__subclasscheck__().\n"
3500"It should return True, False or NotImplemented. If it returns\n"
3501"NotImplemented, the normal algorithm is used. Otherwise, it\n"
3502"overrides the normal algorithm (and the outcome is cached).\n");
Eric Smith8c663262007-08-25 02:26:07 +00003503
3504/*
3505 from PEP 3101, this code implements:
3506
3507 class object:
3508 def __format__(self, format_spec):
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003509 return format(str(self), format_spec)
Eric Smith8c663262007-08-25 02:26:07 +00003510*/
3511static PyObject *
3512object_format(PyObject *self, PyObject *args)
3513{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003514 PyObject *format_spec;
3515 PyObject *self_as_str = NULL;
3516 PyObject *result = NULL;
Eric Smith8c663262007-08-25 02:26:07 +00003517
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003518 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
3519 return NULL;
Eric Smith8c663262007-08-25 02:26:07 +00003520
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003521 self_as_str = PyObject_Str(self);
Eric Smithe4d63172010-09-13 20:48:43 +00003522 if (self_as_str != NULL) {
3523 /* Issue 7994: If we're converting to a string, we
Eric V. Smithb9cd3532011-03-12 10:08:48 -05003524 should reject format specifications */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003525 if (PyUnicode_GET_LENGTH(format_spec) > 0) {
Eric V. Smithb9cd3532011-03-12 10:08:48 -05003526 if (PyErr_WarnEx(PyExc_DeprecationWarning,
3527 "object.__format__ with a non-empty format "
3528 "string is deprecated", 1) < 0) {
3529 goto done;
3530 }
3531 /* Eventually this will become an error:
3532 PyErr_Format(PyExc_TypeError,
3533 "non-empty format string passed to object.__format__");
3534 goto done;
3535 */
3536 }
Eric Smith8c663262007-08-25 02:26:07 +00003537
Eric V. Smithb9cd3532011-03-12 10:08:48 -05003538 result = PyObject_Format(self_as_str, format_spec);
Eric Smithe4d63172010-09-13 20:48:43 +00003539 }
3540
3541done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003542 Py_XDECREF(self_as_str);
Eric Smith8c663262007-08-25 02:26:07 +00003543
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003544 return result;
Eric Smith8c663262007-08-25 02:26:07 +00003545}
3546
Martin v. Löwis00709aa2008-06-04 14:18:43 +00003547static PyObject *
3548object_sizeof(PyObject *self, PyObject *args)
3549{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003550 Py_ssize_t res, isize;
Martin v. Löwis00709aa2008-06-04 14:18:43 +00003551
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003552 res = 0;
3553 isize = self->ob_type->tp_itemsize;
3554 if (isize > 0)
3555 res = Py_SIZE(self->ob_type) * isize;
3556 res += self->ob_type->tp_basicsize;
Martin v. Löwis00709aa2008-06-04 14:18:43 +00003557
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003558 return PyLong_FromSsize_t(res);
Martin v. Löwis00709aa2008-06-04 14:18:43 +00003559}
3560
Benjamin Peterson82b00c12011-05-24 11:09:06 -05003561/* __dir__ for generic objects: returns __dict__, __class__,
3562 and recursively up the __class__.__bases__ chain.
3563*/
3564static PyObject *
3565object_dir(PyObject *self, PyObject *args)
3566{
3567 PyObject *result = NULL;
3568 PyObject *dict = NULL;
3569 PyObject *itsclass = NULL;
3570
3571 /* Get __dict__ (which may or may not be a real dict...) */
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02003572 dict = _PyObject_GetAttrId(self, &PyId___dict__);
Benjamin Peterson82b00c12011-05-24 11:09:06 -05003573 if (dict == NULL) {
3574 PyErr_Clear();
3575 dict = PyDict_New();
3576 }
3577 else if (!PyDict_Check(dict)) {
3578 Py_DECREF(dict);
3579 dict = PyDict_New();
3580 }
3581 else {
3582 /* Copy __dict__ to avoid mutating it. */
3583 PyObject *temp = PyDict_Copy(dict);
3584 Py_DECREF(dict);
3585 dict = temp;
3586 }
3587
3588 if (dict == NULL)
3589 goto error;
3590
3591 /* Merge in attrs reachable from its class. */
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02003592 itsclass = _PyObject_GetAttrId(self, &PyId___class__);
Benjamin Peterson82b00c12011-05-24 11:09:06 -05003593 if (itsclass == NULL)
3594 /* XXX(tomer): Perhaps fall back to obj->ob_type if no
3595 __class__ exists? */
3596 PyErr_Clear();
3597 else if (merge_class_dict(dict, itsclass) != 0)
3598 goto error;
3599
3600 result = PyDict_Keys(dict);
3601 /* fall through */
3602error:
3603 Py_XDECREF(itsclass);
3604 Py_XDECREF(dict);
3605 return result;
3606}
3607
Guido van Rossum3926a632001-09-25 16:25:58 +00003608static PyMethodDef object_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003609 {"__reduce_ex__", object_reduce_ex, METH_VARARGS,
3610 PyDoc_STR("helper for pickle")},
3611 {"__reduce__", object_reduce, METH_VARARGS,
3612 PyDoc_STR("helper for pickle")},
3613 {"__subclasshook__", object_subclasshook, METH_CLASS | METH_VARARGS,
3614 object_subclasshook_doc},
3615 {"__format__", object_format, METH_VARARGS,
3616 PyDoc_STR("default object formatter")},
3617 {"__sizeof__", object_sizeof, METH_NOARGS,
Benjamin Petersonfbe56bb2011-05-24 12:42:51 -05003618 PyDoc_STR("__sizeof__() -> int\nsize of object in memory, in bytes")},
Benjamin Peterson82b00c12011-05-24 11:09:06 -05003619 {"__dir__", object_dir, METH_NOARGS,
Benjamin Petersonc7284122011-05-24 12:46:15 -05003620 PyDoc_STR("__dir__() -> list\ndefault dir() implementation")},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003621 {0}
Guido van Rossum3926a632001-09-25 16:25:58 +00003622};
3623
Guido van Rossum036f9992003-02-21 22:02:54 +00003624
Tim Peters6d6c1a32001-08-02 04:15:00 +00003625PyTypeObject PyBaseObject_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003626 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3627 "object", /* tp_name */
3628 sizeof(PyObject), /* tp_basicsize */
3629 0, /* tp_itemsize */
3630 object_dealloc, /* tp_dealloc */
3631 0, /* tp_print */
3632 0, /* tp_getattr */
3633 0, /* tp_setattr */
3634 0, /* tp_reserved */
3635 object_repr, /* tp_repr */
3636 0, /* tp_as_number */
3637 0, /* tp_as_sequence */
3638 0, /* tp_as_mapping */
3639 (hashfunc)_Py_HashPointer, /* tp_hash */
3640 0, /* tp_call */
3641 object_str, /* tp_str */
3642 PyObject_GenericGetAttr, /* tp_getattro */
3643 PyObject_GenericSetAttr, /* tp_setattro */
3644 0, /* tp_as_buffer */
3645 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
3646 PyDoc_STR("The most base type"), /* tp_doc */
3647 0, /* tp_traverse */
3648 0, /* tp_clear */
3649 object_richcompare, /* tp_richcompare */
3650 0, /* tp_weaklistoffset */
3651 0, /* tp_iter */
3652 0, /* tp_iternext */
3653 object_methods, /* tp_methods */
3654 0, /* tp_members */
3655 object_getsets, /* tp_getset */
3656 0, /* tp_base */
3657 0, /* tp_dict */
3658 0, /* tp_descr_get */
3659 0, /* tp_descr_set */
3660 0, /* tp_dictoffset */
3661 object_init, /* tp_init */
3662 PyType_GenericAlloc, /* tp_alloc */
3663 object_new, /* tp_new */
3664 PyObject_Del, /* tp_free */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003665};
3666
3667
Guido van Rossum50e9fb92006-08-17 05:42:55 +00003668/* Add the methods from tp_methods to the __dict__ in a type object */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003669
3670static int
3671add_methods(PyTypeObject *type, PyMethodDef *meth)
3672{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003673 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003674
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003675 for (; meth->ml_name != NULL; meth++) {
3676 PyObject *descr;
3677 if (PyDict_GetItemString(dict, meth->ml_name) &&
3678 !(meth->ml_flags & METH_COEXIST))
3679 continue;
3680 if (meth->ml_flags & METH_CLASS) {
3681 if (meth->ml_flags & METH_STATIC) {
3682 PyErr_SetString(PyExc_ValueError,
3683 "method cannot be both class and static");
3684 return -1;
3685 }
3686 descr = PyDescr_NewClassMethod(type, meth);
3687 }
3688 else if (meth->ml_flags & METH_STATIC) {
Antoine Pitrou5b629422011-12-23 12:40:16 +01003689 PyObject *cfunc = PyCFunction_New(meth, (PyObject*)type);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003690 if (cfunc == NULL)
3691 return -1;
3692 descr = PyStaticMethod_New(cfunc);
3693 Py_DECREF(cfunc);
3694 }
3695 else {
3696 descr = PyDescr_NewMethod(type, meth);
3697 }
3698 if (descr == NULL)
3699 return -1;
3700 if (PyDict_SetItemString(dict, meth->ml_name, descr) < 0)
3701 return -1;
3702 Py_DECREF(descr);
3703 }
3704 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003705}
3706
3707static int
Guido van Rossum6f799372001-09-20 20:46:19 +00003708add_members(PyTypeObject *type, PyMemberDef *memb)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003709{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003710 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003711
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003712 for (; memb->name != NULL; memb++) {
3713 PyObject *descr;
3714 if (PyDict_GetItemString(dict, memb->name))
3715 continue;
3716 descr = PyDescr_NewMember(type, memb);
3717 if (descr == NULL)
3718 return -1;
3719 if (PyDict_SetItemString(dict, memb->name, descr) < 0)
3720 return -1;
3721 Py_DECREF(descr);
3722 }
3723 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003724}
3725
3726static int
Guido van Rossum32d34c82001-09-20 21:45:26 +00003727add_getset(PyTypeObject *type, PyGetSetDef *gsp)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003728{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003729 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003730
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003731 for (; gsp->name != NULL; gsp++) {
3732 PyObject *descr;
3733 if (PyDict_GetItemString(dict, gsp->name))
3734 continue;
3735 descr = PyDescr_NewGetSet(type, gsp);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003736
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003737 if (descr == NULL)
3738 return -1;
3739 if (PyDict_SetItemString(dict, gsp->name, descr) < 0)
3740 return -1;
3741 Py_DECREF(descr);
3742 }
3743 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003744}
3745
Guido van Rossum13d52f02001-08-10 21:24:08 +00003746static void
3747inherit_special(PyTypeObject *type, PyTypeObject *base)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003748{
Tim Peters6d6c1a32001-08-02 04:15:00 +00003749
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003750 /* Copying basicsize is connected to the GC flags */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003751 if (!(type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
3752 (base->tp_flags & Py_TPFLAGS_HAVE_GC) &&
3753 (!type->tp_traverse && !type->tp_clear)) {
3754 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
3755 if (type->tp_traverse == NULL)
3756 type->tp_traverse = base->tp_traverse;
3757 if (type->tp_clear == NULL)
3758 type->tp_clear = base->tp_clear;
3759 }
3760 {
3761 /* The condition below could use some explanation.
3762 It appears that tp_new is not inherited for static types
3763 whose base class is 'object'; this seems to be a precaution
3764 so that old extension types don't suddenly become
3765 callable (object.__new__ wouldn't insure the invariants
3766 that the extension type's own factory function ensures).
3767 Heap types, of course, are under our control, so they do
3768 inherit tp_new; static extension types that specify some
Florent Xiclunaaa6c1d22011-12-12 18:54:29 +01003769 other built-in type as the default also
3770 inherit object.__new__. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003771 if (base != &PyBaseObject_Type ||
3772 (type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
3773 if (type->tp_new == NULL)
3774 type->tp_new = base->tp_new;
3775 }
3776 }
Benjamin Petersona7465e22010-07-05 15:01:22 +00003777 if (type->tp_basicsize == 0)
3778 type->tp_basicsize = base->tp_basicsize;
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00003779
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003780 /* Copy other non-function slots */
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00003781
3782#undef COPYVAL
3783#define COPYVAL(SLOT) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003784 if (type->SLOT == 0) type->SLOT = base->SLOT
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00003785
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003786 COPYVAL(tp_itemsize);
3787 COPYVAL(tp_weaklistoffset);
3788 COPYVAL(tp_dictoffset);
Thomas Wouters27d517b2007-02-25 20:39:11 +00003789
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003790 /* Setup fast subclass flags */
3791 if (PyType_IsSubtype(base, (PyTypeObject*)PyExc_BaseException))
3792 type->tp_flags |= Py_TPFLAGS_BASE_EXC_SUBCLASS;
3793 else if (PyType_IsSubtype(base, &PyType_Type))
3794 type->tp_flags |= Py_TPFLAGS_TYPE_SUBCLASS;
3795 else if (PyType_IsSubtype(base, &PyLong_Type))
3796 type->tp_flags |= Py_TPFLAGS_LONG_SUBCLASS;
3797 else if (PyType_IsSubtype(base, &PyBytes_Type))
3798 type->tp_flags |= Py_TPFLAGS_BYTES_SUBCLASS;
3799 else if (PyType_IsSubtype(base, &PyUnicode_Type))
3800 type->tp_flags |= Py_TPFLAGS_UNICODE_SUBCLASS;
3801 else if (PyType_IsSubtype(base, &PyTuple_Type))
3802 type->tp_flags |= Py_TPFLAGS_TUPLE_SUBCLASS;
3803 else if (PyType_IsSubtype(base, &PyList_Type))
3804 type->tp_flags |= Py_TPFLAGS_LIST_SUBCLASS;
3805 else if (PyType_IsSubtype(base, &PyDict_Type))
3806 type->tp_flags |= Py_TPFLAGS_DICT_SUBCLASS;
Guido van Rossum13d52f02001-08-10 21:24:08 +00003807}
3808
Guido van Rossum38938152006-08-21 23:36:26 +00003809static int
Guido van Rossumf5243f02008-01-01 04:06:48 +00003810overrides_hash(PyTypeObject *type)
Guido van Rossum38938152006-08-21 23:36:26 +00003811{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003812 PyObject *dict = type->tp_dict;
Victor Stinner3c1e4812012-03-26 22:10:51 +02003813 _Py_IDENTIFIER(__eq__);
Guido van Rossum38938152006-08-21 23:36:26 +00003814
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003815 assert(dict != NULL);
Victor Stinner3c1e4812012-03-26 22:10:51 +02003816 if (_PyDict_GetItemId(dict, &PyId___eq__) != NULL)
3817 return 1;
3818 if (_PyDict_GetItemId(dict, &PyId___hash__) != NULL)
3819 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003820 return 0;
Guido van Rossum38938152006-08-21 23:36:26 +00003821}
3822
Guido van Rossum13d52f02001-08-10 21:24:08 +00003823static void
3824inherit_slots(PyTypeObject *type, PyTypeObject *base)
3825{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003826 PyTypeObject *basebase;
Guido van Rossum13d52f02001-08-10 21:24:08 +00003827
3828#undef SLOTDEFINED
Tim Peters6d6c1a32001-08-02 04:15:00 +00003829#undef COPYSLOT
3830#undef COPYNUM
3831#undef COPYSEQ
3832#undef COPYMAP
Guido van Rossum5af588b2001-10-12 14:13:21 +00003833#undef COPYBUF
Guido van Rossum13d52f02001-08-10 21:24:08 +00003834
3835#define SLOTDEFINED(SLOT) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003836 (base->SLOT != 0 && \
3837 (basebase == NULL || base->SLOT != basebase->SLOT))
Guido van Rossum13d52f02001-08-10 21:24:08 +00003838
Tim Peters6d6c1a32001-08-02 04:15:00 +00003839#define COPYSLOT(SLOT) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003840 if (!type->SLOT && SLOTDEFINED(SLOT)) type->SLOT = base->SLOT
Tim Peters6d6c1a32001-08-02 04:15:00 +00003841
3842#define COPYNUM(SLOT) COPYSLOT(tp_as_number->SLOT)
3843#define COPYSEQ(SLOT) COPYSLOT(tp_as_sequence->SLOT)
3844#define COPYMAP(SLOT) COPYSLOT(tp_as_mapping->SLOT)
Tim Petersfc57ccb2001-10-12 02:38:24 +00003845#define COPYBUF(SLOT) COPYSLOT(tp_as_buffer->SLOT)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003846
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003847 /* This won't inherit indirect slots (from tp_as_number etc.)
3848 if type doesn't provide the space. */
Guido van Rossum13d52f02001-08-10 21:24:08 +00003849
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003850 if (type->tp_as_number != NULL && base->tp_as_number != NULL) {
3851 basebase = base->tp_base;
3852 if (basebase->tp_as_number == NULL)
3853 basebase = NULL;
3854 COPYNUM(nb_add);
3855 COPYNUM(nb_subtract);
3856 COPYNUM(nb_multiply);
3857 COPYNUM(nb_remainder);
3858 COPYNUM(nb_divmod);
3859 COPYNUM(nb_power);
3860 COPYNUM(nb_negative);
3861 COPYNUM(nb_positive);
3862 COPYNUM(nb_absolute);
3863 COPYNUM(nb_bool);
3864 COPYNUM(nb_invert);
3865 COPYNUM(nb_lshift);
3866 COPYNUM(nb_rshift);
3867 COPYNUM(nb_and);
3868 COPYNUM(nb_xor);
3869 COPYNUM(nb_or);
3870 COPYNUM(nb_int);
3871 COPYNUM(nb_float);
3872 COPYNUM(nb_inplace_add);
3873 COPYNUM(nb_inplace_subtract);
3874 COPYNUM(nb_inplace_multiply);
3875 COPYNUM(nb_inplace_remainder);
3876 COPYNUM(nb_inplace_power);
3877 COPYNUM(nb_inplace_lshift);
3878 COPYNUM(nb_inplace_rshift);
3879 COPYNUM(nb_inplace_and);
3880 COPYNUM(nb_inplace_xor);
3881 COPYNUM(nb_inplace_or);
3882 COPYNUM(nb_true_divide);
3883 COPYNUM(nb_floor_divide);
3884 COPYNUM(nb_inplace_true_divide);
3885 COPYNUM(nb_inplace_floor_divide);
3886 COPYNUM(nb_index);
3887 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003888
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003889 if (type->tp_as_sequence != NULL && base->tp_as_sequence != NULL) {
3890 basebase = base->tp_base;
3891 if (basebase->tp_as_sequence == NULL)
3892 basebase = NULL;
3893 COPYSEQ(sq_length);
3894 COPYSEQ(sq_concat);
3895 COPYSEQ(sq_repeat);
3896 COPYSEQ(sq_item);
3897 COPYSEQ(sq_ass_item);
3898 COPYSEQ(sq_contains);
3899 COPYSEQ(sq_inplace_concat);
3900 COPYSEQ(sq_inplace_repeat);
3901 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003902
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003903 if (type->tp_as_mapping != NULL && base->tp_as_mapping != NULL) {
3904 basebase = base->tp_base;
3905 if (basebase->tp_as_mapping == NULL)
3906 basebase = NULL;
3907 COPYMAP(mp_length);
3908 COPYMAP(mp_subscript);
3909 COPYMAP(mp_ass_subscript);
3910 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003911
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003912 if (type->tp_as_buffer != NULL && base->tp_as_buffer != NULL) {
3913 basebase = base->tp_base;
3914 if (basebase->tp_as_buffer == NULL)
3915 basebase = NULL;
3916 COPYBUF(bf_getbuffer);
3917 COPYBUF(bf_releasebuffer);
3918 }
Tim Petersfc57ccb2001-10-12 02:38:24 +00003919
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003920 basebase = base->tp_base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003921
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003922 COPYSLOT(tp_dealloc);
3923 if (type->tp_getattr == NULL && type->tp_getattro == NULL) {
3924 type->tp_getattr = base->tp_getattr;
3925 type->tp_getattro = base->tp_getattro;
3926 }
3927 if (type->tp_setattr == NULL && type->tp_setattro == NULL) {
3928 type->tp_setattr = base->tp_setattr;
3929 type->tp_setattro = base->tp_setattro;
3930 }
3931 /* tp_reserved is ignored */
3932 COPYSLOT(tp_repr);
3933 /* tp_hash see tp_richcompare */
3934 COPYSLOT(tp_call);
3935 COPYSLOT(tp_str);
3936 {
3937 /* Copy comparison-related slots only when
3938 not overriding them anywhere */
3939 if (type->tp_richcompare == NULL &&
3940 type->tp_hash == NULL &&
3941 !overrides_hash(type))
3942 {
3943 type->tp_richcompare = base->tp_richcompare;
3944 type->tp_hash = base->tp_hash;
3945 }
3946 }
3947 {
3948 COPYSLOT(tp_iter);
3949 COPYSLOT(tp_iternext);
3950 }
3951 {
3952 COPYSLOT(tp_descr_get);
3953 COPYSLOT(tp_descr_set);
3954 COPYSLOT(tp_dictoffset);
3955 COPYSLOT(tp_init);
3956 COPYSLOT(tp_alloc);
3957 COPYSLOT(tp_is_gc);
3958 if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) ==
3959 (base->tp_flags & Py_TPFLAGS_HAVE_GC)) {
3960 /* They agree about gc. */
3961 COPYSLOT(tp_free);
3962 }
3963 else if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
3964 type->tp_free == NULL &&
3965 base->tp_free == PyObject_Free) {
3966 /* A bit of magic to plug in the correct default
3967 * tp_free function when a derived class adds gc,
3968 * didn't define tp_free, and the base uses the
3969 * default non-gc tp_free.
3970 */
3971 type->tp_free = PyObject_GC_Del;
3972 }
3973 /* else they didn't agree about gc, and there isn't something
3974 * obvious to be done -- the type is on its own.
3975 */
3976 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003977}
3978
Jeremy Hylton938ace62002-07-17 16:30:39 +00003979static int add_operators(PyTypeObject *);
Guido van Rossum13d52f02001-08-10 21:24:08 +00003980
Tim Peters6d6c1a32001-08-02 04:15:00 +00003981int
Guido van Rossum528b7eb2001-08-07 17:24:28 +00003982PyType_Ready(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003983{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003984 PyObject *dict, *bases;
3985 PyTypeObject *base;
3986 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003987
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003988 if (type->tp_flags & Py_TPFLAGS_READY) {
3989 assert(type->tp_dict != NULL);
3990 return 0;
3991 }
3992 assert((type->tp_flags & Py_TPFLAGS_READYING) == 0);
Guido van Rossumd614f972001-08-10 17:39:49 +00003993
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003994 type->tp_flags |= Py_TPFLAGS_READYING;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003995
Tim Peters36eb4df2003-03-23 03:33:13 +00003996#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003997 /* PyType_Ready is the closest thing we have to a choke point
3998 * for type objects, so is the best place I can think of to try
3999 * to get type objects into the doubly-linked list of all objects.
4000 * Still, not all type objects go thru PyType_Ready.
4001 */
4002 _Py_AddToAllObjects((PyObject *)type, 0);
Tim Peters36eb4df2003-03-23 03:33:13 +00004003#endif
4004
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004005 /* Initialize tp_base (defaults to BaseObject unless that's us) */
4006 base = type->tp_base;
4007 if (base == NULL && type != &PyBaseObject_Type) {
4008 base = type->tp_base = &PyBaseObject_Type;
4009 Py_INCREF(base);
4010 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004011
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004012 /* Now the only way base can still be NULL is if type is
4013 * &PyBaseObject_Type.
4014 */
Guido van Rossum692cdbc2006-03-10 02:04:28 +00004015
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004016 /* Initialize the base class */
4017 if (base != NULL && base->tp_dict == NULL) {
4018 if (PyType_Ready(base) < 0)
4019 goto error;
4020 }
Guido van Rossum323a9cf2002-08-14 17:26:30 +00004021
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004022 /* Initialize ob_type if NULL. This means extensions that want to be
4023 compilable separately on Windows can call PyType_Ready() instead of
4024 initializing the ob_type field of their type objects. */
4025 /* The test for base != NULL is really unnecessary, since base is only
4026 NULL when type is &PyBaseObject_Type, and we know its ob_type is
4027 not NULL (it's initialized to &PyType_Type). But coverity doesn't
4028 know that. */
4029 if (Py_TYPE(type) == NULL && base != NULL)
4030 Py_TYPE(type) = Py_TYPE(base);
Guido van Rossum0986d822002-04-08 01:38:42 +00004031
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004032 /* Initialize tp_bases */
4033 bases = type->tp_bases;
4034 if (bases == NULL) {
4035 if (base == NULL)
4036 bases = PyTuple_New(0);
4037 else
4038 bases = PyTuple_Pack(1, base);
4039 if (bases == NULL)
4040 goto error;
4041 type->tp_bases = bases;
4042 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004043
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004044 /* Initialize tp_dict */
4045 dict = type->tp_dict;
4046 if (dict == NULL) {
4047 dict = PyDict_New();
4048 if (dict == NULL)
4049 goto error;
4050 type->tp_dict = dict;
4051 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004052
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004053 /* Add type-specific descriptors to tp_dict */
4054 if (add_operators(type) < 0)
4055 goto error;
4056 if (type->tp_methods != NULL) {
4057 if (add_methods(type, type->tp_methods) < 0)
4058 goto error;
4059 }
4060 if (type->tp_members != NULL) {
4061 if (add_members(type, type->tp_members) < 0)
4062 goto error;
4063 }
4064 if (type->tp_getset != NULL) {
4065 if (add_getset(type, type->tp_getset) < 0)
4066 goto error;
4067 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004068
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004069 /* Calculate method resolution order */
4070 if (mro_internal(type) < 0) {
4071 goto error;
4072 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004073
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004074 /* Inherit special flags from dominant base */
4075 if (type->tp_base != NULL)
4076 inherit_special(type, type->tp_base);
Guido van Rossum13d52f02001-08-10 21:24:08 +00004077
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004078 /* Initialize tp_dict properly */
4079 bases = type->tp_mro;
4080 assert(bases != NULL);
4081 assert(PyTuple_Check(bases));
4082 n = PyTuple_GET_SIZE(bases);
4083 for (i = 1; i < n; i++) {
4084 PyObject *b = PyTuple_GET_ITEM(bases, i);
4085 if (PyType_Check(b))
4086 inherit_slots(type, (PyTypeObject *)b);
4087 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004088
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004089 /* Sanity check for tp_free. */
4090 if (PyType_IS_GC(type) && (type->tp_flags & Py_TPFLAGS_BASETYPE) &&
4091 (type->tp_free == NULL || type->tp_free == PyObject_Del)) {
4092 /* This base class needs to call tp_free, but doesn't have
4093 * one, or its tp_free is for non-gc'ed objects.
4094 */
4095 PyErr_Format(PyExc_TypeError, "type '%.100s' participates in "
4096 "gc and is a base type but has inappropriate "
4097 "tp_free slot",
4098 type->tp_name);
4099 goto error;
4100 }
Tim Peters3cfe7542003-05-21 21:29:48 +00004101
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004102 /* if the type dictionary doesn't contain a __doc__, set it from
4103 the tp_doc slot.
4104 */
Victor Stinner3c1e4812012-03-26 22:10:51 +02004105 if (_PyDict_GetItemId(type->tp_dict, &PyId___doc__) == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004106 if (type->tp_doc != NULL) {
4107 PyObject *doc = PyUnicode_FromString(type->tp_doc);
4108 if (doc == NULL)
4109 goto error;
Victor Stinner3c1e4812012-03-26 22:10:51 +02004110 _PyDict_SetItemId(type->tp_dict, &PyId___doc__, doc);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004111 Py_DECREF(doc);
4112 } else {
Victor Stinner3c1e4812012-03-26 22:10:51 +02004113 _PyDict_SetItemId(type->tp_dict,
4114 &PyId___doc__, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004115 }
4116 }
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00004117
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004118 /* Hack for tp_hash and __hash__.
4119 If after all that, tp_hash is still NULL, and __hash__ is not in
4120 tp_dict, set tp_hash to PyObject_HashNotImplemented and
4121 tp_dict['__hash__'] equal to None.
4122 This signals that __hash__ is not inherited.
4123 */
4124 if (type->tp_hash == NULL) {
Victor Stinner3c1e4812012-03-26 22:10:51 +02004125 if (_PyDict_GetItemId(type->tp_dict, &PyId___hash__) == NULL) {
4126 if (_PyDict_SetItemId(type->tp_dict, &PyId___hash__, Py_None) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004127 goto error;
4128 type->tp_hash = PyObject_HashNotImplemented;
4129 }
4130 }
Guido van Rossum38938152006-08-21 23:36:26 +00004131
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004132 /* Some more special stuff */
4133 base = type->tp_base;
4134 if (base != NULL) {
4135 if (type->tp_as_number == NULL)
4136 type->tp_as_number = base->tp_as_number;
4137 if (type->tp_as_sequence == NULL)
4138 type->tp_as_sequence = base->tp_as_sequence;
4139 if (type->tp_as_mapping == NULL)
4140 type->tp_as_mapping = base->tp_as_mapping;
4141 if (type->tp_as_buffer == NULL)
4142 type->tp_as_buffer = base->tp_as_buffer;
4143 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004144
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004145 /* Link into each base class's list of subclasses */
4146 bases = type->tp_bases;
4147 n = PyTuple_GET_SIZE(bases);
4148 for (i = 0; i < n; i++) {
4149 PyObject *b = PyTuple_GET_ITEM(bases, i);
4150 if (PyType_Check(b) &&
4151 add_subclass((PyTypeObject *)b, type) < 0)
4152 goto error;
4153 }
Guido van Rossum1c450732001-10-08 15:18:27 +00004154
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004155 /* Warn for a type that implements tp_compare (now known as
4156 tp_reserved) but not tp_richcompare. */
4157 if (type->tp_reserved && !type->tp_richcompare) {
4158 int error;
Victor Stinner4a2b7a12010-08-13 14:03:48 +00004159 error = PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
4160 "Type %.100s defines tp_reserved (formerly tp_compare) "
4161 "but not tp_richcompare. Comparisons may not behave as intended.",
4162 type->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004163 if (error == -1)
4164 goto error;
4165 }
Mark Dickinson2a7d45b2009-02-08 11:02:10 +00004166
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004167 /* All done -- set the ready flag */
4168 assert(type->tp_dict != NULL);
4169 type->tp_flags =
4170 (type->tp_flags & ~Py_TPFLAGS_READYING) | Py_TPFLAGS_READY;
4171 return 0;
Guido van Rossumd614f972001-08-10 17:39:49 +00004172
4173 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004174 type->tp_flags &= ~Py_TPFLAGS_READYING;
4175 return -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004176}
4177
Guido van Rossum1c450732001-10-08 15:18:27 +00004178static int
4179add_subclass(PyTypeObject *base, PyTypeObject *type)
4180{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004181 Py_ssize_t i;
4182 int result;
4183 PyObject *list, *ref, *newobj;
Guido van Rossum1c450732001-10-08 15:18:27 +00004184
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004185 list = base->tp_subclasses;
4186 if (list == NULL) {
4187 base->tp_subclasses = list = PyList_New(0);
4188 if (list == NULL)
4189 return -1;
4190 }
4191 assert(PyList_Check(list));
4192 newobj = PyWeakref_NewRef((PyObject *)type, NULL);
4193 i = PyList_GET_SIZE(list);
4194 while (--i >= 0) {
4195 ref = PyList_GET_ITEM(list, i);
4196 assert(PyWeakref_CheckRef(ref));
4197 if (PyWeakref_GET_OBJECT(ref) == Py_None)
4198 return PyList_SetItem(list, i, newobj);
4199 }
4200 result = PyList_Append(list, newobj);
4201 Py_DECREF(newobj);
4202 return result;
Guido van Rossum1c450732001-10-08 15:18:27 +00004203}
4204
Michael W. Hudson98bbc492002-11-26 14:47:27 +00004205static void
4206remove_subclass(PyTypeObject *base, PyTypeObject *type)
4207{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004208 Py_ssize_t i;
4209 PyObject *list, *ref;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00004210
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004211 list = base->tp_subclasses;
4212 if (list == NULL) {
4213 return;
4214 }
4215 assert(PyList_Check(list));
4216 i = PyList_GET_SIZE(list);
4217 while (--i >= 0) {
4218 ref = PyList_GET_ITEM(list, i);
4219 assert(PyWeakref_CheckRef(ref));
4220 if (PyWeakref_GET_OBJECT(ref) == (PyObject*)type) {
4221 /* this can't fail, right? */
4222 PySequence_DelItem(list, i);
4223 return;
4224 }
4225 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +00004226}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004227
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004228static int
4229check_num_args(PyObject *ob, int n)
4230{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004231 if (!PyTuple_CheckExact(ob)) {
4232 PyErr_SetString(PyExc_SystemError,
4233 "PyArg_UnpackTuple() argument list is not a tuple");
4234 return 0;
4235 }
4236 if (n == PyTuple_GET_SIZE(ob))
4237 return 1;
4238 PyErr_Format(
4239 PyExc_TypeError,
4240 "expected %d arguments, got %zd", n, PyTuple_GET_SIZE(ob));
4241 return 0;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004242}
4243
Tim Peters6d6c1a32001-08-02 04:15:00 +00004244/* Generic wrappers for overloadable 'operators' such as __getitem__ */
4245
4246/* There's a wrapper *function* for each distinct function typedef used
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004247 for type object slots (e.g. binaryfunc, ternaryfunc, etc.). There's a
Tim Peters6d6c1a32001-08-02 04:15:00 +00004248 wrapper *table* for each distinct operation (e.g. __len__, __add__).
4249 Most tables have only one entry; the tables for binary operators have two
4250 entries, one regular and one with reversed arguments. */
4251
4252static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00004253wrap_lenfunc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004254{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004255 lenfunc func = (lenfunc)wrapped;
4256 Py_ssize_t res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004257
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004258 if (!check_num_args(args, 0))
4259 return NULL;
4260 res = (*func)(self);
4261 if (res == -1 && PyErr_Occurred())
4262 return NULL;
4263 return PyLong_FromLong((long)res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004264}
4265
Tim Peters6d6c1a32001-08-02 04:15:00 +00004266static PyObject *
Raymond Hettingerf34f2642003-10-11 17:29:04 +00004267wrap_inquirypred(PyObject *self, PyObject *args, void *wrapped)
4268{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004269 inquiry func = (inquiry)wrapped;
4270 int res;
Raymond Hettingerf34f2642003-10-11 17:29:04 +00004271
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004272 if (!check_num_args(args, 0))
4273 return NULL;
4274 res = (*func)(self);
4275 if (res == -1 && PyErr_Occurred())
4276 return NULL;
4277 return PyBool_FromLong((long)res);
Raymond Hettingerf34f2642003-10-11 17:29:04 +00004278}
4279
4280static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00004281wrap_binaryfunc(PyObject *self, PyObject *args, void *wrapped)
4282{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004283 binaryfunc func = (binaryfunc)wrapped;
4284 PyObject *other;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004285
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004286 if (!check_num_args(args, 1))
4287 return NULL;
4288 other = PyTuple_GET_ITEM(args, 0);
4289 return (*func)(self, other);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004290}
4291
4292static PyObject *
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00004293wrap_binaryfunc_l(PyObject *self, PyObject *args, void *wrapped)
4294{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004295 binaryfunc func = (binaryfunc)wrapped;
4296 PyObject *other;
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00004297
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004298 if (!check_num_args(args, 1))
4299 return NULL;
4300 other = PyTuple_GET_ITEM(args, 0);
4301 return (*func)(self, other);
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00004302}
4303
4304static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00004305wrap_binaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
4306{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004307 binaryfunc func = (binaryfunc)wrapped;
4308 PyObject *other;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004309
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004310 if (!check_num_args(args, 1))
4311 return NULL;
4312 other = PyTuple_GET_ITEM(args, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004313 return (*func)(other, self);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004314}
4315
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004316static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00004317wrap_ternaryfunc(PyObject *self, PyObject *args, void *wrapped)
4318{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004319 ternaryfunc func = (ternaryfunc)wrapped;
4320 PyObject *other;
4321 PyObject *third = Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004322
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004323 /* Note: This wrapper only works for __pow__() */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004324
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004325 if (!PyArg_UnpackTuple(args, "", 1, 2, &other, &third))
4326 return NULL;
4327 return (*func)(self, other, third);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004328}
4329
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00004330static PyObject *
4331wrap_ternaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
4332{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004333 ternaryfunc func = (ternaryfunc)wrapped;
4334 PyObject *other;
4335 PyObject *third = Py_None;
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00004336
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004337 /* Note: This wrapper only works for __pow__() */
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00004338
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004339 if (!PyArg_UnpackTuple(args, "", 1, 2, &other, &third))
4340 return NULL;
4341 return (*func)(other, self, third);
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00004342}
4343
Tim Peters6d6c1a32001-08-02 04:15:00 +00004344static PyObject *
4345wrap_unaryfunc(PyObject *self, PyObject *args, void *wrapped)
4346{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004347 unaryfunc func = (unaryfunc)wrapped;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004348
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004349 if (!check_num_args(args, 0))
4350 return NULL;
4351 return (*func)(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004352}
4353
Tim Peters6d6c1a32001-08-02 04:15:00 +00004354static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004355wrap_indexargfunc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004356{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004357 ssizeargfunc func = (ssizeargfunc)wrapped;
4358 PyObject* o;
4359 Py_ssize_t i;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004360
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004361 if (!PyArg_UnpackTuple(args, "", 1, 1, &o))
4362 return NULL;
4363 i = PyNumber_AsSsize_t(o, PyExc_OverflowError);
4364 if (i == -1 && PyErr_Occurred())
4365 return NULL;
4366 return (*func)(self, i);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004367}
4368
Martin v. Löwis18e16552006-02-15 17:27:45 +00004369static Py_ssize_t
Guido van Rossum5d815f32001-08-17 21:57:47 +00004370getindex(PyObject *self, PyObject *arg)
4371{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004372 Py_ssize_t i;
Guido van Rossum5d815f32001-08-17 21:57:47 +00004373
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004374 i = PyNumber_AsSsize_t(arg, PyExc_OverflowError);
4375 if (i == -1 && PyErr_Occurred())
4376 return -1;
4377 if (i < 0) {
4378 PySequenceMethods *sq = Py_TYPE(self)->tp_as_sequence;
4379 if (sq && sq->sq_length) {
4380 Py_ssize_t n = (*sq->sq_length)(self);
4381 if (n < 0)
4382 return -1;
4383 i += n;
4384 }
4385 }
4386 return i;
Guido van Rossum5d815f32001-08-17 21:57:47 +00004387}
4388
4389static PyObject *
4390wrap_sq_item(PyObject *self, PyObject *args, void *wrapped)
4391{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004392 ssizeargfunc func = (ssizeargfunc)wrapped;
4393 PyObject *arg;
4394 Py_ssize_t i;
Guido van Rossum5d815f32001-08-17 21:57:47 +00004395
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004396 if (PyTuple_GET_SIZE(args) == 1) {
4397 arg = PyTuple_GET_ITEM(args, 0);
4398 i = getindex(self, arg);
4399 if (i == -1 && PyErr_Occurred())
4400 return NULL;
4401 return (*func)(self, i);
4402 }
4403 check_num_args(args, 1);
4404 assert(PyErr_Occurred());
4405 return NULL;
Guido van Rossum5d815f32001-08-17 21:57:47 +00004406}
4407
Tim Peters6d6c1a32001-08-02 04:15:00 +00004408static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00004409wrap_sq_setitem(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004410{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004411 ssizeobjargproc func = (ssizeobjargproc)wrapped;
4412 Py_ssize_t i;
4413 int res;
4414 PyObject *arg, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004415
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004416 if (!PyArg_UnpackTuple(args, "", 2, 2, &arg, &value))
4417 return NULL;
4418 i = getindex(self, arg);
4419 if (i == -1 && PyErr_Occurred())
4420 return NULL;
4421 res = (*func)(self, i, value);
4422 if (res == -1 && PyErr_Occurred())
4423 return NULL;
4424 Py_INCREF(Py_None);
4425 return Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004426}
4427
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004428static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00004429wrap_sq_delitem(PyObject *self, PyObject *args, void *wrapped)
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004430{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004431 ssizeobjargproc func = (ssizeobjargproc)wrapped;
4432 Py_ssize_t i;
4433 int res;
4434 PyObject *arg;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004435
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004436 if (!check_num_args(args, 1))
4437 return NULL;
4438 arg = PyTuple_GET_ITEM(args, 0);
4439 i = getindex(self, arg);
4440 if (i == -1 && PyErr_Occurred())
4441 return NULL;
4442 res = (*func)(self, i, NULL);
4443 if (res == -1 && PyErr_Occurred())
4444 return NULL;
4445 Py_INCREF(Py_None);
4446 return Py_None;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004447}
4448
Tim Peters6d6c1a32001-08-02 04:15:00 +00004449/* XXX objobjproc is a misnomer; should be objargpred */
4450static PyObject *
4451wrap_objobjproc(PyObject *self, PyObject *args, void *wrapped)
4452{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004453 objobjproc func = (objobjproc)wrapped;
4454 int res;
4455 PyObject *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004456
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004457 if (!check_num_args(args, 1))
4458 return NULL;
4459 value = PyTuple_GET_ITEM(args, 0);
4460 res = (*func)(self, value);
4461 if (res == -1 && PyErr_Occurred())
4462 return NULL;
4463 else
4464 return PyBool_FromLong(res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004465}
4466
Tim Peters6d6c1a32001-08-02 04:15:00 +00004467static PyObject *
4468wrap_objobjargproc(PyObject *self, PyObject *args, void *wrapped)
4469{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004470 objobjargproc func = (objobjargproc)wrapped;
4471 int res;
4472 PyObject *key, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004473
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004474 if (!PyArg_UnpackTuple(args, "", 2, 2, &key, &value))
4475 return NULL;
4476 res = (*func)(self, key, value);
4477 if (res == -1 && PyErr_Occurred())
4478 return NULL;
4479 Py_INCREF(Py_None);
4480 return Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004481}
4482
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004483static PyObject *
4484wrap_delitem(PyObject *self, PyObject *args, void *wrapped)
4485{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004486 objobjargproc func = (objobjargproc)wrapped;
4487 int res;
4488 PyObject *key;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004489
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004490 if (!check_num_args(args, 1))
4491 return NULL;
4492 key = PyTuple_GET_ITEM(args, 0);
4493 res = (*func)(self, key, NULL);
4494 if (res == -1 && PyErr_Occurred())
4495 return NULL;
4496 Py_INCREF(Py_None);
4497 return Py_None;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004498}
4499
Guido van Rossum4dcdb782003-04-14 21:46:03 +00004500/* Helper to check for object.__setattr__ or __delattr__ applied to a type.
Guido van Rossum52b27052003-04-15 20:05:10 +00004501 This is called the Carlo Verre hack after its discoverer. */
Guido van Rossum4dcdb782003-04-14 21:46:03 +00004502static int
4503hackcheck(PyObject *self, setattrofunc func, char *what)
4504{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004505 PyTypeObject *type = Py_TYPE(self);
4506 while (type && type->tp_flags & Py_TPFLAGS_HEAPTYPE)
4507 type = type->tp_base;
4508 /* If type is NULL now, this is a really weird type.
4509 In the spirit of backwards compatibility (?), just shut up. */
4510 if (type && type->tp_setattro != func) {
4511 PyErr_Format(PyExc_TypeError,
4512 "can't apply this %s to %s object",
4513 what,
4514 type->tp_name);
4515 return 0;
4516 }
4517 return 1;
Guido van Rossum4dcdb782003-04-14 21:46:03 +00004518}
4519
Tim Peters6d6c1a32001-08-02 04:15:00 +00004520static PyObject *
4521wrap_setattr(PyObject *self, PyObject *args, void *wrapped)
4522{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004523 setattrofunc func = (setattrofunc)wrapped;
4524 int res;
4525 PyObject *name, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004526
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004527 if (!PyArg_UnpackTuple(args, "", 2, 2, &name, &value))
4528 return NULL;
4529 if (!hackcheck(self, func, "__setattr__"))
4530 return NULL;
4531 res = (*func)(self, name, value);
4532 if (res < 0)
4533 return NULL;
4534 Py_INCREF(Py_None);
4535 return Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004536}
4537
4538static PyObject *
4539wrap_delattr(PyObject *self, PyObject *args, void *wrapped)
4540{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004541 setattrofunc func = (setattrofunc)wrapped;
4542 int res;
4543 PyObject *name;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004544
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004545 if (!check_num_args(args, 1))
4546 return NULL;
4547 name = PyTuple_GET_ITEM(args, 0);
4548 if (!hackcheck(self, func, "__delattr__"))
4549 return NULL;
4550 res = (*func)(self, name, NULL);
4551 if (res < 0)
4552 return NULL;
4553 Py_INCREF(Py_None);
4554 return Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004555}
4556
Tim Peters6d6c1a32001-08-02 04:15:00 +00004557static PyObject *
4558wrap_hashfunc(PyObject *self, PyObject *args, void *wrapped)
4559{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004560 hashfunc func = (hashfunc)wrapped;
Benjamin Peterson8035bc52010-10-23 16:20:50 +00004561 Py_hash_t res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004562
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004563 if (!check_num_args(args, 0))
4564 return NULL;
4565 res = (*func)(self);
4566 if (res == -1 && PyErr_Occurred())
4567 return NULL;
Benjamin Peterson8035bc52010-10-23 16:20:50 +00004568 return PyLong_FromSsize_t(res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004569}
4570
Tim Peters6d6c1a32001-08-02 04:15:00 +00004571static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00004572wrap_call(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004573{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004574 ternaryfunc func = (ternaryfunc)wrapped;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004575
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004576 return (*func)(self, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004577}
4578
Tim Peters6d6c1a32001-08-02 04:15:00 +00004579static PyObject *
4580wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op)
4581{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004582 richcmpfunc func = (richcmpfunc)wrapped;
4583 PyObject *other;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004584
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004585 if (!check_num_args(args, 1))
4586 return NULL;
4587 other = PyTuple_GET_ITEM(args, 0);
4588 return (*func)(self, other, op);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004589}
4590
4591#undef RICHCMP_WRAPPER
4592#define RICHCMP_WRAPPER(NAME, OP) \
4593static PyObject * \
4594richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \
4595{ \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004596 return wrap_richcmpfunc(self, args, wrapped, OP); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004597}
4598
Jack Jansen8e938b42001-08-08 15:29:49 +00004599RICHCMP_WRAPPER(lt, Py_LT)
4600RICHCMP_WRAPPER(le, Py_LE)
4601RICHCMP_WRAPPER(eq, Py_EQ)
4602RICHCMP_WRAPPER(ne, Py_NE)
4603RICHCMP_WRAPPER(gt, Py_GT)
4604RICHCMP_WRAPPER(ge, Py_GE)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004605
Tim Peters6d6c1a32001-08-02 04:15:00 +00004606static PyObject *
4607wrap_next(PyObject *self, PyObject *args, void *wrapped)
4608{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004609 unaryfunc func = (unaryfunc)wrapped;
4610 PyObject *res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004611
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004612 if (!check_num_args(args, 0))
4613 return NULL;
4614 res = (*func)(self);
4615 if (res == NULL && !PyErr_Occurred())
4616 PyErr_SetNone(PyExc_StopIteration);
4617 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004618}
4619
Tim Peters6d6c1a32001-08-02 04:15:00 +00004620static PyObject *
4621wrap_descr_get(PyObject *self, PyObject *args, void *wrapped)
4622{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004623 descrgetfunc func = (descrgetfunc)wrapped;
4624 PyObject *obj;
4625 PyObject *type = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004626
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004627 if (!PyArg_UnpackTuple(args, "", 1, 2, &obj, &type))
4628 return NULL;
4629 if (obj == Py_None)
4630 obj = NULL;
4631 if (type == Py_None)
4632 type = NULL;
4633 if (type == NULL &&obj == NULL) {
4634 PyErr_SetString(PyExc_TypeError,
4635 "__get__(None, None) is invalid");
4636 return NULL;
4637 }
4638 return (*func)(self, obj, type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004639}
4640
Tim Peters6d6c1a32001-08-02 04:15:00 +00004641static PyObject *
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004642wrap_descr_set(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004643{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004644 descrsetfunc func = (descrsetfunc)wrapped;
4645 PyObject *obj, *value;
4646 int ret;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004647
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004648 if (!PyArg_UnpackTuple(args, "", 2, 2, &obj, &value))
4649 return NULL;
4650 ret = (*func)(self, obj, value);
4651 if (ret < 0)
4652 return NULL;
4653 Py_INCREF(Py_None);
4654 return Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004655}
Guido van Rossum22b13872002-08-06 21:41:44 +00004656
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00004657static PyObject *
4658wrap_descr_delete(PyObject *self, PyObject *args, void *wrapped)
4659{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004660 descrsetfunc func = (descrsetfunc)wrapped;
4661 PyObject *obj;
4662 int ret;
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00004663
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004664 if (!check_num_args(args, 1))
4665 return NULL;
4666 obj = PyTuple_GET_ITEM(args, 0);
4667 ret = (*func)(self, obj, NULL);
4668 if (ret < 0)
4669 return NULL;
4670 Py_INCREF(Py_None);
4671 return Py_None;
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00004672}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004673
Tim Peters6d6c1a32001-08-02 04:15:00 +00004674static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00004675wrap_init(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004676{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004677 initproc func = (initproc)wrapped;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004678
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004679 if (func(self, args, kwds) < 0)
4680 return NULL;
4681 Py_INCREF(Py_None);
4682 return Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004683}
4684
Tim Peters6d6c1a32001-08-02 04:15:00 +00004685static PyObject *
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004686tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004687{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004688 PyTypeObject *type, *subtype, *staticbase;
4689 PyObject *arg0, *res;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004690
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004691 if (self == NULL || !PyType_Check(self))
4692 Py_FatalError("__new__() called with non-type 'self'");
4693 type = (PyTypeObject *)self;
4694 if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) {
4695 PyErr_Format(PyExc_TypeError,
4696 "%s.__new__(): not enough arguments",
4697 type->tp_name);
4698 return NULL;
4699 }
4700 arg0 = PyTuple_GET_ITEM(args, 0);
4701 if (!PyType_Check(arg0)) {
4702 PyErr_Format(PyExc_TypeError,
4703 "%s.__new__(X): X is not a type object (%s)",
4704 type->tp_name,
4705 Py_TYPE(arg0)->tp_name);
4706 return NULL;
4707 }
4708 subtype = (PyTypeObject *)arg0;
4709 if (!PyType_IsSubtype(subtype, type)) {
4710 PyErr_Format(PyExc_TypeError,
4711 "%s.__new__(%s): %s is not a subtype of %s",
4712 type->tp_name,
4713 subtype->tp_name,
4714 subtype->tp_name,
4715 type->tp_name);
4716 return NULL;
4717 }
Barry Warsaw60f01882001-08-22 19:24:42 +00004718
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004719 /* Check that the use doesn't do something silly and unsafe like
4720 object.__new__(dict). To do this, we check that the
4721 most derived base that's not a heap type is this type. */
4722 staticbase = subtype;
4723 while (staticbase && (staticbase->tp_flags & Py_TPFLAGS_HEAPTYPE))
4724 staticbase = staticbase->tp_base;
4725 /* If staticbase is NULL now, it is a really weird type.
4726 In the spirit of backwards compatibility (?), just shut up. */
4727 if (staticbase && staticbase->tp_new != type->tp_new) {
4728 PyErr_Format(PyExc_TypeError,
4729 "%s.__new__(%s) is not safe, use %s.__new__()",
4730 type->tp_name,
4731 subtype->tp_name,
4732 staticbase == NULL ? "?" : staticbase->tp_name);
4733 return NULL;
4734 }
Barry Warsaw60f01882001-08-22 19:24:42 +00004735
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004736 args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
4737 if (args == NULL)
4738 return NULL;
4739 res = type->tp_new(subtype, args, kwds);
4740 Py_DECREF(args);
4741 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004742}
4743
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004744static struct PyMethodDef tp_new_methoddef[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004745 {"__new__", (PyCFunction)tp_new_wrapper, METH_VARARGS|METH_KEYWORDS,
4746 PyDoc_STR("T.__new__(S, ...) -> "
4747 "a new object with type S, a subtype of T")},
4748 {0}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004749};
4750
4751static int
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004752add_tp_new_wrapper(PyTypeObject *type)
4753{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004754 PyObject *func;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004755
Victor Stinner3c1e4812012-03-26 22:10:51 +02004756 if (_PyDict_GetItemId(type->tp_dict, &PyId___new__) != NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004757 return 0;
4758 func = PyCFunction_New(tp_new_methoddef, (PyObject *)type);
4759 if (func == NULL)
4760 return -1;
Victor Stinner3c1e4812012-03-26 22:10:51 +02004761 if (_PyDict_SetItemId(type->tp_dict, &PyId___new__, func)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004762 Py_DECREF(func);
4763 return -1;
4764 }
4765 Py_DECREF(func);
4766 return 0;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004767}
4768
Guido van Rossumf040ede2001-08-07 16:40:56 +00004769/* Slot wrappers that call the corresponding __foo__ slot. See comments
4770 below at override_slots() for more explanation. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004771
Guido van Rossumdc91b992001-08-08 22:26:22 +00004772#define SLOT0(FUNCNAME, OPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004773static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004774FUNCNAME(PyObject *self) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004775{ \
Benjamin Petersonce798522012-01-22 11:24:29 -05004776 _Py_static_string(id, OPSTR); \
4777 return call_method(self, &id, "()"); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004778}
4779
Guido van Rossumdc91b992001-08-08 22:26:22 +00004780#define SLOT1(FUNCNAME, OPSTR, ARG1TYPE, ARGCODES) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004781static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004782FUNCNAME(PyObject *self, ARG1TYPE arg1) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004783{ \
Benjamin Petersonce798522012-01-22 11:24:29 -05004784 _Py_static_string(id, OPSTR); \
4785 return call_method(self, &id, "(" ARGCODES ")", arg1); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004786}
4787
Guido van Rossumcd118802003-01-06 22:57:47 +00004788/* Boolean helper for SLOT1BINFULL().
4789 right.__class__ is a nontrivial subclass of left.__class__. */
4790static int
Victor Stinner3c1e4812012-03-26 22:10:51 +02004791method_is_overloaded(PyObject *left, PyObject *right, struct _Py_Identifier *name)
Guido van Rossumcd118802003-01-06 22:57:47 +00004792{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004793 PyObject *a, *b;
4794 int ok;
Guido van Rossumcd118802003-01-06 22:57:47 +00004795
Victor Stinner3c1e4812012-03-26 22:10:51 +02004796 b = _PyObject_GetAttrId((PyObject *)(Py_TYPE(right)), name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004797 if (b == NULL) {
4798 PyErr_Clear();
4799 /* If right doesn't have it, it's not overloaded */
4800 return 0;
4801 }
Guido van Rossumcd118802003-01-06 22:57:47 +00004802
Victor Stinner3c1e4812012-03-26 22:10:51 +02004803 a = _PyObject_GetAttrId((PyObject *)(Py_TYPE(left)), name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004804 if (a == NULL) {
4805 PyErr_Clear();
4806 Py_DECREF(b);
4807 /* If right has it but left doesn't, it's overloaded */
4808 return 1;
4809 }
Guido van Rossumcd118802003-01-06 22:57:47 +00004810
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004811 ok = PyObject_RichCompareBool(a, b, Py_NE);
4812 Py_DECREF(a);
4813 Py_DECREF(b);
4814 if (ok < 0) {
4815 PyErr_Clear();
4816 return 0;
4817 }
Guido van Rossumcd118802003-01-06 22:57:47 +00004818
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004819 return ok;
Guido van Rossumcd118802003-01-06 22:57:47 +00004820}
4821
Guido van Rossumdc91b992001-08-08 22:26:22 +00004822
4823#define SLOT1BINFULL(FUNCNAME, TESTFUNC, SLOTNAME, OPSTR, ROPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004824static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004825FUNCNAME(PyObject *self, PyObject *other) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004826{ \
Benjamin Petersonce798522012-01-22 11:24:29 -05004827 _Py_static_string(op_id, OPSTR); \
4828 _Py_static_string(rop_id, ROPSTR); \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004829 int do_other = Py_TYPE(self) != Py_TYPE(other) && \
4830 Py_TYPE(other)->tp_as_number != NULL && \
4831 Py_TYPE(other)->tp_as_number->SLOTNAME == TESTFUNC; \
4832 if (Py_TYPE(self)->tp_as_number != NULL && \
4833 Py_TYPE(self)->tp_as_number->SLOTNAME == TESTFUNC) { \
4834 PyObject *r; \
4835 if (do_other && \
4836 PyType_IsSubtype(Py_TYPE(other), Py_TYPE(self)) && \
Victor Stinner3c1e4812012-03-26 22:10:51 +02004837 method_is_overloaded(self, other, &rop_id)) { \
Benjamin Petersonce798522012-01-22 11:24:29 -05004838 r = call_maybe(other, &rop_id, "(O)", self); \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004839 if (r != Py_NotImplemented) \
4840 return r; \
4841 Py_DECREF(r); \
4842 do_other = 0; \
4843 } \
Benjamin Petersonce798522012-01-22 11:24:29 -05004844 r = call_maybe(self, &op_id, "(O)", other); \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004845 if (r != Py_NotImplemented || \
4846 Py_TYPE(other) == Py_TYPE(self)) \
4847 return r; \
4848 Py_DECREF(r); \
4849 } \
4850 if (do_other) { \
Benjamin Petersonce798522012-01-22 11:24:29 -05004851 return call_maybe(other, &rop_id, "(O)", self); \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004852 } \
Brian Curtindfc80e32011-08-10 20:28:54 -05004853 Py_RETURN_NOTIMPLEMENTED; \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004854}
4855
4856#define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004857 SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR)
Guido van Rossumdc91b992001-08-08 22:26:22 +00004858
4859#define SLOT2(FUNCNAME, OPSTR, ARG1TYPE, ARG2TYPE, ARGCODES) \
4860static PyObject * \
4861FUNCNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \
4862{ \
Benjamin Petersonce798522012-01-22 11:24:29 -05004863 _Py_static_string(id, #OPSTR); \
4864 return call_method(self, &id, "(" ARGCODES ")", arg1, arg2); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004865}
4866
Martin v. Löwis18e16552006-02-15 17:27:45 +00004867static Py_ssize_t
Tim Peters6d6c1a32001-08-02 04:15:00 +00004868slot_sq_length(PyObject *self)
4869{
Benjamin Petersonce798522012-01-22 11:24:29 -05004870 _Py_IDENTIFIER(__len__);
4871 PyObject *res = call_method(self, &PyId___len__, "()");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004872 Py_ssize_t len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004873
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004874 if (res == NULL)
4875 return -1;
4876 len = PyNumber_AsSsize_t(res, PyExc_OverflowError);
4877 Py_DECREF(res);
4878 if (len < 0) {
4879 if (!PyErr_Occurred())
4880 PyErr_SetString(PyExc_ValueError,
4881 "__len__() should return >= 0");
4882 return -1;
4883 }
4884 return len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004885}
4886
Guido van Rossumf4593e02001-10-03 12:09:30 +00004887/* Super-optimized version of slot_sq_item.
4888 Other slots could do the same... */
4889static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00004890slot_sq_item(PyObject *self, Py_ssize_t i)
Guido van Rossumf4593e02001-10-03 12:09:30 +00004891{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004892 PyObject *func, *args = NULL, *ival = NULL, *retval = NULL;
4893 descrgetfunc f;
Guido van Rossumf4593e02001-10-03 12:09:30 +00004894
Victor Stinner3c1e4812012-03-26 22:10:51 +02004895 func = _PyType_LookupId(Py_TYPE(self), &PyId___getitem__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004896 if (func != NULL) {
4897 if ((f = Py_TYPE(func)->tp_descr_get) == NULL)
4898 Py_INCREF(func);
4899 else {
4900 func = f(func, self, (PyObject *)(Py_TYPE(self)));
4901 if (func == NULL) {
4902 return NULL;
4903 }
4904 }
4905 ival = PyLong_FromSsize_t(i);
4906 if (ival != NULL) {
4907 args = PyTuple_New(1);
4908 if (args != NULL) {
4909 PyTuple_SET_ITEM(args, 0, ival);
4910 retval = PyObject_Call(func, args, NULL);
4911 Py_XDECREF(args);
4912 Py_XDECREF(func);
4913 return retval;
4914 }
4915 }
4916 }
4917 else {
Victor Stinner3c1e4812012-03-26 22:10:51 +02004918 PyObject *getitem_str = _PyUnicode_FromId(&PyId___getitem__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004919 PyErr_SetObject(PyExc_AttributeError, getitem_str);
4920 }
4921 Py_XDECREF(args);
4922 Py_XDECREF(ival);
4923 Py_XDECREF(func);
4924 return NULL;
Guido van Rossumf4593e02001-10-03 12:09:30 +00004925}
4926
Tim Peters6d6c1a32001-08-02 04:15:00 +00004927static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00004928slot_sq_ass_item(PyObject *self, Py_ssize_t index, PyObject *value)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004929{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004930 PyObject *res;
Benjamin Petersonce798522012-01-22 11:24:29 -05004931 _Py_IDENTIFIER(__delitem__);
4932 _Py_IDENTIFIER(__setitem__);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004933
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004934 if (value == NULL)
Benjamin Petersonce798522012-01-22 11:24:29 -05004935 res = call_method(self, &PyId___delitem__, "(n)", index);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004936 else
Benjamin Petersonce798522012-01-22 11:24:29 -05004937 res = call_method(self, &PyId___setitem__, "(nO)", index, value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004938 if (res == NULL)
4939 return -1;
4940 Py_DECREF(res);
4941 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004942}
4943
4944static int
Tim Peters6d6c1a32001-08-02 04:15:00 +00004945slot_sq_contains(PyObject *self, PyObject *value)
4946{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004947 PyObject *func, *res, *args;
4948 int result = -1;
Benjamin Petersonce798522012-01-22 11:24:29 -05004949 _Py_IDENTIFIER(__contains__);
Tim Petersbf9b2442003-03-23 05:35:36 +00004950
Benjamin Petersonce798522012-01-22 11:24:29 -05004951 func = lookup_maybe(self, &PyId___contains__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004952 if (func != NULL) {
4953 args = PyTuple_Pack(1, value);
4954 if (args == NULL)
4955 res = NULL;
4956 else {
4957 res = PyObject_Call(func, args, NULL);
4958 Py_DECREF(args);
4959 }
4960 Py_DECREF(func);
4961 if (res != NULL) {
4962 result = PyObject_IsTrue(res);
4963 Py_DECREF(res);
4964 }
4965 }
4966 else if (! PyErr_Occurred()) {
4967 /* Possible results: -1 and 1 */
4968 result = (int)_PySequence_IterSearch(self, value,
4969 PY_ITERSEARCH_CONTAINS);
4970 }
4971 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004972}
4973
Tim Peters6d6c1a32001-08-02 04:15:00 +00004974#define slot_mp_length slot_sq_length
4975
Guido van Rossumdc91b992001-08-08 22:26:22 +00004976SLOT1(slot_mp_subscript, "__getitem__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004977
4978static int
4979slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value)
4980{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004981 PyObject *res;
Benjamin Petersonce798522012-01-22 11:24:29 -05004982 _Py_IDENTIFIER(__delitem__);
4983 _Py_IDENTIFIER(__setitem__);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004984
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004985 if (value == NULL)
Benjamin Petersonce798522012-01-22 11:24:29 -05004986 res = call_method(self, &PyId___delitem__, "(O)", key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004987 else
Benjamin Petersonce798522012-01-22 11:24:29 -05004988 res = call_method(self, &PyId___setitem__, "(OO)", key, value);
4989
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004990 if (res == NULL)
4991 return -1;
4992 Py_DECREF(res);
4993 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004994}
4995
Guido van Rossumdc91b992001-08-08 22:26:22 +00004996SLOT1BIN(slot_nb_add, nb_add, "__add__", "__radd__")
4997SLOT1BIN(slot_nb_subtract, nb_subtract, "__sub__", "__rsub__")
4998SLOT1BIN(slot_nb_multiply, nb_multiply, "__mul__", "__rmul__")
Guido van Rossumdc91b992001-08-08 22:26:22 +00004999SLOT1BIN(slot_nb_remainder, nb_remainder, "__mod__", "__rmod__")
5000SLOT1BIN(slot_nb_divmod, nb_divmod, "__divmod__", "__rdivmod__")
5001
Jeremy Hylton938ace62002-07-17 16:30:39 +00005002static PyObject *slot_nb_power(PyObject *, PyObject *, PyObject *);
Guido van Rossumdc91b992001-08-08 22:26:22 +00005003
5004SLOT1BINFULL(slot_nb_power_binary, slot_nb_power,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005005 nb_power, "__pow__", "__rpow__")
Guido van Rossumdc91b992001-08-08 22:26:22 +00005006
5007static PyObject *
5008slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus)
5009{
Benjamin Petersonce798522012-01-22 11:24:29 -05005010 _Py_IDENTIFIER(__pow__);
Guido van Rossum2730b132001-08-28 18:22:14 +00005011
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005012 if (modulus == Py_None)
5013 return slot_nb_power_binary(self, other);
5014 /* Three-arg power doesn't use __rpow__. But ternary_op
5015 can call this when the second argument's type uses
5016 slot_nb_power, so check before calling self.__pow__. */
5017 if (Py_TYPE(self)->tp_as_number != NULL &&
5018 Py_TYPE(self)->tp_as_number->nb_power == slot_nb_power) {
Benjamin Petersonce798522012-01-22 11:24:29 -05005019 return call_method(self, &PyId___pow__, "(OO)", other, modulus);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005020 }
Brian Curtindfc80e32011-08-10 20:28:54 -05005021 Py_RETURN_NOTIMPLEMENTED;
Guido van Rossumdc91b992001-08-08 22:26:22 +00005022}
5023
5024SLOT0(slot_nb_negative, "__neg__")
5025SLOT0(slot_nb_positive, "__pos__")
5026SLOT0(slot_nb_absolute, "__abs__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00005027
5028static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00005029slot_nb_bool(PyObject *self)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005030{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005031 PyObject *func, *args;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005032 int result = -1;
5033 int using_len = 0;
Benjamin Petersonce798522012-01-22 11:24:29 -05005034 _Py_IDENTIFIER(__len__);
5035 _Py_IDENTIFIER(__bool__);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005036
Benjamin Petersonce798522012-01-22 11:24:29 -05005037 func = lookup_maybe(self, &PyId___bool__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005038 if (func == NULL) {
5039 if (PyErr_Occurred())
5040 return -1;
Benjamin Petersonce798522012-01-22 11:24:29 -05005041 func = lookup_maybe(self, &PyId___len__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005042 if (func == NULL)
5043 return PyErr_Occurred() ? -1 : 1;
5044 using_len = 1;
5045 }
5046 args = PyTuple_New(0);
5047 if (args != NULL) {
5048 PyObject *temp = PyObject_Call(func, args, NULL);
5049 Py_DECREF(args);
5050 if (temp != NULL) {
5051 if (using_len) {
5052 /* enforced by slot_nb_len */
5053 result = PyObject_IsTrue(temp);
5054 }
5055 else if (PyBool_Check(temp)) {
5056 result = PyObject_IsTrue(temp);
5057 }
5058 else {
5059 PyErr_Format(PyExc_TypeError,
5060 "__bool__ should return "
5061 "bool, returned %s",
5062 Py_TYPE(temp)->tp_name);
5063 result = -1;
5064 }
5065 Py_DECREF(temp);
5066 }
5067 }
5068 Py_DECREF(func);
5069 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005070}
5071
Guido van Rossum38fff8c2006-03-07 18:50:55 +00005072
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00005073static PyObject *
Guido van Rossum38fff8c2006-03-07 18:50:55 +00005074slot_nb_index(PyObject *self)
5075{
Benjamin Petersonce798522012-01-22 11:24:29 -05005076 _Py_IDENTIFIER(__index__);
5077 return call_method(self, &PyId___index__, "()");
Guido van Rossum38fff8c2006-03-07 18:50:55 +00005078}
5079
5080
Guido van Rossumdc91b992001-08-08 22:26:22 +00005081SLOT0(slot_nb_invert, "__invert__")
5082SLOT1BIN(slot_nb_lshift, nb_lshift, "__lshift__", "__rlshift__")
5083SLOT1BIN(slot_nb_rshift, nb_rshift, "__rshift__", "__rrshift__")
5084SLOT1BIN(slot_nb_and, nb_and, "__and__", "__rand__")
5085SLOT1BIN(slot_nb_xor, nb_xor, "__xor__", "__rxor__")
5086SLOT1BIN(slot_nb_or, nb_or, "__or__", "__ror__")
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00005087
Guido van Rossumdc91b992001-08-08 22:26:22 +00005088SLOT0(slot_nb_int, "__int__")
Guido van Rossumdc91b992001-08-08 22:26:22 +00005089SLOT0(slot_nb_float, "__float__")
Guido van Rossumdc91b992001-08-08 22:26:22 +00005090SLOT1(slot_nb_inplace_add, "__iadd__", PyObject *, "O")
5091SLOT1(slot_nb_inplace_subtract, "__isub__", PyObject *, "O")
5092SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *, "O")
Guido van Rossumdc91b992001-08-08 22:26:22 +00005093SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *, "O")
Thomas Wouterscf297e42007-02-23 15:07:44 +00005094/* Can't use SLOT1 here, because nb_inplace_power is ternary */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005095static PyObject *
5096slot_nb_inplace_power(PyObject *self, PyObject * arg1, PyObject *arg2)
5097{
Benjamin Petersonce798522012-01-22 11:24:29 -05005098 _Py_IDENTIFIER(__ipow__);
5099 return call_method(self, &PyId___ipow__, "(" "O" ")", arg1);
Thomas Wouterscf297e42007-02-23 15:07:44 +00005100}
Guido van Rossumdc91b992001-08-08 22:26:22 +00005101SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *, "O")
5102SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *, "O")
5103SLOT1(slot_nb_inplace_and, "__iand__", PyObject *, "O")
5104SLOT1(slot_nb_inplace_xor, "__ixor__", PyObject *, "O")
5105SLOT1(slot_nb_inplace_or, "__ior__", PyObject *, "O")
5106SLOT1BIN(slot_nb_floor_divide, nb_floor_divide,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005107 "__floordiv__", "__rfloordiv__")
Guido van Rossumdc91b992001-08-08 22:26:22 +00005108SLOT1BIN(slot_nb_true_divide, nb_true_divide, "__truediv__", "__rtruediv__")
5109SLOT1(slot_nb_inplace_floor_divide, "__ifloordiv__", PyObject *, "O")
5110SLOT1(slot_nb_inplace_true_divide, "__itruediv__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00005111
Guido van Rossumb8f63662001-08-15 23:57:02 +00005112static PyObject *
5113slot_tp_repr(PyObject *self)
5114{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005115 PyObject *func, *res;
Benjamin Petersonce798522012-01-22 11:24:29 -05005116 _Py_IDENTIFIER(__repr__);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005117
Benjamin Petersonce798522012-01-22 11:24:29 -05005118 func = lookup_method(self, &PyId___repr__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005119 if (func != NULL) {
5120 res = PyEval_CallObject(func, NULL);
5121 Py_DECREF(func);
5122 return res;
5123 }
5124 PyErr_Clear();
5125 return PyUnicode_FromFormat("<%s object at %p>",
5126 Py_TYPE(self)->tp_name, self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005127}
5128
5129static PyObject *
5130slot_tp_str(PyObject *self)
5131{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005132 PyObject *func, *res;
Benjamin Petersonce798522012-01-22 11:24:29 -05005133 _Py_IDENTIFIER(__str__);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005134
Benjamin Petersonce798522012-01-22 11:24:29 -05005135 func = lookup_method(self, &PyId___str__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005136 if (func != NULL) {
5137 res = PyEval_CallObject(func, NULL);
5138 Py_DECREF(func);
5139 return res;
5140 }
5141 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005142 /* PyObject *ress; */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005143 PyErr_Clear();
5144 res = slot_tp_repr(self);
5145 if (!res)
5146 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005147 /* XXX this is non-sensical. Why should we return
5148 a bytes object from __str__. Is this code even
5149 used? - mvl */
5150 assert(0);
5151 return res;
5152 /*
Victor Stinnerf3fd7332011-03-02 01:03:11 +00005153 ress = _PyUnicode_AsDefaultEncodedString(res);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005154 Py_DECREF(res);
5155 return ress;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005156 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005157 }
Guido van Rossumb8f63662001-08-15 23:57:02 +00005158}
Tim Peters6d6c1a32001-08-02 04:15:00 +00005159
Benjamin Peterson8f67d082010-10-17 20:54:53 +00005160static Py_hash_t
Tim Peters6d6c1a32001-08-02 04:15:00 +00005161slot_tp_hash(PyObject *self)
5162{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005163 PyObject *func, *res;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00005164 Py_ssize_t h;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005165
Benjamin Petersonce798522012-01-22 11:24:29 -05005166 func = lookup_method(self, &PyId___hash__);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005167
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005168 if (func == Py_None) {
5169 Py_DECREF(func);
5170 func = NULL;
5171 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +00005172
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005173 if (func == NULL) {
5174 return PyObject_HashNotImplemented(self);
5175 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +00005176
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005177 res = PyEval_CallObject(func, NULL);
5178 Py_DECREF(func);
5179 if (res == NULL)
5180 return -1;
Mark Dickinsondc787d22010-05-23 13:33:13 +00005181
5182 if (!PyLong_Check(res)) {
5183 PyErr_SetString(PyExc_TypeError,
5184 "__hash__ method should return an integer");
5185 return -1;
5186 }
Benjamin Peterson8f67d082010-10-17 20:54:53 +00005187 /* Transform the PyLong `res` to a Py_hash_t `h`. For an existing
5188 hashable Python object x, hash(x) will always lie within the range of
5189 Py_hash_t. Therefore our transformation must preserve values that
5190 already lie within this range, to ensure that if x.__hash__() returns
5191 hash(y) then hash(x) == hash(y). */
5192 h = PyLong_AsSsize_t(res);
5193 if (h == -1 && PyErr_Occurred()) {
5194 /* res was not within the range of a Py_hash_t, so we're free to
Mark Dickinsondc787d22010-05-23 13:33:13 +00005195 use any sufficiently bit-mixing transformation;
5196 long.__hash__ will do nicely. */
Benjamin Peterson8f67d082010-10-17 20:54:53 +00005197 PyErr_Clear();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005198 h = PyLong_Type.tp_hash(res);
Benjamin Peterson8f67d082010-10-17 20:54:53 +00005199 }
Benjamin Petersone7dfeeb2010-10-17 21:27:01 +00005200 /* -1 is reserved for errors. */
5201 if (h == -1)
5202 h = -2;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005203 Py_DECREF(res);
Mark Dickinsondc787d22010-05-23 13:33:13 +00005204 return h;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005205}
5206
5207static PyObject *
5208slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds)
5209{
Benjamin Petersonce798522012-01-22 11:24:29 -05005210 _Py_IDENTIFIER(__call__);
5211 PyObject *meth = lookup_method(self, &PyId___call__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005212 PyObject *res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005213
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005214 if (meth == NULL)
5215 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005216
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005217 res = PyObject_Call(meth, args, kwds);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005218
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005219 Py_DECREF(meth);
5220 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005221}
5222
Guido van Rossum14a6f832001-10-17 13:59:09 +00005223/* There are two slot dispatch functions for tp_getattro.
5224
5225 - slot_tp_getattro() is used when __getattribute__ is overridden
5226 but no __getattr__ hook is present;
5227
5228 - slot_tp_getattr_hook() is used when a __getattr__ hook is present.
5229
Guido van Rossumc334df52002-04-04 23:44:47 +00005230 The code in update_one_slot() always installs slot_tp_getattr_hook(); this
5231 detects the absence of __getattr__ and then installs the simpler slot if
5232 necessary. */
Guido van Rossum14a6f832001-10-17 13:59:09 +00005233
Tim Peters6d6c1a32001-08-02 04:15:00 +00005234static PyObject *
5235slot_tp_getattro(PyObject *self, PyObject *name)
5236{
Benjamin Petersonce798522012-01-22 11:24:29 -05005237 return call_method(self, &PyId___getattribute__, "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005238}
5239
Guido van Rossum19c1cd52001-09-21 21:24:49 +00005240static PyObject *
Benjamin Peterson9262b842008-11-17 22:45:50 +00005241call_attribute(PyObject *self, PyObject *attr, PyObject *name)
5242{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005243 PyObject *res, *descr = NULL;
5244 descrgetfunc f = Py_TYPE(attr)->tp_descr_get;
Benjamin Peterson9262b842008-11-17 22:45:50 +00005245
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005246 if (f != NULL) {
5247 descr = f(attr, self, (PyObject *)(Py_TYPE(self)));
5248 if (descr == NULL)
5249 return NULL;
5250 else
5251 attr = descr;
5252 }
5253 res = PyObject_CallFunctionObjArgs(attr, name, NULL);
5254 Py_XDECREF(descr);
5255 return res;
Benjamin Peterson9262b842008-11-17 22:45:50 +00005256}
5257
5258static PyObject *
Guido van Rossum19c1cd52001-09-21 21:24:49 +00005259slot_tp_getattr_hook(PyObject *self, PyObject *name)
5260{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005261 PyTypeObject *tp = Py_TYPE(self);
5262 PyObject *getattr, *getattribute, *res;
Victor Stinner3c1e4812012-03-26 22:10:51 +02005263 _Py_IDENTIFIER(__getattr__);
Guido van Rossum19c1cd52001-09-21 21:24:49 +00005264
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005265 /* speed hack: we could use lookup_maybe, but that would resolve the
5266 method fully for each attribute lookup for classes with
5267 __getattr__, even when the attribute is present. So we use
5268 _PyType_Lookup and create the method only when needed, with
5269 call_attribute. */
Victor Stinner3c1e4812012-03-26 22:10:51 +02005270 getattr = _PyType_LookupId(tp, &PyId___getattr__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005271 if (getattr == NULL) {
5272 /* No __getattr__ hook: use a simpler dispatcher */
5273 tp->tp_getattro = slot_tp_getattro;
5274 return slot_tp_getattro(self, name);
5275 }
5276 Py_INCREF(getattr);
5277 /* speed hack: we could use lookup_maybe, but that would resolve the
5278 method fully for each attribute lookup for classes with
5279 __getattr__, even when self has the default __getattribute__
5280 method. So we use _PyType_Lookup and create the method only when
5281 needed, with call_attribute. */
Victor Stinner3c1e4812012-03-26 22:10:51 +02005282 getattribute = _PyType_LookupId(tp, &PyId___getattribute__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005283 if (getattribute == NULL ||
5284 (Py_TYPE(getattribute) == &PyWrapperDescr_Type &&
5285 ((PyWrapperDescrObject *)getattribute)->d_wrapped ==
5286 (void *)PyObject_GenericGetAttr))
5287 res = PyObject_GenericGetAttr(self, name);
5288 else {
5289 Py_INCREF(getattribute);
5290 res = call_attribute(self, getattribute, name);
5291 Py_DECREF(getattribute);
5292 }
5293 if (res == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) {
5294 PyErr_Clear();
5295 res = call_attribute(self, getattr, name);
5296 }
5297 Py_DECREF(getattr);
5298 return res;
Guido van Rossum19c1cd52001-09-21 21:24:49 +00005299}
5300
Tim Peters6d6c1a32001-08-02 04:15:00 +00005301static int
5302slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value)
5303{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005304 PyObject *res;
Benjamin Petersonce798522012-01-22 11:24:29 -05005305 _Py_IDENTIFIER(__delattr__);
5306 _Py_IDENTIFIER(__setattr__);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005307
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005308 if (value == NULL)
Benjamin Petersonce798522012-01-22 11:24:29 -05005309 res = call_method(self, &PyId___delattr__, "(O)", name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005310 else
Benjamin Petersonce798522012-01-22 11:24:29 -05005311 res = call_method(self, &PyId___setattr__, "(OO)", name, value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005312 if (res == NULL)
5313 return -1;
5314 Py_DECREF(res);
5315 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005316}
5317
Benjamin Petersonce798522012-01-22 11:24:29 -05005318static _Py_Identifier name_op[] = {
5319 {0, "__lt__", 0},
5320 {0, "__le__", 0},
5321 {0, "__eq__", 0},
5322 {0, "__ne__", 0},
5323 {0, "__gt__", 0},
5324 {0, "__ge__", 0}
Guido van Rossumf5243f02008-01-01 04:06:48 +00005325};
5326
Tim Peters6d6c1a32001-08-02 04:15:00 +00005327static PyObject *
Mark Dickinson6f1d0492009-11-15 13:58:49 +00005328slot_tp_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005329{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005330 PyObject *func, *args, *res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005331
Benjamin Petersonce798522012-01-22 11:24:29 -05005332 func = lookup_method(self, &name_op[op]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005333 if (func == NULL) {
5334 PyErr_Clear();
Brian Curtindfc80e32011-08-10 20:28:54 -05005335 Py_RETURN_NOTIMPLEMENTED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005336 }
5337 args = PyTuple_Pack(1, other);
5338 if (args == NULL)
5339 res = NULL;
5340 else {
5341 res = PyObject_Call(func, args, NULL);
5342 Py_DECREF(args);
5343 }
5344 Py_DECREF(func);
5345 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005346}
5347
Guido van Rossumb8f63662001-08-15 23:57:02 +00005348static PyObject *
Guido van Rossumb8f63662001-08-15 23:57:02 +00005349slot_tp_iter(PyObject *self)
5350{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005351 PyObject *func, *res;
Benjamin Petersonce798522012-01-22 11:24:29 -05005352 _Py_IDENTIFIER(__iter__);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005353
Benjamin Petersonce798522012-01-22 11:24:29 -05005354 func = lookup_method(self, &PyId___iter__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005355 if (func != NULL) {
5356 PyObject *args;
5357 args = res = PyTuple_New(0);
5358 if (args != NULL) {
5359 res = PyObject_Call(func, args, NULL);
5360 Py_DECREF(args);
5361 }
5362 Py_DECREF(func);
5363 return res;
5364 }
5365 PyErr_Clear();
Benjamin Petersonce798522012-01-22 11:24:29 -05005366 func = lookup_method(self, &PyId___getitem__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005367 if (func == NULL) {
5368 PyErr_Format(PyExc_TypeError,
5369 "'%.200s' object is not iterable",
5370 Py_TYPE(self)->tp_name);
5371 return NULL;
5372 }
5373 Py_DECREF(func);
5374 return PySeqIter_New(self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005375}
Tim Peters6d6c1a32001-08-02 04:15:00 +00005376
5377static PyObject *
5378slot_tp_iternext(PyObject *self)
5379{
Benjamin Petersonce798522012-01-22 11:24:29 -05005380 _Py_IDENTIFIER(__next__);
5381 return call_method(self, &PyId___next__, "()");
Tim Peters6d6c1a32001-08-02 04:15:00 +00005382}
5383
Guido van Rossum1a493502001-08-17 16:47:50 +00005384static PyObject *
5385slot_tp_descr_get(PyObject *self, PyObject *obj, PyObject *type)
5386{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005387 PyTypeObject *tp = Py_TYPE(self);
5388 PyObject *get;
Victor Stinner3c1e4812012-03-26 22:10:51 +02005389 _Py_IDENTIFIER(__get__);
Guido van Rossum1a493502001-08-17 16:47:50 +00005390
Victor Stinner3c1e4812012-03-26 22:10:51 +02005391 get = _PyType_LookupId(tp, &PyId___get__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005392 if (get == NULL) {
5393 /* Avoid further slowdowns */
5394 if (tp->tp_descr_get == slot_tp_descr_get)
5395 tp->tp_descr_get = NULL;
5396 Py_INCREF(self);
5397 return self;
5398 }
5399 if (obj == NULL)
5400 obj = Py_None;
5401 if (type == NULL)
5402 type = Py_None;
5403 return PyObject_CallFunctionObjArgs(get, self, obj, type, NULL);
Guido van Rossum1a493502001-08-17 16:47:50 +00005404}
Tim Peters6d6c1a32001-08-02 04:15:00 +00005405
5406static int
5407slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value)
5408{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005409 PyObject *res;
Benjamin Petersonce798522012-01-22 11:24:29 -05005410 _Py_IDENTIFIER(__delete__);
5411 _Py_IDENTIFIER(__set__);
Guido van Rossum2c252392001-08-24 10:13:31 +00005412
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005413 if (value == NULL)
Benjamin Petersonce798522012-01-22 11:24:29 -05005414 res = call_method(self, &PyId___delete__, "(O)", target);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005415 else
Benjamin Petersonce798522012-01-22 11:24:29 -05005416 res = call_method(self, &PyId___set__, "(OO)", target, value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005417 if (res == NULL)
5418 return -1;
5419 Py_DECREF(res);
5420 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005421}
5422
5423static int
5424slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds)
5425{
Benjamin Petersonce798522012-01-22 11:24:29 -05005426 _Py_IDENTIFIER(__init__);
5427 PyObject *meth = lookup_method(self, &PyId___init__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005428 PyObject *res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005429
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005430 if (meth == NULL)
5431 return -1;
5432 res = PyObject_Call(meth, args, kwds);
5433 Py_DECREF(meth);
5434 if (res == NULL)
5435 return -1;
5436 if (res != Py_None) {
5437 PyErr_Format(PyExc_TypeError,
5438 "__init__() should return None, not '%.200s'",
5439 Py_TYPE(res)->tp_name);
5440 Py_DECREF(res);
5441 return -1;
5442 }
5443 Py_DECREF(res);
5444 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005445}
5446
5447static PyObject *
5448slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
5449{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005450 PyObject *func;
5451 PyObject *newargs, *x;
5452 Py_ssize_t i, n;
Victor Stinner3c1e4812012-03-26 22:10:51 +02005453 _Py_IDENTIFIER(__new__);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005454
Victor Stinner3c1e4812012-03-26 22:10:51 +02005455 func = _PyObject_GetAttrId((PyObject *)type, &PyId___new__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005456 if (func == NULL)
5457 return NULL;
5458 assert(PyTuple_Check(args));
5459 n = PyTuple_GET_SIZE(args);
5460 newargs = PyTuple_New(n+1);
5461 if (newargs == NULL)
5462 return NULL;
5463 Py_INCREF(type);
5464 PyTuple_SET_ITEM(newargs, 0, (PyObject *)type);
5465 for (i = 0; i < n; i++) {
5466 x = PyTuple_GET_ITEM(args, i);
5467 Py_INCREF(x);
5468 PyTuple_SET_ITEM(newargs, i+1, x);
5469 }
5470 x = PyObject_Call(func, newargs, kwds);
5471 Py_DECREF(newargs);
5472 Py_DECREF(func);
5473 return x;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005474}
5475
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005476static void
5477slot_tp_del(PyObject *self)
5478{
Benjamin Petersonce798522012-01-22 11:24:29 -05005479 _Py_IDENTIFIER(__del__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005480 PyObject *del, *res;
5481 PyObject *error_type, *error_value, *error_traceback;
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005482
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005483 /* Temporarily resurrect the object. */
5484 assert(self->ob_refcnt == 0);
5485 self->ob_refcnt = 1;
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005486
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005487 /* Save the current exception, if any. */
5488 PyErr_Fetch(&error_type, &error_value, &error_traceback);
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005489
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005490 /* Execute __del__ method, if any. */
Benjamin Petersonce798522012-01-22 11:24:29 -05005491 del = lookup_maybe(self, &PyId___del__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005492 if (del != NULL) {
5493 res = PyEval_CallObject(del, NULL);
5494 if (res == NULL)
5495 PyErr_WriteUnraisable(del);
5496 else
5497 Py_DECREF(res);
5498 Py_DECREF(del);
5499 }
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005500
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005501 /* Restore the saved exception. */
5502 PyErr_Restore(error_type, error_value, error_traceback);
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005503
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005504 /* Undo the temporary resurrection; can't use DECREF here, it would
5505 * cause a recursive call.
5506 */
5507 assert(self->ob_refcnt > 0);
5508 if (--self->ob_refcnt == 0)
5509 return; /* this is the normal path out */
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005510
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005511 /* __del__ resurrected it! Make it look like the original Py_DECREF
5512 * never happened.
5513 */
5514 {
5515 Py_ssize_t refcnt = self->ob_refcnt;
5516 _Py_NewReference(self);
5517 self->ob_refcnt = refcnt;
5518 }
5519 assert(!PyType_IS_GC(Py_TYPE(self)) ||
5520 _Py_AS_GC(self)->gc.gc_refs != _PyGC_REFS_UNTRACKED);
5521 /* If Py_REF_DEBUG, _Py_NewReference bumped _Py_RefTotal, so
5522 * we need to undo that. */
5523 _Py_DEC_REFTOTAL;
5524 /* If Py_TRACE_REFS, _Py_NewReference re-added self to the object
5525 * chain, so no more to do there.
5526 * If COUNT_ALLOCS, the original decref bumped tp_frees, and
5527 * _Py_NewReference bumped tp_allocs: both of those need to be
5528 * undone.
5529 */
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005530#ifdef COUNT_ALLOCS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005531 --Py_TYPE(self)->tp_frees;
5532 --Py_TYPE(self)->tp_allocs;
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005533#endif
5534}
5535
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005536
5537/* Table mapping __foo__ names to tp_foo offsets and slot_tp_foo wrapper
Tim Petersbf9b2442003-03-23 05:35:36 +00005538 functions. The offsets here are relative to the 'PyHeapTypeObject'
Guido van Rossume5c691a2003-03-07 15:13:17 +00005539 structure, which incorporates the additional structures used for numbers,
5540 sequences and mappings.
5541 Note that multiple names may map to the same slot (e.g. __eq__,
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005542 __ne__ etc. all map to tp_richcompare) and one name may map to multiple
Guido van Rossumc334df52002-04-04 23:44:47 +00005543 slots (e.g. __str__ affects tp_str as well as tp_repr). The table is
5544 terminated with an all-zero entry. (This table is further initialized and
5545 sorted in init_slotdefs() below.) */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005546
Guido van Rossum6d204072001-10-21 00:44:31 +00005547typedef struct wrapperbase slotdef;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005548
5549#undef TPSLOT
Guido van Rossumc8e56452001-10-22 00:43:43 +00005550#undef FLSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005551#undef ETSLOT
5552#undef SQSLOT
5553#undef MPSLOT
5554#undef NBSLOT
Guido van Rossum6d204072001-10-21 00:44:31 +00005555#undef UNSLOT
5556#undef IBSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005557#undef BINSLOT
5558#undef RBINSLOT
5559
Guido van Rossum6d204072001-10-21 00:44:31 +00005560#define TPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005561 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
5562 PyDoc_STR(DOC)}
Guido van Rossumc8e56452001-10-22 00:43:43 +00005563#define FLSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC, FLAGS) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005564 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
5565 PyDoc_STR(DOC), FLAGS}
Guido van Rossum6d204072001-10-21 00:44:31 +00005566#define ETSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005567 {NAME, offsetof(PyHeapTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
5568 PyDoc_STR(DOC)}
Guido van Rossum6d204072001-10-21 00:44:31 +00005569#define SQSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005570 ETSLOT(NAME, as_sequence.SLOT, FUNCTION, WRAPPER, DOC)
Guido van Rossum6d204072001-10-21 00:44:31 +00005571#define MPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005572 ETSLOT(NAME, as_mapping.SLOT, FUNCTION, WRAPPER, DOC)
Guido van Rossum6d204072001-10-21 00:44:31 +00005573#define NBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005574 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, DOC)
Guido van Rossum6d204072001-10-21 00:44:31 +00005575#define UNSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005576 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
5577 "x." NAME "() <==> " DOC)
Guido van Rossum6d204072001-10-21 00:44:31 +00005578#define IBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005579 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
5580 "x." NAME "(y) <==> x" DOC "y")
Guido van Rossum6d204072001-10-21 00:44:31 +00005581#define BINSLOT(NAME, SLOT, FUNCTION, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005582 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
5583 "x." NAME "(y) <==> x" DOC "y")
Guido van Rossum6d204072001-10-21 00:44:31 +00005584#define RBINSLOT(NAME, SLOT, FUNCTION, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005585 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
5586 "x." NAME "(y) <==> y" DOC "x")
Anthony Baxter56616992005-06-03 14:12:21 +00005587#define BINSLOTNOTINFIX(NAME, SLOT, FUNCTION, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005588 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
5589 "x." NAME "(y) <==> " DOC)
Anthony Baxter56616992005-06-03 14:12:21 +00005590#define RBINSLOTNOTINFIX(NAME, SLOT, FUNCTION, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005591 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
5592 "x." NAME "(y) <==> " DOC)
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005593
5594static slotdef slotdefs[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005595 SQSLOT("__len__", sq_length, slot_sq_length, wrap_lenfunc,
5596 "x.__len__() <==> len(x)"),
5597 /* Heap types defining __add__/__mul__ have sq_concat/sq_repeat == NULL.
5598 The logic in abstract.c always falls back to nb_add/nb_multiply in
5599 this case. Defining both the nb_* and the sq_* slots to call the
5600 user-defined methods has unexpected side-effects, as shown by
5601 test_descr.notimplemented() */
5602 SQSLOT("__add__", sq_concat, NULL, wrap_binaryfunc,
5603 "x.__add__(y) <==> x+y"),
5604 SQSLOT("__mul__", sq_repeat, NULL, wrap_indexargfunc,
5605 "x.__mul__(n) <==> x*n"),
5606 SQSLOT("__rmul__", sq_repeat, NULL, wrap_indexargfunc,
5607 "x.__rmul__(n) <==> n*x"),
5608 SQSLOT("__getitem__", sq_item, slot_sq_item, wrap_sq_item,
5609 "x.__getitem__(y) <==> x[y]"),
5610 SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_setitem,
5611 "x.__setitem__(i, y) <==> x[i]=y"),
5612 SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_delitem,
5613 "x.__delitem__(y) <==> del x[y]"),
5614 SQSLOT("__contains__", sq_contains, slot_sq_contains, wrap_objobjproc,
5615 "x.__contains__(y) <==> y in x"),
5616 SQSLOT("__iadd__", sq_inplace_concat, NULL,
5617 wrap_binaryfunc, "x.__iadd__(y) <==> x+=y"),
5618 SQSLOT("__imul__", sq_inplace_repeat, NULL,
5619 wrap_indexargfunc, "x.__imul__(y) <==> x*=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005620
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005621 MPSLOT("__len__", mp_length, slot_mp_length, wrap_lenfunc,
5622 "x.__len__() <==> len(x)"),
5623 MPSLOT("__getitem__", mp_subscript, slot_mp_subscript,
5624 wrap_binaryfunc,
5625 "x.__getitem__(y) <==> x[y]"),
5626 MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript,
5627 wrap_objobjargproc,
5628 "x.__setitem__(i, y) <==> x[i]=y"),
5629 MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript,
5630 wrap_delitem,
5631 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005632
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005633 BINSLOT("__add__", nb_add, slot_nb_add,
5634 "+"),
5635 RBINSLOT("__radd__", nb_add, slot_nb_add,
5636 "+"),
5637 BINSLOT("__sub__", nb_subtract, slot_nb_subtract,
5638 "-"),
5639 RBINSLOT("__rsub__", nb_subtract, slot_nb_subtract,
5640 "-"),
5641 BINSLOT("__mul__", nb_multiply, slot_nb_multiply,
5642 "*"),
5643 RBINSLOT("__rmul__", nb_multiply, slot_nb_multiply,
5644 "*"),
5645 BINSLOT("__mod__", nb_remainder, slot_nb_remainder,
5646 "%"),
5647 RBINSLOT("__rmod__", nb_remainder, slot_nb_remainder,
5648 "%"),
5649 BINSLOTNOTINFIX("__divmod__", nb_divmod, slot_nb_divmod,
5650 "divmod(x, y)"),
5651 RBINSLOTNOTINFIX("__rdivmod__", nb_divmod, slot_nb_divmod,
5652 "divmod(y, x)"),
5653 NBSLOT("__pow__", nb_power, slot_nb_power, wrap_ternaryfunc,
5654 "x.__pow__(y[, z]) <==> pow(x, y[, z])"),
5655 NBSLOT("__rpow__", nb_power, slot_nb_power, wrap_ternaryfunc_r,
5656 "y.__rpow__(x[, z]) <==> pow(x, y[, z])"),
5657 UNSLOT("__neg__", nb_negative, slot_nb_negative, wrap_unaryfunc, "-x"),
5658 UNSLOT("__pos__", nb_positive, slot_nb_positive, wrap_unaryfunc, "+x"),
5659 UNSLOT("__abs__", nb_absolute, slot_nb_absolute, wrap_unaryfunc,
5660 "abs(x)"),
5661 UNSLOT("__bool__", nb_bool, slot_nb_bool, wrap_inquirypred,
5662 "x != 0"),
5663 UNSLOT("__invert__", nb_invert, slot_nb_invert, wrap_unaryfunc, "~x"),
5664 BINSLOT("__lshift__", nb_lshift, slot_nb_lshift, "<<"),
5665 RBINSLOT("__rlshift__", nb_lshift, slot_nb_lshift, "<<"),
5666 BINSLOT("__rshift__", nb_rshift, slot_nb_rshift, ">>"),
5667 RBINSLOT("__rrshift__", nb_rshift, slot_nb_rshift, ">>"),
5668 BINSLOT("__and__", nb_and, slot_nb_and, "&"),
5669 RBINSLOT("__rand__", nb_and, slot_nb_and, "&"),
5670 BINSLOT("__xor__", nb_xor, slot_nb_xor, "^"),
5671 RBINSLOT("__rxor__", nb_xor, slot_nb_xor, "^"),
5672 BINSLOT("__or__", nb_or, slot_nb_or, "|"),
5673 RBINSLOT("__ror__", nb_or, slot_nb_or, "|"),
5674 UNSLOT("__int__", nb_int, slot_nb_int, wrap_unaryfunc,
5675 "int(x)"),
5676 UNSLOT("__float__", nb_float, slot_nb_float, wrap_unaryfunc,
5677 "float(x)"),
5678 NBSLOT("__index__", nb_index, slot_nb_index, wrap_unaryfunc,
5679 "x[y:z] <==> x[y.__index__():z.__index__()]"),
5680 IBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add,
Eli Benderskyd3baae72011-11-11 16:57:05 +02005681 wrap_binaryfunc, "+="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005682 IBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract,
Eli Benderskyd3baae72011-11-11 16:57:05 +02005683 wrap_binaryfunc, "-="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005684 IBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply,
Eli Benderskyd3baae72011-11-11 16:57:05 +02005685 wrap_binaryfunc, "*="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005686 IBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder,
Eli Benderskyd3baae72011-11-11 16:57:05 +02005687 wrap_binaryfunc, "%="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005688 IBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power,
Eli Benderskyd3baae72011-11-11 16:57:05 +02005689 wrap_binaryfunc, "**="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005690 IBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift,
Eli Benderskyd3baae72011-11-11 16:57:05 +02005691 wrap_binaryfunc, "<<="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005692 IBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift,
Eli Benderskyd3baae72011-11-11 16:57:05 +02005693 wrap_binaryfunc, ">>="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005694 IBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and,
Eli Benderskyd3baae72011-11-11 16:57:05 +02005695 wrap_binaryfunc, "&="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005696 IBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor,
Eli Benderskyd3baae72011-11-11 16:57:05 +02005697 wrap_binaryfunc, "^="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005698 IBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or,
Eli Benderskyd3baae72011-11-11 16:57:05 +02005699 wrap_binaryfunc, "|="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005700 BINSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
5701 RBINSLOT("__rfloordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
5702 BINSLOT("__truediv__", nb_true_divide, slot_nb_true_divide, "/"),
5703 RBINSLOT("__rtruediv__", nb_true_divide, slot_nb_true_divide, "/"),
5704 IBSLOT("__ifloordiv__", nb_inplace_floor_divide,
5705 slot_nb_inplace_floor_divide, wrap_binaryfunc, "//"),
5706 IBSLOT("__itruediv__", nb_inplace_true_divide,
5707 slot_nb_inplace_true_divide, wrap_binaryfunc, "/"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005708
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005709 TPSLOT("__str__", tp_str, slot_tp_str, wrap_unaryfunc,
5710 "x.__str__() <==> str(x)"),
5711 TPSLOT("__repr__", tp_repr, slot_tp_repr, wrap_unaryfunc,
5712 "x.__repr__() <==> repr(x)"),
5713 TPSLOT("__hash__", tp_hash, slot_tp_hash, wrap_hashfunc,
5714 "x.__hash__() <==> hash(x)"),
5715 FLSLOT("__call__", tp_call, slot_tp_call, (wrapperfunc)wrap_call,
5716 "x.__call__(...) <==> x(...)", PyWrapperFlag_KEYWORDS),
5717 TPSLOT("__getattribute__", tp_getattro, slot_tp_getattr_hook,
5718 wrap_binaryfunc, "x.__getattribute__('name') <==> x.name"),
5719 TPSLOT("__getattribute__", tp_getattr, NULL, NULL, ""),
5720 TPSLOT("__getattr__", tp_getattro, slot_tp_getattr_hook, NULL, ""),
5721 TPSLOT("__getattr__", tp_getattr, NULL, NULL, ""),
5722 TPSLOT("__setattr__", tp_setattro, slot_tp_setattro, wrap_setattr,
5723 "x.__setattr__('name', value) <==> x.name = value"),
5724 TPSLOT("__setattr__", tp_setattr, NULL, NULL, ""),
5725 TPSLOT("__delattr__", tp_setattro, slot_tp_setattro, wrap_delattr,
5726 "x.__delattr__('name') <==> del x.name"),
5727 TPSLOT("__delattr__", tp_setattr, NULL, NULL, ""),
5728 TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare, richcmp_lt,
5729 "x.__lt__(y) <==> x<y"),
5730 TPSLOT("__le__", tp_richcompare, slot_tp_richcompare, richcmp_le,
5731 "x.__le__(y) <==> x<=y"),
5732 TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare, richcmp_eq,
5733 "x.__eq__(y) <==> x==y"),
5734 TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare, richcmp_ne,
5735 "x.__ne__(y) <==> x!=y"),
5736 TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare, richcmp_gt,
5737 "x.__gt__(y) <==> x>y"),
5738 TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare, richcmp_ge,
5739 "x.__ge__(y) <==> x>=y"),
5740 TPSLOT("__iter__", tp_iter, slot_tp_iter, wrap_unaryfunc,
5741 "x.__iter__() <==> iter(x)"),
5742 TPSLOT("__next__", tp_iternext, slot_tp_iternext, wrap_next,
5743 "x.__next__() <==> next(x)"),
5744 TPSLOT("__get__", tp_descr_get, slot_tp_descr_get, wrap_descr_get,
5745 "descr.__get__(obj[, type]) -> value"),
5746 TPSLOT("__set__", tp_descr_set, slot_tp_descr_set, wrap_descr_set,
5747 "descr.__set__(obj, value)"),
5748 TPSLOT("__delete__", tp_descr_set, slot_tp_descr_set,
5749 wrap_descr_delete, "descr.__delete__(obj)"),
5750 FLSLOT("__init__", tp_init, slot_tp_init, (wrapperfunc)wrap_init,
5751 "x.__init__(...) initializes x; "
Alexander Belopolsky977a6842010-08-16 20:17:07 +00005752 "see help(type(x)) for signature",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005753 PyWrapperFlag_KEYWORDS),
5754 TPSLOT("__new__", tp_new, slot_tp_new, NULL, ""),
5755 TPSLOT("__del__", tp_del, slot_tp_del, NULL, ""),
5756 {NULL}
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005757};
5758
Guido van Rossumc334df52002-04-04 23:44:47 +00005759/* Given a type pointer and an offset gotten from a slotdef entry, return a
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005760 pointer to the actual slot. This is not quite the same as simply adding
Guido van Rossumc334df52002-04-04 23:44:47 +00005761 the offset to the type pointer, since it takes care to indirect through the
5762 proper indirection pointer (as_buffer, etc.); it returns NULL if the
5763 indirection pointer is NULL. */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005764static void **
Martin v. Löwis18e16552006-02-15 17:27:45 +00005765slotptr(PyTypeObject *type, int ioffset)
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005766{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005767 char *ptr;
5768 long offset = ioffset;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005769
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005770 /* Note: this depends on the order of the members of PyHeapTypeObject! */
5771 assert(offset >= 0);
5772 assert((size_t)offset < offsetof(PyHeapTypeObject, as_buffer));
5773 if ((size_t)offset >= offsetof(PyHeapTypeObject, as_sequence)) {
5774 ptr = (char *)type->tp_as_sequence;
5775 offset -= offsetof(PyHeapTypeObject, as_sequence);
5776 }
5777 else if ((size_t)offset >= offsetof(PyHeapTypeObject, as_mapping)) {
5778 ptr = (char *)type->tp_as_mapping;
5779 offset -= offsetof(PyHeapTypeObject, as_mapping);
5780 }
5781 else if ((size_t)offset >= offsetof(PyHeapTypeObject, as_number)) {
5782 ptr = (char *)type->tp_as_number;
5783 offset -= offsetof(PyHeapTypeObject, as_number);
5784 }
5785 else {
5786 ptr = (char *)type;
5787 }
5788 if (ptr != NULL)
5789 ptr += offset;
5790 return (void **)ptr;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005791}
Guido van Rossumf040ede2001-08-07 16:40:56 +00005792
Guido van Rossumc334df52002-04-04 23:44:47 +00005793/* Length of array of slotdef pointers used to store slots with the
5794 same __name__. There should be at most MAX_EQUIV-1 slotdef entries with
5795 the same __name__, for any __name__. Since that's a static property, it is
5796 appropriate to declare fixed-size arrays for this. */
5797#define MAX_EQUIV 10
5798
5799/* Return a slot pointer for a given name, but ONLY if the attribute has
5800 exactly one slot function. The name must be an interned string. */
5801static void **
5802resolve_slotdups(PyTypeObject *type, PyObject *name)
5803{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005804 /* XXX Maybe this could be optimized more -- but is it worth it? */
Guido van Rossumc334df52002-04-04 23:44:47 +00005805
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005806 /* pname and ptrs act as a little cache */
5807 static PyObject *pname;
5808 static slotdef *ptrs[MAX_EQUIV];
5809 slotdef *p, **pp;
5810 void **res, **ptr;
Guido van Rossumc334df52002-04-04 23:44:47 +00005811
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005812 if (pname != name) {
5813 /* Collect all slotdefs that match name into ptrs. */
5814 pname = name;
5815 pp = ptrs;
5816 for (p = slotdefs; p->name_strobj; p++) {
5817 if (p->name_strobj == name)
5818 *pp++ = p;
5819 }
5820 *pp = NULL;
5821 }
Guido van Rossumc334df52002-04-04 23:44:47 +00005822
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005823 /* Look in all matching slots of the type; if exactly one of these has
5824 a filled-in slot, return its value. Otherwise return NULL. */
5825 res = NULL;
5826 for (pp = ptrs; *pp; pp++) {
5827 ptr = slotptr(type, (*pp)->offset);
5828 if (ptr == NULL || *ptr == NULL)
5829 continue;
5830 if (res != NULL)
5831 return NULL;
5832 res = ptr;
5833 }
5834 return res;
Guido van Rossumc334df52002-04-04 23:44:47 +00005835}
5836
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005837/* Common code for update_slots_callback() and fixup_slot_dispatchers(). This
Guido van Rossumc334df52002-04-04 23:44:47 +00005838 does some incredibly complex thinking and then sticks something into the
5839 slot. (It sees if the adjacent slotdefs for the same slot have conflicting
5840 interests, and then stores a generic wrapper or a specific function into
5841 the slot.) Return a pointer to the next slotdef with a different offset,
5842 because that's convenient for fixup_slot_dispatchers(). */
5843static slotdef *
5844update_one_slot(PyTypeObject *type, slotdef *p)
5845{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005846 PyObject *descr;
5847 PyWrapperDescrObject *d;
5848 void *generic = NULL, *specific = NULL;
5849 int use_generic = 0;
5850 int offset = p->offset;
5851 void **ptr = slotptr(type, offset);
Guido van Rossumc334df52002-04-04 23:44:47 +00005852
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005853 if (ptr == NULL) {
5854 do {
5855 ++p;
5856 } while (p->offset == offset);
5857 return p;
5858 }
5859 do {
5860 descr = _PyType_Lookup(type, p->name_strobj);
5861 if (descr == NULL) {
5862 if (ptr == (void**)&type->tp_iternext) {
5863 specific = _PyObject_NextNotImplemented;
5864 }
5865 continue;
5866 }
5867 if (Py_TYPE(descr) == &PyWrapperDescr_Type) {
5868 void **tptr = resolve_slotdups(type, p->name_strobj);
5869 if (tptr == NULL || tptr == ptr)
5870 generic = p->function;
5871 d = (PyWrapperDescrObject *)descr;
5872 if (d->d_base->wrapper == p->wrapper &&
5873 PyType_IsSubtype(type, PyDescr_TYPE(d)))
5874 {
5875 if (specific == NULL ||
5876 specific == d->d_wrapped)
5877 specific = d->d_wrapped;
5878 else
5879 use_generic = 1;
5880 }
5881 }
5882 else if (Py_TYPE(descr) == &PyCFunction_Type &&
5883 PyCFunction_GET_FUNCTION(descr) ==
5884 (PyCFunction)tp_new_wrapper &&
5885 ptr == (void**)&type->tp_new)
5886 {
5887 /* The __new__ wrapper is not a wrapper descriptor,
5888 so must be special-cased differently.
5889 If we don't do this, creating an instance will
5890 always use slot_tp_new which will look up
5891 __new__ in the MRO which will call tp_new_wrapper
5892 which will look through the base classes looking
5893 for a static base and call its tp_new (usually
5894 PyType_GenericNew), after performing various
5895 sanity checks and constructing a new argument
5896 list. Cut all that nonsense short -- this speeds
5897 up instance creation tremendously. */
5898 specific = (void *)type->tp_new;
5899 /* XXX I'm not 100% sure that there isn't a hole
5900 in this reasoning that requires additional
5901 sanity checks. I'll buy the first person to
5902 point out a bug in this reasoning a beer. */
5903 }
5904 else if (descr == Py_None &&
5905 ptr == (void**)&type->tp_hash) {
5906 /* We specifically allow __hash__ to be set to None
5907 to prevent inheritance of the default
5908 implementation from object.__hash__ */
5909 specific = PyObject_HashNotImplemented;
5910 }
5911 else {
5912 use_generic = 1;
5913 generic = p->function;
5914 }
5915 } while ((++p)->offset == offset);
5916 if (specific && !use_generic)
5917 *ptr = specific;
5918 else
5919 *ptr = generic;
5920 return p;
Guido van Rossumc334df52002-04-04 23:44:47 +00005921}
5922
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005923/* In the type, update the slots whose slotdefs are gathered in the pp array.
5924 This is a callback for update_subclasses(). */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005925static int
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005926update_slots_callback(PyTypeObject *type, void *data)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005927{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005928 slotdef **pp = (slotdef **)data;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005929
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005930 for (; *pp; pp++)
5931 update_one_slot(type, *pp);
5932 return 0;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005933}
5934
Guido van Rossumc334df52002-04-04 23:44:47 +00005935/* Comparison function for qsort() to compare slotdefs by their offset, and
5936 for equal offset by their address (to force a stable sort). */
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005937static int
5938slotdef_cmp(const void *aa, const void *bb)
5939{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005940 const slotdef *a = (const slotdef *)aa, *b = (const slotdef *)bb;
5941 int c = a->offset - b->offset;
5942 if (c != 0)
5943 return c;
5944 else
5945 /* Cannot use a-b, as this gives off_t,
5946 which may lose precision when converted to int. */
5947 return (a > b) ? 1 : (a < b) ? -1 : 0;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005948}
5949
Guido van Rossumc334df52002-04-04 23:44:47 +00005950/* Initialize the slotdefs table by adding interned string objects for the
5951 names and sorting the entries. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005952static void
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005953init_slotdefs(void)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005954{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005955 slotdef *p;
5956 static int initialized = 0;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005957
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005958 if (initialized)
5959 return;
5960 for (p = slotdefs; p->name; p++) {
5961 p->name_strobj = PyUnicode_InternFromString(p->name);
5962 if (!p->name_strobj)
5963 Py_FatalError("Out of memory interning slotdef names");
5964 }
5965 qsort((void *)slotdefs, (size_t)(p-slotdefs), sizeof(slotdef),
5966 slotdef_cmp);
5967 initialized = 1;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005968}
5969
Guido van Rossumc334df52002-04-04 23:44:47 +00005970/* Update the slots after assignment to a class (type) attribute. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005971static int
5972update_slot(PyTypeObject *type, PyObject *name)
5973{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005974 slotdef *ptrs[MAX_EQUIV];
5975 slotdef *p;
5976 slotdef **pp;
5977 int offset;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005978
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005979 /* Clear the VALID_VERSION flag of 'type' and all its
5980 subclasses. This could possibly be unified with the
5981 update_subclasses() recursion below, but carefully:
5982 they each have their own conditions on which to stop
5983 recursing into subclasses. */
5984 PyType_Modified(type);
Christian Heimesa62da1d2008-01-12 19:39:10 +00005985
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005986 init_slotdefs();
5987 pp = ptrs;
5988 for (p = slotdefs; p->name; p++) {
5989 /* XXX assume name is interned! */
5990 if (p->name_strobj == name)
5991 *pp++ = p;
5992 }
5993 *pp = NULL;
5994 for (pp = ptrs; *pp; pp++) {
5995 p = *pp;
5996 offset = p->offset;
5997 while (p > slotdefs && (p-1)->offset == offset)
5998 --p;
5999 *pp = p;
6000 }
6001 if (ptrs[0] == NULL)
6002 return 0; /* Not an attribute that affects any slots */
6003 return update_subclasses(type, name,
6004 update_slots_callback, (void *)ptrs);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006005}
6006
Guido van Rossumc334df52002-04-04 23:44:47 +00006007/* Store the proper functions in the slot dispatches at class (type)
6008 definition time, based upon which operations the class overrides in its
6009 dict. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00006010static void
Guido van Rossum7b9144b2001-10-09 19:39:46 +00006011fixup_slot_dispatchers(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00006012{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006013 slotdef *p;
Tim Peters6d6c1a32001-08-02 04:15:00 +00006014
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006015 init_slotdefs();
6016 for (p = slotdefs; p->name; )
6017 p = update_one_slot(type, p);
Tim Peters6d6c1a32001-08-02 04:15:00 +00006018}
Guido van Rossum705f0f52001-08-24 16:47:00 +00006019
Michael W. Hudson98bbc492002-11-26 14:47:27 +00006020static void
6021update_all_slots(PyTypeObject* type)
6022{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006023 slotdef *p;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00006024
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006025 init_slotdefs();
6026 for (p = slotdefs; p->name; p++) {
6027 /* update_slot returns int but can't actually fail */
6028 update_slot(type, p->name_strobj);
6029 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +00006030}
6031
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006032/* recurse_down_subclasses() and update_subclasses() are mutually
6033 recursive functions to call a callback for all subclasses,
6034 but refraining from recursing into subclasses that define 'name'. */
6035
6036static int
6037update_subclasses(PyTypeObject *type, PyObject *name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006038 update_callback callback, void *data)
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006039{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006040 if (callback(type, data) < 0)
6041 return -1;
6042 return recurse_down_subclasses(type, name, callback, data);
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006043}
6044
6045static int
6046recurse_down_subclasses(PyTypeObject *type, PyObject *name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006047 update_callback callback, void *data)
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006048{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006049 PyTypeObject *subclass;
6050 PyObject *ref, *subclasses, *dict;
6051 Py_ssize_t i, n;
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006052
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006053 subclasses = type->tp_subclasses;
6054 if (subclasses == NULL)
6055 return 0;
6056 assert(PyList_Check(subclasses));
6057 n = PyList_GET_SIZE(subclasses);
6058 for (i = 0; i < n; i++) {
6059 ref = PyList_GET_ITEM(subclasses, i);
6060 assert(PyWeakref_CheckRef(ref));
6061 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
6062 assert(subclass != NULL);
6063 if ((PyObject *)subclass == Py_None)
6064 continue;
6065 assert(PyType_Check(subclass));
6066 /* Avoid recursing down into unaffected classes */
6067 dict = subclass->tp_dict;
6068 if (dict != NULL && PyDict_Check(dict) &&
6069 PyDict_GetItem(dict, name) != NULL)
6070 continue;
6071 if (update_subclasses(subclass, name, callback, data) < 0)
6072 return -1;
6073 }
6074 return 0;
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006075}
6076
Guido van Rossum6d204072001-10-21 00:44:31 +00006077/* This function is called by PyType_Ready() to populate the type's
6078 dictionary with method descriptors for function slots. For each
Guido van Rossum09638c12002-06-13 19:17:46 +00006079 function slot (like tp_repr) that's defined in the type, one or more
6080 corresponding descriptors are added in the type's tp_dict dictionary
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006081 under the appropriate name (like __repr__). Some function slots
Guido van Rossum09638c12002-06-13 19:17:46 +00006082 cause more than one descriptor to be added (for example, the nb_add
6083 slot adds both __add__ and __radd__ descriptors) and some function
6084 slots compete for the same descriptor (for example both sq_item and
6085 mp_subscript generate a __getitem__ descriptor).
6086
Ezio Melotti13925002011-03-16 11:05:33 +02006087 In the latter case, the first slotdef entry encountered wins. Since
Tim Petersbf9b2442003-03-23 05:35:36 +00006088 slotdef entries are sorted by the offset of the slot in the
Guido van Rossume5c691a2003-03-07 15:13:17 +00006089 PyHeapTypeObject, this gives us some control over disambiguating
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006090 between competing slots: the members of PyHeapTypeObject are listed
6091 from most general to least general, so the most general slot is
6092 preferred. In particular, because as_mapping comes before as_sequence,
6093 for a type that defines both mp_subscript and sq_item, mp_subscript
6094 wins.
Guido van Rossum09638c12002-06-13 19:17:46 +00006095
6096 This only adds new descriptors and doesn't overwrite entries in
6097 tp_dict that were previously defined. The descriptors contain a
6098 reference to the C function they must call, so that it's safe if they
6099 are copied into a subtype's __dict__ and the subtype has a different
6100 C function in its slot -- calling the method defined by the
6101 descriptor will call the C function that was used to create it,
6102 rather than the C function present in the slot when it is called.
6103 (This is important because a subtype may have a C function in the
6104 slot that calls the method from the dictionary, and we want to avoid
6105 infinite recursion here.) */
Guido van Rossum6d204072001-10-21 00:44:31 +00006106
6107static int
6108add_operators(PyTypeObject *type)
6109{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006110 PyObject *dict = type->tp_dict;
6111 slotdef *p;
6112 PyObject *descr;
6113 void **ptr;
Guido van Rossum6d204072001-10-21 00:44:31 +00006114
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006115 init_slotdefs();
6116 for (p = slotdefs; p->name; p++) {
6117 if (p->wrapper == NULL)
6118 continue;
6119 ptr = slotptr(type, p->offset);
6120 if (!ptr || !*ptr)
6121 continue;
6122 if (PyDict_GetItem(dict, p->name_strobj))
6123 continue;
6124 if (*ptr == PyObject_HashNotImplemented) {
6125 /* Classes may prevent the inheritance of the tp_hash
6126 slot by storing PyObject_HashNotImplemented in it. Make it
6127 visible as a None value for the __hash__ attribute. */
6128 if (PyDict_SetItem(dict, p->name_strobj, Py_None) < 0)
6129 return -1;
6130 }
6131 else {
6132 descr = PyDescr_NewWrapper(type, p, *ptr);
6133 if (descr == NULL)
6134 return -1;
6135 if (PyDict_SetItem(dict, p->name_strobj, descr) < 0)
6136 return -1;
6137 Py_DECREF(descr);
6138 }
6139 }
6140 if (type->tp_new != NULL) {
6141 if (add_tp_new_wrapper(type) < 0)
6142 return -1;
6143 }
6144 return 0;
Guido van Rossum6d204072001-10-21 00:44:31 +00006145}
6146
Guido van Rossum705f0f52001-08-24 16:47:00 +00006147
6148/* Cooperative 'super' */
6149
6150typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006151 PyObject_HEAD
6152 PyTypeObject *type;
6153 PyObject *obj;
6154 PyTypeObject *obj_type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006155} superobject;
6156
Guido van Rossum6f799372001-09-20 20:46:19 +00006157static PyMemberDef super_members[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006158 {"__thisclass__", T_OBJECT, offsetof(superobject, type), READONLY,
6159 "the class invoking super()"},
6160 {"__self__", T_OBJECT, offsetof(superobject, obj), READONLY,
6161 "the instance invoking super(); may be None"},
6162 {"__self_class__", T_OBJECT, offsetof(superobject, obj_type), READONLY,
6163 "the type of the instance invoking super(); may be None"},
6164 {0}
Guido van Rossum41eb14d2001-08-30 23:13:11 +00006165};
6166
Guido van Rossum705f0f52001-08-24 16:47:00 +00006167static void
6168super_dealloc(PyObject *self)
6169{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006170 superobject *su = (superobject *)self;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006171
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006172 _PyObject_GC_UNTRACK(self);
6173 Py_XDECREF(su->obj);
6174 Py_XDECREF(su->type);
6175 Py_XDECREF(su->obj_type);
6176 Py_TYPE(self)->tp_free(self);
Guido van Rossum705f0f52001-08-24 16:47:00 +00006177}
6178
6179static PyObject *
Guido van Rossum41eb14d2001-08-30 23:13:11 +00006180super_repr(PyObject *self)
6181{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006182 superobject *su = (superobject *)self;
Guido van Rossum41eb14d2001-08-30 23:13:11 +00006183
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006184 if (su->obj_type)
6185 return PyUnicode_FromFormat(
6186 "<super: <class '%s'>, <%s object>>",
6187 su->type ? su->type->tp_name : "NULL",
6188 su->obj_type->tp_name);
6189 else
6190 return PyUnicode_FromFormat(
6191 "<super: <class '%s'>, NULL>",
6192 su->type ? su->type->tp_name : "NULL");
Guido van Rossum41eb14d2001-08-30 23:13:11 +00006193}
6194
6195static PyObject *
Guido van Rossum705f0f52001-08-24 16:47:00 +00006196super_getattro(PyObject *self, PyObject *name)
6197{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006198 superobject *su = (superobject *)self;
6199 int skip = su->obj_type == NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006200
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006201 if (!skip) {
6202 /* We want __class__ to return the class of the super object
6203 (i.e. super, or a subclass), not the class of su->obj. */
6204 skip = (PyUnicode_Check(name) &&
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006205 PyUnicode_GET_LENGTH(name) == 9 &&
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006206 PyUnicode_CompareWithASCIIString(name, "__class__") == 0);
6207 }
Guido van Rossum76ba09f2003-04-16 19:40:58 +00006208
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006209 if (!skip) {
6210 PyObject *mro, *res, *tmp, *dict;
6211 PyTypeObject *starttype;
6212 descrgetfunc f;
6213 Py_ssize_t i, n;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006214
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006215 starttype = su->obj_type;
6216 mro = starttype->tp_mro;
Guido van Rossum155db9a2002-04-02 17:53:47 +00006217
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006218 if (mro == NULL)
6219 n = 0;
6220 else {
6221 assert(PyTuple_Check(mro));
6222 n = PyTuple_GET_SIZE(mro);
6223 }
6224 for (i = 0; i < n; i++) {
6225 if ((PyObject *)(su->type) == PyTuple_GET_ITEM(mro, i))
6226 break;
6227 }
6228 i++;
6229 res = NULL;
Victor Stinnerd74782b2012-03-09 00:39:08 +01006230 /* keep a strong reference to mro because starttype->tp_mro can be
6231 replaced during PyDict_GetItem(dict, name) */
6232 Py_INCREF(mro);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006233 for (; i < n; i++) {
6234 tmp = PyTuple_GET_ITEM(mro, i);
6235 if (PyType_Check(tmp))
6236 dict = ((PyTypeObject *)tmp)->tp_dict;
6237 else
6238 continue;
6239 res = PyDict_GetItem(dict, name);
6240 if (res != NULL) {
6241 Py_INCREF(res);
6242 f = Py_TYPE(res)->tp_descr_get;
6243 if (f != NULL) {
6244 tmp = f(res,
6245 /* Only pass 'obj' param if
6246 this is instance-mode super
6247 (See SF ID #743627)
6248 */
6249 (su->obj == (PyObject *)
6250 su->obj_type
6251 ? (PyObject *)NULL
6252 : su->obj),
6253 (PyObject *)starttype);
6254 Py_DECREF(res);
6255 res = tmp;
6256 }
Victor Stinnerd74782b2012-03-09 00:39:08 +01006257 Py_DECREF(mro);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006258 return res;
6259 }
6260 }
Victor Stinnerd74782b2012-03-09 00:39:08 +01006261 Py_DECREF(mro);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006262 }
6263 return PyObject_GenericGetAttr(self, name);
Guido van Rossum705f0f52001-08-24 16:47:00 +00006264}
6265
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006266static PyTypeObject *
Guido van Rossum5b443c62001-12-03 15:38:28 +00006267supercheck(PyTypeObject *type, PyObject *obj)
6268{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006269 /* Check that a super() call makes sense. Return a type object.
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006270
Florent Xiclunaaa6c1d22011-12-12 18:54:29 +01006271 obj can be a class, or an instance of one:
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006272
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006273 - If it is a class, it must be a subclass of 'type'. This case is
6274 used for class methods; the return value is obj.
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006275
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006276 - If it is an instance, it must be an instance of 'type'. This is
6277 the normal case; the return value is obj.__class__.
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006278
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006279 But... when obj is an instance, we want to allow for the case where
6280 Py_TYPE(obj) is not a subclass of type, but obj.__class__ is!
6281 This will allow using super() with a proxy for obj.
6282 */
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006283
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006284 /* Check for first bullet above (special case) */
6285 if (PyType_Check(obj) && PyType_IsSubtype((PyTypeObject *)obj, type)) {
6286 Py_INCREF(obj);
6287 return (PyTypeObject *)obj;
6288 }
Guido van Rossum8e80a722003-02-18 19:22:22 +00006289
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006290 /* Normal case */
6291 if (PyType_IsSubtype(Py_TYPE(obj), type)) {
6292 Py_INCREF(Py_TYPE(obj));
6293 return Py_TYPE(obj);
6294 }
6295 else {
6296 /* Try the slow way */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006297 PyObject *class_attr;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006298
Martin v. Löwisbfc6d742011-10-13 20:03:57 +02006299 class_attr = _PyObject_GetAttrId(obj, &PyId___class__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006300 if (class_attr != NULL &&
6301 PyType_Check(class_attr) &&
6302 (PyTypeObject *)class_attr != Py_TYPE(obj))
6303 {
6304 int ok = PyType_IsSubtype(
6305 (PyTypeObject *)class_attr, type);
6306 if (ok)
6307 return (PyTypeObject *)class_attr;
6308 }
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006309
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006310 if (class_attr == NULL)
6311 PyErr_Clear();
6312 else
6313 Py_DECREF(class_attr);
6314 }
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006315
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006316 PyErr_SetString(PyExc_TypeError,
6317 "super(type, obj): "
6318 "obj must be an instance or subtype of type");
6319 return NULL;
Guido van Rossum5b443c62001-12-03 15:38:28 +00006320}
6321
Guido van Rossum705f0f52001-08-24 16:47:00 +00006322static PyObject *
6323super_descr_get(PyObject *self, PyObject *obj, PyObject *type)
6324{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006325 superobject *su = (superobject *)self;
6326 superobject *newobj;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006327
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006328 if (obj == NULL || obj == Py_None || su->obj != NULL) {
6329 /* Not binding to an object, or already bound */
6330 Py_INCREF(self);
6331 return self;
6332 }
6333 if (Py_TYPE(su) != &PySuper_Type)
6334 /* If su is an instance of a (strict) subclass of super,
6335 call its type */
6336 return PyObject_CallFunctionObjArgs((PyObject *)Py_TYPE(su),
6337 su->type, obj, NULL);
6338 else {
6339 /* Inline the common case */
6340 PyTypeObject *obj_type = supercheck(su->type, obj);
6341 if (obj_type == NULL)
6342 return NULL;
6343 newobj = (superobject *)PySuper_Type.tp_new(&PySuper_Type,
6344 NULL, NULL);
6345 if (newobj == NULL)
6346 return NULL;
6347 Py_INCREF(su->type);
6348 Py_INCREF(obj);
6349 newobj->type = su->type;
6350 newobj->obj = obj;
6351 newobj->obj_type = obj_type;
6352 return (PyObject *)newobj;
6353 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00006354}
6355
6356static int
6357super_init(PyObject *self, PyObject *args, PyObject *kwds)
6358{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006359 superobject *su = (superobject *)self;
6360 PyTypeObject *type = NULL;
6361 PyObject *obj = NULL;
6362 PyTypeObject *obj_type = NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006363
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006364 if (!_PyArg_NoKeywords("super", kwds))
6365 return -1;
6366 if (!PyArg_ParseTuple(args, "|O!O:super", &PyType_Type, &type, &obj))
6367 return -1;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00006368
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006369 if (type == NULL) {
6370 /* Call super(), without args -- fill in from __class__
6371 and first local variable on the stack. */
6372 PyFrameObject *f = PyThreadState_GET()->frame;
6373 PyCodeObject *co = f->f_code;
Victor Stinner0fcab4a2011-01-04 12:59:15 +00006374 Py_ssize_t i, n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006375 if (co == NULL) {
6376 PyErr_SetString(PyExc_SystemError,
6377 "super(): no code object");
6378 return -1;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00006379 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006380 if (co->co_argcount == 0) {
6381 PyErr_SetString(PyExc_SystemError,
6382 "super(): no arguments");
6383 return -1;
6384 }
6385 obj = f->f_localsplus[0];
6386 if (obj == NULL) {
6387 PyErr_SetString(PyExc_SystemError,
6388 "super(): arg[0] deleted");
6389 return -1;
6390 }
6391 if (co->co_freevars == NULL)
6392 n = 0;
6393 else {
6394 assert(PyTuple_Check(co->co_freevars));
6395 n = PyTuple_GET_SIZE(co->co_freevars);
6396 }
6397 for (i = 0; i < n; i++) {
6398 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
6399 assert(PyUnicode_Check(name));
6400 if (!PyUnicode_CompareWithASCIIString(name,
Benjamin Petersonf5ff2232011-06-19 19:42:22 -05006401 "@__class__")) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006402 Py_ssize_t index = co->co_nlocals +
6403 PyTuple_GET_SIZE(co->co_cellvars) + i;
6404 PyObject *cell = f->f_localsplus[index];
6405 if (cell == NULL || !PyCell_Check(cell)) {
6406 PyErr_SetString(PyExc_SystemError,
6407 "super(): bad __class__ cell");
6408 return -1;
6409 }
6410 type = (PyTypeObject *) PyCell_GET(cell);
6411 if (type == NULL) {
6412 PyErr_SetString(PyExc_SystemError,
6413 "super(): empty __class__ cell");
6414 return -1;
6415 }
6416 if (!PyType_Check(type)) {
6417 PyErr_Format(PyExc_SystemError,
6418 "super(): __class__ is not a type (%s)",
6419 Py_TYPE(type)->tp_name);
6420 return -1;
6421 }
6422 break;
6423 }
6424 }
6425 if (type == NULL) {
6426 PyErr_SetString(PyExc_SystemError,
6427 "super(): __class__ cell not found");
6428 return -1;
6429 }
6430 }
Guido van Rossumcd16bf62007-06-13 18:07:49 +00006431
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006432 if (obj == Py_None)
6433 obj = NULL;
6434 if (obj != NULL) {
6435 obj_type = supercheck(type, obj);
6436 if (obj_type == NULL)
6437 return -1;
6438 Py_INCREF(obj);
6439 }
6440 Py_INCREF(type);
6441 su->type = type;
6442 su->obj = obj;
6443 su->obj_type = obj_type;
6444 return 0;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006445}
6446
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00006447PyDoc_STRVAR(super_doc,
Guido van Rossumcd16bf62007-06-13 18:07:49 +00006448"super() -> same as super(__class__, <first argument>)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00006449"super(type) -> unbound super object\n"
6450"super(type, obj) -> bound super object; requires isinstance(obj, type)\n"
Guido van Rossume705ef12001-08-29 15:47:06 +00006451"super(type, type2) -> bound super object; requires issubclass(type2, type)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00006452"Typical use to call a cooperative superclass method:\n"
6453"class C(B):\n"
6454" def meth(self, arg):\n"
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006455" super().meth(arg)\n"
Guido van Rossumcd16bf62007-06-13 18:07:49 +00006456"This works for class methods too:\n"
6457"class C(B):\n"
6458" @classmethod\n"
6459" def cmeth(cls, arg):\n"
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006460" super().cmeth(arg)\n");
Guido van Rossum705f0f52001-08-24 16:47:00 +00006461
Guido van Rossum048eb752001-10-02 21:24:57 +00006462static int
6463super_traverse(PyObject *self, visitproc visit, void *arg)
6464{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006465 superobject *su = (superobject *)self;
Guido van Rossum048eb752001-10-02 21:24:57 +00006466
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006467 Py_VISIT(su->obj);
6468 Py_VISIT(su->type);
6469 Py_VISIT(su->obj_type);
Guido van Rossum048eb752001-10-02 21:24:57 +00006470
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006471 return 0;
Guido van Rossum048eb752001-10-02 21:24:57 +00006472}
6473
Guido van Rossum705f0f52001-08-24 16:47:00 +00006474PyTypeObject PySuper_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006475 PyVarObject_HEAD_INIT(&PyType_Type, 0)
6476 "super", /* tp_name */
6477 sizeof(superobject), /* tp_basicsize */
6478 0, /* tp_itemsize */
6479 /* methods */
6480 super_dealloc, /* tp_dealloc */
6481 0, /* tp_print */
6482 0, /* tp_getattr */
6483 0, /* tp_setattr */
6484 0, /* tp_reserved */
6485 super_repr, /* tp_repr */
6486 0, /* tp_as_number */
6487 0, /* tp_as_sequence */
6488 0, /* tp_as_mapping */
6489 0, /* tp_hash */
6490 0, /* tp_call */
6491 0, /* tp_str */
6492 super_getattro, /* tp_getattro */
6493 0, /* tp_setattro */
6494 0, /* tp_as_buffer */
6495 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
6496 Py_TPFLAGS_BASETYPE, /* tp_flags */
6497 super_doc, /* tp_doc */
6498 super_traverse, /* tp_traverse */
6499 0, /* tp_clear */
6500 0, /* tp_richcompare */
6501 0, /* tp_weaklistoffset */
6502 0, /* tp_iter */
6503 0, /* tp_iternext */
6504 0, /* tp_methods */
6505 super_members, /* tp_members */
6506 0, /* tp_getset */
6507 0, /* tp_base */
6508 0, /* tp_dict */
6509 super_descr_get, /* tp_descr_get */
6510 0, /* tp_descr_set */
6511 0, /* tp_dictoffset */
6512 super_init, /* tp_init */
6513 PyType_GenericAlloc, /* tp_alloc */
6514 PyType_GenericNew, /* tp_new */
6515 PyObject_GC_Del, /* tp_free */
Guido van Rossum705f0f52001-08-24 16:47:00 +00006516};