blob: 010120a4e80ef930f17903432dbfec1ee35b1fd5 [file] [log] [blame]
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001/* Type object implementation */
2
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003#include "Python.h"
Guido van Rossumcd16bf62007-06-13 18:07:49 +00004#include "frameobject.h"
Tim Peters6d6c1a32001-08-02 04:15:00 +00005#include "structmember.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00006
Guido van Rossum9923ffe2002-06-04 19:52:53 +00007#include <ctype.h>
8
Christian Heimesa62da1d2008-01-12 19:39:10 +00009
10/* Support type attribute cache */
11
12/* The cache can keep references to the names alive for longer than
13 they normally would. This is why the maximum size is limited to
14 MCACHE_MAX_ATTR_SIZE, since it might be a problem if very large
15 strings are used as attribute names. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000016#define MCACHE_MAX_ATTR_SIZE 100
17#define MCACHE_SIZE_EXP 10
18#define MCACHE_HASH(version, name_hash) \
19 (((unsigned int)(version) * (unsigned int)(name_hash)) \
20 >> (8*sizeof(unsigned int) - MCACHE_SIZE_EXP))
Christian Heimesa62da1d2008-01-12 19:39:10 +000021#define MCACHE_HASH_METHOD(type, name) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000022 MCACHE_HASH((type)->tp_version_tag, \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020023 ((PyASCIIObject *)(name))->hash)
Christian Heimesa62da1d2008-01-12 19:39:10 +000024#define MCACHE_CACHEABLE_NAME(name) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000025 PyUnicode_CheckExact(name) && \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020026 PyUnicode_READY(name) != -1 && \
27 PyUnicode_GET_LENGTH(name) <= MCACHE_MAX_ATTR_SIZE
Christian Heimesa62da1d2008-01-12 19:39:10 +000028
29struct method_cache_entry {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000030 unsigned int version;
31 PyObject *name; /* reference to exactly a str or None */
32 PyObject *value; /* borrowed */
Christian Heimesa62da1d2008-01-12 19:39:10 +000033};
34
35static struct method_cache_entry method_cache[1 << MCACHE_SIZE_EXP];
36static unsigned int next_version_tag = 0;
Christian Heimes26855632008-01-27 23:50:43 +000037
Martin v. Löwisbd928fe2011-10-14 10:20:37 +020038_Py_IDENTIFIER(__dict__);
39_Py_IDENTIFIER(__class__);
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +020040
Christian Heimes26855632008-01-27 23:50:43 +000041unsigned int
42PyType_ClearCache(void)
43{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000044 Py_ssize_t i;
45 unsigned int cur_version_tag = next_version_tag - 1;
46
47 for (i = 0; i < (1 << MCACHE_SIZE_EXP); i++) {
48 method_cache[i].version = 0;
49 Py_CLEAR(method_cache[i].name);
50 method_cache[i].value = NULL;
51 }
52 next_version_tag = 0;
53 /* mark all version tags as invalid */
54 PyType_Modified(&PyBaseObject_Type);
55 return cur_version_tag;
Christian Heimes26855632008-01-27 23:50:43 +000056}
Christian Heimesa62da1d2008-01-12 19:39:10 +000057
Georg Brandlf08a9dd2008-06-10 16:57:31 +000058void
59PyType_Modified(PyTypeObject *type)
Christian Heimesa62da1d2008-01-12 19:39:10 +000060{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000061 /* Invalidate any cached data for the specified type and all
62 subclasses. This function is called after the base
63 classes, mro, or attributes of the type are altered.
Christian Heimesa62da1d2008-01-12 19:39:10 +000064
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000065 Invariants:
Christian Heimesa62da1d2008-01-12 19:39:10 +000066
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000067 - Py_TPFLAGS_VALID_VERSION_TAG is never set if
68 Py_TPFLAGS_HAVE_VERSION_TAG is not set (e.g. on type
69 objects coming from non-recompiled extension modules)
Christian Heimesa62da1d2008-01-12 19:39:10 +000070
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000071 - before Py_TPFLAGS_VALID_VERSION_TAG can be set on a type,
72 it must first be set on all super types.
Christian Heimesa62da1d2008-01-12 19:39:10 +000073
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000074 This function clears the Py_TPFLAGS_VALID_VERSION_TAG of a
75 type (so it must first clear it on all subclasses). The
76 tp_version_tag value is meaningless unless this flag is set.
77 We don't assign new version tags eagerly, but only as
78 needed.
79 */
80 PyObject *raw, *ref;
81 Py_ssize_t i, n;
Christian Heimesa62da1d2008-01-12 19:39:10 +000082
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000083 if (!PyType_HasFeature(type, Py_TPFLAGS_VALID_VERSION_TAG))
84 return;
Christian Heimesa62da1d2008-01-12 19:39:10 +000085
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000086 raw = type->tp_subclasses;
87 if (raw != NULL) {
88 n = PyList_GET_SIZE(raw);
89 for (i = 0; i < n; i++) {
90 ref = PyList_GET_ITEM(raw, i);
91 ref = PyWeakref_GET_OBJECT(ref);
92 if (ref != Py_None) {
93 PyType_Modified((PyTypeObject *)ref);
94 }
95 }
96 }
97 type->tp_flags &= ~Py_TPFLAGS_VALID_VERSION_TAG;
Christian Heimesa62da1d2008-01-12 19:39:10 +000098}
99
100static void
101type_mro_modified(PyTypeObject *type, PyObject *bases) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000102 /*
103 Check that all base classes or elements of the mro of type are
104 able to be cached. This function is called after the base
105 classes or mro of the type are altered.
Christian Heimesa62da1d2008-01-12 19:39:10 +0000106
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000107 Unset HAVE_VERSION_TAG and VALID_VERSION_TAG if the type
108 inherits from an old-style class, either directly or if it
109 appears in the MRO of a new-style class. No support either for
110 custom MROs that include types that are not officially super
111 types.
Christian Heimesa62da1d2008-01-12 19:39:10 +0000112
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000113 Called from mro_internal, which will subsequently be called on
114 each subclass when their mro is recursively updated.
115 */
116 Py_ssize_t i, n;
117 int clear = 0;
Christian Heimesa62da1d2008-01-12 19:39:10 +0000118
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000119 if (!PyType_HasFeature(type, Py_TPFLAGS_HAVE_VERSION_TAG))
120 return;
Christian Heimesa62da1d2008-01-12 19:39:10 +0000121
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000122 n = PyTuple_GET_SIZE(bases);
123 for (i = 0; i < n; i++) {
124 PyObject *b = PyTuple_GET_ITEM(bases, i);
125 PyTypeObject *cls;
Christian Heimesa62da1d2008-01-12 19:39:10 +0000126
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000127 if (!PyType_Check(b) ) {
128 clear = 1;
129 break;
130 }
Christian Heimesa62da1d2008-01-12 19:39:10 +0000131
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000132 cls = (PyTypeObject *)b;
Christian Heimesa62da1d2008-01-12 19:39:10 +0000133
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000134 if (!PyType_HasFeature(cls, Py_TPFLAGS_HAVE_VERSION_TAG) ||
135 !PyType_IsSubtype(type, cls)) {
136 clear = 1;
137 break;
138 }
139 }
Christian Heimesa62da1d2008-01-12 19:39:10 +0000140
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000141 if (clear)
142 type->tp_flags &= ~(Py_TPFLAGS_HAVE_VERSION_TAG|
143 Py_TPFLAGS_VALID_VERSION_TAG);
Christian Heimesa62da1d2008-01-12 19:39:10 +0000144}
145
146static int
147assign_version_tag(PyTypeObject *type)
148{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000149 /* Ensure that the tp_version_tag is valid and set
150 Py_TPFLAGS_VALID_VERSION_TAG. To respect the invariant, this
151 must first be done on all super classes. Return 0 if this
152 cannot be done, 1 if Py_TPFLAGS_VALID_VERSION_TAG.
153 */
154 Py_ssize_t i, n;
155 PyObject *bases;
Christian Heimesa62da1d2008-01-12 19:39:10 +0000156
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000157 if (PyType_HasFeature(type, Py_TPFLAGS_VALID_VERSION_TAG))
158 return 1;
159 if (!PyType_HasFeature(type, Py_TPFLAGS_HAVE_VERSION_TAG))
160 return 0;
161 if (!PyType_HasFeature(type, Py_TPFLAGS_READY))
162 return 0;
Christian Heimesa62da1d2008-01-12 19:39:10 +0000163
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000164 type->tp_version_tag = next_version_tag++;
165 /* for stress-testing: next_version_tag &= 0xFF; */
Christian Heimesa62da1d2008-01-12 19:39:10 +0000166
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000167 if (type->tp_version_tag == 0) {
168 /* wrap-around or just starting Python - clear the whole
169 cache by filling names with references to Py_None.
170 Values are also set to NULL for added protection, as they
171 are borrowed reference */
172 for (i = 0; i < (1 << MCACHE_SIZE_EXP); i++) {
173 method_cache[i].value = NULL;
174 Py_XDECREF(method_cache[i].name);
175 method_cache[i].name = Py_None;
176 Py_INCREF(Py_None);
177 }
178 /* mark all version tags as invalid */
179 PyType_Modified(&PyBaseObject_Type);
180 return 1;
181 }
182 bases = type->tp_bases;
183 n = PyTuple_GET_SIZE(bases);
184 for (i = 0; i < n; i++) {
185 PyObject *b = PyTuple_GET_ITEM(bases, i);
186 assert(PyType_Check(b));
187 if (!assign_version_tag((PyTypeObject *)b))
188 return 0;
189 }
190 type->tp_flags |= Py_TPFLAGS_VALID_VERSION_TAG;
191 return 1;
Christian Heimesa62da1d2008-01-12 19:39:10 +0000192}
193
194
Guido van Rossum6f799372001-09-20 20:46:19 +0000195static PyMemberDef type_members[] = {
Benjamin Peterson0e102062010-08-25 23:13:17 +0000196 {"__basicsize__", T_PYSSIZET, offsetof(PyTypeObject,tp_basicsize),READONLY},
197 {"__itemsize__", T_PYSSIZET, offsetof(PyTypeObject, tp_itemsize), READONLY},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000198 {"__flags__", T_LONG, offsetof(PyTypeObject, tp_flags), READONLY},
199 {"__weakrefoffset__", T_LONG,
200 offsetof(PyTypeObject, tp_weaklistoffset), READONLY},
201 {"__base__", T_OBJECT, offsetof(PyTypeObject, tp_base), READONLY},
202 {"__dictoffset__", T_LONG,
203 offsetof(PyTypeObject, tp_dictoffset), READONLY},
204 {"__mro__", T_OBJECT, offsetof(PyTypeObject, tp_mro), READONLY},
205 {0}
Tim Peters6d6c1a32001-08-02 04:15:00 +0000206};
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000207
Benjamin Petersond9f23d22011-08-17 11:54:03 -0500208static int
209check_set_special_type_attr(PyTypeObject *type, PyObject *value, const char *name)
210{
211 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
212 PyErr_Format(PyExc_TypeError,
213 "can't set %s.%s", type->tp_name, name);
214 return 0;
215 }
216 if (!value) {
217 PyErr_Format(PyExc_TypeError,
218 "can't delete %s.%s", type->tp_name, name);
219 return 0;
220 }
221 return 1;
222}
223
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000224static PyObject *
Guido van Rossumc3542212001-08-16 09:18:56 +0000225type_name(PyTypeObject *type, void *context)
226{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000227 const char *s;
Guido van Rossumc3542212001-08-16 09:18:56 +0000228
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000229 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
230 PyHeapTypeObject* et = (PyHeapTypeObject*)type;
Tim Petersea7f75d2002-12-07 21:39:16 +0000231
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000232 Py_INCREF(et->ht_name);
233 return et->ht_name;
234 }
235 else {
236 s = strrchr(type->tp_name, '.');
237 if (s == NULL)
238 s = type->tp_name;
239 else
240 s++;
241 return PyUnicode_FromString(s);
242 }
Guido van Rossumc3542212001-08-16 09:18:56 +0000243}
244
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100245static PyObject *
246type_qualname(PyTypeObject *type, void *context)
247{
248 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
249 PyHeapTypeObject* et = (PyHeapTypeObject*)type;
250 Py_INCREF(et->ht_qualname);
251 return et->ht_qualname;
252 }
253 else {
254 return type_name(type, context);
255 }
256}
257
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000258static int
259type_set_name(PyTypeObject *type, PyObject *value, void *context)
260{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000261 PyHeapTypeObject* et;
262 char *tp_name;
263 PyObject *tmp;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000264
Benjamin Petersond9f23d22011-08-17 11:54:03 -0500265 if (!check_set_special_type_attr(type, value, "__name__"))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000266 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000267 if (!PyUnicode_Check(value)) {
268 PyErr_Format(PyExc_TypeError,
269 "can only assign string to %s.__name__, not '%s'",
270 type->tp_name, Py_TYPE(value)->tp_name);
271 return -1;
272 }
Guido van Rossume845c0f2007-11-02 23:07:07 +0000273
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000274 /* Check absence of null characters */
275 tmp = PyUnicode_FromStringAndSize("\0", 1);
276 if (tmp == NULL)
277 return -1;
278 if (PyUnicode_Contains(value, tmp) != 0) {
279 Py_DECREF(tmp);
280 PyErr_Format(PyExc_ValueError,
281 "__name__ must not contain null bytes");
282 return -1;
283 }
284 Py_DECREF(tmp);
Guido van Rossume845c0f2007-11-02 23:07:07 +0000285
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000286 tp_name = _PyUnicode_AsString(value);
287 if (tp_name == NULL)
288 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000289
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000290 et = (PyHeapTypeObject*)type;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000291
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000292 Py_INCREF(value);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000293
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000294 Py_DECREF(et->ht_name);
295 et->ht_name = value;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000296
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000297 type->tp_name = tp_name;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000298
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000299 return 0;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000300}
301
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100302static int
303type_set_qualname(PyTypeObject *type, PyObject *value, void *context)
304{
305 PyHeapTypeObject* et;
306
307 if (!PyUnicode_Check(value)) {
308 PyErr_Format(PyExc_TypeError,
309 "can only assign string to %s.__qualname__, not '%s'",
310 type->tp_name, Py_TYPE(value)->tp_name);
311 return -1;
312 }
313
314 et = (PyHeapTypeObject*)type;
315 Py_INCREF(value);
316 Py_DECREF(et->ht_qualname);
317 et->ht_qualname = value;
318 return 0;
319}
320
Guido van Rossumc3542212001-08-16 09:18:56 +0000321static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000322type_module(PyTypeObject *type, void *context)
Guido van Rossum29ca26e1995-01-07 11:58:15 +0000323{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000324 PyObject *mod;
325 char *s;
Guido van Rossumc3542212001-08-16 09:18:56 +0000326
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000327 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
328 mod = PyDict_GetItemString(type->tp_dict, "__module__");
329 if (!mod) {
330 PyErr_Format(PyExc_AttributeError, "__module__");
331 return 0;
332 }
333 Py_XINCREF(mod);
334 return mod;
335 }
336 else {
337 s = strrchr(type->tp_name, '.');
338 if (s != NULL)
339 return PyUnicode_FromStringAndSize(
340 type->tp_name, (Py_ssize_t)(s - type->tp_name));
341 return PyUnicode_FromString("builtins");
342 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000343}
344
Guido van Rossum3926a632001-09-25 16:25:58 +0000345static int
346type_set_module(PyTypeObject *type, PyObject *value, void *context)
347{
Benjamin Petersond9f23d22011-08-17 11:54:03 -0500348 if (!check_set_special_type_attr(type, value, "__module__"))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000349 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000350
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000351 PyType_Modified(type);
Christian Heimesa62da1d2008-01-12 19:39:10 +0000352
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000353 return PyDict_SetItemString(type->tp_dict, "__module__", value);
Guido van Rossum3926a632001-09-25 16:25:58 +0000354}
355
Tim Peters6d6c1a32001-08-02 04:15:00 +0000356static PyObject *
Christian Heimes9e7f1d22008-02-28 12:27:11 +0000357type_abstractmethods(PyTypeObject *type, void *context)
358{
Benjamin Petersonaec5fd12010-10-02 00:03:31 +0000359 PyObject *mod = NULL;
Benjamin Peterson84060b82010-10-03 02:13:39 +0000360 /* type itself has an __abstractmethods__ descriptor (this). Don't return
361 that. */
Benjamin Petersonaec5fd12010-10-02 00:03:31 +0000362 if (type != &PyType_Type)
363 mod = PyDict_GetItemString(type->tp_dict, "__abstractmethods__");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000364 if (!mod) {
Benjamin Peterson23b628e2011-01-12 18:56:07 +0000365 PyErr_SetString(PyExc_AttributeError, "__abstractmethods__");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000366 return NULL;
367 }
368 Py_XINCREF(mod);
369 return mod;
Christian Heimes9e7f1d22008-02-28 12:27:11 +0000370}
371
372static int
373type_set_abstractmethods(PyTypeObject *type, PyObject *value, void *context)
374{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000375 /* __abstractmethods__ should only be set once on a type, in
376 abc.ABCMeta.__new__, so this function doesn't do anything
377 special to update subclasses.
378 */
Benjamin Peterson477ba912011-01-12 15:34:01 +0000379 int res;
380 if (value != NULL) {
381 res = PyDict_SetItemString(type->tp_dict, "__abstractmethods__", value);
382 }
383 else {
384 res = PyDict_DelItemString(type->tp_dict, "__abstractmethods__");
385 if (res && PyErr_ExceptionMatches(PyExc_KeyError)) {
Benjamin Peterson23b628e2011-01-12 18:56:07 +0000386 PyErr_SetString(PyExc_AttributeError, "__abstractmethods__");
Benjamin Peterson477ba912011-01-12 15:34:01 +0000387 return -1;
388 }
389 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000390 if (res == 0) {
391 PyType_Modified(type);
392 if (value && PyObject_IsTrue(value)) {
393 type->tp_flags |= Py_TPFLAGS_IS_ABSTRACT;
394 }
395 else {
396 type->tp_flags &= ~Py_TPFLAGS_IS_ABSTRACT;
397 }
398 }
399 return res;
Christian Heimes9e7f1d22008-02-28 12:27:11 +0000400}
401
402static PyObject *
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000403type_get_bases(PyTypeObject *type, void *context)
404{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000405 Py_INCREF(type->tp_bases);
406 return type->tp_bases;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000407}
408
409static PyTypeObject *best_base(PyObject *);
410static int mro_internal(PyTypeObject *);
411static int compatible_for_assignment(PyTypeObject *, PyTypeObject *, char *);
412static int add_subclass(PyTypeObject*, PyTypeObject*);
413static void remove_subclass(PyTypeObject *, PyTypeObject *);
414static void update_all_slots(PyTypeObject *);
415
Guido van Rossum8d24ee92003-03-24 23:49:49 +0000416typedef int (*update_callback)(PyTypeObject *, void *);
417static int update_subclasses(PyTypeObject *type, PyObject *name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000418 update_callback callback, void *data);
Guido van Rossum8d24ee92003-03-24 23:49:49 +0000419static int recurse_down_subclasses(PyTypeObject *type, PyObject *name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000420 update_callback callback, void *data);
Guido van Rossum8d24ee92003-03-24 23:49:49 +0000421
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000422static int
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000423mro_subclasses(PyTypeObject *type, PyObject* temp)
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000424{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000425 PyTypeObject *subclass;
426 PyObject *ref, *subclasses, *old_mro;
427 Py_ssize_t i, n;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000428
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000429 subclasses = type->tp_subclasses;
430 if (subclasses == NULL)
431 return 0;
432 assert(PyList_Check(subclasses));
433 n = PyList_GET_SIZE(subclasses);
434 for (i = 0; i < n; i++) {
435 ref = PyList_GET_ITEM(subclasses, i);
436 assert(PyWeakref_CheckRef(ref));
437 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
438 assert(subclass != NULL);
439 if ((PyObject *)subclass == Py_None)
440 continue;
441 assert(PyType_Check(subclass));
442 old_mro = subclass->tp_mro;
443 if (mro_internal(subclass) < 0) {
444 subclass->tp_mro = old_mro;
445 return -1;
446 }
447 else {
448 PyObject* tuple;
449 tuple = PyTuple_Pack(2, subclass, old_mro);
450 Py_DECREF(old_mro);
451 if (!tuple)
452 return -1;
453 if (PyList_Append(temp, tuple) < 0)
454 return -1;
455 Py_DECREF(tuple);
456 }
457 if (mro_subclasses(subclass, temp) < 0)
458 return -1;
459 }
460 return 0;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000461}
462
463static int
464type_set_bases(PyTypeObject *type, PyObject *value, void *context)
465{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000466 Py_ssize_t i;
467 int r = 0;
468 PyObject *ob, *temp;
469 PyTypeObject *new_base, *old_base;
470 PyObject *old_bases, *old_mro;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000471
Benjamin Petersond9f23d22011-08-17 11:54:03 -0500472 if (!check_set_special_type_attr(type, value, "__bases__"))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000473 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000474 if (!PyTuple_Check(value)) {
475 PyErr_Format(PyExc_TypeError,
476 "can only assign tuple to %s.__bases__, not %s",
477 type->tp_name, Py_TYPE(value)->tp_name);
478 return -1;
479 }
480 if (PyTuple_GET_SIZE(value) == 0) {
481 PyErr_Format(PyExc_TypeError,
482 "can only assign non-empty tuple to %s.__bases__, not ()",
483 type->tp_name);
484 return -1;
485 }
486 for (i = 0; i < PyTuple_GET_SIZE(value); i++) {
487 ob = PyTuple_GET_ITEM(value, i);
488 if (!PyType_Check(ob)) {
489 PyErr_Format(
490 PyExc_TypeError,
491 "%s.__bases__ must be tuple of old- or new-style classes, not '%s'",
492 type->tp_name, Py_TYPE(ob)->tp_name);
493 return -1;
494 }
495 if (PyType_Check(ob)) {
496 if (PyType_IsSubtype((PyTypeObject*)ob, type)) {
497 PyErr_SetString(PyExc_TypeError,
498 "a __bases__ item causes an inheritance cycle");
499 return -1;
500 }
501 }
502 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000503
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000504 new_base = best_base(value);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000505
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000506 if (!new_base) {
507 return -1;
508 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000509
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000510 if (!compatible_for_assignment(type->tp_base, new_base, "__bases__"))
511 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000512
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000513 Py_INCREF(new_base);
514 Py_INCREF(value);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000515
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000516 old_bases = type->tp_bases;
517 old_base = type->tp_base;
518 old_mro = type->tp_mro;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000519
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000520 type->tp_bases = value;
521 type->tp_base = new_base;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000522
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000523 if (mro_internal(type) < 0) {
524 goto bail;
525 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000526
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000527 temp = PyList_New(0);
528 if (!temp)
529 goto bail;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000530
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000531 r = mro_subclasses(type, temp);
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000532
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000533 if (r < 0) {
534 for (i = 0; i < PyList_Size(temp); i++) {
535 PyTypeObject* cls;
536 PyObject* mro;
537 PyArg_UnpackTuple(PyList_GET_ITEM(temp, i),
538 "", 2, 2, &cls, &mro);
539 Py_INCREF(mro);
540 ob = cls->tp_mro;
541 cls->tp_mro = mro;
542 Py_DECREF(ob);
543 }
544 Py_DECREF(temp);
545 goto bail;
546 }
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000547
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000548 Py_DECREF(temp);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000549
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000550 /* any base that was in __bases__ but now isn't, we
551 need to remove |type| from its tp_subclasses.
552 conversely, any class now in __bases__ that wasn't
553 needs to have |type| added to its subclasses. */
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000554
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000555 /* for now, sod that: just remove from all old_bases,
556 add to all new_bases */
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000557
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000558 for (i = PyTuple_GET_SIZE(old_bases) - 1; i >= 0; i--) {
559 ob = PyTuple_GET_ITEM(old_bases, i);
560 if (PyType_Check(ob)) {
561 remove_subclass(
562 (PyTypeObject*)ob, type);
563 }
564 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000565
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000566 for (i = PyTuple_GET_SIZE(value) - 1; i >= 0; i--) {
567 ob = PyTuple_GET_ITEM(value, i);
568 if (PyType_Check(ob)) {
569 if (add_subclass((PyTypeObject*)ob, type) < 0)
570 r = -1;
571 }
572 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000573
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000574 update_all_slots(type);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000575
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000576 Py_DECREF(old_bases);
577 Py_DECREF(old_base);
578 Py_DECREF(old_mro);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000579
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000580 return r;
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000581
582 bail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000583 Py_DECREF(type->tp_bases);
584 Py_DECREF(type->tp_base);
585 if (type->tp_mro != old_mro) {
586 Py_DECREF(type->tp_mro);
587 }
Michael W. Hudsone723e452003-08-07 14:58:10 +0000588
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000589 type->tp_bases = old_bases;
590 type->tp_base = old_base;
591 type->tp_mro = old_mro;
Tim Petersea7f75d2002-12-07 21:39:16 +0000592
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000593 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000594}
595
596static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000597type_dict(PyTypeObject *type, void *context)
598{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000599 if (type->tp_dict == NULL) {
600 Py_INCREF(Py_None);
601 return Py_None;
602 }
603 return PyDictProxy_New(type->tp_dict);
Guido van Rossum29ca26e1995-01-07 11:58:15 +0000604}
605
Tim Peters24008312002-03-17 18:56:20 +0000606static PyObject *
607type_get_doc(PyTypeObject *type, void *context)
608{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000609 PyObject *result;
610 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE) && type->tp_doc != NULL)
611 return PyUnicode_FromString(type->tp_doc);
612 result = PyDict_GetItemString(type->tp_dict, "__doc__");
613 if (result == NULL) {
614 result = Py_None;
615 Py_INCREF(result);
616 }
617 else if (Py_TYPE(result)->tp_descr_get) {
618 result = Py_TYPE(result)->tp_descr_get(result, NULL,
619 (PyObject *)type);
620 }
621 else {
622 Py_INCREF(result);
623 }
624 return result;
Tim Peters24008312002-03-17 18:56:20 +0000625}
626
Benjamin Peterson01fc6cd2011-08-17 12:03:47 -0500627static int
628type_set_doc(PyTypeObject *type, PyObject *value, void *context)
629{
630 if (!check_set_special_type_attr(type, value, "__doc__"))
631 return -1;
632 PyType_Modified(type);
633 return PyDict_SetItemString(type->tp_dict, "__doc__", value);
634}
635
Antoine Pitrouec569b72008-08-26 22:40:48 +0000636static PyObject *
637type___instancecheck__(PyObject *type, PyObject *inst)
638{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000639 switch (_PyObject_RealIsInstance(inst, type)) {
640 case -1:
641 return NULL;
642 case 0:
643 Py_RETURN_FALSE;
644 default:
645 Py_RETURN_TRUE;
646 }
Antoine Pitrouec569b72008-08-26 22:40:48 +0000647}
648
649
650static PyObject *
Antoine Pitrouec569b72008-08-26 22:40:48 +0000651type___subclasscheck__(PyObject *type, PyObject *inst)
652{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000653 switch (_PyObject_RealIsSubclass(inst, type)) {
654 case -1:
655 return NULL;
656 case 0:
657 Py_RETURN_FALSE;
658 default:
659 Py_RETURN_TRUE;
660 }
Antoine Pitrouec569b72008-08-26 22:40:48 +0000661}
662
Antoine Pitrouec569b72008-08-26 22:40:48 +0000663
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000664static PyGetSetDef type_getsets[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000665 {"__name__", (getter)type_name, (setter)type_set_name, NULL},
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100666 {"__qualname__", (getter)type_qualname, (setter)type_set_qualname, NULL},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000667 {"__bases__", (getter)type_get_bases, (setter)type_set_bases, NULL},
668 {"__module__", (getter)type_module, (setter)type_set_module, NULL},
669 {"__abstractmethods__", (getter)type_abstractmethods,
670 (setter)type_set_abstractmethods, NULL},
671 {"__dict__", (getter)type_dict, NULL, NULL},
Benjamin Peterson01fc6cd2011-08-17 12:03:47 -0500672 {"__doc__", (getter)type_get_doc, (setter)type_set_doc, NULL},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000673 {0}
Tim Peters6d6c1a32001-08-02 04:15:00 +0000674};
675
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000676static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000677type_repr(PyTypeObject *type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000678{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000679 PyObject *mod, *name, *rtn;
Guido van Rossumc3542212001-08-16 09:18:56 +0000680
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000681 mod = type_module(type, NULL);
682 if (mod == NULL)
683 PyErr_Clear();
684 else if (!PyUnicode_Check(mod)) {
685 Py_DECREF(mod);
686 mod = NULL;
687 }
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100688 name = type_qualname(type, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000689 if (name == NULL)
690 return NULL;
Barry Warsaw7ce36942001-08-24 18:34:26 +0000691
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000692 if (mod != NULL && PyUnicode_CompareWithASCIIString(mod, "builtins"))
693 rtn = PyUnicode_FromFormat("<class '%U.%U'>", mod, name);
694 else
695 rtn = PyUnicode_FromFormat("<class '%s'>", type->tp_name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000696
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000697 Py_XDECREF(mod);
698 Py_DECREF(name);
699 return rtn;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000700}
701
Tim Peters6d6c1a32001-08-02 04:15:00 +0000702static PyObject *
703type_call(PyTypeObject *type, PyObject *args, PyObject *kwds)
704{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000705 PyObject *obj;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000706
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000707 if (type->tp_new == NULL) {
708 PyErr_Format(PyExc_TypeError,
709 "cannot create '%.100s' instances",
710 type->tp_name);
711 return NULL;
712 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000713
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000714 obj = type->tp_new(type, args, kwds);
715 if (obj != NULL) {
716 /* Ugly exception: when the call was type(something),
717 don't call tp_init on the result. */
718 if (type == &PyType_Type &&
719 PyTuple_Check(args) && PyTuple_GET_SIZE(args) == 1 &&
720 (kwds == NULL ||
721 (PyDict_Check(kwds) && PyDict_Size(kwds) == 0)))
722 return obj;
723 /* If the returned object is not an instance of type,
724 it won't be initialized. */
725 if (!PyType_IsSubtype(Py_TYPE(obj), type))
726 return obj;
727 type = Py_TYPE(obj);
728 if (type->tp_init != NULL &&
729 type->tp_init(obj, args, kwds) < 0) {
730 Py_DECREF(obj);
731 obj = NULL;
732 }
733 }
734 return obj;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000735}
736
737PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000738PyType_GenericAlloc(PyTypeObject *type, Py_ssize_t nitems)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000739{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000740 PyObject *obj;
741 const size_t size = _PyObject_VAR_SIZE(type, nitems+1);
742 /* note that we need to add one, for the sentinel */
Tim Peters406fe3b2001-10-06 19:04:01 +0000743
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000744 if (PyType_IS_GC(type))
745 obj = _PyObject_GC_Malloc(size);
746 else
747 obj = (PyObject *)PyObject_MALLOC(size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000748
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000749 if (obj == NULL)
750 return PyErr_NoMemory();
Tim Peters406fe3b2001-10-06 19:04:01 +0000751
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000752 memset(obj, '\0', size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000753
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000754 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
755 Py_INCREF(type);
Tim Peters406fe3b2001-10-06 19:04:01 +0000756
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000757 if (type->tp_itemsize == 0)
758 PyObject_INIT(obj, type);
759 else
760 (void) PyObject_INIT_VAR((PyVarObject *)obj, type, nitems);
Tim Peters406fe3b2001-10-06 19:04:01 +0000761
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000762 if (PyType_IS_GC(type))
763 _PyObject_GC_TRACK(obj);
764 return obj;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000765}
766
767PyObject *
768PyType_GenericNew(PyTypeObject *type, PyObject *args, PyObject *kwds)
769{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000770 return type->tp_alloc(type, 0);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000771}
772
Guido van Rossum9475a232001-10-05 20:51:39 +0000773/* Helpers for subtyping */
774
775static int
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000776traverse_slots(PyTypeObject *type, PyObject *self, visitproc visit, void *arg)
777{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000778 Py_ssize_t i, n;
779 PyMemberDef *mp;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000780
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000781 n = Py_SIZE(type);
782 mp = PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type);
783 for (i = 0; i < n; i++, mp++) {
784 if (mp->type == T_OBJECT_EX) {
785 char *addr = (char *)self + mp->offset;
786 PyObject *obj = *(PyObject **)addr;
787 if (obj != NULL) {
788 int err = visit(obj, arg);
789 if (err)
790 return err;
791 }
792 }
793 }
794 return 0;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000795}
796
797static int
Guido van Rossum9475a232001-10-05 20:51:39 +0000798subtype_traverse(PyObject *self, visitproc visit, void *arg)
799{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000800 PyTypeObject *type, *base;
801 traverseproc basetraverse;
Guido van Rossum9475a232001-10-05 20:51:39 +0000802
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000803 /* Find the nearest base with a different tp_traverse,
804 and traverse slots while we're at it */
805 type = Py_TYPE(self);
806 base = type;
807 while ((basetraverse = base->tp_traverse) == subtype_traverse) {
808 if (Py_SIZE(base)) {
809 int err = traverse_slots(base, self, visit, arg);
810 if (err)
811 return err;
812 }
813 base = base->tp_base;
814 assert(base);
815 }
Guido van Rossum9475a232001-10-05 20:51:39 +0000816
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000817 if (type->tp_dictoffset != base->tp_dictoffset) {
818 PyObject **dictptr = _PyObject_GetDictPtr(self);
819 if (dictptr && *dictptr)
820 Py_VISIT(*dictptr);
821 }
Guido van Rossum9475a232001-10-05 20:51:39 +0000822
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000823 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
824 /* For a heaptype, the instances count as references
825 to the type. Traverse the type so the collector
826 can find cycles involving this link. */
827 Py_VISIT(type);
Guido van Rossuma3862092002-06-10 15:24:42 +0000828
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000829 if (basetraverse)
830 return basetraverse(self, visit, arg);
831 return 0;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000832}
833
834static void
835clear_slots(PyTypeObject *type, PyObject *self)
836{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000837 Py_ssize_t i, n;
838 PyMemberDef *mp;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000839
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000840 n = Py_SIZE(type);
841 mp = PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type);
842 for (i = 0; i < n; i++, mp++) {
843 if (mp->type == T_OBJECT_EX && !(mp->flags & READONLY)) {
844 char *addr = (char *)self + mp->offset;
845 PyObject *obj = *(PyObject **)addr;
846 if (obj != NULL) {
847 *(PyObject **)addr = NULL;
848 Py_DECREF(obj);
849 }
850 }
851 }
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000852}
853
854static int
855subtype_clear(PyObject *self)
856{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000857 PyTypeObject *type, *base;
858 inquiry baseclear;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000859
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000860 /* Find the nearest base with a different tp_clear
861 and clear slots while we're at it */
862 type = Py_TYPE(self);
863 base = type;
864 while ((baseclear = base->tp_clear) == subtype_clear) {
865 if (Py_SIZE(base))
866 clear_slots(base, self);
867 base = base->tp_base;
868 assert(base);
869 }
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000870
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000871 /* There's no need to clear the instance dict (if any);
872 the collector will call its tp_clear handler. */
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000873
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000874 if (baseclear)
875 return baseclear(self);
876 return 0;
Guido van Rossum9475a232001-10-05 20:51:39 +0000877}
Tim Peters6d6c1a32001-08-02 04:15:00 +0000878
879static void
880subtype_dealloc(PyObject *self)
881{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000882 PyTypeObject *type, *base;
883 destructor basedealloc;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000884
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000885 /* Extract the type; we expect it to be a heap type */
886 type = Py_TYPE(self);
887 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000888
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000889 /* Test whether the type has GC exactly once */
Guido van Rossum22b13872002-08-06 21:41:44 +0000890
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000891 if (!PyType_IS_GC(type)) {
892 /* It's really rare to find a dynamic type that doesn't have
893 GC; it can only happen when deriving from 'object' and not
894 adding any slots or instance variables. This allows
895 certain simplifications: there's no need to call
896 clear_slots(), or DECREF the dict, or clear weakrefs. */
Guido van Rossum22b13872002-08-06 21:41:44 +0000897
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000898 /* Maybe call finalizer; exit early if resurrected */
899 if (type->tp_del) {
900 type->tp_del(self);
901 if (self->ob_refcnt > 0)
902 return;
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;
907 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
908 assert(Py_SIZE(base) == 0);
909 base = base->tp_base;
910 assert(base);
911 }
Guido van Rossum22b13872002-08-06 21:41:44 +0000912
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000913 /* Extract the type again; tp_del may have changed it */
914 type = Py_TYPE(self);
Benjamin Peterson193152c2009-04-25 01:08:45 +0000915
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000916 /* Call the base tp_dealloc() */
917 assert(basedealloc);
918 basedealloc(self);
Guido van Rossum22b13872002-08-06 21:41:44 +0000919
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000920 /* Can't reference self beyond this point */
921 Py_DECREF(type);
Guido van Rossum22b13872002-08-06 21:41:44 +0000922
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000923 /* Done */
924 return;
925 }
Guido van Rossum22b13872002-08-06 21:41:44 +0000926
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000927 /* We get here only if the type has GC */
Guido van Rossum22b13872002-08-06 21:41:44 +0000928
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000929 /* UnTrack and re-Track around the trashcan macro, alas */
930 /* See explanation at end of function for full disclosure */
931 PyObject_GC_UnTrack(self);
932 ++_PyTrash_delete_nesting;
933 Py_TRASHCAN_SAFE_BEGIN(self);
934 --_PyTrash_delete_nesting;
935 /* DO NOT restore GC tracking at this point. weakref callbacks
936 * (if any, and whether directly here or indirectly in something we
937 * call) may trigger GC, and if self is tracked at that point, it
938 * will look like trash to GC and GC will try to delete self again.
939 */
Guido van Rossum22b13872002-08-06 21:41:44 +0000940
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000941 /* Find the nearest base with a different tp_dealloc */
942 base = type;
Brett Cannonb94767f2011-02-22 20:15:44 +0000943 while ((/*basedealloc =*/ base->tp_dealloc) == subtype_dealloc) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000944 base = base->tp_base;
945 assert(base);
946 }
Guido van Rossum14227b42001-12-06 02:35:58 +0000947
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000948 /* If we added a weaklist, we clear it. Do this *before* calling
949 the finalizer (__del__), clearing slots, or clearing the instance
950 dict. */
Guido van Rossum59195fd2003-06-13 20:54:40 +0000951
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000952 if (type->tp_weaklistoffset && !base->tp_weaklistoffset)
953 PyObject_ClearWeakRefs(self);
Guido van Rossum1987c662003-05-29 14:29:23 +0000954
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000955 /* Maybe call finalizer; exit early if resurrected */
956 if (type->tp_del) {
957 _PyObject_GC_TRACK(self);
958 type->tp_del(self);
959 if (self->ob_refcnt > 0)
960 goto endlabel; /* resurrected */
961 else
962 _PyObject_GC_UNTRACK(self);
963 /* New weakrefs could be created during the finalizer call.
964 If this occurs, clear them out without calling their
965 finalizers since they might rely on part of the object
966 being finalized that has already been destroyed. */
967 if (type->tp_weaklistoffset && !base->tp_weaklistoffset) {
968 /* Modeled after GET_WEAKREFS_LISTPTR() */
969 PyWeakReference **list = (PyWeakReference **) \
970 PyObject_GET_WEAKREFS_LISTPTR(self);
971 while (*list)
972 _PyWeakref_ClearRef(*list);
973 }
974 }
Guido van Rossum1987c662003-05-29 14:29:23 +0000975
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000976 /* Clear slots up to the nearest base with a different tp_dealloc */
977 base = type;
978 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
979 if (Py_SIZE(base))
980 clear_slots(base, self);
981 base = base->tp_base;
982 assert(base);
983 }
Guido van Rossum59195fd2003-06-13 20:54:40 +0000984
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000985 /* If we added a dict, DECREF it */
986 if (type->tp_dictoffset && !base->tp_dictoffset) {
987 PyObject **dictptr = _PyObject_GetDictPtr(self);
988 if (dictptr != NULL) {
989 PyObject *dict = *dictptr;
990 if (dict != NULL) {
991 Py_DECREF(dict);
992 *dictptr = NULL;
993 }
994 }
995 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000996
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000997 /* Extract the type again; tp_del may have changed it */
998 type = Py_TYPE(self);
Benjamin Peterson193152c2009-04-25 01:08:45 +0000999
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001000 /* Call the base tp_dealloc(); first retrack self if
1001 * basedealloc knows about gc.
1002 */
1003 if (PyType_IS_GC(base))
1004 _PyObject_GC_TRACK(self);
1005 assert(basedealloc);
1006 basedealloc(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001007
Antoine Pitrou84f1b172011-07-12 21:57:15 +02001008 PyType_Modified(type);
1009
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001010 /* Can't reference self beyond this point */
1011 Py_DECREF(type);
Guido van Rossum22b13872002-08-06 21:41:44 +00001012
Guido van Rossum0906e072002-08-07 20:42:09 +00001013 endlabel:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001014 ++_PyTrash_delete_nesting;
1015 Py_TRASHCAN_SAFE_END(self);
1016 --_PyTrash_delete_nesting;
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001017
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001018 /* Explanation of the weirdness around the trashcan macros:
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001019
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001020 Q. What do the trashcan macros do?
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001021
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001022 A. Read the comment titled "Trashcan mechanism" in object.h.
1023 For one, this explains why there must be a call to GC-untrack
1024 before the trashcan begin macro. Without understanding the
1025 trashcan code, the answers to the following questions don't make
1026 sense.
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001027
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001028 Q. Why do we GC-untrack before the trashcan and then immediately
1029 GC-track again afterward?
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001030
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001031 A. In the case that the base class is GC-aware, the base class
1032 probably GC-untracks the object. If it does that using the
1033 UNTRACK macro, this will crash when the object is already
1034 untracked. Because we don't know what the base class does, the
1035 only safe thing is to make sure the object is tracked when we
1036 call the base class dealloc. But... The trashcan begin macro
1037 requires that the object is *untracked* before it is called. So
1038 the dance becomes:
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001039
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001040 GC untrack
1041 trashcan begin
1042 GC track
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001043
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001044 Q. Why did the last question say "immediately GC-track again"?
1045 It's nowhere near immediately.
Tim Petersf7f9e992003-11-13 21:59:32 +00001046
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001047 A. Because the code *used* to re-track immediately. Bad Idea.
1048 self has a refcount of 0, and if gc ever gets its hands on it
1049 (which can happen if any weakref callback gets invoked), it
1050 looks like trash to gc too, and gc also tries to delete self
Ezio Melotti13925002011-03-16 11:05:33 +02001051 then. But we're already deleting self. Double deallocation is
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001052 a subtle disaster.
Tim Petersf7f9e992003-11-13 21:59:32 +00001053
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001054 Q. Why the bizarre (net-zero) manipulation of
1055 _PyTrash_delete_nesting around the trashcan macros?
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001056
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001057 A. Some base classes (e.g. list) also use the trashcan mechanism.
1058 The following scenario used to be possible:
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001059
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001060 - suppose the trashcan level is one below the trashcan limit
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001061
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001062 - subtype_dealloc() is called
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001063
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001064 - the trashcan limit is not yet reached, so the trashcan level
1065 is incremented and the code between trashcan begin and end is
1066 executed
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001067
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001068 - this destroys much of the object's contents, including its
1069 slots and __dict__
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001070
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001071 - basedealloc() is called; this is really list_dealloc(), or
1072 some other type which also uses the trashcan macros
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001073
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001074 - the trashcan limit is now reached, so the object is put on the
1075 trashcan's to-be-deleted-later list
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001076
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001077 - basedealloc() returns
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001078
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001079 - subtype_dealloc() decrefs the object's type
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001080
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001081 - subtype_dealloc() returns
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001082
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001083 - later, the trashcan code starts deleting the objects from its
1084 to-be-deleted-later list
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001085
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001086 - subtype_dealloc() is called *AGAIN* for the same object
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001087
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001088 - at the very least (if the destroyed slots and __dict__ don't
1089 cause problems) the object's type gets decref'ed a second
1090 time, which is *BAD*!!!
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001091
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001092 The remedy is to make sure that if the code between trashcan
1093 begin and end in subtype_dealloc() is called, the code between
1094 trashcan begin and end in basedealloc() will also be called.
1095 This is done by decrementing the level after passing into the
1096 trashcan block, and incrementing it just before leaving the
1097 block.
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001098
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001099 But now it's possible that a chain of objects consisting solely
1100 of objects whose deallocator is subtype_dealloc() will defeat
1101 the trashcan mechanism completely: the decremented level means
1102 that the effective level never reaches the limit. Therefore, we
1103 *increment* the level *before* entering the trashcan block, and
1104 matchingly decrement it after leaving. This means the trashcan
1105 code will trigger a little early, but that's no big deal.
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001106
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001107 Q. Are there any live examples of code in need of all this
1108 complexity?
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001109
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001110 A. Yes. See SF bug 668433 for code that crashed (when Python was
1111 compiled in debug mode) before the trashcan level manipulations
1112 were added. For more discussion, see SF patches 581742, 575073
1113 and bug 574207.
1114 */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001115}
1116
Jeremy Hylton938ace62002-07-17 16:30:39 +00001117static PyTypeObject *solid_base(PyTypeObject *type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001118
Tim Peters6d6c1a32001-08-02 04:15:00 +00001119/* type test with subclassing support */
1120
1121int
1122PyType_IsSubtype(PyTypeObject *a, PyTypeObject *b)
1123{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001124 PyObject *mro;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001125
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001126 mro = a->tp_mro;
1127 if (mro != NULL) {
1128 /* Deal with multiple inheritance without recursion
1129 by walking the MRO tuple */
1130 Py_ssize_t i, n;
1131 assert(PyTuple_Check(mro));
1132 n = PyTuple_GET_SIZE(mro);
1133 for (i = 0; i < n; i++) {
1134 if (PyTuple_GET_ITEM(mro, i) == (PyObject *)b)
1135 return 1;
1136 }
1137 return 0;
1138 }
1139 else {
1140 /* a is not completely initilized yet; follow tp_base */
1141 do {
1142 if (a == b)
1143 return 1;
1144 a = a->tp_base;
1145 } while (a != NULL);
1146 return b == &PyBaseObject_Type;
1147 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001148}
1149
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001150/* Internal routines to do a method lookup in the type
Guido van Rossum60718732001-08-28 17:47:51 +00001151 without looking in the instance dictionary
1152 (so we can't use PyObject_GetAttr) but still binding
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001153 it to the instance. The arguments are the object,
Guido van Rossum60718732001-08-28 17:47:51 +00001154 the method name as a C string, and the address of a
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001155 static variable used to cache the interned Python string.
1156
1157 Two variants:
1158
1159 - lookup_maybe() returns NULL without raising an exception
1160 when the _PyType_Lookup() call fails;
1161
1162 - lookup_method() always raises an exception upon errors.
Benjamin Peterson224205f2009-05-08 03:25:19 +00001163
1164 - _PyObject_LookupSpecial() exported for the benefit of other places.
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001165*/
Guido van Rossum60718732001-08-28 17:47:51 +00001166
1167static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001168lookup_maybe(PyObject *self, char *attrstr, PyObject **attrobj)
Guido van Rossum60718732001-08-28 17:47:51 +00001169{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001170 PyObject *res;
Guido van Rossum60718732001-08-28 17:47:51 +00001171
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001172 if (*attrobj == NULL) {
1173 *attrobj = PyUnicode_InternFromString(attrstr);
1174 if (*attrobj == NULL)
1175 return NULL;
1176 }
1177 res = _PyType_Lookup(Py_TYPE(self), *attrobj);
1178 if (res != NULL) {
1179 descrgetfunc f;
1180 if ((f = Py_TYPE(res)->tp_descr_get) == NULL)
1181 Py_INCREF(res);
1182 else
1183 res = f(res, self, (PyObject *)(Py_TYPE(self)));
1184 }
1185 return res;
Guido van Rossum60718732001-08-28 17:47:51 +00001186}
1187
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001188static PyObject *
1189lookup_method(PyObject *self, char *attrstr, PyObject **attrobj)
1190{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001191 PyObject *res = lookup_maybe(self, attrstr, attrobj);
1192 if (res == NULL && !PyErr_Occurred())
1193 PyErr_SetObject(PyExc_AttributeError, *attrobj);
1194 return res;
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001195}
1196
Benjamin Peterson224205f2009-05-08 03:25:19 +00001197PyObject *
1198_PyObject_LookupSpecial(PyObject *self, char *attrstr, PyObject **attrobj)
1199{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001200 return lookup_maybe(self, attrstr, attrobj);
Benjamin Peterson224205f2009-05-08 03:25:19 +00001201}
1202
Guido van Rossum2730b132001-08-28 18:22:14 +00001203/* A variation of PyObject_CallMethod that uses lookup_method()
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001204 instead of PyObject_GetAttrString(). This uses the same convention
Guido van Rossum2730b132001-08-28 18:22:14 +00001205 as lookup_method to cache the interned name string object. */
1206
Neil Schemenauerf23473f2001-10-21 22:28:58 +00001207static PyObject *
Guido van Rossum2730b132001-08-28 18:22:14 +00001208call_method(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 Rossum2730b132001-08-28 18:22:14 +00001213
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001214 func = lookup_maybe(o, name, nameobj);
1215 if (func == NULL) {
1216 va_end(va);
1217 if (!PyErr_Occurred())
1218 PyErr_SetObject(PyExc_AttributeError, *nameobj);
1219 return NULL;
1220 }
Guido van Rossumf21c6be2001-09-14 17:51:50 +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 Rossumf21c6be2001-09-14 17:51:50 +00001226
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001227 va_end(va);
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001228
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001229 if (args == NULL)
1230 return NULL;
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001231
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001232 assert(PyTuple_Check(args));
1233 retval = PyObject_Call(func, args, NULL);
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001234
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001235 Py_DECREF(args);
1236 Py_DECREF(func);
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001237
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001238 return retval;
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001239}
1240
1241/* Clone of call_method() that returns NotImplemented when the lookup fails. */
1242
Neil Schemenauerf23473f2001-10-21 22:28:58 +00001243static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001244call_maybe(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
1245{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001246 va_list va;
1247 PyObject *args, *func = 0, *retval;
1248 va_start(va, format);
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001249
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001250 func = lookup_maybe(o, name, nameobj);
1251 if (func == NULL) {
1252 va_end(va);
Brian Curtindfc80e32011-08-10 20:28:54 -05001253 if (!PyErr_Occurred())
1254 Py_RETURN_NOTIMPLEMENTED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001255 return NULL;
1256 }
Guido van Rossum2730b132001-08-28 18:22:14 +00001257
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001258 if (format && *format)
1259 args = Py_VaBuildValue(format, va);
1260 else
1261 args = PyTuple_New(0);
Guido van Rossum2730b132001-08-28 18:22:14 +00001262
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001263 va_end(va);
Guido van Rossum2730b132001-08-28 18:22:14 +00001264
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001265 if (args == NULL)
1266 return NULL;
Guido van Rossum2730b132001-08-28 18:22:14 +00001267
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001268 assert(PyTuple_Check(args));
1269 retval = PyObject_Call(func, args, NULL);
Guido van Rossum2730b132001-08-28 18:22:14 +00001270
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001271 Py_DECREF(args);
1272 Py_DECREF(func);
Guido van Rossum2730b132001-08-28 18:22:14 +00001273
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001274 return retval;
Guido van Rossum2730b132001-08-28 18:22:14 +00001275}
1276
Tim Petersea7f75d2002-12-07 21:39:16 +00001277/*
Guido van Rossum1f121312002-11-14 19:49:16 +00001278 Method resolution order algorithm C3 described in
1279 "A Monotonic Superclass Linearization for Dylan",
1280 by Kim Barrett, Bob Cassel, Paul Haahr,
Tim Petersea7f75d2002-12-07 21:39:16 +00001281 David A. Moon, Keith Playford, and P. Tucker Withington.
Guido van Rossum1f121312002-11-14 19:49:16 +00001282 (OOPSLA 1996)
1283
Guido van Rossum98f33732002-11-25 21:36:54 +00001284 Some notes about the rules implied by C3:
1285
Tim Petersea7f75d2002-12-07 21:39:16 +00001286 No duplicate bases.
Guido van Rossum98f33732002-11-25 21:36:54 +00001287 It isn't legal to repeat a class in a list of base classes.
1288
1289 The next three properties are the 3 constraints in "C3".
1290
Tim Petersea7f75d2002-12-07 21:39:16 +00001291 Local precendece order.
Guido van Rossum98f33732002-11-25 21:36:54 +00001292 If A precedes B in C's MRO, then A will precede B in the MRO of all
1293 subclasses of C.
1294
1295 Monotonicity.
1296 The MRO of a class must be an extension without reordering of the
1297 MRO of each of its superclasses.
1298
1299 Extended Precedence Graph (EPG).
1300 Linearization is consistent if there is a path in the EPG from
1301 each class to all its successors in the linearization. See
1302 the paper for definition of EPG.
Guido van Rossum1f121312002-11-14 19:49:16 +00001303 */
1304
Tim Petersea7f75d2002-12-07 21:39:16 +00001305static int
Guido van Rossum1f121312002-11-14 19:49:16 +00001306tail_contains(PyObject *list, int whence, PyObject *o) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001307 Py_ssize_t j, size;
1308 size = PyList_GET_SIZE(list);
Guido van Rossum1f121312002-11-14 19:49:16 +00001309
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001310 for (j = whence+1; j < size; j++) {
1311 if (PyList_GET_ITEM(list, j) == o)
1312 return 1;
1313 }
1314 return 0;
Guido van Rossum1f121312002-11-14 19:49:16 +00001315}
1316
Guido van Rossum98f33732002-11-25 21:36:54 +00001317static PyObject *
1318class_name(PyObject *cls)
1319{
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001320 _Py_IDENTIFIER(__name__);
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001321 PyObject *name = _PyObject_GetAttrId(cls, &PyId___name__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001322 if (name == NULL) {
1323 PyErr_Clear();
1324 Py_XDECREF(name);
1325 name = PyObject_Repr(cls);
1326 }
1327 if (name == NULL)
1328 return NULL;
1329 if (!PyUnicode_Check(name)) {
1330 Py_DECREF(name);
1331 return NULL;
1332 }
1333 return name;
Guido van Rossum98f33732002-11-25 21:36:54 +00001334}
1335
1336static int
1337check_duplicates(PyObject *list)
1338{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001339 Py_ssize_t i, j, n;
1340 /* Let's use a quadratic time algorithm,
1341 assuming that the bases lists is short.
1342 */
1343 n = PyList_GET_SIZE(list);
1344 for (i = 0; i < n; i++) {
1345 PyObject *o = PyList_GET_ITEM(list, i);
1346 for (j = i + 1; j < n; j++) {
1347 if (PyList_GET_ITEM(list, j) == o) {
1348 o = class_name(o);
1349 if (o != NULL) {
1350 PyErr_Format(PyExc_TypeError,
1351 "duplicate base class %U",
1352 o);
1353 Py_DECREF(o);
1354 } else {
1355 PyErr_SetString(PyExc_TypeError,
1356 "duplicate base class");
1357 }
1358 return -1;
1359 }
1360 }
1361 }
1362 return 0;
Guido van Rossum98f33732002-11-25 21:36:54 +00001363}
1364
1365/* Raise a TypeError for an MRO order disagreement.
1366
1367 It's hard to produce a good error message. In the absence of better
1368 insight into error reporting, report the classes that were candidates
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001369 to be put next into the MRO. There is some conflict between the
Guido van Rossum98f33732002-11-25 21:36:54 +00001370 order in which they should be put in the MRO, but it's hard to
1371 diagnose what constraint can't be satisfied.
1372*/
1373
1374static void
1375set_mro_error(PyObject *to_merge, int *remain)
1376{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001377 Py_ssize_t i, n, off, to_merge_size;
1378 char buf[1000];
1379 PyObject *k, *v;
1380 PyObject *set = PyDict_New();
1381 if (!set) return;
Guido van Rossum98f33732002-11-25 21:36:54 +00001382
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001383 to_merge_size = PyList_GET_SIZE(to_merge);
1384 for (i = 0; i < to_merge_size; i++) {
1385 PyObject *L = PyList_GET_ITEM(to_merge, i);
1386 if (remain[i] < PyList_GET_SIZE(L)) {
1387 PyObject *c = PyList_GET_ITEM(L, remain[i]);
1388 if (PyDict_SetItem(set, c, Py_None) < 0) {
1389 Py_DECREF(set);
1390 return;
1391 }
1392 }
1393 }
1394 n = PyDict_Size(set);
Guido van Rossum98f33732002-11-25 21:36:54 +00001395
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001396 off = PyOS_snprintf(buf, sizeof(buf), "Cannot create a \
Raymond Hettingerf394df42003-04-06 19:13:41 +00001397consistent method resolution\norder (MRO) for bases");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001398 i = 0;
1399 while (PyDict_Next(set, &i, &k, &v) && (size_t)off < sizeof(buf)) {
1400 PyObject *name = class_name(k);
Victor Stinnere5f99f32010-05-19 01:42:46 +00001401 char *name_str;
1402 if (name != NULL) {
1403 name_str = _PyUnicode_AsString(name);
1404 if (name_str == NULL)
Victor Stinnerba644a62010-05-19 01:50:45 +00001405 name_str = "?";
Victor Stinnere5f99f32010-05-19 01:42:46 +00001406 } else
Victor Stinnerba644a62010-05-19 01:50:45 +00001407 name_str = "?";
Victor Stinnere5f99f32010-05-19 01:42:46 +00001408 off += PyOS_snprintf(buf + off, sizeof(buf) - off, " %s", name_str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001409 Py_XDECREF(name);
1410 if (--n && (size_t)(off+1) < sizeof(buf)) {
1411 buf[off++] = ',';
1412 buf[off] = '\0';
1413 }
1414 }
1415 PyErr_SetString(PyExc_TypeError, buf);
1416 Py_DECREF(set);
Guido van Rossum98f33732002-11-25 21:36:54 +00001417}
1418
Tim Petersea7f75d2002-12-07 21:39:16 +00001419static int
Guido van Rossum1f121312002-11-14 19:49:16 +00001420pmerge(PyObject *acc, PyObject* to_merge) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001421 Py_ssize_t i, j, to_merge_size, empty_cnt;
1422 int *remain;
1423 int ok;
Tim Petersea7f75d2002-12-07 21:39:16 +00001424
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001425 to_merge_size = PyList_GET_SIZE(to_merge);
Guido van Rossum1f121312002-11-14 19:49:16 +00001426
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001427 /* remain stores an index into each sublist of to_merge.
1428 remain[i] is the index of the next base in to_merge[i]
1429 that is not included in acc.
1430 */
1431 remain = (int *)PyMem_MALLOC(SIZEOF_INT*to_merge_size);
1432 if (remain == NULL)
1433 return -1;
1434 for (i = 0; i < to_merge_size; i++)
1435 remain[i] = 0;
Guido van Rossum1f121312002-11-14 19:49:16 +00001436
1437 again:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001438 empty_cnt = 0;
1439 for (i = 0; i < to_merge_size; i++) {
1440 PyObject *candidate;
Tim Petersea7f75d2002-12-07 21:39:16 +00001441
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001442 PyObject *cur_list = PyList_GET_ITEM(to_merge, i);
Guido van Rossum1f121312002-11-14 19:49:16 +00001443
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001444 if (remain[i] >= PyList_GET_SIZE(cur_list)) {
1445 empty_cnt++;
1446 continue;
1447 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001448
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001449 /* Choose next candidate for MRO.
Guido van Rossum98f33732002-11-25 21:36:54 +00001450
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001451 The input sequences alone can determine the choice.
1452 If not, choose the class which appears in the MRO
1453 of the earliest direct superclass of the new class.
1454 */
Guido van Rossum98f33732002-11-25 21:36:54 +00001455
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001456 candidate = PyList_GET_ITEM(cur_list, remain[i]);
1457 for (j = 0; j < to_merge_size; j++) {
1458 PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
1459 if (tail_contains(j_lst, remain[j], candidate)) {
1460 goto skip; /* continue outer loop */
1461 }
1462 }
1463 ok = PyList_Append(acc, candidate);
1464 if (ok < 0) {
1465 PyMem_Free(remain);
1466 return -1;
1467 }
1468 for (j = 0; j < to_merge_size; j++) {
1469 PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
1470 if (remain[j] < PyList_GET_SIZE(j_lst) &&
1471 PyList_GET_ITEM(j_lst, remain[j]) == candidate) {
1472 remain[j]++;
1473 }
1474 }
1475 goto again;
1476 skip: ;
1477 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001478
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001479 if (empty_cnt == to_merge_size) {
1480 PyMem_FREE(remain);
1481 return 0;
1482 }
1483 set_mro_error(to_merge, remain);
1484 PyMem_FREE(remain);
1485 return -1;
Guido van Rossum1f121312002-11-14 19:49:16 +00001486}
1487
Tim Peters6d6c1a32001-08-02 04:15:00 +00001488static PyObject *
1489mro_implementation(PyTypeObject *type)
1490{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001491 Py_ssize_t i, n;
1492 int ok;
1493 PyObject *bases, *result;
1494 PyObject *to_merge, *bases_aslist;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001495
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001496 if (type->tp_dict == NULL) {
1497 if (PyType_Ready(type) < 0)
1498 return NULL;
1499 }
Guido van Rossum63517572002-06-18 16:44:57 +00001500
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001501 /* Find a superclass linearization that honors the constraints
1502 of the explicit lists of bases and the constraints implied by
1503 each base class.
Guido van Rossum98f33732002-11-25 21:36:54 +00001504
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001505 to_merge is a list of lists, where each list is a superclass
1506 linearization implied by a base class. The last element of
1507 to_merge is the declared list of bases.
1508 */
Guido van Rossum98f33732002-11-25 21:36:54 +00001509
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001510 bases = type->tp_bases;
1511 n = PyTuple_GET_SIZE(bases);
Guido van Rossum1f121312002-11-14 19:49:16 +00001512
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001513 to_merge = PyList_New(n+1);
1514 if (to_merge == NULL)
1515 return NULL;
Guido van Rossum1f121312002-11-14 19:49:16 +00001516
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001517 for (i = 0; i < n; i++) {
1518 PyObject *base = PyTuple_GET_ITEM(bases, i);
1519 PyObject *parentMRO;
1520 parentMRO = PySequence_List(((PyTypeObject*)base)->tp_mro);
1521 if (parentMRO == NULL) {
1522 Py_DECREF(to_merge);
1523 return NULL;
1524 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001525
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001526 PyList_SET_ITEM(to_merge, i, parentMRO);
1527 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001528
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001529 bases_aslist = PySequence_List(bases);
1530 if (bases_aslist == NULL) {
1531 Py_DECREF(to_merge);
1532 return NULL;
1533 }
1534 /* This is just a basic sanity check. */
1535 if (check_duplicates(bases_aslist) < 0) {
1536 Py_DECREF(to_merge);
1537 Py_DECREF(bases_aslist);
1538 return NULL;
1539 }
1540 PyList_SET_ITEM(to_merge, n, bases_aslist);
Guido van Rossum1f121312002-11-14 19:49:16 +00001541
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001542 result = Py_BuildValue("[O]", (PyObject *)type);
1543 if (result == NULL) {
1544 Py_DECREF(to_merge);
1545 return NULL;
1546 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001547
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001548 ok = pmerge(result, to_merge);
1549 Py_DECREF(to_merge);
1550 if (ok < 0) {
1551 Py_DECREF(result);
1552 return NULL;
1553 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001554
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001555 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001556}
1557
1558static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001559mro_external(PyObject *self)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001560{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001561 PyTypeObject *type = (PyTypeObject *)self;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001562
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001563 return mro_implementation(type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001564}
1565
1566static int
1567mro_internal(PyTypeObject *type)
1568{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001569 PyObject *mro, *result, *tuple;
1570 int checkit = 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001571
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001572 if (Py_TYPE(type) == &PyType_Type) {
1573 result = mro_implementation(type);
1574 }
1575 else {
1576 static PyObject *mro_str;
1577 checkit = 1;
1578 mro = lookup_method((PyObject *)type, "mro", &mro_str);
1579 if (mro == NULL)
1580 return -1;
1581 result = PyObject_CallObject(mro, NULL);
1582 Py_DECREF(mro);
1583 }
1584 if (result == NULL)
1585 return -1;
1586 tuple = PySequence_Tuple(result);
1587 Py_DECREF(result);
1588 if (tuple == NULL)
1589 return -1;
1590 if (checkit) {
1591 Py_ssize_t i, len;
1592 PyObject *cls;
1593 PyTypeObject *solid;
Armin Rigo037d1e02005-12-29 17:07:39 +00001594
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001595 solid = solid_base(type);
Armin Rigo037d1e02005-12-29 17:07:39 +00001596
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001597 len = PyTuple_GET_SIZE(tuple);
Armin Rigo037d1e02005-12-29 17:07:39 +00001598
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001599 for (i = 0; i < len; i++) {
1600 PyTypeObject *t;
1601 cls = PyTuple_GET_ITEM(tuple, i);
1602 if (!PyType_Check(cls)) {
1603 PyErr_Format(PyExc_TypeError,
1604 "mro() returned a non-class ('%.500s')",
1605 Py_TYPE(cls)->tp_name);
1606 Py_DECREF(tuple);
1607 return -1;
1608 }
1609 t = (PyTypeObject*)cls;
1610 if (!PyType_IsSubtype(solid, solid_base(t))) {
1611 PyErr_Format(PyExc_TypeError,
1612 "mro() returned base with unsuitable layout ('%.500s')",
1613 t->tp_name);
1614 Py_DECREF(tuple);
1615 return -1;
1616 }
1617 }
1618 }
1619 type->tp_mro = tuple;
Christian Heimesa62da1d2008-01-12 19:39:10 +00001620
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001621 type_mro_modified(type, type->tp_mro);
1622 /* corner case: the old-style super class might have been hidden
1623 from the custom MRO */
1624 type_mro_modified(type, type->tp_bases);
Christian Heimesa62da1d2008-01-12 19:39:10 +00001625
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001626 PyType_Modified(type);
Christian Heimesa62da1d2008-01-12 19:39:10 +00001627
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001628 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001629}
1630
1631
1632/* Calculate the best base amongst multiple base classes.
1633 This is the first one that's on the path to the "solid base". */
1634
1635static PyTypeObject *
1636best_base(PyObject *bases)
1637{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001638 Py_ssize_t i, n;
1639 PyTypeObject *base, *winner, *candidate, *base_i;
1640 PyObject *base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001641
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001642 assert(PyTuple_Check(bases));
1643 n = PyTuple_GET_SIZE(bases);
1644 assert(n > 0);
1645 base = NULL;
1646 winner = NULL;
1647 for (i = 0; i < n; i++) {
1648 base_proto = PyTuple_GET_ITEM(bases, i);
1649 if (!PyType_Check(base_proto)) {
1650 PyErr_SetString(
1651 PyExc_TypeError,
1652 "bases must be types");
1653 return NULL;
1654 }
1655 base_i = (PyTypeObject *)base_proto;
1656 if (base_i->tp_dict == NULL) {
1657 if (PyType_Ready(base_i) < 0)
1658 return NULL;
1659 }
1660 candidate = solid_base(base_i);
1661 if (winner == NULL) {
1662 winner = candidate;
1663 base = base_i;
1664 }
1665 else if (PyType_IsSubtype(winner, candidate))
1666 ;
1667 else if (PyType_IsSubtype(candidate, winner)) {
1668 winner = candidate;
1669 base = base_i;
1670 }
1671 else {
1672 PyErr_SetString(
1673 PyExc_TypeError,
1674 "multiple bases have "
1675 "instance lay-out conflict");
1676 return NULL;
1677 }
1678 }
1679 if (base == NULL)
1680 PyErr_SetString(PyExc_TypeError,
1681 "a new-style class can't have only classic bases");
1682 return base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001683}
1684
1685static int
1686extra_ivars(PyTypeObject *type, PyTypeObject *base)
1687{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001688 size_t t_size = type->tp_basicsize;
1689 size_t b_size = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001690
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001691 assert(t_size >= b_size); /* Else type smaller than base! */
1692 if (type->tp_itemsize || base->tp_itemsize) {
1693 /* If itemsize is involved, stricter rules */
1694 return t_size != b_size ||
1695 type->tp_itemsize != base->tp_itemsize;
1696 }
1697 if (type->tp_weaklistoffset && base->tp_weaklistoffset == 0 &&
1698 type->tp_weaklistoffset + sizeof(PyObject *) == t_size &&
1699 type->tp_flags & Py_TPFLAGS_HEAPTYPE)
1700 t_size -= sizeof(PyObject *);
1701 if (type->tp_dictoffset && base->tp_dictoffset == 0 &&
1702 type->tp_dictoffset + sizeof(PyObject *) == t_size &&
1703 type->tp_flags & Py_TPFLAGS_HEAPTYPE)
1704 t_size -= sizeof(PyObject *);
Guido van Rossum9676b222001-08-17 20:32:36 +00001705
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001706 return t_size != b_size;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001707}
1708
1709static PyTypeObject *
1710solid_base(PyTypeObject *type)
1711{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001712 PyTypeObject *base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001713
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001714 if (type->tp_base)
1715 base = solid_base(type->tp_base);
1716 else
1717 base = &PyBaseObject_Type;
1718 if (extra_ivars(type, base))
1719 return type;
1720 else
1721 return base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001722}
1723
Jeremy Hylton938ace62002-07-17 16:30:39 +00001724static void object_dealloc(PyObject *);
1725static int object_init(PyObject *, PyObject *, PyObject *);
1726static int update_slot(PyTypeObject *, PyObject *);
1727static void fixup_slot_dispatchers(PyTypeObject *);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001728
Guido van Rossum360e4b82007-05-14 22:51:27 +00001729/*
1730 * Helpers for __dict__ descriptor. We don't want to expose the dicts
1731 * inherited from various builtin types. The builtin base usually provides
1732 * its own __dict__ descriptor, so we use that when we can.
1733 */
1734static PyTypeObject *
1735get_builtin_base_with_dict(PyTypeObject *type)
1736{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001737 while (type->tp_base != NULL) {
1738 if (type->tp_dictoffset != 0 &&
1739 !(type->tp_flags & Py_TPFLAGS_HEAPTYPE))
1740 return type;
1741 type = type->tp_base;
1742 }
1743 return NULL;
Guido van Rossum360e4b82007-05-14 22:51:27 +00001744}
1745
1746static PyObject *
1747get_dict_descriptor(PyTypeObject *type)
1748{
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001749 PyObject *dict_str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001750 PyObject *descr;
Guido van Rossum360e4b82007-05-14 22:51:27 +00001751
Martin v. Löwisd10759f2011-11-07 13:00:05 +01001752 dict_str = _PyUnicode_FromId(&PyId___dict__); /* borrowed */
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001753 if (dict_str == NULL)
1754 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001755 descr = _PyType_Lookup(type, dict_str);
1756 if (descr == NULL || !PyDescr_IsData(descr))
1757 return NULL;
Guido van Rossum360e4b82007-05-14 22:51:27 +00001758
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001759 return descr;
Guido van Rossum360e4b82007-05-14 22:51:27 +00001760}
1761
1762static void
1763raise_dict_descr_error(PyObject *obj)
1764{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001765 PyErr_Format(PyExc_TypeError,
1766 "this __dict__ descriptor does not support "
1767 "'%.200s' objects", Py_TYPE(obj)->tp_name);
Guido van Rossum360e4b82007-05-14 22:51:27 +00001768}
1769
Tim Peters6d6c1a32001-08-02 04:15:00 +00001770static PyObject *
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001771subtype_dict(PyObject *obj, void *context)
1772{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001773 PyObject **dictptr;
1774 PyObject *dict;
1775 PyTypeObject *base;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001776
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001777 base = get_builtin_base_with_dict(Py_TYPE(obj));
1778 if (base != NULL) {
1779 descrgetfunc func;
1780 PyObject *descr = get_dict_descriptor(base);
1781 if (descr == NULL) {
1782 raise_dict_descr_error(obj);
1783 return NULL;
1784 }
1785 func = Py_TYPE(descr)->tp_descr_get;
1786 if (func == NULL) {
1787 raise_dict_descr_error(obj);
1788 return NULL;
1789 }
1790 return func(descr, obj, (PyObject *)(Py_TYPE(obj)));
1791 }
Guido van Rossum360e4b82007-05-14 22:51:27 +00001792
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001793 dictptr = _PyObject_GetDictPtr(obj);
1794 if (dictptr == NULL) {
1795 PyErr_SetString(PyExc_AttributeError,
1796 "This object has no __dict__");
1797 return NULL;
1798 }
1799 dict = *dictptr;
1800 if (dict == NULL)
1801 *dictptr = dict = PyDict_New();
1802 Py_XINCREF(dict);
1803 return dict;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001804}
1805
Guido van Rossum6661be32001-10-26 04:26:12 +00001806static int
1807subtype_setdict(PyObject *obj, PyObject *value, void *context)
1808{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001809 PyObject **dictptr;
1810 PyObject *dict;
1811 PyTypeObject *base;
Guido van Rossum6661be32001-10-26 04:26:12 +00001812
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001813 base = get_builtin_base_with_dict(Py_TYPE(obj));
1814 if (base != NULL) {
1815 descrsetfunc func;
1816 PyObject *descr = get_dict_descriptor(base);
1817 if (descr == NULL) {
1818 raise_dict_descr_error(obj);
1819 return -1;
1820 }
1821 func = Py_TYPE(descr)->tp_descr_set;
1822 if (func == NULL) {
1823 raise_dict_descr_error(obj);
1824 return -1;
1825 }
1826 return func(descr, obj, value);
1827 }
Guido van Rossum360e4b82007-05-14 22:51:27 +00001828
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001829 dictptr = _PyObject_GetDictPtr(obj);
1830 if (dictptr == NULL) {
1831 PyErr_SetString(PyExc_AttributeError,
1832 "This object has no __dict__");
1833 return -1;
1834 }
1835 if (value != NULL && !PyDict_Check(value)) {
1836 PyErr_Format(PyExc_TypeError,
1837 "__dict__ must be set to a dictionary, "
1838 "not a '%.200s'", Py_TYPE(value)->tp_name);
1839 return -1;
1840 }
1841 dict = *dictptr;
1842 Py_XINCREF(value);
1843 *dictptr = value;
1844 Py_XDECREF(dict);
1845 return 0;
Guido van Rossum6661be32001-10-26 04:26:12 +00001846}
1847
Guido van Rossumad47da02002-08-12 19:05:44 +00001848static PyObject *
1849subtype_getweakref(PyObject *obj, void *context)
1850{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001851 PyObject **weaklistptr;
1852 PyObject *result;
Guido van Rossumad47da02002-08-12 19:05:44 +00001853
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001854 if (Py_TYPE(obj)->tp_weaklistoffset == 0) {
1855 PyErr_SetString(PyExc_AttributeError,
1856 "This object has no __weakref__");
1857 return NULL;
1858 }
1859 assert(Py_TYPE(obj)->tp_weaklistoffset > 0);
1860 assert(Py_TYPE(obj)->tp_weaklistoffset + sizeof(PyObject *) <=
1861 (size_t)(Py_TYPE(obj)->tp_basicsize));
1862 weaklistptr = (PyObject **)
1863 ((char *)obj + Py_TYPE(obj)->tp_weaklistoffset);
1864 if (*weaklistptr == NULL)
1865 result = Py_None;
1866 else
1867 result = *weaklistptr;
1868 Py_INCREF(result);
1869 return result;
Guido van Rossumad47da02002-08-12 19:05:44 +00001870}
1871
Guido van Rossum373c7412003-01-07 13:41:37 +00001872/* Three variants on the subtype_getsets list. */
1873
1874static PyGetSetDef subtype_getsets_full[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001875 {"__dict__", subtype_dict, subtype_setdict,
1876 PyDoc_STR("dictionary for instance variables (if defined)")},
1877 {"__weakref__", subtype_getweakref, NULL,
1878 PyDoc_STR("list of weak references to the object (if defined)")},
1879 {0}
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001880};
1881
Guido van Rossum373c7412003-01-07 13:41:37 +00001882static PyGetSetDef subtype_getsets_dict_only[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001883 {"__dict__", subtype_dict, subtype_setdict,
1884 PyDoc_STR("dictionary for instance variables (if defined)")},
1885 {0}
Guido van Rossum373c7412003-01-07 13:41:37 +00001886};
1887
1888static PyGetSetDef subtype_getsets_weakref_only[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001889 {"__weakref__", subtype_getweakref, NULL,
1890 PyDoc_STR("list of weak references to the object (if defined)")},
1891 {0}
Guido van Rossum373c7412003-01-07 13:41:37 +00001892};
1893
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001894static int
1895valid_identifier(PyObject *s)
1896{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001897 if (!PyUnicode_Check(s)) {
1898 PyErr_Format(PyExc_TypeError,
1899 "__slots__ items must be strings, not '%.200s'",
1900 Py_TYPE(s)->tp_name);
1901 return 0;
1902 }
1903 if (!PyUnicode_IsIdentifier(s)) {
1904 PyErr_SetString(PyExc_TypeError,
1905 "__slots__ must be identifiers");
1906 return 0;
1907 }
1908 return 1;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001909}
1910
Guido van Rossumd8faa362007-04-27 19:54:29 +00001911/* Forward */
1912static int
1913object_init(PyObject *self, PyObject *args, PyObject *kwds);
1914
1915static int
1916type_init(PyObject *cls, PyObject *args, PyObject *kwds)
1917{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001918 int res;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001919
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001920 assert(args != NULL && PyTuple_Check(args));
1921 assert(kwds == NULL || PyDict_Check(kwds));
Guido van Rossumd8faa362007-04-27 19:54:29 +00001922
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001923 if (kwds != NULL && PyDict_Check(kwds) && PyDict_Size(kwds) != 0) {
1924 PyErr_SetString(PyExc_TypeError,
1925 "type.__init__() takes no keyword arguments");
1926 return -1;
1927 }
Guido van Rossumd8faa362007-04-27 19:54:29 +00001928
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001929 if (args != NULL && PyTuple_Check(args) &&
1930 (PyTuple_GET_SIZE(args) != 1 && PyTuple_GET_SIZE(args) != 3)) {
1931 PyErr_SetString(PyExc_TypeError,
1932 "type.__init__() takes 1 or 3 arguments");
1933 return -1;
1934 }
Guido van Rossumd8faa362007-04-27 19:54:29 +00001935
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001936 /* Call object.__init__(self) now. */
1937 /* XXX Could call super(type, cls).__init__() but what's the point? */
1938 args = PyTuple_GetSlice(args, 0, 0);
1939 res = object_init(cls, args, NULL);
1940 Py_DECREF(args);
1941 return res;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001942}
1943
Martin v. Löwis738236d2011-02-05 20:35:29 +00001944long
1945PyType_GetFlags(PyTypeObject *type)
1946{
1947 return type->tp_flags;
1948}
1949
Nick Coghlande31b192011-10-23 22:04:16 +10001950/* Determine the most derived metatype. */
1951PyTypeObject *
1952_PyType_CalculateMetaclass(PyTypeObject *metatype, PyObject *bases)
1953{
1954 Py_ssize_t i, nbases;
1955 PyTypeObject *winner;
1956 PyObject *tmp;
1957 PyTypeObject *tmptype;
1958
1959 /* Determine the proper metatype to deal with this,
1960 and check for metatype conflicts while we're at it.
1961 Note that if some other metatype wins to contract,
1962 it's possible that its instances are not types. */
1963
1964 nbases = PyTuple_GET_SIZE(bases);
1965 winner = metatype;
1966 for (i = 0; i < nbases; i++) {
1967 tmp = PyTuple_GET_ITEM(bases, i);
1968 tmptype = Py_TYPE(tmp);
1969 if (PyType_IsSubtype(winner, tmptype))
1970 continue;
1971 if (PyType_IsSubtype(tmptype, winner)) {
1972 winner = tmptype;
1973 continue;
1974 }
1975 /* else: */
1976 PyErr_SetString(PyExc_TypeError,
1977 "metaclass conflict: "
1978 "the metaclass of a derived class "
1979 "must be a (non-strict) subclass "
1980 "of the metaclasses of all its bases");
1981 return NULL;
1982 }
1983 return winner;
1984}
1985
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001986static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00001987type_new(PyTypeObject *metatype, PyObject *args, PyObject *kwds)
1988{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001989 PyObject *name, *bases, *dict;
1990 static char *kwlist[] = {"name", "bases", "dict", 0};
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001991 PyObject *qualname, *slots, *tmp, *newslots;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001992 PyTypeObject *type, *base, *tmptype, *winner;
1993 PyHeapTypeObject *et;
1994 PyMemberDef *mp;
1995 Py_ssize_t i, nbases, nslots, slotoffset, add_dict, add_weak;
1996 int j, may_add_dict, may_add_weak;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001997
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001998 assert(args != NULL && PyTuple_Check(args));
1999 assert(kwds == NULL || PyDict_Check(kwds));
Tim Peters3abca122001-10-27 19:37:48 +00002000
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002001 /* Special case: type(x) should return x->ob_type */
2002 {
2003 const Py_ssize_t nargs = PyTuple_GET_SIZE(args);
2004 const Py_ssize_t nkwds = kwds == NULL ? 0 : PyDict_Size(kwds);
Tim Peters3abca122001-10-27 19:37:48 +00002005
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002006 if (PyType_CheckExact(metatype) && nargs == 1 && nkwds == 0) {
2007 PyObject *x = PyTuple_GET_ITEM(args, 0);
2008 Py_INCREF(Py_TYPE(x));
2009 return (PyObject *) Py_TYPE(x);
2010 }
Tim Peters3abca122001-10-27 19:37:48 +00002011
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002012 /* SF bug 475327 -- if that didn't trigger, we need 3
2013 arguments. but PyArg_ParseTupleAndKeywords below may give
2014 a msg saying type() needs exactly 3. */
2015 if (nargs + nkwds != 3) {
2016 PyErr_SetString(PyExc_TypeError,
2017 "type() takes 1 or 3 arguments");
2018 return NULL;
2019 }
2020 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002021
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002022 /* Check arguments: (name, bases, dict) */
2023 if (!PyArg_ParseTupleAndKeywords(args, kwds, "UO!O!:type", kwlist,
2024 &name,
2025 &PyTuple_Type, &bases,
2026 &PyDict_Type, &dict))
2027 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002028
Nick Coghlande31b192011-10-23 22:04:16 +10002029 /* Determine the proper metatype to deal with this: */
2030 winner = _PyType_CalculateMetaclass(metatype, bases);
2031 if (winner == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002032 return NULL;
2033 }
Nick Coghlande31b192011-10-23 22:04:16 +10002034
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002035 if (winner != metatype) {
2036 if (winner->tp_new != type_new) /* Pass it to the winner */
2037 return winner->tp_new(winner, args, kwds);
2038 metatype = winner;
2039 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002040
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002041 /* Adjust for empty tuple bases */
Nick Coghlande31b192011-10-23 22:04:16 +10002042 nbases = PyTuple_GET_SIZE(bases);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002043 if (nbases == 0) {
2044 bases = PyTuple_Pack(1, &PyBaseObject_Type);
2045 if (bases == NULL)
2046 return NULL;
2047 nbases = 1;
2048 }
2049 else
2050 Py_INCREF(bases);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002051
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002052 /* XXX From here until type is allocated, "return NULL" leaks bases! */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002053
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002054 /* Calculate best base, and check that all bases are type objects */
2055 base = best_base(bases);
2056 if (base == NULL) {
2057 Py_DECREF(bases);
2058 return NULL;
2059 }
2060 if (!PyType_HasFeature(base, Py_TPFLAGS_BASETYPE)) {
2061 PyErr_Format(PyExc_TypeError,
2062 "type '%.100s' is not an acceptable base type",
2063 base->tp_name);
2064 Py_DECREF(bases);
2065 return NULL;
2066 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002067
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002068 /* Check for a __qualname__ variable in dict */
2069 qualname = PyDict_GetItemString(dict, "__qualname__");
2070 if (qualname == NULL) {
2071 qualname = name;
2072 }
2073 else {
2074 if (PyDict_DelItemString(dict, "__qualname__") < 0) {
2075 Py_DECREF(bases);
2076 return NULL;
2077 }
2078 }
2079
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002080 /* Check for a __slots__ sequence variable in dict, and count it */
2081 slots = PyDict_GetItemString(dict, "__slots__");
2082 nslots = 0;
2083 add_dict = 0;
2084 add_weak = 0;
2085 may_add_dict = base->tp_dictoffset == 0;
2086 may_add_weak = base->tp_weaklistoffset == 0 && base->tp_itemsize == 0;
2087 if (slots == NULL) {
2088 if (may_add_dict) {
2089 add_dict++;
2090 }
2091 if (may_add_weak) {
2092 add_weak++;
2093 }
2094 }
2095 else {
2096 /* Have slots */
Guido van Rossumad47da02002-08-12 19:05:44 +00002097
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002098 /* Make it into a tuple */
2099 if (PyUnicode_Check(slots))
2100 slots = PyTuple_Pack(1, slots);
2101 else
2102 slots = PySequence_Tuple(slots);
2103 if (slots == NULL) {
2104 Py_DECREF(bases);
2105 return NULL;
2106 }
2107 assert(PyTuple_Check(slots));
Guido van Rossumad47da02002-08-12 19:05:44 +00002108
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002109 /* Are slots allowed? */
2110 nslots = PyTuple_GET_SIZE(slots);
2111 if (nslots > 0 && base->tp_itemsize != 0) {
2112 PyErr_Format(PyExc_TypeError,
2113 "nonempty __slots__ "
2114 "not supported for subtype of '%s'",
2115 base->tp_name);
2116 bad_slots:
2117 Py_DECREF(bases);
2118 Py_DECREF(slots);
2119 return NULL;
2120 }
Guido van Rossumad47da02002-08-12 19:05:44 +00002121
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002122 /* Check for valid slot names and two special cases */
2123 for (i = 0; i < nslots; i++) {
2124 PyObject *tmp = PyTuple_GET_ITEM(slots, i);
2125 if (!valid_identifier(tmp))
2126 goto bad_slots;
2127 assert(PyUnicode_Check(tmp));
2128 if (PyUnicode_CompareWithASCIIString(tmp, "__dict__") == 0) {
2129 if (!may_add_dict || add_dict) {
2130 PyErr_SetString(PyExc_TypeError,
2131 "__dict__ slot disallowed: "
2132 "we already got one");
2133 goto bad_slots;
2134 }
2135 add_dict++;
2136 }
2137 if (PyUnicode_CompareWithASCIIString(tmp, "__weakref__") == 0) {
2138 if (!may_add_weak || add_weak) {
2139 PyErr_SetString(PyExc_TypeError,
2140 "__weakref__ slot disallowed: "
2141 "either we already got one, "
2142 "or __itemsize__ != 0");
2143 goto bad_slots;
2144 }
2145 add_weak++;
2146 }
2147 }
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00002148
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002149 /* Copy slots into a list, mangle names and sort them.
2150 Sorted names are needed for __class__ assignment.
2151 Convert them back to tuple at the end.
2152 */
2153 newslots = PyList_New(nslots - add_dict - add_weak);
2154 if (newslots == NULL)
2155 goto bad_slots;
2156 for (i = j = 0; i < nslots; i++) {
2157 tmp = PyTuple_GET_ITEM(slots, i);
2158 if ((add_dict &&
2159 PyUnicode_CompareWithASCIIString(tmp, "__dict__") == 0) ||
2160 (add_weak &&
2161 PyUnicode_CompareWithASCIIString(tmp, "__weakref__") == 0))
2162 continue;
2163 tmp =_Py_Mangle(name, tmp);
Benjamin Petersonae13c882011-08-16 22:26:48 -05002164 if (!tmp) {
2165 Py_DECREF(newslots);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002166 goto bad_slots;
Benjamin Petersonae13c882011-08-16 22:26:48 -05002167 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002168 PyList_SET_ITEM(newslots, j, tmp);
Benjamin Petersonc4085c82011-08-16 18:53:26 -05002169 if (PyDict_GetItem(dict, tmp)) {
2170 PyErr_Format(PyExc_ValueError,
2171 "%R in __slots__ conflicts with class variable",
2172 tmp);
Benjamin Petersond17cefc2011-08-16 22:28:23 -05002173 Py_DECREF(newslots);
Benjamin Petersonc4085c82011-08-16 18:53:26 -05002174 goto bad_slots;
2175 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002176 j++;
2177 }
2178 assert(j == nslots - add_dict - add_weak);
2179 nslots = j;
2180 Py_DECREF(slots);
2181 if (PyList_Sort(newslots) == -1) {
2182 Py_DECREF(bases);
2183 Py_DECREF(newslots);
2184 return NULL;
2185 }
2186 slots = PyList_AsTuple(newslots);
2187 Py_DECREF(newslots);
2188 if (slots == NULL) {
2189 Py_DECREF(bases);
2190 return NULL;
2191 }
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00002192
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002193 /* Secondary bases may provide weakrefs or dict */
2194 if (nbases > 1 &&
2195 ((may_add_dict && !add_dict) ||
2196 (may_add_weak && !add_weak))) {
2197 for (i = 0; i < nbases; i++) {
2198 tmp = PyTuple_GET_ITEM(bases, i);
2199 if (tmp == (PyObject *)base)
2200 continue; /* Skip primary base */
2201 assert(PyType_Check(tmp));
2202 tmptype = (PyTypeObject *)tmp;
2203 if (may_add_dict && !add_dict &&
2204 tmptype->tp_dictoffset != 0)
2205 add_dict++;
2206 if (may_add_weak && !add_weak &&
2207 tmptype->tp_weaklistoffset != 0)
2208 add_weak++;
2209 if (may_add_dict && !add_dict)
2210 continue;
2211 if (may_add_weak && !add_weak)
2212 continue;
2213 /* Nothing more to check */
2214 break;
2215 }
2216 }
2217 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002218
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002219 /* XXX From here until type is safely allocated,
2220 "return NULL" may leak slots! */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002221
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002222 /* Allocate the type object */
2223 type = (PyTypeObject *)metatype->tp_alloc(metatype, nslots);
2224 if (type == NULL) {
2225 Py_XDECREF(slots);
2226 Py_DECREF(bases);
2227 return NULL;
2228 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002229
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002230 /* Keep name and slots alive in the extended type object */
2231 et = (PyHeapTypeObject *)type;
2232 Py_INCREF(name);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002233 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002234 et->ht_name = name;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002235 et->ht_qualname = qualname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002236 et->ht_slots = slots;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002237
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002238 /* Initialize tp_flags */
2239 type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE |
2240 Py_TPFLAGS_BASETYPE;
2241 if (base->tp_flags & Py_TPFLAGS_HAVE_GC)
2242 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossumdc91b992001-08-08 22:26:22 +00002243
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002244 /* Initialize essential fields */
2245 type->tp_as_number = &et->as_number;
2246 type->tp_as_sequence = &et->as_sequence;
2247 type->tp_as_mapping = &et->as_mapping;
2248 type->tp_as_buffer = &et->as_buffer;
2249 type->tp_name = _PyUnicode_AsString(name);
2250 if (!type->tp_name) {
2251 Py_DECREF(type);
2252 return NULL;
2253 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002254
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002255 /* Set tp_base and tp_bases */
2256 type->tp_bases = bases;
2257 Py_INCREF(base);
2258 type->tp_base = base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002259
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002260 /* Initialize tp_dict from passed-in dict */
2261 type->tp_dict = dict = PyDict_Copy(dict);
2262 if (dict == NULL) {
2263 Py_DECREF(type);
2264 return NULL;
2265 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002266
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002267 /* Set __module__ in the dict */
2268 if (PyDict_GetItemString(dict, "__module__") == NULL) {
2269 tmp = PyEval_GetGlobals();
2270 if (tmp != NULL) {
2271 tmp = PyDict_GetItemString(tmp, "__name__");
2272 if (tmp != NULL) {
2273 if (PyDict_SetItemString(dict, "__module__",
2274 tmp) < 0)
2275 return NULL;
2276 }
2277 }
2278 }
Guido van Rossumc3542212001-08-16 09:18:56 +00002279
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002280 /* Set tp_doc to a copy of dict['__doc__'], if the latter is there
2281 and is a string. The __doc__ accessor will first look for tp_doc;
2282 if that fails, it will still look into __dict__.
2283 */
2284 {
2285 PyObject *doc = PyDict_GetItemString(dict, "__doc__");
2286 if (doc != NULL && PyUnicode_Check(doc)) {
2287 Py_ssize_t len;
2288 char *doc_str;
2289 char *tp_doc;
Alexandre Vassalottia85998a2008-05-03 18:24:43 +00002290
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002291 doc_str = _PyUnicode_AsString(doc);
2292 if (doc_str == NULL) {
2293 Py_DECREF(type);
2294 return NULL;
2295 }
2296 /* Silently truncate the docstring if it contains null bytes. */
2297 len = strlen(doc_str);
2298 tp_doc = (char *)PyObject_MALLOC(len + 1);
2299 if (tp_doc == NULL) {
2300 Py_DECREF(type);
2301 return NULL;
2302 }
2303 memcpy(tp_doc, doc_str, len + 1);
2304 type->tp_doc = tp_doc;
2305 }
2306 }
Tim Peters2f93e282001-10-04 05:27:00 +00002307
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002308 /* Special-case __new__: if it's a plain function,
2309 make it a static function */
2310 tmp = PyDict_GetItemString(dict, "__new__");
2311 if (tmp != NULL && PyFunction_Check(tmp)) {
2312 tmp = PyStaticMethod_New(tmp);
2313 if (tmp == NULL) {
2314 Py_DECREF(type);
2315 return NULL;
2316 }
2317 PyDict_SetItemString(dict, "__new__", tmp);
2318 Py_DECREF(tmp);
2319 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002320
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002321 /* Add descriptors for custom slots from __slots__, or for __dict__ */
2322 mp = PyHeapType_GET_MEMBERS(et);
2323 slotoffset = base->tp_basicsize;
2324 if (slots != NULL) {
2325 for (i = 0; i < nslots; i++, mp++) {
2326 mp->name = _PyUnicode_AsString(
2327 PyTuple_GET_ITEM(slots, i));
Victor Stinnere5f99f32010-05-19 01:42:46 +00002328 if (mp->name == NULL) {
2329 Py_DECREF(type);
2330 return NULL;
2331 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002332 mp->type = T_OBJECT_EX;
2333 mp->offset = slotoffset;
Guido van Rossumd8faa362007-04-27 19:54:29 +00002334
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002335 /* __dict__ and __weakref__ are already filtered out */
2336 assert(strcmp(mp->name, "__dict__") != 0);
2337 assert(strcmp(mp->name, "__weakref__") != 0);
Guido van Rossumd8faa362007-04-27 19:54:29 +00002338
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002339 slotoffset += sizeof(PyObject *);
2340 }
2341 }
2342 if (add_dict) {
2343 if (base->tp_itemsize)
2344 type->tp_dictoffset = -(long)sizeof(PyObject *);
2345 else
2346 type->tp_dictoffset = slotoffset;
2347 slotoffset += sizeof(PyObject *);
2348 }
2349 if (add_weak) {
2350 assert(!base->tp_itemsize);
2351 type->tp_weaklistoffset = slotoffset;
2352 slotoffset += sizeof(PyObject *);
2353 }
2354 type->tp_basicsize = slotoffset;
2355 type->tp_itemsize = base->tp_itemsize;
2356 type->tp_members = PyHeapType_GET_MEMBERS(et);
Guido van Rossum373c7412003-01-07 13:41:37 +00002357
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002358 if (type->tp_weaklistoffset && type->tp_dictoffset)
2359 type->tp_getset = subtype_getsets_full;
2360 else if (type->tp_weaklistoffset && !type->tp_dictoffset)
2361 type->tp_getset = subtype_getsets_weakref_only;
2362 else if (!type->tp_weaklistoffset && type->tp_dictoffset)
2363 type->tp_getset = subtype_getsets_dict_only;
2364 else
2365 type->tp_getset = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002366
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002367 /* Special case some slots */
2368 if (type->tp_dictoffset != 0 || nslots > 0) {
2369 if (base->tp_getattr == NULL && base->tp_getattro == NULL)
2370 type->tp_getattro = PyObject_GenericGetAttr;
2371 if (base->tp_setattr == NULL && base->tp_setattro == NULL)
2372 type->tp_setattro = PyObject_GenericSetAttr;
2373 }
2374 type->tp_dealloc = subtype_dealloc;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002375
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002376 /* Enable GC unless there are really no instance variables possible */
2377 if (!(type->tp_basicsize == sizeof(PyObject) &&
2378 type->tp_itemsize == 0))
2379 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossum9475a232001-10-05 20:51:39 +00002380
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002381 /* Always override allocation strategy to use regular heap */
2382 type->tp_alloc = PyType_GenericAlloc;
2383 if (type->tp_flags & Py_TPFLAGS_HAVE_GC) {
2384 type->tp_free = PyObject_GC_Del;
2385 type->tp_traverse = subtype_traverse;
2386 type->tp_clear = subtype_clear;
2387 }
2388 else
2389 type->tp_free = PyObject_Del;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002390
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002391 /* Initialize the rest */
2392 if (PyType_Ready(type) < 0) {
2393 Py_DECREF(type);
2394 return NULL;
2395 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002396
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002397 /* Put the proper slots in place */
2398 fixup_slot_dispatchers(type);
Guido van Rossumf040ede2001-08-07 16:40:56 +00002399
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002400 return (PyObject *)type;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002401}
2402
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002403static short slotoffsets[] = {
2404 -1, /* invalid slot */
2405#include "typeslots.inc"
2406};
2407
2408PyObject* PyType_FromSpec(PyType_Spec *spec)
2409{
2410 PyHeapTypeObject *res = (PyHeapTypeObject*)PyType_GenericAlloc(&PyType_Type, 0);
2411 char *res_start = (char*)res;
2412 PyType_Slot *slot;
2413
Martin v. Löwis5e06a5d2011-02-21 16:24:00 +00002414 if (res == NULL)
2415 return NULL;
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002416 res->ht_name = PyUnicode_FromString(spec->name);
2417 if (!res->ht_name)
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002418 goto fail;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002419 res->ht_qualname = res->ht_name;
2420 Py_INCREF(res->ht_qualname);
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002421 res->ht_type.tp_name = _PyUnicode_AsString(res->ht_name);
2422 if (!res->ht_type.tp_name)
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002423 goto fail;
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002424
2425 res->ht_type.tp_basicsize = spec->basicsize;
2426 res->ht_type.tp_itemsize = spec->itemsize;
2427 res->ht_type.tp_flags = spec->flags | Py_TPFLAGS_HEAPTYPE;
Victor Stinner0fcab4a2011-01-04 12:59:15 +00002428
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002429 for (slot = spec->slots; slot->slot; slot++) {
Victor Stinner63941882011-09-29 00:42:28 +02002430 if (slot->slot >= Py_ARRAY_LENGTH(slotoffsets)) {
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002431 PyErr_SetString(PyExc_RuntimeError, "invalid slot offset");
2432 goto fail;
2433 }
2434 *(void**)(res_start + slotoffsets[slot->slot]) = slot->pfunc;
Georg Brandl032400b2011-02-19 21:47:02 +00002435
2436 /* need to make a copy of the docstring slot, which usually
2437 points to a static string literal */
2438 if (slot->slot == Py_tp_doc) {
2439 ssize_t len = strlen(slot->pfunc)+1;
2440 char *tp_doc = PyObject_MALLOC(len);
2441 if (tp_doc == NULL)
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002442 goto fail;
Georg Brandl032400b2011-02-19 21:47:02 +00002443 memcpy(tp_doc, slot->pfunc, len);
2444 res->ht_type.tp_doc = tp_doc;
2445 }
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002446 }
2447
2448 return (PyObject*)res;
Victor Stinner0fcab4a2011-01-04 12:59:15 +00002449
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002450 fail:
2451 Py_DECREF(res);
2452 return NULL;
2453}
2454
2455
Tim Peters6d6c1a32001-08-02 04:15:00 +00002456/* Internal API to look for a name through the MRO.
2457 This returns a borrowed reference, and doesn't set an exception! */
2458PyObject *
2459_PyType_Lookup(PyTypeObject *type, PyObject *name)
2460{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002461 Py_ssize_t i, n;
2462 PyObject *mro, *res, *base, *dict;
2463 unsigned int h;
Christian Heimesa62da1d2008-01-12 19:39:10 +00002464
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002465 if (MCACHE_CACHEABLE_NAME(name) &&
2466 PyType_HasFeature(type, Py_TPFLAGS_VALID_VERSION_TAG)) {
2467 /* fast path */
2468 h = MCACHE_HASH_METHOD(type, name);
2469 if (method_cache[h].version == type->tp_version_tag &&
2470 method_cache[h].name == name)
2471 return method_cache[h].value;
2472 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002473
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002474 /* Look in tp_dict of types in MRO */
2475 mro = type->tp_mro;
Guido van Rossum23094982002-06-10 14:30:43 +00002476
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002477 /* If mro is NULL, the type is either not yet initialized
2478 by PyType_Ready(), or already cleared by type_clear().
2479 Either way the safest thing to do is to return NULL. */
2480 if (mro == NULL)
2481 return NULL;
Guido van Rossum23094982002-06-10 14:30:43 +00002482
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002483 res = NULL;
2484 assert(PyTuple_Check(mro));
2485 n = PyTuple_GET_SIZE(mro);
2486 for (i = 0; i < n; i++) {
2487 base = PyTuple_GET_ITEM(mro, i);
2488 assert(PyType_Check(base));
2489 dict = ((PyTypeObject *)base)->tp_dict;
2490 assert(dict && PyDict_Check(dict));
2491 res = PyDict_GetItem(dict, name);
2492 if (res != NULL)
2493 break;
2494 }
Christian Heimesa62da1d2008-01-12 19:39:10 +00002495
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002496 if (MCACHE_CACHEABLE_NAME(name) && assign_version_tag(type)) {
2497 h = MCACHE_HASH_METHOD(type, name);
2498 method_cache[h].version = type->tp_version_tag;
2499 method_cache[h].value = res; /* borrowed */
2500 Py_INCREF(name);
2501 Py_DECREF(method_cache[h].name);
2502 method_cache[h].name = name;
2503 }
2504 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002505}
2506
2507/* This is similar to PyObject_GenericGetAttr(),
2508 but uses _PyType_Lookup() instead of just looking in type->tp_dict. */
2509static PyObject *
2510type_getattro(PyTypeObject *type, PyObject *name)
2511{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002512 PyTypeObject *metatype = Py_TYPE(type);
2513 PyObject *meta_attribute, *attribute;
2514 descrgetfunc meta_get;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002515
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002516 /* Initialize this type (we'll assume the metatype is initialized) */
2517 if (type->tp_dict == NULL) {
2518 if (PyType_Ready(type) < 0)
2519 return NULL;
2520 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002521
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002522 /* No readable descriptor found yet */
2523 meta_get = NULL;
Tim Peters34592512002-07-11 06:23:50 +00002524
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002525 /* Look for the attribute in the metatype */
2526 meta_attribute = _PyType_Lookup(metatype, name);
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002527
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002528 if (meta_attribute != NULL) {
2529 meta_get = Py_TYPE(meta_attribute)->tp_descr_get;
Tim Peters34592512002-07-11 06:23:50 +00002530
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002531 if (meta_get != NULL && PyDescr_IsData(meta_attribute)) {
2532 /* Data descriptors implement tp_descr_set to intercept
2533 * writes. Assume the attribute is not overridden in
2534 * type's tp_dict (and bases): call the descriptor now.
2535 */
2536 return meta_get(meta_attribute, (PyObject *)type,
2537 (PyObject *)metatype);
2538 }
2539 Py_INCREF(meta_attribute);
2540 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002541
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002542 /* No data descriptor found on metatype. Look in tp_dict of this
2543 * type and its bases */
2544 attribute = _PyType_Lookup(type, name);
2545 if (attribute != NULL) {
2546 /* Implement descriptor functionality, if any */
2547 descrgetfunc local_get = Py_TYPE(attribute)->tp_descr_get;
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00002548
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002549 Py_XDECREF(meta_attribute);
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00002550
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002551 if (local_get != NULL) {
2552 /* NULL 2nd argument indicates the descriptor was
2553 * found on the target object itself (or a base) */
2554 return local_get(attribute, (PyObject *)NULL,
2555 (PyObject *)type);
2556 }
Tim Peters34592512002-07-11 06:23:50 +00002557
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002558 Py_INCREF(attribute);
2559 return attribute;
2560 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002561
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002562 /* No attribute found in local __dict__ (or bases): use the
2563 * descriptor from the metatype, if any */
2564 if (meta_get != NULL) {
2565 PyObject *res;
2566 res = meta_get(meta_attribute, (PyObject *)type,
2567 (PyObject *)metatype);
2568 Py_DECREF(meta_attribute);
2569 return res;
2570 }
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002571
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002572 /* If an ordinary attribute was found on the metatype, return it now */
2573 if (meta_attribute != NULL) {
2574 return meta_attribute;
2575 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002576
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002577 /* Give up */
2578 PyErr_Format(PyExc_AttributeError,
2579 "type object '%.50s' has no attribute '%U'",
2580 type->tp_name, name);
2581 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002582}
2583
2584static int
2585type_setattro(PyTypeObject *type, PyObject *name, PyObject *value)
2586{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002587 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
2588 PyErr_Format(
2589 PyExc_TypeError,
2590 "can't set attributes of built-in/extension type '%s'",
2591 type->tp_name);
2592 return -1;
2593 }
2594 if (PyObject_GenericSetAttr((PyObject *)type, name, value) < 0)
2595 return -1;
2596 return update_slot(type, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002597}
2598
2599static void
2600type_dealloc(PyTypeObject *type)
2601{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002602 PyHeapTypeObject *et;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002603
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002604 /* Assert this is a heap-allocated type object */
2605 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
2606 _PyObject_GC_UNTRACK(type);
2607 PyObject_ClearWeakRefs((PyObject *)type);
2608 et = (PyHeapTypeObject *)type;
2609 Py_XDECREF(type->tp_base);
2610 Py_XDECREF(type->tp_dict);
2611 Py_XDECREF(type->tp_bases);
2612 Py_XDECREF(type->tp_mro);
2613 Py_XDECREF(type->tp_cache);
2614 Py_XDECREF(type->tp_subclasses);
2615 /* A type's tp_doc is heap allocated, unlike the tp_doc slots
2616 * of most other objects. It's okay to cast it to char *.
2617 */
2618 PyObject_Free((char *)type->tp_doc);
2619 Py_XDECREF(et->ht_name);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002620 Py_XDECREF(et->ht_qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002621 Py_XDECREF(et->ht_slots);
2622 Py_TYPE(type)->tp_free((PyObject *)type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002623}
2624
Guido van Rossum1c450732001-10-08 15:18:27 +00002625static PyObject *
2626type_subclasses(PyTypeObject *type, PyObject *args_ignored)
2627{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002628 PyObject *list, *raw, *ref;
2629 Py_ssize_t i, n;
Guido van Rossum1c450732001-10-08 15:18:27 +00002630
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002631 list = PyList_New(0);
2632 if (list == NULL)
2633 return NULL;
2634 raw = type->tp_subclasses;
2635 if (raw == NULL)
2636 return list;
2637 assert(PyList_Check(raw));
2638 n = PyList_GET_SIZE(raw);
2639 for (i = 0; i < n; i++) {
2640 ref = PyList_GET_ITEM(raw, i);
2641 assert(PyWeakref_CheckRef(ref));
2642 ref = PyWeakref_GET_OBJECT(ref);
2643 if (ref != Py_None) {
2644 if (PyList_Append(list, ref) < 0) {
2645 Py_DECREF(list);
2646 return NULL;
2647 }
2648 }
2649 }
2650 return list;
Guido van Rossum1c450732001-10-08 15:18:27 +00002651}
2652
Guido van Rossum47374822007-08-02 16:48:17 +00002653static PyObject *
2654type_prepare(PyObject *self, PyObject *args, PyObject *kwds)
2655{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002656 return PyDict_New();
Guido van Rossum47374822007-08-02 16:48:17 +00002657}
2658
Victor Stinner63941882011-09-29 00:42:28 +02002659/*
Benjamin Peterson82b00c12011-05-24 11:09:06 -05002660 Merge the __dict__ of aclass into dict, and recursively also all
2661 the __dict__s of aclass's base classes. The order of merging isn't
2662 defined, as it's expected that only the final set of dict keys is
2663 interesting.
2664 Return 0 on success, -1 on error.
2665*/
2666
2667static int
2668merge_class_dict(PyObject *dict, PyObject *aclass)
2669{
2670 PyObject *classdict;
2671 PyObject *bases;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02002672 _Py_IDENTIFIER(__bases__);
Benjamin Peterson82b00c12011-05-24 11:09:06 -05002673
2674 assert(PyDict_Check(dict));
2675 assert(aclass);
2676
2677 /* Merge in the type's dict (if any). */
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002678 classdict = _PyObject_GetAttrId(aclass, &PyId___dict__);
Benjamin Peterson82b00c12011-05-24 11:09:06 -05002679 if (classdict == NULL)
2680 PyErr_Clear();
2681 else {
2682 int status = PyDict_Update(dict, classdict);
2683 Py_DECREF(classdict);
2684 if (status < 0)
2685 return -1;
2686 }
2687
2688 /* Recursively merge in the base types' (if any) dicts. */
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002689 bases = _PyObject_GetAttrId(aclass, &PyId___bases__);
Benjamin Peterson82b00c12011-05-24 11:09:06 -05002690 if (bases == NULL)
2691 PyErr_Clear();
2692 else {
2693 /* We have no guarantee that bases is a real tuple */
2694 Py_ssize_t i, n;
2695 n = PySequence_Size(bases); /* This better be right */
2696 if (n < 0)
2697 PyErr_Clear();
2698 else {
2699 for (i = 0; i < n; i++) {
2700 int status;
2701 PyObject *base = PySequence_GetItem(bases, i);
2702 if (base == NULL) {
2703 Py_DECREF(bases);
2704 return -1;
2705 }
2706 status = merge_class_dict(dict, base);
2707 Py_DECREF(base);
2708 if (status < 0) {
2709 Py_DECREF(bases);
2710 return -1;
2711 }
2712 }
2713 }
2714 Py_DECREF(bases);
2715 }
2716 return 0;
2717}
2718
2719/* __dir__ for type objects: returns __dict__ and __bases__.
2720 We deliberately don't suck up its __class__, as methods belonging to the
2721 metaclass would probably be more confusing than helpful.
2722*/
2723static PyObject *
2724type_dir(PyObject *self, PyObject *args)
2725{
2726 PyObject *result = NULL;
2727 PyObject *dict = PyDict_New();
2728
2729 if (dict != NULL && merge_class_dict(dict, self) == 0)
2730 result = PyDict_Keys(dict);
2731
2732 Py_XDECREF(dict);
2733 return result;
2734}
2735
Tim Peters6d6c1a32001-08-02 04:15:00 +00002736static PyMethodDef type_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002737 {"mro", (PyCFunction)mro_external, METH_NOARGS,
2738 PyDoc_STR("mro() -> list\nreturn a type's method resolution order")},
2739 {"__subclasses__", (PyCFunction)type_subclasses, METH_NOARGS,
2740 PyDoc_STR("__subclasses__() -> list of immediate subclasses")},
2741 {"__prepare__", (PyCFunction)type_prepare,
2742 METH_VARARGS | METH_KEYWORDS | METH_CLASS,
2743 PyDoc_STR("__prepare__() -> dict\n"
2744 "used to create the namespace for the class statement")},
2745 {"__instancecheck__", type___instancecheck__, METH_O,
Benjamin Petersonfbe56bb2011-05-24 12:42:51 -05002746 PyDoc_STR("__instancecheck__() -> bool\ncheck if an object is an instance")},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002747 {"__subclasscheck__", type___subclasscheck__, METH_O,
Benjamin Petersonfbe56bb2011-05-24 12:42:51 -05002748 PyDoc_STR("__subclasscheck__() -> bool\ncheck if a class is a subclass")},
Benjamin Peterson82b00c12011-05-24 11:09:06 -05002749 {"__dir__", type_dir, METH_NOARGS,
Benjamin Petersonc7284122011-05-24 12:46:15 -05002750 PyDoc_STR("__dir__() -> list\nspecialized __dir__ implementation for types")},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002751 {0}
Tim Peters6d6c1a32001-08-02 04:15:00 +00002752};
2753
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002754PyDoc_STRVAR(type_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00002755"type(object) -> the object's type\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002756"type(name, bases, dict) -> a new type");
Tim Peters6d6c1a32001-08-02 04:15:00 +00002757
Guido van Rossum048eb752001-10-02 21:24:57 +00002758static int
2759type_traverse(PyTypeObject *type, visitproc visit, void *arg)
2760{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002761 /* Because of type_is_gc(), the collector only calls this
2762 for heaptypes. */
2763 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002764
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002765 Py_VISIT(type->tp_dict);
2766 Py_VISIT(type->tp_cache);
2767 Py_VISIT(type->tp_mro);
2768 Py_VISIT(type->tp_bases);
2769 Py_VISIT(type->tp_base);
Guido van Rossuma3862092002-06-10 15:24:42 +00002770
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002771 /* There's no need to visit type->tp_subclasses or
2772 ((PyHeapTypeObject *)type)->ht_slots, because they can't be involved
2773 in cycles; tp_subclasses is a list of weak references,
2774 and slots is a tuple of strings. */
Guido van Rossum048eb752001-10-02 21:24:57 +00002775
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002776 return 0;
Guido van Rossum048eb752001-10-02 21:24:57 +00002777}
2778
2779static int
2780type_clear(PyTypeObject *type)
2781{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002782 /* Because of type_is_gc(), the collector only calls this
2783 for heaptypes. */
2784 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002785
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002786 /* The only field we need to clear is tp_mro, which is part of a
2787 hard cycle (its first element is the class itself) that won't
2788 be broken otherwise (it's a tuple and tuples don't have a
2789 tp_clear handler). None of the other fields need to be
2790 cleared, and here's why:
Guido van Rossum048eb752001-10-02 21:24:57 +00002791
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002792 tp_dict:
2793 It is a dict, so the collector will call its tp_clear.
Guido van Rossuma3862092002-06-10 15:24:42 +00002794
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002795 tp_cache:
2796 Not used; if it were, it would be a dict.
Guido van Rossuma3862092002-06-10 15:24:42 +00002797
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002798 tp_bases, tp_base:
2799 If these are involved in a cycle, there must be at least
2800 one other, mutable object in the cycle, e.g. a base
2801 class's dict; the cycle will be broken that way.
Guido van Rossuma3862092002-06-10 15:24:42 +00002802
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002803 tp_subclasses:
2804 A list of weak references can't be part of a cycle; and
2805 lists have their own tp_clear.
Guido van Rossuma3862092002-06-10 15:24:42 +00002806
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002807 slots (in PyHeapTypeObject):
2808 A tuple of strings can't be part of a cycle.
2809 */
Guido van Rossuma3862092002-06-10 15:24:42 +00002810
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002811 Py_CLEAR(type->tp_mro);
Guido van Rossum048eb752001-10-02 21:24:57 +00002812
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002813 return 0;
Guido van Rossum048eb752001-10-02 21:24:57 +00002814}
2815
2816static int
2817type_is_gc(PyTypeObject *type)
2818{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002819 return type->tp_flags & Py_TPFLAGS_HEAPTYPE;
Guido van Rossum048eb752001-10-02 21:24:57 +00002820}
2821
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002822PyTypeObject PyType_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002823 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2824 "type", /* tp_name */
2825 sizeof(PyHeapTypeObject), /* tp_basicsize */
2826 sizeof(PyMemberDef), /* tp_itemsize */
2827 (destructor)type_dealloc, /* tp_dealloc */
2828 0, /* tp_print */
2829 0, /* tp_getattr */
2830 0, /* tp_setattr */
2831 0, /* tp_reserved */
2832 (reprfunc)type_repr, /* tp_repr */
2833 0, /* tp_as_number */
2834 0, /* tp_as_sequence */
2835 0, /* tp_as_mapping */
2836 0, /* tp_hash */
2837 (ternaryfunc)type_call, /* tp_call */
2838 0, /* tp_str */
2839 (getattrofunc)type_getattro, /* tp_getattro */
2840 (setattrofunc)type_setattro, /* tp_setattro */
2841 0, /* tp_as_buffer */
2842 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
2843 Py_TPFLAGS_BASETYPE | Py_TPFLAGS_TYPE_SUBCLASS, /* tp_flags */
2844 type_doc, /* tp_doc */
2845 (traverseproc)type_traverse, /* tp_traverse */
2846 (inquiry)type_clear, /* tp_clear */
2847 0, /* tp_richcompare */
2848 offsetof(PyTypeObject, tp_weaklist), /* tp_weaklistoffset */
2849 0, /* tp_iter */
2850 0, /* tp_iternext */
2851 type_methods, /* tp_methods */
2852 type_members, /* tp_members */
2853 type_getsets, /* tp_getset */
2854 0, /* tp_base */
2855 0, /* tp_dict */
2856 0, /* tp_descr_get */
2857 0, /* tp_descr_set */
2858 offsetof(PyTypeObject, tp_dict), /* tp_dictoffset */
2859 type_init, /* tp_init */
2860 0, /* tp_alloc */
2861 type_new, /* tp_new */
2862 PyObject_GC_Del, /* tp_free */
2863 (inquiry)type_is_gc, /* tp_is_gc */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002864};
Tim Peters6d6c1a32001-08-02 04:15:00 +00002865
2866
2867/* The base type of all types (eventually)... except itself. */
2868
Guido van Rossumd8faa362007-04-27 19:54:29 +00002869/* You may wonder why object.__new__() only complains about arguments
2870 when object.__init__() is not overridden, and vice versa.
2871
2872 Consider the use cases:
2873
2874 1. When neither is overridden, we want to hear complaints about
2875 excess (i.e., any) arguments, since their presence could
2876 indicate there's a bug.
2877
2878 2. When defining an Immutable type, we are likely to override only
2879 __new__(), since __init__() is called too late to initialize an
2880 Immutable object. Since __new__() defines the signature for the
2881 type, it would be a pain to have to override __init__() just to
2882 stop it from complaining about excess arguments.
2883
2884 3. When defining a Mutable type, we are likely to override only
2885 __init__(). So here the converse reasoning applies: we don't
2886 want to have to override __new__() just to stop it from
2887 complaining.
2888
2889 4. When __init__() is overridden, and the subclass __init__() calls
2890 object.__init__(), the latter should complain about excess
2891 arguments; ditto for __new__().
2892
2893 Use cases 2 and 3 make it unattractive to unconditionally check for
2894 excess arguments. The best solution that addresses all four use
2895 cases is as follows: __init__() complains about excess arguments
2896 unless __new__() is overridden and __init__() is not overridden
2897 (IOW, if __init__() is overridden or __new__() is not overridden);
2898 symmetrically, __new__() complains about excess arguments unless
2899 __init__() is overridden and __new__() is not overridden
2900 (IOW, if __new__() is overridden or __init__() is not overridden).
2901
2902 However, for backwards compatibility, this breaks too much code.
2903 Therefore, in 2.6, we'll *warn* about excess arguments when both
2904 methods are overridden; for all other cases we'll use the above
2905 rules.
2906
2907*/
2908
2909/* Forward */
2910static PyObject *
2911object_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
2912
2913static int
2914excess_args(PyObject *args, PyObject *kwds)
2915{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002916 return PyTuple_GET_SIZE(args) ||
2917 (kwds && PyDict_Check(kwds) && PyDict_Size(kwds));
Guido van Rossumd8faa362007-04-27 19:54:29 +00002918}
2919
Tim Peters6d6c1a32001-08-02 04:15:00 +00002920static int
2921object_init(PyObject *self, PyObject *args, PyObject *kwds)
2922{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002923 int err = 0;
2924 if (excess_args(args, kwds)) {
2925 PyTypeObject *type = Py_TYPE(self);
2926 if (type->tp_init != object_init &&
2927 type->tp_new != object_new)
2928 {
2929 err = PyErr_WarnEx(PyExc_DeprecationWarning,
2930 "object.__init__() takes no parameters",
2931 1);
2932 }
2933 else if (type->tp_init != object_init ||
2934 type->tp_new == object_new)
2935 {
2936 PyErr_SetString(PyExc_TypeError,
2937 "object.__init__() takes no parameters");
2938 err = -1;
2939 }
2940 }
2941 return err;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002942}
2943
Guido van Rossum298e4212003-02-13 16:30:16 +00002944static PyObject *
2945object_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2946{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002947 int err = 0;
2948 if (excess_args(args, kwds)) {
2949 if (type->tp_new != object_new &&
2950 type->tp_init != object_init)
2951 {
2952 err = PyErr_WarnEx(PyExc_DeprecationWarning,
2953 "object.__new__() takes no parameters",
2954 1);
2955 }
2956 else if (type->tp_new != object_new ||
2957 type->tp_init == object_init)
2958 {
2959 PyErr_SetString(PyExc_TypeError,
2960 "object.__new__() takes no parameters");
2961 err = -1;
2962 }
2963 }
2964 if (err < 0)
2965 return NULL;
Christian Heimes9e7f1d22008-02-28 12:27:11 +00002966
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002967 if (type->tp_flags & Py_TPFLAGS_IS_ABSTRACT) {
2968 static PyObject *comma = NULL;
2969 PyObject *abstract_methods = NULL;
2970 PyObject *builtins;
2971 PyObject *sorted;
2972 PyObject *sorted_methods = NULL;
2973 PyObject *joined = NULL;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02002974 _Py_IDENTIFIER(join);
Christian Heimes9e7f1d22008-02-28 12:27:11 +00002975
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002976 /* Compute ", ".join(sorted(type.__abstractmethods__))
2977 into joined. */
2978 abstract_methods = type_abstractmethods(type, NULL);
2979 if (abstract_methods == NULL)
2980 goto error;
2981 builtins = PyEval_GetBuiltins();
2982 if (builtins == NULL)
2983 goto error;
2984 sorted = PyDict_GetItemString(builtins, "sorted");
2985 if (sorted == NULL)
2986 goto error;
2987 sorted_methods = PyObject_CallFunctionObjArgs(sorted,
2988 abstract_methods,
2989 NULL);
2990 if (sorted_methods == NULL)
2991 goto error;
2992 if (comma == NULL) {
2993 comma = PyUnicode_InternFromString(", ");
2994 if (comma == NULL)
2995 goto error;
2996 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002997 joined = _PyObject_CallMethodId(comma, &PyId_join,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002998 "O", sorted_methods);
2999 if (joined == NULL)
3000 goto error;
Christian Heimes9e7f1d22008-02-28 12:27:11 +00003001
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003002 PyErr_Format(PyExc_TypeError,
3003 "Can't instantiate abstract class %s "
3004 "with abstract methods %U",
3005 type->tp_name,
3006 joined);
3007 error:
3008 Py_XDECREF(joined);
3009 Py_XDECREF(sorted_methods);
3010 Py_XDECREF(abstract_methods);
3011 return NULL;
3012 }
3013 return type->tp_alloc(type, 0);
Guido van Rossum298e4212003-02-13 16:30:16 +00003014}
3015
Tim Peters6d6c1a32001-08-02 04:15:00 +00003016static void
3017object_dealloc(PyObject *self)
3018{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003019 Py_TYPE(self)->tp_free(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003020}
3021
Guido van Rossum8e248182001-08-12 05:17:56 +00003022static PyObject *
3023object_repr(PyObject *self)
3024{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003025 PyTypeObject *type;
3026 PyObject *mod, *name, *rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00003027
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003028 type = Py_TYPE(self);
3029 mod = type_module(type, NULL);
3030 if (mod == NULL)
3031 PyErr_Clear();
3032 else if (!PyUnicode_Check(mod)) {
3033 Py_DECREF(mod);
3034 mod = NULL;
3035 }
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003036 name = type_qualname(type, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003037 if (name == NULL)
3038 return NULL;
3039 if (mod != NULL && PyUnicode_CompareWithASCIIString(mod, "builtins"))
3040 rtn = PyUnicode_FromFormat("<%U.%U object at %p>", mod, name, self);
3041 else
3042 rtn = PyUnicode_FromFormat("<%s object at %p>",
3043 type->tp_name, self);
3044 Py_XDECREF(mod);
3045 Py_DECREF(name);
3046 return rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00003047}
3048
Guido van Rossumb8f63662001-08-15 23:57:02 +00003049static PyObject *
3050object_str(PyObject *self)
3051{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003052 unaryfunc f;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003053
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003054 f = Py_TYPE(self)->tp_repr;
Antoine Pitrou8cdc40e2011-07-15 21:15:07 +02003055 if (f == NULL || f == object_str)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003056 f = object_repr;
3057 return f(self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003058}
3059
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003060static PyObject *
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003061object_richcompare(PyObject *self, PyObject *other, int op)
3062{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003063 PyObject *res;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003064
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003065 switch (op) {
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003066
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003067 case Py_EQ:
3068 /* Return NotImplemented instead of False, so if two
3069 objects are compared, both get a chance at the
3070 comparison. See issue #1393. */
3071 res = (self == other) ? Py_True : Py_NotImplemented;
3072 Py_INCREF(res);
3073 break;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003074
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003075 case Py_NE:
3076 /* By default, != returns the opposite of ==,
3077 unless the latter returns NotImplemented. */
3078 res = PyObject_RichCompare(self, other, Py_EQ);
3079 if (res != NULL && res != Py_NotImplemented) {
3080 int ok = PyObject_IsTrue(res);
3081 Py_DECREF(res);
3082 if (ok < 0)
3083 res = NULL;
3084 else {
3085 if (ok)
3086 res = Py_False;
3087 else
3088 res = Py_True;
3089 Py_INCREF(res);
3090 }
3091 }
3092 break;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003093
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003094 default:
3095 res = Py_NotImplemented;
3096 Py_INCREF(res);
3097 break;
3098 }
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003099
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003100 return res;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003101}
3102
3103static PyObject *
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003104object_get_class(PyObject *self, void *closure)
3105{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003106 Py_INCREF(Py_TYPE(self));
3107 return (PyObject *)(Py_TYPE(self));
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003108}
3109
3110static int
3111equiv_structs(PyTypeObject *a, PyTypeObject *b)
3112{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003113 return a == b ||
3114 (a != NULL &&
3115 b != NULL &&
3116 a->tp_basicsize == b->tp_basicsize &&
3117 a->tp_itemsize == b->tp_itemsize &&
3118 a->tp_dictoffset == b->tp_dictoffset &&
3119 a->tp_weaklistoffset == b->tp_weaklistoffset &&
3120 ((a->tp_flags & Py_TPFLAGS_HAVE_GC) ==
3121 (b->tp_flags & Py_TPFLAGS_HAVE_GC)));
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003122}
3123
3124static int
3125same_slots_added(PyTypeObject *a, PyTypeObject *b)
3126{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003127 PyTypeObject *base = a->tp_base;
3128 Py_ssize_t size;
3129 PyObject *slots_a, *slots_b;
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003130
Benjamin Peterson67641d22011-01-17 19:24:34 +00003131 assert(base == b->tp_base);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003132 size = base->tp_basicsize;
3133 if (a->tp_dictoffset == size && b->tp_dictoffset == size)
3134 size += sizeof(PyObject *);
3135 if (a->tp_weaklistoffset == size && b->tp_weaklistoffset == size)
3136 size += sizeof(PyObject *);
Guido van Rossumd8faa362007-04-27 19:54:29 +00003137
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003138 /* Check slots compliance */
3139 slots_a = ((PyHeapTypeObject *)a)->ht_slots;
3140 slots_b = ((PyHeapTypeObject *)b)->ht_slots;
3141 if (slots_a && slots_b) {
3142 if (PyObject_RichCompareBool(slots_a, slots_b, Py_EQ) != 1)
3143 return 0;
3144 size += sizeof(PyObject *) * PyTuple_GET_SIZE(slots_a);
3145 }
3146 return size == a->tp_basicsize && size == b->tp_basicsize;
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003147}
3148
3149static int
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003150compatible_for_assignment(PyTypeObject* oldto, PyTypeObject* newto, char* attr)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003151{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003152 PyTypeObject *newbase, *oldbase;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003153
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003154 if (newto->tp_dealloc != oldto->tp_dealloc ||
3155 newto->tp_free != oldto->tp_free)
3156 {
3157 PyErr_Format(PyExc_TypeError,
3158 "%s assignment: "
3159 "'%s' deallocator differs from '%s'",
3160 attr,
3161 newto->tp_name,
3162 oldto->tp_name);
3163 return 0;
3164 }
3165 newbase = newto;
3166 oldbase = oldto;
3167 while (equiv_structs(newbase, newbase->tp_base))
3168 newbase = newbase->tp_base;
3169 while (equiv_structs(oldbase, oldbase->tp_base))
3170 oldbase = oldbase->tp_base;
3171 if (newbase != oldbase &&
3172 (newbase->tp_base != oldbase->tp_base ||
3173 !same_slots_added(newbase, oldbase))) {
3174 PyErr_Format(PyExc_TypeError,
3175 "%s assignment: "
3176 "'%s' object layout differs from '%s'",
3177 attr,
3178 newto->tp_name,
3179 oldto->tp_name);
3180 return 0;
3181 }
Tim Petersea7f75d2002-12-07 21:39:16 +00003182
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003183 return 1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003184}
3185
3186static int
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003187object_set_class(PyObject *self, PyObject *value, void *closure)
3188{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003189 PyTypeObject *oldto = Py_TYPE(self);
3190 PyTypeObject *newto;
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003191
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003192 if (value == NULL) {
3193 PyErr_SetString(PyExc_TypeError,
3194 "can't delete __class__ attribute");
3195 return -1;
3196 }
3197 if (!PyType_Check(value)) {
3198 PyErr_Format(PyExc_TypeError,
3199 "__class__ must be set to new-style class, not '%s' object",
3200 Py_TYPE(value)->tp_name);
3201 return -1;
3202 }
3203 newto = (PyTypeObject *)value;
3204 if (!(newto->tp_flags & Py_TPFLAGS_HEAPTYPE) ||
3205 !(oldto->tp_flags & Py_TPFLAGS_HEAPTYPE))
3206 {
3207 PyErr_Format(PyExc_TypeError,
3208 "__class__ assignment: only for heap types");
3209 return -1;
3210 }
3211 if (compatible_for_assignment(newto, oldto, "__class__")) {
3212 Py_INCREF(newto);
3213 Py_TYPE(self) = newto;
3214 Py_DECREF(oldto);
3215 return 0;
3216 }
3217 else {
3218 return -1;
3219 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003220}
3221
3222static PyGetSetDef object_getsets[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003223 {"__class__", object_get_class, object_set_class,
3224 PyDoc_STR("the object's class")},
3225 {0}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003226};
3227
Guido van Rossumc53f0092003-02-18 22:05:12 +00003228
Guido van Rossum036f9992003-02-21 22:02:54 +00003229/* Stuff to implement __reduce_ex__ for pickle protocols >= 2.
Alexandre Vassalottif7fa63d2008-05-11 08:55:36 +00003230 We fall back to helpers in copyreg for:
Guido van Rossum036f9992003-02-21 22:02:54 +00003231 - pickle protocols < 2
3232 - calculating the list of slot names (done only once per class)
3233 - the __newobj__ function (which is used as a token but never called)
3234*/
3235
3236static PyObject *
Alexandre Vassalottif7fa63d2008-05-11 08:55:36 +00003237import_copyreg(void)
Guido van Rossum036f9992003-02-21 22:02:54 +00003238{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003239 static PyObject *copyreg_str;
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003240 static PyObject *mod_copyreg = NULL;
Guido van Rossum3926a632001-09-25 16:25:58 +00003241
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003242 if (!copyreg_str) {
3243 copyreg_str = PyUnicode_InternFromString("copyreg");
3244 if (copyreg_str == NULL)
3245 return NULL;
3246 }
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003247 if (!mod_copyreg) {
3248 mod_copyreg = PyImport_Import(copyreg_str);
3249 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003250
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003251 Py_XINCREF(mod_copyreg);
3252 return mod_copyreg;
Guido van Rossum036f9992003-02-21 22:02:54 +00003253}
3254
3255static PyObject *
3256slotnames(PyObject *cls)
3257{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003258 PyObject *clsdict;
3259 PyObject *copyreg;
3260 PyObject *slotnames;
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003261 static PyObject *str_slotnames;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02003262 _Py_IDENTIFIER(_slotnames);
Guido van Rossum036f9992003-02-21 22:02:54 +00003263
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003264 if (str_slotnames == NULL) {
3265 str_slotnames = PyUnicode_InternFromString("__slotnames__");
3266 if (str_slotnames == NULL)
3267 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003268 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003269
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003270 clsdict = ((PyTypeObject *)cls)->tp_dict;
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003271 slotnames = PyDict_GetItem(clsdict, str_slotnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003272 if (slotnames != NULL && PyList_Check(slotnames)) {
3273 Py_INCREF(slotnames);
3274 return slotnames;
3275 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003276
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003277 copyreg = import_copyreg();
3278 if (copyreg == NULL)
3279 return NULL;
Guido van Rossum036f9992003-02-21 22:02:54 +00003280
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02003281 slotnames = _PyObject_CallMethodId(copyreg, &PyId__slotnames, "O", cls);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003282 Py_DECREF(copyreg);
3283 if (slotnames != NULL &&
3284 slotnames != Py_None &&
3285 !PyList_Check(slotnames))
3286 {
3287 PyErr_SetString(PyExc_TypeError,
3288 "copyreg._slotnames didn't return a list or None");
3289 Py_DECREF(slotnames);
3290 slotnames = NULL;
3291 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003292
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003293 return slotnames;
Guido van Rossum036f9992003-02-21 22:02:54 +00003294}
3295
3296static PyObject *
3297reduce_2(PyObject *obj)
3298{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003299 PyObject *cls, *getnewargs;
3300 PyObject *args = NULL, *args2 = NULL;
3301 PyObject *getstate = NULL, *state = NULL, *names = NULL;
3302 PyObject *slots = NULL, *listitems = NULL, *dictitems = NULL;
3303 PyObject *copyreg = NULL, *newobj = NULL, *res = NULL;
3304 Py_ssize_t i, n;
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003305 static PyObject *str_getnewargs = NULL, *str_getstate = NULL,
3306 *str_newobj = NULL;
Guido van Rossum036f9992003-02-21 22:02:54 +00003307
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003308 if (str_getnewargs == NULL) {
3309 str_getnewargs = PyUnicode_InternFromString("__getnewargs__");
3310 str_getstate = PyUnicode_InternFromString("__getstate__");
3311 str_newobj = PyUnicode_InternFromString("__newobj__");
3312 if (!str_getnewargs || !str_getstate || !str_newobj)
3313 return NULL;
3314 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003315
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003316 cls = (PyObject *) Py_TYPE(obj);
3317
3318 getnewargs = PyObject_GetAttr(obj, str_getnewargs);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003319 if (getnewargs != NULL) {
3320 args = PyObject_CallObject(getnewargs, NULL);
3321 Py_DECREF(getnewargs);
3322 if (args != NULL && !PyTuple_Check(args)) {
3323 PyErr_Format(PyExc_TypeError,
3324 "__getnewargs__ should return a tuple, "
3325 "not '%.200s'", Py_TYPE(args)->tp_name);
3326 goto end;
3327 }
3328 }
3329 else {
3330 PyErr_Clear();
3331 args = PyTuple_New(0);
3332 }
3333 if (args == NULL)
3334 goto end;
Guido van Rossum036f9992003-02-21 22:02:54 +00003335
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003336 getstate = PyObject_GetAttr(obj, str_getstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003337 if (getstate != NULL) {
3338 state = PyObject_CallObject(getstate, NULL);
3339 Py_DECREF(getstate);
3340 if (state == NULL)
3341 goto end;
3342 }
3343 else {
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003344 PyObject **dict;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003345 PyErr_Clear();
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003346 dict = _PyObject_GetDictPtr(obj);
3347 if (dict && *dict)
3348 state = *dict;
3349 else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003350 state = Py_None;
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003351 Py_INCREF(state);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003352 names = slotnames(cls);
3353 if (names == NULL)
3354 goto end;
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003355 if (names != Py_None && PyList_GET_SIZE(names) > 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003356 assert(PyList_Check(names));
3357 slots = PyDict_New();
3358 if (slots == NULL)
3359 goto end;
3360 n = 0;
3361 /* Can't pre-compute the list size; the list
3362 is stored on the class so accessible to other
3363 threads, which may be run by DECREF */
3364 for (i = 0; i < PyList_GET_SIZE(names); i++) {
3365 PyObject *name, *value;
3366 name = PyList_GET_ITEM(names, i);
3367 value = PyObject_GetAttr(obj, name);
3368 if (value == NULL)
3369 PyErr_Clear();
3370 else {
3371 int err = PyDict_SetItem(slots, name,
3372 value);
3373 Py_DECREF(value);
3374 if (err)
3375 goto end;
3376 n++;
3377 }
3378 }
3379 if (n) {
3380 state = Py_BuildValue("(NO)", state, slots);
3381 if (state == NULL)
3382 goto end;
3383 }
3384 }
3385 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003386
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003387 if (!PyList_Check(obj)) {
3388 listitems = Py_None;
3389 Py_INCREF(listitems);
3390 }
3391 else {
3392 listitems = PyObject_GetIter(obj);
3393 if (listitems == NULL)
3394 goto end;
3395 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003396
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003397 if (!PyDict_Check(obj)) {
3398 dictitems = Py_None;
3399 Py_INCREF(dictitems);
3400 }
3401 else {
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02003402 _Py_IDENTIFIER(items);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02003403 PyObject *items = _PyObject_CallMethodId(obj, &PyId_items, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003404 if (items == NULL)
3405 goto end;
3406 dictitems = PyObject_GetIter(items);
3407 Py_DECREF(items);
3408 if (dictitems == NULL)
3409 goto end;
3410 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003411
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003412 copyreg = import_copyreg();
3413 if (copyreg == NULL)
3414 goto end;
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003415 newobj = PyObject_GetAttr(copyreg, str_newobj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003416 if (newobj == NULL)
3417 goto end;
Guido van Rossum036f9992003-02-21 22:02:54 +00003418
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003419 n = PyTuple_GET_SIZE(args);
3420 args2 = PyTuple_New(n+1);
3421 if (args2 == NULL)
3422 goto end;
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003423 Py_INCREF(cls);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003424 PyTuple_SET_ITEM(args2, 0, cls);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003425 for (i = 0; i < n; i++) {
3426 PyObject *v = PyTuple_GET_ITEM(args, i);
3427 Py_INCREF(v);
3428 PyTuple_SET_ITEM(args2, i+1, v);
3429 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003430
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003431 res = PyTuple_Pack(5, newobj, args2, state, listitems, dictitems);
Guido van Rossum036f9992003-02-21 22:02:54 +00003432
3433 end:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003434 Py_XDECREF(args);
3435 Py_XDECREF(args2);
3436 Py_XDECREF(slots);
3437 Py_XDECREF(state);
3438 Py_XDECREF(names);
3439 Py_XDECREF(listitems);
3440 Py_XDECREF(dictitems);
3441 Py_XDECREF(copyreg);
3442 Py_XDECREF(newobj);
3443 return res;
Guido van Rossum036f9992003-02-21 22:02:54 +00003444}
3445
Guido van Rossumd8faa362007-04-27 19:54:29 +00003446/*
3447 * There were two problems when object.__reduce__ and object.__reduce_ex__
3448 * were implemented in the same function:
3449 * - trying to pickle an object with a custom __reduce__ method that
3450 * fell back to object.__reduce__ in certain circumstances led to
3451 * infinite recursion at Python level and eventual RuntimeError.
3452 * - Pickling objects that lied about their type by overwriting the
3453 * __class__ descriptor could lead to infinite recursion at C level
3454 * and eventual segfault.
3455 *
3456 * Because of backwards compatibility, the two methods still have to
3457 * behave in the same way, even if this is not required by the pickle
3458 * protocol. This common functionality was moved to the _common_reduce
3459 * function.
3460 */
3461static PyObject *
3462_common_reduce(PyObject *self, int proto)
3463{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003464 PyObject *copyreg, *res;
Guido van Rossumd8faa362007-04-27 19:54:29 +00003465
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003466 if (proto >= 2)
3467 return reduce_2(self);
Guido van Rossumd8faa362007-04-27 19:54:29 +00003468
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003469 copyreg = import_copyreg();
3470 if (!copyreg)
3471 return NULL;
Guido van Rossumd8faa362007-04-27 19:54:29 +00003472
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003473 res = PyEval_CallMethod(copyreg, "_reduce_ex", "(Oi)", self, proto);
3474 Py_DECREF(copyreg);
Guido van Rossumd8faa362007-04-27 19:54:29 +00003475
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003476 return res;
Guido van Rossumd8faa362007-04-27 19:54:29 +00003477}
3478
3479static PyObject *
3480object_reduce(PyObject *self, PyObject *args)
3481{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003482 int proto = 0;
Guido van Rossumd8faa362007-04-27 19:54:29 +00003483
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003484 if (!PyArg_ParseTuple(args, "|i:__reduce__", &proto))
3485 return NULL;
Guido van Rossumd8faa362007-04-27 19:54:29 +00003486
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003487 return _common_reduce(self, proto);
Guido van Rossumd8faa362007-04-27 19:54:29 +00003488}
3489
Guido van Rossum036f9992003-02-21 22:02:54 +00003490static PyObject *
3491object_reduce_ex(PyObject *self, PyObject *args)
3492{
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003493 static PyObject *str_reduce = NULL, *objreduce;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003494 PyObject *reduce, *res;
3495 int proto = 0;
Guido van Rossum036f9992003-02-21 22:02:54 +00003496
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003497 if (!PyArg_ParseTuple(args, "|i:__reduce_ex__", &proto))
3498 return NULL;
Guido van Rossum036f9992003-02-21 22:02:54 +00003499
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003500 if (str_reduce == NULL) {
3501 str_reduce = PyUnicode_InternFromString("__reduce__");
3502 objreduce = PyDict_GetItemString(PyBaseObject_Type.tp_dict,
3503 "__reduce__");
3504 if (str_reduce == NULL || objreduce == NULL)
3505 return NULL;
3506 }
3507
3508 reduce = PyObject_GetAttr(self, str_reduce);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003509 if (reduce == NULL)
3510 PyErr_Clear();
3511 else {
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003512 PyObject *cls, *clsreduce;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003513 int override;
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003514
3515 cls = (PyObject *) Py_TYPE(self);
3516 clsreduce = PyObject_GetAttr(cls, str_reduce);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003517 if (clsreduce == NULL) {
3518 Py_DECREF(reduce);
3519 return NULL;
3520 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003521 override = (clsreduce != objreduce);
3522 Py_DECREF(clsreduce);
3523 if (override) {
3524 res = PyObject_CallObject(reduce, NULL);
3525 Py_DECREF(reduce);
3526 return res;
3527 }
3528 else
3529 Py_DECREF(reduce);
3530 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003531
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003532 return _common_reduce(self, proto);
Guido van Rossum3926a632001-09-25 16:25:58 +00003533}
3534
Christian Heimes9e7f1d22008-02-28 12:27:11 +00003535static PyObject *
3536object_subclasshook(PyObject *cls, PyObject *args)
3537{
Brian Curtindfc80e32011-08-10 20:28:54 -05003538 Py_RETURN_NOTIMPLEMENTED;
Christian Heimes9e7f1d22008-02-28 12:27:11 +00003539}
3540
3541PyDoc_STRVAR(object_subclasshook_doc,
3542"Abstract classes can override this to customize issubclass().\n"
3543"\n"
3544"This is invoked early on by abc.ABCMeta.__subclasscheck__().\n"
3545"It should return True, False or NotImplemented. If it returns\n"
3546"NotImplemented, the normal algorithm is used. Otherwise, it\n"
3547"overrides the normal algorithm (and the outcome is cached).\n");
Eric Smith8c663262007-08-25 02:26:07 +00003548
3549/*
3550 from PEP 3101, this code implements:
3551
3552 class object:
3553 def __format__(self, format_spec):
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003554 return format(str(self), format_spec)
Eric Smith8c663262007-08-25 02:26:07 +00003555*/
3556static PyObject *
3557object_format(PyObject *self, PyObject *args)
3558{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003559 PyObject *format_spec;
3560 PyObject *self_as_str = NULL;
3561 PyObject *result = NULL;
Eric Smith8c663262007-08-25 02:26:07 +00003562
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003563 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
3564 return NULL;
Eric Smith8c663262007-08-25 02:26:07 +00003565
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003566 self_as_str = PyObject_Str(self);
Eric Smithe4d63172010-09-13 20:48:43 +00003567 if (self_as_str != NULL) {
3568 /* Issue 7994: If we're converting to a string, we
Eric V. Smithb9cd3532011-03-12 10:08:48 -05003569 should reject format specifications */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003570 if (PyUnicode_GET_LENGTH(format_spec) > 0) {
Eric V. Smithb9cd3532011-03-12 10:08:48 -05003571 if (PyErr_WarnEx(PyExc_DeprecationWarning,
3572 "object.__format__ with a non-empty format "
3573 "string is deprecated", 1) < 0) {
3574 goto done;
3575 }
3576 /* Eventually this will become an error:
3577 PyErr_Format(PyExc_TypeError,
3578 "non-empty format string passed to object.__format__");
3579 goto done;
3580 */
3581 }
Eric Smith8c663262007-08-25 02:26:07 +00003582
Eric V. Smithb9cd3532011-03-12 10:08:48 -05003583 result = PyObject_Format(self_as_str, format_spec);
Eric Smithe4d63172010-09-13 20:48:43 +00003584 }
3585
3586done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003587 Py_XDECREF(self_as_str);
Eric Smith8c663262007-08-25 02:26:07 +00003588
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003589 return result;
Eric Smith8c663262007-08-25 02:26:07 +00003590}
3591
Martin v. Löwis00709aa2008-06-04 14:18:43 +00003592static PyObject *
3593object_sizeof(PyObject *self, PyObject *args)
3594{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003595 Py_ssize_t res, isize;
Martin v. Löwis00709aa2008-06-04 14:18:43 +00003596
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003597 res = 0;
3598 isize = self->ob_type->tp_itemsize;
3599 if (isize > 0)
3600 res = Py_SIZE(self->ob_type) * isize;
3601 res += self->ob_type->tp_basicsize;
Martin v. Löwis00709aa2008-06-04 14:18:43 +00003602
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003603 return PyLong_FromSsize_t(res);
Martin v. Löwis00709aa2008-06-04 14:18:43 +00003604}
3605
Benjamin Peterson82b00c12011-05-24 11:09:06 -05003606/* __dir__ for generic objects: returns __dict__, __class__,
3607 and recursively up the __class__.__bases__ chain.
3608*/
3609static PyObject *
3610object_dir(PyObject *self, PyObject *args)
3611{
3612 PyObject *result = NULL;
3613 PyObject *dict = NULL;
3614 PyObject *itsclass = NULL;
3615
3616 /* Get __dict__ (which may or may not be a real dict...) */
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02003617 dict = _PyObject_GetAttrId(self, &PyId___dict__);
Benjamin Peterson82b00c12011-05-24 11:09:06 -05003618 if (dict == NULL) {
3619 PyErr_Clear();
3620 dict = PyDict_New();
3621 }
3622 else if (!PyDict_Check(dict)) {
3623 Py_DECREF(dict);
3624 dict = PyDict_New();
3625 }
3626 else {
3627 /* Copy __dict__ to avoid mutating it. */
3628 PyObject *temp = PyDict_Copy(dict);
3629 Py_DECREF(dict);
3630 dict = temp;
3631 }
3632
3633 if (dict == NULL)
3634 goto error;
3635
3636 /* Merge in attrs reachable from its class. */
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02003637 itsclass = _PyObject_GetAttrId(self, &PyId___class__);
Benjamin Peterson82b00c12011-05-24 11:09:06 -05003638 if (itsclass == NULL)
3639 /* XXX(tomer): Perhaps fall back to obj->ob_type if no
3640 __class__ exists? */
3641 PyErr_Clear();
3642 else if (merge_class_dict(dict, itsclass) != 0)
3643 goto error;
3644
3645 result = PyDict_Keys(dict);
3646 /* fall through */
3647error:
3648 Py_XDECREF(itsclass);
3649 Py_XDECREF(dict);
3650 return result;
3651}
3652
Guido van Rossum3926a632001-09-25 16:25:58 +00003653static PyMethodDef object_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003654 {"__reduce_ex__", object_reduce_ex, METH_VARARGS,
3655 PyDoc_STR("helper for pickle")},
3656 {"__reduce__", object_reduce, METH_VARARGS,
3657 PyDoc_STR("helper for pickle")},
3658 {"__subclasshook__", object_subclasshook, METH_CLASS | METH_VARARGS,
3659 object_subclasshook_doc},
3660 {"__format__", object_format, METH_VARARGS,
3661 PyDoc_STR("default object formatter")},
3662 {"__sizeof__", object_sizeof, METH_NOARGS,
Benjamin Petersonfbe56bb2011-05-24 12:42:51 -05003663 PyDoc_STR("__sizeof__() -> int\nsize of object in memory, in bytes")},
Benjamin Peterson82b00c12011-05-24 11:09:06 -05003664 {"__dir__", object_dir, METH_NOARGS,
Benjamin Petersonc7284122011-05-24 12:46:15 -05003665 PyDoc_STR("__dir__() -> list\ndefault dir() implementation")},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003666 {0}
Guido van Rossum3926a632001-09-25 16:25:58 +00003667};
3668
Guido van Rossum036f9992003-02-21 22:02:54 +00003669
Tim Peters6d6c1a32001-08-02 04:15:00 +00003670PyTypeObject PyBaseObject_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003671 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3672 "object", /* tp_name */
3673 sizeof(PyObject), /* tp_basicsize */
3674 0, /* tp_itemsize */
3675 object_dealloc, /* tp_dealloc */
3676 0, /* tp_print */
3677 0, /* tp_getattr */
3678 0, /* tp_setattr */
3679 0, /* tp_reserved */
3680 object_repr, /* tp_repr */
3681 0, /* tp_as_number */
3682 0, /* tp_as_sequence */
3683 0, /* tp_as_mapping */
3684 (hashfunc)_Py_HashPointer, /* tp_hash */
3685 0, /* tp_call */
3686 object_str, /* tp_str */
3687 PyObject_GenericGetAttr, /* tp_getattro */
3688 PyObject_GenericSetAttr, /* tp_setattro */
3689 0, /* tp_as_buffer */
3690 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
3691 PyDoc_STR("The most base type"), /* tp_doc */
3692 0, /* tp_traverse */
3693 0, /* tp_clear */
3694 object_richcompare, /* tp_richcompare */
3695 0, /* tp_weaklistoffset */
3696 0, /* tp_iter */
3697 0, /* tp_iternext */
3698 object_methods, /* tp_methods */
3699 0, /* tp_members */
3700 object_getsets, /* tp_getset */
3701 0, /* tp_base */
3702 0, /* tp_dict */
3703 0, /* tp_descr_get */
3704 0, /* tp_descr_set */
3705 0, /* tp_dictoffset */
3706 object_init, /* tp_init */
3707 PyType_GenericAlloc, /* tp_alloc */
3708 object_new, /* tp_new */
3709 PyObject_Del, /* tp_free */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003710};
3711
3712
Guido van Rossum50e9fb92006-08-17 05:42:55 +00003713/* Add the methods from tp_methods to the __dict__ in a type object */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003714
3715static int
3716add_methods(PyTypeObject *type, PyMethodDef *meth)
3717{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003718 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003719
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003720 for (; meth->ml_name != NULL; meth++) {
3721 PyObject *descr;
3722 if (PyDict_GetItemString(dict, meth->ml_name) &&
3723 !(meth->ml_flags & METH_COEXIST))
3724 continue;
3725 if (meth->ml_flags & METH_CLASS) {
3726 if (meth->ml_flags & METH_STATIC) {
3727 PyErr_SetString(PyExc_ValueError,
3728 "method cannot be both class and static");
3729 return -1;
3730 }
3731 descr = PyDescr_NewClassMethod(type, meth);
3732 }
3733 else if (meth->ml_flags & METH_STATIC) {
3734 PyObject *cfunc = PyCFunction_New(meth, NULL);
3735 if (cfunc == NULL)
3736 return -1;
3737 descr = PyStaticMethod_New(cfunc);
3738 Py_DECREF(cfunc);
3739 }
3740 else {
3741 descr = PyDescr_NewMethod(type, meth);
3742 }
3743 if (descr == NULL)
3744 return -1;
3745 if (PyDict_SetItemString(dict, meth->ml_name, descr) < 0)
3746 return -1;
3747 Py_DECREF(descr);
3748 }
3749 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003750}
3751
3752static int
Guido van Rossum6f799372001-09-20 20:46:19 +00003753add_members(PyTypeObject *type, PyMemberDef *memb)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003754{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003755 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003756
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003757 for (; memb->name != NULL; memb++) {
3758 PyObject *descr;
3759 if (PyDict_GetItemString(dict, memb->name))
3760 continue;
3761 descr = PyDescr_NewMember(type, memb);
3762 if (descr == NULL)
3763 return -1;
3764 if (PyDict_SetItemString(dict, memb->name, descr) < 0)
3765 return -1;
3766 Py_DECREF(descr);
3767 }
3768 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003769}
3770
3771static int
Guido van Rossum32d34c82001-09-20 21:45:26 +00003772add_getset(PyTypeObject *type, PyGetSetDef *gsp)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003773{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003774 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003775
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003776 for (; gsp->name != NULL; gsp++) {
3777 PyObject *descr;
3778 if (PyDict_GetItemString(dict, gsp->name))
3779 continue;
3780 descr = PyDescr_NewGetSet(type, gsp);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003781
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003782 if (descr == NULL)
3783 return -1;
3784 if (PyDict_SetItemString(dict, gsp->name, descr) < 0)
3785 return -1;
3786 Py_DECREF(descr);
3787 }
3788 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003789}
3790
Guido van Rossum13d52f02001-08-10 21:24:08 +00003791static void
3792inherit_special(PyTypeObject *type, PyTypeObject *base)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003793{
Tim Peters6d6c1a32001-08-02 04:15:00 +00003794
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003795 /* Copying basicsize is connected to the GC flags */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003796 if (!(type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
3797 (base->tp_flags & Py_TPFLAGS_HAVE_GC) &&
3798 (!type->tp_traverse && !type->tp_clear)) {
3799 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
3800 if (type->tp_traverse == NULL)
3801 type->tp_traverse = base->tp_traverse;
3802 if (type->tp_clear == NULL)
3803 type->tp_clear = base->tp_clear;
3804 }
3805 {
3806 /* The condition below could use some explanation.
3807 It appears that tp_new is not inherited for static types
3808 whose base class is 'object'; this seems to be a precaution
3809 so that old extension types don't suddenly become
3810 callable (object.__new__ wouldn't insure the invariants
3811 that the extension type's own factory function ensures).
3812 Heap types, of course, are under our control, so they do
3813 inherit tp_new; static extension types that specify some
3814 other built-in type as the default are considered
3815 new-style-aware so they also inherit object.__new__. */
3816 if (base != &PyBaseObject_Type ||
3817 (type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
3818 if (type->tp_new == NULL)
3819 type->tp_new = base->tp_new;
3820 }
3821 }
Benjamin Petersona7465e22010-07-05 15:01:22 +00003822 if (type->tp_basicsize == 0)
3823 type->tp_basicsize = base->tp_basicsize;
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00003824
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003825 /* Copy other non-function slots */
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00003826
3827#undef COPYVAL
3828#define COPYVAL(SLOT) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003829 if (type->SLOT == 0) type->SLOT = base->SLOT
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00003830
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003831 COPYVAL(tp_itemsize);
3832 COPYVAL(tp_weaklistoffset);
3833 COPYVAL(tp_dictoffset);
Thomas Wouters27d517b2007-02-25 20:39:11 +00003834
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003835 /* Setup fast subclass flags */
3836 if (PyType_IsSubtype(base, (PyTypeObject*)PyExc_BaseException))
3837 type->tp_flags |= Py_TPFLAGS_BASE_EXC_SUBCLASS;
3838 else if (PyType_IsSubtype(base, &PyType_Type))
3839 type->tp_flags |= Py_TPFLAGS_TYPE_SUBCLASS;
3840 else if (PyType_IsSubtype(base, &PyLong_Type))
3841 type->tp_flags |= Py_TPFLAGS_LONG_SUBCLASS;
3842 else if (PyType_IsSubtype(base, &PyBytes_Type))
3843 type->tp_flags |= Py_TPFLAGS_BYTES_SUBCLASS;
3844 else if (PyType_IsSubtype(base, &PyUnicode_Type))
3845 type->tp_flags |= Py_TPFLAGS_UNICODE_SUBCLASS;
3846 else if (PyType_IsSubtype(base, &PyTuple_Type))
3847 type->tp_flags |= Py_TPFLAGS_TUPLE_SUBCLASS;
3848 else if (PyType_IsSubtype(base, &PyList_Type))
3849 type->tp_flags |= Py_TPFLAGS_LIST_SUBCLASS;
3850 else if (PyType_IsSubtype(base, &PyDict_Type))
3851 type->tp_flags |= Py_TPFLAGS_DICT_SUBCLASS;
Guido van Rossum13d52f02001-08-10 21:24:08 +00003852}
3853
Guido van Rossumf5243f02008-01-01 04:06:48 +00003854static char *hash_name_op[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003855 "__eq__",
3856 "__hash__",
3857 NULL
Guido van Rossum38938152006-08-21 23:36:26 +00003858};
3859
3860static int
Guido van Rossumf5243f02008-01-01 04:06:48 +00003861overrides_hash(PyTypeObject *type)
Guido van Rossum38938152006-08-21 23:36:26 +00003862{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003863 char **p;
3864 PyObject *dict = type->tp_dict;
Guido van Rossum38938152006-08-21 23:36:26 +00003865
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003866 assert(dict != NULL);
3867 for (p = hash_name_op; *p; p++) {
3868 if (PyDict_GetItemString(dict, *p) != NULL)
3869 return 1;
3870 }
3871 return 0;
Guido van Rossum38938152006-08-21 23:36:26 +00003872}
3873
Guido van Rossum13d52f02001-08-10 21:24:08 +00003874static void
3875inherit_slots(PyTypeObject *type, PyTypeObject *base)
3876{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003877 PyTypeObject *basebase;
Guido van Rossum13d52f02001-08-10 21:24:08 +00003878
3879#undef SLOTDEFINED
Tim Peters6d6c1a32001-08-02 04:15:00 +00003880#undef COPYSLOT
3881#undef COPYNUM
3882#undef COPYSEQ
3883#undef COPYMAP
Guido van Rossum5af588b2001-10-12 14:13:21 +00003884#undef COPYBUF
Guido van Rossum13d52f02001-08-10 21:24:08 +00003885
3886#define SLOTDEFINED(SLOT) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003887 (base->SLOT != 0 && \
3888 (basebase == NULL || base->SLOT != basebase->SLOT))
Guido van Rossum13d52f02001-08-10 21:24:08 +00003889
Tim Peters6d6c1a32001-08-02 04:15:00 +00003890#define COPYSLOT(SLOT) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003891 if (!type->SLOT && SLOTDEFINED(SLOT)) type->SLOT = base->SLOT
Tim Peters6d6c1a32001-08-02 04:15:00 +00003892
3893#define COPYNUM(SLOT) COPYSLOT(tp_as_number->SLOT)
3894#define COPYSEQ(SLOT) COPYSLOT(tp_as_sequence->SLOT)
3895#define COPYMAP(SLOT) COPYSLOT(tp_as_mapping->SLOT)
Tim Petersfc57ccb2001-10-12 02:38:24 +00003896#define COPYBUF(SLOT) COPYSLOT(tp_as_buffer->SLOT)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003897
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003898 /* This won't inherit indirect slots (from tp_as_number etc.)
3899 if type doesn't provide the space. */
Guido van Rossum13d52f02001-08-10 21:24:08 +00003900
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003901 if (type->tp_as_number != NULL && base->tp_as_number != NULL) {
3902 basebase = base->tp_base;
3903 if (basebase->tp_as_number == NULL)
3904 basebase = NULL;
3905 COPYNUM(nb_add);
3906 COPYNUM(nb_subtract);
3907 COPYNUM(nb_multiply);
3908 COPYNUM(nb_remainder);
3909 COPYNUM(nb_divmod);
3910 COPYNUM(nb_power);
3911 COPYNUM(nb_negative);
3912 COPYNUM(nb_positive);
3913 COPYNUM(nb_absolute);
3914 COPYNUM(nb_bool);
3915 COPYNUM(nb_invert);
3916 COPYNUM(nb_lshift);
3917 COPYNUM(nb_rshift);
3918 COPYNUM(nb_and);
3919 COPYNUM(nb_xor);
3920 COPYNUM(nb_or);
3921 COPYNUM(nb_int);
3922 COPYNUM(nb_float);
3923 COPYNUM(nb_inplace_add);
3924 COPYNUM(nb_inplace_subtract);
3925 COPYNUM(nb_inplace_multiply);
3926 COPYNUM(nb_inplace_remainder);
3927 COPYNUM(nb_inplace_power);
3928 COPYNUM(nb_inplace_lshift);
3929 COPYNUM(nb_inplace_rshift);
3930 COPYNUM(nb_inplace_and);
3931 COPYNUM(nb_inplace_xor);
3932 COPYNUM(nb_inplace_or);
3933 COPYNUM(nb_true_divide);
3934 COPYNUM(nb_floor_divide);
3935 COPYNUM(nb_inplace_true_divide);
3936 COPYNUM(nb_inplace_floor_divide);
3937 COPYNUM(nb_index);
3938 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003939
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003940 if (type->tp_as_sequence != NULL && base->tp_as_sequence != NULL) {
3941 basebase = base->tp_base;
3942 if (basebase->tp_as_sequence == NULL)
3943 basebase = NULL;
3944 COPYSEQ(sq_length);
3945 COPYSEQ(sq_concat);
3946 COPYSEQ(sq_repeat);
3947 COPYSEQ(sq_item);
3948 COPYSEQ(sq_ass_item);
3949 COPYSEQ(sq_contains);
3950 COPYSEQ(sq_inplace_concat);
3951 COPYSEQ(sq_inplace_repeat);
3952 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003953
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003954 if (type->tp_as_mapping != NULL && base->tp_as_mapping != NULL) {
3955 basebase = base->tp_base;
3956 if (basebase->tp_as_mapping == NULL)
3957 basebase = NULL;
3958 COPYMAP(mp_length);
3959 COPYMAP(mp_subscript);
3960 COPYMAP(mp_ass_subscript);
3961 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003962
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003963 if (type->tp_as_buffer != NULL && base->tp_as_buffer != NULL) {
3964 basebase = base->tp_base;
3965 if (basebase->tp_as_buffer == NULL)
3966 basebase = NULL;
3967 COPYBUF(bf_getbuffer);
3968 COPYBUF(bf_releasebuffer);
3969 }
Tim Petersfc57ccb2001-10-12 02:38:24 +00003970
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003971 basebase = base->tp_base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003972
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003973 COPYSLOT(tp_dealloc);
3974 if (type->tp_getattr == NULL && type->tp_getattro == NULL) {
3975 type->tp_getattr = base->tp_getattr;
3976 type->tp_getattro = base->tp_getattro;
3977 }
3978 if (type->tp_setattr == NULL && type->tp_setattro == NULL) {
3979 type->tp_setattr = base->tp_setattr;
3980 type->tp_setattro = base->tp_setattro;
3981 }
3982 /* tp_reserved is ignored */
3983 COPYSLOT(tp_repr);
3984 /* tp_hash see tp_richcompare */
3985 COPYSLOT(tp_call);
3986 COPYSLOT(tp_str);
3987 {
3988 /* Copy comparison-related slots only when
3989 not overriding them anywhere */
3990 if (type->tp_richcompare == NULL &&
3991 type->tp_hash == NULL &&
3992 !overrides_hash(type))
3993 {
3994 type->tp_richcompare = base->tp_richcompare;
3995 type->tp_hash = base->tp_hash;
3996 }
3997 }
3998 {
3999 COPYSLOT(tp_iter);
4000 COPYSLOT(tp_iternext);
4001 }
4002 {
4003 COPYSLOT(tp_descr_get);
4004 COPYSLOT(tp_descr_set);
4005 COPYSLOT(tp_dictoffset);
4006 COPYSLOT(tp_init);
4007 COPYSLOT(tp_alloc);
4008 COPYSLOT(tp_is_gc);
4009 if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) ==
4010 (base->tp_flags & Py_TPFLAGS_HAVE_GC)) {
4011 /* They agree about gc. */
4012 COPYSLOT(tp_free);
4013 }
4014 else if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
4015 type->tp_free == NULL &&
4016 base->tp_free == PyObject_Free) {
4017 /* A bit of magic to plug in the correct default
4018 * tp_free function when a derived class adds gc,
4019 * didn't define tp_free, and the base uses the
4020 * default non-gc tp_free.
4021 */
4022 type->tp_free = PyObject_GC_Del;
4023 }
4024 /* else they didn't agree about gc, and there isn't something
4025 * obvious to be done -- the type is on its own.
4026 */
4027 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004028}
4029
Jeremy Hylton938ace62002-07-17 16:30:39 +00004030static int add_operators(PyTypeObject *);
Guido van Rossum13d52f02001-08-10 21:24:08 +00004031
Tim Peters6d6c1a32001-08-02 04:15:00 +00004032int
Guido van Rossum528b7eb2001-08-07 17:24:28 +00004033PyType_Ready(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004034{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004035 PyObject *dict, *bases;
4036 PyTypeObject *base;
4037 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004038
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004039 if (type->tp_flags & Py_TPFLAGS_READY) {
4040 assert(type->tp_dict != NULL);
4041 return 0;
4042 }
4043 assert((type->tp_flags & Py_TPFLAGS_READYING) == 0);
Guido van Rossumd614f972001-08-10 17:39:49 +00004044
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004045 type->tp_flags |= Py_TPFLAGS_READYING;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004046
Tim Peters36eb4df2003-03-23 03:33:13 +00004047#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004048 /* PyType_Ready is the closest thing we have to a choke point
4049 * for type objects, so is the best place I can think of to try
4050 * to get type objects into the doubly-linked list of all objects.
4051 * Still, not all type objects go thru PyType_Ready.
4052 */
4053 _Py_AddToAllObjects((PyObject *)type, 0);
Tim Peters36eb4df2003-03-23 03:33:13 +00004054#endif
4055
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004056 /* Initialize tp_base (defaults to BaseObject unless that's us) */
4057 base = type->tp_base;
4058 if (base == NULL && type != &PyBaseObject_Type) {
4059 base = type->tp_base = &PyBaseObject_Type;
4060 Py_INCREF(base);
4061 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004062
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004063 /* Now the only way base can still be NULL is if type is
4064 * &PyBaseObject_Type.
4065 */
Guido van Rossum692cdbc2006-03-10 02:04:28 +00004066
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004067 /* Initialize the base class */
4068 if (base != NULL && base->tp_dict == NULL) {
4069 if (PyType_Ready(base) < 0)
4070 goto error;
4071 }
Guido van Rossum323a9cf2002-08-14 17:26:30 +00004072
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004073 /* Initialize ob_type if NULL. This means extensions that want to be
4074 compilable separately on Windows can call PyType_Ready() instead of
4075 initializing the ob_type field of their type objects. */
4076 /* The test for base != NULL is really unnecessary, since base is only
4077 NULL when type is &PyBaseObject_Type, and we know its ob_type is
4078 not NULL (it's initialized to &PyType_Type). But coverity doesn't
4079 know that. */
4080 if (Py_TYPE(type) == NULL && base != NULL)
4081 Py_TYPE(type) = Py_TYPE(base);
Guido van Rossum0986d822002-04-08 01:38:42 +00004082
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004083 /* Initialize tp_bases */
4084 bases = type->tp_bases;
4085 if (bases == NULL) {
4086 if (base == NULL)
4087 bases = PyTuple_New(0);
4088 else
4089 bases = PyTuple_Pack(1, base);
4090 if (bases == NULL)
4091 goto error;
4092 type->tp_bases = bases;
4093 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004094
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004095 /* Initialize tp_dict */
4096 dict = type->tp_dict;
4097 if (dict == NULL) {
4098 dict = PyDict_New();
4099 if (dict == NULL)
4100 goto error;
4101 type->tp_dict = dict;
4102 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004103
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004104 /* Add type-specific descriptors to tp_dict */
4105 if (add_operators(type) < 0)
4106 goto error;
4107 if (type->tp_methods != NULL) {
4108 if (add_methods(type, type->tp_methods) < 0)
4109 goto error;
4110 }
4111 if (type->tp_members != NULL) {
4112 if (add_members(type, type->tp_members) < 0)
4113 goto error;
4114 }
4115 if (type->tp_getset != NULL) {
4116 if (add_getset(type, type->tp_getset) < 0)
4117 goto error;
4118 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004119
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004120 /* Calculate method resolution order */
4121 if (mro_internal(type) < 0) {
4122 goto error;
4123 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004124
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004125 /* Inherit special flags from dominant base */
4126 if (type->tp_base != NULL)
4127 inherit_special(type, type->tp_base);
Guido van Rossum13d52f02001-08-10 21:24:08 +00004128
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004129 /* Initialize tp_dict properly */
4130 bases = type->tp_mro;
4131 assert(bases != NULL);
4132 assert(PyTuple_Check(bases));
4133 n = PyTuple_GET_SIZE(bases);
4134 for (i = 1; i < n; i++) {
4135 PyObject *b = PyTuple_GET_ITEM(bases, i);
4136 if (PyType_Check(b))
4137 inherit_slots(type, (PyTypeObject *)b);
4138 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004139
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004140 /* Sanity check for tp_free. */
4141 if (PyType_IS_GC(type) && (type->tp_flags & Py_TPFLAGS_BASETYPE) &&
4142 (type->tp_free == NULL || type->tp_free == PyObject_Del)) {
4143 /* This base class needs to call tp_free, but doesn't have
4144 * one, or its tp_free is for non-gc'ed objects.
4145 */
4146 PyErr_Format(PyExc_TypeError, "type '%.100s' participates in "
4147 "gc and is a base type but has inappropriate "
4148 "tp_free slot",
4149 type->tp_name);
4150 goto error;
4151 }
Tim Peters3cfe7542003-05-21 21:29:48 +00004152
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004153 /* if the type dictionary doesn't contain a __doc__, set it from
4154 the tp_doc slot.
4155 */
4156 if (PyDict_GetItemString(type->tp_dict, "__doc__") == NULL) {
4157 if (type->tp_doc != NULL) {
4158 PyObject *doc = PyUnicode_FromString(type->tp_doc);
4159 if (doc == NULL)
4160 goto error;
4161 PyDict_SetItemString(type->tp_dict, "__doc__", doc);
4162 Py_DECREF(doc);
4163 } else {
4164 PyDict_SetItemString(type->tp_dict,
4165 "__doc__", Py_None);
4166 }
4167 }
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00004168
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004169 /* Hack for tp_hash and __hash__.
4170 If after all that, tp_hash is still NULL, and __hash__ is not in
4171 tp_dict, set tp_hash to PyObject_HashNotImplemented and
4172 tp_dict['__hash__'] equal to None.
4173 This signals that __hash__ is not inherited.
4174 */
4175 if (type->tp_hash == NULL) {
4176 if (PyDict_GetItemString(type->tp_dict, "__hash__") == NULL) {
4177 if (PyDict_SetItemString(type->tp_dict, "__hash__", Py_None) < 0)
4178 goto error;
4179 type->tp_hash = PyObject_HashNotImplemented;
4180 }
4181 }
Guido van Rossum38938152006-08-21 23:36:26 +00004182
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004183 /* Some more special stuff */
4184 base = type->tp_base;
4185 if (base != NULL) {
4186 if (type->tp_as_number == NULL)
4187 type->tp_as_number = base->tp_as_number;
4188 if (type->tp_as_sequence == NULL)
4189 type->tp_as_sequence = base->tp_as_sequence;
4190 if (type->tp_as_mapping == NULL)
4191 type->tp_as_mapping = base->tp_as_mapping;
4192 if (type->tp_as_buffer == NULL)
4193 type->tp_as_buffer = base->tp_as_buffer;
4194 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004195
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004196 /* Link into each base class's list of subclasses */
4197 bases = type->tp_bases;
4198 n = PyTuple_GET_SIZE(bases);
4199 for (i = 0; i < n; i++) {
4200 PyObject *b = PyTuple_GET_ITEM(bases, i);
4201 if (PyType_Check(b) &&
4202 add_subclass((PyTypeObject *)b, type) < 0)
4203 goto error;
4204 }
Guido van Rossum1c450732001-10-08 15:18:27 +00004205
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004206 /* Warn for a type that implements tp_compare (now known as
4207 tp_reserved) but not tp_richcompare. */
4208 if (type->tp_reserved && !type->tp_richcompare) {
4209 int error;
Victor Stinner4a2b7a12010-08-13 14:03:48 +00004210 error = PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
4211 "Type %.100s defines tp_reserved (formerly tp_compare) "
4212 "but not tp_richcompare. Comparisons may not behave as intended.",
4213 type->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004214 if (error == -1)
4215 goto error;
4216 }
Mark Dickinson2a7d45b2009-02-08 11:02:10 +00004217
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004218 /* All done -- set the ready flag */
4219 assert(type->tp_dict != NULL);
4220 type->tp_flags =
4221 (type->tp_flags & ~Py_TPFLAGS_READYING) | Py_TPFLAGS_READY;
4222 return 0;
Guido van Rossumd614f972001-08-10 17:39:49 +00004223
4224 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004225 type->tp_flags &= ~Py_TPFLAGS_READYING;
4226 return -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004227}
4228
Guido van Rossum1c450732001-10-08 15:18:27 +00004229static int
4230add_subclass(PyTypeObject *base, PyTypeObject *type)
4231{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004232 Py_ssize_t i;
4233 int result;
4234 PyObject *list, *ref, *newobj;
Guido van Rossum1c450732001-10-08 15:18:27 +00004235
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004236 list = base->tp_subclasses;
4237 if (list == NULL) {
4238 base->tp_subclasses = list = PyList_New(0);
4239 if (list == NULL)
4240 return -1;
4241 }
4242 assert(PyList_Check(list));
4243 newobj = PyWeakref_NewRef((PyObject *)type, NULL);
4244 i = PyList_GET_SIZE(list);
4245 while (--i >= 0) {
4246 ref = PyList_GET_ITEM(list, i);
4247 assert(PyWeakref_CheckRef(ref));
4248 if (PyWeakref_GET_OBJECT(ref) == Py_None)
4249 return PyList_SetItem(list, i, newobj);
4250 }
4251 result = PyList_Append(list, newobj);
4252 Py_DECREF(newobj);
4253 return result;
Guido van Rossum1c450732001-10-08 15:18:27 +00004254}
4255
Michael W. Hudson98bbc492002-11-26 14:47:27 +00004256static void
4257remove_subclass(PyTypeObject *base, PyTypeObject *type)
4258{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004259 Py_ssize_t i;
4260 PyObject *list, *ref;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00004261
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004262 list = base->tp_subclasses;
4263 if (list == NULL) {
4264 return;
4265 }
4266 assert(PyList_Check(list));
4267 i = PyList_GET_SIZE(list);
4268 while (--i >= 0) {
4269 ref = PyList_GET_ITEM(list, i);
4270 assert(PyWeakref_CheckRef(ref));
4271 if (PyWeakref_GET_OBJECT(ref) == (PyObject*)type) {
4272 /* this can't fail, right? */
4273 PySequence_DelItem(list, i);
4274 return;
4275 }
4276 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +00004277}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004278
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004279static int
4280check_num_args(PyObject *ob, int n)
4281{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004282 if (!PyTuple_CheckExact(ob)) {
4283 PyErr_SetString(PyExc_SystemError,
4284 "PyArg_UnpackTuple() argument list is not a tuple");
4285 return 0;
4286 }
4287 if (n == PyTuple_GET_SIZE(ob))
4288 return 1;
4289 PyErr_Format(
4290 PyExc_TypeError,
4291 "expected %d arguments, got %zd", n, PyTuple_GET_SIZE(ob));
4292 return 0;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004293}
4294
Tim Peters6d6c1a32001-08-02 04:15:00 +00004295/* Generic wrappers for overloadable 'operators' such as __getitem__ */
4296
4297/* There's a wrapper *function* for each distinct function typedef used
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004298 for type object slots (e.g. binaryfunc, ternaryfunc, etc.). There's a
Tim Peters6d6c1a32001-08-02 04:15:00 +00004299 wrapper *table* for each distinct operation (e.g. __len__, __add__).
4300 Most tables have only one entry; the tables for binary operators have two
4301 entries, one regular and one with reversed arguments. */
4302
4303static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00004304wrap_lenfunc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004305{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004306 lenfunc func = (lenfunc)wrapped;
4307 Py_ssize_t res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004308
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004309 if (!check_num_args(args, 0))
4310 return NULL;
4311 res = (*func)(self);
4312 if (res == -1 && PyErr_Occurred())
4313 return NULL;
4314 return PyLong_FromLong((long)res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004315}
4316
Tim Peters6d6c1a32001-08-02 04:15:00 +00004317static PyObject *
Raymond Hettingerf34f2642003-10-11 17:29:04 +00004318wrap_inquirypred(PyObject *self, PyObject *args, void *wrapped)
4319{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004320 inquiry func = (inquiry)wrapped;
4321 int res;
Raymond Hettingerf34f2642003-10-11 17:29:04 +00004322
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004323 if (!check_num_args(args, 0))
4324 return NULL;
4325 res = (*func)(self);
4326 if (res == -1 && PyErr_Occurred())
4327 return NULL;
4328 return PyBool_FromLong((long)res);
Raymond Hettingerf34f2642003-10-11 17:29:04 +00004329}
4330
4331static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00004332wrap_binaryfunc(PyObject *self, PyObject *args, void *wrapped)
4333{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004334 binaryfunc func = (binaryfunc)wrapped;
4335 PyObject *other;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004336
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004337 if (!check_num_args(args, 1))
4338 return NULL;
4339 other = PyTuple_GET_ITEM(args, 0);
4340 return (*func)(self, other);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004341}
4342
4343static PyObject *
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00004344wrap_binaryfunc_l(PyObject *self, PyObject *args, void *wrapped)
4345{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004346 binaryfunc func = (binaryfunc)wrapped;
4347 PyObject *other;
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00004348
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004349 if (!check_num_args(args, 1))
4350 return NULL;
4351 other = PyTuple_GET_ITEM(args, 0);
4352 return (*func)(self, other);
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00004353}
4354
4355static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00004356wrap_binaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
4357{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004358 binaryfunc func = (binaryfunc)wrapped;
4359 PyObject *other;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004360
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004361 if (!check_num_args(args, 1))
4362 return NULL;
4363 other = PyTuple_GET_ITEM(args, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004364 return (*func)(other, self);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004365}
4366
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004367static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00004368wrap_ternaryfunc(PyObject *self, PyObject *args, void *wrapped)
4369{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004370 ternaryfunc func = (ternaryfunc)wrapped;
4371 PyObject *other;
4372 PyObject *third = Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004373
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004374 /* Note: This wrapper only works for __pow__() */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004375
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004376 if (!PyArg_UnpackTuple(args, "", 1, 2, &other, &third))
4377 return NULL;
4378 return (*func)(self, other, third);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004379}
4380
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00004381static PyObject *
4382wrap_ternaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
4383{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004384 ternaryfunc func = (ternaryfunc)wrapped;
4385 PyObject *other;
4386 PyObject *third = Py_None;
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00004387
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004388 /* Note: This wrapper only works for __pow__() */
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00004389
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004390 if (!PyArg_UnpackTuple(args, "", 1, 2, &other, &third))
4391 return NULL;
4392 return (*func)(other, self, third);
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00004393}
4394
Tim Peters6d6c1a32001-08-02 04:15:00 +00004395static PyObject *
4396wrap_unaryfunc(PyObject *self, PyObject *args, void *wrapped)
4397{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004398 unaryfunc func = (unaryfunc)wrapped;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004399
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004400 if (!check_num_args(args, 0))
4401 return NULL;
4402 return (*func)(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004403}
4404
Tim Peters6d6c1a32001-08-02 04:15:00 +00004405static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004406wrap_indexargfunc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004407{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004408 ssizeargfunc func = (ssizeargfunc)wrapped;
4409 PyObject* o;
4410 Py_ssize_t i;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004411
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004412 if (!PyArg_UnpackTuple(args, "", 1, 1, &o))
4413 return NULL;
4414 i = PyNumber_AsSsize_t(o, PyExc_OverflowError);
4415 if (i == -1 && PyErr_Occurred())
4416 return NULL;
4417 return (*func)(self, i);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004418}
4419
Martin v. Löwis18e16552006-02-15 17:27:45 +00004420static Py_ssize_t
Guido van Rossum5d815f32001-08-17 21:57:47 +00004421getindex(PyObject *self, PyObject *arg)
4422{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004423 Py_ssize_t i;
Guido van Rossum5d815f32001-08-17 21:57:47 +00004424
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004425 i = PyNumber_AsSsize_t(arg, PyExc_OverflowError);
4426 if (i == -1 && PyErr_Occurred())
4427 return -1;
4428 if (i < 0) {
4429 PySequenceMethods *sq = Py_TYPE(self)->tp_as_sequence;
4430 if (sq && sq->sq_length) {
4431 Py_ssize_t n = (*sq->sq_length)(self);
4432 if (n < 0)
4433 return -1;
4434 i += n;
4435 }
4436 }
4437 return i;
Guido van Rossum5d815f32001-08-17 21:57:47 +00004438}
4439
4440static PyObject *
4441wrap_sq_item(PyObject *self, PyObject *args, void *wrapped)
4442{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004443 ssizeargfunc func = (ssizeargfunc)wrapped;
4444 PyObject *arg;
4445 Py_ssize_t i;
Guido van Rossum5d815f32001-08-17 21:57:47 +00004446
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004447 if (PyTuple_GET_SIZE(args) == 1) {
4448 arg = PyTuple_GET_ITEM(args, 0);
4449 i = getindex(self, arg);
4450 if (i == -1 && PyErr_Occurred())
4451 return NULL;
4452 return (*func)(self, i);
4453 }
4454 check_num_args(args, 1);
4455 assert(PyErr_Occurred());
4456 return NULL;
Guido van Rossum5d815f32001-08-17 21:57:47 +00004457}
4458
Tim Peters6d6c1a32001-08-02 04:15:00 +00004459static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00004460wrap_sq_setitem(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004461{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004462 ssizeobjargproc func = (ssizeobjargproc)wrapped;
4463 Py_ssize_t i;
4464 int res;
4465 PyObject *arg, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004466
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004467 if (!PyArg_UnpackTuple(args, "", 2, 2, &arg, &value))
4468 return NULL;
4469 i = getindex(self, arg);
4470 if (i == -1 && PyErr_Occurred())
4471 return NULL;
4472 res = (*func)(self, i, value);
4473 if (res == -1 && PyErr_Occurred())
4474 return NULL;
4475 Py_INCREF(Py_None);
4476 return Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004477}
4478
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004479static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00004480wrap_sq_delitem(PyObject *self, PyObject *args, void *wrapped)
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004481{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004482 ssizeobjargproc func = (ssizeobjargproc)wrapped;
4483 Py_ssize_t i;
4484 int res;
4485 PyObject *arg;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004486
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004487 if (!check_num_args(args, 1))
4488 return NULL;
4489 arg = PyTuple_GET_ITEM(args, 0);
4490 i = getindex(self, arg);
4491 if (i == -1 && PyErr_Occurred())
4492 return NULL;
4493 res = (*func)(self, i, NULL);
4494 if (res == -1 && PyErr_Occurred())
4495 return NULL;
4496 Py_INCREF(Py_None);
4497 return Py_None;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004498}
4499
Tim Peters6d6c1a32001-08-02 04:15:00 +00004500/* XXX objobjproc is a misnomer; should be objargpred */
4501static PyObject *
4502wrap_objobjproc(PyObject *self, PyObject *args, void *wrapped)
4503{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004504 objobjproc func = (objobjproc)wrapped;
4505 int res;
4506 PyObject *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004507
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004508 if (!check_num_args(args, 1))
4509 return NULL;
4510 value = PyTuple_GET_ITEM(args, 0);
4511 res = (*func)(self, value);
4512 if (res == -1 && PyErr_Occurred())
4513 return NULL;
4514 else
4515 return PyBool_FromLong(res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004516}
4517
Tim Peters6d6c1a32001-08-02 04:15:00 +00004518static PyObject *
4519wrap_objobjargproc(PyObject *self, PyObject *args, void *wrapped)
4520{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004521 objobjargproc func = (objobjargproc)wrapped;
4522 int res;
4523 PyObject *key, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004524
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004525 if (!PyArg_UnpackTuple(args, "", 2, 2, &key, &value))
4526 return NULL;
4527 res = (*func)(self, key, value);
4528 if (res == -1 && PyErr_Occurred())
4529 return NULL;
4530 Py_INCREF(Py_None);
4531 return Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004532}
4533
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004534static PyObject *
4535wrap_delitem(PyObject *self, PyObject *args, void *wrapped)
4536{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004537 objobjargproc func = (objobjargproc)wrapped;
4538 int res;
4539 PyObject *key;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004540
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004541 if (!check_num_args(args, 1))
4542 return NULL;
4543 key = PyTuple_GET_ITEM(args, 0);
4544 res = (*func)(self, key, NULL);
4545 if (res == -1 && PyErr_Occurred())
4546 return NULL;
4547 Py_INCREF(Py_None);
4548 return Py_None;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004549}
4550
Guido van Rossum4dcdb782003-04-14 21:46:03 +00004551/* Helper to check for object.__setattr__ or __delattr__ applied to a type.
Guido van Rossum52b27052003-04-15 20:05:10 +00004552 This is called the Carlo Verre hack after its discoverer. */
Guido van Rossum4dcdb782003-04-14 21:46:03 +00004553static int
4554hackcheck(PyObject *self, setattrofunc func, char *what)
4555{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004556 PyTypeObject *type = Py_TYPE(self);
4557 while (type && type->tp_flags & Py_TPFLAGS_HEAPTYPE)
4558 type = type->tp_base;
4559 /* If type is NULL now, this is a really weird type.
4560 In the spirit of backwards compatibility (?), just shut up. */
4561 if (type && type->tp_setattro != func) {
4562 PyErr_Format(PyExc_TypeError,
4563 "can't apply this %s to %s object",
4564 what,
4565 type->tp_name);
4566 return 0;
4567 }
4568 return 1;
Guido van Rossum4dcdb782003-04-14 21:46:03 +00004569}
4570
Tim Peters6d6c1a32001-08-02 04:15:00 +00004571static PyObject *
4572wrap_setattr(PyObject *self, PyObject *args, void *wrapped)
4573{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004574 setattrofunc func = (setattrofunc)wrapped;
4575 int res;
4576 PyObject *name, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004577
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004578 if (!PyArg_UnpackTuple(args, "", 2, 2, &name, &value))
4579 return NULL;
4580 if (!hackcheck(self, func, "__setattr__"))
4581 return NULL;
4582 res = (*func)(self, name, value);
4583 if (res < 0)
4584 return NULL;
4585 Py_INCREF(Py_None);
4586 return Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004587}
4588
4589static PyObject *
4590wrap_delattr(PyObject *self, PyObject *args, void *wrapped)
4591{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004592 setattrofunc func = (setattrofunc)wrapped;
4593 int res;
4594 PyObject *name;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004595
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004596 if (!check_num_args(args, 1))
4597 return NULL;
4598 name = PyTuple_GET_ITEM(args, 0);
4599 if (!hackcheck(self, func, "__delattr__"))
4600 return NULL;
4601 res = (*func)(self, name, NULL);
4602 if (res < 0)
4603 return NULL;
4604 Py_INCREF(Py_None);
4605 return Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004606}
4607
Tim Peters6d6c1a32001-08-02 04:15:00 +00004608static PyObject *
4609wrap_hashfunc(PyObject *self, PyObject *args, void *wrapped)
4610{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004611 hashfunc func = (hashfunc)wrapped;
Benjamin Peterson8035bc52010-10-23 16:20:50 +00004612 Py_hash_t res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004613
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004614 if (!check_num_args(args, 0))
4615 return NULL;
4616 res = (*func)(self);
4617 if (res == -1 && PyErr_Occurred())
4618 return NULL;
Benjamin Peterson8035bc52010-10-23 16:20:50 +00004619 return PyLong_FromSsize_t(res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004620}
4621
Tim Peters6d6c1a32001-08-02 04:15:00 +00004622static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00004623wrap_call(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004624{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004625 ternaryfunc func = (ternaryfunc)wrapped;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004626
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004627 return (*func)(self, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004628}
4629
Tim Peters6d6c1a32001-08-02 04:15:00 +00004630static PyObject *
4631wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op)
4632{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004633 richcmpfunc func = (richcmpfunc)wrapped;
4634 PyObject *other;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004635
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004636 if (!check_num_args(args, 1))
4637 return NULL;
4638 other = PyTuple_GET_ITEM(args, 0);
4639 return (*func)(self, other, op);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004640}
4641
4642#undef RICHCMP_WRAPPER
4643#define RICHCMP_WRAPPER(NAME, OP) \
4644static PyObject * \
4645richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \
4646{ \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004647 return wrap_richcmpfunc(self, args, wrapped, OP); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004648}
4649
Jack Jansen8e938b42001-08-08 15:29:49 +00004650RICHCMP_WRAPPER(lt, Py_LT)
4651RICHCMP_WRAPPER(le, Py_LE)
4652RICHCMP_WRAPPER(eq, Py_EQ)
4653RICHCMP_WRAPPER(ne, Py_NE)
4654RICHCMP_WRAPPER(gt, Py_GT)
4655RICHCMP_WRAPPER(ge, Py_GE)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004656
Tim Peters6d6c1a32001-08-02 04:15:00 +00004657static PyObject *
4658wrap_next(PyObject *self, PyObject *args, void *wrapped)
4659{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004660 unaryfunc func = (unaryfunc)wrapped;
4661 PyObject *res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004662
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004663 if (!check_num_args(args, 0))
4664 return NULL;
4665 res = (*func)(self);
4666 if (res == NULL && !PyErr_Occurred())
4667 PyErr_SetNone(PyExc_StopIteration);
4668 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004669}
4670
Tim Peters6d6c1a32001-08-02 04:15:00 +00004671static PyObject *
4672wrap_descr_get(PyObject *self, PyObject *args, void *wrapped)
4673{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004674 descrgetfunc func = (descrgetfunc)wrapped;
4675 PyObject *obj;
4676 PyObject *type = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004677
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004678 if (!PyArg_UnpackTuple(args, "", 1, 2, &obj, &type))
4679 return NULL;
4680 if (obj == Py_None)
4681 obj = NULL;
4682 if (type == Py_None)
4683 type = NULL;
4684 if (type == NULL &&obj == NULL) {
4685 PyErr_SetString(PyExc_TypeError,
4686 "__get__(None, None) is invalid");
4687 return NULL;
4688 }
4689 return (*func)(self, obj, type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004690}
4691
Tim Peters6d6c1a32001-08-02 04:15:00 +00004692static PyObject *
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004693wrap_descr_set(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004694{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004695 descrsetfunc func = (descrsetfunc)wrapped;
4696 PyObject *obj, *value;
4697 int ret;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004698
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004699 if (!PyArg_UnpackTuple(args, "", 2, 2, &obj, &value))
4700 return NULL;
4701 ret = (*func)(self, obj, value);
4702 if (ret < 0)
4703 return NULL;
4704 Py_INCREF(Py_None);
4705 return Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004706}
Guido van Rossum22b13872002-08-06 21:41:44 +00004707
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00004708static PyObject *
4709wrap_descr_delete(PyObject *self, PyObject *args, void *wrapped)
4710{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004711 descrsetfunc func = (descrsetfunc)wrapped;
4712 PyObject *obj;
4713 int ret;
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00004714
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004715 if (!check_num_args(args, 1))
4716 return NULL;
4717 obj = PyTuple_GET_ITEM(args, 0);
4718 ret = (*func)(self, obj, NULL);
4719 if (ret < 0)
4720 return NULL;
4721 Py_INCREF(Py_None);
4722 return Py_None;
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00004723}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004724
Tim Peters6d6c1a32001-08-02 04:15:00 +00004725static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00004726wrap_init(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004727{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004728 initproc func = (initproc)wrapped;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004729
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004730 if (func(self, args, kwds) < 0)
4731 return NULL;
4732 Py_INCREF(Py_None);
4733 return Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004734}
4735
Tim Peters6d6c1a32001-08-02 04:15:00 +00004736static PyObject *
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004737tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004738{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004739 PyTypeObject *type, *subtype, *staticbase;
4740 PyObject *arg0, *res;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004741
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004742 if (self == NULL || !PyType_Check(self))
4743 Py_FatalError("__new__() called with non-type 'self'");
4744 type = (PyTypeObject *)self;
4745 if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) {
4746 PyErr_Format(PyExc_TypeError,
4747 "%s.__new__(): not enough arguments",
4748 type->tp_name);
4749 return NULL;
4750 }
4751 arg0 = PyTuple_GET_ITEM(args, 0);
4752 if (!PyType_Check(arg0)) {
4753 PyErr_Format(PyExc_TypeError,
4754 "%s.__new__(X): X is not a type object (%s)",
4755 type->tp_name,
4756 Py_TYPE(arg0)->tp_name);
4757 return NULL;
4758 }
4759 subtype = (PyTypeObject *)arg0;
4760 if (!PyType_IsSubtype(subtype, type)) {
4761 PyErr_Format(PyExc_TypeError,
4762 "%s.__new__(%s): %s is not a subtype of %s",
4763 type->tp_name,
4764 subtype->tp_name,
4765 subtype->tp_name,
4766 type->tp_name);
4767 return NULL;
4768 }
Barry Warsaw60f01882001-08-22 19:24:42 +00004769
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004770 /* Check that the use doesn't do something silly and unsafe like
4771 object.__new__(dict). To do this, we check that the
4772 most derived base that's not a heap type is this type. */
4773 staticbase = subtype;
4774 while (staticbase && (staticbase->tp_flags & Py_TPFLAGS_HEAPTYPE))
4775 staticbase = staticbase->tp_base;
4776 /* If staticbase is NULL now, it is a really weird type.
4777 In the spirit of backwards compatibility (?), just shut up. */
4778 if (staticbase && staticbase->tp_new != type->tp_new) {
4779 PyErr_Format(PyExc_TypeError,
4780 "%s.__new__(%s) is not safe, use %s.__new__()",
4781 type->tp_name,
4782 subtype->tp_name,
4783 staticbase == NULL ? "?" : staticbase->tp_name);
4784 return NULL;
4785 }
Barry Warsaw60f01882001-08-22 19:24:42 +00004786
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004787 args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
4788 if (args == NULL)
4789 return NULL;
4790 res = type->tp_new(subtype, args, kwds);
4791 Py_DECREF(args);
4792 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004793}
4794
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004795static struct PyMethodDef tp_new_methoddef[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004796 {"__new__", (PyCFunction)tp_new_wrapper, METH_VARARGS|METH_KEYWORDS,
4797 PyDoc_STR("T.__new__(S, ...) -> "
4798 "a new object with type S, a subtype of T")},
4799 {0}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004800};
4801
4802static int
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004803add_tp_new_wrapper(PyTypeObject *type)
4804{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004805 PyObject *func;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004806
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004807 if (PyDict_GetItemString(type->tp_dict, "__new__") != NULL)
4808 return 0;
4809 func = PyCFunction_New(tp_new_methoddef, (PyObject *)type);
4810 if (func == NULL)
4811 return -1;
4812 if (PyDict_SetItemString(type->tp_dict, "__new__", func)) {
4813 Py_DECREF(func);
4814 return -1;
4815 }
4816 Py_DECREF(func);
4817 return 0;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004818}
4819
Guido van Rossumf040ede2001-08-07 16:40:56 +00004820/* Slot wrappers that call the corresponding __foo__ slot. See comments
4821 below at override_slots() for more explanation. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004822
Guido van Rossumdc91b992001-08-08 22:26:22 +00004823#define SLOT0(FUNCNAME, OPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004824static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004825FUNCNAME(PyObject *self) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004826{ \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004827 static PyObject *cache_str; \
4828 return call_method(self, OPSTR, &cache_str, "()"); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004829}
4830
Guido van Rossumdc91b992001-08-08 22:26:22 +00004831#define SLOT1(FUNCNAME, OPSTR, ARG1TYPE, ARGCODES) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004832static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004833FUNCNAME(PyObject *self, ARG1TYPE arg1) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004834{ \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004835 static PyObject *cache_str; \
4836 return call_method(self, OPSTR, &cache_str, "(" ARGCODES ")", arg1); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004837}
4838
Guido van Rossumcd118802003-01-06 22:57:47 +00004839/* Boolean helper for SLOT1BINFULL().
4840 right.__class__ is a nontrivial subclass of left.__class__. */
4841static int
4842method_is_overloaded(PyObject *left, PyObject *right, char *name)
4843{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004844 PyObject *a, *b;
4845 int ok;
Guido van Rossumcd118802003-01-06 22:57:47 +00004846
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004847 b = PyObject_GetAttrString((PyObject *)(Py_TYPE(right)), name);
4848 if (b == NULL) {
4849 PyErr_Clear();
4850 /* If right doesn't have it, it's not overloaded */
4851 return 0;
4852 }
Guido van Rossumcd118802003-01-06 22:57:47 +00004853
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004854 a = PyObject_GetAttrString((PyObject *)(Py_TYPE(left)), name);
4855 if (a == NULL) {
4856 PyErr_Clear();
4857 Py_DECREF(b);
4858 /* If right has it but left doesn't, it's overloaded */
4859 return 1;
4860 }
Guido van Rossumcd118802003-01-06 22:57:47 +00004861
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004862 ok = PyObject_RichCompareBool(a, b, Py_NE);
4863 Py_DECREF(a);
4864 Py_DECREF(b);
4865 if (ok < 0) {
4866 PyErr_Clear();
4867 return 0;
4868 }
Guido van Rossumcd118802003-01-06 22:57:47 +00004869
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004870 return ok;
Guido van Rossumcd118802003-01-06 22:57:47 +00004871}
4872
Guido van Rossumdc91b992001-08-08 22:26:22 +00004873
4874#define SLOT1BINFULL(FUNCNAME, TESTFUNC, SLOTNAME, OPSTR, ROPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004875static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004876FUNCNAME(PyObject *self, PyObject *other) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004877{ \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004878 static PyObject *cache_str, *rcache_str; \
4879 int do_other = Py_TYPE(self) != Py_TYPE(other) && \
4880 Py_TYPE(other)->tp_as_number != NULL && \
4881 Py_TYPE(other)->tp_as_number->SLOTNAME == TESTFUNC; \
4882 if (Py_TYPE(self)->tp_as_number != NULL && \
4883 Py_TYPE(self)->tp_as_number->SLOTNAME == TESTFUNC) { \
4884 PyObject *r; \
4885 if (do_other && \
4886 PyType_IsSubtype(Py_TYPE(other), Py_TYPE(self)) && \
4887 method_is_overloaded(self, other, ROPSTR)) { \
4888 r = call_maybe( \
4889 other, ROPSTR, &rcache_str, "(O)", self); \
4890 if (r != Py_NotImplemented) \
4891 return r; \
4892 Py_DECREF(r); \
4893 do_other = 0; \
4894 } \
4895 r = call_maybe( \
4896 self, OPSTR, &cache_str, "(O)", other); \
4897 if (r != Py_NotImplemented || \
4898 Py_TYPE(other) == Py_TYPE(self)) \
4899 return r; \
4900 Py_DECREF(r); \
4901 } \
4902 if (do_other) { \
4903 return call_maybe( \
4904 other, ROPSTR, &rcache_str, "(O)", self); \
4905 } \
Brian Curtindfc80e32011-08-10 20:28:54 -05004906 Py_RETURN_NOTIMPLEMENTED; \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004907}
4908
4909#define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004910 SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR)
Guido van Rossumdc91b992001-08-08 22:26:22 +00004911
4912#define SLOT2(FUNCNAME, OPSTR, ARG1TYPE, ARG2TYPE, ARGCODES) \
4913static PyObject * \
4914FUNCNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \
4915{ \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004916 static PyObject *cache_str; \
4917 return call_method(self, OPSTR, &cache_str, \
4918 "(" ARGCODES ")", arg1, arg2); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004919}
4920
Martin v. Löwis18e16552006-02-15 17:27:45 +00004921static Py_ssize_t
Tim Peters6d6c1a32001-08-02 04:15:00 +00004922slot_sq_length(PyObject *self)
4923{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004924 static PyObject *len_str;
4925 PyObject *res = call_method(self, "__len__", &len_str, "()");
4926 Py_ssize_t len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004927
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004928 if (res == NULL)
4929 return -1;
4930 len = PyNumber_AsSsize_t(res, PyExc_OverflowError);
4931 Py_DECREF(res);
4932 if (len < 0) {
4933 if (!PyErr_Occurred())
4934 PyErr_SetString(PyExc_ValueError,
4935 "__len__() should return >= 0");
4936 return -1;
4937 }
4938 return len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004939}
4940
Guido van Rossumf4593e02001-10-03 12:09:30 +00004941/* Super-optimized version of slot_sq_item.
4942 Other slots could do the same... */
4943static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00004944slot_sq_item(PyObject *self, Py_ssize_t i)
Guido van Rossumf4593e02001-10-03 12:09:30 +00004945{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004946 static PyObject *getitem_str;
4947 PyObject *func, *args = NULL, *ival = NULL, *retval = NULL;
4948 descrgetfunc f;
Guido van Rossumf4593e02001-10-03 12:09:30 +00004949
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004950 if (getitem_str == NULL) {
4951 getitem_str = PyUnicode_InternFromString("__getitem__");
4952 if (getitem_str == NULL)
4953 return NULL;
4954 }
4955 func = _PyType_Lookup(Py_TYPE(self), getitem_str);
4956 if (func != NULL) {
4957 if ((f = Py_TYPE(func)->tp_descr_get) == NULL)
4958 Py_INCREF(func);
4959 else {
4960 func = f(func, self, (PyObject *)(Py_TYPE(self)));
4961 if (func == NULL) {
4962 return NULL;
4963 }
4964 }
4965 ival = PyLong_FromSsize_t(i);
4966 if (ival != NULL) {
4967 args = PyTuple_New(1);
4968 if (args != NULL) {
4969 PyTuple_SET_ITEM(args, 0, ival);
4970 retval = PyObject_Call(func, args, NULL);
4971 Py_XDECREF(args);
4972 Py_XDECREF(func);
4973 return retval;
4974 }
4975 }
4976 }
4977 else {
4978 PyErr_SetObject(PyExc_AttributeError, getitem_str);
4979 }
4980 Py_XDECREF(args);
4981 Py_XDECREF(ival);
4982 Py_XDECREF(func);
4983 return NULL;
Guido van Rossumf4593e02001-10-03 12:09:30 +00004984}
4985
Tim Peters6d6c1a32001-08-02 04:15:00 +00004986static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00004987slot_sq_ass_item(PyObject *self, Py_ssize_t index, PyObject *value)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004988{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004989 PyObject *res;
4990 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004991
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004992 if (value == NULL)
4993 res = call_method(self, "__delitem__", &delitem_str,
4994 "(n)", index);
4995 else
4996 res = call_method(self, "__setitem__", &setitem_str,
4997 "(nO)", index, value);
4998 if (res == NULL)
4999 return -1;
5000 Py_DECREF(res);
5001 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005002}
5003
5004static int
Tim Peters6d6c1a32001-08-02 04:15:00 +00005005slot_sq_contains(PyObject *self, PyObject *value)
5006{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005007 PyObject *func, *res, *args;
5008 int result = -1;
Tim Petersbf9b2442003-03-23 05:35:36 +00005009
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005010 static PyObject *contains_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005011
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005012 func = lookup_maybe(self, "__contains__", &contains_str);
5013 if (func != NULL) {
5014 args = PyTuple_Pack(1, value);
5015 if (args == NULL)
5016 res = NULL;
5017 else {
5018 res = PyObject_Call(func, args, NULL);
5019 Py_DECREF(args);
5020 }
5021 Py_DECREF(func);
5022 if (res != NULL) {
5023 result = PyObject_IsTrue(res);
5024 Py_DECREF(res);
5025 }
5026 }
5027 else if (! PyErr_Occurred()) {
5028 /* Possible results: -1 and 1 */
5029 result = (int)_PySequence_IterSearch(self, value,
5030 PY_ITERSEARCH_CONTAINS);
5031 }
5032 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005033}
5034
Tim Peters6d6c1a32001-08-02 04:15:00 +00005035#define slot_mp_length slot_sq_length
5036
Guido van Rossumdc91b992001-08-08 22:26:22 +00005037SLOT1(slot_mp_subscript, "__getitem__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00005038
5039static int
5040slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value)
5041{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005042 PyObject *res;
5043 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005044
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005045 if (value == NULL)
5046 res = call_method(self, "__delitem__", &delitem_str,
5047 "(O)", key);
5048 else
5049 res = call_method(self, "__setitem__", &setitem_str,
5050 "(OO)", key, value);
5051 if (res == NULL)
5052 return -1;
5053 Py_DECREF(res);
5054 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005055}
5056
Guido van Rossumdc91b992001-08-08 22:26:22 +00005057SLOT1BIN(slot_nb_add, nb_add, "__add__", "__radd__")
5058SLOT1BIN(slot_nb_subtract, nb_subtract, "__sub__", "__rsub__")
5059SLOT1BIN(slot_nb_multiply, nb_multiply, "__mul__", "__rmul__")
Guido van Rossumdc91b992001-08-08 22:26:22 +00005060SLOT1BIN(slot_nb_remainder, nb_remainder, "__mod__", "__rmod__")
5061SLOT1BIN(slot_nb_divmod, nb_divmod, "__divmod__", "__rdivmod__")
5062
Jeremy Hylton938ace62002-07-17 16:30:39 +00005063static PyObject *slot_nb_power(PyObject *, PyObject *, PyObject *);
Guido van Rossumdc91b992001-08-08 22:26:22 +00005064
5065SLOT1BINFULL(slot_nb_power_binary, slot_nb_power,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005066 nb_power, "__pow__", "__rpow__")
Guido van Rossumdc91b992001-08-08 22:26:22 +00005067
5068static PyObject *
5069slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus)
5070{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005071 static PyObject *pow_str;
Guido van Rossum2730b132001-08-28 18:22:14 +00005072
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005073 if (modulus == Py_None)
5074 return slot_nb_power_binary(self, other);
5075 /* Three-arg power doesn't use __rpow__. But ternary_op
5076 can call this when the second argument's type uses
5077 slot_nb_power, so check before calling self.__pow__. */
5078 if (Py_TYPE(self)->tp_as_number != NULL &&
5079 Py_TYPE(self)->tp_as_number->nb_power == slot_nb_power) {
5080 return call_method(self, "__pow__", &pow_str,
5081 "(OO)", other, modulus);
5082 }
Brian Curtindfc80e32011-08-10 20:28:54 -05005083 Py_RETURN_NOTIMPLEMENTED;
Guido van Rossumdc91b992001-08-08 22:26:22 +00005084}
5085
5086SLOT0(slot_nb_negative, "__neg__")
5087SLOT0(slot_nb_positive, "__pos__")
5088SLOT0(slot_nb_absolute, "__abs__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00005089
5090static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00005091slot_nb_bool(PyObject *self)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005092{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005093 PyObject *func, *args;
5094 static PyObject *bool_str, *len_str;
5095 int result = -1;
5096 int using_len = 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005097
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005098 func = lookup_maybe(self, "__bool__", &bool_str);
5099 if (func == NULL) {
5100 if (PyErr_Occurred())
5101 return -1;
5102 func = lookup_maybe(self, "__len__", &len_str);
5103 if (func == NULL)
5104 return PyErr_Occurred() ? -1 : 1;
5105 using_len = 1;
5106 }
5107 args = PyTuple_New(0);
5108 if (args != NULL) {
5109 PyObject *temp = PyObject_Call(func, args, NULL);
5110 Py_DECREF(args);
5111 if (temp != NULL) {
5112 if (using_len) {
5113 /* enforced by slot_nb_len */
5114 result = PyObject_IsTrue(temp);
5115 }
5116 else if (PyBool_Check(temp)) {
5117 result = PyObject_IsTrue(temp);
5118 }
5119 else {
5120 PyErr_Format(PyExc_TypeError,
5121 "__bool__ should return "
5122 "bool, returned %s",
5123 Py_TYPE(temp)->tp_name);
5124 result = -1;
5125 }
5126 Py_DECREF(temp);
5127 }
5128 }
5129 Py_DECREF(func);
5130 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005131}
5132
Guido van Rossum38fff8c2006-03-07 18:50:55 +00005133
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00005134static PyObject *
Guido van Rossum38fff8c2006-03-07 18:50:55 +00005135slot_nb_index(PyObject *self)
5136{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005137 static PyObject *index_str;
5138 return call_method(self, "__index__", &index_str, "()");
Guido van Rossum38fff8c2006-03-07 18:50:55 +00005139}
5140
5141
Guido van Rossumdc91b992001-08-08 22:26:22 +00005142SLOT0(slot_nb_invert, "__invert__")
5143SLOT1BIN(slot_nb_lshift, nb_lshift, "__lshift__", "__rlshift__")
5144SLOT1BIN(slot_nb_rshift, nb_rshift, "__rshift__", "__rrshift__")
5145SLOT1BIN(slot_nb_and, nb_and, "__and__", "__rand__")
5146SLOT1BIN(slot_nb_xor, nb_xor, "__xor__", "__rxor__")
5147SLOT1BIN(slot_nb_or, nb_or, "__or__", "__ror__")
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00005148
Guido van Rossumdc91b992001-08-08 22:26:22 +00005149SLOT0(slot_nb_int, "__int__")
Guido van Rossumdc91b992001-08-08 22:26:22 +00005150SLOT0(slot_nb_float, "__float__")
Guido van Rossumdc91b992001-08-08 22:26:22 +00005151SLOT1(slot_nb_inplace_add, "__iadd__", PyObject *, "O")
5152SLOT1(slot_nb_inplace_subtract, "__isub__", PyObject *, "O")
5153SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *, "O")
Guido van Rossumdc91b992001-08-08 22:26:22 +00005154SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *, "O")
Thomas Wouterscf297e42007-02-23 15:07:44 +00005155/* Can't use SLOT1 here, because nb_inplace_power is ternary */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005156static PyObject *
5157slot_nb_inplace_power(PyObject *self, PyObject * arg1, PyObject *arg2)
5158{
5159 static PyObject *cache_str;
5160 return call_method(self, "__ipow__", &cache_str, "(" "O" ")", arg1);
Thomas Wouterscf297e42007-02-23 15:07:44 +00005161}
Guido van Rossumdc91b992001-08-08 22:26:22 +00005162SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *, "O")
5163SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *, "O")
5164SLOT1(slot_nb_inplace_and, "__iand__", PyObject *, "O")
5165SLOT1(slot_nb_inplace_xor, "__ixor__", PyObject *, "O")
5166SLOT1(slot_nb_inplace_or, "__ior__", PyObject *, "O")
5167SLOT1BIN(slot_nb_floor_divide, nb_floor_divide,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005168 "__floordiv__", "__rfloordiv__")
Guido van Rossumdc91b992001-08-08 22:26:22 +00005169SLOT1BIN(slot_nb_true_divide, nb_true_divide, "__truediv__", "__rtruediv__")
5170SLOT1(slot_nb_inplace_floor_divide, "__ifloordiv__", PyObject *, "O")
5171SLOT1(slot_nb_inplace_true_divide, "__itruediv__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00005172
Guido van Rossumb8f63662001-08-15 23:57:02 +00005173static PyObject *
5174slot_tp_repr(PyObject *self)
5175{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005176 PyObject *func, *res;
5177 static PyObject *repr_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00005178
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005179 func = lookup_method(self, "__repr__", &repr_str);
5180 if (func != NULL) {
5181 res = PyEval_CallObject(func, NULL);
5182 Py_DECREF(func);
5183 return res;
5184 }
5185 PyErr_Clear();
5186 return PyUnicode_FromFormat("<%s object at %p>",
5187 Py_TYPE(self)->tp_name, self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005188}
5189
5190static PyObject *
5191slot_tp_str(PyObject *self)
5192{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005193 PyObject *func, *res;
5194 static PyObject *str_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00005195
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005196 func = lookup_method(self, "__str__", &str_str);
5197 if (func != NULL) {
5198 res = PyEval_CallObject(func, NULL);
5199 Py_DECREF(func);
5200 return res;
5201 }
5202 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005203 /* PyObject *ress; */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005204 PyErr_Clear();
5205 res = slot_tp_repr(self);
5206 if (!res)
5207 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005208 /* XXX this is non-sensical. Why should we return
5209 a bytes object from __str__. Is this code even
5210 used? - mvl */
5211 assert(0);
5212 return res;
5213 /*
Victor Stinnerf3fd7332011-03-02 01:03:11 +00005214 ress = _PyUnicode_AsDefaultEncodedString(res);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005215 Py_DECREF(res);
5216 return ress;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005217 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005218 }
Guido van Rossumb8f63662001-08-15 23:57:02 +00005219}
Tim Peters6d6c1a32001-08-02 04:15:00 +00005220
Benjamin Peterson8f67d082010-10-17 20:54:53 +00005221static Py_hash_t
Tim Peters6d6c1a32001-08-02 04:15:00 +00005222slot_tp_hash(PyObject *self)
5223{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005224 PyObject *func, *res;
5225 static PyObject *hash_str;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00005226 Py_ssize_t h;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005227
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005228 func = lookup_method(self, "__hash__", &hash_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005229
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005230 if (func == Py_None) {
5231 Py_DECREF(func);
5232 func = NULL;
5233 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +00005234
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005235 if (func == NULL) {
5236 return PyObject_HashNotImplemented(self);
5237 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +00005238
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005239 res = PyEval_CallObject(func, NULL);
5240 Py_DECREF(func);
5241 if (res == NULL)
5242 return -1;
Mark Dickinsondc787d22010-05-23 13:33:13 +00005243
5244 if (!PyLong_Check(res)) {
5245 PyErr_SetString(PyExc_TypeError,
5246 "__hash__ method should return an integer");
5247 return -1;
5248 }
Benjamin Peterson8f67d082010-10-17 20:54:53 +00005249 /* Transform the PyLong `res` to a Py_hash_t `h`. For an existing
5250 hashable Python object x, hash(x) will always lie within the range of
5251 Py_hash_t. Therefore our transformation must preserve values that
5252 already lie within this range, to ensure that if x.__hash__() returns
5253 hash(y) then hash(x) == hash(y). */
5254 h = PyLong_AsSsize_t(res);
5255 if (h == -1 && PyErr_Occurred()) {
5256 /* res was not within the range of a Py_hash_t, so we're free to
Mark Dickinsondc787d22010-05-23 13:33:13 +00005257 use any sufficiently bit-mixing transformation;
5258 long.__hash__ will do nicely. */
Benjamin Peterson8f67d082010-10-17 20:54:53 +00005259 PyErr_Clear();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005260 h = PyLong_Type.tp_hash(res);
Benjamin Peterson8f67d082010-10-17 20:54:53 +00005261 }
Benjamin Petersone7dfeeb2010-10-17 21:27:01 +00005262 /* -1 is reserved for errors. */
5263 if (h == -1)
5264 h = -2;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005265 Py_DECREF(res);
Mark Dickinsondc787d22010-05-23 13:33:13 +00005266 return h;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005267}
5268
5269static PyObject *
5270slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds)
5271{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005272 static PyObject *call_str;
5273 PyObject *meth = lookup_method(self, "__call__", &call_str);
5274 PyObject *res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005275
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005276 if (meth == NULL)
5277 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005278
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005279 res = PyObject_Call(meth, args, kwds);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005280
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005281 Py_DECREF(meth);
5282 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005283}
5284
Guido van Rossum14a6f832001-10-17 13:59:09 +00005285/* There are two slot dispatch functions for tp_getattro.
5286
5287 - slot_tp_getattro() is used when __getattribute__ is overridden
5288 but no __getattr__ hook is present;
5289
5290 - slot_tp_getattr_hook() is used when a __getattr__ hook is present.
5291
Guido van Rossumc334df52002-04-04 23:44:47 +00005292 The code in update_one_slot() always installs slot_tp_getattr_hook(); this
5293 detects the absence of __getattr__ and then installs the simpler slot if
5294 necessary. */
Guido van Rossum14a6f832001-10-17 13:59:09 +00005295
Tim Peters6d6c1a32001-08-02 04:15:00 +00005296static PyObject *
5297slot_tp_getattro(PyObject *self, PyObject *name)
5298{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005299 static PyObject *getattribute_str = NULL;
5300 return call_method(self, "__getattribute__", &getattribute_str,
5301 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005302}
5303
Guido van Rossum19c1cd52001-09-21 21:24:49 +00005304static PyObject *
Benjamin Peterson9262b842008-11-17 22:45:50 +00005305call_attribute(PyObject *self, PyObject *attr, PyObject *name)
5306{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005307 PyObject *res, *descr = NULL;
5308 descrgetfunc f = Py_TYPE(attr)->tp_descr_get;
Benjamin Peterson9262b842008-11-17 22:45:50 +00005309
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005310 if (f != NULL) {
5311 descr = f(attr, self, (PyObject *)(Py_TYPE(self)));
5312 if (descr == NULL)
5313 return NULL;
5314 else
5315 attr = descr;
5316 }
5317 res = PyObject_CallFunctionObjArgs(attr, name, NULL);
5318 Py_XDECREF(descr);
5319 return res;
Benjamin Peterson9262b842008-11-17 22:45:50 +00005320}
5321
5322static PyObject *
Guido van Rossum19c1cd52001-09-21 21:24:49 +00005323slot_tp_getattr_hook(PyObject *self, PyObject *name)
5324{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005325 PyTypeObject *tp = Py_TYPE(self);
5326 PyObject *getattr, *getattribute, *res;
5327 static PyObject *getattribute_str = NULL;
5328 static PyObject *getattr_str = NULL;
Guido van Rossum19c1cd52001-09-21 21:24:49 +00005329
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005330 if (getattr_str == NULL) {
5331 getattr_str = PyUnicode_InternFromString("__getattr__");
5332 if (getattr_str == NULL)
5333 return NULL;
5334 }
5335 if (getattribute_str == NULL) {
5336 getattribute_str =
5337 PyUnicode_InternFromString("__getattribute__");
5338 if (getattribute_str == NULL)
5339 return NULL;
5340 }
5341 /* speed hack: we could use lookup_maybe, but that would resolve the
5342 method fully for each attribute lookup for classes with
5343 __getattr__, even when the attribute is present. So we use
5344 _PyType_Lookup and create the method only when needed, with
5345 call_attribute. */
5346 getattr = _PyType_Lookup(tp, getattr_str);
5347 if (getattr == NULL) {
5348 /* No __getattr__ hook: use a simpler dispatcher */
5349 tp->tp_getattro = slot_tp_getattro;
5350 return slot_tp_getattro(self, name);
5351 }
5352 Py_INCREF(getattr);
5353 /* speed hack: we could use lookup_maybe, but that would resolve the
5354 method fully for each attribute lookup for classes with
5355 __getattr__, even when self has the default __getattribute__
5356 method. So we use _PyType_Lookup and create the method only when
5357 needed, with call_attribute. */
5358 getattribute = _PyType_Lookup(tp, getattribute_str);
5359 if (getattribute == NULL ||
5360 (Py_TYPE(getattribute) == &PyWrapperDescr_Type &&
5361 ((PyWrapperDescrObject *)getattribute)->d_wrapped ==
5362 (void *)PyObject_GenericGetAttr))
5363 res = PyObject_GenericGetAttr(self, name);
5364 else {
5365 Py_INCREF(getattribute);
5366 res = call_attribute(self, getattribute, name);
5367 Py_DECREF(getattribute);
5368 }
5369 if (res == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) {
5370 PyErr_Clear();
5371 res = call_attribute(self, getattr, name);
5372 }
5373 Py_DECREF(getattr);
5374 return res;
Guido van Rossum19c1cd52001-09-21 21:24:49 +00005375}
5376
Tim Peters6d6c1a32001-08-02 04:15:00 +00005377static int
5378slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value)
5379{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005380 PyObject *res;
5381 static PyObject *delattr_str, *setattr_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005382
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005383 if (value == NULL)
5384 res = call_method(self, "__delattr__", &delattr_str,
5385 "(O)", name);
5386 else
5387 res = call_method(self, "__setattr__", &setattr_str,
5388 "(OO)", name, value);
5389 if (res == NULL)
5390 return -1;
5391 Py_DECREF(res);
5392 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005393}
5394
Guido van Rossumf5243f02008-01-01 04:06:48 +00005395static char *name_op[] = {
5396 "__lt__",
5397 "__le__",
5398 "__eq__",
5399 "__ne__",
5400 "__gt__",
5401 "__ge__",
5402};
5403
Tim Peters6d6c1a32001-08-02 04:15:00 +00005404static PyObject *
Mark Dickinson6f1d0492009-11-15 13:58:49 +00005405slot_tp_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005406{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005407 PyObject *func, *args, *res;
5408 static PyObject *op_str[6];
Tim Peters6d6c1a32001-08-02 04:15:00 +00005409
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005410 func = lookup_method(self, name_op[op], &op_str[op]);
5411 if (func == NULL) {
5412 PyErr_Clear();
Brian Curtindfc80e32011-08-10 20:28:54 -05005413 Py_RETURN_NOTIMPLEMENTED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005414 }
5415 args = PyTuple_Pack(1, other);
5416 if (args == NULL)
5417 res = NULL;
5418 else {
5419 res = PyObject_Call(func, args, NULL);
5420 Py_DECREF(args);
5421 }
5422 Py_DECREF(func);
5423 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005424}
5425
Guido van Rossumb8f63662001-08-15 23:57:02 +00005426static PyObject *
Guido van Rossumb8f63662001-08-15 23:57:02 +00005427slot_tp_iter(PyObject *self)
5428{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005429 PyObject *func, *res;
5430 static PyObject *iter_str, *getitem_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00005431
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005432 func = lookup_method(self, "__iter__", &iter_str);
5433 if (func != NULL) {
5434 PyObject *args;
5435 args = res = PyTuple_New(0);
5436 if (args != NULL) {
5437 res = PyObject_Call(func, args, NULL);
5438 Py_DECREF(args);
5439 }
5440 Py_DECREF(func);
5441 return res;
5442 }
5443 PyErr_Clear();
5444 func = lookup_method(self, "__getitem__", &getitem_str);
5445 if (func == NULL) {
5446 PyErr_Format(PyExc_TypeError,
5447 "'%.200s' object is not iterable",
5448 Py_TYPE(self)->tp_name);
5449 return NULL;
5450 }
5451 Py_DECREF(func);
5452 return PySeqIter_New(self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005453}
Tim Peters6d6c1a32001-08-02 04:15:00 +00005454
5455static PyObject *
5456slot_tp_iternext(PyObject *self)
5457{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005458 static PyObject *next_str;
5459 return call_method(self, "__next__", &next_str, "()");
Tim Peters6d6c1a32001-08-02 04:15:00 +00005460}
5461
Guido van Rossum1a493502001-08-17 16:47:50 +00005462static PyObject *
5463slot_tp_descr_get(PyObject *self, PyObject *obj, PyObject *type)
5464{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005465 PyTypeObject *tp = Py_TYPE(self);
5466 PyObject *get;
5467 static PyObject *get_str = NULL;
Guido van Rossum1a493502001-08-17 16:47:50 +00005468
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005469 if (get_str == NULL) {
5470 get_str = PyUnicode_InternFromString("__get__");
5471 if (get_str == NULL)
5472 return NULL;
5473 }
5474 get = _PyType_Lookup(tp, get_str);
5475 if (get == NULL) {
5476 /* Avoid further slowdowns */
5477 if (tp->tp_descr_get == slot_tp_descr_get)
5478 tp->tp_descr_get = NULL;
5479 Py_INCREF(self);
5480 return self;
5481 }
5482 if (obj == NULL)
5483 obj = Py_None;
5484 if (type == NULL)
5485 type = Py_None;
5486 return PyObject_CallFunctionObjArgs(get, self, obj, type, NULL);
Guido van Rossum1a493502001-08-17 16:47:50 +00005487}
Tim Peters6d6c1a32001-08-02 04:15:00 +00005488
5489static int
5490slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value)
5491{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005492 PyObject *res;
5493 static PyObject *del_str, *set_str;
Guido van Rossum2c252392001-08-24 10:13:31 +00005494
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005495 if (value == NULL)
5496 res = call_method(self, "__delete__", &del_str,
5497 "(O)", target);
5498 else
5499 res = call_method(self, "__set__", &set_str,
5500 "(OO)", target, value);
5501 if (res == NULL)
5502 return -1;
5503 Py_DECREF(res);
5504 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005505}
5506
5507static int
5508slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds)
5509{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005510 static PyObject *init_str;
5511 PyObject *meth = lookup_method(self, "__init__", &init_str);
5512 PyObject *res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005513
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005514 if (meth == NULL)
5515 return -1;
5516 res = PyObject_Call(meth, args, kwds);
5517 Py_DECREF(meth);
5518 if (res == NULL)
5519 return -1;
5520 if (res != Py_None) {
5521 PyErr_Format(PyExc_TypeError,
5522 "__init__() should return None, not '%.200s'",
5523 Py_TYPE(res)->tp_name);
5524 Py_DECREF(res);
5525 return -1;
5526 }
5527 Py_DECREF(res);
5528 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005529}
5530
5531static PyObject *
5532slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
5533{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005534 static PyObject *new_str;
5535 PyObject *func;
5536 PyObject *newargs, *x;
5537 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005538
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005539 if (new_str == NULL) {
5540 new_str = PyUnicode_InternFromString("__new__");
5541 if (new_str == NULL)
5542 return NULL;
5543 }
5544 func = PyObject_GetAttr((PyObject *)type, new_str);
5545 if (func == NULL)
5546 return NULL;
5547 assert(PyTuple_Check(args));
5548 n = PyTuple_GET_SIZE(args);
5549 newargs = PyTuple_New(n+1);
5550 if (newargs == NULL)
5551 return NULL;
5552 Py_INCREF(type);
5553 PyTuple_SET_ITEM(newargs, 0, (PyObject *)type);
5554 for (i = 0; i < n; i++) {
5555 x = PyTuple_GET_ITEM(args, i);
5556 Py_INCREF(x);
5557 PyTuple_SET_ITEM(newargs, i+1, x);
5558 }
5559 x = PyObject_Call(func, newargs, kwds);
5560 Py_DECREF(newargs);
5561 Py_DECREF(func);
5562 return x;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005563}
5564
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005565static void
5566slot_tp_del(PyObject *self)
5567{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005568 static PyObject *del_str = NULL;
5569 PyObject *del, *res;
5570 PyObject *error_type, *error_value, *error_traceback;
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005571
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005572 /* Temporarily resurrect the object. */
5573 assert(self->ob_refcnt == 0);
5574 self->ob_refcnt = 1;
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005575
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005576 /* Save the current exception, if any. */
5577 PyErr_Fetch(&error_type, &error_value, &error_traceback);
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005578
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005579 /* Execute __del__ method, if any. */
5580 del = lookup_maybe(self, "__del__", &del_str);
5581 if (del != NULL) {
5582 res = PyEval_CallObject(del, NULL);
5583 if (res == NULL)
5584 PyErr_WriteUnraisable(del);
5585 else
5586 Py_DECREF(res);
5587 Py_DECREF(del);
5588 }
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005589
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005590 /* Restore the saved exception. */
5591 PyErr_Restore(error_type, error_value, error_traceback);
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005592
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005593 /* Undo the temporary resurrection; can't use DECREF here, it would
5594 * cause a recursive call.
5595 */
5596 assert(self->ob_refcnt > 0);
5597 if (--self->ob_refcnt == 0)
5598 return; /* this is the normal path out */
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005599
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005600 /* __del__ resurrected it! Make it look like the original Py_DECREF
5601 * never happened.
5602 */
5603 {
5604 Py_ssize_t refcnt = self->ob_refcnt;
5605 _Py_NewReference(self);
5606 self->ob_refcnt = refcnt;
5607 }
5608 assert(!PyType_IS_GC(Py_TYPE(self)) ||
5609 _Py_AS_GC(self)->gc.gc_refs != _PyGC_REFS_UNTRACKED);
5610 /* If Py_REF_DEBUG, _Py_NewReference bumped _Py_RefTotal, so
5611 * we need to undo that. */
5612 _Py_DEC_REFTOTAL;
5613 /* If Py_TRACE_REFS, _Py_NewReference re-added self to the object
5614 * chain, so no more to do there.
5615 * If COUNT_ALLOCS, the original decref bumped tp_frees, and
5616 * _Py_NewReference bumped tp_allocs: both of those need to be
5617 * undone.
5618 */
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005619#ifdef COUNT_ALLOCS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005620 --Py_TYPE(self)->tp_frees;
5621 --Py_TYPE(self)->tp_allocs;
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005622#endif
5623}
5624
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005625
5626/* Table mapping __foo__ names to tp_foo offsets and slot_tp_foo wrapper
Tim Petersbf9b2442003-03-23 05:35:36 +00005627 functions. The offsets here are relative to the 'PyHeapTypeObject'
Guido van Rossume5c691a2003-03-07 15:13:17 +00005628 structure, which incorporates the additional structures used for numbers,
5629 sequences and mappings.
5630 Note that multiple names may map to the same slot (e.g. __eq__,
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005631 __ne__ etc. all map to tp_richcompare) and one name may map to multiple
Guido van Rossumc334df52002-04-04 23:44:47 +00005632 slots (e.g. __str__ affects tp_str as well as tp_repr). The table is
5633 terminated with an all-zero entry. (This table is further initialized and
5634 sorted in init_slotdefs() below.) */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005635
Guido van Rossum6d204072001-10-21 00:44:31 +00005636typedef struct wrapperbase slotdef;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005637
5638#undef TPSLOT
Guido van Rossumc8e56452001-10-22 00:43:43 +00005639#undef FLSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005640#undef ETSLOT
5641#undef SQSLOT
5642#undef MPSLOT
5643#undef NBSLOT
Guido van Rossum6d204072001-10-21 00:44:31 +00005644#undef UNSLOT
5645#undef IBSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005646#undef BINSLOT
5647#undef RBINSLOT
5648
Guido van Rossum6d204072001-10-21 00:44:31 +00005649#define TPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005650 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
5651 PyDoc_STR(DOC)}
Guido van Rossumc8e56452001-10-22 00:43:43 +00005652#define FLSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC, FLAGS) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005653 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
5654 PyDoc_STR(DOC), FLAGS}
Guido van Rossum6d204072001-10-21 00:44:31 +00005655#define ETSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005656 {NAME, offsetof(PyHeapTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
5657 PyDoc_STR(DOC)}
Guido van Rossum6d204072001-10-21 00:44:31 +00005658#define SQSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005659 ETSLOT(NAME, as_sequence.SLOT, FUNCTION, WRAPPER, DOC)
Guido van Rossum6d204072001-10-21 00:44:31 +00005660#define MPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005661 ETSLOT(NAME, as_mapping.SLOT, FUNCTION, WRAPPER, DOC)
Guido van Rossum6d204072001-10-21 00:44:31 +00005662#define NBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005663 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, DOC)
Guido van Rossum6d204072001-10-21 00:44:31 +00005664#define UNSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005665 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
5666 "x." NAME "() <==> " DOC)
Guido van Rossum6d204072001-10-21 00:44:31 +00005667#define IBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005668 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
5669 "x." NAME "(y) <==> x" DOC "y")
Guido van Rossum6d204072001-10-21 00:44:31 +00005670#define BINSLOT(NAME, SLOT, FUNCTION, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005671 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
5672 "x." NAME "(y) <==> x" DOC "y")
Guido van Rossum6d204072001-10-21 00:44:31 +00005673#define RBINSLOT(NAME, SLOT, FUNCTION, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005674 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
5675 "x." NAME "(y) <==> y" DOC "x")
Anthony Baxter56616992005-06-03 14:12:21 +00005676#define BINSLOTNOTINFIX(NAME, SLOT, FUNCTION, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005677 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
5678 "x." NAME "(y) <==> " DOC)
Anthony Baxter56616992005-06-03 14:12:21 +00005679#define RBINSLOTNOTINFIX(NAME, SLOT, FUNCTION, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005680 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
5681 "x." NAME "(y) <==> " DOC)
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005682
5683static slotdef slotdefs[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005684 SQSLOT("__len__", sq_length, slot_sq_length, wrap_lenfunc,
5685 "x.__len__() <==> len(x)"),
5686 /* Heap types defining __add__/__mul__ have sq_concat/sq_repeat == NULL.
5687 The logic in abstract.c always falls back to nb_add/nb_multiply in
5688 this case. Defining both the nb_* and the sq_* slots to call the
5689 user-defined methods has unexpected side-effects, as shown by
5690 test_descr.notimplemented() */
5691 SQSLOT("__add__", sq_concat, NULL, wrap_binaryfunc,
5692 "x.__add__(y) <==> x+y"),
5693 SQSLOT("__mul__", sq_repeat, NULL, wrap_indexargfunc,
5694 "x.__mul__(n) <==> x*n"),
5695 SQSLOT("__rmul__", sq_repeat, NULL, wrap_indexargfunc,
5696 "x.__rmul__(n) <==> n*x"),
5697 SQSLOT("__getitem__", sq_item, slot_sq_item, wrap_sq_item,
5698 "x.__getitem__(y) <==> x[y]"),
5699 SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_setitem,
5700 "x.__setitem__(i, y) <==> x[i]=y"),
5701 SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_delitem,
5702 "x.__delitem__(y) <==> del x[y]"),
5703 SQSLOT("__contains__", sq_contains, slot_sq_contains, wrap_objobjproc,
5704 "x.__contains__(y) <==> y in x"),
5705 SQSLOT("__iadd__", sq_inplace_concat, NULL,
5706 wrap_binaryfunc, "x.__iadd__(y) <==> x+=y"),
5707 SQSLOT("__imul__", sq_inplace_repeat, NULL,
5708 wrap_indexargfunc, "x.__imul__(y) <==> x*=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005709
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005710 MPSLOT("__len__", mp_length, slot_mp_length, wrap_lenfunc,
5711 "x.__len__() <==> len(x)"),
5712 MPSLOT("__getitem__", mp_subscript, slot_mp_subscript,
5713 wrap_binaryfunc,
5714 "x.__getitem__(y) <==> x[y]"),
5715 MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript,
5716 wrap_objobjargproc,
5717 "x.__setitem__(i, y) <==> x[i]=y"),
5718 MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript,
5719 wrap_delitem,
5720 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005721
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005722 BINSLOT("__add__", nb_add, slot_nb_add,
5723 "+"),
5724 RBINSLOT("__radd__", nb_add, slot_nb_add,
5725 "+"),
5726 BINSLOT("__sub__", nb_subtract, slot_nb_subtract,
5727 "-"),
5728 RBINSLOT("__rsub__", nb_subtract, slot_nb_subtract,
5729 "-"),
5730 BINSLOT("__mul__", nb_multiply, slot_nb_multiply,
5731 "*"),
5732 RBINSLOT("__rmul__", nb_multiply, slot_nb_multiply,
5733 "*"),
5734 BINSLOT("__mod__", nb_remainder, slot_nb_remainder,
5735 "%"),
5736 RBINSLOT("__rmod__", nb_remainder, slot_nb_remainder,
5737 "%"),
5738 BINSLOTNOTINFIX("__divmod__", nb_divmod, slot_nb_divmod,
5739 "divmod(x, y)"),
5740 RBINSLOTNOTINFIX("__rdivmod__", nb_divmod, slot_nb_divmod,
5741 "divmod(y, x)"),
5742 NBSLOT("__pow__", nb_power, slot_nb_power, wrap_ternaryfunc,
5743 "x.__pow__(y[, z]) <==> pow(x, y[, z])"),
5744 NBSLOT("__rpow__", nb_power, slot_nb_power, wrap_ternaryfunc_r,
5745 "y.__rpow__(x[, z]) <==> pow(x, y[, z])"),
5746 UNSLOT("__neg__", nb_negative, slot_nb_negative, wrap_unaryfunc, "-x"),
5747 UNSLOT("__pos__", nb_positive, slot_nb_positive, wrap_unaryfunc, "+x"),
5748 UNSLOT("__abs__", nb_absolute, slot_nb_absolute, wrap_unaryfunc,
5749 "abs(x)"),
5750 UNSLOT("__bool__", nb_bool, slot_nb_bool, wrap_inquirypred,
5751 "x != 0"),
5752 UNSLOT("__invert__", nb_invert, slot_nb_invert, wrap_unaryfunc, "~x"),
5753 BINSLOT("__lshift__", nb_lshift, slot_nb_lshift, "<<"),
5754 RBINSLOT("__rlshift__", nb_lshift, slot_nb_lshift, "<<"),
5755 BINSLOT("__rshift__", nb_rshift, slot_nb_rshift, ">>"),
5756 RBINSLOT("__rrshift__", nb_rshift, slot_nb_rshift, ">>"),
5757 BINSLOT("__and__", nb_and, slot_nb_and, "&"),
5758 RBINSLOT("__rand__", nb_and, slot_nb_and, "&"),
5759 BINSLOT("__xor__", nb_xor, slot_nb_xor, "^"),
5760 RBINSLOT("__rxor__", nb_xor, slot_nb_xor, "^"),
5761 BINSLOT("__or__", nb_or, slot_nb_or, "|"),
5762 RBINSLOT("__ror__", nb_or, slot_nb_or, "|"),
5763 UNSLOT("__int__", nb_int, slot_nb_int, wrap_unaryfunc,
5764 "int(x)"),
5765 UNSLOT("__float__", nb_float, slot_nb_float, wrap_unaryfunc,
5766 "float(x)"),
5767 NBSLOT("__index__", nb_index, slot_nb_index, wrap_unaryfunc,
5768 "x[y:z] <==> x[y.__index__():z.__index__()]"),
5769 IBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add,
Eli Benderskyd3baae72011-11-11 16:57:05 +02005770 wrap_binaryfunc, "+="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005771 IBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract,
Eli Benderskyd3baae72011-11-11 16:57:05 +02005772 wrap_binaryfunc, "-="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005773 IBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply,
Eli Benderskyd3baae72011-11-11 16:57:05 +02005774 wrap_binaryfunc, "*="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005775 IBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder,
Eli Benderskyd3baae72011-11-11 16:57:05 +02005776 wrap_binaryfunc, "%="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005777 IBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power,
Eli Benderskyd3baae72011-11-11 16:57:05 +02005778 wrap_binaryfunc, "**="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005779 IBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift,
Eli Benderskyd3baae72011-11-11 16:57:05 +02005780 wrap_binaryfunc, "<<="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005781 IBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift,
Eli Benderskyd3baae72011-11-11 16:57:05 +02005782 wrap_binaryfunc, ">>="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005783 IBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and,
Eli Benderskyd3baae72011-11-11 16:57:05 +02005784 wrap_binaryfunc, "&="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005785 IBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor,
Eli Benderskyd3baae72011-11-11 16:57:05 +02005786 wrap_binaryfunc, "^="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005787 IBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or,
Eli Benderskyd3baae72011-11-11 16:57:05 +02005788 wrap_binaryfunc, "|="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005789 BINSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
5790 RBINSLOT("__rfloordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
5791 BINSLOT("__truediv__", nb_true_divide, slot_nb_true_divide, "/"),
5792 RBINSLOT("__rtruediv__", nb_true_divide, slot_nb_true_divide, "/"),
5793 IBSLOT("__ifloordiv__", nb_inplace_floor_divide,
5794 slot_nb_inplace_floor_divide, wrap_binaryfunc, "//"),
5795 IBSLOT("__itruediv__", nb_inplace_true_divide,
5796 slot_nb_inplace_true_divide, wrap_binaryfunc, "/"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005797
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005798 TPSLOT("__str__", tp_str, slot_tp_str, wrap_unaryfunc,
5799 "x.__str__() <==> str(x)"),
5800 TPSLOT("__repr__", tp_repr, slot_tp_repr, wrap_unaryfunc,
5801 "x.__repr__() <==> repr(x)"),
5802 TPSLOT("__hash__", tp_hash, slot_tp_hash, wrap_hashfunc,
5803 "x.__hash__() <==> hash(x)"),
5804 FLSLOT("__call__", tp_call, slot_tp_call, (wrapperfunc)wrap_call,
5805 "x.__call__(...) <==> x(...)", PyWrapperFlag_KEYWORDS),
5806 TPSLOT("__getattribute__", tp_getattro, slot_tp_getattr_hook,
5807 wrap_binaryfunc, "x.__getattribute__('name') <==> x.name"),
5808 TPSLOT("__getattribute__", tp_getattr, NULL, NULL, ""),
5809 TPSLOT("__getattr__", tp_getattro, slot_tp_getattr_hook, NULL, ""),
5810 TPSLOT("__getattr__", tp_getattr, NULL, NULL, ""),
5811 TPSLOT("__setattr__", tp_setattro, slot_tp_setattro, wrap_setattr,
5812 "x.__setattr__('name', value) <==> x.name = value"),
5813 TPSLOT("__setattr__", tp_setattr, NULL, NULL, ""),
5814 TPSLOT("__delattr__", tp_setattro, slot_tp_setattro, wrap_delattr,
5815 "x.__delattr__('name') <==> del x.name"),
5816 TPSLOT("__delattr__", tp_setattr, NULL, NULL, ""),
5817 TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare, richcmp_lt,
5818 "x.__lt__(y) <==> x<y"),
5819 TPSLOT("__le__", tp_richcompare, slot_tp_richcompare, richcmp_le,
5820 "x.__le__(y) <==> x<=y"),
5821 TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare, richcmp_eq,
5822 "x.__eq__(y) <==> x==y"),
5823 TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare, richcmp_ne,
5824 "x.__ne__(y) <==> x!=y"),
5825 TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare, richcmp_gt,
5826 "x.__gt__(y) <==> x>y"),
5827 TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare, richcmp_ge,
5828 "x.__ge__(y) <==> x>=y"),
5829 TPSLOT("__iter__", tp_iter, slot_tp_iter, wrap_unaryfunc,
5830 "x.__iter__() <==> iter(x)"),
5831 TPSLOT("__next__", tp_iternext, slot_tp_iternext, wrap_next,
5832 "x.__next__() <==> next(x)"),
5833 TPSLOT("__get__", tp_descr_get, slot_tp_descr_get, wrap_descr_get,
5834 "descr.__get__(obj[, type]) -> value"),
5835 TPSLOT("__set__", tp_descr_set, slot_tp_descr_set, wrap_descr_set,
5836 "descr.__set__(obj, value)"),
5837 TPSLOT("__delete__", tp_descr_set, slot_tp_descr_set,
5838 wrap_descr_delete, "descr.__delete__(obj)"),
5839 FLSLOT("__init__", tp_init, slot_tp_init, (wrapperfunc)wrap_init,
5840 "x.__init__(...) initializes x; "
Alexander Belopolsky977a6842010-08-16 20:17:07 +00005841 "see help(type(x)) for signature",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005842 PyWrapperFlag_KEYWORDS),
5843 TPSLOT("__new__", tp_new, slot_tp_new, NULL, ""),
5844 TPSLOT("__del__", tp_del, slot_tp_del, NULL, ""),
5845 {NULL}
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005846};
5847
Guido van Rossumc334df52002-04-04 23:44:47 +00005848/* Given a type pointer and an offset gotten from a slotdef entry, return a
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005849 pointer to the actual slot. This is not quite the same as simply adding
Guido van Rossumc334df52002-04-04 23:44:47 +00005850 the offset to the type pointer, since it takes care to indirect through the
5851 proper indirection pointer (as_buffer, etc.); it returns NULL if the
5852 indirection pointer is NULL. */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005853static void **
Martin v. Löwis18e16552006-02-15 17:27:45 +00005854slotptr(PyTypeObject *type, int ioffset)
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005855{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005856 char *ptr;
5857 long offset = ioffset;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005858
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005859 /* Note: this depends on the order of the members of PyHeapTypeObject! */
5860 assert(offset >= 0);
5861 assert((size_t)offset < offsetof(PyHeapTypeObject, as_buffer));
5862 if ((size_t)offset >= offsetof(PyHeapTypeObject, as_sequence)) {
5863 ptr = (char *)type->tp_as_sequence;
5864 offset -= offsetof(PyHeapTypeObject, as_sequence);
5865 }
5866 else if ((size_t)offset >= offsetof(PyHeapTypeObject, as_mapping)) {
5867 ptr = (char *)type->tp_as_mapping;
5868 offset -= offsetof(PyHeapTypeObject, as_mapping);
5869 }
5870 else if ((size_t)offset >= offsetof(PyHeapTypeObject, as_number)) {
5871 ptr = (char *)type->tp_as_number;
5872 offset -= offsetof(PyHeapTypeObject, as_number);
5873 }
5874 else {
5875 ptr = (char *)type;
5876 }
5877 if (ptr != NULL)
5878 ptr += offset;
5879 return (void **)ptr;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005880}
Guido van Rossumf040ede2001-08-07 16:40:56 +00005881
Guido van Rossumc334df52002-04-04 23:44:47 +00005882/* Length of array of slotdef pointers used to store slots with the
5883 same __name__. There should be at most MAX_EQUIV-1 slotdef entries with
5884 the same __name__, for any __name__. Since that's a static property, it is
5885 appropriate to declare fixed-size arrays for this. */
5886#define MAX_EQUIV 10
5887
5888/* Return a slot pointer for a given name, but ONLY if the attribute has
5889 exactly one slot function. The name must be an interned string. */
5890static void **
5891resolve_slotdups(PyTypeObject *type, PyObject *name)
5892{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005893 /* XXX Maybe this could be optimized more -- but is it worth it? */
Guido van Rossumc334df52002-04-04 23:44:47 +00005894
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005895 /* pname and ptrs act as a little cache */
5896 static PyObject *pname;
5897 static slotdef *ptrs[MAX_EQUIV];
5898 slotdef *p, **pp;
5899 void **res, **ptr;
Guido van Rossumc334df52002-04-04 23:44:47 +00005900
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005901 if (pname != name) {
5902 /* Collect all slotdefs that match name into ptrs. */
5903 pname = name;
5904 pp = ptrs;
5905 for (p = slotdefs; p->name_strobj; p++) {
5906 if (p->name_strobj == name)
5907 *pp++ = p;
5908 }
5909 *pp = NULL;
5910 }
Guido van Rossumc334df52002-04-04 23:44:47 +00005911
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005912 /* Look in all matching slots of the type; if exactly one of these has
5913 a filled-in slot, return its value. Otherwise return NULL. */
5914 res = NULL;
5915 for (pp = ptrs; *pp; pp++) {
5916 ptr = slotptr(type, (*pp)->offset);
5917 if (ptr == NULL || *ptr == NULL)
5918 continue;
5919 if (res != NULL)
5920 return NULL;
5921 res = ptr;
5922 }
5923 return res;
Guido van Rossumc334df52002-04-04 23:44:47 +00005924}
5925
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005926/* Common code for update_slots_callback() and fixup_slot_dispatchers(). This
Guido van Rossumc334df52002-04-04 23:44:47 +00005927 does some incredibly complex thinking and then sticks something into the
5928 slot. (It sees if the adjacent slotdefs for the same slot have conflicting
5929 interests, and then stores a generic wrapper or a specific function into
5930 the slot.) Return a pointer to the next slotdef with a different offset,
5931 because that's convenient for fixup_slot_dispatchers(). */
5932static slotdef *
5933update_one_slot(PyTypeObject *type, slotdef *p)
5934{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005935 PyObject *descr;
5936 PyWrapperDescrObject *d;
5937 void *generic = NULL, *specific = NULL;
5938 int use_generic = 0;
5939 int offset = p->offset;
5940 void **ptr = slotptr(type, offset);
Guido van Rossumc334df52002-04-04 23:44:47 +00005941
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005942 if (ptr == NULL) {
5943 do {
5944 ++p;
5945 } while (p->offset == offset);
5946 return p;
5947 }
5948 do {
5949 descr = _PyType_Lookup(type, p->name_strobj);
5950 if (descr == NULL) {
5951 if (ptr == (void**)&type->tp_iternext) {
5952 specific = _PyObject_NextNotImplemented;
5953 }
5954 continue;
5955 }
5956 if (Py_TYPE(descr) == &PyWrapperDescr_Type) {
5957 void **tptr = resolve_slotdups(type, p->name_strobj);
5958 if (tptr == NULL || tptr == ptr)
5959 generic = p->function;
5960 d = (PyWrapperDescrObject *)descr;
5961 if (d->d_base->wrapper == p->wrapper &&
5962 PyType_IsSubtype(type, PyDescr_TYPE(d)))
5963 {
5964 if (specific == NULL ||
5965 specific == d->d_wrapped)
5966 specific = d->d_wrapped;
5967 else
5968 use_generic = 1;
5969 }
5970 }
5971 else if (Py_TYPE(descr) == &PyCFunction_Type &&
5972 PyCFunction_GET_FUNCTION(descr) ==
5973 (PyCFunction)tp_new_wrapper &&
5974 ptr == (void**)&type->tp_new)
5975 {
5976 /* The __new__ wrapper is not a wrapper descriptor,
5977 so must be special-cased differently.
5978 If we don't do this, creating an instance will
5979 always use slot_tp_new which will look up
5980 __new__ in the MRO which will call tp_new_wrapper
5981 which will look through the base classes looking
5982 for a static base and call its tp_new (usually
5983 PyType_GenericNew), after performing various
5984 sanity checks and constructing a new argument
5985 list. Cut all that nonsense short -- this speeds
5986 up instance creation tremendously. */
5987 specific = (void *)type->tp_new;
5988 /* XXX I'm not 100% sure that there isn't a hole
5989 in this reasoning that requires additional
5990 sanity checks. I'll buy the first person to
5991 point out a bug in this reasoning a beer. */
5992 }
5993 else if (descr == Py_None &&
5994 ptr == (void**)&type->tp_hash) {
5995 /* We specifically allow __hash__ to be set to None
5996 to prevent inheritance of the default
5997 implementation from object.__hash__ */
5998 specific = PyObject_HashNotImplemented;
5999 }
6000 else {
6001 use_generic = 1;
6002 generic = p->function;
6003 }
6004 } while ((++p)->offset == offset);
6005 if (specific && !use_generic)
6006 *ptr = specific;
6007 else
6008 *ptr = generic;
6009 return p;
Guido van Rossumc334df52002-04-04 23:44:47 +00006010}
6011
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006012/* In the type, update the slots whose slotdefs are gathered in the pp array.
6013 This is a callback for update_subclasses(). */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006014static int
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006015update_slots_callback(PyTypeObject *type, void *data)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006016{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006017 slotdef **pp = (slotdef **)data;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006018
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006019 for (; *pp; pp++)
6020 update_one_slot(type, *pp);
6021 return 0;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006022}
6023
Guido van Rossumc334df52002-04-04 23:44:47 +00006024/* Comparison function for qsort() to compare slotdefs by their offset, and
6025 for equal offset by their address (to force a stable sort). */
Guido van Rossumd396b9c2001-10-13 20:02:41 +00006026static int
6027slotdef_cmp(const void *aa, const void *bb)
6028{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006029 const slotdef *a = (const slotdef *)aa, *b = (const slotdef *)bb;
6030 int c = a->offset - b->offset;
6031 if (c != 0)
6032 return c;
6033 else
6034 /* Cannot use a-b, as this gives off_t,
6035 which may lose precision when converted to int. */
6036 return (a > b) ? 1 : (a < b) ? -1 : 0;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00006037}
6038
Guido van Rossumc334df52002-04-04 23:44:47 +00006039/* Initialize the slotdefs table by adding interned string objects for the
6040 names and sorting the entries. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006041static void
Guido van Rossumd396b9c2001-10-13 20:02:41 +00006042init_slotdefs(void)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006043{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006044 slotdef *p;
6045 static int initialized = 0;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006046
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006047 if (initialized)
6048 return;
6049 for (p = slotdefs; p->name; p++) {
6050 p->name_strobj = PyUnicode_InternFromString(p->name);
6051 if (!p->name_strobj)
6052 Py_FatalError("Out of memory interning slotdef names");
6053 }
6054 qsort((void *)slotdefs, (size_t)(p-slotdefs), sizeof(slotdef),
6055 slotdef_cmp);
6056 initialized = 1;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006057}
6058
Guido van Rossumc334df52002-04-04 23:44:47 +00006059/* Update the slots after assignment to a class (type) attribute. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006060static int
6061update_slot(PyTypeObject *type, PyObject *name)
6062{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006063 slotdef *ptrs[MAX_EQUIV];
6064 slotdef *p;
6065 slotdef **pp;
6066 int offset;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006067
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006068 /* Clear the VALID_VERSION flag of 'type' and all its
6069 subclasses. This could possibly be unified with the
6070 update_subclasses() recursion below, but carefully:
6071 they each have their own conditions on which to stop
6072 recursing into subclasses. */
6073 PyType_Modified(type);
Christian Heimesa62da1d2008-01-12 19:39:10 +00006074
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006075 init_slotdefs();
6076 pp = ptrs;
6077 for (p = slotdefs; p->name; p++) {
6078 /* XXX assume name is interned! */
6079 if (p->name_strobj == name)
6080 *pp++ = p;
6081 }
6082 *pp = NULL;
6083 for (pp = ptrs; *pp; pp++) {
6084 p = *pp;
6085 offset = p->offset;
6086 while (p > slotdefs && (p-1)->offset == offset)
6087 --p;
6088 *pp = p;
6089 }
6090 if (ptrs[0] == NULL)
6091 return 0; /* Not an attribute that affects any slots */
6092 return update_subclasses(type, name,
6093 update_slots_callback, (void *)ptrs);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006094}
6095
Guido van Rossumc334df52002-04-04 23:44:47 +00006096/* Store the proper functions in the slot dispatches at class (type)
6097 definition time, based upon which operations the class overrides in its
6098 dict. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00006099static void
Guido van Rossum7b9144b2001-10-09 19:39:46 +00006100fixup_slot_dispatchers(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00006101{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006102 slotdef *p;
Tim Peters6d6c1a32001-08-02 04:15:00 +00006103
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006104 init_slotdefs();
6105 for (p = slotdefs; p->name; )
6106 p = update_one_slot(type, p);
Tim Peters6d6c1a32001-08-02 04:15:00 +00006107}
Guido van Rossum705f0f52001-08-24 16:47:00 +00006108
Michael W. Hudson98bbc492002-11-26 14:47:27 +00006109static void
6110update_all_slots(PyTypeObject* type)
6111{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006112 slotdef *p;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00006113
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006114 init_slotdefs();
6115 for (p = slotdefs; p->name; p++) {
6116 /* update_slot returns int but can't actually fail */
6117 update_slot(type, p->name_strobj);
6118 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +00006119}
6120
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006121/* recurse_down_subclasses() and update_subclasses() are mutually
6122 recursive functions to call a callback for all subclasses,
6123 but refraining from recursing into subclasses that define 'name'. */
6124
6125static int
6126update_subclasses(PyTypeObject *type, PyObject *name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006127 update_callback callback, void *data)
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006128{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006129 if (callback(type, data) < 0)
6130 return -1;
6131 return recurse_down_subclasses(type, name, callback, data);
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006132}
6133
6134static int
6135recurse_down_subclasses(PyTypeObject *type, PyObject *name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006136 update_callback callback, void *data)
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006137{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006138 PyTypeObject *subclass;
6139 PyObject *ref, *subclasses, *dict;
6140 Py_ssize_t i, n;
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006141
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006142 subclasses = type->tp_subclasses;
6143 if (subclasses == NULL)
6144 return 0;
6145 assert(PyList_Check(subclasses));
6146 n = PyList_GET_SIZE(subclasses);
6147 for (i = 0; i < n; i++) {
6148 ref = PyList_GET_ITEM(subclasses, i);
6149 assert(PyWeakref_CheckRef(ref));
6150 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
6151 assert(subclass != NULL);
6152 if ((PyObject *)subclass == Py_None)
6153 continue;
6154 assert(PyType_Check(subclass));
6155 /* Avoid recursing down into unaffected classes */
6156 dict = subclass->tp_dict;
6157 if (dict != NULL && PyDict_Check(dict) &&
6158 PyDict_GetItem(dict, name) != NULL)
6159 continue;
6160 if (update_subclasses(subclass, name, callback, data) < 0)
6161 return -1;
6162 }
6163 return 0;
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006164}
6165
Guido van Rossum6d204072001-10-21 00:44:31 +00006166/* This function is called by PyType_Ready() to populate the type's
6167 dictionary with method descriptors for function slots. For each
Guido van Rossum09638c12002-06-13 19:17:46 +00006168 function slot (like tp_repr) that's defined in the type, one or more
6169 corresponding descriptors are added in the type's tp_dict dictionary
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006170 under the appropriate name (like __repr__). Some function slots
Guido van Rossum09638c12002-06-13 19:17:46 +00006171 cause more than one descriptor to be added (for example, the nb_add
6172 slot adds both __add__ and __radd__ descriptors) and some function
6173 slots compete for the same descriptor (for example both sq_item and
6174 mp_subscript generate a __getitem__ descriptor).
6175
Ezio Melotti13925002011-03-16 11:05:33 +02006176 In the latter case, the first slotdef entry encountered wins. Since
Tim Petersbf9b2442003-03-23 05:35:36 +00006177 slotdef entries are sorted by the offset of the slot in the
Guido van Rossume5c691a2003-03-07 15:13:17 +00006178 PyHeapTypeObject, this gives us some control over disambiguating
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006179 between competing slots: the members of PyHeapTypeObject are listed
6180 from most general to least general, so the most general slot is
6181 preferred. In particular, because as_mapping comes before as_sequence,
6182 for a type that defines both mp_subscript and sq_item, mp_subscript
6183 wins.
Guido van Rossum09638c12002-06-13 19:17:46 +00006184
6185 This only adds new descriptors and doesn't overwrite entries in
6186 tp_dict that were previously defined. The descriptors contain a
6187 reference to the C function they must call, so that it's safe if they
6188 are copied into a subtype's __dict__ and the subtype has a different
6189 C function in its slot -- calling the method defined by the
6190 descriptor will call the C function that was used to create it,
6191 rather than the C function present in the slot when it is called.
6192 (This is important because a subtype may have a C function in the
6193 slot that calls the method from the dictionary, and we want to avoid
6194 infinite recursion here.) */
Guido van Rossum6d204072001-10-21 00:44:31 +00006195
6196static int
6197add_operators(PyTypeObject *type)
6198{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006199 PyObject *dict = type->tp_dict;
6200 slotdef *p;
6201 PyObject *descr;
6202 void **ptr;
Guido van Rossum6d204072001-10-21 00:44:31 +00006203
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006204 init_slotdefs();
6205 for (p = slotdefs; p->name; p++) {
6206 if (p->wrapper == NULL)
6207 continue;
6208 ptr = slotptr(type, p->offset);
6209 if (!ptr || !*ptr)
6210 continue;
6211 if (PyDict_GetItem(dict, p->name_strobj))
6212 continue;
6213 if (*ptr == PyObject_HashNotImplemented) {
6214 /* Classes may prevent the inheritance of the tp_hash
6215 slot by storing PyObject_HashNotImplemented in it. Make it
6216 visible as a None value for the __hash__ attribute. */
6217 if (PyDict_SetItem(dict, p->name_strobj, Py_None) < 0)
6218 return -1;
6219 }
6220 else {
6221 descr = PyDescr_NewWrapper(type, p, *ptr);
6222 if (descr == NULL)
6223 return -1;
6224 if (PyDict_SetItem(dict, p->name_strobj, descr) < 0)
6225 return -1;
6226 Py_DECREF(descr);
6227 }
6228 }
6229 if (type->tp_new != NULL) {
6230 if (add_tp_new_wrapper(type) < 0)
6231 return -1;
6232 }
6233 return 0;
Guido van Rossum6d204072001-10-21 00:44:31 +00006234}
6235
Guido van Rossum705f0f52001-08-24 16:47:00 +00006236
6237/* Cooperative 'super' */
6238
6239typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006240 PyObject_HEAD
6241 PyTypeObject *type;
6242 PyObject *obj;
6243 PyTypeObject *obj_type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006244} superobject;
6245
Guido van Rossum6f799372001-09-20 20:46:19 +00006246static PyMemberDef super_members[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006247 {"__thisclass__", T_OBJECT, offsetof(superobject, type), READONLY,
6248 "the class invoking super()"},
6249 {"__self__", T_OBJECT, offsetof(superobject, obj), READONLY,
6250 "the instance invoking super(); may be None"},
6251 {"__self_class__", T_OBJECT, offsetof(superobject, obj_type), READONLY,
6252 "the type of the instance invoking super(); may be None"},
6253 {0}
Guido van Rossum41eb14d2001-08-30 23:13:11 +00006254};
6255
Guido van Rossum705f0f52001-08-24 16:47:00 +00006256static void
6257super_dealloc(PyObject *self)
6258{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006259 superobject *su = (superobject *)self;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006260
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006261 _PyObject_GC_UNTRACK(self);
6262 Py_XDECREF(su->obj);
6263 Py_XDECREF(su->type);
6264 Py_XDECREF(su->obj_type);
6265 Py_TYPE(self)->tp_free(self);
Guido van Rossum705f0f52001-08-24 16:47:00 +00006266}
6267
6268static PyObject *
Guido van Rossum41eb14d2001-08-30 23:13:11 +00006269super_repr(PyObject *self)
6270{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006271 superobject *su = (superobject *)self;
Guido van Rossum41eb14d2001-08-30 23:13:11 +00006272
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006273 if (su->obj_type)
6274 return PyUnicode_FromFormat(
6275 "<super: <class '%s'>, <%s object>>",
6276 su->type ? su->type->tp_name : "NULL",
6277 su->obj_type->tp_name);
6278 else
6279 return PyUnicode_FromFormat(
6280 "<super: <class '%s'>, NULL>",
6281 su->type ? su->type->tp_name : "NULL");
Guido van Rossum41eb14d2001-08-30 23:13:11 +00006282}
6283
6284static PyObject *
Guido van Rossum705f0f52001-08-24 16:47:00 +00006285super_getattro(PyObject *self, PyObject *name)
6286{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006287 superobject *su = (superobject *)self;
6288 int skip = su->obj_type == NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006289
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006290 if (!skip) {
6291 /* We want __class__ to return the class of the super object
6292 (i.e. super, or a subclass), not the class of su->obj. */
6293 skip = (PyUnicode_Check(name) &&
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006294 PyUnicode_GET_LENGTH(name) == 9 &&
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006295 PyUnicode_CompareWithASCIIString(name, "__class__") == 0);
6296 }
Guido van Rossum76ba09f2003-04-16 19:40:58 +00006297
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006298 if (!skip) {
6299 PyObject *mro, *res, *tmp, *dict;
6300 PyTypeObject *starttype;
6301 descrgetfunc f;
6302 Py_ssize_t i, n;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006303
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006304 starttype = su->obj_type;
6305 mro = starttype->tp_mro;
Guido van Rossum155db9a2002-04-02 17:53:47 +00006306
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006307 if (mro == NULL)
6308 n = 0;
6309 else {
6310 assert(PyTuple_Check(mro));
6311 n = PyTuple_GET_SIZE(mro);
6312 }
6313 for (i = 0; i < n; i++) {
6314 if ((PyObject *)(su->type) == PyTuple_GET_ITEM(mro, i))
6315 break;
6316 }
6317 i++;
6318 res = NULL;
6319 for (; i < n; i++) {
6320 tmp = PyTuple_GET_ITEM(mro, i);
6321 if (PyType_Check(tmp))
6322 dict = ((PyTypeObject *)tmp)->tp_dict;
6323 else
6324 continue;
6325 res = PyDict_GetItem(dict, name);
6326 if (res != NULL) {
6327 Py_INCREF(res);
6328 f = Py_TYPE(res)->tp_descr_get;
6329 if (f != NULL) {
6330 tmp = f(res,
6331 /* Only pass 'obj' param if
6332 this is instance-mode super
6333 (See SF ID #743627)
6334 */
6335 (su->obj == (PyObject *)
6336 su->obj_type
6337 ? (PyObject *)NULL
6338 : su->obj),
6339 (PyObject *)starttype);
6340 Py_DECREF(res);
6341 res = tmp;
6342 }
6343 return res;
6344 }
6345 }
6346 }
6347 return PyObject_GenericGetAttr(self, name);
Guido van Rossum705f0f52001-08-24 16:47:00 +00006348}
6349
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006350static PyTypeObject *
Guido van Rossum5b443c62001-12-03 15:38:28 +00006351supercheck(PyTypeObject *type, PyObject *obj)
6352{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006353 /* Check that a super() call makes sense. Return a type object.
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006354
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006355 obj can be a new-style class, or an instance of one:
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006356
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006357 - If it is a class, it must be a subclass of 'type'. This case is
6358 used for class methods; the return value is obj.
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006359
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006360 - If it is an instance, it must be an instance of 'type'. This is
6361 the normal case; the return value is obj.__class__.
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006362
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006363 But... when obj is an instance, we want to allow for the case where
6364 Py_TYPE(obj) is not a subclass of type, but obj.__class__ is!
6365 This will allow using super() with a proxy for obj.
6366 */
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006367
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006368 /* Check for first bullet above (special case) */
6369 if (PyType_Check(obj) && PyType_IsSubtype((PyTypeObject *)obj, type)) {
6370 Py_INCREF(obj);
6371 return (PyTypeObject *)obj;
6372 }
Guido van Rossum8e80a722003-02-18 19:22:22 +00006373
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006374 /* Normal case */
6375 if (PyType_IsSubtype(Py_TYPE(obj), type)) {
6376 Py_INCREF(Py_TYPE(obj));
6377 return Py_TYPE(obj);
6378 }
6379 else {
6380 /* Try the slow way */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006381 PyObject *class_attr;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006382
Martin v. Löwisbfc6d742011-10-13 20:03:57 +02006383 class_attr = _PyObject_GetAttrId(obj, &PyId___class__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006384 if (class_attr != NULL &&
6385 PyType_Check(class_attr) &&
6386 (PyTypeObject *)class_attr != Py_TYPE(obj))
6387 {
6388 int ok = PyType_IsSubtype(
6389 (PyTypeObject *)class_attr, type);
6390 if (ok)
6391 return (PyTypeObject *)class_attr;
6392 }
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006393
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006394 if (class_attr == NULL)
6395 PyErr_Clear();
6396 else
6397 Py_DECREF(class_attr);
6398 }
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006399
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006400 PyErr_SetString(PyExc_TypeError,
6401 "super(type, obj): "
6402 "obj must be an instance or subtype of type");
6403 return NULL;
Guido van Rossum5b443c62001-12-03 15:38:28 +00006404}
6405
Guido van Rossum705f0f52001-08-24 16:47:00 +00006406static PyObject *
6407super_descr_get(PyObject *self, PyObject *obj, PyObject *type)
6408{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006409 superobject *su = (superobject *)self;
6410 superobject *newobj;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006411
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006412 if (obj == NULL || obj == Py_None || su->obj != NULL) {
6413 /* Not binding to an object, or already bound */
6414 Py_INCREF(self);
6415 return self;
6416 }
6417 if (Py_TYPE(su) != &PySuper_Type)
6418 /* If su is an instance of a (strict) subclass of super,
6419 call its type */
6420 return PyObject_CallFunctionObjArgs((PyObject *)Py_TYPE(su),
6421 su->type, obj, NULL);
6422 else {
6423 /* Inline the common case */
6424 PyTypeObject *obj_type = supercheck(su->type, obj);
6425 if (obj_type == NULL)
6426 return NULL;
6427 newobj = (superobject *)PySuper_Type.tp_new(&PySuper_Type,
6428 NULL, NULL);
6429 if (newobj == NULL)
6430 return NULL;
6431 Py_INCREF(su->type);
6432 Py_INCREF(obj);
6433 newobj->type = su->type;
6434 newobj->obj = obj;
6435 newobj->obj_type = obj_type;
6436 return (PyObject *)newobj;
6437 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00006438}
6439
6440static int
6441super_init(PyObject *self, PyObject *args, PyObject *kwds)
6442{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006443 superobject *su = (superobject *)self;
6444 PyTypeObject *type = NULL;
6445 PyObject *obj = NULL;
6446 PyTypeObject *obj_type = NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006447
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006448 if (!_PyArg_NoKeywords("super", kwds))
6449 return -1;
6450 if (!PyArg_ParseTuple(args, "|O!O:super", &PyType_Type, &type, &obj))
6451 return -1;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00006452
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006453 if (type == NULL) {
6454 /* Call super(), without args -- fill in from __class__
6455 and first local variable on the stack. */
6456 PyFrameObject *f = PyThreadState_GET()->frame;
6457 PyCodeObject *co = f->f_code;
Victor Stinner0fcab4a2011-01-04 12:59:15 +00006458 Py_ssize_t i, n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006459 if (co == NULL) {
6460 PyErr_SetString(PyExc_SystemError,
6461 "super(): no code object");
6462 return -1;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00006463 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006464 if (co->co_argcount == 0) {
6465 PyErr_SetString(PyExc_SystemError,
6466 "super(): no arguments");
6467 return -1;
6468 }
6469 obj = f->f_localsplus[0];
6470 if (obj == NULL) {
6471 PyErr_SetString(PyExc_SystemError,
6472 "super(): arg[0] deleted");
6473 return -1;
6474 }
6475 if (co->co_freevars == NULL)
6476 n = 0;
6477 else {
6478 assert(PyTuple_Check(co->co_freevars));
6479 n = PyTuple_GET_SIZE(co->co_freevars);
6480 }
6481 for (i = 0; i < n; i++) {
6482 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
6483 assert(PyUnicode_Check(name));
6484 if (!PyUnicode_CompareWithASCIIString(name,
Benjamin Petersonf5ff2232011-06-19 19:42:22 -05006485 "@__class__")) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006486 Py_ssize_t index = co->co_nlocals +
6487 PyTuple_GET_SIZE(co->co_cellvars) + i;
6488 PyObject *cell = f->f_localsplus[index];
6489 if (cell == NULL || !PyCell_Check(cell)) {
6490 PyErr_SetString(PyExc_SystemError,
6491 "super(): bad __class__ cell");
6492 return -1;
6493 }
6494 type = (PyTypeObject *) PyCell_GET(cell);
6495 if (type == NULL) {
6496 PyErr_SetString(PyExc_SystemError,
6497 "super(): empty __class__ cell");
6498 return -1;
6499 }
6500 if (!PyType_Check(type)) {
6501 PyErr_Format(PyExc_SystemError,
6502 "super(): __class__ is not a type (%s)",
6503 Py_TYPE(type)->tp_name);
6504 return -1;
6505 }
6506 break;
6507 }
6508 }
6509 if (type == NULL) {
6510 PyErr_SetString(PyExc_SystemError,
6511 "super(): __class__ cell not found");
6512 return -1;
6513 }
6514 }
Guido van Rossumcd16bf62007-06-13 18:07:49 +00006515
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006516 if (obj == Py_None)
6517 obj = NULL;
6518 if (obj != NULL) {
6519 obj_type = supercheck(type, obj);
6520 if (obj_type == NULL)
6521 return -1;
6522 Py_INCREF(obj);
6523 }
6524 Py_INCREF(type);
6525 su->type = type;
6526 su->obj = obj;
6527 su->obj_type = obj_type;
6528 return 0;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006529}
6530
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00006531PyDoc_STRVAR(super_doc,
Guido van Rossumcd16bf62007-06-13 18:07:49 +00006532"super() -> same as super(__class__, <first argument>)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00006533"super(type) -> unbound super object\n"
6534"super(type, obj) -> bound super object; requires isinstance(obj, type)\n"
Guido van Rossume705ef12001-08-29 15:47:06 +00006535"super(type, type2) -> bound super object; requires issubclass(type2, type)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00006536"Typical use to call a cooperative superclass method:\n"
6537"class C(B):\n"
6538" def meth(self, arg):\n"
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006539" super().meth(arg)\n"
Guido van Rossumcd16bf62007-06-13 18:07:49 +00006540"This works for class methods too:\n"
6541"class C(B):\n"
6542" @classmethod\n"
6543" def cmeth(cls, arg):\n"
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006544" super().cmeth(arg)\n");
Guido van Rossum705f0f52001-08-24 16:47:00 +00006545
Guido van Rossum048eb752001-10-02 21:24:57 +00006546static int
6547super_traverse(PyObject *self, visitproc visit, void *arg)
6548{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006549 superobject *su = (superobject *)self;
Guido van Rossum048eb752001-10-02 21:24:57 +00006550
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006551 Py_VISIT(su->obj);
6552 Py_VISIT(su->type);
6553 Py_VISIT(su->obj_type);
Guido van Rossum048eb752001-10-02 21:24:57 +00006554
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006555 return 0;
Guido van Rossum048eb752001-10-02 21:24:57 +00006556}
6557
Guido van Rossum705f0f52001-08-24 16:47:00 +00006558PyTypeObject PySuper_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006559 PyVarObject_HEAD_INIT(&PyType_Type, 0)
6560 "super", /* tp_name */
6561 sizeof(superobject), /* tp_basicsize */
6562 0, /* tp_itemsize */
6563 /* methods */
6564 super_dealloc, /* tp_dealloc */
6565 0, /* tp_print */
6566 0, /* tp_getattr */
6567 0, /* tp_setattr */
6568 0, /* tp_reserved */
6569 super_repr, /* tp_repr */
6570 0, /* tp_as_number */
6571 0, /* tp_as_sequence */
6572 0, /* tp_as_mapping */
6573 0, /* tp_hash */
6574 0, /* tp_call */
6575 0, /* tp_str */
6576 super_getattro, /* tp_getattro */
6577 0, /* tp_setattro */
6578 0, /* tp_as_buffer */
6579 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
6580 Py_TPFLAGS_BASETYPE, /* tp_flags */
6581 super_doc, /* tp_doc */
6582 super_traverse, /* tp_traverse */
6583 0, /* tp_clear */
6584 0, /* tp_richcompare */
6585 0, /* tp_weaklistoffset */
6586 0, /* tp_iter */
6587 0, /* tp_iternext */
6588 0, /* tp_methods */
6589 super_members, /* tp_members */
6590 0, /* tp_getset */
6591 0, /* tp_base */
6592 0, /* tp_dict */
6593 super_descr_get, /* tp_descr_get */
6594 0, /* tp_descr_set */
6595 0, /* tp_dictoffset */
6596 super_init, /* tp_init */
6597 PyType_GenericAlloc, /* tp_alloc */
6598 PyType_GenericNew, /* tp_new */
6599 PyObject_GC_Del, /* tp_free */
Guido van Rossum705f0f52001-08-24 16:47:00 +00006600};