blob: 9aa752e057305f7aa6b8b2ace23632f122ae7036 [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(__dict__);
39_Py_IDENTIFIER(__class__);
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +020040
Christian Heimes26855632008-01-27 23:50:43 +000041unsigned int
42PyType_ClearCache(void)
43{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000044 Py_ssize_t i;
45 unsigned int cur_version_tag = next_version_tag - 1;
46
47 for (i = 0; i < (1 << MCACHE_SIZE_EXP); i++) {
48 method_cache[i].version = 0;
49 Py_CLEAR(method_cache[i].name);
50 method_cache[i].value = NULL;
51 }
52 next_version_tag = 0;
53 /* mark all version tags as invalid */
54 PyType_Modified(&PyBaseObject_Type);
55 return cur_version_tag;
Christian Heimes26855632008-01-27 23:50:43 +000056}
Christian Heimesa62da1d2008-01-12 19:39:10 +000057
Georg Brandlf08a9dd2008-06-10 16:57:31 +000058void
59PyType_Modified(PyTypeObject *type)
Christian Heimesa62da1d2008-01-12 19:39:10 +000060{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000061 /* Invalidate any cached data for the specified type and all
62 subclasses. This function is called after the base
63 classes, mro, or attributes of the type are altered.
Christian Heimesa62da1d2008-01-12 19:39:10 +000064
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000065 Invariants:
Christian Heimesa62da1d2008-01-12 19:39:10 +000066
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000067 - Py_TPFLAGS_VALID_VERSION_TAG is never set if
68 Py_TPFLAGS_HAVE_VERSION_TAG is not set (e.g. on type
69 objects coming from non-recompiled extension modules)
Christian Heimesa62da1d2008-01-12 19:39:10 +000070
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000071 - before Py_TPFLAGS_VALID_VERSION_TAG can be set on a type,
72 it must first be set on all super types.
Christian Heimesa62da1d2008-01-12 19:39:10 +000073
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000074 This function clears the Py_TPFLAGS_VALID_VERSION_TAG of a
75 type (so it must first clear it on all subclasses). The
76 tp_version_tag value is meaningless unless this flag is set.
77 We don't assign new version tags eagerly, but only as
78 needed.
79 */
80 PyObject *raw, *ref;
81 Py_ssize_t i, n;
Christian Heimesa62da1d2008-01-12 19:39:10 +000082
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000083 if (!PyType_HasFeature(type, Py_TPFLAGS_VALID_VERSION_TAG))
84 return;
Christian Heimesa62da1d2008-01-12 19:39:10 +000085
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000086 raw = type->tp_subclasses;
87 if (raw != NULL) {
88 n = PyList_GET_SIZE(raw);
89 for (i = 0; i < n; i++) {
90 ref = PyList_GET_ITEM(raw, i);
91 ref = PyWeakref_GET_OBJECT(ref);
92 if (ref != Py_None) {
93 PyType_Modified((PyTypeObject *)ref);
94 }
95 }
96 }
97 type->tp_flags &= ~Py_TPFLAGS_VALID_VERSION_TAG;
Christian Heimesa62da1d2008-01-12 19:39:10 +000098}
99
100static void
101type_mro_modified(PyTypeObject *type, PyObject *bases) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000102 /*
Florent Xiclunaaa6c1d22011-12-12 18:54:29 +0100103 Check that all base classes or elements of the MRO of type are
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000104 able to be cached. This function is called after the base
105 classes or mro of the type are altered.
Christian Heimesa62da1d2008-01-12 19:39:10 +0000106
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000107 Unset HAVE_VERSION_TAG and VALID_VERSION_TAG if the type
Florent Xiclunaaa6c1d22011-12-12 18:54:29 +0100108 has a custom MRO that includes a type which is not officially
109 super type.
Christian Heimesa62da1d2008-01-12 19:39:10 +0000110
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000111 Called from mro_internal, which will subsequently be called on
112 each subclass when their mro is recursively updated.
113 */
114 Py_ssize_t i, n;
115 int clear = 0;
Christian Heimesa62da1d2008-01-12 19:39:10 +0000116
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000117 if (!PyType_HasFeature(type, Py_TPFLAGS_HAVE_VERSION_TAG))
118 return;
Christian Heimesa62da1d2008-01-12 19:39:10 +0000119
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000120 n = PyTuple_GET_SIZE(bases);
121 for (i = 0; i < n; i++) {
122 PyObject *b = PyTuple_GET_ITEM(bases, i);
123 PyTypeObject *cls;
Christian Heimesa62da1d2008-01-12 19:39:10 +0000124
Florent Xiclunaaa6c1d22011-12-12 18:54:29 +0100125 assert(PyType_Check(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000126 cls = (PyTypeObject *)b;
Christian Heimesa62da1d2008-01-12 19:39:10 +0000127
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000128 if (!PyType_HasFeature(cls, Py_TPFLAGS_HAVE_VERSION_TAG) ||
129 !PyType_IsSubtype(type, cls)) {
130 clear = 1;
131 break;
132 }
133 }
Christian Heimesa62da1d2008-01-12 19:39:10 +0000134
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000135 if (clear)
136 type->tp_flags &= ~(Py_TPFLAGS_HAVE_VERSION_TAG|
137 Py_TPFLAGS_VALID_VERSION_TAG);
Christian Heimesa62da1d2008-01-12 19:39:10 +0000138}
139
140static int
141assign_version_tag(PyTypeObject *type)
142{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000143 /* Ensure that the tp_version_tag is valid and set
144 Py_TPFLAGS_VALID_VERSION_TAG. To respect the invariant, this
145 must first be done on all super classes. Return 0 if this
146 cannot be done, 1 if Py_TPFLAGS_VALID_VERSION_TAG.
147 */
148 Py_ssize_t i, n;
149 PyObject *bases;
Christian Heimesa62da1d2008-01-12 19:39:10 +0000150
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000151 if (PyType_HasFeature(type, Py_TPFLAGS_VALID_VERSION_TAG))
152 return 1;
153 if (!PyType_HasFeature(type, Py_TPFLAGS_HAVE_VERSION_TAG))
154 return 0;
155 if (!PyType_HasFeature(type, Py_TPFLAGS_READY))
156 return 0;
Christian Heimesa62da1d2008-01-12 19:39:10 +0000157
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000158 type->tp_version_tag = next_version_tag++;
159 /* for stress-testing: next_version_tag &= 0xFF; */
Christian Heimesa62da1d2008-01-12 19:39:10 +0000160
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000161 if (type->tp_version_tag == 0) {
162 /* wrap-around or just starting Python - clear the whole
163 cache by filling names with references to Py_None.
164 Values are also set to NULL for added protection, as they
165 are borrowed reference */
166 for (i = 0; i < (1 << MCACHE_SIZE_EXP); i++) {
167 method_cache[i].value = NULL;
168 Py_XDECREF(method_cache[i].name);
169 method_cache[i].name = Py_None;
170 Py_INCREF(Py_None);
171 }
172 /* mark all version tags as invalid */
173 PyType_Modified(&PyBaseObject_Type);
174 return 1;
175 }
176 bases = type->tp_bases;
177 n = PyTuple_GET_SIZE(bases);
178 for (i = 0; i < n; i++) {
179 PyObject *b = PyTuple_GET_ITEM(bases, i);
180 assert(PyType_Check(b));
181 if (!assign_version_tag((PyTypeObject *)b))
182 return 0;
183 }
184 type->tp_flags |= Py_TPFLAGS_VALID_VERSION_TAG;
185 return 1;
Christian Heimesa62da1d2008-01-12 19:39:10 +0000186}
187
188
Guido van Rossum6f799372001-09-20 20:46:19 +0000189static PyMemberDef type_members[] = {
Benjamin Peterson0e102062010-08-25 23:13:17 +0000190 {"__basicsize__", T_PYSSIZET, offsetof(PyTypeObject,tp_basicsize),READONLY},
191 {"__itemsize__", T_PYSSIZET, offsetof(PyTypeObject, tp_itemsize), READONLY},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000192 {"__flags__", T_LONG, offsetof(PyTypeObject, tp_flags), READONLY},
193 {"__weakrefoffset__", T_LONG,
194 offsetof(PyTypeObject, tp_weaklistoffset), READONLY},
195 {"__base__", T_OBJECT, offsetof(PyTypeObject, tp_base), READONLY},
196 {"__dictoffset__", T_LONG,
197 offsetof(PyTypeObject, tp_dictoffset), READONLY},
198 {"__mro__", T_OBJECT, offsetof(PyTypeObject, tp_mro), READONLY},
199 {0}
Tim Peters6d6c1a32001-08-02 04:15:00 +0000200};
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000201
Benjamin Petersond9f23d22011-08-17 11:54:03 -0500202static int
203check_set_special_type_attr(PyTypeObject *type, PyObject *value, const char *name)
204{
205 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
206 PyErr_Format(PyExc_TypeError,
207 "can't set %s.%s", type->tp_name, name);
208 return 0;
209 }
210 if (!value) {
211 PyErr_Format(PyExc_TypeError,
212 "can't delete %s.%s", type->tp_name, name);
213 return 0;
214 }
215 return 1;
216}
217
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000218static PyObject *
Guido van Rossumc3542212001-08-16 09:18:56 +0000219type_name(PyTypeObject *type, void *context)
220{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000221 const char *s;
Guido van Rossumc3542212001-08-16 09:18:56 +0000222
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000223 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
224 PyHeapTypeObject* et = (PyHeapTypeObject*)type;
Tim Petersea7f75d2002-12-07 21:39:16 +0000225
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000226 Py_INCREF(et->ht_name);
227 return et->ht_name;
228 }
229 else {
230 s = strrchr(type->tp_name, '.');
231 if (s == NULL)
232 s = type->tp_name;
233 else
234 s++;
235 return PyUnicode_FromString(s);
236 }
Guido van Rossumc3542212001-08-16 09:18:56 +0000237}
238
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100239static PyObject *
240type_qualname(PyTypeObject *type, void *context)
241{
242 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
243 PyHeapTypeObject* et = (PyHeapTypeObject*)type;
244 Py_INCREF(et->ht_qualname);
245 return et->ht_qualname;
246 }
247 else {
248 return type_name(type, context);
249 }
250}
251
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000252static int
253type_set_name(PyTypeObject *type, PyObject *value, void *context)
254{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000255 PyHeapTypeObject* et;
256 char *tp_name;
257 PyObject *tmp;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000258
Benjamin Petersond9f23d22011-08-17 11:54:03 -0500259 if (!check_set_special_type_attr(type, value, "__name__"))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000260 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000261 if (!PyUnicode_Check(value)) {
262 PyErr_Format(PyExc_TypeError,
263 "can only assign string to %s.__name__, not '%s'",
264 type->tp_name, Py_TYPE(value)->tp_name);
265 return -1;
266 }
Guido van Rossume845c0f2007-11-02 23:07:07 +0000267
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000268 /* Check absence of null characters */
269 tmp = PyUnicode_FromStringAndSize("\0", 1);
270 if (tmp == NULL)
271 return -1;
272 if (PyUnicode_Contains(value, tmp) != 0) {
273 Py_DECREF(tmp);
274 PyErr_Format(PyExc_ValueError,
275 "__name__ must not contain null bytes");
276 return -1;
277 }
278 Py_DECREF(tmp);
Guido van Rossume845c0f2007-11-02 23:07:07 +0000279
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000280 tp_name = _PyUnicode_AsString(value);
281 if (tp_name == NULL)
282 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000283
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000284 et = (PyHeapTypeObject*)type;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000285
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000286 Py_INCREF(value);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000287
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000288 Py_DECREF(et->ht_name);
289 et->ht_name = value;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000290
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000291 type->tp_name = tp_name;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000292
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000293 return 0;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000294}
295
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100296static int
297type_set_qualname(PyTypeObject *type, PyObject *value, void *context)
298{
299 PyHeapTypeObject* et;
300
301 if (!PyUnicode_Check(value)) {
302 PyErr_Format(PyExc_TypeError,
303 "can only assign string to %s.__qualname__, not '%s'",
304 type->tp_name, Py_TYPE(value)->tp_name);
305 return -1;
306 }
307
308 et = (PyHeapTypeObject*)type;
309 Py_INCREF(value);
310 Py_DECREF(et->ht_qualname);
311 et->ht_qualname = value;
312 return 0;
313}
314
Guido van Rossumc3542212001-08-16 09:18:56 +0000315static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000316type_module(PyTypeObject *type, void *context)
Guido van Rossum29ca26e1995-01-07 11:58:15 +0000317{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000318 PyObject *mod;
319 char *s;
Guido van Rossumc3542212001-08-16 09:18:56 +0000320
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000321 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
322 mod = PyDict_GetItemString(type->tp_dict, "__module__");
323 if (!mod) {
324 PyErr_Format(PyExc_AttributeError, "__module__");
325 return 0;
326 }
327 Py_XINCREF(mod);
328 return mod;
329 }
330 else {
331 s = strrchr(type->tp_name, '.');
332 if (s != NULL)
333 return PyUnicode_FromStringAndSize(
334 type->tp_name, (Py_ssize_t)(s - type->tp_name));
335 return PyUnicode_FromString("builtins");
336 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000337}
338
Guido van Rossum3926a632001-09-25 16:25:58 +0000339static int
340type_set_module(PyTypeObject *type, PyObject *value, void *context)
341{
Benjamin Petersond9f23d22011-08-17 11:54:03 -0500342 if (!check_set_special_type_attr(type, value, "__module__"))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000343 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000344
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000345 PyType_Modified(type);
Christian Heimesa62da1d2008-01-12 19:39:10 +0000346
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000347 return PyDict_SetItemString(type->tp_dict, "__module__", value);
Guido van Rossum3926a632001-09-25 16:25:58 +0000348}
349
Tim Peters6d6c1a32001-08-02 04:15:00 +0000350static PyObject *
Christian Heimes9e7f1d22008-02-28 12:27:11 +0000351type_abstractmethods(PyTypeObject *type, void *context)
352{
Benjamin Petersonaec5fd12010-10-02 00:03:31 +0000353 PyObject *mod = NULL;
Benjamin Peterson84060b82010-10-03 02:13:39 +0000354 /* type itself has an __abstractmethods__ descriptor (this). Don't return
355 that. */
Benjamin Petersonaec5fd12010-10-02 00:03:31 +0000356 if (type != &PyType_Type)
357 mod = PyDict_GetItemString(type->tp_dict, "__abstractmethods__");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000358 if (!mod) {
Benjamin Peterson23b628e2011-01-12 18:56:07 +0000359 PyErr_SetString(PyExc_AttributeError, "__abstractmethods__");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000360 return NULL;
361 }
362 Py_XINCREF(mod);
363 return mod;
Christian Heimes9e7f1d22008-02-28 12:27:11 +0000364}
365
366static int
367type_set_abstractmethods(PyTypeObject *type, PyObject *value, void *context)
368{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000369 /* __abstractmethods__ should only be set once on a type, in
370 abc.ABCMeta.__new__, so this function doesn't do anything
371 special to update subclasses.
372 */
Benjamin Peterson477ba912011-01-12 15:34:01 +0000373 int res;
374 if (value != NULL) {
375 res = PyDict_SetItemString(type->tp_dict, "__abstractmethods__", value);
376 }
377 else {
378 res = PyDict_DelItemString(type->tp_dict, "__abstractmethods__");
379 if (res && PyErr_ExceptionMatches(PyExc_KeyError)) {
Benjamin Peterson23b628e2011-01-12 18:56:07 +0000380 PyErr_SetString(PyExc_AttributeError, "__abstractmethods__");
Benjamin Peterson477ba912011-01-12 15:34:01 +0000381 return -1;
382 }
383 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000384 if (res == 0) {
385 PyType_Modified(type);
386 if (value && PyObject_IsTrue(value)) {
387 type->tp_flags |= Py_TPFLAGS_IS_ABSTRACT;
388 }
389 else {
390 type->tp_flags &= ~Py_TPFLAGS_IS_ABSTRACT;
391 }
392 }
393 return res;
Christian Heimes9e7f1d22008-02-28 12:27:11 +0000394}
395
396static PyObject *
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000397type_get_bases(PyTypeObject *type, void *context)
398{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000399 Py_INCREF(type->tp_bases);
400 return type->tp_bases;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000401}
402
403static PyTypeObject *best_base(PyObject *);
404static int mro_internal(PyTypeObject *);
405static int compatible_for_assignment(PyTypeObject *, PyTypeObject *, char *);
406static int add_subclass(PyTypeObject*, PyTypeObject*);
407static void remove_subclass(PyTypeObject *, PyTypeObject *);
408static void update_all_slots(PyTypeObject *);
409
Guido van Rossum8d24ee92003-03-24 23:49:49 +0000410typedef int (*update_callback)(PyTypeObject *, void *);
411static int update_subclasses(PyTypeObject *type, PyObject *name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000412 update_callback callback, void *data);
Guido van Rossum8d24ee92003-03-24 23:49:49 +0000413static int recurse_down_subclasses(PyTypeObject *type, PyObject *name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000414 update_callback callback, void *data);
Guido van Rossum8d24ee92003-03-24 23:49:49 +0000415
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000416static int
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000417mro_subclasses(PyTypeObject *type, PyObject* temp)
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000418{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000419 PyTypeObject *subclass;
420 PyObject *ref, *subclasses, *old_mro;
421 Py_ssize_t i, n;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000422
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000423 subclasses = type->tp_subclasses;
424 if (subclasses == NULL)
425 return 0;
426 assert(PyList_Check(subclasses));
427 n = PyList_GET_SIZE(subclasses);
428 for (i = 0; i < n; i++) {
429 ref = PyList_GET_ITEM(subclasses, i);
430 assert(PyWeakref_CheckRef(ref));
431 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
432 assert(subclass != NULL);
433 if ((PyObject *)subclass == Py_None)
434 continue;
435 assert(PyType_Check(subclass));
436 old_mro = subclass->tp_mro;
437 if (mro_internal(subclass) < 0) {
438 subclass->tp_mro = old_mro;
439 return -1;
440 }
441 else {
442 PyObject* tuple;
443 tuple = PyTuple_Pack(2, subclass, old_mro);
444 Py_DECREF(old_mro);
445 if (!tuple)
446 return -1;
447 if (PyList_Append(temp, tuple) < 0)
448 return -1;
449 Py_DECREF(tuple);
450 }
451 if (mro_subclasses(subclass, temp) < 0)
452 return -1;
453 }
454 return 0;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000455}
456
457static int
458type_set_bases(PyTypeObject *type, PyObject *value, void *context)
459{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000460 Py_ssize_t i;
461 int r = 0;
462 PyObject *ob, *temp;
463 PyTypeObject *new_base, *old_base;
464 PyObject *old_bases, *old_mro;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000465
Benjamin Petersond9f23d22011-08-17 11:54:03 -0500466 if (!check_set_special_type_attr(type, value, "__bases__"))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000467 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000468 if (!PyTuple_Check(value)) {
469 PyErr_Format(PyExc_TypeError,
470 "can only assign tuple to %s.__bases__, not %s",
471 type->tp_name, Py_TYPE(value)->tp_name);
472 return -1;
473 }
474 if (PyTuple_GET_SIZE(value) == 0) {
475 PyErr_Format(PyExc_TypeError,
476 "can only assign non-empty tuple to %s.__bases__, not ()",
477 type->tp_name);
478 return -1;
479 }
480 for (i = 0; i < PyTuple_GET_SIZE(value); i++) {
481 ob = PyTuple_GET_ITEM(value, i);
482 if (!PyType_Check(ob)) {
483 PyErr_Format(
484 PyExc_TypeError,
Florent Xiclunaaa6c1d22011-12-12 18:54:29 +0100485 "%s.__bases__ must be tuple of classes, not '%s'",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000486 type->tp_name, Py_TYPE(ob)->tp_name);
487 return -1;
488 }
489 if (PyType_Check(ob)) {
490 if (PyType_IsSubtype((PyTypeObject*)ob, type)) {
491 PyErr_SetString(PyExc_TypeError,
492 "a __bases__ item causes an inheritance cycle");
493 return -1;
494 }
495 }
496 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000497
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000498 new_base = best_base(value);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000499
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000500 if (!new_base) {
501 return -1;
502 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000503
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000504 if (!compatible_for_assignment(type->tp_base, new_base, "__bases__"))
505 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000506
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000507 Py_INCREF(new_base);
508 Py_INCREF(value);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000509
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000510 old_bases = type->tp_bases;
511 old_base = type->tp_base;
512 old_mro = type->tp_mro;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000513
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000514 type->tp_bases = value;
515 type->tp_base = new_base;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000516
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000517 if (mro_internal(type) < 0) {
518 goto bail;
519 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000520
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000521 temp = PyList_New(0);
522 if (!temp)
523 goto bail;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000524
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000525 r = mro_subclasses(type, temp);
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000526
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000527 if (r < 0) {
528 for (i = 0; i < PyList_Size(temp); i++) {
529 PyTypeObject* cls;
530 PyObject* mro;
531 PyArg_UnpackTuple(PyList_GET_ITEM(temp, i),
532 "", 2, 2, &cls, &mro);
533 Py_INCREF(mro);
534 ob = cls->tp_mro;
535 cls->tp_mro = mro;
536 Py_DECREF(ob);
537 }
538 Py_DECREF(temp);
539 goto bail;
540 }
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000541
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000542 Py_DECREF(temp);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000543
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000544 /* any base that was in __bases__ but now isn't, we
545 need to remove |type| from its tp_subclasses.
546 conversely, any class now in __bases__ that wasn't
547 needs to have |type| added to its subclasses. */
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000548
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000549 /* for now, sod that: just remove from all old_bases,
550 add to all new_bases */
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000551
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000552 for (i = PyTuple_GET_SIZE(old_bases) - 1; i >= 0; i--) {
553 ob = PyTuple_GET_ITEM(old_bases, i);
554 if (PyType_Check(ob)) {
555 remove_subclass(
556 (PyTypeObject*)ob, type);
557 }
558 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000559
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000560 for (i = PyTuple_GET_SIZE(value) - 1; i >= 0; i--) {
561 ob = PyTuple_GET_ITEM(value, i);
562 if (PyType_Check(ob)) {
563 if (add_subclass((PyTypeObject*)ob, type) < 0)
564 r = -1;
565 }
566 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000567
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000568 update_all_slots(type);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000569
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000570 Py_DECREF(old_bases);
571 Py_DECREF(old_base);
572 Py_DECREF(old_mro);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000573
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000574 return r;
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000575
576 bail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000577 Py_DECREF(type->tp_bases);
578 Py_DECREF(type->tp_base);
579 if (type->tp_mro != old_mro) {
580 Py_DECREF(type->tp_mro);
581 }
Michael W. Hudsone723e452003-08-07 14:58:10 +0000582
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000583 type->tp_bases = old_bases;
584 type->tp_base = old_base;
585 type->tp_mro = old_mro;
Tim Petersea7f75d2002-12-07 21:39:16 +0000586
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000587 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000588}
589
590static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000591type_dict(PyTypeObject *type, void *context)
592{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000593 if (type->tp_dict == NULL) {
594 Py_INCREF(Py_None);
595 return Py_None;
596 }
597 return PyDictProxy_New(type->tp_dict);
Guido van Rossum29ca26e1995-01-07 11:58:15 +0000598}
599
Tim Peters24008312002-03-17 18:56:20 +0000600static PyObject *
601type_get_doc(PyTypeObject *type, void *context)
602{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000603 PyObject *result;
604 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE) && type->tp_doc != NULL)
605 return PyUnicode_FromString(type->tp_doc);
606 result = PyDict_GetItemString(type->tp_dict, "__doc__");
607 if (result == NULL) {
608 result = Py_None;
609 Py_INCREF(result);
610 }
611 else if (Py_TYPE(result)->tp_descr_get) {
612 result = Py_TYPE(result)->tp_descr_get(result, NULL,
613 (PyObject *)type);
614 }
615 else {
616 Py_INCREF(result);
617 }
618 return result;
Tim Peters24008312002-03-17 18:56:20 +0000619}
620
Benjamin Peterson01fc6cd2011-08-17 12:03:47 -0500621static int
622type_set_doc(PyTypeObject *type, PyObject *value, void *context)
623{
624 if (!check_set_special_type_attr(type, value, "__doc__"))
625 return -1;
626 PyType_Modified(type);
627 return PyDict_SetItemString(type->tp_dict, "__doc__", value);
628}
629
Antoine Pitrouec569b72008-08-26 22:40:48 +0000630static PyObject *
631type___instancecheck__(PyObject *type, PyObject *inst)
632{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000633 switch (_PyObject_RealIsInstance(inst, type)) {
634 case -1:
635 return NULL;
636 case 0:
637 Py_RETURN_FALSE;
638 default:
639 Py_RETURN_TRUE;
640 }
Antoine Pitrouec569b72008-08-26 22:40:48 +0000641}
642
643
644static PyObject *
Antoine Pitrouec569b72008-08-26 22:40:48 +0000645type___subclasscheck__(PyObject *type, PyObject *inst)
646{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000647 switch (_PyObject_RealIsSubclass(inst, type)) {
648 case -1:
649 return NULL;
650 case 0:
651 Py_RETURN_FALSE;
652 default:
653 Py_RETURN_TRUE;
654 }
Antoine Pitrouec569b72008-08-26 22:40:48 +0000655}
656
Antoine Pitrouec569b72008-08-26 22:40:48 +0000657
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000658static PyGetSetDef type_getsets[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000659 {"__name__", (getter)type_name, (setter)type_set_name, NULL},
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100660 {"__qualname__", (getter)type_qualname, (setter)type_set_qualname, NULL},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000661 {"__bases__", (getter)type_get_bases, (setter)type_set_bases, NULL},
662 {"__module__", (getter)type_module, (setter)type_set_module, NULL},
663 {"__abstractmethods__", (getter)type_abstractmethods,
664 (setter)type_set_abstractmethods, NULL},
665 {"__dict__", (getter)type_dict, NULL, NULL},
Benjamin Peterson01fc6cd2011-08-17 12:03:47 -0500666 {"__doc__", (getter)type_get_doc, (setter)type_set_doc, NULL},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000667 {0}
Tim Peters6d6c1a32001-08-02 04:15:00 +0000668};
669
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000670static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000671type_repr(PyTypeObject *type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000672{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000673 PyObject *mod, *name, *rtn;
Guido van Rossumc3542212001-08-16 09:18:56 +0000674
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000675 mod = type_module(type, NULL);
676 if (mod == NULL)
677 PyErr_Clear();
678 else if (!PyUnicode_Check(mod)) {
679 Py_DECREF(mod);
680 mod = NULL;
681 }
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100682 name = type_qualname(type, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000683 if (name == NULL)
684 return NULL;
Barry Warsaw7ce36942001-08-24 18:34:26 +0000685
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000686 if (mod != NULL && PyUnicode_CompareWithASCIIString(mod, "builtins"))
687 rtn = PyUnicode_FromFormat("<class '%U.%U'>", mod, name);
688 else
689 rtn = PyUnicode_FromFormat("<class '%s'>", type->tp_name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000690
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000691 Py_XDECREF(mod);
692 Py_DECREF(name);
693 return rtn;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000694}
695
Tim Peters6d6c1a32001-08-02 04:15:00 +0000696static PyObject *
697type_call(PyTypeObject *type, PyObject *args, PyObject *kwds)
698{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000699 PyObject *obj;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000700
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000701 if (type->tp_new == NULL) {
702 PyErr_Format(PyExc_TypeError,
703 "cannot create '%.100s' instances",
704 type->tp_name);
705 return NULL;
706 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000707
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000708 obj = type->tp_new(type, args, kwds);
709 if (obj != NULL) {
710 /* Ugly exception: when the call was type(something),
711 don't call tp_init on the result. */
712 if (type == &PyType_Type &&
713 PyTuple_Check(args) && PyTuple_GET_SIZE(args) == 1 &&
714 (kwds == NULL ||
715 (PyDict_Check(kwds) && PyDict_Size(kwds) == 0)))
716 return obj;
717 /* If the returned object is not an instance of type,
718 it won't be initialized. */
719 if (!PyType_IsSubtype(Py_TYPE(obj), type))
720 return obj;
721 type = Py_TYPE(obj);
722 if (type->tp_init != NULL &&
723 type->tp_init(obj, args, kwds) < 0) {
724 Py_DECREF(obj);
725 obj = NULL;
726 }
727 }
728 return obj;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000729}
730
731PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000732PyType_GenericAlloc(PyTypeObject *type, Py_ssize_t nitems)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000733{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000734 PyObject *obj;
735 const size_t size = _PyObject_VAR_SIZE(type, nitems+1);
736 /* note that we need to add one, for the sentinel */
Tim Peters406fe3b2001-10-06 19:04:01 +0000737
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000738 if (PyType_IS_GC(type))
739 obj = _PyObject_GC_Malloc(size);
740 else
741 obj = (PyObject *)PyObject_MALLOC(size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000742
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000743 if (obj == NULL)
744 return PyErr_NoMemory();
Tim Peters406fe3b2001-10-06 19:04:01 +0000745
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000746 memset(obj, '\0', size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000747
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000748 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
749 Py_INCREF(type);
Tim Peters406fe3b2001-10-06 19:04:01 +0000750
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000751 if (type->tp_itemsize == 0)
752 PyObject_INIT(obj, type);
753 else
754 (void) PyObject_INIT_VAR((PyVarObject *)obj, type, nitems);
Tim Peters406fe3b2001-10-06 19:04:01 +0000755
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000756 if (PyType_IS_GC(type))
757 _PyObject_GC_TRACK(obj);
758 return obj;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000759}
760
761PyObject *
762PyType_GenericNew(PyTypeObject *type, PyObject *args, PyObject *kwds)
763{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000764 return type->tp_alloc(type, 0);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000765}
766
Guido van Rossum9475a232001-10-05 20:51:39 +0000767/* Helpers for subtyping */
768
769static int
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000770traverse_slots(PyTypeObject *type, PyObject *self, visitproc visit, void *arg)
771{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000772 Py_ssize_t i, n;
773 PyMemberDef *mp;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000774
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000775 n = Py_SIZE(type);
776 mp = PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type);
777 for (i = 0; i < n; i++, mp++) {
778 if (mp->type == T_OBJECT_EX) {
779 char *addr = (char *)self + mp->offset;
780 PyObject *obj = *(PyObject **)addr;
781 if (obj != NULL) {
782 int err = visit(obj, arg);
783 if (err)
784 return err;
785 }
786 }
787 }
788 return 0;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000789}
790
791static int
Guido van Rossum9475a232001-10-05 20:51:39 +0000792subtype_traverse(PyObject *self, visitproc visit, void *arg)
793{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000794 PyTypeObject *type, *base;
795 traverseproc basetraverse;
Guido van Rossum9475a232001-10-05 20:51:39 +0000796
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000797 /* Find the nearest base with a different tp_traverse,
798 and traverse slots while we're at it */
799 type = Py_TYPE(self);
800 base = type;
801 while ((basetraverse = base->tp_traverse) == subtype_traverse) {
802 if (Py_SIZE(base)) {
803 int err = traverse_slots(base, self, visit, arg);
804 if (err)
805 return err;
806 }
807 base = base->tp_base;
808 assert(base);
809 }
Guido van Rossum9475a232001-10-05 20:51:39 +0000810
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000811 if (type->tp_dictoffset != base->tp_dictoffset) {
812 PyObject **dictptr = _PyObject_GetDictPtr(self);
813 if (dictptr && *dictptr)
814 Py_VISIT(*dictptr);
815 }
Guido van Rossum9475a232001-10-05 20:51:39 +0000816
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000817 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
818 /* For a heaptype, the instances count as references
819 to the type. Traverse the type so the collector
820 can find cycles involving this link. */
821 Py_VISIT(type);
Guido van Rossuma3862092002-06-10 15:24:42 +0000822
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000823 if (basetraverse)
824 return basetraverse(self, visit, arg);
825 return 0;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000826}
827
828static void
829clear_slots(PyTypeObject *type, PyObject *self)
830{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000831 Py_ssize_t i, n;
832 PyMemberDef *mp;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000833
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000834 n = Py_SIZE(type);
835 mp = PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type);
836 for (i = 0; i < n; i++, mp++) {
837 if (mp->type == T_OBJECT_EX && !(mp->flags & READONLY)) {
838 char *addr = (char *)self + mp->offset;
839 PyObject *obj = *(PyObject **)addr;
840 if (obj != NULL) {
841 *(PyObject **)addr = NULL;
842 Py_DECREF(obj);
843 }
844 }
845 }
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000846}
847
848static int
849subtype_clear(PyObject *self)
850{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000851 PyTypeObject *type, *base;
852 inquiry baseclear;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000853
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000854 /* Find the nearest base with a different tp_clear
855 and clear slots while we're at it */
856 type = Py_TYPE(self);
857 base = type;
858 while ((baseclear = base->tp_clear) == subtype_clear) {
859 if (Py_SIZE(base))
860 clear_slots(base, self);
861 base = base->tp_base;
862 assert(base);
863 }
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000864
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000865 /* There's no need to clear the instance dict (if any);
866 the collector will call its tp_clear handler. */
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000867
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000868 if (baseclear)
869 return baseclear(self);
870 return 0;
Guido van Rossum9475a232001-10-05 20:51:39 +0000871}
Tim Peters6d6c1a32001-08-02 04:15:00 +0000872
873static void
874subtype_dealloc(PyObject *self)
875{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000876 PyTypeObject *type, *base;
877 destructor basedealloc;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000878
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000879 /* Extract the type; we expect it to be a heap type */
880 type = Py_TYPE(self);
881 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000882
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000883 /* Test whether the type has GC exactly once */
Guido van Rossum22b13872002-08-06 21:41:44 +0000884
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000885 if (!PyType_IS_GC(type)) {
886 /* It's really rare to find a dynamic type that doesn't have
887 GC; it can only happen when deriving from 'object' and not
888 adding any slots or instance variables. This allows
889 certain simplifications: there's no need to call
890 clear_slots(), or DECREF the dict, or clear weakrefs. */
Guido van Rossum22b13872002-08-06 21:41:44 +0000891
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000892 /* Maybe call finalizer; exit early if resurrected */
893 if (type->tp_del) {
894 type->tp_del(self);
895 if (self->ob_refcnt > 0)
896 return;
897 }
Guido van Rossum22b13872002-08-06 21:41:44 +0000898
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000899 /* Find the nearest base with a different tp_dealloc */
900 base = type;
901 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
902 assert(Py_SIZE(base) == 0);
903 base = base->tp_base;
904 assert(base);
905 }
Guido van Rossum22b13872002-08-06 21:41:44 +0000906
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000907 /* Extract the type again; tp_del may have changed it */
908 type = Py_TYPE(self);
Benjamin Peterson193152c2009-04-25 01:08:45 +0000909
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000910 /* Call the base tp_dealloc() */
911 assert(basedealloc);
912 basedealloc(self);
Guido van Rossum22b13872002-08-06 21:41:44 +0000913
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000914 /* Can't reference self beyond this point */
915 Py_DECREF(type);
Guido van Rossum22b13872002-08-06 21:41:44 +0000916
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000917 /* Done */
918 return;
919 }
Guido van Rossum22b13872002-08-06 21:41:44 +0000920
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000921 /* We get here only if the type has GC */
Guido van Rossum22b13872002-08-06 21:41:44 +0000922
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000923 /* UnTrack and re-Track around the trashcan macro, alas */
924 /* See explanation at end of function for full disclosure */
925 PyObject_GC_UnTrack(self);
926 ++_PyTrash_delete_nesting;
927 Py_TRASHCAN_SAFE_BEGIN(self);
928 --_PyTrash_delete_nesting;
929 /* DO NOT restore GC tracking at this point. weakref callbacks
930 * (if any, and whether directly here or indirectly in something we
931 * call) may trigger GC, and if self is tracked at that point, it
932 * will look like trash to GC and GC will try to delete self again.
933 */
Guido van Rossum22b13872002-08-06 21:41:44 +0000934
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000935 /* Find the nearest base with a different tp_dealloc */
936 base = type;
Brett Cannonb94767f2011-02-22 20:15:44 +0000937 while ((/*basedealloc =*/ base->tp_dealloc) == subtype_dealloc) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000938 base = base->tp_base;
939 assert(base);
940 }
Guido van Rossum14227b42001-12-06 02:35:58 +0000941
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000942 /* If we added a weaklist, we clear it. Do this *before* calling
943 the finalizer (__del__), clearing slots, or clearing the instance
944 dict. */
Guido van Rossum59195fd2003-06-13 20:54:40 +0000945
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000946 if (type->tp_weaklistoffset && !base->tp_weaklistoffset)
947 PyObject_ClearWeakRefs(self);
Guido van Rossum1987c662003-05-29 14:29:23 +0000948
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000949 /* Maybe call finalizer; exit early if resurrected */
950 if (type->tp_del) {
951 _PyObject_GC_TRACK(self);
952 type->tp_del(self);
953 if (self->ob_refcnt > 0)
954 goto endlabel; /* resurrected */
955 else
956 _PyObject_GC_UNTRACK(self);
957 /* New weakrefs could be created during the finalizer call.
958 If this occurs, clear them out without calling their
959 finalizers since they might rely on part of the object
960 being finalized that has already been destroyed. */
961 if (type->tp_weaklistoffset && !base->tp_weaklistoffset) {
962 /* Modeled after GET_WEAKREFS_LISTPTR() */
963 PyWeakReference **list = (PyWeakReference **) \
964 PyObject_GET_WEAKREFS_LISTPTR(self);
965 while (*list)
966 _PyWeakref_ClearRef(*list);
967 }
968 }
Guido van Rossum1987c662003-05-29 14:29:23 +0000969
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000970 /* Clear slots up to the nearest base with a different tp_dealloc */
971 base = type;
972 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
973 if (Py_SIZE(base))
974 clear_slots(base, self);
975 base = base->tp_base;
976 assert(base);
977 }
Guido van Rossum59195fd2003-06-13 20:54:40 +0000978
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000979 /* If we added a dict, DECREF it */
980 if (type->tp_dictoffset && !base->tp_dictoffset) {
981 PyObject **dictptr = _PyObject_GetDictPtr(self);
982 if (dictptr != NULL) {
983 PyObject *dict = *dictptr;
984 if (dict != NULL) {
985 Py_DECREF(dict);
986 *dictptr = NULL;
987 }
988 }
989 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000990
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000991 /* Extract the type again; tp_del may have changed it */
992 type = Py_TYPE(self);
Benjamin Peterson193152c2009-04-25 01:08:45 +0000993
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000994 /* Call the base tp_dealloc(); first retrack self if
995 * basedealloc knows about gc.
996 */
997 if (PyType_IS_GC(base))
998 _PyObject_GC_TRACK(self);
999 assert(basedealloc);
1000 basedealloc(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001001
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001002 /* Can't reference self beyond this point */
1003 Py_DECREF(type);
Guido van Rossum22b13872002-08-06 21:41:44 +00001004
Guido van Rossum0906e072002-08-07 20:42:09 +00001005 endlabel:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001006 ++_PyTrash_delete_nesting;
1007 Py_TRASHCAN_SAFE_END(self);
1008 --_PyTrash_delete_nesting;
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001009
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001010 /* Explanation of the weirdness around the trashcan macros:
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001011
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001012 Q. What do the trashcan macros do?
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001013
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001014 A. Read the comment titled "Trashcan mechanism" in object.h.
1015 For one, this explains why there must be a call to GC-untrack
1016 before the trashcan begin macro. Without understanding the
1017 trashcan code, the answers to the following questions don't make
1018 sense.
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001019
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001020 Q. Why do we GC-untrack before the trashcan and then immediately
1021 GC-track again afterward?
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001022
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001023 A. In the case that the base class is GC-aware, the base class
1024 probably GC-untracks the object. If it does that using the
1025 UNTRACK macro, this will crash when the object is already
1026 untracked. Because we don't know what the base class does, the
1027 only safe thing is to make sure the object is tracked when we
1028 call the base class dealloc. But... The trashcan begin macro
1029 requires that the object is *untracked* before it is called. So
1030 the dance becomes:
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001031
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001032 GC untrack
1033 trashcan begin
1034 GC track
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001035
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001036 Q. Why did the last question say "immediately GC-track again"?
1037 It's nowhere near immediately.
Tim Petersf7f9e992003-11-13 21:59:32 +00001038
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001039 A. Because the code *used* to re-track immediately. Bad Idea.
1040 self has a refcount of 0, and if gc ever gets its hands on it
1041 (which can happen if any weakref callback gets invoked), it
1042 looks like trash to gc too, and gc also tries to delete self
Ezio Melotti13925002011-03-16 11:05:33 +02001043 then. But we're already deleting self. Double deallocation is
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001044 a subtle disaster.
Tim Petersf7f9e992003-11-13 21:59:32 +00001045
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001046 Q. Why the bizarre (net-zero) manipulation of
1047 _PyTrash_delete_nesting around the trashcan macros?
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001048
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001049 A. Some base classes (e.g. list) also use the trashcan mechanism.
1050 The following scenario used to be possible:
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001051
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001052 - suppose the trashcan level is one below the trashcan limit
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001053
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001054 - subtype_dealloc() is called
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001055
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001056 - the trashcan limit is not yet reached, so the trashcan level
1057 is incremented and the code between trashcan begin and end is
1058 executed
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001059
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001060 - this destroys much of the object's contents, including its
1061 slots and __dict__
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001062
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001063 - basedealloc() is called; this is really list_dealloc(), or
1064 some other type which also uses the trashcan macros
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001065
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001066 - the trashcan limit is now reached, so the object is put on the
1067 trashcan's to-be-deleted-later list
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001068
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001069 - basedealloc() returns
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001070
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001071 - subtype_dealloc() decrefs the object's type
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001072
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001073 - subtype_dealloc() returns
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001074
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001075 - later, the trashcan code starts deleting the objects from its
1076 to-be-deleted-later list
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001077
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001078 - subtype_dealloc() is called *AGAIN* for the same object
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001079
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001080 - at the very least (if the destroyed slots and __dict__ don't
1081 cause problems) the object's type gets decref'ed a second
1082 time, which is *BAD*!!!
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001083
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001084 The remedy is to make sure that if the code between trashcan
1085 begin and end in subtype_dealloc() is called, the code between
1086 trashcan begin and end in basedealloc() will also be called.
1087 This is done by decrementing the level after passing into the
1088 trashcan block, and incrementing it just before leaving the
1089 block.
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001090
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001091 But now it's possible that a chain of objects consisting solely
1092 of objects whose deallocator is subtype_dealloc() will defeat
1093 the trashcan mechanism completely: the decremented level means
1094 that the effective level never reaches the limit. Therefore, we
1095 *increment* the level *before* entering the trashcan block, and
1096 matchingly decrement it after leaving. This means the trashcan
1097 code will trigger a little early, but that's no big deal.
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001098
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001099 Q. Are there any live examples of code in need of all this
1100 complexity?
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001101
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001102 A. Yes. See SF bug 668433 for code that crashed (when Python was
1103 compiled in debug mode) before the trashcan level manipulations
1104 were added. For more discussion, see SF patches 581742, 575073
1105 and bug 574207.
1106 */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001107}
1108
Jeremy Hylton938ace62002-07-17 16:30:39 +00001109static PyTypeObject *solid_base(PyTypeObject *type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001110
Tim Peters6d6c1a32001-08-02 04:15:00 +00001111/* type test with subclassing support */
1112
1113int
1114PyType_IsSubtype(PyTypeObject *a, PyTypeObject *b)
1115{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001116 PyObject *mro;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001117
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001118 mro = a->tp_mro;
1119 if (mro != NULL) {
1120 /* Deal with multiple inheritance without recursion
1121 by walking the MRO tuple */
1122 Py_ssize_t i, n;
1123 assert(PyTuple_Check(mro));
1124 n = PyTuple_GET_SIZE(mro);
1125 for (i = 0; i < n; i++) {
1126 if (PyTuple_GET_ITEM(mro, i) == (PyObject *)b)
1127 return 1;
1128 }
1129 return 0;
1130 }
1131 else {
1132 /* a is not completely initilized yet; follow tp_base */
1133 do {
1134 if (a == b)
1135 return 1;
1136 a = a->tp_base;
1137 } while (a != NULL);
1138 return b == &PyBaseObject_Type;
1139 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001140}
1141
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001142/* Internal routines to do a method lookup in the type
Guido van Rossum60718732001-08-28 17:47:51 +00001143 without looking in the instance dictionary
1144 (so we can't use PyObject_GetAttr) but still binding
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001145 it to the instance. The arguments are the object,
Guido van Rossum60718732001-08-28 17:47:51 +00001146 the method name as a C string, and the address of a
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001147 static variable used to cache the interned Python string.
1148
1149 Two variants:
1150
1151 - lookup_maybe() returns NULL without raising an exception
1152 when the _PyType_Lookup() call fails;
1153
1154 - lookup_method() always raises an exception upon errors.
Benjamin Peterson224205f2009-05-08 03:25:19 +00001155
1156 - _PyObject_LookupSpecial() exported for the benefit of other places.
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001157*/
Guido van Rossum60718732001-08-28 17:47:51 +00001158
1159static PyObject *
Benjamin Petersonce798522012-01-22 11:24:29 -05001160lookup_maybe(PyObject *self, _Py_Identifier *attrid)
Guido van Rossum60718732001-08-28 17:47:51 +00001161{
Benjamin Petersonce798522012-01-22 11:24:29 -05001162 PyObject *attr, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00001163
Benjamin Petersonce798522012-01-22 11:24:29 -05001164 attr = _PyUnicode_FromId(attrid);
1165 if (attr == NULL)
1166 return NULL;
1167 res = _PyType_Lookup(Py_TYPE(self), attr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001168 if (res != NULL) {
1169 descrgetfunc f;
1170 if ((f = Py_TYPE(res)->tp_descr_get) == NULL)
1171 Py_INCREF(res);
1172 else
1173 res = f(res, self, (PyObject *)(Py_TYPE(self)));
1174 }
1175 return res;
Guido van Rossum60718732001-08-28 17:47:51 +00001176}
1177
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001178static PyObject *
Benjamin Petersonce798522012-01-22 11:24:29 -05001179lookup_method(PyObject *self, _Py_Identifier *attrid)
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001180{
Benjamin Petersonce798522012-01-22 11:24:29 -05001181 PyObject *res = lookup_maybe(self, attrid);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001182 if (res == NULL && !PyErr_Occurred())
Benjamin Petersonce798522012-01-22 11:24:29 -05001183 PyErr_SetObject(PyExc_AttributeError, attrid->object);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001184 return res;
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001185}
1186
Benjamin Peterson224205f2009-05-08 03:25:19 +00001187PyObject *
Benjamin Petersonce798522012-01-22 11:24:29 -05001188_PyObject_LookupSpecial(PyObject *self, _Py_Identifier *attrid)
Benjamin Peterson224205f2009-05-08 03:25:19 +00001189{
Benjamin Petersonce798522012-01-22 11:24:29 -05001190 return lookup_maybe(self, attrid);
Benjamin Peterson224205f2009-05-08 03:25:19 +00001191}
1192
Guido van Rossum2730b132001-08-28 18:22:14 +00001193/* A variation of PyObject_CallMethod that uses lookup_method()
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001194 instead of PyObject_GetAttrString(). This uses the same convention
Guido van Rossum2730b132001-08-28 18:22:14 +00001195 as lookup_method to cache the interned name string object. */
1196
Neil Schemenauerf23473f2001-10-21 22:28:58 +00001197static PyObject *
Benjamin Petersonce798522012-01-22 11:24:29 -05001198call_method(PyObject *o, _Py_Identifier *nameid, char *format, ...)
Guido van Rossum2730b132001-08-28 18:22:14 +00001199{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001200 va_list va;
1201 PyObject *args, *func = 0, *retval;
1202 va_start(va, format);
Guido van Rossum2730b132001-08-28 18:22:14 +00001203
Benjamin Petersonce798522012-01-22 11:24:29 -05001204 func = lookup_maybe(o, nameid);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001205 if (func == NULL) {
1206 va_end(va);
1207 if (!PyErr_Occurred())
Benjamin Petersonce798522012-01-22 11:24:29 -05001208 PyErr_SetObject(PyExc_AttributeError, nameid->object);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001209 return NULL;
1210 }
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001211
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001212 if (format && *format)
1213 args = Py_VaBuildValue(format, va);
1214 else
1215 args = PyTuple_New(0);
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001216
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001217 va_end(va);
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001218
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001219 if (args == NULL)
1220 return NULL;
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001221
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001222 assert(PyTuple_Check(args));
1223 retval = PyObject_Call(func, args, NULL);
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001224
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001225 Py_DECREF(args);
1226 Py_DECREF(func);
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001227
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001228 return retval;
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001229}
1230
1231/* Clone of call_method() that returns NotImplemented when the lookup fails. */
1232
Neil Schemenauerf23473f2001-10-21 22:28:58 +00001233static PyObject *
Benjamin Petersonce798522012-01-22 11:24:29 -05001234call_maybe(PyObject *o, _Py_Identifier *nameid, char *format, ...)
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001235{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001236 va_list va;
1237 PyObject *args, *func = 0, *retval;
1238 va_start(va, format);
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001239
Benjamin Petersonce798522012-01-22 11:24:29 -05001240 func = lookup_maybe(o, nameid);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001241 if (func == NULL) {
1242 va_end(va);
Brian Curtindfc80e32011-08-10 20:28:54 -05001243 if (!PyErr_Occurred())
1244 Py_RETURN_NOTIMPLEMENTED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001245 return NULL;
1246 }
Guido van Rossum2730b132001-08-28 18:22:14 +00001247
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001248 if (format && *format)
1249 args = Py_VaBuildValue(format, va);
1250 else
1251 args = PyTuple_New(0);
Guido van Rossum2730b132001-08-28 18:22:14 +00001252
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001253 va_end(va);
Guido van Rossum2730b132001-08-28 18:22:14 +00001254
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001255 if (args == NULL)
1256 return NULL;
Guido van Rossum2730b132001-08-28 18:22:14 +00001257
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001258 assert(PyTuple_Check(args));
1259 retval = PyObject_Call(func, args, NULL);
Guido van Rossum2730b132001-08-28 18:22:14 +00001260
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001261 Py_DECREF(args);
1262 Py_DECREF(func);
Guido van Rossum2730b132001-08-28 18:22:14 +00001263
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001264 return retval;
Guido van Rossum2730b132001-08-28 18:22:14 +00001265}
1266
Tim Petersea7f75d2002-12-07 21:39:16 +00001267/*
Guido van Rossum1f121312002-11-14 19:49:16 +00001268 Method resolution order algorithm C3 described in
1269 "A Monotonic Superclass Linearization for Dylan",
1270 by Kim Barrett, Bob Cassel, Paul Haahr,
Tim Petersea7f75d2002-12-07 21:39:16 +00001271 David A. Moon, Keith Playford, and P. Tucker Withington.
Guido van Rossum1f121312002-11-14 19:49:16 +00001272 (OOPSLA 1996)
1273
Guido van Rossum98f33732002-11-25 21:36:54 +00001274 Some notes about the rules implied by C3:
1275
Tim Petersea7f75d2002-12-07 21:39:16 +00001276 No duplicate bases.
Guido van Rossum98f33732002-11-25 21:36:54 +00001277 It isn't legal to repeat a class in a list of base classes.
1278
1279 The next three properties are the 3 constraints in "C3".
1280
Tim Petersea7f75d2002-12-07 21:39:16 +00001281 Local precendece order.
Guido van Rossum98f33732002-11-25 21:36:54 +00001282 If A precedes B in C's MRO, then A will precede B in the MRO of all
1283 subclasses of C.
1284
1285 Monotonicity.
1286 The MRO of a class must be an extension without reordering of the
1287 MRO of each of its superclasses.
1288
1289 Extended Precedence Graph (EPG).
1290 Linearization is consistent if there is a path in the EPG from
1291 each class to all its successors in the linearization. See
1292 the paper for definition of EPG.
Guido van Rossum1f121312002-11-14 19:49:16 +00001293 */
1294
Tim Petersea7f75d2002-12-07 21:39:16 +00001295static int
Guido van Rossum1f121312002-11-14 19:49:16 +00001296tail_contains(PyObject *list, int whence, PyObject *o) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001297 Py_ssize_t j, size;
1298 size = PyList_GET_SIZE(list);
Guido van Rossum1f121312002-11-14 19:49:16 +00001299
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001300 for (j = whence+1; j < size; j++) {
1301 if (PyList_GET_ITEM(list, j) == o)
1302 return 1;
1303 }
1304 return 0;
Guido van Rossum1f121312002-11-14 19:49:16 +00001305}
1306
Guido van Rossum98f33732002-11-25 21:36:54 +00001307static PyObject *
1308class_name(PyObject *cls)
1309{
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001310 _Py_IDENTIFIER(__name__);
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001311 PyObject *name = _PyObject_GetAttrId(cls, &PyId___name__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001312 if (name == NULL) {
1313 PyErr_Clear();
1314 Py_XDECREF(name);
1315 name = PyObject_Repr(cls);
1316 }
1317 if (name == NULL)
1318 return NULL;
1319 if (!PyUnicode_Check(name)) {
1320 Py_DECREF(name);
1321 return NULL;
1322 }
1323 return name;
Guido van Rossum98f33732002-11-25 21:36:54 +00001324}
1325
1326static int
1327check_duplicates(PyObject *list)
1328{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001329 Py_ssize_t i, j, n;
1330 /* Let's use a quadratic time algorithm,
1331 assuming that the bases lists is short.
1332 */
1333 n = PyList_GET_SIZE(list);
1334 for (i = 0; i < n; i++) {
1335 PyObject *o = PyList_GET_ITEM(list, i);
1336 for (j = i + 1; j < n; j++) {
1337 if (PyList_GET_ITEM(list, j) == o) {
1338 o = class_name(o);
1339 if (o != NULL) {
1340 PyErr_Format(PyExc_TypeError,
1341 "duplicate base class %U",
1342 o);
1343 Py_DECREF(o);
1344 } else {
1345 PyErr_SetString(PyExc_TypeError,
1346 "duplicate base class");
1347 }
1348 return -1;
1349 }
1350 }
1351 }
1352 return 0;
Guido van Rossum98f33732002-11-25 21:36:54 +00001353}
1354
1355/* Raise a TypeError for an MRO order disagreement.
1356
1357 It's hard to produce a good error message. In the absence of better
1358 insight into error reporting, report the classes that were candidates
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001359 to be put next into the MRO. There is some conflict between the
Guido van Rossum98f33732002-11-25 21:36:54 +00001360 order in which they should be put in the MRO, but it's hard to
1361 diagnose what constraint can't be satisfied.
1362*/
1363
1364static void
1365set_mro_error(PyObject *to_merge, int *remain)
1366{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001367 Py_ssize_t i, n, off, to_merge_size;
1368 char buf[1000];
1369 PyObject *k, *v;
1370 PyObject *set = PyDict_New();
1371 if (!set) return;
Guido van Rossum98f33732002-11-25 21:36:54 +00001372
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001373 to_merge_size = PyList_GET_SIZE(to_merge);
1374 for (i = 0; i < to_merge_size; i++) {
1375 PyObject *L = PyList_GET_ITEM(to_merge, i);
1376 if (remain[i] < PyList_GET_SIZE(L)) {
1377 PyObject *c = PyList_GET_ITEM(L, remain[i]);
1378 if (PyDict_SetItem(set, c, Py_None) < 0) {
1379 Py_DECREF(set);
1380 return;
1381 }
1382 }
1383 }
1384 n = PyDict_Size(set);
Guido van Rossum98f33732002-11-25 21:36:54 +00001385
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001386 off = PyOS_snprintf(buf, sizeof(buf), "Cannot create a \
Raymond Hettingerf394df42003-04-06 19:13:41 +00001387consistent method resolution\norder (MRO) for bases");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001388 i = 0;
1389 while (PyDict_Next(set, &i, &k, &v) && (size_t)off < sizeof(buf)) {
1390 PyObject *name = class_name(k);
Victor Stinnere5f99f32010-05-19 01:42:46 +00001391 char *name_str;
1392 if (name != NULL) {
1393 name_str = _PyUnicode_AsString(name);
1394 if (name_str == NULL)
Victor Stinnerba644a62010-05-19 01:50:45 +00001395 name_str = "?";
Victor Stinnere5f99f32010-05-19 01:42:46 +00001396 } else
Victor Stinnerba644a62010-05-19 01:50:45 +00001397 name_str = "?";
Victor Stinnere5f99f32010-05-19 01:42:46 +00001398 off += PyOS_snprintf(buf + off, sizeof(buf) - off, " %s", name_str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001399 Py_XDECREF(name);
1400 if (--n && (size_t)(off+1) < sizeof(buf)) {
1401 buf[off++] = ',';
1402 buf[off] = '\0';
1403 }
1404 }
1405 PyErr_SetString(PyExc_TypeError, buf);
1406 Py_DECREF(set);
Guido van Rossum98f33732002-11-25 21:36:54 +00001407}
1408
Tim Petersea7f75d2002-12-07 21:39:16 +00001409static int
Guido van Rossum1f121312002-11-14 19:49:16 +00001410pmerge(PyObject *acc, PyObject* to_merge) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001411 Py_ssize_t i, j, to_merge_size, empty_cnt;
1412 int *remain;
1413 int ok;
Tim Petersea7f75d2002-12-07 21:39:16 +00001414
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001415 to_merge_size = PyList_GET_SIZE(to_merge);
Guido van Rossum1f121312002-11-14 19:49:16 +00001416
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001417 /* remain stores an index into each sublist of to_merge.
1418 remain[i] is the index of the next base in to_merge[i]
1419 that is not included in acc.
1420 */
1421 remain = (int *)PyMem_MALLOC(SIZEOF_INT*to_merge_size);
1422 if (remain == NULL)
1423 return -1;
1424 for (i = 0; i < to_merge_size; i++)
1425 remain[i] = 0;
Guido van Rossum1f121312002-11-14 19:49:16 +00001426
1427 again:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001428 empty_cnt = 0;
1429 for (i = 0; i < to_merge_size; i++) {
1430 PyObject *candidate;
Tim Petersea7f75d2002-12-07 21:39:16 +00001431
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001432 PyObject *cur_list = PyList_GET_ITEM(to_merge, i);
Guido van Rossum1f121312002-11-14 19:49:16 +00001433
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001434 if (remain[i] >= PyList_GET_SIZE(cur_list)) {
1435 empty_cnt++;
1436 continue;
1437 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001438
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001439 /* Choose next candidate for MRO.
Guido van Rossum98f33732002-11-25 21:36:54 +00001440
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001441 The input sequences alone can determine the choice.
1442 If not, choose the class which appears in the MRO
1443 of the earliest direct superclass of the new class.
1444 */
Guido van Rossum98f33732002-11-25 21:36:54 +00001445
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001446 candidate = PyList_GET_ITEM(cur_list, remain[i]);
1447 for (j = 0; j < to_merge_size; j++) {
1448 PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
1449 if (tail_contains(j_lst, remain[j], candidate)) {
1450 goto skip; /* continue outer loop */
1451 }
1452 }
1453 ok = PyList_Append(acc, candidate);
1454 if (ok < 0) {
1455 PyMem_Free(remain);
1456 return -1;
1457 }
1458 for (j = 0; j < to_merge_size; j++) {
1459 PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
1460 if (remain[j] < PyList_GET_SIZE(j_lst) &&
1461 PyList_GET_ITEM(j_lst, remain[j]) == candidate) {
1462 remain[j]++;
1463 }
1464 }
1465 goto again;
1466 skip: ;
1467 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001468
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001469 if (empty_cnt == to_merge_size) {
1470 PyMem_FREE(remain);
1471 return 0;
1472 }
1473 set_mro_error(to_merge, remain);
1474 PyMem_FREE(remain);
1475 return -1;
Guido van Rossum1f121312002-11-14 19:49:16 +00001476}
1477
Tim Peters6d6c1a32001-08-02 04:15:00 +00001478static PyObject *
1479mro_implementation(PyTypeObject *type)
1480{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001481 Py_ssize_t i, n;
1482 int ok;
1483 PyObject *bases, *result;
1484 PyObject *to_merge, *bases_aslist;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001485
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001486 if (type->tp_dict == NULL) {
1487 if (PyType_Ready(type) < 0)
1488 return NULL;
1489 }
Guido van Rossum63517572002-06-18 16:44:57 +00001490
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001491 /* Find a superclass linearization that honors the constraints
1492 of the explicit lists of bases and the constraints implied by
1493 each base class.
Guido van Rossum98f33732002-11-25 21:36:54 +00001494
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001495 to_merge is a list of lists, where each list is a superclass
1496 linearization implied by a base class. The last element of
1497 to_merge is the declared list of bases.
1498 */
Guido van Rossum98f33732002-11-25 21:36:54 +00001499
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001500 bases = type->tp_bases;
1501 n = PyTuple_GET_SIZE(bases);
Guido van Rossum1f121312002-11-14 19:49:16 +00001502
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001503 to_merge = PyList_New(n+1);
1504 if (to_merge == NULL)
1505 return NULL;
Guido van Rossum1f121312002-11-14 19:49:16 +00001506
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001507 for (i = 0; i < n; i++) {
1508 PyObject *base = PyTuple_GET_ITEM(bases, i);
1509 PyObject *parentMRO;
1510 parentMRO = PySequence_List(((PyTypeObject*)base)->tp_mro);
1511 if (parentMRO == NULL) {
1512 Py_DECREF(to_merge);
1513 return NULL;
1514 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001515
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001516 PyList_SET_ITEM(to_merge, i, parentMRO);
1517 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001518
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001519 bases_aslist = PySequence_List(bases);
1520 if (bases_aslist == NULL) {
1521 Py_DECREF(to_merge);
1522 return NULL;
1523 }
1524 /* This is just a basic sanity check. */
1525 if (check_duplicates(bases_aslist) < 0) {
1526 Py_DECREF(to_merge);
1527 Py_DECREF(bases_aslist);
1528 return NULL;
1529 }
1530 PyList_SET_ITEM(to_merge, n, bases_aslist);
Guido van Rossum1f121312002-11-14 19:49:16 +00001531
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001532 result = Py_BuildValue("[O]", (PyObject *)type);
1533 if (result == NULL) {
1534 Py_DECREF(to_merge);
1535 return NULL;
1536 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001537
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001538 ok = pmerge(result, to_merge);
1539 Py_DECREF(to_merge);
1540 if (ok < 0) {
1541 Py_DECREF(result);
1542 return NULL;
1543 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001544
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001545 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001546}
1547
1548static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001549mro_external(PyObject *self)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001550{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001551 PyTypeObject *type = (PyTypeObject *)self;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001552
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001553 return mro_implementation(type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001554}
1555
1556static int
1557mro_internal(PyTypeObject *type)
1558{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001559 PyObject *mro, *result, *tuple;
1560 int checkit = 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001561
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001562 if (Py_TYPE(type) == &PyType_Type) {
1563 result = mro_implementation(type);
1564 }
1565 else {
Benjamin Petersonce798522012-01-22 11:24:29 -05001566 _Py_IDENTIFIER(mro);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001567 checkit = 1;
Benjamin Petersonce798522012-01-22 11:24:29 -05001568 mro = lookup_method((PyObject *)type, &PyId_mro);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001569 if (mro == NULL)
1570 return -1;
1571 result = PyObject_CallObject(mro, NULL);
1572 Py_DECREF(mro);
1573 }
1574 if (result == NULL)
1575 return -1;
1576 tuple = PySequence_Tuple(result);
1577 Py_DECREF(result);
1578 if (tuple == NULL)
1579 return -1;
1580 if (checkit) {
1581 Py_ssize_t i, len;
1582 PyObject *cls;
1583 PyTypeObject *solid;
Armin Rigo037d1e02005-12-29 17:07:39 +00001584
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001585 solid = solid_base(type);
Armin Rigo037d1e02005-12-29 17:07:39 +00001586
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001587 len = PyTuple_GET_SIZE(tuple);
Armin Rigo037d1e02005-12-29 17:07:39 +00001588
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001589 for (i = 0; i < len; i++) {
1590 PyTypeObject *t;
1591 cls = PyTuple_GET_ITEM(tuple, i);
1592 if (!PyType_Check(cls)) {
1593 PyErr_Format(PyExc_TypeError,
1594 "mro() returned a non-class ('%.500s')",
1595 Py_TYPE(cls)->tp_name);
1596 Py_DECREF(tuple);
1597 return -1;
1598 }
1599 t = (PyTypeObject*)cls;
1600 if (!PyType_IsSubtype(solid, solid_base(t))) {
1601 PyErr_Format(PyExc_TypeError,
1602 "mro() returned base with unsuitable layout ('%.500s')",
1603 t->tp_name);
1604 Py_DECREF(tuple);
1605 return -1;
1606 }
1607 }
1608 }
1609 type->tp_mro = tuple;
Christian Heimesa62da1d2008-01-12 19:39:10 +00001610
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001611 type_mro_modified(type, type->tp_mro);
Florent Xiclunaaa6c1d22011-12-12 18:54:29 +01001612 /* corner case: the super class might have been hidden
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001613 from the custom MRO */
1614 type_mro_modified(type, type->tp_bases);
Christian Heimesa62da1d2008-01-12 19:39:10 +00001615
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001616 PyType_Modified(type);
Christian Heimesa62da1d2008-01-12 19:39:10 +00001617
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001618 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001619}
1620
1621
1622/* Calculate the best base amongst multiple base classes.
1623 This is the first one that's on the path to the "solid base". */
1624
1625static PyTypeObject *
1626best_base(PyObject *bases)
1627{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001628 Py_ssize_t i, n;
1629 PyTypeObject *base, *winner, *candidate, *base_i;
1630 PyObject *base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001631
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001632 assert(PyTuple_Check(bases));
1633 n = PyTuple_GET_SIZE(bases);
1634 assert(n > 0);
1635 base = NULL;
1636 winner = NULL;
1637 for (i = 0; i < n; i++) {
1638 base_proto = PyTuple_GET_ITEM(bases, i);
1639 if (!PyType_Check(base_proto)) {
1640 PyErr_SetString(
1641 PyExc_TypeError,
1642 "bases must be types");
1643 return NULL;
1644 }
1645 base_i = (PyTypeObject *)base_proto;
1646 if (base_i->tp_dict == NULL) {
1647 if (PyType_Ready(base_i) < 0)
1648 return NULL;
1649 }
1650 candidate = solid_base(base_i);
1651 if (winner == NULL) {
1652 winner = candidate;
1653 base = base_i;
1654 }
1655 else if (PyType_IsSubtype(winner, candidate))
1656 ;
1657 else if (PyType_IsSubtype(candidate, winner)) {
1658 winner = candidate;
1659 base = base_i;
1660 }
1661 else {
1662 PyErr_SetString(
1663 PyExc_TypeError,
1664 "multiple bases have "
1665 "instance lay-out conflict");
1666 return NULL;
1667 }
1668 }
Florent Xiclunaaa6c1d22011-12-12 18:54:29 +01001669 assert (base != NULL);
1670
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001671 return base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001672}
1673
1674static int
1675extra_ivars(PyTypeObject *type, PyTypeObject *base)
1676{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001677 size_t t_size = type->tp_basicsize;
1678 size_t b_size = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001679
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001680 assert(t_size >= b_size); /* Else type smaller than base! */
1681 if (type->tp_itemsize || base->tp_itemsize) {
1682 /* If itemsize is involved, stricter rules */
1683 return t_size != b_size ||
1684 type->tp_itemsize != base->tp_itemsize;
1685 }
1686 if (type->tp_weaklistoffset && base->tp_weaklistoffset == 0 &&
1687 type->tp_weaklistoffset + sizeof(PyObject *) == t_size &&
1688 type->tp_flags & Py_TPFLAGS_HEAPTYPE)
1689 t_size -= sizeof(PyObject *);
1690 if (type->tp_dictoffset && base->tp_dictoffset == 0 &&
1691 type->tp_dictoffset + sizeof(PyObject *) == t_size &&
1692 type->tp_flags & Py_TPFLAGS_HEAPTYPE)
1693 t_size -= sizeof(PyObject *);
Guido van Rossum9676b222001-08-17 20:32:36 +00001694
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001695 return t_size != b_size;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001696}
1697
1698static PyTypeObject *
1699solid_base(PyTypeObject *type)
1700{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001701 PyTypeObject *base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001702
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001703 if (type->tp_base)
1704 base = solid_base(type->tp_base);
1705 else
1706 base = &PyBaseObject_Type;
1707 if (extra_ivars(type, base))
1708 return type;
1709 else
1710 return base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001711}
1712
Jeremy Hylton938ace62002-07-17 16:30:39 +00001713static void object_dealloc(PyObject *);
1714static int object_init(PyObject *, PyObject *, PyObject *);
1715static int update_slot(PyTypeObject *, PyObject *);
1716static void fixup_slot_dispatchers(PyTypeObject *);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001717
Guido van Rossum360e4b82007-05-14 22:51:27 +00001718/*
1719 * Helpers for __dict__ descriptor. We don't want to expose the dicts
1720 * inherited from various builtin types. The builtin base usually provides
1721 * its own __dict__ descriptor, so we use that when we can.
1722 */
1723static PyTypeObject *
1724get_builtin_base_with_dict(PyTypeObject *type)
1725{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001726 while (type->tp_base != NULL) {
1727 if (type->tp_dictoffset != 0 &&
1728 !(type->tp_flags & Py_TPFLAGS_HEAPTYPE))
1729 return type;
1730 type = type->tp_base;
1731 }
1732 return NULL;
Guido van Rossum360e4b82007-05-14 22:51:27 +00001733}
1734
1735static PyObject *
1736get_dict_descriptor(PyTypeObject *type)
1737{
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001738 PyObject *dict_str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001739 PyObject *descr;
Guido van Rossum360e4b82007-05-14 22:51:27 +00001740
Martin v. Löwisd10759f2011-11-07 13:00:05 +01001741 dict_str = _PyUnicode_FromId(&PyId___dict__); /* borrowed */
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001742 if (dict_str == NULL)
1743 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001744 descr = _PyType_Lookup(type, dict_str);
1745 if (descr == NULL || !PyDescr_IsData(descr))
1746 return NULL;
Guido van Rossum360e4b82007-05-14 22:51:27 +00001747
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001748 return descr;
Guido van Rossum360e4b82007-05-14 22:51:27 +00001749}
1750
1751static void
1752raise_dict_descr_error(PyObject *obj)
1753{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001754 PyErr_Format(PyExc_TypeError,
1755 "this __dict__ descriptor does not support "
1756 "'%.200s' objects", Py_TYPE(obj)->tp_name);
Guido van Rossum360e4b82007-05-14 22:51:27 +00001757}
1758
Tim Peters6d6c1a32001-08-02 04:15:00 +00001759static PyObject *
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001760subtype_dict(PyObject *obj, void *context)
1761{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001762 PyTypeObject *base;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001763
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001764 base = get_builtin_base_with_dict(Py_TYPE(obj));
1765 if (base != NULL) {
1766 descrgetfunc func;
1767 PyObject *descr = get_dict_descriptor(base);
1768 if (descr == NULL) {
1769 raise_dict_descr_error(obj);
1770 return NULL;
1771 }
1772 func = Py_TYPE(descr)->tp_descr_get;
1773 if (func == NULL) {
1774 raise_dict_descr_error(obj);
1775 return NULL;
1776 }
1777 return func(descr, obj, (PyObject *)(Py_TYPE(obj)));
1778 }
Benjamin Peterson8eb12692012-02-19 19:59:10 -05001779 return PyObject_GenericGetDict(obj, context);
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001780}
1781
Guido van Rossum6661be32001-10-26 04:26:12 +00001782static int
1783subtype_setdict(PyObject *obj, PyObject *value, void *context)
1784{
Benjamin Peterson8eb12692012-02-19 19:59:10 -05001785 PyObject *dict, **dictptr;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001786 PyTypeObject *base;
Guido van Rossum6661be32001-10-26 04:26:12 +00001787
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001788 base = get_builtin_base_with_dict(Py_TYPE(obj));
1789 if (base != NULL) {
1790 descrsetfunc func;
1791 PyObject *descr = get_dict_descriptor(base);
1792 if (descr == NULL) {
1793 raise_dict_descr_error(obj);
1794 return -1;
1795 }
1796 func = Py_TYPE(descr)->tp_descr_set;
1797 if (func == NULL) {
1798 raise_dict_descr_error(obj);
1799 return -1;
1800 }
1801 return func(descr, obj, value);
1802 }
Benjamin Peterson8eb12692012-02-19 19:59:10 -05001803 /* Almost like PyObject_GenericSetDict, but allow __dict__ to be deleted. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001804 dictptr = _PyObject_GetDictPtr(obj);
1805 if (dictptr == NULL) {
1806 PyErr_SetString(PyExc_AttributeError,
1807 "This object has no __dict__");
1808 return -1;
1809 }
Benjamin Peterson006c5a22012-02-19 20:36:12 -05001810 if (value != NULL && !PyDict_Check(value)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001811 PyErr_Format(PyExc_TypeError,
1812 "__dict__ must be set to a dictionary, "
1813 "not a '%.200s'", Py_TYPE(value)->tp_name);
1814 return -1;
1815 }
1816 dict = *dictptr;
1817 Py_XINCREF(value);
1818 *dictptr = value;
1819 Py_XDECREF(dict);
1820 return 0;
Guido van Rossum6661be32001-10-26 04:26:12 +00001821}
1822
Guido van Rossumad47da02002-08-12 19:05:44 +00001823static PyObject *
1824subtype_getweakref(PyObject *obj, void *context)
1825{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001826 PyObject **weaklistptr;
1827 PyObject *result;
Guido van Rossumad47da02002-08-12 19:05:44 +00001828
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001829 if (Py_TYPE(obj)->tp_weaklistoffset == 0) {
1830 PyErr_SetString(PyExc_AttributeError,
1831 "This object has no __weakref__");
1832 return NULL;
1833 }
1834 assert(Py_TYPE(obj)->tp_weaklistoffset > 0);
1835 assert(Py_TYPE(obj)->tp_weaklistoffset + sizeof(PyObject *) <=
1836 (size_t)(Py_TYPE(obj)->tp_basicsize));
1837 weaklistptr = (PyObject **)
1838 ((char *)obj + Py_TYPE(obj)->tp_weaklistoffset);
1839 if (*weaklistptr == NULL)
1840 result = Py_None;
1841 else
1842 result = *weaklistptr;
1843 Py_INCREF(result);
1844 return result;
Guido van Rossumad47da02002-08-12 19:05:44 +00001845}
1846
Guido van Rossum373c7412003-01-07 13:41:37 +00001847/* Three variants on the subtype_getsets list. */
1848
1849static PyGetSetDef subtype_getsets_full[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001850 {"__dict__", subtype_dict, subtype_setdict,
1851 PyDoc_STR("dictionary for instance variables (if defined)")},
1852 {"__weakref__", subtype_getweakref, NULL,
1853 PyDoc_STR("list of weak references to the object (if defined)")},
1854 {0}
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001855};
1856
Guido van Rossum373c7412003-01-07 13:41:37 +00001857static PyGetSetDef subtype_getsets_dict_only[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001858 {"__dict__", subtype_dict, subtype_setdict,
1859 PyDoc_STR("dictionary for instance variables (if defined)")},
1860 {0}
Guido van Rossum373c7412003-01-07 13:41:37 +00001861};
1862
1863static PyGetSetDef subtype_getsets_weakref_only[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001864 {"__weakref__", subtype_getweakref, NULL,
1865 PyDoc_STR("list of weak references to the object (if defined)")},
1866 {0}
Guido van Rossum373c7412003-01-07 13:41:37 +00001867};
1868
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001869static int
1870valid_identifier(PyObject *s)
1871{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001872 if (!PyUnicode_Check(s)) {
1873 PyErr_Format(PyExc_TypeError,
1874 "__slots__ items must be strings, not '%.200s'",
1875 Py_TYPE(s)->tp_name);
1876 return 0;
1877 }
1878 if (!PyUnicode_IsIdentifier(s)) {
1879 PyErr_SetString(PyExc_TypeError,
1880 "__slots__ must be identifiers");
1881 return 0;
1882 }
1883 return 1;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001884}
1885
Guido van Rossumd8faa362007-04-27 19:54:29 +00001886/* Forward */
1887static int
1888object_init(PyObject *self, PyObject *args, PyObject *kwds);
1889
1890static int
1891type_init(PyObject *cls, PyObject *args, PyObject *kwds)
1892{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001893 int res;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001894
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001895 assert(args != NULL && PyTuple_Check(args));
1896 assert(kwds == NULL || PyDict_Check(kwds));
Guido van Rossumd8faa362007-04-27 19:54:29 +00001897
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001898 if (kwds != NULL && PyDict_Check(kwds) && PyDict_Size(kwds) != 0) {
1899 PyErr_SetString(PyExc_TypeError,
1900 "type.__init__() takes no keyword arguments");
1901 return -1;
1902 }
Guido van Rossumd8faa362007-04-27 19:54:29 +00001903
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001904 if (args != NULL && PyTuple_Check(args) &&
1905 (PyTuple_GET_SIZE(args) != 1 && PyTuple_GET_SIZE(args) != 3)) {
1906 PyErr_SetString(PyExc_TypeError,
1907 "type.__init__() takes 1 or 3 arguments");
1908 return -1;
1909 }
Guido van Rossumd8faa362007-04-27 19:54:29 +00001910
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001911 /* Call object.__init__(self) now. */
1912 /* XXX Could call super(type, cls).__init__() but what's the point? */
1913 args = PyTuple_GetSlice(args, 0, 0);
1914 res = object_init(cls, args, NULL);
1915 Py_DECREF(args);
1916 return res;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001917}
1918
Martin v. Löwis738236d2011-02-05 20:35:29 +00001919long
1920PyType_GetFlags(PyTypeObject *type)
1921{
1922 return type->tp_flags;
1923}
1924
Nick Coghlande31b192011-10-23 22:04:16 +10001925/* Determine the most derived metatype. */
1926PyTypeObject *
1927_PyType_CalculateMetaclass(PyTypeObject *metatype, PyObject *bases)
1928{
1929 Py_ssize_t i, nbases;
1930 PyTypeObject *winner;
1931 PyObject *tmp;
1932 PyTypeObject *tmptype;
1933
1934 /* Determine the proper metatype to deal with this,
1935 and check for metatype conflicts while we're at it.
1936 Note that if some other metatype wins to contract,
1937 it's possible that its instances are not types. */
1938
1939 nbases = PyTuple_GET_SIZE(bases);
1940 winner = metatype;
1941 for (i = 0; i < nbases; i++) {
1942 tmp = PyTuple_GET_ITEM(bases, i);
1943 tmptype = Py_TYPE(tmp);
1944 if (PyType_IsSubtype(winner, tmptype))
1945 continue;
1946 if (PyType_IsSubtype(tmptype, winner)) {
1947 winner = tmptype;
1948 continue;
1949 }
1950 /* else: */
1951 PyErr_SetString(PyExc_TypeError,
1952 "metaclass conflict: "
1953 "the metaclass of a derived class "
1954 "must be a (non-strict) subclass "
1955 "of the metaclasses of all its bases");
1956 return NULL;
1957 }
1958 return winner;
1959}
1960
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001961static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00001962type_new(PyTypeObject *metatype, PyObject *args, PyObject *kwds)
1963{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001964 PyObject *name, *bases, *dict;
1965 static char *kwlist[] = {"name", "bases", "dict", 0};
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001966 PyObject *qualname, *slots, *tmp, *newslots;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001967 PyTypeObject *type, *base, *tmptype, *winner;
1968 PyHeapTypeObject *et;
1969 PyMemberDef *mp;
1970 Py_ssize_t i, nbases, nslots, slotoffset, add_dict, add_weak;
1971 int j, may_add_dict, may_add_weak;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001972
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001973 assert(args != NULL && PyTuple_Check(args));
1974 assert(kwds == NULL || PyDict_Check(kwds));
Tim Peters3abca122001-10-27 19:37:48 +00001975
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001976 /* Special case: type(x) should return x->ob_type */
1977 {
1978 const Py_ssize_t nargs = PyTuple_GET_SIZE(args);
1979 const Py_ssize_t nkwds = kwds == NULL ? 0 : PyDict_Size(kwds);
Tim Peters3abca122001-10-27 19:37:48 +00001980
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001981 if (PyType_CheckExact(metatype) && nargs == 1 && nkwds == 0) {
1982 PyObject *x = PyTuple_GET_ITEM(args, 0);
1983 Py_INCREF(Py_TYPE(x));
1984 return (PyObject *) Py_TYPE(x);
1985 }
Tim Peters3abca122001-10-27 19:37:48 +00001986
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001987 /* SF bug 475327 -- if that didn't trigger, we need 3
1988 arguments. but PyArg_ParseTupleAndKeywords below may give
1989 a msg saying type() needs exactly 3. */
1990 if (nargs + nkwds != 3) {
1991 PyErr_SetString(PyExc_TypeError,
1992 "type() takes 1 or 3 arguments");
1993 return NULL;
1994 }
1995 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001996
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001997 /* Check arguments: (name, bases, dict) */
1998 if (!PyArg_ParseTupleAndKeywords(args, kwds, "UO!O!:type", kwlist,
1999 &name,
2000 &PyTuple_Type, &bases,
2001 &PyDict_Type, &dict))
2002 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002003
Nick Coghlande31b192011-10-23 22:04:16 +10002004 /* Determine the proper metatype to deal with this: */
2005 winner = _PyType_CalculateMetaclass(metatype, bases);
2006 if (winner == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002007 return NULL;
2008 }
Nick Coghlande31b192011-10-23 22:04:16 +10002009
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002010 if (winner != metatype) {
2011 if (winner->tp_new != type_new) /* Pass it to the winner */
2012 return winner->tp_new(winner, args, kwds);
2013 metatype = winner;
2014 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002015
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002016 /* Adjust for empty tuple bases */
Nick Coghlande31b192011-10-23 22:04:16 +10002017 nbases = PyTuple_GET_SIZE(bases);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002018 if (nbases == 0) {
2019 bases = PyTuple_Pack(1, &PyBaseObject_Type);
2020 if (bases == NULL)
2021 return NULL;
2022 nbases = 1;
2023 }
2024 else
2025 Py_INCREF(bases);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002026
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002027 /* XXX From here until type is allocated, "return NULL" leaks bases! */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002028
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002029 /* Calculate best base, and check that all bases are type objects */
2030 base = best_base(bases);
2031 if (base == NULL) {
2032 Py_DECREF(bases);
2033 return NULL;
2034 }
2035 if (!PyType_HasFeature(base, Py_TPFLAGS_BASETYPE)) {
2036 PyErr_Format(PyExc_TypeError,
2037 "type '%.100s' is not an acceptable base type",
2038 base->tp_name);
2039 Py_DECREF(bases);
2040 return NULL;
2041 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002042
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002043 /* Check for a __qualname__ variable in dict */
2044 qualname = PyDict_GetItemString(dict, "__qualname__");
2045 if (qualname == NULL) {
2046 qualname = name;
2047 }
2048 else {
2049 if (PyDict_DelItemString(dict, "__qualname__") < 0) {
2050 Py_DECREF(bases);
2051 return NULL;
2052 }
2053 }
2054
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002055 /* Check for a __slots__ sequence variable in dict, and count it */
2056 slots = PyDict_GetItemString(dict, "__slots__");
2057 nslots = 0;
2058 add_dict = 0;
2059 add_weak = 0;
2060 may_add_dict = base->tp_dictoffset == 0;
2061 may_add_weak = base->tp_weaklistoffset == 0 && base->tp_itemsize == 0;
2062 if (slots == NULL) {
2063 if (may_add_dict) {
2064 add_dict++;
2065 }
2066 if (may_add_weak) {
2067 add_weak++;
2068 }
2069 }
2070 else {
2071 /* Have slots */
Guido van Rossumad47da02002-08-12 19:05:44 +00002072
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002073 /* Make it into a tuple */
2074 if (PyUnicode_Check(slots))
2075 slots = PyTuple_Pack(1, slots);
2076 else
2077 slots = PySequence_Tuple(slots);
2078 if (slots == NULL) {
2079 Py_DECREF(bases);
2080 return NULL;
2081 }
2082 assert(PyTuple_Check(slots));
Guido van Rossumad47da02002-08-12 19:05:44 +00002083
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002084 /* Are slots allowed? */
2085 nslots = PyTuple_GET_SIZE(slots);
2086 if (nslots > 0 && base->tp_itemsize != 0) {
2087 PyErr_Format(PyExc_TypeError,
2088 "nonempty __slots__ "
2089 "not supported for subtype of '%s'",
2090 base->tp_name);
2091 bad_slots:
2092 Py_DECREF(bases);
2093 Py_DECREF(slots);
2094 return NULL;
2095 }
Guido van Rossumad47da02002-08-12 19:05:44 +00002096
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002097 /* Check for valid slot names and two special cases */
2098 for (i = 0; i < nslots; i++) {
2099 PyObject *tmp = PyTuple_GET_ITEM(slots, i);
2100 if (!valid_identifier(tmp))
2101 goto bad_slots;
2102 assert(PyUnicode_Check(tmp));
2103 if (PyUnicode_CompareWithASCIIString(tmp, "__dict__") == 0) {
2104 if (!may_add_dict || add_dict) {
2105 PyErr_SetString(PyExc_TypeError,
2106 "__dict__ slot disallowed: "
2107 "we already got one");
2108 goto bad_slots;
2109 }
2110 add_dict++;
2111 }
2112 if (PyUnicode_CompareWithASCIIString(tmp, "__weakref__") == 0) {
2113 if (!may_add_weak || add_weak) {
2114 PyErr_SetString(PyExc_TypeError,
2115 "__weakref__ slot disallowed: "
2116 "either we already got one, "
2117 "or __itemsize__ != 0");
2118 goto bad_slots;
2119 }
2120 add_weak++;
2121 }
2122 }
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00002123
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002124 /* Copy slots into a list, mangle names and sort them.
2125 Sorted names are needed for __class__ assignment.
2126 Convert them back to tuple at the end.
2127 */
2128 newslots = PyList_New(nslots - add_dict - add_weak);
2129 if (newslots == NULL)
2130 goto bad_slots;
2131 for (i = j = 0; i < nslots; i++) {
2132 tmp = PyTuple_GET_ITEM(slots, i);
2133 if ((add_dict &&
2134 PyUnicode_CompareWithASCIIString(tmp, "__dict__") == 0) ||
2135 (add_weak &&
2136 PyUnicode_CompareWithASCIIString(tmp, "__weakref__") == 0))
2137 continue;
2138 tmp =_Py_Mangle(name, tmp);
Benjamin Petersonae13c882011-08-16 22:26:48 -05002139 if (!tmp) {
2140 Py_DECREF(newslots);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002141 goto bad_slots;
Benjamin Petersonae13c882011-08-16 22:26:48 -05002142 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002143 PyList_SET_ITEM(newslots, j, tmp);
Benjamin Petersonc4085c82011-08-16 18:53:26 -05002144 if (PyDict_GetItem(dict, tmp)) {
2145 PyErr_Format(PyExc_ValueError,
2146 "%R in __slots__ conflicts with class variable",
2147 tmp);
Benjamin Petersond17cefc2011-08-16 22:28:23 -05002148 Py_DECREF(newslots);
Benjamin Petersonc4085c82011-08-16 18:53:26 -05002149 goto bad_slots;
2150 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002151 j++;
2152 }
2153 assert(j == nslots - add_dict - add_weak);
2154 nslots = j;
2155 Py_DECREF(slots);
2156 if (PyList_Sort(newslots) == -1) {
2157 Py_DECREF(bases);
2158 Py_DECREF(newslots);
2159 return NULL;
2160 }
2161 slots = PyList_AsTuple(newslots);
2162 Py_DECREF(newslots);
2163 if (slots == NULL) {
2164 Py_DECREF(bases);
2165 return NULL;
2166 }
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00002167
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002168 /* Secondary bases may provide weakrefs or dict */
2169 if (nbases > 1 &&
2170 ((may_add_dict && !add_dict) ||
2171 (may_add_weak && !add_weak))) {
2172 for (i = 0; i < nbases; i++) {
2173 tmp = PyTuple_GET_ITEM(bases, i);
2174 if (tmp == (PyObject *)base)
2175 continue; /* Skip primary base */
2176 assert(PyType_Check(tmp));
2177 tmptype = (PyTypeObject *)tmp;
2178 if (may_add_dict && !add_dict &&
2179 tmptype->tp_dictoffset != 0)
2180 add_dict++;
2181 if (may_add_weak && !add_weak &&
2182 tmptype->tp_weaklistoffset != 0)
2183 add_weak++;
2184 if (may_add_dict && !add_dict)
2185 continue;
2186 if (may_add_weak && !add_weak)
2187 continue;
2188 /* Nothing more to check */
2189 break;
2190 }
2191 }
2192 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002193
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002194 /* XXX From here until type is safely allocated,
2195 "return NULL" may leak slots! */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002196
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002197 /* Allocate the type object */
2198 type = (PyTypeObject *)metatype->tp_alloc(metatype, nslots);
2199 if (type == NULL) {
2200 Py_XDECREF(slots);
2201 Py_DECREF(bases);
2202 return NULL;
2203 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002204
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002205 /* Keep name and slots alive in the extended type object */
2206 et = (PyHeapTypeObject *)type;
2207 Py_INCREF(name);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002208 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002209 et->ht_name = name;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002210 et->ht_qualname = qualname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002211 et->ht_slots = slots;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002212
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002213 /* Initialize tp_flags */
2214 type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE |
2215 Py_TPFLAGS_BASETYPE;
2216 if (base->tp_flags & Py_TPFLAGS_HAVE_GC)
2217 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossumdc91b992001-08-08 22:26:22 +00002218
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002219 /* Initialize essential fields */
2220 type->tp_as_number = &et->as_number;
2221 type->tp_as_sequence = &et->as_sequence;
2222 type->tp_as_mapping = &et->as_mapping;
2223 type->tp_as_buffer = &et->as_buffer;
2224 type->tp_name = _PyUnicode_AsString(name);
2225 if (!type->tp_name) {
2226 Py_DECREF(type);
2227 return NULL;
2228 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002229
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002230 /* Set tp_base and tp_bases */
2231 type->tp_bases = bases;
2232 Py_INCREF(base);
2233 type->tp_base = base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002234
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002235 /* Initialize tp_dict from passed-in dict */
2236 type->tp_dict = dict = PyDict_Copy(dict);
2237 if (dict == NULL) {
2238 Py_DECREF(type);
2239 return NULL;
2240 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002241
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002242 /* Set __module__ in the dict */
2243 if (PyDict_GetItemString(dict, "__module__") == NULL) {
2244 tmp = PyEval_GetGlobals();
2245 if (tmp != NULL) {
2246 tmp = PyDict_GetItemString(tmp, "__name__");
2247 if (tmp != NULL) {
2248 if (PyDict_SetItemString(dict, "__module__",
2249 tmp) < 0)
2250 return NULL;
2251 }
2252 }
2253 }
Guido van Rossumc3542212001-08-16 09:18:56 +00002254
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002255 /* Set tp_doc to a copy of dict['__doc__'], if the latter is there
2256 and is a string. The __doc__ accessor will first look for tp_doc;
2257 if that fails, it will still look into __dict__.
2258 */
2259 {
2260 PyObject *doc = PyDict_GetItemString(dict, "__doc__");
2261 if (doc != NULL && PyUnicode_Check(doc)) {
2262 Py_ssize_t len;
2263 char *doc_str;
2264 char *tp_doc;
Alexandre Vassalottia85998a2008-05-03 18:24:43 +00002265
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002266 doc_str = _PyUnicode_AsString(doc);
2267 if (doc_str == NULL) {
2268 Py_DECREF(type);
2269 return NULL;
2270 }
2271 /* Silently truncate the docstring if it contains null bytes. */
2272 len = strlen(doc_str);
2273 tp_doc = (char *)PyObject_MALLOC(len + 1);
2274 if (tp_doc == NULL) {
2275 Py_DECREF(type);
2276 return NULL;
2277 }
2278 memcpy(tp_doc, doc_str, len + 1);
2279 type->tp_doc = tp_doc;
2280 }
2281 }
Tim Peters2f93e282001-10-04 05:27:00 +00002282
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002283 /* Special-case __new__: if it's a plain function,
2284 make it a static function */
2285 tmp = PyDict_GetItemString(dict, "__new__");
2286 if (tmp != NULL && PyFunction_Check(tmp)) {
2287 tmp = PyStaticMethod_New(tmp);
2288 if (tmp == NULL) {
2289 Py_DECREF(type);
2290 return NULL;
2291 }
2292 PyDict_SetItemString(dict, "__new__", tmp);
2293 Py_DECREF(tmp);
2294 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002295
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002296 /* Add descriptors for custom slots from __slots__, or for __dict__ */
2297 mp = PyHeapType_GET_MEMBERS(et);
2298 slotoffset = base->tp_basicsize;
2299 if (slots != NULL) {
2300 for (i = 0; i < nslots; i++, mp++) {
2301 mp->name = _PyUnicode_AsString(
2302 PyTuple_GET_ITEM(slots, i));
Victor Stinnere5f99f32010-05-19 01:42:46 +00002303 if (mp->name == NULL) {
2304 Py_DECREF(type);
2305 return NULL;
2306 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002307 mp->type = T_OBJECT_EX;
2308 mp->offset = slotoffset;
Guido van Rossumd8faa362007-04-27 19:54:29 +00002309
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002310 /* __dict__ and __weakref__ are already filtered out */
2311 assert(strcmp(mp->name, "__dict__") != 0);
2312 assert(strcmp(mp->name, "__weakref__") != 0);
Guido van Rossumd8faa362007-04-27 19:54:29 +00002313
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002314 slotoffset += sizeof(PyObject *);
2315 }
2316 }
2317 if (add_dict) {
2318 if (base->tp_itemsize)
2319 type->tp_dictoffset = -(long)sizeof(PyObject *);
2320 else
2321 type->tp_dictoffset = slotoffset;
2322 slotoffset += sizeof(PyObject *);
2323 }
2324 if (add_weak) {
2325 assert(!base->tp_itemsize);
2326 type->tp_weaklistoffset = slotoffset;
2327 slotoffset += sizeof(PyObject *);
2328 }
2329 type->tp_basicsize = slotoffset;
2330 type->tp_itemsize = base->tp_itemsize;
2331 type->tp_members = PyHeapType_GET_MEMBERS(et);
Guido van Rossum373c7412003-01-07 13:41:37 +00002332
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002333 if (type->tp_weaklistoffset && type->tp_dictoffset)
2334 type->tp_getset = subtype_getsets_full;
2335 else if (type->tp_weaklistoffset && !type->tp_dictoffset)
2336 type->tp_getset = subtype_getsets_weakref_only;
2337 else if (!type->tp_weaklistoffset && type->tp_dictoffset)
2338 type->tp_getset = subtype_getsets_dict_only;
2339 else
2340 type->tp_getset = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002341
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002342 /* Special case some slots */
2343 if (type->tp_dictoffset != 0 || nslots > 0) {
2344 if (base->tp_getattr == NULL && base->tp_getattro == NULL)
2345 type->tp_getattro = PyObject_GenericGetAttr;
2346 if (base->tp_setattr == NULL && base->tp_setattro == NULL)
2347 type->tp_setattro = PyObject_GenericSetAttr;
2348 }
2349 type->tp_dealloc = subtype_dealloc;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002350
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002351 /* Enable GC unless there are really no instance variables possible */
2352 if (!(type->tp_basicsize == sizeof(PyObject) &&
2353 type->tp_itemsize == 0))
2354 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossum9475a232001-10-05 20:51:39 +00002355
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002356 /* Always override allocation strategy to use regular heap */
2357 type->tp_alloc = PyType_GenericAlloc;
2358 if (type->tp_flags & Py_TPFLAGS_HAVE_GC) {
2359 type->tp_free = PyObject_GC_Del;
2360 type->tp_traverse = subtype_traverse;
2361 type->tp_clear = subtype_clear;
2362 }
2363 else
2364 type->tp_free = PyObject_Del;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002365
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002366 /* Initialize the rest */
2367 if (PyType_Ready(type) < 0) {
2368 Py_DECREF(type);
2369 return NULL;
2370 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002371
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002372 /* Put the proper slots in place */
2373 fixup_slot_dispatchers(type);
Guido van Rossumf040ede2001-08-07 16:40:56 +00002374
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002375 return (PyObject *)type;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002376}
2377
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002378static short slotoffsets[] = {
2379 -1, /* invalid slot */
2380#include "typeslots.inc"
2381};
2382
Benjamin Petersone28108c2012-01-29 20:13:18 -05002383PyObject *
2384PyType_FromSpec(PyType_Spec *spec)
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002385{
2386 PyHeapTypeObject *res = (PyHeapTypeObject*)PyType_GenericAlloc(&PyType_Type, 0);
2387 char *res_start = (char*)res;
2388 PyType_Slot *slot;
2389
Martin v. Löwis5e06a5d2011-02-21 16:24:00 +00002390 if (res == NULL)
2391 return NULL;
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002392 res->ht_name = PyUnicode_FromString(spec->name);
2393 if (!res->ht_name)
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002394 goto fail;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002395 res->ht_qualname = res->ht_name;
2396 Py_INCREF(res->ht_qualname);
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002397 res->ht_type.tp_name = _PyUnicode_AsString(res->ht_name);
2398 if (!res->ht_type.tp_name)
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002399 goto fail;
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002400
2401 res->ht_type.tp_basicsize = spec->basicsize;
2402 res->ht_type.tp_itemsize = spec->itemsize;
2403 res->ht_type.tp_flags = spec->flags | Py_TPFLAGS_HEAPTYPE;
Victor Stinner0fcab4a2011-01-04 12:59:15 +00002404
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002405 for (slot = spec->slots; slot->slot; slot++) {
Victor Stinner63941882011-09-29 00:42:28 +02002406 if (slot->slot >= Py_ARRAY_LENGTH(slotoffsets)) {
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002407 PyErr_SetString(PyExc_RuntimeError, "invalid slot offset");
2408 goto fail;
2409 }
2410 *(void**)(res_start + slotoffsets[slot->slot]) = slot->pfunc;
Georg Brandl032400b2011-02-19 21:47:02 +00002411
2412 /* need to make a copy of the docstring slot, which usually
2413 points to a static string literal */
2414 if (slot->slot == Py_tp_doc) {
2415 ssize_t len = strlen(slot->pfunc)+1;
2416 char *tp_doc = PyObject_MALLOC(len);
2417 if (tp_doc == NULL)
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002418 goto fail;
Georg Brandl032400b2011-02-19 21:47:02 +00002419 memcpy(tp_doc, slot->pfunc, len);
2420 res->ht_type.tp_doc = tp_doc;
2421 }
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002422 }
2423
Benjamin Peterson2652d252012-01-29 20:16:37 -05002424 if (PyType_Ready(&res->ht_type) < 0)
2425 goto fail;
2426
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002427 return (PyObject*)res;
Victor Stinner0fcab4a2011-01-04 12:59:15 +00002428
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002429 fail:
2430 Py_DECREF(res);
2431 return NULL;
2432}
2433
2434
Tim Peters6d6c1a32001-08-02 04:15:00 +00002435/* Internal API to look for a name through the MRO.
2436 This returns a borrowed reference, and doesn't set an exception! */
2437PyObject *
2438_PyType_Lookup(PyTypeObject *type, PyObject *name)
2439{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002440 Py_ssize_t i, n;
2441 PyObject *mro, *res, *base, *dict;
2442 unsigned int h;
Christian Heimesa62da1d2008-01-12 19:39:10 +00002443
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002444 if (MCACHE_CACHEABLE_NAME(name) &&
2445 PyType_HasFeature(type, Py_TPFLAGS_VALID_VERSION_TAG)) {
2446 /* fast path */
2447 h = MCACHE_HASH_METHOD(type, name);
2448 if (method_cache[h].version == type->tp_version_tag &&
2449 method_cache[h].name == name)
2450 return method_cache[h].value;
2451 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002452
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002453 /* Look in tp_dict of types in MRO */
2454 mro = type->tp_mro;
Guido van Rossum23094982002-06-10 14:30:43 +00002455
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002456 /* If mro is NULL, the type is either not yet initialized
2457 by PyType_Ready(), or already cleared by type_clear().
2458 Either way the safest thing to do is to return NULL. */
2459 if (mro == NULL)
2460 return NULL;
Guido van Rossum23094982002-06-10 14:30:43 +00002461
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002462 res = NULL;
2463 assert(PyTuple_Check(mro));
2464 n = PyTuple_GET_SIZE(mro);
2465 for (i = 0; i < n; i++) {
2466 base = PyTuple_GET_ITEM(mro, i);
2467 assert(PyType_Check(base));
2468 dict = ((PyTypeObject *)base)->tp_dict;
2469 assert(dict && PyDict_Check(dict));
2470 res = PyDict_GetItem(dict, name);
2471 if (res != NULL)
2472 break;
2473 }
Christian Heimesa62da1d2008-01-12 19:39:10 +00002474
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002475 if (MCACHE_CACHEABLE_NAME(name) && assign_version_tag(type)) {
2476 h = MCACHE_HASH_METHOD(type, name);
2477 method_cache[h].version = type->tp_version_tag;
2478 method_cache[h].value = res; /* borrowed */
2479 Py_INCREF(name);
2480 Py_DECREF(method_cache[h].name);
2481 method_cache[h].name = name;
2482 }
2483 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002484}
2485
2486/* This is similar to PyObject_GenericGetAttr(),
2487 but uses _PyType_Lookup() instead of just looking in type->tp_dict. */
2488static PyObject *
2489type_getattro(PyTypeObject *type, PyObject *name)
2490{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002491 PyTypeObject *metatype = Py_TYPE(type);
2492 PyObject *meta_attribute, *attribute;
2493 descrgetfunc meta_get;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002494
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002495 /* Initialize this type (we'll assume the metatype is initialized) */
2496 if (type->tp_dict == NULL) {
2497 if (PyType_Ready(type) < 0)
2498 return NULL;
2499 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002500
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002501 /* No readable descriptor found yet */
2502 meta_get = NULL;
Tim Peters34592512002-07-11 06:23:50 +00002503
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002504 /* Look for the attribute in the metatype */
2505 meta_attribute = _PyType_Lookup(metatype, name);
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002506
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002507 if (meta_attribute != NULL) {
2508 meta_get = Py_TYPE(meta_attribute)->tp_descr_get;
Tim Peters34592512002-07-11 06:23:50 +00002509
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002510 if (meta_get != NULL && PyDescr_IsData(meta_attribute)) {
2511 /* Data descriptors implement tp_descr_set to intercept
2512 * writes. Assume the attribute is not overridden in
2513 * type's tp_dict (and bases): call the descriptor now.
2514 */
2515 return meta_get(meta_attribute, (PyObject *)type,
2516 (PyObject *)metatype);
2517 }
2518 Py_INCREF(meta_attribute);
2519 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002520
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002521 /* No data descriptor found on metatype. Look in tp_dict of this
2522 * type and its bases */
2523 attribute = _PyType_Lookup(type, name);
2524 if (attribute != NULL) {
2525 /* Implement descriptor functionality, if any */
2526 descrgetfunc local_get = Py_TYPE(attribute)->tp_descr_get;
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00002527
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002528 Py_XDECREF(meta_attribute);
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00002529
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002530 if (local_get != NULL) {
2531 /* NULL 2nd argument indicates the descriptor was
2532 * found on the target object itself (or a base) */
2533 return local_get(attribute, (PyObject *)NULL,
2534 (PyObject *)type);
2535 }
Tim Peters34592512002-07-11 06:23:50 +00002536
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002537 Py_INCREF(attribute);
2538 return attribute;
2539 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002540
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002541 /* No attribute found in local __dict__ (or bases): use the
2542 * descriptor from the metatype, if any */
2543 if (meta_get != NULL) {
2544 PyObject *res;
2545 res = meta_get(meta_attribute, (PyObject *)type,
2546 (PyObject *)metatype);
2547 Py_DECREF(meta_attribute);
2548 return res;
2549 }
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002550
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002551 /* If an ordinary attribute was found on the metatype, return it now */
2552 if (meta_attribute != NULL) {
2553 return meta_attribute;
2554 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002555
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002556 /* Give up */
2557 PyErr_Format(PyExc_AttributeError,
2558 "type object '%.50s' has no attribute '%U'",
2559 type->tp_name, name);
2560 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002561}
2562
2563static int
2564type_setattro(PyTypeObject *type, PyObject *name, PyObject *value)
2565{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002566 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
2567 PyErr_Format(
2568 PyExc_TypeError,
2569 "can't set attributes of built-in/extension type '%s'",
2570 type->tp_name);
2571 return -1;
2572 }
2573 if (PyObject_GenericSetAttr((PyObject *)type, name, value) < 0)
2574 return -1;
2575 return update_slot(type, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002576}
2577
2578static void
2579type_dealloc(PyTypeObject *type)
2580{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002581 PyHeapTypeObject *et;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002582
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002583 /* Assert this is a heap-allocated type object */
2584 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
2585 _PyObject_GC_UNTRACK(type);
2586 PyObject_ClearWeakRefs((PyObject *)type);
2587 et = (PyHeapTypeObject *)type;
2588 Py_XDECREF(type->tp_base);
2589 Py_XDECREF(type->tp_dict);
2590 Py_XDECREF(type->tp_bases);
2591 Py_XDECREF(type->tp_mro);
2592 Py_XDECREF(type->tp_cache);
2593 Py_XDECREF(type->tp_subclasses);
2594 /* A type's tp_doc is heap allocated, unlike the tp_doc slots
2595 * of most other objects. It's okay to cast it to char *.
2596 */
2597 PyObject_Free((char *)type->tp_doc);
2598 Py_XDECREF(et->ht_name);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002599 Py_XDECREF(et->ht_qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002600 Py_XDECREF(et->ht_slots);
2601 Py_TYPE(type)->tp_free((PyObject *)type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002602}
2603
Guido van Rossum1c450732001-10-08 15:18:27 +00002604static PyObject *
2605type_subclasses(PyTypeObject *type, PyObject *args_ignored)
2606{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002607 PyObject *list, *raw, *ref;
2608 Py_ssize_t i, n;
Guido van Rossum1c450732001-10-08 15:18:27 +00002609
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002610 list = PyList_New(0);
2611 if (list == NULL)
2612 return NULL;
2613 raw = type->tp_subclasses;
2614 if (raw == NULL)
2615 return list;
2616 assert(PyList_Check(raw));
2617 n = PyList_GET_SIZE(raw);
2618 for (i = 0; i < n; i++) {
2619 ref = PyList_GET_ITEM(raw, i);
2620 assert(PyWeakref_CheckRef(ref));
2621 ref = PyWeakref_GET_OBJECT(ref);
2622 if (ref != Py_None) {
2623 if (PyList_Append(list, ref) < 0) {
2624 Py_DECREF(list);
2625 return NULL;
2626 }
2627 }
2628 }
2629 return list;
Guido van Rossum1c450732001-10-08 15:18:27 +00002630}
2631
Guido van Rossum47374822007-08-02 16:48:17 +00002632static PyObject *
2633type_prepare(PyObject *self, PyObject *args, PyObject *kwds)
2634{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002635 return PyDict_New();
Guido van Rossum47374822007-08-02 16:48:17 +00002636}
2637
Victor Stinner63941882011-09-29 00:42:28 +02002638/*
Benjamin Peterson82b00c12011-05-24 11:09:06 -05002639 Merge the __dict__ of aclass into dict, and recursively also all
2640 the __dict__s of aclass's base classes. The order of merging isn't
2641 defined, as it's expected that only the final set of dict keys is
2642 interesting.
2643 Return 0 on success, -1 on error.
2644*/
2645
2646static int
2647merge_class_dict(PyObject *dict, PyObject *aclass)
2648{
2649 PyObject *classdict;
2650 PyObject *bases;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02002651 _Py_IDENTIFIER(__bases__);
Benjamin Peterson82b00c12011-05-24 11:09:06 -05002652
2653 assert(PyDict_Check(dict));
2654 assert(aclass);
2655
2656 /* Merge in the type's dict (if any). */
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002657 classdict = _PyObject_GetAttrId(aclass, &PyId___dict__);
Benjamin Peterson82b00c12011-05-24 11:09:06 -05002658 if (classdict == NULL)
2659 PyErr_Clear();
2660 else {
2661 int status = PyDict_Update(dict, classdict);
2662 Py_DECREF(classdict);
2663 if (status < 0)
2664 return -1;
2665 }
2666
2667 /* Recursively merge in the base types' (if any) dicts. */
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002668 bases = _PyObject_GetAttrId(aclass, &PyId___bases__);
Benjamin Peterson82b00c12011-05-24 11:09:06 -05002669 if (bases == NULL)
2670 PyErr_Clear();
2671 else {
2672 /* We have no guarantee that bases is a real tuple */
2673 Py_ssize_t i, n;
2674 n = PySequence_Size(bases); /* This better be right */
2675 if (n < 0)
2676 PyErr_Clear();
2677 else {
2678 for (i = 0; i < n; i++) {
2679 int status;
2680 PyObject *base = PySequence_GetItem(bases, i);
2681 if (base == NULL) {
2682 Py_DECREF(bases);
2683 return -1;
2684 }
2685 status = merge_class_dict(dict, base);
2686 Py_DECREF(base);
2687 if (status < 0) {
2688 Py_DECREF(bases);
2689 return -1;
2690 }
2691 }
2692 }
2693 Py_DECREF(bases);
2694 }
2695 return 0;
2696}
2697
2698/* __dir__ for type objects: returns __dict__ and __bases__.
2699 We deliberately don't suck up its __class__, as methods belonging to the
2700 metaclass would probably be more confusing than helpful.
2701*/
2702static PyObject *
2703type_dir(PyObject *self, PyObject *args)
2704{
2705 PyObject *result = NULL;
2706 PyObject *dict = PyDict_New();
2707
2708 if (dict != NULL && merge_class_dict(dict, self) == 0)
2709 result = PyDict_Keys(dict);
2710
2711 Py_XDECREF(dict);
2712 return result;
2713}
2714
Tim Peters6d6c1a32001-08-02 04:15:00 +00002715static PyMethodDef type_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002716 {"mro", (PyCFunction)mro_external, METH_NOARGS,
2717 PyDoc_STR("mro() -> list\nreturn a type's method resolution order")},
2718 {"__subclasses__", (PyCFunction)type_subclasses, METH_NOARGS,
2719 PyDoc_STR("__subclasses__() -> list of immediate subclasses")},
2720 {"__prepare__", (PyCFunction)type_prepare,
2721 METH_VARARGS | METH_KEYWORDS | METH_CLASS,
2722 PyDoc_STR("__prepare__() -> dict\n"
2723 "used to create the namespace for the class statement")},
2724 {"__instancecheck__", type___instancecheck__, METH_O,
Benjamin Petersonfbe56bb2011-05-24 12:42:51 -05002725 PyDoc_STR("__instancecheck__() -> bool\ncheck if an object is an instance")},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002726 {"__subclasscheck__", type___subclasscheck__, METH_O,
Benjamin Petersonfbe56bb2011-05-24 12:42:51 -05002727 PyDoc_STR("__subclasscheck__() -> bool\ncheck if a class is a subclass")},
Benjamin Peterson82b00c12011-05-24 11:09:06 -05002728 {"__dir__", type_dir, METH_NOARGS,
Benjamin Petersonc7284122011-05-24 12:46:15 -05002729 PyDoc_STR("__dir__() -> list\nspecialized __dir__ implementation for types")},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002730 {0}
Tim Peters6d6c1a32001-08-02 04:15:00 +00002731};
2732
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002733PyDoc_STRVAR(type_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00002734"type(object) -> the object's type\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002735"type(name, bases, dict) -> a new type");
Tim Peters6d6c1a32001-08-02 04:15:00 +00002736
Guido van Rossum048eb752001-10-02 21:24:57 +00002737static int
2738type_traverse(PyTypeObject *type, visitproc visit, void *arg)
2739{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002740 /* Because of type_is_gc(), the collector only calls this
2741 for heaptypes. */
2742 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002743
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002744 Py_VISIT(type->tp_dict);
2745 Py_VISIT(type->tp_cache);
2746 Py_VISIT(type->tp_mro);
2747 Py_VISIT(type->tp_bases);
2748 Py_VISIT(type->tp_base);
Guido van Rossuma3862092002-06-10 15:24:42 +00002749
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002750 /* There's no need to visit type->tp_subclasses or
2751 ((PyHeapTypeObject *)type)->ht_slots, because they can't be involved
2752 in cycles; tp_subclasses is a list of weak references,
2753 and slots is a tuple of strings. */
Guido van Rossum048eb752001-10-02 21:24:57 +00002754
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002755 return 0;
Guido van Rossum048eb752001-10-02 21:24:57 +00002756}
2757
2758static int
2759type_clear(PyTypeObject *type)
2760{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002761 /* Because of type_is_gc(), the collector only calls this
2762 for heaptypes. */
2763 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002764
Antoine Pitrou2e872082011-12-15 14:15:31 +01002765 /* We need to invalidate the method cache carefully before clearing
2766 the dict, so that other objects caught in a reference cycle
2767 don't start calling destroyed methods.
2768
2769 Otherwise, the only field we need to clear is tp_mro, which is
2770 part of a hard cycle (its first element is the class itself) that
2771 won't be broken otherwise (it's a tuple and tuples don't have a
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002772 tp_clear handler). None of the other fields need to be
2773 cleared, and here's why:
Guido van Rossum048eb752001-10-02 21:24:57 +00002774
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002775 tp_cache:
2776 Not used; if it were, it would be a dict.
Guido van Rossuma3862092002-06-10 15:24:42 +00002777
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002778 tp_bases, tp_base:
2779 If these are involved in a cycle, there must be at least
2780 one other, mutable object in the cycle, e.g. a base
2781 class's dict; the cycle will be broken that way.
Guido van Rossuma3862092002-06-10 15:24:42 +00002782
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002783 tp_subclasses:
2784 A list of weak references can't be part of a cycle; and
2785 lists have their own tp_clear.
Guido van Rossuma3862092002-06-10 15:24:42 +00002786
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002787 slots (in PyHeapTypeObject):
2788 A tuple of strings can't be part of a cycle.
2789 */
Guido van Rossuma3862092002-06-10 15:24:42 +00002790
Antoine Pitrou2e872082011-12-15 14:15:31 +01002791 PyType_Modified(type);
2792 if (type->tp_dict)
2793 PyDict_Clear(type->tp_dict);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002794 Py_CLEAR(type->tp_mro);
Guido van Rossum048eb752001-10-02 21:24:57 +00002795
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002796 return 0;
Guido van Rossum048eb752001-10-02 21:24:57 +00002797}
2798
2799static int
2800type_is_gc(PyTypeObject *type)
2801{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002802 return type->tp_flags & Py_TPFLAGS_HEAPTYPE;
Guido van Rossum048eb752001-10-02 21:24:57 +00002803}
2804
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002805PyTypeObject PyType_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002806 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2807 "type", /* tp_name */
2808 sizeof(PyHeapTypeObject), /* tp_basicsize */
2809 sizeof(PyMemberDef), /* tp_itemsize */
2810 (destructor)type_dealloc, /* tp_dealloc */
2811 0, /* tp_print */
2812 0, /* tp_getattr */
2813 0, /* tp_setattr */
2814 0, /* tp_reserved */
2815 (reprfunc)type_repr, /* tp_repr */
2816 0, /* tp_as_number */
2817 0, /* tp_as_sequence */
2818 0, /* tp_as_mapping */
2819 0, /* tp_hash */
2820 (ternaryfunc)type_call, /* tp_call */
2821 0, /* tp_str */
2822 (getattrofunc)type_getattro, /* tp_getattro */
2823 (setattrofunc)type_setattro, /* tp_setattro */
2824 0, /* tp_as_buffer */
2825 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
2826 Py_TPFLAGS_BASETYPE | Py_TPFLAGS_TYPE_SUBCLASS, /* tp_flags */
2827 type_doc, /* tp_doc */
2828 (traverseproc)type_traverse, /* tp_traverse */
2829 (inquiry)type_clear, /* tp_clear */
2830 0, /* tp_richcompare */
2831 offsetof(PyTypeObject, tp_weaklist), /* tp_weaklistoffset */
2832 0, /* tp_iter */
2833 0, /* tp_iternext */
2834 type_methods, /* tp_methods */
2835 type_members, /* tp_members */
2836 type_getsets, /* tp_getset */
2837 0, /* tp_base */
2838 0, /* tp_dict */
2839 0, /* tp_descr_get */
2840 0, /* tp_descr_set */
2841 offsetof(PyTypeObject, tp_dict), /* tp_dictoffset */
2842 type_init, /* tp_init */
2843 0, /* tp_alloc */
2844 type_new, /* tp_new */
2845 PyObject_GC_Del, /* tp_free */
2846 (inquiry)type_is_gc, /* tp_is_gc */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002847};
Tim Peters6d6c1a32001-08-02 04:15:00 +00002848
2849
2850/* The base type of all types (eventually)... except itself. */
2851
Guido van Rossumd8faa362007-04-27 19:54:29 +00002852/* You may wonder why object.__new__() only complains about arguments
2853 when object.__init__() is not overridden, and vice versa.
2854
2855 Consider the use cases:
2856
2857 1. When neither is overridden, we want to hear complaints about
2858 excess (i.e., any) arguments, since their presence could
2859 indicate there's a bug.
2860
2861 2. When defining an Immutable type, we are likely to override only
2862 __new__(), since __init__() is called too late to initialize an
2863 Immutable object. Since __new__() defines the signature for the
2864 type, it would be a pain to have to override __init__() just to
2865 stop it from complaining about excess arguments.
2866
2867 3. When defining a Mutable type, we are likely to override only
2868 __init__(). So here the converse reasoning applies: we don't
2869 want to have to override __new__() just to stop it from
2870 complaining.
2871
2872 4. When __init__() is overridden, and the subclass __init__() calls
2873 object.__init__(), the latter should complain about excess
2874 arguments; ditto for __new__().
2875
2876 Use cases 2 and 3 make it unattractive to unconditionally check for
2877 excess arguments. The best solution that addresses all four use
2878 cases is as follows: __init__() complains about excess arguments
2879 unless __new__() is overridden and __init__() is not overridden
2880 (IOW, if __init__() is overridden or __new__() is not overridden);
2881 symmetrically, __new__() complains about excess arguments unless
2882 __init__() is overridden and __new__() is not overridden
2883 (IOW, if __new__() is overridden or __init__() is not overridden).
2884
2885 However, for backwards compatibility, this breaks too much code.
2886 Therefore, in 2.6, we'll *warn* about excess arguments when both
2887 methods are overridden; for all other cases we'll use the above
2888 rules.
2889
2890*/
2891
2892/* Forward */
2893static PyObject *
2894object_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
2895
2896static int
2897excess_args(PyObject *args, PyObject *kwds)
2898{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002899 return PyTuple_GET_SIZE(args) ||
2900 (kwds && PyDict_Check(kwds) && PyDict_Size(kwds));
Guido van Rossumd8faa362007-04-27 19:54:29 +00002901}
2902
Tim Peters6d6c1a32001-08-02 04:15:00 +00002903static int
2904object_init(PyObject *self, PyObject *args, PyObject *kwds)
2905{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002906 int err = 0;
2907 if (excess_args(args, kwds)) {
2908 PyTypeObject *type = Py_TYPE(self);
2909 if (type->tp_init != object_init &&
2910 type->tp_new != object_new)
2911 {
2912 err = PyErr_WarnEx(PyExc_DeprecationWarning,
2913 "object.__init__() takes no parameters",
2914 1);
2915 }
2916 else if (type->tp_init != object_init ||
2917 type->tp_new == object_new)
2918 {
2919 PyErr_SetString(PyExc_TypeError,
2920 "object.__init__() takes no parameters");
2921 err = -1;
2922 }
2923 }
2924 return err;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002925}
2926
Guido van Rossum298e4212003-02-13 16:30:16 +00002927static PyObject *
2928object_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2929{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002930 int err = 0;
2931 if (excess_args(args, kwds)) {
2932 if (type->tp_new != object_new &&
2933 type->tp_init != object_init)
2934 {
2935 err = PyErr_WarnEx(PyExc_DeprecationWarning,
2936 "object.__new__() takes no parameters",
2937 1);
2938 }
2939 else if (type->tp_new != object_new ||
2940 type->tp_init == object_init)
2941 {
2942 PyErr_SetString(PyExc_TypeError,
2943 "object.__new__() takes no parameters");
2944 err = -1;
2945 }
2946 }
2947 if (err < 0)
2948 return NULL;
Christian Heimes9e7f1d22008-02-28 12:27:11 +00002949
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002950 if (type->tp_flags & Py_TPFLAGS_IS_ABSTRACT) {
2951 static PyObject *comma = NULL;
2952 PyObject *abstract_methods = NULL;
2953 PyObject *builtins;
2954 PyObject *sorted;
2955 PyObject *sorted_methods = NULL;
2956 PyObject *joined = NULL;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02002957 _Py_IDENTIFIER(join);
Christian Heimes9e7f1d22008-02-28 12:27:11 +00002958
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002959 /* Compute ", ".join(sorted(type.__abstractmethods__))
2960 into joined. */
2961 abstract_methods = type_abstractmethods(type, NULL);
2962 if (abstract_methods == NULL)
2963 goto error;
2964 builtins = PyEval_GetBuiltins();
2965 if (builtins == NULL)
2966 goto error;
2967 sorted = PyDict_GetItemString(builtins, "sorted");
2968 if (sorted == NULL)
2969 goto error;
2970 sorted_methods = PyObject_CallFunctionObjArgs(sorted,
2971 abstract_methods,
2972 NULL);
2973 if (sorted_methods == NULL)
2974 goto error;
2975 if (comma == NULL) {
2976 comma = PyUnicode_InternFromString(", ");
2977 if (comma == NULL)
2978 goto error;
2979 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002980 joined = _PyObject_CallMethodId(comma, &PyId_join,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002981 "O", sorted_methods);
2982 if (joined == NULL)
2983 goto error;
Christian Heimes9e7f1d22008-02-28 12:27:11 +00002984
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002985 PyErr_Format(PyExc_TypeError,
2986 "Can't instantiate abstract class %s "
2987 "with abstract methods %U",
2988 type->tp_name,
2989 joined);
2990 error:
2991 Py_XDECREF(joined);
2992 Py_XDECREF(sorted_methods);
2993 Py_XDECREF(abstract_methods);
2994 return NULL;
2995 }
2996 return type->tp_alloc(type, 0);
Guido van Rossum298e4212003-02-13 16:30:16 +00002997}
2998
Tim Peters6d6c1a32001-08-02 04:15:00 +00002999static void
3000object_dealloc(PyObject *self)
3001{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003002 Py_TYPE(self)->tp_free(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003003}
3004
Guido van Rossum8e248182001-08-12 05:17:56 +00003005static PyObject *
3006object_repr(PyObject *self)
3007{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003008 PyTypeObject *type;
3009 PyObject *mod, *name, *rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00003010
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003011 type = Py_TYPE(self);
3012 mod = type_module(type, NULL);
3013 if (mod == NULL)
3014 PyErr_Clear();
3015 else if (!PyUnicode_Check(mod)) {
3016 Py_DECREF(mod);
3017 mod = NULL;
3018 }
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003019 name = type_qualname(type, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003020 if (name == NULL)
3021 return NULL;
3022 if (mod != NULL && PyUnicode_CompareWithASCIIString(mod, "builtins"))
3023 rtn = PyUnicode_FromFormat("<%U.%U object at %p>", mod, name, self);
3024 else
3025 rtn = PyUnicode_FromFormat("<%s object at %p>",
3026 type->tp_name, self);
3027 Py_XDECREF(mod);
3028 Py_DECREF(name);
3029 return rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00003030}
3031
Guido van Rossumb8f63662001-08-15 23:57:02 +00003032static PyObject *
3033object_str(PyObject *self)
3034{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003035 unaryfunc f;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003036
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003037 f = Py_TYPE(self)->tp_repr;
Antoine Pitrou8cdc40e2011-07-15 21:15:07 +02003038 if (f == NULL || f == object_str)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003039 f = object_repr;
3040 return f(self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003041}
3042
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003043static PyObject *
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003044object_richcompare(PyObject *self, PyObject *other, int op)
3045{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003046 PyObject *res;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003047
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003048 switch (op) {
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003049
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003050 case Py_EQ:
3051 /* Return NotImplemented instead of False, so if two
3052 objects are compared, both get a chance at the
3053 comparison. See issue #1393. */
3054 res = (self == other) ? Py_True : Py_NotImplemented;
3055 Py_INCREF(res);
3056 break;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003057
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003058 case Py_NE:
3059 /* By default, != returns the opposite of ==,
3060 unless the latter returns NotImplemented. */
3061 res = PyObject_RichCompare(self, other, Py_EQ);
3062 if (res != NULL && res != Py_NotImplemented) {
3063 int ok = PyObject_IsTrue(res);
3064 Py_DECREF(res);
3065 if (ok < 0)
3066 res = NULL;
3067 else {
3068 if (ok)
3069 res = Py_False;
3070 else
3071 res = Py_True;
3072 Py_INCREF(res);
3073 }
3074 }
3075 break;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003076
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003077 default:
3078 res = Py_NotImplemented;
3079 Py_INCREF(res);
3080 break;
3081 }
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003082
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003083 return res;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003084}
3085
3086static PyObject *
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003087object_get_class(PyObject *self, void *closure)
3088{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003089 Py_INCREF(Py_TYPE(self));
3090 return (PyObject *)(Py_TYPE(self));
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003091}
3092
3093static int
3094equiv_structs(PyTypeObject *a, PyTypeObject *b)
3095{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003096 return a == b ||
3097 (a != NULL &&
3098 b != NULL &&
3099 a->tp_basicsize == b->tp_basicsize &&
3100 a->tp_itemsize == b->tp_itemsize &&
3101 a->tp_dictoffset == b->tp_dictoffset &&
3102 a->tp_weaklistoffset == b->tp_weaklistoffset &&
3103 ((a->tp_flags & Py_TPFLAGS_HAVE_GC) ==
3104 (b->tp_flags & Py_TPFLAGS_HAVE_GC)));
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003105}
3106
3107static int
3108same_slots_added(PyTypeObject *a, PyTypeObject *b)
3109{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003110 PyTypeObject *base = a->tp_base;
3111 Py_ssize_t size;
3112 PyObject *slots_a, *slots_b;
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003113
Benjamin Peterson67641d22011-01-17 19:24:34 +00003114 assert(base == b->tp_base);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003115 size = base->tp_basicsize;
3116 if (a->tp_dictoffset == size && b->tp_dictoffset == size)
3117 size += sizeof(PyObject *);
3118 if (a->tp_weaklistoffset == size && b->tp_weaklistoffset == size)
3119 size += sizeof(PyObject *);
Guido van Rossumd8faa362007-04-27 19:54:29 +00003120
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003121 /* Check slots compliance */
3122 slots_a = ((PyHeapTypeObject *)a)->ht_slots;
3123 slots_b = ((PyHeapTypeObject *)b)->ht_slots;
3124 if (slots_a && slots_b) {
3125 if (PyObject_RichCompareBool(slots_a, slots_b, Py_EQ) != 1)
3126 return 0;
3127 size += sizeof(PyObject *) * PyTuple_GET_SIZE(slots_a);
3128 }
3129 return size == a->tp_basicsize && size == b->tp_basicsize;
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003130}
3131
3132static int
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003133compatible_for_assignment(PyTypeObject* oldto, PyTypeObject* newto, char* attr)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003134{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003135 PyTypeObject *newbase, *oldbase;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003136
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003137 if (newto->tp_dealloc != oldto->tp_dealloc ||
3138 newto->tp_free != oldto->tp_free)
3139 {
3140 PyErr_Format(PyExc_TypeError,
3141 "%s assignment: "
3142 "'%s' deallocator differs from '%s'",
3143 attr,
3144 newto->tp_name,
3145 oldto->tp_name);
3146 return 0;
3147 }
3148 newbase = newto;
3149 oldbase = oldto;
3150 while (equiv_structs(newbase, newbase->tp_base))
3151 newbase = newbase->tp_base;
3152 while (equiv_structs(oldbase, oldbase->tp_base))
3153 oldbase = oldbase->tp_base;
3154 if (newbase != oldbase &&
3155 (newbase->tp_base != oldbase->tp_base ||
3156 !same_slots_added(newbase, oldbase))) {
3157 PyErr_Format(PyExc_TypeError,
3158 "%s assignment: "
3159 "'%s' object layout differs from '%s'",
3160 attr,
3161 newto->tp_name,
3162 oldto->tp_name);
3163 return 0;
3164 }
Tim Petersea7f75d2002-12-07 21:39:16 +00003165
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003166 return 1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003167}
3168
3169static int
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003170object_set_class(PyObject *self, PyObject *value, void *closure)
3171{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003172 PyTypeObject *oldto = Py_TYPE(self);
3173 PyTypeObject *newto;
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003174
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003175 if (value == NULL) {
3176 PyErr_SetString(PyExc_TypeError,
3177 "can't delete __class__ attribute");
3178 return -1;
3179 }
3180 if (!PyType_Check(value)) {
3181 PyErr_Format(PyExc_TypeError,
Florent Xiclunaaa6c1d22011-12-12 18:54:29 +01003182 "__class__ must be set to a class, not '%s' object",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003183 Py_TYPE(value)->tp_name);
3184 return -1;
3185 }
3186 newto = (PyTypeObject *)value;
3187 if (!(newto->tp_flags & Py_TPFLAGS_HEAPTYPE) ||
3188 !(oldto->tp_flags & Py_TPFLAGS_HEAPTYPE))
3189 {
3190 PyErr_Format(PyExc_TypeError,
3191 "__class__ assignment: only for heap types");
3192 return -1;
3193 }
3194 if (compatible_for_assignment(newto, oldto, "__class__")) {
3195 Py_INCREF(newto);
3196 Py_TYPE(self) = newto;
3197 Py_DECREF(oldto);
3198 return 0;
3199 }
3200 else {
3201 return -1;
3202 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003203}
3204
3205static PyGetSetDef object_getsets[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003206 {"__class__", object_get_class, object_set_class,
3207 PyDoc_STR("the object's class")},
3208 {0}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003209};
3210
Guido van Rossumc53f0092003-02-18 22:05:12 +00003211
Guido van Rossum036f9992003-02-21 22:02:54 +00003212/* Stuff to implement __reduce_ex__ for pickle protocols >= 2.
Alexandre Vassalottif7fa63d2008-05-11 08:55:36 +00003213 We fall back to helpers in copyreg for:
Guido van Rossum036f9992003-02-21 22:02:54 +00003214 - pickle protocols < 2
3215 - calculating the list of slot names (done only once per class)
3216 - the __newobj__ function (which is used as a token but never called)
3217*/
3218
3219static PyObject *
Alexandre Vassalottif7fa63d2008-05-11 08:55:36 +00003220import_copyreg(void)
Guido van Rossum036f9992003-02-21 22:02:54 +00003221{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003222 static PyObject *copyreg_str;
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003223 static PyObject *mod_copyreg = NULL;
Guido van Rossum3926a632001-09-25 16:25:58 +00003224
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003225 if (!copyreg_str) {
3226 copyreg_str = PyUnicode_InternFromString("copyreg");
3227 if (copyreg_str == NULL)
3228 return NULL;
3229 }
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003230 if (!mod_copyreg) {
3231 mod_copyreg = PyImport_Import(copyreg_str);
3232 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003233
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003234 Py_XINCREF(mod_copyreg);
3235 return mod_copyreg;
Guido van Rossum036f9992003-02-21 22:02:54 +00003236}
3237
3238static PyObject *
3239slotnames(PyObject *cls)
3240{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003241 PyObject *clsdict;
3242 PyObject *copyreg;
3243 PyObject *slotnames;
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003244 static PyObject *str_slotnames;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02003245 _Py_IDENTIFIER(_slotnames);
Guido van Rossum036f9992003-02-21 22:02:54 +00003246
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003247 if (str_slotnames == NULL) {
3248 str_slotnames = PyUnicode_InternFromString("__slotnames__");
3249 if (str_slotnames == NULL)
3250 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003251 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003252
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003253 clsdict = ((PyTypeObject *)cls)->tp_dict;
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003254 slotnames = PyDict_GetItem(clsdict, str_slotnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003255 if (slotnames != NULL && PyList_Check(slotnames)) {
3256 Py_INCREF(slotnames);
3257 return slotnames;
3258 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003259
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003260 copyreg = import_copyreg();
3261 if (copyreg == NULL)
3262 return NULL;
Guido van Rossum036f9992003-02-21 22:02:54 +00003263
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02003264 slotnames = _PyObject_CallMethodId(copyreg, &PyId__slotnames, "O", cls);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003265 Py_DECREF(copyreg);
3266 if (slotnames != NULL &&
3267 slotnames != Py_None &&
3268 !PyList_Check(slotnames))
3269 {
3270 PyErr_SetString(PyExc_TypeError,
3271 "copyreg._slotnames didn't return a list or None");
3272 Py_DECREF(slotnames);
3273 slotnames = NULL;
3274 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003275
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003276 return slotnames;
Guido van Rossum036f9992003-02-21 22:02:54 +00003277}
3278
3279static PyObject *
3280reduce_2(PyObject *obj)
3281{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003282 PyObject *cls, *getnewargs;
3283 PyObject *args = NULL, *args2 = NULL;
3284 PyObject *getstate = NULL, *state = NULL, *names = NULL;
3285 PyObject *slots = NULL, *listitems = NULL, *dictitems = NULL;
3286 PyObject *copyreg = NULL, *newobj = NULL, *res = NULL;
3287 Py_ssize_t i, n;
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003288 static PyObject *str_getnewargs = NULL, *str_getstate = NULL,
3289 *str_newobj = NULL;
Guido van Rossum036f9992003-02-21 22:02:54 +00003290
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003291 if (str_getnewargs == NULL) {
3292 str_getnewargs = PyUnicode_InternFromString("__getnewargs__");
3293 str_getstate = PyUnicode_InternFromString("__getstate__");
3294 str_newobj = PyUnicode_InternFromString("__newobj__");
3295 if (!str_getnewargs || !str_getstate || !str_newobj)
3296 return NULL;
3297 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003298
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003299 cls = (PyObject *) Py_TYPE(obj);
3300
3301 getnewargs = PyObject_GetAttr(obj, str_getnewargs);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003302 if (getnewargs != NULL) {
3303 args = PyObject_CallObject(getnewargs, NULL);
3304 Py_DECREF(getnewargs);
3305 if (args != NULL && !PyTuple_Check(args)) {
3306 PyErr_Format(PyExc_TypeError,
3307 "__getnewargs__ should return a tuple, "
3308 "not '%.200s'", Py_TYPE(args)->tp_name);
3309 goto end;
3310 }
3311 }
3312 else {
3313 PyErr_Clear();
3314 args = PyTuple_New(0);
3315 }
3316 if (args == NULL)
3317 goto end;
Guido van Rossum036f9992003-02-21 22:02:54 +00003318
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003319 getstate = PyObject_GetAttr(obj, str_getstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003320 if (getstate != NULL) {
3321 state = PyObject_CallObject(getstate, NULL);
3322 Py_DECREF(getstate);
3323 if (state == NULL)
3324 goto end;
3325 }
3326 else {
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003327 PyObject **dict;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003328 PyErr_Clear();
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003329 dict = _PyObject_GetDictPtr(obj);
3330 if (dict && *dict)
3331 state = *dict;
3332 else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003333 state = Py_None;
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003334 Py_INCREF(state);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003335 names = slotnames(cls);
3336 if (names == NULL)
3337 goto end;
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003338 if (names != Py_None && PyList_GET_SIZE(names) > 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003339 assert(PyList_Check(names));
3340 slots = PyDict_New();
3341 if (slots == NULL)
3342 goto end;
3343 n = 0;
3344 /* Can't pre-compute the list size; the list
3345 is stored on the class so accessible to other
3346 threads, which may be run by DECREF */
3347 for (i = 0; i < PyList_GET_SIZE(names); i++) {
3348 PyObject *name, *value;
3349 name = PyList_GET_ITEM(names, i);
3350 value = PyObject_GetAttr(obj, name);
3351 if (value == NULL)
3352 PyErr_Clear();
3353 else {
3354 int err = PyDict_SetItem(slots, name,
3355 value);
3356 Py_DECREF(value);
3357 if (err)
3358 goto end;
3359 n++;
3360 }
3361 }
3362 if (n) {
3363 state = Py_BuildValue("(NO)", state, slots);
3364 if (state == NULL)
3365 goto end;
3366 }
3367 }
3368 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003369
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003370 if (!PyList_Check(obj)) {
3371 listitems = Py_None;
3372 Py_INCREF(listitems);
3373 }
3374 else {
3375 listitems = PyObject_GetIter(obj);
3376 if (listitems == NULL)
3377 goto end;
3378 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003379
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003380 if (!PyDict_Check(obj)) {
3381 dictitems = Py_None;
3382 Py_INCREF(dictitems);
3383 }
3384 else {
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02003385 _Py_IDENTIFIER(items);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02003386 PyObject *items = _PyObject_CallMethodId(obj, &PyId_items, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003387 if (items == NULL)
3388 goto end;
3389 dictitems = PyObject_GetIter(items);
3390 Py_DECREF(items);
3391 if (dictitems == NULL)
3392 goto end;
3393 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003394
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003395 copyreg = import_copyreg();
3396 if (copyreg == NULL)
3397 goto end;
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003398 newobj = PyObject_GetAttr(copyreg, str_newobj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003399 if (newobj == NULL)
3400 goto end;
Guido van Rossum036f9992003-02-21 22:02:54 +00003401
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003402 n = PyTuple_GET_SIZE(args);
3403 args2 = PyTuple_New(n+1);
3404 if (args2 == NULL)
3405 goto end;
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003406 Py_INCREF(cls);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003407 PyTuple_SET_ITEM(args2, 0, cls);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003408 for (i = 0; i < n; i++) {
3409 PyObject *v = PyTuple_GET_ITEM(args, i);
3410 Py_INCREF(v);
3411 PyTuple_SET_ITEM(args2, i+1, v);
3412 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003413
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003414 res = PyTuple_Pack(5, newobj, args2, state, listitems, dictitems);
Guido van Rossum036f9992003-02-21 22:02:54 +00003415
3416 end:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003417 Py_XDECREF(args);
3418 Py_XDECREF(args2);
3419 Py_XDECREF(slots);
3420 Py_XDECREF(state);
3421 Py_XDECREF(names);
3422 Py_XDECREF(listitems);
3423 Py_XDECREF(dictitems);
3424 Py_XDECREF(copyreg);
3425 Py_XDECREF(newobj);
3426 return res;
Guido van Rossum036f9992003-02-21 22:02:54 +00003427}
3428
Guido van Rossumd8faa362007-04-27 19:54:29 +00003429/*
3430 * There were two problems when object.__reduce__ and object.__reduce_ex__
3431 * were implemented in the same function:
3432 * - trying to pickle an object with a custom __reduce__ method that
3433 * fell back to object.__reduce__ in certain circumstances led to
3434 * infinite recursion at Python level and eventual RuntimeError.
3435 * - Pickling objects that lied about their type by overwriting the
3436 * __class__ descriptor could lead to infinite recursion at C level
3437 * and eventual segfault.
3438 *
3439 * Because of backwards compatibility, the two methods still have to
3440 * behave in the same way, even if this is not required by the pickle
3441 * protocol. This common functionality was moved to the _common_reduce
3442 * function.
3443 */
3444static PyObject *
3445_common_reduce(PyObject *self, int proto)
3446{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003447 PyObject *copyreg, *res;
Guido van Rossumd8faa362007-04-27 19:54:29 +00003448
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003449 if (proto >= 2)
3450 return reduce_2(self);
Guido van Rossumd8faa362007-04-27 19:54:29 +00003451
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003452 copyreg = import_copyreg();
3453 if (!copyreg)
3454 return NULL;
Guido van Rossumd8faa362007-04-27 19:54:29 +00003455
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003456 res = PyEval_CallMethod(copyreg, "_reduce_ex", "(Oi)", self, proto);
3457 Py_DECREF(copyreg);
Guido van Rossumd8faa362007-04-27 19:54:29 +00003458
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003459 return res;
Guido van Rossumd8faa362007-04-27 19:54:29 +00003460}
3461
3462static PyObject *
3463object_reduce(PyObject *self, PyObject *args)
3464{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003465 int proto = 0;
Guido van Rossumd8faa362007-04-27 19:54:29 +00003466
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003467 if (!PyArg_ParseTuple(args, "|i:__reduce__", &proto))
3468 return NULL;
Guido van Rossumd8faa362007-04-27 19:54:29 +00003469
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003470 return _common_reduce(self, proto);
Guido van Rossumd8faa362007-04-27 19:54:29 +00003471}
3472
Guido van Rossum036f9992003-02-21 22:02:54 +00003473static PyObject *
3474object_reduce_ex(PyObject *self, PyObject *args)
3475{
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003476 static PyObject *str_reduce = NULL, *objreduce;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003477 PyObject *reduce, *res;
3478 int proto = 0;
Guido van Rossum036f9992003-02-21 22:02:54 +00003479
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003480 if (!PyArg_ParseTuple(args, "|i:__reduce_ex__", &proto))
3481 return NULL;
Guido van Rossum036f9992003-02-21 22:02:54 +00003482
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003483 if (str_reduce == NULL) {
3484 str_reduce = PyUnicode_InternFromString("__reduce__");
3485 objreduce = PyDict_GetItemString(PyBaseObject_Type.tp_dict,
3486 "__reduce__");
3487 if (str_reduce == NULL || objreduce == NULL)
3488 return NULL;
3489 }
3490
3491 reduce = PyObject_GetAttr(self, str_reduce);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003492 if (reduce == NULL)
3493 PyErr_Clear();
3494 else {
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003495 PyObject *cls, *clsreduce;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003496 int override;
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003497
3498 cls = (PyObject *) Py_TYPE(self);
3499 clsreduce = PyObject_GetAttr(cls, str_reduce);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003500 if (clsreduce == NULL) {
3501 Py_DECREF(reduce);
3502 return NULL;
3503 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003504 override = (clsreduce != objreduce);
3505 Py_DECREF(clsreduce);
3506 if (override) {
3507 res = PyObject_CallObject(reduce, NULL);
3508 Py_DECREF(reduce);
3509 return res;
3510 }
3511 else
3512 Py_DECREF(reduce);
3513 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003514
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003515 return _common_reduce(self, proto);
Guido van Rossum3926a632001-09-25 16:25:58 +00003516}
3517
Christian Heimes9e7f1d22008-02-28 12:27:11 +00003518static PyObject *
3519object_subclasshook(PyObject *cls, PyObject *args)
3520{
Brian Curtindfc80e32011-08-10 20:28:54 -05003521 Py_RETURN_NOTIMPLEMENTED;
Christian Heimes9e7f1d22008-02-28 12:27:11 +00003522}
3523
3524PyDoc_STRVAR(object_subclasshook_doc,
3525"Abstract classes can override this to customize issubclass().\n"
3526"\n"
3527"This is invoked early on by abc.ABCMeta.__subclasscheck__().\n"
3528"It should return True, False or NotImplemented. If it returns\n"
3529"NotImplemented, the normal algorithm is used. Otherwise, it\n"
3530"overrides the normal algorithm (and the outcome is cached).\n");
Eric Smith8c663262007-08-25 02:26:07 +00003531
3532/*
3533 from PEP 3101, this code implements:
3534
3535 class object:
3536 def __format__(self, format_spec):
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003537 return format(str(self), format_spec)
Eric Smith8c663262007-08-25 02:26:07 +00003538*/
3539static PyObject *
3540object_format(PyObject *self, PyObject *args)
3541{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003542 PyObject *format_spec;
3543 PyObject *self_as_str = NULL;
3544 PyObject *result = NULL;
Eric Smith8c663262007-08-25 02:26:07 +00003545
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003546 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
3547 return NULL;
Eric Smith8c663262007-08-25 02:26:07 +00003548
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003549 self_as_str = PyObject_Str(self);
Eric Smithe4d63172010-09-13 20:48:43 +00003550 if (self_as_str != NULL) {
3551 /* Issue 7994: If we're converting to a string, we
Eric V. Smithb9cd3532011-03-12 10:08:48 -05003552 should reject format specifications */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003553 if (PyUnicode_GET_LENGTH(format_spec) > 0) {
Eric V. Smithb9cd3532011-03-12 10:08:48 -05003554 if (PyErr_WarnEx(PyExc_DeprecationWarning,
3555 "object.__format__ with a non-empty format "
3556 "string is deprecated", 1) < 0) {
3557 goto done;
3558 }
3559 /* Eventually this will become an error:
3560 PyErr_Format(PyExc_TypeError,
3561 "non-empty format string passed to object.__format__");
3562 goto done;
3563 */
3564 }
Eric Smith8c663262007-08-25 02:26:07 +00003565
Eric V. Smithb9cd3532011-03-12 10:08:48 -05003566 result = PyObject_Format(self_as_str, format_spec);
Eric Smithe4d63172010-09-13 20:48:43 +00003567 }
3568
3569done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003570 Py_XDECREF(self_as_str);
Eric Smith8c663262007-08-25 02:26:07 +00003571
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003572 return result;
Eric Smith8c663262007-08-25 02:26:07 +00003573}
3574
Martin v. Löwis00709aa2008-06-04 14:18:43 +00003575static PyObject *
3576object_sizeof(PyObject *self, PyObject *args)
3577{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003578 Py_ssize_t res, isize;
Martin v. Löwis00709aa2008-06-04 14:18:43 +00003579
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003580 res = 0;
3581 isize = self->ob_type->tp_itemsize;
3582 if (isize > 0)
3583 res = Py_SIZE(self->ob_type) * isize;
3584 res += self->ob_type->tp_basicsize;
Martin v. Löwis00709aa2008-06-04 14:18:43 +00003585
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003586 return PyLong_FromSsize_t(res);
Martin v. Löwis00709aa2008-06-04 14:18:43 +00003587}
3588
Benjamin Peterson82b00c12011-05-24 11:09:06 -05003589/* __dir__ for generic objects: returns __dict__, __class__,
3590 and recursively up the __class__.__bases__ chain.
3591*/
3592static PyObject *
3593object_dir(PyObject *self, PyObject *args)
3594{
3595 PyObject *result = NULL;
3596 PyObject *dict = NULL;
3597 PyObject *itsclass = NULL;
3598
3599 /* Get __dict__ (which may or may not be a real dict...) */
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02003600 dict = _PyObject_GetAttrId(self, &PyId___dict__);
Benjamin Peterson82b00c12011-05-24 11:09:06 -05003601 if (dict == NULL) {
3602 PyErr_Clear();
3603 dict = PyDict_New();
3604 }
3605 else if (!PyDict_Check(dict)) {
3606 Py_DECREF(dict);
3607 dict = PyDict_New();
3608 }
3609 else {
3610 /* Copy __dict__ to avoid mutating it. */
3611 PyObject *temp = PyDict_Copy(dict);
3612 Py_DECREF(dict);
3613 dict = temp;
3614 }
3615
3616 if (dict == NULL)
3617 goto error;
3618
3619 /* Merge in attrs reachable from its class. */
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02003620 itsclass = _PyObject_GetAttrId(self, &PyId___class__);
Benjamin Peterson82b00c12011-05-24 11:09:06 -05003621 if (itsclass == NULL)
3622 /* XXX(tomer): Perhaps fall back to obj->ob_type if no
3623 __class__ exists? */
3624 PyErr_Clear();
3625 else if (merge_class_dict(dict, itsclass) != 0)
3626 goto error;
3627
3628 result = PyDict_Keys(dict);
3629 /* fall through */
3630error:
3631 Py_XDECREF(itsclass);
3632 Py_XDECREF(dict);
3633 return result;
3634}
3635
Guido van Rossum3926a632001-09-25 16:25:58 +00003636static PyMethodDef object_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003637 {"__reduce_ex__", object_reduce_ex, METH_VARARGS,
3638 PyDoc_STR("helper for pickle")},
3639 {"__reduce__", object_reduce, METH_VARARGS,
3640 PyDoc_STR("helper for pickle")},
3641 {"__subclasshook__", object_subclasshook, METH_CLASS | METH_VARARGS,
3642 object_subclasshook_doc},
3643 {"__format__", object_format, METH_VARARGS,
3644 PyDoc_STR("default object formatter")},
3645 {"__sizeof__", object_sizeof, METH_NOARGS,
Benjamin Petersonfbe56bb2011-05-24 12:42:51 -05003646 PyDoc_STR("__sizeof__() -> int\nsize of object in memory, in bytes")},
Benjamin Peterson82b00c12011-05-24 11:09:06 -05003647 {"__dir__", object_dir, METH_NOARGS,
Benjamin Petersonc7284122011-05-24 12:46:15 -05003648 PyDoc_STR("__dir__() -> list\ndefault dir() implementation")},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003649 {0}
Guido van Rossum3926a632001-09-25 16:25:58 +00003650};
3651
Guido van Rossum036f9992003-02-21 22:02:54 +00003652
Tim Peters6d6c1a32001-08-02 04:15:00 +00003653PyTypeObject PyBaseObject_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003654 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3655 "object", /* tp_name */
3656 sizeof(PyObject), /* tp_basicsize */
3657 0, /* tp_itemsize */
3658 object_dealloc, /* tp_dealloc */
3659 0, /* tp_print */
3660 0, /* tp_getattr */
3661 0, /* tp_setattr */
3662 0, /* tp_reserved */
3663 object_repr, /* tp_repr */
3664 0, /* tp_as_number */
3665 0, /* tp_as_sequence */
3666 0, /* tp_as_mapping */
3667 (hashfunc)_Py_HashPointer, /* tp_hash */
3668 0, /* tp_call */
3669 object_str, /* tp_str */
3670 PyObject_GenericGetAttr, /* tp_getattro */
3671 PyObject_GenericSetAttr, /* tp_setattro */
3672 0, /* tp_as_buffer */
3673 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
3674 PyDoc_STR("The most base type"), /* tp_doc */
3675 0, /* tp_traverse */
3676 0, /* tp_clear */
3677 object_richcompare, /* tp_richcompare */
3678 0, /* tp_weaklistoffset */
3679 0, /* tp_iter */
3680 0, /* tp_iternext */
3681 object_methods, /* tp_methods */
3682 0, /* tp_members */
3683 object_getsets, /* tp_getset */
3684 0, /* tp_base */
3685 0, /* tp_dict */
3686 0, /* tp_descr_get */
3687 0, /* tp_descr_set */
3688 0, /* tp_dictoffset */
3689 object_init, /* tp_init */
3690 PyType_GenericAlloc, /* tp_alloc */
3691 object_new, /* tp_new */
3692 PyObject_Del, /* tp_free */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003693};
3694
3695
Guido van Rossum50e9fb92006-08-17 05:42:55 +00003696/* Add the methods from tp_methods to the __dict__ in a type object */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003697
3698static int
3699add_methods(PyTypeObject *type, PyMethodDef *meth)
3700{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003701 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003702
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003703 for (; meth->ml_name != NULL; meth++) {
3704 PyObject *descr;
3705 if (PyDict_GetItemString(dict, meth->ml_name) &&
3706 !(meth->ml_flags & METH_COEXIST))
3707 continue;
3708 if (meth->ml_flags & METH_CLASS) {
3709 if (meth->ml_flags & METH_STATIC) {
3710 PyErr_SetString(PyExc_ValueError,
3711 "method cannot be both class and static");
3712 return -1;
3713 }
3714 descr = PyDescr_NewClassMethod(type, meth);
3715 }
3716 else if (meth->ml_flags & METH_STATIC) {
Antoine Pitrou5b629422011-12-23 12:40:16 +01003717 PyObject *cfunc = PyCFunction_New(meth, (PyObject*)type);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003718 if (cfunc == NULL)
3719 return -1;
3720 descr = PyStaticMethod_New(cfunc);
3721 Py_DECREF(cfunc);
3722 }
3723 else {
3724 descr = PyDescr_NewMethod(type, meth);
3725 }
3726 if (descr == NULL)
3727 return -1;
3728 if (PyDict_SetItemString(dict, meth->ml_name, descr) < 0)
3729 return -1;
3730 Py_DECREF(descr);
3731 }
3732 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003733}
3734
3735static int
Guido van Rossum6f799372001-09-20 20:46:19 +00003736add_members(PyTypeObject *type, PyMemberDef *memb)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003737{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003738 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003739
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003740 for (; memb->name != NULL; memb++) {
3741 PyObject *descr;
3742 if (PyDict_GetItemString(dict, memb->name))
3743 continue;
3744 descr = PyDescr_NewMember(type, memb);
3745 if (descr == NULL)
3746 return -1;
3747 if (PyDict_SetItemString(dict, memb->name, descr) < 0)
3748 return -1;
3749 Py_DECREF(descr);
3750 }
3751 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003752}
3753
3754static int
Guido van Rossum32d34c82001-09-20 21:45:26 +00003755add_getset(PyTypeObject *type, PyGetSetDef *gsp)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003756{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003757 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003758
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003759 for (; gsp->name != NULL; gsp++) {
3760 PyObject *descr;
3761 if (PyDict_GetItemString(dict, gsp->name))
3762 continue;
3763 descr = PyDescr_NewGetSet(type, gsp);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003764
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003765 if (descr == NULL)
3766 return -1;
3767 if (PyDict_SetItemString(dict, gsp->name, descr) < 0)
3768 return -1;
3769 Py_DECREF(descr);
3770 }
3771 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003772}
3773
Guido van Rossum13d52f02001-08-10 21:24:08 +00003774static void
3775inherit_special(PyTypeObject *type, PyTypeObject *base)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003776{
Tim Peters6d6c1a32001-08-02 04:15:00 +00003777
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003778 /* Copying basicsize is connected to the GC flags */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003779 if (!(type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
3780 (base->tp_flags & Py_TPFLAGS_HAVE_GC) &&
3781 (!type->tp_traverse && !type->tp_clear)) {
3782 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
3783 if (type->tp_traverse == NULL)
3784 type->tp_traverse = base->tp_traverse;
3785 if (type->tp_clear == NULL)
3786 type->tp_clear = base->tp_clear;
3787 }
3788 {
3789 /* The condition below could use some explanation.
3790 It appears that tp_new is not inherited for static types
3791 whose base class is 'object'; this seems to be a precaution
3792 so that old extension types don't suddenly become
3793 callable (object.__new__ wouldn't insure the invariants
3794 that the extension type's own factory function ensures).
3795 Heap types, of course, are under our control, so they do
3796 inherit tp_new; static extension types that specify some
Florent Xiclunaaa6c1d22011-12-12 18:54:29 +01003797 other built-in type as the default also
3798 inherit object.__new__. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003799 if (base != &PyBaseObject_Type ||
3800 (type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
3801 if (type->tp_new == NULL)
3802 type->tp_new = base->tp_new;
3803 }
3804 }
Benjamin Petersona7465e22010-07-05 15:01:22 +00003805 if (type->tp_basicsize == 0)
3806 type->tp_basicsize = base->tp_basicsize;
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00003807
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003808 /* Copy other non-function slots */
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00003809
3810#undef COPYVAL
3811#define COPYVAL(SLOT) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003812 if (type->SLOT == 0) type->SLOT = base->SLOT
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00003813
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003814 COPYVAL(tp_itemsize);
3815 COPYVAL(tp_weaklistoffset);
3816 COPYVAL(tp_dictoffset);
Thomas Wouters27d517b2007-02-25 20:39:11 +00003817
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003818 /* Setup fast subclass flags */
3819 if (PyType_IsSubtype(base, (PyTypeObject*)PyExc_BaseException))
3820 type->tp_flags |= Py_TPFLAGS_BASE_EXC_SUBCLASS;
3821 else if (PyType_IsSubtype(base, &PyType_Type))
3822 type->tp_flags |= Py_TPFLAGS_TYPE_SUBCLASS;
3823 else if (PyType_IsSubtype(base, &PyLong_Type))
3824 type->tp_flags |= Py_TPFLAGS_LONG_SUBCLASS;
3825 else if (PyType_IsSubtype(base, &PyBytes_Type))
3826 type->tp_flags |= Py_TPFLAGS_BYTES_SUBCLASS;
3827 else if (PyType_IsSubtype(base, &PyUnicode_Type))
3828 type->tp_flags |= Py_TPFLAGS_UNICODE_SUBCLASS;
3829 else if (PyType_IsSubtype(base, &PyTuple_Type))
3830 type->tp_flags |= Py_TPFLAGS_TUPLE_SUBCLASS;
3831 else if (PyType_IsSubtype(base, &PyList_Type))
3832 type->tp_flags |= Py_TPFLAGS_LIST_SUBCLASS;
3833 else if (PyType_IsSubtype(base, &PyDict_Type))
3834 type->tp_flags |= Py_TPFLAGS_DICT_SUBCLASS;
Guido van Rossum13d52f02001-08-10 21:24:08 +00003835}
3836
Guido van Rossumf5243f02008-01-01 04:06:48 +00003837static char *hash_name_op[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003838 "__eq__",
3839 "__hash__",
3840 NULL
Guido van Rossum38938152006-08-21 23:36:26 +00003841};
3842
3843static int
Guido van Rossumf5243f02008-01-01 04:06:48 +00003844overrides_hash(PyTypeObject *type)
Guido van Rossum38938152006-08-21 23:36:26 +00003845{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003846 char **p;
3847 PyObject *dict = type->tp_dict;
Guido van Rossum38938152006-08-21 23:36:26 +00003848
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003849 assert(dict != NULL);
3850 for (p = hash_name_op; *p; p++) {
3851 if (PyDict_GetItemString(dict, *p) != NULL)
3852 return 1;
3853 }
3854 return 0;
Guido van Rossum38938152006-08-21 23:36:26 +00003855}
3856
Guido van Rossum13d52f02001-08-10 21:24:08 +00003857static void
3858inherit_slots(PyTypeObject *type, PyTypeObject *base)
3859{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003860 PyTypeObject *basebase;
Guido van Rossum13d52f02001-08-10 21:24:08 +00003861
3862#undef SLOTDEFINED
Tim Peters6d6c1a32001-08-02 04:15:00 +00003863#undef COPYSLOT
3864#undef COPYNUM
3865#undef COPYSEQ
3866#undef COPYMAP
Guido van Rossum5af588b2001-10-12 14:13:21 +00003867#undef COPYBUF
Guido van Rossum13d52f02001-08-10 21:24:08 +00003868
3869#define SLOTDEFINED(SLOT) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003870 (base->SLOT != 0 && \
3871 (basebase == NULL || base->SLOT != basebase->SLOT))
Guido van Rossum13d52f02001-08-10 21:24:08 +00003872
Tim Peters6d6c1a32001-08-02 04:15:00 +00003873#define COPYSLOT(SLOT) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003874 if (!type->SLOT && SLOTDEFINED(SLOT)) type->SLOT = base->SLOT
Tim Peters6d6c1a32001-08-02 04:15:00 +00003875
3876#define COPYNUM(SLOT) COPYSLOT(tp_as_number->SLOT)
3877#define COPYSEQ(SLOT) COPYSLOT(tp_as_sequence->SLOT)
3878#define COPYMAP(SLOT) COPYSLOT(tp_as_mapping->SLOT)
Tim Petersfc57ccb2001-10-12 02:38:24 +00003879#define COPYBUF(SLOT) COPYSLOT(tp_as_buffer->SLOT)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003880
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003881 /* This won't inherit indirect slots (from tp_as_number etc.)
3882 if type doesn't provide the space. */
Guido van Rossum13d52f02001-08-10 21:24:08 +00003883
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003884 if (type->tp_as_number != NULL && base->tp_as_number != NULL) {
3885 basebase = base->tp_base;
3886 if (basebase->tp_as_number == NULL)
3887 basebase = NULL;
3888 COPYNUM(nb_add);
3889 COPYNUM(nb_subtract);
3890 COPYNUM(nb_multiply);
3891 COPYNUM(nb_remainder);
3892 COPYNUM(nb_divmod);
3893 COPYNUM(nb_power);
3894 COPYNUM(nb_negative);
3895 COPYNUM(nb_positive);
3896 COPYNUM(nb_absolute);
3897 COPYNUM(nb_bool);
3898 COPYNUM(nb_invert);
3899 COPYNUM(nb_lshift);
3900 COPYNUM(nb_rshift);
3901 COPYNUM(nb_and);
3902 COPYNUM(nb_xor);
3903 COPYNUM(nb_or);
3904 COPYNUM(nb_int);
3905 COPYNUM(nb_float);
3906 COPYNUM(nb_inplace_add);
3907 COPYNUM(nb_inplace_subtract);
3908 COPYNUM(nb_inplace_multiply);
3909 COPYNUM(nb_inplace_remainder);
3910 COPYNUM(nb_inplace_power);
3911 COPYNUM(nb_inplace_lshift);
3912 COPYNUM(nb_inplace_rshift);
3913 COPYNUM(nb_inplace_and);
3914 COPYNUM(nb_inplace_xor);
3915 COPYNUM(nb_inplace_or);
3916 COPYNUM(nb_true_divide);
3917 COPYNUM(nb_floor_divide);
3918 COPYNUM(nb_inplace_true_divide);
3919 COPYNUM(nb_inplace_floor_divide);
3920 COPYNUM(nb_index);
3921 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003922
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003923 if (type->tp_as_sequence != NULL && base->tp_as_sequence != NULL) {
3924 basebase = base->tp_base;
3925 if (basebase->tp_as_sequence == NULL)
3926 basebase = NULL;
3927 COPYSEQ(sq_length);
3928 COPYSEQ(sq_concat);
3929 COPYSEQ(sq_repeat);
3930 COPYSEQ(sq_item);
3931 COPYSEQ(sq_ass_item);
3932 COPYSEQ(sq_contains);
3933 COPYSEQ(sq_inplace_concat);
3934 COPYSEQ(sq_inplace_repeat);
3935 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003936
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003937 if (type->tp_as_mapping != NULL && base->tp_as_mapping != NULL) {
3938 basebase = base->tp_base;
3939 if (basebase->tp_as_mapping == NULL)
3940 basebase = NULL;
3941 COPYMAP(mp_length);
3942 COPYMAP(mp_subscript);
3943 COPYMAP(mp_ass_subscript);
3944 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003945
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003946 if (type->tp_as_buffer != NULL && base->tp_as_buffer != NULL) {
3947 basebase = base->tp_base;
3948 if (basebase->tp_as_buffer == NULL)
3949 basebase = NULL;
3950 COPYBUF(bf_getbuffer);
3951 COPYBUF(bf_releasebuffer);
3952 }
Tim Petersfc57ccb2001-10-12 02:38:24 +00003953
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003954 basebase = base->tp_base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003955
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003956 COPYSLOT(tp_dealloc);
3957 if (type->tp_getattr == NULL && type->tp_getattro == NULL) {
3958 type->tp_getattr = base->tp_getattr;
3959 type->tp_getattro = base->tp_getattro;
3960 }
3961 if (type->tp_setattr == NULL && type->tp_setattro == NULL) {
3962 type->tp_setattr = base->tp_setattr;
3963 type->tp_setattro = base->tp_setattro;
3964 }
3965 /* tp_reserved is ignored */
3966 COPYSLOT(tp_repr);
3967 /* tp_hash see tp_richcompare */
3968 COPYSLOT(tp_call);
3969 COPYSLOT(tp_str);
3970 {
3971 /* Copy comparison-related slots only when
3972 not overriding them anywhere */
3973 if (type->tp_richcompare == NULL &&
3974 type->tp_hash == NULL &&
3975 !overrides_hash(type))
3976 {
3977 type->tp_richcompare = base->tp_richcompare;
3978 type->tp_hash = base->tp_hash;
3979 }
3980 }
3981 {
3982 COPYSLOT(tp_iter);
3983 COPYSLOT(tp_iternext);
3984 }
3985 {
3986 COPYSLOT(tp_descr_get);
3987 COPYSLOT(tp_descr_set);
3988 COPYSLOT(tp_dictoffset);
3989 COPYSLOT(tp_init);
3990 COPYSLOT(tp_alloc);
3991 COPYSLOT(tp_is_gc);
3992 if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) ==
3993 (base->tp_flags & Py_TPFLAGS_HAVE_GC)) {
3994 /* They agree about gc. */
3995 COPYSLOT(tp_free);
3996 }
3997 else if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
3998 type->tp_free == NULL &&
3999 base->tp_free == PyObject_Free) {
4000 /* A bit of magic to plug in the correct default
4001 * tp_free function when a derived class adds gc,
4002 * didn't define tp_free, and the base uses the
4003 * default non-gc tp_free.
4004 */
4005 type->tp_free = PyObject_GC_Del;
4006 }
4007 /* else they didn't agree about gc, and there isn't something
4008 * obvious to be done -- the type is on its own.
4009 */
4010 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004011}
4012
Jeremy Hylton938ace62002-07-17 16:30:39 +00004013static int add_operators(PyTypeObject *);
Guido van Rossum13d52f02001-08-10 21:24:08 +00004014
Tim Peters6d6c1a32001-08-02 04:15:00 +00004015int
Guido van Rossum528b7eb2001-08-07 17:24:28 +00004016PyType_Ready(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004017{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004018 PyObject *dict, *bases;
4019 PyTypeObject *base;
4020 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004021
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004022 if (type->tp_flags & Py_TPFLAGS_READY) {
4023 assert(type->tp_dict != NULL);
4024 return 0;
4025 }
4026 assert((type->tp_flags & Py_TPFLAGS_READYING) == 0);
Guido van Rossumd614f972001-08-10 17:39:49 +00004027
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004028 type->tp_flags |= Py_TPFLAGS_READYING;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004029
Tim Peters36eb4df2003-03-23 03:33:13 +00004030#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004031 /* PyType_Ready is the closest thing we have to a choke point
4032 * for type objects, so is the best place I can think of to try
4033 * to get type objects into the doubly-linked list of all objects.
4034 * Still, not all type objects go thru PyType_Ready.
4035 */
4036 _Py_AddToAllObjects((PyObject *)type, 0);
Tim Peters36eb4df2003-03-23 03:33:13 +00004037#endif
4038
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004039 /* Initialize tp_base (defaults to BaseObject unless that's us) */
4040 base = type->tp_base;
4041 if (base == NULL && type != &PyBaseObject_Type) {
4042 base = type->tp_base = &PyBaseObject_Type;
4043 Py_INCREF(base);
4044 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004045
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004046 /* Now the only way base can still be NULL is if type is
4047 * &PyBaseObject_Type.
4048 */
Guido van Rossum692cdbc2006-03-10 02:04:28 +00004049
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004050 /* Initialize the base class */
4051 if (base != NULL && base->tp_dict == NULL) {
4052 if (PyType_Ready(base) < 0)
4053 goto error;
4054 }
Guido van Rossum323a9cf2002-08-14 17:26:30 +00004055
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004056 /* Initialize ob_type if NULL. This means extensions that want to be
4057 compilable separately on Windows can call PyType_Ready() instead of
4058 initializing the ob_type field of their type objects. */
4059 /* The test for base != NULL is really unnecessary, since base is only
4060 NULL when type is &PyBaseObject_Type, and we know its ob_type is
4061 not NULL (it's initialized to &PyType_Type). But coverity doesn't
4062 know that. */
4063 if (Py_TYPE(type) == NULL && base != NULL)
4064 Py_TYPE(type) = Py_TYPE(base);
Guido van Rossum0986d822002-04-08 01:38:42 +00004065
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004066 /* Initialize tp_bases */
4067 bases = type->tp_bases;
4068 if (bases == NULL) {
4069 if (base == NULL)
4070 bases = PyTuple_New(0);
4071 else
4072 bases = PyTuple_Pack(1, base);
4073 if (bases == NULL)
4074 goto error;
4075 type->tp_bases = bases;
4076 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004077
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004078 /* Initialize tp_dict */
4079 dict = type->tp_dict;
4080 if (dict == NULL) {
4081 dict = PyDict_New();
4082 if (dict == NULL)
4083 goto error;
4084 type->tp_dict = dict;
4085 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004086
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004087 /* Add type-specific descriptors to tp_dict */
4088 if (add_operators(type) < 0)
4089 goto error;
4090 if (type->tp_methods != NULL) {
4091 if (add_methods(type, type->tp_methods) < 0)
4092 goto error;
4093 }
4094 if (type->tp_members != NULL) {
4095 if (add_members(type, type->tp_members) < 0)
4096 goto error;
4097 }
4098 if (type->tp_getset != NULL) {
4099 if (add_getset(type, type->tp_getset) < 0)
4100 goto error;
4101 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004102
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004103 /* Calculate method resolution order */
4104 if (mro_internal(type) < 0) {
4105 goto error;
4106 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004107
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004108 /* Inherit special flags from dominant base */
4109 if (type->tp_base != NULL)
4110 inherit_special(type, type->tp_base);
Guido van Rossum13d52f02001-08-10 21:24:08 +00004111
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004112 /* Initialize tp_dict properly */
4113 bases = type->tp_mro;
4114 assert(bases != NULL);
4115 assert(PyTuple_Check(bases));
4116 n = PyTuple_GET_SIZE(bases);
4117 for (i = 1; i < n; i++) {
4118 PyObject *b = PyTuple_GET_ITEM(bases, i);
4119 if (PyType_Check(b))
4120 inherit_slots(type, (PyTypeObject *)b);
4121 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004122
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004123 /* Sanity check for tp_free. */
4124 if (PyType_IS_GC(type) && (type->tp_flags & Py_TPFLAGS_BASETYPE) &&
4125 (type->tp_free == NULL || type->tp_free == PyObject_Del)) {
4126 /* This base class needs to call tp_free, but doesn't have
4127 * one, or its tp_free is for non-gc'ed objects.
4128 */
4129 PyErr_Format(PyExc_TypeError, "type '%.100s' participates in "
4130 "gc and is a base type but has inappropriate "
4131 "tp_free slot",
4132 type->tp_name);
4133 goto error;
4134 }
Tim Peters3cfe7542003-05-21 21:29:48 +00004135
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004136 /* if the type dictionary doesn't contain a __doc__, set it from
4137 the tp_doc slot.
4138 */
4139 if (PyDict_GetItemString(type->tp_dict, "__doc__") == NULL) {
4140 if (type->tp_doc != NULL) {
4141 PyObject *doc = PyUnicode_FromString(type->tp_doc);
4142 if (doc == NULL)
4143 goto error;
4144 PyDict_SetItemString(type->tp_dict, "__doc__", doc);
4145 Py_DECREF(doc);
4146 } else {
4147 PyDict_SetItemString(type->tp_dict,
4148 "__doc__", Py_None);
4149 }
4150 }
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00004151
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004152 /* Hack for tp_hash and __hash__.
4153 If after all that, tp_hash is still NULL, and __hash__ is not in
4154 tp_dict, set tp_hash to PyObject_HashNotImplemented and
4155 tp_dict['__hash__'] equal to None.
4156 This signals that __hash__ is not inherited.
4157 */
4158 if (type->tp_hash == NULL) {
4159 if (PyDict_GetItemString(type->tp_dict, "__hash__") == NULL) {
4160 if (PyDict_SetItemString(type->tp_dict, "__hash__", Py_None) < 0)
4161 goto error;
4162 type->tp_hash = PyObject_HashNotImplemented;
4163 }
4164 }
Guido van Rossum38938152006-08-21 23:36:26 +00004165
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004166 /* Some more special stuff */
4167 base = type->tp_base;
4168 if (base != NULL) {
4169 if (type->tp_as_number == NULL)
4170 type->tp_as_number = base->tp_as_number;
4171 if (type->tp_as_sequence == NULL)
4172 type->tp_as_sequence = base->tp_as_sequence;
4173 if (type->tp_as_mapping == NULL)
4174 type->tp_as_mapping = base->tp_as_mapping;
4175 if (type->tp_as_buffer == NULL)
4176 type->tp_as_buffer = base->tp_as_buffer;
4177 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004178
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004179 /* Link into each base class's list of subclasses */
4180 bases = type->tp_bases;
4181 n = PyTuple_GET_SIZE(bases);
4182 for (i = 0; i < n; i++) {
4183 PyObject *b = PyTuple_GET_ITEM(bases, i);
4184 if (PyType_Check(b) &&
4185 add_subclass((PyTypeObject *)b, type) < 0)
4186 goto error;
4187 }
Guido van Rossum1c450732001-10-08 15:18:27 +00004188
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004189 /* Warn for a type that implements tp_compare (now known as
4190 tp_reserved) but not tp_richcompare. */
4191 if (type->tp_reserved && !type->tp_richcompare) {
4192 int error;
Victor Stinner4a2b7a12010-08-13 14:03:48 +00004193 error = PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
4194 "Type %.100s defines tp_reserved (formerly tp_compare) "
4195 "but not tp_richcompare. Comparisons may not behave as intended.",
4196 type->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004197 if (error == -1)
4198 goto error;
4199 }
Mark Dickinson2a7d45b2009-02-08 11:02:10 +00004200
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004201 /* All done -- set the ready flag */
4202 assert(type->tp_dict != NULL);
4203 type->tp_flags =
4204 (type->tp_flags & ~Py_TPFLAGS_READYING) | Py_TPFLAGS_READY;
4205 return 0;
Guido van Rossumd614f972001-08-10 17:39:49 +00004206
4207 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004208 type->tp_flags &= ~Py_TPFLAGS_READYING;
4209 return -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004210}
4211
Guido van Rossum1c450732001-10-08 15:18:27 +00004212static int
4213add_subclass(PyTypeObject *base, PyTypeObject *type)
4214{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004215 Py_ssize_t i;
4216 int result;
4217 PyObject *list, *ref, *newobj;
Guido van Rossum1c450732001-10-08 15:18:27 +00004218
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004219 list = base->tp_subclasses;
4220 if (list == NULL) {
4221 base->tp_subclasses = list = PyList_New(0);
4222 if (list == NULL)
4223 return -1;
4224 }
4225 assert(PyList_Check(list));
4226 newobj = PyWeakref_NewRef((PyObject *)type, NULL);
4227 i = PyList_GET_SIZE(list);
4228 while (--i >= 0) {
4229 ref = PyList_GET_ITEM(list, i);
4230 assert(PyWeakref_CheckRef(ref));
4231 if (PyWeakref_GET_OBJECT(ref) == Py_None)
4232 return PyList_SetItem(list, i, newobj);
4233 }
4234 result = PyList_Append(list, newobj);
4235 Py_DECREF(newobj);
4236 return result;
Guido van Rossum1c450732001-10-08 15:18:27 +00004237}
4238
Michael W. Hudson98bbc492002-11-26 14:47:27 +00004239static void
4240remove_subclass(PyTypeObject *base, PyTypeObject *type)
4241{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004242 Py_ssize_t i;
4243 PyObject *list, *ref;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00004244
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004245 list = base->tp_subclasses;
4246 if (list == NULL) {
4247 return;
4248 }
4249 assert(PyList_Check(list));
4250 i = PyList_GET_SIZE(list);
4251 while (--i >= 0) {
4252 ref = PyList_GET_ITEM(list, i);
4253 assert(PyWeakref_CheckRef(ref));
4254 if (PyWeakref_GET_OBJECT(ref) == (PyObject*)type) {
4255 /* this can't fail, right? */
4256 PySequence_DelItem(list, i);
4257 return;
4258 }
4259 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +00004260}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004261
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004262static int
4263check_num_args(PyObject *ob, int n)
4264{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004265 if (!PyTuple_CheckExact(ob)) {
4266 PyErr_SetString(PyExc_SystemError,
4267 "PyArg_UnpackTuple() argument list is not a tuple");
4268 return 0;
4269 }
4270 if (n == PyTuple_GET_SIZE(ob))
4271 return 1;
4272 PyErr_Format(
4273 PyExc_TypeError,
4274 "expected %d arguments, got %zd", n, PyTuple_GET_SIZE(ob));
4275 return 0;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004276}
4277
Tim Peters6d6c1a32001-08-02 04:15:00 +00004278/* Generic wrappers for overloadable 'operators' such as __getitem__ */
4279
4280/* There's a wrapper *function* for each distinct function typedef used
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004281 for type object slots (e.g. binaryfunc, ternaryfunc, etc.). There's a
Tim Peters6d6c1a32001-08-02 04:15:00 +00004282 wrapper *table* for each distinct operation (e.g. __len__, __add__).
4283 Most tables have only one entry; the tables for binary operators have two
4284 entries, one regular and one with reversed arguments. */
4285
4286static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00004287wrap_lenfunc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004288{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004289 lenfunc func = (lenfunc)wrapped;
4290 Py_ssize_t res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004291
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004292 if (!check_num_args(args, 0))
4293 return NULL;
4294 res = (*func)(self);
4295 if (res == -1 && PyErr_Occurred())
4296 return NULL;
4297 return PyLong_FromLong((long)res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004298}
4299
Tim Peters6d6c1a32001-08-02 04:15:00 +00004300static PyObject *
Raymond Hettingerf34f2642003-10-11 17:29:04 +00004301wrap_inquirypred(PyObject *self, PyObject *args, void *wrapped)
4302{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004303 inquiry func = (inquiry)wrapped;
4304 int res;
Raymond Hettingerf34f2642003-10-11 17:29:04 +00004305
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004306 if (!check_num_args(args, 0))
4307 return NULL;
4308 res = (*func)(self);
4309 if (res == -1 && PyErr_Occurred())
4310 return NULL;
4311 return PyBool_FromLong((long)res);
Raymond Hettingerf34f2642003-10-11 17:29:04 +00004312}
4313
4314static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00004315wrap_binaryfunc(PyObject *self, PyObject *args, void *wrapped)
4316{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004317 binaryfunc func = (binaryfunc)wrapped;
4318 PyObject *other;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004319
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004320 if (!check_num_args(args, 1))
4321 return NULL;
4322 other = PyTuple_GET_ITEM(args, 0);
4323 return (*func)(self, other);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004324}
4325
4326static PyObject *
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00004327wrap_binaryfunc_l(PyObject *self, PyObject *args, void *wrapped)
4328{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004329 binaryfunc func = (binaryfunc)wrapped;
4330 PyObject *other;
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00004331
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004332 if (!check_num_args(args, 1))
4333 return NULL;
4334 other = PyTuple_GET_ITEM(args, 0);
4335 return (*func)(self, other);
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00004336}
4337
4338static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00004339wrap_binaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
4340{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004341 binaryfunc func = (binaryfunc)wrapped;
4342 PyObject *other;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004343
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004344 if (!check_num_args(args, 1))
4345 return NULL;
4346 other = PyTuple_GET_ITEM(args, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004347 return (*func)(other, self);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004348}
4349
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004350static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00004351wrap_ternaryfunc(PyObject *self, PyObject *args, void *wrapped)
4352{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004353 ternaryfunc func = (ternaryfunc)wrapped;
4354 PyObject *other;
4355 PyObject *third = Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004356
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004357 /* Note: This wrapper only works for __pow__() */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004358
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004359 if (!PyArg_UnpackTuple(args, "", 1, 2, &other, &third))
4360 return NULL;
4361 return (*func)(self, other, third);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004362}
4363
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00004364static PyObject *
4365wrap_ternaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
4366{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004367 ternaryfunc func = (ternaryfunc)wrapped;
4368 PyObject *other;
4369 PyObject *third = Py_None;
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00004370
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004371 /* Note: This wrapper only works for __pow__() */
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00004372
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004373 if (!PyArg_UnpackTuple(args, "", 1, 2, &other, &third))
4374 return NULL;
4375 return (*func)(other, self, third);
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00004376}
4377
Tim Peters6d6c1a32001-08-02 04:15:00 +00004378static PyObject *
4379wrap_unaryfunc(PyObject *self, PyObject *args, void *wrapped)
4380{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004381 unaryfunc func = (unaryfunc)wrapped;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004382
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004383 if (!check_num_args(args, 0))
4384 return NULL;
4385 return (*func)(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004386}
4387
Tim Peters6d6c1a32001-08-02 04:15:00 +00004388static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004389wrap_indexargfunc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004390{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004391 ssizeargfunc func = (ssizeargfunc)wrapped;
4392 PyObject* o;
4393 Py_ssize_t i;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004394
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004395 if (!PyArg_UnpackTuple(args, "", 1, 1, &o))
4396 return NULL;
4397 i = PyNumber_AsSsize_t(o, PyExc_OverflowError);
4398 if (i == -1 && PyErr_Occurred())
4399 return NULL;
4400 return (*func)(self, i);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004401}
4402
Martin v. Löwis18e16552006-02-15 17:27:45 +00004403static Py_ssize_t
Guido van Rossum5d815f32001-08-17 21:57:47 +00004404getindex(PyObject *self, PyObject *arg)
4405{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004406 Py_ssize_t i;
Guido van Rossum5d815f32001-08-17 21:57:47 +00004407
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004408 i = PyNumber_AsSsize_t(arg, PyExc_OverflowError);
4409 if (i == -1 && PyErr_Occurred())
4410 return -1;
4411 if (i < 0) {
4412 PySequenceMethods *sq = Py_TYPE(self)->tp_as_sequence;
4413 if (sq && sq->sq_length) {
4414 Py_ssize_t n = (*sq->sq_length)(self);
4415 if (n < 0)
4416 return -1;
4417 i += n;
4418 }
4419 }
4420 return i;
Guido van Rossum5d815f32001-08-17 21:57:47 +00004421}
4422
4423static PyObject *
4424wrap_sq_item(PyObject *self, PyObject *args, void *wrapped)
4425{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004426 ssizeargfunc func = (ssizeargfunc)wrapped;
4427 PyObject *arg;
4428 Py_ssize_t i;
Guido van Rossum5d815f32001-08-17 21:57:47 +00004429
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004430 if (PyTuple_GET_SIZE(args) == 1) {
4431 arg = PyTuple_GET_ITEM(args, 0);
4432 i = getindex(self, arg);
4433 if (i == -1 && PyErr_Occurred())
4434 return NULL;
4435 return (*func)(self, i);
4436 }
4437 check_num_args(args, 1);
4438 assert(PyErr_Occurred());
4439 return NULL;
Guido van Rossum5d815f32001-08-17 21:57:47 +00004440}
4441
Tim Peters6d6c1a32001-08-02 04:15:00 +00004442static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00004443wrap_sq_setitem(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004444{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004445 ssizeobjargproc func = (ssizeobjargproc)wrapped;
4446 Py_ssize_t i;
4447 int res;
4448 PyObject *arg, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004449
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004450 if (!PyArg_UnpackTuple(args, "", 2, 2, &arg, &value))
4451 return NULL;
4452 i = getindex(self, arg);
4453 if (i == -1 && PyErr_Occurred())
4454 return NULL;
4455 res = (*func)(self, i, value);
4456 if (res == -1 && PyErr_Occurred())
4457 return NULL;
4458 Py_INCREF(Py_None);
4459 return Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004460}
4461
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004462static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00004463wrap_sq_delitem(PyObject *self, PyObject *args, void *wrapped)
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004464{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004465 ssizeobjargproc func = (ssizeobjargproc)wrapped;
4466 Py_ssize_t i;
4467 int res;
4468 PyObject *arg;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004469
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004470 if (!check_num_args(args, 1))
4471 return NULL;
4472 arg = PyTuple_GET_ITEM(args, 0);
4473 i = getindex(self, arg);
4474 if (i == -1 && PyErr_Occurred())
4475 return NULL;
4476 res = (*func)(self, i, NULL);
4477 if (res == -1 && PyErr_Occurred())
4478 return NULL;
4479 Py_INCREF(Py_None);
4480 return Py_None;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004481}
4482
Tim Peters6d6c1a32001-08-02 04:15:00 +00004483/* XXX objobjproc is a misnomer; should be objargpred */
4484static PyObject *
4485wrap_objobjproc(PyObject *self, PyObject *args, void *wrapped)
4486{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004487 objobjproc func = (objobjproc)wrapped;
4488 int res;
4489 PyObject *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004490
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004491 if (!check_num_args(args, 1))
4492 return NULL;
4493 value = PyTuple_GET_ITEM(args, 0);
4494 res = (*func)(self, value);
4495 if (res == -1 && PyErr_Occurred())
4496 return NULL;
4497 else
4498 return PyBool_FromLong(res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004499}
4500
Tim Peters6d6c1a32001-08-02 04:15:00 +00004501static PyObject *
4502wrap_objobjargproc(PyObject *self, PyObject *args, void *wrapped)
4503{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004504 objobjargproc func = (objobjargproc)wrapped;
4505 int res;
4506 PyObject *key, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004507
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004508 if (!PyArg_UnpackTuple(args, "", 2, 2, &key, &value))
4509 return NULL;
4510 res = (*func)(self, key, value);
4511 if (res == -1 && PyErr_Occurred())
4512 return NULL;
4513 Py_INCREF(Py_None);
4514 return Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004515}
4516
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004517static PyObject *
4518wrap_delitem(PyObject *self, PyObject *args, void *wrapped)
4519{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004520 objobjargproc func = (objobjargproc)wrapped;
4521 int res;
4522 PyObject *key;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004523
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004524 if (!check_num_args(args, 1))
4525 return NULL;
4526 key = PyTuple_GET_ITEM(args, 0);
4527 res = (*func)(self, key, NULL);
4528 if (res == -1 && PyErr_Occurred())
4529 return NULL;
4530 Py_INCREF(Py_None);
4531 return Py_None;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004532}
4533
Guido van Rossum4dcdb782003-04-14 21:46:03 +00004534/* Helper to check for object.__setattr__ or __delattr__ applied to a type.
Guido van Rossum52b27052003-04-15 20:05:10 +00004535 This is called the Carlo Verre hack after its discoverer. */
Guido van Rossum4dcdb782003-04-14 21:46:03 +00004536static int
4537hackcheck(PyObject *self, setattrofunc func, char *what)
4538{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004539 PyTypeObject *type = Py_TYPE(self);
4540 while (type && type->tp_flags & Py_TPFLAGS_HEAPTYPE)
4541 type = type->tp_base;
4542 /* If type is NULL now, this is a really weird type.
4543 In the spirit of backwards compatibility (?), just shut up. */
4544 if (type && type->tp_setattro != func) {
4545 PyErr_Format(PyExc_TypeError,
4546 "can't apply this %s to %s object",
4547 what,
4548 type->tp_name);
4549 return 0;
4550 }
4551 return 1;
Guido van Rossum4dcdb782003-04-14 21:46:03 +00004552}
4553
Tim Peters6d6c1a32001-08-02 04:15:00 +00004554static PyObject *
4555wrap_setattr(PyObject *self, PyObject *args, void *wrapped)
4556{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004557 setattrofunc func = (setattrofunc)wrapped;
4558 int res;
4559 PyObject *name, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004560
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004561 if (!PyArg_UnpackTuple(args, "", 2, 2, &name, &value))
4562 return NULL;
4563 if (!hackcheck(self, func, "__setattr__"))
4564 return NULL;
4565 res = (*func)(self, name, value);
4566 if (res < 0)
4567 return NULL;
4568 Py_INCREF(Py_None);
4569 return Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004570}
4571
4572static PyObject *
4573wrap_delattr(PyObject *self, PyObject *args, void *wrapped)
4574{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004575 setattrofunc func = (setattrofunc)wrapped;
4576 int res;
4577 PyObject *name;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004578
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004579 if (!check_num_args(args, 1))
4580 return NULL;
4581 name = PyTuple_GET_ITEM(args, 0);
4582 if (!hackcheck(self, func, "__delattr__"))
4583 return NULL;
4584 res = (*func)(self, name, NULL);
4585 if (res < 0)
4586 return NULL;
4587 Py_INCREF(Py_None);
4588 return Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004589}
4590
Tim Peters6d6c1a32001-08-02 04:15:00 +00004591static PyObject *
4592wrap_hashfunc(PyObject *self, PyObject *args, void *wrapped)
4593{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004594 hashfunc func = (hashfunc)wrapped;
Benjamin Peterson8035bc52010-10-23 16:20:50 +00004595 Py_hash_t res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004596
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004597 if (!check_num_args(args, 0))
4598 return NULL;
4599 res = (*func)(self);
4600 if (res == -1 && PyErr_Occurred())
4601 return NULL;
Benjamin Peterson8035bc52010-10-23 16:20:50 +00004602 return PyLong_FromSsize_t(res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004603}
4604
Tim Peters6d6c1a32001-08-02 04:15:00 +00004605static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00004606wrap_call(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004607{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004608 ternaryfunc func = (ternaryfunc)wrapped;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004609
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004610 return (*func)(self, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004611}
4612
Tim Peters6d6c1a32001-08-02 04:15:00 +00004613static PyObject *
4614wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op)
4615{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004616 richcmpfunc func = (richcmpfunc)wrapped;
4617 PyObject *other;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004618
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004619 if (!check_num_args(args, 1))
4620 return NULL;
4621 other = PyTuple_GET_ITEM(args, 0);
4622 return (*func)(self, other, op);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004623}
4624
4625#undef RICHCMP_WRAPPER
4626#define RICHCMP_WRAPPER(NAME, OP) \
4627static PyObject * \
4628richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \
4629{ \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004630 return wrap_richcmpfunc(self, args, wrapped, OP); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004631}
4632
Jack Jansen8e938b42001-08-08 15:29:49 +00004633RICHCMP_WRAPPER(lt, Py_LT)
4634RICHCMP_WRAPPER(le, Py_LE)
4635RICHCMP_WRAPPER(eq, Py_EQ)
4636RICHCMP_WRAPPER(ne, Py_NE)
4637RICHCMP_WRAPPER(gt, Py_GT)
4638RICHCMP_WRAPPER(ge, Py_GE)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004639
Tim Peters6d6c1a32001-08-02 04:15:00 +00004640static PyObject *
4641wrap_next(PyObject *self, PyObject *args, void *wrapped)
4642{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004643 unaryfunc func = (unaryfunc)wrapped;
4644 PyObject *res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004645
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004646 if (!check_num_args(args, 0))
4647 return NULL;
4648 res = (*func)(self);
4649 if (res == NULL && !PyErr_Occurred())
4650 PyErr_SetNone(PyExc_StopIteration);
4651 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004652}
4653
Tim Peters6d6c1a32001-08-02 04:15:00 +00004654static PyObject *
4655wrap_descr_get(PyObject *self, PyObject *args, void *wrapped)
4656{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004657 descrgetfunc func = (descrgetfunc)wrapped;
4658 PyObject *obj;
4659 PyObject *type = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004660
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004661 if (!PyArg_UnpackTuple(args, "", 1, 2, &obj, &type))
4662 return NULL;
4663 if (obj == Py_None)
4664 obj = NULL;
4665 if (type == Py_None)
4666 type = NULL;
4667 if (type == NULL &&obj == NULL) {
4668 PyErr_SetString(PyExc_TypeError,
4669 "__get__(None, None) is invalid");
4670 return NULL;
4671 }
4672 return (*func)(self, obj, type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004673}
4674
Tim Peters6d6c1a32001-08-02 04:15:00 +00004675static PyObject *
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004676wrap_descr_set(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004677{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004678 descrsetfunc func = (descrsetfunc)wrapped;
4679 PyObject *obj, *value;
4680 int ret;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004681
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004682 if (!PyArg_UnpackTuple(args, "", 2, 2, &obj, &value))
4683 return NULL;
4684 ret = (*func)(self, obj, value);
4685 if (ret < 0)
4686 return NULL;
4687 Py_INCREF(Py_None);
4688 return Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004689}
Guido van Rossum22b13872002-08-06 21:41:44 +00004690
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00004691static PyObject *
4692wrap_descr_delete(PyObject *self, PyObject *args, void *wrapped)
4693{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004694 descrsetfunc func = (descrsetfunc)wrapped;
4695 PyObject *obj;
4696 int ret;
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00004697
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004698 if (!check_num_args(args, 1))
4699 return NULL;
4700 obj = PyTuple_GET_ITEM(args, 0);
4701 ret = (*func)(self, obj, NULL);
4702 if (ret < 0)
4703 return NULL;
4704 Py_INCREF(Py_None);
4705 return Py_None;
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00004706}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004707
Tim Peters6d6c1a32001-08-02 04:15:00 +00004708static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00004709wrap_init(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004710{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004711 initproc func = (initproc)wrapped;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004712
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004713 if (func(self, args, kwds) < 0)
4714 return NULL;
4715 Py_INCREF(Py_None);
4716 return Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004717}
4718
Tim Peters6d6c1a32001-08-02 04:15:00 +00004719static PyObject *
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004720tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004721{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004722 PyTypeObject *type, *subtype, *staticbase;
4723 PyObject *arg0, *res;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004724
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004725 if (self == NULL || !PyType_Check(self))
4726 Py_FatalError("__new__() called with non-type 'self'");
4727 type = (PyTypeObject *)self;
4728 if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) {
4729 PyErr_Format(PyExc_TypeError,
4730 "%s.__new__(): not enough arguments",
4731 type->tp_name);
4732 return NULL;
4733 }
4734 arg0 = PyTuple_GET_ITEM(args, 0);
4735 if (!PyType_Check(arg0)) {
4736 PyErr_Format(PyExc_TypeError,
4737 "%s.__new__(X): X is not a type object (%s)",
4738 type->tp_name,
4739 Py_TYPE(arg0)->tp_name);
4740 return NULL;
4741 }
4742 subtype = (PyTypeObject *)arg0;
4743 if (!PyType_IsSubtype(subtype, type)) {
4744 PyErr_Format(PyExc_TypeError,
4745 "%s.__new__(%s): %s is not a subtype of %s",
4746 type->tp_name,
4747 subtype->tp_name,
4748 subtype->tp_name,
4749 type->tp_name);
4750 return NULL;
4751 }
Barry Warsaw60f01882001-08-22 19:24:42 +00004752
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004753 /* Check that the use doesn't do something silly and unsafe like
4754 object.__new__(dict). To do this, we check that the
4755 most derived base that's not a heap type is this type. */
4756 staticbase = subtype;
4757 while (staticbase && (staticbase->tp_flags & Py_TPFLAGS_HEAPTYPE))
4758 staticbase = staticbase->tp_base;
4759 /* If staticbase is NULL now, it is a really weird type.
4760 In the spirit of backwards compatibility (?), just shut up. */
4761 if (staticbase && staticbase->tp_new != type->tp_new) {
4762 PyErr_Format(PyExc_TypeError,
4763 "%s.__new__(%s) is not safe, use %s.__new__()",
4764 type->tp_name,
4765 subtype->tp_name,
4766 staticbase == NULL ? "?" : staticbase->tp_name);
4767 return NULL;
4768 }
Barry Warsaw60f01882001-08-22 19:24:42 +00004769
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004770 args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
4771 if (args == NULL)
4772 return NULL;
4773 res = type->tp_new(subtype, args, kwds);
4774 Py_DECREF(args);
4775 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004776}
4777
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004778static struct PyMethodDef tp_new_methoddef[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004779 {"__new__", (PyCFunction)tp_new_wrapper, METH_VARARGS|METH_KEYWORDS,
4780 PyDoc_STR("T.__new__(S, ...) -> "
4781 "a new object with type S, a subtype of T")},
4782 {0}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004783};
4784
4785static int
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004786add_tp_new_wrapper(PyTypeObject *type)
4787{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004788 PyObject *func;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004789
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004790 if (PyDict_GetItemString(type->tp_dict, "__new__") != NULL)
4791 return 0;
4792 func = PyCFunction_New(tp_new_methoddef, (PyObject *)type);
4793 if (func == NULL)
4794 return -1;
4795 if (PyDict_SetItemString(type->tp_dict, "__new__", func)) {
4796 Py_DECREF(func);
4797 return -1;
4798 }
4799 Py_DECREF(func);
4800 return 0;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004801}
4802
Guido van Rossumf040ede2001-08-07 16:40:56 +00004803/* Slot wrappers that call the corresponding __foo__ slot. See comments
4804 below at override_slots() for more explanation. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004805
Guido van Rossumdc91b992001-08-08 22:26:22 +00004806#define SLOT0(FUNCNAME, OPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004807static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004808FUNCNAME(PyObject *self) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004809{ \
Benjamin Petersonce798522012-01-22 11:24:29 -05004810 _Py_static_string(id, OPSTR); \
4811 return call_method(self, &id, "()"); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004812}
4813
Guido van Rossumdc91b992001-08-08 22:26:22 +00004814#define SLOT1(FUNCNAME, OPSTR, ARG1TYPE, ARGCODES) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004815static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004816FUNCNAME(PyObject *self, ARG1TYPE arg1) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004817{ \
Benjamin Petersonce798522012-01-22 11:24:29 -05004818 _Py_static_string(id, OPSTR); \
4819 return call_method(self, &id, "(" ARGCODES ")", arg1); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004820}
4821
Guido van Rossumcd118802003-01-06 22:57:47 +00004822/* Boolean helper for SLOT1BINFULL().
4823 right.__class__ is a nontrivial subclass of left.__class__. */
4824static int
4825method_is_overloaded(PyObject *left, PyObject *right, char *name)
4826{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004827 PyObject *a, *b;
4828 int ok;
Guido van Rossumcd118802003-01-06 22:57:47 +00004829
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004830 b = PyObject_GetAttrString((PyObject *)(Py_TYPE(right)), name);
4831 if (b == NULL) {
4832 PyErr_Clear();
4833 /* If right doesn't have it, it's not overloaded */
4834 return 0;
4835 }
Guido van Rossumcd118802003-01-06 22:57:47 +00004836
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004837 a = PyObject_GetAttrString((PyObject *)(Py_TYPE(left)), name);
4838 if (a == NULL) {
4839 PyErr_Clear();
4840 Py_DECREF(b);
4841 /* If right has it but left doesn't, it's overloaded */
4842 return 1;
4843 }
Guido van Rossumcd118802003-01-06 22:57:47 +00004844
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004845 ok = PyObject_RichCompareBool(a, b, Py_NE);
4846 Py_DECREF(a);
4847 Py_DECREF(b);
4848 if (ok < 0) {
4849 PyErr_Clear();
4850 return 0;
4851 }
Guido van Rossumcd118802003-01-06 22:57:47 +00004852
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004853 return ok;
Guido van Rossumcd118802003-01-06 22:57:47 +00004854}
4855
Guido van Rossumdc91b992001-08-08 22:26:22 +00004856
4857#define SLOT1BINFULL(FUNCNAME, TESTFUNC, SLOTNAME, OPSTR, ROPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004858static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004859FUNCNAME(PyObject *self, PyObject *other) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004860{ \
Benjamin Petersonce798522012-01-22 11:24:29 -05004861 _Py_static_string(op_id, OPSTR); \
4862 _Py_static_string(rop_id, ROPSTR); \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004863 int do_other = Py_TYPE(self) != Py_TYPE(other) && \
4864 Py_TYPE(other)->tp_as_number != NULL && \
4865 Py_TYPE(other)->tp_as_number->SLOTNAME == TESTFUNC; \
4866 if (Py_TYPE(self)->tp_as_number != NULL && \
4867 Py_TYPE(self)->tp_as_number->SLOTNAME == TESTFUNC) { \
4868 PyObject *r; \
4869 if (do_other && \
4870 PyType_IsSubtype(Py_TYPE(other), Py_TYPE(self)) && \
4871 method_is_overloaded(self, other, ROPSTR)) { \
Benjamin Petersonce798522012-01-22 11:24:29 -05004872 r = call_maybe(other, &rop_id, "(O)", self); \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004873 if (r != Py_NotImplemented) \
4874 return r; \
4875 Py_DECREF(r); \
4876 do_other = 0; \
4877 } \
Benjamin Petersonce798522012-01-22 11:24:29 -05004878 r = call_maybe(self, &op_id, "(O)", other); \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004879 if (r != Py_NotImplemented || \
4880 Py_TYPE(other) == Py_TYPE(self)) \
4881 return r; \
4882 Py_DECREF(r); \
4883 } \
4884 if (do_other) { \
Benjamin Petersonce798522012-01-22 11:24:29 -05004885 return call_maybe(other, &rop_id, "(O)", self); \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004886 } \
Brian Curtindfc80e32011-08-10 20:28:54 -05004887 Py_RETURN_NOTIMPLEMENTED; \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004888}
4889
4890#define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004891 SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR)
Guido van Rossumdc91b992001-08-08 22:26:22 +00004892
4893#define SLOT2(FUNCNAME, OPSTR, ARG1TYPE, ARG2TYPE, ARGCODES) \
4894static PyObject * \
4895FUNCNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \
4896{ \
Benjamin Petersonce798522012-01-22 11:24:29 -05004897 _Py_static_string(id, #OPSTR); \
4898 return call_method(self, &id, "(" ARGCODES ")", arg1, arg2); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004899}
4900
Martin v. Löwis18e16552006-02-15 17:27:45 +00004901static Py_ssize_t
Tim Peters6d6c1a32001-08-02 04:15:00 +00004902slot_sq_length(PyObject *self)
4903{
Benjamin Petersonce798522012-01-22 11:24:29 -05004904 _Py_IDENTIFIER(__len__);
4905 PyObject *res = call_method(self, &PyId___len__, "()");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004906 Py_ssize_t len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004907
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004908 if (res == NULL)
4909 return -1;
4910 len = PyNumber_AsSsize_t(res, PyExc_OverflowError);
4911 Py_DECREF(res);
4912 if (len < 0) {
4913 if (!PyErr_Occurred())
4914 PyErr_SetString(PyExc_ValueError,
4915 "__len__() should return >= 0");
4916 return -1;
4917 }
4918 return len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004919}
4920
Guido van Rossumf4593e02001-10-03 12:09:30 +00004921/* Super-optimized version of slot_sq_item.
4922 Other slots could do the same... */
4923static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00004924slot_sq_item(PyObject *self, Py_ssize_t i)
Guido van Rossumf4593e02001-10-03 12:09:30 +00004925{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004926 static PyObject *getitem_str;
4927 PyObject *func, *args = NULL, *ival = NULL, *retval = NULL;
4928 descrgetfunc f;
Guido van Rossumf4593e02001-10-03 12:09:30 +00004929
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004930 if (getitem_str == NULL) {
4931 getitem_str = PyUnicode_InternFromString("__getitem__");
4932 if (getitem_str == NULL)
4933 return NULL;
4934 }
4935 func = _PyType_Lookup(Py_TYPE(self), getitem_str);
4936 if (func != NULL) {
4937 if ((f = Py_TYPE(func)->tp_descr_get) == NULL)
4938 Py_INCREF(func);
4939 else {
4940 func = f(func, self, (PyObject *)(Py_TYPE(self)));
4941 if (func == NULL) {
4942 return NULL;
4943 }
4944 }
4945 ival = PyLong_FromSsize_t(i);
4946 if (ival != NULL) {
4947 args = PyTuple_New(1);
4948 if (args != NULL) {
4949 PyTuple_SET_ITEM(args, 0, ival);
4950 retval = PyObject_Call(func, args, NULL);
4951 Py_XDECREF(args);
4952 Py_XDECREF(func);
4953 return retval;
4954 }
4955 }
4956 }
4957 else {
4958 PyErr_SetObject(PyExc_AttributeError, getitem_str);
4959 }
4960 Py_XDECREF(args);
4961 Py_XDECREF(ival);
4962 Py_XDECREF(func);
4963 return NULL;
Guido van Rossumf4593e02001-10-03 12:09:30 +00004964}
4965
Tim Peters6d6c1a32001-08-02 04:15:00 +00004966static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00004967slot_sq_ass_item(PyObject *self, Py_ssize_t index, PyObject *value)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004968{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004969 PyObject *res;
Benjamin Petersonce798522012-01-22 11:24:29 -05004970 _Py_IDENTIFIER(__delitem__);
4971 _Py_IDENTIFIER(__setitem__);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004972
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004973 if (value == NULL)
Benjamin Petersonce798522012-01-22 11:24:29 -05004974 res = call_method(self, &PyId___delitem__, "(n)", index);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004975 else
Benjamin Petersonce798522012-01-22 11:24:29 -05004976 res = call_method(self, &PyId___setitem__, "(nO)", index, value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004977 if (res == NULL)
4978 return -1;
4979 Py_DECREF(res);
4980 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004981}
4982
4983static int
Tim Peters6d6c1a32001-08-02 04:15:00 +00004984slot_sq_contains(PyObject *self, PyObject *value)
4985{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004986 PyObject *func, *res, *args;
4987 int result = -1;
Benjamin Petersonce798522012-01-22 11:24:29 -05004988 _Py_IDENTIFIER(__contains__);
Tim Petersbf9b2442003-03-23 05:35:36 +00004989
Benjamin Petersonce798522012-01-22 11:24:29 -05004990 func = lookup_maybe(self, &PyId___contains__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004991 if (func != NULL) {
4992 args = PyTuple_Pack(1, value);
4993 if (args == NULL)
4994 res = NULL;
4995 else {
4996 res = PyObject_Call(func, args, NULL);
4997 Py_DECREF(args);
4998 }
4999 Py_DECREF(func);
5000 if (res != NULL) {
5001 result = PyObject_IsTrue(res);
5002 Py_DECREF(res);
5003 }
5004 }
5005 else if (! PyErr_Occurred()) {
5006 /* Possible results: -1 and 1 */
5007 result = (int)_PySequence_IterSearch(self, value,
5008 PY_ITERSEARCH_CONTAINS);
5009 }
5010 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005011}
5012
Tim Peters6d6c1a32001-08-02 04:15:00 +00005013#define slot_mp_length slot_sq_length
5014
Guido van Rossumdc91b992001-08-08 22:26:22 +00005015SLOT1(slot_mp_subscript, "__getitem__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00005016
5017static int
5018slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value)
5019{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005020 PyObject *res;
Benjamin Petersonce798522012-01-22 11:24:29 -05005021 _Py_IDENTIFIER(__delitem__);
5022 _Py_IDENTIFIER(__setitem__);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005023
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005024 if (value == NULL)
Benjamin Petersonce798522012-01-22 11:24:29 -05005025 res = call_method(self, &PyId___delitem__, "(O)", key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005026 else
Benjamin Petersonce798522012-01-22 11:24:29 -05005027 res = call_method(self, &PyId___setitem__, "(OO)", key, value);
5028
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005029 if (res == NULL)
5030 return -1;
5031 Py_DECREF(res);
5032 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005033}
5034
Guido van Rossumdc91b992001-08-08 22:26:22 +00005035SLOT1BIN(slot_nb_add, nb_add, "__add__", "__radd__")
5036SLOT1BIN(slot_nb_subtract, nb_subtract, "__sub__", "__rsub__")
5037SLOT1BIN(slot_nb_multiply, nb_multiply, "__mul__", "__rmul__")
Guido van Rossumdc91b992001-08-08 22:26:22 +00005038SLOT1BIN(slot_nb_remainder, nb_remainder, "__mod__", "__rmod__")
5039SLOT1BIN(slot_nb_divmod, nb_divmod, "__divmod__", "__rdivmod__")
5040
Jeremy Hylton938ace62002-07-17 16:30:39 +00005041static PyObject *slot_nb_power(PyObject *, PyObject *, PyObject *);
Guido van Rossumdc91b992001-08-08 22:26:22 +00005042
5043SLOT1BINFULL(slot_nb_power_binary, slot_nb_power,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005044 nb_power, "__pow__", "__rpow__")
Guido van Rossumdc91b992001-08-08 22:26:22 +00005045
5046static PyObject *
5047slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus)
5048{
Benjamin Petersonce798522012-01-22 11:24:29 -05005049 _Py_IDENTIFIER(__pow__);
Guido van Rossum2730b132001-08-28 18:22:14 +00005050
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005051 if (modulus == Py_None)
5052 return slot_nb_power_binary(self, other);
5053 /* Three-arg power doesn't use __rpow__. But ternary_op
5054 can call this when the second argument's type uses
5055 slot_nb_power, so check before calling self.__pow__. */
5056 if (Py_TYPE(self)->tp_as_number != NULL &&
5057 Py_TYPE(self)->tp_as_number->nb_power == slot_nb_power) {
Benjamin Petersonce798522012-01-22 11:24:29 -05005058 return call_method(self, &PyId___pow__, "(OO)", other, modulus);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005059 }
Brian Curtindfc80e32011-08-10 20:28:54 -05005060 Py_RETURN_NOTIMPLEMENTED;
Guido van Rossumdc91b992001-08-08 22:26:22 +00005061}
5062
5063SLOT0(slot_nb_negative, "__neg__")
5064SLOT0(slot_nb_positive, "__pos__")
5065SLOT0(slot_nb_absolute, "__abs__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00005066
5067static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00005068slot_nb_bool(PyObject *self)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005069{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005070 PyObject *func, *args;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005071 int result = -1;
5072 int using_len = 0;
Benjamin Petersonce798522012-01-22 11:24:29 -05005073 _Py_IDENTIFIER(__len__);
5074 _Py_IDENTIFIER(__bool__);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005075
Benjamin Petersonce798522012-01-22 11:24:29 -05005076 func = lookup_maybe(self, &PyId___bool__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005077 if (func == NULL) {
5078 if (PyErr_Occurred())
5079 return -1;
Benjamin Petersonce798522012-01-22 11:24:29 -05005080 func = lookup_maybe(self, &PyId___len__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005081 if (func == NULL)
5082 return PyErr_Occurred() ? -1 : 1;
5083 using_len = 1;
5084 }
5085 args = PyTuple_New(0);
5086 if (args != NULL) {
5087 PyObject *temp = PyObject_Call(func, args, NULL);
5088 Py_DECREF(args);
5089 if (temp != NULL) {
5090 if (using_len) {
5091 /* enforced by slot_nb_len */
5092 result = PyObject_IsTrue(temp);
5093 }
5094 else if (PyBool_Check(temp)) {
5095 result = PyObject_IsTrue(temp);
5096 }
5097 else {
5098 PyErr_Format(PyExc_TypeError,
5099 "__bool__ should return "
5100 "bool, returned %s",
5101 Py_TYPE(temp)->tp_name);
5102 result = -1;
5103 }
5104 Py_DECREF(temp);
5105 }
5106 }
5107 Py_DECREF(func);
5108 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005109}
5110
Guido van Rossum38fff8c2006-03-07 18:50:55 +00005111
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00005112static PyObject *
Guido van Rossum38fff8c2006-03-07 18:50:55 +00005113slot_nb_index(PyObject *self)
5114{
Benjamin Petersonce798522012-01-22 11:24:29 -05005115 _Py_IDENTIFIER(__index__);
5116 return call_method(self, &PyId___index__, "()");
Guido van Rossum38fff8c2006-03-07 18:50:55 +00005117}
5118
5119
Guido van Rossumdc91b992001-08-08 22:26:22 +00005120SLOT0(slot_nb_invert, "__invert__")
5121SLOT1BIN(slot_nb_lshift, nb_lshift, "__lshift__", "__rlshift__")
5122SLOT1BIN(slot_nb_rshift, nb_rshift, "__rshift__", "__rrshift__")
5123SLOT1BIN(slot_nb_and, nb_and, "__and__", "__rand__")
5124SLOT1BIN(slot_nb_xor, nb_xor, "__xor__", "__rxor__")
5125SLOT1BIN(slot_nb_or, nb_or, "__or__", "__ror__")
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00005126
Guido van Rossumdc91b992001-08-08 22:26:22 +00005127SLOT0(slot_nb_int, "__int__")
Guido van Rossumdc91b992001-08-08 22:26:22 +00005128SLOT0(slot_nb_float, "__float__")
Guido van Rossumdc91b992001-08-08 22:26:22 +00005129SLOT1(slot_nb_inplace_add, "__iadd__", PyObject *, "O")
5130SLOT1(slot_nb_inplace_subtract, "__isub__", PyObject *, "O")
5131SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *, "O")
Guido van Rossumdc91b992001-08-08 22:26:22 +00005132SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *, "O")
Thomas Wouterscf297e42007-02-23 15:07:44 +00005133/* Can't use SLOT1 here, because nb_inplace_power is ternary */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005134static PyObject *
5135slot_nb_inplace_power(PyObject *self, PyObject * arg1, PyObject *arg2)
5136{
Benjamin Petersonce798522012-01-22 11:24:29 -05005137 _Py_IDENTIFIER(__ipow__);
5138 return call_method(self, &PyId___ipow__, "(" "O" ")", arg1);
Thomas Wouterscf297e42007-02-23 15:07:44 +00005139}
Guido van Rossumdc91b992001-08-08 22:26:22 +00005140SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *, "O")
5141SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *, "O")
5142SLOT1(slot_nb_inplace_and, "__iand__", PyObject *, "O")
5143SLOT1(slot_nb_inplace_xor, "__ixor__", PyObject *, "O")
5144SLOT1(slot_nb_inplace_or, "__ior__", PyObject *, "O")
5145SLOT1BIN(slot_nb_floor_divide, nb_floor_divide,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005146 "__floordiv__", "__rfloordiv__")
Guido van Rossumdc91b992001-08-08 22:26:22 +00005147SLOT1BIN(slot_nb_true_divide, nb_true_divide, "__truediv__", "__rtruediv__")
5148SLOT1(slot_nb_inplace_floor_divide, "__ifloordiv__", PyObject *, "O")
5149SLOT1(slot_nb_inplace_true_divide, "__itruediv__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00005150
Guido van Rossumb8f63662001-08-15 23:57:02 +00005151static PyObject *
5152slot_tp_repr(PyObject *self)
5153{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005154 PyObject *func, *res;
Benjamin Petersonce798522012-01-22 11:24:29 -05005155 _Py_IDENTIFIER(__repr__);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005156
Benjamin Petersonce798522012-01-22 11:24:29 -05005157 func = lookup_method(self, &PyId___repr__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005158 if (func != NULL) {
5159 res = PyEval_CallObject(func, NULL);
5160 Py_DECREF(func);
5161 return res;
5162 }
5163 PyErr_Clear();
5164 return PyUnicode_FromFormat("<%s object at %p>",
5165 Py_TYPE(self)->tp_name, self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005166}
5167
5168static PyObject *
5169slot_tp_str(PyObject *self)
5170{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005171 PyObject *func, *res;
Benjamin Petersonce798522012-01-22 11:24:29 -05005172 _Py_IDENTIFIER(__str__);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005173
Benjamin Petersonce798522012-01-22 11:24:29 -05005174 func = lookup_method(self, &PyId___str__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005175 if (func != NULL) {
5176 res = PyEval_CallObject(func, NULL);
5177 Py_DECREF(func);
5178 return res;
5179 }
5180 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005181 /* PyObject *ress; */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005182 PyErr_Clear();
5183 res = slot_tp_repr(self);
5184 if (!res)
5185 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005186 /* XXX this is non-sensical. Why should we return
5187 a bytes object from __str__. Is this code even
5188 used? - mvl */
5189 assert(0);
5190 return res;
5191 /*
Victor Stinnerf3fd7332011-03-02 01:03:11 +00005192 ress = _PyUnicode_AsDefaultEncodedString(res);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005193 Py_DECREF(res);
5194 return ress;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005195 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005196 }
Guido van Rossumb8f63662001-08-15 23:57:02 +00005197}
Tim Peters6d6c1a32001-08-02 04:15:00 +00005198
Benjamin Peterson8f67d082010-10-17 20:54:53 +00005199static Py_hash_t
Tim Peters6d6c1a32001-08-02 04:15:00 +00005200slot_tp_hash(PyObject *self)
5201{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005202 PyObject *func, *res;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00005203 Py_ssize_t h;
Benjamin Petersonce798522012-01-22 11:24:29 -05005204 _Py_IDENTIFIER(__hash__);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005205
Benjamin Petersonce798522012-01-22 11:24:29 -05005206 func = lookup_method(self, &PyId___hash__);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005207
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005208 if (func == Py_None) {
5209 Py_DECREF(func);
5210 func = NULL;
5211 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +00005212
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005213 if (func == NULL) {
5214 return PyObject_HashNotImplemented(self);
5215 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +00005216
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005217 res = PyEval_CallObject(func, NULL);
5218 Py_DECREF(func);
5219 if (res == NULL)
5220 return -1;
Mark Dickinsondc787d22010-05-23 13:33:13 +00005221
5222 if (!PyLong_Check(res)) {
5223 PyErr_SetString(PyExc_TypeError,
5224 "__hash__ method should return an integer");
5225 return -1;
5226 }
Benjamin Peterson8f67d082010-10-17 20:54:53 +00005227 /* Transform the PyLong `res` to a Py_hash_t `h`. For an existing
5228 hashable Python object x, hash(x) will always lie within the range of
5229 Py_hash_t. Therefore our transformation must preserve values that
5230 already lie within this range, to ensure that if x.__hash__() returns
5231 hash(y) then hash(x) == hash(y). */
5232 h = PyLong_AsSsize_t(res);
5233 if (h == -1 && PyErr_Occurred()) {
5234 /* res was not within the range of a Py_hash_t, so we're free to
Mark Dickinsondc787d22010-05-23 13:33:13 +00005235 use any sufficiently bit-mixing transformation;
5236 long.__hash__ will do nicely. */
Benjamin Peterson8f67d082010-10-17 20:54:53 +00005237 PyErr_Clear();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005238 h = PyLong_Type.tp_hash(res);
Benjamin Peterson8f67d082010-10-17 20:54:53 +00005239 }
Benjamin Petersone7dfeeb2010-10-17 21:27:01 +00005240 /* -1 is reserved for errors. */
5241 if (h == -1)
5242 h = -2;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005243 Py_DECREF(res);
Mark Dickinsondc787d22010-05-23 13:33:13 +00005244 return h;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005245}
5246
5247static PyObject *
5248slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds)
5249{
Benjamin Petersonce798522012-01-22 11:24:29 -05005250 _Py_IDENTIFIER(__call__);
5251 PyObject *meth = lookup_method(self, &PyId___call__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005252 PyObject *res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005253
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005254 if (meth == NULL)
5255 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005256
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005257 res = PyObject_Call(meth, args, kwds);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005258
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005259 Py_DECREF(meth);
5260 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005261}
5262
Guido van Rossum14a6f832001-10-17 13:59:09 +00005263/* There are two slot dispatch functions for tp_getattro.
5264
5265 - slot_tp_getattro() is used when __getattribute__ is overridden
5266 but no __getattr__ hook is present;
5267
5268 - slot_tp_getattr_hook() is used when a __getattr__ hook is present.
5269
Guido van Rossumc334df52002-04-04 23:44:47 +00005270 The code in update_one_slot() always installs slot_tp_getattr_hook(); this
5271 detects the absence of __getattr__ and then installs the simpler slot if
5272 necessary. */
Guido van Rossum14a6f832001-10-17 13:59:09 +00005273
Tim Peters6d6c1a32001-08-02 04:15:00 +00005274static PyObject *
5275slot_tp_getattro(PyObject *self, PyObject *name)
5276{
Benjamin Petersonce798522012-01-22 11:24:29 -05005277 _Py_IDENTIFIER(__getattribute__);
5278 return call_method(self, &PyId___getattribute__, "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005279}
5280
Guido van Rossum19c1cd52001-09-21 21:24:49 +00005281static PyObject *
Benjamin Peterson9262b842008-11-17 22:45:50 +00005282call_attribute(PyObject *self, PyObject *attr, PyObject *name)
5283{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005284 PyObject *res, *descr = NULL;
5285 descrgetfunc f = Py_TYPE(attr)->tp_descr_get;
Benjamin Peterson9262b842008-11-17 22:45:50 +00005286
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005287 if (f != NULL) {
5288 descr = f(attr, self, (PyObject *)(Py_TYPE(self)));
5289 if (descr == NULL)
5290 return NULL;
5291 else
5292 attr = descr;
5293 }
5294 res = PyObject_CallFunctionObjArgs(attr, name, NULL);
5295 Py_XDECREF(descr);
5296 return res;
Benjamin Peterson9262b842008-11-17 22:45:50 +00005297}
5298
5299static PyObject *
Guido van Rossum19c1cd52001-09-21 21:24:49 +00005300slot_tp_getattr_hook(PyObject *self, PyObject *name)
5301{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005302 PyTypeObject *tp = Py_TYPE(self);
5303 PyObject *getattr, *getattribute, *res;
5304 static PyObject *getattribute_str = NULL;
5305 static PyObject *getattr_str = NULL;
Guido van Rossum19c1cd52001-09-21 21:24:49 +00005306
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005307 if (getattr_str == NULL) {
5308 getattr_str = PyUnicode_InternFromString("__getattr__");
5309 if (getattr_str == NULL)
5310 return NULL;
5311 }
5312 if (getattribute_str == NULL) {
5313 getattribute_str =
5314 PyUnicode_InternFromString("__getattribute__");
5315 if (getattribute_str == NULL)
5316 return NULL;
5317 }
5318 /* speed hack: we could use lookup_maybe, but that would resolve the
5319 method fully for each attribute lookup for classes with
5320 __getattr__, even when the attribute is present. So we use
5321 _PyType_Lookup and create the method only when needed, with
5322 call_attribute. */
5323 getattr = _PyType_Lookup(tp, getattr_str);
5324 if (getattr == NULL) {
5325 /* No __getattr__ hook: use a simpler dispatcher */
5326 tp->tp_getattro = slot_tp_getattro;
5327 return slot_tp_getattro(self, name);
5328 }
5329 Py_INCREF(getattr);
5330 /* speed hack: we could use lookup_maybe, but that would resolve the
5331 method fully for each attribute lookup for classes with
5332 __getattr__, even when self has the default __getattribute__
5333 method. So we use _PyType_Lookup and create the method only when
5334 needed, with call_attribute. */
5335 getattribute = _PyType_Lookup(tp, getattribute_str);
5336 if (getattribute == NULL ||
5337 (Py_TYPE(getattribute) == &PyWrapperDescr_Type &&
5338 ((PyWrapperDescrObject *)getattribute)->d_wrapped ==
5339 (void *)PyObject_GenericGetAttr))
5340 res = PyObject_GenericGetAttr(self, name);
5341 else {
5342 Py_INCREF(getattribute);
5343 res = call_attribute(self, getattribute, name);
5344 Py_DECREF(getattribute);
5345 }
5346 if (res == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) {
5347 PyErr_Clear();
5348 res = call_attribute(self, getattr, name);
5349 }
5350 Py_DECREF(getattr);
5351 return res;
Guido van Rossum19c1cd52001-09-21 21:24:49 +00005352}
5353
Tim Peters6d6c1a32001-08-02 04:15:00 +00005354static int
5355slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value)
5356{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005357 PyObject *res;
Benjamin Petersonce798522012-01-22 11:24:29 -05005358 _Py_IDENTIFIER(__delattr__);
5359 _Py_IDENTIFIER(__setattr__);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005360
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005361 if (value == NULL)
Benjamin Petersonce798522012-01-22 11:24:29 -05005362 res = call_method(self, &PyId___delattr__, "(O)", name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005363 else
Benjamin Petersonce798522012-01-22 11:24:29 -05005364 res = call_method(self, &PyId___setattr__, "(OO)", name, value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005365 if (res == NULL)
5366 return -1;
5367 Py_DECREF(res);
5368 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005369}
5370
Benjamin Petersonce798522012-01-22 11:24:29 -05005371static _Py_Identifier name_op[] = {
5372 {0, "__lt__", 0},
5373 {0, "__le__", 0},
5374 {0, "__eq__", 0},
5375 {0, "__ne__", 0},
5376 {0, "__gt__", 0},
5377 {0, "__ge__", 0}
Guido van Rossumf5243f02008-01-01 04:06:48 +00005378};
5379
Tim Peters6d6c1a32001-08-02 04:15:00 +00005380static PyObject *
Mark Dickinson6f1d0492009-11-15 13:58:49 +00005381slot_tp_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005382{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005383 PyObject *func, *args, *res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005384
Benjamin Petersonce798522012-01-22 11:24:29 -05005385 func = lookup_method(self, &name_op[op]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005386 if (func == NULL) {
5387 PyErr_Clear();
Brian Curtindfc80e32011-08-10 20:28:54 -05005388 Py_RETURN_NOTIMPLEMENTED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005389 }
5390 args = PyTuple_Pack(1, other);
5391 if (args == NULL)
5392 res = NULL;
5393 else {
5394 res = PyObject_Call(func, args, NULL);
5395 Py_DECREF(args);
5396 }
5397 Py_DECREF(func);
5398 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005399}
5400
Guido van Rossumb8f63662001-08-15 23:57:02 +00005401static PyObject *
Guido van Rossumb8f63662001-08-15 23:57:02 +00005402slot_tp_iter(PyObject *self)
5403{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005404 PyObject *func, *res;
Benjamin Petersonce798522012-01-22 11:24:29 -05005405 _Py_IDENTIFIER(__iter__);
5406 _Py_IDENTIFIER(__getitem__);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005407
Benjamin Petersonce798522012-01-22 11:24:29 -05005408 func = lookup_method(self, &PyId___iter__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005409 if (func != NULL) {
5410 PyObject *args;
5411 args = res = PyTuple_New(0);
5412 if (args != NULL) {
5413 res = PyObject_Call(func, args, NULL);
5414 Py_DECREF(args);
5415 }
5416 Py_DECREF(func);
5417 return res;
5418 }
5419 PyErr_Clear();
Benjamin Petersonce798522012-01-22 11:24:29 -05005420 func = lookup_method(self, &PyId___getitem__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005421 if (func == NULL) {
5422 PyErr_Format(PyExc_TypeError,
5423 "'%.200s' object is not iterable",
5424 Py_TYPE(self)->tp_name);
5425 return NULL;
5426 }
5427 Py_DECREF(func);
5428 return PySeqIter_New(self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005429}
Tim Peters6d6c1a32001-08-02 04:15:00 +00005430
5431static PyObject *
5432slot_tp_iternext(PyObject *self)
5433{
Benjamin Petersonce798522012-01-22 11:24:29 -05005434 _Py_IDENTIFIER(__next__);
5435 return call_method(self, &PyId___next__, "()");
Tim Peters6d6c1a32001-08-02 04:15:00 +00005436}
5437
Guido van Rossum1a493502001-08-17 16:47:50 +00005438static PyObject *
5439slot_tp_descr_get(PyObject *self, PyObject *obj, PyObject *type)
5440{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005441 PyTypeObject *tp = Py_TYPE(self);
5442 PyObject *get;
5443 static PyObject *get_str = NULL;
Guido van Rossum1a493502001-08-17 16:47:50 +00005444
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005445 if (get_str == NULL) {
5446 get_str = PyUnicode_InternFromString("__get__");
5447 if (get_str == NULL)
5448 return NULL;
5449 }
5450 get = _PyType_Lookup(tp, get_str);
5451 if (get == NULL) {
5452 /* Avoid further slowdowns */
5453 if (tp->tp_descr_get == slot_tp_descr_get)
5454 tp->tp_descr_get = NULL;
5455 Py_INCREF(self);
5456 return self;
5457 }
5458 if (obj == NULL)
5459 obj = Py_None;
5460 if (type == NULL)
5461 type = Py_None;
5462 return PyObject_CallFunctionObjArgs(get, self, obj, type, NULL);
Guido van Rossum1a493502001-08-17 16:47:50 +00005463}
Tim Peters6d6c1a32001-08-02 04:15:00 +00005464
5465static int
5466slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value)
5467{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005468 PyObject *res;
Benjamin Petersonce798522012-01-22 11:24:29 -05005469 _Py_IDENTIFIER(__delete__);
5470 _Py_IDENTIFIER(__set__);
Guido van Rossum2c252392001-08-24 10:13:31 +00005471
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005472 if (value == NULL)
Benjamin Petersonce798522012-01-22 11:24:29 -05005473 res = call_method(self, &PyId___delete__, "(O)", target);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005474 else
Benjamin Petersonce798522012-01-22 11:24:29 -05005475 res = call_method(self, &PyId___set__, "(OO)", target, value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005476 if (res == NULL)
5477 return -1;
5478 Py_DECREF(res);
5479 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005480}
5481
5482static int
5483slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds)
5484{
Benjamin Petersonce798522012-01-22 11:24:29 -05005485 _Py_IDENTIFIER(__init__);
5486 PyObject *meth = lookup_method(self, &PyId___init__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005487 PyObject *res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005488
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005489 if (meth == NULL)
5490 return -1;
5491 res = PyObject_Call(meth, args, kwds);
5492 Py_DECREF(meth);
5493 if (res == NULL)
5494 return -1;
5495 if (res != Py_None) {
5496 PyErr_Format(PyExc_TypeError,
5497 "__init__() should return None, not '%.200s'",
5498 Py_TYPE(res)->tp_name);
5499 Py_DECREF(res);
5500 return -1;
5501 }
5502 Py_DECREF(res);
5503 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005504}
5505
5506static PyObject *
5507slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
5508{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005509 static PyObject *new_str;
5510 PyObject *func;
5511 PyObject *newargs, *x;
5512 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005513
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005514 if (new_str == NULL) {
5515 new_str = PyUnicode_InternFromString("__new__");
5516 if (new_str == NULL)
5517 return NULL;
5518 }
5519 func = PyObject_GetAttr((PyObject *)type, new_str);
5520 if (func == NULL)
5521 return NULL;
5522 assert(PyTuple_Check(args));
5523 n = PyTuple_GET_SIZE(args);
5524 newargs = PyTuple_New(n+1);
5525 if (newargs == NULL)
5526 return NULL;
5527 Py_INCREF(type);
5528 PyTuple_SET_ITEM(newargs, 0, (PyObject *)type);
5529 for (i = 0; i < n; i++) {
5530 x = PyTuple_GET_ITEM(args, i);
5531 Py_INCREF(x);
5532 PyTuple_SET_ITEM(newargs, i+1, x);
5533 }
5534 x = PyObject_Call(func, newargs, kwds);
5535 Py_DECREF(newargs);
5536 Py_DECREF(func);
5537 return x;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005538}
5539
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005540static void
5541slot_tp_del(PyObject *self)
5542{
Benjamin Petersonce798522012-01-22 11:24:29 -05005543 _Py_IDENTIFIER(__del__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005544 PyObject *del, *res;
5545 PyObject *error_type, *error_value, *error_traceback;
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005546
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005547 /* Temporarily resurrect the object. */
5548 assert(self->ob_refcnt == 0);
5549 self->ob_refcnt = 1;
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005550
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005551 /* Save the current exception, if any. */
5552 PyErr_Fetch(&error_type, &error_value, &error_traceback);
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005553
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005554 /* Execute __del__ method, if any. */
Benjamin Petersonce798522012-01-22 11:24:29 -05005555 del = lookup_maybe(self, &PyId___del__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005556 if (del != NULL) {
5557 res = PyEval_CallObject(del, NULL);
5558 if (res == NULL)
5559 PyErr_WriteUnraisable(del);
5560 else
5561 Py_DECREF(res);
5562 Py_DECREF(del);
5563 }
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005564
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005565 /* Restore the saved exception. */
5566 PyErr_Restore(error_type, error_value, error_traceback);
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005567
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005568 /* Undo the temporary resurrection; can't use DECREF here, it would
5569 * cause a recursive call.
5570 */
5571 assert(self->ob_refcnt > 0);
5572 if (--self->ob_refcnt == 0)
5573 return; /* this is the normal path out */
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005574
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005575 /* __del__ resurrected it! Make it look like the original Py_DECREF
5576 * never happened.
5577 */
5578 {
5579 Py_ssize_t refcnt = self->ob_refcnt;
5580 _Py_NewReference(self);
5581 self->ob_refcnt = refcnt;
5582 }
5583 assert(!PyType_IS_GC(Py_TYPE(self)) ||
5584 _Py_AS_GC(self)->gc.gc_refs != _PyGC_REFS_UNTRACKED);
5585 /* If Py_REF_DEBUG, _Py_NewReference bumped _Py_RefTotal, so
5586 * we need to undo that. */
5587 _Py_DEC_REFTOTAL;
5588 /* If Py_TRACE_REFS, _Py_NewReference re-added self to the object
5589 * chain, so no more to do there.
5590 * If COUNT_ALLOCS, the original decref bumped tp_frees, and
5591 * _Py_NewReference bumped tp_allocs: both of those need to be
5592 * undone.
5593 */
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005594#ifdef COUNT_ALLOCS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005595 --Py_TYPE(self)->tp_frees;
5596 --Py_TYPE(self)->tp_allocs;
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005597#endif
5598}
5599
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005600
5601/* Table mapping __foo__ names to tp_foo offsets and slot_tp_foo wrapper
Tim Petersbf9b2442003-03-23 05:35:36 +00005602 functions. The offsets here are relative to the 'PyHeapTypeObject'
Guido van Rossume5c691a2003-03-07 15:13:17 +00005603 structure, which incorporates the additional structures used for numbers,
5604 sequences and mappings.
5605 Note that multiple names may map to the same slot (e.g. __eq__,
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005606 __ne__ etc. all map to tp_richcompare) and one name may map to multiple
Guido van Rossumc334df52002-04-04 23:44:47 +00005607 slots (e.g. __str__ affects tp_str as well as tp_repr). The table is
5608 terminated with an all-zero entry. (This table is further initialized and
5609 sorted in init_slotdefs() below.) */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005610
Guido van Rossum6d204072001-10-21 00:44:31 +00005611typedef struct wrapperbase slotdef;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005612
5613#undef TPSLOT
Guido van Rossumc8e56452001-10-22 00:43:43 +00005614#undef FLSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005615#undef ETSLOT
5616#undef SQSLOT
5617#undef MPSLOT
5618#undef NBSLOT
Guido van Rossum6d204072001-10-21 00:44:31 +00005619#undef UNSLOT
5620#undef IBSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005621#undef BINSLOT
5622#undef RBINSLOT
5623
Guido van Rossum6d204072001-10-21 00:44:31 +00005624#define TPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005625 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
5626 PyDoc_STR(DOC)}
Guido van Rossumc8e56452001-10-22 00:43:43 +00005627#define FLSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC, FLAGS) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005628 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
5629 PyDoc_STR(DOC), FLAGS}
Guido van Rossum6d204072001-10-21 00:44:31 +00005630#define ETSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005631 {NAME, offsetof(PyHeapTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
5632 PyDoc_STR(DOC)}
Guido van Rossum6d204072001-10-21 00:44:31 +00005633#define SQSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005634 ETSLOT(NAME, as_sequence.SLOT, FUNCTION, WRAPPER, DOC)
Guido van Rossum6d204072001-10-21 00:44:31 +00005635#define MPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005636 ETSLOT(NAME, as_mapping.SLOT, FUNCTION, WRAPPER, DOC)
Guido van Rossum6d204072001-10-21 00:44:31 +00005637#define NBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005638 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, DOC)
Guido van Rossum6d204072001-10-21 00:44:31 +00005639#define UNSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005640 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
5641 "x." NAME "() <==> " DOC)
Guido van Rossum6d204072001-10-21 00:44:31 +00005642#define IBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005643 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
5644 "x." NAME "(y) <==> x" DOC "y")
Guido van Rossum6d204072001-10-21 00:44:31 +00005645#define BINSLOT(NAME, SLOT, FUNCTION, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005646 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
5647 "x." NAME "(y) <==> x" DOC "y")
Guido van Rossum6d204072001-10-21 00:44:31 +00005648#define RBINSLOT(NAME, SLOT, FUNCTION, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005649 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
5650 "x." NAME "(y) <==> y" DOC "x")
Anthony Baxter56616992005-06-03 14:12:21 +00005651#define BINSLOTNOTINFIX(NAME, SLOT, FUNCTION, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005652 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
5653 "x." NAME "(y) <==> " DOC)
Anthony Baxter56616992005-06-03 14:12:21 +00005654#define RBINSLOTNOTINFIX(NAME, SLOT, FUNCTION, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005655 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
5656 "x." NAME "(y) <==> " DOC)
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005657
5658static slotdef slotdefs[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005659 SQSLOT("__len__", sq_length, slot_sq_length, wrap_lenfunc,
5660 "x.__len__() <==> len(x)"),
5661 /* Heap types defining __add__/__mul__ have sq_concat/sq_repeat == NULL.
5662 The logic in abstract.c always falls back to nb_add/nb_multiply in
5663 this case. Defining both the nb_* and the sq_* slots to call the
5664 user-defined methods has unexpected side-effects, as shown by
5665 test_descr.notimplemented() */
5666 SQSLOT("__add__", sq_concat, NULL, wrap_binaryfunc,
5667 "x.__add__(y) <==> x+y"),
5668 SQSLOT("__mul__", sq_repeat, NULL, wrap_indexargfunc,
5669 "x.__mul__(n) <==> x*n"),
5670 SQSLOT("__rmul__", sq_repeat, NULL, wrap_indexargfunc,
5671 "x.__rmul__(n) <==> n*x"),
5672 SQSLOT("__getitem__", sq_item, slot_sq_item, wrap_sq_item,
5673 "x.__getitem__(y) <==> x[y]"),
5674 SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_setitem,
5675 "x.__setitem__(i, y) <==> x[i]=y"),
5676 SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_delitem,
5677 "x.__delitem__(y) <==> del x[y]"),
5678 SQSLOT("__contains__", sq_contains, slot_sq_contains, wrap_objobjproc,
5679 "x.__contains__(y) <==> y in x"),
5680 SQSLOT("__iadd__", sq_inplace_concat, NULL,
5681 wrap_binaryfunc, "x.__iadd__(y) <==> x+=y"),
5682 SQSLOT("__imul__", sq_inplace_repeat, NULL,
5683 wrap_indexargfunc, "x.__imul__(y) <==> x*=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005684
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005685 MPSLOT("__len__", mp_length, slot_mp_length, wrap_lenfunc,
5686 "x.__len__() <==> len(x)"),
5687 MPSLOT("__getitem__", mp_subscript, slot_mp_subscript,
5688 wrap_binaryfunc,
5689 "x.__getitem__(y) <==> x[y]"),
5690 MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript,
5691 wrap_objobjargproc,
5692 "x.__setitem__(i, y) <==> x[i]=y"),
5693 MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript,
5694 wrap_delitem,
5695 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005696
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005697 BINSLOT("__add__", nb_add, slot_nb_add,
5698 "+"),
5699 RBINSLOT("__radd__", nb_add, slot_nb_add,
5700 "+"),
5701 BINSLOT("__sub__", nb_subtract, slot_nb_subtract,
5702 "-"),
5703 RBINSLOT("__rsub__", nb_subtract, slot_nb_subtract,
5704 "-"),
5705 BINSLOT("__mul__", nb_multiply, slot_nb_multiply,
5706 "*"),
5707 RBINSLOT("__rmul__", nb_multiply, slot_nb_multiply,
5708 "*"),
5709 BINSLOT("__mod__", nb_remainder, slot_nb_remainder,
5710 "%"),
5711 RBINSLOT("__rmod__", nb_remainder, slot_nb_remainder,
5712 "%"),
5713 BINSLOTNOTINFIX("__divmod__", nb_divmod, slot_nb_divmod,
5714 "divmod(x, y)"),
5715 RBINSLOTNOTINFIX("__rdivmod__", nb_divmod, slot_nb_divmod,
5716 "divmod(y, x)"),
5717 NBSLOT("__pow__", nb_power, slot_nb_power, wrap_ternaryfunc,
5718 "x.__pow__(y[, z]) <==> pow(x, y[, z])"),
5719 NBSLOT("__rpow__", nb_power, slot_nb_power, wrap_ternaryfunc_r,
5720 "y.__rpow__(x[, z]) <==> pow(x, y[, z])"),
5721 UNSLOT("__neg__", nb_negative, slot_nb_negative, wrap_unaryfunc, "-x"),
5722 UNSLOT("__pos__", nb_positive, slot_nb_positive, wrap_unaryfunc, "+x"),
5723 UNSLOT("__abs__", nb_absolute, slot_nb_absolute, wrap_unaryfunc,
5724 "abs(x)"),
5725 UNSLOT("__bool__", nb_bool, slot_nb_bool, wrap_inquirypred,
5726 "x != 0"),
5727 UNSLOT("__invert__", nb_invert, slot_nb_invert, wrap_unaryfunc, "~x"),
5728 BINSLOT("__lshift__", nb_lshift, slot_nb_lshift, "<<"),
5729 RBINSLOT("__rlshift__", nb_lshift, slot_nb_lshift, "<<"),
5730 BINSLOT("__rshift__", nb_rshift, slot_nb_rshift, ">>"),
5731 RBINSLOT("__rrshift__", nb_rshift, slot_nb_rshift, ">>"),
5732 BINSLOT("__and__", nb_and, slot_nb_and, "&"),
5733 RBINSLOT("__rand__", nb_and, slot_nb_and, "&"),
5734 BINSLOT("__xor__", nb_xor, slot_nb_xor, "^"),
5735 RBINSLOT("__rxor__", nb_xor, slot_nb_xor, "^"),
5736 BINSLOT("__or__", nb_or, slot_nb_or, "|"),
5737 RBINSLOT("__ror__", nb_or, slot_nb_or, "|"),
5738 UNSLOT("__int__", nb_int, slot_nb_int, wrap_unaryfunc,
5739 "int(x)"),
5740 UNSLOT("__float__", nb_float, slot_nb_float, wrap_unaryfunc,
5741 "float(x)"),
5742 NBSLOT("__index__", nb_index, slot_nb_index, wrap_unaryfunc,
5743 "x[y:z] <==> x[y.__index__():z.__index__()]"),
5744 IBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add,
Eli Benderskyd3baae72011-11-11 16:57:05 +02005745 wrap_binaryfunc, "+="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005746 IBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract,
Eli Benderskyd3baae72011-11-11 16:57:05 +02005747 wrap_binaryfunc, "-="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005748 IBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply,
Eli Benderskyd3baae72011-11-11 16:57:05 +02005749 wrap_binaryfunc, "*="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005750 IBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder,
Eli Benderskyd3baae72011-11-11 16:57:05 +02005751 wrap_binaryfunc, "%="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005752 IBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power,
Eli Benderskyd3baae72011-11-11 16:57:05 +02005753 wrap_binaryfunc, "**="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005754 IBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift,
Eli Benderskyd3baae72011-11-11 16:57:05 +02005755 wrap_binaryfunc, "<<="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005756 IBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift,
Eli Benderskyd3baae72011-11-11 16:57:05 +02005757 wrap_binaryfunc, ">>="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005758 IBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and,
Eli Benderskyd3baae72011-11-11 16:57:05 +02005759 wrap_binaryfunc, "&="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005760 IBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor,
Eli Benderskyd3baae72011-11-11 16:57:05 +02005761 wrap_binaryfunc, "^="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005762 IBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or,
Eli Benderskyd3baae72011-11-11 16:57:05 +02005763 wrap_binaryfunc, "|="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005764 BINSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
5765 RBINSLOT("__rfloordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
5766 BINSLOT("__truediv__", nb_true_divide, slot_nb_true_divide, "/"),
5767 RBINSLOT("__rtruediv__", nb_true_divide, slot_nb_true_divide, "/"),
5768 IBSLOT("__ifloordiv__", nb_inplace_floor_divide,
5769 slot_nb_inplace_floor_divide, wrap_binaryfunc, "//"),
5770 IBSLOT("__itruediv__", nb_inplace_true_divide,
5771 slot_nb_inplace_true_divide, wrap_binaryfunc, "/"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005772
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005773 TPSLOT("__str__", tp_str, slot_tp_str, wrap_unaryfunc,
5774 "x.__str__() <==> str(x)"),
5775 TPSLOT("__repr__", tp_repr, slot_tp_repr, wrap_unaryfunc,
5776 "x.__repr__() <==> repr(x)"),
5777 TPSLOT("__hash__", tp_hash, slot_tp_hash, wrap_hashfunc,
5778 "x.__hash__() <==> hash(x)"),
5779 FLSLOT("__call__", tp_call, slot_tp_call, (wrapperfunc)wrap_call,
5780 "x.__call__(...) <==> x(...)", PyWrapperFlag_KEYWORDS),
5781 TPSLOT("__getattribute__", tp_getattro, slot_tp_getattr_hook,
5782 wrap_binaryfunc, "x.__getattribute__('name') <==> x.name"),
5783 TPSLOT("__getattribute__", tp_getattr, NULL, NULL, ""),
5784 TPSLOT("__getattr__", tp_getattro, slot_tp_getattr_hook, NULL, ""),
5785 TPSLOT("__getattr__", tp_getattr, NULL, NULL, ""),
5786 TPSLOT("__setattr__", tp_setattro, slot_tp_setattro, wrap_setattr,
5787 "x.__setattr__('name', value) <==> x.name = value"),
5788 TPSLOT("__setattr__", tp_setattr, NULL, NULL, ""),
5789 TPSLOT("__delattr__", tp_setattro, slot_tp_setattro, wrap_delattr,
5790 "x.__delattr__('name') <==> del x.name"),
5791 TPSLOT("__delattr__", tp_setattr, NULL, NULL, ""),
5792 TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare, richcmp_lt,
5793 "x.__lt__(y) <==> x<y"),
5794 TPSLOT("__le__", tp_richcompare, slot_tp_richcompare, richcmp_le,
5795 "x.__le__(y) <==> x<=y"),
5796 TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare, richcmp_eq,
5797 "x.__eq__(y) <==> x==y"),
5798 TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare, richcmp_ne,
5799 "x.__ne__(y) <==> x!=y"),
5800 TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare, richcmp_gt,
5801 "x.__gt__(y) <==> x>y"),
5802 TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare, richcmp_ge,
5803 "x.__ge__(y) <==> x>=y"),
5804 TPSLOT("__iter__", tp_iter, slot_tp_iter, wrap_unaryfunc,
5805 "x.__iter__() <==> iter(x)"),
5806 TPSLOT("__next__", tp_iternext, slot_tp_iternext, wrap_next,
5807 "x.__next__() <==> next(x)"),
5808 TPSLOT("__get__", tp_descr_get, slot_tp_descr_get, wrap_descr_get,
5809 "descr.__get__(obj[, type]) -> value"),
5810 TPSLOT("__set__", tp_descr_set, slot_tp_descr_set, wrap_descr_set,
5811 "descr.__set__(obj, value)"),
5812 TPSLOT("__delete__", tp_descr_set, slot_tp_descr_set,
5813 wrap_descr_delete, "descr.__delete__(obj)"),
5814 FLSLOT("__init__", tp_init, slot_tp_init, (wrapperfunc)wrap_init,
5815 "x.__init__(...) initializes x; "
Alexander Belopolsky977a6842010-08-16 20:17:07 +00005816 "see help(type(x)) for signature",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005817 PyWrapperFlag_KEYWORDS),
5818 TPSLOT("__new__", tp_new, slot_tp_new, NULL, ""),
5819 TPSLOT("__del__", tp_del, slot_tp_del, NULL, ""),
5820 {NULL}
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005821};
5822
Guido van Rossumc334df52002-04-04 23:44:47 +00005823/* Given a type pointer and an offset gotten from a slotdef entry, return a
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005824 pointer to the actual slot. This is not quite the same as simply adding
Guido van Rossumc334df52002-04-04 23:44:47 +00005825 the offset to the type pointer, since it takes care to indirect through the
5826 proper indirection pointer (as_buffer, etc.); it returns NULL if the
5827 indirection pointer is NULL. */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005828static void **
Martin v. Löwis18e16552006-02-15 17:27:45 +00005829slotptr(PyTypeObject *type, int ioffset)
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005830{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005831 char *ptr;
5832 long offset = ioffset;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005833
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005834 /* Note: this depends on the order of the members of PyHeapTypeObject! */
5835 assert(offset >= 0);
5836 assert((size_t)offset < offsetof(PyHeapTypeObject, as_buffer));
5837 if ((size_t)offset >= offsetof(PyHeapTypeObject, as_sequence)) {
5838 ptr = (char *)type->tp_as_sequence;
5839 offset -= offsetof(PyHeapTypeObject, as_sequence);
5840 }
5841 else if ((size_t)offset >= offsetof(PyHeapTypeObject, as_mapping)) {
5842 ptr = (char *)type->tp_as_mapping;
5843 offset -= offsetof(PyHeapTypeObject, as_mapping);
5844 }
5845 else if ((size_t)offset >= offsetof(PyHeapTypeObject, as_number)) {
5846 ptr = (char *)type->tp_as_number;
5847 offset -= offsetof(PyHeapTypeObject, as_number);
5848 }
5849 else {
5850 ptr = (char *)type;
5851 }
5852 if (ptr != NULL)
5853 ptr += offset;
5854 return (void **)ptr;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005855}
Guido van Rossumf040ede2001-08-07 16:40:56 +00005856
Guido van Rossumc334df52002-04-04 23:44:47 +00005857/* Length of array of slotdef pointers used to store slots with the
5858 same __name__. There should be at most MAX_EQUIV-1 slotdef entries with
5859 the same __name__, for any __name__. Since that's a static property, it is
5860 appropriate to declare fixed-size arrays for this. */
5861#define MAX_EQUIV 10
5862
5863/* Return a slot pointer for a given name, but ONLY if the attribute has
5864 exactly one slot function. The name must be an interned string. */
5865static void **
5866resolve_slotdups(PyTypeObject *type, PyObject *name)
5867{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005868 /* XXX Maybe this could be optimized more -- but is it worth it? */
Guido van Rossumc334df52002-04-04 23:44:47 +00005869
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005870 /* pname and ptrs act as a little cache */
5871 static PyObject *pname;
5872 static slotdef *ptrs[MAX_EQUIV];
5873 slotdef *p, **pp;
5874 void **res, **ptr;
Guido van Rossumc334df52002-04-04 23:44:47 +00005875
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005876 if (pname != name) {
5877 /* Collect all slotdefs that match name into ptrs. */
5878 pname = name;
5879 pp = ptrs;
5880 for (p = slotdefs; p->name_strobj; p++) {
5881 if (p->name_strobj == name)
5882 *pp++ = p;
5883 }
5884 *pp = NULL;
5885 }
Guido van Rossumc334df52002-04-04 23:44:47 +00005886
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005887 /* Look in all matching slots of the type; if exactly one of these has
5888 a filled-in slot, return its value. Otherwise return NULL. */
5889 res = NULL;
5890 for (pp = ptrs; *pp; pp++) {
5891 ptr = slotptr(type, (*pp)->offset);
5892 if (ptr == NULL || *ptr == NULL)
5893 continue;
5894 if (res != NULL)
5895 return NULL;
5896 res = ptr;
5897 }
5898 return res;
Guido van Rossumc334df52002-04-04 23:44:47 +00005899}
5900
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005901/* Common code for update_slots_callback() and fixup_slot_dispatchers(). This
Guido van Rossumc334df52002-04-04 23:44:47 +00005902 does some incredibly complex thinking and then sticks something into the
5903 slot. (It sees if the adjacent slotdefs for the same slot have conflicting
5904 interests, and then stores a generic wrapper or a specific function into
5905 the slot.) Return a pointer to the next slotdef with a different offset,
5906 because that's convenient for fixup_slot_dispatchers(). */
5907static slotdef *
5908update_one_slot(PyTypeObject *type, slotdef *p)
5909{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005910 PyObject *descr;
5911 PyWrapperDescrObject *d;
5912 void *generic = NULL, *specific = NULL;
5913 int use_generic = 0;
5914 int offset = p->offset;
5915 void **ptr = slotptr(type, offset);
Guido van Rossumc334df52002-04-04 23:44:47 +00005916
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005917 if (ptr == NULL) {
5918 do {
5919 ++p;
5920 } while (p->offset == offset);
5921 return p;
5922 }
5923 do {
5924 descr = _PyType_Lookup(type, p->name_strobj);
5925 if (descr == NULL) {
5926 if (ptr == (void**)&type->tp_iternext) {
5927 specific = _PyObject_NextNotImplemented;
5928 }
5929 continue;
5930 }
5931 if (Py_TYPE(descr) == &PyWrapperDescr_Type) {
5932 void **tptr = resolve_slotdups(type, p->name_strobj);
5933 if (tptr == NULL || tptr == ptr)
5934 generic = p->function;
5935 d = (PyWrapperDescrObject *)descr;
5936 if (d->d_base->wrapper == p->wrapper &&
5937 PyType_IsSubtype(type, PyDescr_TYPE(d)))
5938 {
5939 if (specific == NULL ||
5940 specific == d->d_wrapped)
5941 specific = d->d_wrapped;
5942 else
5943 use_generic = 1;
5944 }
5945 }
5946 else if (Py_TYPE(descr) == &PyCFunction_Type &&
5947 PyCFunction_GET_FUNCTION(descr) ==
5948 (PyCFunction)tp_new_wrapper &&
5949 ptr == (void**)&type->tp_new)
5950 {
5951 /* The __new__ wrapper is not a wrapper descriptor,
5952 so must be special-cased differently.
5953 If we don't do this, creating an instance will
5954 always use slot_tp_new which will look up
5955 __new__ in the MRO which will call tp_new_wrapper
5956 which will look through the base classes looking
5957 for a static base and call its tp_new (usually
5958 PyType_GenericNew), after performing various
5959 sanity checks and constructing a new argument
5960 list. Cut all that nonsense short -- this speeds
5961 up instance creation tremendously. */
5962 specific = (void *)type->tp_new;
5963 /* XXX I'm not 100% sure that there isn't a hole
5964 in this reasoning that requires additional
5965 sanity checks. I'll buy the first person to
5966 point out a bug in this reasoning a beer. */
5967 }
5968 else if (descr == Py_None &&
5969 ptr == (void**)&type->tp_hash) {
5970 /* We specifically allow __hash__ to be set to None
5971 to prevent inheritance of the default
5972 implementation from object.__hash__ */
5973 specific = PyObject_HashNotImplemented;
5974 }
5975 else {
5976 use_generic = 1;
5977 generic = p->function;
5978 }
5979 } while ((++p)->offset == offset);
5980 if (specific && !use_generic)
5981 *ptr = specific;
5982 else
5983 *ptr = generic;
5984 return p;
Guido van Rossumc334df52002-04-04 23:44:47 +00005985}
5986
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005987/* In the type, update the slots whose slotdefs are gathered in the pp array.
5988 This is a callback for update_subclasses(). */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005989static int
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005990update_slots_callback(PyTypeObject *type, void *data)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005991{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005992 slotdef **pp = (slotdef **)data;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005993
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005994 for (; *pp; pp++)
5995 update_one_slot(type, *pp);
5996 return 0;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005997}
5998
Guido van Rossumc334df52002-04-04 23:44:47 +00005999/* Comparison function for qsort() to compare slotdefs by their offset, and
6000 for equal offset by their address (to force a stable sort). */
Guido van Rossumd396b9c2001-10-13 20:02:41 +00006001static int
6002slotdef_cmp(const void *aa, const void *bb)
6003{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006004 const slotdef *a = (const slotdef *)aa, *b = (const slotdef *)bb;
6005 int c = a->offset - b->offset;
6006 if (c != 0)
6007 return c;
6008 else
6009 /* Cannot use a-b, as this gives off_t,
6010 which may lose precision when converted to int. */
6011 return (a > b) ? 1 : (a < b) ? -1 : 0;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00006012}
6013
Guido van Rossumc334df52002-04-04 23:44:47 +00006014/* Initialize the slotdefs table by adding interned string objects for the
6015 names and sorting the entries. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006016static void
Guido van Rossumd396b9c2001-10-13 20:02:41 +00006017init_slotdefs(void)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006018{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006019 slotdef *p;
6020 static int initialized = 0;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006021
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006022 if (initialized)
6023 return;
6024 for (p = slotdefs; p->name; p++) {
6025 p->name_strobj = PyUnicode_InternFromString(p->name);
6026 if (!p->name_strobj)
6027 Py_FatalError("Out of memory interning slotdef names");
6028 }
6029 qsort((void *)slotdefs, (size_t)(p-slotdefs), sizeof(slotdef),
6030 slotdef_cmp);
6031 initialized = 1;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006032}
6033
Guido van Rossumc334df52002-04-04 23:44:47 +00006034/* Update the slots after assignment to a class (type) attribute. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006035static int
6036update_slot(PyTypeObject *type, PyObject *name)
6037{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006038 slotdef *ptrs[MAX_EQUIV];
6039 slotdef *p;
6040 slotdef **pp;
6041 int offset;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006042
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006043 /* Clear the VALID_VERSION flag of 'type' and all its
6044 subclasses. This could possibly be unified with the
6045 update_subclasses() recursion below, but carefully:
6046 they each have their own conditions on which to stop
6047 recursing into subclasses. */
6048 PyType_Modified(type);
Christian Heimesa62da1d2008-01-12 19:39:10 +00006049
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006050 init_slotdefs();
6051 pp = ptrs;
6052 for (p = slotdefs; p->name; p++) {
6053 /* XXX assume name is interned! */
6054 if (p->name_strobj == name)
6055 *pp++ = p;
6056 }
6057 *pp = NULL;
6058 for (pp = ptrs; *pp; pp++) {
6059 p = *pp;
6060 offset = p->offset;
6061 while (p > slotdefs && (p-1)->offset == offset)
6062 --p;
6063 *pp = p;
6064 }
6065 if (ptrs[0] == NULL)
6066 return 0; /* Not an attribute that affects any slots */
6067 return update_subclasses(type, name,
6068 update_slots_callback, (void *)ptrs);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006069}
6070
Guido van Rossumc334df52002-04-04 23:44:47 +00006071/* Store the proper functions in the slot dispatches at class (type)
6072 definition time, based upon which operations the class overrides in its
6073 dict. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00006074static void
Guido van Rossum7b9144b2001-10-09 19:39:46 +00006075fixup_slot_dispatchers(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00006076{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006077 slotdef *p;
Tim Peters6d6c1a32001-08-02 04:15:00 +00006078
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006079 init_slotdefs();
6080 for (p = slotdefs; p->name; )
6081 p = update_one_slot(type, p);
Tim Peters6d6c1a32001-08-02 04:15:00 +00006082}
Guido van Rossum705f0f52001-08-24 16:47:00 +00006083
Michael W. Hudson98bbc492002-11-26 14:47:27 +00006084static void
6085update_all_slots(PyTypeObject* type)
6086{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006087 slotdef *p;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00006088
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006089 init_slotdefs();
6090 for (p = slotdefs; p->name; p++) {
6091 /* update_slot returns int but can't actually fail */
6092 update_slot(type, p->name_strobj);
6093 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +00006094}
6095
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006096/* recurse_down_subclasses() and update_subclasses() are mutually
6097 recursive functions to call a callback for all subclasses,
6098 but refraining from recursing into subclasses that define 'name'. */
6099
6100static int
6101update_subclasses(PyTypeObject *type, PyObject *name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006102 update_callback callback, void *data)
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006103{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006104 if (callback(type, data) < 0)
6105 return -1;
6106 return recurse_down_subclasses(type, name, callback, data);
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006107}
6108
6109static int
6110recurse_down_subclasses(PyTypeObject *type, PyObject *name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006111 update_callback callback, void *data)
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006112{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006113 PyTypeObject *subclass;
6114 PyObject *ref, *subclasses, *dict;
6115 Py_ssize_t i, n;
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006116
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006117 subclasses = type->tp_subclasses;
6118 if (subclasses == NULL)
6119 return 0;
6120 assert(PyList_Check(subclasses));
6121 n = PyList_GET_SIZE(subclasses);
6122 for (i = 0; i < n; i++) {
6123 ref = PyList_GET_ITEM(subclasses, i);
6124 assert(PyWeakref_CheckRef(ref));
6125 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
6126 assert(subclass != NULL);
6127 if ((PyObject *)subclass == Py_None)
6128 continue;
6129 assert(PyType_Check(subclass));
6130 /* Avoid recursing down into unaffected classes */
6131 dict = subclass->tp_dict;
6132 if (dict != NULL && PyDict_Check(dict) &&
6133 PyDict_GetItem(dict, name) != NULL)
6134 continue;
6135 if (update_subclasses(subclass, name, callback, data) < 0)
6136 return -1;
6137 }
6138 return 0;
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006139}
6140
Guido van Rossum6d204072001-10-21 00:44:31 +00006141/* This function is called by PyType_Ready() to populate the type's
6142 dictionary with method descriptors for function slots. For each
Guido van Rossum09638c12002-06-13 19:17:46 +00006143 function slot (like tp_repr) that's defined in the type, one or more
6144 corresponding descriptors are added in the type's tp_dict dictionary
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006145 under the appropriate name (like __repr__). Some function slots
Guido van Rossum09638c12002-06-13 19:17:46 +00006146 cause more than one descriptor to be added (for example, the nb_add
6147 slot adds both __add__ and __radd__ descriptors) and some function
6148 slots compete for the same descriptor (for example both sq_item and
6149 mp_subscript generate a __getitem__ descriptor).
6150
Ezio Melotti13925002011-03-16 11:05:33 +02006151 In the latter case, the first slotdef entry encountered wins. Since
Tim Petersbf9b2442003-03-23 05:35:36 +00006152 slotdef entries are sorted by the offset of the slot in the
Guido van Rossume5c691a2003-03-07 15:13:17 +00006153 PyHeapTypeObject, this gives us some control over disambiguating
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006154 between competing slots: the members of PyHeapTypeObject are listed
6155 from most general to least general, so the most general slot is
6156 preferred. In particular, because as_mapping comes before as_sequence,
6157 for a type that defines both mp_subscript and sq_item, mp_subscript
6158 wins.
Guido van Rossum09638c12002-06-13 19:17:46 +00006159
6160 This only adds new descriptors and doesn't overwrite entries in
6161 tp_dict that were previously defined. The descriptors contain a
6162 reference to the C function they must call, so that it's safe if they
6163 are copied into a subtype's __dict__ and the subtype has a different
6164 C function in its slot -- calling the method defined by the
6165 descriptor will call the C function that was used to create it,
6166 rather than the C function present in the slot when it is called.
6167 (This is important because a subtype may have a C function in the
6168 slot that calls the method from the dictionary, and we want to avoid
6169 infinite recursion here.) */
Guido van Rossum6d204072001-10-21 00:44:31 +00006170
6171static int
6172add_operators(PyTypeObject *type)
6173{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006174 PyObject *dict = type->tp_dict;
6175 slotdef *p;
6176 PyObject *descr;
6177 void **ptr;
Guido van Rossum6d204072001-10-21 00:44:31 +00006178
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006179 init_slotdefs();
6180 for (p = slotdefs; p->name; p++) {
6181 if (p->wrapper == NULL)
6182 continue;
6183 ptr = slotptr(type, p->offset);
6184 if (!ptr || !*ptr)
6185 continue;
6186 if (PyDict_GetItem(dict, p->name_strobj))
6187 continue;
6188 if (*ptr == PyObject_HashNotImplemented) {
6189 /* Classes may prevent the inheritance of the tp_hash
6190 slot by storing PyObject_HashNotImplemented in it. Make it
6191 visible as a None value for the __hash__ attribute. */
6192 if (PyDict_SetItem(dict, p->name_strobj, Py_None) < 0)
6193 return -1;
6194 }
6195 else {
6196 descr = PyDescr_NewWrapper(type, p, *ptr);
6197 if (descr == NULL)
6198 return -1;
6199 if (PyDict_SetItem(dict, p->name_strobj, descr) < 0)
6200 return -1;
6201 Py_DECREF(descr);
6202 }
6203 }
6204 if (type->tp_new != NULL) {
6205 if (add_tp_new_wrapper(type) < 0)
6206 return -1;
6207 }
6208 return 0;
Guido van Rossum6d204072001-10-21 00:44:31 +00006209}
6210
Guido van Rossum705f0f52001-08-24 16:47:00 +00006211
6212/* Cooperative 'super' */
6213
6214typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006215 PyObject_HEAD
6216 PyTypeObject *type;
6217 PyObject *obj;
6218 PyTypeObject *obj_type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006219} superobject;
6220
Guido van Rossum6f799372001-09-20 20:46:19 +00006221static PyMemberDef super_members[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006222 {"__thisclass__", T_OBJECT, offsetof(superobject, type), READONLY,
6223 "the class invoking super()"},
6224 {"__self__", T_OBJECT, offsetof(superobject, obj), READONLY,
6225 "the instance invoking super(); may be None"},
6226 {"__self_class__", T_OBJECT, offsetof(superobject, obj_type), READONLY,
6227 "the type of the instance invoking super(); may be None"},
6228 {0}
Guido van Rossum41eb14d2001-08-30 23:13:11 +00006229};
6230
Guido van Rossum705f0f52001-08-24 16:47:00 +00006231static void
6232super_dealloc(PyObject *self)
6233{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006234 superobject *su = (superobject *)self;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006235
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006236 _PyObject_GC_UNTRACK(self);
6237 Py_XDECREF(su->obj);
6238 Py_XDECREF(su->type);
6239 Py_XDECREF(su->obj_type);
6240 Py_TYPE(self)->tp_free(self);
Guido van Rossum705f0f52001-08-24 16:47:00 +00006241}
6242
6243static PyObject *
Guido van Rossum41eb14d2001-08-30 23:13:11 +00006244super_repr(PyObject *self)
6245{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006246 superobject *su = (superobject *)self;
Guido van Rossum41eb14d2001-08-30 23:13:11 +00006247
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006248 if (su->obj_type)
6249 return PyUnicode_FromFormat(
6250 "<super: <class '%s'>, <%s object>>",
6251 su->type ? su->type->tp_name : "NULL",
6252 su->obj_type->tp_name);
6253 else
6254 return PyUnicode_FromFormat(
6255 "<super: <class '%s'>, NULL>",
6256 su->type ? su->type->tp_name : "NULL");
Guido van Rossum41eb14d2001-08-30 23:13:11 +00006257}
6258
6259static PyObject *
Guido van Rossum705f0f52001-08-24 16:47:00 +00006260super_getattro(PyObject *self, PyObject *name)
6261{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006262 superobject *su = (superobject *)self;
6263 int skip = su->obj_type == NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006264
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006265 if (!skip) {
6266 /* We want __class__ to return the class of the super object
6267 (i.e. super, or a subclass), not the class of su->obj. */
6268 skip = (PyUnicode_Check(name) &&
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006269 PyUnicode_GET_LENGTH(name) == 9 &&
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006270 PyUnicode_CompareWithASCIIString(name, "__class__") == 0);
6271 }
Guido van Rossum76ba09f2003-04-16 19:40:58 +00006272
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006273 if (!skip) {
6274 PyObject *mro, *res, *tmp, *dict;
6275 PyTypeObject *starttype;
6276 descrgetfunc f;
6277 Py_ssize_t i, n;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006278
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006279 starttype = su->obj_type;
6280 mro = starttype->tp_mro;
Guido van Rossum155db9a2002-04-02 17:53:47 +00006281
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006282 if (mro == NULL)
6283 n = 0;
6284 else {
6285 assert(PyTuple_Check(mro));
6286 n = PyTuple_GET_SIZE(mro);
6287 }
6288 for (i = 0; i < n; i++) {
6289 if ((PyObject *)(su->type) == PyTuple_GET_ITEM(mro, i))
6290 break;
6291 }
6292 i++;
6293 res = NULL;
6294 for (; i < n; i++) {
6295 tmp = PyTuple_GET_ITEM(mro, i);
6296 if (PyType_Check(tmp))
6297 dict = ((PyTypeObject *)tmp)->tp_dict;
6298 else
6299 continue;
6300 res = PyDict_GetItem(dict, name);
6301 if (res != NULL) {
6302 Py_INCREF(res);
6303 f = Py_TYPE(res)->tp_descr_get;
6304 if (f != NULL) {
6305 tmp = f(res,
6306 /* Only pass 'obj' param if
6307 this is instance-mode super
6308 (See SF ID #743627)
6309 */
6310 (su->obj == (PyObject *)
6311 su->obj_type
6312 ? (PyObject *)NULL
6313 : su->obj),
6314 (PyObject *)starttype);
6315 Py_DECREF(res);
6316 res = tmp;
6317 }
6318 return res;
6319 }
6320 }
6321 }
6322 return PyObject_GenericGetAttr(self, name);
Guido van Rossum705f0f52001-08-24 16:47:00 +00006323}
6324
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006325static PyTypeObject *
Guido van Rossum5b443c62001-12-03 15:38:28 +00006326supercheck(PyTypeObject *type, PyObject *obj)
6327{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006328 /* Check that a super() call makes sense. Return a type object.
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006329
Florent Xiclunaaa6c1d22011-12-12 18:54:29 +01006330 obj can be a class, or an instance of one:
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006331
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006332 - If it is a class, it must be a subclass of 'type'. This case is
6333 used for class methods; the return value is obj.
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006334
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006335 - If it is an instance, it must be an instance of 'type'. This is
6336 the normal case; the return value is obj.__class__.
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006337
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006338 But... when obj is an instance, we want to allow for the case where
6339 Py_TYPE(obj) is not a subclass of type, but obj.__class__ is!
6340 This will allow using super() with a proxy for obj.
6341 */
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006342
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006343 /* Check for first bullet above (special case) */
6344 if (PyType_Check(obj) && PyType_IsSubtype((PyTypeObject *)obj, type)) {
6345 Py_INCREF(obj);
6346 return (PyTypeObject *)obj;
6347 }
Guido van Rossum8e80a722003-02-18 19:22:22 +00006348
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006349 /* Normal case */
6350 if (PyType_IsSubtype(Py_TYPE(obj), type)) {
6351 Py_INCREF(Py_TYPE(obj));
6352 return Py_TYPE(obj);
6353 }
6354 else {
6355 /* Try the slow way */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006356 PyObject *class_attr;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006357
Martin v. Löwisbfc6d742011-10-13 20:03:57 +02006358 class_attr = _PyObject_GetAttrId(obj, &PyId___class__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006359 if (class_attr != NULL &&
6360 PyType_Check(class_attr) &&
6361 (PyTypeObject *)class_attr != Py_TYPE(obj))
6362 {
6363 int ok = PyType_IsSubtype(
6364 (PyTypeObject *)class_attr, type);
6365 if (ok)
6366 return (PyTypeObject *)class_attr;
6367 }
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006368
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006369 if (class_attr == NULL)
6370 PyErr_Clear();
6371 else
6372 Py_DECREF(class_attr);
6373 }
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006374
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006375 PyErr_SetString(PyExc_TypeError,
6376 "super(type, obj): "
6377 "obj must be an instance or subtype of type");
6378 return NULL;
Guido van Rossum5b443c62001-12-03 15:38:28 +00006379}
6380
Guido van Rossum705f0f52001-08-24 16:47:00 +00006381static PyObject *
6382super_descr_get(PyObject *self, PyObject *obj, PyObject *type)
6383{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006384 superobject *su = (superobject *)self;
6385 superobject *newobj;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006386
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006387 if (obj == NULL || obj == Py_None || su->obj != NULL) {
6388 /* Not binding to an object, or already bound */
6389 Py_INCREF(self);
6390 return self;
6391 }
6392 if (Py_TYPE(su) != &PySuper_Type)
6393 /* If su is an instance of a (strict) subclass of super,
6394 call its type */
6395 return PyObject_CallFunctionObjArgs((PyObject *)Py_TYPE(su),
6396 su->type, obj, NULL);
6397 else {
6398 /* Inline the common case */
6399 PyTypeObject *obj_type = supercheck(su->type, obj);
6400 if (obj_type == NULL)
6401 return NULL;
6402 newobj = (superobject *)PySuper_Type.tp_new(&PySuper_Type,
6403 NULL, NULL);
6404 if (newobj == NULL)
6405 return NULL;
6406 Py_INCREF(su->type);
6407 Py_INCREF(obj);
6408 newobj->type = su->type;
6409 newobj->obj = obj;
6410 newobj->obj_type = obj_type;
6411 return (PyObject *)newobj;
6412 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00006413}
6414
6415static int
6416super_init(PyObject *self, PyObject *args, PyObject *kwds)
6417{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006418 superobject *su = (superobject *)self;
6419 PyTypeObject *type = NULL;
6420 PyObject *obj = NULL;
6421 PyTypeObject *obj_type = NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006422
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006423 if (!_PyArg_NoKeywords("super", kwds))
6424 return -1;
6425 if (!PyArg_ParseTuple(args, "|O!O:super", &PyType_Type, &type, &obj))
6426 return -1;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00006427
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006428 if (type == NULL) {
6429 /* Call super(), without args -- fill in from __class__
6430 and first local variable on the stack. */
6431 PyFrameObject *f = PyThreadState_GET()->frame;
6432 PyCodeObject *co = f->f_code;
Victor Stinner0fcab4a2011-01-04 12:59:15 +00006433 Py_ssize_t i, n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006434 if (co == NULL) {
6435 PyErr_SetString(PyExc_SystemError,
6436 "super(): no code object");
6437 return -1;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00006438 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006439 if (co->co_argcount == 0) {
6440 PyErr_SetString(PyExc_SystemError,
6441 "super(): no arguments");
6442 return -1;
6443 }
6444 obj = f->f_localsplus[0];
6445 if (obj == NULL) {
6446 PyErr_SetString(PyExc_SystemError,
6447 "super(): arg[0] deleted");
6448 return -1;
6449 }
6450 if (co->co_freevars == NULL)
6451 n = 0;
6452 else {
6453 assert(PyTuple_Check(co->co_freevars));
6454 n = PyTuple_GET_SIZE(co->co_freevars);
6455 }
6456 for (i = 0; i < n; i++) {
6457 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
6458 assert(PyUnicode_Check(name));
6459 if (!PyUnicode_CompareWithASCIIString(name,
Benjamin Petersonf5ff2232011-06-19 19:42:22 -05006460 "@__class__")) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006461 Py_ssize_t index = co->co_nlocals +
6462 PyTuple_GET_SIZE(co->co_cellvars) + i;
6463 PyObject *cell = f->f_localsplus[index];
6464 if (cell == NULL || !PyCell_Check(cell)) {
6465 PyErr_SetString(PyExc_SystemError,
6466 "super(): bad __class__ cell");
6467 return -1;
6468 }
6469 type = (PyTypeObject *) PyCell_GET(cell);
6470 if (type == NULL) {
6471 PyErr_SetString(PyExc_SystemError,
6472 "super(): empty __class__ cell");
6473 return -1;
6474 }
6475 if (!PyType_Check(type)) {
6476 PyErr_Format(PyExc_SystemError,
6477 "super(): __class__ is not a type (%s)",
6478 Py_TYPE(type)->tp_name);
6479 return -1;
6480 }
6481 break;
6482 }
6483 }
6484 if (type == NULL) {
6485 PyErr_SetString(PyExc_SystemError,
6486 "super(): __class__ cell not found");
6487 return -1;
6488 }
6489 }
Guido van Rossumcd16bf62007-06-13 18:07:49 +00006490
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006491 if (obj == Py_None)
6492 obj = NULL;
6493 if (obj != NULL) {
6494 obj_type = supercheck(type, obj);
6495 if (obj_type == NULL)
6496 return -1;
6497 Py_INCREF(obj);
6498 }
6499 Py_INCREF(type);
6500 su->type = type;
6501 su->obj = obj;
6502 su->obj_type = obj_type;
6503 return 0;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006504}
6505
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00006506PyDoc_STRVAR(super_doc,
Guido van Rossumcd16bf62007-06-13 18:07:49 +00006507"super() -> same as super(__class__, <first argument>)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00006508"super(type) -> unbound super object\n"
6509"super(type, obj) -> bound super object; requires isinstance(obj, type)\n"
Guido van Rossume705ef12001-08-29 15:47:06 +00006510"super(type, type2) -> bound super object; requires issubclass(type2, type)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00006511"Typical use to call a cooperative superclass method:\n"
6512"class C(B):\n"
6513" def meth(self, arg):\n"
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006514" super().meth(arg)\n"
Guido van Rossumcd16bf62007-06-13 18:07:49 +00006515"This works for class methods too:\n"
6516"class C(B):\n"
6517" @classmethod\n"
6518" def cmeth(cls, arg):\n"
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006519" super().cmeth(arg)\n");
Guido van Rossum705f0f52001-08-24 16:47:00 +00006520
Guido van Rossum048eb752001-10-02 21:24:57 +00006521static int
6522super_traverse(PyObject *self, visitproc visit, void *arg)
6523{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006524 superobject *su = (superobject *)self;
Guido van Rossum048eb752001-10-02 21:24:57 +00006525
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006526 Py_VISIT(su->obj);
6527 Py_VISIT(su->type);
6528 Py_VISIT(su->obj_type);
Guido van Rossum048eb752001-10-02 21:24:57 +00006529
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006530 return 0;
Guido van Rossum048eb752001-10-02 21:24:57 +00006531}
6532
Guido van Rossum705f0f52001-08-24 16:47:00 +00006533PyTypeObject PySuper_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006534 PyVarObject_HEAD_INIT(&PyType_Type, 0)
6535 "super", /* tp_name */
6536 sizeof(superobject), /* tp_basicsize */
6537 0, /* tp_itemsize */
6538 /* methods */
6539 super_dealloc, /* tp_dealloc */
6540 0, /* tp_print */
6541 0, /* tp_getattr */
6542 0, /* tp_setattr */
6543 0, /* tp_reserved */
6544 super_repr, /* tp_repr */
6545 0, /* tp_as_number */
6546 0, /* tp_as_sequence */
6547 0, /* tp_as_mapping */
6548 0, /* tp_hash */
6549 0, /* tp_call */
6550 0, /* tp_str */
6551 super_getattro, /* tp_getattro */
6552 0, /* tp_setattro */
6553 0, /* tp_as_buffer */
6554 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
6555 Py_TPFLAGS_BASETYPE, /* tp_flags */
6556 super_doc, /* tp_doc */
6557 super_traverse, /* tp_traverse */
6558 0, /* tp_clear */
6559 0, /* tp_richcompare */
6560 0, /* tp_weaklistoffset */
6561 0, /* tp_iter */
6562 0, /* tp_iternext */
6563 0, /* tp_methods */
6564 super_members, /* tp_members */
6565 0, /* tp_getset */
6566 0, /* tp_base */
6567 0, /* tp_dict */
6568 super_descr_get, /* tp_descr_get */
6569 0, /* tp_descr_set */
6570 0, /* tp_dictoffset */
6571 super_init, /* tp_init */
6572 PyType_GenericAlloc, /* tp_alloc */
6573 PyType_GenericNew, /* tp_new */
6574 PyObject_GC_Del, /* tp_free */
Guido van Rossum705f0f52001-08-24 16:47:00 +00006575};