blob: adb69cb627dbd6bdd6c1df16305cdedc802b59b2 [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, \
23 ((PyUnicodeObject *)(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) && \
26 PyUnicode_GET_SIZE(name) <= MCACHE_MAX_ATTR_SIZE
Christian Heimesa62da1d2008-01-12 19:39:10 +000027
28struct method_cache_entry {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000029 unsigned int version;
30 PyObject *name; /* reference to exactly a str or None */
31 PyObject *value; /* borrowed */
Christian Heimesa62da1d2008-01-12 19:39:10 +000032};
33
34static struct method_cache_entry method_cache[1 << MCACHE_SIZE_EXP];
35static unsigned int next_version_tag = 0;
Christian Heimes26855632008-01-27 23:50:43 +000036
37unsigned int
38PyType_ClearCache(void)
39{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000040 Py_ssize_t i;
41 unsigned int cur_version_tag = next_version_tag - 1;
42
43 for (i = 0; i < (1 << MCACHE_SIZE_EXP); i++) {
44 method_cache[i].version = 0;
45 Py_CLEAR(method_cache[i].name);
46 method_cache[i].value = NULL;
47 }
48 next_version_tag = 0;
49 /* mark all version tags as invalid */
50 PyType_Modified(&PyBaseObject_Type);
51 return cur_version_tag;
Christian Heimes26855632008-01-27 23:50:43 +000052}
Christian Heimesa62da1d2008-01-12 19:39:10 +000053
Georg Brandlf08a9dd2008-06-10 16:57:31 +000054void
55PyType_Modified(PyTypeObject *type)
Christian Heimesa62da1d2008-01-12 19:39:10 +000056{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000057 /* Invalidate any cached data for the specified type and all
58 subclasses. This function is called after the base
59 classes, mro, or attributes of the type are altered.
Christian Heimesa62da1d2008-01-12 19:39:10 +000060
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000061 Invariants:
Christian Heimesa62da1d2008-01-12 19:39:10 +000062
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000063 - Py_TPFLAGS_VALID_VERSION_TAG is never set if
64 Py_TPFLAGS_HAVE_VERSION_TAG is not set (e.g. on type
65 objects coming from non-recompiled extension modules)
Christian Heimesa62da1d2008-01-12 19:39:10 +000066
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000067 - before Py_TPFLAGS_VALID_VERSION_TAG can be set on a type,
68 it must first be set on all super types.
Christian Heimesa62da1d2008-01-12 19:39:10 +000069
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000070 This function clears the Py_TPFLAGS_VALID_VERSION_TAG of a
71 type (so it must first clear it on all subclasses). The
72 tp_version_tag value is meaningless unless this flag is set.
73 We don't assign new version tags eagerly, but only as
74 needed.
75 */
76 PyObject *raw, *ref;
77 Py_ssize_t i, n;
Christian Heimesa62da1d2008-01-12 19:39:10 +000078
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000079 if (!PyType_HasFeature(type, Py_TPFLAGS_VALID_VERSION_TAG))
80 return;
Christian Heimesa62da1d2008-01-12 19:39:10 +000081
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000082 raw = type->tp_subclasses;
83 if (raw != NULL) {
84 n = PyList_GET_SIZE(raw);
85 for (i = 0; i < n; i++) {
86 ref = PyList_GET_ITEM(raw, i);
87 ref = PyWeakref_GET_OBJECT(ref);
88 if (ref != Py_None) {
89 PyType_Modified((PyTypeObject *)ref);
90 }
91 }
92 }
93 type->tp_flags &= ~Py_TPFLAGS_VALID_VERSION_TAG;
Christian Heimesa62da1d2008-01-12 19:39:10 +000094}
95
96static void
97type_mro_modified(PyTypeObject *type, PyObject *bases) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000098 /*
99 Check that all base classes or elements of the mro of type are
100 able to be cached. This function is called after the base
101 classes or mro of the type are altered.
Christian Heimesa62da1d2008-01-12 19:39:10 +0000102
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000103 Unset HAVE_VERSION_TAG and VALID_VERSION_TAG if the type
104 inherits from an old-style class, either directly or if it
105 appears in the MRO of a new-style class. No support either for
106 custom MROs that include types that are not officially super
107 types.
Christian Heimesa62da1d2008-01-12 19:39:10 +0000108
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000109 Called from mro_internal, which will subsequently be called on
110 each subclass when their mro is recursively updated.
111 */
112 Py_ssize_t i, n;
113 int clear = 0;
Christian Heimesa62da1d2008-01-12 19:39:10 +0000114
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000115 if (!PyType_HasFeature(type, Py_TPFLAGS_HAVE_VERSION_TAG))
116 return;
Christian Heimesa62da1d2008-01-12 19:39:10 +0000117
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000118 n = PyTuple_GET_SIZE(bases);
119 for (i = 0; i < n; i++) {
120 PyObject *b = PyTuple_GET_ITEM(bases, i);
121 PyTypeObject *cls;
Christian Heimesa62da1d2008-01-12 19:39:10 +0000122
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000123 if (!PyType_Check(b) ) {
124 clear = 1;
125 break;
126 }
Christian Heimesa62da1d2008-01-12 19:39:10 +0000127
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000128 cls = (PyTypeObject *)b;
Christian Heimesa62da1d2008-01-12 19:39:10 +0000129
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000130 if (!PyType_HasFeature(cls, Py_TPFLAGS_HAVE_VERSION_TAG) ||
131 !PyType_IsSubtype(type, cls)) {
132 clear = 1;
133 break;
134 }
135 }
Christian Heimesa62da1d2008-01-12 19:39:10 +0000136
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000137 if (clear)
138 type->tp_flags &= ~(Py_TPFLAGS_HAVE_VERSION_TAG|
139 Py_TPFLAGS_VALID_VERSION_TAG);
Christian Heimesa62da1d2008-01-12 19:39:10 +0000140}
141
142static int
143assign_version_tag(PyTypeObject *type)
144{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000145 /* Ensure that the tp_version_tag is valid and set
146 Py_TPFLAGS_VALID_VERSION_TAG. To respect the invariant, this
147 must first be done on all super classes. Return 0 if this
148 cannot be done, 1 if Py_TPFLAGS_VALID_VERSION_TAG.
149 */
150 Py_ssize_t i, n;
151 PyObject *bases;
Christian Heimesa62da1d2008-01-12 19:39:10 +0000152
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000153 if (PyType_HasFeature(type, Py_TPFLAGS_VALID_VERSION_TAG))
154 return 1;
155 if (!PyType_HasFeature(type, Py_TPFLAGS_HAVE_VERSION_TAG))
156 return 0;
157 if (!PyType_HasFeature(type, Py_TPFLAGS_READY))
158 return 0;
Christian Heimesa62da1d2008-01-12 19:39:10 +0000159
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000160 type->tp_version_tag = next_version_tag++;
161 /* for stress-testing: next_version_tag &= 0xFF; */
Christian Heimesa62da1d2008-01-12 19:39:10 +0000162
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000163 if (type->tp_version_tag == 0) {
164 /* wrap-around or just starting Python - clear the whole
165 cache by filling names with references to Py_None.
166 Values are also set to NULL for added protection, as they
167 are borrowed reference */
168 for (i = 0; i < (1 << MCACHE_SIZE_EXP); i++) {
169 method_cache[i].value = NULL;
170 Py_XDECREF(method_cache[i].name);
171 method_cache[i].name = Py_None;
172 Py_INCREF(Py_None);
173 }
174 /* mark all version tags as invalid */
175 PyType_Modified(&PyBaseObject_Type);
176 return 1;
177 }
178 bases = type->tp_bases;
179 n = PyTuple_GET_SIZE(bases);
180 for (i = 0; i < n; i++) {
181 PyObject *b = PyTuple_GET_ITEM(bases, i);
182 assert(PyType_Check(b));
183 if (!assign_version_tag((PyTypeObject *)b))
184 return 0;
185 }
186 type->tp_flags |= Py_TPFLAGS_VALID_VERSION_TAG;
187 return 1;
Christian Heimesa62da1d2008-01-12 19:39:10 +0000188}
189
190
Guido van Rossum6f799372001-09-20 20:46:19 +0000191static PyMemberDef type_members[] = {
Benjamin Peterson0e102062010-08-25 23:13:17 +0000192 {"__basicsize__", T_PYSSIZET, offsetof(PyTypeObject,tp_basicsize),READONLY},
193 {"__itemsize__", T_PYSSIZET, offsetof(PyTypeObject, tp_itemsize), READONLY},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000194 {"__flags__", T_LONG, offsetof(PyTypeObject, tp_flags), READONLY},
195 {"__weakrefoffset__", T_LONG,
196 offsetof(PyTypeObject, tp_weaklistoffset), READONLY},
197 {"__base__", T_OBJECT, offsetof(PyTypeObject, tp_base), READONLY},
198 {"__dictoffset__", T_LONG,
199 offsetof(PyTypeObject, tp_dictoffset), READONLY},
200 {"__mro__", T_OBJECT, offsetof(PyTypeObject, tp_mro), READONLY},
201 {0}
Tim Peters6d6c1a32001-08-02 04:15:00 +0000202};
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000203
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000204static PyObject *
Guido van Rossumc3542212001-08-16 09:18:56 +0000205type_name(PyTypeObject *type, void *context)
206{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000207 const char *s;
Guido van Rossumc3542212001-08-16 09:18:56 +0000208
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000209 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
210 PyHeapTypeObject* et = (PyHeapTypeObject*)type;
Tim Petersea7f75d2002-12-07 21:39:16 +0000211
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000212 Py_INCREF(et->ht_name);
213 return et->ht_name;
214 }
215 else {
216 s = strrchr(type->tp_name, '.');
217 if (s == NULL)
218 s = type->tp_name;
219 else
220 s++;
221 return PyUnicode_FromString(s);
222 }
Guido van Rossumc3542212001-08-16 09:18:56 +0000223}
224
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000225static int
226type_set_name(PyTypeObject *type, PyObject *value, void *context)
227{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000228 PyHeapTypeObject* et;
229 char *tp_name;
230 PyObject *tmp;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000231
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000232 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
233 PyErr_Format(PyExc_TypeError,
234 "can't set %s.__name__", type->tp_name);
235 return -1;
236 }
237 if (!value) {
238 PyErr_Format(PyExc_TypeError,
239 "can't delete %s.__name__", type->tp_name);
240 return -1;
241 }
242 if (!PyUnicode_Check(value)) {
243 PyErr_Format(PyExc_TypeError,
244 "can only assign string to %s.__name__, not '%s'",
245 type->tp_name, Py_TYPE(value)->tp_name);
246 return -1;
247 }
Guido van Rossume845c0f2007-11-02 23:07:07 +0000248
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000249 /* Check absence of null characters */
250 tmp = PyUnicode_FromStringAndSize("\0", 1);
251 if (tmp == NULL)
252 return -1;
253 if (PyUnicode_Contains(value, tmp) != 0) {
254 Py_DECREF(tmp);
255 PyErr_Format(PyExc_ValueError,
256 "__name__ must not contain null bytes");
257 return -1;
258 }
259 Py_DECREF(tmp);
Guido van Rossume845c0f2007-11-02 23:07:07 +0000260
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000261 tp_name = _PyUnicode_AsString(value);
262 if (tp_name == NULL)
263 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000264
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000265 et = (PyHeapTypeObject*)type;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000266
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000267 Py_INCREF(value);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000268
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000269 Py_DECREF(et->ht_name);
270 et->ht_name = value;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000271
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000272 type->tp_name = tp_name;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000273
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000274 return 0;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000275}
276
Guido van Rossumc3542212001-08-16 09:18:56 +0000277static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000278type_module(PyTypeObject *type, void *context)
Guido van Rossum29ca26e1995-01-07 11:58:15 +0000279{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000280 PyObject *mod;
281 char *s;
Guido van Rossumc3542212001-08-16 09:18:56 +0000282
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000283 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
284 mod = PyDict_GetItemString(type->tp_dict, "__module__");
285 if (!mod) {
286 PyErr_Format(PyExc_AttributeError, "__module__");
287 return 0;
288 }
289 Py_XINCREF(mod);
290 return mod;
291 }
292 else {
293 s = strrchr(type->tp_name, '.');
294 if (s != NULL)
295 return PyUnicode_FromStringAndSize(
296 type->tp_name, (Py_ssize_t)(s - type->tp_name));
297 return PyUnicode_FromString("builtins");
298 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000299}
300
Guido van Rossum3926a632001-09-25 16:25:58 +0000301static int
302type_set_module(PyTypeObject *type, PyObject *value, void *context)
303{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000304 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
305 PyErr_Format(PyExc_TypeError,
306 "can't set %s.__module__", type->tp_name);
307 return -1;
308 }
309 if (!value) {
310 PyErr_Format(PyExc_TypeError,
311 "can't delete %s.__module__", type->tp_name);
312 return -1;
313 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000314
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000315 PyType_Modified(type);
Christian Heimesa62da1d2008-01-12 19:39:10 +0000316
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000317 return PyDict_SetItemString(type->tp_dict, "__module__", value);
Guido van Rossum3926a632001-09-25 16:25:58 +0000318}
319
Tim Peters6d6c1a32001-08-02 04:15:00 +0000320static PyObject *
Christian Heimes9e7f1d22008-02-28 12:27:11 +0000321type_abstractmethods(PyTypeObject *type, void *context)
322{
Benjamin Petersonaec5fd12010-10-02 00:03:31 +0000323 PyObject *mod = NULL;
Benjamin Peterson84060b82010-10-03 02:13:39 +0000324 /* type itself has an __abstractmethods__ descriptor (this). Don't return
325 that. */
Benjamin Petersonaec5fd12010-10-02 00:03:31 +0000326 if (type != &PyType_Type)
327 mod = PyDict_GetItemString(type->tp_dict, "__abstractmethods__");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000328 if (!mod) {
Benjamin Peterson23b628e2011-01-12 18:56:07 +0000329 PyErr_SetString(PyExc_AttributeError, "__abstractmethods__");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000330 return NULL;
331 }
332 Py_XINCREF(mod);
333 return mod;
Christian Heimes9e7f1d22008-02-28 12:27:11 +0000334}
335
336static int
337type_set_abstractmethods(PyTypeObject *type, PyObject *value, void *context)
338{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000339 /* __abstractmethods__ should only be set once on a type, in
340 abc.ABCMeta.__new__, so this function doesn't do anything
341 special to update subclasses.
342 */
Antoine Pitrou6f430e42012-08-15 23:18:25 +0200343 int abstract, res;
Benjamin Peterson477ba912011-01-12 15:34:01 +0000344 if (value != NULL) {
Antoine Pitrou6f430e42012-08-15 23:18:25 +0200345 abstract = PyObject_IsTrue(value);
346 if (abstract < 0)
347 return -1;
Benjamin Peterson477ba912011-01-12 15:34:01 +0000348 res = PyDict_SetItemString(type->tp_dict, "__abstractmethods__", value);
349 }
350 else {
Antoine Pitrou6f430e42012-08-15 23:18:25 +0200351 abstract = 0;
Benjamin Peterson477ba912011-01-12 15:34:01 +0000352 res = PyDict_DelItemString(type->tp_dict, "__abstractmethods__");
353 if (res && PyErr_ExceptionMatches(PyExc_KeyError)) {
Benjamin Peterson23b628e2011-01-12 18:56:07 +0000354 PyErr_SetString(PyExc_AttributeError, "__abstractmethods__");
Benjamin Peterson477ba912011-01-12 15:34:01 +0000355 return -1;
356 }
357 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000358 if (res == 0) {
359 PyType_Modified(type);
Antoine Pitrou6f430e42012-08-15 23:18:25 +0200360 if (abstract)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000361 type->tp_flags |= Py_TPFLAGS_IS_ABSTRACT;
Antoine Pitrou6f430e42012-08-15 23:18:25 +0200362 else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000363 type->tp_flags &= ~Py_TPFLAGS_IS_ABSTRACT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000364 }
365 return res;
Christian Heimes9e7f1d22008-02-28 12:27:11 +0000366}
367
368static PyObject *
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000369type_get_bases(PyTypeObject *type, void *context)
370{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000371 Py_INCREF(type->tp_bases);
372 return type->tp_bases;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000373}
374
375static PyTypeObject *best_base(PyObject *);
376static int mro_internal(PyTypeObject *);
377static int compatible_for_assignment(PyTypeObject *, PyTypeObject *, char *);
378static int add_subclass(PyTypeObject*, PyTypeObject*);
379static void remove_subclass(PyTypeObject *, PyTypeObject *);
380static void update_all_slots(PyTypeObject *);
381
Guido van Rossum8d24ee92003-03-24 23:49:49 +0000382typedef int (*update_callback)(PyTypeObject *, void *);
383static int update_subclasses(PyTypeObject *type, PyObject *name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000384 update_callback callback, void *data);
Guido van Rossum8d24ee92003-03-24 23:49:49 +0000385static int recurse_down_subclasses(PyTypeObject *type, PyObject *name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000386 update_callback callback, void *data);
Guido van Rossum8d24ee92003-03-24 23:49:49 +0000387
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000388static int
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000389mro_subclasses(PyTypeObject *type, PyObject* temp)
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000390{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000391 PyTypeObject *subclass;
392 PyObject *ref, *subclasses, *old_mro;
393 Py_ssize_t i, n;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000394
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000395 subclasses = type->tp_subclasses;
396 if (subclasses == NULL)
397 return 0;
398 assert(PyList_Check(subclasses));
399 n = PyList_GET_SIZE(subclasses);
400 for (i = 0; i < n; i++) {
401 ref = PyList_GET_ITEM(subclasses, i);
402 assert(PyWeakref_CheckRef(ref));
403 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
404 assert(subclass != NULL);
405 if ((PyObject *)subclass == Py_None)
406 continue;
407 assert(PyType_Check(subclass));
408 old_mro = subclass->tp_mro;
409 if (mro_internal(subclass) < 0) {
410 subclass->tp_mro = old_mro;
411 return -1;
412 }
413 else {
414 PyObject* tuple;
415 tuple = PyTuple_Pack(2, subclass, old_mro);
416 Py_DECREF(old_mro);
417 if (!tuple)
418 return -1;
419 if (PyList_Append(temp, tuple) < 0)
420 return -1;
421 Py_DECREF(tuple);
422 }
423 if (mro_subclasses(subclass, temp) < 0)
424 return -1;
425 }
426 return 0;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000427}
428
429static int
430type_set_bases(PyTypeObject *type, PyObject *value, void *context)
431{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000432 Py_ssize_t i;
433 int r = 0;
434 PyObject *ob, *temp;
435 PyTypeObject *new_base, *old_base;
436 PyObject *old_bases, *old_mro;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000437
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000438 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
439 PyErr_Format(PyExc_TypeError,
440 "can't set %s.__bases__", type->tp_name);
441 return -1;
442 }
443 if (!value) {
444 PyErr_Format(PyExc_TypeError,
445 "can't delete %s.__bases__", type->tp_name);
446 return -1;
447 }
448 if (!PyTuple_Check(value)) {
449 PyErr_Format(PyExc_TypeError,
450 "can only assign tuple to %s.__bases__, not %s",
451 type->tp_name, Py_TYPE(value)->tp_name);
452 return -1;
453 }
454 if (PyTuple_GET_SIZE(value) == 0) {
455 PyErr_Format(PyExc_TypeError,
456 "can only assign non-empty tuple to %s.__bases__, not ()",
457 type->tp_name);
458 return -1;
459 }
460 for (i = 0; i < PyTuple_GET_SIZE(value); i++) {
461 ob = PyTuple_GET_ITEM(value, i);
462 if (!PyType_Check(ob)) {
Benjamin Petersonb6af60c2012-04-01 18:49:54 -0400463 PyErr_Format(PyExc_TypeError,
464 "%s.__bases__ must be tuple of old- or "
465 "new-style classes, not '%s'",
466 type->tp_name, Py_TYPE(ob)->tp_name);
467 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000468 }
Benjamin Peterson3471bb62012-04-01 18:48:40 -0400469 if (PyType_IsSubtype((PyTypeObject*)ob, type)) {
470 PyErr_SetString(PyExc_TypeError,
471 "a __bases__ item causes an inheritance cycle");
472 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000473 }
474 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000475
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000476 new_base = best_base(value);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000477
Benjamin Petersonab3c1c12012-04-01 18:48:02 -0400478 if (!new_base)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000479 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000480
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000481 if (!compatible_for_assignment(type->tp_base, new_base, "__bases__"))
482 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000483
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000484 Py_INCREF(new_base);
485 Py_INCREF(value);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000486
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000487 old_bases = type->tp_bases;
488 old_base = type->tp_base;
489 old_mro = type->tp_mro;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000490
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000491 type->tp_bases = value;
492 type->tp_base = new_base;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000493
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000494 if (mro_internal(type) < 0) {
495 goto bail;
496 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000497
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000498 temp = PyList_New(0);
499 if (!temp)
500 goto bail;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000501
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000502 r = mro_subclasses(type, temp);
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000503
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000504 if (r < 0) {
505 for (i = 0; i < PyList_Size(temp); i++) {
506 PyTypeObject* cls;
507 PyObject* mro;
508 PyArg_UnpackTuple(PyList_GET_ITEM(temp, i),
509 "", 2, 2, &cls, &mro);
510 Py_INCREF(mro);
511 ob = cls->tp_mro;
512 cls->tp_mro = mro;
513 Py_DECREF(ob);
514 }
515 Py_DECREF(temp);
516 goto bail;
517 }
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000518
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000519 Py_DECREF(temp);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000520
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000521 /* any base that was in __bases__ but now isn't, we
522 need to remove |type| from its tp_subclasses.
523 conversely, any class now in __bases__ that wasn't
524 needs to have |type| added to its subclasses. */
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000525
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000526 /* for now, sod that: just remove from all old_bases,
527 add to all new_bases */
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000528
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000529 for (i = PyTuple_GET_SIZE(old_bases) - 1; i >= 0; i--) {
530 ob = PyTuple_GET_ITEM(old_bases, i);
531 if (PyType_Check(ob)) {
532 remove_subclass(
533 (PyTypeObject*)ob, type);
534 }
535 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000536
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000537 for (i = PyTuple_GET_SIZE(value) - 1; i >= 0; i--) {
538 ob = PyTuple_GET_ITEM(value, i);
539 if (PyType_Check(ob)) {
540 if (add_subclass((PyTypeObject*)ob, type) < 0)
541 r = -1;
542 }
543 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000544
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000545 update_all_slots(type);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000546
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000547 Py_DECREF(old_bases);
548 Py_DECREF(old_base);
549 Py_DECREF(old_mro);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000550
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000551 return r;
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000552
553 bail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000554 Py_DECREF(type->tp_bases);
555 Py_DECREF(type->tp_base);
556 if (type->tp_mro != old_mro) {
557 Py_DECREF(type->tp_mro);
558 }
Michael W. Hudsone723e452003-08-07 14:58:10 +0000559
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000560 type->tp_bases = old_bases;
561 type->tp_base = old_base;
562 type->tp_mro = old_mro;
Tim Petersea7f75d2002-12-07 21:39:16 +0000563
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000564 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000565}
566
567static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000568type_dict(PyTypeObject *type, void *context)
569{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000570 if (type->tp_dict == NULL) {
571 Py_INCREF(Py_None);
572 return Py_None;
573 }
574 return PyDictProxy_New(type->tp_dict);
Guido van Rossum29ca26e1995-01-07 11:58:15 +0000575}
576
Tim Peters24008312002-03-17 18:56:20 +0000577static PyObject *
578type_get_doc(PyTypeObject *type, void *context)
579{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000580 PyObject *result;
581 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE) && type->tp_doc != NULL)
582 return PyUnicode_FromString(type->tp_doc);
583 result = PyDict_GetItemString(type->tp_dict, "__doc__");
584 if (result == NULL) {
585 result = Py_None;
586 Py_INCREF(result);
587 }
588 else if (Py_TYPE(result)->tp_descr_get) {
589 result = Py_TYPE(result)->tp_descr_get(result, NULL,
590 (PyObject *)type);
591 }
592 else {
593 Py_INCREF(result);
594 }
595 return result;
Tim Peters24008312002-03-17 18:56:20 +0000596}
597
Antoine Pitrouec569b72008-08-26 22:40:48 +0000598static PyObject *
599type___instancecheck__(PyObject *type, PyObject *inst)
600{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000601 switch (_PyObject_RealIsInstance(inst, type)) {
602 case -1:
603 return NULL;
604 case 0:
605 Py_RETURN_FALSE;
606 default:
607 Py_RETURN_TRUE;
608 }
Antoine Pitrouec569b72008-08-26 22:40:48 +0000609}
610
611
612static PyObject *
Antoine Pitrouec569b72008-08-26 22:40:48 +0000613type___subclasscheck__(PyObject *type, PyObject *inst)
614{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000615 switch (_PyObject_RealIsSubclass(inst, type)) {
616 case -1:
617 return NULL;
618 case 0:
619 Py_RETURN_FALSE;
620 default:
621 Py_RETURN_TRUE;
622 }
Antoine Pitrouec569b72008-08-26 22:40:48 +0000623}
624
Antoine Pitrouec569b72008-08-26 22:40:48 +0000625
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000626static PyGetSetDef type_getsets[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000627 {"__name__", (getter)type_name, (setter)type_set_name, NULL},
628 {"__bases__", (getter)type_get_bases, (setter)type_set_bases, NULL},
629 {"__module__", (getter)type_module, (setter)type_set_module, NULL},
630 {"__abstractmethods__", (getter)type_abstractmethods,
631 (setter)type_set_abstractmethods, NULL},
632 {"__dict__", (getter)type_dict, NULL, NULL},
633 {"__doc__", (getter)type_get_doc, NULL, NULL},
634 {0}
Tim Peters6d6c1a32001-08-02 04:15:00 +0000635};
636
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000637static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000638type_repr(PyTypeObject *type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000639{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000640 PyObject *mod, *name, *rtn;
Guido van Rossumc3542212001-08-16 09:18:56 +0000641
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000642 mod = type_module(type, NULL);
643 if (mod == NULL)
644 PyErr_Clear();
645 else if (!PyUnicode_Check(mod)) {
646 Py_DECREF(mod);
647 mod = NULL;
648 }
649 name = type_name(type, NULL);
650 if (name == NULL)
651 return NULL;
Barry Warsaw7ce36942001-08-24 18:34:26 +0000652
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000653 if (mod != NULL && PyUnicode_CompareWithASCIIString(mod, "builtins"))
654 rtn = PyUnicode_FromFormat("<class '%U.%U'>", mod, name);
655 else
656 rtn = PyUnicode_FromFormat("<class '%s'>", type->tp_name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000657
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000658 Py_XDECREF(mod);
659 Py_DECREF(name);
660 return rtn;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000661}
662
Tim Peters6d6c1a32001-08-02 04:15:00 +0000663static PyObject *
664type_call(PyTypeObject *type, PyObject *args, PyObject *kwds)
665{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000666 PyObject *obj;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000667
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000668 if (type->tp_new == NULL) {
669 PyErr_Format(PyExc_TypeError,
670 "cannot create '%.100s' instances",
671 type->tp_name);
672 return NULL;
673 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000674
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000675 obj = type->tp_new(type, args, kwds);
676 if (obj != NULL) {
677 /* Ugly exception: when the call was type(something),
678 don't call tp_init on the result. */
679 if (type == &PyType_Type &&
680 PyTuple_Check(args) && PyTuple_GET_SIZE(args) == 1 &&
681 (kwds == NULL ||
682 (PyDict_Check(kwds) && PyDict_Size(kwds) == 0)))
683 return obj;
684 /* If the returned object is not an instance of type,
685 it won't be initialized. */
686 if (!PyType_IsSubtype(Py_TYPE(obj), type))
687 return obj;
688 type = Py_TYPE(obj);
689 if (type->tp_init != NULL &&
690 type->tp_init(obj, args, kwds) < 0) {
691 Py_DECREF(obj);
692 obj = NULL;
693 }
694 }
695 return obj;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000696}
697
698PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000699PyType_GenericAlloc(PyTypeObject *type, Py_ssize_t nitems)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000700{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000701 PyObject *obj;
702 const size_t size = _PyObject_VAR_SIZE(type, nitems+1);
703 /* note that we need to add one, for the sentinel */
Tim Peters406fe3b2001-10-06 19:04:01 +0000704
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000705 if (PyType_IS_GC(type))
706 obj = _PyObject_GC_Malloc(size);
707 else
708 obj = (PyObject *)PyObject_MALLOC(size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000709
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000710 if (obj == NULL)
711 return PyErr_NoMemory();
Tim Peters406fe3b2001-10-06 19:04:01 +0000712
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000713 memset(obj, '\0', size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000714
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000715 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
716 Py_INCREF(type);
Tim Peters406fe3b2001-10-06 19:04:01 +0000717
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000718 if (type->tp_itemsize == 0)
719 PyObject_INIT(obj, type);
720 else
721 (void) PyObject_INIT_VAR((PyVarObject *)obj, type, nitems);
Tim Peters406fe3b2001-10-06 19:04:01 +0000722
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000723 if (PyType_IS_GC(type))
724 _PyObject_GC_TRACK(obj);
725 return obj;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000726}
727
728PyObject *
729PyType_GenericNew(PyTypeObject *type, PyObject *args, PyObject *kwds)
730{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000731 return type->tp_alloc(type, 0);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000732}
733
Guido van Rossum9475a232001-10-05 20:51:39 +0000734/* Helpers for subtyping */
735
736static int
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000737traverse_slots(PyTypeObject *type, PyObject *self, visitproc visit, void *arg)
738{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000739 Py_ssize_t i, n;
740 PyMemberDef *mp;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000741
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000742 n = Py_SIZE(type);
743 mp = PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type);
744 for (i = 0; i < n; i++, mp++) {
745 if (mp->type == T_OBJECT_EX) {
746 char *addr = (char *)self + mp->offset;
747 PyObject *obj = *(PyObject **)addr;
748 if (obj != NULL) {
749 int err = visit(obj, arg);
750 if (err)
751 return err;
752 }
753 }
754 }
755 return 0;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000756}
757
758static int
Guido van Rossum9475a232001-10-05 20:51:39 +0000759subtype_traverse(PyObject *self, visitproc visit, void *arg)
760{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000761 PyTypeObject *type, *base;
762 traverseproc basetraverse;
Guido van Rossum9475a232001-10-05 20:51:39 +0000763
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000764 /* Find the nearest base with a different tp_traverse,
765 and traverse slots while we're at it */
766 type = Py_TYPE(self);
767 base = type;
768 while ((basetraverse = base->tp_traverse) == subtype_traverse) {
769 if (Py_SIZE(base)) {
770 int err = traverse_slots(base, self, visit, arg);
771 if (err)
772 return err;
773 }
774 base = base->tp_base;
775 assert(base);
776 }
Guido van Rossum9475a232001-10-05 20:51:39 +0000777
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000778 if (type->tp_dictoffset != base->tp_dictoffset) {
779 PyObject **dictptr = _PyObject_GetDictPtr(self);
780 if (dictptr && *dictptr)
781 Py_VISIT(*dictptr);
782 }
Guido van Rossum9475a232001-10-05 20:51:39 +0000783
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000784 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
785 /* For a heaptype, the instances count as references
786 to the type. Traverse the type so the collector
787 can find cycles involving this link. */
788 Py_VISIT(type);
Guido van Rossuma3862092002-06-10 15:24:42 +0000789
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000790 if (basetraverse)
791 return basetraverse(self, visit, arg);
792 return 0;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000793}
794
795static void
796clear_slots(PyTypeObject *type, PyObject *self)
797{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000798 Py_ssize_t i, n;
799 PyMemberDef *mp;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000800
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000801 n = Py_SIZE(type);
802 mp = PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type);
803 for (i = 0; i < n; i++, mp++) {
804 if (mp->type == T_OBJECT_EX && !(mp->flags & READONLY)) {
805 char *addr = (char *)self + mp->offset;
806 PyObject *obj = *(PyObject **)addr;
807 if (obj != NULL) {
808 *(PyObject **)addr = NULL;
809 Py_DECREF(obj);
810 }
811 }
812 }
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000813}
814
815static int
816subtype_clear(PyObject *self)
817{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000818 PyTypeObject *type, *base;
819 inquiry baseclear;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000820
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000821 /* Find the nearest base with a different tp_clear
822 and clear slots while we're at it */
823 type = Py_TYPE(self);
824 base = type;
825 while ((baseclear = base->tp_clear) == subtype_clear) {
826 if (Py_SIZE(base))
827 clear_slots(base, self);
828 base = base->tp_base;
829 assert(base);
830 }
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000831
Benjamin Peterson52c42432012-03-07 18:41:11 -0600832 /* Clear the instance dict (if any), to break cycles involving only
833 __dict__ slots (as in the case 'self.__dict__ is self'). */
834 if (type->tp_dictoffset != base->tp_dictoffset) {
835 PyObject **dictptr = _PyObject_GetDictPtr(self);
836 if (dictptr && *dictptr)
837 Py_CLEAR(*dictptr);
838 }
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000839
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000840 if (baseclear)
841 return baseclear(self);
842 return 0;
Guido van Rossum9475a232001-10-05 20:51:39 +0000843}
Tim Peters6d6c1a32001-08-02 04:15:00 +0000844
845static void
846subtype_dealloc(PyObject *self)
847{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000848 PyTypeObject *type, *base;
849 destructor basedealloc;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000850
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000851 /* Extract the type; we expect it to be a heap type */
852 type = Py_TYPE(self);
853 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000854
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000855 /* Test whether the type has GC exactly once */
Guido van Rossum22b13872002-08-06 21:41:44 +0000856
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000857 if (!PyType_IS_GC(type)) {
858 /* It's really rare to find a dynamic type that doesn't have
859 GC; it can only happen when deriving from 'object' and not
860 adding any slots or instance variables. This allows
861 certain simplifications: there's no need to call
862 clear_slots(), or DECREF the dict, or clear weakrefs. */
Guido van Rossum22b13872002-08-06 21:41:44 +0000863
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000864 /* Maybe call finalizer; exit early if resurrected */
865 if (type->tp_del) {
866 type->tp_del(self);
867 if (self->ob_refcnt > 0)
868 return;
869 }
Guido van Rossum22b13872002-08-06 21:41:44 +0000870
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000871 /* Find the nearest base with a different tp_dealloc */
872 base = type;
873 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
874 assert(Py_SIZE(base) == 0);
875 base = base->tp_base;
876 assert(base);
877 }
Guido van Rossum22b13872002-08-06 21:41:44 +0000878
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000879 /* Extract the type again; tp_del may have changed it */
880 type = Py_TYPE(self);
Benjamin Peterson193152c2009-04-25 01:08:45 +0000881
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000882 /* Call the base tp_dealloc() */
883 assert(basedealloc);
884 basedealloc(self);
Guido van Rossum22b13872002-08-06 21:41:44 +0000885
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000886 /* Can't reference self beyond this point */
887 Py_DECREF(type);
Guido van Rossum22b13872002-08-06 21:41:44 +0000888
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000889 /* Done */
890 return;
891 }
Guido van Rossum22b13872002-08-06 21:41:44 +0000892
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000893 /* We get here only if the type has GC */
Guido van Rossum22b13872002-08-06 21:41:44 +0000894
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000895 /* UnTrack and re-Track around the trashcan macro, alas */
896 /* See explanation at end of function for full disclosure */
897 PyObject_GC_UnTrack(self);
898 ++_PyTrash_delete_nesting;
899 Py_TRASHCAN_SAFE_BEGIN(self);
900 --_PyTrash_delete_nesting;
901 /* DO NOT restore GC tracking at this point. weakref callbacks
902 * (if any, and whether directly here or indirectly in something we
903 * call) may trigger GC, and if self is tracked at that point, it
904 * will look like trash to GC and GC will try to delete self again.
905 */
Guido van Rossum22b13872002-08-06 21:41:44 +0000906
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000907 /* Find the nearest base with a different tp_dealloc */
908 base = type;
909 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
910 base = base->tp_base;
911 assert(base);
912 }
Guido van Rossum14227b42001-12-06 02:35:58 +0000913
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000914 /* If we added a weaklist, we clear it. Do this *before* calling
915 the finalizer (__del__), clearing slots, or clearing the instance
916 dict. */
Guido van Rossum59195fd2003-06-13 20:54:40 +0000917
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000918 if (type->tp_weaklistoffset && !base->tp_weaklistoffset)
919 PyObject_ClearWeakRefs(self);
Guido van Rossum1987c662003-05-29 14:29:23 +0000920
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000921 /* Maybe call finalizer; exit early if resurrected */
922 if (type->tp_del) {
923 _PyObject_GC_TRACK(self);
924 type->tp_del(self);
925 if (self->ob_refcnt > 0)
926 goto endlabel; /* resurrected */
927 else
928 _PyObject_GC_UNTRACK(self);
929 /* New weakrefs could be created during the finalizer call.
930 If this occurs, clear them out without calling their
931 finalizers since they might rely on part of the object
932 being finalized that has already been destroyed. */
933 if (type->tp_weaklistoffset && !base->tp_weaklistoffset) {
934 /* Modeled after GET_WEAKREFS_LISTPTR() */
935 PyWeakReference **list = (PyWeakReference **) \
936 PyObject_GET_WEAKREFS_LISTPTR(self);
937 while (*list)
938 _PyWeakref_ClearRef(*list);
939 }
940 }
Guido van Rossum1987c662003-05-29 14:29:23 +0000941
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000942 /* Clear slots up to the nearest base with a different tp_dealloc */
943 base = type;
944 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
945 if (Py_SIZE(base))
946 clear_slots(base, self);
947 base = base->tp_base;
948 assert(base);
949 }
Guido van Rossum59195fd2003-06-13 20:54:40 +0000950
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000951 /* If we added a dict, DECREF it */
952 if (type->tp_dictoffset && !base->tp_dictoffset) {
953 PyObject **dictptr = _PyObject_GetDictPtr(self);
954 if (dictptr != NULL) {
955 PyObject *dict = *dictptr;
956 if (dict != NULL) {
957 Py_DECREF(dict);
958 *dictptr = NULL;
959 }
960 }
961 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000962
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000963 /* Extract the type again; tp_del may have changed it */
964 type = Py_TYPE(self);
Benjamin Peterson193152c2009-04-25 01:08:45 +0000965
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000966 /* Call the base tp_dealloc(); first retrack self if
967 * basedealloc knows about gc.
968 */
969 if (PyType_IS_GC(base))
970 _PyObject_GC_TRACK(self);
971 assert(basedealloc);
972 basedealloc(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000973
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000974 /* Can't reference self beyond this point */
975 Py_DECREF(type);
Guido van Rossum22b13872002-08-06 21:41:44 +0000976
Guido van Rossum0906e072002-08-07 20:42:09 +0000977 endlabel:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000978 ++_PyTrash_delete_nesting;
979 Py_TRASHCAN_SAFE_END(self);
980 --_PyTrash_delete_nesting;
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000981
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000982 /* Explanation of the weirdness around the trashcan macros:
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000983
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000984 Q. What do the trashcan macros do?
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000985
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000986 A. Read the comment titled "Trashcan mechanism" in object.h.
987 For one, this explains why there must be a call to GC-untrack
988 before the trashcan begin macro. Without understanding the
989 trashcan code, the answers to the following questions don't make
990 sense.
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000991
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000992 Q. Why do we GC-untrack before the trashcan and then immediately
993 GC-track again afterward?
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000994
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000995 A. In the case that the base class is GC-aware, the base class
996 probably GC-untracks the object. If it does that using the
997 UNTRACK macro, this will crash when the object is already
998 untracked. Because we don't know what the base class does, the
999 only safe thing is to make sure the object is tracked when we
1000 call the base class dealloc. But... The trashcan begin macro
1001 requires that the object is *untracked* before it is called. So
1002 the dance becomes:
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001003
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001004 GC untrack
1005 trashcan begin
1006 GC track
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001007
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001008 Q. Why did the last question say "immediately GC-track again"?
1009 It's nowhere near immediately.
Tim Petersf7f9e992003-11-13 21:59:32 +00001010
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001011 A. Because the code *used* to re-track immediately. Bad Idea.
1012 self has a refcount of 0, and if gc ever gets its hands on it
1013 (which can happen if any weakref callback gets invoked), it
1014 looks like trash to gc too, and gc also tries to delete self
Ezio Melotti13925002011-03-16 11:05:33 +02001015 then. But we're already deleting self. Double deallocation is
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001016 a subtle disaster.
Tim Petersf7f9e992003-11-13 21:59:32 +00001017
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001018 Q. Why the bizarre (net-zero) manipulation of
1019 _PyTrash_delete_nesting around the trashcan macros?
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001020
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001021 A. Some base classes (e.g. list) also use the trashcan mechanism.
1022 The following scenario used to be possible:
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001023
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001024 - suppose the trashcan level is one below the trashcan limit
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001025
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001026 - subtype_dealloc() is called
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001027
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001028 - the trashcan limit is not yet reached, so the trashcan level
1029 is incremented and the code between trashcan begin and end is
1030 executed
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001031
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001032 - this destroys much of the object's contents, including its
1033 slots and __dict__
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001034
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001035 - basedealloc() is called; this is really list_dealloc(), or
1036 some other type which also uses the trashcan macros
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001037
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001038 - the trashcan limit is now reached, so the object is put on the
1039 trashcan's to-be-deleted-later list
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001040
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001041 - basedealloc() returns
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001042
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001043 - subtype_dealloc() decrefs the object's type
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001044
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001045 - subtype_dealloc() returns
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001046
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001047 - later, the trashcan code starts deleting the objects from its
1048 to-be-deleted-later list
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001049
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001050 - subtype_dealloc() is called *AGAIN* for the same object
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001051
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001052 - at the very least (if the destroyed slots and __dict__ don't
1053 cause problems) the object's type gets decref'ed a second
1054 time, which is *BAD*!!!
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001055
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001056 The remedy is to make sure that if the code between trashcan
1057 begin and end in subtype_dealloc() is called, the code between
1058 trashcan begin and end in basedealloc() will also be called.
1059 This is done by decrementing the level after passing into the
1060 trashcan block, and incrementing it just before leaving the
1061 block.
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001062
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001063 But now it's possible that a chain of objects consisting solely
1064 of objects whose deallocator is subtype_dealloc() will defeat
1065 the trashcan mechanism completely: the decremented level means
1066 that the effective level never reaches the limit. Therefore, we
1067 *increment* the level *before* entering the trashcan block, and
1068 matchingly decrement it after leaving. This means the trashcan
1069 code will trigger a little early, but that's no big deal.
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001070
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001071 Q. Are there any live examples of code in need of all this
1072 complexity?
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001073
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001074 A. Yes. See SF bug 668433 for code that crashed (when Python was
1075 compiled in debug mode) before the trashcan level manipulations
1076 were added. For more discussion, see SF patches 581742, 575073
1077 and bug 574207.
1078 */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001079}
1080
Jeremy Hylton938ace62002-07-17 16:30:39 +00001081static PyTypeObject *solid_base(PyTypeObject *type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001082
Tim Peters6d6c1a32001-08-02 04:15:00 +00001083/* type test with subclassing support */
1084
1085int
1086PyType_IsSubtype(PyTypeObject *a, PyTypeObject *b)
1087{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001088 PyObject *mro;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001089
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001090 mro = a->tp_mro;
1091 if (mro != NULL) {
1092 /* Deal with multiple inheritance without recursion
1093 by walking the MRO tuple */
1094 Py_ssize_t i, n;
1095 assert(PyTuple_Check(mro));
1096 n = PyTuple_GET_SIZE(mro);
1097 for (i = 0; i < n; i++) {
1098 if (PyTuple_GET_ITEM(mro, i) == (PyObject *)b)
1099 return 1;
1100 }
1101 return 0;
1102 }
1103 else {
1104 /* a is not completely initilized yet; follow tp_base */
1105 do {
1106 if (a == b)
1107 return 1;
1108 a = a->tp_base;
1109 } while (a != NULL);
1110 return b == &PyBaseObject_Type;
1111 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001112}
1113
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001114/* Internal routines to do a method lookup in the type
Guido van Rossum60718732001-08-28 17:47:51 +00001115 without looking in the instance dictionary
1116 (so we can't use PyObject_GetAttr) but still binding
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001117 it to the instance. The arguments are the object,
Guido van Rossum60718732001-08-28 17:47:51 +00001118 the method name as a C string, and the address of a
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001119 static variable used to cache the interned Python string.
1120
1121 Two variants:
1122
1123 - lookup_maybe() returns NULL without raising an exception
1124 when the _PyType_Lookup() call fails;
1125
1126 - lookup_method() always raises an exception upon errors.
Benjamin Peterson224205f2009-05-08 03:25:19 +00001127
1128 - _PyObject_LookupSpecial() exported for the benefit of other places.
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001129*/
Guido van Rossum60718732001-08-28 17:47:51 +00001130
1131static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001132lookup_maybe(PyObject *self, char *attrstr, PyObject **attrobj)
Guido van Rossum60718732001-08-28 17:47:51 +00001133{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001134 PyObject *res;
Guido van Rossum60718732001-08-28 17:47:51 +00001135
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001136 if (*attrobj == NULL) {
1137 *attrobj = PyUnicode_InternFromString(attrstr);
1138 if (*attrobj == NULL)
1139 return NULL;
1140 }
1141 res = _PyType_Lookup(Py_TYPE(self), *attrobj);
1142 if (res != NULL) {
1143 descrgetfunc f;
1144 if ((f = Py_TYPE(res)->tp_descr_get) == NULL)
1145 Py_INCREF(res);
1146 else
1147 res = f(res, self, (PyObject *)(Py_TYPE(self)));
1148 }
1149 return res;
Guido van Rossum60718732001-08-28 17:47:51 +00001150}
1151
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001152static PyObject *
1153lookup_method(PyObject *self, char *attrstr, PyObject **attrobj)
1154{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001155 PyObject *res = lookup_maybe(self, attrstr, attrobj);
1156 if (res == NULL && !PyErr_Occurred())
1157 PyErr_SetObject(PyExc_AttributeError, *attrobj);
1158 return res;
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001159}
1160
Benjamin Peterson224205f2009-05-08 03:25:19 +00001161PyObject *
1162_PyObject_LookupSpecial(PyObject *self, char *attrstr, PyObject **attrobj)
1163{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001164 return lookup_maybe(self, attrstr, attrobj);
Benjamin Peterson224205f2009-05-08 03:25:19 +00001165}
1166
Guido van Rossum2730b132001-08-28 18:22:14 +00001167/* A variation of PyObject_CallMethod that uses lookup_method()
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001168 instead of PyObject_GetAttrString(). This uses the same convention
Guido van Rossum2730b132001-08-28 18:22:14 +00001169 as lookup_method to cache the interned name string object. */
1170
Neil Schemenauerf23473f2001-10-21 22:28:58 +00001171static PyObject *
Guido van Rossum2730b132001-08-28 18:22:14 +00001172call_method(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
1173{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001174 va_list va;
1175 PyObject *args, *func = 0, *retval;
1176 va_start(va, format);
Guido van Rossum2730b132001-08-28 18:22:14 +00001177
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001178 func = lookup_maybe(o, name, nameobj);
1179 if (func == NULL) {
1180 va_end(va);
1181 if (!PyErr_Occurred())
1182 PyErr_SetObject(PyExc_AttributeError, *nameobj);
1183 return NULL;
1184 }
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001185
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001186 if (format && *format)
1187 args = Py_VaBuildValue(format, va);
1188 else
1189 args = PyTuple_New(0);
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001190
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001191 va_end(va);
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001192
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001193 if (args == NULL)
1194 return NULL;
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001195
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001196 assert(PyTuple_Check(args));
1197 retval = PyObject_Call(func, args, NULL);
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001198
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001199 Py_DECREF(args);
1200 Py_DECREF(func);
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001201
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001202 return retval;
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001203}
1204
1205/* Clone of call_method() that returns NotImplemented when the lookup fails. */
1206
Neil Schemenauerf23473f2001-10-21 22:28:58 +00001207static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001208call_maybe(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
1209{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001210 va_list va;
1211 PyObject *args, *func = 0, *retval;
1212 va_start(va, format);
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001213
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001214 func = lookup_maybe(o, name, nameobj);
1215 if (func == NULL) {
1216 va_end(va);
1217 if (!PyErr_Occurred()) {
1218 Py_INCREF(Py_NotImplemented);
1219 return Py_NotImplemented;
1220 }
1221 return NULL;
1222 }
Guido van Rossum2730b132001-08-28 18:22:14 +00001223
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001224 if (format && *format)
1225 args = Py_VaBuildValue(format, va);
1226 else
1227 args = PyTuple_New(0);
Guido van Rossum2730b132001-08-28 18:22:14 +00001228
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001229 va_end(va);
Guido van Rossum2730b132001-08-28 18:22:14 +00001230
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001231 if (args == NULL)
1232 return NULL;
Guido van Rossum2730b132001-08-28 18:22:14 +00001233
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001234 assert(PyTuple_Check(args));
1235 retval = PyObject_Call(func, args, NULL);
Guido van Rossum2730b132001-08-28 18:22:14 +00001236
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001237 Py_DECREF(args);
1238 Py_DECREF(func);
Guido van Rossum2730b132001-08-28 18:22:14 +00001239
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001240 return retval;
Guido van Rossum2730b132001-08-28 18:22:14 +00001241}
1242
Tim Petersea7f75d2002-12-07 21:39:16 +00001243/*
Guido van Rossum1f121312002-11-14 19:49:16 +00001244 Method resolution order algorithm C3 described in
1245 "A Monotonic Superclass Linearization for Dylan",
1246 by Kim Barrett, Bob Cassel, Paul Haahr,
Tim Petersea7f75d2002-12-07 21:39:16 +00001247 David A. Moon, Keith Playford, and P. Tucker Withington.
Guido van Rossum1f121312002-11-14 19:49:16 +00001248 (OOPSLA 1996)
1249
Guido van Rossum98f33732002-11-25 21:36:54 +00001250 Some notes about the rules implied by C3:
1251
Tim Petersea7f75d2002-12-07 21:39:16 +00001252 No duplicate bases.
Guido van Rossum98f33732002-11-25 21:36:54 +00001253 It isn't legal to repeat a class in a list of base classes.
1254
1255 The next three properties are the 3 constraints in "C3".
1256
Tim Petersea7f75d2002-12-07 21:39:16 +00001257 Local precendece order.
Guido van Rossum98f33732002-11-25 21:36:54 +00001258 If A precedes B in C's MRO, then A will precede B in the MRO of all
1259 subclasses of C.
1260
1261 Monotonicity.
1262 The MRO of a class must be an extension without reordering of the
1263 MRO of each of its superclasses.
1264
1265 Extended Precedence Graph (EPG).
1266 Linearization is consistent if there is a path in the EPG from
1267 each class to all its successors in the linearization. See
1268 the paper for definition of EPG.
Guido van Rossum1f121312002-11-14 19:49:16 +00001269 */
1270
Tim Petersea7f75d2002-12-07 21:39:16 +00001271static int
Guido van Rossum1f121312002-11-14 19:49:16 +00001272tail_contains(PyObject *list, int whence, PyObject *o) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001273 Py_ssize_t j, size;
1274 size = PyList_GET_SIZE(list);
Guido van Rossum1f121312002-11-14 19:49:16 +00001275
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001276 for (j = whence+1; j < size; j++) {
1277 if (PyList_GET_ITEM(list, j) == o)
1278 return 1;
1279 }
1280 return 0;
Guido van Rossum1f121312002-11-14 19:49:16 +00001281}
1282
Guido van Rossum98f33732002-11-25 21:36:54 +00001283static PyObject *
1284class_name(PyObject *cls)
1285{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001286 PyObject *name = PyObject_GetAttrString(cls, "__name__");
1287 if (name == NULL) {
1288 PyErr_Clear();
1289 Py_XDECREF(name);
1290 name = PyObject_Repr(cls);
1291 }
1292 if (name == NULL)
1293 return NULL;
1294 if (!PyUnicode_Check(name)) {
1295 Py_DECREF(name);
1296 return NULL;
1297 }
1298 return name;
Guido van Rossum98f33732002-11-25 21:36:54 +00001299}
1300
1301static int
1302check_duplicates(PyObject *list)
1303{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001304 Py_ssize_t i, j, n;
1305 /* Let's use a quadratic time algorithm,
1306 assuming that the bases lists is short.
1307 */
1308 n = PyList_GET_SIZE(list);
1309 for (i = 0; i < n; i++) {
1310 PyObject *o = PyList_GET_ITEM(list, i);
1311 for (j = i + 1; j < n; j++) {
1312 if (PyList_GET_ITEM(list, j) == o) {
1313 o = class_name(o);
1314 if (o != NULL) {
1315 PyErr_Format(PyExc_TypeError,
1316 "duplicate base class %U",
1317 o);
1318 Py_DECREF(o);
1319 } else {
1320 PyErr_SetString(PyExc_TypeError,
1321 "duplicate base class");
1322 }
1323 return -1;
1324 }
1325 }
1326 }
1327 return 0;
Guido van Rossum98f33732002-11-25 21:36:54 +00001328}
1329
1330/* Raise a TypeError for an MRO order disagreement.
1331
1332 It's hard to produce a good error message. In the absence of better
1333 insight into error reporting, report the classes that were candidates
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001334 to be put next into the MRO. There is some conflict between the
Guido van Rossum98f33732002-11-25 21:36:54 +00001335 order in which they should be put in the MRO, but it's hard to
1336 diagnose what constraint can't be satisfied.
1337*/
1338
1339static void
1340set_mro_error(PyObject *to_merge, int *remain)
1341{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001342 Py_ssize_t i, n, off, to_merge_size;
1343 char buf[1000];
1344 PyObject *k, *v;
1345 PyObject *set = PyDict_New();
1346 if (!set) return;
Guido van Rossum98f33732002-11-25 21:36:54 +00001347
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001348 to_merge_size = PyList_GET_SIZE(to_merge);
1349 for (i = 0; i < to_merge_size; i++) {
1350 PyObject *L = PyList_GET_ITEM(to_merge, i);
1351 if (remain[i] < PyList_GET_SIZE(L)) {
1352 PyObject *c = PyList_GET_ITEM(L, remain[i]);
1353 if (PyDict_SetItem(set, c, Py_None) < 0) {
1354 Py_DECREF(set);
1355 return;
1356 }
1357 }
1358 }
1359 n = PyDict_Size(set);
Guido van Rossum98f33732002-11-25 21:36:54 +00001360
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001361 off = PyOS_snprintf(buf, sizeof(buf), "Cannot create a \
Raymond Hettingerf394df42003-04-06 19:13:41 +00001362consistent method resolution\norder (MRO) for bases");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001363 i = 0;
1364 while (PyDict_Next(set, &i, &k, &v) && (size_t)off < sizeof(buf)) {
1365 PyObject *name = class_name(k);
Victor Stinnere5f99f32010-05-19 01:42:46 +00001366 char *name_str;
1367 if (name != NULL) {
1368 name_str = _PyUnicode_AsString(name);
1369 if (name_str == NULL)
Victor Stinnerba644a62010-05-19 01:50:45 +00001370 name_str = "?";
Victor Stinnere5f99f32010-05-19 01:42:46 +00001371 } else
Victor Stinnerba644a62010-05-19 01:50:45 +00001372 name_str = "?";
Victor Stinnere5f99f32010-05-19 01:42:46 +00001373 off += PyOS_snprintf(buf + off, sizeof(buf) - off, " %s", name_str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001374 Py_XDECREF(name);
1375 if (--n && (size_t)(off+1) < sizeof(buf)) {
1376 buf[off++] = ',';
1377 buf[off] = '\0';
1378 }
1379 }
1380 PyErr_SetString(PyExc_TypeError, buf);
1381 Py_DECREF(set);
Guido van Rossum98f33732002-11-25 21:36:54 +00001382}
1383
Tim Petersea7f75d2002-12-07 21:39:16 +00001384static int
Guido van Rossum1f121312002-11-14 19:49:16 +00001385pmerge(PyObject *acc, PyObject* to_merge) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001386 Py_ssize_t i, j, to_merge_size, empty_cnt;
1387 int *remain;
1388 int ok;
Tim Petersea7f75d2002-12-07 21:39:16 +00001389
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001390 to_merge_size = PyList_GET_SIZE(to_merge);
Guido van Rossum1f121312002-11-14 19:49:16 +00001391
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001392 /* remain stores an index into each sublist of to_merge.
1393 remain[i] is the index of the next base in to_merge[i]
1394 that is not included in acc.
1395 */
1396 remain = (int *)PyMem_MALLOC(SIZEOF_INT*to_merge_size);
1397 if (remain == NULL)
1398 return -1;
1399 for (i = 0; i < to_merge_size; i++)
1400 remain[i] = 0;
Guido van Rossum1f121312002-11-14 19:49:16 +00001401
1402 again:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001403 empty_cnt = 0;
1404 for (i = 0; i < to_merge_size; i++) {
1405 PyObject *candidate;
Tim Petersea7f75d2002-12-07 21:39:16 +00001406
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001407 PyObject *cur_list = PyList_GET_ITEM(to_merge, i);
Guido van Rossum1f121312002-11-14 19:49:16 +00001408
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001409 if (remain[i] >= PyList_GET_SIZE(cur_list)) {
1410 empty_cnt++;
1411 continue;
1412 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001413
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001414 /* Choose next candidate for MRO.
Guido van Rossum98f33732002-11-25 21:36:54 +00001415
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001416 The input sequences alone can determine the choice.
1417 If not, choose the class which appears in the MRO
1418 of the earliest direct superclass of the new class.
1419 */
Guido van Rossum98f33732002-11-25 21:36:54 +00001420
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001421 candidate = PyList_GET_ITEM(cur_list, remain[i]);
1422 for (j = 0; j < to_merge_size; j++) {
1423 PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
1424 if (tail_contains(j_lst, remain[j], candidate)) {
1425 goto skip; /* continue outer loop */
1426 }
1427 }
1428 ok = PyList_Append(acc, candidate);
1429 if (ok < 0) {
1430 PyMem_Free(remain);
1431 return -1;
1432 }
1433 for (j = 0; j < to_merge_size; j++) {
1434 PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
1435 if (remain[j] < PyList_GET_SIZE(j_lst) &&
1436 PyList_GET_ITEM(j_lst, remain[j]) == candidate) {
1437 remain[j]++;
1438 }
1439 }
1440 goto again;
1441 skip: ;
1442 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001443
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001444 if (empty_cnt == to_merge_size) {
1445 PyMem_FREE(remain);
1446 return 0;
1447 }
1448 set_mro_error(to_merge, remain);
1449 PyMem_FREE(remain);
1450 return -1;
Guido van Rossum1f121312002-11-14 19:49:16 +00001451}
1452
Tim Peters6d6c1a32001-08-02 04:15:00 +00001453static PyObject *
1454mro_implementation(PyTypeObject *type)
1455{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001456 Py_ssize_t i, n;
1457 int ok;
1458 PyObject *bases, *result;
1459 PyObject *to_merge, *bases_aslist;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001460
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001461 if (type->tp_dict == NULL) {
1462 if (PyType_Ready(type) < 0)
1463 return NULL;
1464 }
Guido van Rossum63517572002-06-18 16:44:57 +00001465
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001466 /* Find a superclass linearization that honors the constraints
1467 of the explicit lists of bases and the constraints implied by
1468 each base class.
Guido van Rossum98f33732002-11-25 21:36:54 +00001469
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001470 to_merge is a list of lists, where each list is a superclass
1471 linearization implied by a base class. The last element of
1472 to_merge is the declared list of bases.
1473 */
Guido van Rossum98f33732002-11-25 21:36:54 +00001474
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001475 bases = type->tp_bases;
1476 n = PyTuple_GET_SIZE(bases);
Guido van Rossum1f121312002-11-14 19:49:16 +00001477
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001478 to_merge = PyList_New(n+1);
1479 if (to_merge == NULL)
1480 return NULL;
Guido van Rossum1f121312002-11-14 19:49:16 +00001481
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001482 for (i = 0; i < n; i++) {
1483 PyObject *base = PyTuple_GET_ITEM(bases, i);
1484 PyObject *parentMRO;
1485 parentMRO = PySequence_List(((PyTypeObject*)base)->tp_mro);
1486 if (parentMRO == NULL) {
1487 Py_DECREF(to_merge);
1488 return NULL;
1489 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001490
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001491 PyList_SET_ITEM(to_merge, i, parentMRO);
1492 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001493
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001494 bases_aslist = PySequence_List(bases);
1495 if (bases_aslist == NULL) {
1496 Py_DECREF(to_merge);
1497 return NULL;
1498 }
1499 /* This is just a basic sanity check. */
1500 if (check_duplicates(bases_aslist) < 0) {
1501 Py_DECREF(to_merge);
1502 Py_DECREF(bases_aslist);
1503 return NULL;
1504 }
1505 PyList_SET_ITEM(to_merge, n, bases_aslist);
Guido van Rossum1f121312002-11-14 19:49:16 +00001506
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001507 result = Py_BuildValue("[O]", (PyObject *)type);
1508 if (result == NULL) {
1509 Py_DECREF(to_merge);
1510 return NULL;
1511 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001512
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001513 ok = pmerge(result, to_merge);
1514 Py_DECREF(to_merge);
1515 if (ok < 0) {
1516 Py_DECREF(result);
1517 return NULL;
1518 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001519
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001520 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001521}
1522
1523static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001524mro_external(PyObject *self)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001525{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001526 PyTypeObject *type = (PyTypeObject *)self;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001527
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001528 return mro_implementation(type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001529}
1530
1531static int
1532mro_internal(PyTypeObject *type)
1533{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001534 PyObject *mro, *result, *tuple;
1535 int checkit = 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001536
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001537 if (Py_TYPE(type) == &PyType_Type) {
1538 result = mro_implementation(type);
1539 }
1540 else {
1541 static PyObject *mro_str;
1542 checkit = 1;
1543 mro = lookup_method((PyObject *)type, "mro", &mro_str);
1544 if (mro == NULL)
1545 return -1;
1546 result = PyObject_CallObject(mro, NULL);
1547 Py_DECREF(mro);
1548 }
1549 if (result == NULL)
1550 return -1;
1551 tuple = PySequence_Tuple(result);
1552 Py_DECREF(result);
1553 if (tuple == NULL)
1554 return -1;
1555 if (checkit) {
1556 Py_ssize_t i, len;
1557 PyObject *cls;
1558 PyTypeObject *solid;
Armin Rigo037d1e02005-12-29 17:07:39 +00001559
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001560 solid = solid_base(type);
Armin Rigo037d1e02005-12-29 17:07:39 +00001561
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001562 len = PyTuple_GET_SIZE(tuple);
Armin Rigo037d1e02005-12-29 17:07:39 +00001563
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001564 for (i = 0; i < len; i++) {
1565 PyTypeObject *t;
1566 cls = PyTuple_GET_ITEM(tuple, i);
1567 if (!PyType_Check(cls)) {
1568 PyErr_Format(PyExc_TypeError,
1569 "mro() returned a non-class ('%.500s')",
1570 Py_TYPE(cls)->tp_name);
1571 Py_DECREF(tuple);
1572 return -1;
1573 }
1574 t = (PyTypeObject*)cls;
1575 if (!PyType_IsSubtype(solid, solid_base(t))) {
1576 PyErr_Format(PyExc_TypeError,
1577 "mro() returned base with unsuitable layout ('%.500s')",
1578 t->tp_name);
1579 Py_DECREF(tuple);
1580 return -1;
1581 }
1582 }
1583 }
1584 type->tp_mro = tuple;
Christian Heimesa62da1d2008-01-12 19:39:10 +00001585
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001586 type_mro_modified(type, type->tp_mro);
1587 /* corner case: the old-style super class might have been hidden
1588 from the custom MRO */
1589 type_mro_modified(type, type->tp_bases);
Christian Heimesa62da1d2008-01-12 19:39:10 +00001590
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001591 PyType_Modified(type);
Christian Heimesa62da1d2008-01-12 19:39:10 +00001592
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001593 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001594}
1595
1596
1597/* Calculate the best base amongst multiple base classes.
1598 This is the first one that's on the path to the "solid base". */
1599
1600static PyTypeObject *
1601best_base(PyObject *bases)
1602{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001603 Py_ssize_t i, n;
1604 PyTypeObject *base, *winner, *candidate, *base_i;
1605 PyObject *base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001606
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001607 assert(PyTuple_Check(bases));
1608 n = PyTuple_GET_SIZE(bases);
1609 assert(n > 0);
1610 base = NULL;
1611 winner = NULL;
1612 for (i = 0; i < n; i++) {
1613 base_proto = PyTuple_GET_ITEM(bases, i);
1614 if (!PyType_Check(base_proto)) {
1615 PyErr_SetString(
1616 PyExc_TypeError,
1617 "bases must be types");
1618 return NULL;
1619 }
1620 base_i = (PyTypeObject *)base_proto;
1621 if (base_i->tp_dict == NULL) {
1622 if (PyType_Ready(base_i) < 0)
1623 return NULL;
1624 }
1625 candidate = solid_base(base_i);
1626 if (winner == NULL) {
1627 winner = candidate;
1628 base = base_i;
1629 }
1630 else if (PyType_IsSubtype(winner, candidate))
1631 ;
1632 else if (PyType_IsSubtype(candidate, winner)) {
1633 winner = candidate;
1634 base = base_i;
1635 }
1636 else {
1637 PyErr_SetString(
1638 PyExc_TypeError,
1639 "multiple bases have "
1640 "instance lay-out conflict");
1641 return NULL;
1642 }
1643 }
1644 if (base == NULL)
1645 PyErr_SetString(PyExc_TypeError,
1646 "a new-style class can't have only classic bases");
1647 return base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001648}
1649
1650static int
1651extra_ivars(PyTypeObject *type, PyTypeObject *base)
1652{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001653 size_t t_size = type->tp_basicsize;
1654 size_t b_size = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001655
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001656 assert(t_size >= b_size); /* Else type smaller than base! */
1657 if (type->tp_itemsize || base->tp_itemsize) {
1658 /* If itemsize is involved, stricter rules */
1659 return t_size != b_size ||
1660 type->tp_itemsize != base->tp_itemsize;
1661 }
1662 if (type->tp_weaklistoffset && base->tp_weaklistoffset == 0 &&
1663 type->tp_weaklistoffset + sizeof(PyObject *) == t_size &&
1664 type->tp_flags & Py_TPFLAGS_HEAPTYPE)
1665 t_size -= sizeof(PyObject *);
1666 if (type->tp_dictoffset && base->tp_dictoffset == 0 &&
1667 type->tp_dictoffset + sizeof(PyObject *) == t_size &&
1668 type->tp_flags & Py_TPFLAGS_HEAPTYPE)
1669 t_size -= sizeof(PyObject *);
Guido van Rossum9676b222001-08-17 20:32:36 +00001670
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001671 return t_size != b_size;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001672}
1673
1674static PyTypeObject *
1675solid_base(PyTypeObject *type)
1676{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001677 PyTypeObject *base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001678
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001679 if (type->tp_base)
1680 base = solid_base(type->tp_base);
1681 else
1682 base = &PyBaseObject_Type;
1683 if (extra_ivars(type, base))
1684 return type;
1685 else
1686 return base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001687}
1688
Jeremy Hylton938ace62002-07-17 16:30:39 +00001689static void object_dealloc(PyObject *);
1690static int object_init(PyObject *, PyObject *, PyObject *);
1691static int update_slot(PyTypeObject *, PyObject *);
1692static void fixup_slot_dispatchers(PyTypeObject *);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001693
Guido van Rossum360e4b82007-05-14 22:51:27 +00001694/*
1695 * Helpers for __dict__ descriptor. We don't want to expose the dicts
1696 * inherited from various builtin types. The builtin base usually provides
1697 * its own __dict__ descriptor, so we use that when we can.
1698 */
1699static PyTypeObject *
1700get_builtin_base_with_dict(PyTypeObject *type)
1701{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001702 while (type->tp_base != NULL) {
1703 if (type->tp_dictoffset != 0 &&
1704 !(type->tp_flags & Py_TPFLAGS_HEAPTYPE))
1705 return type;
1706 type = type->tp_base;
1707 }
1708 return NULL;
Guido van Rossum360e4b82007-05-14 22:51:27 +00001709}
1710
1711static PyObject *
1712get_dict_descriptor(PyTypeObject *type)
1713{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001714 static PyObject *dict_str;
1715 PyObject *descr;
Guido van Rossum360e4b82007-05-14 22:51:27 +00001716
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001717 if (dict_str == NULL) {
1718 dict_str = PyUnicode_InternFromString("__dict__");
1719 if (dict_str == NULL)
1720 return NULL;
1721 }
1722 descr = _PyType_Lookup(type, dict_str);
1723 if (descr == NULL || !PyDescr_IsData(descr))
1724 return NULL;
Guido van Rossum360e4b82007-05-14 22:51:27 +00001725
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001726 return descr;
Guido van Rossum360e4b82007-05-14 22:51:27 +00001727}
1728
1729static void
1730raise_dict_descr_error(PyObject *obj)
1731{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001732 PyErr_Format(PyExc_TypeError,
1733 "this __dict__ descriptor does not support "
1734 "'%.200s' objects", Py_TYPE(obj)->tp_name);
Guido van Rossum360e4b82007-05-14 22:51:27 +00001735}
1736
Tim Peters6d6c1a32001-08-02 04:15:00 +00001737static PyObject *
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001738subtype_dict(PyObject *obj, void *context)
1739{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001740 PyObject **dictptr;
1741 PyObject *dict;
1742 PyTypeObject *base;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001743
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001744 base = get_builtin_base_with_dict(Py_TYPE(obj));
1745 if (base != NULL) {
1746 descrgetfunc func;
1747 PyObject *descr = get_dict_descriptor(base);
1748 if (descr == NULL) {
1749 raise_dict_descr_error(obj);
1750 return NULL;
1751 }
1752 func = Py_TYPE(descr)->tp_descr_get;
1753 if (func == NULL) {
1754 raise_dict_descr_error(obj);
1755 return NULL;
1756 }
1757 return func(descr, obj, (PyObject *)(Py_TYPE(obj)));
1758 }
Guido van Rossum360e4b82007-05-14 22:51:27 +00001759
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001760 dictptr = _PyObject_GetDictPtr(obj);
1761 if (dictptr == NULL) {
1762 PyErr_SetString(PyExc_AttributeError,
1763 "This object has no __dict__");
1764 return NULL;
1765 }
1766 dict = *dictptr;
1767 if (dict == NULL)
1768 *dictptr = dict = PyDict_New();
1769 Py_XINCREF(dict);
1770 return dict;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001771}
1772
Guido van Rossum6661be32001-10-26 04:26:12 +00001773static int
1774subtype_setdict(PyObject *obj, PyObject *value, void *context)
1775{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001776 PyObject **dictptr;
1777 PyObject *dict;
1778 PyTypeObject *base;
Guido van Rossum6661be32001-10-26 04:26:12 +00001779
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001780 base = get_builtin_base_with_dict(Py_TYPE(obj));
1781 if (base != NULL) {
1782 descrsetfunc func;
1783 PyObject *descr = get_dict_descriptor(base);
1784 if (descr == NULL) {
1785 raise_dict_descr_error(obj);
1786 return -1;
1787 }
1788 func = Py_TYPE(descr)->tp_descr_set;
1789 if (func == NULL) {
1790 raise_dict_descr_error(obj);
1791 return -1;
1792 }
1793 return func(descr, obj, value);
1794 }
Guido van Rossum360e4b82007-05-14 22:51:27 +00001795
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001796 dictptr = _PyObject_GetDictPtr(obj);
1797 if (dictptr == NULL) {
1798 PyErr_SetString(PyExc_AttributeError,
1799 "This object has no __dict__");
1800 return -1;
1801 }
1802 if (value != NULL && !PyDict_Check(value)) {
1803 PyErr_Format(PyExc_TypeError,
1804 "__dict__ must be set to a dictionary, "
1805 "not a '%.200s'", Py_TYPE(value)->tp_name);
1806 return -1;
1807 }
1808 dict = *dictptr;
1809 Py_XINCREF(value);
1810 *dictptr = value;
1811 Py_XDECREF(dict);
1812 return 0;
Guido van Rossum6661be32001-10-26 04:26:12 +00001813}
1814
Guido van Rossumad47da02002-08-12 19:05:44 +00001815static PyObject *
1816subtype_getweakref(PyObject *obj, void *context)
1817{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001818 PyObject **weaklistptr;
1819 PyObject *result;
Guido van Rossumad47da02002-08-12 19:05:44 +00001820
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001821 if (Py_TYPE(obj)->tp_weaklistoffset == 0) {
1822 PyErr_SetString(PyExc_AttributeError,
1823 "This object has no __weakref__");
1824 return NULL;
1825 }
1826 assert(Py_TYPE(obj)->tp_weaklistoffset > 0);
1827 assert(Py_TYPE(obj)->tp_weaklistoffset + sizeof(PyObject *) <=
1828 (size_t)(Py_TYPE(obj)->tp_basicsize));
1829 weaklistptr = (PyObject **)
1830 ((char *)obj + Py_TYPE(obj)->tp_weaklistoffset);
1831 if (*weaklistptr == NULL)
1832 result = Py_None;
1833 else
1834 result = *weaklistptr;
1835 Py_INCREF(result);
1836 return result;
Guido van Rossumad47da02002-08-12 19:05:44 +00001837}
1838
Guido van Rossum373c7412003-01-07 13:41:37 +00001839/* Three variants on the subtype_getsets list. */
1840
1841static PyGetSetDef subtype_getsets_full[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001842 {"__dict__", subtype_dict, subtype_setdict,
1843 PyDoc_STR("dictionary for instance variables (if defined)")},
1844 {"__weakref__", subtype_getweakref, NULL,
1845 PyDoc_STR("list of weak references to the object (if defined)")},
1846 {0}
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001847};
1848
Guido van Rossum373c7412003-01-07 13:41:37 +00001849static PyGetSetDef subtype_getsets_dict_only[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001850 {"__dict__", subtype_dict, subtype_setdict,
1851 PyDoc_STR("dictionary for instance variables (if defined)")},
1852 {0}
Guido van Rossum373c7412003-01-07 13:41:37 +00001853};
1854
1855static PyGetSetDef subtype_getsets_weakref_only[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001856 {"__weakref__", subtype_getweakref, NULL,
1857 PyDoc_STR("list of weak references to the object (if defined)")},
1858 {0}
Guido van Rossum373c7412003-01-07 13:41:37 +00001859};
1860
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001861static int
1862valid_identifier(PyObject *s)
1863{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001864 if (!PyUnicode_Check(s)) {
1865 PyErr_Format(PyExc_TypeError,
1866 "__slots__ items must be strings, not '%.200s'",
1867 Py_TYPE(s)->tp_name);
1868 return 0;
1869 }
1870 if (!PyUnicode_IsIdentifier(s)) {
1871 PyErr_SetString(PyExc_TypeError,
1872 "__slots__ must be identifiers");
1873 return 0;
1874 }
1875 return 1;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001876}
1877
Guido van Rossumd8faa362007-04-27 19:54:29 +00001878/* Forward */
1879static int
1880object_init(PyObject *self, PyObject *args, PyObject *kwds);
1881
1882static int
1883type_init(PyObject *cls, PyObject *args, PyObject *kwds)
1884{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001885 int res;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001886
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001887 assert(args != NULL && PyTuple_Check(args));
1888 assert(kwds == NULL || PyDict_Check(kwds));
Guido van Rossumd8faa362007-04-27 19:54:29 +00001889
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001890 if (kwds != NULL && PyDict_Check(kwds) && PyDict_Size(kwds) != 0) {
1891 PyErr_SetString(PyExc_TypeError,
1892 "type.__init__() takes no keyword arguments");
1893 return -1;
1894 }
Guido van Rossumd8faa362007-04-27 19:54:29 +00001895
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001896 if (args != NULL && PyTuple_Check(args) &&
1897 (PyTuple_GET_SIZE(args) != 1 && PyTuple_GET_SIZE(args) != 3)) {
1898 PyErr_SetString(PyExc_TypeError,
1899 "type.__init__() takes 1 or 3 arguments");
1900 return -1;
1901 }
Guido van Rossumd8faa362007-04-27 19:54:29 +00001902
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001903 /* Call object.__init__(self) now. */
1904 /* XXX Could call super(type, cls).__init__() but what's the point? */
1905 args = PyTuple_GetSlice(args, 0, 0);
1906 res = object_init(cls, args, NULL);
1907 Py_DECREF(args);
1908 return res;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001909}
1910
Martin v. Löwis738236d2011-02-05 20:35:29 +00001911long
1912PyType_GetFlags(PyTypeObject *type)
1913{
1914 return type->tp_flags;
1915}
1916
Nick Coghlande31b192011-10-23 22:04:16 +10001917/* Determine the most derived metatype. */
1918PyTypeObject *
1919_PyType_CalculateMetaclass(PyTypeObject *metatype, PyObject *bases)
1920{
1921 Py_ssize_t i, nbases;
1922 PyTypeObject *winner;
1923 PyObject *tmp;
1924 PyTypeObject *tmptype;
1925
1926 /* Determine the proper metatype to deal with this,
1927 and check for metatype conflicts while we're at it.
1928 Note that if some other metatype wins to contract,
1929 it's possible that its instances are not types. */
1930
1931 nbases = PyTuple_GET_SIZE(bases);
1932 winner = metatype;
1933 for (i = 0; i < nbases; i++) {
1934 tmp = PyTuple_GET_ITEM(bases, i);
1935 tmptype = Py_TYPE(tmp);
1936 if (PyType_IsSubtype(winner, tmptype))
1937 continue;
1938 if (PyType_IsSubtype(tmptype, winner)) {
1939 winner = tmptype;
1940 continue;
1941 }
1942 /* else: */
1943 PyErr_SetString(PyExc_TypeError,
1944 "metaclass conflict: "
1945 "the metaclass of a derived class "
1946 "must be a (non-strict) subclass "
1947 "of the metaclasses of all its bases");
1948 return NULL;
1949 }
1950 return winner;
1951}
1952
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001953static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00001954type_new(PyTypeObject *metatype, PyObject *args, PyObject *kwds)
1955{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001956 PyObject *name, *bases, *dict;
1957 static char *kwlist[] = {"name", "bases", "dict", 0};
1958 PyObject *slots, *tmp, *newslots;
1959 PyTypeObject *type, *base, *tmptype, *winner;
1960 PyHeapTypeObject *et;
1961 PyMemberDef *mp;
1962 Py_ssize_t i, nbases, nslots, slotoffset, add_dict, add_weak;
1963 int j, may_add_dict, may_add_weak;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001964
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001965 assert(args != NULL && PyTuple_Check(args));
1966 assert(kwds == NULL || PyDict_Check(kwds));
Tim Peters3abca122001-10-27 19:37:48 +00001967
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001968 /* Special case: type(x) should return x->ob_type */
1969 {
1970 const Py_ssize_t nargs = PyTuple_GET_SIZE(args);
1971 const Py_ssize_t nkwds = kwds == NULL ? 0 : PyDict_Size(kwds);
Tim Peters3abca122001-10-27 19:37:48 +00001972
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001973 if (PyType_CheckExact(metatype) && nargs == 1 && nkwds == 0) {
1974 PyObject *x = PyTuple_GET_ITEM(args, 0);
1975 Py_INCREF(Py_TYPE(x));
1976 return (PyObject *) Py_TYPE(x);
1977 }
Tim Peters3abca122001-10-27 19:37:48 +00001978
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001979 /* SF bug 475327 -- if that didn't trigger, we need 3
1980 arguments. but PyArg_ParseTupleAndKeywords below may give
1981 a msg saying type() needs exactly 3. */
1982 if (nargs + nkwds != 3) {
1983 PyErr_SetString(PyExc_TypeError,
1984 "type() takes 1 or 3 arguments");
1985 return NULL;
1986 }
1987 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001988
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001989 /* Check arguments: (name, bases, dict) */
1990 if (!PyArg_ParseTupleAndKeywords(args, kwds, "UO!O!:type", kwlist,
1991 &name,
1992 &PyTuple_Type, &bases,
1993 &PyDict_Type, &dict))
1994 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001995
Nick Coghlande31b192011-10-23 22:04:16 +10001996 /* Determine the proper metatype to deal with this: */
1997 winner = _PyType_CalculateMetaclass(metatype, bases);
1998 if (winner == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001999 return NULL;
2000 }
Nick Coghlande31b192011-10-23 22:04:16 +10002001
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002002 if (winner != metatype) {
2003 if (winner->tp_new != type_new) /* Pass it to the winner */
2004 return winner->tp_new(winner, args, kwds);
2005 metatype = winner;
2006 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002007
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002008 /* Adjust for empty tuple bases */
Nick Coghlande31b192011-10-23 22:04:16 +10002009 nbases = PyTuple_GET_SIZE(bases);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002010 if (nbases == 0) {
2011 bases = PyTuple_Pack(1, &PyBaseObject_Type);
2012 if (bases == NULL)
2013 return NULL;
2014 nbases = 1;
2015 }
2016 else
2017 Py_INCREF(bases);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002018
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002019 /* XXX From here until type is allocated, "return NULL" leaks bases! */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002020
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002021 /* Calculate best base, and check that all bases are type objects */
2022 base = best_base(bases);
2023 if (base == NULL) {
2024 Py_DECREF(bases);
2025 return NULL;
2026 }
2027 if (!PyType_HasFeature(base, Py_TPFLAGS_BASETYPE)) {
2028 PyErr_Format(PyExc_TypeError,
2029 "type '%.100s' is not an acceptable base type",
2030 base->tp_name);
2031 Py_DECREF(bases);
2032 return NULL;
2033 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002034
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002035 /* Check for a __slots__ sequence variable in dict, and count it */
2036 slots = PyDict_GetItemString(dict, "__slots__");
2037 nslots = 0;
2038 add_dict = 0;
2039 add_weak = 0;
2040 may_add_dict = base->tp_dictoffset == 0;
2041 may_add_weak = base->tp_weaklistoffset == 0 && base->tp_itemsize == 0;
2042 if (slots == NULL) {
2043 if (may_add_dict) {
2044 add_dict++;
2045 }
2046 if (may_add_weak) {
2047 add_weak++;
2048 }
2049 }
2050 else {
2051 /* Have slots */
Guido van Rossumad47da02002-08-12 19:05:44 +00002052
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002053 /* Make it into a tuple */
2054 if (PyUnicode_Check(slots))
2055 slots = PyTuple_Pack(1, slots);
2056 else
2057 slots = PySequence_Tuple(slots);
2058 if (slots == NULL) {
2059 Py_DECREF(bases);
2060 return NULL;
2061 }
2062 assert(PyTuple_Check(slots));
Guido van Rossumad47da02002-08-12 19:05:44 +00002063
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002064 /* Are slots allowed? */
2065 nslots = PyTuple_GET_SIZE(slots);
2066 if (nslots > 0 && base->tp_itemsize != 0) {
2067 PyErr_Format(PyExc_TypeError,
2068 "nonempty __slots__ "
2069 "not supported for subtype of '%s'",
2070 base->tp_name);
2071 bad_slots:
2072 Py_DECREF(bases);
2073 Py_DECREF(slots);
2074 return NULL;
2075 }
Guido van Rossumad47da02002-08-12 19:05:44 +00002076
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002077 /* Check for valid slot names and two special cases */
2078 for (i = 0; i < nslots; i++) {
2079 PyObject *tmp = PyTuple_GET_ITEM(slots, i);
2080 if (!valid_identifier(tmp))
2081 goto bad_slots;
2082 assert(PyUnicode_Check(tmp));
2083 if (PyUnicode_CompareWithASCIIString(tmp, "__dict__") == 0) {
2084 if (!may_add_dict || add_dict) {
2085 PyErr_SetString(PyExc_TypeError,
2086 "__dict__ slot disallowed: "
2087 "we already got one");
2088 goto bad_slots;
2089 }
2090 add_dict++;
2091 }
2092 if (PyUnicode_CompareWithASCIIString(tmp, "__weakref__") == 0) {
2093 if (!may_add_weak || add_weak) {
2094 PyErr_SetString(PyExc_TypeError,
2095 "__weakref__ slot disallowed: "
2096 "either we already got one, "
2097 "or __itemsize__ != 0");
2098 goto bad_slots;
2099 }
2100 add_weak++;
2101 }
2102 }
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00002103
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002104 /* Copy slots into a list, mangle names and sort them.
2105 Sorted names are needed for __class__ assignment.
2106 Convert them back to tuple at the end.
2107 */
2108 newslots = PyList_New(nslots - add_dict - add_weak);
2109 if (newslots == NULL)
2110 goto bad_slots;
2111 for (i = j = 0; i < nslots; i++) {
2112 tmp = PyTuple_GET_ITEM(slots, i);
2113 if ((add_dict &&
2114 PyUnicode_CompareWithASCIIString(tmp, "__dict__") == 0) ||
2115 (add_weak &&
2116 PyUnicode_CompareWithASCIIString(tmp, "__weakref__") == 0))
2117 continue;
2118 tmp =_Py_Mangle(name, tmp);
Benjamin Petersonae13c882011-08-16 22:26:48 -05002119 if (!tmp) {
2120 Py_DECREF(newslots);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002121 goto bad_slots;
Benjamin Petersonae13c882011-08-16 22:26:48 -05002122 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002123 PyList_SET_ITEM(newslots, j, tmp);
2124 j++;
2125 }
2126 assert(j == nslots - add_dict - add_weak);
2127 nslots = j;
2128 Py_DECREF(slots);
2129 if (PyList_Sort(newslots) == -1) {
2130 Py_DECREF(bases);
2131 Py_DECREF(newslots);
2132 return NULL;
2133 }
2134 slots = PyList_AsTuple(newslots);
2135 Py_DECREF(newslots);
2136 if (slots == NULL) {
2137 Py_DECREF(bases);
2138 return NULL;
2139 }
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00002140
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002141 /* Secondary bases may provide weakrefs or dict */
2142 if (nbases > 1 &&
2143 ((may_add_dict && !add_dict) ||
2144 (may_add_weak && !add_weak))) {
2145 for (i = 0; i < nbases; i++) {
2146 tmp = PyTuple_GET_ITEM(bases, i);
2147 if (tmp == (PyObject *)base)
2148 continue; /* Skip primary base */
2149 assert(PyType_Check(tmp));
2150 tmptype = (PyTypeObject *)tmp;
2151 if (may_add_dict && !add_dict &&
2152 tmptype->tp_dictoffset != 0)
2153 add_dict++;
2154 if (may_add_weak && !add_weak &&
2155 tmptype->tp_weaklistoffset != 0)
2156 add_weak++;
2157 if (may_add_dict && !add_dict)
2158 continue;
2159 if (may_add_weak && !add_weak)
2160 continue;
2161 /* Nothing more to check */
2162 break;
2163 }
2164 }
2165 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002166
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002167 /* XXX From here until type is safely allocated,
2168 "return NULL" may leak slots! */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002169
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002170 /* Allocate the type object */
2171 type = (PyTypeObject *)metatype->tp_alloc(metatype, nslots);
2172 if (type == NULL) {
2173 Py_XDECREF(slots);
2174 Py_DECREF(bases);
2175 return NULL;
2176 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002177
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002178 /* Keep name and slots alive in the extended type object */
2179 et = (PyHeapTypeObject *)type;
2180 Py_INCREF(name);
2181 et->ht_name = name;
2182 et->ht_slots = slots;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002183
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002184 /* Initialize tp_flags */
2185 type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE |
2186 Py_TPFLAGS_BASETYPE;
2187 if (base->tp_flags & Py_TPFLAGS_HAVE_GC)
2188 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossumdc91b992001-08-08 22:26:22 +00002189
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002190 /* Initialize essential fields */
2191 type->tp_as_number = &et->as_number;
2192 type->tp_as_sequence = &et->as_sequence;
2193 type->tp_as_mapping = &et->as_mapping;
2194 type->tp_as_buffer = &et->as_buffer;
2195 type->tp_name = _PyUnicode_AsString(name);
2196 if (!type->tp_name) {
2197 Py_DECREF(type);
2198 return NULL;
2199 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002200
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002201 /* Set tp_base and tp_bases */
2202 type->tp_bases = bases;
2203 Py_INCREF(base);
2204 type->tp_base = base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002205
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002206 /* Initialize tp_dict from passed-in dict */
2207 type->tp_dict = dict = PyDict_Copy(dict);
2208 if (dict == NULL) {
2209 Py_DECREF(type);
2210 return NULL;
2211 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002212
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002213 /* Set __module__ in the dict */
2214 if (PyDict_GetItemString(dict, "__module__") == NULL) {
2215 tmp = PyEval_GetGlobals();
2216 if (tmp != NULL) {
2217 tmp = PyDict_GetItemString(tmp, "__name__");
2218 if (tmp != NULL) {
2219 if (PyDict_SetItemString(dict, "__module__",
2220 tmp) < 0)
2221 return NULL;
2222 }
2223 }
2224 }
Guido van Rossumc3542212001-08-16 09:18:56 +00002225
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002226 /* Set tp_doc to a copy of dict['__doc__'], if the latter is there
2227 and is a string. The __doc__ accessor will first look for tp_doc;
2228 if that fails, it will still look into __dict__.
2229 */
2230 {
2231 PyObject *doc = PyDict_GetItemString(dict, "__doc__");
2232 if (doc != NULL && PyUnicode_Check(doc)) {
2233 Py_ssize_t len;
2234 char *doc_str;
2235 char *tp_doc;
Alexandre Vassalottia85998a2008-05-03 18:24:43 +00002236
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002237 doc_str = _PyUnicode_AsString(doc);
2238 if (doc_str == NULL) {
2239 Py_DECREF(type);
2240 return NULL;
2241 }
2242 /* Silently truncate the docstring if it contains null bytes. */
2243 len = strlen(doc_str);
2244 tp_doc = (char *)PyObject_MALLOC(len + 1);
2245 if (tp_doc == NULL) {
2246 Py_DECREF(type);
2247 return NULL;
2248 }
2249 memcpy(tp_doc, doc_str, len + 1);
2250 type->tp_doc = tp_doc;
2251 }
2252 }
Tim Peters2f93e282001-10-04 05:27:00 +00002253
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002254 /* Special-case __new__: if it's a plain function,
2255 make it a static function */
2256 tmp = PyDict_GetItemString(dict, "__new__");
2257 if (tmp != NULL && PyFunction_Check(tmp)) {
2258 tmp = PyStaticMethod_New(tmp);
2259 if (tmp == NULL) {
2260 Py_DECREF(type);
2261 return NULL;
2262 }
2263 PyDict_SetItemString(dict, "__new__", tmp);
2264 Py_DECREF(tmp);
2265 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002266
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002267 /* Add descriptors for custom slots from __slots__, or for __dict__ */
2268 mp = PyHeapType_GET_MEMBERS(et);
2269 slotoffset = base->tp_basicsize;
2270 if (slots != NULL) {
2271 for (i = 0; i < nslots; i++, mp++) {
2272 mp->name = _PyUnicode_AsString(
2273 PyTuple_GET_ITEM(slots, i));
Victor Stinnere5f99f32010-05-19 01:42:46 +00002274 if (mp->name == NULL) {
2275 Py_DECREF(type);
2276 return NULL;
2277 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002278 mp->type = T_OBJECT_EX;
2279 mp->offset = slotoffset;
Guido van Rossumd8faa362007-04-27 19:54:29 +00002280
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002281 /* __dict__ and __weakref__ are already filtered out */
2282 assert(strcmp(mp->name, "__dict__") != 0);
2283 assert(strcmp(mp->name, "__weakref__") != 0);
Guido van Rossumd8faa362007-04-27 19:54:29 +00002284
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002285 slotoffset += sizeof(PyObject *);
2286 }
2287 }
2288 if (add_dict) {
2289 if (base->tp_itemsize)
2290 type->tp_dictoffset = -(long)sizeof(PyObject *);
2291 else
2292 type->tp_dictoffset = slotoffset;
2293 slotoffset += sizeof(PyObject *);
2294 }
2295 if (add_weak) {
2296 assert(!base->tp_itemsize);
2297 type->tp_weaklistoffset = slotoffset;
2298 slotoffset += sizeof(PyObject *);
2299 }
2300 type->tp_basicsize = slotoffset;
2301 type->tp_itemsize = base->tp_itemsize;
2302 type->tp_members = PyHeapType_GET_MEMBERS(et);
Guido van Rossum373c7412003-01-07 13:41:37 +00002303
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002304 if (type->tp_weaklistoffset && type->tp_dictoffset)
2305 type->tp_getset = subtype_getsets_full;
2306 else if (type->tp_weaklistoffset && !type->tp_dictoffset)
2307 type->tp_getset = subtype_getsets_weakref_only;
2308 else if (!type->tp_weaklistoffset && type->tp_dictoffset)
2309 type->tp_getset = subtype_getsets_dict_only;
2310 else
2311 type->tp_getset = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002312
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002313 /* Special case some slots */
2314 if (type->tp_dictoffset != 0 || nslots > 0) {
2315 if (base->tp_getattr == NULL && base->tp_getattro == NULL)
2316 type->tp_getattro = PyObject_GenericGetAttr;
2317 if (base->tp_setattr == NULL && base->tp_setattro == NULL)
2318 type->tp_setattro = PyObject_GenericSetAttr;
2319 }
2320 type->tp_dealloc = subtype_dealloc;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002321
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002322 /* Enable GC unless there are really no instance variables possible */
2323 if (!(type->tp_basicsize == sizeof(PyObject) &&
2324 type->tp_itemsize == 0))
2325 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossum9475a232001-10-05 20:51:39 +00002326
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002327 /* Always override allocation strategy to use regular heap */
2328 type->tp_alloc = PyType_GenericAlloc;
2329 if (type->tp_flags & Py_TPFLAGS_HAVE_GC) {
2330 type->tp_free = PyObject_GC_Del;
2331 type->tp_traverse = subtype_traverse;
2332 type->tp_clear = subtype_clear;
2333 }
2334 else
2335 type->tp_free = PyObject_Del;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002336
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002337 /* Initialize the rest */
2338 if (PyType_Ready(type) < 0) {
2339 Py_DECREF(type);
2340 return NULL;
2341 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002342
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002343 /* Put the proper slots in place */
2344 fixup_slot_dispatchers(type);
Guido van Rossumf040ede2001-08-07 16:40:56 +00002345
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002346 return (PyObject *)type;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002347}
2348
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002349static short slotoffsets[] = {
2350 -1, /* invalid slot */
2351#include "typeslots.inc"
2352};
2353
Benjamin Petersone28108c2012-01-29 20:13:18 -05002354PyObject *
2355PyType_FromSpec(PyType_Spec *spec)
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002356{
2357 PyHeapTypeObject *res = (PyHeapTypeObject*)PyType_GenericAlloc(&PyType_Type, 0);
2358 char *res_start = (char*)res;
2359 PyType_Slot *slot;
2360
Martin v. Löwis7be5b782011-02-21 16:26:47 +00002361 if (res == NULL)
2362 return NULL;
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002363 res->ht_name = PyUnicode_FromString(spec->name);
2364 if (!res->ht_name)
Antoine Pitroua1433fe2012-05-14 14:43:25 +02002365 goto fail;
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002366 res->ht_type.tp_name = _PyUnicode_AsString(res->ht_name);
2367 if (!res->ht_type.tp_name)
Antoine Pitroua1433fe2012-05-14 14:43:25 +02002368 goto fail;
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002369
2370 res->ht_type.tp_basicsize = spec->basicsize;
2371 res->ht_type.tp_itemsize = spec->itemsize;
2372 res->ht_type.tp_flags = spec->flags | Py_TPFLAGS_HEAPTYPE;
Victor Stinner0fcab4a2011-01-04 12:59:15 +00002373
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002374 for (slot = spec->slots; slot->slot; slot++) {
Antoine Pitroua1433fe2012-05-14 14:43:25 +02002375 if (slot->slot >= sizeof(slotoffsets)/sizeof(slotoffsets[0])) {
2376 PyErr_SetString(PyExc_RuntimeError, "invalid slot offset");
2377 goto fail;
2378 }
2379 *(void**)(res_start + slotoffsets[slot->slot]) = slot->pfunc;
Georg Brandl032400b2011-02-19 21:47:02 +00002380
2381 /* need to make a copy of the docstring slot, which usually
2382 points to a static string literal */
2383 if (slot->slot == Py_tp_doc) {
Antoine Pitrou682d94c2012-05-14 14:43:03 +02002384 size_t len = strlen(slot->pfunc)+1;
Georg Brandl032400b2011-02-19 21:47:02 +00002385 char *tp_doc = PyObject_MALLOC(len);
2386 if (tp_doc == NULL)
Antoine Pitroua1433fe2012-05-14 14:43:25 +02002387 goto fail;
Georg Brandl032400b2011-02-19 21:47:02 +00002388 memcpy(tp_doc, slot->pfunc, len);
2389 res->ht_type.tp_doc = tp_doc;
2390 }
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002391 }
Antoine Pitrou99cc6292012-06-23 14:42:38 +02002392 if (res->ht_type.tp_dealloc == NULL) {
2393 /* It's a heap type, so needs the heap types' dealloc.
2394 subtype_dealloc will call the base type's tp_dealloc, if
2395 necessary. */
2396 res->ht_type.tp_dealloc = subtype_dealloc;
2397 }
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002398
Benjamin Peterson2652d252012-01-29 20:16:37 -05002399 if (PyType_Ready(&res->ht_type) < 0)
2400 goto fail;
2401
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002402 return (PyObject*)res;
Victor Stinner0fcab4a2011-01-04 12:59:15 +00002403
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002404 fail:
2405 Py_DECREF(res);
2406 return NULL;
2407}
2408
2409
Tim Peters6d6c1a32001-08-02 04:15:00 +00002410/* Internal API to look for a name through the MRO.
2411 This returns a borrowed reference, and doesn't set an exception! */
2412PyObject *
2413_PyType_Lookup(PyTypeObject *type, PyObject *name)
2414{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002415 Py_ssize_t i, n;
2416 PyObject *mro, *res, *base, *dict;
2417 unsigned int h;
Christian Heimesa62da1d2008-01-12 19:39:10 +00002418
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002419 if (MCACHE_CACHEABLE_NAME(name) &&
2420 PyType_HasFeature(type, Py_TPFLAGS_VALID_VERSION_TAG)) {
2421 /* fast path */
2422 h = MCACHE_HASH_METHOD(type, name);
2423 if (method_cache[h].version == type->tp_version_tag &&
2424 method_cache[h].name == name)
2425 return method_cache[h].value;
2426 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002427
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002428 /* Look in tp_dict of types in MRO */
2429 mro = type->tp_mro;
Guido van Rossum23094982002-06-10 14:30:43 +00002430
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002431 /* If mro is NULL, the type is either not yet initialized
2432 by PyType_Ready(), or already cleared by type_clear().
2433 Either way the safest thing to do is to return NULL. */
2434 if (mro == NULL)
2435 return NULL;
Guido van Rossum23094982002-06-10 14:30:43 +00002436
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002437 res = NULL;
2438 assert(PyTuple_Check(mro));
2439 n = PyTuple_GET_SIZE(mro);
2440 for (i = 0; i < n; i++) {
2441 base = PyTuple_GET_ITEM(mro, i);
2442 assert(PyType_Check(base));
2443 dict = ((PyTypeObject *)base)->tp_dict;
2444 assert(dict && PyDict_Check(dict));
2445 res = PyDict_GetItem(dict, name);
2446 if (res != NULL)
2447 break;
2448 }
Christian Heimesa62da1d2008-01-12 19:39:10 +00002449
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002450 if (MCACHE_CACHEABLE_NAME(name) && assign_version_tag(type)) {
2451 h = MCACHE_HASH_METHOD(type, name);
2452 method_cache[h].version = type->tp_version_tag;
2453 method_cache[h].value = res; /* borrowed */
2454 Py_INCREF(name);
2455 Py_DECREF(method_cache[h].name);
2456 method_cache[h].name = name;
2457 }
2458 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002459}
2460
2461/* This is similar to PyObject_GenericGetAttr(),
2462 but uses _PyType_Lookup() instead of just looking in type->tp_dict. */
2463static PyObject *
2464type_getattro(PyTypeObject *type, PyObject *name)
2465{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002466 PyTypeObject *metatype = Py_TYPE(type);
2467 PyObject *meta_attribute, *attribute;
2468 descrgetfunc meta_get;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002469
Benjamin Peterson16d84ac2012-03-16 09:32:59 -05002470 if (!PyUnicode_Check(name)) {
2471 PyErr_Format(PyExc_TypeError,
2472 "attribute name must be string, not '%.200s'",
2473 name->ob_type->tp_name);
2474 return NULL;
2475 }
2476
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002477 /* Initialize this type (we'll assume the metatype is initialized) */
2478 if (type->tp_dict == NULL) {
2479 if (PyType_Ready(type) < 0)
2480 return NULL;
2481 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002482
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002483 /* No readable descriptor found yet */
2484 meta_get = NULL;
Tim Peters34592512002-07-11 06:23:50 +00002485
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002486 /* Look for the attribute in the metatype */
2487 meta_attribute = _PyType_Lookup(metatype, name);
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002488
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002489 if (meta_attribute != NULL) {
2490 meta_get = Py_TYPE(meta_attribute)->tp_descr_get;
Tim Peters34592512002-07-11 06:23:50 +00002491
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002492 if (meta_get != NULL && PyDescr_IsData(meta_attribute)) {
2493 /* Data descriptors implement tp_descr_set to intercept
2494 * writes. Assume the attribute is not overridden in
2495 * type's tp_dict (and bases): call the descriptor now.
2496 */
2497 return meta_get(meta_attribute, (PyObject *)type,
2498 (PyObject *)metatype);
2499 }
2500 Py_INCREF(meta_attribute);
2501 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002502
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002503 /* No data descriptor found on metatype. Look in tp_dict of this
2504 * type and its bases */
2505 attribute = _PyType_Lookup(type, name);
2506 if (attribute != NULL) {
2507 /* Implement descriptor functionality, if any */
2508 descrgetfunc local_get = Py_TYPE(attribute)->tp_descr_get;
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00002509
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002510 Py_XDECREF(meta_attribute);
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00002511
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002512 if (local_get != NULL) {
2513 /* NULL 2nd argument indicates the descriptor was
2514 * found on the target object itself (or a base) */
2515 return local_get(attribute, (PyObject *)NULL,
2516 (PyObject *)type);
2517 }
Tim Peters34592512002-07-11 06:23:50 +00002518
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002519 Py_INCREF(attribute);
2520 return attribute;
2521 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002522
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002523 /* No attribute found in local __dict__ (or bases): use the
2524 * descriptor from the metatype, if any */
2525 if (meta_get != NULL) {
2526 PyObject *res;
2527 res = meta_get(meta_attribute, (PyObject *)type,
2528 (PyObject *)metatype);
2529 Py_DECREF(meta_attribute);
2530 return res;
2531 }
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002532
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002533 /* If an ordinary attribute was found on the metatype, return it now */
2534 if (meta_attribute != NULL) {
2535 return meta_attribute;
2536 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002537
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002538 /* Give up */
2539 PyErr_Format(PyExc_AttributeError,
2540 "type object '%.50s' has no attribute '%U'",
2541 type->tp_name, name);
2542 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002543}
2544
2545static int
2546type_setattro(PyTypeObject *type, PyObject *name, PyObject *value)
2547{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002548 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
2549 PyErr_Format(
2550 PyExc_TypeError,
2551 "can't set attributes of built-in/extension type '%s'",
2552 type->tp_name);
2553 return -1;
2554 }
2555 if (PyObject_GenericSetAttr((PyObject *)type, name, value) < 0)
2556 return -1;
2557 return update_slot(type, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002558}
2559
2560static void
2561type_dealloc(PyTypeObject *type)
2562{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002563 PyHeapTypeObject *et;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002564
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002565 /* Assert this is a heap-allocated type object */
2566 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
2567 _PyObject_GC_UNTRACK(type);
2568 PyObject_ClearWeakRefs((PyObject *)type);
2569 et = (PyHeapTypeObject *)type;
2570 Py_XDECREF(type->tp_base);
2571 Py_XDECREF(type->tp_dict);
2572 Py_XDECREF(type->tp_bases);
2573 Py_XDECREF(type->tp_mro);
2574 Py_XDECREF(type->tp_cache);
2575 Py_XDECREF(type->tp_subclasses);
2576 /* A type's tp_doc is heap allocated, unlike the tp_doc slots
2577 * of most other objects. It's okay to cast it to char *.
2578 */
2579 PyObject_Free((char *)type->tp_doc);
2580 Py_XDECREF(et->ht_name);
2581 Py_XDECREF(et->ht_slots);
2582 Py_TYPE(type)->tp_free((PyObject *)type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002583}
2584
Guido van Rossum1c450732001-10-08 15:18:27 +00002585static PyObject *
2586type_subclasses(PyTypeObject *type, PyObject *args_ignored)
2587{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002588 PyObject *list, *raw, *ref;
2589 Py_ssize_t i, n;
Guido van Rossum1c450732001-10-08 15:18:27 +00002590
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002591 list = PyList_New(0);
2592 if (list == NULL)
2593 return NULL;
2594 raw = type->tp_subclasses;
2595 if (raw == NULL)
2596 return list;
2597 assert(PyList_Check(raw));
2598 n = PyList_GET_SIZE(raw);
2599 for (i = 0; i < n; i++) {
2600 ref = PyList_GET_ITEM(raw, i);
2601 assert(PyWeakref_CheckRef(ref));
2602 ref = PyWeakref_GET_OBJECT(ref);
2603 if (ref != Py_None) {
2604 if (PyList_Append(list, ref) < 0) {
2605 Py_DECREF(list);
2606 return NULL;
2607 }
2608 }
2609 }
2610 return list;
Guido van Rossum1c450732001-10-08 15:18:27 +00002611}
2612
Guido van Rossum47374822007-08-02 16:48:17 +00002613static PyObject *
2614type_prepare(PyObject *self, PyObject *args, PyObject *kwds)
2615{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002616 return PyDict_New();
Guido van Rossum47374822007-08-02 16:48:17 +00002617}
2618
Tim Peters6d6c1a32001-08-02 04:15:00 +00002619static PyMethodDef type_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002620 {"mro", (PyCFunction)mro_external, METH_NOARGS,
2621 PyDoc_STR("mro() -> list\nreturn a type's method resolution order")},
2622 {"__subclasses__", (PyCFunction)type_subclasses, METH_NOARGS,
2623 PyDoc_STR("__subclasses__() -> list of immediate subclasses")},
2624 {"__prepare__", (PyCFunction)type_prepare,
2625 METH_VARARGS | METH_KEYWORDS | METH_CLASS,
2626 PyDoc_STR("__prepare__() -> dict\n"
2627 "used to create the namespace for the class statement")},
2628 {"__instancecheck__", type___instancecheck__, METH_O,
Benjamin Petersonfbe56bb2011-05-24 12:42:51 -05002629 PyDoc_STR("__instancecheck__() -> bool\ncheck if an object is an instance")},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002630 {"__subclasscheck__", type___subclasscheck__, METH_O,
Benjamin Petersonfbe56bb2011-05-24 12:42:51 -05002631 PyDoc_STR("__subclasscheck__() -> bool\ncheck if a class is a subclass")},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002632 {0}
Tim Peters6d6c1a32001-08-02 04:15:00 +00002633};
2634
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002635PyDoc_STRVAR(type_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00002636"type(object) -> the object's type\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002637"type(name, bases, dict) -> a new type");
Tim Peters6d6c1a32001-08-02 04:15:00 +00002638
Guido van Rossum048eb752001-10-02 21:24:57 +00002639static int
2640type_traverse(PyTypeObject *type, visitproc visit, void *arg)
2641{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002642 /* Because of type_is_gc(), the collector only calls this
2643 for heaptypes. */
2644 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002645
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002646 Py_VISIT(type->tp_dict);
2647 Py_VISIT(type->tp_cache);
2648 Py_VISIT(type->tp_mro);
2649 Py_VISIT(type->tp_bases);
2650 Py_VISIT(type->tp_base);
Guido van Rossuma3862092002-06-10 15:24:42 +00002651
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002652 /* There's no need to visit type->tp_subclasses or
2653 ((PyHeapTypeObject *)type)->ht_slots, because they can't be involved
2654 in cycles; tp_subclasses is a list of weak references,
2655 and slots is a tuple of strings. */
Guido van Rossum048eb752001-10-02 21:24:57 +00002656
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002657 return 0;
Guido van Rossum048eb752001-10-02 21:24:57 +00002658}
2659
2660static int
2661type_clear(PyTypeObject *type)
2662{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002663 /* Because of type_is_gc(), the collector only calls this
2664 for heaptypes. */
2665 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002666
Antoine Pitrou2e872082011-12-15 14:15:31 +01002667 /* We need to invalidate the method cache carefully before clearing
2668 the dict, so that other objects caught in a reference cycle
2669 don't start calling destroyed methods.
2670
2671 Otherwise, the only field we need to clear is tp_mro, which is
2672 part of a hard cycle (its first element is the class itself) that
2673 won't be broken otherwise (it's a tuple and tuples don't have a
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002674 tp_clear handler). None of the other fields need to be
2675 cleared, and here's why:
Guido van Rossum048eb752001-10-02 21:24:57 +00002676
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002677 tp_cache:
2678 Not used; if it were, it would be a dict.
Guido van Rossuma3862092002-06-10 15:24:42 +00002679
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002680 tp_bases, tp_base:
2681 If these are involved in a cycle, there must be at least
2682 one other, mutable object in the cycle, e.g. a base
2683 class's dict; the cycle will be broken that way.
Guido van Rossuma3862092002-06-10 15:24:42 +00002684
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002685 tp_subclasses:
2686 A list of weak references can't be part of a cycle; and
2687 lists have their own tp_clear.
Guido van Rossuma3862092002-06-10 15:24:42 +00002688
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002689 slots (in PyHeapTypeObject):
2690 A tuple of strings can't be part of a cycle.
2691 */
Guido van Rossuma3862092002-06-10 15:24:42 +00002692
Antoine Pitrou2e872082011-12-15 14:15:31 +01002693 PyType_Modified(type);
2694 if (type->tp_dict)
2695 PyDict_Clear(type->tp_dict);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002696 Py_CLEAR(type->tp_mro);
Guido van Rossum048eb752001-10-02 21:24:57 +00002697
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002698 return 0;
Guido van Rossum048eb752001-10-02 21:24:57 +00002699}
2700
2701static int
2702type_is_gc(PyTypeObject *type)
2703{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002704 return type->tp_flags & Py_TPFLAGS_HEAPTYPE;
Guido van Rossum048eb752001-10-02 21:24:57 +00002705}
2706
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002707PyTypeObject PyType_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002708 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2709 "type", /* tp_name */
2710 sizeof(PyHeapTypeObject), /* tp_basicsize */
2711 sizeof(PyMemberDef), /* tp_itemsize */
2712 (destructor)type_dealloc, /* tp_dealloc */
2713 0, /* tp_print */
2714 0, /* tp_getattr */
2715 0, /* tp_setattr */
2716 0, /* tp_reserved */
2717 (reprfunc)type_repr, /* tp_repr */
2718 0, /* tp_as_number */
2719 0, /* tp_as_sequence */
2720 0, /* tp_as_mapping */
2721 0, /* tp_hash */
2722 (ternaryfunc)type_call, /* tp_call */
2723 0, /* tp_str */
2724 (getattrofunc)type_getattro, /* tp_getattro */
2725 (setattrofunc)type_setattro, /* tp_setattro */
2726 0, /* tp_as_buffer */
2727 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
2728 Py_TPFLAGS_BASETYPE | Py_TPFLAGS_TYPE_SUBCLASS, /* tp_flags */
2729 type_doc, /* tp_doc */
2730 (traverseproc)type_traverse, /* tp_traverse */
2731 (inquiry)type_clear, /* tp_clear */
2732 0, /* tp_richcompare */
2733 offsetof(PyTypeObject, tp_weaklist), /* tp_weaklistoffset */
2734 0, /* tp_iter */
2735 0, /* tp_iternext */
2736 type_methods, /* tp_methods */
2737 type_members, /* tp_members */
2738 type_getsets, /* tp_getset */
2739 0, /* tp_base */
2740 0, /* tp_dict */
2741 0, /* tp_descr_get */
2742 0, /* tp_descr_set */
2743 offsetof(PyTypeObject, tp_dict), /* tp_dictoffset */
2744 type_init, /* tp_init */
2745 0, /* tp_alloc */
2746 type_new, /* tp_new */
2747 PyObject_GC_Del, /* tp_free */
2748 (inquiry)type_is_gc, /* tp_is_gc */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002749};
Tim Peters6d6c1a32001-08-02 04:15:00 +00002750
2751
2752/* The base type of all types (eventually)... except itself. */
2753
Guido van Rossumd8faa362007-04-27 19:54:29 +00002754/* You may wonder why object.__new__() only complains about arguments
2755 when object.__init__() is not overridden, and vice versa.
2756
2757 Consider the use cases:
2758
2759 1. When neither is overridden, we want to hear complaints about
2760 excess (i.e., any) arguments, since their presence could
2761 indicate there's a bug.
2762
2763 2. When defining an Immutable type, we are likely to override only
2764 __new__(), since __init__() is called too late to initialize an
2765 Immutable object. Since __new__() defines the signature for the
2766 type, it would be a pain to have to override __init__() just to
2767 stop it from complaining about excess arguments.
2768
2769 3. When defining a Mutable type, we are likely to override only
2770 __init__(). So here the converse reasoning applies: we don't
2771 want to have to override __new__() just to stop it from
2772 complaining.
2773
2774 4. When __init__() is overridden, and the subclass __init__() calls
2775 object.__init__(), the latter should complain about excess
2776 arguments; ditto for __new__().
2777
2778 Use cases 2 and 3 make it unattractive to unconditionally check for
2779 excess arguments. The best solution that addresses all four use
2780 cases is as follows: __init__() complains about excess arguments
2781 unless __new__() is overridden and __init__() is not overridden
2782 (IOW, if __init__() is overridden or __new__() is not overridden);
2783 symmetrically, __new__() complains about excess arguments unless
2784 __init__() is overridden and __new__() is not overridden
2785 (IOW, if __new__() is overridden or __init__() is not overridden).
2786
2787 However, for backwards compatibility, this breaks too much code.
2788 Therefore, in 2.6, we'll *warn* about excess arguments when both
2789 methods are overridden; for all other cases we'll use the above
2790 rules.
2791
2792*/
2793
2794/* Forward */
2795static PyObject *
2796object_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
2797
2798static int
2799excess_args(PyObject *args, PyObject *kwds)
2800{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002801 return PyTuple_GET_SIZE(args) ||
2802 (kwds && PyDict_Check(kwds) && PyDict_Size(kwds));
Guido van Rossumd8faa362007-04-27 19:54:29 +00002803}
2804
Tim Peters6d6c1a32001-08-02 04:15:00 +00002805static int
2806object_init(PyObject *self, PyObject *args, PyObject *kwds)
2807{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002808 int err = 0;
2809 if (excess_args(args, kwds)) {
2810 PyTypeObject *type = Py_TYPE(self);
2811 if (type->tp_init != object_init &&
2812 type->tp_new != object_new)
2813 {
2814 err = PyErr_WarnEx(PyExc_DeprecationWarning,
2815 "object.__init__() takes no parameters",
2816 1);
2817 }
2818 else if (type->tp_init != object_init ||
2819 type->tp_new == object_new)
2820 {
2821 PyErr_SetString(PyExc_TypeError,
2822 "object.__init__() takes no parameters");
2823 err = -1;
2824 }
2825 }
2826 return err;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002827}
2828
Guido van Rossum298e4212003-02-13 16:30:16 +00002829static PyObject *
2830object_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2831{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002832 int err = 0;
2833 if (excess_args(args, kwds)) {
2834 if (type->tp_new != object_new &&
2835 type->tp_init != object_init)
2836 {
2837 err = PyErr_WarnEx(PyExc_DeprecationWarning,
2838 "object.__new__() takes no parameters",
2839 1);
2840 }
2841 else if (type->tp_new != object_new ||
2842 type->tp_init == object_init)
2843 {
2844 PyErr_SetString(PyExc_TypeError,
2845 "object.__new__() takes no parameters");
2846 err = -1;
2847 }
2848 }
2849 if (err < 0)
2850 return NULL;
Christian Heimes9e7f1d22008-02-28 12:27:11 +00002851
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002852 if (type->tp_flags & Py_TPFLAGS_IS_ABSTRACT) {
2853 static PyObject *comma = NULL;
2854 PyObject *abstract_methods = NULL;
2855 PyObject *builtins;
2856 PyObject *sorted;
2857 PyObject *sorted_methods = NULL;
2858 PyObject *joined = NULL;
Christian Heimes9e7f1d22008-02-28 12:27:11 +00002859
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002860 /* Compute ", ".join(sorted(type.__abstractmethods__))
2861 into joined. */
2862 abstract_methods = type_abstractmethods(type, NULL);
2863 if (abstract_methods == NULL)
2864 goto error;
2865 builtins = PyEval_GetBuiltins();
2866 if (builtins == NULL)
2867 goto error;
2868 sorted = PyDict_GetItemString(builtins, "sorted");
2869 if (sorted == NULL)
2870 goto error;
2871 sorted_methods = PyObject_CallFunctionObjArgs(sorted,
2872 abstract_methods,
2873 NULL);
2874 if (sorted_methods == NULL)
2875 goto error;
2876 if (comma == NULL) {
2877 comma = PyUnicode_InternFromString(", ");
2878 if (comma == NULL)
2879 goto error;
2880 }
2881 joined = PyObject_CallMethod(comma, "join",
2882 "O", sorted_methods);
2883 if (joined == NULL)
2884 goto error;
Christian Heimes9e7f1d22008-02-28 12:27:11 +00002885
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002886 PyErr_Format(PyExc_TypeError,
2887 "Can't instantiate abstract class %s "
2888 "with abstract methods %U",
2889 type->tp_name,
2890 joined);
2891 error:
2892 Py_XDECREF(joined);
2893 Py_XDECREF(sorted_methods);
2894 Py_XDECREF(abstract_methods);
2895 return NULL;
2896 }
2897 return type->tp_alloc(type, 0);
Guido van Rossum298e4212003-02-13 16:30:16 +00002898}
2899
Tim Peters6d6c1a32001-08-02 04:15:00 +00002900static void
2901object_dealloc(PyObject *self)
2902{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002903 Py_TYPE(self)->tp_free(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002904}
2905
Guido van Rossum8e248182001-08-12 05:17:56 +00002906static PyObject *
2907object_repr(PyObject *self)
2908{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002909 PyTypeObject *type;
2910 PyObject *mod, *name, *rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00002911
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002912 type = Py_TYPE(self);
2913 mod = type_module(type, NULL);
2914 if (mod == NULL)
2915 PyErr_Clear();
2916 else if (!PyUnicode_Check(mod)) {
2917 Py_DECREF(mod);
2918 mod = NULL;
2919 }
2920 name = type_name(type, NULL);
2921 if (name == NULL)
2922 return NULL;
2923 if (mod != NULL && PyUnicode_CompareWithASCIIString(mod, "builtins"))
2924 rtn = PyUnicode_FromFormat("<%U.%U object at %p>", mod, name, self);
2925 else
2926 rtn = PyUnicode_FromFormat("<%s object at %p>",
2927 type->tp_name, self);
2928 Py_XDECREF(mod);
2929 Py_DECREF(name);
2930 return rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00002931}
2932
Guido van Rossumb8f63662001-08-15 23:57:02 +00002933static PyObject *
2934object_str(PyObject *self)
2935{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002936 unaryfunc f;
Guido van Rossumb8f63662001-08-15 23:57:02 +00002937
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002938 f = Py_TYPE(self)->tp_repr;
Benjamin Peterson7b166872012-04-24 11:06:25 -04002939 if (f == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002940 f = object_repr;
2941 return f(self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002942}
2943
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002944static PyObject *
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002945object_richcompare(PyObject *self, PyObject *other, int op)
2946{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002947 PyObject *res;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002948
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002949 switch (op) {
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002950
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002951 case Py_EQ:
2952 /* Return NotImplemented instead of False, so if two
2953 objects are compared, both get a chance at the
2954 comparison. See issue #1393. */
2955 res = (self == other) ? Py_True : Py_NotImplemented;
2956 Py_INCREF(res);
2957 break;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002958
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002959 case Py_NE:
2960 /* By default, != returns the opposite of ==,
2961 unless the latter returns NotImplemented. */
2962 res = PyObject_RichCompare(self, other, Py_EQ);
2963 if (res != NULL && res != Py_NotImplemented) {
2964 int ok = PyObject_IsTrue(res);
2965 Py_DECREF(res);
2966 if (ok < 0)
2967 res = NULL;
2968 else {
2969 if (ok)
2970 res = Py_False;
2971 else
2972 res = Py_True;
2973 Py_INCREF(res);
2974 }
2975 }
2976 break;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002977
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002978 default:
2979 res = Py_NotImplemented;
2980 Py_INCREF(res);
2981 break;
2982 }
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002983
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002984 return res;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002985}
2986
2987static PyObject *
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002988object_get_class(PyObject *self, void *closure)
2989{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002990 Py_INCREF(Py_TYPE(self));
2991 return (PyObject *)(Py_TYPE(self));
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002992}
2993
2994static int
2995equiv_structs(PyTypeObject *a, PyTypeObject *b)
2996{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002997 return a == b ||
2998 (a != NULL &&
2999 b != NULL &&
3000 a->tp_basicsize == b->tp_basicsize &&
3001 a->tp_itemsize == b->tp_itemsize &&
3002 a->tp_dictoffset == b->tp_dictoffset &&
3003 a->tp_weaklistoffset == b->tp_weaklistoffset &&
3004 ((a->tp_flags & Py_TPFLAGS_HAVE_GC) ==
3005 (b->tp_flags & Py_TPFLAGS_HAVE_GC)));
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003006}
3007
3008static int
3009same_slots_added(PyTypeObject *a, PyTypeObject *b)
3010{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003011 PyTypeObject *base = a->tp_base;
3012 Py_ssize_t size;
3013 PyObject *slots_a, *slots_b;
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003014
Benjamin Peterson67641d22011-01-17 19:24:34 +00003015 assert(base == b->tp_base);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003016 size = base->tp_basicsize;
3017 if (a->tp_dictoffset == size && b->tp_dictoffset == size)
3018 size += sizeof(PyObject *);
3019 if (a->tp_weaklistoffset == size && b->tp_weaklistoffset == size)
3020 size += sizeof(PyObject *);
Guido van Rossumd8faa362007-04-27 19:54:29 +00003021
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003022 /* Check slots compliance */
3023 slots_a = ((PyHeapTypeObject *)a)->ht_slots;
3024 slots_b = ((PyHeapTypeObject *)b)->ht_slots;
3025 if (slots_a && slots_b) {
3026 if (PyObject_RichCompareBool(slots_a, slots_b, Py_EQ) != 1)
3027 return 0;
3028 size += sizeof(PyObject *) * PyTuple_GET_SIZE(slots_a);
3029 }
3030 return size == a->tp_basicsize && size == b->tp_basicsize;
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003031}
3032
3033static int
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003034compatible_for_assignment(PyTypeObject* oldto, PyTypeObject* newto, char* attr)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003035{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003036 PyTypeObject *newbase, *oldbase;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003037
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003038 if (newto->tp_dealloc != oldto->tp_dealloc ||
3039 newto->tp_free != oldto->tp_free)
3040 {
3041 PyErr_Format(PyExc_TypeError,
3042 "%s assignment: "
3043 "'%s' deallocator differs from '%s'",
3044 attr,
3045 newto->tp_name,
3046 oldto->tp_name);
3047 return 0;
3048 }
3049 newbase = newto;
3050 oldbase = oldto;
3051 while (equiv_structs(newbase, newbase->tp_base))
3052 newbase = newbase->tp_base;
3053 while (equiv_structs(oldbase, oldbase->tp_base))
3054 oldbase = oldbase->tp_base;
3055 if (newbase != oldbase &&
3056 (newbase->tp_base != oldbase->tp_base ||
3057 !same_slots_added(newbase, oldbase))) {
3058 PyErr_Format(PyExc_TypeError,
3059 "%s assignment: "
3060 "'%s' object layout differs from '%s'",
3061 attr,
3062 newto->tp_name,
3063 oldto->tp_name);
3064 return 0;
3065 }
Tim Petersea7f75d2002-12-07 21:39:16 +00003066
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003067 return 1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003068}
3069
3070static int
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003071object_set_class(PyObject *self, PyObject *value, void *closure)
3072{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003073 PyTypeObject *oldto = Py_TYPE(self);
3074 PyTypeObject *newto;
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003075
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003076 if (value == NULL) {
3077 PyErr_SetString(PyExc_TypeError,
3078 "can't delete __class__ attribute");
3079 return -1;
3080 }
3081 if (!PyType_Check(value)) {
3082 PyErr_Format(PyExc_TypeError,
3083 "__class__ must be set to new-style class, not '%s' object",
3084 Py_TYPE(value)->tp_name);
3085 return -1;
3086 }
3087 newto = (PyTypeObject *)value;
3088 if (!(newto->tp_flags & Py_TPFLAGS_HEAPTYPE) ||
3089 !(oldto->tp_flags & Py_TPFLAGS_HEAPTYPE))
3090 {
3091 PyErr_Format(PyExc_TypeError,
3092 "__class__ assignment: only for heap types");
3093 return -1;
3094 }
3095 if (compatible_for_assignment(newto, oldto, "__class__")) {
3096 Py_INCREF(newto);
3097 Py_TYPE(self) = newto;
3098 Py_DECREF(oldto);
3099 return 0;
3100 }
3101 else {
3102 return -1;
3103 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003104}
3105
3106static PyGetSetDef object_getsets[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003107 {"__class__", object_get_class, object_set_class,
3108 PyDoc_STR("the object's class")},
3109 {0}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003110};
3111
Guido van Rossumc53f0092003-02-18 22:05:12 +00003112
Guido van Rossum036f9992003-02-21 22:02:54 +00003113/* Stuff to implement __reduce_ex__ for pickle protocols >= 2.
Alexandre Vassalottif7fa63d2008-05-11 08:55:36 +00003114 We fall back to helpers in copyreg for:
Guido van Rossum036f9992003-02-21 22:02:54 +00003115 - pickle protocols < 2
3116 - calculating the list of slot names (done only once per class)
3117 - the __newobj__ function (which is used as a token but never called)
3118*/
3119
3120static PyObject *
Alexandre Vassalottif7fa63d2008-05-11 08:55:36 +00003121import_copyreg(void)
Guido van Rossum036f9992003-02-21 22:02:54 +00003122{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003123 static PyObject *copyreg_str;
Guido van Rossum3926a632001-09-25 16:25:58 +00003124
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003125 if (!copyreg_str) {
3126 copyreg_str = PyUnicode_InternFromString("copyreg");
3127 if (copyreg_str == NULL)
3128 return NULL;
3129 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003130
Antoine Pitrouff150f22010-10-22 21:41:05 +00003131 return PyImport_Import(copyreg_str);
Guido van Rossum036f9992003-02-21 22:02:54 +00003132}
3133
3134static PyObject *
3135slotnames(PyObject *cls)
3136{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003137 PyObject *clsdict;
3138 PyObject *copyreg;
3139 PyObject *slotnames;
Guido van Rossum036f9992003-02-21 22:02:54 +00003140
Antoine Pitrouff150f22010-10-22 21:41:05 +00003141 if (!PyType_Check(cls)) {
3142 Py_INCREF(Py_None);
3143 return Py_None;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003144 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003145
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003146 clsdict = ((PyTypeObject *)cls)->tp_dict;
Antoine Pitrouff150f22010-10-22 21:41:05 +00003147 slotnames = PyDict_GetItemString(clsdict, "__slotnames__");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003148 if (slotnames != NULL && PyList_Check(slotnames)) {
3149 Py_INCREF(slotnames);
3150 return slotnames;
3151 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003152
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003153 copyreg = import_copyreg();
3154 if (copyreg == NULL)
3155 return NULL;
Guido van Rossum036f9992003-02-21 22:02:54 +00003156
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003157 slotnames = PyObject_CallMethod(copyreg, "_slotnames", "O", cls);
3158 Py_DECREF(copyreg);
3159 if (slotnames != NULL &&
3160 slotnames != Py_None &&
3161 !PyList_Check(slotnames))
3162 {
3163 PyErr_SetString(PyExc_TypeError,
3164 "copyreg._slotnames didn't return a list or None");
3165 Py_DECREF(slotnames);
3166 slotnames = NULL;
3167 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003168
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003169 return slotnames;
Guido van Rossum036f9992003-02-21 22:02:54 +00003170}
3171
3172static PyObject *
3173reduce_2(PyObject *obj)
3174{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003175 PyObject *cls, *getnewargs;
3176 PyObject *args = NULL, *args2 = NULL;
3177 PyObject *getstate = NULL, *state = NULL, *names = NULL;
3178 PyObject *slots = NULL, *listitems = NULL, *dictitems = NULL;
3179 PyObject *copyreg = NULL, *newobj = NULL, *res = NULL;
3180 Py_ssize_t i, n;
Guido van Rossum036f9992003-02-21 22:02:54 +00003181
Antoine Pitrouff150f22010-10-22 21:41:05 +00003182 cls = PyObject_GetAttrString(obj, "__class__");
3183 if (cls == NULL)
3184 return NULL;
Guido van Rossum036f9992003-02-21 22:02:54 +00003185
Antoine Pitrouff150f22010-10-22 21:41:05 +00003186 getnewargs = PyObject_GetAttrString(obj, "__getnewargs__");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003187 if (getnewargs != NULL) {
3188 args = PyObject_CallObject(getnewargs, NULL);
3189 Py_DECREF(getnewargs);
3190 if (args != NULL && !PyTuple_Check(args)) {
3191 PyErr_Format(PyExc_TypeError,
3192 "__getnewargs__ should return a tuple, "
3193 "not '%.200s'", Py_TYPE(args)->tp_name);
3194 goto end;
3195 }
3196 }
3197 else {
3198 PyErr_Clear();
3199 args = PyTuple_New(0);
3200 }
3201 if (args == NULL)
3202 goto end;
Guido van Rossum036f9992003-02-21 22:02:54 +00003203
Antoine Pitrouff150f22010-10-22 21:41:05 +00003204 getstate = PyObject_GetAttrString(obj, "__getstate__");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003205 if (getstate != NULL) {
3206 state = PyObject_CallObject(getstate, NULL);
3207 Py_DECREF(getstate);
3208 if (state == NULL)
3209 goto end;
3210 }
3211 else {
3212 PyErr_Clear();
Antoine Pitrouff150f22010-10-22 21:41:05 +00003213 state = PyObject_GetAttrString(obj, "__dict__");
3214 if (state == NULL) {
3215 PyErr_Clear();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003216 state = Py_None;
Antoine Pitrouff150f22010-10-22 21:41:05 +00003217 Py_INCREF(state);
3218 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003219 names = slotnames(cls);
3220 if (names == NULL)
3221 goto end;
Antoine Pitrouff150f22010-10-22 21:41:05 +00003222 if (names != Py_None) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003223 assert(PyList_Check(names));
3224 slots = PyDict_New();
3225 if (slots == NULL)
3226 goto end;
3227 n = 0;
3228 /* Can't pre-compute the list size; the list
3229 is stored on the class so accessible to other
3230 threads, which may be run by DECREF */
3231 for (i = 0; i < PyList_GET_SIZE(names); i++) {
3232 PyObject *name, *value;
3233 name = PyList_GET_ITEM(names, i);
3234 value = PyObject_GetAttr(obj, name);
3235 if (value == NULL)
3236 PyErr_Clear();
3237 else {
3238 int err = PyDict_SetItem(slots, name,
3239 value);
3240 Py_DECREF(value);
3241 if (err)
3242 goto end;
3243 n++;
3244 }
3245 }
3246 if (n) {
3247 state = Py_BuildValue("(NO)", state, slots);
3248 if (state == NULL)
3249 goto end;
3250 }
3251 }
3252 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003253
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003254 if (!PyList_Check(obj)) {
3255 listitems = Py_None;
3256 Py_INCREF(listitems);
3257 }
3258 else {
3259 listitems = PyObject_GetIter(obj);
3260 if (listitems == NULL)
3261 goto end;
3262 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003263
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003264 if (!PyDict_Check(obj)) {
3265 dictitems = Py_None;
3266 Py_INCREF(dictitems);
3267 }
3268 else {
3269 PyObject *items = PyObject_CallMethod(obj, "items", "");
3270 if (items == NULL)
3271 goto end;
3272 dictitems = PyObject_GetIter(items);
3273 Py_DECREF(items);
3274 if (dictitems == NULL)
3275 goto end;
3276 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003277
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003278 copyreg = import_copyreg();
3279 if (copyreg == NULL)
3280 goto end;
Antoine Pitrouff150f22010-10-22 21:41:05 +00003281 newobj = PyObject_GetAttrString(copyreg, "__newobj__");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003282 if (newobj == NULL)
3283 goto end;
Guido van Rossum036f9992003-02-21 22:02:54 +00003284
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003285 n = PyTuple_GET_SIZE(args);
3286 args2 = PyTuple_New(n+1);
3287 if (args2 == NULL)
3288 goto end;
3289 PyTuple_SET_ITEM(args2, 0, cls);
Antoine Pitrouff150f22010-10-22 21:41:05 +00003290 cls = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003291 for (i = 0; i < n; i++) {
3292 PyObject *v = PyTuple_GET_ITEM(args, i);
3293 Py_INCREF(v);
3294 PyTuple_SET_ITEM(args2, i+1, v);
3295 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003296
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003297 res = PyTuple_Pack(5, newobj, args2, state, listitems, dictitems);
Guido van Rossum036f9992003-02-21 22:02:54 +00003298
3299 end:
Antoine Pitrouff150f22010-10-22 21:41:05 +00003300 Py_XDECREF(cls);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003301 Py_XDECREF(args);
3302 Py_XDECREF(args2);
3303 Py_XDECREF(slots);
3304 Py_XDECREF(state);
3305 Py_XDECREF(names);
3306 Py_XDECREF(listitems);
3307 Py_XDECREF(dictitems);
3308 Py_XDECREF(copyreg);
3309 Py_XDECREF(newobj);
3310 return res;
Guido van Rossum036f9992003-02-21 22:02:54 +00003311}
3312
Guido van Rossumd8faa362007-04-27 19:54:29 +00003313/*
3314 * There were two problems when object.__reduce__ and object.__reduce_ex__
3315 * were implemented in the same function:
3316 * - trying to pickle an object with a custom __reduce__ method that
3317 * fell back to object.__reduce__ in certain circumstances led to
3318 * infinite recursion at Python level and eventual RuntimeError.
3319 * - Pickling objects that lied about their type by overwriting the
3320 * __class__ descriptor could lead to infinite recursion at C level
3321 * and eventual segfault.
3322 *
3323 * Because of backwards compatibility, the two methods still have to
3324 * behave in the same way, even if this is not required by the pickle
3325 * protocol. This common functionality was moved to the _common_reduce
3326 * function.
3327 */
3328static PyObject *
3329_common_reduce(PyObject *self, int proto)
3330{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003331 PyObject *copyreg, *res;
Guido van Rossumd8faa362007-04-27 19:54:29 +00003332
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003333 if (proto >= 2)
3334 return reduce_2(self);
Guido van Rossumd8faa362007-04-27 19:54:29 +00003335
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003336 copyreg = import_copyreg();
3337 if (!copyreg)
3338 return NULL;
Guido van Rossumd8faa362007-04-27 19:54:29 +00003339
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003340 res = PyEval_CallMethod(copyreg, "_reduce_ex", "(Oi)", self, proto);
3341 Py_DECREF(copyreg);
Guido van Rossumd8faa362007-04-27 19:54:29 +00003342
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003343 return res;
Guido van Rossumd8faa362007-04-27 19:54:29 +00003344}
3345
3346static PyObject *
3347object_reduce(PyObject *self, PyObject *args)
3348{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003349 int proto = 0;
Guido van Rossumd8faa362007-04-27 19:54:29 +00003350
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003351 if (!PyArg_ParseTuple(args, "|i:__reduce__", &proto))
3352 return NULL;
Guido van Rossumd8faa362007-04-27 19:54:29 +00003353
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003354 return _common_reduce(self, proto);
Guido van Rossumd8faa362007-04-27 19:54:29 +00003355}
3356
Guido van Rossum036f9992003-02-21 22:02:54 +00003357static PyObject *
3358object_reduce_ex(PyObject *self, PyObject *args)
3359{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003360 PyObject *reduce, *res;
3361 int proto = 0;
Guido van Rossum036f9992003-02-21 22:02:54 +00003362
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003363 if (!PyArg_ParseTuple(args, "|i:__reduce_ex__", &proto))
3364 return NULL;
Guido van Rossum036f9992003-02-21 22:02:54 +00003365
Antoine Pitrouff150f22010-10-22 21:41:05 +00003366 reduce = PyObject_GetAttrString(self, "__reduce__");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003367 if (reduce == NULL)
3368 PyErr_Clear();
3369 else {
Antoine Pitrouff150f22010-10-22 21:41:05 +00003370 PyObject *cls, *clsreduce, *objreduce;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003371 int override;
Antoine Pitrouff150f22010-10-22 21:41:05 +00003372 cls = PyObject_GetAttrString(self, "__class__");
3373 if (cls == NULL) {
3374 Py_DECREF(reduce);
3375 return NULL;
3376 }
3377 clsreduce = PyObject_GetAttrString(cls, "__reduce__");
3378 Py_DECREF(cls);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003379 if (clsreduce == NULL) {
3380 Py_DECREF(reduce);
3381 return NULL;
3382 }
Antoine Pitrouff150f22010-10-22 21:41:05 +00003383 objreduce = PyDict_GetItemString(PyBaseObject_Type.tp_dict,
3384 "__reduce__");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003385 override = (clsreduce != objreduce);
3386 Py_DECREF(clsreduce);
3387 if (override) {
3388 res = PyObject_CallObject(reduce, NULL);
3389 Py_DECREF(reduce);
3390 return res;
3391 }
3392 else
3393 Py_DECREF(reduce);
3394 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003395
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003396 return _common_reduce(self, proto);
Guido van Rossum3926a632001-09-25 16:25:58 +00003397}
3398
Christian Heimes9e7f1d22008-02-28 12:27:11 +00003399static PyObject *
3400object_subclasshook(PyObject *cls, PyObject *args)
3401{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003402 Py_INCREF(Py_NotImplemented);
3403 return Py_NotImplemented;
Christian Heimes9e7f1d22008-02-28 12:27:11 +00003404}
3405
3406PyDoc_STRVAR(object_subclasshook_doc,
3407"Abstract classes can override this to customize issubclass().\n"
3408"\n"
3409"This is invoked early on by abc.ABCMeta.__subclasscheck__().\n"
3410"It should return True, False or NotImplemented. If it returns\n"
3411"NotImplemented, the normal algorithm is used. Otherwise, it\n"
3412"overrides the normal algorithm (and the outcome is cached).\n");
Eric Smith8c663262007-08-25 02:26:07 +00003413
3414/*
3415 from PEP 3101, this code implements:
3416
3417 class object:
3418 def __format__(self, format_spec):
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003419 return format(str(self), format_spec)
Eric Smith8c663262007-08-25 02:26:07 +00003420*/
3421static PyObject *
3422object_format(PyObject *self, PyObject *args)
3423{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003424 PyObject *format_spec;
3425 PyObject *self_as_str = NULL;
3426 PyObject *result = NULL;
Eric Smith8c663262007-08-25 02:26:07 +00003427
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003428 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
3429 return NULL;
Eric Smith8c663262007-08-25 02:26:07 +00003430
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003431 self_as_str = PyObject_Str(self);
Eric Smithe4d63172010-09-13 20:48:43 +00003432 if (self_as_str != NULL) {
3433 /* Issue 7994: If we're converting to a string, we
3434 should reject format specifications */
3435 if (PyUnicode_GET_SIZE(format_spec) > 0) {
3436 if (PyErr_WarnEx(PyExc_PendingDeprecationWarning,
3437 "object.__format__ with a non-empty format "
3438 "string is deprecated", 1) < 0) {
3439 goto done;
3440 }
3441 /* Eventually this will become an error:
3442 PyErr_Format(PyExc_TypeError,
3443 "non-empty format string passed to object.__format__");
3444 goto done;
3445 */
3446 }
Eric Smith8c663262007-08-25 02:26:07 +00003447
Eric Smithe4d63172010-09-13 20:48:43 +00003448 result = PyObject_Format(self_as_str, format_spec);
3449 }
3450
3451done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003452 Py_XDECREF(self_as_str);
Eric Smith8c663262007-08-25 02:26:07 +00003453
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003454 return result;
Eric Smith8c663262007-08-25 02:26:07 +00003455}
3456
Martin v. Löwis00709aa2008-06-04 14:18:43 +00003457static PyObject *
3458object_sizeof(PyObject *self, PyObject *args)
3459{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003460 Py_ssize_t res, isize;
Martin v. Löwis00709aa2008-06-04 14:18:43 +00003461
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003462 res = 0;
3463 isize = self->ob_type->tp_itemsize;
3464 if (isize > 0)
3465 res = Py_SIZE(self->ob_type) * isize;
3466 res += self->ob_type->tp_basicsize;
Martin v. Löwis00709aa2008-06-04 14:18:43 +00003467
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003468 return PyLong_FromSsize_t(res);
Martin v. Löwis00709aa2008-06-04 14:18:43 +00003469}
3470
Guido van Rossum3926a632001-09-25 16:25:58 +00003471static PyMethodDef object_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003472 {"__reduce_ex__", object_reduce_ex, METH_VARARGS,
3473 PyDoc_STR("helper for pickle")},
3474 {"__reduce__", object_reduce, METH_VARARGS,
3475 PyDoc_STR("helper for pickle")},
3476 {"__subclasshook__", object_subclasshook, METH_CLASS | METH_VARARGS,
3477 object_subclasshook_doc},
3478 {"__format__", object_format, METH_VARARGS,
3479 PyDoc_STR("default object formatter")},
3480 {"__sizeof__", object_sizeof, METH_NOARGS,
Benjamin Petersonfbe56bb2011-05-24 12:42:51 -05003481 PyDoc_STR("__sizeof__() -> int\nsize of object in memory, in bytes")},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003482 {0}
Guido van Rossum3926a632001-09-25 16:25:58 +00003483};
3484
Guido van Rossum036f9992003-02-21 22:02:54 +00003485
Tim Peters6d6c1a32001-08-02 04:15:00 +00003486PyTypeObject PyBaseObject_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003487 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3488 "object", /* tp_name */
3489 sizeof(PyObject), /* tp_basicsize */
3490 0, /* tp_itemsize */
3491 object_dealloc, /* tp_dealloc */
3492 0, /* tp_print */
3493 0, /* tp_getattr */
3494 0, /* tp_setattr */
3495 0, /* tp_reserved */
3496 object_repr, /* tp_repr */
3497 0, /* tp_as_number */
3498 0, /* tp_as_sequence */
3499 0, /* tp_as_mapping */
3500 (hashfunc)_Py_HashPointer, /* tp_hash */
3501 0, /* tp_call */
3502 object_str, /* tp_str */
3503 PyObject_GenericGetAttr, /* tp_getattro */
3504 PyObject_GenericSetAttr, /* tp_setattro */
3505 0, /* tp_as_buffer */
3506 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
3507 PyDoc_STR("The most base type"), /* tp_doc */
3508 0, /* tp_traverse */
3509 0, /* tp_clear */
3510 object_richcompare, /* tp_richcompare */
3511 0, /* tp_weaklistoffset */
3512 0, /* tp_iter */
3513 0, /* tp_iternext */
3514 object_methods, /* tp_methods */
3515 0, /* tp_members */
3516 object_getsets, /* tp_getset */
3517 0, /* tp_base */
3518 0, /* tp_dict */
3519 0, /* tp_descr_get */
3520 0, /* tp_descr_set */
3521 0, /* tp_dictoffset */
3522 object_init, /* tp_init */
3523 PyType_GenericAlloc, /* tp_alloc */
3524 object_new, /* tp_new */
3525 PyObject_Del, /* tp_free */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003526};
3527
3528
Guido van Rossum50e9fb92006-08-17 05:42:55 +00003529/* Add the methods from tp_methods to the __dict__ in a type object */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003530
3531static int
3532add_methods(PyTypeObject *type, PyMethodDef *meth)
3533{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003534 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003535
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003536 for (; meth->ml_name != NULL; meth++) {
3537 PyObject *descr;
Benjamin Peterson89a6e9a2012-05-08 09:22:24 -04003538 int err;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003539 if (PyDict_GetItemString(dict, meth->ml_name) &&
3540 !(meth->ml_flags & METH_COEXIST))
3541 continue;
3542 if (meth->ml_flags & METH_CLASS) {
3543 if (meth->ml_flags & METH_STATIC) {
3544 PyErr_SetString(PyExc_ValueError,
3545 "method cannot be both class and static");
3546 return -1;
3547 }
3548 descr = PyDescr_NewClassMethod(type, meth);
3549 }
3550 else if (meth->ml_flags & METH_STATIC) {
3551 PyObject *cfunc = PyCFunction_New(meth, NULL);
3552 if (cfunc == NULL)
3553 return -1;
3554 descr = PyStaticMethod_New(cfunc);
3555 Py_DECREF(cfunc);
3556 }
3557 else {
3558 descr = PyDescr_NewMethod(type, meth);
3559 }
3560 if (descr == NULL)
3561 return -1;
Benjamin Peterson89a6e9a2012-05-08 09:22:24 -04003562 err = PyDict_SetItemString(dict, meth->ml_name, descr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003563 Py_DECREF(descr);
Benjamin Peterson89a6e9a2012-05-08 09:22:24 -04003564 if (err < 0)
3565 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003566 }
3567 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003568}
3569
3570static int
Guido van Rossum6f799372001-09-20 20:46:19 +00003571add_members(PyTypeObject *type, PyMemberDef *memb)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003572{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003573 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003574
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003575 for (; memb->name != NULL; memb++) {
3576 PyObject *descr;
3577 if (PyDict_GetItemString(dict, memb->name))
3578 continue;
3579 descr = PyDescr_NewMember(type, memb);
3580 if (descr == NULL)
3581 return -1;
3582 if (PyDict_SetItemString(dict, memb->name, descr) < 0)
3583 return -1;
3584 Py_DECREF(descr);
3585 }
3586 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003587}
3588
3589static int
Guido van Rossum32d34c82001-09-20 21:45:26 +00003590add_getset(PyTypeObject *type, PyGetSetDef *gsp)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003591{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003592 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003593
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003594 for (; gsp->name != NULL; gsp++) {
3595 PyObject *descr;
3596 if (PyDict_GetItemString(dict, gsp->name))
3597 continue;
3598 descr = PyDescr_NewGetSet(type, gsp);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003599
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003600 if (descr == NULL)
3601 return -1;
3602 if (PyDict_SetItemString(dict, gsp->name, descr) < 0)
3603 return -1;
3604 Py_DECREF(descr);
3605 }
3606 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003607}
3608
Guido van Rossum13d52f02001-08-10 21:24:08 +00003609static void
3610inherit_special(PyTypeObject *type, PyTypeObject *base)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003611{
Tim Peters6d6c1a32001-08-02 04:15:00 +00003612
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003613 /* Copying basicsize is connected to the GC flags */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003614 if (!(type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
3615 (base->tp_flags & Py_TPFLAGS_HAVE_GC) &&
3616 (!type->tp_traverse && !type->tp_clear)) {
3617 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
3618 if (type->tp_traverse == NULL)
3619 type->tp_traverse = base->tp_traverse;
3620 if (type->tp_clear == NULL)
3621 type->tp_clear = base->tp_clear;
3622 }
3623 {
3624 /* The condition below could use some explanation.
3625 It appears that tp_new is not inherited for static types
3626 whose base class is 'object'; this seems to be a precaution
3627 so that old extension types don't suddenly become
3628 callable (object.__new__ wouldn't insure the invariants
3629 that the extension type's own factory function ensures).
3630 Heap types, of course, are under our control, so they do
3631 inherit tp_new; static extension types that specify some
3632 other built-in type as the default are considered
3633 new-style-aware so they also inherit object.__new__. */
3634 if (base != &PyBaseObject_Type ||
3635 (type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
3636 if (type->tp_new == NULL)
3637 type->tp_new = base->tp_new;
3638 }
3639 }
Benjamin Petersona7465e22010-07-05 15:01:22 +00003640 if (type->tp_basicsize == 0)
3641 type->tp_basicsize = base->tp_basicsize;
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00003642
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003643 /* Copy other non-function slots */
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00003644
3645#undef COPYVAL
3646#define COPYVAL(SLOT) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003647 if (type->SLOT == 0) type->SLOT = base->SLOT
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00003648
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003649 COPYVAL(tp_itemsize);
3650 COPYVAL(tp_weaklistoffset);
3651 COPYVAL(tp_dictoffset);
Thomas Wouters27d517b2007-02-25 20:39:11 +00003652
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003653 /* Setup fast subclass flags */
3654 if (PyType_IsSubtype(base, (PyTypeObject*)PyExc_BaseException))
3655 type->tp_flags |= Py_TPFLAGS_BASE_EXC_SUBCLASS;
3656 else if (PyType_IsSubtype(base, &PyType_Type))
3657 type->tp_flags |= Py_TPFLAGS_TYPE_SUBCLASS;
3658 else if (PyType_IsSubtype(base, &PyLong_Type))
3659 type->tp_flags |= Py_TPFLAGS_LONG_SUBCLASS;
3660 else if (PyType_IsSubtype(base, &PyBytes_Type))
3661 type->tp_flags |= Py_TPFLAGS_BYTES_SUBCLASS;
3662 else if (PyType_IsSubtype(base, &PyUnicode_Type))
3663 type->tp_flags |= Py_TPFLAGS_UNICODE_SUBCLASS;
3664 else if (PyType_IsSubtype(base, &PyTuple_Type))
3665 type->tp_flags |= Py_TPFLAGS_TUPLE_SUBCLASS;
3666 else if (PyType_IsSubtype(base, &PyList_Type))
3667 type->tp_flags |= Py_TPFLAGS_LIST_SUBCLASS;
3668 else if (PyType_IsSubtype(base, &PyDict_Type))
3669 type->tp_flags |= Py_TPFLAGS_DICT_SUBCLASS;
Guido van Rossum13d52f02001-08-10 21:24:08 +00003670}
3671
Guido van Rossumf5243f02008-01-01 04:06:48 +00003672static char *hash_name_op[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003673 "__eq__",
3674 "__hash__",
3675 NULL
Guido van Rossum38938152006-08-21 23:36:26 +00003676};
3677
3678static int
Guido van Rossumf5243f02008-01-01 04:06:48 +00003679overrides_hash(PyTypeObject *type)
Guido van Rossum38938152006-08-21 23:36:26 +00003680{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003681 char **p;
3682 PyObject *dict = type->tp_dict;
Guido van Rossum38938152006-08-21 23:36:26 +00003683
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003684 assert(dict != NULL);
3685 for (p = hash_name_op; *p; p++) {
3686 if (PyDict_GetItemString(dict, *p) != NULL)
3687 return 1;
3688 }
3689 return 0;
Guido van Rossum38938152006-08-21 23:36:26 +00003690}
3691
Guido van Rossum13d52f02001-08-10 21:24:08 +00003692static void
3693inherit_slots(PyTypeObject *type, PyTypeObject *base)
3694{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003695 PyTypeObject *basebase;
Guido van Rossum13d52f02001-08-10 21:24:08 +00003696
3697#undef SLOTDEFINED
Tim Peters6d6c1a32001-08-02 04:15:00 +00003698#undef COPYSLOT
3699#undef COPYNUM
3700#undef COPYSEQ
3701#undef COPYMAP
Guido van Rossum5af588b2001-10-12 14:13:21 +00003702#undef COPYBUF
Guido van Rossum13d52f02001-08-10 21:24:08 +00003703
3704#define SLOTDEFINED(SLOT) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003705 (base->SLOT != 0 && \
3706 (basebase == NULL || base->SLOT != basebase->SLOT))
Guido van Rossum13d52f02001-08-10 21:24:08 +00003707
Tim Peters6d6c1a32001-08-02 04:15:00 +00003708#define COPYSLOT(SLOT) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003709 if (!type->SLOT && SLOTDEFINED(SLOT)) type->SLOT = base->SLOT
Tim Peters6d6c1a32001-08-02 04:15:00 +00003710
3711#define COPYNUM(SLOT) COPYSLOT(tp_as_number->SLOT)
3712#define COPYSEQ(SLOT) COPYSLOT(tp_as_sequence->SLOT)
3713#define COPYMAP(SLOT) COPYSLOT(tp_as_mapping->SLOT)
Tim Petersfc57ccb2001-10-12 02:38:24 +00003714#define COPYBUF(SLOT) COPYSLOT(tp_as_buffer->SLOT)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003715
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003716 /* This won't inherit indirect slots (from tp_as_number etc.)
3717 if type doesn't provide the space. */
Guido van Rossum13d52f02001-08-10 21:24:08 +00003718
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003719 if (type->tp_as_number != NULL && base->tp_as_number != NULL) {
3720 basebase = base->tp_base;
3721 if (basebase->tp_as_number == NULL)
3722 basebase = NULL;
3723 COPYNUM(nb_add);
3724 COPYNUM(nb_subtract);
3725 COPYNUM(nb_multiply);
3726 COPYNUM(nb_remainder);
3727 COPYNUM(nb_divmod);
3728 COPYNUM(nb_power);
3729 COPYNUM(nb_negative);
3730 COPYNUM(nb_positive);
3731 COPYNUM(nb_absolute);
3732 COPYNUM(nb_bool);
3733 COPYNUM(nb_invert);
3734 COPYNUM(nb_lshift);
3735 COPYNUM(nb_rshift);
3736 COPYNUM(nb_and);
3737 COPYNUM(nb_xor);
3738 COPYNUM(nb_or);
3739 COPYNUM(nb_int);
3740 COPYNUM(nb_float);
3741 COPYNUM(nb_inplace_add);
3742 COPYNUM(nb_inplace_subtract);
3743 COPYNUM(nb_inplace_multiply);
3744 COPYNUM(nb_inplace_remainder);
3745 COPYNUM(nb_inplace_power);
3746 COPYNUM(nb_inplace_lshift);
3747 COPYNUM(nb_inplace_rshift);
3748 COPYNUM(nb_inplace_and);
3749 COPYNUM(nb_inplace_xor);
3750 COPYNUM(nb_inplace_or);
3751 COPYNUM(nb_true_divide);
3752 COPYNUM(nb_floor_divide);
3753 COPYNUM(nb_inplace_true_divide);
3754 COPYNUM(nb_inplace_floor_divide);
3755 COPYNUM(nb_index);
3756 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003757
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003758 if (type->tp_as_sequence != NULL && base->tp_as_sequence != NULL) {
3759 basebase = base->tp_base;
3760 if (basebase->tp_as_sequence == NULL)
3761 basebase = NULL;
3762 COPYSEQ(sq_length);
3763 COPYSEQ(sq_concat);
3764 COPYSEQ(sq_repeat);
3765 COPYSEQ(sq_item);
3766 COPYSEQ(sq_ass_item);
3767 COPYSEQ(sq_contains);
3768 COPYSEQ(sq_inplace_concat);
3769 COPYSEQ(sq_inplace_repeat);
3770 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003771
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003772 if (type->tp_as_mapping != NULL && base->tp_as_mapping != NULL) {
3773 basebase = base->tp_base;
3774 if (basebase->tp_as_mapping == NULL)
3775 basebase = NULL;
3776 COPYMAP(mp_length);
3777 COPYMAP(mp_subscript);
3778 COPYMAP(mp_ass_subscript);
3779 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003780
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003781 if (type->tp_as_buffer != NULL && base->tp_as_buffer != NULL) {
3782 basebase = base->tp_base;
3783 if (basebase->tp_as_buffer == NULL)
3784 basebase = NULL;
3785 COPYBUF(bf_getbuffer);
3786 COPYBUF(bf_releasebuffer);
3787 }
Tim Petersfc57ccb2001-10-12 02:38:24 +00003788
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003789 basebase = base->tp_base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003790
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003791 COPYSLOT(tp_dealloc);
3792 if (type->tp_getattr == NULL && type->tp_getattro == NULL) {
3793 type->tp_getattr = base->tp_getattr;
3794 type->tp_getattro = base->tp_getattro;
3795 }
3796 if (type->tp_setattr == NULL && type->tp_setattro == NULL) {
3797 type->tp_setattr = base->tp_setattr;
3798 type->tp_setattro = base->tp_setattro;
3799 }
3800 /* tp_reserved is ignored */
3801 COPYSLOT(tp_repr);
3802 /* tp_hash see tp_richcompare */
3803 COPYSLOT(tp_call);
3804 COPYSLOT(tp_str);
3805 {
3806 /* Copy comparison-related slots only when
3807 not overriding them anywhere */
3808 if (type->tp_richcompare == NULL &&
3809 type->tp_hash == NULL &&
3810 !overrides_hash(type))
3811 {
3812 type->tp_richcompare = base->tp_richcompare;
3813 type->tp_hash = base->tp_hash;
3814 }
3815 }
3816 {
3817 COPYSLOT(tp_iter);
3818 COPYSLOT(tp_iternext);
3819 }
3820 {
3821 COPYSLOT(tp_descr_get);
3822 COPYSLOT(tp_descr_set);
3823 COPYSLOT(tp_dictoffset);
3824 COPYSLOT(tp_init);
3825 COPYSLOT(tp_alloc);
3826 COPYSLOT(tp_is_gc);
3827 if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) ==
3828 (base->tp_flags & Py_TPFLAGS_HAVE_GC)) {
3829 /* They agree about gc. */
3830 COPYSLOT(tp_free);
3831 }
3832 else if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
3833 type->tp_free == NULL &&
3834 base->tp_free == PyObject_Free) {
3835 /* A bit of magic to plug in the correct default
3836 * tp_free function when a derived class adds gc,
3837 * didn't define tp_free, and the base uses the
3838 * default non-gc tp_free.
3839 */
3840 type->tp_free = PyObject_GC_Del;
3841 }
3842 /* else they didn't agree about gc, and there isn't something
3843 * obvious to be done -- the type is on its own.
3844 */
3845 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003846}
3847
Jeremy Hylton938ace62002-07-17 16:30:39 +00003848static int add_operators(PyTypeObject *);
Guido van Rossum13d52f02001-08-10 21:24:08 +00003849
Tim Peters6d6c1a32001-08-02 04:15:00 +00003850int
Guido van Rossum528b7eb2001-08-07 17:24:28 +00003851PyType_Ready(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003852{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003853 PyObject *dict, *bases;
3854 PyTypeObject *base;
3855 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003856
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003857 if (type->tp_flags & Py_TPFLAGS_READY) {
3858 assert(type->tp_dict != NULL);
3859 return 0;
3860 }
3861 assert((type->tp_flags & Py_TPFLAGS_READYING) == 0);
Guido van Rossumd614f972001-08-10 17:39:49 +00003862
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003863 type->tp_flags |= Py_TPFLAGS_READYING;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003864
Tim Peters36eb4df2003-03-23 03:33:13 +00003865#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003866 /* PyType_Ready is the closest thing we have to a choke point
3867 * for type objects, so is the best place I can think of to try
3868 * to get type objects into the doubly-linked list of all objects.
3869 * Still, not all type objects go thru PyType_Ready.
3870 */
3871 _Py_AddToAllObjects((PyObject *)type, 0);
Tim Peters36eb4df2003-03-23 03:33:13 +00003872#endif
3873
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003874 /* Initialize tp_base (defaults to BaseObject unless that's us) */
3875 base = type->tp_base;
3876 if (base == NULL && type != &PyBaseObject_Type) {
3877 base = type->tp_base = &PyBaseObject_Type;
3878 Py_INCREF(base);
3879 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003880
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003881 /* Now the only way base can still be NULL is if type is
3882 * &PyBaseObject_Type.
3883 */
Guido van Rossum692cdbc2006-03-10 02:04:28 +00003884
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003885 /* Initialize the base class */
3886 if (base != NULL && base->tp_dict == NULL) {
3887 if (PyType_Ready(base) < 0)
3888 goto error;
3889 }
Guido van Rossum323a9cf2002-08-14 17:26:30 +00003890
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003891 /* Initialize ob_type if NULL. This means extensions that want to be
3892 compilable separately on Windows can call PyType_Ready() instead of
3893 initializing the ob_type field of their type objects. */
3894 /* The test for base != NULL is really unnecessary, since base is only
3895 NULL when type is &PyBaseObject_Type, and we know its ob_type is
3896 not NULL (it's initialized to &PyType_Type). But coverity doesn't
3897 know that. */
3898 if (Py_TYPE(type) == NULL && base != NULL)
3899 Py_TYPE(type) = Py_TYPE(base);
Guido van Rossum0986d822002-04-08 01:38:42 +00003900
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003901 /* Initialize tp_bases */
3902 bases = type->tp_bases;
3903 if (bases == NULL) {
3904 if (base == NULL)
3905 bases = PyTuple_New(0);
3906 else
3907 bases = PyTuple_Pack(1, base);
3908 if (bases == NULL)
3909 goto error;
3910 type->tp_bases = bases;
3911 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003912
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003913 /* Initialize tp_dict */
3914 dict = type->tp_dict;
3915 if (dict == NULL) {
3916 dict = PyDict_New();
3917 if (dict == NULL)
3918 goto error;
3919 type->tp_dict = dict;
3920 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003921
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003922 /* Add type-specific descriptors to tp_dict */
3923 if (add_operators(type) < 0)
3924 goto error;
3925 if (type->tp_methods != NULL) {
3926 if (add_methods(type, type->tp_methods) < 0)
3927 goto error;
3928 }
3929 if (type->tp_members != NULL) {
3930 if (add_members(type, type->tp_members) < 0)
3931 goto error;
3932 }
3933 if (type->tp_getset != NULL) {
3934 if (add_getset(type, type->tp_getset) < 0)
3935 goto error;
3936 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003937
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003938 /* Calculate method resolution order */
3939 if (mro_internal(type) < 0) {
3940 goto error;
3941 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003942
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003943 /* Inherit special flags from dominant base */
3944 if (type->tp_base != NULL)
3945 inherit_special(type, type->tp_base);
Guido van Rossum13d52f02001-08-10 21:24:08 +00003946
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003947 /* Initialize tp_dict properly */
3948 bases = type->tp_mro;
3949 assert(bases != NULL);
3950 assert(PyTuple_Check(bases));
3951 n = PyTuple_GET_SIZE(bases);
3952 for (i = 1; i < n; i++) {
3953 PyObject *b = PyTuple_GET_ITEM(bases, i);
3954 if (PyType_Check(b))
3955 inherit_slots(type, (PyTypeObject *)b);
3956 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003957
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003958 /* Sanity check for tp_free. */
3959 if (PyType_IS_GC(type) && (type->tp_flags & Py_TPFLAGS_BASETYPE) &&
3960 (type->tp_free == NULL || type->tp_free == PyObject_Del)) {
3961 /* This base class needs to call tp_free, but doesn't have
3962 * one, or its tp_free is for non-gc'ed objects.
3963 */
3964 PyErr_Format(PyExc_TypeError, "type '%.100s' participates in "
3965 "gc and is a base type but has inappropriate "
3966 "tp_free slot",
3967 type->tp_name);
3968 goto error;
3969 }
Tim Peters3cfe7542003-05-21 21:29:48 +00003970
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003971 /* if the type dictionary doesn't contain a __doc__, set it from
3972 the tp_doc slot.
3973 */
3974 if (PyDict_GetItemString(type->tp_dict, "__doc__") == NULL) {
3975 if (type->tp_doc != NULL) {
3976 PyObject *doc = PyUnicode_FromString(type->tp_doc);
3977 if (doc == NULL)
3978 goto error;
3979 PyDict_SetItemString(type->tp_dict, "__doc__", doc);
3980 Py_DECREF(doc);
3981 } else {
3982 PyDict_SetItemString(type->tp_dict,
3983 "__doc__", Py_None);
3984 }
3985 }
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00003986
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003987 /* Hack for tp_hash and __hash__.
3988 If after all that, tp_hash is still NULL, and __hash__ is not in
3989 tp_dict, set tp_hash to PyObject_HashNotImplemented and
3990 tp_dict['__hash__'] equal to None.
3991 This signals that __hash__ is not inherited.
3992 */
3993 if (type->tp_hash == NULL) {
3994 if (PyDict_GetItemString(type->tp_dict, "__hash__") == NULL) {
3995 if (PyDict_SetItemString(type->tp_dict, "__hash__", Py_None) < 0)
3996 goto error;
3997 type->tp_hash = PyObject_HashNotImplemented;
3998 }
3999 }
Guido van Rossum38938152006-08-21 23:36:26 +00004000
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004001 /* Some more special stuff */
4002 base = type->tp_base;
4003 if (base != NULL) {
4004 if (type->tp_as_number == NULL)
4005 type->tp_as_number = base->tp_as_number;
4006 if (type->tp_as_sequence == NULL)
4007 type->tp_as_sequence = base->tp_as_sequence;
4008 if (type->tp_as_mapping == NULL)
4009 type->tp_as_mapping = base->tp_as_mapping;
4010 if (type->tp_as_buffer == NULL)
4011 type->tp_as_buffer = base->tp_as_buffer;
4012 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004013
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004014 /* Link into each base class's list of subclasses */
4015 bases = type->tp_bases;
4016 n = PyTuple_GET_SIZE(bases);
4017 for (i = 0; i < n; i++) {
4018 PyObject *b = PyTuple_GET_ITEM(bases, i);
4019 if (PyType_Check(b) &&
4020 add_subclass((PyTypeObject *)b, type) < 0)
4021 goto error;
4022 }
Guido van Rossum1c450732001-10-08 15:18:27 +00004023
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004024 /* Warn for a type that implements tp_compare (now known as
4025 tp_reserved) but not tp_richcompare. */
4026 if (type->tp_reserved && !type->tp_richcompare) {
4027 int error;
Victor Stinner4a2b7a12010-08-13 14:03:48 +00004028 error = PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
4029 "Type %.100s defines tp_reserved (formerly tp_compare) "
4030 "but not tp_richcompare. Comparisons may not behave as intended.",
4031 type->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004032 if (error == -1)
4033 goto error;
4034 }
Mark Dickinson2a7d45b2009-02-08 11:02:10 +00004035
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004036 /* All done -- set the ready flag */
4037 assert(type->tp_dict != NULL);
4038 type->tp_flags =
4039 (type->tp_flags & ~Py_TPFLAGS_READYING) | Py_TPFLAGS_READY;
4040 return 0;
Guido van Rossumd614f972001-08-10 17:39:49 +00004041
4042 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004043 type->tp_flags &= ~Py_TPFLAGS_READYING;
4044 return -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004045}
4046
Guido van Rossum1c450732001-10-08 15:18:27 +00004047static int
4048add_subclass(PyTypeObject *base, PyTypeObject *type)
4049{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004050 Py_ssize_t i;
4051 int result;
4052 PyObject *list, *ref, *newobj;
Guido van Rossum1c450732001-10-08 15:18:27 +00004053
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004054 list = base->tp_subclasses;
4055 if (list == NULL) {
4056 base->tp_subclasses = list = PyList_New(0);
4057 if (list == NULL)
4058 return -1;
4059 }
4060 assert(PyList_Check(list));
4061 newobj = PyWeakref_NewRef((PyObject *)type, NULL);
4062 i = PyList_GET_SIZE(list);
4063 while (--i >= 0) {
4064 ref = PyList_GET_ITEM(list, i);
4065 assert(PyWeakref_CheckRef(ref));
4066 if (PyWeakref_GET_OBJECT(ref) == Py_None)
4067 return PyList_SetItem(list, i, newobj);
4068 }
4069 result = PyList_Append(list, newobj);
4070 Py_DECREF(newobj);
4071 return result;
Guido van Rossum1c450732001-10-08 15:18:27 +00004072}
4073
Michael W. Hudson98bbc492002-11-26 14:47:27 +00004074static void
4075remove_subclass(PyTypeObject *base, PyTypeObject *type)
4076{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004077 Py_ssize_t i;
4078 PyObject *list, *ref;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00004079
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004080 list = base->tp_subclasses;
4081 if (list == NULL) {
4082 return;
4083 }
4084 assert(PyList_Check(list));
4085 i = PyList_GET_SIZE(list);
4086 while (--i >= 0) {
4087 ref = PyList_GET_ITEM(list, i);
4088 assert(PyWeakref_CheckRef(ref));
4089 if (PyWeakref_GET_OBJECT(ref) == (PyObject*)type) {
4090 /* this can't fail, right? */
4091 PySequence_DelItem(list, i);
4092 return;
4093 }
4094 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +00004095}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004096
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004097static int
4098check_num_args(PyObject *ob, int n)
4099{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004100 if (!PyTuple_CheckExact(ob)) {
4101 PyErr_SetString(PyExc_SystemError,
4102 "PyArg_UnpackTuple() argument list is not a tuple");
4103 return 0;
4104 }
4105 if (n == PyTuple_GET_SIZE(ob))
4106 return 1;
4107 PyErr_Format(
4108 PyExc_TypeError,
4109 "expected %d arguments, got %zd", n, PyTuple_GET_SIZE(ob));
4110 return 0;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004111}
4112
Tim Peters6d6c1a32001-08-02 04:15:00 +00004113/* Generic wrappers for overloadable 'operators' such as __getitem__ */
4114
4115/* There's a wrapper *function* for each distinct function typedef used
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004116 for type object slots (e.g. binaryfunc, ternaryfunc, etc.). There's a
Tim Peters6d6c1a32001-08-02 04:15:00 +00004117 wrapper *table* for each distinct operation (e.g. __len__, __add__).
4118 Most tables have only one entry; the tables for binary operators have two
4119 entries, one regular and one with reversed arguments. */
4120
4121static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00004122wrap_lenfunc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004123{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004124 lenfunc func = (lenfunc)wrapped;
4125 Py_ssize_t res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004126
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004127 if (!check_num_args(args, 0))
4128 return NULL;
4129 res = (*func)(self);
4130 if (res == -1 && PyErr_Occurred())
4131 return NULL;
4132 return PyLong_FromLong((long)res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004133}
4134
Tim Peters6d6c1a32001-08-02 04:15:00 +00004135static PyObject *
Raymond Hettingerf34f2642003-10-11 17:29:04 +00004136wrap_inquirypred(PyObject *self, PyObject *args, void *wrapped)
4137{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004138 inquiry func = (inquiry)wrapped;
4139 int res;
Raymond Hettingerf34f2642003-10-11 17:29:04 +00004140
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004141 if (!check_num_args(args, 0))
4142 return NULL;
4143 res = (*func)(self);
4144 if (res == -1 && PyErr_Occurred())
4145 return NULL;
4146 return PyBool_FromLong((long)res);
Raymond Hettingerf34f2642003-10-11 17:29:04 +00004147}
4148
4149static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00004150wrap_binaryfunc(PyObject *self, PyObject *args, void *wrapped)
4151{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004152 binaryfunc func = (binaryfunc)wrapped;
4153 PyObject *other;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004154
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004155 if (!check_num_args(args, 1))
4156 return NULL;
4157 other = PyTuple_GET_ITEM(args, 0);
4158 return (*func)(self, other);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004159}
4160
4161static PyObject *
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00004162wrap_binaryfunc_l(PyObject *self, PyObject *args, void *wrapped)
4163{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004164 binaryfunc func = (binaryfunc)wrapped;
4165 PyObject *other;
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00004166
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004167 if (!check_num_args(args, 1))
4168 return NULL;
4169 other = PyTuple_GET_ITEM(args, 0);
4170 return (*func)(self, other);
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00004171}
4172
4173static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00004174wrap_binaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
4175{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004176 binaryfunc func = (binaryfunc)wrapped;
4177 PyObject *other;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004178
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004179 if (!check_num_args(args, 1))
4180 return NULL;
4181 other = PyTuple_GET_ITEM(args, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004182 return (*func)(other, self);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004183}
4184
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004185static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00004186wrap_ternaryfunc(PyObject *self, PyObject *args, void *wrapped)
4187{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004188 ternaryfunc func = (ternaryfunc)wrapped;
4189 PyObject *other;
4190 PyObject *third = Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004191
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004192 /* Note: This wrapper only works for __pow__() */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004193
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004194 if (!PyArg_UnpackTuple(args, "", 1, 2, &other, &third))
4195 return NULL;
4196 return (*func)(self, other, third);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004197}
4198
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00004199static PyObject *
4200wrap_ternaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
4201{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004202 ternaryfunc func = (ternaryfunc)wrapped;
4203 PyObject *other;
4204 PyObject *third = Py_None;
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00004205
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004206 /* Note: This wrapper only works for __pow__() */
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00004207
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004208 if (!PyArg_UnpackTuple(args, "", 1, 2, &other, &third))
4209 return NULL;
4210 return (*func)(other, self, third);
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00004211}
4212
Tim Peters6d6c1a32001-08-02 04:15:00 +00004213static PyObject *
4214wrap_unaryfunc(PyObject *self, PyObject *args, void *wrapped)
4215{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004216 unaryfunc func = (unaryfunc)wrapped;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004217
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004218 if (!check_num_args(args, 0))
4219 return NULL;
4220 return (*func)(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004221}
4222
Tim Peters6d6c1a32001-08-02 04:15:00 +00004223static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004224wrap_indexargfunc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004225{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004226 ssizeargfunc func = (ssizeargfunc)wrapped;
4227 PyObject* o;
4228 Py_ssize_t i;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004229
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004230 if (!PyArg_UnpackTuple(args, "", 1, 1, &o))
4231 return NULL;
4232 i = PyNumber_AsSsize_t(o, PyExc_OverflowError);
4233 if (i == -1 && PyErr_Occurred())
4234 return NULL;
4235 return (*func)(self, i);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004236}
4237
Martin v. Löwis18e16552006-02-15 17:27:45 +00004238static Py_ssize_t
Guido van Rossum5d815f32001-08-17 21:57:47 +00004239getindex(PyObject *self, PyObject *arg)
4240{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004241 Py_ssize_t i;
Guido van Rossum5d815f32001-08-17 21:57:47 +00004242
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004243 i = PyNumber_AsSsize_t(arg, PyExc_OverflowError);
4244 if (i == -1 && PyErr_Occurred())
4245 return -1;
4246 if (i < 0) {
4247 PySequenceMethods *sq = Py_TYPE(self)->tp_as_sequence;
4248 if (sq && sq->sq_length) {
4249 Py_ssize_t n = (*sq->sq_length)(self);
4250 if (n < 0)
4251 return -1;
4252 i += n;
4253 }
4254 }
4255 return i;
Guido van Rossum5d815f32001-08-17 21:57:47 +00004256}
4257
4258static PyObject *
4259wrap_sq_item(PyObject *self, PyObject *args, void *wrapped)
4260{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004261 ssizeargfunc func = (ssizeargfunc)wrapped;
4262 PyObject *arg;
4263 Py_ssize_t i;
Guido van Rossum5d815f32001-08-17 21:57:47 +00004264
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004265 if (PyTuple_GET_SIZE(args) == 1) {
4266 arg = PyTuple_GET_ITEM(args, 0);
4267 i = getindex(self, arg);
4268 if (i == -1 && PyErr_Occurred())
4269 return NULL;
4270 return (*func)(self, i);
4271 }
4272 check_num_args(args, 1);
4273 assert(PyErr_Occurred());
4274 return NULL;
Guido van Rossum5d815f32001-08-17 21:57:47 +00004275}
4276
Tim Peters6d6c1a32001-08-02 04:15:00 +00004277static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00004278wrap_sq_setitem(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004279{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004280 ssizeobjargproc func = (ssizeobjargproc)wrapped;
4281 Py_ssize_t i;
4282 int res;
4283 PyObject *arg, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004284
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004285 if (!PyArg_UnpackTuple(args, "", 2, 2, &arg, &value))
4286 return NULL;
4287 i = getindex(self, arg);
4288 if (i == -1 && PyErr_Occurred())
4289 return NULL;
4290 res = (*func)(self, i, value);
4291 if (res == -1 && PyErr_Occurred())
4292 return NULL;
4293 Py_INCREF(Py_None);
4294 return Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004295}
4296
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004297static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00004298wrap_sq_delitem(PyObject *self, PyObject *args, void *wrapped)
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004299{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004300 ssizeobjargproc func = (ssizeobjargproc)wrapped;
4301 Py_ssize_t i;
4302 int res;
4303 PyObject *arg;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004304
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004305 if (!check_num_args(args, 1))
4306 return NULL;
4307 arg = PyTuple_GET_ITEM(args, 0);
4308 i = getindex(self, arg);
4309 if (i == -1 && PyErr_Occurred())
4310 return NULL;
4311 res = (*func)(self, i, NULL);
4312 if (res == -1 && PyErr_Occurred())
4313 return NULL;
4314 Py_INCREF(Py_None);
4315 return Py_None;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004316}
4317
Tim Peters6d6c1a32001-08-02 04:15:00 +00004318/* XXX objobjproc is a misnomer; should be objargpred */
4319static PyObject *
4320wrap_objobjproc(PyObject *self, PyObject *args, void *wrapped)
4321{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004322 objobjproc func = (objobjproc)wrapped;
4323 int res;
4324 PyObject *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004325
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004326 if (!check_num_args(args, 1))
4327 return NULL;
4328 value = PyTuple_GET_ITEM(args, 0);
4329 res = (*func)(self, value);
4330 if (res == -1 && PyErr_Occurred())
4331 return NULL;
4332 else
4333 return PyBool_FromLong(res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004334}
4335
Tim Peters6d6c1a32001-08-02 04:15:00 +00004336static PyObject *
4337wrap_objobjargproc(PyObject *self, PyObject *args, void *wrapped)
4338{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004339 objobjargproc func = (objobjargproc)wrapped;
4340 int res;
4341 PyObject *key, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004342
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004343 if (!PyArg_UnpackTuple(args, "", 2, 2, &key, &value))
4344 return NULL;
4345 res = (*func)(self, key, value);
4346 if (res == -1 && PyErr_Occurred())
4347 return NULL;
4348 Py_INCREF(Py_None);
4349 return Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004350}
4351
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004352static PyObject *
4353wrap_delitem(PyObject *self, PyObject *args, void *wrapped)
4354{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004355 objobjargproc func = (objobjargproc)wrapped;
4356 int res;
4357 PyObject *key;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004358
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004359 if (!check_num_args(args, 1))
4360 return NULL;
4361 key = PyTuple_GET_ITEM(args, 0);
4362 res = (*func)(self, key, NULL);
4363 if (res == -1 && PyErr_Occurred())
4364 return NULL;
4365 Py_INCREF(Py_None);
4366 return Py_None;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004367}
4368
Guido van Rossum4dcdb782003-04-14 21:46:03 +00004369/* Helper to check for object.__setattr__ or __delattr__ applied to a type.
Guido van Rossum52b27052003-04-15 20:05:10 +00004370 This is called the Carlo Verre hack after its discoverer. */
Guido van Rossum4dcdb782003-04-14 21:46:03 +00004371static int
4372hackcheck(PyObject *self, setattrofunc func, char *what)
4373{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004374 PyTypeObject *type = Py_TYPE(self);
4375 while (type && type->tp_flags & Py_TPFLAGS_HEAPTYPE)
4376 type = type->tp_base;
4377 /* If type is NULL now, this is a really weird type.
4378 In the spirit of backwards compatibility (?), just shut up. */
4379 if (type && type->tp_setattro != func) {
4380 PyErr_Format(PyExc_TypeError,
4381 "can't apply this %s to %s object",
4382 what,
4383 type->tp_name);
4384 return 0;
4385 }
4386 return 1;
Guido van Rossum4dcdb782003-04-14 21:46:03 +00004387}
4388
Tim Peters6d6c1a32001-08-02 04:15:00 +00004389static PyObject *
4390wrap_setattr(PyObject *self, PyObject *args, void *wrapped)
4391{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004392 setattrofunc func = (setattrofunc)wrapped;
4393 int res;
4394 PyObject *name, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004395
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004396 if (!PyArg_UnpackTuple(args, "", 2, 2, &name, &value))
4397 return NULL;
4398 if (!hackcheck(self, func, "__setattr__"))
4399 return NULL;
4400 res = (*func)(self, name, value);
4401 if (res < 0)
4402 return NULL;
4403 Py_INCREF(Py_None);
4404 return Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004405}
4406
4407static PyObject *
4408wrap_delattr(PyObject *self, PyObject *args, void *wrapped)
4409{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004410 setattrofunc func = (setattrofunc)wrapped;
4411 int res;
4412 PyObject *name;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004413
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004414 if (!check_num_args(args, 1))
4415 return NULL;
4416 name = PyTuple_GET_ITEM(args, 0);
4417 if (!hackcheck(self, func, "__delattr__"))
4418 return NULL;
4419 res = (*func)(self, name, NULL);
4420 if (res < 0)
4421 return NULL;
4422 Py_INCREF(Py_None);
4423 return Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004424}
4425
Tim Peters6d6c1a32001-08-02 04:15:00 +00004426static PyObject *
4427wrap_hashfunc(PyObject *self, PyObject *args, void *wrapped)
4428{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004429 hashfunc func = (hashfunc)wrapped;
Benjamin Peterson8035bc52010-10-23 16:20:50 +00004430 Py_hash_t res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004431
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004432 if (!check_num_args(args, 0))
4433 return NULL;
4434 res = (*func)(self);
4435 if (res == -1 && PyErr_Occurred())
4436 return NULL;
Benjamin Peterson8035bc52010-10-23 16:20:50 +00004437 return PyLong_FromSsize_t(res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004438}
4439
Tim Peters6d6c1a32001-08-02 04:15:00 +00004440static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00004441wrap_call(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004442{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004443 ternaryfunc func = (ternaryfunc)wrapped;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004444
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004445 return (*func)(self, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004446}
4447
Tim Peters6d6c1a32001-08-02 04:15:00 +00004448static PyObject *
4449wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op)
4450{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004451 richcmpfunc func = (richcmpfunc)wrapped;
4452 PyObject *other;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004453
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004454 if (!check_num_args(args, 1))
4455 return NULL;
4456 other = PyTuple_GET_ITEM(args, 0);
4457 return (*func)(self, other, op);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004458}
4459
4460#undef RICHCMP_WRAPPER
4461#define RICHCMP_WRAPPER(NAME, OP) \
4462static PyObject * \
4463richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \
4464{ \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004465 return wrap_richcmpfunc(self, args, wrapped, OP); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004466}
4467
Jack Jansen8e938b42001-08-08 15:29:49 +00004468RICHCMP_WRAPPER(lt, Py_LT)
4469RICHCMP_WRAPPER(le, Py_LE)
4470RICHCMP_WRAPPER(eq, Py_EQ)
4471RICHCMP_WRAPPER(ne, Py_NE)
4472RICHCMP_WRAPPER(gt, Py_GT)
4473RICHCMP_WRAPPER(ge, Py_GE)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004474
Tim Peters6d6c1a32001-08-02 04:15:00 +00004475static PyObject *
4476wrap_next(PyObject *self, PyObject *args, void *wrapped)
4477{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004478 unaryfunc func = (unaryfunc)wrapped;
4479 PyObject *res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004480
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004481 if (!check_num_args(args, 0))
4482 return NULL;
4483 res = (*func)(self);
4484 if (res == NULL && !PyErr_Occurred())
4485 PyErr_SetNone(PyExc_StopIteration);
4486 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004487}
4488
Tim Peters6d6c1a32001-08-02 04:15:00 +00004489static PyObject *
4490wrap_descr_get(PyObject *self, PyObject *args, void *wrapped)
4491{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004492 descrgetfunc func = (descrgetfunc)wrapped;
4493 PyObject *obj;
4494 PyObject *type = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004495
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004496 if (!PyArg_UnpackTuple(args, "", 1, 2, &obj, &type))
4497 return NULL;
4498 if (obj == Py_None)
4499 obj = NULL;
4500 if (type == Py_None)
4501 type = NULL;
4502 if (type == NULL &&obj == NULL) {
4503 PyErr_SetString(PyExc_TypeError,
4504 "__get__(None, None) is invalid");
4505 return NULL;
4506 }
4507 return (*func)(self, obj, type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004508}
4509
Tim Peters6d6c1a32001-08-02 04:15:00 +00004510static PyObject *
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004511wrap_descr_set(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004512{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004513 descrsetfunc func = (descrsetfunc)wrapped;
4514 PyObject *obj, *value;
4515 int ret;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004516
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004517 if (!PyArg_UnpackTuple(args, "", 2, 2, &obj, &value))
4518 return NULL;
4519 ret = (*func)(self, obj, value);
4520 if (ret < 0)
4521 return NULL;
4522 Py_INCREF(Py_None);
4523 return Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004524}
Guido van Rossum22b13872002-08-06 21:41:44 +00004525
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00004526static PyObject *
4527wrap_descr_delete(PyObject *self, PyObject *args, void *wrapped)
4528{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004529 descrsetfunc func = (descrsetfunc)wrapped;
4530 PyObject *obj;
4531 int ret;
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00004532
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004533 if (!check_num_args(args, 1))
4534 return NULL;
4535 obj = PyTuple_GET_ITEM(args, 0);
4536 ret = (*func)(self, obj, NULL);
4537 if (ret < 0)
4538 return NULL;
4539 Py_INCREF(Py_None);
4540 return Py_None;
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00004541}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004542
Tim Peters6d6c1a32001-08-02 04:15:00 +00004543static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00004544wrap_init(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004545{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004546 initproc func = (initproc)wrapped;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004547
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004548 if (func(self, args, kwds) < 0)
4549 return NULL;
4550 Py_INCREF(Py_None);
4551 return Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004552}
4553
Tim Peters6d6c1a32001-08-02 04:15:00 +00004554static PyObject *
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004555tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004556{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004557 PyTypeObject *type, *subtype, *staticbase;
4558 PyObject *arg0, *res;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004559
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004560 if (self == NULL || !PyType_Check(self))
4561 Py_FatalError("__new__() called with non-type 'self'");
4562 type = (PyTypeObject *)self;
4563 if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) {
4564 PyErr_Format(PyExc_TypeError,
4565 "%s.__new__(): not enough arguments",
4566 type->tp_name);
4567 return NULL;
4568 }
4569 arg0 = PyTuple_GET_ITEM(args, 0);
4570 if (!PyType_Check(arg0)) {
4571 PyErr_Format(PyExc_TypeError,
4572 "%s.__new__(X): X is not a type object (%s)",
4573 type->tp_name,
4574 Py_TYPE(arg0)->tp_name);
4575 return NULL;
4576 }
4577 subtype = (PyTypeObject *)arg0;
4578 if (!PyType_IsSubtype(subtype, type)) {
4579 PyErr_Format(PyExc_TypeError,
4580 "%s.__new__(%s): %s is not a subtype of %s",
4581 type->tp_name,
4582 subtype->tp_name,
4583 subtype->tp_name,
4584 type->tp_name);
4585 return NULL;
4586 }
Barry Warsaw60f01882001-08-22 19:24:42 +00004587
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004588 /* Check that the use doesn't do something silly and unsafe like
4589 object.__new__(dict). To do this, we check that the
4590 most derived base that's not a heap type is this type. */
4591 staticbase = subtype;
4592 while (staticbase && (staticbase->tp_flags & Py_TPFLAGS_HEAPTYPE))
4593 staticbase = staticbase->tp_base;
4594 /* If staticbase is NULL now, it is a really weird type.
4595 In the spirit of backwards compatibility (?), just shut up. */
4596 if (staticbase && staticbase->tp_new != type->tp_new) {
4597 PyErr_Format(PyExc_TypeError,
4598 "%s.__new__(%s) is not safe, use %s.__new__()",
4599 type->tp_name,
4600 subtype->tp_name,
4601 staticbase == NULL ? "?" : staticbase->tp_name);
4602 return NULL;
4603 }
Barry Warsaw60f01882001-08-22 19:24:42 +00004604
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004605 args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
4606 if (args == NULL)
4607 return NULL;
4608 res = type->tp_new(subtype, args, kwds);
4609 Py_DECREF(args);
4610 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004611}
4612
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004613static struct PyMethodDef tp_new_methoddef[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004614 {"__new__", (PyCFunction)tp_new_wrapper, METH_VARARGS|METH_KEYWORDS,
4615 PyDoc_STR("T.__new__(S, ...) -> "
4616 "a new object with type S, a subtype of T")},
4617 {0}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004618};
4619
4620static int
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004621add_tp_new_wrapper(PyTypeObject *type)
4622{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004623 PyObject *func;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004624
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004625 if (PyDict_GetItemString(type->tp_dict, "__new__") != NULL)
4626 return 0;
4627 func = PyCFunction_New(tp_new_methoddef, (PyObject *)type);
4628 if (func == NULL)
4629 return -1;
4630 if (PyDict_SetItemString(type->tp_dict, "__new__", func)) {
4631 Py_DECREF(func);
4632 return -1;
4633 }
4634 Py_DECREF(func);
4635 return 0;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004636}
4637
Guido van Rossumf040ede2001-08-07 16:40:56 +00004638/* Slot wrappers that call the corresponding __foo__ slot. See comments
4639 below at override_slots() for more explanation. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004640
Guido van Rossumdc91b992001-08-08 22:26:22 +00004641#define SLOT0(FUNCNAME, OPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004642static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004643FUNCNAME(PyObject *self) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004644{ \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004645 static PyObject *cache_str; \
4646 return call_method(self, OPSTR, &cache_str, "()"); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004647}
4648
Guido van Rossumdc91b992001-08-08 22:26:22 +00004649#define SLOT1(FUNCNAME, OPSTR, ARG1TYPE, ARGCODES) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004650static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004651FUNCNAME(PyObject *self, ARG1TYPE arg1) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004652{ \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004653 static PyObject *cache_str; \
4654 return call_method(self, OPSTR, &cache_str, "(" ARGCODES ")", arg1); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004655}
4656
Guido van Rossumcd118802003-01-06 22:57:47 +00004657/* Boolean helper for SLOT1BINFULL().
4658 right.__class__ is a nontrivial subclass of left.__class__. */
4659static int
4660method_is_overloaded(PyObject *left, PyObject *right, char *name)
4661{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004662 PyObject *a, *b;
4663 int ok;
Guido van Rossumcd118802003-01-06 22:57:47 +00004664
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004665 b = PyObject_GetAttrString((PyObject *)(Py_TYPE(right)), name);
4666 if (b == NULL) {
4667 PyErr_Clear();
4668 /* If right doesn't have it, it's not overloaded */
4669 return 0;
4670 }
Guido van Rossumcd118802003-01-06 22:57:47 +00004671
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004672 a = PyObject_GetAttrString((PyObject *)(Py_TYPE(left)), name);
4673 if (a == NULL) {
4674 PyErr_Clear();
4675 Py_DECREF(b);
4676 /* If right has it but left doesn't, it's overloaded */
4677 return 1;
4678 }
Guido van Rossumcd118802003-01-06 22:57:47 +00004679
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004680 ok = PyObject_RichCompareBool(a, b, Py_NE);
4681 Py_DECREF(a);
4682 Py_DECREF(b);
4683 if (ok < 0) {
4684 PyErr_Clear();
4685 return 0;
4686 }
Guido van Rossumcd118802003-01-06 22:57:47 +00004687
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004688 return ok;
Guido van Rossumcd118802003-01-06 22:57:47 +00004689}
4690
Guido van Rossumdc91b992001-08-08 22:26:22 +00004691
4692#define SLOT1BINFULL(FUNCNAME, TESTFUNC, SLOTNAME, OPSTR, ROPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004693static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004694FUNCNAME(PyObject *self, PyObject *other) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004695{ \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004696 static PyObject *cache_str, *rcache_str; \
4697 int do_other = Py_TYPE(self) != Py_TYPE(other) && \
4698 Py_TYPE(other)->tp_as_number != NULL && \
4699 Py_TYPE(other)->tp_as_number->SLOTNAME == TESTFUNC; \
4700 if (Py_TYPE(self)->tp_as_number != NULL && \
4701 Py_TYPE(self)->tp_as_number->SLOTNAME == TESTFUNC) { \
4702 PyObject *r; \
4703 if (do_other && \
4704 PyType_IsSubtype(Py_TYPE(other), Py_TYPE(self)) && \
4705 method_is_overloaded(self, other, ROPSTR)) { \
4706 r = call_maybe( \
4707 other, ROPSTR, &rcache_str, "(O)", self); \
4708 if (r != Py_NotImplemented) \
4709 return r; \
4710 Py_DECREF(r); \
4711 do_other = 0; \
4712 } \
4713 r = call_maybe( \
4714 self, OPSTR, &cache_str, "(O)", other); \
4715 if (r != Py_NotImplemented || \
4716 Py_TYPE(other) == Py_TYPE(self)) \
4717 return r; \
4718 Py_DECREF(r); \
4719 } \
4720 if (do_other) { \
4721 return call_maybe( \
4722 other, ROPSTR, &rcache_str, "(O)", self); \
4723 } \
4724 Py_INCREF(Py_NotImplemented); \
4725 return Py_NotImplemented; \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004726}
4727
4728#define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004729 SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR)
Guido van Rossumdc91b992001-08-08 22:26:22 +00004730
4731#define SLOT2(FUNCNAME, OPSTR, ARG1TYPE, ARG2TYPE, ARGCODES) \
4732static PyObject * \
4733FUNCNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \
4734{ \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004735 static PyObject *cache_str; \
4736 return call_method(self, OPSTR, &cache_str, \
4737 "(" ARGCODES ")", arg1, arg2); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004738}
4739
Martin v. Löwis18e16552006-02-15 17:27:45 +00004740static Py_ssize_t
Tim Peters6d6c1a32001-08-02 04:15:00 +00004741slot_sq_length(PyObject *self)
4742{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004743 static PyObject *len_str;
4744 PyObject *res = call_method(self, "__len__", &len_str, "()");
4745 Py_ssize_t len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004746
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004747 if (res == NULL)
4748 return -1;
4749 len = PyNumber_AsSsize_t(res, PyExc_OverflowError);
4750 Py_DECREF(res);
4751 if (len < 0) {
4752 if (!PyErr_Occurred())
4753 PyErr_SetString(PyExc_ValueError,
4754 "__len__() should return >= 0");
4755 return -1;
4756 }
4757 return len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004758}
4759
Guido van Rossumf4593e02001-10-03 12:09:30 +00004760/* Super-optimized version of slot_sq_item.
4761 Other slots could do the same... */
4762static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00004763slot_sq_item(PyObject *self, Py_ssize_t i)
Guido van Rossumf4593e02001-10-03 12:09:30 +00004764{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004765 static PyObject *getitem_str;
4766 PyObject *func, *args = NULL, *ival = NULL, *retval = NULL;
4767 descrgetfunc f;
Guido van Rossumf4593e02001-10-03 12:09:30 +00004768
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004769 if (getitem_str == NULL) {
4770 getitem_str = PyUnicode_InternFromString("__getitem__");
4771 if (getitem_str == NULL)
4772 return NULL;
4773 }
4774 func = _PyType_Lookup(Py_TYPE(self), getitem_str);
4775 if (func != NULL) {
4776 if ((f = Py_TYPE(func)->tp_descr_get) == NULL)
4777 Py_INCREF(func);
4778 else {
4779 func = f(func, self, (PyObject *)(Py_TYPE(self)));
4780 if (func == NULL) {
4781 return NULL;
4782 }
4783 }
4784 ival = PyLong_FromSsize_t(i);
4785 if (ival != NULL) {
4786 args = PyTuple_New(1);
4787 if (args != NULL) {
4788 PyTuple_SET_ITEM(args, 0, ival);
4789 retval = PyObject_Call(func, args, NULL);
4790 Py_XDECREF(args);
4791 Py_XDECREF(func);
4792 return retval;
4793 }
4794 }
4795 }
4796 else {
4797 PyErr_SetObject(PyExc_AttributeError, getitem_str);
4798 }
4799 Py_XDECREF(args);
4800 Py_XDECREF(ival);
4801 Py_XDECREF(func);
4802 return NULL;
Guido van Rossumf4593e02001-10-03 12:09:30 +00004803}
4804
Tim Peters6d6c1a32001-08-02 04:15:00 +00004805static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00004806slot_sq_ass_item(PyObject *self, Py_ssize_t index, PyObject *value)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004807{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004808 PyObject *res;
4809 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004810
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004811 if (value == NULL)
4812 res = call_method(self, "__delitem__", &delitem_str,
4813 "(n)", index);
4814 else
4815 res = call_method(self, "__setitem__", &setitem_str,
4816 "(nO)", index, value);
4817 if (res == NULL)
4818 return -1;
4819 Py_DECREF(res);
4820 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004821}
4822
4823static int
Tim Peters6d6c1a32001-08-02 04:15:00 +00004824slot_sq_contains(PyObject *self, PyObject *value)
4825{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004826 PyObject *func, *res, *args;
4827 int result = -1;
Tim Petersbf9b2442003-03-23 05:35:36 +00004828
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004829 static PyObject *contains_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004830
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004831 func = lookup_maybe(self, "__contains__", &contains_str);
4832 if (func != NULL) {
4833 args = PyTuple_Pack(1, value);
4834 if (args == NULL)
4835 res = NULL;
4836 else {
4837 res = PyObject_Call(func, args, NULL);
4838 Py_DECREF(args);
4839 }
4840 Py_DECREF(func);
4841 if (res != NULL) {
4842 result = PyObject_IsTrue(res);
4843 Py_DECREF(res);
4844 }
4845 }
4846 else if (! PyErr_Occurred()) {
4847 /* Possible results: -1 and 1 */
4848 result = (int)_PySequence_IterSearch(self, value,
4849 PY_ITERSEARCH_CONTAINS);
4850 }
4851 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004852}
4853
Tim Peters6d6c1a32001-08-02 04:15:00 +00004854#define slot_mp_length slot_sq_length
4855
Guido van Rossumdc91b992001-08-08 22:26:22 +00004856SLOT1(slot_mp_subscript, "__getitem__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004857
4858static int
4859slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value)
4860{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004861 PyObject *res;
4862 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004863
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004864 if (value == NULL)
4865 res = call_method(self, "__delitem__", &delitem_str,
4866 "(O)", key);
4867 else
4868 res = call_method(self, "__setitem__", &setitem_str,
4869 "(OO)", key, value);
4870 if (res == NULL)
4871 return -1;
4872 Py_DECREF(res);
4873 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004874}
4875
Guido van Rossumdc91b992001-08-08 22:26:22 +00004876SLOT1BIN(slot_nb_add, nb_add, "__add__", "__radd__")
4877SLOT1BIN(slot_nb_subtract, nb_subtract, "__sub__", "__rsub__")
4878SLOT1BIN(slot_nb_multiply, nb_multiply, "__mul__", "__rmul__")
Guido van Rossumdc91b992001-08-08 22:26:22 +00004879SLOT1BIN(slot_nb_remainder, nb_remainder, "__mod__", "__rmod__")
4880SLOT1BIN(slot_nb_divmod, nb_divmod, "__divmod__", "__rdivmod__")
4881
Jeremy Hylton938ace62002-07-17 16:30:39 +00004882static PyObject *slot_nb_power(PyObject *, PyObject *, PyObject *);
Guido van Rossumdc91b992001-08-08 22:26:22 +00004883
4884SLOT1BINFULL(slot_nb_power_binary, slot_nb_power,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004885 nb_power, "__pow__", "__rpow__")
Guido van Rossumdc91b992001-08-08 22:26:22 +00004886
4887static PyObject *
4888slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus)
4889{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004890 static PyObject *pow_str;
Guido van Rossum2730b132001-08-28 18:22:14 +00004891
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004892 if (modulus == Py_None)
4893 return slot_nb_power_binary(self, other);
4894 /* Three-arg power doesn't use __rpow__. But ternary_op
4895 can call this when the second argument's type uses
4896 slot_nb_power, so check before calling self.__pow__. */
4897 if (Py_TYPE(self)->tp_as_number != NULL &&
4898 Py_TYPE(self)->tp_as_number->nb_power == slot_nb_power) {
4899 return call_method(self, "__pow__", &pow_str,
4900 "(OO)", other, modulus);
4901 }
4902 Py_INCREF(Py_NotImplemented);
4903 return Py_NotImplemented;
Guido van Rossumdc91b992001-08-08 22:26:22 +00004904}
4905
4906SLOT0(slot_nb_negative, "__neg__")
4907SLOT0(slot_nb_positive, "__pos__")
4908SLOT0(slot_nb_absolute, "__abs__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004909
4910static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00004911slot_nb_bool(PyObject *self)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004912{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004913 PyObject *func, *args;
4914 static PyObject *bool_str, *len_str;
4915 int result = -1;
4916 int using_len = 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004917
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004918 func = lookup_maybe(self, "__bool__", &bool_str);
4919 if (func == NULL) {
4920 if (PyErr_Occurred())
4921 return -1;
4922 func = lookup_maybe(self, "__len__", &len_str);
4923 if (func == NULL)
4924 return PyErr_Occurred() ? -1 : 1;
4925 using_len = 1;
4926 }
4927 args = PyTuple_New(0);
4928 if (args != NULL) {
4929 PyObject *temp = PyObject_Call(func, args, NULL);
4930 Py_DECREF(args);
4931 if (temp != NULL) {
4932 if (using_len) {
4933 /* enforced by slot_nb_len */
4934 result = PyObject_IsTrue(temp);
4935 }
4936 else if (PyBool_Check(temp)) {
4937 result = PyObject_IsTrue(temp);
4938 }
4939 else {
4940 PyErr_Format(PyExc_TypeError,
4941 "__bool__ should return "
4942 "bool, returned %s",
4943 Py_TYPE(temp)->tp_name);
4944 result = -1;
4945 }
4946 Py_DECREF(temp);
4947 }
4948 }
4949 Py_DECREF(func);
4950 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004951}
4952
Guido van Rossum38fff8c2006-03-07 18:50:55 +00004953
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00004954static PyObject *
Guido van Rossum38fff8c2006-03-07 18:50:55 +00004955slot_nb_index(PyObject *self)
4956{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004957 static PyObject *index_str;
4958 return call_method(self, "__index__", &index_str, "()");
Guido van Rossum38fff8c2006-03-07 18:50:55 +00004959}
4960
4961
Guido van Rossumdc91b992001-08-08 22:26:22 +00004962SLOT0(slot_nb_invert, "__invert__")
4963SLOT1BIN(slot_nb_lshift, nb_lshift, "__lshift__", "__rlshift__")
4964SLOT1BIN(slot_nb_rshift, nb_rshift, "__rshift__", "__rrshift__")
4965SLOT1BIN(slot_nb_and, nb_and, "__and__", "__rand__")
4966SLOT1BIN(slot_nb_xor, nb_xor, "__xor__", "__rxor__")
4967SLOT1BIN(slot_nb_or, nb_or, "__or__", "__ror__")
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004968
Guido van Rossumdc91b992001-08-08 22:26:22 +00004969SLOT0(slot_nb_int, "__int__")
Guido van Rossumdc91b992001-08-08 22:26:22 +00004970SLOT0(slot_nb_float, "__float__")
Guido van Rossumdc91b992001-08-08 22:26:22 +00004971SLOT1(slot_nb_inplace_add, "__iadd__", PyObject *, "O")
4972SLOT1(slot_nb_inplace_subtract, "__isub__", PyObject *, "O")
4973SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *, "O")
Guido van Rossumdc91b992001-08-08 22:26:22 +00004974SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *, "O")
Thomas Wouterscf297e42007-02-23 15:07:44 +00004975/* Can't use SLOT1 here, because nb_inplace_power is ternary */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004976static PyObject *
4977slot_nb_inplace_power(PyObject *self, PyObject * arg1, PyObject *arg2)
4978{
4979 static PyObject *cache_str;
4980 return call_method(self, "__ipow__", &cache_str, "(" "O" ")", arg1);
Thomas Wouterscf297e42007-02-23 15:07:44 +00004981}
Guido van Rossumdc91b992001-08-08 22:26:22 +00004982SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *, "O")
4983SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *, "O")
4984SLOT1(slot_nb_inplace_and, "__iand__", PyObject *, "O")
4985SLOT1(slot_nb_inplace_xor, "__ixor__", PyObject *, "O")
4986SLOT1(slot_nb_inplace_or, "__ior__", PyObject *, "O")
4987SLOT1BIN(slot_nb_floor_divide, nb_floor_divide,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004988 "__floordiv__", "__rfloordiv__")
Guido van Rossumdc91b992001-08-08 22:26:22 +00004989SLOT1BIN(slot_nb_true_divide, nb_true_divide, "__truediv__", "__rtruediv__")
4990SLOT1(slot_nb_inplace_floor_divide, "__ifloordiv__", PyObject *, "O")
4991SLOT1(slot_nb_inplace_true_divide, "__itruediv__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004992
Guido van Rossumb8f63662001-08-15 23:57:02 +00004993static PyObject *
4994slot_tp_repr(PyObject *self)
4995{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004996 PyObject *func, *res;
4997 static PyObject *repr_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004998
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004999 func = lookup_method(self, "__repr__", &repr_str);
5000 if (func != NULL) {
5001 res = PyEval_CallObject(func, NULL);
5002 Py_DECREF(func);
5003 return res;
5004 }
5005 PyErr_Clear();
5006 return PyUnicode_FromFormat("<%s object at %p>",
5007 Py_TYPE(self)->tp_name, self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005008}
5009
5010static PyObject *
5011slot_tp_str(PyObject *self)
5012{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005013 PyObject *func, *res;
5014 static PyObject *str_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00005015
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005016 func = lookup_method(self, "__str__", &str_str);
5017 if (func != NULL) {
5018 res = PyEval_CallObject(func, NULL);
5019 Py_DECREF(func);
5020 return res;
5021 }
5022 else {
5023 PyObject *ress;
5024 PyErr_Clear();
5025 res = slot_tp_repr(self);
5026 if (!res)
5027 return NULL;
5028 ress = _PyUnicode_AsDefaultEncodedString(res, NULL);
5029 Py_DECREF(res);
5030 return ress;
5031 }
Guido van Rossumb8f63662001-08-15 23:57:02 +00005032}
Tim Peters6d6c1a32001-08-02 04:15:00 +00005033
Benjamin Peterson8f67d082010-10-17 20:54:53 +00005034static Py_hash_t
Tim Peters6d6c1a32001-08-02 04:15:00 +00005035slot_tp_hash(PyObject *self)
5036{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005037 PyObject *func, *res;
5038 static PyObject *hash_str;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00005039 Py_ssize_t h;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005040
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005041 func = lookup_method(self, "__hash__", &hash_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005042
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005043 if (func == Py_None) {
5044 Py_DECREF(func);
5045 func = NULL;
5046 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +00005047
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005048 if (func == NULL) {
5049 return PyObject_HashNotImplemented(self);
5050 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +00005051
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005052 res = PyEval_CallObject(func, NULL);
5053 Py_DECREF(func);
5054 if (res == NULL)
5055 return -1;
Mark Dickinsondc787d22010-05-23 13:33:13 +00005056
5057 if (!PyLong_Check(res)) {
5058 PyErr_SetString(PyExc_TypeError,
5059 "__hash__ method should return an integer");
5060 return -1;
5061 }
Benjamin Peterson8f67d082010-10-17 20:54:53 +00005062 /* Transform the PyLong `res` to a Py_hash_t `h`. For an existing
5063 hashable Python object x, hash(x) will always lie within the range of
5064 Py_hash_t. Therefore our transformation must preserve values that
5065 already lie within this range, to ensure that if x.__hash__() returns
5066 hash(y) then hash(x) == hash(y). */
5067 h = PyLong_AsSsize_t(res);
5068 if (h == -1 && PyErr_Occurred()) {
5069 /* res was not within the range of a Py_hash_t, so we're free to
Mark Dickinsondc787d22010-05-23 13:33:13 +00005070 use any sufficiently bit-mixing transformation;
5071 long.__hash__ will do nicely. */
Benjamin Peterson8f67d082010-10-17 20:54:53 +00005072 PyErr_Clear();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005073 h = PyLong_Type.tp_hash(res);
Benjamin Peterson8f67d082010-10-17 20:54:53 +00005074 }
Benjamin Petersone7dfeeb2010-10-17 21:27:01 +00005075 /* -1 is reserved for errors. */
5076 if (h == -1)
5077 h = -2;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005078 Py_DECREF(res);
Mark Dickinsondc787d22010-05-23 13:33:13 +00005079 return h;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005080}
5081
5082static PyObject *
5083slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds)
5084{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005085 static PyObject *call_str;
5086 PyObject *meth = lookup_method(self, "__call__", &call_str);
5087 PyObject *res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005088
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005089 if (meth == NULL)
5090 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005091
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005092 res = PyObject_Call(meth, args, kwds);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005093
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005094 Py_DECREF(meth);
5095 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005096}
5097
Guido van Rossum14a6f832001-10-17 13:59:09 +00005098/* There are two slot dispatch functions for tp_getattro.
5099
5100 - slot_tp_getattro() is used when __getattribute__ is overridden
5101 but no __getattr__ hook is present;
5102
5103 - slot_tp_getattr_hook() is used when a __getattr__ hook is present.
5104
Guido van Rossumc334df52002-04-04 23:44:47 +00005105 The code in update_one_slot() always installs slot_tp_getattr_hook(); this
5106 detects the absence of __getattr__ and then installs the simpler slot if
5107 necessary. */
Guido van Rossum14a6f832001-10-17 13:59:09 +00005108
Tim Peters6d6c1a32001-08-02 04:15:00 +00005109static PyObject *
5110slot_tp_getattro(PyObject *self, PyObject *name)
5111{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005112 static PyObject *getattribute_str = NULL;
5113 return call_method(self, "__getattribute__", &getattribute_str,
5114 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005115}
5116
Guido van Rossum19c1cd52001-09-21 21:24:49 +00005117static PyObject *
Benjamin Peterson9262b842008-11-17 22:45:50 +00005118call_attribute(PyObject *self, PyObject *attr, PyObject *name)
5119{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005120 PyObject *res, *descr = NULL;
5121 descrgetfunc f = Py_TYPE(attr)->tp_descr_get;
Benjamin Peterson9262b842008-11-17 22:45:50 +00005122
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005123 if (f != NULL) {
5124 descr = f(attr, self, (PyObject *)(Py_TYPE(self)));
5125 if (descr == NULL)
5126 return NULL;
5127 else
5128 attr = descr;
5129 }
5130 res = PyObject_CallFunctionObjArgs(attr, name, NULL);
5131 Py_XDECREF(descr);
5132 return res;
Benjamin Peterson9262b842008-11-17 22:45:50 +00005133}
5134
5135static PyObject *
Guido van Rossum19c1cd52001-09-21 21:24:49 +00005136slot_tp_getattr_hook(PyObject *self, PyObject *name)
5137{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005138 PyTypeObject *tp = Py_TYPE(self);
5139 PyObject *getattr, *getattribute, *res;
5140 static PyObject *getattribute_str = NULL;
5141 static PyObject *getattr_str = NULL;
Guido van Rossum19c1cd52001-09-21 21:24:49 +00005142
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005143 if (getattr_str == NULL) {
5144 getattr_str = PyUnicode_InternFromString("__getattr__");
5145 if (getattr_str == NULL)
5146 return NULL;
5147 }
5148 if (getattribute_str == NULL) {
5149 getattribute_str =
5150 PyUnicode_InternFromString("__getattribute__");
5151 if (getattribute_str == NULL)
5152 return NULL;
5153 }
5154 /* speed hack: we could use lookup_maybe, but that would resolve the
5155 method fully for each attribute lookup for classes with
5156 __getattr__, even when the attribute is present. So we use
5157 _PyType_Lookup and create the method only when needed, with
5158 call_attribute. */
5159 getattr = _PyType_Lookup(tp, getattr_str);
5160 if (getattr == NULL) {
5161 /* No __getattr__ hook: use a simpler dispatcher */
5162 tp->tp_getattro = slot_tp_getattro;
5163 return slot_tp_getattro(self, name);
5164 }
5165 Py_INCREF(getattr);
5166 /* speed hack: we could use lookup_maybe, but that would resolve the
5167 method fully for each attribute lookup for classes with
5168 __getattr__, even when self has the default __getattribute__
5169 method. So we use _PyType_Lookup and create the method only when
5170 needed, with call_attribute. */
5171 getattribute = _PyType_Lookup(tp, getattribute_str);
5172 if (getattribute == NULL ||
5173 (Py_TYPE(getattribute) == &PyWrapperDescr_Type &&
5174 ((PyWrapperDescrObject *)getattribute)->d_wrapped ==
5175 (void *)PyObject_GenericGetAttr))
5176 res = PyObject_GenericGetAttr(self, name);
5177 else {
5178 Py_INCREF(getattribute);
5179 res = call_attribute(self, getattribute, name);
5180 Py_DECREF(getattribute);
5181 }
5182 if (res == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) {
5183 PyErr_Clear();
5184 res = call_attribute(self, getattr, name);
5185 }
5186 Py_DECREF(getattr);
5187 return res;
Guido van Rossum19c1cd52001-09-21 21:24:49 +00005188}
5189
Tim Peters6d6c1a32001-08-02 04:15:00 +00005190static int
5191slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value)
5192{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005193 PyObject *res;
5194 static PyObject *delattr_str, *setattr_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005195
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005196 if (value == NULL)
5197 res = call_method(self, "__delattr__", &delattr_str,
5198 "(O)", name);
5199 else
5200 res = call_method(self, "__setattr__", &setattr_str,
5201 "(OO)", name, value);
5202 if (res == NULL)
5203 return -1;
5204 Py_DECREF(res);
5205 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005206}
5207
Guido van Rossumf5243f02008-01-01 04:06:48 +00005208static char *name_op[] = {
5209 "__lt__",
5210 "__le__",
5211 "__eq__",
5212 "__ne__",
5213 "__gt__",
5214 "__ge__",
5215};
5216
Tim Peters6d6c1a32001-08-02 04:15:00 +00005217static PyObject *
Mark Dickinson6f1d0492009-11-15 13:58:49 +00005218slot_tp_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005219{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005220 PyObject *func, *args, *res;
5221 static PyObject *op_str[6];
Tim Peters6d6c1a32001-08-02 04:15:00 +00005222
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005223 func = lookup_method(self, name_op[op], &op_str[op]);
5224 if (func == NULL) {
5225 PyErr_Clear();
5226 Py_INCREF(Py_NotImplemented);
5227 return Py_NotImplemented;
5228 }
5229 args = PyTuple_Pack(1, other);
5230 if (args == NULL)
5231 res = NULL;
5232 else {
5233 res = PyObject_Call(func, args, NULL);
5234 Py_DECREF(args);
5235 }
5236 Py_DECREF(func);
5237 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005238}
5239
Guido van Rossumb8f63662001-08-15 23:57:02 +00005240static PyObject *
Guido van Rossumb8f63662001-08-15 23:57:02 +00005241slot_tp_iter(PyObject *self)
5242{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005243 PyObject *func, *res;
5244 static PyObject *iter_str, *getitem_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00005245
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005246 func = lookup_method(self, "__iter__", &iter_str);
5247 if (func != NULL) {
5248 PyObject *args;
5249 args = res = PyTuple_New(0);
5250 if (args != NULL) {
5251 res = PyObject_Call(func, args, NULL);
5252 Py_DECREF(args);
5253 }
5254 Py_DECREF(func);
5255 return res;
5256 }
5257 PyErr_Clear();
5258 func = lookup_method(self, "__getitem__", &getitem_str);
5259 if (func == NULL) {
5260 PyErr_Format(PyExc_TypeError,
5261 "'%.200s' object is not iterable",
5262 Py_TYPE(self)->tp_name);
5263 return NULL;
5264 }
5265 Py_DECREF(func);
5266 return PySeqIter_New(self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005267}
Tim Peters6d6c1a32001-08-02 04:15:00 +00005268
5269static PyObject *
5270slot_tp_iternext(PyObject *self)
5271{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005272 static PyObject *next_str;
5273 return call_method(self, "__next__", &next_str, "()");
Tim Peters6d6c1a32001-08-02 04:15:00 +00005274}
5275
Guido van Rossum1a493502001-08-17 16:47:50 +00005276static PyObject *
5277slot_tp_descr_get(PyObject *self, PyObject *obj, PyObject *type)
5278{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005279 PyTypeObject *tp = Py_TYPE(self);
5280 PyObject *get;
5281 static PyObject *get_str = NULL;
Guido van Rossum1a493502001-08-17 16:47:50 +00005282
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005283 if (get_str == NULL) {
5284 get_str = PyUnicode_InternFromString("__get__");
5285 if (get_str == NULL)
5286 return NULL;
5287 }
5288 get = _PyType_Lookup(tp, get_str);
5289 if (get == NULL) {
5290 /* Avoid further slowdowns */
5291 if (tp->tp_descr_get == slot_tp_descr_get)
5292 tp->tp_descr_get = NULL;
5293 Py_INCREF(self);
5294 return self;
5295 }
5296 if (obj == NULL)
5297 obj = Py_None;
5298 if (type == NULL)
5299 type = Py_None;
5300 return PyObject_CallFunctionObjArgs(get, self, obj, type, NULL);
Guido van Rossum1a493502001-08-17 16:47:50 +00005301}
Tim Peters6d6c1a32001-08-02 04:15:00 +00005302
5303static int
5304slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value)
5305{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005306 PyObject *res;
5307 static PyObject *del_str, *set_str;
Guido van Rossum2c252392001-08-24 10:13:31 +00005308
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005309 if (value == NULL)
5310 res = call_method(self, "__delete__", &del_str,
5311 "(O)", target);
5312 else
5313 res = call_method(self, "__set__", &set_str,
5314 "(OO)", target, value);
5315 if (res == NULL)
5316 return -1;
5317 Py_DECREF(res);
5318 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005319}
5320
5321static int
5322slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds)
5323{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005324 static PyObject *init_str;
5325 PyObject *meth = lookup_method(self, "__init__", &init_str);
5326 PyObject *res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005327
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005328 if (meth == NULL)
5329 return -1;
5330 res = PyObject_Call(meth, args, kwds);
5331 Py_DECREF(meth);
5332 if (res == NULL)
5333 return -1;
5334 if (res != Py_None) {
5335 PyErr_Format(PyExc_TypeError,
5336 "__init__() should return None, not '%.200s'",
5337 Py_TYPE(res)->tp_name);
5338 Py_DECREF(res);
5339 return -1;
5340 }
5341 Py_DECREF(res);
5342 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005343}
5344
5345static PyObject *
5346slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
5347{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005348 static PyObject *new_str;
5349 PyObject *func;
5350 PyObject *newargs, *x;
5351 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005352
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005353 if (new_str == NULL) {
5354 new_str = PyUnicode_InternFromString("__new__");
5355 if (new_str == NULL)
5356 return NULL;
5357 }
5358 func = PyObject_GetAttr((PyObject *)type, new_str);
5359 if (func == NULL)
5360 return NULL;
5361 assert(PyTuple_Check(args));
5362 n = PyTuple_GET_SIZE(args);
5363 newargs = PyTuple_New(n+1);
5364 if (newargs == NULL)
5365 return NULL;
5366 Py_INCREF(type);
5367 PyTuple_SET_ITEM(newargs, 0, (PyObject *)type);
5368 for (i = 0; i < n; i++) {
5369 x = PyTuple_GET_ITEM(args, i);
5370 Py_INCREF(x);
5371 PyTuple_SET_ITEM(newargs, i+1, x);
5372 }
5373 x = PyObject_Call(func, newargs, kwds);
5374 Py_DECREF(newargs);
5375 Py_DECREF(func);
5376 return x;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005377}
5378
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005379static void
5380slot_tp_del(PyObject *self)
5381{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005382 static PyObject *del_str = NULL;
5383 PyObject *del, *res;
5384 PyObject *error_type, *error_value, *error_traceback;
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005385
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005386 /* Temporarily resurrect the object. */
5387 assert(self->ob_refcnt == 0);
5388 self->ob_refcnt = 1;
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005389
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005390 /* Save the current exception, if any. */
5391 PyErr_Fetch(&error_type, &error_value, &error_traceback);
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005392
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005393 /* Execute __del__ method, if any. */
5394 del = lookup_maybe(self, "__del__", &del_str);
5395 if (del != NULL) {
5396 res = PyEval_CallObject(del, NULL);
5397 if (res == NULL)
5398 PyErr_WriteUnraisable(del);
5399 else
5400 Py_DECREF(res);
5401 Py_DECREF(del);
5402 }
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005403
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005404 /* Restore the saved exception. */
5405 PyErr_Restore(error_type, error_value, error_traceback);
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005406
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005407 /* Undo the temporary resurrection; can't use DECREF here, it would
5408 * cause a recursive call.
5409 */
5410 assert(self->ob_refcnt > 0);
5411 if (--self->ob_refcnt == 0)
5412 return; /* this is the normal path out */
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005413
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005414 /* __del__ resurrected it! Make it look like the original Py_DECREF
5415 * never happened.
5416 */
5417 {
5418 Py_ssize_t refcnt = self->ob_refcnt;
5419 _Py_NewReference(self);
5420 self->ob_refcnt = refcnt;
5421 }
5422 assert(!PyType_IS_GC(Py_TYPE(self)) ||
5423 _Py_AS_GC(self)->gc.gc_refs != _PyGC_REFS_UNTRACKED);
5424 /* If Py_REF_DEBUG, _Py_NewReference bumped _Py_RefTotal, so
5425 * we need to undo that. */
5426 _Py_DEC_REFTOTAL;
5427 /* If Py_TRACE_REFS, _Py_NewReference re-added self to the object
5428 * chain, so no more to do there.
5429 * If COUNT_ALLOCS, the original decref bumped tp_frees, and
5430 * _Py_NewReference bumped tp_allocs: both of those need to be
5431 * undone.
5432 */
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005433#ifdef COUNT_ALLOCS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005434 --Py_TYPE(self)->tp_frees;
5435 --Py_TYPE(self)->tp_allocs;
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005436#endif
5437}
5438
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005439
5440/* Table mapping __foo__ names to tp_foo offsets and slot_tp_foo wrapper
Tim Petersbf9b2442003-03-23 05:35:36 +00005441 functions. The offsets here are relative to the 'PyHeapTypeObject'
Guido van Rossume5c691a2003-03-07 15:13:17 +00005442 structure, which incorporates the additional structures used for numbers,
5443 sequences and mappings.
5444 Note that multiple names may map to the same slot (e.g. __eq__,
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005445 __ne__ etc. all map to tp_richcompare) and one name may map to multiple
Guido van Rossumc334df52002-04-04 23:44:47 +00005446 slots (e.g. __str__ affects tp_str as well as tp_repr). The table is
5447 terminated with an all-zero entry. (This table is further initialized and
5448 sorted in init_slotdefs() below.) */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005449
Guido van Rossum6d204072001-10-21 00:44:31 +00005450typedef struct wrapperbase slotdef;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005451
5452#undef TPSLOT
Guido van Rossumc8e56452001-10-22 00:43:43 +00005453#undef FLSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005454#undef ETSLOT
5455#undef SQSLOT
5456#undef MPSLOT
5457#undef NBSLOT
Guido van Rossum6d204072001-10-21 00:44:31 +00005458#undef UNSLOT
5459#undef IBSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005460#undef BINSLOT
5461#undef RBINSLOT
5462
Guido van Rossum6d204072001-10-21 00:44:31 +00005463#define TPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005464 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
5465 PyDoc_STR(DOC)}
Guido van Rossumc8e56452001-10-22 00:43:43 +00005466#define FLSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC, FLAGS) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005467 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
5468 PyDoc_STR(DOC), FLAGS}
Guido van Rossum6d204072001-10-21 00:44:31 +00005469#define ETSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005470 {NAME, offsetof(PyHeapTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
5471 PyDoc_STR(DOC)}
Guido van Rossum6d204072001-10-21 00:44:31 +00005472#define SQSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005473 ETSLOT(NAME, as_sequence.SLOT, FUNCTION, WRAPPER, DOC)
Guido van Rossum6d204072001-10-21 00:44:31 +00005474#define MPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005475 ETSLOT(NAME, as_mapping.SLOT, FUNCTION, WRAPPER, DOC)
Guido van Rossum6d204072001-10-21 00:44:31 +00005476#define NBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005477 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, DOC)
Guido van Rossum6d204072001-10-21 00:44:31 +00005478#define UNSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005479 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
5480 "x." NAME "() <==> " DOC)
Guido van Rossum6d204072001-10-21 00:44:31 +00005481#define IBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005482 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
5483 "x." NAME "(y) <==> x" DOC "y")
Guido van Rossum6d204072001-10-21 00:44:31 +00005484#define BINSLOT(NAME, SLOT, FUNCTION, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005485 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
5486 "x." NAME "(y) <==> x" DOC "y")
Guido van Rossum6d204072001-10-21 00:44:31 +00005487#define RBINSLOT(NAME, SLOT, FUNCTION, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005488 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
5489 "x." NAME "(y) <==> y" DOC "x")
Anthony Baxter56616992005-06-03 14:12:21 +00005490#define BINSLOTNOTINFIX(NAME, SLOT, FUNCTION, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005491 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
5492 "x." NAME "(y) <==> " DOC)
Anthony Baxter56616992005-06-03 14:12:21 +00005493#define RBINSLOTNOTINFIX(NAME, SLOT, FUNCTION, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005494 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
5495 "x." NAME "(y) <==> " DOC)
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005496
5497static slotdef slotdefs[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005498 SQSLOT("__len__", sq_length, slot_sq_length, wrap_lenfunc,
5499 "x.__len__() <==> len(x)"),
5500 /* Heap types defining __add__/__mul__ have sq_concat/sq_repeat == NULL.
5501 The logic in abstract.c always falls back to nb_add/nb_multiply in
5502 this case. Defining both the nb_* and the sq_* slots to call the
5503 user-defined methods has unexpected side-effects, as shown by
5504 test_descr.notimplemented() */
5505 SQSLOT("__add__", sq_concat, NULL, wrap_binaryfunc,
5506 "x.__add__(y) <==> x+y"),
5507 SQSLOT("__mul__", sq_repeat, NULL, wrap_indexargfunc,
5508 "x.__mul__(n) <==> x*n"),
5509 SQSLOT("__rmul__", sq_repeat, NULL, wrap_indexargfunc,
5510 "x.__rmul__(n) <==> n*x"),
5511 SQSLOT("__getitem__", sq_item, slot_sq_item, wrap_sq_item,
5512 "x.__getitem__(y) <==> x[y]"),
5513 SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_setitem,
5514 "x.__setitem__(i, y) <==> x[i]=y"),
5515 SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_delitem,
5516 "x.__delitem__(y) <==> del x[y]"),
5517 SQSLOT("__contains__", sq_contains, slot_sq_contains, wrap_objobjproc,
5518 "x.__contains__(y) <==> y in x"),
5519 SQSLOT("__iadd__", sq_inplace_concat, NULL,
5520 wrap_binaryfunc, "x.__iadd__(y) <==> x+=y"),
5521 SQSLOT("__imul__", sq_inplace_repeat, NULL,
5522 wrap_indexargfunc, "x.__imul__(y) <==> x*=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005523
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005524 MPSLOT("__len__", mp_length, slot_mp_length, wrap_lenfunc,
5525 "x.__len__() <==> len(x)"),
5526 MPSLOT("__getitem__", mp_subscript, slot_mp_subscript,
5527 wrap_binaryfunc,
5528 "x.__getitem__(y) <==> x[y]"),
5529 MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript,
5530 wrap_objobjargproc,
5531 "x.__setitem__(i, y) <==> x[i]=y"),
5532 MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript,
5533 wrap_delitem,
5534 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005535
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005536 BINSLOT("__add__", nb_add, slot_nb_add,
5537 "+"),
5538 RBINSLOT("__radd__", nb_add, slot_nb_add,
5539 "+"),
5540 BINSLOT("__sub__", nb_subtract, slot_nb_subtract,
5541 "-"),
5542 RBINSLOT("__rsub__", nb_subtract, slot_nb_subtract,
5543 "-"),
5544 BINSLOT("__mul__", nb_multiply, slot_nb_multiply,
5545 "*"),
5546 RBINSLOT("__rmul__", nb_multiply, slot_nb_multiply,
5547 "*"),
5548 BINSLOT("__mod__", nb_remainder, slot_nb_remainder,
5549 "%"),
5550 RBINSLOT("__rmod__", nb_remainder, slot_nb_remainder,
5551 "%"),
5552 BINSLOTNOTINFIX("__divmod__", nb_divmod, slot_nb_divmod,
5553 "divmod(x, y)"),
5554 RBINSLOTNOTINFIX("__rdivmod__", nb_divmod, slot_nb_divmod,
5555 "divmod(y, x)"),
5556 NBSLOT("__pow__", nb_power, slot_nb_power, wrap_ternaryfunc,
5557 "x.__pow__(y[, z]) <==> pow(x, y[, z])"),
5558 NBSLOT("__rpow__", nb_power, slot_nb_power, wrap_ternaryfunc_r,
5559 "y.__rpow__(x[, z]) <==> pow(x, y[, z])"),
5560 UNSLOT("__neg__", nb_negative, slot_nb_negative, wrap_unaryfunc, "-x"),
5561 UNSLOT("__pos__", nb_positive, slot_nb_positive, wrap_unaryfunc, "+x"),
5562 UNSLOT("__abs__", nb_absolute, slot_nb_absolute, wrap_unaryfunc,
5563 "abs(x)"),
5564 UNSLOT("__bool__", nb_bool, slot_nb_bool, wrap_inquirypred,
5565 "x != 0"),
5566 UNSLOT("__invert__", nb_invert, slot_nb_invert, wrap_unaryfunc, "~x"),
5567 BINSLOT("__lshift__", nb_lshift, slot_nb_lshift, "<<"),
5568 RBINSLOT("__rlshift__", nb_lshift, slot_nb_lshift, "<<"),
5569 BINSLOT("__rshift__", nb_rshift, slot_nb_rshift, ">>"),
5570 RBINSLOT("__rrshift__", nb_rshift, slot_nb_rshift, ">>"),
5571 BINSLOT("__and__", nb_and, slot_nb_and, "&"),
5572 RBINSLOT("__rand__", nb_and, slot_nb_and, "&"),
5573 BINSLOT("__xor__", nb_xor, slot_nb_xor, "^"),
5574 RBINSLOT("__rxor__", nb_xor, slot_nb_xor, "^"),
5575 BINSLOT("__or__", nb_or, slot_nb_or, "|"),
5576 RBINSLOT("__ror__", nb_or, slot_nb_or, "|"),
5577 UNSLOT("__int__", nb_int, slot_nb_int, wrap_unaryfunc,
5578 "int(x)"),
5579 UNSLOT("__float__", nb_float, slot_nb_float, wrap_unaryfunc,
5580 "float(x)"),
5581 NBSLOT("__index__", nb_index, slot_nb_index, wrap_unaryfunc,
5582 "x[y:z] <==> x[y.__index__():z.__index__()]"),
5583 IBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add,
Eli Benderskyd3baae72011-11-11 16:57:05 +02005584 wrap_binaryfunc, "+="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005585 IBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract,
Eli Benderskyd3baae72011-11-11 16:57:05 +02005586 wrap_binaryfunc, "-="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005587 IBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply,
Eli Benderskyd3baae72011-11-11 16:57:05 +02005588 wrap_binaryfunc, "*="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005589 IBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder,
Eli Benderskyd3baae72011-11-11 16:57:05 +02005590 wrap_binaryfunc, "%="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005591 IBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power,
Eli Benderskyd3baae72011-11-11 16:57:05 +02005592 wrap_binaryfunc, "**="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005593 IBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift,
Eli Benderskyd3baae72011-11-11 16:57:05 +02005594 wrap_binaryfunc, "<<="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005595 IBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift,
Eli Benderskyd3baae72011-11-11 16:57:05 +02005596 wrap_binaryfunc, ">>="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005597 IBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and,
Eli Benderskyd3baae72011-11-11 16:57:05 +02005598 wrap_binaryfunc, "&="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005599 IBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor,
Eli Benderskyd3baae72011-11-11 16:57:05 +02005600 wrap_binaryfunc, "^="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005601 IBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or,
Eli Benderskyd3baae72011-11-11 16:57:05 +02005602 wrap_binaryfunc, "|="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005603 BINSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
5604 RBINSLOT("__rfloordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
5605 BINSLOT("__truediv__", nb_true_divide, slot_nb_true_divide, "/"),
5606 RBINSLOT("__rtruediv__", nb_true_divide, slot_nb_true_divide, "/"),
5607 IBSLOT("__ifloordiv__", nb_inplace_floor_divide,
5608 slot_nb_inplace_floor_divide, wrap_binaryfunc, "//"),
5609 IBSLOT("__itruediv__", nb_inplace_true_divide,
5610 slot_nb_inplace_true_divide, wrap_binaryfunc, "/"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005611
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005612 TPSLOT("__str__", tp_str, slot_tp_str, wrap_unaryfunc,
5613 "x.__str__() <==> str(x)"),
5614 TPSLOT("__repr__", tp_repr, slot_tp_repr, wrap_unaryfunc,
5615 "x.__repr__() <==> repr(x)"),
5616 TPSLOT("__hash__", tp_hash, slot_tp_hash, wrap_hashfunc,
5617 "x.__hash__() <==> hash(x)"),
5618 FLSLOT("__call__", tp_call, slot_tp_call, (wrapperfunc)wrap_call,
5619 "x.__call__(...) <==> x(...)", PyWrapperFlag_KEYWORDS),
5620 TPSLOT("__getattribute__", tp_getattro, slot_tp_getattr_hook,
5621 wrap_binaryfunc, "x.__getattribute__('name') <==> x.name"),
5622 TPSLOT("__getattribute__", tp_getattr, NULL, NULL, ""),
5623 TPSLOT("__getattr__", tp_getattro, slot_tp_getattr_hook, NULL, ""),
5624 TPSLOT("__getattr__", tp_getattr, NULL, NULL, ""),
5625 TPSLOT("__setattr__", tp_setattro, slot_tp_setattro, wrap_setattr,
5626 "x.__setattr__('name', value) <==> x.name = value"),
5627 TPSLOT("__setattr__", tp_setattr, NULL, NULL, ""),
5628 TPSLOT("__delattr__", tp_setattro, slot_tp_setattro, wrap_delattr,
5629 "x.__delattr__('name') <==> del x.name"),
5630 TPSLOT("__delattr__", tp_setattr, NULL, NULL, ""),
5631 TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare, richcmp_lt,
5632 "x.__lt__(y) <==> x<y"),
5633 TPSLOT("__le__", tp_richcompare, slot_tp_richcompare, richcmp_le,
5634 "x.__le__(y) <==> x<=y"),
5635 TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare, richcmp_eq,
5636 "x.__eq__(y) <==> x==y"),
5637 TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare, richcmp_ne,
5638 "x.__ne__(y) <==> x!=y"),
5639 TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare, richcmp_gt,
5640 "x.__gt__(y) <==> x>y"),
5641 TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare, richcmp_ge,
5642 "x.__ge__(y) <==> x>=y"),
5643 TPSLOT("__iter__", tp_iter, slot_tp_iter, wrap_unaryfunc,
5644 "x.__iter__() <==> iter(x)"),
5645 TPSLOT("__next__", tp_iternext, slot_tp_iternext, wrap_next,
5646 "x.__next__() <==> next(x)"),
5647 TPSLOT("__get__", tp_descr_get, slot_tp_descr_get, wrap_descr_get,
5648 "descr.__get__(obj[, type]) -> value"),
5649 TPSLOT("__set__", tp_descr_set, slot_tp_descr_set, wrap_descr_set,
5650 "descr.__set__(obj, value)"),
5651 TPSLOT("__delete__", tp_descr_set, slot_tp_descr_set,
5652 wrap_descr_delete, "descr.__delete__(obj)"),
5653 FLSLOT("__init__", tp_init, slot_tp_init, (wrapperfunc)wrap_init,
5654 "x.__init__(...) initializes x; "
Alexander Belopolsky977a6842010-08-16 20:17:07 +00005655 "see help(type(x)) for signature",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005656 PyWrapperFlag_KEYWORDS),
5657 TPSLOT("__new__", tp_new, slot_tp_new, NULL, ""),
5658 TPSLOT("__del__", tp_del, slot_tp_del, NULL, ""),
5659 {NULL}
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005660};
5661
Guido van Rossumc334df52002-04-04 23:44:47 +00005662/* Given a type pointer and an offset gotten from a slotdef entry, return a
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005663 pointer to the actual slot. This is not quite the same as simply adding
Guido van Rossumc334df52002-04-04 23:44:47 +00005664 the offset to the type pointer, since it takes care to indirect through the
5665 proper indirection pointer (as_buffer, etc.); it returns NULL if the
5666 indirection pointer is NULL. */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005667static void **
Martin v. Löwis18e16552006-02-15 17:27:45 +00005668slotptr(PyTypeObject *type, int ioffset)
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005669{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005670 char *ptr;
5671 long offset = ioffset;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005672
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005673 /* Note: this depends on the order of the members of PyHeapTypeObject! */
5674 assert(offset >= 0);
5675 assert((size_t)offset < offsetof(PyHeapTypeObject, as_buffer));
5676 if ((size_t)offset >= offsetof(PyHeapTypeObject, as_sequence)) {
5677 ptr = (char *)type->tp_as_sequence;
5678 offset -= offsetof(PyHeapTypeObject, as_sequence);
5679 }
5680 else if ((size_t)offset >= offsetof(PyHeapTypeObject, as_mapping)) {
5681 ptr = (char *)type->tp_as_mapping;
5682 offset -= offsetof(PyHeapTypeObject, as_mapping);
5683 }
5684 else if ((size_t)offset >= offsetof(PyHeapTypeObject, as_number)) {
5685 ptr = (char *)type->tp_as_number;
5686 offset -= offsetof(PyHeapTypeObject, as_number);
5687 }
5688 else {
5689 ptr = (char *)type;
5690 }
5691 if (ptr != NULL)
5692 ptr += offset;
5693 return (void **)ptr;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005694}
Guido van Rossumf040ede2001-08-07 16:40:56 +00005695
Guido van Rossumc334df52002-04-04 23:44:47 +00005696/* Length of array of slotdef pointers used to store slots with the
5697 same __name__. There should be at most MAX_EQUIV-1 slotdef entries with
5698 the same __name__, for any __name__. Since that's a static property, it is
5699 appropriate to declare fixed-size arrays for this. */
5700#define MAX_EQUIV 10
5701
5702/* Return a slot pointer for a given name, but ONLY if the attribute has
5703 exactly one slot function. The name must be an interned string. */
5704static void **
5705resolve_slotdups(PyTypeObject *type, PyObject *name)
5706{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005707 /* XXX Maybe this could be optimized more -- but is it worth it? */
Guido van Rossumc334df52002-04-04 23:44:47 +00005708
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005709 /* pname and ptrs act as a little cache */
5710 static PyObject *pname;
5711 static slotdef *ptrs[MAX_EQUIV];
5712 slotdef *p, **pp;
5713 void **res, **ptr;
Guido van Rossumc334df52002-04-04 23:44:47 +00005714
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005715 if (pname != name) {
5716 /* Collect all slotdefs that match name into ptrs. */
5717 pname = name;
5718 pp = ptrs;
5719 for (p = slotdefs; p->name_strobj; p++) {
5720 if (p->name_strobj == name)
5721 *pp++ = p;
5722 }
5723 *pp = NULL;
5724 }
Guido van Rossumc334df52002-04-04 23:44:47 +00005725
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005726 /* Look in all matching slots of the type; if exactly one of these has
5727 a filled-in slot, return its value. Otherwise return NULL. */
5728 res = NULL;
5729 for (pp = ptrs; *pp; pp++) {
5730 ptr = slotptr(type, (*pp)->offset);
5731 if (ptr == NULL || *ptr == NULL)
5732 continue;
5733 if (res != NULL)
5734 return NULL;
5735 res = ptr;
5736 }
5737 return res;
Guido van Rossumc334df52002-04-04 23:44:47 +00005738}
5739
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005740/* Common code for update_slots_callback() and fixup_slot_dispatchers(). This
Guido van Rossumc334df52002-04-04 23:44:47 +00005741 does some incredibly complex thinking and then sticks something into the
5742 slot. (It sees if the adjacent slotdefs for the same slot have conflicting
5743 interests, and then stores a generic wrapper or a specific function into
5744 the slot.) Return a pointer to the next slotdef with a different offset,
5745 because that's convenient for fixup_slot_dispatchers(). */
5746static slotdef *
5747update_one_slot(PyTypeObject *type, slotdef *p)
5748{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005749 PyObject *descr;
5750 PyWrapperDescrObject *d;
5751 void *generic = NULL, *specific = NULL;
5752 int use_generic = 0;
5753 int offset = p->offset;
5754 void **ptr = slotptr(type, offset);
Guido van Rossumc334df52002-04-04 23:44:47 +00005755
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005756 if (ptr == NULL) {
5757 do {
5758 ++p;
5759 } while (p->offset == offset);
5760 return p;
5761 }
5762 do {
5763 descr = _PyType_Lookup(type, p->name_strobj);
5764 if (descr == NULL) {
5765 if (ptr == (void**)&type->tp_iternext) {
5766 specific = _PyObject_NextNotImplemented;
5767 }
5768 continue;
5769 }
Benjamin Peterson7b166872012-04-24 11:06:25 -04005770 if (Py_TYPE(descr) == &PyWrapperDescr_Type &&
5771 ((PyWrapperDescrObject *)descr)->d_base->name_strobj == p->name_strobj) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005772 void **tptr = resolve_slotdups(type, p->name_strobj);
5773 if (tptr == NULL || tptr == ptr)
5774 generic = p->function;
5775 d = (PyWrapperDescrObject *)descr;
5776 if (d->d_base->wrapper == p->wrapper &&
5777 PyType_IsSubtype(type, PyDescr_TYPE(d)))
5778 {
5779 if (specific == NULL ||
5780 specific == d->d_wrapped)
5781 specific = d->d_wrapped;
5782 else
5783 use_generic = 1;
5784 }
5785 }
5786 else if (Py_TYPE(descr) == &PyCFunction_Type &&
5787 PyCFunction_GET_FUNCTION(descr) ==
5788 (PyCFunction)tp_new_wrapper &&
5789 ptr == (void**)&type->tp_new)
5790 {
5791 /* The __new__ wrapper is not a wrapper descriptor,
5792 so must be special-cased differently.
5793 If we don't do this, creating an instance will
5794 always use slot_tp_new which will look up
5795 __new__ in the MRO which will call tp_new_wrapper
5796 which will look through the base classes looking
5797 for a static base and call its tp_new (usually
5798 PyType_GenericNew), after performing various
5799 sanity checks and constructing a new argument
5800 list. Cut all that nonsense short -- this speeds
5801 up instance creation tremendously. */
5802 specific = (void *)type->tp_new;
5803 /* XXX I'm not 100% sure that there isn't a hole
5804 in this reasoning that requires additional
5805 sanity checks. I'll buy the first person to
5806 point out a bug in this reasoning a beer. */
5807 }
5808 else if (descr == Py_None &&
5809 ptr == (void**)&type->tp_hash) {
5810 /* We specifically allow __hash__ to be set to None
5811 to prevent inheritance of the default
5812 implementation from object.__hash__ */
5813 specific = PyObject_HashNotImplemented;
5814 }
5815 else {
5816 use_generic = 1;
5817 generic = p->function;
5818 }
5819 } while ((++p)->offset == offset);
5820 if (specific && !use_generic)
5821 *ptr = specific;
5822 else
5823 *ptr = generic;
5824 return p;
Guido van Rossumc334df52002-04-04 23:44:47 +00005825}
5826
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005827/* In the type, update the slots whose slotdefs are gathered in the pp array.
5828 This is a callback for update_subclasses(). */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005829static int
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005830update_slots_callback(PyTypeObject *type, void *data)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005831{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005832 slotdef **pp = (slotdef **)data;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005833
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005834 for (; *pp; pp++)
5835 update_one_slot(type, *pp);
5836 return 0;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005837}
5838
Guido van Rossumc334df52002-04-04 23:44:47 +00005839/* Comparison function for qsort() to compare slotdefs by their offset, and
5840 for equal offset by their address (to force a stable sort). */
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005841static int
5842slotdef_cmp(const void *aa, const void *bb)
5843{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005844 const slotdef *a = (const slotdef *)aa, *b = (const slotdef *)bb;
5845 int c = a->offset - b->offset;
5846 if (c != 0)
5847 return c;
5848 else
5849 /* Cannot use a-b, as this gives off_t,
5850 which may lose precision when converted to int. */
5851 return (a > b) ? 1 : (a < b) ? -1 : 0;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005852}
5853
Guido van Rossumc334df52002-04-04 23:44:47 +00005854/* Initialize the slotdefs table by adding interned string objects for the
5855 names and sorting the entries. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005856static void
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005857init_slotdefs(void)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005858{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005859 slotdef *p;
5860 static int initialized = 0;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005861
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005862 if (initialized)
5863 return;
5864 for (p = slotdefs; p->name; p++) {
5865 p->name_strobj = PyUnicode_InternFromString(p->name);
5866 if (!p->name_strobj)
5867 Py_FatalError("Out of memory interning slotdef names");
5868 }
5869 qsort((void *)slotdefs, (size_t)(p-slotdefs), sizeof(slotdef),
5870 slotdef_cmp);
5871 initialized = 1;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005872}
5873
Guido van Rossumc334df52002-04-04 23:44:47 +00005874/* Update the slots after assignment to a class (type) attribute. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005875static int
5876update_slot(PyTypeObject *type, PyObject *name)
5877{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005878 slotdef *ptrs[MAX_EQUIV];
5879 slotdef *p;
5880 slotdef **pp;
5881 int offset;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005882
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005883 /* Clear the VALID_VERSION flag of 'type' and all its
5884 subclasses. This could possibly be unified with the
5885 update_subclasses() recursion below, but carefully:
5886 they each have their own conditions on which to stop
5887 recursing into subclasses. */
5888 PyType_Modified(type);
Christian Heimesa62da1d2008-01-12 19:39:10 +00005889
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005890 init_slotdefs();
5891 pp = ptrs;
5892 for (p = slotdefs; p->name; p++) {
5893 /* XXX assume name is interned! */
5894 if (p->name_strobj == name)
5895 *pp++ = p;
5896 }
5897 *pp = NULL;
5898 for (pp = ptrs; *pp; pp++) {
5899 p = *pp;
5900 offset = p->offset;
5901 while (p > slotdefs && (p-1)->offset == offset)
5902 --p;
5903 *pp = p;
5904 }
5905 if (ptrs[0] == NULL)
5906 return 0; /* Not an attribute that affects any slots */
5907 return update_subclasses(type, name,
5908 update_slots_callback, (void *)ptrs);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005909}
5910
Guido van Rossumc334df52002-04-04 23:44:47 +00005911/* Store the proper functions in the slot dispatches at class (type)
5912 definition time, based upon which operations the class overrides in its
5913 dict. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00005914static void
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005915fixup_slot_dispatchers(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005916{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005917 slotdef *p;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005918
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005919 init_slotdefs();
5920 for (p = slotdefs; p->name; )
5921 p = update_one_slot(type, p);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005922}
Guido van Rossum705f0f52001-08-24 16:47:00 +00005923
Michael W. Hudson98bbc492002-11-26 14:47:27 +00005924static void
5925update_all_slots(PyTypeObject* type)
5926{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005927 slotdef *p;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00005928
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005929 init_slotdefs();
5930 for (p = slotdefs; p->name; p++) {
5931 /* update_slot returns int but can't actually fail */
5932 update_slot(type, p->name_strobj);
5933 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +00005934}
5935
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005936/* recurse_down_subclasses() and update_subclasses() are mutually
5937 recursive functions to call a callback for all subclasses,
5938 but refraining from recursing into subclasses that define 'name'. */
5939
5940static int
5941update_subclasses(PyTypeObject *type, PyObject *name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005942 update_callback callback, void *data)
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005943{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005944 if (callback(type, data) < 0)
5945 return -1;
5946 return recurse_down_subclasses(type, name, callback, data);
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005947}
5948
5949static int
5950recurse_down_subclasses(PyTypeObject *type, PyObject *name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005951 update_callback callback, void *data)
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005952{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005953 PyTypeObject *subclass;
5954 PyObject *ref, *subclasses, *dict;
5955 Py_ssize_t i, n;
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005956
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005957 subclasses = type->tp_subclasses;
5958 if (subclasses == NULL)
5959 return 0;
5960 assert(PyList_Check(subclasses));
5961 n = PyList_GET_SIZE(subclasses);
5962 for (i = 0; i < n; i++) {
5963 ref = PyList_GET_ITEM(subclasses, i);
5964 assert(PyWeakref_CheckRef(ref));
5965 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
5966 assert(subclass != NULL);
5967 if ((PyObject *)subclass == Py_None)
5968 continue;
5969 assert(PyType_Check(subclass));
5970 /* Avoid recursing down into unaffected classes */
5971 dict = subclass->tp_dict;
5972 if (dict != NULL && PyDict_Check(dict) &&
5973 PyDict_GetItem(dict, name) != NULL)
5974 continue;
5975 if (update_subclasses(subclass, name, callback, data) < 0)
5976 return -1;
5977 }
5978 return 0;
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005979}
5980
Guido van Rossum6d204072001-10-21 00:44:31 +00005981/* This function is called by PyType_Ready() to populate the type's
5982 dictionary with method descriptors for function slots. For each
Guido van Rossum09638c12002-06-13 19:17:46 +00005983 function slot (like tp_repr) that's defined in the type, one or more
5984 corresponding descriptors are added in the type's tp_dict dictionary
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005985 under the appropriate name (like __repr__). Some function slots
Guido van Rossum09638c12002-06-13 19:17:46 +00005986 cause more than one descriptor to be added (for example, the nb_add
5987 slot adds both __add__ and __radd__ descriptors) and some function
5988 slots compete for the same descriptor (for example both sq_item and
5989 mp_subscript generate a __getitem__ descriptor).
5990
Ezio Melotti13925002011-03-16 11:05:33 +02005991 In the latter case, the first slotdef entry encountered wins. Since
Tim Petersbf9b2442003-03-23 05:35:36 +00005992 slotdef entries are sorted by the offset of the slot in the
Guido van Rossume5c691a2003-03-07 15:13:17 +00005993 PyHeapTypeObject, this gives us some control over disambiguating
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005994 between competing slots: the members of PyHeapTypeObject are listed
5995 from most general to least general, so the most general slot is
5996 preferred. In particular, because as_mapping comes before as_sequence,
5997 for a type that defines both mp_subscript and sq_item, mp_subscript
5998 wins.
Guido van Rossum09638c12002-06-13 19:17:46 +00005999
6000 This only adds new descriptors and doesn't overwrite entries in
6001 tp_dict that were previously defined. The descriptors contain a
6002 reference to the C function they must call, so that it's safe if they
6003 are copied into a subtype's __dict__ and the subtype has a different
6004 C function in its slot -- calling the method defined by the
6005 descriptor will call the C function that was used to create it,
6006 rather than the C function present in the slot when it is called.
6007 (This is important because a subtype may have a C function in the
6008 slot that calls the method from the dictionary, and we want to avoid
6009 infinite recursion here.) */
Guido van Rossum6d204072001-10-21 00:44:31 +00006010
6011static int
6012add_operators(PyTypeObject *type)
6013{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006014 PyObject *dict = type->tp_dict;
6015 slotdef *p;
6016 PyObject *descr;
6017 void **ptr;
Guido van Rossum6d204072001-10-21 00:44:31 +00006018
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006019 init_slotdefs();
6020 for (p = slotdefs; p->name; p++) {
6021 if (p->wrapper == NULL)
6022 continue;
6023 ptr = slotptr(type, p->offset);
6024 if (!ptr || !*ptr)
6025 continue;
6026 if (PyDict_GetItem(dict, p->name_strobj))
6027 continue;
6028 if (*ptr == PyObject_HashNotImplemented) {
6029 /* Classes may prevent the inheritance of the tp_hash
6030 slot by storing PyObject_HashNotImplemented in it. Make it
6031 visible as a None value for the __hash__ attribute. */
6032 if (PyDict_SetItem(dict, p->name_strobj, Py_None) < 0)
6033 return -1;
6034 }
6035 else {
6036 descr = PyDescr_NewWrapper(type, p, *ptr);
6037 if (descr == NULL)
6038 return -1;
6039 if (PyDict_SetItem(dict, p->name_strobj, descr) < 0)
6040 return -1;
6041 Py_DECREF(descr);
6042 }
6043 }
6044 if (type->tp_new != NULL) {
6045 if (add_tp_new_wrapper(type) < 0)
6046 return -1;
6047 }
6048 return 0;
Guido van Rossum6d204072001-10-21 00:44:31 +00006049}
6050
Guido van Rossum705f0f52001-08-24 16:47:00 +00006051
6052/* Cooperative 'super' */
6053
6054typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006055 PyObject_HEAD
6056 PyTypeObject *type;
6057 PyObject *obj;
6058 PyTypeObject *obj_type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006059} superobject;
6060
Guido van Rossum6f799372001-09-20 20:46:19 +00006061static PyMemberDef super_members[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006062 {"__thisclass__", T_OBJECT, offsetof(superobject, type), READONLY,
6063 "the class invoking super()"},
6064 {"__self__", T_OBJECT, offsetof(superobject, obj), READONLY,
6065 "the instance invoking super(); may be None"},
6066 {"__self_class__", T_OBJECT, offsetof(superobject, obj_type), READONLY,
6067 "the type of the instance invoking super(); may be None"},
6068 {0}
Guido van Rossum41eb14d2001-08-30 23:13:11 +00006069};
6070
Guido van Rossum705f0f52001-08-24 16:47:00 +00006071static void
6072super_dealloc(PyObject *self)
6073{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006074 superobject *su = (superobject *)self;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006075
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006076 _PyObject_GC_UNTRACK(self);
6077 Py_XDECREF(su->obj);
6078 Py_XDECREF(su->type);
6079 Py_XDECREF(su->obj_type);
6080 Py_TYPE(self)->tp_free(self);
Guido van Rossum705f0f52001-08-24 16:47:00 +00006081}
6082
6083static PyObject *
Guido van Rossum41eb14d2001-08-30 23:13:11 +00006084super_repr(PyObject *self)
6085{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006086 superobject *su = (superobject *)self;
Guido van Rossum41eb14d2001-08-30 23:13:11 +00006087
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006088 if (su->obj_type)
6089 return PyUnicode_FromFormat(
6090 "<super: <class '%s'>, <%s object>>",
6091 su->type ? su->type->tp_name : "NULL",
6092 su->obj_type->tp_name);
6093 else
6094 return PyUnicode_FromFormat(
6095 "<super: <class '%s'>, NULL>",
6096 su->type ? su->type->tp_name : "NULL");
Guido van Rossum41eb14d2001-08-30 23:13:11 +00006097}
6098
6099static PyObject *
Guido van Rossum705f0f52001-08-24 16:47:00 +00006100super_getattro(PyObject *self, PyObject *name)
6101{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006102 superobject *su = (superobject *)self;
6103 int skip = su->obj_type == NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006104
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006105 if (!skip) {
6106 /* We want __class__ to return the class of the super object
6107 (i.e. super, or a subclass), not the class of su->obj. */
6108 skip = (PyUnicode_Check(name) &&
6109 PyUnicode_GET_SIZE(name) == 9 &&
6110 PyUnicode_CompareWithASCIIString(name, "__class__") == 0);
6111 }
Guido van Rossum76ba09f2003-04-16 19:40:58 +00006112
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006113 if (!skip) {
6114 PyObject *mro, *res, *tmp, *dict;
6115 PyTypeObject *starttype;
6116 descrgetfunc f;
6117 Py_ssize_t i, n;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006118
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006119 starttype = su->obj_type;
6120 mro = starttype->tp_mro;
Guido van Rossum155db9a2002-04-02 17:53:47 +00006121
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006122 if (mro == NULL)
6123 n = 0;
6124 else {
6125 assert(PyTuple_Check(mro));
6126 n = PyTuple_GET_SIZE(mro);
6127 }
6128 for (i = 0; i < n; i++) {
6129 if ((PyObject *)(su->type) == PyTuple_GET_ITEM(mro, i))
6130 break;
6131 }
6132 i++;
6133 res = NULL;
6134 for (; i < n; i++) {
6135 tmp = PyTuple_GET_ITEM(mro, i);
6136 if (PyType_Check(tmp))
6137 dict = ((PyTypeObject *)tmp)->tp_dict;
6138 else
6139 continue;
6140 res = PyDict_GetItem(dict, name);
6141 if (res != NULL) {
6142 Py_INCREF(res);
6143 f = Py_TYPE(res)->tp_descr_get;
6144 if (f != NULL) {
6145 tmp = f(res,
6146 /* Only pass 'obj' param if
6147 this is instance-mode super
6148 (See SF ID #743627)
6149 */
6150 (su->obj == (PyObject *)
6151 su->obj_type
6152 ? (PyObject *)NULL
6153 : su->obj),
6154 (PyObject *)starttype);
6155 Py_DECREF(res);
6156 res = tmp;
6157 }
6158 return res;
6159 }
6160 }
6161 }
6162 return PyObject_GenericGetAttr(self, name);
Guido van Rossum705f0f52001-08-24 16:47:00 +00006163}
6164
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006165static PyTypeObject *
Guido van Rossum5b443c62001-12-03 15:38:28 +00006166supercheck(PyTypeObject *type, PyObject *obj)
6167{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006168 /* Check that a super() call makes sense. Return a type object.
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006169
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006170 obj can be a new-style class, or an instance of one:
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006171
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006172 - If it is a class, it must be a subclass of 'type'. This case is
6173 used for class methods; the return value is obj.
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006174
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006175 - If it is an instance, it must be an instance of 'type'. This is
6176 the normal case; the return value is obj.__class__.
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006177
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006178 But... when obj is an instance, we want to allow for the case where
6179 Py_TYPE(obj) is not a subclass of type, but obj.__class__ is!
6180 This will allow using super() with a proxy for obj.
6181 */
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006182
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006183 /* Check for first bullet above (special case) */
6184 if (PyType_Check(obj) && PyType_IsSubtype((PyTypeObject *)obj, type)) {
6185 Py_INCREF(obj);
6186 return (PyTypeObject *)obj;
6187 }
Guido van Rossum8e80a722003-02-18 19:22:22 +00006188
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006189 /* Normal case */
6190 if (PyType_IsSubtype(Py_TYPE(obj), type)) {
6191 Py_INCREF(Py_TYPE(obj));
6192 return Py_TYPE(obj);
6193 }
6194 else {
6195 /* Try the slow way */
6196 static PyObject *class_str = NULL;
6197 PyObject *class_attr;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006198
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006199 if (class_str == NULL) {
6200 class_str = PyUnicode_FromString("__class__");
6201 if (class_str == NULL)
6202 return NULL;
6203 }
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006204
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006205 class_attr = PyObject_GetAttr(obj, class_str);
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006206
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006207 if (class_attr != NULL &&
6208 PyType_Check(class_attr) &&
6209 (PyTypeObject *)class_attr != Py_TYPE(obj))
6210 {
6211 int ok = PyType_IsSubtype(
6212 (PyTypeObject *)class_attr, type);
6213 if (ok)
6214 return (PyTypeObject *)class_attr;
6215 }
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006216
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006217 if (class_attr == NULL)
6218 PyErr_Clear();
6219 else
6220 Py_DECREF(class_attr);
6221 }
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006222
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006223 PyErr_SetString(PyExc_TypeError,
6224 "super(type, obj): "
6225 "obj must be an instance or subtype of type");
6226 return NULL;
Guido van Rossum5b443c62001-12-03 15:38:28 +00006227}
6228
Guido van Rossum705f0f52001-08-24 16:47:00 +00006229static PyObject *
6230super_descr_get(PyObject *self, PyObject *obj, PyObject *type)
6231{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006232 superobject *su = (superobject *)self;
6233 superobject *newobj;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006234
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006235 if (obj == NULL || obj == Py_None || su->obj != NULL) {
6236 /* Not binding to an object, or already bound */
6237 Py_INCREF(self);
6238 return self;
6239 }
6240 if (Py_TYPE(su) != &PySuper_Type)
6241 /* If su is an instance of a (strict) subclass of super,
6242 call its type */
6243 return PyObject_CallFunctionObjArgs((PyObject *)Py_TYPE(su),
6244 su->type, obj, NULL);
6245 else {
6246 /* Inline the common case */
6247 PyTypeObject *obj_type = supercheck(su->type, obj);
6248 if (obj_type == NULL)
6249 return NULL;
6250 newobj = (superobject *)PySuper_Type.tp_new(&PySuper_Type,
6251 NULL, NULL);
6252 if (newobj == NULL)
6253 return NULL;
6254 Py_INCREF(su->type);
6255 Py_INCREF(obj);
6256 newobj->type = su->type;
6257 newobj->obj = obj;
6258 newobj->obj_type = obj_type;
6259 return (PyObject *)newobj;
6260 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00006261}
6262
6263static int
6264super_init(PyObject *self, PyObject *args, PyObject *kwds)
6265{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006266 superobject *su = (superobject *)self;
6267 PyTypeObject *type = NULL;
6268 PyObject *obj = NULL;
6269 PyTypeObject *obj_type = NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006270
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006271 if (!_PyArg_NoKeywords("super", kwds))
6272 return -1;
6273 if (!PyArg_ParseTuple(args, "|O!O:super", &PyType_Type, &type, &obj))
6274 return -1;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00006275
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006276 if (type == NULL) {
6277 /* Call super(), without args -- fill in from __class__
6278 and first local variable on the stack. */
6279 PyFrameObject *f = PyThreadState_GET()->frame;
6280 PyCodeObject *co = f->f_code;
Victor Stinner0fcab4a2011-01-04 12:59:15 +00006281 Py_ssize_t i, n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006282 if (co == NULL) {
6283 PyErr_SetString(PyExc_SystemError,
6284 "super(): no code object");
6285 return -1;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00006286 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006287 if (co->co_argcount == 0) {
6288 PyErr_SetString(PyExc_SystemError,
6289 "super(): no arguments");
6290 return -1;
6291 }
6292 obj = f->f_localsplus[0];
6293 if (obj == NULL) {
6294 PyErr_SetString(PyExc_SystemError,
6295 "super(): arg[0] deleted");
6296 return -1;
6297 }
6298 if (co->co_freevars == NULL)
6299 n = 0;
6300 else {
6301 assert(PyTuple_Check(co->co_freevars));
6302 n = PyTuple_GET_SIZE(co->co_freevars);
6303 }
6304 for (i = 0; i < n; i++) {
6305 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
6306 assert(PyUnicode_Check(name));
6307 if (!PyUnicode_CompareWithASCIIString(name,
6308 "__class__")) {
6309 Py_ssize_t index = co->co_nlocals +
6310 PyTuple_GET_SIZE(co->co_cellvars) + i;
6311 PyObject *cell = f->f_localsplus[index];
6312 if (cell == NULL || !PyCell_Check(cell)) {
6313 PyErr_SetString(PyExc_SystemError,
6314 "super(): bad __class__ cell");
6315 return -1;
6316 }
6317 type = (PyTypeObject *) PyCell_GET(cell);
6318 if (type == NULL) {
6319 PyErr_SetString(PyExc_SystemError,
6320 "super(): empty __class__ cell");
6321 return -1;
6322 }
6323 if (!PyType_Check(type)) {
6324 PyErr_Format(PyExc_SystemError,
6325 "super(): __class__ is not a type (%s)",
6326 Py_TYPE(type)->tp_name);
6327 return -1;
6328 }
6329 break;
6330 }
6331 }
6332 if (type == NULL) {
6333 PyErr_SetString(PyExc_SystemError,
6334 "super(): __class__ cell not found");
6335 return -1;
6336 }
6337 }
Guido van Rossumcd16bf62007-06-13 18:07:49 +00006338
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006339 if (obj == Py_None)
6340 obj = NULL;
6341 if (obj != NULL) {
6342 obj_type = supercheck(type, obj);
6343 if (obj_type == NULL)
6344 return -1;
6345 Py_INCREF(obj);
6346 }
6347 Py_INCREF(type);
6348 su->type = type;
6349 su->obj = obj;
6350 su->obj_type = obj_type;
6351 return 0;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006352}
6353
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00006354PyDoc_STRVAR(super_doc,
Guido van Rossumcd16bf62007-06-13 18:07:49 +00006355"super() -> same as super(__class__, <first argument>)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00006356"super(type) -> unbound super object\n"
6357"super(type, obj) -> bound super object; requires isinstance(obj, type)\n"
Guido van Rossume705ef12001-08-29 15:47:06 +00006358"super(type, type2) -> bound super object; requires issubclass(type2, type)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00006359"Typical use to call a cooperative superclass method:\n"
6360"class C(B):\n"
6361" def meth(self, arg):\n"
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006362" super().meth(arg)\n"
Guido van Rossumcd16bf62007-06-13 18:07:49 +00006363"This works for class methods too:\n"
6364"class C(B):\n"
6365" @classmethod\n"
6366" def cmeth(cls, arg):\n"
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006367" super().cmeth(arg)\n");
Guido van Rossum705f0f52001-08-24 16:47:00 +00006368
Guido van Rossum048eb752001-10-02 21:24:57 +00006369static int
6370super_traverse(PyObject *self, visitproc visit, void *arg)
6371{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006372 superobject *su = (superobject *)self;
Guido van Rossum048eb752001-10-02 21:24:57 +00006373
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006374 Py_VISIT(su->obj);
6375 Py_VISIT(su->type);
6376 Py_VISIT(su->obj_type);
Guido van Rossum048eb752001-10-02 21:24:57 +00006377
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006378 return 0;
Guido van Rossum048eb752001-10-02 21:24:57 +00006379}
6380
Guido van Rossum705f0f52001-08-24 16:47:00 +00006381PyTypeObject PySuper_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006382 PyVarObject_HEAD_INIT(&PyType_Type, 0)
6383 "super", /* tp_name */
6384 sizeof(superobject), /* tp_basicsize */
6385 0, /* tp_itemsize */
6386 /* methods */
6387 super_dealloc, /* tp_dealloc */
6388 0, /* tp_print */
6389 0, /* tp_getattr */
6390 0, /* tp_setattr */
6391 0, /* tp_reserved */
6392 super_repr, /* tp_repr */
6393 0, /* tp_as_number */
6394 0, /* tp_as_sequence */
6395 0, /* tp_as_mapping */
6396 0, /* tp_hash */
6397 0, /* tp_call */
6398 0, /* tp_str */
6399 super_getattro, /* tp_getattro */
6400 0, /* tp_setattro */
6401 0, /* tp_as_buffer */
6402 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
6403 Py_TPFLAGS_BASETYPE, /* tp_flags */
6404 super_doc, /* tp_doc */
6405 super_traverse, /* tp_traverse */
6406 0, /* tp_clear */
6407 0, /* tp_richcompare */
6408 0, /* tp_weaklistoffset */
6409 0, /* tp_iter */
6410 0, /* tp_iternext */
6411 0, /* tp_methods */
6412 super_members, /* tp_members */
6413 0, /* tp_getset */
6414 0, /* tp_base */
6415 0, /* tp_dict */
6416 super_descr_get, /* tp_descr_get */
6417 0, /* tp_descr_set */
6418 0, /* tp_dictoffset */
6419 super_init, /* tp_init */
6420 PyType_GenericAlloc, /* tp_alloc */
6421 PyType_GenericNew, /* tp_new */
6422 PyObject_GC_Del, /* tp_free */
Guido van Rossum705f0f52001-08-24 16:47:00 +00006423};