blob: 02f86ef22b88b052f411a0f089e9e56ec2158249 [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 */
Benjamin Peterson477ba912011-01-12 15:34:01 +0000343 int res;
344 if (value != NULL) {
345 res = PyDict_SetItemString(type->tp_dict, "__abstractmethods__", value);
346 }
347 else {
348 res = PyDict_DelItemString(type->tp_dict, "__abstractmethods__");
349 if (res && PyErr_ExceptionMatches(PyExc_KeyError)) {
Benjamin Peterson23b628e2011-01-12 18:56:07 +0000350 PyErr_SetString(PyExc_AttributeError, "__abstractmethods__");
Benjamin Peterson477ba912011-01-12 15:34:01 +0000351 return -1;
352 }
353 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000354 if (res == 0) {
355 PyType_Modified(type);
356 if (value && PyObject_IsTrue(value)) {
357 type->tp_flags |= Py_TPFLAGS_IS_ABSTRACT;
358 }
359 else {
360 type->tp_flags &= ~Py_TPFLAGS_IS_ABSTRACT;
361 }
362 }
363 return res;
Christian Heimes9e7f1d22008-02-28 12:27:11 +0000364}
365
366static PyObject *
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000367type_get_bases(PyTypeObject *type, void *context)
368{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000369 Py_INCREF(type->tp_bases);
370 return type->tp_bases;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000371}
372
373static PyTypeObject *best_base(PyObject *);
374static int mro_internal(PyTypeObject *);
375static int compatible_for_assignment(PyTypeObject *, PyTypeObject *, char *);
376static int add_subclass(PyTypeObject*, PyTypeObject*);
377static void remove_subclass(PyTypeObject *, PyTypeObject *);
378static void update_all_slots(PyTypeObject *);
379
Guido van Rossum8d24ee92003-03-24 23:49:49 +0000380typedef int (*update_callback)(PyTypeObject *, void *);
381static int update_subclasses(PyTypeObject *type, PyObject *name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000382 update_callback callback, void *data);
Guido van Rossum8d24ee92003-03-24 23:49:49 +0000383static int recurse_down_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 +0000385
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000386static int
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000387mro_subclasses(PyTypeObject *type, PyObject* temp)
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000388{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000389 PyTypeObject *subclass;
390 PyObject *ref, *subclasses, *old_mro;
391 Py_ssize_t i, n;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000392
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000393 subclasses = type->tp_subclasses;
394 if (subclasses == NULL)
395 return 0;
396 assert(PyList_Check(subclasses));
397 n = PyList_GET_SIZE(subclasses);
398 for (i = 0; i < n; i++) {
399 ref = PyList_GET_ITEM(subclasses, i);
400 assert(PyWeakref_CheckRef(ref));
401 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
402 assert(subclass != NULL);
403 if ((PyObject *)subclass == Py_None)
404 continue;
405 assert(PyType_Check(subclass));
406 old_mro = subclass->tp_mro;
407 if (mro_internal(subclass) < 0) {
408 subclass->tp_mro = old_mro;
409 return -1;
410 }
411 else {
412 PyObject* tuple;
413 tuple = PyTuple_Pack(2, subclass, old_mro);
414 Py_DECREF(old_mro);
415 if (!tuple)
416 return -1;
417 if (PyList_Append(temp, tuple) < 0)
418 return -1;
419 Py_DECREF(tuple);
420 }
421 if (mro_subclasses(subclass, temp) < 0)
422 return -1;
423 }
424 return 0;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000425}
426
427static int
428type_set_bases(PyTypeObject *type, PyObject *value, void *context)
429{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000430 Py_ssize_t i;
431 int r = 0;
432 PyObject *ob, *temp;
433 PyTypeObject *new_base, *old_base;
434 PyObject *old_bases, *old_mro;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000435
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000436 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
437 PyErr_Format(PyExc_TypeError,
438 "can't set %s.__bases__", type->tp_name);
439 return -1;
440 }
441 if (!value) {
442 PyErr_Format(PyExc_TypeError,
443 "can't delete %s.__bases__", type->tp_name);
444 return -1;
445 }
446 if (!PyTuple_Check(value)) {
447 PyErr_Format(PyExc_TypeError,
448 "can only assign tuple to %s.__bases__, not %s",
449 type->tp_name, Py_TYPE(value)->tp_name);
450 return -1;
451 }
452 if (PyTuple_GET_SIZE(value) == 0) {
453 PyErr_Format(PyExc_TypeError,
454 "can only assign non-empty tuple to %s.__bases__, not ()",
455 type->tp_name);
456 return -1;
457 }
458 for (i = 0; i < PyTuple_GET_SIZE(value); i++) {
459 ob = PyTuple_GET_ITEM(value, i);
460 if (!PyType_Check(ob)) {
461 PyErr_Format(
462 PyExc_TypeError,
463 "%s.__bases__ must be tuple of old- or new-style classes, not '%s'",
464 type->tp_name, Py_TYPE(ob)->tp_name);
465 return -1;
466 }
467 if (PyType_Check(ob)) {
468 if (PyType_IsSubtype((PyTypeObject*)ob, type)) {
469 PyErr_SetString(PyExc_TypeError,
470 "a __bases__ item causes an inheritance cycle");
471 return -1;
472 }
473 }
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
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000478 if (!new_base) {
479 return -1;
480 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000481
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000482 if (!compatible_for_assignment(type->tp_base, new_base, "__bases__"))
483 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000484
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000485 Py_INCREF(new_base);
486 Py_INCREF(value);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000487
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000488 old_bases = type->tp_bases;
489 old_base = type->tp_base;
490 old_mro = type->tp_mro;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000491
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000492 type->tp_bases = value;
493 type->tp_base = new_base;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000494
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000495 if (mro_internal(type) < 0) {
496 goto bail;
497 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000498
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000499 temp = PyList_New(0);
500 if (!temp)
501 goto bail;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000502
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000503 r = mro_subclasses(type, temp);
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000504
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000505 if (r < 0) {
506 for (i = 0; i < PyList_Size(temp); i++) {
507 PyTypeObject* cls;
508 PyObject* mro;
509 PyArg_UnpackTuple(PyList_GET_ITEM(temp, i),
510 "", 2, 2, &cls, &mro);
511 Py_INCREF(mro);
512 ob = cls->tp_mro;
513 cls->tp_mro = mro;
514 Py_DECREF(ob);
515 }
516 Py_DECREF(temp);
517 goto bail;
518 }
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000519
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000520 Py_DECREF(temp);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000521
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000522 /* any base that was in __bases__ but now isn't, we
523 need to remove |type| from its tp_subclasses.
524 conversely, any class now in __bases__ that wasn't
525 needs to have |type| added to its subclasses. */
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000526
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000527 /* for now, sod that: just remove from all old_bases,
528 add to all new_bases */
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000529
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000530 for (i = PyTuple_GET_SIZE(old_bases) - 1; i >= 0; i--) {
531 ob = PyTuple_GET_ITEM(old_bases, i);
532 if (PyType_Check(ob)) {
533 remove_subclass(
534 (PyTypeObject*)ob, type);
535 }
536 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000537
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000538 for (i = PyTuple_GET_SIZE(value) - 1; i >= 0; i--) {
539 ob = PyTuple_GET_ITEM(value, i);
540 if (PyType_Check(ob)) {
541 if (add_subclass((PyTypeObject*)ob, type) < 0)
542 r = -1;
543 }
544 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000545
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000546 update_all_slots(type);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000547
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000548 Py_DECREF(old_bases);
549 Py_DECREF(old_base);
550 Py_DECREF(old_mro);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000551
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000552 return r;
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000553
554 bail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000555 Py_DECREF(type->tp_bases);
556 Py_DECREF(type->tp_base);
557 if (type->tp_mro != old_mro) {
558 Py_DECREF(type->tp_mro);
559 }
Michael W. Hudsone723e452003-08-07 14:58:10 +0000560
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000561 type->tp_bases = old_bases;
562 type->tp_base = old_base;
563 type->tp_mro = old_mro;
Tim Petersea7f75d2002-12-07 21:39:16 +0000564
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000565 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000566}
567
568static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000569type_dict(PyTypeObject *type, void *context)
570{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000571 if (type->tp_dict == NULL) {
572 Py_INCREF(Py_None);
573 return Py_None;
574 }
575 return PyDictProxy_New(type->tp_dict);
Guido van Rossum29ca26e1995-01-07 11:58:15 +0000576}
577
Tim Peters24008312002-03-17 18:56:20 +0000578static PyObject *
579type_get_doc(PyTypeObject *type, void *context)
580{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000581 PyObject *result;
582 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE) && type->tp_doc != NULL)
583 return PyUnicode_FromString(type->tp_doc);
584 result = PyDict_GetItemString(type->tp_dict, "__doc__");
585 if (result == NULL) {
586 result = Py_None;
587 Py_INCREF(result);
588 }
589 else if (Py_TYPE(result)->tp_descr_get) {
590 result = Py_TYPE(result)->tp_descr_get(result, NULL,
591 (PyObject *)type);
592 }
593 else {
594 Py_INCREF(result);
595 }
596 return result;
Tim Peters24008312002-03-17 18:56:20 +0000597}
598
Antoine Pitrouec569b72008-08-26 22:40:48 +0000599static PyObject *
600type___instancecheck__(PyObject *type, PyObject *inst)
601{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000602 switch (_PyObject_RealIsInstance(inst, type)) {
603 case -1:
604 return NULL;
605 case 0:
606 Py_RETURN_FALSE;
607 default:
608 Py_RETURN_TRUE;
609 }
Antoine Pitrouec569b72008-08-26 22:40:48 +0000610}
611
612
613static PyObject *
Antoine Pitrouec569b72008-08-26 22:40:48 +0000614type___subclasscheck__(PyObject *type, PyObject *inst)
615{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000616 switch (_PyObject_RealIsSubclass(inst, type)) {
617 case -1:
618 return NULL;
619 case 0:
620 Py_RETURN_FALSE;
621 default:
622 Py_RETURN_TRUE;
623 }
Antoine Pitrouec569b72008-08-26 22:40:48 +0000624}
625
Antoine Pitrouec569b72008-08-26 22:40:48 +0000626
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000627static PyGetSetDef type_getsets[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000628 {"__name__", (getter)type_name, (setter)type_set_name, NULL},
629 {"__bases__", (getter)type_get_bases, (setter)type_set_bases, NULL},
630 {"__module__", (getter)type_module, (setter)type_set_module, NULL},
631 {"__abstractmethods__", (getter)type_abstractmethods,
632 (setter)type_set_abstractmethods, NULL},
633 {"__dict__", (getter)type_dict, NULL, NULL},
634 {"__doc__", (getter)type_get_doc, NULL, NULL},
635 {0}
Tim Peters6d6c1a32001-08-02 04:15:00 +0000636};
637
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000638static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000639type_repr(PyTypeObject *type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000640{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000641 PyObject *mod, *name, *rtn;
Guido van Rossumc3542212001-08-16 09:18:56 +0000642
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000643 mod = type_module(type, NULL);
644 if (mod == NULL)
645 PyErr_Clear();
646 else if (!PyUnicode_Check(mod)) {
647 Py_DECREF(mod);
648 mod = NULL;
649 }
650 name = type_name(type, NULL);
651 if (name == NULL)
652 return NULL;
Barry Warsaw7ce36942001-08-24 18:34:26 +0000653
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000654 if (mod != NULL && PyUnicode_CompareWithASCIIString(mod, "builtins"))
655 rtn = PyUnicode_FromFormat("<class '%U.%U'>", mod, name);
656 else
657 rtn = PyUnicode_FromFormat("<class '%s'>", type->tp_name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000658
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000659 Py_XDECREF(mod);
660 Py_DECREF(name);
661 return rtn;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000662}
663
Tim Peters6d6c1a32001-08-02 04:15:00 +0000664static PyObject *
665type_call(PyTypeObject *type, PyObject *args, PyObject *kwds)
666{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000667 PyObject *obj;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000668
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000669 if (type->tp_new == NULL) {
670 PyErr_Format(PyExc_TypeError,
671 "cannot create '%.100s' instances",
672 type->tp_name);
673 return NULL;
674 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000675
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000676 obj = type->tp_new(type, args, kwds);
677 if (obj != NULL) {
678 /* Ugly exception: when the call was type(something),
679 don't call tp_init on the result. */
680 if (type == &PyType_Type &&
681 PyTuple_Check(args) && PyTuple_GET_SIZE(args) == 1 &&
682 (kwds == NULL ||
683 (PyDict_Check(kwds) && PyDict_Size(kwds) == 0)))
684 return obj;
685 /* If the returned object is not an instance of type,
686 it won't be initialized. */
687 if (!PyType_IsSubtype(Py_TYPE(obj), type))
688 return obj;
689 type = Py_TYPE(obj);
690 if (type->tp_init != NULL &&
691 type->tp_init(obj, args, kwds) < 0) {
692 Py_DECREF(obj);
693 obj = NULL;
694 }
695 }
696 return obj;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000697}
698
699PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000700PyType_GenericAlloc(PyTypeObject *type, Py_ssize_t nitems)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000701{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000702 PyObject *obj;
703 const size_t size = _PyObject_VAR_SIZE(type, nitems+1);
704 /* note that we need to add one, for the sentinel */
Tim Peters406fe3b2001-10-06 19:04:01 +0000705
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000706 if (PyType_IS_GC(type))
707 obj = _PyObject_GC_Malloc(size);
708 else
709 obj = (PyObject *)PyObject_MALLOC(size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000710
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000711 if (obj == NULL)
712 return PyErr_NoMemory();
Tim Peters406fe3b2001-10-06 19:04:01 +0000713
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000714 memset(obj, '\0', size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000715
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000716 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
717 Py_INCREF(type);
Tim Peters406fe3b2001-10-06 19:04:01 +0000718
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000719 if (type->tp_itemsize == 0)
720 PyObject_INIT(obj, type);
721 else
722 (void) PyObject_INIT_VAR((PyVarObject *)obj, type, nitems);
Tim Peters406fe3b2001-10-06 19:04:01 +0000723
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000724 if (PyType_IS_GC(type))
725 _PyObject_GC_TRACK(obj);
726 return obj;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000727}
728
729PyObject *
730PyType_GenericNew(PyTypeObject *type, PyObject *args, PyObject *kwds)
731{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000732 return type->tp_alloc(type, 0);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000733}
734
Guido van Rossum9475a232001-10-05 20:51:39 +0000735/* Helpers for subtyping */
736
737static int
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000738traverse_slots(PyTypeObject *type, PyObject *self, visitproc visit, void *arg)
739{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000740 Py_ssize_t i, n;
741 PyMemberDef *mp;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000742
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000743 n = Py_SIZE(type);
744 mp = PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type);
745 for (i = 0; i < n; i++, mp++) {
746 if (mp->type == T_OBJECT_EX) {
747 char *addr = (char *)self + mp->offset;
748 PyObject *obj = *(PyObject **)addr;
749 if (obj != NULL) {
750 int err = visit(obj, arg);
751 if (err)
752 return err;
753 }
754 }
755 }
756 return 0;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000757}
758
759static int
Guido van Rossum9475a232001-10-05 20:51:39 +0000760subtype_traverse(PyObject *self, visitproc visit, void *arg)
761{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000762 PyTypeObject *type, *base;
763 traverseproc basetraverse;
Guido van Rossum9475a232001-10-05 20:51:39 +0000764
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000765 /* Find the nearest base with a different tp_traverse,
766 and traverse slots while we're at it */
767 type = Py_TYPE(self);
768 base = type;
769 while ((basetraverse = base->tp_traverse) == subtype_traverse) {
770 if (Py_SIZE(base)) {
771 int err = traverse_slots(base, self, visit, arg);
772 if (err)
773 return err;
774 }
775 base = base->tp_base;
776 assert(base);
777 }
Guido van Rossum9475a232001-10-05 20:51:39 +0000778
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000779 if (type->tp_dictoffset != base->tp_dictoffset) {
780 PyObject **dictptr = _PyObject_GetDictPtr(self);
781 if (dictptr && *dictptr)
782 Py_VISIT(*dictptr);
783 }
Guido van Rossum9475a232001-10-05 20:51:39 +0000784
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000785 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
786 /* For a heaptype, the instances count as references
787 to the type. Traverse the type so the collector
788 can find cycles involving this link. */
789 Py_VISIT(type);
Guido van Rossuma3862092002-06-10 15:24:42 +0000790
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000791 if (basetraverse)
792 return basetraverse(self, visit, arg);
793 return 0;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000794}
795
796static void
797clear_slots(PyTypeObject *type, PyObject *self)
798{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000799 Py_ssize_t i, n;
800 PyMemberDef *mp;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000801
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000802 n = Py_SIZE(type);
803 mp = PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type);
804 for (i = 0; i < n; i++, mp++) {
805 if (mp->type == T_OBJECT_EX && !(mp->flags & READONLY)) {
806 char *addr = (char *)self + mp->offset;
807 PyObject *obj = *(PyObject **)addr;
808 if (obj != NULL) {
809 *(PyObject **)addr = NULL;
810 Py_DECREF(obj);
811 }
812 }
813 }
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000814}
815
816static int
817subtype_clear(PyObject *self)
818{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000819 PyTypeObject *type, *base;
820 inquiry baseclear;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000821
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000822 /* Find the nearest base with a different tp_clear
823 and clear slots while we're at it */
824 type = Py_TYPE(self);
825 base = type;
826 while ((baseclear = base->tp_clear) == subtype_clear) {
827 if (Py_SIZE(base))
828 clear_slots(base, self);
829 base = base->tp_base;
830 assert(base);
831 }
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000832
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000833 /* There's no need to clear the instance dict (if any);
834 the collector will call its tp_clear handler. */
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000835
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000836 if (baseclear)
837 return baseclear(self);
838 return 0;
Guido van Rossum9475a232001-10-05 20:51:39 +0000839}
Tim Peters6d6c1a32001-08-02 04:15:00 +0000840
841static void
842subtype_dealloc(PyObject *self)
843{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000844 PyTypeObject *type, *base;
845 destructor basedealloc;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000846
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000847 /* Extract the type; we expect it to be a heap type */
848 type = Py_TYPE(self);
849 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000850
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000851 /* Test whether the type has GC exactly once */
Guido van Rossum22b13872002-08-06 21:41:44 +0000852
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000853 if (!PyType_IS_GC(type)) {
854 /* It's really rare to find a dynamic type that doesn't have
855 GC; it can only happen when deriving from 'object' and not
856 adding any slots or instance variables. This allows
857 certain simplifications: there's no need to call
858 clear_slots(), or DECREF the dict, or clear weakrefs. */
Guido van Rossum22b13872002-08-06 21:41:44 +0000859
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000860 /* Maybe call finalizer; exit early if resurrected */
861 if (type->tp_del) {
862 type->tp_del(self);
863 if (self->ob_refcnt > 0)
864 return;
865 }
Guido van Rossum22b13872002-08-06 21:41:44 +0000866
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000867 /* Find the nearest base with a different tp_dealloc */
868 base = type;
869 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
870 assert(Py_SIZE(base) == 0);
871 base = base->tp_base;
872 assert(base);
873 }
Guido van Rossum22b13872002-08-06 21:41:44 +0000874
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000875 /* Extract the type again; tp_del may have changed it */
876 type = Py_TYPE(self);
Benjamin Peterson193152c2009-04-25 01:08:45 +0000877
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000878 /* Call the base tp_dealloc() */
879 assert(basedealloc);
880 basedealloc(self);
Guido van Rossum22b13872002-08-06 21:41:44 +0000881
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000882 /* Can't reference self beyond this point */
883 Py_DECREF(type);
Guido van Rossum22b13872002-08-06 21:41:44 +0000884
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000885 /* Done */
886 return;
887 }
Guido van Rossum22b13872002-08-06 21:41:44 +0000888
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000889 /* We get here only if the type has GC */
Guido van Rossum22b13872002-08-06 21:41:44 +0000890
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000891 /* UnTrack and re-Track around the trashcan macro, alas */
892 /* See explanation at end of function for full disclosure */
893 PyObject_GC_UnTrack(self);
894 ++_PyTrash_delete_nesting;
895 Py_TRASHCAN_SAFE_BEGIN(self);
896 --_PyTrash_delete_nesting;
897 /* DO NOT restore GC tracking at this point. weakref callbacks
898 * (if any, and whether directly here or indirectly in something we
899 * call) may trigger GC, and if self is tracked at that point, it
900 * will look like trash to GC and GC will try to delete self again.
901 */
Guido van Rossum22b13872002-08-06 21:41:44 +0000902
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000903 /* Find the nearest base with a different tp_dealloc */
904 base = type;
Brett Cannonb94767f2011-02-22 20:15:44 +0000905 while ((/*basedealloc =*/ base->tp_dealloc) == subtype_dealloc) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000906 base = base->tp_base;
907 assert(base);
908 }
Guido van Rossum14227b42001-12-06 02:35:58 +0000909
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000910 /* If we added a weaklist, we clear it. Do this *before* calling
911 the finalizer (__del__), clearing slots, or clearing the instance
912 dict. */
Guido van Rossum59195fd2003-06-13 20:54:40 +0000913
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000914 if (type->tp_weaklistoffset && !base->tp_weaklistoffset)
915 PyObject_ClearWeakRefs(self);
Guido van Rossum1987c662003-05-29 14:29:23 +0000916
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000917 /* Maybe call finalizer; exit early if resurrected */
918 if (type->tp_del) {
919 _PyObject_GC_TRACK(self);
920 type->tp_del(self);
921 if (self->ob_refcnt > 0)
922 goto endlabel; /* resurrected */
923 else
924 _PyObject_GC_UNTRACK(self);
925 /* New weakrefs could be created during the finalizer call.
926 If this occurs, clear them out without calling their
927 finalizers since they might rely on part of the object
928 being finalized that has already been destroyed. */
929 if (type->tp_weaklistoffset && !base->tp_weaklistoffset) {
930 /* Modeled after GET_WEAKREFS_LISTPTR() */
931 PyWeakReference **list = (PyWeakReference **) \
932 PyObject_GET_WEAKREFS_LISTPTR(self);
933 while (*list)
934 _PyWeakref_ClearRef(*list);
935 }
936 }
Guido van Rossum1987c662003-05-29 14:29:23 +0000937
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000938 /* Clear slots up to the nearest base with a different tp_dealloc */
939 base = type;
940 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
941 if (Py_SIZE(base))
942 clear_slots(base, self);
943 base = base->tp_base;
944 assert(base);
945 }
Guido van Rossum59195fd2003-06-13 20:54:40 +0000946
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000947 /* If we added a dict, DECREF it */
948 if (type->tp_dictoffset && !base->tp_dictoffset) {
949 PyObject **dictptr = _PyObject_GetDictPtr(self);
950 if (dictptr != NULL) {
951 PyObject *dict = *dictptr;
952 if (dict != NULL) {
953 Py_DECREF(dict);
954 *dictptr = NULL;
955 }
956 }
957 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000958
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000959 /* Extract the type again; tp_del may have changed it */
960 type = Py_TYPE(self);
Benjamin Peterson193152c2009-04-25 01:08:45 +0000961
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000962 /* Call the base tp_dealloc(); first retrack self if
963 * basedealloc knows about gc.
964 */
965 if (PyType_IS_GC(base))
966 _PyObject_GC_TRACK(self);
967 assert(basedealloc);
968 basedealloc(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000969
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000970 /* Can't reference self beyond this point */
971 Py_DECREF(type);
Guido van Rossum22b13872002-08-06 21:41:44 +0000972
Guido van Rossum0906e072002-08-07 20:42:09 +0000973 endlabel:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000974 ++_PyTrash_delete_nesting;
975 Py_TRASHCAN_SAFE_END(self);
976 --_PyTrash_delete_nesting;
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000977
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000978 /* Explanation of the weirdness around the trashcan macros:
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000979
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000980 Q. What do the trashcan macros do?
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000981
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000982 A. Read the comment titled "Trashcan mechanism" in object.h.
983 For one, this explains why there must be a call to GC-untrack
984 before the trashcan begin macro. Without understanding the
985 trashcan code, the answers to the following questions don't make
986 sense.
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000987
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000988 Q. Why do we GC-untrack before the trashcan and then immediately
989 GC-track again afterward?
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000990
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000991 A. In the case that the base class is GC-aware, the base class
992 probably GC-untracks the object. If it does that using the
993 UNTRACK macro, this will crash when the object is already
994 untracked. Because we don't know what the base class does, the
995 only safe thing is to make sure the object is tracked when we
996 call the base class dealloc. But... The trashcan begin macro
997 requires that the object is *untracked* before it is called. So
998 the dance becomes:
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000999
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001000 GC untrack
1001 trashcan begin
1002 GC track
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001003
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001004 Q. Why did the last question say "immediately GC-track again"?
1005 It's nowhere near immediately.
Tim Petersf7f9e992003-11-13 21:59:32 +00001006
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001007 A. Because the code *used* to re-track immediately. Bad Idea.
1008 self has a refcount of 0, and if gc ever gets its hands on it
1009 (which can happen if any weakref callback gets invoked), it
1010 looks like trash to gc too, and gc also tries to delete self
Ezio Melotti13925002011-03-16 11:05:33 +02001011 then. But we're already deleting self. Double deallocation is
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001012 a subtle disaster.
Tim Petersf7f9e992003-11-13 21:59:32 +00001013
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001014 Q. Why the bizarre (net-zero) manipulation of
1015 _PyTrash_delete_nesting around the trashcan macros?
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001016
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001017 A. Some base classes (e.g. list) also use the trashcan mechanism.
1018 The following scenario used to be possible:
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001019
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001020 - suppose the trashcan level is one below the trashcan limit
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001021
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001022 - subtype_dealloc() is called
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001023
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001024 - the trashcan limit is not yet reached, so the trashcan level
1025 is incremented and the code between trashcan begin and end is
1026 executed
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001027
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001028 - this destroys much of the object's contents, including its
1029 slots and __dict__
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001030
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001031 - basedealloc() is called; this is really list_dealloc(), or
1032 some other type which also uses the trashcan macros
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001033
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001034 - the trashcan limit is now reached, so the object is put on the
1035 trashcan's to-be-deleted-later list
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001036
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001037 - basedealloc() returns
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001038
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001039 - subtype_dealloc() decrefs the object's type
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001040
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001041 - subtype_dealloc() returns
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001042
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001043 - later, the trashcan code starts deleting the objects from its
1044 to-be-deleted-later list
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001045
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001046 - subtype_dealloc() is called *AGAIN* for the same object
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001047
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001048 - at the very least (if the destroyed slots and __dict__ don't
1049 cause problems) the object's type gets decref'ed a second
1050 time, which is *BAD*!!!
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001051
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001052 The remedy is to make sure that if the code between trashcan
1053 begin and end in subtype_dealloc() is called, the code between
1054 trashcan begin and end in basedealloc() will also be called.
1055 This is done by decrementing the level after passing into the
1056 trashcan block, and incrementing it just before leaving the
1057 block.
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001058
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001059 But now it's possible that a chain of objects consisting solely
1060 of objects whose deallocator is subtype_dealloc() will defeat
1061 the trashcan mechanism completely: the decremented level means
1062 that the effective level never reaches the limit. Therefore, we
1063 *increment* the level *before* entering the trashcan block, and
1064 matchingly decrement it after leaving. This means the trashcan
1065 code will trigger a little early, but that's no big deal.
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001066
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001067 Q. Are there any live examples of code in need of all this
1068 complexity?
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001069
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001070 A. Yes. See SF bug 668433 for code that crashed (when Python was
1071 compiled in debug mode) before the trashcan level manipulations
1072 were added. For more discussion, see SF patches 581742, 575073
1073 and bug 574207.
1074 */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001075}
1076
Jeremy Hylton938ace62002-07-17 16:30:39 +00001077static PyTypeObject *solid_base(PyTypeObject *type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001078
Tim Peters6d6c1a32001-08-02 04:15:00 +00001079/* type test with subclassing support */
1080
1081int
1082PyType_IsSubtype(PyTypeObject *a, PyTypeObject *b)
1083{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001084 PyObject *mro;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001085
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001086 mro = a->tp_mro;
1087 if (mro != NULL) {
1088 /* Deal with multiple inheritance without recursion
1089 by walking the MRO tuple */
1090 Py_ssize_t i, n;
1091 assert(PyTuple_Check(mro));
1092 n = PyTuple_GET_SIZE(mro);
1093 for (i = 0; i < n; i++) {
1094 if (PyTuple_GET_ITEM(mro, i) == (PyObject *)b)
1095 return 1;
1096 }
1097 return 0;
1098 }
1099 else {
1100 /* a is not completely initilized yet; follow tp_base */
1101 do {
1102 if (a == b)
1103 return 1;
1104 a = a->tp_base;
1105 } while (a != NULL);
1106 return b == &PyBaseObject_Type;
1107 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001108}
1109
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001110/* Internal routines to do a method lookup in the type
Guido van Rossum60718732001-08-28 17:47:51 +00001111 without looking in the instance dictionary
1112 (so we can't use PyObject_GetAttr) but still binding
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001113 it to the instance. The arguments are the object,
Guido van Rossum60718732001-08-28 17:47:51 +00001114 the method name as a C string, and the address of a
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001115 static variable used to cache the interned Python string.
1116
1117 Two variants:
1118
1119 - lookup_maybe() returns NULL without raising an exception
1120 when the _PyType_Lookup() call fails;
1121
1122 - lookup_method() always raises an exception upon errors.
Benjamin Peterson224205f2009-05-08 03:25:19 +00001123
1124 - _PyObject_LookupSpecial() exported for the benefit of other places.
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001125*/
Guido van Rossum60718732001-08-28 17:47:51 +00001126
1127static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001128lookup_maybe(PyObject *self, char *attrstr, PyObject **attrobj)
Guido van Rossum60718732001-08-28 17:47:51 +00001129{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001130 PyObject *res;
Guido van Rossum60718732001-08-28 17:47:51 +00001131
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001132 if (*attrobj == NULL) {
1133 *attrobj = PyUnicode_InternFromString(attrstr);
1134 if (*attrobj == NULL)
1135 return NULL;
1136 }
1137 res = _PyType_Lookup(Py_TYPE(self), *attrobj);
1138 if (res != NULL) {
1139 descrgetfunc f;
1140 if ((f = Py_TYPE(res)->tp_descr_get) == NULL)
1141 Py_INCREF(res);
1142 else
1143 res = f(res, self, (PyObject *)(Py_TYPE(self)));
1144 }
1145 return res;
Guido van Rossum60718732001-08-28 17:47:51 +00001146}
1147
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001148static PyObject *
1149lookup_method(PyObject *self, char *attrstr, PyObject **attrobj)
1150{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001151 PyObject *res = lookup_maybe(self, attrstr, attrobj);
1152 if (res == NULL && !PyErr_Occurred())
1153 PyErr_SetObject(PyExc_AttributeError, *attrobj);
1154 return res;
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001155}
1156
Benjamin Peterson224205f2009-05-08 03:25:19 +00001157PyObject *
1158_PyObject_LookupSpecial(PyObject *self, char *attrstr, PyObject **attrobj)
1159{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001160 return lookup_maybe(self, attrstr, attrobj);
Benjamin Peterson224205f2009-05-08 03:25:19 +00001161}
1162
Guido van Rossum2730b132001-08-28 18:22:14 +00001163/* A variation of PyObject_CallMethod that uses lookup_method()
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001164 instead of PyObject_GetAttrString(). This uses the same convention
Guido van Rossum2730b132001-08-28 18:22:14 +00001165 as lookup_method to cache the interned name string object. */
1166
Neil Schemenauerf23473f2001-10-21 22:28:58 +00001167static PyObject *
Guido van Rossum2730b132001-08-28 18:22:14 +00001168call_method(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
1169{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001170 va_list va;
1171 PyObject *args, *func = 0, *retval;
1172 va_start(va, format);
Guido van Rossum2730b132001-08-28 18:22:14 +00001173
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001174 func = lookup_maybe(o, name, nameobj);
1175 if (func == NULL) {
1176 va_end(va);
1177 if (!PyErr_Occurred())
1178 PyErr_SetObject(PyExc_AttributeError, *nameobj);
1179 return NULL;
1180 }
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001181
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001182 if (format && *format)
1183 args = Py_VaBuildValue(format, va);
1184 else
1185 args = PyTuple_New(0);
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001186
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001187 va_end(va);
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001188
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001189 if (args == NULL)
1190 return NULL;
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001191
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001192 assert(PyTuple_Check(args));
1193 retval = PyObject_Call(func, args, NULL);
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001194
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001195 Py_DECREF(args);
1196 Py_DECREF(func);
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001197
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001198 return retval;
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001199}
1200
1201/* Clone of call_method() that returns NotImplemented when the lookup fails. */
1202
Neil Schemenauerf23473f2001-10-21 22:28:58 +00001203static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001204call_maybe(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
1205{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001206 va_list va;
1207 PyObject *args, *func = 0, *retval;
1208 va_start(va, format);
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001209
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001210 func = lookup_maybe(o, name, nameobj);
1211 if (func == NULL) {
1212 va_end(va);
1213 if (!PyErr_Occurred()) {
1214 Py_INCREF(Py_NotImplemented);
1215 return Py_NotImplemented;
1216 }
1217 return NULL;
1218 }
Guido van Rossum2730b132001-08-28 18:22:14 +00001219
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001220 if (format && *format)
1221 args = Py_VaBuildValue(format, va);
1222 else
1223 args = PyTuple_New(0);
Guido van Rossum2730b132001-08-28 18:22:14 +00001224
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001225 va_end(va);
Guido van Rossum2730b132001-08-28 18:22:14 +00001226
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001227 if (args == NULL)
1228 return NULL;
Guido van Rossum2730b132001-08-28 18:22:14 +00001229
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001230 assert(PyTuple_Check(args));
1231 retval = PyObject_Call(func, args, NULL);
Guido van Rossum2730b132001-08-28 18:22:14 +00001232
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001233 Py_DECREF(args);
1234 Py_DECREF(func);
Guido van Rossum2730b132001-08-28 18:22:14 +00001235
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001236 return retval;
Guido van Rossum2730b132001-08-28 18:22:14 +00001237}
1238
Tim Petersea7f75d2002-12-07 21:39:16 +00001239/*
Guido van Rossum1f121312002-11-14 19:49:16 +00001240 Method resolution order algorithm C3 described in
1241 "A Monotonic Superclass Linearization for Dylan",
1242 by Kim Barrett, Bob Cassel, Paul Haahr,
Tim Petersea7f75d2002-12-07 21:39:16 +00001243 David A. Moon, Keith Playford, and P. Tucker Withington.
Guido van Rossum1f121312002-11-14 19:49:16 +00001244 (OOPSLA 1996)
1245
Guido van Rossum98f33732002-11-25 21:36:54 +00001246 Some notes about the rules implied by C3:
1247
Tim Petersea7f75d2002-12-07 21:39:16 +00001248 No duplicate bases.
Guido van Rossum98f33732002-11-25 21:36:54 +00001249 It isn't legal to repeat a class in a list of base classes.
1250
1251 The next three properties are the 3 constraints in "C3".
1252
Tim Petersea7f75d2002-12-07 21:39:16 +00001253 Local precendece order.
Guido van Rossum98f33732002-11-25 21:36:54 +00001254 If A precedes B in C's MRO, then A will precede B in the MRO of all
1255 subclasses of C.
1256
1257 Monotonicity.
1258 The MRO of a class must be an extension without reordering of the
1259 MRO of each of its superclasses.
1260
1261 Extended Precedence Graph (EPG).
1262 Linearization is consistent if there is a path in the EPG from
1263 each class to all its successors in the linearization. See
1264 the paper for definition of EPG.
Guido van Rossum1f121312002-11-14 19:49:16 +00001265 */
1266
Tim Petersea7f75d2002-12-07 21:39:16 +00001267static int
Guido van Rossum1f121312002-11-14 19:49:16 +00001268tail_contains(PyObject *list, int whence, PyObject *o) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001269 Py_ssize_t j, size;
1270 size = PyList_GET_SIZE(list);
Guido van Rossum1f121312002-11-14 19:49:16 +00001271
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001272 for (j = whence+1; j < size; j++) {
1273 if (PyList_GET_ITEM(list, j) == o)
1274 return 1;
1275 }
1276 return 0;
Guido van Rossum1f121312002-11-14 19:49:16 +00001277}
1278
Guido van Rossum98f33732002-11-25 21:36:54 +00001279static PyObject *
1280class_name(PyObject *cls)
1281{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001282 PyObject *name = PyObject_GetAttrString(cls, "__name__");
1283 if (name == NULL) {
1284 PyErr_Clear();
1285 Py_XDECREF(name);
1286 name = PyObject_Repr(cls);
1287 }
1288 if (name == NULL)
1289 return NULL;
1290 if (!PyUnicode_Check(name)) {
1291 Py_DECREF(name);
1292 return NULL;
1293 }
1294 return name;
Guido van Rossum98f33732002-11-25 21:36:54 +00001295}
1296
1297static int
1298check_duplicates(PyObject *list)
1299{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001300 Py_ssize_t i, j, n;
1301 /* Let's use a quadratic time algorithm,
1302 assuming that the bases lists is short.
1303 */
1304 n = PyList_GET_SIZE(list);
1305 for (i = 0; i < n; i++) {
1306 PyObject *o = PyList_GET_ITEM(list, i);
1307 for (j = i + 1; j < n; j++) {
1308 if (PyList_GET_ITEM(list, j) == o) {
1309 o = class_name(o);
1310 if (o != NULL) {
1311 PyErr_Format(PyExc_TypeError,
1312 "duplicate base class %U",
1313 o);
1314 Py_DECREF(o);
1315 } else {
1316 PyErr_SetString(PyExc_TypeError,
1317 "duplicate base class");
1318 }
1319 return -1;
1320 }
1321 }
1322 }
1323 return 0;
Guido van Rossum98f33732002-11-25 21:36:54 +00001324}
1325
1326/* Raise a TypeError for an MRO order disagreement.
1327
1328 It's hard to produce a good error message. In the absence of better
1329 insight into error reporting, report the classes that were candidates
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001330 to be put next into the MRO. There is some conflict between the
Guido van Rossum98f33732002-11-25 21:36:54 +00001331 order in which they should be put in the MRO, but it's hard to
1332 diagnose what constraint can't be satisfied.
1333*/
1334
1335static void
1336set_mro_error(PyObject *to_merge, int *remain)
1337{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001338 Py_ssize_t i, n, off, to_merge_size;
1339 char buf[1000];
1340 PyObject *k, *v;
1341 PyObject *set = PyDict_New();
1342 if (!set) return;
Guido van Rossum98f33732002-11-25 21:36:54 +00001343
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001344 to_merge_size = PyList_GET_SIZE(to_merge);
1345 for (i = 0; i < to_merge_size; i++) {
1346 PyObject *L = PyList_GET_ITEM(to_merge, i);
1347 if (remain[i] < PyList_GET_SIZE(L)) {
1348 PyObject *c = PyList_GET_ITEM(L, remain[i]);
1349 if (PyDict_SetItem(set, c, Py_None) < 0) {
1350 Py_DECREF(set);
1351 return;
1352 }
1353 }
1354 }
1355 n = PyDict_Size(set);
Guido van Rossum98f33732002-11-25 21:36:54 +00001356
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001357 off = PyOS_snprintf(buf, sizeof(buf), "Cannot create a \
Raymond Hettingerf394df42003-04-06 19:13:41 +00001358consistent method resolution\norder (MRO) for bases");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001359 i = 0;
1360 while (PyDict_Next(set, &i, &k, &v) && (size_t)off < sizeof(buf)) {
1361 PyObject *name = class_name(k);
Victor Stinnere5f99f32010-05-19 01:42:46 +00001362 char *name_str;
1363 if (name != NULL) {
1364 name_str = _PyUnicode_AsString(name);
1365 if (name_str == NULL)
Victor Stinnerba644a62010-05-19 01:50:45 +00001366 name_str = "?";
Victor Stinnere5f99f32010-05-19 01:42:46 +00001367 } else
Victor Stinnerba644a62010-05-19 01:50:45 +00001368 name_str = "?";
Victor Stinnere5f99f32010-05-19 01:42:46 +00001369 off += PyOS_snprintf(buf + off, sizeof(buf) - off, " %s", name_str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001370 Py_XDECREF(name);
1371 if (--n && (size_t)(off+1) < sizeof(buf)) {
1372 buf[off++] = ',';
1373 buf[off] = '\0';
1374 }
1375 }
1376 PyErr_SetString(PyExc_TypeError, buf);
1377 Py_DECREF(set);
Guido van Rossum98f33732002-11-25 21:36:54 +00001378}
1379
Tim Petersea7f75d2002-12-07 21:39:16 +00001380static int
Guido van Rossum1f121312002-11-14 19:49:16 +00001381pmerge(PyObject *acc, PyObject* to_merge) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001382 Py_ssize_t i, j, to_merge_size, empty_cnt;
1383 int *remain;
1384 int ok;
Tim Petersea7f75d2002-12-07 21:39:16 +00001385
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001386 to_merge_size = PyList_GET_SIZE(to_merge);
Guido van Rossum1f121312002-11-14 19:49:16 +00001387
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001388 /* remain stores an index into each sublist of to_merge.
1389 remain[i] is the index of the next base in to_merge[i]
1390 that is not included in acc.
1391 */
1392 remain = (int *)PyMem_MALLOC(SIZEOF_INT*to_merge_size);
1393 if (remain == NULL)
1394 return -1;
1395 for (i = 0; i < to_merge_size; i++)
1396 remain[i] = 0;
Guido van Rossum1f121312002-11-14 19:49:16 +00001397
1398 again:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001399 empty_cnt = 0;
1400 for (i = 0; i < to_merge_size; i++) {
1401 PyObject *candidate;
Tim Petersea7f75d2002-12-07 21:39:16 +00001402
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001403 PyObject *cur_list = PyList_GET_ITEM(to_merge, i);
Guido van Rossum1f121312002-11-14 19:49:16 +00001404
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001405 if (remain[i] >= PyList_GET_SIZE(cur_list)) {
1406 empty_cnt++;
1407 continue;
1408 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001409
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001410 /* Choose next candidate for MRO.
Guido van Rossum98f33732002-11-25 21:36:54 +00001411
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001412 The input sequences alone can determine the choice.
1413 If not, choose the class which appears in the MRO
1414 of the earliest direct superclass of the new class.
1415 */
Guido van Rossum98f33732002-11-25 21:36:54 +00001416
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001417 candidate = PyList_GET_ITEM(cur_list, remain[i]);
1418 for (j = 0; j < to_merge_size; j++) {
1419 PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
1420 if (tail_contains(j_lst, remain[j], candidate)) {
1421 goto skip; /* continue outer loop */
1422 }
1423 }
1424 ok = PyList_Append(acc, candidate);
1425 if (ok < 0) {
1426 PyMem_Free(remain);
1427 return -1;
1428 }
1429 for (j = 0; j < to_merge_size; j++) {
1430 PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
1431 if (remain[j] < PyList_GET_SIZE(j_lst) &&
1432 PyList_GET_ITEM(j_lst, remain[j]) == candidate) {
1433 remain[j]++;
1434 }
1435 }
1436 goto again;
1437 skip: ;
1438 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001439
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001440 if (empty_cnt == to_merge_size) {
1441 PyMem_FREE(remain);
1442 return 0;
1443 }
1444 set_mro_error(to_merge, remain);
1445 PyMem_FREE(remain);
1446 return -1;
Guido van Rossum1f121312002-11-14 19:49:16 +00001447}
1448
Tim Peters6d6c1a32001-08-02 04:15:00 +00001449static PyObject *
1450mro_implementation(PyTypeObject *type)
1451{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001452 Py_ssize_t i, n;
1453 int ok;
1454 PyObject *bases, *result;
1455 PyObject *to_merge, *bases_aslist;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001456
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001457 if (type->tp_dict == NULL) {
1458 if (PyType_Ready(type) < 0)
1459 return NULL;
1460 }
Guido van Rossum63517572002-06-18 16:44:57 +00001461
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001462 /* Find a superclass linearization that honors the constraints
1463 of the explicit lists of bases and the constraints implied by
1464 each base class.
Guido van Rossum98f33732002-11-25 21:36:54 +00001465
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001466 to_merge is a list of lists, where each list is a superclass
1467 linearization implied by a base class. The last element of
1468 to_merge is the declared list of bases.
1469 */
Guido van Rossum98f33732002-11-25 21:36:54 +00001470
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001471 bases = type->tp_bases;
1472 n = PyTuple_GET_SIZE(bases);
Guido van Rossum1f121312002-11-14 19:49:16 +00001473
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001474 to_merge = PyList_New(n+1);
1475 if (to_merge == NULL)
1476 return NULL;
Guido van Rossum1f121312002-11-14 19:49:16 +00001477
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001478 for (i = 0; i < n; i++) {
1479 PyObject *base = PyTuple_GET_ITEM(bases, i);
1480 PyObject *parentMRO;
1481 parentMRO = PySequence_List(((PyTypeObject*)base)->tp_mro);
1482 if (parentMRO == NULL) {
1483 Py_DECREF(to_merge);
1484 return NULL;
1485 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001486
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001487 PyList_SET_ITEM(to_merge, i, parentMRO);
1488 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001489
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001490 bases_aslist = PySequence_List(bases);
1491 if (bases_aslist == NULL) {
1492 Py_DECREF(to_merge);
1493 return NULL;
1494 }
1495 /* This is just a basic sanity check. */
1496 if (check_duplicates(bases_aslist) < 0) {
1497 Py_DECREF(to_merge);
1498 Py_DECREF(bases_aslist);
1499 return NULL;
1500 }
1501 PyList_SET_ITEM(to_merge, n, bases_aslist);
Guido van Rossum1f121312002-11-14 19:49:16 +00001502
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001503 result = Py_BuildValue("[O]", (PyObject *)type);
1504 if (result == NULL) {
1505 Py_DECREF(to_merge);
1506 return NULL;
1507 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001508
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001509 ok = pmerge(result, to_merge);
1510 Py_DECREF(to_merge);
1511 if (ok < 0) {
1512 Py_DECREF(result);
1513 return NULL;
1514 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001515
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001516 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001517}
1518
1519static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001520mro_external(PyObject *self)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001521{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001522 PyTypeObject *type = (PyTypeObject *)self;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001523
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001524 return mro_implementation(type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001525}
1526
1527static int
1528mro_internal(PyTypeObject *type)
1529{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001530 PyObject *mro, *result, *tuple;
1531 int checkit = 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001532
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001533 if (Py_TYPE(type) == &PyType_Type) {
1534 result = mro_implementation(type);
1535 }
1536 else {
1537 static PyObject *mro_str;
1538 checkit = 1;
1539 mro = lookup_method((PyObject *)type, "mro", &mro_str);
1540 if (mro == NULL)
1541 return -1;
1542 result = PyObject_CallObject(mro, NULL);
1543 Py_DECREF(mro);
1544 }
1545 if (result == NULL)
1546 return -1;
1547 tuple = PySequence_Tuple(result);
1548 Py_DECREF(result);
1549 if (tuple == NULL)
1550 return -1;
1551 if (checkit) {
1552 Py_ssize_t i, len;
1553 PyObject *cls;
1554 PyTypeObject *solid;
Armin Rigo037d1e02005-12-29 17:07:39 +00001555
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001556 solid = solid_base(type);
Armin Rigo037d1e02005-12-29 17:07:39 +00001557
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001558 len = PyTuple_GET_SIZE(tuple);
Armin Rigo037d1e02005-12-29 17:07:39 +00001559
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001560 for (i = 0; i < len; i++) {
1561 PyTypeObject *t;
1562 cls = PyTuple_GET_ITEM(tuple, i);
1563 if (!PyType_Check(cls)) {
1564 PyErr_Format(PyExc_TypeError,
1565 "mro() returned a non-class ('%.500s')",
1566 Py_TYPE(cls)->tp_name);
1567 Py_DECREF(tuple);
1568 return -1;
1569 }
1570 t = (PyTypeObject*)cls;
1571 if (!PyType_IsSubtype(solid, solid_base(t))) {
1572 PyErr_Format(PyExc_TypeError,
1573 "mro() returned base with unsuitable layout ('%.500s')",
1574 t->tp_name);
1575 Py_DECREF(tuple);
1576 return -1;
1577 }
1578 }
1579 }
1580 type->tp_mro = tuple;
Christian Heimesa62da1d2008-01-12 19:39:10 +00001581
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001582 type_mro_modified(type, type->tp_mro);
1583 /* corner case: the old-style super class might have been hidden
1584 from the custom MRO */
1585 type_mro_modified(type, type->tp_bases);
Christian Heimesa62da1d2008-01-12 19:39:10 +00001586
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001587 PyType_Modified(type);
Christian Heimesa62da1d2008-01-12 19:39:10 +00001588
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001589 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001590}
1591
1592
1593/* Calculate the best base amongst multiple base classes.
1594 This is the first one that's on the path to the "solid base". */
1595
1596static PyTypeObject *
1597best_base(PyObject *bases)
1598{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001599 Py_ssize_t i, n;
1600 PyTypeObject *base, *winner, *candidate, *base_i;
1601 PyObject *base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001602
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001603 assert(PyTuple_Check(bases));
1604 n = PyTuple_GET_SIZE(bases);
1605 assert(n > 0);
1606 base = NULL;
1607 winner = NULL;
1608 for (i = 0; i < n; i++) {
1609 base_proto = PyTuple_GET_ITEM(bases, i);
1610 if (!PyType_Check(base_proto)) {
1611 PyErr_SetString(
1612 PyExc_TypeError,
1613 "bases must be types");
1614 return NULL;
1615 }
1616 base_i = (PyTypeObject *)base_proto;
1617 if (base_i->tp_dict == NULL) {
1618 if (PyType_Ready(base_i) < 0)
1619 return NULL;
1620 }
1621 candidate = solid_base(base_i);
1622 if (winner == NULL) {
1623 winner = candidate;
1624 base = base_i;
1625 }
1626 else if (PyType_IsSubtype(winner, candidate))
1627 ;
1628 else if (PyType_IsSubtype(candidate, winner)) {
1629 winner = candidate;
1630 base = base_i;
1631 }
1632 else {
1633 PyErr_SetString(
1634 PyExc_TypeError,
1635 "multiple bases have "
1636 "instance lay-out conflict");
1637 return NULL;
1638 }
1639 }
1640 if (base == NULL)
1641 PyErr_SetString(PyExc_TypeError,
1642 "a new-style class can't have only classic bases");
1643 return base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001644}
1645
1646static int
1647extra_ivars(PyTypeObject *type, PyTypeObject *base)
1648{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001649 size_t t_size = type->tp_basicsize;
1650 size_t b_size = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001651
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001652 assert(t_size >= b_size); /* Else type smaller than base! */
1653 if (type->tp_itemsize || base->tp_itemsize) {
1654 /* If itemsize is involved, stricter rules */
1655 return t_size != b_size ||
1656 type->tp_itemsize != base->tp_itemsize;
1657 }
1658 if (type->tp_weaklistoffset && base->tp_weaklistoffset == 0 &&
1659 type->tp_weaklistoffset + sizeof(PyObject *) == t_size &&
1660 type->tp_flags & Py_TPFLAGS_HEAPTYPE)
1661 t_size -= sizeof(PyObject *);
1662 if (type->tp_dictoffset && base->tp_dictoffset == 0 &&
1663 type->tp_dictoffset + sizeof(PyObject *) == t_size &&
1664 type->tp_flags & Py_TPFLAGS_HEAPTYPE)
1665 t_size -= sizeof(PyObject *);
Guido van Rossum9676b222001-08-17 20:32:36 +00001666
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001667 return t_size != b_size;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001668}
1669
1670static PyTypeObject *
1671solid_base(PyTypeObject *type)
1672{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001673 PyTypeObject *base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001674
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001675 if (type->tp_base)
1676 base = solid_base(type->tp_base);
1677 else
1678 base = &PyBaseObject_Type;
1679 if (extra_ivars(type, base))
1680 return type;
1681 else
1682 return base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001683}
1684
Jeremy Hylton938ace62002-07-17 16:30:39 +00001685static void object_dealloc(PyObject *);
1686static int object_init(PyObject *, PyObject *, PyObject *);
1687static int update_slot(PyTypeObject *, PyObject *);
1688static void fixup_slot_dispatchers(PyTypeObject *);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001689
Guido van Rossum360e4b82007-05-14 22:51:27 +00001690/*
1691 * Helpers for __dict__ descriptor. We don't want to expose the dicts
1692 * inherited from various builtin types. The builtin base usually provides
1693 * its own __dict__ descriptor, so we use that when we can.
1694 */
1695static PyTypeObject *
1696get_builtin_base_with_dict(PyTypeObject *type)
1697{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001698 while (type->tp_base != NULL) {
1699 if (type->tp_dictoffset != 0 &&
1700 !(type->tp_flags & Py_TPFLAGS_HEAPTYPE))
1701 return type;
1702 type = type->tp_base;
1703 }
1704 return NULL;
Guido van Rossum360e4b82007-05-14 22:51:27 +00001705}
1706
1707static PyObject *
1708get_dict_descriptor(PyTypeObject *type)
1709{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001710 static PyObject *dict_str;
1711 PyObject *descr;
Guido van Rossum360e4b82007-05-14 22:51:27 +00001712
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001713 if (dict_str == NULL) {
1714 dict_str = PyUnicode_InternFromString("__dict__");
1715 if (dict_str == NULL)
1716 return NULL;
1717 }
1718 descr = _PyType_Lookup(type, dict_str);
1719 if (descr == NULL || !PyDescr_IsData(descr))
1720 return NULL;
Guido van Rossum360e4b82007-05-14 22:51:27 +00001721
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001722 return descr;
Guido van Rossum360e4b82007-05-14 22:51:27 +00001723}
1724
1725static void
1726raise_dict_descr_error(PyObject *obj)
1727{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001728 PyErr_Format(PyExc_TypeError,
1729 "this __dict__ descriptor does not support "
1730 "'%.200s' objects", Py_TYPE(obj)->tp_name);
Guido van Rossum360e4b82007-05-14 22:51:27 +00001731}
1732
Tim Peters6d6c1a32001-08-02 04:15:00 +00001733static PyObject *
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001734subtype_dict(PyObject *obj, void *context)
1735{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001736 PyObject **dictptr;
1737 PyObject *dict;
1738 PyTypeObject *base;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001739
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001740 base = get_builtin_base_with_dict(Py_TYPE(obj));
1741 if (base != NULL) {
1742 descrgetfunc func;
1743 PyObject *descr = get_dict_descriptor(base);
1744 if (descr == NULL) {
1745 raise_dict_descr_error(obj);
1746 return NULL;
1747 }
1748 func = Py_TYPE(descr)->tp_descr_get;
1749 if (func == NULL) {
1750 raise_dict_descr_error(obj);
1751 return NULL;
1752 }
1753 return func(descr, obj, (PyObject *)(Py_TYPE(obj)));
1754 }
Guido van Rossum360e4b82007-05-14 22:51:27 +00001755
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001756 dictptr = _PyObject_GetDictPtr(obj);
1757 if (dictptr == NULL) {
1758 PyErr_SetString(PyExc_AttributeError,
1759 "This object has no __dict__");
1760 return NULL;
1761 }
1762 dict = *dictptr;
1763 if (dict == NULL)
1764 *dictptr = dict = PyDict_New();
1765 Py_XINCREF(dict);
1766 return dict;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001767}
1768
Guido van Rossum6661be32001-10-26 04:26:12 +00001769static int
1770subtype_setdict(PyObject *obj, PyObject *value, void *context)
1771{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001772 PyObject **dictptr;
1773 PyObject *dict;
1774 PyTypeObject *base;
Guido van Rossum6661be32001-10-26 04:26:12 +00001775
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001776 base = get_builtin_base_with_dict(Py_TYPE(obj));
1777 if (base != NULL) {
1778 descrsetfunc func;
1779 PyObject *descr = get_dict_descriptor(base);
1780 if (descr == NULL) {
1781 raise_dict_descr_error(obj);
1782 return -1;
1783 }
1784 func = Py_TYPE(descr)->tp_descr_set;
1785 if (func == NULL) {
1786 raise_dict_descr_error(obj);
1787 return -1;
1788 }
1789 return func(descr, obj, value);
1790 }
Guido van Rossum360e4b82007-05-14 22:51:27 +00001791
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001792 dictptr = _PyObject_GetDictPtr(obj);
1793 if (dictptr == NULL) {
1794 PyErr_SetString(PyExc_AttributeError,
1795 "This object has no __dict__");
1796 return -1;
1797 }
1798 if (value != NULL && !PyDict_Check(value)) {
1799 PyErr_Format(PyExc_TypeError,
1800 "__dict__ must be set to a dictionary, "
1801 "not a '%.200s'", Py_TYPE(value)->tp_name);
1802 return -1;
1803 }
1804 dict = *dictptr;
1805 Py_XINCREF(value);
1806 *dictptr = value;
1807 Py_XDECREF(dict);
1808 return 0;
Guido van Rossum6661be32001-10-26 04:26:12 +00001809}
1810
Guido van Rossumad47da02002-08-12 19:05:44 +00001811static PyObject *
1812subtype_getweakref(PyObject *obj, void *context)
1813{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001814 PyObject **weaklistptr;
1815 PyObject *result;
Guido van Rossumad47da02002-08-12 19:05:44 +00001816
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001817 if (Py_TYPE(obj)->tp_weaklistoffset == 0) {
1818 PyErr_SetString(PyExc_AttributeError,
1819 "This object has no __weakref__");
1820 return NULL;
1821 }
1822 assert(Py_TYPE(obj)->tp_weaklistoffset > 0);
1823 assert(Py_TYPE(obj)->tp_weaklistoffset + sizeof(PyObject *) <=
1824 (size_t)(Py_TYPE(obj)->tp_basicsize));
1825 weaklistptr = (PyObject **)
1826 ((char *)obj + Py_TYPE(obj)->tp_weaklistoffset);
1827 if (*weaklistptr == NULL)
1828 result = Py_None;
1829 else
1830 result = *weaklistptr;
1831 Py_INCREF(result);
1832 return result;
Guido van Rossumad47da02002-08-12 19:05:44 +00001833}
1834
Guido van Rossum373c7412003-01-07 13:41:37 +00001835/* Three variants on the subtype_getsets list. */
1836
1837static PyGetSetDef subtype_getsets_full[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001838 {"__dict__", subtype_dict, subtype_setdict,
1839 PyDoc_STR("dictionary for instance variables (if defined)")},
1840 {"__weakref__", subtype_getweakref, NULL,
1841 PyDoc_STR("list of weak references to the object (if defined)")},
1842 {0}
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001843};
1844
Guido van Rossum373c7412003-01-07 13:41:37 +00001845static PyGetSetDef subtype_getsets_dict_only[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001846 {"__dict__", subtype_dict, subtype_setdict,
1847 PyDoc_STR("dictionary for instance variables (if defined)")},
1848 {0}
Guido van Rossum373c7412003-01-07 13:41:37 +00001849};
1850
1851static PyGetSetDef subtype_getsets_weakref_only[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001852 {"__weakref__", subtype_getweakref, NULL,
1853 PyDoc_STR("list of weak references to the object (if defined)")},
1854 {0}
Guido van Rossum373c7412003-01-07 13:41:37 +00001855};
1856
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001857static int
1858valid_identifier(PyObject *s)
1859{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001860 if (!PyUnicode_Check(s)) {
1861 PyErr_Format(PyExc_TypeError,
1862 "__slots__ items must be strings, not '%.200s'",
1863 Py_TYPE(s)->tp_name);
1864 return 0;
1865 }
1866 if (!PyUnicode_IsIdentifier(s)) {
1867 PyErr_SetString(PyExc_TypeError,
1868 "__slots__ must be identifiers");
1869 return 0;
1870 }
1871 return 1;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001872}
1873
Guido van Rossumd8faa362007-04-27 19:54:29 +00001874/* Forward */
1875static int
1876object_init(PyObject *self, PyObject *args, PyObject *kwds);
1877
1878static int
1879type_init(PyObject *cls, PyObject *args, PyObject *kwds)
1880{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001881 int res;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001882
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001883 assert(args != NULL && PyTuple_Check(args));
1884 assert(kwds == NULL || PyDict_Check(kwds));
Guido van Rossumd8faa362007-04-27 19:54:29 +00001885
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001886 if (kwds != NULL && PyDict_Check(kwds) && PyDict_Size(kwds) != 0) {
1887 PyErr_SetString(PyExc_TypeError,
1888 "type.__init__() takes no keyword arguments");
1889 return -1;
1890 }
Guido van Rossumd8faa362007-04-27 19:54:29 +00001891
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001892 if (args != NULL && PyTuple_Check(args) &&
1893 (PyTuple_GET_SIZE(args) != 1 && PyTuple_GET_SIZE(args) != 3)) {
1894 PyErr_SetString(PyExc_TypeError,
1895 "type.__init__() takes 1 or 3 arguments");
1896 return -1;
1897 }
Guido van Rossumd8faa362007-04-27 19:54:29 +00001898
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001899 /* Call object.__init__(self) now. */
1900 /* XXX Could call super(type, cls).__init__() but what's the point? */
1901 args = PyTuple_GetSlice(args, 0, 0);
1902 res = object_init(cls, args, NULL);
1903 Py_DECREF(args);
1904 return res;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001905}
1906
Martin v. Löwis738236d2011-02-05 20:35:29 +00001907long
1908PyType_GetFlags(PyTypeObject *type)
1909{
1910 return type->tp_flags;
1911}
1912
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001913static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00001914type_new(PyTypeObject *metatype, PyObject *args, PyObject *kwds)
1915{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001916 PyObject *name, *bases, *dict;
1917 static char *kwlist[] = {"name", "bases", "dict", 0};
1918 PyObject *slots, *tmp, *newslots;
1919 PyTypeObject *type, *base, *tmptype, *winner;
1920 PyHeapTypeObject *et;
1921 PyMemberDef *mp;
1922 Py_ssize_t i, nbases, nslots, slotoffset, add_dict, add_weak;
1923 int j, may_add_dict, may_add_weak;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001924
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001925 assert(args != NULL && PyTuple_Check(args));
1926 assert(kwds == NULL || PyDict_Check(kwds));
Tim Peters3abca122001-10-27 19:37:48 +00001927
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001928 /* Special case: type(x) should return x->ob_type */
1929 {
1930 const Py_ssize_t nargs = PyTuple_GET_SIZE(args);
1931 const Py_ssize_t nkwds = kwds == NULL ? 0 : PyDict_Size(kwds);
Tim Peters3abca122001-10-27 19:37:48 +00001932
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001933 if (PyType_CheckExact(metatype) && nargs == 1 && nkwds == 0) {
1934 PyObject *x = PyTuple_GET_ITEM(args, 0);
1935 Py_INCREF(Py_TYPE(x));
1936 return (PyObject *) Py_TYPE(x);
1937 }
Tim Peters3abca122001-10-27 19:37:48 +00001938
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001939 /* SF bug 475327 -- if that didn't trigger, we need 3
1940 arguments. but PyArg_ParseTupleAndKeywords below may give
1941 a msg saying type() needs exactly 3. */
1942 if (nargs + nkwds != 3) {
1943 PyErr_SetString(PyExc_TypeError,
1944 "type() takes 1 or 3 arguments");
1945 return NULL;
1946 }
1947 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001948
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001949 /* Check arguments: (name, bases, dict) */
1950 if (!PyArg_ParseTupleAndKeywords(args, kwds, "UO!O!:type", kwlist,
1951 &name,
1952 &PyTuple_Type, &bases,
1953 &PyDict_Type, &dict))
1954 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001955
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001956 /* Determine the proper metatype to deal with this,
1957 and check for metatype conflicts while we're at it.
1958 Note that if some other metatype wins to contract,
1959 it's possible that its instances are not types. */
1960 nbases = PyTuple_GET_SIZE(bases);
1961 winner = metatype;
1962 for (i = 0; i < nbases; i++) {
1963 tmp = PyTuple_GET_ITEM(bases, i);
1964 tmptype = Py_TYPE(tmp);
1965 if (PyType_IsSubtype(winner, tmptype))
1966 continue;
1967 if (PyType_IsSubtype(tmptype, winner)) {
1968 winner = tmptype;
1969 continue;
1970 }
1971 PyErr_SetString(PyExc_TypeError,
1972 "metaclass conflict: "
1973 "the metaclass of a derived class "
1974 "must be a (non-strict) subclass "
1975 "of the metaclasses of all its bases");
1976 return NULL;
1977 }
1978 if (winner != metatype) {
1979 if (winner->tp_new != type_new) /* Pass it to the winner */
1980 return winner->tp_new(winner, args, kwds);
1981 metatype = winner;
1982 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001983
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001984 /* Adjust for empty tuple bases */
1985 if (nbases == 0) {
1986 bases = PyTuple_Pack(1, &PyBaseObject_Type);
1987 if (bases == NULL)
1988 return NULL;
1989 nbases = 1;
1990 }
1991 else
1992 Py_INCREF(bases);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001993
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001994 /* XXX From here until type is allocated, "return NULL" leaks bases! */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001995
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001996 /* Calculate best base, and check that all bases are type objects */
1997 base = best_base(bases);
1998 if (base == NULL) {
1999 Py_DECREF(bases);
2000 return NULL;
2001 }
2002 if (!PyType_HasFeature(base, Py_TPFLAGS_BASETYPE)) {
2003 PyErr_Format(PyExc_TypeError,
2004 "type '%.100s' is not an acceptable base type",
2005 base->tp_name);
2006 Py_DECREF(bases);
2007 return NULL;
2008 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002009
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002010 /* Check for a __slots__ sequence variable in dict, and count it */
2011 slots = PyDict_GetItemString(dict, "__slots__");
2012 nslots = 0;
2013 add_dict = 0;
2014 add_weak = 0;
2015 may_add_dict = base->tp_dictoffset == 0;
2016 may_add_weak = base->tp_weaklistoffset == 0 && base->tp_itemsize == 0;
2017 if (slots == NULL) {
2018 if (may_add_dict) {
2019 add_dict++;
2020 }
2021 if (may_add_weak) {
2022 add_weak++;
2023 }
2024 }
2025 else {
2026 /* Have slots */
Guido van Rossumad47da02002-08-12 19:05:44 +00002027
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002028 /* Make it into a tuple */
2029 if (PyUnicode_Check(slots))
2030 slots = PyTuple_Pack(1, slots);
2031 else
2032 slots = PySequence_Tuple(slots);
2033 if (slots == NULL) {
2034 Py_DECREF(bases);
2035 return NULL;
2036 }
2037 assert(PyTuple_Check(slots));
Guido van Rossumad47da02002-08-12 19:05:44 +00002038
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002039 /* Are slots allowed? */
2040 nslots = PyTuple_GET_SIZE(slots);
2041 if (nslots > 0 && base->tp_itemsize != 0) {
2042 PyErr_Format(PyExc_TypeError,
2043 "nonempty __slots__ "
2044 "not supported for subtype of '%s'",
2045 base->tp_name);
2046 bad_slots:
2047 Py_DECREF(bases);
2048 Py_DECREF(slots);
2049 return NULL;
2050 }
Guido van Rossumad47da02002-08-12 19:05:44 +00002051
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002052 /* Check for valid slot names and two special cases */
2053 for (i = 0; i < nslots; i++) {
2054 PyObject *tmp = PyTuple_GET_ITEM(slots, i);
2055 if (!valid_identifier(tmp))
2056 goto bad_slots;
2057 assert(PyUnicode_Check(tmp));
2058 if (PyUnicode_CompareWithASCIIString(tmp, "__dict__") == 0) {
2059 if (!may_add_dict || add_dict) {
2060 PyErr_SetString(PyExc_TypeError,
2061 "__dict__ slot disallowed: "
2062 "we already got one");
2063 goto bad_slots;
2064 }
2065 add_dict++;
2066 }
2067 if (PyUnicode_CompareWithASCIIString(tmp, "__weakref__") == 0) {
2068 if (!may_add_weak || add_weak) {
2069 PyErr_SetString(PyExc_TypeError,
2070 "__weakref__ slot disallowed: "
2071 "either we already got one, "
2072 "or __itemsize__ != 0");
2073 goto bad_slots;
2074 }
2075 add_weak++;
2076 }
2077 }
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00002078
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002079 /* Copy slots into a list, mangle names and sort them.
2080 Sorted names are needed for __class__ assignment.
2081 Convert them back to tuple at the end.
2082 */
2083 newslots = PyList_New(nslots - add_dict - add_weak);
2084 if (newslots == NULL)
2085 goto bad_slots;
2086 for (i = j = 0; i < nslots; i++) {
2087 tmp = PyTuple_GET_ITEM(slots, i);
2088 if ((add_dict &&
2089 PyUnicode_CompareWithASCIIString(tmp, "__dict__") == 0) ||
2090 (add_weak &&
2091 PyUnicode_CompareWithASCIIString(tmp, "__weakref__") == 0))
2092 continue;
2093 tmp =_Py_Mangle(name, tmp);
2094 if (!tmp)
2095 goto bad_slots;
2096 PyList_SET_ITEM(newslots, j, tmp);
2097 j++;
2098 }
2099 assert(j == nslots - add_dict - add_weak);
2100 nslots = j;
2101 Py_DECREF(slots);
2102 if (PyList_Sort(newslots) == -1) {
2103 Py_DECREF(bases);
2104 Py_DECREF(newslots);
2105 return NULL;
2106 }
2107 slots = PyList_AsTuple(newslots);
2108 Py_DECREF(newslots);
2109 if (slots == NULL) {
2110 Py_DECREF(bases);
2111 return NULL;
2112 }
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00002113
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002114 /* Secondary bases may provide weakrefs or dict */
2115 if (nbases > 1 &&
2116 ((may_add_dict && !add_dict) ||
2117 (may_add_weak && !add_weak))) {
2118 for (i = 0; i < nbases; i++) {
2119 tmp = PyTuple_GET_ITEM(bases, i);
2120 if (tmp == (PyObject *)base)
2121 continue; /* Skip primary base */
2122 assert(PyType_Check(tmp));
2123 tmptype = (PyTypeObject *)tmp;
2124 if (may_add_dict && !add_dict &&
2125 tmptype->tp_dictoffset != 0)
2126 add_dict++;
2127 if (may_add_weak && !add_weak &&
2128 tmptype->tp_weaklistoffset != 0)
2129 add_weak++;
2130 if (may_add_dict && !add_dict)
2131 continue;
2132 if (may_add_weak && !add_weak)
2133 continue;
2134 /* Nothing more to check */
2135 break;
2136 }
2137 }
2138 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002139
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002140 /* XXX From here until type is safely allocated,
2141 "return NULL" may leak slots! */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002142
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002143 /* Allocate the type object */
2144 type = (PyTypeObject *)metatype->tp_alloc(metatype, nslots);
2145 if (type == NULL) {
2146 Py_XDECREF(slots);
2147 Py_DECREF(bases);
2148 return NULL;
2149 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002150
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002151 /* Keep name and slots alive in the extended type object */
2152 et = (PyHeapTypeObject *)type;
2153 Py_INCREF(name);
2154 et->ht_name = name;
2155 et->ht_slots = slots;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002156
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002157 /* Initialize tp_flags */
2158 type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE |
2159 Py_TPFLAGS_BASETYPE;
2160 if (base->tp_flags & Py_TPFLAGS_HAVE_GC)
2161 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossumdc91b992001-08-08 22:26:22 +00002162
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002163 /* Initialize essential fields */
2164 type->tp_as_number = &et->as_number;
2165 type->tp_as_sequence = &et->as_sequence;
2166 type->tp_as_mapping = &et->as_mapping;
2167 type->tp_as_buffer = &et->as_buffer;
2168 type->tp_name = _PyUnicode_AsString(name);
2169 if (!type->tp_name) {
2170 Py_DECREF(type);
2171 return NULL;
2172 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002173
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002174 /* Set tp_base and tp_bases */
2175 type->tp_bases = bases;
2176 Py_INCREF(base);
2177 type->tp_base = base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002178
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002179 /* Initialize tp_dict from passed-in dict */
2180 type->tp_dict = dict = PyDict_Copy(dict);
2181 if (dict == NULL) {
2182 Py_DECREF(type);
2183 return NULL;
2184 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002185
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002186 /* Set __module__ in the dict */
2187 if (PyDict_GetItemString(dict, "__module__") == NULL) {
2188 tmp = PyEval_GetGlobals();
2189 if (tmp != NULL) {
2190 tmp = PyDict_GetItemString(tmp, "__name__");
2191 if (tmp != NULL) {
2192 if (PyDict_SetItemString(dict, "__module__",
2193 tmp) < 0)
2194 return NULL;
2195 }
2196 }
2197 }
Guido van Rossumc3542212001-08-16 09:18:56 +00002198
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002199 /* Set tp_doc to a copy of dict['__doc__'], if the latter is there
2200 and is a string. The __doc__ accessor will first look for tp_doc;
2201 if that fails, it will still look into __dict__.
2202 */
2203 {
2204 PyObject *doc = PyDict_GetItemString(dict, "__doc__");
2205 if (doc != NULL && PyUnicode_Check(doc)) {
2206 Py_ssize_t len;
2207 char *doc_str;
2208 char *tp_doc;
Alexandre Vassalottia85998a2008-05-03 18:24:43 +00002209
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002210 doc_str = _PyUnicode_AsString(doc);
2211 if (doc_str == NULL) {
2212 Py_DECREF(type);
2213 return NULL;
2214 }
2215 /* Silently truncate the docstring if it contains null bytes. */
2216 len = strlen(doc_str);
2217 tp_doc = (char *)PyObject_MALLOC(len + 1);
2218 if (tp_doc == NULL) {
2219 Py_DECREF(type);
2220 return NULL;
2221 }
2222 memcpy(tp_doc, doc_str, len + 1);
2223 type->tp_doc = tp_doc;
2224 }
2225 }
Tim Peters2f93e282001-10-04 05:27:00 +00002226
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002227 /* Special-case __new__: if it's a plain function,
2228 make it a static function */
2229 tmp = PyDict_GetItemString(dict, "__new__");
2230 if (tmp != NULL && PyFunction_Check(tmp)) {
2231 tmp = PyStaticMethod_New(tmp);
2232 if (tmp == NULL) {
2233 Py_DECREF(type);
2234 return NULL;
2235 }
2236 PyDict_SetItemString(dict, "__new__", tmp);
2237 Py_DECREF(tmp);
2238 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002239
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002240 /* Add descriptors for custom slots from __slots__, or for __dict__ */
2241 mp = PyHeapType_GET_MEMBERS(et);
2242 slotoffset = base->tp_basicsize;
2243 if (slots != NULL) {
2244 for (i = 0; i < nslots; i++, mp++) {
2245 mp->name = _PyUnicode_AsString(
2246 PyTuple_GET_ITEM(slots, i));
Victor Stinnere5f99f32010-05-19 01:42:46 +00002247 if (mp->name == NULL) {
2248 Py_DECREF(type);
2249 return NULL;
2250 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002251 mp->type = T_OBJECT_EX;
2252 mp->offset = slotoffset;
Guido van Rossumd8faa362007-04-27 19:54:29 +00002253
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002254 /* __dict__ and __weakref__ are already filtered out */
2255 assert(strcmp(mp->name, "__dict__") != 0);
2256 assert(strcmp(mp->name, "__weakref__") != 0);
Guido van Rossumd8faa362007-04-27 19:54:29 +00002257
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002258 slotoffset += sizeof(PyObject *);
2259 }
2260 }
2261 if (add_dict) {
2262 if (base->tp_itemsize)
2263 type->tp_dictoffset = -(long)sizeof(PyObject *);
2264 else
2265 type->tp_dictoffset = slotoffset;
2266 slotoffset += sizeof(PyObject *);
2267 }
2268 if (add_weak) {
2269 assert(!base->tp_itemsize);
2270 type->tp_weaklistoffset = slotoffset;
2271 slotoffset += sizeof(PyObject *);
2272 }
2273 type->tp_basicsize = slotoffset;
2274 type->tp_itemsize = base->tp_itemsize;
2275 type->tp_members = PyHeapType_GET_MEMBERS(et);
Guido van Rossum373c7412003-01-07 13:41:37 +00002276
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002277 if (type->tp_weaklistoffset && type->tp_dictoffset)
2278 type->tp_getset = subtype_getsets_full;
2279 else if (type->tp_weaklistoffset && !type->tp_dictoffset)
2280 type->tp_getset = subtype_getsets_weakref_only;
2281 else if (!type->tp_weaklistoffset && type->tp_dictoffset)
2282 type->tp_getset = subtype_getsets_dict_only;
2283 else
2284 type->tp_getset = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002285
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002286 /* Special case some slots */
2287 if (type->tp_dictoffset != 0 || nslots > 0) {
2288 if (base->tp_getattr == NULL && base->tp_getattro == NULL)
2289 type->tp_getattro = PyObject_GenericGetAttr;
2290 if (base->tp_setattr == NULL && base->tp_setattro == NULL)
2291 type->tp_setattro = PyObject_GenericSetAttr;
2292 }
2293 type->tp_dealloc = subtype_dealloc;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002294
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002295 /* Enable GC unless there are really no instance variables possible */
2296 if (!(type->tp_basicsize == sizeof(PyObject) &&
2297 type->tp_itemsize == 0))
2298 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossum9475a232001-10-05 20:51:39 +00002299
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002300 /* Always override allocation strategy to use regular heap */
2301 type->tp_alloc = PyType_GenericAlloc;
2302 if (type->tp_flags & Py_TPFLAGS_HAVE_GC) {
2303 type->tp_free = PyObject_GC_Del;
2304 type->tp_traverse = subtype_traverse;
2305 type->tp_clear = subtype_clear;
2306 }
2307 else
2308 type->tp_free = PyObject_Del;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002309
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002310 /* Initialize the rest */
2311 if (PyType_Ready(type) < 0) {
2312 Py_DECREF(type);
2313 return NULL;
2314 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002315
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002316 /* Put the proper slots in place */
2317 fixup_slot_dispatchers(type);
Guido van Rossumf040ede2001-08-07 16:40:56 +00002318
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002319 return (PyObject *)type;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002320}
2321
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002322static short slotoffsets[] = {
2323 -1, /* invalid slot */
2324#include "typeslots.inc"
2325};
2326
2327PyObject* PyType_FromSpec(PyType_Spec *spec)
2328{
2329 PyHeapTypeObject *res = (PyHeapTypeObject*)PyType_GenericAlloc(&PyType_Type, 0);
2330 char *res_start = (char*)res;
2331 PyType_Slot *slot;
2332
Martin v. Löwis5e06a5d2011-02-21 16:24:00 +00002333 if (res == NULL)
2334 return NULL;
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002335 res->ht_name = PyUnicode_FromString(spec->name);
2336 if (!res->ht_name)
2337 goto fail;
2338 res->ht_type.tp_name = _PyUnicode_AsString(res->ht_name);
2339 if (!res->ht_type.tp_name)
2340 goto fail;
2341
2342 res->ht_type.tp_basicsize = spec->basicsize;
2343 res->ht_type.tp_itemsize = spec->itemsize;
2344 res->ht_type.tp_flags = spec->flags | Py_TPFLAGS_HEAPTYPE;
Victor Stinner0fcab4a2011-01-04 12:59:15 +00002345
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002346 for (slot = spec->slots; slot->slot; slot++) {
2347 if (slot->slot >= sizeof(slotoffsets)/sizeof(slotoffsets[0])) {
2348 PyErr_SetString(PyExc_RuntimeError, "invalid slot offset");
2349 goto fail;
2350 }
2351 *(void**)(res_start + slotoffsets[slot->slot]) = slot->pfunc;
Georg Brandl032400b2011-02-19 21:47:02 +00002352
2353 /* need to make a copy of the docstring slot, which usually
2354 points to a static string literal */
2355 if (slot->slot == Py_tp_doc) {
2356 ssize_t len = strlen(slot->pfunc)+1;
2357 char *tp_doc = PyObject_MALLOC(len);
2358 if (tp_doc == NULL)
2359 goto fail;
2360 memcpy(tp_doc, slot->pfunc, len);
2361 res->ht_type.tp_doc = tp_doc;
2362 }
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002363 }
2364
2365 return (PyObject*)res;
Victor Stinner0fcab4a2011-01-04 12:59:15 +00002366
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002367 fail:
2368 Py_DECREF(res);
2369 return NULL;
2370}
2371
2372
Tim Peters6d6c1a32001-08-02 04:15:00 +00002373/* Internal API to look for a name through the MRO.
2374 This returns a borrowed reference, and doesn't set an exception! */
2375PyObject *
2376_PyType_Lookup(PyTypeObject *type, PyObject *name)
2377{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002378 Py_ssize_t i, n;
2379 PyObject *mro, *res, *base, *dict;
2380 unsigned int h;
Christian Heimesa62da1d2008-01-12 19:39:10 +00002381
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002382 if (MCACHE_CACHEABLE_NAME(name) &&
2383 PyType_HasFeature(type, Py_TPFLAGS_VALID_VERSION_TAG)) {
2384 /* fast path */
2385 h = MCACHE_HASH_METHOD(type, name);
2386 if (method_cache[h].version == type->tp_version_tag &&
2387 method_cache[h].name == name)
2388 return method_cache[h].value;
2389 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002390
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002391 /* Look in tp_dict of types in MRO */
2392 mro = type->tp_mro;
Guido van Rossum23094982002-06-10 14:30:43 +00002393
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002394 /* If mro is NULL, the type is either not yet initialized
2395 by PyType_Ready(), or already cleared by type_clear().
2396 Either way the safest thing to do is to return NULL. */
2397 if (mro == NULL)
2398 return NULL;
Guido van Rossum23094982002-06-10 14:30:43 +00002399
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002400 res = NULL;
2401 assert(PyTuple_Check(mro));
2402 n = PyTuple_GET_SIZE(mro);
2403 for (i = 0; i < n; i++) {
2404 base = PyTuple_GET_ITEM(mro, i);
2405 assert(PyType_Check(base));
2406 dict = ((PyTypeObject *)base)->tp_dict;
2407 assert(dict && PyDict_Check(dict));
2408 res = PyDict_GetItem(dict, name);
2409 if (res != NULL)
2410 break;
2411 }
Christian Heimesa62da1d2008-01-12 19:39:10 +00002412
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002413 if (MCACHE_CACHEABLE_NAME(name) && assign_version_tag(type)) {
2414 h = MCACHE_HASH_METHOD(type, name);
2415 method_cache[h].version = type->tp_version_tag;
2416 method_cache[h].value = res; /* borrowed */
2417 Py_INCREF(name);
2418 Py_DECREF(method_cache[h].name);
2419 method_cache[h].name = name;
2420 }
2421 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002422}
2423
2424/* This is similar to PyObject_GenericGetAttr(),
2425 but uses _PyType_Lookup() instead of just looking in type->tp_dict. */
2426static PyObject *
2427type_getattro(PyTypeObject *type, PyObject *name)
2428{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002429 PyTypeObject *metatype = Py_TYPE(type);
2430 PyObject *meta_attribute, *attribute;
2431 descrgetfunc meta_get;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002432
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002433 /* Initialize this type (we'll assume the metatype is initialized) */
2434 if (type->tp_dict == NULL) {
2435 if (PyType_Ready(type) < 0)
2436 return NULL;
2437 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002438
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002439 /* No readable descriptor found yet */
2440 meta_get = NULL;
Tim Peters34592512002-07-11 06:23:50 +00002441
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002442 /* Look for the attribute in the metatype */
2443 meta_attribute = _PyType_Lookup(metatype, name);
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002444
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002445 if (meta_attribute != NULL) {
2446 meta_get = Py_TYPE(meta_attribute)->tp_descr_get;
Tim Peters34592512002-07-11 06:23:50 +00002447
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002448 if (meta_get != NULL && PyDescr_IsData(meta_attribute)) {
2449 /* Data descriptors implement tp_descr_set to intercept
2450 * writes. Assume the attribute is not overridden in
2451 * type's tp_dict (and bases): call the descriptor now.
2452 */
2453 return meta_get(meta_attribute, (PyObject *)type,
2454 (PyObject *)metatype);
2455 }
2456 Py_INCREF(meta_attribute);
2457 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002458
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002459 /* No data descriptor found on metatype. Look in tp_dict of this
2460 * type and its bases */
2461 attribute = _PyType_Lookup(type, name);
2462 if (attribute != NULL) {
2463 /* Implement descriptor functionality, if any */
2464 descrgetfunc local_get = Py_TYPE(attribute)->tp_descr_get;
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00002465
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002466 Py_XDECREF(meta_attribute);
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00002467
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002468 if (local_get != NULL) {
2469 /* NULL 2nd argument indicates the descriptor was
2470 * found on the target object itself (or a base) */
2471 return local_get(attribute, (PyObject *)NULL,
2472 (PyObject *)type);
2473 }
Tim Peters34592512002-07-11 06:23:50 +00002474
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002475 Py_INCREF(attribute);
2476 return attribute;
2477 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002478
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002479 /* No attribute found in local __dict__ (or bases): use the
2480 * descriptor from the metatype, if any */
2481 if (meta_get != NULL) {
2482 PyObject *res;
2483 res = meta_get(meta_attribute, (PyObject *)type,
2484 (PyObject *)metatype);
2485 Py_DECREF(meta_attribute);
2486 return res;
2487 }
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002488
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002489 /* If an ordinary attribute was found on the metatype, return it now */
2490 if (meta_attribute != NULL) {
2491 return meta_attribute;
2492 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002493
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002494 /* Give up */
2495 PyErr_Format(PyExc_AttributeError,
2496 "type object '%.50s' has no attribute '%U'",
2497 type->tp_name, name);
2498 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002499}
2500
2501static int
2502type_setattro(PyTypeObject *type, PyObject *name, PyObject *value)
2503{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002504 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
2505 PyErr_Format(
2506 PyExc_TypeError,
2507 "can't set attributes of built-in/extension type '%s'",
2508 type->tp_name);
2509 return -1;
2510 }
2511 if (PyObject_GenericSetAttr((PyObject *)type, name, value) < 0)
2512 return -1;
2513 return update_slot(type, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002514}
2515
2516static void
2517type_dealloc(PyTypeObject *type)
2518{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002519 PyHeapTypeObject *et;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002520
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002521 /* Assert this is a heap-allocated type object */
2522 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
2523 _PyObject_GC_UNTRACK(type);
2524 PyObject_ClearWeakRefs((PyObject *)type);
2525 et = (PyHeapTypeObject *)type;
2526 Py_XDECREF(type->tp_base);
2527 Py_XDECREF(type->tp_dict);
2528 Py_XDECREF(type->tp_bases);
2529 Py_XDECREF(type->tp_mro);
2530 Py_XDECREF(type->tp_cache);
2531 Py_XDECREF(type->tp_subclasses);
2532 /* A type's tp_doc is heap allocated, unlike the tp_doc slots
2533 * of most other objects. It's okay to cast it to char *.
2534 */
2535 PyObject_Free((char *)type->tp_doc);
2536 Py_XDECREF(et->ht_name);
2537 Py_XDECREF(et->ht_slots);
2538 Py_TYPE(type)->tp_free((PyObject *)type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002539}
2540
Guido van Rossum1c450732001-10-08 15:18:27 +00002541static PyObject *
2542type_subclasses(PyTypeObject *type, PyObject *args_ignored)
2543{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002544 PyObject *list, *raw, *ref;
2545 Py_ssize_t i, n;
Guido van Rossum1c450732001-10-08 15:18:27 +00002546
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002547 list = PyList_New(0);
2548 if (list == NULL)
2549 return NULL;
2550 raw = type->tp_subclasses;
2551 if (raw == NULL)
2552 return list;
2553 assert(PyList_Check(raw));
2554 n = PyList_GET_SIZE(raw);
2555 for (i = 0; i < n; i++) {
2556 ref = PyList_GET_ITEM(raw, i);
2557 assert(PyWeakref_CheckRef(ref));
2558 ref = PyWeakref_GET_OBJECT(ref);
2559 if (ref != Py_None) {
2560 if (PyList_Append(list, ref) < 0) {
2561 Py_DECREF(list);
2562 return NULL;
2563 }
2564 }
2565 }
2566 return list;
Guido van Rossum1c450732001-10-08 15:18:27 +00002567}
2568
Guido van Rossum47374822007-08-02 16:48:17 +00002569static PyObject *
2570type_prepare(PyObject *self, PyObject *args, PyObject *kwds)
2571{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002572 return PyDict_New();
Guido van Rossum47374822007-08-02 16:48:17 +00002573}
2574
Benjamin Peterson82b00c12011-05-24 11:09:06 -05002575/*
2576 Merge the __dict__ of aclass into dict, and recursively also all
2577 the __dict__s of aclass's base classes. The order of merging isn't
2578 defined, as it's expected that only the final set of dict keys is
2579 interesting.
2580 Return 0 on success, -1 on error.
2581*/
2582
2583static int
2584merge_class_dict(PyObject *dict, PyObject *aclass)
2585{
2586 PyObject *classdict;
2587 PyObject *bases;
2588
2589 assert(PyDict_Check(dict));
2590 assert(aclass);
2591
2592 /* Merge in the type's dict (if any). */
2593 classdict = PyObject_GetAttrString(aclass, "__dict__");
2594 if (classdict == NULL)
2595 PyErr_Clear();
2596 else {
2597 int status = PyDict_Update(dict, classdict);
2598 Py_DECREF(classdict);
2599 if (status < 0)
2600 return -1;
2601 }
2602
2603 /* Recursively merge in the base types' (if any) dicts. */
2604 bases = PyObject_GetAttrString(aclass, "__bases__");
2605 if (bases == NULL)
2606 PyErr_Clear();
2607 else {
2608 /* We have no guarantee that bases is a real tuple */
2609 Py_ssize_t i, n;
2610 n = PySequence_Size(bases); /* This better be right */
2611 if (n < 0)
2612 PyErr_Clear();
2613 else {
2614 for (i = 0; i < n; i++) {
2615 int status;
2616 PyObject *base = PySequence_GetItem(bases, i);
2617 if (base == NULL) {
2618 Py_DECREF(bases);
2619 return -1;
2620 }
2621 status = merge_class_dict(dict, base);
2622 Py_DECREF(base);
2623 if (status < 0) {
2624 Py_DECREF(bases);
2625 return -1;
2626 }
2627 }
2628 }
2629 Py_DECREF(bases);
2630 }
2631 return 0;
2632}
2633
2634/* __dir__ for type objects: returns __dict__ and __bases__.
2635 We deliberately don't suck up its __class__, as methods belonging to the
2636 metaclass would probably be more confusing than helpful.
2637*/
2638static PyObject *
2639type_dir(PyObject *self, PyObject *args)
2640{
2641 PyObject *result = NULL;
2642 PyObject *dict = PyDict_New();
2643
2644 if (dict != NULL && merge_class_dict(dict, self) == 0)
2645 result = PyDict_Keys(dict);
2646
2647 Py_XDECREF(dict);
2648 return result;
2649}
2650
Tim Peters6d6c1a32001-08-02 04:15:00 +00002651static PyMethodDef type_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002652 {"mro", (PyCFunction)mro_external, METH_NOARGS,
2653 PyDoc_STR("mro() -> list\nreturn a type's method resolution order")},
2654 {"__subclasses__", (PyCFunction)type_subclasses, METH_NOARGS,
2655 PyDoc_STR("__subclasses__() -> list of immediate subclasses")},
2656 {"__prepare__", (PyCFunction)type_prepare,
2657 METH_VARARGS | METH_KEYWORDS | METH_CLASS,
2658 PyDoc_STR("__prepare__() -> dict\n"
2659 "used to create the namespace for the class statement")},
2660 {"__instancecheck__", type___instancecheck__, METH_O,
Benjamin Petersonfbe56bb2011-05-24 12:42:51 -05002661 PyDoc_STR("__instancecheck__() -> bool\ncheck if an object is an instance")},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002662 {"__subclasscheck__", type___subclasscheck__, METH_O,
Benjamin Petersonfbe56bb2011-05-24 12:42:51 -05002663 PyDoc_STR("__subclasscheck__() -> bool\ncheck if a class is a subclass")},
Benjamin Peterson82b00c12011-05-24 11:09:06 -05002664 {"__dir__", type_dir, METH_NOARGS,
Benjamin Petersonc7284122011-05-24 12:46:15 -05002665 PyDoc_STR("__dir__() -> list\nspecialized __dir__ implementation for types")},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002666 {0}
Tim Peters6d6c1a32001-08-02 04:15:00 +00002667};
2668
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002669PyDoc_STRVAR(type_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00002670"type(object) -> the object's type\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002671"type(name, bases, dict) -> a new type");
Tim Peters6d6c1a32001-08-02 04:15:00 +00002672
Guido van Rossum048eb752001-10-02 21:24:57 +00002673static int
2674type_traverse(PyTypeObject *type, visitproc visit, void *arg)
2675{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002676 /* Because of type_is_gc(), the collector only calls this
2677 for heaptypes. */
2678 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002679
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002680 Py_VISIT(type->tp_dict);
2681 Py_VISIT(type->tp_cache);
2682 Py_VISIT(type->tp_mro);
2683 Py_VISIT(type->tp_bases);
2684 Py_VISIT(type->tp_base);
Guido van Rossuma3862092002-06-10 15:24:42 +00002685
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002686 /* There's no need to visit type->tp_subclasses or
2687 ((PyHeapTypeObject *)type)->ht_slots, because they can't be involved
2688 in cycles; tp_subclasses is a list of weak references,
2689 and slots is a tuple of strings. */
Guido van Rossum048eb752001-10-02 21:24:57 +00002690
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002691 return 0;
Guido van Rossum048eb752001-10-02 21:24:57 +00002692}
2693
2694static int
2695type_clear(PyTypeObject *type)
2696{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002697 /* Because of type_is_gc(), the collector only calls this
2698 for heaptypes. */
2699 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002700
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002701 /* The only field we need to clear is tp_mro, which is part of a
2702 hard cycle (its first element is the class itself) that won't
2703 be broken otherwise (it's a tuple and tuples don't have a
2704 tp_clear handler). None of the other fields need to be
2705 cleared, and here's why:
Guido van Rossum048eb752001-10-02 21:24:57 +00002706
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002707 tp_dict:
2708 It is a dict, so the collector will call its tp_clear.
Guido van Rossuma3862092002-06-10 15:24:42 +00002709
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002710 tp_cache:
2711 Not used; if it were, it would be a dict.
Guido van Rossuma3862092002-06-10 15:24:42 +00002712
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002713 tp_bases, tp_base:
2714 If these are involved in a cycle, there must be at least
2715 one other, mutable object in the cycle, e.g. a base
2716 class's dict; the cycle will be broken that way.
Guido van Rossuma3862092002-06-10 15:24:42 +00002717
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002718 tp_subclasses:
2719 A list of weak references can't be part of a cycle; and
2720 lists have their own tp_clear.
Guido van Rossuma3862092002-06-10 15:24:42 +00002721
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002722 slots (in PyHeapTypeObject):
2723 A tuple of strings can't be part of a cycle.
2724 */
Guido van Rossuma3862092002-06-10 15:24:42 +00002725
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002726 Py_CLEAR(type->tp_mro);
Guido van Rossum048eb752001-10-02 21:24:57 +00002727
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002728 return 0;
Guido van Rossum048eb752001-10-02 21:24:57 +00002729}
2730
2731static int
2732type_is_gc(PyTypeObject *type)
2733{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002734 return type->tp_flags & Py_TPFLAGS_HEAPTYPE;
Guido van Rossum048eb752001-10-02 21:24:57 +00002735}
2736
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002737PyTypeObject PyType_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002738 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2739 "type", /* tp_name */
2740 sizeof(PyHeapTypeObject), /* tp_basicsize */
2741 sizeof(PyMemberDef), /* tp_itemsize */
2742 (destructor)type_dealloc, /* tp_dealloc */
2743 0, /* tp_print */
2744 0, /* tp_getattr */
2745 0, /* tp_setattr */
2746 0, /* tp_reserved */
2747 (reprfunc)type_repr, /* tp_repr */
2748 0, /* tp_as_number */
2749 0, /* tp_as_sequence */
2750 0, /* tp_as_mapping */
2751 0, /* tp_hash */
2752 (ternaryfunc)type_call, /* tp_call */
2753 0, /* tp_str */
2754 (getattrofunc)type_getattro, /* tp_getattro */
2755 (setattrofunc)type_setattro, /* tp_setattro */
2756 0, /* tp_as_buffer */
2757 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
2758 Py_TPFLAGS_BASETYPE | Py_TPFLAGS_TYPE_SUBCLASS, /* tp_flags */
2759 type_doc, /* tp_doc */
2760 (traverseproc)type_traverse, /* tp_traverse */
2761 (inquiry)type_clear, /* tp_clear */
2762 0, /* tp_richcompare */
2763 offsetof(PyTypeObject, tp_weaklist), /* tp_weaklistoffset */
2764 0, /* tp_iter */
2765 0, /* tp_iternext */
2766 type_methods, /* tp_methods */
2767 type_members, /* tp_members */
2768 type_getsets, /* tp_getset */
2769 0, /* tp_base */
2770 0, /* tp_dict */
2771 0, /* tp_descr_get */
2772 0, /* tp_descr_set */
2773 offsetof(PyTypeObject, tp_dict), /* tp_dictoffset */
2774 type_init, /* tp_init */
2775 0, /* tp_alloc */
2776 type_new, /* tp_new */
2777 PyObject_GC_Del, /* tp_free */
2778 (inquiry)type_is_gc, /* tp_is_gc */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002779};
Tim Peters6d6c1a32001-08-02 04:15:00 +00002780
2781
2782/* The base type of all types (eventually)... except itself. */
2783
Guido van Rossumd8faa362007-04-27 19:54:29 +00002784/* You may wonder why object.__new__() only complains about arguments
2785 when object.__init__() is not overridden, and vice versa.
2786
2787 Consider the use cases:
2788
2789 1. When neither is overridden, we want to hear complaints about
2790 excess (i.e., any) arguments, since their presence could
2791 indicate there's a bug.
2792
2793 2. When defining an Immutable type, we are likely to override only
2794 __new__(), since __init__() is called too late to initialize an
2795 Immutable object. Since __new__() defines the signature for the
2796 type, it would be a pain to have to override __init__() just to
2797 stop it from complaining about excess arguments.
2798
2799 3. When defining a Mutable type, we are likely to override only
2800 __init__(). So here the converse reasoning applies: we don't
2801 want to have to override __new__() just to stop it from
2802 complaining.
2803
2804 4. When __init__() is overridden, and the subclass __init__() calls
2805 object.__init__(), the latter should complain about excess
2806 arguments; ditto for __new__().
2807
2808 Use cases 2 and 3 make it unattractive to unconditionally check for
2809 excess arguments. The best solution that addresses all four use
2810 cases is as follows: __init__() complains about excess arguments
2811 unless __new__() is overridden and __init__() is not overridden
2812 (IOW, if __init__() is overridden or __new__() is not overridden);
2813 symmetrically, __new__() complains about excess arguments unless
2814 __init__() is overridden and __new__() is not overridden
2815 (IOW, if __new__() is overridden or __init__() is not overridden).
2816
2817 However, for backwards compatibility, this breaks too much code.
2818 Therefore, in 2.6, we'll *warn* about excess arguments when both
2819 methods are overridden; for all other cases we'll use the above
2820 rules.
2821
2822*/
2823
2824/* Forward */
2825static PyObject *
2826object_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
2827
2828static int
2829excess_args(PyObject *args, PyObject *kwds)
2830{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002831 return PyTuple_GET_SIZE(args) ||
2832 (kwds && PyDict_Check(kwds) && PyDict_Size(kwds));
Guido van Rossumd8faa362007-04-27 19:54:29 +00002833}
2834
Tim Peters6d6c1a32001-08-02 04:15:00 +00002835static int
2836object_init(PyObject *self, PyObject *args, PyObject *kwds)
2837{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002838 int err = 0;
2839 if (excess_args(args, kwds)) {
2840 PyTypeObject *type = Py_TYPE(self);
2841 if (type->tp_init != object_init &&
2842 type->tp_new != object_new)
2843 {
2844 err = PyErr_WarnEx(PyExc_DeprecationWarning,
2845 "object.__init__() takes no parameters",
2846 1);
2847 }
2848 else if (type->tp_init != object_init ||
2849 type->tp_new == object_new)
2850 {
2851 PyErr_SetString(PyExc_TypeError,
2852 "object.__init__() takes no parameters");
2853 err = -1;
2854 }
2855 }
2856 return err;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002857}
2858
Guido van Rossum298e4212003-02-13 16:30:16 +00002859static PyObject *
2860object_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2861{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002862 int err = 0;
2863 if (excess_args(args, kwds)) {
2864 if (type->tp_new != object_new &&
2865 type->tp_init != object_init)
2866 {
2867 err = PyErr_WarnEx(PyExc_DeprecationWarning,
2868 "object.__new__() takes no parameters",
2869 1);
2870 }
2871 else if (type->tp_new != object_new ||
2872 type->tp_init == object_init)
2873 {
2874 PyErr_SetString(PyExc_TypeError,
2875 "object.__new__() takes no parameters");
2876 err = -1;
2877 }
2878 }
2879 if (err < 0)
2880 return NULL;
Christian Heimes9e7f1d22008-02-28 12:27:11 +00002881
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002882 if (type->tp_flags & Py_TPFLAGS_IS_ABSTRACT) {
2883 static PyObject *comma = NULL;
2884 PyObject *abstract_methods = NULL;
2885 PyObject *builtins;
2886 PyObject *sorted;
2887 PyObject *sorted_methods = NULL;
2888 PyObject *joined = NULL;
Christian Heimes9e7f1d22008-02-28 12:27:11 +00002889
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002890 /* Compute ", ".join(sorted(type.__abstractmethods__))
2891 into joined. */
2892 abstract_methods = type_abstractmethods(type, NULL);
2893 if (abstract_methods == NULL)
2894 goto error;
2895 builtins = PyEval_GetBuiltins();
2896 if (builtins == NULL)
2897 goto error;
2898 sorted = PyDict_GetItemString(builtins, "sorted");
2899 if (sorted == NULL)
2900 goto error;
2901 sorted_methods = PyObject_CallFunctionObjArgs(sorted,
2902 abstract_methods,
2903 NULL);
2904 if (sorted_methods == NULL)
2905 goto error;
2906 if (comma == NULL) {
2907 comma = PyUnicode_InternFromString(", ");
2908 if (comma == NULL)
2909 goto error;
2910 }
2911 joined = PyObject_CallMethod(comma, "join",
2912 "O", sorted_methods);
2913 if (joined == NULL)
2914 goto error;
Christian Heimes9e7f1d22008-02-28 12:27:11 +00002915
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002916 PyErr_Format(PyExc_TypeError,
2917 "Can't instantiate abstract class %s "
2918 "with abstract methods %U",
2919 type->tp_name,
2920 joined);
2921 error:
2922 Py_XDECREF(joined);
2923 Py_XDECREF(sorted_methods);
2924 Py_XDECREF(abstract_methods);
2925 return NULL;
2926 }
2927 return type->tp_alloc(type, 0);
Guido van Rossum298e4212003-02-13 16:30:16 +00002928}
2929
Tim Peters6d6c1a32001-08-02 04:15:00 +00002930static void
2931object_dealloc(PyObject *self)
2932{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002933 Py_TYPE(self)->tp_free(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002934}
2935
Guido van Rossum8e248182001-08-12 05:17:56 +00002936static PyObject *
2937object_repr(PyObject *self)
2938{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002939 PyTypeObject *type;
2940 PyObject *mod, *name, *rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00002941
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002942 type = Py_TYPE(self);
2943 mod = type_module(type, NULL);
2944 if (mod == NULL)
2945 PyErr_Clear();
2946 else if (!PyUnicode_Check(mod)) {
2947 Py_DECREF(mod);
2948 mod = NULL;
2949 }
2950 name = type_name(type, NULL);
2951 if (name == NULL)
2952 return NULL;
2953 if (mod != NULL && PyUnicode_CompareWithASCIIString(mod, "builtins"))
2954 rtn = PyUnicode_FromFormat("<%U.%U object at %p>", mod, name, self);
2955 else
2956 rtn = PyUnicode_FromFormat("<%s object at %p>",
2957 type->tp_name, self);
2958 Py_XDECREF(mod);
2959 Py_DECREF(name);
2960 return rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00002961}
2962
Guido van Rossumb8f63662001-08-15 23:57:02 +00002963static PyObject *
2964object_str(PyObject *self)
2965{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002966 unaryfunc f;
Guido van Rossumb8f63662001-08-15 23:57:02 +00002967
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002968 f = Py_TYPE(self)->tp_repr;
2969 if (f == NULL)
2970 f = object_repr;
2971 return f(self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002972}
2973
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002974static PyObject *
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002975object_richcompare(PyObject *self, PyObject *other, int op)
2976{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002977 PyObject *res;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002978
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002979 switch (op) {
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002980
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002981 case Py_EQ:
2982 /* Return NotImplemented instead of False, so if two
2983 objects are compared, both get a chance at the
2984 comparison. See issue #1393. */
2985 res = (self == other) ? Py_True : Py_NotImplemented;
2986 Py_INCREF(res);
2987 break;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002988
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002989 case Py_NE:
2990 /* By default, != returns the opposite of ==,
2991 unless the latter returns NotImplemented. */
2992 res = PyObject_RichCompare(self, other, Py_EQ);
2993 if (res != NULL && res != Py_NotImplemented) {
2994 int ok = PyObject_IsTrue(res);
2995 Py_DECREF(res);
2996 if (ok < 0)
2997 res = NULL;
2998 else {
2999 if (ok)
3000 res = Py_False;
3001 else
3002 res = Py_True;
3003 Py_INCREF(res);
3004 }
3005 }
3006 break;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003007
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003008 default:
3009 res = Py_NotImplemented;
3010 Py_INCREF(res);
3011 break;
3012 }
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003013
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003014 return res;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003015}
3016
3017static PyObject *
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003018object_get_class(PyObject *self, void *closure)
3019{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003020 Py_INCREF(Py_TYPE(self));
3021 return (PyObject *)(Py_TYPE(self));
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003022}
3023
3024static int
3025equiv_structs(PyTypeObject *a, PyTypeObject *b)
3026{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003027 return a == b ||
3028 (a != NULL &&
3029 b != NULL &&
3030 a->tp_basicsize == b->tp_basicsize &&
3031 a->tp_itemsize == b->tp_itemsize &&
3032 a->tp_dictoffset == b->tp_dictoffset &&
3033 a->tp_weaklistoffset == b->tp_weaklistoffset &&
3034 ((a->tp_flags & Py_TPFLAGS_HAVE_GC) ==
3035 (b->tp_flags & Py_TPFLAGS_HAVE_GC)));
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003036}
3037
3038static int
3039same_slots_added(PyTypeObject *a, PyTypeObject *b)
3040{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003041 PyTypeObject *base = a->tp_base;
3042 Py_ssize_t size;
3043 PyObject *slots_a, *slots_b;
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003044
Benjamin Peterson67641d22011-01-17 19:24:34 +00003045 assert(base == b->tp_base);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003046 size = base->tp_basicsize;
3047 if (a->tp_dictoffset == size && b->tp_dictoffset == size)
3048 size += sizeof(PyObject *);
3049 if (a->tp_weaklistoffset == size && b->tp_weaklistoffset == size)
3050 size += sizeof(PyObject *);
Guido van Rossumd8faa362007-04-27 19:54:29 +00003051
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003052 /* Check slots compliance */
3053 slots_a = ((PyHeapTypeObject *)a)->ht_slots;
3054 slots_b = ((PyHeapTypeObject *)b)->ht_slots;
3055 if (slots_a && slots_b) {
3056 if (PyObject_RichCompareBool(slots_a, slots_b, Py_EQ) != 1)
3057 return 0;
3058 size += sizeof(PyObject *) * PyTuple_GET_SIZE(slots_a);
3059 }
3060 return size == a->tp_basicsize && size == b->tp_basicsize;
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003061}
3062
3063static int
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003064compatible_for_assignment(PyTypeObject* oldto, PyTypeObject* newto, char* attr)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003065{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003066 PyTypeObject *newbase, *oldbase;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003067
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003068 if (newto->tp_dealloc != oldto->tp_dealloc ||
3069 newto->tp_free != oldto->tp_free)
3070 {
3071 PyErr_Format(PyExc_TypeError,
3072 "%s assignment: "
3073 "'%s' deallocator differs from '%s'",
3074 attr,
3075 newto->tp_name,
3076 oldto->tp_name);
3077 return 0;
3078 }
3079 newbase = newto;
3080 oldbase = oldto;
3081 while (equiv_structs(newbase, newbase->tp_base))
3082 newbase = newbase->tp_base;
3083 while (equiv_structs(oldbase, oldbase->tp_base))
3084 oldbase = oldbase->tp_base;
3085 if (newbase != oldbase &&
3086 (newbase->tp_base != oldbase->tp_base ||
3087 !same_slots_added(newbase, oldbase))) {
3088 PyErr_Format(PyExc_TypeError,
3089 "%s assignment: "
3090 "'%s' object layout differs from '%s'",
3091 attr,
3092 newto->tp_name,
3093 oldto->tp_name);
3094 return 0;
3095 }
Tim Petersea7f75d2002-12-07 21:39:16 +00003096
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003097 return 1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003098}
3099
3100static int
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003101object_set_class(PyObject *self, PyObject *value, void *closure)
3102{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003103 PyTypeObject *oldto = Py_TYPE(self);
3104 PyTypeObject *newto;
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003105
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003106 if (value == NULL) {
3107 PyErr_SetString(PyExc_TypeError,
3108 "can't delete __class__ attribute");
3109 return -1;
3110 }
3111 if (!PyType_Check(value)) {
3112 PyErr_Format(PyExc_TypeError,
3113 "__class__ must be set to new-style class, not '%s' object",
3114 Py_TYPE(value)->tp_name);
3115 return -1;
3116 }
3117 newto = (PyTypeObject *)value;
3118 if (!(newto->tp_flags & Py_TPFLAGS_HEAPTYPE) ||
3119 !(oldto->tp_flags & Py_TPFLAGS_HEAPTYPE))
3120 {
3121 PyErr_Format(PyExc_TypeError,
3122 "__class__ assignment: only for heap types");
3123 return -1;
3124 }
3125 if (compatible_for_assignment(newto, oldto, "__class__")) {
3126 Py_INCREF(newto);
3127 Py_TYPE(self) = newto;
3128 Py_DECREF(oldto);
3129 return 0;
3130 }
3131 else {
3132 return -1;
3133 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003134}
3135
3136static PyGetSetDef object_getsets[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003137 {"__class__", object_get_class, object_set_class,
3138 PyDoc_STR("the object's class")},
3139 {0}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003140};
3141
Guido van Rossumc53f0092003-02-18 22:05:12 +00003142
Guido van Rossum036f9992003-02-21 22:02:54 +00003143/* Stuff to implement __reduce_ex__ for pickle protocols >= 2.
Alexandre Vassalottif7fa63d2008-05-11 08:55:36 +00003144 We fall back to helpers in copyreg for:
Guido van Rossum036f9992003-02-21 22:02:54 +00003145 - pickle protocols < 2
3146 - calculating the list of slot names (done only once per class)
3147 - the __newobj__ function (which is used as a token but never called)
3148*/
3149
3150static PyObject *
Alexandre Vassalottif7fa63d2008-05-11 08:55:36 +00003151import_copyreg(void)
Guido van Rossum036f9992003-02-21 22:02:54 +00003152{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003153 static PyObject *copyreg_str;
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003154 static PyObject *mod_copyreg = NULL;
Guido van Rossum3926a632001-09-25 16:25:58 +00003155
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003156 if (!copyreg_str) {
3157 copyreg_str = PyUnicode_InternFromString("copyreg");
3158 if (copyreg_str == NULL)
3159 return NULL;
3160 }
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003161 if (!mod_copyreg) {
3162 mod_copyreg = PyImport_Import(copyreg_str);
3163 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003164
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003165 Py_XINCREF(mod_copyreg);
3166 return mod_copyreg;
Guido van Rossum036f9992003-02-21 22:02:54 +00003167}
3168
3169static PyObject *
3170slotnames(PyObject *cls)
3171{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003172 PyObject *clsdict;
3173 PyObject *copyreg;
3174 PyObject *slotnames;
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003175 static PyObject *str_slotnames;
Guido van Rossum036f9992003-02-21 22:02:54 +00003176
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003177 if (str_slotnames == NULL) {
3178 str_slotnames = PyUnicode_InternFromString("__slotnames__");
3179 if (str_slotnames == NULL)
3180 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003181 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003182
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003183 clsdict = ((PyTypeObject *)cls)->tp_dict;
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003184 slotnames = PyDict_GetItem(clsdict, str_slotnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003185 if (slotnames != NULL && PyList_Check(slotnames)) {
3186 Py_INCREF(slotnames);
3187 return slotnames;
3188 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003189
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003190 copyreg = import_copyreg();
3191 if (copyreg == NULL)
3192 return NULL;
Guido van Rossum036f9992003-02-21 22:02:54 +00003193
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003194 slotnames = PyObject_CallMethod(copyreg, "_slotnames", "O", cls);
3195 Py_DECREF(copyreg);
3196 if (slotnames != NULL &&
3197 slotnames != Py_None &&
3198 !PyList_Check(slotnames))
3199 {
3200 PyErr_SetString(PyExc_TypeError,
3201 "copyreg._slotnames didn't return a list or None");
3202 Py_DECREF(slotnames);
3203 slotnames = NULL;
3204 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003205
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003206 return slotnames;
Guido van Rossum036f9992003-02-21 22:02:54 +00003207}
3208
3209static PyObject *
3210reduce_2(PyObject *obj)
3211{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003212 PyObject *cls, *getnewargs;
3213 PyObject *args = NULL, *args2 = NULL;
3214 PyObject *getstate = NULL, *state = NULL, *names = NULL;
3215 PyObject *slots = NULL, *listitems = NULL, *dictitems = NULL;
3216 PyObject *copyreg = NULL, *newobj = NULL, *res = NULL;
3217 Py_ssize_t i, n;
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003218 static PyObject *str_getnewargs = NULL, *str_getstate = NULL,
3219 *str_newobj = NULL;
Guido van Rossum036f9992003-02-21 22:02:54 +00003220
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003221 if (str_getnewargs == NULL) {
3222 str_getnewargs = PyUnicode_InternFromString("__getnewargs__");
3223 str_getstate = PyUnicode_InternFromString("__getstate__");
3224 str_newobj = PyUnicode_InternFromString("__newobj__");
3225 if (!str_getnewargs || !str_getstate || !str_newobj)
3226 return NULL;
3227 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003228
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003229 cls = (PyObject *) Py_TYPE(obj);
3230
3231 getnewargs = PyObject_GetAttr(obj, str_getnewargs);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003232 if (getnewargs != NULL) {
3233 args = PyObject_CallObject(getnewargs, NULL);
3234 Py_DECREF(getnewargs);
3235 if (args != NULL && !PyTuple_Check(args)) {
3236 PyErr_Format(PyExc_TypeError,
3237 "__getnewargs__ should return a tuple, "
3238 "not '%.200s'", Py_TYPE(args)->tp_name);
3239 goto end;
3240 }
3241 }
3242 else {
3243 PyErr_Clear();
3244 args = PyTuple_New(0);
3245 }
3246 if (args == NULL)
3247 goto end;
Guido van Rossum036f9992003-02-21 22:02:54 +00003248
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003249 getstate = PyObject_GetAttr(obj, str_getstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003250 if (getstate != NULL) {
3251 state = PyObject_CallObject(getstate, NULL);
3252 Py_DECREF(getstate);
3253 if (state == NULL)
3254 goto end;
3255 }
3256 else {
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003257 PyObject **dict;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003258 PyErr_Clear();
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003259 dict = _PyObject_GetDictPtr(obj);
3260 if (dict && *dict)
3261 state = *dict;
3262 else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003263 state = Py_None;
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003264 Py_INCREF(state);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003265 names = slotnames(cls);
3266 if (names == NULL)
3267 goto end;
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003268 if (names != Py_None && PyList_GET_SIZE(names) > 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003269 assert(PyList_Check(names));
3270 slots = PyDict_New();
3271 if (slots == NULL)
3272 goto end;
3273 n = 0;
3274 /* Can't pre-compute the list size; the list
3275 is stored on the class so accessible to other
3276 threads, which may be run by DECREF */
3277 for (i = 0; i < PyList_GET_SIZE(names); i++) {
3278 PyObject *name, *value;
3279 name = PyList_GET_ITEM(names, i);
3280 value = PyObject_GetAttr(obj, name);
3281 if (value == NULL)
3282 PyErr_Clear();
3283 else {
3284 int err = PyDict_SetItem(slots, name,
3285 value);
3286 Py_DECREF(value);
3287 if (err)
3288 goto end;
3289 n++;
3290 }
3291 }
3292 if (n) {
3293 state = Py_BuildValue("(NO)", state, slots);
3294 if (state == NULL)
3295 goto end;
3296 }
3297 }
3298 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003299
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003300 if (!PyList_Check(obj)) {
3301 listitems = Py_None;
3302 Py_INCREF(listitems);
3303 }
3304 else {
3305 listitems = PyObject_GetIter(obj);
3306 if (listitems == NULL)
3307 goto end;
3308 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003309
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003310 if (!PyDict_Check(obj)) {
3311 dictitems = Py_None;
3312 Py_INCREF(dictitems);
3313 }
3314 else {
3315 PyObject *items = PyObject_CallMethod(obj, "items", "");
3316 if (items == NULL)
3317 goto end;
3318 dictitems = PyObject_GetIter(items);
3319 Py_DECREF(items);
3320 if (dictitems == NULL)
3321 goto end;
3322 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003323
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003324 copyreg = import_copyreg();
3325 if (copyreg == NULL)
3326 goto end;
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003327 newobj = PyObject_GetAttr(copyreg, str_newobj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003328 if (newobj == NULL)
3329 goto end;
Guido van Rossum036f9992003-02-21 22:02:54 +00003330
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003331 n = PyTuple_GET_SIZE(args);
3332 args2 = PyTuple_New(n+1);
3333 if (args2 == NULL)
3334 goto end;
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003335 Py_INCREF(cls);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003336 PyTuple_SET_ITEM(args2, 0, cls);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003337 for (i = 0; i < n; i++) {
3338 PyObject *v = PyTuple_GET_ITEM(args, i);
3339 Py_INCREF(v);
3340 PyTuple_SET_ITEM(args2, i+1, v);
3341 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003342
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003343 res = PyTuple_Pack(5, newobj, args2, state, listitems, dictitems);
Guido van Rossum036f9992003-02-21 22:02:54 +00003344
3345 end:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003346 Py_XDECREF(args);
3347 Py_XDECREF(args2);
3348 Py_XDECREF(slots);
3349 Py_XDECREF(state);
3350 Py_XDECREF(names);
3351 Py_XDECREF(listitems);
3352 Py_XDECREF(dictitems);
3353 Py_XDECREF(copyreg);
3354 Py_XDECREF(newobj);
3355 return res;
Guido van Rossum036f9992003-02-21 22:02:54 +00003356}
3357
Guido van Rossumd8faa362007-04-27 19:54:29 +00003358/*
3359 * There were two problems when object.__reduce__ and object.__reduce_ex__
3360 * were implemented in the same function:
3361 * - trying to pickle an object with a custom __reduce__ method that
3362 * fell back to object.__reduce__ in certain circumstances led to
3363 * infinite recursion at Python level and eventual RuntimeError.
3364 * - Pickling objects that lied about their type by overwriting the
3365 * __class__ descriptor could lead to infinite recursion at C level
3366 * and eventual segfault.
3367 *
3368 * Because of backwards compatibility, the two methods still have to
3369 * behave in the same way, even if this is not required by the pickle
3370 * protocol. This common functionality was moved to the _common_reduce
3371 * function.
3372 */
3373static PyObject *
3374_common_reduce(PyObject *self, int proto)
3375{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003376 PyObject *copyreg, *res;
Guido van Rossumd8faa362007-04-27 19:54:29 +00003377
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003378 if (proto >= 2)
3379 return reduce_2(self);
Guido van Rossumd8faa362007-04-27 19:54:29 +00003380
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003381 copyreg = import_copyreg();
3382 if (!copyreg)
3383 return NULL;
Guido van Rossumd8faa362007-04-27 19:54:29 +00003384
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003385 res = PyEval_CallMethod(copyreg, "_reduce_ex", "(Oi)", self, proto);
3386 Py_DECREF(copyreg);
Guido van Rossumd8faa362007-04-27 19:54:29 +00003387
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003388 return res;
Guido van Rossumd8faa362007-04-27 19:54:29 +00003389}
3390
3391static PyObject *
3392object_reduce(PyObject *self, PyObject *args)
3393{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003394 int proto = 0;
Guido van Rossumd8faa362007-04-27 19:54:29 +00003395
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003396 if (!PyArg_ParseTuple(args, "|i:__reduce__", &proto))
3397 return NULL;
Guido van Rossumd8faa362007-04-27 19:54:29 +00003398
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003399 return _common_reduce(self, proto);
Guido van Rossumd8faa362007-04-27 19:54:29 +00003400}
3401
Guido van Rossum036f9992003-02-21 22:02:54 +00003402static PyObject *
3403object_reduce_ex(PyObject *self, PyObject *args)
3404{
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003405 static PyObject *str_reduce = NULL, *objreduce;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003406 PyObject *reduce, *res;
3407 int proto = 0;
Guido van Rossum036f9992003-02-21 22:02:54 +00003408
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003409 if (!PyArg_ParseTuple(args, "|i:__reduce_ex__", &proto))
3410 return NULL;
Guido van Rossum036f9992003-02-21 22:02:54 +00003411
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003412 if (str_reduce == NULL) {
3413 str_reduce = PyUnicode_InternFromString("__reduce__");
3414 objreduce = PyDict_GetItemString(PyBaseObject_Type.tp_dict,
3415 "__reduce__");
3416 if (str_reduce == NULL || objreduce == NULL)
3417 return NULL;
3418 }
3419
3420 reduce = PyObject_GetAttr(self, str_reduce);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003421 if (reduce == NULL)
3422 PyErr_Clear();
3423 else {
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003424 PyObject *cls, *clsreduce;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003425 int override;
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003426
3427 cls = (PyObject *) Py_TYPE(self);
3428 clsreduce = PyObject_GetAttr(cls, str_reduce);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003429 if (clsreduce == NULL) {
3430 Py_DECREF(reduce);
3431 return NULL;
3432 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003433 override = (clsreduce != objreduce);
3434 Py_DECREF(clsreduce);
3435 if (override) {
3436 res = PyObject_CallObject(reduce, NULL);
3437 Py_DECREF(reduce);
3438 return res;
3439 }
3440 else
3441 Py_DECREF(reduce);
3442 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003443
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003444 return _common_reduce(self, proto);
Guido van Rossum3926a632001-09-25 16:25:58 +00003445}
3446
Christian Heimes9e7f1d22008-02-28 12:27:11 +00003447static PyObject *
3448object_subclasshook(PyObject *cls, PyObject *args)
3449{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003450 Py_INCREF(Py_NotImplemented);
3451 return Py_NotImplemented;
Christian Heimes9e7f1d22008-02-28 12:27:11 +00003452}
3453
3454PyDoc_STRVAR(object_subclasshook_doc,
3455"Abstract classes can override this to customize issubclass().\n"
3456"\n"
3457"This is invoked early on by abc.ABCMeta.__subclasscheck__().\n"
3458"It should return True, False or NotImplemented. If it returns\n"
3459"NotImplemented, the normal algorithm is used. Otherwise, it\n"
3460"overrides the normal algorithm (and the outcome is cached).\n");
Eric Smith8c663262007-08-25 02:26:07 +00003461
3462/*
3463 from PEP 3101, this code implements:
3464
3465 class object:
3466 def __format__(self, format_spec):
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003467 return format(str(self), format_spec)
Eric Smith8c663262007-08-25 02:26:07 +00003468*/
3469static PyObject *
3470object_format(PyObject *self, PyObject *args)
3471{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003472 PyObject *format_spec;
3473 PyObject *self_as_str = NULL;
3474 PyObject *result = NULL;
Eric Smith8c663262007-08-25 02:26:07 +00003475
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003476 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
3477 return NULL;
Eric Smith8c663262007-08-25 02:26:07 +00003478
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003479 self_as_str = PyObject_Str(self);
Eric Smithe4d63172010-09-13 20:48:43 +00003480 if (self_as_str != NULL) {
3481 /* Issue 7994: If we're converting to a string, we
Eric V. Smithb9cd3532011-03-12 10:08:48 -05003482 should reject format specifications */
Eric Smithe4d63172010-09-13 20:48:43 +00003483 if (PyUnicode_GET_SIZE(format_spec) > 0) {
Eric V. Smithb9cd3532011-03-12 10:08:48 -05003484 if (PyErr_WarnEx(PyExc_DeprecationWarning,
3485 "object.__format__ with a non-empty format "
3486 "string is deprecated", 1) < 0) {
3487 goto done;
3488 }
3489 /* Eventually this will become an error:
3490 PyErr_Format(PyExc_TypeError,
3491 "non-empty format string passed to object.__format__");
3492 goto done;
3493 */
3494 }
Eric Smith8c663262007-08-25 02:26:07 +00003495
Eric V. Smithb9cd3532011-03-12 10:08:48 -05003496 result = PyObject_Format(self_as_str, format_spec);
Eric Smithe4d63172010-09-13 20:48:43 +00003497 }
3498
3499done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003500 Py_XDECREF(self_as_str);
Eric Smith8c663262007-08-25 02:26:07 +00003501
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003502 return result;
Eric Smith8c663262007-08-25 02:26:07 +00003503}
3504
Martin v. Löwis00709aa2008-06-04 14:18:43 +00003505static PyObject *
3506object_sizeof(PyObject *self, PyObject *args)
3507{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003508 Py_ssize_t res, isize;
Martin v. Löwis00709aa2008-06-04 14:18:43 +00003509
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003510 res = 0;
3511 isize = self->ob_type->tp_itemsize;
3512 if (isize > 0)
3513 res = Py_SIZE(self->ob_type) * isize;
3514 res += self->ob_type->tp_basicsize;
Martin v. Löwis00709aa2008-06-04 14:18:43 +00003515
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003516 return PyLong_FromSsize_t(res);
Martin v. Löwis00709aa2008-06-04 14:18:43 +00003517}
3518
Benjamin Peterson82b00c12011-05-24 11:09:06 -05003519/* __dir__ for generic objects: returns __dict__, __class__,
3520 and recursively up the __class__.__bases__ chain.
3521*/
3522static PyObject *
3523object_dir(PyObject *self, PyObject *args)
3524{
3525 PyObject *result = NULL;
3526 PyObject *dict = NULL;
3527 PyObject *itsclass = NULL;
3528
3529 /* Get __dict__ (which may or may not be a real dict...) */
3530 dict = PyObject_GetAttrString(self, "__dict__");
3531 if (dict == NULL) {
3532 PyErr_Clear();
3533 dict = PyDict_New();
3534 }
3535 else if (!PyDict_Check(dict)) {
3536 Py_DECREF(dict);
3537 dict = PyDict_New();
3538 }
3539 else {
3540 /* Copy __dict__ to avoid mutating it. */
3541 PyObject *temp = PyDict_Copy(dict);
3542 Py_DECREF(dict);
3543 dict = temp;
3544 }
3545
3546 if (dict == NULL)
3547 goto error;
3548
3549 /* Merge in attrs reachable from its class. */
3550 itsclass = PyObject_GetAttrString(self, "__class__");
3551 if (itsclass == NULL)
3552 /* XXX(tomer): Perhaps fall back to obj->ob_type if no
3553 __class__ exists? */
3554 PyErr_Clear();
3555 else if (merge_class_dict(dict, itsclass) != 0)
3556 goto error;
3557
3558 result = PyDict_Keys(dict);
3559 /* fall through */
3560error:
3561 Py_XDECREF(itsclass);
3562 Py_XDECREF(dict);
3563 return result;
3564}
3565
Guido van Rossum3926a632001-09-25 16:25:58 +00003566static PyMethodDef object_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003567 {"__reduce_ex__", object_reduce_ex, METH_VARARGS,
3568 PyDoc_STR("helper for pickle")},
3569 {"__reduce__", object_reduce, METH_VARARGS,
3570 PyDoc_STR("helper for pickle")},
3571 {"__subclasshook__", object_subclasshook, METH_CLASS | METH_VARARGS,
3572 object_subclasshook_doc},
3573 {"__format__", object_format, METH_VARARGS,
3574 PyDoc_STR("default object formatter")},
3575 {"__sizeof__", object_sizeof, METH_NOARGS,
Benjamin Petersonfbe56bb2011-05-24 12:42:51 -05003576 PyDoc_STR("__sizeof__() -> int\nsize of object in memory, in bytes")},
Benjamin Peterson82b00c12011-05-24 11:09:06 -05003577 {"__dir__", object_dir, METH_NOARGS,
Benjamin Petersonc7284122011-05-24 12:46:15 -05003578 PyDoc_STR("__dir__() -> list\ndefault dir() implementation")},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003579 {0}
Guido van Rossum3926a632001-09-25 16:25:58 +00003580};
3581
Guido van Rossum036f9992003-02-21 22:02:54 +00003582
Tim Peters6d6c1a32001-08-02 04:15:00 +00003583PyTypeObject PyBaseObject_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003584 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3585 "object", /* tp_name */
3586 sizeof(PyObject), /* tp_basicsize */
3587 0, /* tp_itemsize */
3588 object_dealloc, /* tp_dealloc */
3589 0, /* tp_print */
3590 0, /* tp_getattr */
3591 0, /* tp_setattr */
3592 0, /* tp_reserved */
3593 object_repr, /* tp_repr */
3594 0, /* tp_as_number */
3595 0, /* tp_as_sequence */
3596 0, /* tp_as_mapping */
3597 (hashfunc)_Py_HashPointer, /* tp_hash */
3598 0, /* tp_call */
3599 object_str, /* tp_str */
3600 PyObject_GenericGetAttr, /* tp_getattro */
3601 PyObject_GenericSetAttr, /* tp_setattro */
3602 0, /* tp_as_buffer */
3603 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
3604 PyDoc_STR("The most base type"), /* tp_doc */
3605 0, /* tp_traverse */
3606 0, /* tp_clear */
3607 object_richcompare, /* tp_richcompare */
3608 0, /* tp_weaklistoffset */
3609 0, /* tp_iter */
3610 0, /* tp_iternext */
3611 object_methods, /* tp_methods */
3612 0, /* tp_members */
3613 object_getsets, /* tp_getset */
3614 0, /* tp_base */
3615 0, /* tp_dict */
3616 0, /* tp_descr_get */
3617 0, /* tp_descr_set */
3618 0, /* tp_dictoffset */
3619 object_init, /* tp_init */
3620 PyType_GenericAlloc, /* tp_alloc */
3621 object_new, /* tp_new */
3622 PyObject_Del, /* tp_free */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003623};
3624
3625
Guido van Rossum50e9fb92006-08-17 05:42:55 +00003626/* Add the methods from tp_methods to the __dict__ in a type object */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003627
3628static int
3629add_methods(PyTypeObject *type, PyMethodDef *meth)
3630{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003631 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003632
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003633 for (; meth->ml_name != NULL; meth++) {
3634 PyObject *descr;
3635 if (PyDict_GetItemString(dict, meth->ml_name) &&
3636 !(meth->ml_flags & METH_COEXIST))
3637 continue;
3638 if (meth->ml_flags & METH_CLASS) {
3639 if (meth->ml_flags & METH_STATIC) {
3640 PyErr_SetString(PyExc_ValueError,
3641 "method cannot be both class and static");
3642 return -1;
3643 }
3644 descr = PyDescr_NewClassMethod(type, meth);
3645 }
3646 else if (meth->ml_flags & METH_STATIC) {
3647 PyObject *cfunc = PyCFunction_New(meth, NULL);
3648 if (cfunc == NULL)
3649 return -1;
3650 descr = PyStaticMethod_New(cfunc);
3651 Py_DECREF(cfunc);
3652 }
3653 else {
3654 descr = PyDescr_NewMethod(type, meth);
3655 }
3656 if (descr == NULL)
3657 return -1;
3658 if (PyDict_SetItemString(dict, meth->ml_name, descr) < 0)
3659 return -1;
3660 Py_DECREF(descr);
3661 }
3662 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003663}
3664
3665static int
Guido van Rossum6f799372001-09-20 20:46:19 +00003666add_members(PyTypeObject *type, PyMemberDef *memb)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003667{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003668 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003669
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003670 for (; memb->name != NULL; memb++) {
3671 PyObject *descr;
3672 if (PyDict_GetItemString(dict, memb->name))
3673 continue;
3674 descr = PyDescr_NewMember(type, memb);
3675 if (descr == NULL)
3676 return -1;
3677 if (PyDict_SetItemString(dict, memb->name, descr) < 0)
3678 return -1;
3679 Py_DECREF(descr);
3680 }
3681 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003682}
3683
3684static int
Guido van Rossum32d34c82001-09-20 21:45:26 +00003685add_getset(PyTypeObject *type, PyGetSetDef *gsp)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003686{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003687 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003688
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003689 for (; gsp->name != NULL; gsp++) {
3690 PyObject *descr;
3691 if (PyDict_GetItemString(dict, gsp->name))
3692 continue;
3693 descr = PyDescr_NewGetSet(type, gsp);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003694
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003695 if (descr == NULL)
3696 return -1;
3697 if (PyDict_SetItemString(dict, gsp->name, descr) < 0)
3698 return -1;
3699 Py_DECREF(descr);
3700 }
3701 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003702}
3703
Guido van Rossum13d52f02001-08-10 21:24:08 +00003704static void
3705inherit_special(PyTypeObject *type, PyTypeObject *base)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003706{
Tim Peters6d6c1a32001-08-02 04:15:00 +00003707
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003708 /* Copying basicsize is connected to the GC flags */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003709 if (!(type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
3710 (base->tp_flags & Py_TPFLAGS_HAVE_GC) &&
3711 (!type->tp_traverse && !type->tp_clear)) {
3712 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
3713 if (type->tp_traverse == NULL)
3714 type->tp_traverse = base->tp_traverse;
3715 if (type->tp_clear == NULL)
3716 type->tp_clear = base->tp_clear;
3717 }
3718 {
3719 /* The condition below could use some explanation.
3720 It appears that tp_new is not inherited for static types
3721 whose base class is 'object'; this seems to be a precaution
3722 so that old extension types don't suddenly become
3723 callable (object.__new__ wouldn't insure the invariants
3724 that the extension type's own factory function ensures).
3725 Heap types, of course, are under our control, so they do
3726 inherit tp_new; static extension types that specify some
3727 other built-in type as the default are considered
3728 new-style-aware so they also inherit object.__new__. */
3729 if (base != &PyBaseObject_Type ||
3730 (type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
3731 if (type->tp_new == NULL)
3732 type->tp_new = base->tp_new;
3733 }
3734 }
Benjamin Petersona7465e22010-07-05 15:01:22 +00003735 if (type->tp_basicsize == 0)
3736 type->tp_basicsize = base->tp_basicsize;
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00003737
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003738 /* Copy other non-function slots */
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00003739
3740#undef COPYVAL
3741#define COPYVAL(SLOT) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003742 if (type->SLOT == 0) type->SLOT = base->SLOT
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00003743
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003744 COPYVAL(tp_itemsize);
3745 COPYVAL(tp_weaklistoffset);
3746 COPYVAL(tp_dictoffset);
Thomas Wouters27d517b2007-02-25 20:39:11 +00003747
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003748 /* Setup fast subclass flags */
3749 if (PyType_IsSubtype(base, (PyTypeObject*)PyExc_BaseException))
3750 type->tp_flags |= Py_TPFLAGS_BASE_EXC_SUBCLASS;
3751 else if (PyType_IsSubtype(base, &PyType_Type))
3752 type->tp_flags |= Py_TPFLAGS_TYPE_SUBCLASS;
3753 else if (PyType_IsSubtype(base, &PyLong_Type))
3754 type->tp_flags |= Py_TPFLAGS_LONG_SUBCLASS;
3755 else if (PyType_IsSubtype(base, &PyBytes_Type))
3756 type->tp_flags |= Py_TPFLAGS_BYTES_SUBCLASS;
3757 else if (PyType_IsSubtype(base, &PyUnicode_Type))
3758 type->tp_flags |= Py_TPFLAGS_UNICODE_SUBCLASS;
3759 else if (PyType_IsSubtype(base, &PyTuple_Type))
3760 type->tp_flags |= Py_TPFLAGS_TUPLE_SUBCLASS;
3761 else if (PyType_IsSubtype(base, &PyList_Type))
3762 type->tp_flags |= Py_TPFLAGS_LIST_SUBCLASS;
3763 else if (PyType_IsSubtype(base, &PyDict_Type))
3764 type->tp_flags |= Py_TPFLAGS_DICT_SUBCLASS;
Guido van Rossum13d52f02001-08-10 21:24:08 +00003765}
3766
Guido van Rossumf5243f02008-01-01 04:06:48 +00003767static char *hash_name_op[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003768 "__eq__",
3769 "__hash__",
3770 NULL
Guido van Rossum38938152006-08-21 23:36:26 +00003771};
3772
3773static int
Guido van Rossumf5243f02008-01-01 04:06:48 +00003774overrides_hash(PyTypeObject *type)
Guido van Rossum38938152006-08-21 23:36:26 +00003775{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003776 char **p;
3777 PyObject *dict = type->tp_dict;
Guido van Rossum38938152006-08-21 23:36:26 +00003778
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003779 assert(dict != NULL);
3780 for (p = hash_name_op; *p; p++) {
3781 if (PyDict_GetItemString(dict, *p) != NULL)
3782 return 1;
3783 }
3784 return 0;
Guido van Rossum38938152006-08-21 23:36:26 +00003785}
3786
Guido van Rossum13d52f02001-08-10 21:24:08 +00003787static void
3788inherit_slots(PyTypeObject *type, PyTypeObject *base)
3789{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003790 PyTypeObject *basebase;
Guido van Rossum13d52f02001-08-10 21:24:08 +00003791
3792#undef SLOTDEFINED
Tim Peters6d6c1a32001-08-02 04:15:00 +00003793#undef COPYSLOT
3794#undef COPYNUM
3795#undef COPYSEQ
3796#undef COPYMAP
Guido van Rossum5af588b2001-10-12 14:13:21 +00003797#undef COPYBUF
Guido van Rossum13d52f02001-08-10 21:24:08 +00003798
3799#define SLOTDEFINED(SLOT) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003800 (base->SLOT != 0 && \
3801 (basebase == NULL || base->SLOT != basebase->SLOT))
Guido van Rossum13d52f02001-08-10 21:24:08 +00003802
Tim Peters6d6c1a32001-08-02 04:15:00 +00003803#define COPYSLOT(SLOT) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003804 if (!type->SLOT && SLOTDEFINED(SLOT)) type->SLOT = base->SLOT
Tim Peters6d6c1a32001-08-02 04:15:00 +00003805
3806#define COPYNUM(SLOT) COPYSLOT(tp_as_number->SLOT)
3807#define COPYSEQ(SLOT) COPYSLOT(tp_as_sequence->SLOT)
3808#define COPYMAP(SLOT) COPYSLOT(tp_as_mapping->SLOT)
Tim Petersfc57ccb2001-10-12 02:38:24 +00003809#define COPYBUF(SLOT) COPYSLOT(tp_as_buffer->SLOT)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003810
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003811 /* This won't inherit indirect slots (from tp_as_number etc.)
3812 if type doesn't provide the space. */
Guido van Rossum13d52f02001-08-10 21:24:08 +00003813
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003814 if (type->tp_as_number != NULL && base->tp_as_number != NULL) {
3815 basebase = base->tp_base;
3816 if (basebase->tp_as_number == NULL)
3817 basebase = NULL;
3818 COPYNUM(nb_add);
3819 COPYNUM(nb_subtract);
3820 COPYNUM(nb_multiply);
3821 COPYNUM(nb_remainder);
3822 COPYNUM(nb_divmod);
3823 COPYNUM(nb_power);
3824 COPYNUM(nb_negative);
3825 COPYNUM(nb_positive);
3826 COPYNUM(nb_absolute);
3827 COPYNUM(nb_bool);
3828 COPYNUM(nb_invert);
3829 COPYNUM(nb_lshift);
3830 COPYNUM(nb_rshift);
3831 COPYNUM(nb_and);
3832 COPYNUM(nb_xor);
3833 COPYNUM(nb_or);
3834 COPYNUM(nb_int);
3835 COPYNUM(nb_float);
3836 COPYNUM(nb_inplace_add);
3837 COPYNUM(nb_inplace_subtract);
3838 COPYNUM(nb_inplace_multiply);
3839 COPYNUM(nb_inplace_remainder);
3840 COPYNUM(nb_inplace_power);
3841 COPYNUM(nb_inplace_lshift);
3842 COPYNUM(nb_inplace_rshift);
3843 COPYNUM(nb_inplace_and);
3844 COPYNUM(nb_inplace_xor);
3845 COPYNUM(nb_inplace_or);
3846 COPYNUM(nb_true_divide);
3847 COPYNUM(nb_floor_divide);
3848 COPYNUM(nb_inplace_true_divide);
3849 COPYNUM(nb_inplace_floor_divide);
3850 COPYNUM(nb_index);
3851 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003852
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003853 if (type->tp_as_sequence != NULL && base->tp_as_sequence != NULL) {
3854 basebase = base->tp_base;
3855 if (basebase->tp_as_sequence == NULL)
3856 basebase = NULL;
3857 COPYSEQ(sq_length);
3858 COPYSEQ(sq_concat);
3859 COPYSEQ(sq_repeat);
3860 COPYSEQ(sq_item);
3861 COPYSEQ(sq_ass_item);
3862 COPYSEQ(sq_contains);
3863 COPYSEQ(sq_inplace_concat);
3864 COPYSEQ(sq_inplace_repeat);
3865 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003866
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003867 if (type->tp_as_mapping != NULL && base->tp_as_mapping != NULL) {
3868 basebase = base->tp_base;
3869 if (basebase->tp_as_mapping == NULL)
3870 basebase = NULL;
3871 COPYMAP(mp_length);
3872 COPYMAP(mp_subscript);
3873 COPYMAP(mp_ass_subscript);
3874 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003875
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003876 if (type->tp_as_buffer != NULL && base->tp_as_buffer != NULL) {
3877 basebase = base->tp_base;
3878 if (basebase->tp_as_buffer == NULL)
3879 basebase = NULL;
3880 COPYBUF(bf_getbuffer);
3881 COPYBUF(bf_releasebuffer);
3882 }
Tim Petersfc57ccb2001-10-12 02:38:24 +00003883
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003884 basebase = base->tp_base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003885
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003886 COPYSLOT(tp_dealloc);
3887 if (type->tp_getattr == NULL && type->tp_getattro == NULL) {
3888 type->tp_getattr = base->tp_getattr;
3889 type->tp_getattro = base->tp_getattro;
3890 }
3891 if (type->tp_setattr == NULL && type->tp_setattro == NULL) {
3892 type->tp_setattr = base->tp_setattr;
3893 type->tp_setattro = base->tp_setattro;
3894 }
3895 /* tp_reserved is ignored */
3896 COPYSLOT(tp_repr);
3897 /* tp_hash see tp_richcompare */
3898 COPYSLOT(tp_call);
3899 COPYSLOT(tp_str);
3900 {
3901 /* Copy comparison-related slots only when
3902 not overriding them anywhere */
3903 if (type->tp_richcompare == NULL &&
3904 type->tp_hash == NULL &&
3905 !overrides_hash(type))
3906 {
3907 type->tp_richcompare = base->tp_richcompare;
3908 type->tp_hash = base->tp_hash;
3909 }
3910 }
3911 {
3912 COPYSLOT(tp_iter);
3913 COPYSLOT(tp_iternext);
3914 }
3915 {
3916 COPYSLOT(tp_descr_get);
3917 COPYSLOT(tp_descr_set);
3918 COPYSLOT(tp_dictoffset);
3919 COPYSLOT(tp_init);
3920 COPYSLOT(tp_alloc);
3921 COPYSLOT(tp_is_gc);
3922 if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) ==
3923 (base->tp_flags & Py_TPFLAGS_HAVE_GC)) {
3924 /* They agree about gc. */
3925 COPYSLOT(tp_free);
3926 }
3927 else if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
3928 type->tp_free == NULL &&
3929 base->tp_free == PyObject_Free) {
3930 /* A bit of magic to plug in the correct default
3931 * tp_free function when a derived class adds gc,
3932 * didn't define tp_free, and the base uses the
3933 * default non-gc tp_free.
3934 */
3935 type->tp_free = PyObject_GC_Del;
3936 }
3937 /* else they didn't agree about gc, and there isn't something
3938 * obvious to be done -- the type is on its own.
3939 */
3940 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003941}
3942
Jeremy Hylton938ace62002-07-17 16:30:39 +00003943static int add_operators(PyTypeObject *);
Guido van Rossum13d52f02001-08-10 21:24:08 +00003944
Tim Peters6d6c1a32001-08-02 04:15:00 +00003945int
Guido van Rossum528b7eb2001-08-07 17:24:28 +00003946PyType_Ready(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003947{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003948 PyObject *dict, *bases;
3949 PyTypeObject *base;
3950 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003951
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003952 if (type->tp_flags & Py_TPFLAGS_READY) {
3953 assert(type->tp_dict != NULL);
3954 return 0;
3955 }
3956 assert((type->tp_flags & Py_TPFLAGS_READYING) == 0);
Guido van Rossumd614f972001-08-10 17:39:49 +00003957
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003958 type->tp_flags |= Py_TPFLAGS_READYING;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003959
Tim Peters36eb4df2003-03-23 03:33:13 +00003960#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003961 /* PyType_Ready is the closest thing we have to a choke point
3962 * for type objects, so is the best place I can think of to try
3963 * to get type objects into the doubly-linked list of all objects.
3964 * Still, not all type objects go thru PyType_Ready.
3965 */
3966 _Py_AddToAllObjects((PyObject *)type, 0);
Tim Peters36eb4df2003-03-23 03:33:13 +00003967#endif
3968
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003969 /* Initialize tp_base (defaults to BaseObject unless that's us) */
3970 base = type->tp_base;
3971 if (base == NULL && type != &PyBaseObject_Type) {
3972 base = type->tp_base = &PyBaseObject_Type;
3973 Py_INCREF(base);
3974 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003975
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003976 /* Now the only way base can still be NULL is if type is
3977 * &PyBaseObject_Type.
3978 */
Guido van Rossum692cdbc2006-03-10 02:04:28 +00003979
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003980 /* Initialize the base class */
3981 if (base != NULL && base->tp_dict == NULL) {
3982 if (PyType_Ready(base) < 0)
3983 goto error;
3984 }
Guido van Rossum323a9cf2002-08-14 17:26:30 +00003985
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003986 /* Initialize ob_type if NULL. This means extensions that want to be
3987 compilable separately on Windows can call PyType_Ready() instead of
3988 initializing the ob_type field of their type objects. */
3989 /* The test for base != NULL is really unnecessary, since base is only
3990 NULL when type is &PyBaseObject_Type, and we know its ob_type is
3991 not NULL (it's initialized to &PyType_Type). But coverity doesn't
3992 know that. */
3993 if (Py_TYPE(type) == NULL && base != NULL)
3994 Py_TYPE(type) = Py_TYPE(base);
Guido van Rossum0986d822002-04-08 01:38:42 +00003995
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003996 /* Initialize tp_bases */
3997 bases = type->tp_bases;
3998 if (bases == NULL) {
3999 if (base == NULL)
4000 bases = PyTuple_New(0);
4001 else
4002 bases = PyTuple_Pack(1, base);
4003 if (bases == NULL)
4004 goto error;
4005 type->tp_bases = bases;
4006 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004007
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004008 /* Initialize tp_dict */
4009 dict = type->tp_dict;
4010 if (dict == NULL) {
4011 dict = PyDict_New();
4012 if (dict == NULL)
4013 goto error;
4014 type->tp_dict = dict;
4015 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004016
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004017 /* Add type-specific descriptors to tp_dict */
4018 if (add_operators(type) < 0)
4019 goto error;
4020 if (type->tp_methods != NULL) {
4021 if (add_methods(type, type->tp_methods) < 0)
4022 goto error;
4023 }
4024 if (type->tp_members != NULL) {
4025 if (add_members(type, type->tp_members) < 0)
4026 goto error;
4027 }
4028 if (type->tp_getset != NULL) {
4029 if (add_getset(type, type->tp_getset) < 0)
4030 goto error;
4031 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004032
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004033 /* Calculate method resolution order */
4034 if (mro_internal(type) < 0) {
4035 goto error;
4036 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004037
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004038 /* Inherit special flags from dominant base */
4039 if (type->tp_base != NULL)
4040 inherit_special(type, type->tp_base);
Guido van Rossum13d52f02001-08-10 21:24:08 +00004041
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004042 /* Initialize tp_dict properly */
4043 bases = type->tp_mro;
4044 assert(bases != NULL);
4045 assert(PyTuple_Check(bases));
4046 n = PyTuple_GET_SIZE(bases);
4047 for (i = 1; i < n; i++) {
4048 PyObject *b = PyTuple_GET_ITEM(bases, i);
4049 if (PyType_Check(b))
4050 inherit_slots(type, (PyTypeObject *)b);
4051 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004052
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004053 /* Sanity check for tp_free. */
4054 if (PyType_IS_GC(type) && (type->tp_flags & Py_TPFLAGS_BASETYPE) &&
4055 (type->tp_free == NULL || type->tp_free == PyObject_Del)) {
4056 /* This base class needs to call tp_free, but doesn't have
4057 * one, or its tp_free is for non-gc'ed objects.
4058 */
4059 PyErr_Format(PyExc_TypeError, "type '%.100s' participates in "
4060 "gc and is a base type but has inappropriate "
4061 "tp_free slot",
4062 type->tp_name);
4063 goto error;
4064 }
Tim Peters3cfe7542003-05-21 21:29:48 +00004065
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004066 /* if the type dictionary doesn't contain a __doc__, set it from
4067 the tp_doc slot.
4068 */
4069 if (PyDict_GetItemString(type->tp_dict, "__doc__") == NULL) {
4070 if (type->tp_doc != NULL) {
4071 PyObject *doc = PyUnicode_FromString(type->tp_doc);
4072 if (doc == NULL)
4073 goto error;
4074 PyDict_SetItemString(type->tp_dict, "__doc__", doc);
4075 Py_DECREF(doc);
4076 } else {
4077 PyDict_SetItemString(type->tp_dict,
4078 "__doc__", Py_None);
4079 }
4080 }
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00004081
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004082 /* Hack for tp_hash and __hash__.
4083 If after all that, tp_hash is still NULL, and __hash__ is not in
4084 tp_dict, set tp_hash to PyObject_HashNotImplemented and
4085 tp_dict['__hash__'] equal to None.
4086 This signals that __hash__ is not inherited.
4087 */
4088 if (type->tp_hash == NULL) {
4089 if (PyDict_GetItemString(type->tp_dict, "__hash__") == NULL) {
4090 if (PyDict_SetItemString(type->tp_dict, "__hash__", Py_None) < 0)
4091 goto error;
4092 type->tp_hash = PyObject_HashNotImplemented;
4093 }
4094 }
Guido van Rossum38938152006-08-21 23:36:26 +00004095
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004096 /* Some more special stuff */
4097 base = type->tp_base;
4098 if (base != NULL) {
4099 if (type->tp_as_number == NULL)
4100 type->tp_as_number = base->tp_as_number;
4101 if (type->tp_as_sequence == NULL)
4102 type->tp_as_sequence = base->tp_as_sequence;
4103 if (type->tp_as_mapping == NULL)
4104 type->tp_as_mapping = base->tp_as_mapping;
4105 if (type->tp_as_buffer == NULL)
4106 type->tp_as_buffer = base->tp_as_buffer;
4107 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004108
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004109 /* Link into each base class's list of subclasses */
4110 bases = type->tp_bases;
4111 n = PyTuple_GET_SIZE(bases);
4112 for (i = 0; i < n; i++) {
4113 PyObject *b = PyTuple_GET_ITEM(bases, i);
4114 if (PyType_Check(b) &&
4115 add_subclass((PyTypeObject *)b, type) < 0)
4116 goto error;
4117 }
Guido van Rossum1c450732001-10-08 15:18:27 +00004118
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004119 /* Warn for a type that implements tp_compare (now known as
4120 tp_reserved) but not tp_richcompare. */
4121 if (type->tp_reserved && !type->tp_richcompare) {
4122 int error;
Victor Stinner4a2b7a12010-08-13 14:03:48 +00004123 error = PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
4124 "Type %.100s defines tp_reserved (formerly tp_compare) "
4125 "but not tp_richcompare. Comparisons may not behave as intended.",
4126 type->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004127 if (error == -1)
4128 goto error;
4129 }
Mark Dickinson2a7d45b2009-02-08 11:02:10 +00004130
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004131 /* All done -- set the ready flag */
4132 assert(type->tp_dict != NULL);
4133 type->tp_flags =
4134 (type->tp_flags & ~Py_TPFLAGS_READYING) | Py_TPFLAGS_READY;
4135 return 0;
Guido van Rossumd614f972001-08-10 17:39:49 +00004136
4137 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004138 type->tp_flags &= ~Py_TPFLAGS_READYING;
4139 return -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004140}
4141
Guido van Rossum1c450732001-10-08 15:18:27 +00004142static int
4143add_subclass(PyTypeObject *base, PyTypeObject *type)
4144{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004145 Py_ssize_t i;
4146 int result;
4147 PyObject *list, *ref, *newobj;
Guido van Rossum1c450732001-10-08 15:18:27 +00004148
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004149 list = base->tp_subclasses;
4150 if (list == NULL) {
4151 base->tp_subclasses = list = PyList_New(0);
4152 if (list == NULL)
4153 return -1;
4154 }
4155 assert(PyList_Check(list));
4156 newobj = PyWeakref_NewRef((PyObject *)type, NULL);
4157 i = PyList_GET_SIZE(list);
4158 while (--i >= 0) {
4159 ref = PyList_GET_ITEM(list, i);
4160 assert(PyWeakref_CheckRef(ref));
4161 if (PyWeakref_GET_OBJECT(ref) == Py_None)
4162 return PyList_SetItem(list, i, newobj);
4163 }
4164 result = PyList_Append(list, newobj);
4165 Py_DECREF(newobj);
4166 return result;
Guido van Rossum1c450732001-10-08 15:18:27 +00004167}
4168
Michael W. Hudson98bbc492002-11-26 14:47:27 +00004169static void
4170remove_subclass(PyTypeObject *base, PyTypeObject *type)
4171{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004172 Py_ssize_t i;
4173 PyObject *list, *ref;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00004174
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004175 list = base->tp_subclasses;
4176 if (list == NULL) {
4177 return;
4178 }
4179 assert(PyList_Check(list));
4180 i = PyList_GET_SIZE(list);
4181 while (--i >= 0) {
4182 ref = PyList_GET_ITEM(list, i);
4183 assert(PyWeakref_CheckRef(ref));
4184 if (PyWeakref_GET_OBJECT(ref) == (PyObject*)type) {
4185 /* this can't fail, right? */
4186 PySequence_DelItem(list, i);
4187 return;
4188 }
4189 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +00004190}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004191
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004192static int
4193check_num_args(PyObject *ob, int n)
4194{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004195 if (!PyTuple_CheckExact(ob)) {
4196 PyErr_SetString(PyExc_SystemError,
4197 "PyArg_UnpackTuple() argument list is not a tuple");
4198 return 0;
4199 }
4200 if (n == PyTuple_GET_SIZE(ob))
4201 return 1;
4202 PyErr_Format(
4203 PyExc_TypeError,
4204 "expected %d arguments, got %zd", n, PyTuple_GET_SIZE(ob));
4205 return 0;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004206}
4207
Tim Peters6d6c1a32001-08-02 04:15:00 +00004208/* Generic wrappers for overloadable 'operators' such as __getitem__ */
4209
4210/* There's a wrapper *function* for each distinct function typedef used
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004211 for type object slots (e.g. binaryfunc, ternaryfunc, etc.). There's a
Tim Peters6d6c1a32001-08-02 04:15:00 +00004212 wrapper *table* for each distinct operation (e.g. __len__, __add__).
4213 Most tables have only one entry; the tables for binary operators have two
4214 entries, one regular and one with reversed arguments. */
4215
4216static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00004217wrap_lenfunc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004218{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004219 lenfunc func = (lenfunc)wrapped;
4220 Py_ssize_t res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004221
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004222 if (!check_num_args(args, 0))
4223 return NULL;
4224 res = (*func)(self);
4225 if (res == -1 && PyErr_Occurred())
4226 return NULL;
4227 return PyLong_FromLong((long)res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004228}
4229
Tim Peters6d6c1a32001-08-02 04:15:00 +00004230static PyObject *
Raymond Hettingerf34f2642003-10-11 17:29:04 +00004231wrap_inquirypred(PyObject *self, PyObject *args, void *wrapped)
4232{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004233 inquiry func = (inquiry)wrapped;
4234 int res;
Raymond Hettingerf34f2642003-10-11 17:29:04 +00004235
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004236 if (!check_num_args(args, 0))
4237 return NULL;
4238 res = (*func)(self);
4239 if (res == -1 && PyErr_Occurred())
4240 return NULL;
4241 return PyBool_FromLong((long)res);
Raymond Hettingerf34f2642003-10-11 17:29:04 +00004242}
4243
4244static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00004245wrap_binaryfunc(PyObject *self, PyObject *args, void *wrapped)
4246{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004247 binaryfunc func = (binaryfunc)wrapped;
4248 PyObject *other;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004249
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004250 if (!check_num_args(args, 1))
4251 return NULL;
4252 other = PyTuple_GET_ITEM(args, 0);
4253 return (*func)(self, other);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004254}
4255
4256static PyObject *
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00004257wrap_binaryfunc_l(PyObject *self, PyObject *args, void *wrapped)
4258{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004259 binaryfunc func = (binaryfunc)wrapped;
4260 PyObject *other;
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00004261
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004262 if (!check_num_args(args, 1))
4263 return NULL;
4264 other = PyTuple_GET_ITEM(args, 0);
4265 return (*func)(self, other);
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00004266}
4267
4268static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00004269wrap_binaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
4270{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004271 binaryfunc func = (binaryfunc)wrapped;
4272 PyObject *other;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004273
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004274 if (!check_num_args(args, 1))
4275 return NULL;
4276 other = PyTuple_GET_ITEM(args, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004277 return (*func)(other, self);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004278}
4279
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004280static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00004281wrap_ternaryfunc(PyObject *self, PyObject *args, void *wrapped)
4282{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004283 ternaryfunc func = (ternaryfunc)wrapped;
4284 PyObject *other;
4285 PyObject *third = Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004286
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004287 /* Note: This wrapper only works for __pow__() */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004288
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004289 if (!PyArg_UnpackTuple(args, "", 1, 2, &other, &third))
4290 return NULL;
4291 return (*func)(self, other, third);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004292}
4293
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00004294static PyObject *
4295wrap_ternaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
4296{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004297 ternaryfunc func = (ternaryfunc)wrapped;
4298 PyObject *other;
4299 PyObject *third = Py_None;
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00004300
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004301 /* Note: This wrapper only works for __pow__() */
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00004302
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004303 if (!PyArg_UnpackTuple(args, "", 1, 2, &other, &third))
4304 return NULL;
4305 return (*func)(other, self, third);
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00004306}
4307
Tim Peters6d6c1a32001-08-02 04:15:00 +00004308static PyObject *
4309wrap_unaryfunc(PyObject *self, PyObject *args, void *wrapped)
4310{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004311 unaryfunc func = (unaryfunc)wrapped;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004312
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004313 if (!check_num_args(args, 0))
4314 return NULL;
4315 return (*func)(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004316}
4317
Tim Peters6d6c1a32001-08-02 04:15:00 +00004318static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004319wrap_indexargfunc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004320{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004321 ssizeargfunc func = (ssizeargfunc)wrapped;
4322 PyObject* o;
4323 Py_ssize_t i;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004324
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004325 if (!PyArg_UnpackTuple(args, "", 1, 1, &o))
4326 return NULL;
4327 i = PyNumber_AsSsize_t(o, PyExc_OverflowError);
4328 if (i == -1 && PyErr_Occurred())
4329 return NULL;
4330 return (*func)(self, i);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004331}
4332
Martin v. Löwis18e16552006-02-15 17:27:45 +00004333static Py_ssize_t
Guido van Rossum5d815f32001-08-17 21:57:47 +00004334getindex(PyObject *self, PyObject *arg)
4335{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004336 Py_ssize_t i;
Guido van Rossum5d815f32001-08-17 21:57:47 +00004337
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004338 i = PyNumber_AsSsize_t(arg, PyExc_OverflowError);
4339 if (i == -1 && PyErr_Occurred())
4340 return -1;
4341 if (i < 0) {
4342 PySequenceMethods *sq = Py_TYPE(self)->tp_as_sequence;
4343 if (sq && sq->sq_length) {
4344 Py_ssize_t n = (*sq->sq_length)(self);
4345 if (n < 0)
4346 return -1;
4347 i += n;
4348 }
4349 }
4350 return i;
Guido van Rossum5d815f32001-08-17 21:57:47 +00004351}
4352
4353static PyObject *
4354wrap_sq_item(PyObject *self, PyObject *args, void *wrapped)
4355{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004356 ssizeargfunc func = (ssizeargfunc)wrapped;
4357 PyObject *arg;
4358 Py_ssize_t i;
Guido van Rossum5d815f32001-08-17 21:57:47 +00004359
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004360 if (PyTuple_GET_SIZE(args) == 1) {
4361 arg = PyTuple_GET_ITEM(args, 0);
4362 i = getindex(self, arg);
4363 if (i == -1 && PyErr_Occurred())
4364 return NULL;
4365 return (*func)(self, i);
4366 }
4367 check_num_args(args, 1);
4368 assert(PyErr_Occurred());
4369 return NULL;
Guido van Rossum5d815f32001-08-17 21:57:47 +00004370}
4371
Tim Peters6d6c1a32001-08-02 04:15:00 +00004372static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00004373wrap_sq_setitem(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004374{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004375 ssizeobjargproc func = (ssizeobjargproc)wrapped;
4376 Py_ssize_t i;
4377 int res;
4378 PyObject *arg, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004379
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004380 if (!PyArg_UnpackTuple(args, "", 2, 2, &arg, &value))
4381 return NULL;
4382 i = getindex(self, arg);
4383 if (i == -1 && PyErr_Occurred())
4384 return NULL;
4385 res = (*func)(self, i, value);
4386 if (res == -1 && PyErr_Occurred())
4387 return NULL;
4388 Py_INCREF(Py_None);
4389 return Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004390}
4391
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004392static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00004393wrap_sq_delitem(PyObject *self, PyObject *args, void *wrapped)
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004394{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004395 ssizeobjargproc func = (ssizeobjargproc)wrapped;
4396 Py_ssize_t i;
4397 int res;
4398 PyObject *arg;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004399
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004400 if (!check_num_args(args, 1))
4401 return NULL;
4402 arg = PyTuple_GET_ITEM(args, 0);
4403 i = getindex(self, arg);
4404 if (i == -1 && PyErr_Occurred())
4405 return NULL;
4406 res = (*func)(self, i, NULL);
4407 if (res == -1 && PyErr_Occurred())
4408 return NULL;
4409 Py_INCREF(Py_None);
4410 return Py_None;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004411}
4412
Tim Peters6d6c1a32001-08-02 04:15:00 +00004413/* XXX objobjproc is a misnomer; should be objargpred */
4414static PyObject *
4415wrap_objobjproc(PyObject *self, PyObject *args, void *wrapped)
4416{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004417 objobjproc func = (objobjproc)wrapped;
4418 int res;
4419 PyObject *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004420
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004421 if (!check_num_args(args, 1))
4422 return NULL;
4423 value = PyTuple_GET_ITEM(args, 0);
4424 res = (*func)(self, value);
4425 if (res == -1 && PyErr_Occurred())
4426 return NULL;
4427 else
4428 return PyBool_FromLong(res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004429}
4430
Tim Peters6d6c1a32001-08-02 04:15:00 +00004431static PyObject *
4432wrap_objobjargproc(PyObject *self, PyObject *args, void *wrapped)
4433{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004434 objobjargproc func = (objobjargproc)wrapped;
4435 int res;
4436 PyObject *key, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004437
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004438 if (!PyArg_UnpackTuple(args, "", 2, 2, &key, &value))
4439 return NULL;
4440 res = (*func)(self, key, value);
4441 if (res == -1 && PyErr_Occurred())
4442 return NULL;
4443 Py_INCREF(Py_None);
4444 return Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004445}
4446
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004447static PyObject *
4448wrap_delitem(PyObject *self, PyObject *args, void *wrapped)
4449{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004450 objobjargproc func = (objobjargproc)wrapped;
4451 int res;
4452 PyObject *key;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004453
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004454 if (!check_num_args(args, 1))
4455 return NULL;
4456 key = PyTuple_GET_ITEM(args, 0);
4457 res = (*func)(self, key, NULL);
4458 if (res == -1 && PyErr_Occurred())
4459 return NULL;
4460 Py_INCREF(Py_None);
4461 return Py_None;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004462}
4463
Guido van Rossum4dcdb782003-04-14 21:46:03 +00004464/* Helper to check for object.__setattr__ or __delattr__ applied to a type.
Guido van Rossum52b27052003-04-15 20:05:10 +00004465 This is called the Carlo Verre hack after its discoverer. */
Guido van Rossum4dcdb782003-04-14 21:46:03 +00004466static int
4467hackcheck(PyObject *self, setattrofunc func, char *what)
4468{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004469 PyTypeObject *type = Py_TYPE(self);
4470 while (type && type->tp_flags & Py_TPFLAGS_HEAPTYPE)
4471 type = type->tp_base;
4472 /* If type is NULL now, this is a really weird type.
4473 In the spirit of backwards compatibility (?), just shut up. */
4474 if (type && type->tp_setattro != func) {
4475 PyErr_Format(PyExc_TypeError,
4476 "can't apply this %s to %s object",
4477 what,
4478 type->tp_name);
4479 return 0;
4480 }
4481 return 1;
Guido van Rossum4dcdb782003-04-14 21:46:03 +00004482}
4483
Tim Peters6d6c1a32001-08-02 04:15:00 +00004484static PyObject *
4485wrap_setattr(PyObject *self, PyObject *args, void *wrapped)
4486{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004487 setattrofunc func = (setattrofunc)wrapped;
4488 int res;
4489 PyObject *name, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004490
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004491 if (!PyArg_UnpackTuple(args, "", 2, 2, &name, &value))
4492 return NULL;
4493 if (!hackcheck(self, func, "__setattr__"))
4494 return NULL;
4495 res = (*func)(self, name, value);
4496 if (res < 0)
4497 return NULL;
4498 Py_INCREF(Py_None);
4499 return Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004500}
4501
4502static PyObject *
4503wrap_delattr(PyObject *self, PyObject *args, void *wrapped)
4504{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004505 setattrofunc func = (setattrofunc)wrapped;
4506 int res;
4507 PyObject *name;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004508
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004509 if (!check_num_args(args, 1))
4510 return NULL;
4511 name = PyTuple_GET_ITEM(args, 0);
4512 if (!hackcheck(self, func, "__delattr__"))
4513 return NULL;
4514 res = (*func)(self, name, NULL);
4515 if (res < 0)
4516 return NULL;
4517 Py_INCREF(Py_None);
4518 return Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004519}
4520
Tim Peters6d6c1a32001-08-02 04:15:00 +00004521static PyObject *
4522wrap_hashfunc(PyObject *self, PyObject *args, void *wrapped)
4523{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004524 hashfunc func = (hashfunc)wrapped;
Benjamin Peterson8035bc52010-10-23 16:20:50 +00004525 Py_hash_t res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004526
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004527 if (!check_num_args(args, 0))
4528 return NULL;
4529 res = (*func)(self);
4530 if (res == -1 && PyErr_Occurred())
4531 return NULL;
Benjamin Peterson8035bc52010-10-23 16:20:50 +00004532 return PyLong_FromSsize_t(res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004533}
4534
Tim Peters6d6c1a32001-08-02 04:15:00 +00004535static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00004536wrap_call(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004537{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004538 ternaryfunc func = (ternaryfunc)wrapped;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004539
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004540 return (*func)(self, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004541}
4542
Tim Peters6d6c1a32001-08-02 04:15:00 +00004543static PyObject *
4544wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op)
4545{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004546 richcmpfunc func = (richcmpfunc)wrapped;
4547 PyObject *other;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004548
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004549 if (!check_num_args(args, 1))
4550 return NULL;
4551 other = PyTuple_GET_ITEM(args, 0);
4552 return (*func)(self, other, op);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004553}
4554
4555#undef RICHCMP_WRAPPER
4556#define RICHCMP_WRAPPER(NAME, OP) \
4557static PyObject * \
4558richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \
4559{ \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004560 return wrap_richcmpfunc(self, args, wrapped, OP); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004561}
4562
Jack Jansen8e938b42001-08-08 15:29:49 +00004563RICHCMP_WRAPPER(lt, Py_LT)
4564RICHCMP_WRAPPER(le, Py_LE)
4565RICHCMP_WRAPPER(eq, Py_EQ)
4566RICHCMP_WRAPPER(ne, Py_NE)
4567RICHCMP_WRAPPER(gt, Py_GT)
4568RICHCMP_WRAPPER(ge, Py_GE)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004569
Tim Peters6d6c1a32001-08-02 04:15:00 +00004570static PyObject *
4571wrap_next(PyObject *self, PyObject *args, void *wrapped)
4572{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004573 unaryfunc func = (unaryfunc)wrapped;
4574 PyObject *res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004575
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004576 if (!check_num_args(args, 0))
4577 return NULL;
4578 res = (*func)(self);
4579 if (res == NULL && !PyErr_Occurred())
4580 PyErr_SetNone(PyExc_StopIteration);
4581 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004582}
4583
Tim Peters6d6c1a32001-08-02 04:15:00 +00004584static PyObject *
4585wrap_descr_get(PyObject *self, PyObject *args, void *wrapped)
4586{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004587 descrgetfunc func = (descrgetfunc)wrapped;
4588 PyObject *obj;
4589 PyObject *type = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004590
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004591 if (!PyArg_UnpackTuple(args, "", 1, 2, &obj, &type))
4592 return NULL;
4593 if (obj == Py_None)
4594 obj = NULL;
4595 if (type == Py_None)
4596 type = NULL;
4597 if (type == NULL &&obj == NULL) {
4598 PyErr_SetString(PyExc_TypeError,
4599 "__get__(None, None) is invalid");
4600 return NULL;
4601 }
4602 return (*func)(self, obj, type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004603}
4604
Tim Peters6d6c1a32001-08-02 04:15:00 +00004605static PyObject *
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004606wrap_descr_set(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004607{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004608 descrsetfunc func = (descrsetfunc)wrapped;
4609 PyObject *obj, *value;
4610 int ret;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004611
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004612 if (!PyArg_UnpackTuple(args, "", 2, 2, &obj, &value))
4613 return NULL;
4614 ret = (*func)(self, obj, value);
4615 if (ret < 0)
4616 return NULL;
4617 Py_INCREF(Py_None);
4618 return Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004619}
Guido van Rossum22b13872002-08-06 21:41:44 +00004620
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00004621static PyObject *
4622wrap_descr_delete(PyObject *self, PyObject *args, void *wrapped)
4623{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004624 descrsetfunc func = (descrsetfunc)wrapped;
4625 PyObject *obj;
4626 int ret;
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00004627
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004628 if (!check_num_args(args, 1))
4629 return NULL;
4630 obj = PyTuple_GET_ITEM(args, 0);
4631 ret = (*func)(self, obj, NULL);
4632 if (ret < 0)
4633 return NULL;
4634 Py_INCREF(Py_None);
4635 return Py_None;
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00004636}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004637
Tim Peters6d6c1a32001-08-02 04:15:00 +00004638static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00004639wrap_init(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004640{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004641 initproc func = (initproc)wrapped;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004642
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004643 if (func(self, args, kwds) < 0)
4644 return NULL;
4645 Py_INCREF(Py_None);
4646 return Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004647}
4648
Tim Peters6d6c1a32001-08-02 04:15:00 +00004649static PyObject *
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004650tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004651{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004652 PyTypeObject *type, *subtype, *staticbase;
4653 PyObject *arg0, *res;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004654
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004655 if (self == NULL || !PyType_Check(self))
4656 Py_FatalError("__new__() called with non-type 'self'");
4657 type = (PyTypeObject *)self;
4658 if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) {
4659 PyErr_Format(PyExc_TypeError,
4660 "%s.__new__(): not enough arguments",
4661 type->tp_name);
4662 return NULL;
4663 }
4664 arg0 = PyTuple_GET_ITEM(args, 0);
4665 if (!PyType_Check(arg0)) {
4666 PyErr_Format(PyExc_TypeError,
4667 "%s.__new__(X): X is not a type object (%s)",
4668 type->tp_name,
4669 Py_TYPE(arg0)->tp_name);
4670 return NULL;
4671 }
4672 subtype = (PyTypeObject *)arg0;
4673 if (!PyType_IsSubtype(subtype, type)) {
4674 PyErr_Format(PyExc_TypeError,
4675 "%s.__new__(%s): %s is not a subtype of %s",
4676 type->tp_name,
4677 subtype->tp_name,
4678 subtype->tp_name,
4679 type->tp_name);
4680 return NULL;
4681 }
Barry Warsaw60f01882001-08-22 19:24:42 +00004682
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004683 /* Check that the use doesn't do something silly and unsafe like
4684 object.__new__(dict). To do this, we check that the
4685 most derived base that's not a heap type is this type. */
4686 staticbase = subtype;
4687 while (staticbase && (staticbase->tp_flags & Py_TPFLAGS_HEAPTYPE))
4688 staticbase = staticbase->tp_base;
4689 /* If staticbase is NULL now, it is a really weird type.
4690 In the spirit of backwards compatibility (?), just shut up. */
4691 if (staticbase && staticbase->tp_new != type->tp_new) {
4692 PyErr_Format(PyExc_TypeError,
4693 "%s.__new__(%s) is not safe, use %s.__new__()",
4694 type->tp_name,
4695 subtype->tp_name,
4696 staticbase == NULL ? "?" : staticbase->tp_name);
4697 return NULL;
4698 }
Barry Warsaw60f01882001-08-22 19:24:42 +00004699
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004700 args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
4701 if (args == NULL)
4702 return NULL;
4703 res = type->tp_new(subtype, args, kwds);
4704 Py_DECREF(args);
4705 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004706}
4707
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004708static struct PyMethodDef tp_new_methoddef[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004709 {"__new__", (PyCFunction)tp_new_wrapper, METH_VARARGS|METH_KEYWORDS,
4710 PyDoc_STR("T.__new__(S, ...) -> "
4711 "a new object with type S, a subtype of T")},
4712 {0}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004713};
4714
4715static int
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004716add_tp_new_wrapper(PyTypeObject *type)
4717{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004718 PyObject *func;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004719
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004720 if (PyDict_GetItemString(type->tp_dict, "__new__") != NULL)
4721 return 0;
4722 func = PyCFunction_New(tp_new_methoddef, (PyObject *)type);
4723 if (func == NULL)
4724 return -1;
4725 if (PyDict_SetItemString(type->tp_dict, "__new__", func)) {
4726 Py_DECREF(func);
4727 return -1;
4728 }
4729 Py_DECREF(func);
4730 return 0;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004731}
4732
Guido van Rossumf040ede2001-08-07 16:40:56 +00004733/* Slot wrappers that call the corresponding __foo__ slot. See comments
4734 below at override_slots() for more explanation. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004735
Guido van Rossumdc91b992001-08-08 22:26:22 +00004736#define SLOT0(FUNCNAME, OPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004737static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004738FUNCNAME(PyObject *self) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004739{ \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004740 static PyObject *cache_str; \
4741 return call_method(self, OPSTR, &cache_str, "()"); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004742}
4743
Guido van Rossumdc91b992001-08-08 22:26:22 +00004744#define SLOT1(FUNCNAME, OPSTR, ARG1TYPE, ARGCODES) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004745static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004746FUNCNAME(PyObject *self, ARG1TYPE arg1) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004747{ \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004748 static PyObject *cache_str; \
4749 return call_method(self, OPSTR, &cache_str, "(" ARGCODES ")", arg1); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004750}
4751
Guido van Rossumcd118802003-01-06 22:57:47 +00004752/* Boolean helper for SLOT1BINFULL().
4753 right.__class__ is a nontrivial subclass of left.__class__. */
4754static int
4755method_is_overloaded(PyObject *left, PyObject *right, char *name)
4756{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004757 PyObject *a, *b;
4758 int ok;
Guido van Rossumcd118802003-01-06 22:57:47 +00004759
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004760 b = PyObject_GetAttrString((PyObject *)(Py_TYPE(right)), name);
4761 if (b == NULL) {
4762 PyErr_Clear();
4763 /* If right doesn't have it, it's not overloaded */
4764 return 0;
4765 }
Guido van Rossumcd118802003-01-06 22:57:47 +00004766
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004767 a = PyObject_GetAttrString((PyObject *)(Py_TYPE(left)), name);
4768 if (a == NULL) {
4769 PyErr_Clear();
4770 Py_DECREF(b);
4771 /* If right has it but left doesn't, it's overloaded */
4772 return 1;
4773 }
Guido van Rossumcd118802003-01-06 22:57:47 +00004774
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004775 ok = PyObject_RichCompareBool(a, b, Py_NE);
4776 Py_DECREF(a);
4777 Py_DECREF(b);
4778 if (ok < 0) {
4779 PyErr_Clear();
4780 return 0;
4781 }
Guido van Rossumcd118802003-01-06 22:57:47 +00004782
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004783 return ok;
Guido van Rossumcd118802003-01-06 22:57:47 +00004784}
4785
Guido van Rossumdc91b992001-08-08 22:26:22 +00004786
4787#define SLOT1BINFULL(FUNCNAME, TESTFUNC, SLOTNAME, OPSTR, ROPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004788static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004789FUNCNAME(PyObject *self, PyObject *other) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004790{ \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004791 static PyObject *cache_str, *rcache_str; \
4792 int do_other = Py_TYPE(self) != Py_TYPE(other) && \
4793 Py_TYPE(other)->tp_as_number != NULL && \
4794 Py_TYPE(other)->tp_as_number->SLOTNAME == TESTFUNC; \
4795 if (Py_TYPE(self)->tp_as_number != NULL && \
4796 Py_TYPE(self)->tp_as_number->SLOTNAME == TESTFUNC) { \
4797 PyObject *r; \
4798 if (do_other && \
4799 PyType_IsSubtype(Py_TYPE(other), Py_TYPE(self)) && \
4800 method_is_overloaded(self, other, ROPSTR)) { \
4801 r = call_maybe( \
4802 other, ROPSTR, &rcache_str, "(O)", self); \
4803 if (r != Py_NotImplemented) \
4804 return r; \
4805 Py_DECREF(r); \
4806 do_other = 0; \
4807 } \
4808 r = call_maybe( \
4809 self, OPSTR, &cache_str, "(O)", other); \
4810 if (r != Py_NotImplemented || \
4811 Py_TYPE(other) == Py_TYPE(self)) \
4812 return r; \
4813 Py_DECREF(r); \
4814 } \
4815 if (do_other) { \
4816 return call_maybe( \
4817 other, ROPSTR, &rcache_str, "(O)", self); \
4818 } \
4819 Py_INCREF(Py_NotImplemented); \
4820 return Py_NotImplemented; \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004821}
4822
4823#define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004824 SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR)
Guido van Rossumdc91b992001-08-08 22:26:22 +00004825
4826#define SLOT2(FUNCNAME, OPSTR, ARG1TYPE, ARG2TYPE, ARGCODES) \
4827static PyObject * \
4828FUNCNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \
4829{ \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004830 static PyObject *cache_str; \
4831 return call_method(self, OPSTR, &cache_str, \
4832 "(" ARGCODES ")", arg1, arg2); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004833}
4834
Martin v. Löwis18e16552006-02-15 17:27:45 +00004835static Py_ssize_t
Tim Peters6d6c1a32001-08-02 04:15:00 +00004836slot_sq_length(PyObject *self)
4837{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004838 static PyObject *len_str;
4839 PyObject *res = call_method(self, "__len__", &len_str, "()");
4840 Py_ssize_t len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004841
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004842 if (res == NULL)
4843 return -1;
4844 len = PyNumber_AsSsize_t(res, PyExc_OverflowError);
4845 Py_DECREF(res);
4846 if (len < 0) {
4847 if (!PyErr_Occurred())
4848 PyErr_SetString(PyExc_ValueError,
4849 "__len__() should return >= 0");
4850 return -1;
4851 }
4852 return len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004853}
4854
Guido van Rossumf4593e02001-10-03 12:09:30 +00004855/* Super-optimized version of slot_sq_item.
4856 Other slots could do the same... */
4857static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00004858slot_sq_item(PyObject *self, Py_ssize_t i)
Guido van Rossumf4593e02001-10-03 12:09:30 +00004859{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004860 static PyObject *getitem_str;
4861 PyObject *func, *args = NULL, *ival = NULL, *retval = NULL;
4862 descrgetfunc f;
Guido van Rossumf4593e02001-10-03 12:09:30 +00004863
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004864 if (getitem_str == NULL) {
4865 getitem_str = PyUnicode_InternFromString("__getitem__");
4866 if (getitem_str == NULL)
4867 return NULL;
4868 }
4869 func = _PyType_Lookup(Py_TYPE(self), getitem_str);
4870 if (func != NULL) {
4871 if ((f = Py_TYPE(func)->tp_descr_get) == NULL)
4872 Py_INCREF(func);
4873 else {
4874 func = f(func, self, (PyObject *)(Py_TYPE(self)));
4875 if (func == NULL) {
4876 return NULL;
4877 }
4878 }
4879 ival = PyLong_FromSsize_t(i);
4880 if (ival != NULL) {
4881 args = PyTuple_New(1);
4882 if (args != NULL) {
4883 PyTuple_SET_ITEM(args, 0, ival);
4884 retval = PyObject_Call(func, args, NULL);
4885 Py_XDECREF(args);
4886 Py_XDECREF(func);
4887 return retval;
4888 }
4889 }
4890 }
4891 else {
4892 PyErr_SetObject(PyExc_AttributeError, getitem_str);
4893 }
4894 Py_XDECREF(args);
4895 Py_XDECREF(ival);
4896 Py_XDECREF(func);
4897 return NULL;
Guido van Rossumf4593e02001-10-03 12:09:30 +00004898}
4899
Tim Peters6d6c1a32001-08-02 04:15:00 +00004900static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00004901slot_sq_ass_item(PyObject *self, Py_ssize_t index, PyObject *value)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004902{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004903 PyObject *res;
4904 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004905
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004906 if (value == NULL)
4907 res = call_method(self, "__delitem__", &delitem_str,
4908 "(n)", index);
4909 else
4910 res = call_method(self, "__setitem__", &setitem_str,
4911 "(nO)", index, value);
4912 if (res == NULL)
4913 return -1;
4914 Py_DECREF(res);
4915 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004916}
4917
4918static int
Tim Peters6d6c1a32001-08-02 04:15:00 +00004919slot_sq_contains(PyObject *self, PyObject *value)
4920{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004921 PyObject *func, *res, *args;
4922 int result = -1;
Tim Petersbf9b2442003-03-23 05:35:36 +00004923
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004924 static PyObject *contains_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004925
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004926 func = lookup_maybe(self, "__contains__", &contains_str);
4927 if (func != NULL) {
4928 args = PyTuple_Pack(1, value);
4929 if (args == NULL)
4930 res = NULL;
4931 else {
4932 res = PyObject_Call(func, args, NULL);
4933 Py_DECREF(args);
4934 }
4935 Py_DECREF(func);
4936 if (res != NULL) {
4937 result = PyObject_IsTrue(res);
4938 Py_DECREF(res);
4939 }
4940 }
4941 else if (! PyErr_Occurred()) {
4942 /* Possible results: -1 and 1 */
4943 result = (int)_PySequence_IterSearch(self, value,
4944 PY_ITERSEARCH_CONTAINS);
4945 }
4946 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004947}
4948
Tim Peters6d6c1a32001-08-02 04:15:00 +00004949#define slot_mp_length slot_sq_length
4950
Guido van Rossumdc91b992001-08-08 22:26:22 +00004951SLOT1(slot_mp_subscript, "__getitem__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004952
4953static int
4954slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value)
4955{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004956 PyObject *res;
4957 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004958
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004959 if (value == NULL)
4960 res = call_method(self, "__delitem__", &delitem_str,
4961 "(O)", key);
4962 else
4963 res = call_method(self, "__setitem__", &setitem_str,
4964 "(OO)", key, value);
4965 if (res == NULL)
4966 return -1;
4967 Py_DECREF(res);
4968 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004969}
4970
Guido van Rossumdc91b992001-08-08 22:26:22 +00004971SLOT1BIN(slot_nb_add, nb_add, "__add__", "__radd__")
4972SLOT1BIN(slot_nb_subtract, nb_subtract, "__sub__", "__rsub__")
4973SLOT1BIN(slot_nb_multiply, nb_multiply, "__mul__", "__rmul__")
Guido van Rossumdc91b992001-08-08 22:26:22 +00004974SLOT1BIN(slot_nb_remainder, nb_remainder, "__mod__", "__rmod__")
4975SLOT1BIN(slot_nb_divmod, nb_divmod, "__divmod__", "__rdivmod__")
4976
Jeremy Hylton938ace62002-07-17 16:30:39 +00004977static PyObject *slot_nb_power(PyObject *, PyObject *, PyObject *);
Guido van Rossumdc91b992001-08-08 22:26:22 +00004978
4979SLOT1BINFULL(slot_nb_power_binary, slot_nb_power,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004980 nb_power, "__pow__", "__rpow__")
Guido van Rossumdc91b992001-08-08 22:26:22 +00004981
4982static PyObject *
4983slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus)
4984{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004985 static PyObject *pow_str;
Guido van Rossum2730b132001-08-28 18:22:14 +00004986
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004987 if (modulus == Py_None)
4988 return slot_nb_power_binary(self, other);
4989 /* Three-arg power doesn't use __rpow__. But ternary_op
4990 can call this when the second argument's type uses
4991 slot_nb_power, so check before calling self.__pow__. */
4992 if (Py_TYPE(self)->tp_as_number != NULL &&
4993 Py_TYPE(self)->tp_as_number->nb_power == slot_nb_power) {
4994 return call_method(self, "__pow__", &pow_str,
4995 "(OO)", other, modulus);
4996 }
4997 Py_INCREF(Py_NotImplemented);
4998 return Py_NotImplemented;
Guido van Rossumdc91b992001-08-08 22:26:22 +00004999}
5000
5001SLOT0(slot_nb_negative, "__neg__")
5002SLOT0(slot_nb_positive, "__pos__")
5003SLOT0(slot_nb_absolute, "__abs__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00005004
5005static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00005006slot_nb_bool(PyObject *self)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005007{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005008 PyObject *func, *args;
5009 static PyObject *bool_str, *len_str;
5010 int result = -1;
5011 int using_len = 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005012
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005013 func = lookup_maybe(self, "__bool__", &bool_str);
5014 if (func == NULL) {
5015 if (PyErr_Occurred())
5016 return -1;
5017 func = lookup_maybe(self, "__len__", &len_str);
5018 if (func == NULL)
5019 return PyErr_Occurred() ? -1 : 1;
5020 using_len = 1;
5021 }
5022 args = PyTuple_New(0);
5023 if (args != NULL) {
5024 PyObject *temp = PyObject_Call(func, args, NULL);
5025 Py_DECREF(args);
5026 if (temp != NULL) {
5027 if (using_len) {
5028 /* enforced by slot_nb_len */
5029 result = PyObject_IsTrue(temp);
5030 }
5031 else if (PyBool_Check(temp)) {
5032 result = PyObject_IsTrue(temp);
5033 }
5034 else {
5035 PyErr_Format(PyExc_TypeError,
5036 "__bool__ should return "
5037 "bool, returned %s",
5038 Py_TYPE(temp)->tp_name);
5039 result = -1;
5040 }
5041 Py_DECREF(temp);
5042 }
5043 }
5044 Py_DECREF(func);
5045 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005046}
5047
Guido van Rossum38fff8c2006-03-07 18:50:55 +00005048
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00005049static PyObject *
Guido van Rossum38fff8c2006-03-07 18:50:55 +00005050slot_nb_index(PyObject *self)
5051{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005052 static PyObject *index_str;
5053 return call_method(self, "__index__", &index_str, "()");
Guido van Rossum38fff8c2006-03-07 18:50:55 +00005054}
5055
5056
Guido van Rossumdc91b992001-08-08 22:26:22 +00005057SLOT0(slot_nb_invert, "__invert__")
5058SLOT1BIN(slot_nb_lshift, nb_lshift, "__lshift__", "__rlshift__")
5059SLOT1BIN(slot_nb_rshift, nb_rshift, "__rshift__", "__rrshift__")
5060SLOT1BIN(slot_nb_and, nb_and, "__and__", "__rand__")
5061SLOT1BIN(slot_nb_xor, nb_xor, "__xor__", "__rxor__")
5062SLOT1BIN(slot_nb_or, nb_or, "__or__", "__ror__")
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00005063
Guido van Rossumdc91b992001-08-08 22:26:22 +00005064SLOT0(slot_nb_int, "__int__")
Guido van Rossumdc91b992001-08-08 22:26:22 +00005065SLOT0(slot_nb_float, "__float__")
Guido van Rossumdc91b992001-08-08 22:26:22 +00005066SLOT1(slot_nb_inplace_add, "__iadd__", PyObject *, "O")
5067SLOT1(slot_nb_inplace_subtract, "__isub__", PyObject *, "O")
5068SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *, "O")
Guido van Rossumdc91b992001-08-08 22:26:22 +00005069SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *, "O")
Thomas Wouterscf297e42007-02-23 15:07:44 +00005070/* Can't use SLOT1 here, because nb_inplace_power is ternary */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005071static PyObject *
5072slot_nb_inplace_power(PyObject *self, PyObject * arg1, PyObject *arg2)
5073{
5074 static PyObject *cache_str;
5075 return call_method(self, "__ipow__", &cache_str, "(" "O" ")", arg1);
Thomas Wouterscf297e42007-02-23 15:07:44 +00005076}
Guido van Rossumdc91b992001-08-08 22:26:22 +00005077SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *, "O")
5078SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *, "O")
5079SLOT1(slot_nb_inplace_and, "__iand__", PyObject *, "O")
5080SLOT1(slot_nb_inplace_xor, "__ixor__", PyObject *, "O")
5081SLOT1(slot_nb_inplace_or, "__ior__", PyObject *, "O")
5082SLOT1BIN(slot_nb_floor_divide, nb_floor_divide,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005083 "__floordiv__", "__rfloordiv__")
Guido van Rossumdc91b992001-08-08 22:26:22 +00005084SLOT1BIN(slot_nb_true_divide, nb_true_divide, "__truediv__", "__rtruediv__")
5085SLOT1(slot_nb_inplace_floor_divide, "__ifloordiv__", PyObject *, "O")
5086SLOT1(slot_nb_inplace_true_divide, "__itruediv__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00005087
Guido van Rossumb8f63662001-08-15 23:57:02 +00005088static PyObject *
5089slot_tp_repr(PyObject *self)
5090{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005091 PyObject *func, *res;
5092 static PyObject *repr_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00005093
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005094 func = lookup_method(self, "__repr__", &repr_str);
5095 if (func != NULL) {
5096 res = PyEval_CallObject(func, NULL);
5097 Py_DECREF(func);
5098 return res;
5099 }
5100 PyErr_Clear();
5101 return PyUnicode_FromFormat("<%s object at %p>",
5102 Py_TYPE(self)->tp_name, self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005103}
5104
5105static PyObject *
5106slot_tp_str(PyObject *self)
5107{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005108 PyObject *func, *res;
5109 static PyObject *str_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00005110
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005111 func = lookup_method(self, "__str__", &str_str);
5112 if (func != NULL) {
5113 res = PyEval_CallObject(func, NULL);
5114 Py_DECREF(func);
5115 return res;
5116 }
5117 else {
5118 PyObject *ress;
5119 PyErr_Clear();
5120 res = slot_tp_repr(self);
5121 if (!res)
5122 return NULL;
Victor Stinnerf3fd7332011-03-02 01:03:11 +00005123 ress = _PyUnicode_AsDefaultEncodedString(res);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005124 Py_DECREF(res);
5125 return ress;
5126 }
Guido van Rossumb8f63662001-08-15 23:57:02 +00005127}
Tim Peters6d6c1a32001-08-02 04:15:00 +00005128
Benjamin Peterson8f67d082010-10-17 20:54:53 +00005129static Py_hash_t
Tim Peters6d6c1a32001-08-02 04:15:00 +00005130slot_tp_hash(PyObject *self)
5131{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005132 PyObject *func, *res;
5133 static PyObject *hash_str;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00005134 Py_ssize_t h;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005135
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005136 func = lookup_method(self, "__hash__", &hash_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005137
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005138 if (func == Py_None) {
5139 Py_DECREF(func);
5140 func = NULL;
5141 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +00005142
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005143 if (func == NULL) {
5144 return PyObject_HashNotImplemented(self);
5145 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +00005146
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005147 res = PyEval_CallObject(func, NULL);
5148 Py_DECREF(func);
5149 if (res == NULL)
5150 return -1;
Mark Dickinsondc787d22010-05-23 13:33:13 +00005151
5152 if (!PyLong_Check(res)) {
5153 PyErr_SetString(PyExc_TypeError,
5154 "__hash__ method should return an integer");
5155 return -1;
5156 }
Benjamin Peterson8f67d082010-10-17 20:54:53 +00005157 /* Transform the PyLong `res` to a Py_hash_t `h`. For an existing
5158 hashable Python object x, hash(x) will always lie within the range of
5159 Py_hash_t. Therefore our transformation must preserve values that
5160 already lie within this range, to ensure that if x.__hash__() returns
5161 hash(y) then hash(x) == hash(y). */
5162 h = PyLong_AsSsize_t(res);
5163 if (h == -1 && PyErr_Occurred()) {
5164 /* res was not within the range of a Py_hash_t, so we're free to
Mark Dickinsondc787d22010-05-23 13:33:13 +00005165 use any sufficiently bit-mixing transformation;
5166 long.__hash__ will do nicely. */
Benjamin Peterson8f67d082010-10-17 20:54:53 +00005167 PyErr_Clear();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005168 h = PyLong_Type.tp_hash(res);
Benjamin Peterson8f67d082010-10-17 20:54:53 +00005169 }
Benjamin Petersone7dfeeb2010-10-17 21:27:01 +00005170 /* -1 is reserved for errors. */
5171 if (h == -1)
5172 h = -2;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005173 Py_DECREF(res);
Mark Dickinsondc787d22010-05-23 13:33:13 +00005174 return h;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005175}
5176
5177static PyObject *
5178slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds)
5179{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005180 static PyObject *call_str;
5181 PyObject *meth = lookup_method(self, "__call__", &call_str);
5182 PyObject *res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005183
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005184 if (meth == NULL)
5185 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005186
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005187 res = PyObject_Call(meth, args, kwds);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005188
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005189 Py_DECREF(meth);
5190 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005191}
5192
Guido van Rossum14a6f832001-10-17 13:59:09 +00005193/* There are two slot dispatch functions for tp_getattro.
5194
5195 - slot_tp_getattro() is used when __getattribute__ is overridden
5196 but no __getattr__ hook is present;
5197
5198 - slot_tp_getattr_hook() is used when a __getattr__ hook is present.
5199
Guido van Rossumc334df52002-04-04 23:44:47 +00005200 The code in update_one_slot() always installs slot_tp_getattr_hook(); this
5201 detects the absence of __getattr__ and then installs the simpler slot if
5202 necessary. */
Guido van Rossum14a6f832001-10-17 13:59:09 +00005203
Tim Peters6d6c1a32001-08-02 04:15:00 +00005204static PyObject *
5205slot_tp_getattro(PyObject *self, PyObject *name)
5206{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005207 static PyObject *getattribute_str = NULL;
5208 return call_method(self, "__getattribute__", &getattribute_str,
5209 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005210}
5211
Guido van Rossum19c1cd52001-09-21 21:24:49 +00005212static PyObject *
Benjamin Peterson9262b842008-11-17 22:45:50 +00005213call_attribute(PyObject *self, PyObject *attr, PyObject *name)
5214{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005215 PyObject *res, *descr = NULL;
5216 descrgetfunc f = Py_TYPE(attr)->tp_descr_get;
Benjamin Peterson9262b842008-11-17 22:45:50 +00005217
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005218 if (f != NULL) {
5219 descr = f(attr, self, (PyObject *)(Py_TYPE(self)));
5220 if (descr == NULL)
5221 return NULL;
5222 else
5223 attr = descr;
5224 }
5225 res = PyObject_CallFunctionObjArgs(attr, name, NULL);
5226 Py_XDECREF(descr);
5227 return res;
Benjamin Peterson9262b842008-11-17 22:45:50 +00005228}
5229
5230static PyObject *
Guido van Rossum19c1cd52001-09-21 21:24:49 +00005231slot_tp_getattr_hook(PyObject *self, PyObject *name)
5232{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005233 PyTypeObject *tp = Py_TYPE(self);
5234 PyObject *getattr, *getattribute, *res;
5235 static PyObject *getattribute_str = NULL;
5236 static PyObject *getattr_str = NULL;
Guido van Rossum19c1cd52001-09-21 21:24:49 +00005237
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005238 if (getattr_str == NULL) {
5239 getattr_str = PyUnicode_InternFromString("__getattr__");
5240 if (getattr_str == NULL)
5241 return NULL;
5242 }
5243 if (getattribute_str == NULL) {
5244 getattribute_str =
5245 PyUnicode_InternFromString("__getattribute__");
5246 if (getattribute_str == NULL)
5247 return NULL;
5248 }
5249 /* speed hack: we could use lookup_maybe, but that would resolve the
5250 method fully for each attribute lookup for classes with
5251 __getattr__, even when the attribute is present. So we use
5252 _PyType_Lookup and create the method only when needed, with
5253 call_attribute. */
5254 getattr = _PyType_Lookup(tp, getattr_str);
5255 if (getattr == NULL) {
5256 /* No __getattr__ hook: use a simpler dispatcher */
5257 tp->tp_getattro = slot_tp_getattro;
5258 return slot_tp_getattro(self, name);
5259 }
5260 Py_INCREF(getattr);
5261 /* speed hack: we could use lookup_maybe, but that would resolve the
5262 method fully for each attribute lookup for classes with
5263 __getattr__, even when self has the default __getattribute__
5264 method. So we use _PyType_Lookup and create the method only when
5265 needed, with call_attribute. */
5266 getattribute = _PyType_Lookup(tp, getattribute_str);
5267 if (getattribute == NULL ||
5268 (Py_TYPE(getattribute) == &PyWrapperDescr_Type &&
5269 ((PyWrapperDescrObject *)getattribute)->d_wrapped ==
5270 (void *)PyObject_GenericGetAttr))
5271 res = PyObject_GenericGetAttr(self, name);
5272 else {
5273 Py_INCREF(getattribute);
5274 res = call_attribute(self, getattribute, name);
5275 Py_DECREF(getattribute);
5276 }
5277 if (res == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) {
5278 PyErr_Clear();
5279 res = call_attribute(self, getattr, name);
5280 }
5281 Py_DECREF(getattr);
5282 return res;
Guido van Rossum19c1cd52001-09-21 21:24:49 +00005283}
5284
Tim Peters6d6c1a32001-08-02 04:15:00 +00005285static int
5286slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value)
5287{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005288 PyObject *res;
5289 static PyObject *delattr_str, *setattr_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005290
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005291 if (value == NULL)
5292 res = call_method(self, "__delattr__", &delattr_str,
5293 "(O)", name);
5294 else
5295 res = call_method(self, "__setattr__", &setattr_str,
5296 "(OO)", name, value);
5297 if (res == NULL)
5298 return -1;
5299 Py_DECREF(res);
5300 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005301}
5302
Guido van Rossumf5243f02008-01-01 04:06:48 +00005303static char *name_op[] = {
5304 "__lt__",
5305 "__le__",
5306 "__eq__",
5307 "__ne__",
5308 "__gt__",
5309 "__ge__",
5310};
5311
Tim Peters6d6c1a32001-08-02 04:15:00 +00005312static PyObject *
Mark Dickinson6f1d0492009-11-15 13:58:49 +00005313slot_tp_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005314{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005315 PyObject *func, *args, *res;
5316 static PyObject *op_str[6];
Tim Peters6d6c1a32001-08-02 04:15:00 +00005317
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005318 func = lookup_method(self, name_op[op], &op_str[op]);
5319 if (func == NULL) {
5320 PyErr_Clear();
5321 Py_INCREF(Py_NotImplemented);
5322 return Py_NotImplemented;
5323 }
5324 args = PyTuple_Pack(1, other);
5325 if (args == NULL)
5326 res = NULL;
5327 else {
5328 res = PyObject_Call(func, args, NULL);
5329 Py_DECREF(args);
5330 }
5331 Py_DECREF(func);
5332 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005333}
5334
Guido van Rossumb8f63662001-08-15 23:57:02 +00005335static PyObject *
Guido van Rossumb8f63662001-08-15 23:57:02 +00005336slot_tp_iter(PyObject *self)
5337{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005338 PyObject *func, *res;
5339 static PyObject *iter_str, *getitem_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00005340
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005341 func = lookup_method(self, "__iter__", &iter_str);
5342 if (func != NULL) {
5343 PyObject *args;
5344 args = res = PyTuple_New(0);
5345 if (args != NULL) {
5346 res = PyObject_Call(func, args, NULL);
5347 Py_DECREF(args);
5348 }
5349 Py_DECREF(func);
5350 return res;
5351 }
5352 PyErr_Clear();
5353 func = lookup_method(self, "__getitem__", &getitem_str);
5354 if (func == NULL) {
5355 PyErr_Format(PyExc_TypeError,
5356 "'%.200s' object is not iterable",
5357 Py_TYPE(self)->tp_name);
5358 return NULL;
5359 }
5360 Py_DECREF(func);
5361 return PySeqIter_New(self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005362}
Tim Peters6d6c1a32001-08-02 04:15:00 +00005363
5364static PyObject *
5365slot_tp_iternext(PyObject *self)
5366{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005367 static PyObject *next_str;
5368 return call_method(self, "__next__", &next_str, "()");
Tim Peters6d6c1a32001-08-02 04:15:00 +00005369}
5370
Guido van Rossum1a493502001-08-17 16:47:50 +00005371static PyObject *
5372slot_tp_descr_get(PyObject *self, PyObject *obj, PyObject *type)
5373{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005374 PyTypeObject *tp = Py_TYPE(self);
5375 PyObject *get;
5376 static PyObject *get_str = NULL;
Guido van Rossum1a493502001-08-17 16:47:50 +00005377
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005378 if (get_str == NULL) {
5379 get_str = PyUnicode_InternFromString("__get__");
5380 if (get_str == NULL)
5381 return NULL;
5382 }
5383 get = _PyType_Lookup(tp, get_str);
5384 if (get == NULL) {
5385 /* Avoid further slowdowns */
5386 if (tp->tp_descr_get == slot_tp_descr_get)
5387 tp->tp_descr_get = NULL;
5388 Py_INCREF(self);
5389 return self;
5390 }
5391 if (obj == NULL)
5392 obj = Py_None;
5393 if (type == NULL)
5394 type = Py_None;
5395 return PyObject_CallFunctionObjArgs(get, self, obj, type, NULL);
Guido van Rossum1a493502001-08-17 16:47:50 +00005396}
Tim Peters6d6c1a32001-08-02 04:15:00 +00005397
5398static int
5399slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value)
5400{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005401 PyObject *res;
5402 static PyObject *del_str, *set_str;
Guido van Rossum2c252392001-08-24 10:13:31 +00005403
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005404 if (value == NULL)
5405 res = call_method(self, "__delete__", &del_str,
5406 "(O)", target);
5407 else
5408 res = call_method(self, "__set__", &set_str,
5409 "(OO)", target, value);
5410 if (res == NULL)
5411 return -1;
5412 Py_DECREF(res);
5413 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005414}
5415
5416static int
5417slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds)
5418{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005419 static PyObject *init_str;
5420 PyObject *meth = lookup_method(self, "__init__", &init_str);
5421 PyObject *res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005422
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005423 if (meth == NULL)
5424 return -1;
5425 res = PyObject_Call(meth, args, kwds);
5426 Py_DECREF(meth);
5427 if (res == NULL)
5428 return -1;
5429 if (res != Py_None) {
5430 PyErr_Format(PyExc_TypeError,
5431 "__init__() should return None, not '%.200s'",
5432 Py_TYPE(res)->tp_name);
5433 Py_DECREF(res);
5434 return -1;
5435 }
5436 Py_DECREF(res);
5437 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005438}
5439
5440static PyObject *
5441slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
5442{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005443 static PyObject *new_str;
5444 PyObject *func;
5445 PyObject *newargs, *x;
5446 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005447
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005448 if (new_str == NULL) {
5449 new_str = PyUnicode_InternFromString("__new__");
5450 if (new_str == NULL)
5451 return NULL;
5452 }
5453 func = PyObject_GetAttr((PyObject *)type, new_str);
5454 if (func == NULL)
5455 return NULL;
5456 assert(PyTuple_Check(args));
5457 n = PyTuple_GET_SIZE(args);
5458 newargs = PyTuple_New(n+1);
5459 if (newargs == NULL)
5460 return NULL;
5461 Py_INCREF(type);
5462 PyTuple_SET_ITEM(newargs, 0, (PyObject *)type);
5463 for (i = 0; i < n; i++) {
5464 x = PyTuple_GET_ITEM(args, i);
5465 Py_INCREF(x);
5466 PyTuple_SET_ITEM(newargs, i+1, x);
5467 }
5468 x = PyObject_Call(func, newargs, kwds);
5469 Py_DECREF(newargs);
5470 Py_DECREF(func);
5471 return x;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005472}
5473
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005474static void
5475slot_tp_del(PyObject *self)
5476{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005477 static PyObject *del_str = NULL;
5478 PyObject *del, *res;
5479 PyObject *error_type, *error_value, *error_traceback;
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005480
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005481 /* Temporarily resurrect the object. */
5482 assert(self->ob_refcnt == 0);
5483 self->ob_refcnt = 1;
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005484
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005485 /* Save the current exception, if any. */
5486 PyErr_Fetch(&error_type, &error_value, &error_traceback);
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005487
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005488 /* Execute __del__ method, if any. */
5489 del = lookup_maybe(self, "__del__", &del_str);
5490 if (del != NULL) {
5491 res = PyEval_CallObject(del, NULL);
5492 if (res == NULL)
5493 PyErr_WriteUnraisable(del);
5494 else
5495 Py_DECREF(res);
5496 Py_DECREF(del);
5497 }
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005498
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005499 /* Restore the saved exception. */
5500 PyErr_Restore(error_type, error_value, error_traceback);
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005501
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005502 /* Undo the temporary resurrection; can't use DECREF here, it would
5503 * cause a recursive call.
5504 */
5505 assert(self->ob_refcnt > 0);
5506 if (--self->ob_refcnt == 0)
5507 return; /* this is the normal path out */
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005508
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005509 /* __del__ resurrected it! Make it look like the original Py_DECREF
5510 * never happened.
5511 */
5512 {
5513 Py_ssize_t refcnt = self->ob_refcnt;
5514 _Py_NewReference(self);
5515 self->ob_refcnt = refcnt;
5516 }
5517 assert(!PyType_IS_GC(Py_TYPE(self)) ||
5518 _Py_AS_GC(self)->gc.gc_refs != _PyGC_REFS_UNTRACKED);
5519 /* If Py_REF_DEBUG, _Py_NewReference bumped _Py_RefTotal, so
5520 * we need to undo that. */
5521 _Py_DEC_REFTOTAL;
5522 /* If Py_TRACE_REFS, _Py_NewReference re-added self to the object
5523 * chain, so no more to do there.
5524 * If COUNT_ALLOCS, the original decref bumped tp_frees, and
5525 * _Py_NewReference bumped tp_allocs: both of those need to be
5526 * undone.
5527 */
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005528#ifdef COUNT_ALLOCS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005529 --Py_TYPE(self)->tp_frees;
5530 --Py_TYPE(self)->tp_allocs;
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005531#endif
5532}
5533
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005534
5535/* Table mapping __foo__ names to tp_foo offsets and slot_tp_foo wrapper
Tim Petersbf9b2442003-03-23 05:35:36 +00005536 functions. The offsets here are relative to the 'PyHeapTypeObject'
Guido van Rossume5c691a2003-03-07 15:13:17 +00005537 structure, which incorporates the additional structures used for numbers,
5538 sequences and mappings.
5539 Note that multiple names may map to the same slot (e.g. __eq__,
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005540 __ne__ etc. all map to tp_richcompare) and one name may map to multiple
Guido van Rossumc334df52002-04-04 23:44:47 +00005541 slots (e.g. __str__ affects tp_str as well as tp_repr). The table is
5542 terminated with an all-zero entry. (This table is further initialized and
5543 sorted in init_slotdefs() below.) */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005544
Guido van Rossum6d204072001-10-21 00:44:31 +00005545typedef struct wrapperbase slotdef;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005546
5547#undef TPSLOT
Guido van Rossumc8e56452001-10-22 00:43:43 +00005548#undef FLSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005549#undef ETSLOT
5550#undef SQSLOT
5551#undef MPSLOT
5552#undef NBSLOT
Guido van Rossum6d204072001-10-21 00:44:31 +00005553#undef UNSLOT
5554#undef IBSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005555#undef BINSLOT
5556#undef RBINSLOT
5557
Guido van Rossum6d204072001-10-21 00:44:31 +00005558#define TPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005559 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
5560 PyDoc_STR(DOC)}
Guido van Rossumc8e56452001-10-22 00:43:43 +00005561#define FLSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC, FLAGS) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005562 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
5563 PyDoc_STR(DOC), FLAGS}
Guido van Rossum6d204072001-10-21 00:44:31 +00005564#define ETSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005565 {NAME, offsetof(PyHeapTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
5566 PyDoc_STR(DOC)}
Guido van Rossum6d204072001-10-21 00:44:31 +00005567#define SQSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005568 ETSLOT(NAME, as_sequence.SLOT, FUNCTION, WRAPPER, DOC)
Guido van Rossum6d204072001-10-21 00:44:31 +00005569#define MPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005570 ETSLOT(NAME, as_mapping.SLOT, FUNCTION, WRAPPER, DOC)
Guido van Rossum6d204072001-10-21 00:44:31 +00005571#define NBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005572 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, DOC)
Guido van Rossum6d204072001-10-21 00:44:31 +00005573#define UNSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005574 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
5575 "x." NAME "() <==> " DOC)
Guido van Rossum6d204072001-10-21 00:44:31 +00005576#define IBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005577 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
5578 "x." NAME "(y) <==> x" DOC "y")
Guido van Rossum6d204072001-10-21 00:44:31 +00005579#define BINSLOT(NAME, SLOT, FUNCTION, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005580 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
5581 "x." NAME "(y) <==> x" DOC "y")
Guido van Rossum6d204072001-10-21 00:44:31 +00005582#define RBINSLOT(NAME, SLOT, FUNCTION, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005583 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
5584 "x." NAME "(y) <==> y" DOC "x")
Anthony Baxter56616992005-06-03 14:12:21 +00005585#define BINSLOTNOTINFIX(NAME, SLOT, FUNCTION, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005586 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
5587 "x." NAME "(y) <==> " DOC)
Anthony Baxter56616992005-06-03 14:12:21 +00005588#define RBINSLOTNOTINFIX(NAME, SLOT, FUNCTION, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005589 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
5590 "x." NAME "(y) <==> " DOC)
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005591
5592static slotdef slotdefs[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005593 SQSLOT("__len__", sq_length, slot_sq_length, wrap_lenfunc,
5594 "x.__len__() <==> len(x)"),
5595 /* Heap types defining __add__/__mul__ have sq_concat/sq_repeat == NULL.
5596 The logic in abstract.c always falls back to nb_add/nb_multiply in
5597 this case. Defining both the nb_* and the sq_* slots to call the
5598 user-defined methods has unexpected side-effects, as shown by
5599 test_descr.notimplemented() */
5600 SQSLOT("__add__", sq_concat, NULL, wrap_binaryfunc,
5601 "x.__add__(y) <==> x+y"),
5602 SQSLOT("__mul__", sq_repeat, NULL, wrap_indexargfunc,
5603 "x.__mul__(n) <==> x*n"),
5604 SQSLOT("__rmul__", sq_repeat, NULL, wrap_indexargfunc,
5605 "x.__rmul__(n) <==> n*x"),
5606 SQSLOT("__getitem__", sq_item, slot_sq_item, wrap_sq_item,
5607 "x.__getitem__(y) <==> x[y]"),
5608 SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_setitem,
5609 "x.__setitem__(i, y) <==> x[i]=y"),
5610 SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_delitem,
5611 "x.__delitem__(y) <==> del x[y]"),
5612 SQSLOT("__contains__", sq_contains, slot_sq_contains, wrap_objobjproc,
5613 "x.__contains__(y) <==> y in x"),
5614 SQSLOT("__iadd__", sq_inplace_concat, NULL,
5615 wrap_binaryfunc, "x.__iadd__(y) <==> x+=y"),
5616 SQSLOT("__imul__", sq_inplace_repeat, NULL,
5617 wrap_indexargfunc, "x.__imul__(y) <==> x*=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005618
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005619 MPSLOT("__len__", mp_length, slot_mp_length, wrap_lenfunc,
5620 "x.__len__() <==> len(x)"),
5621 MPSLOT("__getitem__", mp_subscript, slot_mp_subscript,
5622 wrap_binaryfunc,
5623 "x.__getitem__(y) <==> x[y]"),
5624 MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript,
5625 wrap_objobjargproc,
5626 "x.__setitem__(i, y) <==> x[i]=y"),
5627 MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript,
5628 wrap_delitem,
5629 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005630
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005631 BINSLOT("__add__", nb_add, slot_nb_add,
5632 "+"),
5633 RBINSLOT("__radd__", nb_add, slot_nb_add,
5634 "+"),
5635 BINSLOT("__sub__", nb_subtract, slot_nb_subtract,
5636 "-"),
5637 RBINSLOT("__rsub__", nb_subtract, slot_nb_subtract,
5638 "-"),
5639 BINSLOT("__mul__", nb_multiply, slot_nb_multiply,
5640 "*"),
5641 RBINSLOT("__rmul__", nb_multiply, slot_nb_multiply,
5642 "*"),
5643 BINSLOT("__mod__", nb_remainder, slot_nb_remainder,
5644 "%"),
5645 RBINSLOT("__rmod__", nb_remainder, slot_nb_remainder,
5646 "%"),
5647 BINSLOTNOTINFIX("__divmod__", nb_divmod, slot_nb_divmod,
5648 "divmod(x, y)"),
5649 RBINSLOTNOTINFIX("__rdivmod__", nb_divmod, slot_nb_divmod,
5650 "divmod(y, x)"),
5651 NBSLOT("__pow__", nb_power, slot_nb_power, wrap_ternaryfunc,
5652 "x.__pow__(y[, z]) <==> pow(x, y[, z])"),
5653 NBSLOT("__rpow__", nb_power, slot_nb_power, wrap_ternaryfunc_r,
5654 "y.__rpow__(x[, z]) <==> pow(x, y[, z])"),
5655 UNSLOT("__neg__", nb_negative, slot_nb_negative, wrap_unaryfunc, "-x"),
5656 UNSLOT("__pos__", nb_positive, slot_nb_positive, wrap_unaryfunc, "+x"),
5657 UNSLOT("__abs__", nb_absolute, slot_nb_absolute, wrap_unaryfunc,
5658 "abs(x)"),
5659 UNSLOT("__bool__", nb_bool, slot_nb_bool, wrap_inquirypred,
5660 "x != 0"),
5661 UNSLOT("__invert__", nb_invert, slot_nb_invert, wrap_unaryfunc, "~x"),
5662 BINSLOT("__lshift__", nb_lshift, slot_nb_lshift, "<<"),
5663 RBINSLOT("__rlshift__", nb_lshift, slot_nb_lshift, "<<"),
5664 BINSLOT("__rshift__", nb_rshift, slot_nb_rshift, ">>"),
5665 RBINSLOT("__rrshift__", nb_rshift, slot_nb_rshift, ">>"),
5666 BINSLOT("__and__", nb_and, slot_nb_and, "&"),
5667 RBINSLOT("__rand__", nb_and, slot_nb_and, "&"),
5668 BINSLOT("__xor__", nb_xor, slot_nb_xor, "^"),
5669 RBINSLOT("__rxor__", nb_xor, slot_nb_xor, "^"),
5670 BINSLOT("__or__", nb_or, slot_nb_or, "|"),
5671 RBINSLOT("__ror__", nb_or, slot_nb_or, "|"),
5672 UNSLOT("__int__", nb_int, slot_nb_int, wrap_unaryfunc,
5673 "int(x)"),
5674 UNSLOT("__float__", nb_float, slot_nb_float, wrap_unaryfunc,
5675 "float(x)"),
5676 NBSLOT("__index__", nb_index, slot_nb_index, wrap_unaryfunc,
5677 "x[y:z] <==> x[y.__index__():z.__index__()]"),
5678 IBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add,
5679 wrap_binaryfunc, "+"),
5680 IBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract,
5681 wrap_binaryfunc, "-"),
5682 IBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply,
5683 wrap_binaryfunc, "*"),
5684 IBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder,
5685 wrap_binaryfunc, "%"),
5686 IBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power,
5687 wrap_binaryfunc, "**"),
5688 IBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift,
5689 wrap_binaryfunc, "<<"),
5690 IBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift,
5691 wrap_binaryfunc, ">>"),
5692 IBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and,
5693 wrap_binaryfunc, "&"),
5694 IBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor,
5695 wrap_binaryfunc, "^"),
5696 IBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or,
5697 wrap_binaryfunc, "|"),
5698 BINSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
5699 RBINSLOT("__rfloordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
5700 BINSLOT("__truediv__", nb_true_divide, slot_nb_true_divide, "/"),
5701 RBINSLOT("__rtruediv__", nb_true_divide, slot_nb_true_divide, "/"),
5702 IBSLOT("__ifloordiv__", nb_inplace_floor_divide,
5703 slot_nb_inplace_floor_divide, wrap_binaryfunc, "//"),
5704 IBSLOT("__itruediv__", nb_inplace_true_divide,
5705 slot_nb_inplace_true_divide, wrap_binaryfunc, "/"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005706
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005707 TPSLOT("__str__", tp_str, slot_tp_str, wrap_unaryfunc,
5708 "x.__str__() <==> str(x)"),
5709 TPSLOT("__repr__", tp_repr, slot_tp_repr, wrap_unaryfunc,
5710 "x.__repr__() <==> repr(x)"),
5711 TPSLOT("__hash__", tp_hash, slot_tp_hash, wrap_hashfunc,
5712 "x.__hash__() <==> hash(x)"),
5713 FLSLOT("__call__", tp_call, slot_tp_call, (wrapperfunc)wrap_call,
5714 "x.__call__(...) <==> x(...)", PyWrapperFlag_KEYWORDS),
5715 TPSLOT("__getattribute__", tp_getattro, slot_tp_getattr_hook,
5716 wrap_binaryfunc, "x.__getattribute__('name') <==> x.name"),
5717 TPSLOT("__getattribute__", tp_getattr, NULL, NULL, ""),
5718 TPSLOT("__getattr__", tp_getattro, slot_tp_getattr_hook, NULL, ""),
5719 TPSLOT("__getattr__", tp_getattr, NULL, NULL, ""),
5720 TPSLOT("__setattr__", tp_setattro, slot_tp_setattro, wrap_setattr,
5721 "x.__setattr__('name', value) <==> x.name = value"),
5722 TPSLOT("__setattr__", tp_setattr, NULL, NULL, ""),
5723 TPSLOT("__delattr__", tp_setattro, slot_tp_setattro, wrap_delattr,
5724 "x.__delattr__('name') <==> del x.name"),
5725 TPSLOT("__delattr__", tp_setattr, NULL, NULL, ""),
5726 TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare, richcmp_lt,
5727 "x.__lt__(y) <==> x<y"),
5728 TPSLOT("__le__", tp_richcompare, slot_tp_richcompare, richcmp_le,
5729 "x.__le__(y) <==> x<=y"),
5730 TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare, richcmp_eq,
5731 "x.__eq__(y) <==> x==y"),
5732 TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare, richcmp_ne,
5733 "x.__ne__(y) <==> x!=y"),
5734 TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare, richcmp_gt,
5735 "x.__gt__(y) <==> x>y"),
5736 TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare, richcmp_ge,
5737 "x.__ge__(y) <==> x>=y"),
5738 TPSLOT("__iter__", tp_iter, slot_tp_iter, wrap_unaryfunc,
5739 "x.__iter__() <==> iter(x)"),
5740 TPSLOT("__next__", tp_iternext, slot_tp_iternext, wrap_next,
5741 "x.__next__() <==> next(x)"),
5742 TPSLOT("__get__", tp_descr_get, slot_tp_descr_get, wrap_descr_get,
5743 "descr.__get__(obj[, type]) -> value"),
5744 TPSLOT("__set__", tp_descr_set, slot_tp_descr_set, wrap_descr_set,
5745 "descr.__set__(obj, value)"),
5746 TPSLOT("__delete__", tp_descr_set, slot_tp_descr_set,
5747 wrap_descr_delete, "descr.__delete__(obj)"),
5748 FLSLOT("__init__", tp_init, slot_tp_init, (wrapperfunc)wrap_init,
5749 "x.__init__(...) initializes x; "
Alexander Belopolsky977a6842010-08-16 20:17:07 +00005750 "see help(type(x)) for signature",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005751 PyWrapperFlag_KEYWORDS),
5752 TPSLOT("__new__", tp_new, slot_tp_new, NULL, ""),
5753 TPSLOT("__del__", tp_del, slot_tp_del, NULL, ""),
5754 {NULL}
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005755};
5756
Guido van Rossumc334df52002-04-04 23:44:47 +00005757/* Given a type pointer and an offset gotten from a slotdef entry, return a
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005758 pointer to the actual slot. This is not quite the same as simply adding
Guido van Rossumc334df52002-04-04 23:44:47 +00005759 the offset to the type pointer, since it takes care to indirect through the
5760 proper indirection pointer (as_buffer, etc.); it returns NULL if the
5761 indirection pointer is NULL. */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005762static void **
Martin v. Löwis18e16552006-02-15 17:27:45 +00005763slotptr(PyTypeObject *type, int ioffset)
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005764{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005765 char *ptr;
5766 long offset = ioffset;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005767
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005768 /* Note: this depends on the order of the members of PyHeapTypeObject! */
5769 assert(offset >= 0);
5770 assert((size_t)offset < offsetof(PyHeapTypeObject, as_buffer));
5771 if ((size_t)offset >= offsetof(PyHeapTypeObject, as_sequence)) {
5772 ptr = (char *)type->tp_as_sequence;
5773 offset -= offsetof(PyHeapTypeObject, as_sequence);
5774 }
5775 else if ((size_t)offset >= offsetof(PyHeapTypeObject, as_mapping)) {
5776 ptr = (char *)type->tp_as_mapping;
5777 offset -= offsetof(PyHeapTypeObject, as_mapping);
5778 }
5779 else if ((size_t)offset >= offsetof(PyHeapTypeObject, as_number)) {
5780 ptr = (char *)type->tp_as_number;
5781 offset -= offsetof(PyHeapTypeObject, as_number);
5782 }
5783 else {
5784 ptr = (char *)type;
5785 }
5786 if (ptr != NULL)
5787 ptr += offset;
5788 return (void **)ptr;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005789}
Guido van Rossumf040ede2001-08-07 16:40:56 +00005790
Guido van Rossumc334df52002-04-04 23:44:47 +00005791/* Length of array of slotdef pointers used to store slots with the
5792 same __name__. There should be at most MAX_EQUIV-1 slotdef entries with
5793 the same __name__, for any __name__. Since that's a static property, it is
5794 appropriate to declare fixed-size arrays for this. */
5795#define MAX_EQUIV 10
5796
5797/* Return a slot pointer for a given name, but ONLY if the attribute has
5798 exactly one slot function. The name must be an interned string. */
5799static void **
5800resolve_slotdups(PyTypeObject *type, PyObject *name)
5801{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005802 /* XXX Maybe this could be optimized more -- but is it worth it? */
Guido van Rossumc334df52002-04-04 23:44:47 +00005803
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005804 /* pname and ptrs act as a little cache */
5805 static PyObject *pname;
5806 static slotdef *ptrs[MAX_EQUIV];
5807 slotdef *p, **pp;
5808 void **res, **ptr;
Guido van Rossumc334df52002-04-04 23:44:47 +00005809
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005810 if (pname != name) {
5811 /* Collect all slotdefs that match name into ptrs. */
5812 pname = name;
5813 pp = ptrs;
5814 for (p = slotdefs; p->name_strobj; p++) {
5815 if (p->name_strobj == name)
5816 *pp++ = p;
5817 }
5818 *pp = NULL;
5819 }
Guido van Rossumc334df52002-04-04 23:44:47 +00005820
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005821 /* Look in all matching slots of the type; if exactly one of these has
5822 a filled-in slot, return its value. Otherwise return NULL. */
5823 res = NULL;
5824 for (pp = ptrs; *pp; pp++) {
5825 ptr = slotptr(type, (*pp)->offset);
5826 if (ptr == NULL || *ptr == NULL)
5827 continue;
5828 if (res != NULL)
5829 return NULL;
5830 res = ptr;
5831 }
5832 return res;
Guido van Rossumc334df52002-04-04 23:44:47 +00005833}
5834
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005835/* Common code for update_slots_callback() and fixup_slot_dispatchers(). This
Guido van Rossumc334df52002-04-04 23:44:47 +00005836 does some incredibly complex thinking and then sticks something into the
5837 slot. (It sees if the adjacent slotdefs for the same slot have conflicting
5838 interests, and then stores a generic wrapper or a specific function into
5839 the slot.) Return a pointer to the next slotdef with a different offset,
5840 because that's convenient for fixup_slot_dispatchers(). */
5841static slotdef *
5842update_one_slot(PyTypeObject *type, slotdef *p)
5843{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005844 PyObject *descr;
5845 PyWrapperDescrObject *d;
5846 void *generic = NULL, *specific = NULL;
5847 int use_generic = 0;
5848 int offset = p->offset;
5849 void **ptr = slotptr(type, offset);
Guido van Rossumc334df52002-04-04 23:44:47 +00005850
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005851 if (ptr == NULL) {
5852 do {
5853 ++p;
5854 } while (p->offset == offset);
5855 return p;
5856 }
5857 do {
5858 descr = _PyType_Lookup(type, p->name_strobj);
5859 if (descr == NULL) {
5860 if (ptr == (void**)&type->tp_iternext) {
5861 specific = _PyObject_NextNotImplemented;
5862 }
5863 continue;
5864 }
5865 if (Py_TYPE(descr) == &PyWrapperDescr_Type) {
5866 void **tptr = resolve_slotdups(type, p->name_strobj);
5867 if (tptr == NULL || tptr == ptr)
5868 generic = p->function;
5869 d = (PyWrapperDescrObject *)descr;
5870 if (d->d_base->wrapper == p->wrapper &&
5871 PyType_IsSubtype(type, PyDescr_TYPE(d)))
5872 {
5873 if (specific == NULL ||
5874 specific == d->d_wrapped)
5875 specific = d->d_wrapped;
5876 else
5877 use_generic = 1;
5878 }
5879 }
5880 else if (Py_TYPE(descr) == &PyCFunction_Type &&
5881 PyCFunction_GET_FUNCTION(descr) ==
5882 (PyCFunction)tp_new_wrapper &&
5883 ptr == (void**)&type->tp_new)
5884 {
5885 /* The __new__ wrapper is not a wrapper descriptor,
5886 so must be special-cased differently.
5887 If we don't do this, creating an instance will
5888 always use slot_tp_new which will look up
5889 __new__ in the MRO which will call tp_new_wrapper
5890 which will look through the base classes looking
5891 for a static base and call its tp_new (usually
5892 PyType_GenericNew), after performing various
5893 sanity checks and constructing a new argument
5894 list. Cut all that nonsense short -- this speeds
5895 up instance creation tremendously. */
5896 specific = (void *)type->tp_new;
5897 /* XXX I'm not 100% sure that there isn't a hole
5898 in this reasoning that requires additional
5899 sanity checks. I'll buy the first person to
5900 point out a bug in this reasoning a beer. */
5901 }
5902 else if (descr == Py_None &&
5903 ptr == (void**)&type->tp_hash) {
5904 /* We specifically allow __hash__ to be set to None
5905 to prevent inheritance of the default
5906 implementation from object.__hash__ */
5907 specific = PyObject_HashNotImplemented;
5908 }
5909 else {
5910 use_generic = 1;
5911 generic = p->function;
5912 }
5913 } while ((++p)->offset == offset);
5914 if (specific && !use_generic)
5915 *ptr = specific;
5916 else
5917 *ptr = generic;
5918 return p;
Guido van Rossumc334df52002-04-04 23:44:47 +00005919}
5920
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005921/* In the type, update the slots whose slotdefs are gathered in the pp array.
5922 This is a callback for update_subclasses(). */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005923static int
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005924update_slots_callback(PyTypeObject *type, void *data)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005925{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005926 slotdef **pp = (slotdef **)data;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005927
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005928 for (; *pp; pp++)
5929 update_one_slot(type, *pp);
5930 return 0;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005931}
5932
Guido van Rossumc334df52002-04-04 23:44:47 +00005933/* Comparison function for qsort() to compare slotdefs by their offset, and
5934 for equal offset by their address (to force a stable sort). */
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005935static int
5936slotdef_cmp(const void *aa, const void *bb)
5937{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005938 const slotdef *a = (const slotdef *)aa, *b = (const slotdef *)bb;
5939 int c = a->offset - b->offset;
5940 if (c != 0)
5941 return c;
5942 else
5943 /* Cannot use a-b, as this gives off_t,
5944 which may lose precision when converted to int. */
5945 return (a > b) ? 1 : (a < b) ? -1 : 0;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005946}
5947
Guido van Rossumc334df52002-04-04 23:44:47 +00005948/* Initialize the slotdefs table by adding interned string objects for the
5949 names and sorting the entries. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005950static void
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005951init_slotdefs(void)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005952{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005953 slotdef *p;
5954 static int initialized = 0;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005955
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005956 if (initialized)
5957 return;
5958 for (p = slotdefs; p->name; p++) {
5959 p->name_strobj = PyUnicode_InternFromString(p->name);
5960 if (!p->name_strobj)
5961 Py_FatalError("Out of memory interning slotdef names");
5962 }
5963 qsort((void *)slotdefs, (size_t)(p-slotdefs), sizeof(slotdef),
5964 slotdef_cmp);
5965 initialized = 1;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005966}
5967
Guido van Rossumc334df52002-04-04 23:44:47 +00005968/* Update the slots after assignment to a class (type) attribute. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005969static int
5970update_slot(PyTypeObject *type, PyObject *name)
5971{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005972 slotdef *ptrs[MAX_EQUIV];
5973 slotdef *p;
5974 slotdef **pp;
5975 int offset;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005976
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005977 /* Clear the VALID_VERSION flag of 'type' and all its
5978 subclasses. This could possibly be unified with the
5979 update_subclasses() recursion below, but carefully:
5980 they each have their own conditions on which to stop
5981 recursing into subclasses. */
5982 PyType_Modified(type);
Christian Heimesa62da1d2008-01-12 19:39:10 +00005983
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005984 init_slotdefs();
5985 pp = ptrs;
5986 for (p = slotdefs; p->name; p++) {
5987 /* XXX assume name is interned! */
5988 if (p->name_strobj == name)
5989 *pp++ = p;
5990 }
5991 *pp = NULL;
5992 for (pp = ptrs; *pp; pp++) {
5993 p = *pp;
5994 offset = p->offset;
5995 while (p > slotdefs && (p-1)->offset == offset)
5996 --p;
5997 *pp = p;
5998 }
5999 if (ptrs[0] == NULL)
6000 return 0; /* Not an attribute that affects any slots */
6001 return update_subclasses(type, name,
6002 update_slots_callback, (void *)ptrs);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006003}
6004
Guido van Rossumc334df52002-04-04 23:44:47 +00006005/* Store the proper functions in the slot dispatches at class (type)
6006 definition time, based upon which operations the class overrides in its
6007 dict. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00006008static void
Guido van Rossum7b9144b2001-10-09 19:39:46 +00006009fixup_slot_dispatchers(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00006010{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006011 slotdef *p;
Tim Peters6d6c1a32001-08-02 04:15:00 +00006012
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006013 init_slotdefs();
6014 for (p = slotdefs; p->name; )
6015 p = update_one_slot(type, p);
Tim Peters6d6c1a32001-08-02 04:15:00 +00006016}
Guido van Rossum705f0f52001-08-24 16:47:00 +00006017
Michael W. Hudson98bbc492002-11-26 14:47:27 +00006018static void
6019update_all_slots(PyTypeObject* type)
6020{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006021 slotdef *p;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00006022
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006023 init_slotdefs();
6024 for (p = slotdefs; p->name; p++) {
6025 /* update_slot returns int but can't actually fail */
6026 update_slot(type, p->name_strobj);
6027 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +00006028}
6029
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006030/* recurse_down_subclasses() and update_subclasses() are mutually
6031 recursive functions to call a callback for all subclasses,
6032 but refraining from recursing into subclasses that define 'name'. */
6033
6034static int
6035update_subclasses(PyTypeObject *type, PyObject *name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006036 update_callback callback, void *data)
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006037{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006038 if (callback(type, data) < 0)
6039 return -1;
6040 return recurse_down_subclasses(type, name, callback, data);
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006041}
6042
6043static int
6044recurse_down_subclasses(PyTypeObject *type, PyObject *name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006045 update_callback callback, void *data)
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006046{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006047 PyTypeObject *subclass;
6048 PyObject *ref, *subclasses, *dict;
6049 Py_ssize_t i, n;
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006050
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006051 subclasses = type->tp_subclasses;
6052 if (subclasses == NULL)
6053 return 0;
6054 assert(PyList_Check(subclasses));
6055 n = PyList_GET_SIZE(subclasses);
6056 for (i = 0; i < n; i++) {
6057 ref = PyList_GET_ITEM(subclasses, i);
6058 assert(PyWeakref_CheckRef(ref));
6059 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
6060 assert(subclass != NULL);
6061 if ((PyObject *)subclass == Py_None)
6062 continue;
6063 assert(PyType_Check(subclass));
6064 /* Avoid recursing down into unaffected classes */
6065 dict = subclass->tp_dict;
6066 if (dict != NULL && PyDict_Check(dict) &&
6067 PyDict_GetItem(dict, name) != NULL)
6068 continue;
6069 if (update_subclasses(subclass, name, callback, data) < 0)
6070 return -1;
6071 }
6072 return 0;
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006073}
6074
Guido van Rossum6d204072001-10-21 00:44:31 +00006075/* This function is called by PyType_Ready() to populate the type's
6076 dictionary with method descriptors for function slots. For each
Guido van Rossum09638c12002-06-13 19:17:46 +00006077 function slot (like tp_repr) that's defined in the type, one or more
6078 corresponding descriptors are added in the type's tp_dict dictionary
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006079 under the appropriate name (like __repr__). Some function slots
Guido van Rossum09638c12002-06-13 19:17:46 +00006080 cause more than one descriptor to be added (for example, the nb_add
6081 slot adds both __add__ and __radd__ descriptors) and some function
6082 slots compete for the same descriptor (for example both sq_item and
6083 mp_subscript generate a __getitem__ descriptor).
6084
Ezio Melotti13925002011-03-16 11:05:33 +02006085 In the latter case, the first slotdef entry encountered wins. Since
Tim Petersbf9b2442003-03-23 05:35:36 +00006086 slotdef entries are sorted by the offset of the slot in the
Guido van Rossume5c691a2003-03-07 15:13:17 +00006087 PyHeapTypeObject, this gives us some control over disambiguating
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006088 between competing slots: the members of PyHeapTypeObject are listed
6089 from most general to least general, so the most general slot is
6090 preferred. In particular, because as_mapping comes before as_sequence,
6091 for a type that defines both mp_subscript and sq_item, mp_subscript
6092 wins.
Guido van Rossum09638c12002-06-13 19:17:46 +00006093
6094 This only adds new descriptors and doesn't overwrite entries in
6095 tp_dict that were previously defined. The descriptors contain a
6096 reference to the C function they must call, so that it's safe if they
6097 are copied into a subtype's __dict__ and the subtype has a different
6098 C function in its slot -- calling the method defined by the
6099 descriptor will call the C function that was used to create it,
6100 rather than the C function present in the slot when it is called.
6101 (This is important because a subtype may have a C function in the
6102 slot that calls the method from the dictionary, and we want to avoid
6103 infinite recursion here.) */
Guido van Rossum6d204072001-10-21 00:44:31 +00006104
6105static int
6106add_operators(PyTypeObject *type)
6107{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006108 PyObject *dict = type->tp_dict;
6109 slotdef *p;
6110 PyObject *descr;
6111 void **ptr;
Guido van Rossum6d204072001-10-21 00:44:31 +00006112
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006113 init_slotdefs();
6114 for (p = slotdefs; p->name; p++) {
6115 if (p->wrapper == NULL)
6116 continue;
6117 ptr = slotptr(type, p->offset);
6118 if (!ptr || !*ptr)
6119 continue;
6120 if (PyDict_GetItem(dict, p->name_strobj))
6121 continue;
6122 if (*ptr == PyObject_HashNotImplemented) {
6123 /* Classes may prevent the inheritance of the tp_hash
6124 slot by storing PyObject_HashNotImplemented in it. Make it
6125 visible as a None value for the __hash__ attribute. */
6126 if (PyDict_SetItem(dict, p->name_strobj, Py_None) < 0)
6127 return -1;
6128 }
6129 else {
6130 descr = PyDescr_NewWrapper(type, p, *ptr);
6131 if (descr == NULL)
6132 return -1;
6133 if (PyDict_SetItem(dict, p->name_strobj, descr) < 0)
6134 return -1;
6135 Py_DECREF(descr);
6136 }
6137 }
6138 if (type->tp_new != NULL) {
6139 if (add_tp_new_wrapper(type) < 0)
6140 return -1;
6141 }
6142 return 0;
Guido van Rossum6d204072001-10-21 00:44:31 +00006143}
6144
Guido van Rossum705f0f52001-08-24 16:47:00 +00006145
6146/* Cooperative 'super' */
6147
6148typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006149 PyObject_HEAD
6150 PyTypeObject *type;
6151 PyObject *obj;
6152 PyTypeObject *obj_type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006153} superobject;
6154
Guido van Rossum6f799372001-09-20 20:46:19 +00006155static PyMemberDef super_members[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006156 {"__thisclass__", T_OBJECT, offsetof(superobject, type), READONLY,
6157 "the class invoking super()"},
6158 {"__self__", T_OBJECT, offsetof(superobject, obj), READONLY,
6159 "the instance invoking super(); may be None"},
6160 {"__self_class__", T_OBJECT, offsetof(superobject, obj_type), READONLY,
6161 "the type of the instance invoking super(); may be None"},
6162 {0}
Guido van Rossum41eb14d2001-08-30 23:13:11 +00006163};
6164
Guido van Rossum705f0f52001-08-24 16:47:00 +00006165static void
6166super_dealloc(PyObject *self)
6167{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006168 superobject *su = (superobject *)self;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006169
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006170 _PyObject_GC_UNTRACK(self);
6171 Py_XDECREF(su->obj);
6172 Py_XDECREF(su->type);
6173 Py_XDECREF(su->obj_type);
6174 Py_TYPE(self)->tp_free(self);
Guido van Rossum705f0f52001-08-24 16:47:00 +00006175}
6176
6177static PyObject *
Guido van Rossum41eb14d2001-08-30 23:13:11 +00006178super_repr(PyObject *self)
6179{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006180 superobject *su = (superobject *)self;
Guido van Rossum41eb14d2001-08-30 23:13:11 +00006181
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006182 if (su->obj_type)
6183 return PyUnicode_FromFormat(
6184 "<super: <class '%s'>, <%s object>>",
6185 su->type ? su->type->tp_name : "NULL",
6186 su->obj_type->tp_name);
6187 else
6188 return PyUnicode_FromFormat(
6189 "<super: <class '%s'>, NULL>",
6190 su->type ? su->type->tp_name : "NULL");
Guido van Rossum41eb14d2001-08-30 23:13:11 +00006191}
6192
6193static PyObject *
Guido van Rossum705f0f52001-08-24 16:47:00 +00006194super_getattro(PyObject *self, PyObject *name)
6195{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006196 superobject *su = (superobject *)self;
6197 int skip = su->obj_type == NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006198
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006199 if (!skip) {
6200 /* We want __class__ to return the class of the super object
6201 (i.e. super, or a subclass), not the class of su->obj. */
6202 skip = (PyUnicode_Check(name) &&
6203 PyUnicode_GET_SIZE(name) == 9 &&
6204 PyUnicode_CompareWithASCIIString(name, "__class__") == 0);
6205 }
Guido van Rossum76ba09f2003-04-16 19:40:58 +00006206
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006207 if (!skip) {
6208 PyObject *mro, *res, *tmp, *dict;
6209 PyTypeObject *starttype;
6210 descrgetfunc f;
6211 Py_ssize_t i, n;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006212
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006213 starttype = su->obj_type;
6214 mro = starttype->tp_mro;
Guido van Rossum155db9a2002-04-02 17:53:47 +00006215
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006216 if (mro == NULL)
6217 n = 0;
6218 else {
6219 assert(PyTuple_Check(mro));
6220 n = PyTuple_GET_SIZE(mro);
6221 }
6222 for (i = 0; i < n; i++) {
6223 if ((PyObject *)(su->type) == PyTuple_GET_ITEM(mro, i))
6224 break;
6225 }
6226 i++;
6227 res = NULL;
6228 for (; i < n; i++) {
6229 tmp = PyTuple_GET_ITEM(mro, i);
6230 if (PyType_Check(tmp))
6231 dict = ((PyTypeObject *)tmp)->tp_dict;
6232 else
6233 continue;
6234 res = PyDict_GetItem(dict, name);
6235 if (res != NULL) {
6236 Py_INCREF(res);
6237 f = Py_TYPE(res)->tp_descr_get;
6238 if (f != NULL) {
6239 tmp = f(res,
6240 /* Only pass 'obj' param if
6241 this is instance-mode super
6242 (See SF ID #743627)
6243 */
6244 (su->obj == (PyObject *)
6245 su->obj_type
6246 ? (PyObject *)NULL
6247 : su->obj),
6248 (PyObject *)starttype);
6249 Py_DECREF(res);
6250 res = tmp;
6251 }
6252 return res;
6253 }
6254 }
6255 }
6256 return PyObject_GenericGetAttr(self, name);
Guido van Rossum705f0f52001-08-24 16:47:00 +00006257}
6258
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006259static PyTypeObject *
Guido van Rossum5b443c62001-12-03 15:38:28 +00006260supercheck(PyTypeObject *type, PyObject *obj)
6261{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006262 /* Check that a super() call makes sense. Return a type object.
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006263
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006264 obj can be a new-style class, or an instance of one:
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006265
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006266 - If it is a class, it must be a subclass of 'type'. This case is
6267 used for class methods; the return value is obj.
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006268
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006269 - If it is an instance, it must be an instance of 'type'. This is
6270 the normal case; the return value is obj.__class__.
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006271
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006272 But... when obj is an instance, we want to allow for the case where
6273 Py_TYPE(obj) is not a subclass of type, but obj.__class__ is!
6274 This will allow using super() with a proxy for obj.
6275 */
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006276
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006277 /* Check for first bullet above (special case) */
6278 if (PyType_Check(obj) && PyType_IsSubtype((PyTypeObject *)obj, type)) {
6279 Py_INCREF(obj);
6280 return (PyTypeObject *)obj;
6281 }
Guido van Rossum8e80a722003-02-18 19:22:22 +00006282
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006283 /* Normal case */
6284 if (PyType_IsSubtype(Py_TYPE(obj), type)) {
6285 Py_INCREF(Py_TYPE(obj));
6286 return Py_TYPE(obj);
6287 }
6288 else {
6289 /* Try the slow way */
6290 static PyObject *class_str = NULL;
6291 PyObject *class_attr;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006292
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006293 if (class_str == NULL) {
6294 class_str = PyUnicode_FromString("__class__");
6295 if (class_str == NULL)
6296 return NULL;
6297 }
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006298
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006299 class_attr = PyObject_GetAttr(obj, class_str);
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006300
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006301 if (class_attr != NULL &&
6302 PyType_Check(class_attr) &&
6303 (PyTypeObject *)class_attr != Py_TYPE(obj))
6304 {
6305 int ok = PyType_IsSubtype(
6306 (PyTypeObject *)class_attr, type);
6307 if (ok)
6308 return (PyTypeObject *)class_attr;
6309 }
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006310
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006311 if (class_attr == NULL)
6312 PyErr_Clear();
6313 else
6314 Py_DECREF(class_attr);
6315 }
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006316
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006317 PyErr_SetString(PyExc_TypeError,
6318 "super(type, obj): "
6319 "obj must be an instance or subtype of type");
6320 return NULL;
Guido van Rossum5b443c62001-12-03 15:38:28 +00006321}
6322
Guido van Rossum705f0f52001-08-24 16:47:00 +00006323static PyObject *
6324super_descr_get(PyObject *self, PyObject *obj, PyObject *type)
6325{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006326 superobject *su = (superobject *)self;
6327 superobject *newobj;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006328
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006329 if (obj == NULL || obj == Py_None || su->obj != NULL) {
6330 /* Not binding to an object, or already bound */
6331 Py_INCREF(self);
6332 return self;
6333 }
6334 if (Py_TYPE(su) != &PySuper_Type)
6335 /* If su is an instance of a (strict) subclass of super,
6336 call its type */
6337 return PyObject_CallFunctionObjArgs((PyObject *)Py_TYPE(su),
6338 su->type, obj, NULL);
6339 else {
6340 /* Inline the common case */
6341 PyTypeObject *obj_type = supercheck(su->type, obj);
6342 if (obj_type == NULL)
6343 return NULL;
6344 newobj = (superobject *)PySuper_Type.tp_new(&PySuper_Type,
6345 NULL, NULL);
6346 if (newobj == NULL)
6347 return NULL;
6348 Py_INCREF(su->type);
6349 Py_INCREF(obj);
6350 newobj->type = su->type;
6351 newobj->obj = obj;
6352 newobj->obj_type = obj_type;
6353 return (PyObject *)newobj;
6354 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00006355}
6356
6357static int
6358super_init(PyObject *self, PyObject *args, PyObject *kwds)
6359{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006360 superobject *su = (superobject *)self;
6361 PyTypeObject *type = NULL;
6362 PyObject *obj = NULL;
6363 PyTypeObject *obj_type = NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006364
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006365 if (!_PyArg_NoKeywords("super", kwds))
6366 return -1;
6367 if (!PyArg_ParseTuple(args, "|O!O:super", &PyType_Type, &type, &obj))
6368 return -1;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00006369
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006370 if (type == NULL) {
6371 /* Call super(), without args -- fill in from __class__
6372 and first local variable on the stack. */
6373 PyFrameObject *f = PyThreadState_GET()->frame;
6374 PyCodeObject *co = f->f_code;
Victor Stinner0fcab4a2011-01-04 12:59:15 +00006375 Py_ssize_t i, n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006376 if (co == NULL) {
6377 PyErr_SetString(PyExc_SystemError,
6378 "super(): no code object");
6379 return -1;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00006380 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006381 if (co->co_argcount == 0) {
6382 PyErr_SetString(PyExc_SystemError,
6383 "super(): no arguments");
6384 return -1;
6385 }
6386 obj = f->f_localsplus[0];
6387 if (obj == NULL) {
6388 PyErr_SetString(PyExc_SystemError,
6389 "super(): arg[0] deleted");
6390 return -1;
6391 }
6392 if (co->co_freevars == NULL)
6393 n = 0;
6394 else {
6395 assert(PyTuple_Check(co->co_freevars));
6396 n = PyTuple_GET_SIZE(co->co_freevars);
6397 }
6398 for (i = 0; i < n; i++) {
6399 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
6400 assert(PyUnicode_Check(name));
6401 if (!PyUnicode_CompareWithASCIIString(name,
6402 "__class__")) {
6403 Py_ssize_t index = co->co_nlocals +
6404 PyTuple_GET_SIZE(co->co_cellvars) + i;
6405 PyObject *cell = f->f_localsplus[index];
6406 if (cell == NULL || !PyCell_Check(cell)) {
6407 PyErr_SetString(PyExc_SystemError,
6408 "super(): bad __class__ cell");
6409 return -1;
6410 }
6411 type = (PyTypeObject *) PyCell_GET(cell);
6412 if (type == NULL) {
6413 PyErr_SetString(PyExc_SystemError,
6414 "super(): empty __class__ cell");
6415 return -1;
6416 }
6417 if (!PyType_Check(type)) {
6418 PyErr_Format(PyExc_SystemError,
6419 "super(): __class__ is not a type (%s)",
6420 Py_TYPE(type)->tp_name);
6421 return -1;
6422 }
6423 break;
6424 }
6425 }
6426 if (type == NULL) {
6427 PyErr_SetString(PyExc_SystemError,
6428 "super(): __class__ cell not found");
6429 return -1;
6430 }
6431 }
Guido van Rossumcd16bf62007-06-13 18:07:49 +00006432
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006433 if (obj == Py_None)
6434 obj = NULL;
6435 if (obj != NULL) {
6436 obj_type = supercheck(type, obj);
6437 if (obj_type == NULL)
6438 return -1;
6439 Py_INCREF(obj);
6440 }
6441 Py_INCREF(type);
6442 su->type = type;
6443 su->obj = obj;
6444 su->obj_type = obj_type;
6445 return 0;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006446}
6447
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00006448PyDoc_STRVAR(super_doc,
Guido van Rossumcd16bf62007-06-13 18:07:49 +00006449"super() -> same as super(__class__, <first argument>)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00006450"super(type) -> unbound super object\n"
6451"super(type, obj) -> bound super object; requires isinstance(obj, type)\n"
Guido van Rossume705ef12001-08-29 15:47:06 +00006452"super(type, type2) -> bound super object; requires issubclass(type2, type)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00006453"Typical use to call a cooperative superclass method:\n"
6454"class C(B):\n"
6455" def meth(self, arg):\n"
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006456" super().meth(arg)\n"
Guido van Rossumcd16bf62007-06-13 18:07:49 +00006457"This works for class methods too:\n"
6458"class C(B):\n"
6459" @classmethod\n"
6460" def cmeth(cls, arg):\n"
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006461" super().cmeth(arg)\n");
Guido van Rossum705f0f52001-08-24 16:47:00 +00006462
Guido van Rossum048eb752001-10-02 21:24:57 +00006463static int
6464super_traverse(PyObject *self, visitproc visit, void *arg)
6465{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006466 superobject *su = (superobject *)self;
Guido van Rossum048eb752001-10-02 21:24:57 +00006467
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006468 Py_VISIT(su->obj);
6469 Py_VISIT(su->type);
6470 Py_VISIT(su->obj_type);
Guido van Rossum048eb752001-10-02 21:24:57 +00006471
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006472 return 0;
Guido van Rossum048eb752001-10-02 21:24:57 +00006473}
6474
Guido van Rossum705f0f52001-08-24 16:47:00 +00006475PyTypeObject PySuper_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006476 PyVarObject_HEAD_INIT(&PyType_Type, 0)
6477 "super", /* tp_name */
6478 sizeof(superobject), /* tp_basicsize */
6479 0, /* tp_itemsize */
6480 /* methods */
6481 super_dealloc, /* tp_dealloc */
6482 0, /* tp_print */
6483 0, /* tp_getattr */
6484 0, /* tp_setattr */
6485 0, /* tp_reserved */
6486 super_repr, /* tp_repr */
6487 0, /* tp_as_number */
6488 0, /* tp_as_sequence */
6489 0, /* tp_as_mapping */
6490 0, /* tp_hash */
6491 0, /* tp_call */
6492 0, /* tp_str */
6493 super_getattro, /* tp_getattro */
6494 0, /* tp_setattro */
6495 0, /* tp_as_buffer */
6496 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
6497 Py_TPFLAGS_BASETYPE, /* tp_flags */
6498 super_doc, /* tp_doc */
6499 super_traverse, /* tp_traverse */
6500 0, /* tp_clear */
6501 0, /* tp_richcompare */
6502 0, /* tp_weaklistoffset */
6503 0, /* tp_iter */
6504 0, /* tp_iternext */
6505 0, /* tp_methods */
6506 super_members, /* tp_members */
6507 0, /* tp_getset */
6508 0, /* tp_base */
6509 0, /* tp_dict */
6510 super_descr_get, /* tp_descr_get */
6511 0, /* tp_descr_set */
6512 0, /* tp_dictoffset */
6513 super_init, /* tp_init */
6514 PyType_GenericAlloc, /* tp_alloc */
6515 PyType_GenericNew, /* tp_new */
6516 PyObject_GC_Del, /* tp_free */
Guido van Rossum705f0f52001-08-24 16:47:00 +00006517};