blob: f94dfbf94ef658cb2f5cc973f2bcd8166abe6d4b [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
38unsigned int
39PyType_ClearCache(void)
40{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000041 Py_ssize_t i;
42 unsigned int cur_version_tag = next_version_tag - 1;
43
44 for (i = 0; i < (1 << MCACHE_SIZE_EXP); i++) {
45 method_cache[i].version = 0;
46 Py_CLEAR(method_cache[i].name);
47 method_cache[i].value = NULL;
48 }
49 next_version_tag = 0;
50 /* mark all version tags as invalid */
51 PyType_Modified(&PyBaseObject_Type);
52 return cur_version_tag;
Christian Heimes26855632008-01-27 23:50:43 +000053}
Christian Heimesa62da1d2008-01-12 19:39:10 +000054
Georg Brandlf08a9dd2008-06-10 16:57:31 +000055void
56PyType_Modified(PyTypeObject *type)
Christian Heimesa62da1d2008-01-12 19:39:10 +000057{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000058 /* Invalidate any cached data for the specified type and all
59 subclasses. This function is called after the base
60 classes, mro, or attributes of the type are altered.
Christian Heimesa62da1d2008-01-12 19:39:10 +000061
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000062 Invariants:
Christian Heimesa62da1d2008-01-12 19:39:10 +000063
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000064 - Py_TPFLAGS_VALID_VERSION_TAG is never set if
65 Py_TPFLAGS_HAVE_VERSION_TAG is not set (e.g. on type
66 objects coming from non-recompiled extension modules)
Christian Heimesa62da1d2008-01-12 19:39:10 +000067
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000068 - before Py_TPFLAGS_VALID_VERSION_TAG can be set on a type,
69 it must first be set on all super types.
Christian Heimesa62da1d2008-01-12 19:39:10 +000070
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000071 This function clears the Py_TPFLAGS_VALID_VERSION_TAG of a
72 type (so it must first clear it on all subclasses). The
73 tp_version_tag value is meaningless unless this flag is set.
74 We don't assign new version tags eagerly, but only as
75 needed.
76 */
77 PyObject *raw, *ref;
78 Py_ssize_t i, n;
Christian Heimesa62da1d2008-01-12 19:39:10 +000079
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000080 if (!PyType_HasFeature(type, Py_TPFLAGS_VALID_VERSION_TAG))
81 return;
Christian Heimesa62da1d2008-01-12 19:39:10 +000082
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000083 raw = type->tp_subclasses;
84 if (raw != NULL) {
85 n = PyList_GET_SIZE(raw);
86 for (i = 0; i < n; i++) {
87 ref = PyList_GET_ITEM(raw, i);
88 ref = PyWeakref_GET_OBJECT(ref);
89 if (ref != Py_None) {
90 PyType_Modified((PyTypeObject *)ref);
91 }
92 }
93 }
94 type->tp_flags &= ~Py_TPFLAGS_VALID_VERSION_TAG;
Christian Heimesa62da1d2008-01-12 19:39:10 +000095}
96
97static void
98type_mro_modified(PyTypeObject *type, PyObject *bases) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000099 /*
100 Check that all base classes or elements of the mro of type are
101 able to be cached. This function is called after the base
102 classes or mro of the type are altered.
Christian Heimesa62da1d2008-01-12 19:39:10 +0000103
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000104 Unset HAVE_VERSION_TAG and VALID_VERSION_TAG if the type
105 inherits from an old-style class, either directly or if it
106 appears in the MRO of a new-style class. No support either for
107 custom MROs that include types that are not officially super
108 types.
Christian Heimesa62da1d2008-01-12 19:39:10 +0000109
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000110 Called from mro_internal, which will subsequently be called on
111 each subclass when their mro is recursively updated.
112 */
113 Py_ssize_t i, n;
114 int clear = 0;
Christian Heimesa62da1d2008-01-12 19:39:10 +0000115
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000116 if (!PyType_HasFeature(type, Py_TPFLAGS_HAVE_VERSION_TAG))
117 return;
Christian Heimesa62da1d2008-01-12 19:39:10 +0000118
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000119 n = PyTuple_GET_SIZE(bases);
120 for (i = 0; i < n; i++) {
121 PyObject *b = PyTuple_GET_ITEM(bases, i);
122 PyTypeObject *cls;
Christian Heimesa62da1d2008-01-12 19:39:10 +0000123
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000124 if (!PyType_Check(b) ) {
125 clear = 1;
126 break;
127 }
Christian Heimesa62da1d2008-01-12 19:39:10 +0000128
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000129 cls = (PyTypeObject *)b;
Christian Heimesa62da1d2008-01-12 19:39:10 +0000130
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000131 if (!PyType_HasFeature(cls, Py_TPFLAGS_HAVE_VERSION_TAG) ||
132 !PyType_IsSubtype(type, cls)) {
133 clear = 1;
134 break;
135 }
136 }
Christian Heimesa62da1d2008-01-12 19:39:10 +0000137
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000138 if (clear)
139 type->tp_flags &= ~(Py_TPFLAGS_HAVE_VERSION_TAG|
140 Py_TPFLAGS_VALID_VERSION_TAG);
Christian Heimesa62da1d2008-01-12 19:39:10 +0000141}
142
143static int
144assign_version_tag(PyTypeObject *type)
145{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000146 /* Ensure that the tp_version_tag is valid and set
147 Py_TPFLAGS_VALID_VERSION_TAG. To respect the invariant, this
148 must first be done on all super classes. Return 0 if this
149 cannot be done, 1 if Py_TPFLAGS_VALID_VERSION_TAG.
150 */
151 Py_ssize_t i, n;
152 PyObject *bases;
Christian Heimesa62da1d2008-01-12 19:39:10 +0000153
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000154 if (PyType_HasFeature(type, Py_TPFLAGS_VALID_VERSION_TAG))
155 return 1;
156 if (!PyType_HasFeature(type, Py_TPFLAGS_HAVE_VERSION_TAG))
157 return 0;
158 if (!PyType_HasFeature(type, Py_TPFLAGS_READY))
159 return 0;
Christian Heimesa62da1d2008-01-12 19:39:10 +0000160
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000161 type->tp_version_tag = next_version_tag++;
162 /* for stress-testing: next_version_tag &= 0xFF; */
Christian Heimesa62da1d2008-01-12 19:39:10 +0000163
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000164 if (type->tp_version_tag == 0) {
165 /* wrap-around or just starting Python - clear the whole
166 cache by filling names with references to Py_None.
167 Values are also set to NULL for added protection, as they
168 are borrowed reference */
169 for (i = 0; i < (1 << MCACHE_SIZE_EXP); i++) {
170 method_cache[i].value = NULL;
171 Py_XDECREF(method_cache[i].name);
172 method_cache[i].name = Py_None;
173 Py_INCREF(Py_None);
174 }
175 /* mark all version tags as invalid */
176 PyType_Modified(&PyBaseObject_Type);
177 return 1;
178 }
179 bases = type->tp_bases;
180 n = PyTuple_GET_SIZE(bases);
181 for (i = 0; i < n; i++) {
182 PyObject *b = PyTuple_GET_ITEM(bases, i);
183 assert(PyType_Check(b));
184 if (!assign_version_tag((PyTypeObject *)b))
185 return 0;
186 }
187 type->tp_flags |= Py_TPFLAGS_VALID_VERSION_TAG;
188 return 1;
Christian Heimesa62da1d2008-01-12 19:39:10 +0000189}
190
191
Guido van Rossum6f799372001-09-20 20:46:19 +0000192static PyMemberDef type_members[] = {
Benjamin Peterson0e102062010-08-25 23:13:17 +0000193 {"__basicsize__", T_PYSSIZET, offsetof(PyTypeObject,tp_basicsize),READONLY},
194 {"__itemsize__", T_PYSSIZET, offsetof(PyTypeObject, tp_itemsize), READONLY},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000195 {"__flags__", T_LONG, offsetof(PyTypeObject, tp_flags), READONLY},
196 {"__weakrefoffset__", T_LONG,
197 offsetof(PyTypeObject, tp_weaklistoffset), READONLY},
198 {"__base__", T_OBJECT, offsetof(PyTypeObject, tp_base), READONLY},
199 {"__dictoffset__", T_LONG,
200 offsetof(PyTypeObject, tp_dictoffset), READONLY},
201 {"__mro__", T_OBJECT, offsetof(PyTypeObject, tp_mro), READONLY},
202 {0}
Tim Peters6d6c1a32001-08-02 04:15:00 +0000203};
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000204
Benjamin Petersond9f23d22011-08-17 11:54:03 -0500205static int
206check_set_special_type_attr(PyTypeObject *type, PyObject *value, const char *name)
207{
208 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
209 PyErr_Format(PyExc_TypeError,
210 "can't set %s.%s", type->tp_name, name);
211 return 0;
212 }
213 if (!value) {
214 PyErr_Format(PyExc_TypeError,
215 "can't delete %s.%s", type->tp_name, name);
216 return 0;
217 }
218 return 1;
219}
220
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000221static PyObject *
Guido van Rossumc3542212001-08-16 09:18:56 +0000222type_name(PyTypeObject *type, void *context)
223{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000224 const char *s;
Guido van Rossumc3542212001-08-16 09:18:56 +0000225
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000226 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
227 PyHeapTypeObject* et = (PyHeapTypeObject*)type;
Tim Petersea7f75d2002-12-07 21:39:16 +0000228
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000229 Py_INCREF(et->ht_name);
230 return et->ht_name;
231 }
232 else {
233 s = strrchr(type->tp_name, '.');
234 if (s == NULL)
235 s = type->tp_name;
236 else
237 s++;
238 return PyUnicode_FromString(s);
239 }
Guido van Rossumc3542212001-08-16 09:18:56 +0000240}
241
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000242static int
243type_set_name(PyTypeObject *type, PyObject *value, void *context)
244{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000245 PyHeapTypeObject* et;
246 char *tp_name;
247 PyObject *tmp;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000248
Benjamin Petersond9f23d22011-08-17 11:54:03 -0500249 if (!check_set_special_type_attr(type, value, "__name__"))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000250 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000251 if (!PyUnicode_Check(value)) {
252 PyErr_Format(PyExc_TypeError,
253 "can only assign string to %s.__name__, not '%s'",
254 type->tp_name, Py_TYPE(value)->tp_name);
255 return -1;
256 }
Guido van Rossume845c0f2007-11-02 23:07:07 +0000257
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000258 /* Check absence of null characters */
259 tmp = PyUnicode_FromStringAndSize("\0", 1);
260 if (tmp == NULL)
261 return -1;
262 if (PyUnicode_Contains(value, tmp) != 0) {
263 Py_DECREF(tmp);
264 PyErr_Format(PyExc_ValueError,
265 "__name__ must not contain null bytes");
266 return -1;
267 }
268 Py_DECREF(tmp);
Guido van Rossume845c0f2007-11-02 23:07:07 +0000269
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000270 tp_name = _PyUnicode_AsString(value);
271 if (tp_name == NULL)
272 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000273
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000274 et = (PyHeapTypeObject*)type;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000275
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000276 Py_INCREF(value);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000277
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000278 Py_DECREF(et->ht_name);
279 et->ht_name = value;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000280
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000281 type->tp_name = tp_name;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000282
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000283 return 0;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000284}
285
Guido van Rossumc3542212001-08-16 09:18:56 +0000286static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000287type_module(PyTypeObject *type, void *context)
Guido van Rossum29ca26e1995-01-07 11:58:15 +0000288{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000289 PyObject *mod;
290 char *s;
Guido van Rossumc3542212001-08-16 09:18:56 +0000291
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000292 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
293 mod = PyDict_GetItemString(type->tp_dict, "__module__");
294 if (!mod) {
295 PyErr_Format(PyExc_AttributeError, "__module__");
296 return 0;
297 }
298 Py_XINCREF(mod);
299 return mod;
300 }
301 else {
302 s = strrchr(type->tp_name, '.');
303 if (s != NULL)
304 return PyUnicode_FromStringAndSize(
305 type->tp_name, (Py_ssize_t)(s - type->tp_name));
306 return PyUnicode_FromString("builtins");
307 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000308}
309
Guido van Rossum3926a632001-09-25 16:25:58 +0000310static int
311type_set_module(PyTypeObject *type, PyObject *value, void *context)
312{
Benjamin Petersond9f23d22011-08-17 11:54:03 -0500313 if (!check_set_special_type_attr(type, value, "__module__"))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000314 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000315
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000316 PyType_Modified(type);
Christian Heimesa62da1d2008-01-12 19:39:10 +0000317
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000318 return PyDict_SetItemString(type->tp_dict, "__module__", value);
Guido van Rossum3926a632001-09-25 16:25:58 +0000319}
320
Tim Peters6d6c1a32001-08-02 04:15:00 +0000321static PyObject *
Christian Heimes9e7f1d22008-02-28 12:27:11 +0000322type_abstractmethods(PyTypeObject *type, void *context)
323{
Benjamin Petersonaec5fd12010-10-02 00:03:31 +0000324 PyObject *mod = NULL;
Benjamin Peterson84060b82010-10-03 02:13:39 +0000325 /* type itself has an __abstractmethods__ descriptor (this). Don't return
326 that. */
Benjamin Petersonaec5fd12010-10-02 00:03:31 +0000327 if (type != &PyType_Type)
328 mod = PyDict_GetItemString(type->tp_dict, "__abstractmethods__");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000329 if (!mod) {
Benjamin Peterson23b628e2011-01-12 18:56:07 +0000330 PyErr_SetString(PyExc_AttributeError, "__abstractmethods__");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000331 return NULL;
332 }
333 Py_XINCREF(mod);
334 return mod;
Christian Heimes9e7f1d22008-02-28 12:27:11 +0000335}
336
337static int
338type_set_abstractmethods(PyTypeObject *type, PyObject *value, void *context)
339{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000340 /* __abstractmethods__ should only be set once on a type, in
341 abc.ABCMeta.__new__, so this function doesn't do anything
342 special to update subclasses.
343 */
Benjamin Peterson477ba912011-01-12 15:34:01 +0000344 int res;
345 if (value != NULL) {
346 res = PyDict_SetItemString(type->tp_dict, "__abstractmethods__", value);
347 }
348 else {
349 res = PyDict_DelItemString(type->tp_dict, "__abstractmethods__");
350 if (res && PyErr_ExceptionMatches(PyExc_KeyError)) {
Benjamin Peterson23b628e2011-01-12 18:56:07 +0000351 PyErr_SetString(PyExc_AttributeError, "__abstractmethods__");
Benjamin Peterson477ba912011-01-12 15:34:01 +0000352 return -1;
353 }
354 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000355 if (res == 0) {
356 PyType_Modified(type);
357 if (value && PyObject_IsTrue(value)) {
358 type->tp_flags |= Py_TPFLAGS_IS_ABSTRACT;
359 }
360 else {
361 type->tp_flags &= ~Py_TPFLAGS_IS_ABSTRACT;
362 }
363 }
364 return res;
Christian Heimes9e7f1d22008-02-28 12:27:11 +0000365}
366
367static PyObject *
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000368type_get_bases(PyTypeObject *type, void *context)
369{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000370 Py_INCREF(type->tp_bases);
371 return type->tp_bases;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000372}
373
374static PyTypeObject *best_base(PyObject *);
375static int mro_internal(PyTypeObject *);
376static int compatible_for_assignment(PyTypeObject *, PyTypeObject *, char *);
377static int add_subclass(PyTypeObject*, PyTypeObject*);
378static void remove_subclass(PyTypeObject *, PyTypeObject *);
379static void update_all_slots(PyTypeObject *);
380
Guido van Rossum8d24ee92003-03-24 23:49:49 +0000381typedef int (*update_callback)(PyTypeObject *, void *);
382static int update_subclasses(PyTypeObject *type, PyObject *name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000383 update_callback callback, void *data);
Guido van Rossum8d24ee92003-03-24 23:49:49 +0000384static int recurse_down_subclasses(PyTypeObject *type, PyObject *name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000385 update_callback callback, void *data);
Guido van Rossum8d24ee92003-03-24 23:49:49 +0000386
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000387static int
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000388mro_subclasses(PyTypeObject *type, PyObject* temp)
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000389{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000390 PyTypeObject *subclass;
391 PyObject *ref, *subclasses, *old_mro;
392 Py_ssize_t i, n;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000393
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000394 subclasses = type->tp_subclasses;
395 if (subclasses == NULL)
396 return 0;
397 assert(PyList_Check(subclasses));
398 n = PyList_GET_SIZE(subclasses);
399 for (i = 0; i < n; i++) {
400 ref = PyList_GET_ITEM(subclasses, i);
401 assert(PyWeakref_CheckRef(ref));
402 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
403 assert(subclass != NULL);
404 if ((PyObject *)subclass == Py_None)
405 continue;
406 assert(PyType_Check(subclass));
407 old_mro = subclass->tp_mro;
408 if (mro_internal(subclass) < 0) {
409 subclass->tp_mro = old_mro;
410 return -1;
411 }
412 else {
413 PyObject* tuple;
414 tuple = PyTuple_Pack(2, subclass, old_mro);
415 Py_DECREF(old_mro);
416 if (!tuple)
417 return -1;
418 if (PyList_Append(temp, tuple) < 0)
419 return -1;
420 Py_DECREF(tuple);
421 }
422 if (mro_subclasses(subclass, temp) < 0)
423 return -1;
424 }
425 return 0;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000426}
427
428static int
429type_set_bases(PyTypeObject *type, PyObject *value, void *context)
430{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000431 Py_ssize_t i;
432 int r = 0;
433 PyObject *ob, *temp;
434 PyTypeObject *new_base, *old_base;
435 PyObject *old_bases, *old_mro;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000436
Benjamin Petersond9f23d22011-08-17 11:54:03 -0500437 if (!check_set_special_type_attr(type, value, "__bases__"))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000438 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000439 if (!PyTuple_Check(value)) {
440 PyErr_Format(PyExc_TypeError,
441 "can only assign tuple to %s.__bases__, not %s",
442 type->tp_name, Py_TYPE(value)->tp_name);
443 return -1;
444 }
445 if (PyTuple_GET_SIZE(value) == 0) {
446 PyErr_Format(PyExc_TypeError,
447 "can only assign non-empty tuple to %s.__bases__, not ()",
448 type->tp_name);
449 return -1;
450 }
451 for (i = 0; i < PyTuple_GET_SIZE(value); i++) {
452 ob = PyTuple_GET_ITEM(value, i);
453 if (!PyType_Check(ob)) {
454 PyErr_Format(
455 PyExc_TypeError,
456 "%s.__bases__ must be tuple of old- or new-style classes, not '%s'",
457 type->tp_name, Py_TYPE(ob)->tp_name);
458 return -1;
459 }
460 if (PyType_Check(ob)) {
461 if (PyType_IsSubtype((PyTypeObject*)ob, type)) {
462 PyErr_SetString(PyExc_TypeError,
463 "a __bases__ item causes an inheritance cycle");
464 return -1;
465 }
466 }
467 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000468
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000469 new_base = best_base(value);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000470
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000471 if (!new_base) {
472 return -1;
473 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000474
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000475 if (!compatible_for_assignment(type->tp_base, new_base, "__bases__"))
476 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000477
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000478 Py_INCREF(new_base);
479 Py_INCREF(value);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000480
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000481 old_bases = type->tp_bases;
482 old_base = type->tp_base;
483 old_mro = type->tp_mro;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000484
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000485 type->tp_bases = value;
486 type->tp_base = new_base;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000487
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000488 if (mro_internal(type) < 0) {
489 goto bail;
490 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000491
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000492 temp = PyList_New(0);
493 if (!temp)
494 goto bail;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000495
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000496 r = mro_subclasses(type, temp);
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000497
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000498 if (r < 0) {
499 for (i = 0; i < PyList_Size(temp); i++) {
500 PyTypeObject* cls;
501 PyObject* mro;
502 PyArg_UnpackTuple(PyList_GET_ITEM(temp, i),
503 "", 2, 2, &cls, &mro);
504 Py_INCREF(mro);
505 ob = cls->tp_mro;
506 cls->tp_mro = mro;
507 Py_DECREF(ob);
508 }
509 Py_DECREF(temp);
510 goto bail;
511 }
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000512
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000513 Py_DECREF(temp);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000514
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000515 /* any base that was in __bases__ but now isn't, we
516 need to remove |type| from its tp_subclasses.
517 conversely, any class now in __bases__ that wasn't
518 needs to have |type| added to its subclasses. */
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000519
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000520 /* for now, sod that: just remove from all old_bases,
521 add to all new_bases */
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000522
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000523 for (i = PyTuple_GET_SIZE(old_bases) - 1; i >= 0; i--) {
524 ob = PyTuple_GET_ITEM(old_bases, i);
525 if (PyType_Check(ob)) {
526 remove_subclass(
527 (PyTypeObject*)ob, type);
528 }
529 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000530
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000531 for (i = PyTuple_GET_SIZE(value) - 1; i >= 0; i--) {
532 ob = PyTuple_GET_ITEM(value, i);
533 if (PyType_Check(ob)) {
534 if (add_subclass((PyTypeObject*)ob, type) < 0)
535 r = -1;
536 }
537 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000538
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000539 update_all_slots(type);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000540
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000541 Py_DECREF(old_bases);
542 Py_DECREF(old_base);
543 Py_DECREF(old_mro);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000544
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000545 return r;
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000546
547 bail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000548 Py_DECREF(type->tp_bases);
549 Py_DECREF(type->tp_base);
550 if (type->tp_mro != old_mro) {
551 Py_DECREF(type->tp_mro);
552 }
Michael W. Hudsone723e452003-08-07 14:58:10 +0000553
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000554 type->tp_bases = old_bases;
555 type->tp_base = old_base;
556 type->tp_mro = old_mro;
Tim Petersea7f75d2002-12-07 21:39:16 +0000557
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000558 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000559}
560
561static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000562type_dict(PyTypeObject *type, void *context)
563{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000564 if (type->tp_dict == NULL) {
565 Py_INCREF(Py_None);
566 return Py_None;
567 }
568 return PyDictProxy_New(type->tp_dict);
Guido van Rossum29ca26e1995-01-07 11:58:15 +0000569}
570
Tim Peters24008312002-03-17 18:56:20 +0000571static PyObject *
572type_get_doc(PyTypeObject *type, void *context)
573{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000574 PyObject *result;
575 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE) && type->tp_doc != NULL)
576 return PyUnicode_FromString(type->tp_doc);
577 result = PyDict_GetItemString(type->tp_dict, "__doc__");
578 if (result == NULL) {
579 result = Py_None;
580 Py_INCREF(result);
581 }
582 else if (Py_TYPE(result)->tp_descr_get) {
583 result = Py_TYPE(result)->tp_descr_get(result, NULL,
584 (PyObject *)type);
585 }
586 else {
587 Py_INCREF(result);
588 }
589 return result;
Tim Peters24008312002-03-17 18:56:20 +0000590}
591
Benjamin Peterson01fc6cd2011-08-17 12:03:47 -0500592static int
593type_set_doc(PyTypeObject *type, PyObject *value, void *context)
594{
595 if (!check_set_special_type_attr(type, value, "__doc__"))
596 return -1;
597 PyType_Modified(type);
598 return PyDict_SetItemString(type->tp_dict, "__doc__", value);
599}
600
Antoine Pitrouec569b72008-08-26 22:40:48 +0000601static PyObject *
602type___instancecheck__(PyObject *type, PyObject *inst)
603{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000604 switch (_PyObject_RealIsInstance(inst, type)) {
605 case -1:
606 return NULL;
607 case 0:
608 Py_RETURN_FALSE;
609 default:
610 Py_RETURN_TRUE;
611 }
Antoine Pitrouec569b72008-08-26 22:40:48 +0000612}
613
614
615static PyObject *
Antoine Pitrouec569b72008-08-26 22:40:48 +0000616type___subclasscheck__(PyObject *type, PyObject *inst)
617{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000618 switch (_PyObject_RealIsSubclass(inst, type)) {
619 case -1:
620 return NULL;
621 case 0:
622 Py_RETURN_FALSE;
623 default:
624 Py_RETURN_TRUE;
625 }
Antoine Pitrouec569b72008-08-26 22:40:48 +0000626}
627
Antoine Pitrouec569b72008-08-26 22:40:48 +0000628
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000629static PyGetSetDef type_getsets[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000630 {"__name__", (getter)type_name, (setter)type_set_name, NULL},
631 {"__bases__", (getter)type_get_bases, (setter)type_set_bases, NULL},
632 {"__module__", (getter)type_module, (setter)type_set_module, NULL},
633 {"__abstractmethods__", (getter)type_abstractmethods,
634 (setter)type_set_abstractmethods, NULL},
635 {"__dict__", (getter)type_dict, NULL, NULL},
Benjamin Peterson01fc6cd2011-08-17 12:03:47 -0500636 {"__doc__", (getter)type_get_doc, (setter)type_set_doc, NULL},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000637 {0}
Tim Peters6d6c1a32001-08-02 04:15:00 +0000638};
639
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000640static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000641type_repr(PyTypeObject *type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000642{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000643 PyObject *mod, *name, *rtn;
Guido van Rossumc3542212001-08-16 09:18:56 +0000644
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000645 mod = type_module(type, NULL);
646 if (mod == NULL)
647 PyErr_Clear();
648 else if (!PyUnicode_Check(mod)) {
649 Py_DECREF(mod);
650 mod = NULL;
651 }
652 name = type_name(type, NULL);
653 if (name == NULL)
654 return NULL;
Barry Warsaw7ce36942001-08-24 18:34:26 +0000655
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000656 if (mod != NULL && PyUnicode_CompareWithASCIIString(mod, "builtins"))
657 rtn = PyUnicode_FromFormat("<class '%U.%U'>", mod, name);
658 else
659 rtn = PyUnicode_FromFormat("<class '%s'>", type->tp_name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000660
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000661 Py_XDECREF(mod);
662 Py_DECREF(name);
663 return rtn;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000664}
665
Tim Peters6d6c1a32001-08-02 04:15:00 +0000666static PyObject *
667type_call(PyTypeObject *type, PyObject *args, PyObject *kwds)
668{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000669 PyObject *obj;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000670
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000671 if (type->tp_new == NULL) {
672 PyErr_Format(PyExc_TypeError,
673 "cannot create '%.100s' instances",
674 type->tp_name);
675 return NULL;
676 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000677
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000678 obj = type->tp_new(type, args, kwds);
679 if (obj != NULL) {
680 /* Ugly exception: when the call was type(something),
681 don't call tp_init on the result. */
682 if (type == &PyType_Type &&
683 PyTuple_Check(args) && PyTuple_GET_SIZE(args) == 1 &&
684 (kwds == NULL ||
685 (PyDict_Check(kwds) && PyDict_Size(kwds) == 0)))
686 return obj;
687 /* If the returned object is not an instance of type,
688 it won't be initialized. */
689 if (!PyType_IsSubtype(Py_TYPE(obj), type))
690 return obj;
691 type = Py_TYPE(obj);
692 if (type->tp_init != NULL &&
693 type->tp_init(obj, args, kwds) < 0) {
694 Py_DECREF(obj);
695 obj = NULL;
696 }
697 }
698 return obj;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000699}
700
701PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000702PyType_GenericAlloc(PyTypeObject *type, Py_ssize_t nitems)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000703{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000704 PyObject *obj;
705 const size_t size = _PyObject_VAR_SIZE(type, nitems+1);
706 /* note that we need to add one, for the sentinel */
Tim Peters406fe3b2001-10-06 19:04:01 +0000707
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000708 if (PyType_IS_GC(type))
709 obj = _PyObject_GC_Malloc(size);
710 else
711 obj = (PyObject *)PyObject_MALLOC(size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000712
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000713 if (obj == NULL)
714 return PyErr_NoMemory();
Tim Peters406fe3b2001-10-06 19:04:01 +0000715
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000716 memset(obj, '\0', size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000717
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000718 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
719 Py_INCREF(type);
Tim Peters406fe3b2001-10-06 19:04:01 +0000720
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000721 if (type->tp_itemsize == 0)
722 PyObject_INIT(obj, type);
723 else
724 (void) PyObject_INIT_VAR((PyVarObject *)obj, type, nitems);
Tim Peters406fe3b2001-10-06 19:04:01 +0000725
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000726 if (PyType_IS_GC(type))
727 _PyObject_GC_TRACK(obj);
728 return obj;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000729}
730
731PyObject *
732PyType_GenericNew(PyTypeObject *type, PyObject *args, PyObject *kwds)
733{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000734 return type->tp_alloc(type, 0);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000735}
736
Guido van Rossum9475a232001-10-05 20:51:39 +0000737/* Helpers for subtyping */
738
739static int
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000740traverse_slots(PyTypeObject *type, PyObject *self, visitproc visit, void *arg)
741{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000742 Py_ssize_t i, n;
743 PyMemberDef *mp;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000744
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000745 n = Py_SIZE(type);
746 mp = PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type);
747 for (i = 0; i < n; i++, mp++) {
748 if (mp->type == T_OBJECT_EX) {
749 char *addr = (char *)self + mp->offset;
750 PyObject *obj = *(PyObject **)addr;
751 if (obj != NULL) {
752 int err = visit(obj, arg);
753 if (err)
754 return err;
755 }
756 }
757 }
758 return 0;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000759}
760
761static int
Guido van Rossum9475a232001-10-05 20:51:39 +0000762subtype_traverse(PyObject *self, visitproc visit, void *arg)
763{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000764 PyTypeObject *type, *base;
765 traverseproc basetraverse;
Guido van Rossum9475a232001-10-05 20:51:39 +0000766
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000767 /* Find the nearest base with a different tp_traverse,
768 and traverse slots while we're at it */
769 type = Py_TYPE(self);
770 base = type;
771 while ((basetraverse = base->tp_traverse) == subtype_traverse) {
772 if (Py_SIZE(base)) {
773 int err = traverse_slots(base, self, visit, arg);
774 if (err)
775 return err;
776 }
777 base = base->tp_base;
778 assert(base);
779 }
Guido van Rossum9475a232001-10-05 20:51:39 +0000780
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000781 if (type->tp_dictoffset != base->tp_dictoffset) {
782 PyObject **dictptr = _PyObject_GetDictPtr(self);
783 if (dictptr && *dictptr)
784 Py_VISIT(*dictptr);
785 }
Guido van Rossum9475a232001-10-05 20:51:39 +0000786
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000787 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
788 /* For a heaptype, the instances count as references
789 to the type. Traverse the type so the collector
790 can find cycles involving this link. */
791 Py_VISIT(type);
Guido van Rossuma3862092002-06-10 15:24:42 +0000792
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000793 if (basetraverse)
794 return basetraverse(self, visit, arg);
795 return 0;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000796}
797
798static void
799clear_slots(PyTypeObject *type, PyObject *self)
800{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000801 Py_ssize_t i, n;
802 PyMemberDef *mp;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000803
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000804 n = Py_SIZE(type);
805 mp = PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type);
806 for (i = 0; i < n; i++, mp++) {
807 if (mp->type == T_OBJECT_EX && !(mp->flags & READONLY)) {
808 char *addr = (char *)self + mp->offset;
809 PyObject *obj = *(PyObject **)addr;
810 if (obj != NULL) {
811 *(PyObject **)addr = NULL;
812 Py_DECREF(obj);
813 }
814 }
815 }
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000816}
817
818static int
819subtype_clear(PyObject *self)
820{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000821 PyTypeObject *type, *base;
822 inquiry baseclear;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000823
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000824 /* Find the nearest base with a different tp_clear
825 and clear slots while we're at it */
826 type = Py_TYPE(self);
827 base = type;
828 while ((baseclear = base->tp_clear) == subtype_clear) {
829 if (Py_SIZE(base))
830 clear_slots(base, self);
831 base = base->tp_base;
832 assert(base);
833 }
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000834
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000835 /* There's no need to clear the instance dict (if any);
836 the collector will call its tp_clear handler. */
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000837
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000838 if (baseclear)
839 return baseclear(self);
840 return 0;
Guido van Rossum9475a232001-10-05 20:51:39 +0000841}
Tim Peters6d6c1a32001-08-02 04:15:00 +0000842
843static void
844subtype_dealloc(PyObject *self)
845{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000846 PyTypeObject *type, *base;
847 destructor basedealloc;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000848
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000849 /* Extract the type; we expect it to be a heap type */
850 type = Py_TYPE(self);
851 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000852
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000853 /* Test whether the type has GC exactly once */
Guido van Rossum22b13872002-08-06 21:41:44 +0000854
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000855 if (!PyType_IS_GC(type)) {
856 /* It's really rare to find a dynamic type that doesn't have
857 GC; it can only happen when deriving from 'object' and not
858 adding any slots or instance variables. This allows
859 certain simplifications: there's no need to call
860 clear_slots(), or DECREF the dict, or clear weakrefs. */
Guido van Rossum22b13872002-08-06 21:41:44 +0000861
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000862 /* Maybe call finalizer; exit early if resurrected */
863 if (type->tp_del) {
864 type->tp_del(self);
865 if (self->ob_refcnt > 0)
866 return;
867 }
Guido van Rossum22b13872002-08-06 21:41:44 +0000868
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000869 /* Find the nearest base with a different tp_dealloc */
870 base = type;
871 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
872 assert(Py_SIZE(base) == 0);
873 base = base->tp_base;
874 assert(base);
875 }
Guido van Rossum22b13872002-08-06 21:41:44 +0000876
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000877 /* Extract the type again; tp_del may have changed it */
878 type = Py_TYPE(self);
Benjamin Peterson193152c2009-04-25 01:08:45 +0000879
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000880 /* Call the base tp_dealloc() */
881 assert(basedealloc);
882 basedealloc(self);
Guido van Rossum22b13872002-08-06 21:41:44 +0000883
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000884 /* Can't reference self beyond this point */
885 Py_DECREF(type);
Guido van Rossum22b13872002-08-06 21:41:44 +0000886
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000887 /* Done */
888 return;
889 }
Guido van Rossum22b13872002-08-06 21:41:44 +0000890
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000891 /* We get here only if the type has GC */
Guido van Rossum22b13872002-08-06 21:41:44 +0000892
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000893 /* UnTrack and re-Track around the trashcan macro, alas */
894 /* See explanation at end of function for full disclosure */
895 PyObject_GC_UnTrack(self);
896 ++_PyTrash_delete_nesting;
897 Py_TRASHCAN_SAFE_BEGIN(self);
898 --_PyTrash_delete_nesting;
899 /* DO NOT restore GC tracking at this point. weakref callbacks
900 * (if any, and whether directly here or indirectly in something we
901 * call) may trigger GC, and if self is tracked at that point, it
902 * will look like trash to GC and GC will try to delete self again.
903 */
Guido van Rossum22b13872002-08-06 21:41:44 +0000904
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000905 /* Find the nearest base with a different tp_dealloc */
906 base = type;
Brett Cannonb94767f2011-02-22 20:15:44 +0000907 while ((/*basedealloc =*/ base->tp_dealloc) == subtype_dealloc) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000908 base = base->tp_base;
909 assert(base);
910 }
Guido van Rossum14227b42001-12-06 02:35:58 +0000911
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000912 /* If we added a weaklist, we clear it. Do this *before* calling
913 the finalizer (__del__), clearing slots, or clearing the instance
914 dict. */
Guido van Rossum59195fd2003-06-13 20:54:40 +0000915
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000916 if (type->tp_weaklistoffset && !base->tp_weaklistoffset)
917 PyObject_ClearWeakRefs(self);
Guido van Rossum1987c662003-05-29 14:29:23 +0000918
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000919 /* Maybe call finalizer; exit early if resurrected */
920 if (type->tp_del) {
921 _PyObject_GC_TRACK(self);
922 type->tp_del(self);
923 if (self->ob_refcnt > 0)
924 goto endlabel; /* resurrected */
925 else
926 _PyObject_GC_UNTRACK(self);
927 /* New weakrefs could be created during the finalizer call.
928 If this occurs, clear them out without calling their
929 finalizers since they might rely on part of the object
930 being finalized that has already been destroyed. */
931 if (type->tp_weaklistoffset && !base->tp_weaklistoffset) {
932 /* Modeled after GET_WEAKREFS_LISTPTR() */
933 PyWeakReference **list = (PyWeakReference **) \
934 PyObject_GET_WEAKREFS_LISTPTR(self);
935 while (*list)
936 _PyWeakref_ClearRef(*list);
937 }
938 }
Guido van Rossum1987c662003-05-29 14:29:23 +0000939
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000940 /* Clear slots up to the nearest base with a different tp_dealloc */
941 base = type;
942 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
943 if (Py_SIZE(base))
944 clear_slots(base, self);
945 base = base->tp_base;
946 assert(base);
947 }
Guido van Rossum59195fd2003-06-13 20:54:40 +0000948
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000949 /* If we added a dict, DECREF it */
950 if (type->tp_dictoffset && !base->tp_dictoffset) {
951 PyObject **dictptr = _PyObject_GetDictPtr(self);
952 if (dictptr != NULL) {
953 PyObject *dict = *dictptr;
954 if (dict != NULL) {
955 Py_DECREF(dict);
956 *dictptr = NULL;
957 }
958 }
959 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000960
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000961 /* Extract the type again; tp_del may have changed it */
962 type = Py_TYPE(self);
Benjamin Peterson193152c2009-04-25 01:08:45 +0000963
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000964 /* Call the base tp_dealloc(); first retrack self if
965 * basedealloc knows about gc.
966 */
967 if (PyType_IS_GC(base))
968 _PyObject_GC_TRACK(self);
969 assert(basedealloc);
970 basedealloc(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000971
Antoine Pitrou84f1b172011-07-12 21:57:15 +0200972 PyType_Modified(type);
973
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000974 /* Can't reference self beyond this point */
975 Py_DECREF(type);
Guido van Rossum22b13872002-08-06 21:41:44 +0000976
Guido van Rossum0906e072002-08-07 20:42:09 +0000977 endlabel:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000978 ++_PyTrash_delete_nesting;
979 Py_TRASHCAN_SAFE_END(self);
980 --_PyTrash_delete_nesting;
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000981
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000982 /* Explanation of the weirdness around the trashcan macros:
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000983
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000984 Q. What do the trashcan macros do?
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000985
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000986 A. Read the comment titled "Trashcan mechanism" in object.h.
987 For one, this explains why there must be a call to GC-untrack
988 before the trashcan begin macro. Without understanding the
989 trashcan code, the answers to the following questions don't make
990 sense.
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000991
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000992 Q. Why do we GC-untrack before the trashcan and then immediately
993 GC-track again afterward?
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000994
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000995 A. In the case that the base class is GC-aware, the base class
996 probably GC-untracks the object. If it does that using the
997 UNTRACK macro, this will crash when the object is already
998 untracked. Because we don't know what the base class does, the
999 only safe thing is to make sure the object is tracked when we
1000 call the base class dealloc. But... The trashcan begin macro
1001 requires that the object is *untracked* before it is called. So
1002 the dance becomes:
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001003
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001004 GC untrack
1005 trashcan begin
1006 GC track
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001007
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001008 Q. Why did the last question say "immediately GC-track again"?
1009 It's nowhere near immediately.
Tim Petersf7f9e992003-11-13 21:59:32 +00001010
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001011 A. Because the code *used* to re-track immediately. Bad Idea.
1012 self has a refcount of 0, and if gc ever gets its hands on it
1013 (which can happen if any weakref callback gets invoked), it
1014 looks like trash to gc too, and gc also tries to delete self
Ezio Melotti13925002011-03-16 11:05:33 +02001015 then. But we're already deleting self. Double deallocation is
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001016 a subtle disaster.
Tim Petersf7f9e992003-11-13 21:59:32 +00001017
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001018 Q. Why the bizarre (net-zero) manipulation of
1019 _PyTrash_delete_nesting around the trashcan macros?
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001020
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001021 A. Some base classes (e.g. list) also use the trashcan mechanism.
1022 The following scenario used to be possible:
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001023
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001024 - suppose the trashcan level is one below the trashcan limit
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001025
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001026 - subtype_dealloc() is called
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001027
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001028 - the trashcan limit is not yet reached, so the trashcan level
1029 is incremented and the code between trashcan begin and end is
1030 executed
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001031
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001032 - this destroys much of the object's contents, including its
1033 slots and __dict__
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001034
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001035 - basedealloc() is called; this is really list_dealloc(), or
1036 some other type which also uses the trashcan macros
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001037
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001038 - the trashcan limit is now reached, so the object is put on the
1039 trashcan's to-be-deleted-later list
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001040
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001041 - basedealloc() returns
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001042
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001043 - subtype_dealloc() decrefs the object's type
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001044
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001045 - subtype_dealloc() returns
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001046
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001047 - later, the trashcan code starts deleting the objects from its
1048 to-be-deleted-later list
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001049
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001050 - subtype_dealloc() is called *AGAIN* for the same object
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001051
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001052 - at the very least (if the destroyed slots and __dict__ don't
1053 cause problems) the object's type gets decref'ed a second
1054 time, which is *BAD*!!!
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001055
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001056 The remedy is to make sure that if the code between trashcan
1057 begin and end in subtype_dealloc() is called, the code between
1058 trashcan begin and end in basedealloc() will also be called.
1059 This is done by decrementing the level after passing into the
1060 trashcan block, and incrementing it just before leaving the
1061 block.
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001062
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001063 But now it's possible that a chain of objects consisting solely
1064 of objects whose deallocator is subtype_dealloc() will defeat
1065 the trashcan mechanism completely: the decremented level means
1066 that the effective level never reaches the limit. Therefore, we
1067 *increment* the level *before* entering the trashcan block, and
1068 matchingly decrement it after leaving. This means the trashcan
1069 code will trigger a little early, but that's no big deal.
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001070
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001071 Q. Are there any live examples of code in need of all this
1072 complexity?
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001073
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001074 A. Yes. See SF bug 668433 for code that crashed (when Python was
1075 compiled in debug mode) before the trashcan level manipulations
1076 were added. For more discussion, see SF patches 581742, 575073
1077 and bug 574207.
1078 */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001079}
1080
Jeremy Hylton938ace62002-07-17 16:30:39 +00001081static PyTypeObject *solid_base(PyTypeObject *type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001082
Tim Peters6d6c1a32001-08-02 04:15:00 +00001083/* type test with subclassing support */
1084
1085int
1086PyType_IsSubtype(PyTypeObject *a, PyTypeObject *b)
1087{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001088 PyObject *mro;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001089
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001090 mro = a->tp_mro;
1091 if (mro != NULL) {
1092 /* Deal with multiple inheritance without recursion
1093 by walking the MRO tuple */
1094 Py_ssize_t i, n;
1095 assert(PyTuple_Check(mro));
1096 n = PyTuple_GET_SIZE(mro);
1097 for (i = 0; i < n; i++) {
1098 if (PyTuple_GET_ITEM(mro, i) == (PyObject *)b)
1099 return 1;
1100 }
1101 return 0;
1102 }
1103 else {
1104 /* a is not completely initilized yet; follow tp_base */
1105 do {
1106 if (a == b)
1107 return 1;
1108 a = a->tp_base;
1109 } while (a != NULL);
1110 return b == &PyBaseObject_Type;
1111 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001112}
1113
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001114/* Internal routines to do a method lookup in the type
Guido van Rossum60718732001-08-28 17:47:51 +00001115 without looking in the instance dictionary
1116 (so we can't use PyObject_GetAttr) but still binding
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001117 it to the instance. The arguments are the object,
Guido van Rossum60718732001-08-28 17:47:51 +00001118 the method name as a C string, and the address of a
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001119 static variable used to cache the interned Python string.
1120
1121 Two variants:
1122
1123 - lookup_maybe() returns NULL without raising an exception
1124 when the _PyType_Lookup() call fails;
1125
1126 - lookup_method() always raises an exception upon errors.
Benjamin Peterson224205f2009-05-08 03:25:19 +00001127
1128 - _PyObject_LookupSpecial() exported for the benefit of other places.
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001129*/
Guido van Rossum60718732001-08-28 17:47:51 +00001130
1131static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001132lookup_maybe(PyObject *self, char *attrstr, PyObject **attrobj)
Guido van Rossum60718732001-08-28 17:47:51 +00001133{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001134 PyObject *res;
Guido van Rossum60718732001-08-28 17:47:51 +00001135
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001136 if (*attrobj == NULL) {
1137 *attrobj = PyUnicode_InternFromString(attrstr);
1138 if (*attrobj == NULL)
1139 return NULL;
1140 }
1141 res = _PyType_Lookup(Py_TYPE(self), *attrobj);
1142 if (res != NULL) {
1143 descrgetfunc f;
1144 if ((f = Py_TYPE(res)->tp_descr_get) == NULL)
1145 Py_INCREF(res);
1146 else
1147 res = f(res, self, (PyObject *)(Py_TYPE(self)));
1148 }
1149 return res;
Guido van Rossum60718732001-08-28 17:47:51 +00001150}
1151
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001152static PyObject *
1153lookup_method(PyObject *self, char *attrstr, PyObject **attrobj)
1154{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001155 PyObject *res = lookup_maybe(self, attrstr, attrobj);
1156 if (res == NULL && !PyErr_Occurred())
1157 PyErr_SetObject(PyExc_AttributeError, *attrobj);
1158 return res;
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001159}
1160
Benjamin Peterson224205f2009-05-08 03:25:19 +00001161PyObject *
1162_PyObject_LookupSpecial(PyObject *self, char *attrstr, PyObject **attrobj)
1163{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001164 return lookup_maybe(self, attrstr, attrobj);
Benjamin Peterson224205f2009-05-08 03:25:19 +00001165}
1166
Guido van Rossum2730b132001-08-28 18:22:14 +00001167/* A variation of PyObject_CallMethod that uses lookup_method()
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001168 instead of PyObject_GetAttrString(). This uses the same convention
Guido van Rossum2730b132001-08-28 18:22:14 +00001169 as lookup_method to cache the interned name string object. */
1170
Neil Schemenauerf23473f2001-10-21 22:28:58 +00001171static PyObject *
Guido van Rossum2730b132001-08-28 18:22:14 +00001172call_method(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
1173{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001174 va_list va;
1175 PyObject *args, *func = 0, *retval;
1176 va_start(va, format);
Guido van Rossum2730b132001-08-28 18:22:14 +00001177
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001178 func = lookup_maybe(o, name, nameobj);
1179 if (func == NULL) {
1180 va_end(va);
1181 if (!PyErr_Occurred())
1182 PyErr_SetObject(PyExc_AttributeError, *nameobj);
1183 return NULL;
1184 }
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001185
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001186 if (format && *format)
1187 args = Py_VaBuildValue(format, va);
1188 else
1189 args = PyTuple_New(0);
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001190
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001191 va_end(va);
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001192
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001193 if (args == NULL)
1194 return NULL;
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001195
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001196 assert(PyTuple_Check(args));
1197 retval = PyObject_Call(func, args, NULL);
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001198
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001199 Py_DECREF(args);
1200 Py_DECREF(func);
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001201
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001202 return retval;
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001203}
1204
1205/* Clone of call_method() that returns NotImplemented when the lookup fails. */
1206
Neil Schemenauerf23473f2001-10-21 22:28:58 +00001207static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001208call_maybe(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
1209{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001210 va_list va;
1211 PyObject *args, *func = 0, *retval;
1212 va_start(va, format);
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001213
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001214 func = lookup_maybe(o, name, nameobj);
1215 if (func == NULL) {
1216 va_end(va);
Brian Curtindfc80e32011-08-10 20:28:54 -05001217 if (!PyErr_Occurred())
1218 Py_RETURN_NOTIMPLEMENTED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001219 return NULL;
1220 }
Guido van Rossum2730b132001-08-28 18:22:14 +00001221
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001222 if (format && *format)
1223 args = Py_VaBuildValue(format, va);
1224 else
1225 args = PyTuple_New(0);
Guido van Rossum2730b132001-08-28 18:22:14 +00001226
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001227 va_end(va);
Guido van Rossum2730b132001-08-28 18:22:14 +00001228
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001229 if (args == NULL)
1230 return NULL;
Guido van Rossum2730b132001-08-28 18:22:14 +00001231
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001232 assert(PyTuple_Check(args));
1233 retval = PyObject_Call(func, args, NULL);
Guido van Rossum2730b132001-08-28 18:22:14 +00001234
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001235 Py_DECREF(args);
1236 Py_DECREF(func);
Guido van Rossum2730b132001-08-28 18:22:14 +00001237
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001238 return retval;
Guido van Rossum2730b132001-08-28 18:22:14 +00001239}
1240
Tim Petersea7f75d2002-12-07 21:39:16 +00001241/*
Guido van Rossum1f121312002-11-14 19:49:16 +00001242 Method resolution order algorithm C3 described in
1243 "A Monotonic Superclass Linearization for Dylan",
1244 by Kim Barrett, Bob Cassel, Paul Haahr,
Tim Petersea7f75d2002-12-07 21:39:16 +00001245 David A. Moon, Keith Playford, and P. Tucker Withington.
Guido van Rossum1f121312002-11-14 19:49:16 +00001246 (OOPSLA 1996)
1247
Guido van Rossum98f33732002-11-25 21:36:54 +00001248 Some notes about the rules implied by C3:
1249
Tim Petersea7f75d2002-12-07 21:39:16 +00001250 No duplicate bases.
Guido van Rossum98f33732002-11-25 21:36:54 +00001251 It isn't legal to repeat a class in a list of base classes.
1252
1253 The next three properties are the 3 constraints in "C3".
1254
Tim Petersea7f75d2002-12-07 21:39:16 +00001255 Local precendece order.
Guido van Rossum98f33732002-11-25 21:36:54 +00001256 If A precedes B in C's MRO, then A will precede B in the MRO of all
1257 subclasses of C.
1258
1259 Monotonicity.
1260 The MRO of a class must be an extension without reordering of the
1261 MRO of each of its superclasses.
1262
1263 Extended Precedence Graph (EPG).
1264 Linearization is consistent if there is a path in the EPG from
1265 each class to all its successors in the linearization. See
1266 the paper for definition of EPG.
Guido van Rossum1f121312002-11-14 19:49:16 +00001267 */
1268
Tim Petersea7f75d2002-12-07 21:39:16 +00001269static int
Guido van Rossum1f121312002-11-14 19:49:16 +00001270tail_contains(PyObject *list, int whence, PyObject *o) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001271 Py_ssize_t j, size;
1272 size = PyList_GET_SIZE(list);
Guido van Rossum1f121312002-11-14 19:49:16 +00001273
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001274 for (j = whence+1; j < size; j++) {
1275 if (PyList_GET_ITEM(list, j) == o)
1276 return 1;
1277 }
1278 return 0;
Guido van Rossum1f121312002-11-14 19:49:16 +00001279}
1280
Guido van Rossum98f33732002-11-25 21:36:54 +00001281static PyObject *
1282class_name(PyObject *cls)
1283{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001284 PyObject *name = PyObject_GetAttrString(cls, "__name__");
1285 if (name == NULL) {
1286 PyErr_Clear();
1287 Py_XDECREF(name);
1288 name = PyObject_Repr(cls);
1289 }
1290 if (name == NULL)
1291 return NULL;
1292 if (!PyUnicode_Check(name)) {
1293 Py_DECREF(name);
1294 return NULL;
1295 }
1296 return name;
Guido van Rossum98f33732002-11-25 21:36:54 +00001297}
1298
1299static int
1300check_duplicates(PyObject *list)
1301{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001302 Py_ssize_t i, j, n;
1303 /* Let's use a quadratic time algorithm,
1304 assuming that the bases lists is short.
1305 */
1306 n = PyList_GET_SIZE(list);
1307 for (i = 0; i < n; i++) {
1308 PyObject *o = PyList_GET_ITEM(list, i);
1309 for (j = i + 1; j < n; j++) {
1310 if (PyList_GET_ITEM(list, j) == o) {
1311 o = class_name(o);
1312 if (o != NULL) {
1313 PyErr_Format(PyExc_TypeError,
1314 "duplicate base class %U",
1315 o);
1316 Py_DECREF(o);
1317 } else {
1318 PyErr_SetString(PyExc_TypeError,
1319 "duplicate base class");
1320 }
1321 return -1;
1322 }
1323 }
1324 }
1325 return 0;
Guido van Rossum98f33732002-11-25 21:36:54 +00001326}
1327
1328/* Raise a TypeError for an MRO order disagreement.
1329
1330 It's hard to produce a good error message. In the absence of better
1331 insight into error reporting, report the classes that were candidates
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001332 to be put next into the MRO. There is some conflict between the
Guido van Rossum98f33732002-11-25 21:36:54 +00001333 order in which they should be put in the MRO, but it's hard to
1334 diagnose what constraint can't be satisfied.
1335*/
1336
1337static void
1338set_mro_error(PyObject *to_merge, int *remain)
1339{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001340 Py_ssize_t i, n, off, to_merge_size;
1341 char buf[1000];
1342 PyObject *k, *v;
1343 PyObject *set = PyDict_New();
1344 if (!set) return;
Guido van Rossum98f33732002-11-25 21:36:54 +00001345
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001346 to_merge_size = PyList_GET_SIZE(to_merge);
1347 for (i = 0; i < to_merge_size; i++) {
1348 PyObject *L = PyList_GET_ITEM(to_merge, i);
1349 if (remain[i] < PyList_GET_SIZE(L)) {
1350 PyObject *c = PyList_GET_ITEM(L, remain[i]);
1351 if (PyDict_SetItem(set, c, Py_None) < 0) {
1352 Py_DECREF(set);
1353 return;
1354 }
1355 }
1356 }
1357 n = PyDict_Size(set);
Guido van Rossum98f33732002-11-25 21:36:54 +00001358
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001359 off = PyOS_snprintf(buf, sizeof(buf), "Cannot create a \
Raymond Hettingerf394df42003-04-06 19:13:41 +00001360consistent method resolution\norder (MRO) for bases");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001361 i = 0;
1362 while (PyDict_Next(set, &i, &k, &v) && (size_t)off < sizeof(buf)) {
1363 PyObject *name = class_name(k);
Victor Stinnere5f99f32010-05-19 01:42:46 +00001364 char *name_str;
1365 if (name != NULL) {
1366 name_str = _PyUnicode_AsString(name);
1367 if (name_str == NULL)
Victor Stinnerba644a62010-05-19 01:50:45 +00001368 name_str = "?";
Victor Stinnere5f99f32010-05-19 01:42:46 +00001369 } else
Victor Stinnerba644a62010-05-19 01:50:45 +00001370 name_str = "?";
Victor Stinnere5f99f32010-05-19 01:42:46 +00001371 off += PyOS_snprintf(buf + off, sizeof(buf) - off, " %s", name_str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001372 Py_XDECREF(name);
1373 if (--n && (size_t)(off+1) < sizeof(buf)) {
1374 buf[off++] = ',';
1375 buf[off] = '\0';
1376 }
1377 }
1378 PyErr_SetString(PyExc_TypeError, buf);
1379 Py_DECREF(set);
Guido van Rossum98f33732002-11-25 21:36:54 +00001380}
1381
Tim Petersea7f75d2002-12-07 21:39:16 +00001382static int
Guido van Rossum1f121312002-11-14 19:49:16 +00001383pmerge(PyObject *acc, PyObject* to_merge) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001384 Py_ssize_t i, j, to_merge_size, empty_cnt;
1385 int *remain;
1386 int ok;
Tim Petersea7f75d2002-12-07 21:39:16 +00001387
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001388 to_merge_size = PyList_GET_SIZE(to_merge);
Guido van Rossum1f121312002-11-14 19:49:16 +00001389
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001390 /* remain stores an index into each sublist of to_merge.
1391 remain[i] is the index of the next base in to_merge[i]
1392 that is not included in acc.
1393 */
1394 remain = (int *)PyMem_MALLOC(SIZEOF_INT*to_merge_size);
1395 if (remain == NULL)
1396 return -1;
1397 for (i = 0; i < to_merge_size; i++)
1398 remain[i] = 0;
Guido van Rossum1f121312002-11-14 19:49:16 +00001399
1400 again:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001401 empty_cnt = 0;
1402 for (i = 0; i < to_merge_size; i++) {
1403 PyObject *candidate;
Tim Petersea7f75d2002-12-07 21:39:16 +00001404
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001405 PyObject *cur_list = PyList_GET_ITEM(to_merge, i);
Guido van Rossum1f121312002-11-14 19:49:16 +00001406
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001407 if (remain[i] >= PyList_GET_SIZE(cur_list)) {
1408 empty_cnt++;
1409 continue;
1410 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001411
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001412 /* Choose next candidate for MRO.
Guido van Rossum98f33732002-11-25 21:36:54 +00001413
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001414 The input sequences alone can determine the choice.
1415 If not, choose the class which appears in the MRO
1416 of the earliest direct superclass of the new class.
1417 */
Guido van Rossum98f33732002-11-25 21:36:54 +00001418
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001419 candidate = PyList_GET_ITEM(cur_list, remain[i]);
1420 for (j = 0; j < to_merge_size; j++) {
1421 PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
1422 if (tail_contains(j_lst, remain[j], candidate)) {
1423 goto skip; /* continue outer loop */
1424 }
1425 }
1426 ok = PyList_Append(acc, candidate);
1427 if (ok < 0) {
1428 PyMem_Free(remain);
1429 return -1;
1430 }
1431 for (j = 0; j < to_merge_size; j++) {
1432 PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
1433 if (remain[j] < PyList_GET_SIZE(j_lst) &&
1434 PyList_GET_ITEM(j_lst, remain[j]) == candidate) {
1435 remain[j]++;
1436 }
1437 }
1438 goto again;
1439 skip: ;
1440 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001441
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001442 if (empty_cnt == to_merge_size) {
1443 PyMem_FREE(remain);
1444 return 0;
1445 }
1446 set_mro_error(to_merge, remain);
1447 PyMem_FREE(remain);
1448 return -1;
Guido van Rossum1f121312002-11-14 19:49:16 +00001449}
1450
Tim Peters6d6c1a32001-08-02 04:15:00 +00001451static PyObject *
1452mro_implementation(PyTypeObject *type)
1453{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001454 Py_ssize_t i, n;
1455 int ok;
1456 PyObject *bases, *result;
1457 PyObject *to_merge, *bases_aslist;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001458
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001459 if (type->tp_dict == NULL) {
1460 if (PyType_Ready(type) < 0)
1461 return NULL;
1462 }
Guido van Rossum63517572002-06-18 16:44:57 +00001463
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001464 /* Find a superclass linearization that honors the constraints
1465 of the explicit lists of bases and the constraints implied by
1466 each base class.
Guido van Rossum98f33732002-11-25 21:36:54 +00001467
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001468 to_merge is a list of lists, where each list is a superclass
1469 linearization implied by a base class. The last element of
1470 to_merge is the declared list of bases.
1471 */
Guido van Rossum98f33732002-11-25 21:36:54 +00001472
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001473 bases = type->tp_bases;
1474 n = PyTuple_GET_SIZE(bases);
Guido van Rossum1f121312002-11-14 19:49:16 +00001475
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001476 to_merge = PyList_New(n+1);
1477 if (to_merge == NULL)
1478 return NULL;
Guido van Rossum1f121312002-11-14 19:49:16 +00001479
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001480 for (i = 0; i < n; i++) {
1481 PyObject *base = PyTuple_GET_ITEM(bases, i);
1482 PyObject *parentMRO;
1483 parentMRO = PySequence_List(((PyTypeObject*)base)->tp_mro);
1484 if (parentMRO == NULL) {
1485 Py_DECREF(to_merge);
1486 return NULL;
1487 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001488
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001489 PyList_SET_ITEM(to_merge, i, parentMRO);
1490 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001491
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001492 bases_aslist = PySequence_List(bases);
1493 if (bases_aslist == NULL) {
1494 Py_DECREF(to_merge);
1495 return NULL;
1496 }
1497 /* This is just a basic sanity check. */
1498 if (check_duplicates(bases_aslist) < 0) {
1499 Py_DECREF(to_merge);
1500 Py_DECREF(bases_aslist);
1501 return NULL;
1502 }
1503 PyList_SET_ITEM(to_merge, n, bases_aslist);
Guido van Rossum1f121312002-11-14 19:49:16 +00001504
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001505 result = Py_BuildValue("[O]", (PyObject *)type);
1506 if (result == NULL) {
1507 Py_DECREF(to_merge);
1508 return NULL;
1509 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001510
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001511 ok = pmerge(result, to_merge);
1512 Py_DECREF(to_merge);
1513 if (ok < 0) {
1514 Py_DECREF(result);
1515 return NULL;
1516 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001517
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001518 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001519}
1520
1521static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001522mro_external(PyObject *self)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001523{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001524 PyTypeObject *type = (PyTypeObject *)self;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001525
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001526 return mro_implementation(type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001527}
1528
1529static int
1530mro_internal(PyTypeObject *type)
1531{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001532 PyObject *mro, *result, *tuple;
1533 int checkit = 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001534
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001535 if (Py_TYPE(type) == &PyType_Type) {
1536 result = mro_implementation(type);
1537 }
1538 else {
1539 static PyObject *mro_str;
1540 checkit = 1;
1541 mro = lookup_method((PyObject *)type, "mro", &mro_str);
1542 if (mro == NULL)
1543 return -1;
1544 result = PyObject_CallObject(mro, NULL);
1545 Py_DECREF(mro);
1546 }
1547 if (result == NULL)
1548 return -1;
1549 tuple = PySequence_Tuple(result);
1550 Py_DECREF(result);
1551 if (tuple == NULL)
1552 return -1;
1553 if (checkit) {
1554 Py_ssize_t i, len;
1555 PyObject *cls;
1556 PyTypeObject *solid;
Armin Rigo037d1e02005-12-29 17:07:39 +00001557
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001558 solid = solid_base(type);
Armin Rigo037d1e02005-12-29 17:07:39 +00001559
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001560 len = PyTuple_GET_SIZE(tuple);
Armin Rigo037d1e02005-12-29 17:07:39 +00001561
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001562 for (i = 0; i < len; i++) {
1563 PyTypeObject *t;
1564 cls = PyTuple_GET_ITEM(tuple, i);
1565 if (!PyType_Check(cls)) {
1566 PyErr_Format(PyExc_TypeError,
1567 "mro() returned a non-class ('%.500s')",
1568 Py_TYPE(cls)->tp_name);
1569 Py_DECREF(tuple);
1570 return -1;
1571 }
1572 t = (PyTypeObject*)cls;
1573 if (!PyType_IsSubtype(solid, solid_base(t))) {
1574 PyErr_Format(PyExc_TypeError,
1575 "mro() returned base with unsuitable layout ('%.500s')",
1576 t->tp_name);
1577 Py_DECREF(tuple);
1578 return -1;
1579 }
1580 }
1581 }
1582 type->tp_mro = tuple;
Christian Heimesa62da1d2008-01-12 19:39:10 +00001583
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001584 type_mro_modified(type, type->tp_mro);
1585 /* corner case: the old-style super class might have been hidden
1586 from the custom MRO */
1587 type_mro_modified(type, type->tp_bases);
Christian Heimesa62da1d2008-01-12 19:39:10 +00001588
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001589 PyType_Modified(type);
Christian Heimesa62da1d2008-01-12 19:39:10 +00001590
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001591 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001592}
1593
1594
1595/* Calculate the best base amongst multiple base classes.
1596 This is the first one that's on the path to the "solid base". */
1597
1598static PyTypeObject *
1599best_base(PyObject *bases)
1600{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001601 Py_ssize_t i, n;
1602 PyTypeObject *base, *winner, *candidate, *base_i;
1603 PyObject *base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001604
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001605 assert(PyTuple_Check(bases));
1606 n = PyTuple_GET_SIZE(bases);
1607 assert(n > 0);
1608 base = NULL;
1609 winner = NULL;
1610 for (i = 0; i < n; i++) {
1611 base_proto = PyTuple_GET_ITEM(bases, i);
1612 if (!PyType_Check(base_proto)) {
1613 PyErr_SetString(
1614 PyExc_TypeError,
1615 "bases must be types");
1616 return NULL;
1617 }
1618 base_i = (PyTypeObject *)base_proto;
1619 if (base_i->tp_dict == NULL) {
1620 if (PyType_Ready(base_i) < 0)
1621 return NULL;
1622 }
1623 candidate = solid_base(base_i);
1624 if (winner == NULL) {
1625 winner = candidate;
1626 base = base_i;
1627 }
1628 else if (PyType_IsSubtype(winner, candidate))
1629 ;
1630 else if (PyType_IsSubtype(candidate, winner)) {
1631 winner = candidate;
1632 base = base_i;
1633 }
1634 else {
1635 PyErr_SetString(
1636 PyExc_TypeError,
1637 "multiple bases have "
1638 "instance lay-out conflict");
1639 return NULL;
1640 }
1641 }
1642 if (base == NULL)
1643 PyErr_SetString(PyExc_TypeError,
1644 "a new-style class can't have only classic bases");
1645 return base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001646}
1647
1648static int
1649extra_ivars(PyTypeObject *type, PyTypeObject *base)
1650{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001651 size_t t_size = type->tp_basicsize;
1652 size_t b_size = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001653
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001654 assert(t_size >= b_size); /* Else type smaller than base! */
1655 if (type->tp_itemsize || base->tp_itemsize) {
1656 /* If itemsize is involved, stricter rules */
1657 return t_size != b_size ||
1658 type->tp_itemsize != base->tp_itemsize;
1659 }
1660 if (type->tp_weaklistoffset && base->tp_weaklistoffset == 0 &&
1661 type->tp_weaklistoffset + sizeof(PyObject *) == t_size &&
1662 type->tp_flags & Py_TPFLAGS_HEAPTYPE)
1663 t_size -= sizeof(PyObject *);
1664 if (type->tp_dictoffset && base->tp_dictoffset == 0 &&
1665 type->tp_dictoffset + sizeof(PyObject *) == t_size &&
1666 type->tp_flags & Py_TPFLAGS_HEAPTYPE)
1667 t_size -= sizeof(PyObject *);
Guido van Rossum9676b222001-08-17 20:32:36 +00001668
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001669 return t_size != b_size;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001670}
1671
1672static PyTypeObject *
1673solid_base(PyTypeObject *type)
1674{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001675 PyTypeObject *base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001676
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001677 if (type->tp_base)
1678 base = solid_base(type->tp_base);
1679 else
1680 base = &PyBaseObject_Type;
1681 if (extra_ivars(type, base))
1682 return type;
1683 else
1684 return base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001685}
1686
Jeremy Hylton938ace62002-07-17 16:30:39 +00001687static void object_dealloc(PyObject *);
1688static int object_init(PyObject *, PyObject *, PyObject *);
1689static int update_slot(PyTypeObject *, PyObject *);
1690static void fixup_slot_dispatchers(PyTypeObject *);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001691
Guido van Rossum360e4b82007-05-14 22:51:27 +00001692/*
1693 * Helpers for __dict__ descriptor. We don't want to expose the dicts
1694 * inherited from various builtin types. The builtin base usually provides
1695 * its own __dict__ descriptor, so we use that when we can.
1696 */
1697static PyTypeObject *
1698get_builtin_base_with_dict(PyTypeObject *type)
1699{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001700 while (type->tp_base != NULL) {
1701 if (type->tp_dictoffset != 0 &&
1702 !(type->tp_flags & Py_TPFLAGS_HEAPTYPE))
1703 return type;
1704 type = type->tp_base;
1705 }
1706 return NULL;
Guido van Rossum360e4b82007-05-14 22:51:27 +00001707}
1708
1709static PyObject *
1710get_dict_descriptor(PyTypeObject *type)
1711{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001712 static PyObject *dict_str;
1713 PyObject *descr;
Guido van Rossum360e4b82007-05-14 22:51:27 +00001714
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001715 if (dict_str == NULL) {
1716 dict_str = PyUnicode_InternFromString("__dict__");
1717 if (dict_str == NULL)
1718 return NULL;
1719 }
1720 descr = _PyType_Lookup(type, dict_str);
1721 if (descr == NULL || !PyDescr_IsData(descr))
1722 return NULL;
Guido van Rossum360e4b82007-05-14 22:51:27 +00001723
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001724 return descr;
Guido van Rossum360e4b82007-05-14 22:51:27 +00001725}
1726
1727static void
1728raise_dict_descr_error(PyObject *obj)
1729{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001730 PyErr_Format(PyExc_TypeError,
1731 "this __dict__ descriptor does not support "
1732 "'%.200s' objects", Py_TYPE(obj)->tp_name);
Guido van Rossum360e4b82007-05-14 22:51:27 +00001733}
1734
Tim Peters6d6c1a32001-08-02 04:15:00 +00001735static PyObject *
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001736subtype_dict(PyObject *obj, void *context)
1737{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001738 PyObject **dictptr;
1739 PyObject *dict;
1740 PyTypeObject *base;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001741
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001742 base = get_builtin_base_with_dict(Py_TYPE(obj));
1743 if (base != NULL) {
1744 descrgetfunc func;
1745 PyObject *descr = get_dict_descriptor(base);
1746 if (descr == NULL) {
1747 raise_dict_descr_error(obj);
1748 return NULL;
1749 }
1750 func = Py_TYPE(descr)->tp_descr_get;
1751 if (func == NULL) {
1752 raise_dict_descr_error(obj);
1753 return NULL;
1754 }
1755 return func(descr, obj, (PyObject *)(Py_TYPE(obj)));
1756 }
Guido van Rossum360e4b82007-05-14 22:51:27 +00001757
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001758 dictptr = _PyObject_GetDictPtr(obj);
1759 if (dictptr == NULL) {
1760 PyErr_SetString(PyExc_AttributeError,
1761 "This object has no __dict__");
1762 return NULL;
1763 }
1764 dict = *dictptr;
1765 if (dict == NULL)
1766 *dictptr = dict = PyDict_New();
1767 Py_XINCREF(dict);
1768 return dict;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001769}
1770
Guido van Rossum6661be32001-10-26 04:26:12 +00001771static int
1772subtype_setdict(PyObject *obj, PyObject *value, void *context)
1773{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001774 PyObject **dictptr;
1775 PyObject *dict;
1776 PyTypeObject *base;
Guido van Rossum6661be32001-10-26 04:26:12 +00001777
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001778 base = get_builtin_base_with_dict(Py_TYPE(obj));
1779 if (base != NULL) {
1780 descrsetfunc func;
1781 PyObject *descr = get_dict_descriptor(base);
1782 if (descr == NULL) {
1783 raise_dict_descr_error(obj);
1784 return -1;
1785 }
1786 func = Py_TYPE(descr)->tp_descr_set;
1787 if (func == NULL) {
1788 raise_dict_descr_error(obj);
1789 return -1;
1790 }
1791 return func(descr, obj, value);
1792 }
Guido van Rossum360e4b82007-05-14 22:51:27 +00001793
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001794 dictptr = _PyObject_GetDictPtr(obj);
1795 if (dictptr == NULL) {
1796 PyErr_SetString(PyExc_AttributeError,
1797 "This object has no __dict__");
1798 return -1;
1799 }
1800 if (value != NULL && !PyDict_Check(value)) {
1801 PyErr_Format(PyExc_TypeError,
1802 "__dict__ must be set to a dictionary, "
1803 "not a '%.200s'", Py_TYPE(value)->tp_name);
1804 return -1;
1805 }
1806 dict = *dictptr;
1807 Py_XINCREF(value);
1808 *dictptr = value;
1809 Py_XDECREF(dict);
1810 return 0;
Guido van Rossum6661be32001-10-26 04:26:12 +00001811}
1812
Guido van Rossumad47da02002-08-12 19:05:44 +00001813static PyObject *
1814subtype_getweakref(PyObject *obj, void *context)
1815{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001816 PyObject **weaklistptr;
1817 PyObject *result;
Guido van Rossumad47da02002-08-12 19:05:44 +00001818
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001819 if (Py_TYPE(obj)->tp_weaklistoffset == 0) {
1820 PyErr_SetString(PyExc_AttributeError,
1821 "This object has no __weakref__");
1822 return NULL;
1823 }
1824 assert(Py_TYPE(obj)->tp_weaklistoffset > 0);
1825 assert(Py_TYPE(obj)->tp_weaklistoffset + sizeof(PyObject *) <=
1826 (size_t)(Py_TYPE(obj)->tp_basicsize));
1827 weaklistptr = (PyObject **)
1828 ((char *)obj + Py_TYPE(obj)->tp_weaklistoffset);
1829 if (*weaklistptr == NULL)
1830 result = Py_None;
1831 else
1832 result = *weaklistptr;
1833 Py_INCREF(result);
1834 return result;
Guido van Rossumad47da02002-08-12 19:05:44 +00001835}
1836
Guido van Rossum373c7412003-01-07 13:41:37 +00001837/* Three variants on the subtype_getsets list. */
1838
1839static PyGetSetDef subtype_getsets_full[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001840 {"__dict__", subtype_dict, subtype_setdict,
1841 PyDoc_STR("dictionary for instance variables (if defined)")},
1842 {"__weakref__", subtype_getweakref, NULL,
1843 PyDoc_STR("list of weak references to the object (if defined)")},
1844 {0}
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001845};
1846
Guido van Rossum373c7412003-01-07 13:41:37 +00001847static PyGetSetDef subtype_getsets_dict_only[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001848 {"__dict__", subtype_dict, subtype_setdict,
1849 PyDoc_STR("dictionary for instance variables (if defined)")},
1850 {0}
Guido van Rossum373c7412003-01-07 13:41:37 +00001851};
1852
1853static PyGetSetDef subtype_getsets_weakref_only[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001854 {"__weakref__", subtype_getweakref, NULL,
1855 PyDoc_STR("list of weak references to the object (if defined)")},
1856 {0}
Guido van Rossum373c7412003-01-07 13:41:37 +00001857};
1858
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001859static int
1860valid_identifier(PyObject *s)
1861{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001862 if (!PyUnicode_Check(s)) {
1863 PyErr_Format(PyExc_TypeError,
1864 "__slots__ items must be strings, not '%.200s'",
1865 Py_TYPE(s)->tp_name);
1866 return 0;
1867 }
1868 if (!PyUnicode_IsIdentifier(s)) {
1869 PyErr_SetString(PyExc_TypeError,
1870 "__slots__ must be identifiers");
1871 return 0;
1872 }
1873 return 1;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001874}
1875
Guido van Rossumd8faa362007-04-27 19:54:29 +00001876/* Forward */
1877static int
1878object_init(PyObject *self, PyObject *args, PyObject *kwds);
1879
1880static int
1881type_init(PyObject *cls, PyObject *args, PyObject *kwds)
1882{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001883 int res;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001884
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001885 assert(args != NULL && PyTuple_Check(args));
1886 assert(kwds == NULL || PyDict_Check(kwds));
Guido van Rossumd8faa362007-04-27 19:54:29 +00001887
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001888 if (kwds != NULL && PyDict_Check(kwds) && PyDict_Size(kwds) != 0) {
1889 PyErr_SetString(PyExc_TypeError,
1890 "type.__init__() takes no keyword arguments");
1891 return -1;
1892 }
Guido van Rossumd8faa362007-04-27 19:54:29 +00001893
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001894 if (args != NULL && PyTuple_Check(args) &&
1895 (PyTuple_GET_SIZE(args) != 1 && PyTuple_GET_SIZE(args) != 3)) {
1896 PyErr_SetString(PyExc_TypeError,
1897 "type.__init__() takes 1 or 3 arguments");
1898 return -1;
1899 }
Guido van Rossumd8faa362007-04-27 19:54:29 +00001900
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001901 /* Call object.__init__(self) now. */
1902 /* XXX Could call super(type, cls).__init__() but what's the point? */
1903 args = PyTuple_GetSlice(args, 0, 0);
1904 res = object_init(cls, args, NULL);
1905 Py_DECREF(args);
1906 return res;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001907}
1908
Martin v. Löwis738236d2011-02-05 20:35:29 +00001909long
1910PyType_GetFlags(PyTypeObject *type)
1911{
1912 return type->tp_flags;
1913}
1914
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001915static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00001916type_new(PyTypeObject *metatype, PyObject *args, PyObject *kwds)
1917{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001918 PyObject *name, *bases, *dict;
1919 static char *kwlist[] = {"name", "bases", "dict", 0};
1920 PyObject *slots, *tmp, *newslots;
1921 PyTypeObject *type, *base, *tmptype, *winner;
1922 PyHeapTypeObject *et;
1923 PyMemberDef *mp;
1924 Py_ssize_t i, nbases, nslots, slotoffset, add_dict, add_weak;
1925 int j, may_add_dict, may_add_weak;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001926
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001927 assert(args != NULL && PyTuple_Check(args));
1928 assert(kwds == NULL || PyDict_Check(kwds));
Tim Peters3abca122001-10-27 19:37:48 +00001929
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001930 /* Special case: type(x) should return x->ob_type */
1931 {
1932 const Py_ssize_t nargs = PyTuple_GET_SIZE(args);
1933 const Py_ssize_t nkwds = kwds == NULL ? 0 : PyDict_Size(kwds);
Tim Peters3abca122001-10-27 19:37:48 +00001934
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001935 if (PyType_CheckExact(metatype) && nargs == 1 && nkwds == 0) {
1936 PyObject *x = PyTuple_GET_ITEM(args, 0);
1937 Py_INCREF(Py_TYPE(x));
1938 return (PyObject *) Py_TYPE(x);
1939 }
Tim Peters3abca122001-10-27 19:37:48 +00001940
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001941 /* SF bug 475327 -- if that didn't trigger, we need 3
1942 arguments. but PyArg_ParseTupleAndKeywords below may give
1943 a msg saying type() needs exactly 3. */
1944 if (nargs + nkwds != 3) {
1945 PyErr_SetString(PyExc_TypeError,
1946 "type() takes 1 or 3 arguments");
1947 return NULL;
1948 }
1949 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001950
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001951 /* Check arguments: (name, bases, dict) */
1952 if (!PyArg_ParseTupleAndKeywords(args, kwds, "UO!O!:type", kwlist,
1953 &name,
1954 &PyTuple_Type, &bases,
1955 &PyDict_Type, &dict))
1956 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001957
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001958 /* Determine the proper metatype to deal with this,
1959 and check for metatype conflicts while we're at it.
1960 Note that if some other metatype wins to contract,
1961 it's possible that its instances are not types. */
1962 nbases = PyTuple_GET_SIZE(bases);
1963 winner = metatype;
1964 for (i = 0; i < nbases; i++) {
1965 tmp = PyTuple_GET_ITEM(bases, i);
1966 tmptype = Py_TYPE(tmp);
1967 if (PyType_IsSubtype(winner, tmptype))
1968 continue;
1969 if (PyType_IsSubtype(tmptype, winner)) {
1970 winner = tmptype;
1971 continue;
1972 }
1973 PyErr_SetString(PyExc_TypeError,
1974 "metaclass conflict: "
1975 "the metaclass of a derived class "
1976 "must be a (non-strict) subclass "
1977 "of the metaclasses of all its bases");
1978 return NULL;
1979 }
1980 if (winner != metatype) {
1981 if (winner->tp_new != type_new) /* Pass it to the winner */
1982 return winner->tp_new(winner, args, kwds);
1983 metatype = winner;
1984 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001985
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001986 /* Adjust for empty tuple bases */
1987 if (nbases == 0) {
1988 bases = PyTuple_Pack(1, &PyBaseObject_Type);
1989 if (bases == NULL)
1990 return NULL;
1991 nbases = 1;
1992 }
1993 else
1994 Py_INCREF(bases);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001995
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001996 /* XXX From here until type is allocated, "return NULL" leaks bases! */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001997
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001998 /* Calculate best base, and check that all bases are type objects */
1999 base = best_base(bases);
2000 if (base == NULL) {
2001 Py_DECREF(bases);
2002 return NULL;
2003 }
2004 if (!PyType_HasFeature(base, Py_TPFLAGS_BASETYPE)) {
2005 PyErr_Format(PyExc_TypeError,
2006 "type '%.100s' is not an acceptable base type",
2007 base->tp_name);
2008 Py_DECREF(bases);
2009 return NULL;
2010 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002011
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002012 /* Check for a __slots__ sequence variable in dict, and count it */
2013 slots = PyDict_GetItemString(dict, "__slots__");
2014 nslots = 0;
2015 add_dict = 0;
2016 add_weak = 0;
2017 may_add_dict = base->tp_dictoffset == 0;
2018 may_add_weak = base->tp_weaklistoffset == 0 && base->tp_itemsize == 0;
2019 if (slots == NULL) {
2020 if (may_add_dict) {
2021 add_dict++;
2022 }
2023 if (may_add_weak) {
2024 add_weak++;
2025 }
2026 }
2027 else {
2028 /* Have slots */
Guido van Rossumad47da02002-08-12 19:05:44 +00002029
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002030 /* Make it into a tuple */
2031 if (PyUnicode_Check(slots))
2032 slots = PyTuple_Pack(1, slots);
2033 else
2034 slots = PySequence_Tuple(slots);
2035 if (slots == NULL) {
2036 Py_DECREF(bases);
2037 return NULL;
2038 }
2039 assert(PyTuple_Check(slots));
Guido van Rossumad47da02002-08-12 19:05:44 +00002040
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002041 /* Are slots allowed? */
2042 nslots = PyTuple_GET_SIZE(slots);
2043 if (nslots > 0 && base->tp_itemsize != 0) {
2044 PyErr_Format(PyExc_TypeError,
2045 "nonempty __slots__ "
2046 "not supported for subtype of '%s'",
2047 base->tp_name);
2048 bad_slots:
2049 Py_DECREF(bases);
2050 Py_DECREF(slots);
2051 return NULL;
2052 }
Guido van Rossumad47da02002-08-12 19:05:44 +00002053
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002054 /* Check for valid slot names and two special cases */
2055 for (i = 0; i < nslots; i++) {
2056 PyObject *tmp = PyTuple_GET_ITEM(slots, i);
2057 if (!valid_identifier(tmp))
2058 goto bad_slots;
2059 assert(PyUnicode_Check(tmp));
2060 if (PyUnicode_CompareWithASCIIString(tmp, "__dict__") == 0) {
2061 if (!may_add_dict || add_dict) {
2062 PyErr_SetString(PyExc_TypeError,
2063 "__dict__ slot disallowed: "
2064 "we already got one");
2065 goto bad_slots;
2066 }
2067 add_dict++;
2068 }
2069 if (PyUnicode_CompareWithASCIIString(tmp, "__weakref__") == 0) {
2070 if (!may_add_weak || add_weak) {
2071 PyErr_SetString(PyExc_TypeError,
2072 "__weakref__ slot disallowed: "
2073 "either we already got one, "
2074 "or __itemsize__ != 0");
2075 goto bad_slots;
2076 }
2077 add_weak++;
2078 }
2079 }
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00002080
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002081 /* Copy slots into a list, mangle names and sort them.
2082 Sorted names are needed for __class__ assignment.
2083 Convert them back to tuple at the end.
2084 */
2085 newslots = PyList_New(nslots - add_dict - add_weak);
2086 if (newslots == NULL)
2087 goto bad_slots;
2088 for (i = j = 0; i < nslots; i++) {
2089 tmp = PyTuple_GET_ITEM(slots, i);
2090 if ((add_dict &&
2091 PyUnicode_CompareWithASCIIString(tmp, "__dict__") == 0) ||
2092 (add_weak &&
2093 PyUnicode_CompareWithASCIIString(tmp, "__weakref__") == 0))
2094 continue;
2095 tmp =_Py_Mangle(name, tmp);
Benjamin Petersonae13c882011-08-16 22:26:48 -05002096 if (!tmp) {
2097 Py_DECREF(newslots);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002098 goto bad_slots;
Benjamin Petersonae13c882011-08-16 22:26:48 -05002099 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002100 PyList_SET_ITEM(newslots, j, tmp);
Benjamin Petersonc4085c82011-08-16 18:53:26 -05002101 if (PyDict_GetItem(dict, tmp)) {
2102 PyErr_Format(PyExc_ValueError,
2103 "%R in __slots__ conflicts with class variable",
2104 tmp);
Benjamin Petersond17cefc2011-08-16 22:28:23 -05002105 Py_DECREF(newslots);
Benjamin Petersonc4085c82011-08-16 18:53:26 -05002106 goto bad_slots;
2107 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002108 j++;
2109 }
2110 assert(j == nslots - add_dict - add_weak);
2111 nslots = j;
2112 Py_DECREF(slots);
2113 if (PyList_Sort(newslots) == -1) {
2114 Py_DECREF(bases);
2115 Py_DECREF(newslots);
2116 return NULL;
2117 }
2118 slots = PyList_AsTuple(newslots);
2119 Py_DECREF(newslots);
2120 if (slots == NULL) {
2121 Py_DECREF(bases);
2122 return NULL;
2123 }
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00002124
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002125 /* Secondary bases may provide weakrefs or dict */
2126 if (nbases > 1 &&
2127 ((may_add_dict && !add_dict) ||
2128 (may_add_weak && !add_weak))) {
2129 for (i = 0; i < nbases; i++) {
2130 tmp = PyTuple_GET_ITEM(bases, i);
2131 if (tmp == (PyObject *)base)
2132 continue; /* Skip primary base */
2133 assert(PyType_Check(tmp));
2134 tmptype = (PyTypeObject *)tmp;
2135 if (may_add_dict && !add_dict &&
2136 tmptype->tp_dictoffset != 0)
2137 add_dict++;
2138 if (may_add_weak && !add_weak &&
2139 tmptype->tp_weaklistoffset != 0)
2140 add_weak++;
2141 if (may_add_dict && !add_dict)
2142 continue;
2143 if (may_add_weak && !add_weak)
2144 continue;
2145 /* Nothing more to check */
2146 break;
2147 }
2148 }
2149 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002150
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002151 /* XXX From here until type is safely allocated,
2152 "return NULL" may leak slots! */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002153
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002154 /* Allocate the type object */
2155 type = (PyTypeObject *)metatype->tp_alloc(metatype, nslots);
2156 if (type == NULL) {
2157 Py_XDECREF(slots);
2158 Py_DECREF(bases);
2159 return NULL;
2160 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002161
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002162 /* Keep name and slots alive in the extended type object */
2163 et = (PyHeapTypeObject *)type;
2164 Py_INCREF(name);
2165 et->ht_name = name;
2166 et->ht_slots = slots;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002167
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002168 /* Initialize tp_flags */
2169 type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE |
2170 Py_TPFLAGS_BASETYPE;
2171 if (base->tp_flags & Py_TPFLAGS_HAVE_GC)
2172 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossumdc91b992001-08-08 22:26:22 +00002173
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002174 /* Initialize essential fields */
2175 type->tp_as_number = &et->as_number;
2176 type->tp_as_sequence = &et->as_sequence;
2177 type->tp_as_mapping = &et->as_mapping;
2178 type->tp_as_buffer = &et->as_buffer;
2179 type->tp_name = _PyUnicode_AsString(name);
2180 if (!type->tp_name) {
2181 Py_DECREF(type);
2182 return NULL;
2183 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002184
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002185 /* Set tp_base and tp_bases */
2186 type->tp_bases = bases;
2187 Py_INCREF(base);
2188 type->tp_base = base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002189
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002190 /* Initialize tp_dict from passed-in dict */
2191 type->tp_dict = dict = PyDict_Copy(dict);
2192 if (dict == NULL) {
2193 Py_DECREF(type);
2194 return NULL;
2195 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002196
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002197 /* Set __module__ in the dict */
2198 if (PyDict_GetItemString(dict, "__module__") == NULL) {
2199 tmp = PyEval_GetGlobals();
2200 if (tmp != NULL) {
2201 tmp = PyDict_GetItemString(tmp, "__name__");
2202 if (tmp != NULL) {
2203 if (PyDict_SetItemString(dict, "__module__",
2204 tmp) < 0)
2205 return NULL;
2206 }
2207 }
2208 }
Guido van Rossumc3542212001-08-16 09:18:56 +00002209
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002210 /* Set tp_doc to a copy of dict['__doc__'], if the latter is there
2211 and is a string. The __doc__ accessor will first look for tp_doc;
2212 if that fails, it will still look into __dict__.
2213 */
2214 {
2215 PyObject *doc = PyDict_GetItemString(dict, "__doc__");
2216 if (doc != NULL && PyUnicode_Check(doc)) {
2217 Py_ssize_t len;
2218 char *doc_str;
2219 char *tp_doc;
Alexandre Vassalottia85998a2008-05-03 18:24:43 +00002220
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002221 doc_str = _PyUnicode_AsString(doc);
2222 if (doc_str == NULL) {
2223 Py_DECREF(type);
2224 return NULL;
2225 }
2226 /* Silently truncate the docstring if it contains null bytes. */
2227 len = strlen(doc_str);
2228 tp_doc = (char *)PyObject_MALLOC(len + 1);
2229 if (tp_doc == NULL) {
2230 Py_DECREF(type);
2231 return NULL;
2232 }
2233 memcpy(tp_doc, doc_str, len + 1);
2234 type->tp_doc = tp_doc;
2235 }
2236 }
Tim Peters2f93e282001-10-04 05:27:00 +00002237
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002238 /* Special-case __new__: if it's a plain function,
2239 make it a static function */
2240 tmp = PyDict_GetItemString(dict, "__new__");
2241 if (tmp != NULL && PyFunction_Check(tmp)) {
2242 tmp = PyStaticMethod_New(tmp);
2243 if (tmp == NULL) {
2244 Py_DECREF(type);
2245 return NULL;
2246 }
2247 PyDict_SetItemString(dict, "__new__", tmp);
2248 Py_DECREF(tmp);
2249 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002250
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002251 /* Add descriptors for custom slots from __slots__, or for __dict__ */
2252 mp = PyHeapType_GET_MEMBERS(et);
2253 slotoffset = base->tp_basicsize;
2254 if (slots != NULL) {
2255 for (i = 0; i < nslots; i++, mp++) {
2256 mp->name = _PyUnicode_AsString(
2257 PyTuple_GET_ITEM(slots, i));
Victor Stinnere5f99f32010-05-19 01:42:46 +00002258 if (mp->name == NULL) {
2259 Py_DECREF(type);
2260 return NULL;
2261 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002262 mp->type = T_OBJECT_EX;
2263 mp->offset = slotoffset;
Guido van Rossumd8faa362007-04-27 19:54:29 +00002264
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002265 /* __dict__ and __weakref__ are already filtered out */
2266 assert(strcmp(mp->name, "__dict__") != 0);
2267 assert(strcmp(mp->name, "__weakref__") != 0);
Guido van Rossumd8faa362007-04-27 19:54:29 +00002268
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002269 slotoffset += sizeof(PyObject *);
2270 }
2271 }
2272 if (add_dict) {
2273 if (base->tp_itemsize)
2274 type->tp_dictoffset = -(long)sizeof(PyObject *);
2275 else
2276 type->tp_dictoffset = slotoffset;
2277 slotoffset += sizeof(PyObject *);
2278 }
2279 if (add_weak) {
2280 assert(!base->tp_itemsize);
2281 type->tp_weaklistoffset = slotoffset;
2282 slotoffset += sizeof(PyObject *);
2283 }
2284 type->tp_basicsize = slotoffset;
2285 type->tp_itemsize = base->tp_itemsize;
2286 type->tp_members = PyHeapType_GET_MEMBERS(et);
Guido van Rossum373c7412003-01-07 13:41:37 +00002287
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002288 if (type->tp_weaklistoffset && type->tp_dictoffset)
2289 type->tp_getset = subtype_getsets_full;
2290 else if (type->tp_weaklistoffset && !type->tp_dictoffset)
2291 type->tp_getset = subtype_getsets_weakref_only;
2292 else if (!type->tp_weaklistoffset && type->tp_dictoffset)
2293 type->tp_getset = subtype_getsets_dict_only;
2294 else
2295 type->tp_getset = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002296
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002297 /* Special case some slots */
2298 if (type->tp_dictoffset != 0 || nslots > 0) {
2299 if (base->tp_getattr == NULL && base->tp_getattro == NULL)
2300 type->tp_getattro = PyObject_GenericGetAttr;
2301 if (base->tp_setattr == NULL && base->tp_setattro == NULL)
2302 type->tp_setattro = PyObject_GenericSetAttr;
2303 }
2304 type->tp_dealloc = subtype_dealloc;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002305
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002306 /* Enable GC unless there are really no instance variables possible */
2307 if (!(type->tp_basicsize == sizeof(PyObject) &&
2308 type->tp_itemsize == 0))
2309 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossum9475a232001-10-05 20:51:39 +00002310
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002311 /* Always override allocation strategy to use regular heap */
2312 type->tp_alloc = PyType_GenericAlloc;
2313 if (type->tp_flags & Py_TPFLAGS_HAVE_GC) {
2314 type->tp_free = PyObject_GC_Del;
2315 type->tp_traverse = subtype_traverse;
2316 type->tp_clear = subtype_clear;
2317 }
2318 else
2319 type->tp_free = PyObject_Del;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002320
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002321 /* Initialize the rest */
2322 if (PyType_Ready(type) < 0) {
2323 Py_DECREF(type);
2324 return NULL;
2325 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002326
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002327 /* Put the proper slots in place */
2328 fixup_slot_dispatchers(type);
Guido van Rossumf040ede2001-08-07 16:40:56 +00002329
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002330 return (PyObject *)type;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002331}
2332
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002333static short slotoffsets[] = {
2334 -1, /* invalid slot */
2335#include "typeslots.inc"
2336};
2337
2338PyObject* PyType_FromSpec(PyType_Spec *spec)
2339{
2340 PyHeapTypeObject *res = (PyHeapTypeObject*)PyType_GenericAlloc(&PyType_Type, 0);
2341 char *res_start = (char*)res;
2342 PyType_Slot *slot;
2343
Martin v. Löwis5e06a5d2011-02-21 16:24:00 +00002344 if (res == NULL)
2345 return NULL;
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002346 res->ht_name = PyUnicode_FromString(spec->name);
2347 if (!res->ht_name)
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002348 goto fail;
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002349 res->ht_type.tp_name = _PyUnicode_AsString(res->ht_name);
2350 if (!res->ht_type.tp_name)
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002351 goto fail;
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002352
2353 res->ht_type.tp_basicsize = spec->basicsize;
2354 res->ht_type.tp_itemsize = spec->itemsize;
2355 res->ht_type.tp_flags = spec->flags | Py_TPFLAGS_HEAPTYPE;
Victor Stinner0fcab4a2011-01-04 12:59:15 +00002356
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002357 for (slot = spec->slots; slot->slot; slot++) {
Victor Stinner63941882011-09-29 00:42:28 +02002358 if (slot->slot >= Py_ARRAY_LENGTH(slotoffsets)) {
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002359 PyErr_SetString(PyExc_RuntimeError, "invalid slot offset");
2360 goto fail;
2361 }
2362 *(void**)(res_start + slotoffsets[slot->slot]) = slot->pfunc;
Georg Brandl032400b2011-02-19 21:47:02 +00002363
2364 /* need to make a copy of the docstring slot, which usually
2365 points to a static string literal */
2366 if (slot->slot == Py_tp_doc) {
2367 ssize_t len = strlen(slot->pfunc)+1;
2368 char *tp_doc = PyObject_MALLOC(len);
2369 if (tp_doc == NULL)
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002370 goto fail;
Georg Brandl032400b2011-02-19 21:47:02 +00002371 memcpy(tp_doc, slot->pfunc, len);
2372 res->ht_type.tp_doc = tp_doc;
2373 }
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002374 }
2375
2376 return (PyObject*)res;
Victor Stinner0fcab4a2011-01-04 12:59:15 +00002377
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002378 fail:
2379 Py_DECREF(res);
2380 return NULL;
2381}
2382
2383
Tim Peters6d6c1a32001-08-02 04:15:00 +00002384/* Internal API to look for a name through the MRO.
2385 This returns a borrowed reference, and doesn't set an exception! */
2386PyObject *
2387_PyType_Lookup(PyTypeObject *type, PyObject *name)
2388{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002389 Py_ssize_t i, n;
2390 PyObject *mro, *res, *base, *dict;
2391 unsigned int h;
Christian Heimesa62da1d2008-01-12 19:39:10 +00002392
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002393 if (MCACHE_CACHEABLE_NAME(name) &&
2394 PyType_HasFeature(type, Py_TPFLAGS_VALID_VERSION_TAG)) {
2395 /* fast path */
2396 h = MCACHE_HASH_METHOD(type, name);
2397 if (method_cache[h].version == type->tp_version_tag &&
2398 method_cache[h].name == name)
2399 return method_cache[h].value;
2400 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002401
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002402 /* Look in tp_dict of types in MRO */
2403 mro = type->tp_mro;
Guido van Rossum23094982002-06-10 14:30:43 +00002404
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002405 /* If mro is NULL, the type is either not yet initialized
2406 by PyType_Ready(), or already cleared by type_clear().
2407 Either way the safest thing to do is to return NULL. */
2408 if (mro == NULL)
2409 return NULL;
Guido van Rossum23094982002-06-10 14:30:43 +00002410
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002411 res = NULL;
2412 assert(PyTuple_Check(mro));
2413 n = PyTuple_GET_SIZE(mro);
2414 for (i = 0; i < n; i++) {
2415 base = PyTuple_GET_ITEM(mro, i);
2416 assert(PyType_Check(base));
2417 dict = ((PyTypeObject *)base)->tp_dict;
2418 assert(dict && PyDict_Check(dict));
2419 res = PyDict_GetItem(dict, name);
2420 if (res != NULL)
2421 break;
2422 }
Christian Heimesa62da1d2008-01-12 19:39:10 +00002423
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002424 if (MCACHE_CACHEABLE_NAME(name) && assign_version_tag(type)) {
2425 h = MCACHE_HASH_METHOD(type, name);
2426 method_cache[h].version = type->tp_version_tag;
2427 method_cache[h].value = res; /* borrowed */
2428 Py_INCREF(name);
2429 Py_DECREF(method_cache[h].name);
2430 method_cache[h].name = name;
2431 }
2432 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002433}
2434
2435/* This is similar to PyObject_GenericGetAttr(),
2436 but uses _PyType_Lookup() instead of just looking in type->tp_dict. */
2437static PyObject *
2438type_getattro(PyTypeObject *type, PyObject *name)
2439{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002440 PyTypeObject *metatype = Py_TYPE(type);
2441 PyObject *meta_attribute, *attribute;
2442 descrgetfunc meta_get;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002443
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002444 /* Initialize this type (we'll assume the metatype is initialized) */
2445 if (type->tp_dict == NULL) {
2446 if (PyType_Ready(type) < 0)
2447 return NULL;
2448 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002449
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002450 /* No readable descriptor found yet */
2451 meta_get = NULL;
Tim Peters34592512002-07-11 06:23:50 +00002452
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002453 /* Look for the attribute in the metatype */
2454 meta_attribute = _PyType_Lookup(metatype, name);
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002455
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002456 if (meta_attribute != NULL) {
2457 meta_get = Py_TYPE(meta_attribute)->tp_descr_get;
Tim Peters34592512002-07-11 06:23:50 +00002458
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002459 if (meta_get != NULL && PyDescr_IsData(meta_attribute)) {
2460 /* Data descriptors implement tp_descr_set to intercept
2461 * writes. Assume the attribute is not overridden in
2462 * type's tp_dict (and bases): call the descriptor now.
2463 */
2464 return meta_get(meta_attribute, (PyObject *)type,
2465 (PyObject *)metatype);
2466 }
2467 Py_INCREF(meta_attribute);
2468 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002469
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002470 /* No data descriptor found on metatype. Look in tp_dict of this
2471 * type and its bases */
2472 attribute = _PyType_Lookup(type, name);
2473 if (attribute != NULL) {
2474 /* Implement descriptor functionality, if any */
2475 descrgetfunc local_get = Py_TYPE(attribute)->tp_descr_get;
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00002476
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002477 Py_XDECREF(meta_attribute);
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00002478
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002479 if (local_get != NULL) {
2480 /* NULL 2nd argument indicates the descriptor was
2481 * found on the target object itself (or a base) */
2482 return local_get(attribute, (PyObject *)NULL,
2483 (PyObject *)type);
2484 }
Tim Peters34592512002-07-11 06:23:50 +00002485
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002486 Py_INCREF(attribute);
2487 return attribute;
2488 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002489
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002490 /* No attribute found in local __dict__ (or bases): use the
2491 * descriptor from the metatype, if any */
2492 if (meta_get != NULL) {
2493 PyObject *res;
2494 res = meta_get(meta_attribute, (PyObject *)type,
2495 (PyObject *)metatype);
2496 Py_DECREF(meta_attribute);
2497 return res;
2498 }
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002499
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002500 /* If an ordinary attribute was found on the metatype, return it now */
2501 if (meta_attribute != NULL) {
2502 return meta_attribute;
2503 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002504
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002505 /* Give up */
2506 PyErr_Format(PyExc_AttributeError,
2507 "type object '%.50s' has no attribute '%U'",
2508 type->tp_name, name);
2509 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002510}
2511
2512static int
2513type_setattro(PyTypeObject *type, PyObject *name, PyObject *value)
2514{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002515 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
2516 PyErr_Format(
2517 PyExc_TypeError,
2518 "can't set attributes of built-in/extension type '%s'",
2519 type->tp_name);
2520 return -1;
2521 }
2522 if (PyObject_GenericSetAttr((PyObject *)type, name, value) < 0)
2523 return -1;
2524 return update_slot(type, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002525}
2526
2527static void
2528type_dealloc(PyTypeObject *type)
2529{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002530 PyHeapTypeObject *et;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002531
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002532 /* Assert this is a heap-allocated type object */
2533 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
2534 _PyObject_GC_UNTRACK(type);
2535 PyObject_ClearWeakRefs((PyObject *)type);
2536 et = (PyHeapTypeObject *)type;
2537 Py_XDECREF(type->tp_base);
2538 Py_XDECREF(type->tp_dict);
2539 Py_XDECREF(type->tp_bases);
2540 Py_XDECREF(type->tp_mro);
2541 Py_XDECREF(type->tp_cache);
2542 Py_XDECREF(type->tp_subclasses);
2543 /* A type's tp_doc is heap allocated, unlike the tp_doc slots
2544 * of most other objects. It's okay to cast it to char *.
2545 */
2546 PyObject_Free((char *)type->tp_doc);
2547 Py_XDECREF(et->ht_name);
2548 Py_XDECREF(et->ht_slots);
2549 Py_TYPE(type)->tp_free((PyObject *)type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002550}
2551
Guido van Rossum1c450732001-10-08 15:18:27 +00002552static PyObject *
2553type_subclasses(PyTypeObject *type, PyObject *args_ignored)
2554{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002555 PyObject *list, *raw, *ref;
2556 Py_ssize_t i, n;
Guido van Rossum1c450732001-10-08 15:18:27 +00002557
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002558 list = PyList_New(0);
2559 if (list == NULL)
2560 return NULL;
2561 raw = type->tp_subclasses;
2562 if (raw == NULL)
2563 return list;
2564 assert(PyList_Check(raw));
2565 n = PyList_GET_SIZE(raw);
2566 for (i = 0; i < n; i++) {
2567 ref = PyList_GET_ITEM(raw, i);
2568 assert(PyWeakref_CheckRef(ref));
2569 ref = PyWeakref_GET_OBJECT(ref);
2570 if (ref != Py_None) {
2571 if (PyList_Append(list, ref) < 0) {
2572 Py_DECREF(list);
2573 return NULL;
2574 }
2575 }
2576 }
2577 return list;
Guido van Rossum1c450732001-10-08 15:18:27 +00002578}
2579
Guido van Rossum47374822007-08-02 16:48:17 +00002580static PyObject *
2581type_prepare(PyObject *self, PyObject *args, PyObject *kwds)
2582{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002583 return PyDict_New();
Guido van Rossum47374822007-08-02 16:48:17 +00002584}
2585
Victor Stinner63941882011-09-29 00:42:28 +02002586/*
Benjamin Peterson82b00c12011-05-24 11:09:06 -05002587 Merge the __dict__ of aclass into dict, and recursively also all
2588 the __dict__s of aclass's base classes. The order of merging isn't
2589 defined, as it's expected that only the final set of dict keys is
2590 interesting.
2591 Return 0 on success, -1 on error.
2592*/
2593
2594static int
2595merge_class_dict(PyObject *dict, PyObject *aclass)
2596{
2597 PyObject *classdict;
2598 PyObject *bases;
2599
2600 assert(PyDict_Check(dict));
2601 assert(aclass);
2602
2603 /* Merge in the type's dict (if any). */
2604 classdict = PyObject_GetAttrString(aclass, "__dict__");
2605 if (classdict == NULL)
2606 PyErr_Clear();
2607 else {
2608 int status = PyDict_Update(dict, classdict);
2609 Py_DECREF(classdict);
2610 if (status < 0)
2611 return -1;
2612 }
2613
2614 /* Recursively merge in the base types' (if any) dicts. */
2615 bases = PyObject_GetAttrString(aclass, "__bases__");
2616 if (bases == NULL)
2617 PyErr_Clear();
2618 else {
2619 /* We have no guarantee that bases is a real tuple */
2620 Py_ssize_t i, n;
2621 n = PySequence_Size(bases); /* This better be right */
2622 if (n < 0)
2623 PyErr_Clear();
2624 else {
2625 for (i = 0; i < n; i++) {
2626 int status;
2627 PyObject *base = PySequence_GetItem(bases, i);
2628 if (base == NULL) {
2629 Py_DECREF(bases);
2630 return -1;
2631 }
2632 status = merge_class_dict(dict, base);
2633 Py_DECREF(base);
2634 if (status < 0) {
2635 Py_DECREF(bases);
2636 return -1;
2637 }
2638 }
2639 }
2640 Py_DECREF(bases);
2641 }
2642 return 0;
2643}
2644
2645/* __dir__ for type objects: returns __dict__ and __bases__.
2646 We deliberately don't suck up its __class__, as methods belonging to the
2647 metaclass would probably be more confusing than helpful.
2648*/
2649static PyObject *
2650type_dir(PyObject *self, PyObject *args)
2651{
2652 PyObject *result = NULL;
2653 PyObject *dict = PyDict_New();
2654
2655 if (dict != NULL && merge_class_dict(dict, self) == 0)
2656 result = PyDict_Keys(dict);
2657
2658 Py_XDECREF(dict);
2659 return result;
2660}
2661
Tim Peters6d6c1a32001-08-02 04:15:00 +00002662static PyMethodDef type_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002663 {"mro", (PyCFunction)mro_external, METH_NOARGS,
2664 PyDoc_STR("mro() -> list\nreturn a type's method resolution order")},
2665 {"__subclasses__", (PyCFunction)type_subclasses, METH_NOARGS,
2666 PyDoc_STR("__subclasses__() -> list of immediate subclasses")},
2667 {"__prepare__", (PyCFunction)type_prepare,
2668 METH_VARARGS | METH_KEYWORDS | METH_CLASS,
2669 PyDoc_STR("__prepare__() -> dict\n"
2670 "used to create the namespace for the class statement")},
2671 {"__instancecheck__", type___instancecheck__, METH_O,
Benjamin Petersonfbe56bb2011-05-24 12:42:51 -05002672 PyDoc_STR("__instancecheck__() -> bool\ncheck if an object is an instance")},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002673 {"__subclasscheck__", type___subclasscheck__, METH_O,
Benjamin Petersonfbe56bb2011-05-24 12:42:51 -05002674 PyDoc_STR("__subclasscheck__() -> bool\ncheck if a class is a subclass")},
Benjamin Peterson82b00c12011-05-24 11:09:06 -05002675 {"__dir__", type_dir, METH_NOARGS,
Benjamin Petersonc7284122011-05-24 12:46:15 -05002676 PyDoc_STR("__dir__() -> list\nspecialized __dir__ implementation for types")},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002677 {0}
Tim Peters6d6c1a32001-08-02 04:15:00 +00002678};
2679
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002680PyDoc_STRVAR(type_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00002681"type(object) -> the object's type\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002682"type(name, bases, dict) -> a new type");
Tim Peters6d6c1a32001-08-02 04:15:00 +00002683
Guido van Rossum048eb752001-10-02 21:24:57 +00002684static int
2685type_traverse(PyTypeObject *type, visitproc visit, void *arg)
2686{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002687 /* Because of type_is_gc(), the collector only calls this
2688 for heaptypes. */
2689 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002690
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002691 Py_VISIT(type->tp_dict);
2692 Py_VISIT(type->tp_cache);
2693 Py_VISIT(type->tp_mro);
2694 Py_VISIT(type->tp_bases);
2695 Py_VISIT(type->tp_base);
Guido van Rossuma3862092002-06-10 15:24:42 +00002696
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002697 /* There's no need to visit type->tp_subclasses or
2698 ((PyHeapTypeObject *)type)->ht_slots, because they can't be involved
2699 in cycles; tp_subclasses is a list of weak references,
2700 and slots is a tuple of strings. */
Guido van Rossum048eb752001-10-02 21:24:57 +00002701
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002702 return 0;
Guido van Rossum048eb752001-10-02 21:24:57 +00002703}
2704
2705static int
2706type_clear(PyTypeObject *type)
2707{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002708 /* Because of type_is_gc(), the collector only calls this
2709 for heaptypes. */
2710 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002711
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002712 /* The only field we need to clear is tp_mro, which is part of a
2713 hard cycle (its first element is the class itself) that won't
2714 be broken otherwise (it's a tuple and tuples don't have a
2715 tp_clear handler). None of the other fields need to be
2716 cleared, and here's why:
Guido van Rossum048eb752001-10-02 21:24:57 +00002717
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002718 tp_dict:
2719 It is a dict, so the collector will call its tp_clear.
Guido van Rossuma3862092002-06-10 15:24:42 +00002720
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002721 tp_cache:
2722 Not used; if it were, it would be a dict.
Guido van Rossuma3862092002-06-10 15:24:42 +00002723
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002724 tp_bases, tp_base:
2725 If these are involved in a cycle, there must be at least
2726 one other, mutable object in the cycle, e.g. a base
2727 class's dict; the cycle will be broken that way.
Guido van Rossuma3862092002-06-10 15:24:42 +00002728
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002729 tp_subclasses:
2730 A list of weak references can't be part of a cycle; and
2731 lists have their own tp_clear.
Guido van Rossuma3862092002-06-10 15:24:42 +00002732
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002733 slots (in PyHeapTypeObject):
2734 A tuple of strings can't be part of a cycle.
2735 */
Guido van Rossuma3862092002-06-10 15:24:42 +00002736
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002737 Py_CLEAR(type->tp_mro);
Guido van Rossum048eb752001-10-02 21:24:57 +00002738
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002739 return 0;
Guido van Rossum048eb752001-10-02 21:24:57 +00002740}
2741
2742static int
2743type_is_gc(PyTypeObject *type)
2744{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002745 return type->tp_flags & Py_TPFLAGS_HEAPTYPE;
Guido van Rossum048eb752001-10-02 21:24:57 +00002746}
2747
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002748PyTypeObject PyType_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002749 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2750 "type", /* tp_name */
2751 sizeof(PyHeapTypeObject), /* tp_basicsize */
2752 sizeof(PyMemberDef), /* tp_itemsize */
2753 (destructor)type_dealloc, /* tp_dealloc */
2754 0, /* tp_print */
2755 0, /* tp_getattr */
2756 0, /* tp_setattr */
2757 0, /* tp_reserved */
2758 (reprfunc)type_repr, /* tp_repr */
2759 0, /* tp_as_number */
2760 0, /* tp_as_sequence */
2761 0, /* tp_as_mapping */
2762 0, /* tp_hash */
2763 (ternaryfunc)type_call, /* tp_call */
2764 0, /* tp_str */
2765 (getattrofunc)type_getattro, /* tp_getattro */
2766 (setattrofunc)type_setattro, /* tp_setattro */
2767 0, /* tp_as_buffer */
2768 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
2769 Py_TPFLAGS_BASETYPE | Py_TPFLAGS_TYPE_SUBCLASS, /* tp_flags */
2770 type_doc, /* tp_doc */
2771 (traverseproc)type_traverse, /* tp_traverse */
2772 (inquiry)type_clear, /* tp_clear */
2773 0, /* tp_richcompare */
2774 offsetof(PyTypeObject, tp_weaklist), /* tp_weaklistoffset */
2775 0, /* tp_iter */
2776 0, /* tp_iternext */
2777 type_methods, /* tp_methods */
2778 type_members, /* tp_members */
2779 type_getsets, /* tp_getset */
2780 0, /* tp_base */
2781 0, /* tp_dict */
2782 0, /* tp_descr_get */
2783 0, /* tp_descr_set */
2784 offsetof(PyTypeObject, tp_dict), /* tp_dictoffset */
2785 type_init, /* tp_init */
2786 0, /* tp_alloc */
2787 type_new, /* tp_new */
2788 PyObject_GC_Del, /* tp_free */
2789 (inquiry)type_is_gc, /* tp_is_gc */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002790};
Tim Peters6d6c1a32001-08-02 04:15:00 +00002791
2792
2793/* The base type of all types (eventually)... except itself. */
2794
Guido van Rossumd8faa362007-04-27 19:54:29 +00002795/* You may wonder why object.__new__() only complains about arguments
2796 when object.__init__() is not overridden, and vice versa.
2797
2798 Consider the use cases:
2799
2800 1. When neither is overridden, we want to hear complaints about
2801 excess (i.e., any) arguments, since their presence could
2802 indicate there's a bug.
2803
2804 2. When defining an Immutable type, we are likely to override only
2805 __new__(), since __init__() is called too late to initialize an
2806 Immutable object. Since __new__() defines the signature for the
2807 type, it would be a pain to have to override __init__() just to
2808 stop it from complaining about excess arguments.
2809
2810 3. When defining a Mutable type, we are likely to override only
2811 __init__(). So here the converse reasoning applies: we don't
2812 want to have to override __new__() just to stop it from
2813 complaining.
2814
2815 4. When __init__() is overridden, and the subclass __init__() calls
2816 object.__init__(), the latter should complain about excess
2817 arguments; ditto for __new__().
2818
2819 Use cases 2 and 3 make it unattractive to unconditionally check for
2820 excess arguments. The best solution that addresses all four use
2821 cases is as follows: __init__() complains about excess arguments
2822 unless __new__() is overridden and __init__() is not overridden
2823 (IOW, if __init__() is overridden or __new__() is not overridden);
2824 symmetrically, __new__() complains about excess arguments unless
2825 __init__() is overridden and __new__() is not overridden
2826 (IOW, if __new__() is overridden or __init__() is not overridden).
2827
2828 However, for backwards compatibility, this breaks too much code.
2829 Therefore, in 2.6, we'll *warn* about excess arguments when both
2830 methods are overridden; for all other cases we'll use the above
2831 rules.
2832
2833*/
2834
2835/* Forward */
2836static PyObject *
2837object_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
2838
2839static int
2840excess_args(PyObject *args, PyObject *kwds)
2841{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002842 return PyTuple_GET_SIZE(args) ||
2843 (kwds && PyDict_Check(kwds) && PyDict_Size(kwds));
Guido van Rossumd8faa362007-04-27 19:54:29 +00002844}
2845
Tim Peters6d6c1a32001-08-02 04:15:00 +00002846static int
2847object_init(PyObject *self, PyObject *args, PyObject *kwds)
2848{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002849 int err = 0;
2850 if (excess_args(args, kwds)) {
2851 PyTypeObject *type = Py_TYPE(self);
2852 if (type->tp_init != object_init &&
2853 type->tp_new != object_new)
2854 {
2855 err = PyErr_WarnEx(PyExc_DeprecationWarning,
2856 "object.__init__() takes no parameters",
2857 1);
2858 }
2859 else if (type->tp_init != object_init ||
2860 type->tp_new == object_new)
2861 {
2862 PyErr_SetString(PyExc_TypeError,
2863 "object.__init__() takes no parameters");
2864 err = -1;
2865 }
2866 }
2867 return err;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002868}
2869
Guido van Rossum298e4212003-02-13 16:30:16 +00002870static PyObject *
2871object_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2872{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002873 int err = 0;
2874 if (excess_args(args, kwds)) {
2875 if (type->tp_new != object_new &&
2876 type->tp_init != object_init)
2877 {
2878 err = PyErr_WarnEx(PyExc_DeprecationWarning,
2879 "object.__new__() takes no parameters",
2880 1);
2881 }
2882 else if (type->tp_new != object_new ||
2883 type->tp_init == object_init)
2884 {
2885 PyErr_SetString(PyExc_TypeError,
2886 "object.__new__() takes no parameters");
2887 err = -1;
2888 }
2889 }
2890 if (err < 0)
2891 return NULL;
Christian Heimes9e7f1d22008-02-28 12:27:11 +00002892
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002893 if (type->tp_flags & Py_TPFLAGS_IS_ABSTRACT) {
2894 static PyObject *comma = NULL;
2895 PyObject *abstract_methods = NULL;
2896 PyObject *builtins;
2897 PyObject *sorted;
2898 PyObject *sorted_methods = NULL;
2899 PyObject *joined = NULL;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002900 _Py_identifier(join);
Christian Heimes9e7f1d22008-02-28 12:27:11 +00002901
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002902 /* Compute ", ".join(sorted(type.__abstractmethods__))
2903 into joined. */
2904 abstract_methods = type_abstractmethods(type, NULL);
2905 if (abstract_methods == NULL)
2906 goto error;
2907 builtins = PyEval_GetBuiltins();
2908 if (builtins == NULL)
2909 goto error;
2910 sorted = PyDict_GetItemString(builtins, "sorted");
2911 if (sorted == NULL)
2912 goto error;
2913 sorted_methods = PyObject_CallFunctionObjArgs(sorted,
2914 abstract_methods,
2915 NULL);
2916 if (sorted_methods == NULL)
2917 goto error;
2918 if (comma == NULL) {
2919 comma = PyUnicode_InternFromString(", ");
2920 if (comma == NULL)
2921 goto error;
2922 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002923 joined = _PyObject_CallMethodId(comma, &PyId_join,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002924 "O", sorted_methods);
2925 if (joined == NULL)
2926 goto error;
Christian Heimes9e7f1d22008-02-28 12:27:11 +00002927
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002928 PyErr_Format(PyExc_TypeError,
2929 "Can't instantiate abstract class %s "
2930 "with abstract methods %U",
2931 type->tp_name,
2932 joined);
2933 error:
2934 Py_XDECREF(joined);
2935 Py_XDECREF(sorted_methods);
2936 Py_XDECREF(abstract_methods);
2937 return NULL;
2938 }
2939 return type->tp_alloc(type, 0);
Guido van Rossum298e4212003-02-13 16:30:16 +00002940}
2941
Tim Peters6d6c1a32001-08-02 04:15:00 +00002942static void
2943object_dealloc(PyObject *self)
2944{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002945 Py_TYPE(self)->tp_free(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002946}
2947
Guido van Rossum8e248182001-08-12 05:17:56 +00002948static PyObject *
2949object_repr(PyObject *self)
2950{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002951 PyTypeObject *type;
2952 PyObject *mod, *name, *rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00002953
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002954 type = Py_TYPE(self);
2955 mod = type_module(type, NULL);
2956 if (mod == NULL)
2957 PyErr_Clear();
2958 else if (!PyUnicode_Check(mod)) {
2959 Py_DECREF(mod);
2960 mod = NULL;
2961 }
2962 name = type_name(type, NULL);
2963 if (name == NULL)
2964 return NULL;
2965 if (mod != NULL && PyUnicode_CompareWithASCIIString(mod, "builtins"))
2966 rtn = PyUnicode_FromFormat("<%U.%U object at %p>", mod, name, self);
2967 else
2968 rtn = PyUnicode_FromFormat("<%s object at %p>",
2969 type->tp_name, self);
2970 Py_XDECREF(mod);
2971 Py_DECREF(name);
2972 return rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00002973}
2974
Guido van Rossumb8f63662001-08-15 23:57:02 +00002975static PyObject *
2976object_str(PyObject *self)
2977{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002978 unaryfunc f;
Guido van Rossumb8f63662001-08-15 23:57:02 +00002979
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002980 f = Py_TYPE(self)->tp_repr;
Antoine Pitrou8cdc40e2011-07-15 21:15:07 +02002981 if (f == NULL || f == object_str)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002982 f = object_repr;
2983 return f(self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002984}
2985
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002986static PyObject *
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002987object_richcompare(PyObject *self, PyObject *other, int op)
2988{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002989 PyObject *res;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002990
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002991 switch (op) {
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002992
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002993 case Py_EQ:
2994 /* Return NotImplemented instead of False, so if two
2995 objects are compared, both get a chance at the
2996 comparison. See issue #1393. */
2997 res = (self == other) ? Py_True : Py_NotImplemented;
2998 Py_INCREF(res);
2999 break;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003000
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003001 case Py_NE:
3002 /* By default, != returns the opposite of ==,
3003 unless the latter returns NotImplemented. */
3004 res = PyObject_RichCompare(self, other, Py_EQ);
3005 if (res != NULL && res != Py_NotImplemented) {
3006 int ok = PyObject_IsTrue(res);
3007 Py_DECREF(res);
3008 if (ok < 0)
3009 res = NULL;
3010 else {
3011 if (ok)
3012 res = Py_False;
3013 else
3014 res = Py_True;
3015 Py_INCREF(res);
3016 }
3017 }
3018 break;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003019
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003020 default:
3021 res = Py_NotImplemented;
3022 Py_INCREF(res);
3023 break;
3024 }
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003025
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003026 return res;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003027}
3028
3029static PyObject *
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003030object_get_class(PyObject *self, void *closure)
3031{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003032 Py_INCREF(Py_TYPE(self));
3033 return (PyObject *)(Py_TYPE(self));
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003034}
3035
3036static int
3037equiv_structs(PyTypeObject *a, PyTypeObject *b)
3038{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003039 return a == b ||
3040 (a != NULL &&
3041 b != NULL &&
3042 a->tp_basicsize == b->tp_basicsize &&
3043 a->tp_itemsize == b->tp_itemsize &&
3044 a->tp_dictoffset == b->tp_dictoffset &&
3045 a->tp_weaklistoffset == b->tp_weaklistoffset &&
3046 ((a->tp_flags & Py_TPFLAGS_HAVE_GC) ==
3047 (b->tp_flags & Py_TPFLAGS_HAVE_GC)));
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003048}
3049
3050static int
3051same_slots_added(PyTypeObject *a, PyTypeObject *b)
3052{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003053 PyTypeObject *base = a->tp_base;
3054 Py_ssize_t size;
3055 PyObject *slots_a, *slots_b;
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003056
Benjamin Peterson67641d22011-01-17 19:24:34 +00003057 assert(base == b->tp_base);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003058 size = base->tp_basicsize;
3059 if (a->tp_dictoffset == size && b->tp_dictoffset == size)
3060 size += sizeof(PyObject *);
3061 if (a->tp_weaklistoffset == size && b->tp_weaklistoffset == size)
3062 size += sizeof(PyObject *);
Guido van Rossumd8faa362007-04-27 19:54:29 +00003063
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003064 /* Check slots compliance */
3065 slots_a = ((PyHeapTypeObject *)a)->ht_slots;
3066 slots_b = ((PyHeapTypeObject *)b)->ht_slots;
3067 if (slots_a && slots_b) {
3068 if (PyObject_RichCompareBool(slots_a, slots_b, Py_EQ) != 1)
3069 return 0;
3070 size += sizeof(PyObject *) * PyTuple_GET_SIZE(slots_a);
3071 }
3072 return size == a->tp_basicsize && size == b->tp_basicsize;
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003073}
3074
3075static int
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003076compatible_for_assignment(PyTypeObject* oldto, PyTypeObject* newto, char* attr)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003077{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003078 PyTypeObject *newbase, *oldbase;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003079
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003080 if (newto->tp_dealloc != oldto->tp_dealloc ||
3081 newto->tp_free != oldto->tp_free)
3082 {
3083 PyErr_Format(PyExc_TypeError,
3084 "%s assignment: "
3085 "'%s' deallocator differs from '%s'",
3086 attr,
3087 newto->tp_name,
3088 oldto->tp_name);
3089 return 0;
3090 }
3091 newbase = newto;
3092 oldbase = oldto;
3093 while (equiv_structs(newbase, newbase->tp_base))
3094 newbase = newbase->tp_base;
3095 while (equiv_structs(oldbase, oldbase->tp_base))
3096 oldbase = oldbase->tp_base;
3097 if (newbase != oldbase &&
3098 (newbase->tp_base != oldbase->tp_base ||
3099 !same_slots_added(newbase, oldbase))) {
3100 PyErr_Format(PyExc_TypeError,
3101 "%s assignment: "
3102 "'%s' object layout differs from '%s'",
3103 attr,
3104 newto->tp_name,
3105 oldto->tp_name);
3106 return 0;
3107 }
Tim Petersea7f75d2002-12-07 21:39:16 +00003108
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003109 return 1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003110}
3111
3112static int
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003113object_set_class(PyObject *self, PyObject *value, void *closure)
3114{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003115 PyTypeObject *oldto = Py_TYPE(self);
3116 PyTypeObject *newto;
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003117
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003118 if (value == NULL) {
3119 PyErr_SetString(PyExc_TypeError,
3120 "can't delete __class__ attribute");
3121 return -1;
3122 }
3123 if (!PyType_Check(value)) {
3124 PyErr_Format(PyExc_TypeError,
3125 "__class__ must be set to new-style class, not '%s' object",
3126 Py_TYPE(value)->tp_name);
3127 return -1;
3128 }
3129 newto = (PyTypeObject *)value;
3130 if (!(newto->tp_flags & Py_TPFLAGS_HEAPTYPE) ||
3131 !(oldto->tp_flags & Py_TPFLAGS_HEAPTYPE))
3132 {
3133 PyErr_Format(PyExc_TypeError,
3134 "__class__ assignment: only for heap types");
3135 return -1;
3136 }
3137 if (compatible_for_assignment(newto, oldto, "__class__")) {
3138 Py_INCREF(newto);
3139 Py_TYPE(self) = newto;
3140 Py_DECREF(oldto);
3141 return 0;
3142 }
3143 else {
3144 return -1;
3145 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003146}
3147
3148static PyGetSetDef object_getsets[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003149 {"__class__", object_get_class, object_set_class,
3150 PyDoc_STR("the object's class")},
3151 {0}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003152};
3153
Guido van Rossumc53f0092003-02-18 22:05:12 +00003154
Guido van Rossum036f9992003-02-21 22:02:54 +00003155/* Stuff to implement __reduce_ex__ for pickle protocols >= 2.
Alexandre Vassalottif7fa63d2008-05-11 08:55:36 +00003156 We fall back to helpers in copyreg for:
Guido van Rossum036f9992003-02-21 22:02:54 +00003157 - pickle protocols < 2
3158 - calculating the list of slot names (done only once per class)
3159 - the __newobj__ function (which is used as a token but never called)
3160*/
3161
3162static PyObject *
Alexandre Vassalottif7fa63d2008-05-11 08:55:36 +00003163import_copyreg(void)
Guido van Rossum036f9992003-02-21 22:02:54 +00003164{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003165 static PyObject *copyreg_str;
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003166 static PyObject *mod_copyreg = NULL;
Guido van Rossum3926a632001-09-25 16:25:58 +00003167
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003168 if (!copyreg_str) {
3169 copyreg_str = PyUnicode_InternFromString("copyreg");
3170 if (copyreg_str == NULL)
3171 return NULL;
3172 }
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003173 if (!mod_copyreg) {
3174 mod_copyreg = PyImport_Import(copyreg_str);
3175 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003176
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003177 Py_XINCREF(mod_copyreg);
3178 return mod_copyreg;
Guido van Rossum036f9992003-02-21 22:02:54 +00003179}
3180
3181static PyObject *
3182slotnames(PyObject *cls)
3183{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003184 PyObject *clsdict;
3185 PyObject *copyreg;
3186 PyObject *slotnames;
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003187 static PyObject *str_slotnames;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02003188 _Py_identifier(_slotnames);
Guido van Rossum036f9992003-02-21 22:02:54 +00003189
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003190 if (str_slotnames == NULL) {
3191 str_slotnames = PyUnicode_InternFromString("__slotnames__");
3192 if (str_slotnames == NULL)
3193 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003194 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003195
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003196 clsdict = ((PyTypeObject *)cls)->tp_dict;
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003197 slotnames = PyDict_GetItem(clsdict, str_slotnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003198 if (slotnames != NULL && PyList_Check(slotnames)) {
3199 Py_INCREF(slotnames);
3200 return slotnames;
3201 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003202
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003203 copyreg = import_copyreg();
3204 if (copyreg == NULL)
3205 return NULL;
Guido van Rossum036f9992003-02-21 22:02:54 +00003206
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02003207 slotnames = _PyObject_CallMethodId(copyreg, &PyId__slotnames, "O", cls);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003208 Py_DECREF(copyreg);
3209 if (slotnames != NULL &&
3210 slotnames != Py_None &&
3211 !PyList_Check(slotnames))
3212 {
3213 PyErr_SetString(PyExc_TypeError,
3214 "copyreg._slotnames didn't return a list or None");
3215 Py_DECREF(slotnames);
3216 slotnames = NULL;
3217 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003218
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003219 return slotnames;
Guido van Rossum036f9992003-02-21 22:02:54 +00003220}
3221
3222static PyObject *
3223reduce_2(PyObject *obj)
3224{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003225 PyObject *cls, *getnewargs;
3226 PyObject *args = NULL, *args2 = NULL;
3227 PyObject *getstate = NULL, *state = NULL, *names = NULL;
3228 PyObject *slots = NULL, *listitems = NULL, *dictitems = NULL;
3229 PyObject *copyreg = NULL, *newobj = NULL, *res = NULL;
3230 Py_ssize_t i, n;
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003231 static PyObject *str_getnewargs = NULL, *str_getstate = NULL,
3232 *str_newobj = NULL;
Guido van Rossum036f9992003-02-21 22:02:54 +00003233
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003234 if (str_getnewargs == NULL) {
3235 str_getnewargs = PyUnicode_InternFromString("__getnewargs__");
3236 str_getstate = PyUnicode_InternFromString("__getstate__");
3237 str_newobj = PyUnicode_InternFromString("__newobj__");
3238 if (!str_getnewargs || !str_getstate || !str_newobj)
3239 return NULL;
3240 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003241
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003242 cls = (PyObject *) Py_TYPE(obj);
3243
3244 getnewargs = PyObject_GetAttr(obj, str_getnewargs);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003245 if (getnewargs != NULL) {
3246 args = PyObject_CallObject(getnewargs, NULL);
3247 Py_DECREF(getnewargs);
3248 if (args != NULL && !PyTuple_Check(args)) {
3249 PyErr_Format(PyExc_TypeError,
3250 "__getnewargs__ should return a tuple, "
3251 "not '%.200s'", Py_TYPE(args)->tp_name);
3252 goto end;
3253 }
3254 }
3255 else {
3256 PyErr_Clear();
3257 args = PyTuple_New(0);
3258 }
3259 if (args == NULL)
3260 goto end;
Guido van Rossum036f9992003-02-21 22:02:54 +00003261
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003262 getstate = PyObject_GetAttr(obj, str_getstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003263 if (getstate != NULL) {
3264 state = PyObject_CallObject(getstate, NULL);
3265 Py_DECREF(getstate);
3266 if (state == NULL)
3267 goto end;
3268 }
3269 else {
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003270 PyObject **dict;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003271 PyErr_Clear();
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003272 dict = _PyObject_GetDictPtr(obj);
3273 if (dict && *dict)
3274 state = *dict;
3275 else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003276 state = Py_None;
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003277 Py_INCREF(state);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003278 names = slotnames(cls);
3279 if (names == NULL)
3280 goto end;
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003281 if (names != Py_None && PyList_GET_SIZE(names) > 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003282 assert(PyList_Check(names));
3283 slots = PyDict_New();
3284 if (slots == NULL)
3285 goto end;
3286 n = 0;
3287 /* Can't pre-compute the list size; the list
3288 is stored on the class so accessible to other
3289 threads, which may be run by DECREF */
3290 for (i = 0; i < PyList_GET_SIZE(names); i++) {
3291 PyObject *name, *value;
3292 name = PyList_GET_ITEM(names, i);
3293 value = PyObject_GetAttr(obj, name);
3294 if (value == NULL)
3295 PyErr_Clear();
3296 else {
3297 int err = PyDict_SetItem(slots, name,
3298 value);
3299 Py_DECREF(value);
3300 if (err)
3301 goto end;
3302 n++;
3303 }
3304 }
3305 if (n) {
3306 state = Py_BuildValue("(NO)", state, slots);
3307 if (state == NULL)
3308 goto end;
3309 }
3310 }
3311 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003312
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003313 if (!PyList_Check(obj)) {
3314 listitems = Py_None;
3315 Py_INCREF(listitems);
3316 }
3317 else {
3318 listitems = PyObject_GetIter(obj);
3319 if (listitems == NULL)
3320 goto end;
3321 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003322
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003323 if (!PyDict_Check(obj)) {
3324 dictitems = Py_None;
3325 Py_INCREF(dictitems);
3326 }
3327 else {
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02003328 _Py_identifier(items);
3329 PyObject *items = _PyObject_CallMethodId(obj, &PyId_items, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003330 if (items == NULL)
3331 goto end;
3332 dictitems = PyObject_GetIter(items);
3333 Py_DECREF(items);
3334 if (dictitems == NULL)
3335 goto end;
3336 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003337
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003338 copyreg = import_copyreg();
3339 if (copyreg == NULL)
3340 goto end;
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003341 newobj = PyObject_GetAttr(copyreg, str_newobj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003342 if (newobj == NULL)
3343 goto end;
Guido van Rossum036f9992003-02-21 22:02:54 +00003344
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003345 n = PyTuple_GET_SIZE(args);
3346 args2 = PyTuple_New(n+1);
3347 if (args2 == NULL)
3348 goto end;
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003349 Py_INCREF(cls);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003350 PyTuple_SET_ITEM(args2, 0, cls);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003351 for (i = 0; i < n; i++) {
3352 PyObject *v = PyTuple_GET_ITEM(args, i);
3353 Py_INCREF(v);
3354 PyTuple_SET_ITEM(args2, i+1, v);
3355 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003356
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003357 res = PyTuple_Pack(5, newobj, args2, state, listitems, dictitems);
Guido van Rossum036f9992003-02-21 22:02:54 +00003358
3359 end:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003360 Py_XDECREF(args);
3361 Py_XDECREF(args2);
3362 Py_XDECREF(slots);
3363 Py_XDECREF(state);
3364 Py_XDECREF(names);
3365 Py_XDECREF(listitems);
3366 Py_XDECREF(dictitems);
3367 Py_XDECREF(copyreg);
3368 Py_XDECREF(newobj);
3369 return res;
Guido van Rossum036f9992003-02-21 22:02:54 +00003370}
3371
Guido van Rossumd8faa362007-04-27 19:54:29 +00003372/*
3373 * There were two problems when object.__reduce__ and object.__reduce_ex__
3374 * were implemented in the same function:
3375 * - trying to pickle an object with a custom __reduce__ method that
3376 * fell back to object.__reduce__ in certain circumstances led to
3377 * infinite recursion at Python level and eventual RuntimeError.
3378 * - Pickling objects that lied about their type by overwriting the
3379 * __class__ descriptor could lead to infinite recursion at C level
3380 * and eventual segfault.
3381 *
3382 * Because of backwards compatibility, the two methods still have to
3383 * behave in the same way, even if this is not required by the pickle
3384 * protocol. This common functionality was moved to the _common_reduce
3385 * function.
3386 */
3387static PyObject *
3388_common_reduce(PyObject *self, int proto)
3389{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003390 PyObject *copyreg, *res;
Guido van Rossumd8faa362007-04-27 19:54:29 +00003391
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003392 if (proto >= 2)
3393 return reduce_2(self);
Guido van Rossumd8faa362007-04-27 19:54:29 +00003394
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003395 copyreg = import_copyreg();
3396 if (!copyreg)
3397 return NULL;
Guido van Rossumd8faa362007-04-27 19:54:29 +00003398
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003399 res = PyEval_CallMethod(copyreg, "_reduce_ex", "(Oi)", self, proto);
3400 Py_DECREF(copyreg);
Guido van Rossumd8faa362007-04-27 19:54:29 +00003401
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003402 return res;
Guido van Rossumd8faa362007-04-27 19:54:29 +00003403}
3404
3405static PyObject *
3406object_reduce(PyObject *self, PyObject *args)
3407{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003408 int proto = 0;
Guido van Rossumd8faa362007-04-27 19:54:29 +00003409
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003410 if (!PyArg_ParseTuple(args, "|i:__reduce__", &proto))
3411 return NULL;
Guido van Rossumd8faa362007-04-27 19:54:29 +00003412
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003413 return _common_reduce(self, proto);
Guido van Rossumd8faa362007-04-27 19:54:29 +00003414}
3415
Guido van Rossum036f9992003-02-21 22:02:54 +00003416static PyObject *
3417object_reduce_ex(PyObject *self, PyObject *args)
3418{
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003419 static PyObject *str_reduce = NULL, *objreduce;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003420 PyObject *reduce, *res;
3421 int proto = 0;
Guido van Rossum036f9992003-02-21 22:02:54 +00003422
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003423 if (!PyArg_ParseTuple(args, "|i:__reduce_ex__", &proto))
3424 return NULL;
Guido van Rossum036f9992003-02-21 22:02:54 +00003425
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003426 if (str_reduce == NULL) {
3427 str_reduce = PyUnicode_InternFromString("__reduce__");
3428 objreduce = PyDict_GetItemString(PyBaseObject_Type.tp_dict,
3429 "__reduce__");
3430 if (str_reduce == NULL || objreduce == NULL)
3431 return NULL;
3432 }
3433
3434 reduce = PyObject_GetAttr(self, str_reduce);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003435 if (reduce == NULL)
3436 PyErr_Clear();
3437 else {
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003438 PyObject *cls, *clsreduce;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003439 int override;
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003440
3441 cls = (PyObject *) Py_TYPE(self);
3442 clsreduce = PyObject_GetAttr(cls, str_reduce);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003443 if (clsreduce == NULL) {
3444 Py_DECREF(reduce);
3445 return NULL;
3446 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003447 override = (clsreduce != objreduce);
3448 Py_DECREF(clsreduce);
3449 if (override) {
3450 res = PyObject_CallObject(reduce, NULL);
3451 Py_DECREF(reduce);
3452 return res;
3453 }
3454 else
3455 Py_DECREF(reduce);
3456 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003457
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003458 return _common_reduce(self, proto);
Guido van Rossum3926a632001-09-25 16:25:58 +00003459}
3460
Christian Heimes9e7f1d22008-02-28 12:27:11 +00003461static PyObject *
3462object_subclasshook(PyObject *cls, PyObject *args)
3463{
Brian Curtindfc80e32011-08-10 20:28:54 -05003464 Py_RETURN_NOTIMPLEMENTED;
Christian Heimes9e7f1d22008-02-28 12:27:11 +00003465}
3466
3467PyDoc_STRVAR(object_subclasshook_doc,
3468"Abstract classes can override this to customize issubclass().\n"
3469"\n"
3470"This is invoked early on by abc.ABCMeta.__subclasscheck__().\n"
3471"It should return True, False or NotImplemented. If it returns\n"
3472"NotImplemented, the normal algorithm is used. Otherwise, it\n"
3473"overrides the normal algorithm (and the outcome is cached).\n");
Eric Smith8c663262007-08-25 02:26:07 +00003474
3475/*
3476 from PEP 3101, this code implements:
3477
3478 class object:
3479 def __format__(self, format_spec):
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003480 return format(str(self), format_spec)
Eric Smith8c663262007-08-25 02:26:07 +00003481*/
3482static PyObject *
3483object_format(PyObject *self, PyObject *args)
3484{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003485 PyObject *format_spec;
3486 PyObject *self_as_str = NULL;
3487 PyObject *result = NULL;
Eric Smith8c663262007-08-25 02:26:07 +00003488
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003489 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
3490 return NULL;
Eric Smith8c663262007-08-25 02:26:07 +00003491
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003492 self_as_str = PyObject_Str(self);
Eric Smithe4d63172010-09-13 20:48:43 +00003493 if (self_as_str != NULL) {
3494 /* Issue 7994: If we're converting to a string, we
Eric V. Smithb9cd3532011-03-12 10:08:48 -05003495 should reject format specifications */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003496 if (PyUnicode_GET_LENGTH(format_spec) > 0) {
Eric V. Smithb9cd3532011-03-12 10:08:48 -05003497 if (PyErr_WarnEx(PyExc_DeprecationWarning,
3498 "object.__format__ with a non-empty format "
3499 "string is deprecated", 1) < 0) {
3500 goto done;
3501 }
3502 /* Eventually this will become an error:
3503 PyErr_Format(PyExc_TypeError,
3504 "non-empty format string passed to object.__format__");
3505 goto done;
3506 */
3507 }
Eric Smith8c663262007-08-25 02:26:07 +00003508
Eric V. Smithb9cd3532011-03-12 10:08:48 -05003509 result = PyObject_Format(self_as_str, format_spec);
Eric Smithe4d63172010-09-13 20:48:43 +00003510 }
3511
3512done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003513 Py_XDECREF(self_as_str);
Eric Smith8c663262007-08-25 02:26:07 +00003514
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003515 return result;
Eric Smith8c663262007-08-25 02:26:07 +00003516}
3517
Martin v. Löwis00709aa2008-06-04 14:18:43 +00003518static PyObject *
3519object_sizeof(PyObject *self, PyObject *args)
3520{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003521 Py_ssize_t res, isize;
Martin v. Löwis00709aa2008-06-04 14:18:43 +00003522
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003523 res = 0;
3524 isize = self->ob_type->tp_itemsize;
3525 if (isize > 0)
3526 res = Py_SIZE(self->ob_type) * isize;
3527 res += self->ob_type->tp_basicsize;
Martin v. Löwis00709aa2008-06-04 14:18:43 +00003528
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003529 return PyLong_FromSsize_t(res);
Martin v. Löwis00709aa2008-06-04 14:18:43 +00003530}
3531
Benjamin Peterson82b00c12011-05-24 11:09:06 -05003532/* __dir__ for generic objects: returns __dict__, __class__,
3533 and recursively up the __class__.__bases__ chain.
3534*/
3535static PyObject *
3536object_dir(PyObject *self, PyObject *args)
3537{
3538 PyObject *result = NULL;
3539 PyObject *dict = NULL;
3540 PyObject *itsclass = NULL;
3541
3542 /* Get __dict__ (which may or may not be a real dict...) */
3543 dict = PyObject_GetAttrString(self, "__dict__");
3544 if (dict == NULL) {
3545 PyErr_Clear();
3546 dict = PyDict_New();
3547 }
3548 else if (!PyDict_Check(dict)) {
3549 Py_DECREF(dict);
3550 dict = PyDict_New();
3551 }
3552 else {
3553 /* Copy __dict__ to avoid mutating it. */
3554 PyObject *temp = PyDict_Copy(dict);
3555 Py_DECREF(dict);
3556 dict = temp;
3557 }
3558
3559 if (dict == NULL)
3560 goto error;
3561
3562 /* Merge in attrs reachable from its class. */
3563 itsclass = PyObject_GetAttrString(self, "__class__");
3564 if (itsclass == NULL)
3565 /* XXX(tomer): Perhaps fall back to obj->ob_type if no
3566 __class__ exists? */
3567 PyErr_Clear();
3568 else if (merge_class_dict(dict, itsclass) != 0)
3569 goto error;
3570
3571 result = PyDict_Keys(dict);
3572 /* fall through */
3573error:
3574 Py_XDECREF(itsclass);
3575 Py_XDECREF(dict);
3576 return result;
3577}
3578
Guido van Rossum3926a632001-09-25 16:25:58 +00003579static PyMethodDef object_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003580 {"__reduce_ex__", object_reduce_ex, METH_VARARGS,
3581 PyDoc_STR("helper for pickle")},
3582 {"__reduce__", object_reduce, METH_VARARGS,
3583 PyDoc_STR("helper for pickle")},
3584 {"__subclasshook__", object_subclasshook, METH_CLASS | METH_VARARGS,
3585 object_subclasshook_doc},
3586 {"__format__", object_format, METH_VARARGS,
3587 PyDoc_STR("default object formatter")},
3588 {"__sizeof__", object_sizeof, METH_NOARGS,
Benjamin Petersonfbe56bb2011-05-24 12:42:51 -05003589 PyDoc_STR("__sizeof__() -> int\nsize of object in memory, in bytes")},
Benjamin Peterson82b00c12011-05-24 11:09:06 -05003590 {"__dir__", object_dir, METH_NOARGS,
Benjamin Petersonc7284122011-05-24 12:46:15 -05003591 PyDoc_STR("__dir__() -> list\ndefault dir() implementation")},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003592 {0}
Guido van Rossum3926a632001-09-25 16:25:58 +00003593};
3594
Guido van Rossum036f9992003-02-21 22:02:54 +00003595
Tim Peters6d6c1a32001-08-02 04:15:00 +00003596PyTypeObject PyBaseObject_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003597 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3598 "object", /* tp_name */
3599 sizeof(PyObject), /* tp_basicsize */
3600 0, /* tp_itemsize */
3601 object_dealloc, /* tp_dealloc */
3602 0, /* tp_print */
3603 0, /* tp_getattr */
3604 0, /* tp_setattr */
3605 0, /* tp_reserved */
3606 object_repr, /* tp_repr */
3607 0, /* tp_as_number */
3608 0, /* tp_as_sequence */
3609 0, /* tp_as_mapping */
3610 (hashfunc)_Py_HashPointer, /* tp_hash */
3611 0, /* tp_call */
3612 object_str, /* tp_str */
3613 PyObject_GenericGetAttr, /* tp_getattro */
3614 PyObject_GenericSetAttr, /* tp_setattro */
3615 0, /* tp_as_buffer */
3616 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
3617 PyDoc_STR("The most base type"), /* tp_doc */
3618 0, /* tp_traverse */
3619 0, /* tp_clear */
3620 object_richcompare, /* tp_richcompare */
3621 0, /* tp_weaklistoffset */
3622 0, /* tp_iter */
3623 0, /* tp_iternext */
3624 object_methods, /* tp_methods */
3625 0, /* tp_members */
3626 object_getsets, /* tp_getset */
3627 0, /* tp_base */
3628 0, /* tp_dict */
3629 0, /* tp_descr_get */
3630 0, /* tp_descr_set */
3631 0, /* tp_dictoffset */
3632 object_init, /* tp_init */
3633 PyType_GenericAlloc, /* tp_alloc */
3634 object_new, /* tp_new */
3635 PyObject_Del, /* tp_free */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003636};
3637
3638
Guido van Rossum50e9fb92006-08-17 05:42:55 +00003639/* Add the methods from tp_methods to the __dict__ in a type object */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003640
3641static int
3642add_methods(PyTypeObject *type, PyMethodDef *meth)
3643{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003644 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003645
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003646 for (; meth->ml_name != NULL; meth++) {
3647 PyObject *descr;
3648 if (PyDict_GetItemString(dict, meth->ml_name) &&
3649 !(meth->ml_flags & METH_COEXIST))
3650 continue;
3651 if (meth->ml_flags & METH_CLASS) {
3652 if (meth->ml_flags & METH_STATIC) {
3653 PyErr_SetString(PyExc_ValueError,
3654 "method cannot be both class and static");
3655 return -1;
3656 }
3657 descr = PyDescr_NewClassMethod(type, meth);
3658 }
3659 else if (meth->ml_flags & METH_STATIC) {
3660 PyObject *cfunc = PyCFunction_New(meth, NULL);
3661 if (cfunc == NULL)
3662 return -1;
3663 descr = PyStaticMethod_New(cfunc);
3664 Py_DECREF(cfunc);
3665 }
3666 else {
3667 descr = PyDescr_NewMethod(type, meth);
3668 }
3669 if (descr == NULL)
3670 return -1;
3671 if (PyDict_SetItemString(dict, meth->ml_name, descr) < 0)
3672 return -1;
3673 Py_DECREF(descr);
3674 }
3675 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003676}
3677
3678static int
Guido van Rossum6f799372001-09-20 20:46:19 +00003679add_members(PyTypeObject *type, PyMemberDef *memb)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003680{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003681 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003682
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003683 for (; memb->name != NULL; memb++) {
3684 PyObject *descr;
3685 if (PyDict_GetItemString(dict, memb->name))
3686 continue;
3687 descr = PyDescr_NewMember(type, memb);
3688 if (descr == NULL)
3689 return -1;
3690 if (PyDict_SetItemString(dict, memb->name, descr) < 0)
3691 return -1;
3692 Py_DECREF(descr);
3693 }
3694 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003695}
3696
3697static int
Guido van Rossum32d34c82001-09-20 21:45:26 +00003698add_getset(PyTypeObject *type, PyGetSetDef *gsp)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003699{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003700 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003701
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003702 for (; gsp->name != NULL; gsp++) {
3703 PyObject *descr;
3704 if (PyDict_GetItemString(dict, gsp->name))
3705 continue;
3706 descr = PyDescr_NewGetSet(type, gsp);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003707
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003708 if (descr == NULL)
3709 return -1;
3710 if (PyDict_SetItemString(dict, gsp->name, descr) < 0)
3711 return -1;
3712 Py_DECREF(descr);
3713 }
3714 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003715}
3716
Guido van Rossum13d52f02001-08-10 21:24:08 +00003717static void
3718inherit_special(PyTypeObject *type, PyTypeObject *base)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003719{
Tim Peters6d6c1a32001-08-02 04:15:00 +00003720
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003721 /* Copying basicsize is connected to the GC flags */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003722 if (!(type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
3723 (base->tp_flags & Py_TPFLAGS_HAVE_GC) &&
3724 (!type->tp_traverse && !type->tp_clear)) {
3725 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
3726 if (type->tp_traverse == NULL)
3727 type->tp_traverse = base->tp_traverse;
3728 if (type->tp_clear == NULL)
3729 type->tp_clear = base->tp_clear;
3730 }
3731 {
3732 /* The condition below could use some explanation.
3733 It appears that tp_new is not inherited for static types
3734 whose base class is 'object'; this seems to be a precaution
3735 so that old extension types don't suddenly become
3736 callable (object.__new__ wouldn't insure the invariants
3737 that the extension type's own factory function ensures).
3738 Heap types, of course, are under our control, so they do
3739 inherit tp_new; static extension types that specify some
3740 other built-in type as the default are considered
3741 new-style-aware so they also inherit object.__new__. */
3742 if (base != &PyBaseObject_Type ||
3743 (type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
3744 if (type->tp_new == NULL)
3745 type->tp_new = base->tp_new;
3746 }
3747 }
Benjamin Petersona7465e22010-07-05 15:01:22 +00003748 if (type->tp_basicsize == 0)
3749 type->tp_basicsize = base->tp_basicsize;
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00003750
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003751 /* Copy other non-function slots */
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00003752
3753#undef COPYVAL
3754#define COPYVAL(SLOT) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003755 if (type->SLOT == 0) type->SLOT = base->SLOT
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00003756
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003757 COPYVAL(tp_itemsize);
3758 COPYVAL(tp_weaklistoffset);
3759 COPYVAL(tp_dictoffset);
Thomas Wouters27d517b2007-02-25 20:39:11 +00003760
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003761 /* Setup fast subclass flags */
3762 if (PyType_IsSubtype(base, (PyTypeObject*)PyExc_BaseException))
3763 type->tp_flags |= Py_TPFLAGS_BASE_EXC_SUBCLASS;
3764 else if (PyType_IsSubtype(base, &PyType_Type))
3765 type->tp_flags |= Py_TPFLAGS_TYPE_SUBCLASS;
3766 else if (PyType_IsSubtype(base, &PyLong_Type))
3767 type->tp_flags |= Py_TPFLAGS_LONG_SUBCLASS;
3768 else if (PyType_IsSubtype(base, &PyBytes_Type))
3769 type->tp_flags |= Py_TPFLAGS_BYTES_SUBCLASS;
3770 else if (PyType_IsSubtype(base, &PyUnicode_Type))
3771 type->tp_flags |= Py_TPFLAGS_UNICODE_SUBCLASS;
3772 else if (PyType_IsSubtype(base, &PyTuple_Type))
3773 type->tp_flags |= Py_TPFLAGS_TUPLE_SUBCLASS;
3774 else if (PyType_IsSubtype(base, &PyList_Type))
3775 type->tp_flags |= Py_TPFLAGS_LIST_SUBCLASS;
3776 else if (PyType_IsSubtype(base, &PyDict_Type))
3777 type->tp_flags |= Py_TPFLAGS_DICT_SUBCLASS;
Guido van Rossum13d52f02001-08-10 21:24:08 +00003778}
3779
Guido van Rossumf5243f02008-01-01 04:06:48 +00003780static char *hash_name_op[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003781 "__eq__",
3782 "__hash__",
3783 NULL
Guido van Rossum38938152006-08-21 23:36:26 +00003784};
3785
3786static int
Guido van Rossumf5243f02008-01-01 04:06:48 +00003787overrides_hash(PyTypeObject *type)
Guido van Rossum38938152006-08-21 23:36:26 +00003788{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003789 char **p;
3790 PyObject *dict = type->tp_dict;
Guido van Rossum38938152006-08-21 23:36:26 +00003791
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003792 assert(dict != NULL);
3793 for (p = hash_name_op; *p; p++) {
3794 if (PyDict_GetItemString(dict, *p) != NULL)
3795 return 1;
3796 }
3797 return 0;
Guido van Rossum38938152006-08-21 23:36:26 +00003798}
3799
Guido van Rossum13d52f02001-08-10 21:24:08 +00003800static void
3801inherit_slots(PyTypeObject *type, PyTypeObject *base)
3802{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003803 PyTypeObject *basebase;
Guido van Rossum13d52f02001-08-10 21:24:08 +00003804
3805#undef SLOTDEFINED
Tim Peters6d6c1a32001-08-02 04:15:00 +00003806#undef COPYSLOT
3807#undef COPYNUM
3808#undef COPYSEQ
3809#undef COPYMAP
Guido van Rossum5af588b2001-10-12 14:13:21 +00003810#undef COPYBUF
Guido van Rossum13d52f02001-08-10 21:24:08 +00003811
3812#define SLOTDEFINED(SLOT) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003813 (base->SLOT != 0 && \
3814 (basebase == NULL || base->SLOT != basebase->SLOT))
Guido van Rossum13d52f02001-08-10 21:24:08 +00003815
Tim Peters6d6c1a32001-08-02 04:15:00 +00003816#define COPYSLOT(SLOT) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003817 if (!type->SLOT && SLOTDEFINED(SLOT)) type->SLOT = base->SLOT
Tim Peters6d6c1a32001-08-02 04:15:00 +00003818
3819#define COPYNUM(SLOT) COPYSLOT(tp_as_number->SLOT)
3820#define COPYSEQ(SLOT) COPYSLOT(tp_as_sequence->SLOT)
3821#define COPYMAP(SLOT) COPYSLOT(tp_as_mapping->SLOT)
Tim Petersfc57ccb2001-10-12 02:38:24 +00003822#define COPYBUF(SLOT) COPYSLOT(tp_as_buffer->SLOT)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003823
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003824 /* This won't inherit indirect slots (from tp_as_number etc.)
3825 if type doesn't provide the space. */
Guido van Rossum13d52f02001-08-10 21:24:08 +00003826
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003827 if (type->tp_as_number != NULL && base->tp_as_number != NULL) {
3828 basebase = base->tp_base;
3829 if (basebase->tp_as_number == NULL)
3830 basebase = NULL;
3831 COPYNUM(nb_add);
3832 COPYNUM(nb_subtract);
3833 COPYNUM(nb_multiply);
3834 COPYNUM(nb_remainder);
3835 COPYNUM(nb_divmod);
3836 COPYNUM(nb_power);
3837 COPYNUM(nb_negative);
3838 COPYNUM(nb_positive);
3839 COPYNUM(nb_absolute);
3840 COPYNUM(nb_bool);
3841 COPYNUM(nb_invert);
3842 COPYNUM(nb_lshift);
3843 COPYNUM(nb_rshift);
3844 COPYNUM(nb_and);
3845 COPYNUM(nb_xor);
3846 COPYNUM(nb_or);
3847 COPYNUM(nb_int);
3848 COPYNUM(nb_float);
3849 COPYNUM(nb_inplace_add);
3850 COPYNUM(nb_inplace_subtract);
3851 COPYNUM(nb_inplace_multiply);
3852 COPYNUM(nb_inplace_remainder);
3853 COPYNUM(nb_inplace_power);
3854 COPYNUM(nb_inplace_lshift);
3855 COPYNUM(nb_inplace_rshift);
3856 COPYNUM(nb_inplace_and);
3857 COPYNUM(nb_inplace_xor);
3858 COPYNUM(nb_inplace_or);
3859 COPYNUM(nb_true_divide);
3860 COPYNUM(nb_floor_divide);
3861 COPYNUM(nb_inplace_true_divide);
3862 COPYNUM(nb_inplace_floor_divide);
3863 COPYNUM(nb_index);
3864 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003865
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003866 if (type->tp_as_sequence != NULL && base->tp_as_sequence != NULL) {
3867 basebase = base->tp_base;
3868 if (basebase->tp_as_sequence == NULL)
3869 basebase = NULL;
3870 COPYSEQ(sq_length);
3871 COPYSEQ(sq_concat);
3872 COPYSEQ(sq_repeat);
3873 COPYSEQ(sq_item);
3874 COPYSEQ(sq_ass_item);
3875 COPYSEQ(sq_contains);
3876 COPYSEQ(sq_inplace_concat);
3877 COPYSEQ(sq_inplace_repeat);
3878 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003879
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003880 if (type->tp_as_mapping != NULL && base->tp_as_mapping != NULL) {
3881 basebase = base->tp_base;
3882 if (basebase->tp_as_mapping == NULL)
3883 basebase = NULL;
3884 COPYMAP(mp_length);
3885 COPYMAP(mp_subscript);
3886 COPYMAP(mp_ass_subscript);
3887 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003888
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003889 if (type->tp_as_buffer != NULL && base->tp_as_buffer != NULL) {
3890 basebase = base->tp_base;
3891 if (basebase->tp_as_buffer == NULL)
3892 basebase = NULL;
3893 COPYBUF(bf_getbuffer);
3894 COPYBUF(bf_releasebuffer);
3895 }
Tim Petersfc57ccb2001-10-12 02:38:24 +00003896
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003897 basebase = base->tp_base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003898
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003899 COPYSLOT(tp_dealloc);
3900 if (type->tp_getattr == NULL && type->tp_getattro == NULL) {
3901 type->tp_getattr = base->tp_getattr;
3902 type->tp_getattro = base->tp_getattro;
3903 }
3904 if (type->tp_setattr == NULL && type->tp_setattro == NULL) {
3905 type->tp_setattr = base->tp_setattr;
3906 type->tp_setattro = base->tp_setattro;
3907 }
3908 /* tp_reserved is ignored */
3909 COPYSLOT(tp_repr);
3910 /* tp_hash see tp_richcompare */
3911 COPYSLOT(tp_call);
3912 COPYSLOT(tp_str);
3913 {
3914 /* Copy comparison-related slots only when
3915 not overriding them anywhere */
3916 if (type->tp_richcompare == NULL &&
3917 type->tp_hash == NULL &&
3918 !overrides_hash(type))
3919 {
3920 type->tp_richcompare = base->tp_richcompare;
3921 type->tp_hash = base->tp_hash;
3922 }
3923 }
3924 {
3925 COPYSLOT(tp_iter);
3926 COPYSLOT(tp_iternext);
3927 }
3928 {
3929 COPYSLOT(tp_descr_get);
3930 COPYSLOT(tp_descr_set);
3931 COPYSLOT(tp_dictoffset);
3932 COPYSLOT(tp_init);
3933 COPYSLOT(tp_alloc);
3934 COPYSLOT(tp_is_gc);
3935 if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) ==
3936 (base->tp_flags & Py_TPFLAGS_HAVE_GC)) {
3937 /* They agree about gc. */
3938 COPYSLOT(tp_free);
3939 }
3940 else if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
3941 type->tp_free == NULL &&
3942 base->tp_free == PyObject_Free) {
3943 /* A bit of magic to plug in the correct default
3944 * tp_free function when a derived class adds gc,
3945 * didn't define tp_free, and the base uses the
3946 * default non-gc tp_free.
3947 */
3948 type->tp_free = PyObject_GC_Del;
3949 }
3950 /* else they didn't agree about gc, and there isn't something
3951 * obvious to be done -- the type is on its own.
3952 */
3953 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003954}
3955
Jeremy Hylton938ace62002-07-17 16:30:39 +00003956static int add_operators(PyTypeObject *);
Guido van Rossum13d52f02001-08-10 21:24:08 +00003957
Tim Peters6d6c1a32001-08-02 04:15:00 +00003958int
Guido van Rossum528b7eb2001-08-07 17:24:28 +00003959PyType_Ready(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003960{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003961 PyObject *dict, *bases;
3962 PyTypeObject *base;
3963 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003964
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003965 if (type->tp_flags & Py_TPFLAGS_READY) {
3966 assert(type->tp_dict != NULL);
3967 return 0;
3968 }
3969 assert((type->tp_flags & Py_TPFLAGS_READYING) == 0);
Guido van Rossumd614f972001-08-10 17:39:49 +00003970
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003971 type->tp_flags |= Py_TPFLAGS_READYING;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003972
Tim Peters36eb4df2003-03-23 03:33:13 +00003973#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003974 /* PyType_Ready is the closest thing we have to a choke point
3975 * for type objects, so is the best place I can think of to try
3976 * to get type objects into the doubly-linked list of all objects.
3977 * Still, not all type objects go thru PyType_Ready.
3978 */
3979 _Py_AddToAllObjects((PyObject *)type, 0);
Tim Peters36eb4df2003-03-23 03:33:13 +00003980#endif
3981
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003982 /* Initialize tp_base (defaults to BaseObject unless that's us) */
3983 base = type->tp_base;
3984 if (base == NULL && type != &PyBaseObject_Type) {
3985 base = type->tp_base = &PyBaseObject_Type;
3986 Py_INCREF(base);
3987 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003988
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003989 /* Now the only way base can still be NULL is if type is
3990 * &PyBaseObject_Type.
3991 */
Guido van Rossum692cdbc2006-03-10 02:04:28 +00003992
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003993 /* Initialize the base class */
3994 if (base != NULL && base->tp_dict == NULL) {
3995 if (PyType_Ready(base) < 0)
3996 goto error;
3997 }
Guido van Rossum323a9cf2002-08-14 17:26:30 +00003998
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003999 /* Initialize ob_type if NULL. This means extensions that want to be
4000 compilable separately on Windows can call PyType_Ready() instead of
4001 initializing the ob_type field of their type objects. */
4002 /* The test for base != NULL is really unnecessary, since base is only
4003 NULL when type is &PyBaseObject_Type, and we know its ob_type is
4004 not NULL (it's initialized to &PyType_Type). But coverity doesn't
4005 know that. */
4006 if (Py_TYPE(type) == NULL && base != NULL)
4007 Py_TYPE(type) = Py_TYPE(base);
Guido van Rossum0986d822002-04-08 01:38:42 +00004008
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004009 /* Initialize tp_bases */
4010 bases = type->tp_bases;
4011 if (bases == NULL) {
4012 if (base == NULL)
4013 bases = PyTuple_New(0);
4014 else
4015 bases = PyTuple_Pack(1, base);
4016 if (bases == NULL)
4017 goto error;
4018 type->tp_bases = bases;
4019 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004020
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004021 /* Initialize tp_dict */
4022 dict = type->tp_dict;
4023 if (dict == NULL) {
4024 dict = PyDict_New();
4025 if (dict == NULL)
4026 goto error;
4027 type->tp_dict = dict;
4028 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004029
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004030 /* Add type-specific descriptors to tp_dict */
4031 if (add_operators(type) < 0)
4032 goto error;
4033 if (type->tp_methods != NULL) {
4034 if (add_methods(type, type->tp_methods) < 0)
4035 goto error;
4036 }
4037 if (type->tp_members != NULL) {
4038 if (add_members(type, type->tp_members) < 0)
4039 goto error;
4040 }
4041 if (type->tp_getset != NULL) {
4042 if (add_getset(type, type->tp_getset) < 0)
4043 goto error;
4044 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004045
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004046 /* Calculate method resolution order */
4047 if (mro_internal(type) < 0) {
4048 goto error;
4049 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004050
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004051 /* Inherit special flags from dominant base */
4052 if (type->tp_base != NULL)
4053 inherit_special(type, type->tp_base);
Guido van Rossum13d52f02001-08-10 21:24:08 +00004054
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004055 /* Initialize tp_dict properly */
4056 bases = type->tp_mro;
4057 assert(bases != NULL);
4058 assert(PyTuple_Check(bases));
4059 n = PyTuple_GET_SIZE(bases);
4060 for (i = 1; i < n; i++) {
4061 PyObject *b = PyTuple_GET_ITEM(bases, i);
4062 if (PyType_Check(b))
4063 inherit_slots(type, (PyTypeObject *)b);
4064 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004065
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004066 /* Sanity check for tp_free. */
4067 if (PyType_IS_GC(type) && (type->tp_flags & Py_TPFLAGS_BASETYPE) &&
4068 (type->tp_free == NULL || type->tp_free == PyObject_Del)) {
4069 /* This base class needs to call tp_free, but doesn't have
4070 * one, or its tp_free is for non-gc'ed objects.
4071 */
4072 PyErr_Format(PyExc_TypeError, "type '%.100s' participates in "
4073 "gc and is a base type but has inappropriate "
4074 "tp_free slot",
4075 type->tp_name);
4076 goto error;
4077 }
Tim Peters3cfe7542003-05-21 21:29:48 +00004078
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004079 /* if the type dictionary doesn't contain a __doc__, set it from
4080 the tp_doc slot.
4081 */
4082 if (PyDict_GetItemString(type->tp_dict, "__doc__") == NULL) {
4083 if (type->tp_doc != NULL) {
4084 PyObject *doc = PyUnicode_FromString(type->tp_doc);
4085 if (doc == NULL)
4086 goto error;
4087 PyDict_SetItemString(type->tp_dict, "__doc__", doc);
4088 Py_DECREF(doc);
4089 } else {
4090 PyDict_SetItemString(type->tp_dict,
4091 "__doc__", Py_None);
4092 }
4093 }
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00004094
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004095 /* Hack for tp_hash and __hash__.
4096 If after all that, tp_hash is still NULL, and __hash__ is not in
4097 tp_dict, set tp_hash to PyObject_HashNotImplemented and
4098 tp_dict['__hash__'] equal to None.
4099 This signals that __hash__ is not inherited.
4100 */
4101 if (type->tp_hash == NULL) {
4102 if (PyDict_GetItemString(type->tp_dict, "__hash__") == NULL) {
4103 if (PyDict_SetItemString(type->tp_dict, "__hash__", Py_None) < 0)
4104 goto error;
4105 type->tp_hash = PyObject_HashNotImplemented;
4106 }
4107 }
Guido van Rossum38938152006-08-21 23:36:26 +00004108
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004109 /* Some more special stuff */
4110 base = type->tp_base;
4111 if (base != NULL) {
4112 if (type->tp_as_number == NULL)
4113 type->tp_as_number = base->tp_as_number;
4114 if (type->tp_as_sequence == NULL)
4115 type->tp_as_sequence = base->tp_as_sequence;
4116 if (type->tp_as_mapping == NULL)
4117 type->tp_as_mapping = base->tp_as_mapping;
4118 if (type->tp_as_buffer == NULL)
4119 type->tp_as_buffer = base->tp_as_buffer;
4120 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004121
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004122 /* Link into each base class's list of subclasses */
4123 bases = type->tp_bases;
4124 n = PyTuple_GET_SIZE(bases);
4125 for (i = 0; i < n; i++) {
4126 PyObject *b = PyTuple_GET_ITEM(bases, i);
4127 if (PyType_Check(b) &&
4128 add_subclass((PyTypeObject *)b, type) < 0)
4129 goto error;
4130 }
Guido van Rossum1c450732001-10-08 15:18:27 +00004131
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004132 /* Warn for a type that implements tp_compare (now known as
4133 tp_reserved) but not tp_richcompare. */
4134 if (type->tp_reserved && !type->tp_richcompare) {
4135 int error;
Victor Stinner4a2b7a12010-08-13 14:03:48 +00004136 error = PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
4137 "Type %.100s defines tp_reserved (formerly tp_compare) "
4138 "but not tp_richcompare. Comparisons may not behave as intended.",
4139 type->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004140 if (error == -1)
4141 goto error;
4142 }
Mark Dickinson2a7d45b2009-02-08 11:02:10 +00004143
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004144 /* All done -- set the ready flag */
4145 assert(type->tp_dict != NULL);
4146 type->tp_flags =
4147 (type->tp_flags & ~Py_TPFLAGS_READYING) | Py_TPFLAGS_READY;
4148 return 0;
Guido van Rossumd614f972001-08-10 17:39:49 +00004149
4150 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004151 type->tp_flags &= ~Py_TPFLAGS_READYING;
4152 return -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004153}
4154
Guido van Rossum1c450732001-10-08 15:18:27 +00004155static int
4156add_subclass(PyTypeObject *base, PyTypeObject *type)
4157{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004158 Py_ssize_t i;
4159 int result;
4160 PyObject *list, *ref, *newobj;
Guido van Rossum1c450732001-10-08 15:18:27 +00004161
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004162 list = base->tp_subclasses;
4163 if (list == NULL) {
4164 base->tp_subclasses = list = PyList_New(0);
4165 if (list == NULL)
4166 return -1;
4167 }
4168 assert(PyList_Check(list));
4169 newobj = PyWeakref_NewRef((PyObject *)type, NULL);
4170 i = PyList_GET_SIZE(list);
4171 while (--i >= 0) {
4172 ref = PyList_GET_ITEM(list, i);
4173 assert(PyWeakref_CheckRef(ref));
4174 if (PyWeakref_GET_OBJECT(ref) == Py_None)
4175 return PyList_SetItem(list, i, newobj);
4176 }
4177 result = PyList_Append(list, newobj);
4178 Py_DECREF(newobj);
4179 return result;
Guido van Rossum1c450732001-10-08 15:18:27 +00004180}
4181
Michael W. Hudson98bbc492002-11-26 14:47:27 +00004182static void
4183remove_subclass(PyTypeObject *base, PyTypeObject *type)
4184{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004185 Py_ssize_t i;
4186 PyObject *list, *ref;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00004187
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004188 list = base->tp_subclasses;
4189 if (list == NULL) {
4190 return;
4191 }
4192 assert(PyList_Check(list));
4193 i = PyList_GET_SIZE(list);
4194 while (--i >= 0) {
4195 ref = PyList_GET_ITEM(list, i);
4196 assert(PyWeakref_CheckRef(ref));
4197 if (PyWeakref_GET_OBJECT(ref) == (PyObject*)type) {
4198 /* this can't fail, right? */
4199 PySequence_DelItem(list, i);
4200 return;
4201 }
4202 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +00004203}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004204
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004205static int
4206check_num_args(PyObject *ob, int n)
4207{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004208 if (!PyTuple_CheckExact(ob)) {
4209 PyErr_SetString(PyExc_SystemError,
4210 "PyArg_UnpackTuple() argument list is not a tuple");
4211 return 0;
4212 }
4213 if (n == PyTuple_GET_SIZE(ob))
4214 return 1;
4215 PyErr_Format(
4216 PyExc_TypeError,
4217 "expected %d arguments, got %zd", n, PyTuple_GET_SIZE(ob));
4218 return 0;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004219}
4220
Tim Peters6d6c1a32001-08-02 04:15:00 +00004221/* Generic wrappers for overloadable 'operators' such as __getitem__ */
4222
4223/* There's a wrapper *function* for each distinct function typedef used
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004224 for type object slots (e.g. binaryfunc, ternaryfunc, etc.). There's a
Tim Peters6d6c1a32001-08-02 04:15:00 +00004225 wrapper *table* for each distinct operation (e.g. __len__, __add__).
4226 Most tables have only one entry; the tables for binary operators have two
4227 entries, one regular and one with reversed arguments. */
4228
4229static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00004230wrap_lenfunc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004231{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004232 lenfunc func = (lenfunc)wrapped;
4233 Py_ssize_t res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004234
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004235 if (!check_num_args(args, 0))
4236 return NULL;
4237 res = (*func)(self);
4238 if (res == -1 && PyErr_Occurred())
4239 return NULL;
4240 return PyLong_FromLong((long)res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004241}
4242
Tim Peters6d6c1a32001-08-02 04:15:00 +00004243static PyObject *
Raymond Hettingerf34f2642003-10-11 17:29:04 +00004244wrap_inquirypred(PyObject *self, PyObject *args, void *wrapped)
4245{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004246 inquiry func = (inquiry)wrapped;
4247 int res;
Raymond Hettingerf34f2642003-10-11 17:29:04 +00004248
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004249 if (!check_num_args(args, 0))
4250 return NULL;
4251 res = (*func)(self);
4252 if (res == -1 && PyErr_Occurred())
4253 return NULL;
4254 return PyBool_FromLong((long)res);
Raymond Hettingerf34f2642003-10-11 17:29:04 +00004255}
4256
4257static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00004258wrap_binaryfunc(PyObject *self, PyObject *args, void *wrapped)
4259{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004260 binaryfunc func = (binaryfunc)wrapped;
4261 PyObject *other;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004262
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004263 if (!check_num_args(args, 1))
4264 return NULL;
4265 other = PyTuple_GET_ITEM(args, 0);
4266 return (*func)(self, other);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004267}
4268
4269static PyObject *
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00004270wrap_binaryfunc_l(PyObject *self, PyObject *args, void *wrapped)
4271{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004272 binaryfunc func = (binaryfunc)wrapped;
4273 PyObject *other;
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00004274
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004275 if (!check_num_args(args, 1))
4276 return NULL;
4277 other = PyTuple_GET_ITEM(args, 0);
4278 return (*func)(self, other);
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00004279}
4280
4281static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00004282wrap_binaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
4283{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004284 binaryfunc func = (binaryfunc)wrapped;
4285 PyObject *other;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004286
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004287 if (!check_num_args(args, 1))
4288 return NULL;
4289 other = PyTuple_GET_ITEM(args, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004290 return (*func)(other, self);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004291}
4292
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004293static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00004294wrap_ternaryfunc(PyObject *self, PyObject *args, void *wrapped)
4295{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004296 ternaryfunc func = (ternaryfunc)wrapped;
4297 PyObject *other;
4298 PyObject *third = Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004299
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004300 /* Note: This wrapper only works for __pow__() */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004301
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004302 if (!PyArg_UnpackTuple(args, "", 1, 2, &other, &third))
4303 return NULL;
4304 return (*func)(self, other, third);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004305}
4306
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00004307static PyObject *
4308wrap_ternaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
4309{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004310 ternaryfunc func = (ternaryfunc)wrapped;
4311 PyObject *other;
4312 PyObject *third = Py_None;
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00004313
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004314 /* Note: This wrapper only works for __pow__() */
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00004315
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004316 if (!PyArg_UnpackTuple(args, "", 1, 2, &other, &third))
4317 return NULL;
4318 return (*func)(other, self, third);
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00004319}
4320
Tim Peters6d6c1a32001-08-02 04:15:00 +00004321static PyObject *
4322wrap_unaryfunc(PyObject *self, PyObject *args, void *wrapped)
4323{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004324 unaryfunc func = (unaryfunc)wrapped;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004325
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004326 if (!check_num_args(args, 0))
4327 return NULL;
4328 return (*func)(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004329}
4330
Tim Peters6d6c1a32001-08-02 04:15:00 +00004331static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004332wrap_indexargfunc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004333{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004334 ssizeargfunc func = (ssizeargfunc)wrapped;
4335 PyObject* o;
4336 Py_ssize_t i;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004337
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004338 if (!PyArg_UnpackTuple(args, "", 1, 1, &o))
4339 return NULL;
4340 i = PyNumber_AsSsize_t(o, PyExc_OverflowError);
4341 if (i == -1 && PyErr_Occurred())
4342 return NULL;
4343 return (*func)(self, i);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004344}
4345
Martin v. Löwis18e16552006-02-15 17:27:45 +00004346static Py_ssize_t
Guido van Rossum5d815f32001-08-17 21:57:47 +00004347getindex(PyObject *self, PyObject *arg)
4348{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004349 Py_ssize_t i;
Guido van Rossum5d815f32001-08-17 21:57:47 +00004350
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004351 i = PyNumber_AsSsize_t(arg, PyExc_OverflowError);
4352 if (i == -1 && PyErr_Occurred())
4353 return -1;
4354 if (i < 0) {
4355 PySequenceMethods *sq = Py_TYPE(self)->tp_as_sequence;
4356 if (sq && sq->sq_length) {
4357 Py_ssize_t n = (*sq->sq_length)(self);
4358 if (n < 0)
4359 return -1;
4360 i += n;
4361 }
4362 }
4363 return i;
Guido van Rossum5d815f32001-08-17 21:57:47 +00004364}
4365
4366static PyObject *
4367wrap_sq_item(PyObject *self, PyObject *args, void *wrapped)
4368{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004369 ssizeargfunc func = (ssizeargfunc)wrapped;
4370 PyObject *arg;
4371 Py_ssize_t i;
Guido van Rossum5d815f32001-08-17 21:57:47 +00004372
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004373 if (PyTuple_GET_SIZE(args) == 1) {
4374 arg = PyTuple_GET_ITEM(args, 0);
4375 i = getindex(self, arg);
4376 if (i == -1 && PyErr_Occurred())
4377 return NULL;
4378 return (*func)(self, i);
4379 }
4380 check_num_args(args, 1);
4381 assert(PyErr_Occurred());
4382 return NULL;
Guido van Rossum5d815f32001-08-17 21:57:47 +00004383}
4384
Tim Peters6d6c1a32001-08-02 04:15:00 +00004385static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00004386wrap_sq_setitem(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004387{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004388 ssizeobjargproc func = (ssizeobjargproc)wrapped;
4389 Py_ssize_t i;
4390 int res;
4391 PyObject *arg, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004392
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004393 if (!PyArg_UnpackTuple(args, "", 2, 2, &arg, &value))
4394 return NULL;
4395 i = getindex(self, arg);
4396 if (i == -1 && PyErr_Occurred())
4397 return NULL;
4398 res = (*func)(self, i, value);
4399 if (res == -1 && PyErr_Occurred())
4400 return NULL;
4401 Py_INCREF(Py_None);
4402 return Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004403}
4404
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004405static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00004406wrap_sq_delitem(PyObject *self, PyObject *args, void *wrapped)
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004407{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004408 ssizeobjargproc func = (ssizeobjargproc)wrapped;
4409 Py_ssize_t i;
4410 int res;
4411 PyObject *arg;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004412
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004413 if (!check_num_args(args, 1))
4414 return NULL;
4415 arg = PyTuple_GET_ITEM(args, 0);
4416 i = getindex(self, arg);
4417 if (i == -1 && PyErr_Occurred())
4418 return NULL;
4419 res = (*func)(self, i, NULL);
4420 if (res == -1 && PyErr_Occurred())
4421 return NULL;
4422 Py_INCREF(Py_None);
4423 return Py_None;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004424}
4425
Tim Peters6d6c1a32001-08-02 04:15:00 +00004426/* XXX objobjproc is a misnomer; should be objargpred */
4427static PyObject *
4428wrap_objobjproc(PyObject *self, PyObject *args, void *wrapped)
4429{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004430 objobjproc func = (objobjproc)wrapped;
4431 int res;
4432 PyObject *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004433
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004434 if (!check_num_args(args, 1))
4435 return NULL;
4436 value = PyTuple_GET_ITEM(args, 0);
4437 res = (*func)(self, value);
4438 if (res == -1 && PyErr_Occurred())
4439 return NULL;
4440 else
4441 return PyBool_FromLong(res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004442}
4443
Tim Peters6d6c1a32001-08-02 04:15:00 +00004444static PyObject *
4445wrap_objobjargproc(PyObject *self, PyObject *args, void *wrapped)
4446{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004447 objobjargproc func = (objobjargproc)wrapped;
4448 int res;
4449 PyObject *key, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004450
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004451 if (!PyArg_UnpackTuple(args, "", 2, 2, &key, &value))
4452 return NULL;
4453 res = (*func)(self, key, value);
4454 if (res == -1 && PyErr_Occurred())
4455 return NULL;
4456 Py_INCREF(Py_None);
4457 return Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004458}
4459
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004460static PyObject *
4461wrap_delitem(PyObject *self, PyObject *args, void *wrapped)
4462{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004463 objobjargproc func = (objobjargproc)wrapped;
4464 int res;
4465 PyObject *key;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004466
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004467 if (!check_num_args(args, 1))
4468 return NULL;
4469 key = PyTuple_GET_ITEM(args, 0);
4470 res = (*func)(self, key, NULL);
4471 if (res == -1 && PyErr_Occurred())
4472 return NULL;
4473 Py_INCREF(Py_None);
4474 return Py_None;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004475}
4476
Guido van Rossum4dcdb782003-04-14 21:46:03 +00004477/* Helper to check for object.__setattr__ or __delattr__ applied to a type.
Guido van Rossum52b27052003-04-15 20:05:10 +00004478 This is called the Carlo Verre hack after its discoverer. */
Guido van Rossum4dcdb782003-04-14 21:46:03 +00004479static int
4480hackcheck(PyObject *self, setattrofunc func, char *what)
4481{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004482 PyTypeObject *type = Py_TYPE(self);
4483 while (type && type->tp_flags & Py_TPFLAGS_HEAPTYPE)
4484 type = type->tp_base;
4485 /* If type is NULL now, this is a really weird type.
4486 In the spirit of backwards compatibility (?), just shut up. */
4487 if (type && type->tp_setattro != func) {
4488 PyErr_Format(PyExc_TypeError,
4489 "can't apply this %s to %s object",
4490 what,
4491 type->tp_name);
4492 return 0;
4493 }
4494 return 1;
Guido van Rossum4dcdb782003-04-14 21:46:03 +00004495}
4496
Tim Peters6d6c1a32001-08-02 04:15:00 +00004497static PyObject *
4498wrap_setattr(PyObject *self, PyObject *args, void *wrapped)
4499{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004500 setattrofunc func = (setattrofunc)wrapped;
4501 int res;
4502 PyObject *name, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004503
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004504 if (!PyArg_UnpackTuple(args, "", 2, 2, &name, &value))
4505 return NULL;
4506 if (!hackcheck(self, func, "__setattr__"))
4507 return NULL;
4508 res = (*func)(self, name, value);
4509 if (res < 0)
4510 return NULL;
4511 Py_INCREF(Py_None);
4512 return Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004513}
4514
4515static PyObject *
4516wrap_delattr(PyObject *self, PyObject *args, void *wrapped)
4517{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004518 setattrofunc func = (setattrofunc)wrapped;
4519 int res;
4520 PyObject *name;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004521
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004522 if (!check_num_args(args, 1))
4523 return NULL;
4524 name = PyTuple_GET_ITEM(args, 0);
4525 if (!hackcheck(self, func, "__delattr__"))
4526 return NULL;
4527 res = (*func)(self, name, NULL);
4528 if (res < 0)
4529 return NULL;
4530 Py_INCREF(Py_None);
4531 return Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004532}
4533
Tim Peters6d6c1a32001-08-02 04:15:00 +00004534static PyObject *
4535wrap_hashfunc(PyObject *self, PyObject *args, void *wrapped)
4536{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004537 hashfunc func = (hashfunc)wrapped;
Benjamin Peterson8035bc52010-10-23 16:20:50 +00004538 Py_hash_t res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004539
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004540 if (!check_num_args(args, 0))
4541 return NULL;
4542 res = (*func)(self);
4543 if (res == -1 && PyErr_Occurred())
4544 return NULL;
Benjamin Peterson8035bc52010-10-23 16:20:50 +00004545 return PyLong_FromSsize_t(res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004546}
4547
Tim Peters6d6c1a32001-08-02 04:15:00 +00004548static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00004549wrap_call(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004550{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004551 ternaryfunc func = (ternaryfunc)wrapped;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004552
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004553 return (*func)(self, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004554}
4555
Tim Peters6d6c1a32001-08-02 04:15:00 +00004556static PyObject *
4557wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op)
4558{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004559 richcmpfunc func = (richcmpfunc)wrapped;
4560 PyObject *other;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004561
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004562 if (!check_num_args(args, 1))
4563 return NULL;
4564 other = PyTuple_GET_ITEM(args, 0);
4565 return (*func)(self, other, op);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004566}
4567
4568#undef RICHCMP_WRAPPER
4569#define RICHCMP_WRAPPER(NAME, OP) \
4570static PyObject * \
4571richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \
4572{ \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004573 return wrap_richcmpfunc(self, args, wrapped, OP); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004574}
4575
Jack Jansen8e938b42001-08-08 15:29:49 +00004576RICHCMP_WRAPPER(lt, Py_LT)
4577RICHCMP_WRAPPER(le, Py_LE)
4578RICHCMP_WRAPPER(eq, Py_EQ)
4579RICHCMP_WRAPPER(ne, Py_NE)
4580RICHCMP_WRAPPER(gt, Py_GT)
4581RICHCMP_WRAPPER(ge, Py_GE)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004582
Tim Peters6d6c1a32001-08-02 04:15:00 +00004583static PyObject *
4584wrap_next(PyObject *self, PyObject *args, void *wrapped)
4585{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004586 unaryfunc func = (unaryfunc)wrapped;
4587 PyObject *res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004588
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004589 if (!check_num_args(args, 0))
4590 return NULL;
4591 res = (*func)(self);
4592 if (res == NULL && !PyErr_Occurred())
4593 PyErr_SetNone(PyExc_StopIteration);
4594 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004595}
4596
Tim Peters6d6c1a32001-08-02 04:15:00 +00004597static PyObject *
4598wrap_descr_get(PyObject *self, PyObject *args, void *wrapped)
4599{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004600 descrgetfunc func = (descrgetfunc)wrapped;
4601 PyObject *obj;
4602 PyObject *type = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004603
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004604 if (!PyArg_UnpackTuple(args, "", 1, 2, &obj, &type))
4605 return NULL;
4606 if (obj == Py_None)
4607 obj = NULL;
4608 if (type == Py_None)
4609 type = NULL;
4610 if (type == NULL &&obj == NULL) {
4611 PyErr_SetString(PyExc_TypeError,
4612 "__get__(None, None) is invalid");
4613 return NULL;
4614 }
4615 return (*func)(self, obj, type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004616}
4617
Tim Peters6d6c1a32001-08-02 04:15:00 +00004618static PyObject *
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004619wrap_descr_set(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004620{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004621 descrsetfunc func = (descrsetfunc)wrapped;
4622 PyObject *obj, *value;
4623 int ret;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004624
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004625 if (!PyArg_UnpackTuple(args, "", 2, 2, &obj, &value))
4626 return NULL;
4627 ret = (*func)(self, obj, value);
4628 if (ret < 0)
4629 return NULL;
4630 Py_INCREF(Py_None);
4631 return Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004632}
Guido van Rossum22b13872002-08-06 21:41:44 +00004633
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00004634static PyObject *
4635wrap_descr_delete(PyObject *self, PyObject *args, void *wrapped)
4636{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004637 descrsetfunc func = (descrsetfunc)wrapped;
4638 PyObject *obj;
4639 int ret;
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00004640
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004641 if (!check_num_args(args, 1))
4642 return NULL;
4643 obj = PyTuple_GET_ITEM(args, 0);
4644 ret = (*func)(self, obj, NULL);
4645 if (ret < 0)
4646 return NULL;
4647 Py_INCREF(Py_None);
4648 return Py_None;
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00004649}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004650
Tim Peters6d6c1a32001-08-02 04:15:00 +00004651static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00004652wrap_init(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004653{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004654 initproc func = (initproc)wrapped;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004655
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004656 if (func(self, args, kwds) < 0)
4657 return NULL;
4658 Py_INCREF(Py_None);
4659 return Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004660}
4661
Tim Peters6d6c1a32001-08-02 04:15:00 +00004662static PyObject *
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004663tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004664{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004665 PyTypeObject *type, *subtype, *staticbase;
4666 PyObject *arg0, *res;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004667
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004668 if (self == NULL || !PyType_Check(self))
4669 Py_FatalError("__new__() called with non-type 'self'");
4670 type = (PyTypeObject *)self;
4671 if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) {
4672 PyErr_Format(PyExc_TypeError,
4673 "%s.__new__(): not enough arguments",
4674 type->tp_name);
4675 return NULL;
4676 }
4677 arg0 = PyTuple_GET_ITEM(args, 0);
4678 if (!PyType_Check(arg0)) {
4679 PyErr_Format(PyExc_TypeError,
4680 "%s.__new__(X): X is not a type object (%s)",
4681 type->tp_name,
4682 Py_TYPE(arg0)->tp_name);
4683 return NULL;
4684 }
4685 subtype = (PyTypeObject *)arg0;
4686 if (!PyType_IsSubtype(subtype, type)) {
4687 PyErr_Format(PyExc_TypeError,
4688 "%s.__new__(%s): %s is not a subtype of %s",
4689 type->tp_name,
4690 subtype->tp_name,
4691 subtype->tp_name,
4692 type->tp_name);
4693 return NULL;
4694 }
Barry Warsaw60f01882001-08-22 19:24:42 +00004695
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004696 /* Check that the use doesn't do something silly and unsafe like
4697 object.__new__(dict). To do this, we check that the
4698 most derived base that's not a heap type is this type. */
4699 staticbase = subtype;
4700 while (staticbase && (staticbase->tp_flags & Py_TPFLAGS_HEAPTYPE))
4701 staticbase = staticbase->tp_base;
4702 /* If staticbase is NULL now, it is a really weird type.
4703 In the spirit of backwards compatibility (?), just shut up. */
4704 if (staticbase && staticbase->tp_new != type->tp_new) {
4705 PyErr_Format(PyExc_TypeError,
4706 "%s.__new__(%s) is not safe, use %s.__new__()",
4707 type->tp_name,
4708 subtype->tp_name,
4709 staticbase == NULL ? "?" : staticbase->tp_name);
4710 return NULL;
4711 }
Barry Warsaw60f01882001-08-22 19:24:42 +00004712
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004713 args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
4714 if (args == NULL)
4715 return NULL;
4716 res = type->tp_new(subtype, args, kwds);
4717 Py_DECREF(args);
4718 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004719}
4720
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004721static struct PyMethodDef tp_new_methoddef[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004722 {"__new__", (PyCFunction)tp_new_wrapper, METH_VARARGS|METH_KEYWORDS,
4723 PyDoc_STR("T.__new__(S, ...) -> "
4724 "a new object with type S, a subtype of T")},
4725 {0}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004726};
4727
4728static int
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004729add_tp_new_wrapper(PyTypeObject *type)
4730{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004731 PyObject *func;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004732
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004733 if (PyDict_GetItemString(type->tp_dict, "__new__") != NULL)
4734 return 0;
4735 func = PyCFunction_New(tp_new_methoddef, (PyObject *)type);
4736 if (func == NULL)
4737 return -1;
4738 if (PyDict_SetItemString(type->tp_dict, "__new__", func)) {
4739 Py_DECREF(func);
4740 return -1;
4741 }
4742 Py_DECREF(func);
4743 return 0;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004744}
4745
Guido van Rossumf040ede2001-08-07 16:40:56 +00004746/* Slot wrappers that call the corresponding __foo__ slot. See comments
4747 below at override_slots() for more explanation. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004748
Guido van Rossumdc91b992001-08-08 22:26:22 +00004749#define SLOT0(FUNCNAME, OPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004750static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004751FUNCNAME(PyObject *self) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004752{ \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004753 static PyObject *cache_str; \
4754 return call_method(self, OPSTR, &cache_str, "()"); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004755}
4756
Guido van Rossumdc91b992001-08-08 22:26:22 +00004757#define SLOT1(FUNCNAME, OPSTR, ARG1TYPE, ARGCODES) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004758static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004759FUNCNAME(PyObject *self, ARG1TYPE arg1) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004760{ \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004761 static PyObject *cache_str; \
4762 return call_method(self, OPSTR, &cache_str, "(" ARGCODES ")", arg1); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004763}
4764
Guido van Rossumcd118802003-01-06 22:57:47 +00004765/* Boolean helper for SLOT1BINFULL().
4766 right.__class__ is a nontrivial subclass of left.__class__. */
4767static int
4768method_is_overloaded(PyObject *left, PyObject *right, char *name)
4769{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004770 PyObject *a, *b;
4771 int ok;
Guido van Rossumcd118802003-01-06 22:57:47 +00004772
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004773 b = PyObject_GetAttrString((PyObject *)(Py_TYPE(right)), name);
4774 if (b == NULL) {
4775 PyErr_Clear();
4776 /* If right doesn't have it, it's not overloaded */
4777 return 0;
4778 }
Guido van Rossumcd118802003-01-06 22:57:47 +00004779
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004780 a = PyObject_GetAttrString((PyObject *)(Py_TYPE(left)), name);
4781 if (a == NULL) {
4782 PyErr_Clear();
4783 Py_DECREF(b);
4784 /* If right has it but left doesn't, it's overloaded */
4785 return 1;
4786 }
Guido van Rossumcd118802003-01-06 22:57:47 +00004787
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004788 ok = PyObject_RichCompareBool(a, b, Py_NE);
4789 Py_DECREF(a);
4790 Py_DECREF(b);
4791 if (ok < 0) {
4792 PyErr_Clear();
4793 return 0;
4794 }
Guido van Rossumcd118802003-01-06 22:57:47 +00004795
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004796 return ok;
Guido van Rossumcd118802003-01-06 22:57:47 +00004797}
4798
Guido van Rossumdc91b992001-08-08 22:26:22 +00004799
4800#define SLOT1BINFULL(FUNCNAME, TESTFUNC, SLOTNAME, OPSTR, ROPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004801static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004802FUNCNAME(PyObject *self, PyObject *other) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004803{ \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004804 static PyObject *cache_str, *rcache_str; \
4805 int do_other = Py_TYPE(self) != Py_TYPE(other) && \
4806 Py_TYPE(other)->tp_as_number != NULL && \
4807 Py_TYPE(other)->tp_as_number->SLOTNAME == TESTFUNC; \
4808 if (Py_TYPE(self)->tp_as_number != NULL && \
4809 Py_TYPE(self)->tp_as_number->SLOTNAME == TESTFUNC) { \
4810 PyObject *r; \
4811 if (do_other && \
4812 PyType_IsSubtype(Py_TYPE(other), Py_TYPE(self)) && \
4813 method_is_overloaded(self, other, ROPSTR)) { \
4814 r = call_maybe( \
4815 other, ROPSTR, &rcache_str, "(O)", self); \
4816 if (r != Py_NotImplemented) \
4817 return r; \
4818 Py_DECREF(r); \
4819 do_other = 0; \
4820 } \
4821 r = call_maybe( \
4822 self, OPSTR, &cache_str, "(O)", other); \
4823 if (r != Py_NotImplemented || \
4824 Py_TYPE(other) == Py_TYPE(self)) \
4825 return r; \
4826 Py_DECREF(r); \
4827 } \
4828 if (do_other) { \
4829 return call_maybe( \
4830 other, ROPSTR, &rcache_str, "(O)", self); \
4831 } \
Brian Curtindfc80e32011-08-10 20:28:54 -05004832 Py_RETURN_NOTIMPLEMENTED; \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004833}
4834
4835#define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004836 SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR)
Guido van Rossumdc91b992001-08-08 22:26:22 +00004837
4838#define SLOT2(FUNCNAME, OPSTR, ARG1TYPE, ARG2TYPE, ARGCODES) \
4839static PyObject * \
4840FUNCNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \
4841{ \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004842 static PyObject *cache_str; \
4843 return call_method(self, OPSTR, &cache_str, \
4844 "(" ARGCODES ")", arg1, arg2); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004845}
4846
Martin v. Löwis18e16552006-02-15 17:27:45 +00004847static Py_ssize_t
Tim Peters6d6c1a32001-08-02 04:15:00 +00004848slot_sq_length(PyObject *self)
4849{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004850 static PyObject *len_str;
4851 PyObject *res = call_method(self, "__len__", &len_str, "()");
4852 Py_ssize_t len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004853
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004854 if (res == NULL)
4855 return -1;
4856 len = PyNumber_AsSsize_t(res, PyExc_OverflowError);
4857 Py_DECREF(res);
4858 if (len < 0) {
4859 if (!PyErr_Occurred())
4860 PyErr_SetString(PyExc_ValueError,
4861 "__len__() should return >= 0");
4862 return -1;
4863 }
4864 return len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004865}
4866
Guido van Rossumf4593e02001-10-03 12:09:30 +00004867/* Super-optimized version of slot_sq_item.
4868 Other slots could do the same... */
4869static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00004870slot_sq_item(PyObject *self, Py_ssize_t i)
Guido van Rossumf4593e02001-10-03 12:09:30 +00004871{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004872 static PyObject *getitem_str;
4873 PyObject *func, *args = NULL, *ival = NULL, *retval = NULL;
4874 descrgetfunc f;
Guido van Rossumf4593e02001-10-03 12:09:30 +00004875
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004876 if (getitem_str == NULL) {
4877 getitem_str = PyUnicode_InternFromString("__getitem__");
4878 if (getitem_str == NULL)
4879 return NULL;
4880 }
4881 func = _PyType_Lookup(Py_TYPE(self), getitem_str);
4882 if (func != NULL) {
4883 if ((f = Py_TYPE(func)->tp_descr_get) == NULL)
4884 Py_INCREF(func);
4885 else {
4886 func = f(func, self, (PyObject *)(Py_TYPE(self)));
4887 if (func == NULL) {
4888 return NULL;
4889 }
4890 }
4891 ival = PyLong_FromSsize_t(i);
4892 if (ival != NULL) {
4893 args = PyTuple_New(1);
4894 if (args != NULL) {
4895 PyTuple_SET_ITEM(args, 0, ival);
4896 retval = PyObject_Call(func, args, NULL);
4897 Py_XDECREF(args);
4898 Py_XDECREF(func);
4899 return retval;
4900 }
4901 }
4902 }
4903 else {
4904 PyErr_SetObject(PyExc_AttributeError, getitem_str);
4905 }
4906 Py_XDECREF(args);
4907 Py_XDECREF(ival);
4908 Py_XDECREF(func);
4909 return NULL;
Guido van Rossumf4593e02001-10-03 12:09:30 +00004910}
4911
Tim Peters6d6c1a32001-08-02 04:15:00 +00004912static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00004913slot_sq_ass_item(PyObject *self, Py_ssize_t index, PyObject *value)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004914{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004915 PyObject *res;
4916 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004917
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004918 if (value == NULL)
4919 res = call_method(self, "__delitem__", &delitem_str,
4920 "(n)", index);
4921 else
4922 res = call_method(self, "__setitem__", &setitem_str,
4923 "(nO)", index, value);
4924 if (res == NULL)
4925 return -1;
4926 Py_DECREF(res);
4927 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004928}
4929
4930static int
Tim Peters6d6c1a32001-08-02 04:15:00 +00004931slot_sq_contains(PyObject *self, PyObject *value)
4932{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004933 PyObject *func, *res, *args;
4934 int result = -1;
Tim Petersbf9b2442003-03-23 05:35:36 +00004935
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004936 static PyObject *contains_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004937
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004938 func = lookup_maybe(self, "__contains__", &contains_str);
4939 if (func != NULL) {
4940 args = PyTuple_Pack(1, value);
4941 if (args == NULL)
4942 res = NULL;
4943 else {
4944 res = PyObject_Call(func, args, NULL);
4945 Py_DECREF(args);
4946 }
4947 Py_DECREF(func);
4948 if (res != NULL) {
4949 result = PyObject_IsTrue(res);
4950 Py_DECREF(res);
4951 }
4952 }
4953 else if (! PyErr_Occurred()) {
4954 /* Possible results: -1 and 1 */
4955 result = (int)_PySequence_IterSearch(self, value,
4956 PY_ITERSEARCH_CONTAINS);
4957 }
4958 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004959}
4960
Tim Peters6d6c1a32001-08-02 04:15:00 +00004961#define slot_mp_length slot_sq_length
4962
Guido van Rossumdc91b992001-08-08 22:26:22 +00004963SLOT1(slot_mp_subscript, "__getitem__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004964
4965static int
4966slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value)
4967{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004968 PyObject *res;
4969 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004970
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004971 if (value == NULL)
4972 res = call_method(self, "__delitem__", &delitem_str,
4973 "(O)", key);
4974 else
4975 res = call_method(self, "__setitem__", &setitem_str,
4976 "(OO)", key, value);
4977 if (res == NULL)
4978 return -1;
4979 Py_DECREF(res);
4980 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004981}
4982
Guido van Rossumdc91b992001-08-08 22:26:22 +00004983SLOT1BIN(slot_nb_add, nb_add, "__add__", "__radd__")
4984SLOT1BIN(slot_nb_subtract, nb_subtract, "__sub__", "__rsub__")
4985SLOT1BIN(slot_nb_multiply, nb_multiply, "__mul__", "__rmul__")
Guido van Rossumdc91b992001-08-08 22:26:22 +00004986SLOT1BIN(slot_nb_remainder, nb_remainder, "__mod__", "__rmod__")
4987SLOT1BIN(slot_nb_divmod, nb_divmod, "__divmod__", "__rdivmod__")
4988
Jeremy Hylton938ace62002-07-17 16:30:39 +00004989static PyObject *slot_nb_power(PyObject *, PyObject *, PyObject *);
Guido van Rossumdc91b992001-08-08 22:26:22 +00004990
4991SLOT1BINFULL(slot_nb_power_binary, slot_nb_power,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004992 nb_power, "__pow__", "__rpow__")
Guido van Rossumdc91b992001-08-08 22:26:22 +00004993
4994static PyObject *
4995slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus)
4996{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004997 static PyObject *pow_str;
Guido van Rossum2730b132001-08-28 18:22:14 +00004998
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004999 if (modulus == Py_None)
5000 return slot_nb_power_binary(self, other);
5001 /* Three-arg power doesn't use __rpow__. But ternary_op
5002 can call this when the second argument's type uses
5003 slot_nb_power, so check before calling self.__pow__. */
5004 if (Py_TYPE(self)->tp_as_number != NULL &&
5005 Py_TYPE(self)->tp_as_number->nb_power == slot_nb_power) {
5006 return call_method(self, "__pow__", &pow_str,
5007 "(OO)", other, modulus);
5008 }
Brian Curtindfc80e32011-08-10 20:28:54 -05005009 Py_RETURN_NOTIMPLEMENTED;
Guido van Rossumdc91b992001-08-08 22:26:22 +00005010}
5011
5012SLOT0(slot_nb_negative, "__neg__")
5013SLOT0(slot_nb_positive, "__pos__")
5014SLOT0(slot_nb_absolute, "__abs__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00005015
5016static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00005017slot_nb_bool(PyObject *self)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005018{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005019 PyObject *func, *args;
5020 static PyObject *bool_str, *len_str;
5021 int result = -1;
5022 int using_len = 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005023
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005024 func = lookup_maybe(self, "__bool__", &bool_str);
5025 if (func == NULL) {
5026 if (PyErr_Occurred())
5027 return -1;
5028 func = lookup_maybe(self, "__len__", &len_str);
5029 if (func == NULL)
5030 return PyErr_Occurred() ? -1 : 1;
5031 using_len = 1;
5032 }
5033 args = PyTuple_New(0);
5034 if (args != NULL) {
5035 PyObject *temp = PyObject_Call(func, args, NULL);
5036 Py_DECREF(args);
5037 if (temp != NULL) {
5038 if (using_len) {
5039 /* enforced by slot_nb_len */
5040 result = PyObject_IsTrue(temp);
5041 }
5042 else if (PyBool_Check(temp)) {
5043 result = PyObject_IsTrue(temp);
5044 }
5045 else {
5046 PyErr_Format(PyExc_TypeError,
5047 "__bool__ should return "
5048 "bool, returned %s",
5049 Py_TYPE(temp)->tp_name);
5050 result = -1;
5051 }
5052 Py_DECREF(temp);
5053 }
5054 }
5055 Py_DECREF(func);
5056 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005057}
5058
Guido van Rossum38fff8c2006-03-07 18:50:55 +00005059
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00005060static PyObject *
Guido van Rossum38fff8c2006-03-07 18:50:55 +00005061slot_nb_index(PyObject *self)
5062{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005063 static PyObject *index_str;
5064 return call_method(self, "__index__", &index_str, "()");
Guido van Rossum38fff8c2006-03-07 18:50:55 +00005065}
5066
5067
Guido van Rossumdc91b992001-08-08 22:26:22 +00005068SLOT0(slot_nb_invert, "__invert__")
5069SLOT1BIN(slot_nb_lshift, nb_lshift, "__lshift__", "__rlshift__")
5070SLOT1BIN(slot_nb_rshift, nb_rshift, "__rshift__", "__rrshift__")
5071SLOT1BIN(slot_nb_and, nb_and, "__and__", "__rand__")
5072SLOT1BIN(slot_nb_xor, nb_xor, "__xor__", "__rxor__")
5073SLOT1BIN(slot_nb_or, nb_or, "__or__", "__ror__")
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00005074
Guido van Rossumdc91b992001-08-08 22:26:22 +00005075SLOT0(slot_nb_int, "__int__")
Guido van Rossumdc91b992001-08-08 22:26:22 +00005076SLOT0(slot_nb_float, "__float__")
Guido van Rossumdc91b992001-08-08 22:26:22 +00005077SLOT1(slot_nb_inplace_add, "__iadd__", PyObject *, "O")
5078SLOT1(slot_nb_inplace_subtract, "__isub__", PyObject *, "O")
5079SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *, "O")
Guido van Rossumdc91b992001-08-08 22:26:22 +00005080SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *, "O")
Thomas Wouterscf297e42007-02-23 15:07:44 +00005081/* Can't use SLOT1 here, because nb_inplace_power is ternary */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005082static PyObject *
5083slot_nb_inplace_power(PyObject *self, PyObject * arg1, PyObject *arg2)
5084{
5085 static PyObject *cache_str;
5086 return call_method(self, "__ipow__", &cache_str, "(" "O" ")", arg1);
Thomas Wouterscf297e42007-02-23 15:07:44 +00005087}
Guido van Rossumdc91b992001-08-08 22:26:22 +00005088SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *, "O")
5089SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *, "O")
5090SLOT1(slot_nb_inplace_and, "__iand__", PyObject *, "O")
5091SLOT1(slot_nb_inplace_xor, "__ixor__", PyObject *, "O")
5092SLOT1(slot_nb_inplace_or, "__ior__", PyObject *, "O")
5093SLOT1BIN(slot_nb_floor_divide, nb_floor_divide,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005094 "__floordiv__", "__rfloordiv__")
Guido van Rossumdc91b992001-08-08 22:26:22 +00005095SLOT1BIN(slot_nb_true_divide, nb_true_divide, "__truediv__", "__rtruediv__")
5096SLOT1(slot_nb_inplace_floor_divide, "__ifloordiv__", PyObject *, "O")
5097SLOT1(slot_nb_inplace_true_divide, "__itruediv__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00005098
Guido van Rossumb8f63662001-08-15 23:57:02 +00005099static PyObject *
5100slot_tp_repr(PyObject *self)
5101{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005102 PyObject *func, *res;
5103 static PyObject *repr_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00005104
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005105 func = lookup_method(self, "__repr__", &repr_str);
5106 if (func != NULL) {
5107 res = PyEval_CallObject(func, NULL);
5108 Py_DECREF(func);
5109 return res;
5110 }
5111 PyErr_Clear();
5112 return PyUnicode_FromFormat("<%s object at %p>",
5113 Py_TYPE(self)->tp_name, self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005114}
5115
5116static PyObject *
5117slot_tp_str(PyObject *self)
5118{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005119 PyObject *func, *res;
5120 static PyObject *str_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00005121
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005122 func = lookup_method(self, "__str__", &str_str);
5123 if (func != NULL) {
5124 res = PyEval_CallObject(func, NULL);
5125 Py_DECREF(func);
5126 return res;
5127 }
5128 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005129 /* PyObject *ress; */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005130 PyErr_Clear();
5131 res = slot_tp_repr(self);
5132 if (!res)
5133 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005134 /* XXX this is non-sensical. Why should we return
5135 a bytes object from __str__. Is this code even
5136 used? - mvl */
5137 assert(0);
5138 return res;
5139 /*
Victor Stinnerf3fd7332011-03-02 01:03:11 +00005140 ress = _PyUnicode_AsDefaultEncodedString(res);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005141 Py_DECREF(res);
5142 return ress;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005143 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005144 }
Guido van Rossumb8f63662001-08-15 23:57:02 +00005145}
Tim Peters6d6c1a32001-08-02 04:15:00 +00005146
Benjamin Peterson8f67d082010-10-17 20:54:53 +00005147static Py_hash_t
Tim Peters6d6c1a32001-08-02 04:15:00 +00005148slot_tp_hash(PyObject *self)
5149{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005150 PyObject *func, *res;
5151 static PyObject *hash_str;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00005152 Py_ssize_t h;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005153
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005154 func = lookup_method(self, "__hash__", &hash_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005155
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005156 if (func == Py_None) {
5157 Py_DECREF(func);
5158 func = NULL;
5159 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +00005160
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005161 if (func == NULL) {
5162 return PyObject_HashNotImplemented(self);
5163 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +00005164
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005165 res = PyEval_CallObject(func, NULL);
5166 Py_DECREF(func);
5167 if (res == NULL)
5168 return -1;
Mark Dickinsondc787d22010-05-23 13:33:13 +00005169
5170 if (!PyLong_Check(res)) {
5171 PyErr_SetString(PyExc_TypeError,
5172 "__hash__ method should return an integer");
5173 return -1;
5174 }
Benjamin Peterson8f67d082010-10-17 20:54:53 +00005175 /* Transform the PyLong `res` to a Py_hash_t `h`. For an existing
5176 hashable Python object x, hash(x) will always lie within the range of
5177 Py_hash_t. Therefore our transformation must preserve values that
5178 already lie within this range, to ensure that if x.__hash__() returns
5179 hash(y) then hash(x) == hash(y). */
5180 h = PyLong_AsSsize_t(res);
5181 if (h == -1 && PyErr_Occurred()) {
5182 /* res was not within the range of a Py_hash_t, so we're free to
Mark Dickinsondc787d22010-05-23 13:33:13 +00005183 use any sufficiently bit-mixing transformation;
5184 long.__hash__ will do nicely. */
Benjamin Peterson8f67d082010-10-17 20:54:53 +00005185 PyErr_Clear();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005186 h = PyLong_Type.tp_hash(res);
Benjamin Peterson8f67d082010-10-17 20:54:53 +00005187 }
Benjamin Petersone7dfeeb2010-10-17 21:27:01 +00005188 /* -1 is reserved for errors. */
5189 if (h == -1)
5190 h = -2;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005191 Py_DECREF(res);
Mark Dickinsondc787d22010-05-23 13:33:13 +00005192 return h;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005193}
5194
5195static PyObject *
5196slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds)
5197{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005198 static PyObject *call_str;
5199 PyObject *meth = lookup_method(self, "__call__", &call_str);
5200 PyObject *res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005201
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005202 if (meth == NULL)
5203 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005204
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005205 res = PyObject_Call(meth, args, kwds);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005206
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005207 Py_DECREF(meth);
5208 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005209}
5210
Guido van Rossum14a6f832001-10-17 13:59:09 +00005211/* There are two slot dispatch functions for tp_getattro.
5212
5213 - slot_tp_getattro() is used when __getattribute__ is overridden
5214 but no __getattr__ hook is present;
5215
5216 - slot_tp_getattr_hook() is used when a __getattr__ hook is present.
5217
Guido van Rossumc334df52002-04-04 23:44:47 +00005218 The code in update_one_slot() always installs slot_tp_getattr_hook(); this
5219 detects the absence of __getattr__ and then installs the simpler slot if
5220 necessary. */
Guido van Rossum14a6f832001-10-17 13:59:09 +00005221
Tim Peters6d6c1a32001-08-02 04:15:00 +00005222static PyObject *
5223slot_tp_getattro(PyObject *self, PyObject *name)
5224{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005225 static PyObject *getattribute_str = NULL;
5226 return call_method(self, "__getattribute__", &getattribute_str,
5227 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005228}
5229
Guido van Rossum19c1cd52001-09-21 21:24:49 +00005230static PyObject *
Benjamin Peterson9262b842008-11-17 22:45:50 +00005231call_attribute(PyObject *self, PyObject *attr, PyObject *name)
5232{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005233 PyObject *res, *descr = NULL;
5234 descrgetfunc f = Py_TYPE(attr)->tp_descr_get;
Benjamin Peterson9262b842008-11-17 22:45:50 +00005235
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005236 if (f != NULL) {
5237 descr = f(attr, self, (PyObject *)(Py_TYPE(self)));
5238 if (descr == NULL)
5239 return NULL;
5240 else
5241 attr = descr;
5242 }
5243 res = PyObject_CallFunctionObjArgs(attr, name, NULL);
5244 Py_XDECREF(descr);
5245 return res;
Benjamin Peterson9262b842008-11-17 22:45:50 +00005246}
5247
5248static PyObject *
Guido van Rossum19c1cd52001-09-21 21:24:49 +00005249slot_tp_getattr_hook(PyObject *self, PyObject *name)
5250{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005251 PyTypeObject *tp = Py_TYPE(self);
5252 PyObject *getattr, *getattribute, *res;
5253 static PyObject *getattribute_str = NULL;
5254 static PyObject *getattr_str = NULL;
Guido van Rossum19c1cd52001-09-21 21:24:49 +00005255
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005256 if (getattr_str == NULL) {
5257 getattr_str = PyUnicode_InternFromString("__getattr__");
5258 if (getattr_str == NULL)
5259 return NULL;
5260 }
5261 if (getattribute_str == NULL) {
5262 getattribute_str =
5263 PyUnicode_InternFromString("__getattribute__");
5264 if (getattribute_str == NULL)
5265 return NULL;
5266 }
5267 /* speed hack: we could use lookup_maybe, but that would resolve the
5268 method fully for each attribute lookup for classes with
5269 __getattr__, even when the attribute is present. So we use
5270 _PyType_Lookup and create the method only when needed, with
5271 call_attribute. */
5272 getattr = _PyType_Lookup(tp, getattr_str);
5273 if (getattr == NULL) {
5274 /* No __getattr__ hook: use a simpler dispatcher */
5275 tp->tp_getattro = slot_tp_getattro;
5276 return slot_tp_getattro(self, name);
5277 }
5278 Py_INCREF(getattr);
5279 /* speed hack: we could use lookup_maybe, but that would resolve the
5280 method fully for each attribute lookup for classes with
5281 __getattr__, even when self has the default __getattribute__
5282 method. So we use _PyType_Lookup and create the method only when
5283 needed, with call_attribute. */
5284 getattribute = _PyType_Lookup(tp, getattribute_str);
5285 if (getattribute == NULL ||
5286 (Py_TYPE(getattribute) == &PyWrapperDescr_Type &&
5287 ((PyWrapperDescrObject *)getattribute)->d_wrapped ==
5288 (void *)PyObject_GenericGetAttr))
5289 res = PyObject_GenericGetAttr(self, name);
5290 else {
5291 Py_INCREF(getattribute);
5292 res = call_attribute(self, getattribute, name);
5293 Py_DECREF(getattribute);
5294 }
5295 if (res == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) {
5296 PyErr_Clear();
5297 res = call_attribute(self, getattr, name);
5298 }
5299 Py_DECREF(getattr);
5300 return res;
Guido van Rossum19c1cd52001-09-21 21:24:49 +00005301}
5302
Tim Peters6d6c1a32001-08-02 04:15:00 +00005303static int
5304slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value)
5305{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005306 PyObject *res;
5307 static PyObject *delattr_str, *setattr_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005308
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005309 if (value == NULL)
5310 res = call_method(self, "__delattr__", &delattr_str,
5311 "(O)", name);
5312 else
5313 res = call_method(self, "__setattr__", &setattr_str,
5314 "(OO)", name, value);
5315 if (res == NULL)
5316 return -1;
5317 Py_DECREF(res);
5318 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005319}
5320
Guido van Rossumf5243f02008-01-01 04:06:48 +00005321static char *name_op[] = {
5322 "__lt__",
5323 "__le__",
5324 "__eq__",
5325 "__ne__",
5326 "__gt__",
5327 "__ge__",
5328};
5329
Tim Peters6d6c1a32001-08-02 04:15:00 +00005330static PyObject *
Mark Dickinson6f1d0492009-11-15 13:58:49 +00005331slot_tp_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005332{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005333 PyObject *func, *args, *res;
5334 static PyObject *op_str[6];
Tim Peters6d6c1a32001-08-02 04:15:00 +00005335
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005336 func = lookup_method(self, name_op[op], &op_str[op]);
5337 if (func == NULL) {
5338 PyErr_Clear();
Brian Curtindfc80e32011-08-10 20:28:54 -05005339 Py_RETURN_NOTIMPLEMENTED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005340 }
5341 args = PyTuple_Pack(1, other);
5342 if (args == NULL)
5343 res = NULL;
5344 else {
5345 res = PyObject_Call(func, args, NULL);
5346 Py_DECREF(args);
5347 }
5348 Py_DECREF(func);
5349 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005350}
5351
Guido van Rossumb8f63662001-08-15 23:57:02 +00005352static PyObject *
Guido van Rossumb8f63662001-08-15 23:57:02 +00005353slot_tp_iter(PyObject *self)
5354{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005355 PyObject *func, *res;
5356 static PyObject *iter_str, *getitem_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00005357
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005358 func = lookup_method(self, "__iter__", &iter_str);
5359 if (func != NULL) {
5360 PyObject *args;
5361 args = res = PyTuple_New(0);
5362 if (args != NULL) {
5363 res = PyObject_Call(func, args, NULL);
5364 Py_DECREF(args);
5365 }
5366 Py_DECREF(func);
5367 return res;
5368 }
5369 PyErr_Clear();
5370 func = lookup_method(self, "__getitem__", &getitem_str);
5371 if (func == NULL) {
5372 PyErr_Format(PyExc_TypeError,
5373 "'%.200s' object is not iterable",
5374 Py_TYPE(self)->tp_name);
5375 return NULL;
5376 }
5377 Py_DECREF(func);
5378 return PySeqIter_New(self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005379}
Tim Peters6d6c1a32001-08-02 04:15:00 +00005380
5381static PyObject *
5382slot_tp_iternext(PyObject *self)
5383{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005384 static PyObject *next_str;
5385 return call_method(self, "__next__", &next_str, "()");
Tim Peters6d6c1a32001-08-02 04:15:00 +00005386}
5387
Guido van Rossum1a493502001-08-17 16:47:50 +00005388static PyObject *
5389slot_tp_descr_get(PyObject *self, PyObject *obj, PyObject *type)
5390{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005391 PyTypeObject *tp = Py_TYPE(self);
5392 PyObject *get;
5393 static PyObject *get_str = NULL;
Guido van Rossum1a493502001-08-17 16:47:50 +00005394
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005395 if (get_str == NULL) {
5396 get_str = PyUnicode_InternFromString("__get__");
5397 if (get_str == NULL)
5398 return NULL;
5399 }
5400 get = _PyType_Lookup(tp, get_str);
5401 if (get == NULL) {
5402 /* Avoid further slowdowns */
5403 if (tp->tp_descr_get == slot_tp_descr_get)
5404 tp->tp_descr_get = NULL;
5405 Py_INCREF(self);
5406 return self;
5407 }
5408 if (obj == NULL)
5409 obj = Py_None;
5410 if (type == NULL)
5411 type = Py_None;
5412 return PyObject_CallFunctionObjArgs(get, self, obj, type, NULL);
Guido van Rossum1a493502001-08-17 16:47:50 +00005413}
Tim Peters6d6c1a32001-08-02 04:15:00 +00005414
5415static int
5416slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value)
5417{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005418 PyObject *res;
5419 static PyObject *del_str, *set_str;
Guido van Rossum2c252392001-08-24 10:13:31 +00005420
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005421 if (value == NULL)
5422 res = call_method(self, "__delete__", &del_str,
5423 "(O)", target);
5424 else
5425 res = call_method(self, "__set__", &set_str,
5426 "(OO)", target, value);
5427 if (res == NULL)
5428 return -1;
5429 Py_DECREF(res);
5430 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005431}
5432
5433static int
5434slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds)
5435{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005436 static PyObject *init_str;
5437 PyObject *meth = lookup_method(self, "__init__", &init_str);
5438 PyObject *res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005439
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005440 if (meth == NULL)
5441 return -1;
5442 res = PyObject_Call(meth, args, kwds);
5443 Py_DECREF(meth);
5444 if (res == NULL)
5445 return -1;
5446 if (res != Py_None) {
5447 PyErr_Format(PyExc_TypeError,
5448 "__init__() should return None, not '%.200s'",
5449 Py_TYPE(res)->tp_name);
5450 Py_DECREF(res);
5451 return -1;
5452 }
5453 Py_DECREF(res);
5454 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005455}
5456
5457static PyObject *
5458slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
5459{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005460 static PyObject *new_str;
5461 PyObject *func;
5462 PyObject *newargs, *x;
5463 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005464
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005465 if (new_str == NULL) {
5466 new_str = PyUnicode_InternFromString("__new__");
5467 if (new_str == NULL)
5468 return NULL;
5469 }
5470 func = PyObject_GetAttr((PyObject *)type, new_str);
5471 if (func == NULL)
5472 return NULL;
5473 assert(PyTuple_Check(args));
5474 n = PyTuple_GET_SIZE(args);
5475 newargs = PyTuple_New(n+1);
5476 if (newargs == NULL)
5477 return NULL;
5478 Py_INCREF(type);
5479 PyTuple_SET_ITEM(newargs, 0, (PyObject *)type);
5480 for (i = 0; i < n; i++) {
5481 x = PyTuple_GET_ITEM(args, i);
5482 Py_INCREF(x);
5483 PyTuple_SET_ITEM(newargs, i+1, x);
5484 }
5485 x = PyObject_Call(func, newargs, kwds);
5486 Py_DECREF(newargs);
5487 Py_DECREF(func);
5488 return x;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005489}
5490
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005491static void
5492slot_tp_del(PyObject *self)
5493{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005494 static PyObject *del_str = NULL;
5495 PyObject *del, *res;
5496 PyObject *error_type, *error_value, *error_traceback;
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005497
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005498 /* Temporarily resurrect the object. */
5499 assert(self->ob_refcnt == 0);
5500 self->ob_refcnt = 1;
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005501
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005502 /* Save the current exception, if any. */
5503 PyErr_Fetch(&error_type, &error_value, &error_traceback);
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005504
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005505 /* Execute __del__ method, if any. */
5506 del = lookup_maybe(self, "__del__", &del_str);
5507 if (del != NULL) {
5508 res = PyEval_CallObject(del, NULL);
5509 if (res == NULL)
5510 PyErr_WriteUnraisable(del);
5511 else
5512 Py_DECREF(res);
5513 Py_DECREF(del);
5514 }
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005515
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005516 /* Restore the saved exception. */
5517 PyErr_Restore(error_type, error_value, error_traceback);
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005518
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005519 /* Undo the temporary resurrection; can't use DECREF here, it would
5520 * cause a recursive call.
5521 */
5522 assert(self->ob_refcnt > 0);
5523 if (--self->ob_refcnt == 0)
5524 return; /* this is the normal path out */
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005525
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005526 /* __del__ resurrected it! Make it look like the original Py_DECREF
5527 * never happened.
5528 */
5529 {
5530 Py_ssize_t refcnt = self->ob_refcnt;
5531 _Py_NewReference(self);
5532 self->ob_refcnt = refcnt;
5533 }
5534 assert(!PyType_IS_GC(Py_TYPE(self)) ||
5535 _Py_AS_GC(self)->gc.gc_refs != _PyGC_REFS_UNTRACKED);
5536 /* If Py_REF_DEBUG, _Py_NewReference bumped _Py_RefTotal, so
5537 * we need to undo that. */
5538 _Py_DEC_REFTOTAL;
5539 /* If Py_TRACE_REFS, _Py_NewReference re-added self to the object
5540 * chain, so no more to do there.
5541 * If COUNT_ALLOCS, the original decref bumped tp_frees, and
5542 * _Py_NewReference bumped tp_allocs: both of those need to be
5543 * undone.
5544 */
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005545#ifdef COUNT_ALLOCS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005546 --Py_TYPE(self)->tp_frees;
5547 --Py_TYPE(self)->tp_allocs;
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005548#endif
5549}
5550
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005551
5552/* Table mapping __foo__ names to tp_foo offsets and slot_tp_foo wrapper
Tim Petersbf9b2442003-03-23 05:35:36 +00005553 functions. The offsets here are relative to the 'PyHeapTypeObject'
Guido van Rossume5c691a2003-03-07 15:13:17 +00005554 structure, which incorporates the additional structures used for numbers,
5555 sequences and mappings.
5556 Note that multiple names may map to the same slot (e.g. __eq__,
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005557 __ne__ etc. all map to tp_richcompare) and one name may map to multiple
Guido van Rossumc334df52002-04-04 23:44:47 +00005558 slots (e.g. __str__ affects tp_str as well as tp_repr). The table is
5559 terminated with an all-zero entry. (This table is further initialized and
5560 sorted in init_slotdefs() below.) */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005561
Guido van Rossum6d204072001-10-21 00:44:31 +00005562typedef struct wrapperbase slotdef;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005563
5564#undef TPSLOT
Guido van Rossumc8e56452001-10-22 00:43:43 +00005565#undef FLSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005566#undef ETSLOT
5567#undef SQSLOT
5568#undef MPSLOT
5569#undef NBSLOT
Guido van Rossum6d204072001-10-21 00:44:31 +00005570#undef UNSLOT
5571#undef IBSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005572#undef BINSLOT
5573#undef RBINSLOT
5574
Guido van Rossum6d204072001-10-21 00:44:31 +00005575#define TPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005576 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
5577 PyDoc_STR(DOC)}
Guido van Rossumc8e56452001-10-22 00:43:43 +00005578#define FLSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC, FLAGS) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005579 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
5580 PyDoc_STR(DOC), FLAGS}
Guido van Rossum6d204072001-10-21 00:44:31 +00005581#define ETSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005582 {NAME, offsetof(PyHeapTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
5583 PyDoc_STR(DOC)}
Guido van Rossum6d204072001-10-21 00:44:31 +00005584#define SQSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005585 ETSLOT(NAME, as_sequence.SLOT, FUNCTION, WRAPPER, DOC)
Guido van Rossum6d204072001-10-21 00:44:31 +00005586#define MPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005587 ETSLOT(NAME, as_mapping.SLOT, FUNCTION, WRAPPER, DOC)
Guido van Rossum6d204072001-10-21 00:44:31 +00005588#define NBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005589 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, DOC)
Guido van Rossum6d204072001-10-21 00:44:31 +00005590#define UNSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005591 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
5592 "x." NAME "() <==> " DOC)
Guido van Rossum6d204072001-10-21 00:44:31 +00005593#define IBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005594 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
5595 "x." NAME "(y) <==> x" DOC "y")
Guido van Rossum6d204072001-10-21 00:44:31 +00005596#define BINSLOT(NAME, SLOT, FUNCTION, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005597 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
5598 "x." NAME "(y) <==> x" DOC "y")
Guido van Rossum6d204072001-10-21 00:44:31 +00005599#define RBINSLOT(NAME, SLOT, FUNCTION, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005600 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
5601 "x." NAME "(y) <==> y" DOC "x")
Anthony Baxter56616992005-06-03 14:12:21 +00005602#define BINSLOTNOTINFIX(NAME, SLOT, FUNCTION, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005603 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
5604 "x." NAME "(y) <==> " DOC)
Anthony Baxter56616992005-06-03 14:12:21 +00005605#define RBINSLOTNOTINFIX(NAME, SLOT, FUNCTION, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005606 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
5607 "x." NAME "(y) <==> " DOC)
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005608
5609static slotdef slotdefs[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005610 SQSLOT("__len__", sq_length, slot_sq_length, wrap_lenfunc,
5611 "x.__len__() <==> len(x)"),
5612 /* Heap types defining __add__/__mul__ have sq_concat/sq_repeat == NULL.
5613 The logic in abstract.c always falls back to nb_add/nb_multiply in
5614 this case. Defining both the nb_* and the sq_* slots to call the
5615 user-defined methods has unexpected side-effects, as shown by
5616 test_descr.notimplemented() */
5617 SQSLOT("__add__", sq_concat, NULL, wrap_binaryfunc,
5618 "x.__add__(y) <==> x+y"),
5619 SQSLOT("__mul__", sq_repeat, NULL, wrap_indexargfunc,
5620 "x.__mul__(n) <==> x*n"),
5621 SQSLOT("__rmul__", sq_repeat, NULL, wrap_indexargfunc,
5622 "x.__rmul__(n) <==> n*x"),
5623 SQSLOT("__getitem__", sq_item, slot_sq_item, wrap_sq_item,
5624 "x.__getitem__(y) <==> x[y]"),
5625 SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_setitem,
5626 "x.__setitem__(i, y) <==> x[i]=y"),
5627 SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_delitem,
5628 "x.__delitem__(y) <==> del x[y]"),
5629 SQSLOT("__contains__", sq_contains, slot_sq_contains, wrap_objobjproc,
5630 "x.__contains__(y) <==> y in x"),
5631 SQSLOT("__iadd__", sq_inplace_concat, NULL,
5632 wrap_binaryfunc, "x.__iadd__(y) <==> x+=y"),
5633 SQSLOT("__imul__", sq_inplace_repeat, NULL,
5634 wrap_indexargfunc, "x.__imul__(y) <==> x*=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005635
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005636 MPSLOT("__len__", mp_length, slot_mp_length, wrap_lenfunc,
5637 "x.__len__() <==> len(x)"),
5638 MPSLOT("__getitem__", mp_subscript, slot_mp_subscript,
5639 wrap_binaryfunc,
5640 "x.__getitem__(y) <==> x[y]"),
5641 MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript,
5642 wrap_objobjargproc,
5643 "x.__setitem__(i, y) <==> x[i]=y"),
5644 MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript,
5645 wrap_delitem,
5646 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005647
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005648 BINSLOT("__add__", nb_add, slot_nb_add,
5649 "+"),
5650 RBINSLOT("__radd__", nb_add, slot_nb_add,
5651 "+"),
5652 BINSLOT("__sub__", nb_subtract, slot_nb_subtract,
5653 "-"),
5654 RBINSLOT("__rsub__", nb_subtract, slot_nb_subtract,
5655 "-"),
5656 BINSLOT("__mul__", nb_multiply, slot_nb_multiply,
5657 "*"),
5658 RBINSLOT("__rmul__", nb_multiply, slot_nb_multiply,
5659 "*"),
5660 BINSLOT("__mod__", nb_remainder, slot_nb_remainder,
5661 "%"),
5662 RBINSLOT("__rmod__", nb_remainder, slot_nb_remainder,
5663 "%"),
5664 BINSLOTNOTINFIX("__divmod__", nb_divmod, slot_nb_divmod,
5665 "divmod(x, y)"),
5666 RBINSLOTNOTINFIX("__rdivmod__", nb_divmod, slot_nb_divmod,
5667 "divmod(y, x)"),
5668 NBSLOT("__pow__", nb_power, slot_nb_power, wrap_ternaryfunc,
5669 "x.__pow__(y[, z]) <==> pow(x, y[, z])"),
5670 NBSLOT("__rpow__", nb_power, slot_nb_power, wrap_ternaryfunc_r,
5671 "y.__rpow__(x[, z]) <==> pow(x, y[, z])"),
5672 UNSLOT("__neg__", nb_negative, slot_nb_negative, wrap_unaryfunc, "-x"),
5673 UNSLOT("__pos__", nb_positive, slot_nb_positive, wrap_unaryfunc, "+x"),
5674 UNSLOT("__abs__", nb_absolute, slot_nb_absolute, wrap_unaryfunc,
5675 "abs(x)"),
5676 UNSLOT("__bool__", nb_bool, slot_nb_bool, wrap_inquirypred,
5677 "x != 0"),
5678 UNSLOT("__invert__", nb_invert, slot_nb_invert, wrap_unaryfunc, "~x"),
5679 BINSLOT("__lshift__", nb_lshift, slot_nb_lshift, "<<"),
5680 RBINSLOT("__rlshift__", nb_lshift, slot_nb_lshift, "<<"),
5681 BINSLOT("__rshift__", nb_rshift, slot_nb_rshift, ">>"),
5682 RBINSLOT("__rrshift__", nb_rshift, slot_nb_rshift, ">>"),
5683 BINSLOT("__and__", nb_and, slot_nb_and, "&"),
5684 RBINSLOT("__rand__", nb_and, slot_nb_and, "&"),
5685 BINSLOT("__xor__", nb_xor, slot_nb_xor, "^"),
5686 RBINSLOT("__rxor__", nb_xor, slot_nb_xor, "^"),
5687 BINSLOT("__or__", nb_or, slot_nb_or, "|"),
5688 RBINSLOT("__ror__", nb_or, slot_nb_or, "|"),
5689 UNSLOT("__int__", nb_int, slot_nb_int, wrap_unaryfunc,
5690 "int(x)"),
5691 UNSLOT("__float__", nb_float, slot_nb_float, wrap_unaryfunc,
5692 "float(x)"),
5693 NBSLOT("__index__", nb_index, slot_nb_index, wrap_unaryfunc,
5694 "x[y:z] <==> x[y.__index__():z.__index__()]"),
5695 IBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add,
5696 wrap_binaryfunc, "+"),
5697 IBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract,
5698 wrap_binaryfunc, "-"),
5699 IBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply,
5700 wrap_binaryfunc, "*"),
5701 IBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder,
5702 wrap_binaryfunc, "%"),
5703 IBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power,
5704 wrap_binaryfunc, "**"),
5705 IBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift,
5706 wrap_binaryfunc, "<<"),
5707 IBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift,
5708 wrap_binaryfunc, ">>"),
5709 IBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and,
5710 wrap_binaryfunc, "&"),
5711 IBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor,
5712 wrap_binaryfunc, "^"),
5713 IBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or,
5714 wrap_binaryfunc, "|"),
5715 BINSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
5716 RBINSLOT("__rfloordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
5717 BINSLOT("__truediv__", nb_true_divide, slot_nb_true_divide, "/"),
5718 RBINSLOT("__rtruediv__", nb_true_divide, slot_nb_true_divide, "/"),
5719 IBSLOT("__ifloordiv__", nb_inplace_floor_divide,
5720 slot_nb_inplace_floor_divide, wrap_binaryfunc, "//"),
5721 IBSLOT("__itruediv__", nb_inplace_true_divide,
5722 slot_nb_inplace_true_divide, wrap_binaryfunc, "/"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005723
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005724 TPSLOT("__str__", tp_str, slot_tp_str, wrap_unaryfunc,
5725 "x.__str__() <==> str(x)"),
5726 TPSLOT("__repr__", tp_repr, slot_tp_repr, wrap_unaryfunc,
5727 "x.__repr__() <==> repr(x)"),
5728 TPSLOT("__hash__", tp_hash, slot_tp_hash, wrap_hashfunc,
5729 "x.__hash__() <==> hash(x)"),
5730 FLSLOT("__call__", tp_call, slot_tp_call, (wrapperfunc)wrap_call,
5731 "x.__call__(...) <==> x(...)", PyWrapperFlag_KEYWORDS),
5732 TPSLOT("__getattribute__", tp_getattro, slot_tp_getattr_hook,
5733 wrap_binaryfunc, "x.__getattribute__('name') <==> x.name"),
5734 TPSLOT("__getattribute__", tp_getattr, NULL, NULL, ""),
5735 TPSLOT("__getattr__", tp_getattro, slot_tp_getattr_hook, NULL, ""),
5736 TPSLOT("__getattr__", tp_getattr, NULL, NULL, ""),
5737 TPSLOT("__setattr__", tp_setattro, slot_tp_setattro, wrap_setattr,
5738 "x.__setattr__('name', value) <==> x.name = value"),
5739 TPSLOT("__setattr__", tp_setattr, NULL, NULL, ""),
5740 TPSLOT("__delattr__", tp_setattro, slot_tp_setattro, wrap_delattr,
5741 "x.__delattr__('name') <==> del x.name"),
5742 TPSLOT("__delattr__", tp_setattr, NULL, NULL, ""),
5743 TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare, richcmp_lt,
5744 "x.__lt__(y) <==> x<y"),
5745 TPSLOT("__le__", tp_richcompare, slot_tp_richcompare, richcmp_le,
5746 "x.__le__(y) <==> x<=y"),
5747 TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare, richcmp_eq,
5748 "x.__eq__(y) <==> x==y"),
5749 TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare, richcmp_ne,
5750 "x.__ne__(y) <==> x!=y"),
5751 TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare, richcmp_gt,
5752 "x.__gt__(y) <==> x>y"),
5753 TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare, richcmp_ge,
5754 "x.__ge__(y) <==> x>=y"),
5755 TPSLOT("__iter__", tp_iter, slot_tp_iter, wrap_unaryfunc,
5756 "x.__iter__() <==> iter(x)"),
5757 TPSLOT("__next__", tp_iternext, slot_tp_iternext, wrap_next,
5758 "x.__next__() <==> next(x)"),
5759 TPSLOT("__get__", tp_descr_get, slot_tp_descr_get, wrap_descr_get,
5760 "descr.__get__(obj[, type]) -> value"),
5761 TPSLOT("__set__", tp_descr_set, slot_tp_descr_set, wrap_descr_set,
5762 "descr.__set__(obj, value)"),
5763 TPSLOT("__delete__", tp_descr_set, slot_tp_descr_set,
5764 wrap_descr_delete, "descr.__delete__(obj)"),
5765 FLSLOT("__init__", tp_init, slot_tp_init, (wrapperfunc)wrap_init,
5766 "x.__init__(...) initializes x; "
Alexander Belopolsky977a6842010-08-16 20:17:07 +00005767 "see help(type(x)) for signature",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005768 PyWrapperFlag_KEYWORDS),
5769 TPSLOT("__new__", tp_new, slot_tp_new, NULL, ""),
5770 TPSLOT("__del__", tp_del, slot_tp_del, NULL, ""),
5771 {NULL}
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005772};
5773
Guido van Rossumc334df52002-04-04 23:44:47 +00005774/* Given a type pointer and an offset gotten from a slotdef entry, return a
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005775 pointer to the actual slot. This is not quite the same as simply adding
Guido van Rossumc334df52002-04-04 23:44:47 +00005776 the offset to the type pointer, since it takes care to indirect through the
5777 proper indirection pointer (as_buffer, etc.); it returns NULL if the
5778 indirection pointer is NULL. */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005779static void **
Martin v. Löwis18e16552006-02-15 17:27:45 +00005780slotptr(PyTypeObject *type, int ioffset)
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005781{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005782 char *ptr;
5783 long offset = ioffset;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005784
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005785 /* Note: this depends on the order of the members of PyHeapTypeObject! */
5786 assert(offset >= 0);
5787 assert((size_t)offset < offsetof(PyHeapTypeObject, as_buffer));
5788 if ((size_t)offset >= offsetof(PyHeapTypeObject, as_sequence)) {
5789 ptr = (char *)type->tp_as_sequence;
5790 offset -= offsetof(PyHeapTypeObject, as_sequence);
5791 }
5792 else if ((size_t)offset >= offsetof(PyHeapTypeObject, as_mapping)) {
5793 ptr = (char *)type->tp_as_mapping;
5794 offset -= offsetof(PyHeapTypeObject, as_mapping);
5795 }
5796 else if ((size_t)offset >= offsetof(PyHeapTypeObject, as_number)) {
5797 ptr = (char *)type->tp_as_number;
5798 offset -= offsetof(PyHeapTypeObject, as_number);
5799 }
5800 else {
5801 ptr = (char *)type;
5802 }
5803 if (ptr != NULL)
5804 ptr += offset;
5805 return (void **)ptr;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005806}
Guido van Rossumf040ede2001-08-07 16:40:56 +00005807
Guido van Rossumc334df52002-04-04 23:44:47 +00005808/* Length of array of slotdef pointers used to store slots with the
5809 same __name__. There should be at most MAX_EQUIV-1 slotdef entries with
5810 the same __name__, for any __name__. Since that's a static property, it is
5811 appropriate to declare fixed-size arrays for this. */
5812#define MAX_EQUIV 10
5813
5814/* Return a slot pointer for a given name, but ONLY if the attribute has
5815 exactly one slot function. The name must be an interned string. */
5816static void **
5817resolve_slotdups(PyTypeObject *type, PyObject *name)
5818{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005819 /* XXX Maybe this could be optimized more -- but is it worth it? */
Guido van Rossumc334df52002-04-04 23:44:47 +00005820
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005821 /* pname and ptrs act as a little cache */
5822 static PyObject *pname;
5823 static slotdef *ptrs[MAX_EQUIV];
5824 slotdef *p, **pp;
5825 void **res, **ptr;
Guido van Rossumc334df52002-04-04 23:44:47 +00005826
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005827 if (pname != name) {
5828 /* Collect all slotdefs that match name into ptrs. */
5829 pname = name;
5830 pp = ptrs;
5831 for (p = slotdefs; p->name_strobj; p++) {
5832 if (p->name_strobj == name)
5833 *pp++ = p;
5834 }
5835 *pp = NULL;
5836 }
Guido van Rossumc334df52002-04-04 23:44:47 +00005837
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005838 /* Look in all matching slots of the type; if exactly one of these has
5839 a filled-in slot, return its value. Otherwise return NULL. */
5840 res = NULL;
5841 for (pp = ptrs; *pp; pp++) {
5842 ptr = slotptr(type, (*pp)->offset);
5843 if (ptr == NULL || *ptr == NULL)
5844 continue;
5845 if (res != NULL)
5846 return NULL;
5847 res = ptr;
5848 }
5849 return res;
Guido van Rossumc334df52002-04-04 23:44:47 +00005850}
5851
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005852/* Common code for update_slots_callback() and fixup_slot_dispatchers(). This
Guido van Rossumc334df52002-04-04 23:44:47 +00005853 does some incredibly complex thinking and then sticks something into the
5854 slot. (It sees if the adjacent slotdefs for the same slot have conflicting
5855 interests, and then stores a generic wrapper or a specific function into
5856 the slot.) Return a pointer to the next slotdef with a different offset,
5857 because that's convenient for fixup_slot_dispatchers(). */
5858static slotdef *
5859update_one_slot(PyTypeObject *type, slotdef *p)
5860{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005861 PyObject *descr;
5862 PyWrapperDescrObject *d;
5863 void *generic = NULL, *specific = NULL;
5864 int use_generic = 0;
5865 int offset = p->offset;
5866 void **ptr = slotptr(type, offset);
Guido van Rossumc334df52002-04-04 23:44:47 +00005867
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005868 if (ptr == NULL) {
5869 do {
5870 ++p;
5871 } while (p->offset == offset);
5872 return p;
5873 }
5874 do {
5875 descr = _PyType_Lookup(type, p->name_strobj);
5876 if (descr == NULL) {
5877 if (ptr == (void**)&type->tp_iternext) {
5878 specific = _PyObject_NextNotImplemented;
5879 }
5880 continue;
5881 }
5882 if (Py_TYPE(descr) == &PyWrapperDescr_Type) {
5883 void **tptr = resolve_slotdups(type, p->name_strobj);
5884 if (tptr == NULL || tptr == ptr)
5885 generic = p->function;
5886 d = (PyWrapperDescrObject *)descr;
5887 if (d->d_base->wrapper == p->wrapper &&
5888 PyType_IsSubtype(type, PyDescr_TYPE(d)))
5889 {
5890 if (specific == NULL ||
5891 specific == d->d_wrapped)
5892 specific = d->d_wrapped;
5893 else
5894 use_generic = 1;
5895 }
5896 }
5897 else if (Py_TYPE(descr) == &PyCFunction_Type &&
5898 PyCFunction_GET_FUNCTION(descr) ==
5899 (PyCFunction)tp_new_wrapper &&
5900 ptr == (void**)&type->tp_new)
5901 {
5902 /* The __new__ wrapper is not a wrapper descriptor,
5903 so must be special-cased differently.
5904 If we don't do this, creating an instance will
5905 always use slot_tp_new which will look up
5906 __new__ in the MRO which will call tp_new_wrapper
5907 which will look through the base classes looking
5908 for a static base and call its tp_new (usually
5909 PyType_GenericNew), after performing various
5910 sanity checks and constructing a new argument
5911 list. Cut all that nonsense short -- this speeds
5912 up instance creation tremendously. */
5913 specific = (void *)type->tp_new;
5914 /* XXX I'm not 100% sure that there isn't a hole
5915 in this reasoning that requires additional
5916 sanity checks. I'll buy the first person to
5917 point out a bug in this reasoning a beer. */
5918 }
5919 else if (descr == Py_None &&
5920 ptr == (void**)&type->tp_hash) {
5921 /* We specifically allow __hash__ to be set to None
5922 to prevent inheritance of the default
5923 implementation from object.__hash__ */
5924 specific = PyObject_HashNotImplemented;
5925 }
5926 else {
5927 use_generic = 1;
5928 generic = p->function;
5929 }
5930 } while ((++p)->offset == offset);
5931 if (specific && !use_generic)
5932 *ptr = specific;
5933 else
5934 *ptr = generic;
5935 return p;
Guido van Rossumc334df52002-04-04 23:44:47 +00005936}
5937
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005938/* In the type, update the slots whose slotdefs are gathered in the pp array.
5939 This is a callback for update_subclasses(). */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005940static int
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005941update_slots_callback(PyTypeObject *type, void *data)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005942{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005943 slotdef **pp = (slotdef **)data;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005944
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005945 for (; *pp; pp++)
5946 update_one_slot(type, *pp);
5947 return 0;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005948}
5949
Guido van Rossumc334df52002-04-04 23:44:47 +00005950/* Comparison function for qsort() to compare slotdefs by their offset, and
5951 for equal offset by their address (to force a stable sort). */
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005952static int
5953slotdef_cmp(const void *aa, const void *bb)
5954{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005955 const slotdef *a = (const slotdef *)aa, *b = (const slotdef *)bb;
5956 int c = a->offset - b->offset;
5957 if (c != 0)
5958 return c;
5959 else
5960 /* Cannot use a-b, as this gives off_t,
5961 which may lose precision when converted to int. */
5962 return (a > b) ? 1 : (a < b) ? -1 : 0;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005963}
5964
Guido van Rossumc334df52002-04-04 23:44:47 +00005965/* Initialize the slotdefs table by adding interned string objects for the
5966 names and sorting the entries. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005967static void
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005968init_slotdefs(void)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005969{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005970 slotdef *p;
5971 static int initialized = 0;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005972
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005973 if (initialized)
5974 return;
5975 for (p = slotdefs; p->name; p++) {
5976 p->name_strobj = PyUnicode_InternFromString(p->name);
5977 if (!p->name_strobj)
5978 Py_FatalError("Out of memory interning slotdef names");
5979 }
5980 qsort((void *)slotdefs, (size_t)(p-slotdefs), sizeof(slotdef),
5981 slotdef_cmp);
5982 initialized = 1;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005983}
5984
Guido van Rossumc334df52002-04-04 23:44:47 +00005985/* Update the slots after assignment to a class (type) attribute. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005986static int
5987update_slot(PyTypeObject *type, PyObject *name)
5988{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005989 slotdef *ptrs[MAX_EQUIV];
5990 slotdef *p;
5991 slotdef **pp;
5992 int offset;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005993
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005994 /* Clear the VALID_VERSION flag of 'type' and all its
5995 subclasses. This could possibly be unified with the
5996 update_subclasses() recursion below, but carefully:
5997 they each have their own conditions on which to stop
5998 recursing into subclasses. */
5999 PyType_Modified(type);
Christian Heimesa62da1d2008-01-12 19:39:10 +00006000
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006001 init_slotdefs();
6002 pp = ptrs;
6003 for (p = slotdefs; p->name; p++) {
6004 /* XXX assume name is interned! */
6005 if (p->name_strobj == name)
6006 *pp++ = p;
6007 }
6008 *pp = NULL;
6009 for (pp = ptrs; *pp; pp++) {
6010 p = *pp;
6011 offset = p->offset;
6012 while (p > slotdefs && (p-1)->offset == offset)
6013 --p;
6014 *pp = p;
6015 }
6016 if (ptrs[0] == NULL)
6017 return 0; /* Not an attribute that affects any slots */
6018 return update_subclasses(type, name,
6019 update_slots_callback, (void *)ptrs);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006020}
6021
Guido van Rossumc334df52002-04-04 23:44:47 +00006022/* Store the proper functions in the slot dispatches at class (type)
6023 definition time, based upon which operations the class overrides in its
6024 dict. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00006025static void
Guido van Rossum7b9144b2001-10-09 19:39:46 +00006026fixup_slot_dispatchers(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00006027{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006028 slotdef *p;
Tim Peters6d6c1a32001-08-02 04:15:00 +00006029
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006030 init_slotdefs();
6031 for (p = slotdefs; p->name; )
6032 p = update_one_slot(type, p);
Tim Peters6d6c1a32001-08-02 04:15:00 +00006033}
Guido van Rossum705f0f52001-08-24 16:47:00 +00006034
Michael W. Hudson98bbc492002-11-26 14:47:27 +00006035static void
6036update_all_slots(PyTypeObject* type)
6037{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006038 slotdef *p;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00006039
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006040 init_slotdefs();
6041 for (p = slotdefs; p->name; p++) {
6042 /* update_slot returns int but can't actually fail */
6043 update_slot(type, p->name_strobj);
6044 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +00006045}
6046
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006047/* recurse_down_subclasses() and update_subclasses() are mutually
6048 recursive functions to call a callback for all subclasses,
6049 but refraining from recursing into subclasses that define 'name'. */
6050
6051static int
6052update_subclasses(PyTypeObject *type, PyObject *name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006053 update_callback callback, void *data)
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006054{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006055 if (callback(type, data) < 0)
6056 return -1;
6057 return recurse_down_subclasses(type, name, callback, data);
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006058}
6059
6060static int
6061recurse_down_subclasses(PyTypeObject *type, PyObject *name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006062 update_callback callback, void *data)
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006063{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006064 PyTypeObject *subclass;
6065 PyObject *ref, *subclasses, *dict;
6066 Py_ssize_t i, n;
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006067
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006068 subclasses = type->tp_subclasses;
6069 if (subclasses == NULL)
6070 return 0;
6071 assert(PyList_Check(subclasses));
6072 n = PyList_GET_SIZE(subclasses);
6073 for (i = 0; i < n; i++) {
6074 ref = PyList_GET_ITEM(subclasses, i);
6075 assert(PyWeakref_CheckRef(ref));
6076 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
6077 assert(subclass != NULL);
6078 if ((PyObject *)subclass == Py_None)
6079 continue;
6080 assert(PyType_Check(subclass));
6081 /* Avoid recursing down into unaffected classes */
6082 dict = subclass->tp_dict;
6083 if (dict != NULL && PyDict_Check(dict) &&
6084 PyDict_GetItem(dict, name) != NULL)
6085 continue;
6086 if (update_subclasses(subclass, name, callback, data) < 0)
6087 return -1;
6088 }
6089 return 0;
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006090}
6091
Guido van Rossum6d204072001-10-21 00:44:31 +00006092/* This function is called by PyType_Ready() to populate the type's
6093 dictionary with method descriptors for function slots. For each
Guido van Rossum09638c12002-06-13 19:17:46 +00006094 function slot (like tp_repr) that's defined in the type, one or more
6095 corresponding descriptors are added in the type's tp_dict dictionary
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006096 under the appropriate name (like __repr__). Some function slots
Guido van Rossum09638c12002-06-13 19:17:46 +00006097 cause more than one descriptor to be added (for example, the nb_add
6098 slot adds both __add__ and __radd__ descriptors) and some function
6099 slots compete for the same descriptor (for example both sq_item and
6100 mp_subscript generate a __getitem__ descriptor).
6101
Ezio Melotti13925002011-03-16 11:05:33 +02006102 In the latter case, the first slotdef entry encountered wins. Since
Tim Petersbf9b2442003-03-23 05:35:36 +00006103 slotdef entries are sorted by the offset of the slot in the
Guido van Rossume5c691a2003-03-07 15:13:17 +00006104 PyHeapTypeObject, this gives us some control over disambiguating
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006105 between competing slots: the members of PyHeapTypeObject are listed
6106 from most general to least general, so the most general slot is
6107 preferred. In particular, because as_mapping comes before as_sequence,
6108 for a type that defines both mp_subscript and sq_item, mp_subscript
6109 wins.
Guido van Rossum09638c12002-06-13 19:17:46 +00006110
6111 This only adds new descriptors and doesn't overwrite entries in
6112 tp_dict that were previously defined. The descriptors contain a
6113 reference to the C function they must call, so that it's safe if they
6114 are copied into a subtype's __dict__ and the subtype has a different
6115 C function in its slot -- calling the method defined by the
6116 descriptor will call the C function that was used to create it,
6117 rather than the C function present in the slot when it is called.
6118 (This is important because a subtype may have a C function in the
6119 slot that calls the method from the dictionary, and we want to avoid
6120 infinite recursion here.) */
Guido van Rossum6d204072001-10-21 00:44:31 +00006121
6122static int
6123add_operators(PyTypeObject *type)
6124{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006125 PyObject *dict = type->tp_dict;
6126 slotdef *p;
6127 PyObject *descr;
6128 void **ptr;
Guido van Rossum6d204072001-10-21 00:44:31 +00006129
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006130 init_slotdefs();
6131 for (p = slotdefs; p->name; p++) {
6132 if (p->wrapper == NULL)
6133 continue;
6134 ptr = slotptr(type, p->offset);
6135 if (!ptr || !*ptr)
6136 continue;
6137 if (PyDict_GetItem(dict, p->name_strobj))
6138 continue;
6139 if (*ptr == PyObject_HashNotImplemented) {
6140 /* Classes may prevent the inheritance of the tp_hash
6141 slot by storing PyObject_HashNotImplemented in it. Make it
6142 visible as a None value for the __hash__ attribute. */
6143 if (PyDict_SetItem(dict, p->name_strobj, Py_None) < 0)
6144 return -1;
6145 }
6146 else {
6147 descr = PyDescr_NewWrapper(type, p, *ptr);
6148 if (descr == NULL)
6149 return -1;
6150 if (PyDict_SetItem(dict, p->name_strobj, descr) < 0)
6151 return -1;
6152 Py_DECREF(descr);
6153 }
6154 }
6155 if (type->tp_new != NULL) {
6156 if (add_tp_new_wrapper(type) < 0)
6157 return -1;
6158 }
6159 return 0;
Guido van Rossum6d204072001-10-21 00:44:31 +00006160}
6161
Guido van Rossum705f0f52001-08-24 16:47:00 +00006162
6163/* Cooperative 'super' */
6164
6165typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006166 PyObject_HEAD
6167 PyTypeObject *type;
6168 PyObject *obj;
6169 PyTypeObject *obj_type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006170} superobject;
6171
Guido van Rossum6f799372001-09-20 20:46:19 +00006172static PyMemberDef super_members[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006173 {"__thisclass__", T_OBJECT, offsetof(superobject, type), READONLY,
6174 "the class invoking super()"},
6175 {"__self__", T_OBJECT, offsetof(superobject, obj), READONLY,
6176 "the instance invoking super(); may be None"},
6177 {"__self_class__", T_OBJECT, offsetof(superobject, obj_type), READONLY,
6178 "the type of the instance invoking super(); may be None"},
6179 {0}
Guido van Rossum41eb14d2001-08-30 23:13:11 +00006180};
6181
Guido van Rossum705f0f52001-08-24 16:47:00 +00006182static void
6183super_dealloc(PyObject *self)
6184{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006185 superobject *su = (superobject *)self;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006186
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006187 _PyObject_GC_UNTRACK(self);
6188 Py_XDECREF(su->obj);
6189 Py_XDECREF(su->type);
6190 Py_XDECREF(su->obj_type);
6191 Py_TYPE(self)->tp_free(self);
Guido van Rossum705f0f52001-08-24 16:47:00 +00006192}
6193
6194static PyObject *
Guido van Rossum41eb14d2001-08-30 23:13:11 +00006195super_repr(PyObject *self)
6196{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006197 superobject *su = (superobject *)self;
Guido van Rossum41eb14d2001-08-30 23:13:11 +00006198
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006199 if (su->obj_type)
6200 return PyUnicode_FromFormat(
6201 "<super: <class '%s'>, <%s object>>",
6202 su->type ? su->type->tp_name : "NULL",
6203 su->obj_type->tp_name);
6204 else
6205 return PyUnicode_FromFormat(
6206 "<super: <class '%s'>, NULL>",
6207 su->type ? su->type->tp_name : "NULL");
Guido van Rossum41eb14d2001-08-30 23:13:11 +00006208}
6209
6210static PyObject *
Guido van Rossum705f0f52001-08-24 16:47:00 +00006211super_getattro(PyObject *self, PyObject *name)
6212{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006213 superobject *su = (superobject *)self;
6214 int skip = su->obj_type == NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006215
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006216 if (!skip) {
6217 /* We want __class__ to return the class of the super object
6218 (i.e. super, or a subclass), not the class of su->obj. */
6219 skip = (PyUnicode_Check(name) &&
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006220 PyUnicode_GET_LENGTH(name) == 9 &&
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006221 PyUnicode_CompareWithASCIIString(name, "__class__") == 0);
6222 }
Guido van Rossum76ba09f2003-04-16 19:40:58 +00006223
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006224 if (!skip) {
6225 PyObject *mro, *res, *tmp, *dict;
6226 PyTypeObject *starttype;
6227 descrgetfunc f;
6228 Py_ssize_t i, n;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006229
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006230 starttype = su->obj_type;
6231 mro = starttype->tp_mro;
Guido van Rossum155db9a2002-04-02 17:53:47 +00006232
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006233 if (mro == NULL)
6234 n = 0;
6235 else {
6236 assert(PyTuple_Check(mro));
6237 n = PyTuple_GET_SIZE(mro);
6238 }
6239 for (i = 0; i < n; i++) {
6240 if ((PyObject *)(su->type) == PyTuple_GET_ITEM(mro, i))
6241 break;
6242 }
6243 i++;
6244 res = NULL;
6245 for (; i < n; i++) {
6246 tmp = PyTuple_GET_ITEM(mro, i);
6247 if (PyType_Check(tmp))
6248 dict = ((PyTypeObject *)tmp)->tp_dict;
6249 else
6250 continue;
6251 res = PyDict_GetItem(dict, name);
6252 if (res != NULL) {
6253 Py_INCREF(res);
6254 f = Py_TYPE(res)->tp_descr_get;
6255 if (f != NULL) {
6256 tmp = f(res,
6257 /* Only pass 'obj' param if
6258 this is instance-mode super
6259 (See SF ID #743627)
6260 */
6261 (su->obj == (PyObject *)
6262 su->obj_type
6263 ? (PyObject *)NULL
6264 : su->obj),
6265 (PyObject *)starttype);
6266 Py_DECREF(res);
6267 res = tmp;
6268 }
6269 return res;
6270 }
6271 }
6272 }
6273 return PyObject_GenericGetAttr(self, name);
Guido van Rossum705f0f52001-08-24 16:47:00 +00006274}
6275
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006276static PyTypeObject *
Guido van Rossum5b443c62001-12-03 15:38:28 +00006277supercheck(PyTypeObject *type, PyObject *obj)
6278{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006279 /* Check that a super() call makes sense. Return a type object.
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006280
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006281 obj can be a new-style class, or an instance of one:
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006282
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006283 - If it is a class, it must be a subclass of 'type'. This case is
6284 used for class methods; the return value is obj.
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006285
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006286 - If it is an instance, it must be an instance of 'type'. This is
6287 the normal case; the return value is obj.__class__.
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006288
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006289 But... when obj is an instance, we want to allow for the case where
6290 Py_TYPE(obj) is not a subclass of type, but obj.__class__ is!
6291 This will allow using super() with a proxy for obj.
6292 */
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006293
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006294 /* Check for first bullet above (special case) */
6295 if (PyType_Check(obj) && PyType_IsSubtype((PyTypeObject *)obj, type)) {
6296 Py_INCREF(obj);
6297 return (PyTypeObject *)obj;
6298 }
Guido van Rossum8e80a722003-02-18 19:22:22 +00006299
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006300 /* Normal case */
6301 if (PyType_IsSubtype(Py_TYPE(obj), type)) {
6302 Py_INCREF(Py_TYPE(obj));
6303 return Py_TYPE(obj);
6304 }
6305 else {
6306 /* Try the slow way */
6307 static PyObject *class_str = NULL;
6308 PyObject *class_attr;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006309
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006310 if (class_str == NULL) {
6311 class_str = PyUnicode_FromString("__class__");
6312 if (class_str == NULL)
6313 return NULL;
6314 }
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006315
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006316 class_attr = PyObject_GetAttr(obj, class_str);
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006317
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006318 if (class_attr != NULL &&
6319 PyType_Check(class_attr) &&
6320 (PyTypeObject *)class_attr != Py_TYPE(obj))
6321 {
6322 int ok = PyType_IsSubtype(
6323 (PyTypeObject *)class_attr, type);
6324 if (ok)
6325 return (PyTypeObject *)class_attr;
6326 }
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006327
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006328 if (class_attr == NULL)
6329 PyErr_Clear();
6330 else
6331 Py_DECREF(class_attr);
6332 }
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006333
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006334 PyErr_SetString(PyExc_TypeError,
6335 "super(type, obj): "
6336 "obj must be an instance or subtype of type");
6337 return NULL;
Guido van Rossum5b443c62001-12-03 15:38:28 +00006338}
6339
Guido van Rossum705f0f52001-08-24 16:47:00 +00006340static PyObject *
6341super_descr_get(PyObject *self, PyObject *obj, PyObject *type)
6342{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006343 superobject *su = (superobject *)self;
6344 superobject *newobj;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006345
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006346 if (obj == NULL || obj == Py_None || su->obj != NULL) {
6347 /* Not binding to an object, or already bound */
6348 Py_INCREF(self);
6349 return self;
6350 }
6351 if (Py_TYPE(su) != &PySuper_Type)
6352 /* If su is an instance of a (strict) subclass of super,
6353 call its type */
6354 return PyObject_CallFunctionObjArgs((PyObject *)Py_TYPE(su),
6355 su->type, obj, NULL);
6356 else {
6357 /* Inline the common case */
6358 PyTypeObject *obj_type = supercheck(su->type, obj);
6359 if (obj_type == NULL)
6360 return NULL;
6361 newobj = (superobject *)PySuper_Type.tp_new(&PySuper_Type,
6362 NULL, NULL);
6363 if (newobj == NULL)
6364 return NULL;
6365 Py_INCREF(su->type);
6366 Py_INCREF(obj);
6367 newobj->type = su->type;
6368 newobj->obj = obj;
6369 newobj->obj_type = obj_type;
6370 return (PyObject *)newobj;
6371 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00006372}
6373
6374static int
6375super_init(PyObject *self, PyObject *args, PyObject *kwds)
6376{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006377 superobject *su = (superobject *)self;
6378 PyTypeObject *type = NULL;
6379 PyObject *obj = NULL;
6380 PyTypeObject *obj_type = NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006381
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006382 if (!_PyArg_NoKeywords("super", kwds))
6383 return -1;
6384 if (!PyArg_ParseTuple(args, "|O!O:super", &PyType_Type, &type, &obj))
6385 return -1;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00006386
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006387 if (type == NULL) {
6388 /* Call super(), without args -- fill in from __class__
6389 and first local variable on the stack. */
6390 PyFrameObject *f = PyThreadState_GET()->frame;
6391 PyCodeObject *co = f->f_code;
Victor Stinner0fcab4a2011-01-04 12:59:15 +00006392 Py_ssize_t i, n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006393 if (co == NULL) {
6394 PyErr_SetString(PyExc_SystemError,
6395 "super(): no code object");
6396 return -1;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00006397 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006398 if (co->co_argcount == 0) {
6399 PyErr_SetString(PyExc_SystemError,
6400 "super(): no arguments");
6401 return -1;
6402 }
6403 obj = f->f_localsplus[0];
6404 if (obj == NULL) {
6405 PyErr_SetString(PyExc_SystemError,
6406 "super(): arg[0] deleted");
6407 return -1;
6408 }
6409 if (co->co_freevars == NULL)
6410 n = 0;
6411 else {
6412 assert(PyTuple_Check(co->co_freevars));
6413 n = PyTuple_GET_SIZE(co->co_freevars);
6414 }
6415 for (i = 0; i < n; i++) {
6416 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
6417 assert(PyUnicode_Check(name));
6418 if (!PyUnicode_CompareWithASCIIString(name,
Benjamin Petersonf5ff2232011-06-19 19:42:22 -05006419 "@__class__")) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006420 Py_ssize_t index = co->co_nlocals +
6421 PyTuple_GET_SIZE(co->co_cellvars) + i;
6422 PyObject *cell = f->f_localsplus[index];
6423 if (cell == NULL || !PyCell_Check(cell)) {
6424 PyErr_SetString(PyExc_SystemError,
6425 "super(): bad __class__ cell");
6426 return -1;
6427 }
6428 type = (PyTypeObject *) PyCell_GET(cell);
6429 if (type == NULL) {
6430 PyErr_SetString(PyExc_SystemError,
6431 "super(): empty __class__ cell");
6432 return -1;
6433 }
6434 if (!PyType_Check(type)) {
6435 PyErr_Format(PyExc_SystemError,
6436 "super(): __class__ is not a type (%s)",
6437 Py_TYPE(type)->tp_name);
6438 return -1;
6439 }
6440 break;
6441 }
6442 }
6443 if (type == NULL) {
6444 PyErr_SetString(PyExc_SystemError,
6445 "super(): __class__ cell not found");
6446 return -1;
6447 }
6448 }
Guido van Rossumcd16bf62007-06-13 18:07:49 +00006449
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006450 if (obj == Py_None)
6451 obj = NULL;
6452 if (obj != NULL) {
6453 obj_type = supercheck(type, obj);
6454 if (obj_type == NULL)
6455 return -1;
6456 Py_INCREF(obj);
6457 }
6458 Py_INCREF(type);
6459 su->type = type;
6460 su->obj = obj;
6461 su->obj_type = obj_type;
6462 return 0;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006463}
6464
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00006465PyDoc_STRVAR(super_doc,
Guido van Rossumcd16bf62007-06-13 18:07:49 +00006466"super() -> same as super(__class__, <first argument>)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00006467"super(type) -> unbound super object\n"
6468"super(type, obj) -> bound super object; requires isinstance(obj, type)\n"
Guido van Rossume705ef12001-08-29 15:47:06 +00006469"super(type, type2) -> bound super object; requires issubclass(type2, type)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00006470"Typical use to call a cooperative superclass method:\n"
6471"class C(B):\n"
6472" def meth(self, arg):\n"
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006473" super().meth(arg)\n"
Guido van Rossumcd16bf62007-06-13 18:07:49 +00006474"This works for class methods too:\n"
6475"class C(B):\n"
6476" @classmethod\n"
6477" def cmeth(cls, arg):\n"
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006478" super().cmeth(arg)\n");
Guido van Rossum705f0f52001-08-24 16:47:00 +00006479
Guido van Rossum048eb752001-10-02 21:24:57 +00006480static int
6481super_traverse(PyObject *self, visitproc visit, void *arg)
6482{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006483 superobject *su = (superobject *)self;
Guido van Rossum048eb752001-10-02 21:24:57 +00006484
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006485 Py_VISIT(su->obj);
6486 Py_VISIT(su->type);
6487 Py_VISIT(su->obj_type);
Guido van Rossum048eb752001-10-02 21:24:57 +00006488
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006489 return 0;
Guido van Rossum048eb752001-10-02 21:24:57 +00006490}
6491
Guido van Rossum705f0f52001-08-24 16:47:00 +00006492PyTypeObject PySuper_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006493 PyVarObject_HEAD_INIT(&PyType_Type, 0)
6494 "super", /* tp_name */
6495 sizeof(superobject), /* tp_basicsize */
6496 0, /* tp_itemsize */
6497 /* methods */
6498 super_dealloc, /* tp_dealloc */
6499 0, /* tp_print */
6500 0, /* tp_getattr */
6501 0, /* tp_setattr */
6502 0, /* tp_reserved */
6503 super_repr, /* tp_repr */
6504 0, /* tp_as_number */
6505 0, /* tp_as_sequence */
6506 0, /* tp_as_mapping */
6507 0, /* tp_hash */
6508 0, /* tp_call */
6509 0, /* tp_str */
6510 super_getattro, /* tp_getattro */
6511 0, /* tp_setattro */
6512 0, /* tp_as_buffer */
6513 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
6514 Py_TPFLAGS_BASETYPE, /* tp_flags */
6515 super_doc, /* tp_doc */
6516 super_traverse, /* tp_traverse */
6517 0, /* tp_clear */
6518 0, /* tp_richcompare */
6519 0, /* tp_weaklistoffset */
6520 0, /* tp_iter */
6521 0, /* tp_iternext */
6522 0, /* tp_methods */
6523 super_members, /* tp_members */
6524 0, /* tp_getset */
6525 0, /* tp_base */
6526 0, /* tp_dict */
6527 super_descr_get, /* tp_descr_get */
6528 0, /* tp_descr_set */
6529 0, /* tp_dictoffset */
6530 super_init, /* tp_init */
6531 PyType_GenericAlloc, /* tp_alloc */
6532 PyType_GenericNew, /* tp_new */
6533 PyObject_GC_Del, /* tp_free */
Guido van Rossum705f0f52001-08-24 16:47:00 +00006534};