blob: a5863dd0a4f9432a58015646620c549fd4a73405 [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) {
329 PyErr_Format(PyExc_AttributeError, "__abstractmethods__");
330 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 */
343 int res = PyDict_SetItemString(type->tp_dict,
344 "__abstractmethods__", value);
345 if (res == 0) {
346 PyType_Modified(type);
347 if (value && PyObject_IsTrue(value)) {
348 type->tp_flags |= Py_TPFLAGS_IS_ABSTRACT;
349 }
350 else {
351 type->tp_flags &= ~Py_TPFLAGS_IS_ABSTRACT;
352 }
353 }
354 return res;
Christian Heimes9e7f1d22008-02-28 12:27:11 +0000355}
356
357static PyObject *
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000358type_get_bases(PyTypeObject *type, void *context)
359{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000360 Py_INCREF(type->tp_bases);
361 return type->tp_bases;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000362}
363
364static PyTypeObject *best_base(PyObject *);
365static int mro_internal(PyTypeObject *);
366static int compatible_for_assignment(PyTypeObject *, PyTypeObject *, char *);
367static int add_subclass(PyTypeObject*, PyTypeObject*);
368static void remove_subclass(PyTypeObject *, PyTypeObject *);
369static void update_all_slots(PyTypeObject *);
370
Guido van Rossum8d24ee92003-03-24 23:49:49 +0000371typedef int (*update_callback)(PyTypeObject *, void *);
372static int update_subclasses(PyTypeObject *type, PyObject *name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000373 update_callback callback, void *data);
Guido van Rossum8d24ee92003-03-24 23:49:49 +0000374static int recurse_down_subclasses(PyTypeObject *type, PyObject *name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000375 update_callback callback, void *data);
Guido van Rossum8d24ee92003-03-24 23:49:49 +0000376
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000377static int
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000378mro_subclasses(PyTypeObject *type, PyObject* temp)
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000379{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000380 PyTypeObject *subclass;
381 PyObject *ref, *subclasses, *old_mro;
382 Py_ssize_t i, n;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000383
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000384 subclasses = type->tp_subclasses;
385 if (subclasses == NULL)
386 return 0;
387 assert(PyList_Check(subclasses));
388 n = PyList_GET_SIZE(subclasses);
389 for (i = 0; i < n; i++) {
390 ref = PyList_GET_ITEM(subclasses, i);
391 assert(PyWeakref_CheckRef(ref));
392 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
393 assert(subclass != NULL);
394 if ((PyObject *)subclass == Py_None)
395 continue;
396 assert(PyType_Check(subclass));
397 old_mro = subclass->tp_mro;
398 if (mro_internal(subclass) < 0) {
399 subclass->tp_mro = old_mro;
400 return -1;
401 }
402 else {
403 PyObject* tuple;
404 tuple = PyTuple_Pack(2, subclass, old_mro);
405 Py_DECREF(old_mro);
406 if (!tuple)
407 return -1;
408 if (PyList_Append(temp, tuple) < 0)
409 return -1;
410 Py_DECREF(tuple);
411 }
412 if (mro_subclasses(subclass, temp) < 0)
413 return -1;
414 }
415 return 0;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000416}
417
418static int
419type_set_bases(PyTypeObject *type, PyObject *value, void *context)
420{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000421 Py_ssize_t i;
422 int r = 0;
423 PyObject *ob, *temp;
424 PyTypeObject *new_base, *old_base;
425 PyObject *old_bases, *old_mro;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000426
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000427 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
428 PyErr_Format(PyExc_TypeError,
429 "can't set %s.__bases__", type->tp_name);
430 return -1;
431 }
432 if (!value) {
433 PyErr_Format(PyExc_TypeError,
434 "can't delete %s.__bases__", type->tp_name);
435 return -1;
436 }
437 if (!PyTuple_Check(value)) {
438 PyErr_Format(PyExc_TypeError,
439 "can only assign tuple to %s.__bases__, not %s",
440 type->tp_name, Py_TYPE(value)->tp_name);
441 return -1;
442 }
443 if (PyTuple_GET_SIZE(value) == 0) {
444 PyErr_Format(PyExc_TypeError,
445 "can only assign non-empty tuple to %s.__bases__, not ()",
446 type->tp_name);
447 return -1;
448 }
449 for (i = 0; i < PyTuple_GET_SIZE(value); i++) {
450 ob = PyTuple_GET_ITEM(value, i);
451 if (!PyType_Check(ob)) {
452 PyErr_Format(
453 PyExc_TypeError,
454 "%s.__bases__ must be tuple of old- or new-style classes, not '%s'",
455 type->tp_name, Py_TYPE(ob)->tp_name);
456 return -1;
457 }
458 if (PyType_Check(ob)) {
459 if (PyType_IsSubtype((PyTypeObject*)ob, type)) {
460 PyErr_SetString(PyExc_TypeError,
461 "a __bases__ item causes an inheritance cycle");
462 return -1;
463 }
464 }
465 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000466
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000467 new_base = best_base(value);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000468
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000469 if (!new_base) {
470 return -1;
471 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000472
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000473 if (!compatible_for_assignment(type->tp_base, new_base, "__bases__"))
474 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000475
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000476 Py_INCREF(new_base);
477 Py_INCREF(value);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000478
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000479 old_bases = type->tp_bases;
480 old_base = type->tp_base;
481 old_mro = type->tp_mro;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000482
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000483 type->tp_bases = value;
484 type->tp_base = new_base;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000485
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000486 if (mro_internal(type) < 0) {
487 goto bail;
488 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000489
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000490 temp = PyList_New(0);
491 if (!temp)
492 goto bail;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000493
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000494 r = mro_subclasses(type, temp);
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000495
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000496 if (r < 0) {
497 for (i = 0; i < PyList_Size(temp); i++) {
498 PyTypeObject* cls;
499 PyObject* mro;
500 PyArg_UnpackTuple(PyList_GET_ITEM(temp, i),
501 "", 2, 2, &cls, &mro);
502 Py_INCREF(mro);
503 ob = cls->tp_mro;
504 cls->tp_mro = mro;
505 Py_DECREF(ob);
506 }
507 Py_DECREF(temp);
508 goto bail;
509 }
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000510
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000511 Py_DECREF(temp);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000512
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000513 /* any base that was in __bases__ but now isn't, we
514 need to remove |type| from its tp_subclasses.
515 conversely, any class now in __bases__ that wasn't
516 needs to have |type| added to its subclasses. */
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000517
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000518 /* for now, sod that: just remove from all old_bases,
519 add to all new_bases */
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000520
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000521 for (i = PyTuple_GET_SIZE(old_bases) - 1; i >= 0; i--) {
522 ob = PyTuple_GET_ITEM(old_bases, i);
523 if (PyType_Check(ob)) {
524 remove_subclass(
525 (PyTypeObject*)ob, type);
526 }
527 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000528
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000529 for (i = PyTuple_GET_SIZE(value) - 1; i >= 0; i--) {
530 ob = PyTuple_GET_ITEM(value, i);
531 if (PyType_Check(ob)) {
532 if (add_subclass((PyTypeObject*)ob, type) < 0)
533 r = -1;
534 }
535 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000536
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000537 update_all_slots(type);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000538
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000539 Py_DECREF(old_bases);
540 Py_DECREF(old_base);
541 Py_DECREF(old_mro);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000542
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000543 return r;
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000544
545 bail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000546 Py_DECREF(type->tp_bases);
547 Py_DECREF(type->tp_base);
548 if (type->tp_mro != old_mro) {
549 Py_DECREF(type->tp_mro);
550 }
Michael W. Hudsone723e452003-08-07 14:58:10 +0000551
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000552 type->tp_bases = old_bases;
553 type->tp_base = old_base;
554 type->tp_mro = old_mro;
Tim Petersea7f75d2002-12-07 21:39:16 +0000555
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000556 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000557}
558
559static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000560type_dict(PyTypeObject *type, void *context)
561{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000562 if (type->tp_dict == NULL) {
563 Py_INCREF(Py_None);
564 return Py_None;
565 }
566 return PyDictProxy_New(type->tp_dict);
Guido van Rossum29ca26e1995-01-07 11:58:15 +0000567}
568
Tim Peters24008312002-03-17 18:56:20 +0000569static PyObject *
570type_get_doc(PyTypeObject *type, void *context)
571{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000572 PyObject *result;
573 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE) && type->tp_doc != NULL)
574 return PyUnicode_FromString(type->tp_doc);
575 result = PyDict_GetItemString(type->tp_dict, "__doc__");
576 if (result == NULL) {
577 result = Py_None;
578 Py_INCREF(result);
579 }
580 else if (Py_TYPE(result)->tp_descr_get) {
581 result = Py_TYPE(result)->tp_descr_get(result, NULL,
582 (PyObject *)type);
583 }
584 else {
585 Py_INCREF(result);
586 }
587 return result;
Tim Peters24008312002-03-17 18:56:20 +0000588}
589
Antoine Pitrouec569b72008-08-26 22:40:48 +0000590static PyObject *
591type___instancecheck__(PyObject *type, PyObject *inst)
592{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000593 switch (_PyObject_RealIsInstance(inst, type)) {
594 case -1:
595 return NULL;
596 case 0:
597 Py_RETURN_FALSE;
598 default:
599 Py_RETURN_TRUE;
600 }
Antoine Pitrouec569b72008-08-26 22:40:48 +0000601}
602
603
604static PyObject *
Antoine Pitrouec569b72008-08-26 22:40:48 +0000605type___subclasscheck__(PyObject *type, PyObject *inst)
606{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000607 switch (_PyObject_RealIsSubclass(inst, type)) {
608 case -1:
609 return NULL;
610 case 0:
611 Py_RETURN_FALSE;
612 default:
613 Py_RETURN_TRUE;
614 }
Antoine Pitrouec569b72008-08-26 22:40:48 +0000615}
616
Antoine Pitrouec569b72008-08-26 22:40:48 +0000617
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000618static PyGetSetDef type_getsets[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000619 {"__name__", (getter)type_name, (setter)type_set_name, NULL},
620 {"__bases__", (getter)type_get_bases, (setter)type_set_bases, NULL},
621 {"__module__", (getter)type_module, (setter)type_set_module, NULL},
622 {"__abstractmethods__", (getter)type_abstractmethods,
623 (setter)type_set_abstractmethods, NULL},
624 {"__dict__", (getter)type_dict, NULL, NULL},
625 {"__doc__", (getter)type_get_doc, NULL, NULL},
626 {0}
Tim Peters6d6c1a32001-08-02 04:15:00 +0000627};
628
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000629static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000630type_repr(PyTypeObject *type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000631{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000632 PyObject *mod, *name, *rtn;
Guido van Rossumc3542212001-08-16 09:18:56 +0000633
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000634 mod = type_module(type, NULL);
635 if (mod == NULL)
636 PyErr_Clear();
637 else if (!PyUnicode_Check(mod)) {
638 Py_DECREF(mod);
639 mod = NULL;
640 }
641 name = type_name(type, NULL);
642 if (name == NULL)
643 return NULL;
Barry Warsaw7ce36942001-08-24 18:34:26 +0000644
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000645 if (mod != NULL && PyUnicode_CompareWithASCIIString(mod, "builtins"))
646 rtn = PyUnicode_FromFormat("<class '%U.%U'>", mod, name);
647 else
648 rtn = PyUnicode_FromFormat("<class '%s'>", type->tp_name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000649
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000650 Py_XDECREF(mod);
651 Py_DECREF(name);
652 return rtn;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000653}
654
Tim Peters6d6c1a32001-08-02 04:15:00 +0000655static PyObject *
656type_call(PyTypeObject *type, PyObject *args, PyObject *kwds)
657{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000658 PyObject *obj;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000659
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000660 if (type->tp_new == NULL) {
661 PyErr_Format(PyExc_TypeError,
662 "cannot create '%.100s' instances",
663 type->tp_name);
664 return NULL;
665 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000666
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000667 obj = type->tp_new(type, args, kwds);
668 if (obj != NULL) {
669 /* Ugly exception: when the call was type(something),
670 don't call tp_init on the result. */
671 if (type == &PyType_Type &&
672 PyTuple_Check(args) && PyTuple_GET_SIZE(args) == 1 &&
673 (kwds == NULL ||
674 (PyDict_Check(kwds) && PyDict_Size(kwds) == 0)))
675 return obj;
676 /* If the returned object is not an instance of type,
677 it won't be initialized. */
678 if (!PyType_IsSubtype(Py_TYPE(obj), type))
679 return obj;
680 type = Py_TYPE(obj);
681 if (type->tp_init != NULL &&
682 type->tp_init(obj, args, kwds) < 0) {
683 Py_DECREF(obj);
684 obj = NULL;
685 }
686 }
687 return obj;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000688}
689
690PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000691PyType_GenericAlloc(PyTypeObject *type, Py_ssize_t nitems)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000692{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000693 PyObject *obj;
694 const size_t size = _PyObject_VAR_SIZE(type, nitems+1);
695 /* note that we need to add one, for the sentinel */
Tim Peters406fe3b2001-10-06 19:04:01 +0000696
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000697 if (PyType_IS_GC(type))
698 obj = _PyObject_GC_Malloc(size);
699 else
700 obj = (PyObject *)PyObject_MALLOC(size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000701
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000702 if (obj == NULL)
703 return PyErr_NoMemory();
Tim Peters406fe3b2001-10-06 19:04:01 +0000704
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000705 memset(obj, '\0', size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000706
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000707 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
708 Py_INCREF(type);
Tim Peters406fe3b2001-10-06 19:04:01 +0000709
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000710 if (type->tp_itemsize == 0)
711 PyObject_INIT(obj, type);
712 else
713 (void) PyObject_INIT_VAR((PyVarObject *)obj, type, nitems);
Tim Peters406fe3b2001-10-06 19:04:01 +0000714
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000715 if (PyType_IS_GC(type))
716 _PyObject_GC_TRACK(obj);
717 return obj;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000718}
719
720PyObject *
721PyType_GenericNew(PyTypeObject *type, PyObject *args, PyObject *kwds)
722{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000723 return type->tp_alloc(type, 0);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000724}
725
Guido van Rossum9475a232001-10-05 20:51:39 +0000726/* Helpers for subtyping */
727
728static int
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000729traverse_slots(PyTypeObject *type, PyObject *self, visitproc visit, void *arg)
730{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000731 Py_ssize_t i, n;
732 PyMemberDef *mp;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000733
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000734 n = Py_SIZE(type);
735 mp = PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type);
736 for (i = 0; i < n; i++, mp++) {
737 if (mp->type == T_OBJECT_EX) {
738 char *addr = (char *)self + mp->offset;
739 PyObject *obj = *(PyObject **)addr;
740 if (obj != NULL) {
741 int err = visit(obj, arg);
742 if (err)
743 return err;
744 }
745 }
746 }
747 return 0;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000748}
749
750static int
Guido van Rossum9475a232001-10-05 20:51:39 +0000751subtype_traverse(PyObject *self, visitproc visit, void *arg)
752{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000753 PyTypeObject *type, *base;
754 traverseproc basetraverse;
Guido van Rossum9475a232001-10-05 20:51:39 +0000755
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000756 /* Find the nearest base with a different tp_traverse,
757 and traverse slots while we're at it */
758 type = Py_TYPE(self);
759 base = type;
760 while ((basetraverse = base->tp_traverse) == subtype_traverse) {
761 if (Py_SIZE(base)) {
762 int err = traverse_slots(base, self, visit, arg);
763 if (err)
764 return err;
765 }
766 base = base->tp_base;
767 assert(base);
768 }
Guido van Rossum9475a232001-10-05 20:51:39 +0000769
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000770 if (type->tp_dictoffset != base->tp_dictoffset) {
771 PyObject **dictptr = _PyObject_GetDictPtr(self);
772 if (dictptr && *dictptr)
773 Py_VISIT(*dictptr);
774 }
Guido van Rossum9475a232001-10-05 20:51:39 +0000775
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000776 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
777 /* For a heaptype, the instances count as references
778 to the type. Traverse the type so the collector
779 can find cycles involving this link. */
780 Py_VISIT(type);
Guido van Rossuma3862092002-06-10 15:24:42 +0000781
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000782 if (basetraverse)
783 return basetraverse(self, visit, arg);
784 return 0;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000785}
786
787static void
788clear_slots(PyTypeObject *type, PyObject *self)
789{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000790 Py_ssize_t i, n;
791 PyMemberDef *mp;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000792
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000793 n = Py_SIZE(type);
794 mp = PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type);
795 for (i = 0; i < n; i++, mp++) {
796 if (mp->type == T_OBJECT_EX && !(mp->flags & READONLY)) {
797 char *addr = (char *)self + mp->offset;
798 PyObject *obj = *(PyObject **)addr;
799 if (obj != NULL) {
800 *(PyObject **)addr = NULL;
801 Py_DECREF(obj);
802 }
803 }
804 }
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000805}
806
807static int
808subtype_clear(PyObject *self)
809{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000810 PyTypeObject *type, *base;
811 inquiry baseclear;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000812
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000813 /* Find the nearest base with a different tp_clear
814 and clear slots while we're at it */
815 type = Py_TYPE(self);
816 base = type;
817 while ((baseclear = base->tp_clear) == subtype_clear) {
818 if (Py_SIZE(base))
819 clear_slots(base, self);
820 base = base->tp_base;
821 assert(base);
822 }
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000823
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000824 /* There's no need to clear the instance dict (if any);
825 the collector will call its tp_clear handler. */
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000826
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000827 if (baseclear)
828 return baseclear(self);
829 return 0;
Guido van Rossum9475a232001-10-05 20:51:39 +0000830}
Tim Peters6d6c1a32001-08-02 04:15:00 +0000831
832static void
833subtype_dealloc(PyObject *self)
834{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000835 PyTypeObject *type, *base;
836 destructor basedealloc;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000837
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000838 /* Extract the type; we expect it to be a heap type */
839 type = Py_TYPE(self);
840 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000841
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000842 /* Test whether the type has GC exactly once */
Guido van Rossum22b13872002-08-06 21:41:44 +0000843
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000844 if (!PyType_IS_GC(type)) {
845 /* It's really rare to find a dynamic type that doesn't have
846 GC; it can only happen when deriving from 'object' and not
847 adding any slots or instance variables. This allows
848 certain simplifications: there's no need to call
849 clear_slots(), or DECREF the dict, or clear weakrefs. */
Guido van Rossum22b13872002-08-06 21:41:44 +0000850
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000851 /* Maybe call finalizer; exit early if resurrected */
852 if (type->tp_del) {
853 type->tp_del(self);
854 if (self->ob_refcnt > 0)
855 return;
856 }
Guido van Rossum22b13872002-08-06 21:41:44 +0000857
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000858 /* Find the nearest base with a different tp_dealloc */
859 base = type;
860 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
861 assert(Py_SIZE(base) == 0);
862 base = base->tp_base;
863 assert(base);
864 }
Guido van Rossum22b13872002-08-06 21:41:44 +0000865
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000866 /* Extract the type again; tp_del may have changed it */
867 type = Py_TYPE(self);
Benjamin Peterson193152c2009-04-25 01:08:45 +0000868
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000869 /* Call the base tp_dealloc() */
870 assert(basedealloc);
871 basedealloc(self);
Guido van Rossum22b13872002-08-06 21:41:44 +0000872
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000873 /* Can't reference self beyond this point */
874 Py_DECREF(type);
Guido van Rossum22b13872002-08-06 21:41:44 +0000875
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000876 /* Done */
877 return;
878 }
Guido van Rossum22b13872002-08-06 21:41:44 +0000879
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000880 /* We get here only if the type has GC */
Guido van Rossum22b13872002-08-06 21:41:44 +0000881
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000882 /* UnTrack and re-Track around the trashcan macro, alas */
883 /* See explanation at end of function for full disclosure */
884 PyObject_GC_UnTrack(self);
885 ++_PyTrash_delete_nesting;
886 Py_TRASHCAN_SAFE_BEGIN(self);
887 --_PyTrash_delete_nesting;
888 /* DO NOT restore GC tracking at this point. weakref callbacks
889 * (if any, and whether directly here or indirectly in something we
890 * call) may trigger GC, and if self is tracked at that point, it
891 * will look like trash to GC and GC will try to delete self again.
892 */
Guido van Rossum22b13872002-08-06 21:41:44 +0000893
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000894 /* Find the nearest base with a different tp_dealloc */
895 base = type;
896 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
897 base = base->tp_base;
898 assert(base);
899 }
Guido van Rossum14227b42001-12-06 02:35:58 +0000900
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000901 /* If we added a weaklist, we clear it. Do this *before* calling
902 the finalizer (__del__), clearing slots, or clearing the instance
903 dict. */
Guido van Rossum59195fd2003-06-13 20:54:40 +0000904
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000905 if (type->tp_weaklistoffset && !base->tp_weaklistoffset)
906 PyObject_ClearWeakRefs(self);
Guido van Rossum1987c662003-05-29 14:29:23 +0000907
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000908 /* Maybe call finalizer; exit early if resurrected */
909 if (type->tp_del) {
910 _PyObject_GC_TRACK(self);
911 type->tp_del(self);
912 if (self->ob_refcnt > 0)
913 goto endlabel; /* resurrected */
914 else
915 _PyObject_GC_UNTRACK(self);
916 /* New weakrefs could be created during the finalizer call.
917 If this occurs, clear them out without calling their
918 finalizers since they might rely on part of the object
919 being finalized that has already been destroyed. */
920 if (type->tp_weaklistoffset && !base->tp_weaklistoffset) {
921 /* Modeled after GET_WEAKREFS_LISTPTR() */
922 PyWeakReference **list = (PyWeakReference **) \
923 PyObject_GET_WEAKREFS_LISTPTR(self);
924 while (*list)
925 _PyWeakref_ClearRef(*list);
926 }
927 }
Guido van Rossum1987c662003-05-29 14:29:23 +0000928
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000929 /* Clear slots up to the nearest base with a different tp_dealloc */
930 base = type;
931 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
932 if (Py_SIZE(base))
933 clear_slots(base, self);
934 base = base->tp_base;
935 assert(base);
936 }
Guido van Rossum59195fd2003-06-13 20:54:40 +0000937
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000938 /* If we added a dict, DECREF it */
939 if (type->tp_dictoffset && !base->tp_dictoffset) {
940 PyObject **dictptr = _PyObject_GetDictPtr(self);
941 if (dictptr != NULL) {
942 PyObject *dict = *dictptr;
943 if (dict != NULL) {
944 Py_DECREF(dict);
945 *dictptr = NULL;
946 }
947 }
948 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000949
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000950 /* Extract the type again; tp_del may have changed it */
951 type = Py_TYPE(self);
Benjamin Peterson193152c2009-04-25 01:08:45 +0000952
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000953 /* Call the base tp_dealloc(); first retrack self if
954 * basedealloc knows about gc.
955 */
956 if (PyType_IS_GC(base))
957 _PyObject_GC_TRACK(self);
958 assert(basedealloc);
959 basedealloc(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000960
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000961 /* Can't reference self beyond this point */
962 Py_DECREF(type);
Guido van Rossum22b13872002-08-06 21:41:44 +0000963
Guido van Rossum0906e072002-08-07 20:42:09 +0000964 endlabel:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000965 ++_PyTrash_delete_nesting;
966 Py_TRASHCAN_SAFE_END(self);
967 --_PyTrash_delete_nesting;
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000968
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000969 /* Explanation of the weirdness around the trashcan macros:
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000970
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000971 Q. What do the trashcan macros do?
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000972
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000973 A. Read the comment titled "Trashcan mechanism" in object.h.
974 For one, this explains why there must be a call to GC-untrack
975 before the trashcan begin macro. Without understanding the
976 trashcan code, the answers to the following questions don't make
977 sense.
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000978
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000979 Q. Why do we GC-untrack before the trashcan and then immediately
980 GC-track again afterward?
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000981
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000982 A. In the case that the base class is GC-aware, the base class
983 probably GC-untracks the object. If it does that using the
984 UNTRACK macro, this will crash when the object is already
985 untracked. Because we don't know what the base class does, the
986 only safe thing is to make sure the object is tracked when we
987 call the base class dealloc. But... The trashcan begin macro
988 requires that the object is *untracked* before it is called. So
989 the dance becomes:
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000990
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000991 GC untrack
992 trashcan begin
993 GC track
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000994
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000995 Q. Why did the last question say "immediately GC-track again"?
996 It's nowhere near immediately.
Tim Petersf7f9e992003-11-13 21:59:32 +0000997
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000998 A. Because the code *used* to re-track immediately. Bad Idea.
999 self has a refcount of 0, and if gc ever gets its hands on it
1000 (which can happen if any weakref callback gets invoked), it
1001 looks like trash to gc too, and gc also tries to delete self
1002 then. But we're already deleting self. Double dealloction is
1003 a subtle disaster.
Tim Petersf7f9e992003-11-13 21:59:32 +00001004
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001005 Q. Why the bizarre (net-zero) manipulation of
1006 _PyTrash_delete_nesting around the trashcan macros?
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001007
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001008 A. Some base classes (e.g. list) also use the trashcan mechanism.
1009 The following scenario used to be possible:
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001010
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001011 - suppose the trashcan level is one below the trashcan limit
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001012
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001013 - subtype_dealloc() is called
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001014
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001015 - the trashcan limit is not yet reached, so the trashcan level
1016 is incremented and the code between trashcan begin and end is
1017 executed
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001018
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001019 - this destroys much of the object's contents, including its
1020 slots and __dict__
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001021
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001022 - basedealloc() is called; this is really list_dealloc(), or
1023 some other type which also uses the trashcan macros
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001024
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001025 - the trashcan limit is now reached, so the object is put on the
1026 trashcan's to-be-deleted-later list
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001027
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001028 - basedealloc() returns
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001029
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001030 - subtype_dealloc() decrefs the object's type
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001031
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001032 - subtype_dealloc() returns
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001033
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001034 - later, the trashcan code starts deleting the objects from its
1035 to-be-deleted-later list
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001036
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001037 - subtype_dealloc() is called *AGAIN* for the same object
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001038
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001039 - at the very least (if the destroyed slots and __dict__ don't
1040 cause problems) the object's type gets decref'ed a second
1041 time, which is *BAD*!!!
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001042
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001043 The remedy is to make sure that if the code between trashcan
1044 begin and end in subtype_dealloc() is called, the code between
1045 trashcan begin and end in basedealloc() will also be called.
1046 This is done by decrementing the level after passing into the
1047 trashcan block, and incrementing it just before leaving the
1048 block.
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001049
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001050 But now it's possible that a chain of objects consisting solely
1051 of objects whose deallocator is subtype_dealloc() will defeat
1052 the trashcan mechanism completely: the decremented level means
1053 that the effective level never reaches the limit. Therefore, we
1054 *increment* the level *before* entering the trashcan block, and
1055 matchingly decrement it after leaving. This means the trashcan
1056 code will trigger a little early, but that's no big deal.
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001057
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001058 Q. Are there any live examples of code in need of all this
1059 complexity?
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001060
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001061 A. Yes. See SF bug 668433 for code that crashed (when Python was
1062 compiled in debug mode) before the trashcan level manipulations
1063 were added. For more discussion, see SF patches 581742, 575073
1064 and bug 574207.
1065 */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001066}
1067
Jeremy Hylton938ace62002-07-17 16:30:39 +00001068static PyTypeObject *solid_base(PyTypeObject *type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001069
Tim Peters6d6c1a32001-08-02 04:15:00 +00001070/* type test with subclassing support */
1071
1072int
1073PyType_IsSubtype(PyTypeObject *a, PyTypeObject *b)
1074{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001075 PyObject *mro;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001076
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001077 mro = a->tp_mro;
1078 if (mro != NULL) {
1079 /* Deal with multiple inheritance without recursion
1080 by walking the MRO tuple */
1081 Py_ssize_t i, n;
1082 assert(PyTuple_Check(mro));
1083 n = PyTuple_GET_SIZE(mro);
1084 for (i = 0; i < n; i++) {
1085 if (PyTuple_GET_ITEM(mro, i) == (PyObject *)b)
1086 return 1;
1087 }
1088 return 0;
1089 }
1090 else {
1091 /* a is not completely initilized yet; follow tp_base */
1092 do {
1093 if (a == b)
1094 return 1;
1095 a = a->tp_base;
1096 } while (a != NULL);
1097 return b == &PyBaseObject_Type;
1098 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001099}
1100
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001101/* Internal routines to do a method lookup in the type
Guido van Rossum60718732001-08-28 17:47:51 +00001102 without looking in the instance dictionary
1103 (so we can't use PyObject_GetAttr) but still binding
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001104 it to the instance. The arguments are the object,
Guido van Rossum60718732001-08-28 17:47:51 +00001105 the method name as a C string, and the address of a
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001106 static variable used to cache the interned Python string.
1107
1108 Two variants:
1109
1110 - lookup_maybe() returns NULL without raising an exception
1111 when the _PyType_Lookup() call fails;
1112
1113 - lookup_method() always raises an exception upon errors.
Benjamin Peterson224205f2009-05-08 03:25:19 +00001114
1115 - _PyObject_LookupSpecial() exported for the benefit of other places.
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001116*/
Guido van Rossum60718732001-08-28 17:47:51 +00001117
1118static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001119lookup_maybe(PyObject *self, char *attrstr, PyObject **attrobj)
Guido van Rossum60718732001-08-28 17:47:51 +00001120{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001121 PyObject *res;
Guido van Rossum60718732001-08-28 17:47:51 +00001122
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001123 if (*attrobj == NULL) {
1124 *attrobj = PyUnicode_InternFromString(attrstr);
1125 if (*attrobj == NULL)
1126 return NULL;
1127 }
1128 res = _PyType_Lookup(Py_TYPE(self), *attrobj);
1129 if (res != NULL) {
1130 descrgetfunc f;
1131 if ((f = Py_TYPE(res)->tp_descr_get) == NULL)
1132 Py_INCREF(res);
1133 else
1134 res = f(res, self, (PyObject *)(Py_TYPE(self)));
1135 }
1136 return res;
Guido van Rossum60718732001-08-28 17:47:51 +00001137}
1138
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001139static PyObject *
1140lookup_method(PyObject *self, char *attrstr, PyObject **attrobj)
1141{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001142 PyObject *res = lookup_maybe(self, attrstr, attrobj);
1143 if (res == NULL && !PyErr_Occurred())
1144 PyErr_SetObject(PyExc_AttributeError, *attrobj);
1145 return res;
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001146}
1147
Benjamin Peterson224205f2009-05-08 03:25:19 +00001148PyObject *
1149_PyObject_LookupSpecial(PyObject *self, char *attrstr, PyObject **attrobj)
1150{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001151 return lookup_maybe(self, attrstr, attrobj);
Benjamin Peterson224205f2009-05-08 03:25:19 +00001152}
1153
Guido van Rossum2730b132001-08-28 18:22:14 +00001154/* A variation of PyObject_CallMethod that uses lookup_method()
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001155 instead of PyObject_GetAttrString(). This uses the same convention
Guido van Rossum2730b132001-08-28 18:22:14 +00001156 as lookup_method to cache the interned name string object. */
1157
Neil Schemenauerf23473f2001-10-21 22:28:58 +00001158static PyObject *
Guido van Rossum2730b132001-08-28 18:22:14 +00001159call_method(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
1160{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001161 va_list va;
1162 PyObject *args, *func = 0, *retval;
1163 va_start(va, format);
Guido van Rossum2730b132001-08-28 18:22:14 +00001164
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001165 func = lookup_maybe(o, name, nameobj);
1166 if (func == NULL) {
1167 va_end(va);
1168 if (!PyErr_Occurred())
1169 PyErr_SetObject(PyExc_AttributeError, *nameobj);
1170 return NULL;
1171 }
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001172
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001173 if (format && *format)
1174 args = Py_VaBuildValue(format, va);
1175 else
1176 args = PyTuple_New(0);
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001177
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001178 va_end(va);
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001179
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001180 if (args == NULL)
1181 return NULL;
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001182
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001183 assert(PyTuple_Check(args));
1184 retval = PyObject_Call(func, args, NULL);
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001185
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001186 Py_DECREF(args);
1187 Py_DECREF(func);
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001188
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001189 return retval;
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001190}
1191
1192/* Clone of call_method() that returns NotImplemented when the lookup fails. */
1193
Neil Schemenauerf23473f2001-10-21 22:28:58 +00001194static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001195call_maybe(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
1196{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001197 va_list va;
1198 PyObject *args, *func = 0, *retval;
1199 va_start(va, format);
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001200
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001201 func = lookup_maybe(o, name, nameobj);
1202 if (func == NULL) {
1203 va_end(va);
1204 if (!PyErr_Occurred()) {
1205 Py_INCREF(Py_NotImplemented);
1206 return Py_NotImplemented;
1207 }
1208 return NULL;
1209 }
Guido van Rossum2730b132001-08-28 18:22:14 +00001210
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001211 if (format && *format)
1212 args = Py_VaBuildValue(format, va);
1213 else
1214 args = PyTuple_New(0);
Guido van Rossum2730b132001-08-28 18:22:14 +00001215
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001216 va_end(va);
Guido van Rossum2730b132001-08-28 18:22:14 +00001217
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001218 if (args == NULL)
1219 return NULL;
Guido van Rossum2730b132001-08-28 18:22:14 +00001220
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001221 assert(PyTuple_Check(args));
1222 retval = PyObject_Call(func, args, NULL);
Guido van Rossum2730b132001-08-28 18:22:14 +00001223
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001224 Py_DECREF(args);
1225 Py_DECREF(func);
Guido van Rossum2730b132001-08-28 18:22:14 +00001226
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001227 return retval;
Guido van Rossum2730b132001-08-28 18:22:14 +00001228}
1229
Tim Petersea7f75d2002-12-07 21:39:16 +00001230/*
Guido van Rossum1f121312002-11-14 19:49:16 +00001231 Method resolution order algorithm C3 described in
1232 "A Monotonic Superclass Linearization for Dylan",
1233 by Kim Barrett, Bob Cassel, Paul Haahr,
Tim Petersea7f75d2002-12-07 21:39:16 +00001234 David A. Moon, Keith Playford, and P. Tucker Withington.
Guido van Rossum1f121312002-11-14 19:49:16 +00001235 (OOPSLA 1996)
1236
Guido van Rossum98f33732002-11-25 21:36:54 +00001237 Some notes about the rules implied by C3:
1238
Tim Petersea7f75d2002-12-07 21:39:16 +00001239 No duplicate bases.
Guido van Rossum98f33732002-11-25 21:36:54 +00001240 It isn't legal to repeat a class in a list of base classes.
1241
1242 The next three properties are the 3 constraints in "C3".
1243
Tim Petersea7f75d2002-12-07 21:39:16 +00001244 Local precendece order.
Guido van Rossum98f33732002-11-25 21:36:54 +00001245 If A precedes B in C's MRO, then A will precede B in the MRO of all
1246 subclasses of C.
1247
1248 Monotonicity.
1249 The MRO of a class must be an extension without reordering of the
1250 MRO of each of its superclasses.
1251
1252 Extended Precedence Graph (EPG).
1253 Linearization is consistent if there is a path in the EPG from
1254 each class to all its successors in the linearization. See
1255 the paper for definition of EPG.
Guido van Rossum1f121312002-11-14 19:49:16 +00001256 */
1257
Tim Petersea7f75d2002-12-07 21:39:16 +00001258static int
Guido van Rossum1f121312002-11-14 19:49:16 +00001259tail_contains(PyObject *list, int whence, PyObject *o) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001260 Py_ssize_t j, size;
1261 size = PyList_GET_SIZE(list);
Guido van Rossum1f121312002-11-14 19:49:16 +00001262
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001263 for (j = whence+1; j < size; j++) {
1264 if (PyList_GET_ITEM(list, j) == o)
1265 return 1;
1266 }
1267 return 0;
Guido van Rossum1f121312002-11-14 19:49:16 +00001268}
1269
Guido van Rossum98f33732002-11-25 21:36:54 +00001270static PyObject *
1271class_name(PyObject *cls)
1272{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001273 PyObject *name = PyObject_GetAttrString(cls, "__name__");
1274 if (name == NULL) {
1275 PyErr_Clear();
1276 Py_XDECREF(name);
1277 name = PyObject_Repr(cls);
1278 }
1279 if (name == NULL)
1280 return NULL;
1281 if (!PyUnicode_Check(name)) {
1282 Py_DECREF(name);
1283 return NULL;
1284 }
1285 return name;
Guido van Rossum98f33732002-11-25 21:36:54 +00001286}
1287
1288static int
1289check_duplicates(PyObject *list)
1290{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001291 Py_ssize_t i, j, n;
1292 /* Let's use a quadratic time algorithm,
1293 assuming that the bases lists is short.
1294 */
1295 n = PyList_GET_SIZE(list);
1296 for (i = 0; i < n; i++) {
1297 PyObject *o = PyList_GET_ITEM(list, i);
1298 for (j = i + 1; j < n; j++) {
1299 if (PyList_GET_ITEM(list, j) == o) {
1300 o = class_name(o);
1301 if (o != NULL) {
1302 PyErr_Format(PyExc_TypeError,
1303 "duplicate base class %U",
1304 o);
1305 Py_DECREF(o);
1306 } else {
1307 PyErr_SetString(PyExc_TypeError,
1308 "duplicate base class");
1309 }
1310 return -1;
1311 }
1312 }
1313 }
1314 return 0;
Guido van Rossum98f33732002-11-25 21:36:54 +00001315}
1316
1317/* Raise a TypeError for an MRO order disagreement.
1318
1319 It's hard to produce a good error message. In the absence of better
1320 insight into error reporting, report the classes that were candidates
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001321 to be put next into the MRO. There is some conflict between the
Guido van Rossum98f33732002-11-25 21:36:54 +00001322 order in which they should be put in the MRO, but it's hard to
1323 diagnose what constraint can't be satisfied.
1324*/
1325
1326static void
1327set_mro_error(PyObject *to_merge, int *remain)
1328{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001329 Py_ssize_t i, n, off, to_merge_size;
1330 char buf[1000];
1331 PyObject *k, *v;
1332 PyObject *set = PyDict_New();
1333 if (!set) return;
Guido van Rossum98f33732002-11-25 21:36:54 +00001334
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001335 to_merge_size = PyList_GET_SIZE(to_merge);
1336 for (i = 0; i < to_merge_size; i++) {
1337 PyObject *L = PyList_GET_ITEM(to_merge, i);
1338 if (remain[i] < PyList_GET_SIZE(L)) {
1339 PyObject *c = PyList_GET_ITEM(L, remain[i]);
1340 if (PyDict_SetItem(set, c, Py_None) < 0) {
1341 Py_DECREF(set);
1342 return;
1343 }
1344 }
1345 }
1346 n = PyDict_Size(set);
Guido van Rossum98f33732002-11-25 21:36:54 +00001347
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001348 off = PyOS_snprintf(buf, sizeof(buf), "Cannot create a \
Raymond Hettingerf394df42003-04-06 19:13:41 +00001349consistent method resolution\norder (MRO) for bases");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001350 i = 0;
1351 while (PyDict_Next(set, &i, &k, &v) && (size_t)off < sizeof(buf)) {
1352 PyObject *name = class_name(k);
Victor Stinnere5f99f32010-05-19 01:42:46 +00001353 char *name_str;
1354 if (name != NULL) {
1355 name_str = _PyUnicode_AsString(name);
1356 if (name_str == NULL)
Victor Stinnerba644a62010-05-19 01:50:45 +00001357 name_str = "?";
Victor Stinnere5f99f32010-05-19 01:42:46 +00001358 } else
Victor Stinnerba644a62010-05-19 01:50:45 +00001359 name_str = "?";
Victor Stinnere5f99f32010-05-19 01:42:46 +00001360 off += PyOS_snprintf(buf + off, sizeof(buf) - off, " %s", name_str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001361 Py_XDECREF(name);
1362 if (--n && (size_t)(off+1) < sizeof(buf)) {
1363 buf[off++] = ',';
1364 buf[off] = '\0';
1365 }
1366 }
1367 PyErr_SetString(PyExc_TypeError, buf);
1368 Py_DECREF(set);
Guido van Rossum98f33732002-11-25 21:36:54 +00001369}
1370
Tim Petersea7f75d2002-12-07 21:39:16 +00001371static int
Guido van Rossum1f121312002-11-14 19:49:16 +00001372pmerge(PyObject *acc, PyObject* to_merge) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001373 Py_ssize_t i, j, to_merge_size, empty_cnt;
1374 int *remain;
1375 int ok;
Tim Petersea7f75d2002-12-07 21:39:16 +00001376
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001377 to_merge_size = PyList_GET_SIZE(to_merge);
Guido van Rossum1f121312002-11-14 19:49:16 +00001378
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001379 /* remain stores an index into each sublist of to_merge.
1380 remain[i] is the index of the next base in to_merge[i]
1381 that is not included in acc.
1382 */
1383 remain = (int *)PyMem_MALLOC(SIZEOF_INT*to_merge_size);
1384 if (remain == NULL)
1385 return -1;
1386 for (i = 0; i < to_merge_size; i++)
1387 remain[i] = 0;
Guido van Rossum1f121312002-11-14 19:49:16 +00001388
1389 again:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001390 empty_cnt = 0;
1391 for (i = 0; i < to_merge_size; i++) {
1392 PyObject *candidate;
Tim Petersea7f75d2002-12-07 21:39:16 +00001393
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001394 PyObject *cur_list = PyList_GET_ITEM(to_merge, i);
Guido van Rossum1f121312002-11-14 19:49:16 +00001395
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001396 if (remain[i] >= PyList_GET_SIZE(cur_list)) {
1397 empty_cnt++;
1398 continue;
1399 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001400
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001401 /* Choose next candidate for MRO.
Guido van Rossum98f33732002-11-25 21:36:54 +00001402
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001403 The input sequences alone can determine the choice.
1404 If not, choose the class which appears in the MRO
1405 of the earliest direct superclass of the new class.
1406 */
Guido van Rossum98f33732002-11-25 21:36:54 +00001407
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001408 candidate = PyList_GET_ITEM(cur_list, remain[i]);
1409 for (j = 0; j < to_merge_size; j++) {
1410 PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
1411 if (tail_contains(j_lst, remain[j], candidate)) {
1412 goto skip; /* continue outer loop */
1413 }
1414 }
1415 ok = PyList_Append(acc, candidate);
1416 if (ok < 0) {
1417 PyMem_Free(remain);
1418 return -1;
1419 }
1420 for (j = 0; j < to_merge_size; j++) {
1421 PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
1422 if (remain[j] < PyList_GET_SIZE(j_lst) &&
1423 PyList_GET_ITEM(j_lst, remain[j]) == candidate) {
1424 remain[j]++;
1425 }
1426 }
1427 goto again;
1428 skip: ;
1429 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001430
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001431 if (empty_cnt == to_merge_size) {
1432 PyMem_FREE(remain);
1433 return 0;
1434 }
1435 set_mro_error(to_merge, remain);
1436 PyMem_FREE(remain);
1437 return -1;
Guido van Rossum1f121312002-11-14 19:49:16 +00001438}
1439
Tim Peters6d6c1a32001-08-02 04:15:00 +00001440static PyObject *
1441mro_implementation(PyTypeObject *type)
1442{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001443 Py_ssize_t i, n;
1444 int ok;
1445 PyObject *bases, *result;
1446 PyObject *to_merge, *bases_aslist;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001447
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001448 if (type->tp_dict == NULL) {
1449 if (PyType_Ready(type) < 0)
1450 return NULL;
1451 }
Guido van Rossum63517572002-06-18 16:44:57 +00001452
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001453 /* Find a superclass linearization that honors the constraints
1454 of the explicit lists of bases and the constraints implied by
1455 each base class.
Guido van Rossum98f33732002-11-25 21:36:54 +00001456
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001457 to_merge is a list of lists, where each list is a superclass
1458 linearization implied by a base class. The last element of
1459 to_merge is the declared list of bases.
1460 */
Guido van Rossum98f33732002-11-25 21:36:54 +00001461
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001462 bases = type->tp_bases;
1463 n = PyTuple_GET_SIZE(bases);
Guido van Rossum1f121312002-11-14 19:49:16 +00001464
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001465 to_merge = PyList_New(n+1);
1466 if (to_merge == NULL)
1467 return NULL;
Guido van Rossum1f121312002-11-14 19:49:16 +00001468
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001469 for (i = 0; i < n; i++) {
1470 PyObject *base = PyTuple_GET_ITEM(bases, i);
1471 PyObject *parentMRO;
1472 parentMRO = PySequence_List(((PyTypeObject*)base)->tp_mro);
1473 if (parentMRO == NULL) {
1474 Py_DECREF(to_merge);
1475 return NULL;
1476 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001477
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001478 PyList_SET_ITEM(to_merge, i, parentMRO);
1479 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001480
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001481 bases_aslist = PySequence_List(bases);
1482 if (bases_aslist == NULL) {
1483 Py_DECREF(to_merge);
1484 return NULL;
1485 }
1486 /* This is just a basic sanity check. */
1487 if (check_duplicates(bases_aslist) < 0) {
1488 Py_DECREF(to_merge);
1489 Py_DECREF(bases_aslist);
1490 return NULL;
1491 }
1492 PyList_SET_ITEM(to_merge, n, bases_aslist);
Guido van Rossum1f121312002-11-14 19:49:16 +00001493
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001494 result = Py_BuildValue("[O]", (PyObject *)type);
1495 if (result == NULL) {
1496 Py_DECREF(to_merge);
1497 return NULL;
1498 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001499
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001500 ok = pmerge(result, to_merge);
1501 Py_DECREF(to_merge);
1502 if (ok < 0) {
1503 Py_DECREF(result);
1504 return NULL;
1505 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001506
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001507 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001508}
1509
1510static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001511mro_external(PyObject *self)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001512{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001513 PyTypeObject *type = (PyTypeObject *)self;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001514
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001515 return mro_implementation(type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001516}
1517
1518static int
1519mro_internal(PyTypeObject *type)
1520{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001521 PyObject *mro, *result, *tuple;
1522 int checkit = 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001523
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001524 if (Py_TYPE(type) == &PyType_Type) {
1525 result = mro_implementation(type);
1526 }
1527 else {
1528 static PyObject *mro_str;
1529 checkit = 1;
1530 mro = lookup_method((PyObject *)type, "mro", &mro_str);
1531 if (mro == NULL)
1532 return -1;
1533 result = PyObject_CallObject(mro, NULL);
1534 Py_DECREF(mro);
1535 }
1536 if (result == NULL)
1537 return -1;
1538 tuple = PySequence_Tuple(result);
1539 Py_DECREF(result);
1540 if (tuple == NULL)
1541 return -1;
1542 if (checkit) {
1543 Py_ssize_t i, len;
1544 PyObject *cls;
1545 PyTypeObject *solid;
Armin Rigo037d1e02005-12-29 17:07:39 +00001546
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001547 solid = solid_base(type);
Armin Rigo037d1e02005-12-29 17:07:39 +00001548
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001549 len = PyTuple_GET_SIZE(tuple);
Armin Rigo037d1e02005-12-29 17:07:39 +00001550
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001551 for (i = 0; i < len; i++) {
1552 PyTypeObject *t;
1553 cls = PyTuple_GET_ITEM(tuple, i);
1554 if (!PyType_Check(cls)) {
1555 PyErr_Format(PyExc_TypeError,
1556 "mro() returned a non-class ('%.500s')",
1557 Py_TYPE(cls)->tp_name);
1558 Py_DECREF(tuple);
1559 return -1;
1560 }
1561 t = (PyTypeObject*)cls;
1562 if (!PyType_IsSubtype(solid, solid_base(t))) {
1563 PyErr_Format(PyExc_TypeError,
1564 "mro() returned base with unsuitable layout ('%.500s')",
1565 t->tp_name);
1566 Py_DECREF(tuple);
1567 return -1;
1568 }
1569 }
1570 }
1571 type->tp_mro = tuple;
Christian Heimesa62da1d2008-01-12 19:39:10 +00001572
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001573 type_mro_modified(type, type->tp_mro);
1574 /* corner case: the old-style super class might have been hidden
1575 from the custom MRO */
1576 type_mro_modified(type, type->tp_bases);
Christian Heimesa62da1d2008-01-12 19:39:10 +00001577
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001578 PyType_Modified(type);
Christian Heimesa62da1d2008-01-12 19:39:10 +00001579
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001580 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001581}
1582
1583
1584/* Calculate the best base amongst multiple base classes.
1585 This is the first one that's on the path to the "solid base". */
1586
1587static PyTypeObject *
1588best_base(PyObject *bases)
1589{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001590 Py_ssize_t i, n;
1591 PyTypeObject *base, *winner, *candidate, *base_i;
1592 PyObject *base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001593
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001594 assert(PyTuple_Check(bases));
1595 n = PyTuple_GET_SIZE(bases);
1596 assert(n > 0);
1597 base = NULL;
1598 winner = NULL;
1599 for (i = 0; i < n; i++) {
1600 base_proto = PyTuple_GET_ITEM(bases, i);
1601 if (!PyType_Check(base_proto)) {
1602 PyErr_SetString(
1603 PyExc_TypeError,
1604 "bases must be types");
1605 return NULL;
1606 }
1607 base_i = (PyTypeObject *)base_proto;
1608 if (base_i->tp_dict == NULL) {
1609 if (PyType_Ready(base_i) < 0)
1610 return NULL;
1611 }
1612 candidate = solid_base(base_i);
1613 if (winner == NULL) {
1614 winner = candidate;
1615 base = base_i;
1616 }
1617 else if (PyType_IsSubtype(winner, candidate))
1618 ;
1619 else if (PyType_IsSubtype(candidate, winner)) {
1620 winner = candidate;
1621 base = base_i;
1622 }
1623 else {
1624 PyErr_SetString(
1625 PyExc_TypeError,
1626 "multiple bases have "
1627 "instance lay-out conflict");
1628 return NULL;
1629 }
1630 }
1631 if (base == NULL)
1632 PyErr_SetString(PyExc_TypeError,
1633 "a new-style class can't have only classic bases");
1634 return base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001635}
1636
1637static int
1638extra_ivars(PyTypeObject *type, PyTypeObject *base)
1639{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001640 size_t t_size = type->tp_basicsize;
1641 size_t b_size = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001642
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001643 assert(t_size >= b_size); /* Else type smaller than base! */
1644 if (type->tp_itemsize || base->tp_itemsize) {
1645 /* If itemsize is involved, stricter rules */
1646 return t_size != b_size ||
1647 type->tp_itemsize != base->tp_itemsize;
1648 }
1649 if (type->tp_weaklistoffset && base->tp_weaklistoffset == 0 &&
1650 type->tp_weaklistoffset + sizeof(PyObject *) == t_size &&
1651 type->tp_flags & Py_TPFLAGS_HEAPTYPE)
1652 t_size -= sizeof(PyObject *);
1653 if (type->tp_dictoffset && base->tp_dictoffset == 0 &&
1654 type->tp_dictoffset + sizeof(PyObject *) == t_size &&
1655 type->tp_flags & Py_TPFLAGS_HEAPTYPE)
1656 t_size -= sizeof(PyObject *);
Guido van Rossum9676b222001-08-17 20:32:36 +00001657
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001658 return t_size != b_size;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001659}
1660
1661static PyTypeObject *
1662solid_base(PyTypeObject *type)
1663{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001664 PyTypeObject *base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001665
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001666 if (type->tp_base)
1667 base = solid_base(type->tp_base);
1668 else
1669 base = &PyBaseObject_Type;
1670 if (extra_ivars(type, base))
1671 return type;
1672 else
1673 return base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001674}
1675
Jeremy Hylton938ace62002-07-17 16:30:39 +00001676static void object_dealloc(PyObject *);
1677static int object_init(PyObject *, PyObject *, PyObject *);
1678static int update_slot(PyTypeObject *, PyObject *);
1679static void fixup_slot_dispatchers(PyTypeObject *);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001680
Guido van Rossum360e4b82007-05-14 22:51:27 +00001681/*
1682 * Helpers for __dict__ descriptor. We don't want to expose the dicts
1683 * inherited from various builtin types. The builtin base usually provides
1684 * its own __dict__ descriptor, so we use that when we can.
1685 */
1686static PyTypeObject *
1687get_builtin_base_with_dict(PyTypeObject *type)
1688{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001689 while (type->tp_base != NULL) {
1690 if (type->tp_dictoffset != 0 &&
1691 !(type->tp_flags & Py_TPFLAGS_HEAPTYPE))
1692 return type;
1693 type = type->tp_base;
1694 }
1695 return NULL;
Guido van Rossum360e4b82007-05-14 22:51:27 +00001696}
1697
1698static PyObject *
1699get_dict_descriptor(PyTypeObject *type)
1700{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001701 static PyObject *dict_str;
1702 PyObject *descr;
Guido van Rossum360e4b82007-05-14 22:51:27 +00001703
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001704 if (dict_str == NULL) {
1705 dict_str = PyUnicode_InternFromString("__dict__");
1706 if (dict_str == NULL)
1707 return NULL;
1708 }
1709 descr = _PyType_Lookup(type, dict_str);
1710 if (descr == NULL || !PyDescr_IsData(descr))
1711 return NULL;
Guido van Rossum360e4b82007-05-14 22:51:27 +00001712
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001713 return descr;
Guido van Rossum360e4b82007-05-14 22:51:27 +00001714}
1715
1716static void
1717raise_dict_descr_error(PyObject *obj)
1718{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001719 PyErr_Format(PyExc_TypeError,
1720 "this __dict__ descriptor does not support "
1721 "'%.200s' objects", Py_TYPE(obj)->tp_name);
Guido van Rossum360e4b82007-05-14 22:51:27 +00001722}
1723
Tim Peters6d6c1a32001-08-02 04:15:00 +00001724static PyObject *
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001725subtype_dict(PyObject *obj, void *context)
1726{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001727 PyObject **dictptr;
1728 PyObject *dict;
1729 PyTypeObject *base;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001730
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001731 base = get_builtin_base_with_dict(Py_TYPE(obj));
1732 if (base != NULL) {
1733 descrgetfunc func;
1734 PyObject *descr = get_dict_descriptor(base);
1735 if (descr == NULL) {
1736 raise_dict_descr_error(obj);
1737 return NULL;
1738 }
1739 func = Py_TYPE(descr)->tp_descr_get;
1740 if (func == NULL) {
1741 raise_dict_descr_error(obj);
1742 return NULL;
1743 }
1744 return func(descr, obj, (PyObject *)(Py_TYPE(obj)));
1745 }
Guido van Rossum360e4b82007-05-14 22:51:27 +00001746
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001747 dictptr = _PyObject_GetDictPtr(obj);
1748 if (dictptr == NULL) {
1749 PyErr_SetString(PyExc_AttributeError,
1750 "This object has no __dict__");
1751 return NULL;
1752 }
1753 dict = *dictptr;
1754 if (dict == NULL)
1755 *dictptr = dict = PyDict_New();
1756 Py_XINCREF(dict);
1757 return dict;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001758}
1759
Guido van Rossum6661be32001-10-26 04:26:12 +00001760static int
1761subtype_setdict(PyObject *obj, PyObject *value, void *context)
1762{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001763 PyObject **dictptr;
1764 PyObject *dict;
1765 PyTypeObject *base;
Guido van Rossum6661be32001-10-26 04:26:12 +00001766
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001767 base = get_builtin_base_with_dict(Py_TYPE(obj));
1768 if (base != NULL) {
1769 descrsetfunc func;
1770 PyObject *descr = get_dict_descriptor(base);
1771 if (descr == NULL) {
1772 raise_dict_descr_error(obj);
1773 return -1;
1774 }
1775 func = Py_TYPE(descr)->tp_descr_set;
1776 if (func == NULL) {
1777 raise_dict_descr_error(obj);
1778 return -1;
1779 }
1780 return func(descr, obj, value);
1781 }
Guido van Rossum360e4b82007-05-14 22:51:27 +00001782
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001783 dictptr = _PyObject_GetDictPtr(obj);
1784 if (dictptr == NULL) {
1785 PyErr_SetString(PyExc_AttributeError,
1786 "This object has no __dict__");
1787 return -1;
1788 }
1789 if (value != NULL && !PyDict_Check(value)) {
1790 PyErr_Format(PyExc_TypeError,
1791 "__dict__ must be set to a dictionary, "
1792 "not a '%.200s'", Py_TYPE(value)->tp_name);
1793 return -1;
1794 }
1795 dict = *dictptr;
1796 Py_XINCREF(value);
1797 *dictptr = value;
1798 Py_XDECREF(dict);
1799 return 0;
Guido van Rossum6661be32001-10-26 04:26:12 +00001800}
1801
Guido van Rossumad47da02002-08-12 19:05:44 +00001802static PyObject *
1803subtype_getweakref(PyObject *obj, void *context)
1804{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001805 PyObject **weaklistptr;
1806 PyObject *result;
Guido van Rossumad47da02002-08-12 19:05:44 +00001807
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001808 if (Py_TYPE(obj)->tp_weaklistoffset == 0) {
1809 PyErr_SetString(PyExc_AttributeError,
1810 "This object has no __weakref__");
1811 return NULL;
1812 }
1813 assert(Py_TYPE(obj)->tp_weaklistoffset > 0);
1814 assert(Py_TYPE(obj)->tp_weaklistoffset + sizeof(PyObject *) <=
1815 (size_t)(Py_TYPE(obj)->tp_basicsize));
1816 weaklistptr = (PyObject **)
1817 ((char *)obj + Py_TYPE(obj)->tp_weaklistoffset);
1818 if (*weaklistptr == NULL)
1819 result = Py_None;
1820 else
1821 result = *weaklistptr;
1822 Py_INCREF(result);
1823 return result;
Guido van Rossumad47da02002-08-12 19:05:44 +00001824}
1825
Guido van Rossum373c7412003-01-07 13:41:37 +00001826/* Three variants on the subtype_getsets list. */
1827
1828static PyGetSetDef subtype_getsets_full[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001829 {"__dict__", subtype_dict, subtype_setdict,
1830 PyDoc_STR("dictionary for instance variables (if defined)")},
1831 {"__weakref__", subtype_getweakref, NULL,
1832 PyDoc_STR("list of weak references to the object (if defined)")},
1833 {0}
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001834};
1835
Guido van Rossum373c7412003-01-07 13:41:37 +00001836static PyGetSetDef subtype_getsets_dict_only[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001837 {"__dict__", subtype_dict, subtype_setdict,
1838 PyDoc_STR("dictionary for instance variables (if defined)")},
1839 {0}
Guido van Rossum373c7412003-01-07 13:41:37 +00001840};
1841
1842static PyGetSetDef subtype_getsets_weakref_only[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001843 {"__weakref__", subtype_getweakref, NULL,
1844 PyDoc_STR("list of weak references to the object (if defined)")},
1845 {0}
Guido van Rossum373c7412003-01-07 13:41:37 +00001846};
1847
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001848static int
1849valid_identifier(PyObject *s)
1850{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001851 if (!PyUnicode_Check(s)) {
1852 PyErr_Format(PyExc_TypeError,
1853 "__slots__ items must be strings, not '%.200s'",
1854 Py_TYPE(s)->tp_name);
1855 return 0;
1856 }
1857 if (!PyUnicode_IsIdentifier(s)) {
1858 PyErr_SetString(PyExc_TypeError,
1859 "__slots__ must be identifiers");
1860 return 0;
1861 }
1862 return 1;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001863}
1864
Guido van Rossumd8faa362007-04-27 19:54:29 +00001865/* Forward */
1866static int
1867object_init(PyObject *self, PyObject *args, PyObject *kwds);
1868
1869static int
1870type_init(PyObject *cls, PyObject *args, PyObject *kwds)
1871{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001872 int res;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001873
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001874 assert(args != NULL && PyTuple_Check(args));
1875 assert(kwds == NULL || PyDict_Check(kwds));
Guido van Rossumd8faa362007-04-27 19:54:29 +00001876
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001877 if (kwds != NULL && PyDict_Check(kwds) && PyDict_Size(kwds) != 0) {
1878 PyErr_SetString(PyExc_TypeError,
1879 "type.__init__() takes no keyword arguments");
1880 return -1;
1881 }
Guido van Rossumd8faa362007-04-27 19:54:29 +00001882
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001883 if (args != NULL && PyTuple_Check(args) &&
1884 (PyTuple_GET_SIZE(args) != 1 && PyTuple_GET_SIZE(args) != 3)) {
1885 PyErr_SetString(PyExc_TypeError,
1886 "type.__init__() takes 1 or 3 arguments");
1887 return -1;
1888 }
Guido van Rossumd8faa362007-04-27 19:54:29 +00001889
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001890 /* Call object.__init__(self) now. */
1891 /* XXX Could call super(type, cls).__init__() but what's the point? */
1892 args = PyTuple_GetSlice(args, 0, 0);
1893 res = object_init(cls, args, NULL);
1894 Py_DECREF(args);
1895 return res;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001896}
1897
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001898static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00001899type_new(PyTypeObject *metatype, PyObject *args, PyObject *kwds)
1900{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001901 PyObject *name, *bases, *dict;
1902 static char *kwlist[] = {"name", "bases", "dict", 0};
1903 PyObject *slots, *tmp, *newslots;
1904 PyTypeObject *type, *base, *tmptype, *winner;
1905 PyHeapTypeObject *et;
1906 PyMemberDef *mp;
1907 Py_ssize_t i, nbases, nslots, slotoffset, add_dict, add_weak;
1908 int j, may_add_dict, may_add_weak;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001909
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001910 assert(args != NULL && PyTuple_Check(args));
1911 assert(kwds == NULL || PyDict_Check(kwds));
Tim Peters3abca122001-10-27 19:37:48 +00001912
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001913 /* Special case: type(x) should return x->ob_type */
1914 {
1915 const Py_ssize_t nargs = PyTuple_GET_SIZE(args);
1916 const Py_ssize_t nkwds = kwds == NULL ? 0 : PyDict_Size(kwds);
Tim Peters3abca122001-10-27 19:37:48 +00001917
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001918 if (PyType_CheckExact(metatype) && nargs == 1 && nkwds == 0) {
1919 PyObject *x = PyTuple_GET_ITEM(args, 0);
1920 Py_INCREF(Py_TYPE(x));
1921 return (PyObject *) Py_TYPE(x);
1922 }
Tim Peters3abca122001-10-27 19:37:48 +00001923
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001924 /* SF bug 475327 -- if that didn't trigger, we need 3
1925 arguments. but PyArg_ParseTupleAndKeywords below may give
1926 a msg saying type() needs exactly 3. */
1927 if (nargs + nkwds != 3) {
1928 PyErr_SetString(PyExc_TypeError,
1929 "type() takes 1 or 3 arguments");
1930 return NULL;
1931 }
1932 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001933
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001934 /* Check arguments: (name, bases, dict) */
1935 if (!PyArg_ParseTupleAndKeywords(args, kwds, "UO!O!:type", kwlist,
1936 &name,
1937 &PyTuple_Type, &bases,
1938 &PyDict_Type, &dict))
1939 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001940
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001941 /* Determine the proper metatype to deal with this,
1942 and check for metatype conflicts while we're at it.
1943 Note that if some other metatype wins to contract,
1944 it's possible that its instances are not types. */
1945 nbases = PyTuple_GET_SIZE(bases);
1946 winner = metatype;
1947 for (i = 0; i < nbases; i++) {
1948 tmp = PyTuple_GET_ITEM(bases, i);
1949 tmptype = Py_TYPE(tmp);
1950 if (PyType_IsSubtype(winner, tmptype))
1951 continue;
1952 if (PyType_IsSubtype(tmptype, winner)) {
1953 winner = tmptype;
1954 continue;
1955 }
1956 PyErr_SetString(PyExc_TypeError,
1957 "metaclass conflict: "
1958 "the metaclass of a derived class "
1959 "must be a (non-strict) subclass "
1960 "of the metaclasses of all its bases");
1961 return NULL;
1962 }
1963 if (winner != metatype) {
1964 if (winner->tp_new != type_new) /* Pass it to the winner */
1965 return winner->tp_new(winner, args, kwds);
1966 metatype = winner;
1967 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001968
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001969 /* Adjust for empty tuple bases */
1970 if (nbases == 0) {
1971 bases = PyTuple_Pack(1, &PyBaseObject_Type);
1972 if (bases == NULL)
1973 return NULL;
1974 nbases = 1;
1975 }
1976 else
1977 Py_INCREF(bases);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001978
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001979 /* XXX From here until type is allocated, "return NULL" leaks bases! */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001980
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001981 /* Calculate best base, and check that all bases are type objects */
1982 base = best_base(bases);
1983 if (base == NULL) {
1984 Py_DECREF(bases);
1985 return NULL;
1986 }
1987 if (!PyType_HasFeature(base, Py_TPFLAGS_BASETYPE)) {
1988 PyErr_Format(PyExc_TypeError,
1989 "type '%.100s' is not an acceptable base type",
1990 base->tp_name);
1991 Py_DECREF(bases);
1992 return NULL;
1993 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001994
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001995 /* Check for a __slots__ sequence variable in dict, and count it */
1996 slots = PyDict_GetItemString(dict, "__slots__");
1997 nslots = 0;
1998 add_dict = 0;
1999 add_weak = 0;
2000 may_add_dict = base->tp_dictoffset == 0;
2001 may_add_weak = base->tp_weaklistoffset == 0 && base->tp_itemsize == 0;
2002 if (slots == NULL) {
2003 if (may_add_dict) {
2004 add_dict++;
2005 }
2006 if (may_add_weak) {
2007 add_weak++;
2008 }
2009 }
2010 else {
2011 /* Have slots */
Guido van Rossumad47da02002-08-12 19:05:44 +00002012
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002013 /* Make it into a tuple */
2014 if (PyUnicode_Check(slots))
2015 slots = PyTuple_Pack(1, slots);
2016 else
2017 slots = PySequence_Tuple(slots);
2018 if (slots == NULL) {
2019 Py_DECREF(bases);
2020 return NULL;
2021 }
2022 assert(PyTuple_Check(slots));
Guido van Rossumad47da02002-08-12 19:05:44 +00002023
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002024 /* Are slots allowed? */
2025 nslots = PyTuple_GET_SIZE(slots);
2026 if (nslots > 0 && base->tp_itemsize != 0) {
2027 PyErr_Format(PyExc_TypeError,
2028 "nonempty __slots__ "
2029 "not supported for subtype of '%s'",
2030 base->tp_name);
2031 bad_slots:
2032 Py_DECREF(bases);
2033 Py_DECREF(slots);
2034 return NULL;
2035 }
Guido van Rossumad47da02002-08-12 19:05:44 +00002036
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002037 /* Check for valid slot names and two special cases */
2038 for (i = 0; i < nslots; i++) {
2039 PyObject *tmp = PyTuple_GET_ITEM(slots, i);
2040 if (!valid_identifier(tmp))
2041 goto bad_slots;
2042 assert(PyUnicode_Check(tmp));
2043 if (PyUnicode_CompareWithASCIIString(tmp, "__dict__") == 0) {
2044 if (!may_add_dict || add_dict) {
2045 PyErr_SetString(PyExc_TypeError,
2046 "__dict__ slot disallowed: "
2047 "we already got one");
2048 goto bad_slots;
2049 }
2050 add_dict++;
2051 }
2052 if (PyUnicode_CompareWithASCIIString(tmp, "__weakref__") == 0) {
2053 if (!may_add_weak || add_weak) {
2054 PyErr_SetString(PyExc_TypeError,
2055 "__weakref__ slot disallowed: "
2056 "either we already got one, "
2057 "or __itemsize__ != 0");
2058 goto bad_slots;
2059 }
2060 add_weak++;
2061 }
2062 }
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00002063
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002064 /* Copy slots into a list, mangle names and sort them.
2065 Sorted names are needed for __class__ assignment.
2066 Convert them back to tuple at the end.
2067 */
2068 newslots = PyList_New(nslots - add_dict - add_weak);
2069 if (newslots == NULL)
2070 goto bad_slots;
2071 for (i = j = 0; i < nslots; i++) {
2072 tmp = PyTuple_GET_ITEM(slots, i);
2073 if ((add_dict &&
2074 PyUnicode_CompareWithASCIIString(tmp, "__dict__") == 0) ||
2075 (add_weak &&
2076 PyUnicode_CompareWithASCIIString(tmp, "__weakref__") == 0))
2077 continue;
2078 tmp =_Py_Mangle(name, tmp);
2079 if (!tmp)
2080 goto bad_slots;
2081 PyList_SET_ITEM(newslots, j, tmp);
2082 j++;
2083 }
2084 assert(j == nslots - add_dict - add_weak);
2085 nslots = j;
2086 Py_DECREF(slots);
2087 if (PyList_Sort(newslots) == -1) {
2088 Py_DECREF(bases);
2089 Py_DECREF(newslots);
2090 return NULL;
2091 }
2092 slots = PyList_AsTuple(newslots);
2093 Py_DECREF(newslots);
2094 if (slots == NULL) {
2095 Py_DECREF(bases);
2096 return NULL;
2097 }
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00002098
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002099 /* Secondary bases may provide weakrefs or dict */
2100 if (nbases > 1 &&
2101 ((may_add_dict && !add_dict) ||
2102 (may_add_weak && !add_weak))) {
2103 for (i = 0; i < nbases; i++) {
2104 tmp = PyTuple_GET_ITEM(bases, i);
2105 if (tmp == (PyObject *)base)
2106 continue; /* Skip primary base */
2107 assert(PyType_Check(tmp));
2108 tmptype = (PyTypeObject *)tmp;
2109 if (may_add_dict && !add_dict &&
2110 tmptype->tp_dictoffset != 0)
2111 add_dict++;
2112 if (may_add_weak && !add_weak &&
2113 tmptype->tp_weaklistoffset != 0)
2114 add_weak++;
2115 if (may_add_dict && !add_dict)
2116 continue;
2117 if (may_add_weak && !add_weak)
2118 continue;
2119 /* Nothing more to check */
2120 break;
2121 }
2122 }
2123 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002124
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002125 /* XXX From here until type is safely allocated,
2126 "return NULL" may leak slots! */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002127
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002128 /* Allocate the type object */
2129 type = (PyTypeObject *)metatype->tp_alloc(metatype, nslots);
2130 if (type == NULL) {
2131 Py_XDECREF(slots);
2132 Py_DECREF(bases);
2133 return NULL;
2134 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002135
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002136 /* Keep name and slots alive in the extended type object */
2137 et = (PyHeapTypeObject *)type;
2138 Py_INCREF(name);
2139 et->ht_name = name;
2140 et->ht_slots = slots;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002141
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002142 /* Initialize tp_flags */
2143 type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE |
2144 Py_TPFLAGS_BASETYPE;
2145 if (base->tp_flags & Py_TPFLAGS_HAVE_GC)
2146 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossumdc91b992001-08-08 22:26:22 +00002147
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002148 /* Initialize essential fields */
2149 type->tp_as_number = &et->as_number;
2150 type->tp_as_sequence = &et->as_sequence;
2151 type->tp_as_mapping = &et->as_mapping;
2152 type->tp_as_buffer = &et->as_buffer;
2153 type->tp_name = _PyUnicode_AsString(name);
2154 if (!type->tp_name) {
2155 Py_DECREF(type);
2156 return NULL;
2157 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002158
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002159 /* Set tp_base and tp_bases */
2160 type->tp_bases = bases;
2161 Py_INCREF(base);
2162 type->tp_base = base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002163
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002164 /* Initialize tp_dict from passed-in dict */
2165 type->tp_dict = dict = PyDict_Copy(dict);
2166 if (dict == NULL) {
2167 Py_DECREF(type);
2168 return NULL;
2169 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002170
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002171 /* Set __module__ in the dict */
2172 if (PyDict_GetItemString(dict, "__module__") == NULL) {
2173 tmp = PyEval_GetGlobals();
2174 if (tmp != NULL) {
2175 tmp = PyDict_GetItemString(tmp, "__name__");
2176 if (tmp != NULL) {
2177 if (PyDict_SetItemString(dict, "__module__",
2178 tmp) < 0)
2179 return NULL;
2180 }
2181 }
2182 }
Guido van Rossumc3542212001-08-16 09:18:56 +00002183
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002184 /* Set tp_doc to a copy of dict['__doc__'], if the latter is there
2185 and is a string. The __doc__ accessor will first look for tp_doc;
2186 if that fails, it will still look into __dict__.
2187 */
2188 {
2189 PyObject *doc = PyDict_GetItemString(dict, "__doc__");
2190 if (doc != NULL && PyUnicode_Check(doc)) {
2191 Py_ssize_t len;
2192 char *doc_str;
2193 char *tp_doc;
Alexandre Vassalottia85998a2008-05-03 18:24:43 +00002194
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002195 doc_str = _PyUnicode_AsString(doc);
2196 if (doc_str == NULL) {
2197 Py_DECREF(type);
2198 return NULL;
2199 }
2200 /* Silently truncate the docstring if it contains null bytes. */
2201 len = strlen(doc_str);
2202 tp_doc = (char *)PyObject_MALLOC(len + 1);
2203 if (tp_doc == NULL) {
2204 Py_DECREF(type);
2205 return NULL;
2206 }
2207 memcpy(tp_doc, doc_str, len + 1);
2208 type->tp_doc = tp_doc;
2209 }
2210 }
Tim Peters2f93e282001-10-04 05:27:00 +00002211
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002212 /* Special-case __new__: if it's a plain function,
2213 make it a static function */
2214 tmp = PyDict_GetItemString(dict, "__new__");
2215 if (tmp != NULL && PyFunction_Check(tmp)) {
2216 tmp = PyStaticMethod_New(tmp);
2217 if (tmp == NULL) {
2218 Py_DECREF(type);
2219 return NULL;
2220 }
2221 PyDict_SetItemString(dict, "__new__", tmp);
2222 Py_DECREF(tmp);
2223 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002224
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002225 /* Add descriptors for custom slots from __slots__, or for __dict__ */
2226 mp = PyHeapType_GET_MEMBERS(et);
2227 slotoffset = base->tp_basicsize;
2228 if (slots != NULL) {
2229 for (i = 0; i < nslots; i++, mp++) {
2230 mp->name = _PyUnicode_AsString(
2231 PyTuple_GET_ITEM(slots, i));
Victor Stinnere5f99f32010-05-19 01:42:46 +00002232 if (mp->name == NULL) {
2233 Py_DECREF(type);
2234 return NULL;
2235 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002236 mp->type = T_OBJECT_EX;
2237 mp->offset = slotoffset;
Guido van Rossumd8faa362007-04-27 19:54:29 +00002238
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002239 /* __dict__ and __weakref__ are already filtered out */
2240 assert(strcmp(mp->name, "__dict__") != 0);
2241 assert(strcmp(mp->name, "__weakref__") != 0);
Guido van Rossumd8faa362007-04-27 19:54:29 +00002242
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002243 slotoffset += sizeof(PyObject *);
2244 }
2245 }
2246 if (add_dict) {
2247 if (base->tp_itemsize)
2248 type->tp_dictoffset = -(long)sizeof(PyObject *);
2249 else
2250 type->tp_dictoffset = slotoffset;
2251 slotoffset += sizeof(PyObject *);
2252 }
2253 if (add_weak) {
2254 assert(!base->tp_itemsize);
2255 type->tp_weaklistoffset = slotoffset;
2256 slotoffset += sizeof(PyObject *);
2257 }
2258 type->tp_basicsize = slotoffset;
2259 type->tp_itemsize = base->tp_itemsize;
2260 type->tp_members = PyHeapType_GET_MEMBERS(et);
Guido van Rossum373c7412003-01-07 13:41:37 +00002261
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002262 if (type->tp_weaklistoffset && type->tp_dictoffset)
2263 type->tp_getset = subtype_getsets_full;
2264 else if (type->tp_weaklistoffset && !type->tp_dictoffset)
2265 type->tp_getset = subtype_getsets_weakref_only;
2266 else if (!type->tp_weaklistoffset && type->tp_dictoffset)
2267 type->tp_getset = subtype_getsets_dict_only;
2268 else
2269 type->tp_getset = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002270
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002271 /* Special case some slots */
2272 if (type->tp_dictoffset != 0 || nslots > 0) {
2273 if (base->tp_getattr == NULL && base->tp_getattro == NULL)
2274 type->tp_getattro = PyObject_GenericGetAttr;
2275 if (base->tp_setattr == NULL && base->tp_setattro == NULL)
2276 type->tp_setattro = PyObject_GenericSetAttr;
2277 }
2278 type->tp_dealloc = subtype_dealloc;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002279
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002280 /* Enable GC unless there are really no instance variables possible */
2281 if (!(type->tp_basicsize == sizeof(PyObject) &&
2282 type->tp_itemsize == 0))
2283 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossum9475a232001-10-05 20:51:39 +00002284
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002285 /* Always override allocation strategy to use regular heap */
2286 type->tp_alloc = PyType_GenericAlloc;
2287 if (type->tp_flags & Py_TPFLAGS_HAVE_GC) {
2288 type->tp_free = PyObject_GC_Del;
2289 type->tp_traverse = subtype_traverse;
2290 type->tp_clear = subtype_clear;
2291 }
2292 else
2293 type->tp_free = PyObject_Del;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002294
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002295 /* Initialize the rest */
2296 if (PyType_Ready(type) < 0) {
2297 Py_DECREF(type);
2298 return NULL;
2299 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002300
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002301 /* Put the proper slots in place */
2302 fixup_slot_dispatchers(type);
Guido van Rossumf040ede2001-08-07 16:40:56 +00002303
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002304 return (PyObject *)type;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002305}
2306
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002307static short slotoffsets[] = {
2308 -1, /* invalid slot */
2309#include "typeslots.inc"
2310};
2311
2312PyObject* PyType_FromSpec(PyType_Spec *spec)
2313{
2314 PyHeapTypeObject *res = (PyHeapTypeObject*)PyType_GenericAlloc(&PyType_Type, 0);
2315 char *res_start = (char*)res;
2316 PyType_Slot *slot;
2317
2318 res->ht_name = PyUnicode_FromString(spec->name);
2319 if (!res->ht_name)
2320 goto fail;
2321 res->ht_type.tp_name = _PyUnicode_AsString(res->ht_name);
2322 if (!res->ht_type.tp_name)
2323 goto fail;
2324
2325 res->ht_type.tp_basicsize = spec->basicsize;
2326 res->ht_type.tp_itemsize = spec->itemsize;
2327 res->ht_type.tp_flags = spec->flags | Py_TPFLAGS_HEAPTYPE;
2328
2329 for (slot = spec->slots; slot->slot; slot++) {
2330 if (slot->slot >= sizeof(slotoffsets)/sizeof(slotoffsets[0])) {
2331 PyErr_SetString(PyExc_RuntimeError, "invalid slot offset");
2332 goto fail;
2333 }
2334 *(void**)(res_start + slotoffsets[slot->slot]) = slot->pfunc;
2335 }
2336
2337 return (PyObject*)res;
2338
2339 fail:
2340 Py_DECREF(res);
2341 return NULL;
2342}
2343
2344
Tim Peters6d6c1a32001-08-02 04:15:00 +00002345/* Internal API to look for a name through the MRO.
2346 This returns a borrowed reference, and doesn't set an exception! */
2347PyObject *
2348_PyType_Lookup(PyTypeObject *type, PyObject *name)
2349{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002350 Py_ssize_t i, n;
2351 PyObject *mro, *res, *base, *dict;
2352 unsigned int h;
Christian Heimesa62da1d2008-01-12 19:39:10 +00002353
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002354 if (MCACHE_CACHEABLE_NAME(name) &&
2355 PyType_HasFeature(type, Py_TPFLAGS_VALID_VERSION_TAG)) {
2356 /* fast path */
2357 h = MCACHE_HASH_METHOD(type, name);
2358 if (method_cache[h].version == type->tp_version_tag &&
2359 method_cache[h].name == name)
2360 return method_cache[h].value;
2361 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002362
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002363 /* Look in tp_dict of types in MRO */
2364 mro = type->tp_mro;
Guido van Rossum23094982002-06-10 14:30:43 +00002365
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002366 /* If mro is NULL, the type is either not yet initialized
2367 by PyType_Ready(), or already cleared by type_clear().
2368 Either way the safest thing to do is to return NULL. */
2369 if (mro == NULL)
2370 return NULL;
Guido van Rossum23094982002-06-10 14:30:43 +00002371
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002372 res = NULL;
2373 assert(PyTuple_Check(mro));
2374 n = PyTuple_GET_SIZE(mro);
2375 for (i = 0; i < n; i++) {
2376 base = PyTuple_GET_ITEM(mro, i);
2377 assert(PyType_Check(base));
2378 dict = ((PyTypeObject *)base)->tp_dict;
2379 assert(dict && PyDict_Check(dict));
2380 res = PyDict_GetItem(dict, name);
2381 if (res != NULL)
2382 break;
2383 }
Christian Heimesa62da1d2008-01-12 19:39:10 +00002384
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002385 if (MCACHE_CACHEABLE_NAME(name) && assign_version_tag(type)) {
2386 h = MCACHE_HASH_METHOD(type, name);
2387 method_cache[h].version = type->tp_version_tag;
2388 method_cache[h].value = res; /* borrowed */
2389 Py_INCREF(name);
2390 Py_DECREF(method_cache[h].name);
2391 method_cache[h].name = name;
2392 }
2393 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002394}
2395
2396/* This is similar to PyObject_GenericGetAttr(),
2397 but uses _PyType_Lookup() instead of just looking in type->tp_dict. */
2398static PyObject *
2399type_getattro(PyTypeObject *type, PyObject *name)
2400{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002401 PyTypeObject *metatype = Py_TYPE(type);
2402 PyObject *meta_attribute, *attribute;
2403 descrgetfunc meta_get;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002404
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002405 /* Initialize this type (we'll assume the metatype is initialized) */
2406 if (type->tp_dict == NULL) {
2407 if (PyType_Ready(type) < 0)
2408 return NULL;
2409 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002410
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002411 /* No readable descriptor found yet */
2412 meta_get = NULL;
Tim Peters34592512002-07-11 06:23:50 +00002413
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002414 /* Look for the attribute in the metatype */
2415 meta_attribute = _PyType_Lookup(metatype, name);
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002416
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002417 if (meta_attribute != NULL) {
2418 meta_get = Py_TYPE(meta_attribute)->tp_descr_get;
Tim Peters34592512002-07-11 06:23:50 +00002419
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002420 if (meta_get != NULL && PyDescr_IsData(meta_attribute)) {
2421 /* Data descriptors implement tp_descr_set to intercept
2422 * writes. Assume the attribute is not overridden in
2423 * type's tp_dict (and bases): call the descriptor now.
2424 */
2425 return meta_get(meta_attribute, (PyObject *)type,
2426 (PyObject *)metatype);
2427 }
2428 Py_INCREF(meta_attribute);
2429 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002430
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002431 /* No data descriptor found on metatype. Look in tp_dict of this
2432 * type and its bases */
2433 attribute = _PyType_Lookup(type, name);
2434 if (attribute != NULL) {
2435 /* Implement descriptor functionality, if any */
2436 descrgetfunc local_get = Py_TYPE(attribute)->tp_descr_get;
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00002437
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002438 Py_XDECREF(meta_attribute);
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00002439
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002440 if (local_get != NULL) {
2441 /* NULL 2nd argument indicates the descriptor was
2442 * found on the target object itself (or a base) */
2443 return local_get(attribute, (PyObject *)NULL,
2444 (PyObject *)type);
2445 }
Tim Peters34592512002-07-11 06:23:50 +00002446
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002447 Py_INCREF(attribute);
2448 return attribute;
2449 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002450
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002451 /* No attribute found in local __dict__ (or bases): use the
2452 * descriptor from the metatype, if any */
2453 if (meta_get != NULL) {
2454 PyObject *res;
2455 res = meta_get(meta_attribute, (PyObject *)type,
2456 (PyObject *)metatype);
2457 Py_DECREF(meta_attribute);
2458 return res;
2459 }
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002460
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002461 /* If an ordinary attribute was found on the metatype, return it now */
2462 if (meta_attribute != NULL) {
2463 return meta_attribute;
2464 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002465
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002466 /* Give up */
2467 PyErr_Format(PyExc_AttributeError,
2468 "type object '%.50s' has no attribute '%U'",
2469 type->tp_name, name);
2470 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002471}
2472
2473static int
2474type_setattro(PyTypeObject *type, PyObject *name, PyObject *value)
2475{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002476 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
2477 PyErr_Format(
2478 PyExc_TypeError,
2479 "can't set attributes of built-in/extension type '%s'",
2480 type->tp_name);
2481 return -1;
2482 }
2483 if (PyObject_GenericSetAttr((PyObject *)type, name, value) < 0)
2484 return -1;
2485 return update_slot(type, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002486}
2487
2488static void
2489type_dealloc(PyTypeObject *type)
2490{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002491 PyHeapTypeObject *et;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002492
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002493 /* Assert this is a heap-allocated type object */
2494 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
2495 _PyObject_GC_UNTRACK(type);
2496 PyObject_ClearWeakRefs((PyObject *)type);
2497 et = (PyHeapTypeObject *)type;
2498 Py_XDECREF(type->tp_base);
2499 Py_XDECREF(type->tp_dict);
2500 Py_XDECREF(type->tp_bases);
2501 Py_XDECREF(type->tp_mro);
2502 Py_XDECREF(type->tp_cache);
2503 Py_XDECREF(type->tp_subclasses);
2504 /* A type's tp_doc is heap allocated, unlike the tp_doc slots
2505 * of most other objects. It's okay to cast it to char *.
2506 */
2507 PyObject_Free((char *)type->tp_doc);
2508 Py_XDECREF(et->ht_name);
2509 Py_XDECREF(et->ht_slots);
2510 Py_TYPE(type)->tp_free((PyObject *)type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002511}
2512
Guido van Rossum1c450732001-10-08 15:18:27 +00002513static PyObject *
2514type_subclasses(PyTypeObject *type, PyObject *args_ignored)
2515{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002516 PyObject *list, *raw, *ref;
2517 Py_ssize_t i, n;
Guido van Rossum1c450732001-10-08 15:18:27 +00002518
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002519 list = PyList_New(0);
2520 if (list == NULL)
2521 return NULL;
2522 raw = type->tp_subclasses;
2523 if (raw == NULL)
2524 return list;
2525 assert(PyList_Check(raw));
2526 n = PyList_GET_SIZE(raw);
2527 for (i = 0; i < n; i++) {
2528 ref = PyList_GET_ITEM(raw, i);
2529 assert(PyWeakref_CheckRef(ref));
2530 ref = PyWeakref_GET_OBJECT(ref);
2531 if (ref != Py_None) {
2532 if (PyList_Append(list, ref) < 0) {
2533 Py_DECREF(list);
2534 return NULL;
2535 }
2536 }
2537 }
2538 return list;
Guido van Rossum1c450732001-10-08 15:18:27 +00002539}
2540
Guido van Rossum47374822007-08-02 16:48:17 +00002541static PyObject *
2542type_prepare(PyObject *self, PyObject *args, PyObject *kwds)
2543{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002544 return PyDict_New();
Guido van Rossum47374822007-08-02 16:48:17 +00002545}
2546
Tim Peters6d6c1a32001-08-02 04:15:00 +00002547static PyMethodDef type_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002548 {"mro", (PyCFunction)mro_external, METH_NOARGS,
2549 PyDoc_STR("mro() -> list\nreturn a type's method resolution order")},
2550 {"__subclasses__", (PyCFunction)type_subclasses, METH_NOARGS,
2551 PyDoc_STR("__subclasses__() -> list of immediate subclasses")},
2552 {"__prepare__", (PyCFunction)type_prepare,
2553 METH_VARARGS | METH_KEYWORDS | METH_CLASS,
2554 PyDoc_STR("__prepare__() -> dict\n"
2555 "used to create the namespace for the class statement")},
2556 {"__instancecheck__", type___instancecheck__, METH_O,
2557 PyDoc_STR("__instancecheck__() -> check if an object is an instance")},
2558 {"__subclasscheck__", type___subclasscheck__, METH_O,
Alexander Belopolsky977a6842010-08-16 20:17:07 +00002559 PyDoc_STR("__subclasscheck__() -> check if a class is a subclass")},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002560 {0}
Tim Peters6d6c1a32001-08-02 04:15:00 +00002561};
2562
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002563PyDoc_STRVAR(type_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00002564"type(object) -> the object's type\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002565"type(name, bases, dict) -> a new type");
Tim Peters6d6c1a32001-08-02 04:15:00 +00002566
Guido van Rossum048eb752001-10-02 21:24:57 +00002567static int
2568type_traverse(PyTypeObject *type, visitproc visit, void *arg)
2569{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002570 /* Because of type_is_gc(), the collector only calls this
2571 for heaptypes. */
2572 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002573
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002574 Py_VISIT(type->tp_dict);
2575 Py_VISIT(type->tp_cache);
2576 Py_VISIT(type->tp_mro);
2577 Py_VISIT(type->tp_bases);
2578 Py_VISIT(type->tp_base);
Guido van Rossuma3862092002-06-10 15:24:42 +00002579
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002580 /* There's no need to visit type->tp_subclasses or
2581 ((PyHeapTypeObject *)type)->ht_slots, because they can't be involved
2582 in cycles; tp_subclasses is a list of weak references,
2583 and slots is a tuple of strings. */
Guido van Rossum048eb752001-10-02 21:24:57 +00002584
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002585 return 0;
Guido van Rossum048eb752001-10-02 21:24:57 +00002586}
2587
2588static int
2589type_clear(PyTypeObject *type)
2590{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002591 /* Because of type_is_gc(), the collector only calls this
2592 for heaptypes. */
2593 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002594
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002595 /* The only field we need to clear is tp_mro, which is part of a
2596 hard cycle (its first element is the class itself) that won't
2597 be broken otherwise (it's a tuple and tuples don't have a
2598 tp_clear handler). None of the other fields need to be
2599 cleared, and here's why:
Guido van Rossum048eb752001-10-02 21:24:57 +00002600
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002601 tp_dict:
2602 It is a dict, so the collector will call its tp_clear.
Guido van Rossuma3862092002-06-10 15:24:42 +00002603
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002604 tp_cache:
2605 Not used; if it were, it would be a dict.
Guido van Rossuma3862092002-06-10 15:24:42 +00002606
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002607 tp_bases, tp_base:
2608 If these are involved in a cycle, there must be at least
2609 one other, mutable object in the cycle, e.g. a base
2610 class's dict; the cycle will be broken that way.
Guido van Rossuma3862092002-06-10 15:24:42 +00002611
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002612 tp_subclasses:
2613 A list of weak references can't be part of a cycle; and
2614 lists have their own tp_clear.
Guido van Rossuma3862092002-06-10 15:24:42 +00002615
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002616 slots (in PyHeapTypeObject):
2617 A tuple of strings can't be part of a cycle.
2618 */
Guido van Rossuma3862092002-06-10 15:24:42 +00002619
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002620 Py_CLEAR(type->tp_mro);
Guido van Rossum048eb752001-10-02 21:24:57 +00002621
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002622 return 0;
Guido van Rossum048eb752001-10-02 21:24:57 +00002623}
2624
2625static int
2626type_is_gc(PyTypeObject *type)
2627{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002628 return type->tp_flags & Py_TPFLAGS_HEAPTYPE;
Guido van Rossum048eb752001-10-02 21:24:57 +00002629}
2630
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002631PyTypeObject PyType_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002632 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2633 "type", /* tp_name */
2634 sizeof(PyHeapTypeObject), /* tp_basicsize */
2635 sizeof(PyMemberDef), /* tp_itemsize */
2636 (destructor)type_dealloc, /* tp_dealloc */
2637 0, /* tp_print */
2638 0, /* tp_getattr */
2639 0, /* tp_setattr */
2640 0, /* tp_reserved */
2641 (reprfunc)type_repr, /* tp_repr */
2642 0, /* tp_as_number */
2643 0, /* tp_as_sequence */
2644 0, /* tp_as_mapping */
2645 0, /* tp_hash */
2646 (ternaryfunc)type_call, /* tp_call */
2647 0, /* tp_str */
2648 (getattrofunc)type_getattro, /* tp_getattro */
2649 (setattrofunc)type_setattro, /* tp_setattro */
2650 0, /* tp_as_buffer */
2651 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
2652 Py_TPFLAGS_BASETYPE | Py_TPFLAGS_TYPE_SUBCLASS, /* tp_flags */
2653 type_doc, /* tp_doc */
2654 (traverseproc)type_traverse, /* tp_traverse */
2655 (inquiry)type_clear, /* tp_clear */
2656 0, /* tp_richcompare */
2657 offsetof(PyTypeObject, tp_weaklist), /* tp_weaklistoffset */
2658 0, /* tp_iter */
2659 0, /* tp_iternext */
2660 type_methods, /* tp_methods */
2661 type_members, /* tp_members */
2662 type_getsets, /* tp_getset */
2663 0, /* tp_base */
2664 0, /* tp_dict */
2665 0, /* tp_descr_get */
2666 0, /* tp_descr_set */
2667 offsetof(PyTypeObject, tp_dict), /* tp_dictoffset */
2668 type_init, /* tp_init */
2669 0, /* tp_alloc */
2670 type_new, /* tp_new */
2671 PyObject_GC_Del, /* tp_free */
2672 (inquiry)type_is_gc, /* tp_is_gc */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002673};
Tim Peters6d6c1a32001-08-02 04:15:00 +00002674
2675
2676/* The base type of all types (eventually)... except itself. */
2677
Guido van Rossumd8faa362007-04-27 19:54:29 +00002678/* You may wonder why object.__new__() only complains about arguments
2679 when object.__init__() is not overridden, and vice versa.
2680
2681 Consider the use cases:
2682
2683 1. When neither is overridden, we want to hear complaints about
2684 excess (i.e., any) arguments, since their presence could
2685 indicate there's a bug.
2686
2687 2. When defining an Immutable type, we are likely to override only
2688 __new__(), since __init__() is called too late to initialize an
2689 Immutable object. Since __new__() defines the signature for the
2690 type, it would be a pain to have to override __init__() just to
2691 stop it from complaining about excess arguments.
2692
2693 3. When defining a Mutable type, we are likely to override only
2694 __init__(). So here the converse reasoning applies: we don't
2695 want to have to override __new__() just to stop it from
2696 complaining.
2697
2698 4. When __init__() is overridden, and the subclass __init__() calls
2699 object.__init__(), the latter should complain about excess
2700 arguments; ditto for __new__().
2701
2702 Use cases 2 and 3 make it unattractive to unconditionally check for
2703 excess arguments. The best solution that addresses all four use
2704 cases is as follows: __init__() complains about excess arguments
2705 unless __new__() is overridden and __init__() is not overridden
2706 (IOW, if __init__() is overridden or __new__() is not overridden);
2707 symmetrically, __new__() complains about excess arguments unless
2708 __init__() is overridden and __new__() is not overridden
2709 (IOW, if __new__() is overridden or __init__() is not overridden).
2710
2711 However, for backwards compatibility, this breaks too much code.
2712 Therefore, in 2.6, we'll *warn* about excess arguments when both
2713 methods are overridden; for all other cases we'll use the above
2714 rules.
2715
2716*/
2717
2718/* Forward */
2719static PyObject *
2720object_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
2721
2722static int
2723excess_args(PyObject *args, PyObject *kwds)
2724{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002725 return PyTuple_GET_SIZE(args) ||
2726 (kwds && PyDict_Check(kwds) && PyDict_Size(kwds));
Guido van Rossumd8faa362007-04-27 19:54:29 +00002727}
2728
Tim Peters6d6c1a32001-08-02 04:15:00 +00002729static int
2730object_init(PyObject *self, PyObject *args, PyObject *kwds)
2731{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002732 int err = 0;
2733 if (excess_args(args, kwds)) {
2734 PyTypeObject *type = Py_TYPE(self);
2735 if (type->tp_init != object_init &&
2736 type->tp_new != object_new)
2737 {
2738 err = PyErr_WarnEx(PyExc_DeprecationWarning,
2739 "object.__init__() takes no parameters",
2740 1);
2741 }
2742 else if (type->tp_init != object_init ||
2743 type->tp_new == object_new)
2744 {
2745 PyErr_SetString(PyExc_TypeError,
2746 "object.__init__() takes no parameters");
2747 err = -1;
2748 }
2749 }
2750 return err;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002751}
2752
Guido van Rossum298e4212003-02-13 16:30:16 +00002753static PyObject *
2754object_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2755{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002756 int err = 0;
2757 if (excess_args(args, kwds)) {
2758 if (type->tp_new != object_new &&
2759 type->tp_init != object_init)
2760 {
2761 err = PyErr_WarnEx(PyExc_DeprecationWarning,
2762 "object.__new__() takes no parameters",
2763 1);
2764 }
2765 else if (type->tp_new != object_new ||
2766 type->tp_init == object_init)
2767 {
2768 PyErr_SetString(PyExc_TypeError,
2769 "object.__new__() takes no parameters");
2770 err = -1;
2771 }
2772 }
2773 if (err < 0)
2774 return NULL;
Christian Heimes9e7f1d22008-02-28 12:27:11 +00002775
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002776 if (type->tp_flags & Py_TPFLAGS_IS_ABSTRACT) {
2777 static PyObject *comma = NULL;
2778 PyObject *abstract_methods = NULL;
2779 PyObject *builtins;
2780 PyObject *sorted;
2781 PyObject *sorted_methods = NULL;
2782 PyObject *joined = NULL;
Christian Heimes9e7f1d22008-02-28 12:27:11 +00002783
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002784 /* Compute ", ".join(sorted(type.__abstractmethods__))
2785 into joined. */
2786 abstract_methods = type_abstractmethods(type, NULL);
2787 if (abstract_methods == NULL)
2788 goto error;
2789 builtins = PyEval_GetBuiltins();
2790 if (builtins == NULL)
2791 goto error;
2792 sorted = PyDict_GetItemString(builtins, "sorted");
2793 if (sorted == NULL)
2794 goto error;
2795 sorted_methods = PyObject_CallFunctionObjArgs(sorted,
2796 abstract_methods,
2797 NULL);
2798 if (sorted_methods == NULL)
2799 goto error;
2800 if (comma == NULL) {
2801 comma = PyUnicode_InternFromString(", ");
2802 if (comma == NULL)
2803 goto error;
2804 }
2805 joined = PyObject_CallMethod(comma, "join",
2806 "O", sorted_methods);
2807 if (joined == NULL)
2808 goto error;
Christian Heimes9e7f1d22008-02-28 12:27:11 +00002809
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002810 PyErr_Format(PyExc_TypeError,
2811 "Can't instantiate abstract class %s "
2812 "with abstract methods %U",
2813 type->tp_name,
2814 joined);
2815 error:
2816 Py_XDECREF(joined);
2817 Py_XDECREF(sorted_methods);
2818 Py_XDECREF(abstract_methods);
2819 return NULL;
2820 }
2821 return type->tp_alloc(type, 0);
Guido van Rossum298e4212003-02-13 16:30:16 +00002822}
2823
Tim Peters6d6c1a32001-08-02 04:15:00 +00002824static void
2825object_dealloc(PyObject *self)
2826{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002827 Py_TYPE(self)->tp_free(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002828}
2829
Guido van Rossum8e248182001-08-12 05:17:56 +00002830static PyObject *
2831object_repr(PyObject *self)
2832{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002833 PyTypeObject *type;
2834 PyObject *mod, *name, *rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00002835
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002836 type = Py_TYPE(self);
2837 mod = type_module(type, NULL);
2838 if (mod == NULL)
2839 PyErr_Clear();
2840 else if (!PyUnicode_Check(mod)) {
2841 Py_DECREF(mod);
2842 mod = NULL;
2843 }
2844 name = type_name(type, NULL);
2845 if (name == NULL)
2846 return NULL;
2847 if (mod != NULL && PyUnicode_CompareWithASCIIString(mod, "builtins"))
2848 rtn = PyUnicode_FromFormat("<%U.%U object at %p>", mod, name, self);
2849 else
2850 rtn = PyUnicode_FromFormat("<%s object at %p>",
2851 type->tp_name, self);
2852 Py_XDECREF(mod);
2853 Py_DECREF(name);
2854 return rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00002855}
2856
Guido van Rossumb8f63662001-08-15 23:57:02 +00002857static PyObject *
2858object_str(PyObject *self)
2859{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002860 unaryfunc f;
Guido van Rossumb8f63662001-08-15 23:57:02 +00002861
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002862 f = Py_TYPE(self)->tp_repr;
2863 if (f == NULL)
2864 f = object_repr;
2865 return f(self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002866}
2867
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002868static PyObject *
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002869object_richcompare(PyObject *self, PyObject *other, int op)
2870{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002871 PyObject *res;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002872
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002873 switch (op) {
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002874
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002875 case Py_EQ:
2876 /* Return NotImplemented instead of False, so if two
2877 objects are compared, both get a chance at the
2878 comparison. See issue #1393. */
2879 res = (self == other) ? Py_True : Py_NotImplemented;
2880 Py_INCREF(res);
2881 break;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002882
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002883 case Py_NE:
2884 /* By default, != returns the opposite of ==,
2885 unless the latter returns NotImplemented. */
2886 res = PyObject_RichCompare(self, other, Py_EQ);
2887 if (res != NULL && res != Py_NotImplemented) {
2888 int ok = PyObject_IsTrue(res);
2889 Py_DECREF(res);
2890 if (ok < 0)
2891 res = NULL;
2892 else {
2893 if (ok)
2894 res = Py_False;
2895 else
2896 res = Py_True;
2897 Py_INCREF(res);
2898 }
2899 }
2900 break;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002901
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002902 default:
2903 res = Py_NotImplemented;
2904 Py_INCREF(res);
2905 break;
2906 }
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002907
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002908 return res;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002909}
2910
2911static PyObject *
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002912object_get_class(PyObject *self, void *closure)
2913{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002914 Py_INCREF(Py_TYPE(self));
2915 return (PyObject *)(Py_TYPE(self));
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002916}
2917
2918static int
2919equiv_structs(PyTypeObject *a, PyTypeObject *b)
2920{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002921 return a == b ||
2922 (a != NULL &&
2923 b != NULL &&
2924 a->tp_basicsize == b->tp_basicsize &&
2925 a->tp_itemsize == b->tp_itemsize &&
2926 a->tp_dictoffset == b->tp_dictoffset &&
2927 a->tp_weaklistoffset == b->tp_weaklistoffset &&
2928 ((a->tp_flags & Py_TPFLAGS_HAVE_GC) ==
2929 (b->tp_flags & Py_TPFLAGS_HAVE_GC)));
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002930}
2931
2932static int
2933same_slots_added(PyTypeObject *a, PyTypeObject *b)
2934{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002935 PyTypeObject *base = a->tp_base;
2936 Py_ssize_t size;
2937 PyObject *slots_a, *slots_b;
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002938
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002939 if (base != b->tp_base)
2940 return 0;
2941 if (equiv_structs(a, base) && equiv_structs(b, base))
2942 return 1;
2943 size = base->tp_basicsize;
2944 if (a->tp_dictoffset == size && b->tp_dictoffset == size)
2945 size += sizeof(PyObject *);
2946 if (a->tp_weaklistoffset == size && b->tp_weaklistoffset == size)
2947 size += sizeof(PyObject *);
Guido van Rossumd8faa362007-04-27 19:54:29 +00002948
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002949 /* Check slots compliance */
2950 slots_a = ((PyHeapTypeObject *)a)->ht_slots;
2951 slots_b = ((PyHeapTypeObject *)b)->ht_slots;
2952 if (slots_a && slots_b) {
2953 if (PyObject_RichCompareBool(slots_a, slots_b, Py_EQ) != 1)
2954 return 0;
2955 size += sizeof(PyObject *) * PyTuple_GET_SIZE(slots_a);
2956 }
2957 return size == a->tp_basicsize && size == b->tp_basicsize;
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002958}
2959
2960static int
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002961compatible_for_assignment(PyTypeObject* oldto, PyTypeObject* newto, char* attr)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002962{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002963 PyTypeObject *newbase, *oldbase;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002964
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002965 if (newto->tp_dealloc != oldto->tp_dealloc ||
2966 newto->tp_free != oldto->tp_free)
2967 {
2968 PyErr_Format(PyExc_TypeError,
2969 "%s assignment: "
2970 "'%s' deallocator differs from '%s'",
2971 attr,
2972 newto->tp_name,
2973 oldto->tp_name);
2974 return 0;
2975 }
2976 newbase = newto;
2977 oldbase = oldto;
2978 while (equiv_structs(newbase, newbase->tp_base))
2979 newbase = newbase->tp_base;
2980 while (equiv_structs(oldbase, oldbase->tp_base))
2981 oldbase = oldbase->tp_base;
2982 if (newbase != oldbase &&
2983 (newbase->tp_base != oldbase->tp_base ||
2984 !same_slots_added(newbase, oldbase))) {
2985 PyErr_Format(PyExc_TypeError,
2986 "%s assignment: "
2987 "'%s' object layout differs from '%s'",
2988 attr,
2989 newto->tp_name,
2990 oldto->tp_name);
2991 return 0;
2992 }
Tim Petersea7f75d2002-12-07 21:39:16 +00002993
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002994 return 1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002995}
2996
2997static int
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002998object_set_class(PyObject *self, PyObject *value, void *closure)
2999{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003000 PyTypeObject *oldto = Py_TYPE(self);
3001 PyTypeObject *newto;
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003002
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003003 if (value == NULL) {
3004 PyErr_SetString(PyExc_TypeError,
3005 "can't delete __class__ attribute");
3006 return -1;
3007 }
3008 if (!PyType_Check(value)) {
3009 PyErr_Format(PyExc_TypeError,
3010 "__class__ must be set to new-style class, not '%s' object",
3011 Py_TYPE(value)->tp_name);
3012 return -1;
3013 }
3014 newto = (PyTypeObject *)value;
3015 if (!(newto->tp_flags & Py_TPFLAGS_HEAPTYPE) ||
3016 !(oldto->tp_flags & Py_TPFLAGS_HEAPTYPE))
3017 {
3018 PyErr_Format(PyExc_TypeError,
3019 "__class__ assignment: only for heap types");
3020 return -1;
3021 }
3022 if (compatible_for_assignment(newto, oldto, "__class__")) {
3023 Py_INCREF(newto);
3024 Py_TYPE(self) = newto;
3025 Py_DECREF(oldto);
3026 return 0;
3027 }
3028 else {
3029 return -1;
3030 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003031}
3032
3033static PyGetSetDef object_getsets[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003034 {"__class__", object_get_class, object_set_class,
3035 PyDoc_STR("the object's class")},
3036 {0}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003037};
3038
Guido van Rossumc53f0092003-02-18 22:05:12 +00003039
Guido van Rossum036f9992003-02-21 22:02:54 +00003040/* Stuff to implement __reduce_ex__ for pickle protocols >= 2.
Alexandre Vassalottif7fa63d2008-05-11 08:55:36 +00003041 We fall back to helpers in copyreg for:
Guido van Rossum036f9992003-02-21 22:02:54 +00003042 - pickle protocols < 2
3043 - calculating the list of slot names (done only once per class)
3044 - the __newobj__ function (which is used as a token but never called)
3045*/
3046
3047static PyObject *
Alexandre Vassalottif7fa63d2008-05-11 08:55:36 +00003048import_copyreg(void)
Guido van Rossum036f9992003-02-21 22:02:54 +00003049{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003050 static PyObject *copyreg_str;
Guido van Rossum3926a632001-09-25 16:25:58 +00003051
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003052 if (!copyreg_str) {
3053 copyreg_str = PyUnicode_InternFromString("copyreg");
3054 if (copyreg_str == NULL)
3055 return NULL;
3056 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003057
Antoine Pitrouff150f22010-10-22 21:41:05 +00003058 return PyImport_Import(copyreg_str);
Guido van Rossum036f9992003-02-21 22:02:54 +00003059}
3060
3061static PyObject *
3062slotnames(PyObject *cls)
3063{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003064 PyObject *clsdict;
3065 PyObject *copyreg;
3066 PyObject *slotnames;
Guido van Rossum036f9992003-02-21 22:02:54 +00003067
Antoine Pitrouff150f22010-10-22 21:41:05 +00003068 if (!PyType_Check(cls)) {
3069 Py_INCREF(Py_None);
3070 return Py_None;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003071 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003072
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003073 clsdict = ((PyTypeObject *)cls)->tp_dict;
Antoine Pitrouff150f22010-10-22 21:41:05 +00003074 slotnames = PyDict_GetItemString(clsdict, "__slotnames__");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003075 if (slotnames != NULL && PyList_Check(slotnames)) {
3076 Py_INCREF(slotnames);
3077 return slotnames;
3078 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003079
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003080 copyreg = import_copyreg();
3081 if (copyreg == NULL)
3082 return NULL;
Guido van Rossum036f9992003-02-21 22:02:54 +00003083
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003084 slotnames = PyObject_CallMethod(copyreg, "_slotnames", "O", cls);
3085 Py_DECREF(copyreg);
3086 if (slotnames != NULL &&
3087 slotnames != Py_None &&
3088 !PyList_Check(slotnames))
3089 {
3090 PyErr_SetString(PyExc_TypeError,
3091 "copyreg._slotnames didn't return a list or None");
3092 Py_DECREF(slotnames);
3093 slotnames = NULL;
3094 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003095
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003096 return slotnames;
Guido van Rossum036f9992003-02-21 22:02:54 +00003097}
3098
3099static PyObject *
3100reduce_2(PyObject *obj)
3101{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003102 PyObject *cls, *getnewargs;
3103 PyObject *args = NULL, *args2 = NULL;
3104 PyObject *getstate = NULL, *state = NULL, *names = NULL;
3105 PyObject *slots = NULL, *listitems = NULL, *dictitems = NULL;
3106 PyObject *copyreg = NULL, *newobj = NULL, *res = NULL;
3107 Py_ssize_t i, n;
Guido van Rossum036f9992003-02-21 22:02:54 +00003108
Antoine Pitrouff150f22010-10-22 21:41:05 +00003109 cls = PyObject_GetAttrString(obj, "__class__");
3110 if (cls == NULL)
3111 return NULL;
Guido van Rossum036f9992003-02-21 22:02:54 +00003112
Antoine Pitrouff150f22010-10-22 21:41:05 +00003113 getnewargs = PyObject_GetAttrString(obj, "__getnewargs__");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003114 if (getnewargs != NULL) {
3115 args = PyObject_CallObject(getnewargs, NULL);
3116 Py_DECREF(getnewargs);
3117 if (args != NULL && !PyTuple_Check(args)) {
3118 PyErr_Format(PyExc_TypeError,
3119 "__getnewargs__ should return a tuple, "
3120 "not '%.200s'", Py_TYPE(args)->tp_name);
3121 goto end;
3122 }
3123 }
3124 else {
3125 PyErr_Clear();
3126 args = PyTuple_New(0);
3127 }
3128 if (args == NULL)
3129 goto end;
Guido van Rossum036f9992003-02-21 22:02:54 +00003130
Antoine Pitrouff150f22010-10-22 21:41:05 +00003131 getstate = PyObject_GetAttrString(obj, "__getstate__");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003132 if (getstate != NULL) {
3133 state = PyObject_CallObject(getstate, NULL);
3134 Py_DECREF(getstate);
3135 if (state == NULL)
3136 goto end;
3137 }
3138 else {
3139 PyErr_Clear();
Antoine Pitrouff150f22010-10-22 21:41:05 +00003140 state = PyObject_GetAttrString(obj, "__dict__");
3141 if (state == NULL) {
3142 PyErr_Clear();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003143 state = Py_None;
Antoine Pitrouff150f22010-10-22 21:41:05 +00003144 Py_INCREF(state);
3145 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003146 names = slotnames(cls);
3147 if (names == NULL)
3148 goto end;
Antoine Pitrouff150f22010-10-22 21:41:05 +00003149 if (names != Py_None) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003150 assert(PyList_Check(names));
3151 slots = PyDict_New();
3152 if (slots == NULL)
3153 goto end;
3154 n = 0;
3155 /* Can't pre-compute the list size; the list
3156 is stored on the class so accessible to other
3157 threads, which may be run by DECREF */
3158 for (i = 0; i < PyList_GET_SIZE(names); i++) {
3159 PyObject *name, *value;
3160 name = PyList_GET_ITEM(names, i);
3161 value = PyObject_GetAttr(obj, name);
3162 if (value == NULL)
3163 PyErr_Clear();
3164 else {
3165 int err = PyDict_SetItem(slots, name,
3166 value);
3167 Py_DECREF(value);
3168 if (err)
3169 goto end;
3170 n++;
3171 }
3172 }
3173 if (n) {
3174 state = Py_BuildValue("(NO)", state, slots);
3175 if (state == NULL)
3176 goto end;
3177 }
3178 }
3179 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003180
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003181 if (!PyList_Check(obj)) {
3182 listitems = Py_None;
3183 Py_INCREF(listitems);
3184 }
3185 else {
3186 listitems = PyObject_GetIter(obj);
3187 if (listitems == NULL)
3188 goto end;
3189 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003190
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003191 if (!PyDict_Check(obj)) {
3192 dictitems = Py_None;
3193 Py_INCREF(dictitems);
3194 }
3195 else {
3196 PyObject *items = PyObject_CallMethod(obj, "items", "");
3197 if (items == NULL)
3198 goto end;
3199 dictitems = PyObject_GetIter(items);
3200 Py_DECREF(items);
3201 if (dictitems == NULL)
3202 goto end;
3203 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003204
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003205 copyreg = import_copyreg();
3206 if (copyreg == NULL)
3207 goto end;
Antoine Pitrouff150f22010-10-22 21:41:05 +00003208 newobj = PyObject_GetAttrString(copyreg, "__newobj__");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003209 if (newobj == NULL)
3210 goto end;
Guido van Rossum036f9992003-02-21 22:02:54 +00003211
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003212 n = PyTuple_GET_SIZE(args);
3213 args2 = PyTuple_New(n+1);
3214 if (args2 == NULL)
3215 goto end;
3216 PyTuple_SET_ITEM(args2, 0, cls);
Antoine Pitrouff150f22010-10-22 21:41:05 +00003217 cls = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003218 for (i = 0; i < n; i++) {
3219 PyObject *v = PyTuple_GET_ITEM(args, i);
3220 Py_INCREF(v);
3221 PyTuple_SET_ITEM(args2, i+1, v);
3222 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003223
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003224 res = PyTuple_Pack(5, newobj, args2, state, listitems, dictitems);
Guido van Rossum036f9992003-02-21 22:02:54 +00003225
3226 end:
Antoine Pitrouff150f22010-10-22 21:41:05 +00003227 Py_XDECREF(cls);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003228 Py_XDECREF(args);
3229 Py_XDECREF(args2);
3230 Py_XDECREF(slots);
3231 Py_XDECREF(state);
3232 Py_XDECREF(names);
3233 Py_XDECREF(listitems);
3234 Py_XDECREF(dictitems);
3235 Py_XDECREF(copyreg);
3236 Py_XDECREF(newobj);
3237 return res;
Guido van Rossum036f9992003-02-21 22:02:54 +00003238}
3239
Guido van Rossumd8faa362007-04-27 19:54:29 +00003240/*
3241 * There were two problems when object.__reduce__ and object.__reduce_ex__
3242 * were implemented in the same function:
3243 * - trying to pickle an object with a custom __reduce__ method that
3244 * fell back to object.__reduce__ in certain circumstances led to
3245 * infinite recursion at Python level and eventual RuntimeError.
3246 * - Pickling objects that lied about their type by overwriting the
3247 * __class__ descriptor could lead to infinite recursion at C level
3248 * and eventual segfault.
3249 *
3250 * Because of backwards compatibility, the two methods still have to
3251 * behave in the same way, even if this is not required by the pickle
3252 * protocol. This common functionality was moved to the _common_reduce
3253 * function.
3254 */
3255static PyObject *
3256_common_reduce(PyObject *self, int proto)
3257{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003258 PyObject *copyreg, *res;
Guido van Rossumd8faa362007-04-27 19:54:29 +00003259
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003260 if (proto >= 2)
3261 return reduce_2(self);
Guido van Rossumd8faa362007-04-27 19:54:29 +00003262
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003263 copyreg = import_copyreg();
3264 if (!copyreg)
3265 return NULL;
Guido van Rossumd8faa362007-04-27 19:54:29 +00003266
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003267 res = PyEval_CallMethod(copyreg, "_reduce_ex", "(Oi)", self, proto);
3268 Py_DECREF(copyreg);
Guido van Rossumd8faa362007-04-27 19:54:29 +00003269
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003270 return res;
Guido van Rossumd8faa362007-04-27 19:54:29 +00003271}
3272
3273static PyObject *
3274object_reduce(PyObject *self, PyObject *args)
3275{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003276 int proto = 0;
Guido van Rossumd8faa362007-04-27 19:54:29 +00003277
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003278 if (!PyArg_ParseTuple(args, "|i:__reduce__", &proto))
3279 return NULL;
Guido van Rossumd8faa362007-04-27 19:54:29 +00003280
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003281 return _common_reduce(self, proto);
Guido van Rossumd8faa362007-04-27 19:54:29 +00003282}
3283
Guido van Rossum036f9992003-02-21 22:02:54 +00003284static PyObject *
3285object_reduce_ex(PyObject *self, PyObject *args)
3286{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003287 PyObject *reduce, *res;
3288 int proto = 0;
Guido van Rossum036f9992003-02-21 22:02:54 +00003289
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003290 if (!PyArg_ParseTuple(args, "|i:__reduce_ex__", &proto))
3291 return NULL;
Guido van Rossum036f9992003-02-21 22:02:54 +00003292
Antoine Pitrouff150f22010-10-22 21:41:05 +00003293 reduce = PyObject_GetAttrString(self, "__reduce__");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003294 if (reduce == NULL)
3295 PyErr_Clear();
3296 else {
Antoine Pitrouff150f22010-10-22 21:41:05 +00003297 PyObject *cls, *clsreduce, *objreduce;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003298 int override;
Antoine Pitrouff150f22010-10-22 21:41:05 +00003299 cls = PyObject_GetAttrString(self, "__class__");
3300 if (cls == NULL) {
3301 Py_DECREF(reduce);
3302 return NULL;
3303 }
3304 clsreduce = PyObject_GetAttrString(cls, "__reduce__");
3305 Py_DECREF(cls);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003306 if (clsreduce == NULL) {
3307 Py_DECREF(reduce);
3308 return NULL;
3309 }
Antoine Pitrouff150f22010-10-22 21:41:05 +00003310 objreduce = PyDict_GetItemString(PyBaseObject_Type.tp_dict,
3311 "__reduce__");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003312 override = (clsreduce != objreduce);
3313 Py_DECREF(clsreduce);
3314 if (override) {
3315 res = PyObject_CallObject(reduce, NULL);
3316 Py_DECREF(reduce);
3317 return res;
3318 }
3319 else
3320 Py_DECREF(reduce);
3321 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003322
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003323 return _common_reduce(self, proto);
Guido van Rossum3926a632001-09-25 16:25:58 +00003324}
3325
Christian Heimes9e7f1d22008-02-28 12:27:11 +00003326static PyObject *
3327object_subclasshook(PyObject *cls, PyObject *args)
3328{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003329 Py_INCREF(Py_NotImplemented);
3330 return Py_NotImplemented;
Christian Heimes9e7f1d22008-02-28 12:27:11 +00003331}
3332
3333PyDoc_STRVAR(object_subclasshook_doc,
3334"Abstract classes can override this to customize issubclass().\n"
3335"\n"
3336"This is invoked early on by abc.ABCMeta.__subclasscheck__().\n"
3337"It should return True, False or NotImplemented. If it returns\n"
3338"NotImplemented, the normal algorithm is used. Otherwise, it\n"
3339"overrides the normal algorithm (and the outcome is cached).\n");
Eric Smith8c663262007-08-25 02:26:07 +00003340
3341/*
3342 from PEP 3101, this code implements:
3343
3344 class object:
3345 def __format__(self, format_spec):
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003346 return format(str(self), format_spec)
Eric Smith8c663262007-08-25 02:26:07 +00003347*/
3348static PyObject *
3349object_format(PyObject *self, PyObject *args)
3350{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003351 PyObject *format_spec;
3352 PyObject *self_as_str = NULL;
3353 PyObject *result = NULL;
Eric Smith8c663262007-08-25 02:26:07 +00003354
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003355 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
3356 return NULL;
Eric Smith8c663262007-08-25 02:26:07 +00003357
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003358 self_as_str = PyObject_Str(self);
Eric Smithe4d63172010-09-13 20:48:43 +00003359 if (self_as_str != NULL) {
3360 /* Issue 7994: If we're converting to a string, we
3361 should reject format specifications */
3362 if (PyUnicode_GET_SIZE(format_spec) > 0) {
3363 if (PyErr_WarnEx(PyExc_PendingDeprecationWarning,
3364 "object.__format__ with a non-empty format "
3365 "string is deprecated", 1) < 0) {
3366 goto done;
3367 }
3368 /* Eventually this will become an error:
3369 PyErr_Format(PyExc_TypeError,
3370 "non-empty format string passed to object.__format__");
3371 goto done;
3372 */
3373 }
Eric Smith8c663262007-08-25 02:26:07 +00003374
Eric Smithe4d63172010-09-13 20:48:43 +00003375 result = PyObject_Format(self_as_str, format_spec);
3376 }
3377
3378done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003379 Py_XDECREF(self_as_str);
Eric Smith8c663262007-08-25 02:26:07 +00003380
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003381 return result;
Eric Smith8c663262007-08-25 02:26:07 +00003382}
3383
Martin v. Löwis00709aa2008-06-04 14:18:43 +00003384static PyObject *
3385object_sizeof(PyObject *self, PyObject *args)
3386{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003387 Py_ssize_t res, isize;
Martin v. Löwis00709aa2008-06-04 14:18:43 +00003388
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003389 res = 0;
3390 isize = self->ob_type->tp_itemsize;
3391 if (isize > 0)
3392 res = Py_SIZE(self->ob_type) * isize;
3393 res += self->ob_type->tp_basicsize;
Martin v. Löwis00709aa2008-06-04 14:18:43 +00003394
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003395 return PyLong_FromSsize_t(res);
Martin v. Löwis00709aa2008-06-04 14:18:43 +00003396}
3397
Guido van Rossum3926a632001-09-25 16:25:58 +00003398static PyMethodDef object_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003399 {"__reduce_ex__", object_reduce_ex, METH_VARARGS,
3400 PyDoc_STR("helper for pickle")},
3401 {"__reduce__", object_reduce, METH_VARARGS,
3402 PyDoc_STR("helper for pickle")},
3403 {"__subclasshook__", object_subclasshook, METH_CLASS | METH_VARARGS,
3404 object_subclasshook_doc},
3405 {"__format__", object_format, METH_VARARGS,
3406 PyDoc_STR("default object formatter")},
3407 {"__sizeof__", object_sizeof, METH_NOARGS,
3408 PyDoc_STR("__sizeof__() -> size of object in memory, in bytes")},
3409 {0}
Guido van Rossum3926a632001-09-25 16:25:58 +00003410};
3411
Guido van Rossum036f9992003-02-21 22:02:54 +00003412
Tim Peters6d6c1a32001-08-02 04:15:00 +00003413PyTypeObject PyBaseObject_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003414 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3415 "object", /* tp_name */
3416 sizeof(PyObject), /* tp_basicsize */
3417 0, /* tp_itemsize */
3418 object_dealloc, /* tp_dealloc */
3419 0, /* tp_print */
3420 0, /* tp_getattr */
3421 0, /* tp_setattr */
3422 0, /* tp_reserved */
3423 object_repr, /* tp_repr */
3424 0, /* tp_as_number */
3425 0, /* tp_as_sequence */
3426 0, /* tp_as_mapping */
3427 (hashfunc)_Py_HashPointer, /* tp_hash */
3428 0, /* tp_call */
3429 object_str, /* tp_str */
3430 PyObject_GenericGetAttr, /* tp_getattro */
3431 PyObject_GenericSetAttr, /* tp_setattro */
3432 0, /* tp_as_buffer */
3433 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
3434 PyDoc_STR("The most base type"), /* tp_doc */
3435 0, /* tp_traverse */
3436 0, /* tp_clear */
3437 object_richcompare, /* tp_richcompare */
3438 0, /* tp_weaklistoffset */
3439 0, /* tp_iter */
3440 0, /* tp_iternext */
3441 object_methods, /* tp_methods */
3442 0, /* tp_members */
3443 object_getsets, /* tp_getset */
3444 0, /* tp_base */
3445 0, /* tp_dict */
3446 0, /* tp_descr_get */
3447 0, /* tp_descr_set */
3448 0, /* tp_dictoffset */
3449 object_init, /* tp_init */
3450 PyType_GenericAlloc, /* tp_alloc */
3451 object_new, /* tp_new */
3452 PyObject_Del, /* tp_free */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003453};
3454
3455
Guido van Rossum50e9fb92006-08-17 05:42:55 +00003456/* Add the methods from tp_methods to the __dict__ in a type object */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003457
3458static int
3459add_methods(PyTypeObject *type, PyMethodDef *meth)
3460{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003461 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003462
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003463 for (; meth->ml_name != NULL; meth++) {
3464 PyObject *descr;
3465 if (PyDict_GetItemString(dict, meth->ml_name) &&
3466 !(meth->ml_flags & METH_COEXIST))
3467 continue;
3468 if (meth->ml_flags & METH_CLASS) {
3469 if (meth->ml_flags & METH_STATIC) {
3470 PyErr_SetString(PyExc_ValueError,
3471 "method cannot be both class and static");
3472 return -1;
3473 }
3474 descr = PyDescr_NewClassMethod(type, meth);
3475 }
3476 else if (meth->ml_flags & METH_STATIC) {
3477 PyObject *cfunc = PyCFunction_New(meth, NULL);
3478 if (cfunc == NULL)
3479 return -1;
3480 descr = PyStaticMethod_New(cfunc);
3481 Py_DECREF(cfunc);
3482 }
3483 else {
3484 descr = PyDescr_NewMethod(type, meth);
3485 }
3486 if (descr == NULL)
3487 return -1;
3488 if (PyDict_SetItemString(dict, meth->ml_name, descr) < 0)
3489 return -1;
3490 Py_DECREF(descr);
3491 }
3492 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003493}
3494
3495static int
Guido van Rossum6f799372001-09-20 20:46:19 +00003496add_members(PyTypeObject *type, PyMemberDef *memb)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003497{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003498 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003499
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003500 for (; memb->name != NULL; memb++) {
3501 PyObject *descr;
3502 if (PyDict_GetItemString(dict, memb->name))
3503 continue;
3504 descr = PyDescr_NewMember(type, memb);
3505 if (descr == NULL)
3506 return -1;
3507 if (PyDict_SetItemString(dict, memb->name, descr) < 0)
3508 return -1;
3509 Py_DECREF(descr);
3510 }
3511 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003512}
3513
3514static int
Guido van Rossum32d34c82001-09-20 21:45:26 +00003515add_getset(PyTypeObject *type, PyGetSetDef *gsp)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003516{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003517 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003518
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003519 for (; gsp->name != NULL; gsp++) {
3520 PyObject *descr;
3521 if (PyDict_GetItemString(dict, gsp->name))
3522 continue;
3523 descr = PyDescr_NewGetSet(type, gsp);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003524
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003525 if (descr == NULL)
3526 return -1;
3527 if (PyDict_SetItemString(dict, gsp->name, descr) < 0)
3528 return -1;
3529 Py_DECREF(descr);
3530 }
3531 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003532}
3533
Guido van Rossum13d52f02001-08-10 21:24:08 +00003534static void
3535inherit_special(PyTypeObject *type, PyTypeObject *base)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003536{
Tim Peters6d6c1a32001-08-02 04:15:00 +00003537
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003538 /* Copying basicsize is connected to the GC flags */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003539 if (!(type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
3540 (base->tp_flags & Py_TPFLAGS_HAVE_GC) &&
3541 (!type->tp_traverse && !type->tp_clear)) {
3542 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
3543 if (type->tp_traverse == NULL)
3544 type->tp_traverse = base->tp_traverse;
3545 if (type->tp_clear == NULL)
3546 type->tp_clear = base->tp_clear;
3547 }
3548 {
3549 /* The condition below could use some explanation.
3550 It appears that tp_new is not inherited for static types
3551 whose base class is 'object'; this seems to be a precaution
3552 so that old extension types don't suddenly become
3553 callable (object.__new__ wouldn't insure the invariants
3554 that the extension type's own factory function ensures).
3555 Heap types, of course, are under our control, so they do
3556 inherit tp_new; static extension types that specify some
3557 other built-in type as the default are considered
3558 new-style-aware so they also inherit object.__new__. */
3559 if (base != &PyBaseObject_Type ||
3560 (type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
3561 if (type->tp_new == NULL)
3562 type->tp_new = base->tp_new;
3563 }
3564 }
Benjamin Petersona7465e22010-07-05 15:01:22 +00003565 if (type->tp_basicsize == 0)
3566 type->tp_basicsize = base->tp_basicsize;
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00003567
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003568 /* Copy other non-function slots */
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00003569
3570#undef COPYVAL
3571#define COPYVAL(SLOT) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003572 if (type->SLOT == 0) type->SLOT = base->SLOT
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00003573
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003574 COPYVAL(tp_itemsize);
3575 COPYVAL(tp_weaklistoffset);
3576 COPYVAL(tp_dictoffset);
Thomas Wouters27d517b2007-02-25 20:39:11 +00003577
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003578 /* Setup fast subclass flags */
3579 if (PyType_IsSubtype(base, (PyTypeObject*)PyExc_BaseException))
3580 type->tp_flags |= Py_TPFLAGS_BASE_EXC_SUBCLASS;
3581 else if (PyType_IsSubtype(base, &PyType_Type))
3582 type->tp_flags |= Py_TPFLAGS_TYPE_SUBCLASS;
3583 else if (PyType_IsSubtype(base, &PyLong_Type))
3584 type->tp_flags |= Py_TPFLAGS_LONG_SUBCLASS;
3585 else if (PyType_IsSubtype(base, &PyBytes_Type))
3586 type->tp_flags |= Py_TPFLAGS_BYTES_SUBCLASS;
3587 else if (PyType_IsSubtype(base, &PyUnicode_Type))
3588 type->tp_flags |= Py_TPFLAGS_UNICODE_SUBCLASS;
3589 else if (PyType_IsSubtype(base, &PyTuple_Type))
3590 type->tp_flags |= Py_TPFLAGS_TUPLE_SUBCLASS;
3591 else if (PyType_IsSubtype(base, &PyList_Type))
3592 type->tp_flags |= Py_TPFLAGS_LIST_SUBCLASS;
3593 else if (PyType_IsSubtype(base, &PyDict_Type))
3594 type->tp_flags |= Py_TPFLAGS_DICT_SUBCLASS;
Guido van Rossum13d52f02001-08-10 21:24:08 +00003595}
3596
Guido van Rossumf5243f02008-01-01 04:06:48 +00003597static char *hash_name_op[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003598 "__eq__",
3599 "__hash__",
3600 NULL
Guido van Rossum38938152006-08-21 23:36:26 +00003601};
3602
3603static int
Guido van Rossumf5243f02008-01-01 04:06:48 +00003604overrides_hash(PyTypeObject *type)
Guido van Rossum38938152006-08-21 23:36:26 +00003605{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003606 char **p;
3607 PyObject *dict = type->tp_dict;
Guido van Rossum38938152006-08-21 23:36:26 +00003608
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003609 assert(dict != NULL);
3610 for (p = hash_name_op; *p; p++) {
3611 if (PyDict_GetItemString(dict, *p) != NULL)
3612 return 1;
3613 }
3614 return 0;
Guido van Rossum38938152006-08-21 23:36:26 +00003615}
3616
Guido van Rossum13d52f02001-08-10 21:24:08 +00003617static void
3618inherit_slots(PyTypeObject *type, PyTypeObject *base)
3619{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003620 PyTypeObject *basebase;
Guido van Rossum13d52f02001-08-10 21:24:08 +00003621
3622#undef SLOTDEFINED
Tim Peters6d6c1a32001-08-02 04:15:00 +00003623#undef COPYSLOT
3624#undef COPYNUM
3625#undef COPYSEQ
3626#undef COPYMAP
Guido van Rossum5af588b2001-10-12 14:13:21 +00003627#undef COPYBUF
Guido van Rossum13d52f02001-08-10 21:24:08 +00003628
3629#define SLOTDEFINED(SLOT) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003630 (base->SLOT != 0 && \
3631 (basebase == NULL || base->SLOT != basebase->SLOT))
Guido van Rossum13d52f02001-08-10 21:24:08 +00003632
Tim Peters6d6c1a32001-08-02 04:15:00 +00003633#define COPYSLOT(SLOT) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003634 if (!type->SLOT && SLOTDEFINED(SLOT)) type->SLOT = base->SLOT
Tim Peters6d6c1a32001-08-02 04:15:00 +00003635
3636#define COPYNUM(SLOT) COPYSLOT(tp_as_number->SLOT)
3637#define COPYSEQ(SLOT) COPYSLOT(tp_as_sequence->SLOT)
3638#define COPYMAP(SLOT) COPYSLOT(tp_as_mapping->SLOT)
Tim Petersfc57ccb2001-10-12 02:38:24 +00003639#define COPYBUF(SLOT) COPYSLOT(tp_as_buffer->SLOT)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003640
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003641 /* This won't inherit indirect slots (from tp_as_number etc.)
3642 if type doesn't provide the space. */
Guido van Rossum13d52f02001-08-10 21:24:08 +00003643
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003644 if (type->tp_as_number != NULL && base->tp_as_number != NULL) {
3645 basebase = base->tp_base;
3646 if (basebase->tp_as_number == NULL)
3647 basebase = NULL;
3648 COPYNUM(nb_add);
3649 COPYNUM(nb_subtract);
3650 COPYNUM(nb_multiply);
3651 COPYNUM(nb_remainder);
3652 COPYNUM(nb_divmod);
3653 COPYNUM(nb_power);
3654 COPYNUM(nb_negative);
3655 COPYNUM(nb_positive);
3656 COPYNUM(nb_absolute);
3657 COPYNUM(nb_bool);
3658 COPYNUM(nb_invert);
3659 COPYNUM(nb_lshift);
3660 COPYNUM(nb_rshift);
3661 COPYNUM(nb_and);
3662 COPYNUM(nb_xor);
3663 COPYNUM(nb_or);
3664 COPYNUM(nb_int);
3665 COPYNUM(nb_float);
3666 COPYNUM(nb_inplace_add);
3667 COPYNUM(nb_inplace_subtract);
3668 COPYNUM(nb_inplace_multiply);
3669 COPYNUM(nb_inplace_remainder);
3670 COPYNUM(nb_inplace_power);
3671 COPYNUM(nb_inplace_lshift);
3672 COPYNUM(nb_inplace_rshift);
3673 COPYNUM(nb_inplace_and);
3674 COPYNUM(nb_inplace_xor);
3675 COPYNUM(nb_inplace_or);
3676 COPYNUM(nb_true_divide);
3677 COPYNUM(nb_floor_divide);
3678 COPYNUM(nb_inplace_true_divide);
3679 COPYNUM(nb_inplace_floor_divide);
3680 COPYNUM(nb_index);
3681 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003682
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003683 if (type->tp_as_sequence != NULL && base->tp_as_sequence != NULL) {
3684 basebase = base->tp_base;
3685 if (basebase->tp_as_sequence == NULL)
3686 basebase = NULL;
3687 COPYSEQ(sq_length);
3688 COPYSEQ(sq_concat);
3689 COPYSEQ(sq_repeat);
3690 COPYSEQ(sq_item);
3691 COPYSEQ(sq_ass_item);
3692 COPYSEQ(sq_contains);
3693 COPYSEQ(sq_inplace_concat);
3694 COPYSEQ(sq_inplace_repeat);
3695 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003696
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003697 if (type->tp_as_mapping != NULL && base->tp_as_mapping != NULL) {
3698 basebase = base->tp_base;
3699 if (basebase->tp_as_mapping == NULL)
3700 basebase = NULL;
3701 COPYMAP(mp_length);
3702 COPYMAP(mp_subscript);
3703 COPYMAP(mp_ass_subscript);
3704 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003705
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003706 if (type->tp_as_buffer != NULL && base->tp_as_buffer != NULL) {
3707 basebase = base->tp_base;
3708 if (basebase->tp_as_buffer == NULL)
3709 basebase = NULL;
3710 COPYBUF(bf_getbuffer);
3711 COPYBUF(bf_releasebuffer);
3712 }
Tim Petersfc57ccb2001-10-12 02:38:24 +00003713
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003714 basebase = base->tp_base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003715
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003716 COPYSLOT(tp_dealloc);
3717 if (type->tp_getattr == NULL && type->tp_getattro == NULL) {
3718 type->tp_getattr = base->tp_getattr;
3719 type->tp_getattro = base->tp_getattro;
3720 }
3721 if (type->tp_setattr == NULL && type->tp_setattro == NULL) {
3722 type->tp_setattr = base->tp_setattr;
3723 type->tp_setattro = base->tp_setattro;
3724 }
3725 /* tp_reserved is ignored */
3726 COPYSLOT(tp_repr);
3727 /* tp_hash see tp_richcompare */
3728 COPYSLOT(tp_call);
3729 COPYSLOT(tp_str);
3730 {
3731 /* Copy comparison-related slots only when
3732 not overriding them anywhere */
3733 if (type->tp_richcompare == NULL &&
3734 type->tp_hash == NULL &&
3735 !overrides_hash(type))
3736 {
3737 type->tp_richcompare = base->tp_richcompare;
3738 type->tp_hash = base->tp_hash;
3739 }
3740 }
3741 {
3742 COPYSLOT(tp_iter);
3743 COPYSLOT(tp_iternext);
3744 }
3745 {
3746 COPYSLOT(tp_descr_get);
3747 COPYSLOT(tp_descr_set);
3748 COPYSLOT(tp_dictoffset);
3749 COPYSLOT(tp_init);
3750 COPYSLOT(tp_alloc);
3751 COPYSLOT(tp_is_gc);
3752 if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) ==
3753 (base->tp_flags & Py_TPFLAGS_HAVE_GC)) {
3754 /* They agree about gc. */
3755 COPYSLOT(tp_free);
3756 }
3757 else if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
3758 type->tp_free == NULL &&
3759 base->tp_free == PyObject_Free) {
3760 /* A bit of magic to plug in the correct default
3761 * tp_free function when a derived class adds gc,
3762 * didn't define tp_free, and the base uses the
3763 * default non-gc tp_free.
3764 */
3765 type->tp_free = PyObject_GC_Del;
3766 }
3767 /* else they didn't agree about gc, and there isn't something
3768 * obvious to be done -- the type is on its own.
3769 */
3770 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003771}
3772
Jeremy Hylton938ace62002-07-17 16:30:39 +00003773static int add_operators(PyTypeObject *);
Guido van Rossum13d52f02001-08-10 21:24:08 +00003774
Tim Peters6d6c1a32001-08-02 04:15:00 +00003775int
Guido van Rossum528b7eb2001-08-07 17:24:28 +00003776PyType_Ready(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003777{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003778 PyObject *dict, *bases;
3779 PyTypeObject *base;
3780 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003781
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003782 if (type->tp_flags & Py_TPFLAGS_READY) {
3783 assert(type->tp_dict != NULL);
3784 return 0;
3785 }
3786 assert((type->tp_flags & Py_TPFLAGS_READYING) == 0);
Guido van Rossumd614f972001-08-10 17:39:49 +00003787
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003788 type->tp_flags |= Py_TPFLAGS_READYING;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003789
Tim Peters36eb4df2003-03-23 03:33:13 +00003790#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003791 /* PyType_Ready is the closest thing we have to a choke point
3792 * for type objects, so is the best place I can think of to try
3793 * to get type objects into the doubly-linked list of all objects.
3794 * Still, not all type objects go thru PyType_Ready.
3795 */
3796 _Py_AddToAllObjects((PyObject *)type, 0);
Tim Peters36eb4df2003-03-23 03:33:13 +00003797#endif
3798
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003799 /* Initialize tp_base (defaults to BaseObject unless that's us) */
3800 base = type->tp_base;
3801 if (base == NULL && type != &PyBaseObject_Type) {
3802 base = type->tp_base = &PyBaseObject_Type;
3803 Py_INCREF(base);
3804 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003805
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003806 /* Now the only way base can still be NULL is if type is
3807 * &PyBaseObject_Type.
3808 */
Guido van Rossum692cdbc2006-03-10 02:04:28 +00003809
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003810 /* Initialize the base class */
3811 if (base != NULL && base->tp_dict == NULL) {
3812 if (PyType_Ready(base) < 0)
3813 goto error;
3814 }
Guido van Rossum323a9cf2002-08-14 17:26:30 +00003815
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003816 /* Initialize ob_type if NULL. This means extensions that want to be
3817 compilable separately on Windows can call PyType_Ready() instead of
3818 initializing the ob_type field of their type objects. */
3819 /* The test for base != NULL is really unnecessary, since base is only
3820 NULL when type is &PyBaseObject_Type, and we know its ob_type is
3821 not NULL (it's initialized to &PyType_Type). But coverity doesn't
3822 know that. */
3823 if (Py_TYPE(type) == NULL && base != NULL)
3824 Py_TYPE(type) = Py_TYPE(base);
Guido van Rossum0986d822002-04-08 01:38:42 +00003825
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003826 /* Initialize tp_bases */
3827 bases = type->tp_bases;
3828 if (bases == NULL) {
3829 if (base == NULL)
3830 bases = PyTuple_New(0);
3831 else
3832 bases = PyTuple_Pack(1, base);
3833 if (bases == NULL)
3834 goto error;
3835 type->tp_bases = bases;
3836 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003837
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003838 /* Initialize tp_dict */
3839 dict = type->tp_dict;
3840 if (dict == NULL) {
3841 dict = PyDict_New();
3842 if (dict == NULL)
3843 goto error;
3844 type->tp_dict = dict;
3845 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003846
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003847 /* Add type-specific descriptors to tp_dict */
3848 if (add_operators(type) < 0)
3849 goto error;
3850 if (type->tp_methods != NULL) {
3851 if (add_methods(type, type->tp_methods) < 0)
3852 goto error;
3853 }
3854 if (type->tp_members != NULL) {
3855 if (add_members(type, type->tp_members) < 0)
3856 goto error;
3857 }
3858 if (type->tp_getset != NULL) {
3859 if (add_getset(type, type->tp_getset) < 0)
3860 goto error;
3861 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003862
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003863 /* Calculate method resolution order */
3864 if (mro_internal(type) < 0) {
3865 goto error;
3866 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003867
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003868 /* Inherit special flags from dominant base */
3869 if (type->tp_base != NULL)
3870 inherit_special(type, type->tp_base);
Guido van Rossum13d52f02001-08-10 21:24:08 +00003871
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003872 /* Initialize tp_dict properly */
3873 bases = type->tp_mro;
3874 assert(bases != NULL);
3875 assert(PyTuple_Check(bases));
3876 n = PyTuple_GET_SIZE(bases);
3877 for (i = 1; i < n; i++) {
3878 PyObject *b = PyTuple_GET_ITEM(bases, i);
3879 if (PyType_Check(b))
3880 inherit_slots(type, (PyTypeObject *)b);
3881 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003882
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003883 /* Sanity check for tp_free. */
3884 if (PyType_IS_GC(type) && (type->tp_flags & Py_TPFLAGS_BASETYPE) &&
3885 (type->tp_free == NULL || type->tp_free == PyObject_Del)) {
3886 /* This base class needs to call tp_free, but doesn't have
3887 * one, or its tp_free is for non-gc'ed objects.
3888 */
3889 PyErr_Format(PyExc_TypeError, "type '%.100s' participates in "
3890 "gc and is a base type but has inappropriate "
3891 "tp_free slot",
3892 type->tp_name);
3893 goto error;
3894 }
Tim Peters3cfe7542003-05-21 21:29:48 +00003895
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003896 /* if the type dictionary doesn't contain a __doc__, set it from
3897 the tp_doc slot.
3898 */
3899 if (PyDict_GetItemString(type->tp_dict, "__doc__") == NULL) {
3900 if (type->tp_doc != NULL) {
3901 PyObject *doc = PyUnicode_FromString(type->tp_doc);
3902 if (doc == NULL)
3903 goto error;
3904 PyDict_SetItemString(type->tp_dict, "__doc__", doc);
3905 Py_DECREF(doc);
3906 } else {
3907 PyDict_SetItemString(type->tp_dict,
3908 "__doc__", Py_None);
3909 }
3910 }
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00003911
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003912 /* Hack for tp_hash and __hash__.
3913 If after all that, tp_hash is still NULL, and __hash__ is not in
3914 tp_dict, set tp_hash to PyObject_HashNotImplemented and
3915 tp_dict['__hash__'] equal to None.
3916 This signals that __hash__ is not inherited.
3917 */
3918 if (type->tp_hash == NULL) {
3919 if (PyDict_GetItemString(type->tp_dict, "__hash__") == NULL) {
3920 if (PyDict_SetItemString(type->tp_dict, "__hash__", Py_None) < 0)
3921 goto error;
3922 type->tp_hash = PyObject_HashNotImplemented;
3923 }
3924 }
Guido van Rossum38938152006-08-21 23:36:26 +00003925
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003926 /* Some more special stuff */
3927 base = type->tp_base;
3928 if (base != NULL) {
3929 if (type->tp_as_number == NULL)
3930 type->tp_as_number = base->tp_as_number;
3931 if (type->tp_as_sequence == NULL)
3932 type->tp_as_sequence = base->tp_as_sequence;
3933 if (type->tp_as_mapping == NULL)
3934 type->tp_as_mapping = base->tp_as_mapping;
3935 if (type->tp_as_buffer == NULL)
3936 type->tp_as_buffer = base->tp_as_buffer;
3937 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003938
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003939 /* Link into each base class's list of subclasses */
3940 bases = type->tp_bases;
3941 n = PyTuple_GET_SIZE(bases);
3942 for (i = 0; i < n; i++) {
3943 PyObject *b = PyTuple_GET_ITEM(bases, i);
3944 if (PyType_Check(b) &&
3945 add_subclass((PyTypeObject *)b, type) < 0)
3946 goto error;
3947 }
Guido van Rossum1c450732001-10-08 15:18:27 +00003948
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003949 /* Warn for a type that implements tp_compare (now known as
3950 tp_reserved) but not tp_richcompare. */
3951 if (type->tp_reserved && !type->tp_richcompare) {
3952 int error;
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003953 error = PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
3954 "Type %.100s defines tp_reserved (formerly tp_compare) "
3955 "but not tp_richcompare. Comparisons may not behave as intended.",
3956 type->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003957 if (error == -1)
3958 goto error;
3959 }
Mark Dickinson2a7d45b2009-02-08 11:02:10 +00003960
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003961 /* All done -- set the ready flag */
3962 assert(type->tp_dict != NULL);
3963 type->tp_flags =
3964 (type->tp_flags & ~Py_TPFLAGS_READYING) | Py_TPFLAGS_READY;
3965 return 0;
Guido van Rossumd614f972001-08-10 17:39:49 +00003966
3967 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003968 type->tp_flags &= ~Py_TPFLAGS_READYING;
3969 return -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003970}
3971
Guido van Rossum1c450732001-10-08 15:18:27 +00003972static int
3973add_subclass(PyTypeObject *base, PyTypeObject *type)
3974{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003975 Py_ssize_t i;
3976 int result;
3977 PyObject *list, *ref, *newobj;
Guido van Rossum1c450732001-10-08 15:18:27 +00003978
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003979 list = base->tp_subclasses;
3980 if (list == NULL) {
3981 base->tp_subclasses = list = PyList_New(0);
3982 if (list == NULL)
3983 return -1;
3984 }
3985 assert(PyList_Check(list));
3986 newobj = PyWeakref_NewRef((PyObject *)type, NULL);
3987 i = PyList_GET_SIZE(list);
3988 while (--i >= 0) {
3989 ref = PyList_GET_ITEM(list, i);
3990 assert(PyWeakref_CheckRef(ref));
3991 if (PyWeakref_GET_OBJECT(ref) == Py_None)
3992 return PyList_SetItem(list, i, newobj);
3993 }
3994 result = PyList_Append(list, newobj);
3995 Py_DECREF(newobj);
3996 return result;
Guido van Rossum1c450732001-10-08 15:18:27 +00003997}
3998
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003999static void
4000remove_subclass(PyTypeObject *base, PyTypeObject *type)
4001{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004002 Py_ssize_t i;
4003 PyObject *list, *ref;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00004004
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004005 list = base->tp_subclasses;
4006 if (list == NULL) {
4007 return;
4008 }
4009 assert(PyList_Check(list));
4010 i = PyList_GET_SIZE(list);
4011 while (--i >= 0) {
4012 ref = PyList_GET_ITEM(list, i);
4013 assert(PyWeakref_CheckRef(ref));
4014 if (PyWeakref_GET_OBJECT(ref) == (PyObject*)type) {
4015 /* this can't fail, right? */
4016 PySequence_DelItem(list, i);
4017 return;
4018 }
4019 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +00004020}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004021
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004022static int
4023check_num_args(PyObject *ob, int n)
4024{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004025 if (!PyTuple_CheckExact(ob)) {
4026 PyErr_SetString(PyExc_SystemError,
4027 "PyArg_UnpackTuple() argument list is not a tuple");
4028 return 0;
4029 }
4030 if (n == PyTuple_GET_SIZE(ob))
4031 return 1;
4032 PyErr_Format(
4033 PyExc_TypeError,
4034 "expected %d arguments, got %zd", n, PyTuple_GET_SIZE(ob));
4035 return 0;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004036}
4037
Tim Peters6d6c1a32001-08-02 04:15:00 +00004038/* Generic wrappers for overloadable 'operators' such as __getitem__ */
4039
4040/* There's a wrapper *function* for each distinct function typedef used
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004041 for type object slots (e.g. binaryfunc, ternaryfunc, etc.). There's a
Tim Peters6d6c1a32001-08-02 04:15:00 +00004042 wrapper *table* for each distinct operation (e.g. __len__, __add__).
4043 Most tables have only one entry; the tables for binary operators have two
4044 entries, one regular and one with reversed arguments. */
4045
4046static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00004047wrap_lenfunc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004048{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004049 lenfunc func = (lenfunc)wrapped;
4050 Py_ssize_t res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004051
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004052 if (!check_num_args(args, 0))
4053 return NULL;
4054 res = (*func)(self);
4055 if (res == -1 && PyErr_Occurred())
4056 return NULL;
4057 return PyLong_FromLong((long)res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004058}
4059
Tim Peters6d6c1a32001-08-02 04:15:00 +00004060static PyObject *
Raymond Hettingerf34f2642003-10-11 17:29:04 +00004061wrap_inquirypred(PyObject *self, PyObject *args, void *wrapped)
4062{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004063 inquiry func = (inquiry)wrapped;
4064 int res;
Raymond Hettingerf34f2642003-10-11 17:29:04 +00004065
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004066 if (!check_num_args(args, 0))
4067 return NULL;
4068 res = (*func)(self);
4069 if (res == -1 && PyErr_Occurred())
4070 return NULL;
4071 return PyBool_FromLong((long)res);
Raymond Hettingerf34f2642003-10-11 17:29:04 +00004072}
4073
4074static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00004075wrap_binaryfunc(PyObject *self, PyObject *args, void *wrapped)
4076{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004077 binaryfunc func = (binaryfunc)wrapped;
4078 PyObject *other;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004079
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004080 if (!check_num_args(args, 1))
4081 return NULL;
4082 other = PyTuple_GET_ITEM(args, 0);
4083 return (*func)(self, other);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004084}
4085
4086static PyObject *
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00004087wrap_binaryfunc_l(PyObject *self, PyObject *args, void *wrapped)
4088{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004089 binaryfunc func = (binaryfunc)wrapped;
4090 PyObject *other;
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00004091
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004092 if (!check_num_args(args, 1))
4093 return NULL;
4094 other = PyTuple_GET_ITEM(args, 0);
4095 return (*func)(self, other);
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00004096}
4097
4098static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00004099wrap_binaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
4100{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004101 binaryfunc func = (binaryfunc)wrapped;
4102 PyObject *other;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004103
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004104 if (!check_num_args(args, 1))
4105 return NULL;
4106 other = PyTuple_GET_ITEM(args, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004107 return (*func)(other, self);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004108}
4109
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004110static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00004111wrap_ternaryfunc(PyObject *self, PyObject *args, void *wrapped)
4112{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004113 ternaryfunc func = (ternaryfunc)wrapped;
4114 PyObject *other;
4115 PyObject *third = Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004116
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004117 /* Note: This wrapper only works for __pow__() */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004118
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004119 if (!PyArg_UnpackTuple(args, "", 1, 2, &other, &third))
4120 return NULL;
4121 return (*func)(self, other, third);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004122}
4123
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00004124static PyObject *
4125wrap_ternaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
4126{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004127 ternaryfunc func = (ternaryfunc)wrapped;
4128 PyObject *other;
4129 PyObject *third = Py_None;
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00004130
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004131 /* Note: This wrapper only works for __pow__() */
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00004132
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004133 if (!PyArg_UnpackTuple(args, "", 1, 2, &other, &third))
4134 return NULL;
4135 return (*func)(other, self, third);
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00004136}
4137
Tim Peters6d6c1a32001-08-02 04:15:00 +00004138static PyObject *
4139wrap_unaryfunc(PyObject *self, PyObject *args, void *wrapped)
4140{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004141 unaryfunc func = (unaryfunc)wrapped;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004142
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004143 if (!check_num_args(args, 0))
4144 return NULL;
4145 return (*func)(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004146}
4147
Tim Peters6d6c1a32001-08-02 04:15:00 +00004148static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004149wrap_indexargfunc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004150{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004151 ssizeargfunc func = (ssizeargfunc)wrapped;
4152 PyObject* o;
4153 Py_ssize_t i;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004154
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004155 if (!PyArg_UnpackTuple(args, "", 1, 1, &o))
4156 return NULL;
4157 i = PyNumber_AsSsize_t(o, PyExc_OverflowError);
4158 if (i == -1 && PyErr_Occurred())
4159 return NULL;
4160 return (*func)(self, i);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004161}
4162
Martin v. Löwis18e16552006-02-15 17:27:45 +00004163static Py_ssize_t
Guido van Rossum5d815f32001-08-17 21:57:47 +00004164getindex(PyObject *self, PyObject *arg)
4165{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004166 Py_ssize_t i;
Guido van Rossum5d815f32001-08-17 21:57:47 +00004167
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004168 i = PyNumber_AsSsize_t(arg, PyExc_OverflowError);
4169 if (i == -1 && PyErr_Occurred())
4170 return -1;
4171 if (i < 0) {
4172 PySequenceMethods *sq = Py_TYPE(self)->tp_as_sequence;
4173 if (sq && sq->sq_length) {
4174 Py_ssize_t n = (*sq->sq_length)(self);
4175 if (n < 0)
4176 return -1;
4177 i += n;
4178 }
4179 }
4180 return i;
Guido van Rossum5d815f32001-08-17 21:57:47 +00004181}
4182
4183static PyObject *
4184wrap_sq_item(PyObject *self, PyObject *args, void *wrapped)
4185{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004186 ssizeargfunc func = (ssizeargfunc)wrapped;
4187 PyObject *arg;
4188 Py_ssize_t i;
Guido van Rossum5d815f32001-08-17 21:57:47 +00004189
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004190 if (PyTuple_GET_SIZE(args) == 1) {
4191 arg = PyTuple_GET_ITEM(args, 0);
4192 i = getindex(self, arg);
4193 if (i == -1 && PyErr_Occurred())
4194 return NULL;
4195 return (*func)(self, i);
4196 }
4197 check_num_args(args, 1);
4198 assert(PyErr_Occurred());
4199 return NULL;
Guido van Rossum5d815f32001-08-17 21:57:47 +00004200}
4201
Tim Peters6d6c1a32001-08-02 04:15:00 +00004202static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00004203wrap_sq_setitem(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004204{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004205 ssizeobjargproc func = (ssizeobjargproc)wrapped;
4206 Py_ssize_t i;
4207 int res;
4208 PyObject *arg, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004209
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004210 if (!PyArg_UnpackTuple(args, "", 2, 2, &arg, &value))
4211 return NULL;
4212 i = getindex(self, arg);
4213 if (i == -1 && PyErr_Occurred())
4214 return NULL;
4215 res = (*func)(self, i, value);
4216 if (res == -1 && PyErr_Occurred())
4217 return NULL;
4218 Py_INCREF(Py_None);
4219 return Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004220}
4221
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004222static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00004223wrap_sq_delitem(PyObject *self, PyObject *args, void *wrapped)
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004224{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004225 ssizeobjargproc func = (ssizeobjargproc)wrapped;
4226 Py_ssize_t i;
4227 int res;
4228 PyObject *arg;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004229
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004230 if (!check_num_args(args, 1))
4231 return NULL;
4232 arg = PyTuple_GET_ITEM(args, 0);
4233 i = getindex(self, arg);
4234 if (i == -1 && PyErr_Occurred())
4235 return NULL;
4236 res = (*func)(self, i, NULL);
4237 if (res == -1 && PyErr_Occurred())
4238 return NULL;
4239 Py_INCREF(Py_None);
4240 return Py_None;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004241}
4242
Tim Peters6d6c1a32001-08-02 04:15:00 +00004243/* XXX objobjproc is a misnomer; should be objargpred */
4244static PyObject *
4245wrap_objobjproc(PyObject *self, PyObject *args, void *wrapped)
4246{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004247 objobjproc func = (objobjproc)wrapped;
4248 int res;
4249 PyObject *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004250
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004251 if (!check_num_args(args, 1))
4252 return NULL;
4253 value = PyTuple_GET_ITEM(args, 0);
4254 res = (*func)(self, value);
4255 if (res == -1 && PyErr_Occurred())
4256 return NULL;
4257 else
4258 return PyBool_FromLong(res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004259}
4260
Tim Peters6d6c1a32001-08-02 04:15:00 +00004261static PyObject *
4262wrap_objobjargproc(PyObject *self, PyObject *args, void *wrapped)
4263{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004264 objobjargproc func = (objobjargproc)wrapped;
4265 int res;
4266 PyObject *key, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004267
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004268 if (!PyArg_UnpackTuple(args, "", 2, 2, &key, &value))
4269 return NULL;
4270 res = (*func)(self, key, value);
4271 if (res == -1 && PyErr_Occurred())
4272 return NULL;
4273 Py_INCREF(Py_None);
4274 return Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004275}
4276
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004277static PyObject *
4278wrap_delitem(PyObject *self, PyObject *args, void *wrapped)
4279{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004280 objobjargproc func = (objobjargproc)wrapped;
4281 int res;
4282 PyObject *key;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004283
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004284 if (!check_num_args(args, 1))
4285 return NULL;
4286 key = PyTuple_GET_ITEM(args, 0);
4287 res = (*func)(self, key, NULL);
4288 if (res == -1 && PyErr_Occurred())
4289 return NULL;
4290 Py_INCREF(Py_None);
4291 return Py_None;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004292}
4293
Guido van Rossum4dcdb782003-04-14 21:46:03 +00004294/* Helper to check for object.__setattr__ or __delattr__ applied to a type.
Guido van Rossum52b27052003-04-15 20:05:10 +00004295 This is called the Carlo Verre hack after its discoverer. */
Guido van Rossum4dcdb782003-04-14 21:46:03 +00004296static int
4297hackcheck(PyObject *self, setattrofunc func, char *what)
4298{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004299 PyTypeObject *type = Py_TYPE(self);
4300 while (type && type->tp_flags & Py_TPFLAGS_HEAPTYPE)
4301 type = type->tp_base;
4302 /* If type is NULL now, this is a really weird type.
4303 In the spirit of backwards compatibility (?), just shut up. */
4304 if (type && type->tp_setattro != func) {
4305 PyErr_Format(PyExc_TypeError,
4306 "can't apply this %s to %s object",
4307 what,
4308 type->tp_name);
4309 return 0;
4310 }
4311 return 1;
Guido van Rossum4dcdb782003-04-14 21:46:03 +00004312}
4313
Tim Peters6d6c1a32001-08-02 04:15:00 +00004314static PyObject *
4315wrap_setattr(PyObject *self, PyObject *args, void *wrapped)
4316{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004317 setattrofunc func = (setattrofunc)wrapped;
4318 int res;
4319 PyObject *name, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004320
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004321 if (!PyArg_UnpackTuple(args, "", 2, 2, &name, &value))
4322 return NULL;
4323 if (!hackcheck(self, func, "__setattr__"))
4324 return NULL;
4325 res = (*func)(self, name, value);
4326 if (res < 0)
4327 return NULL;
4328 Py_INCREF(Py_None);
4329 return Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004330}
4331
4332static PyObject *
4333wrap_delattr(PyObject *self, PyObject *args, void *wrapped)
4334{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004335 setattrofunc func = (setattrofunc)wrapped;
4336 int res;
4337 PyObject *name;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004338
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004339 if (!check_num_args(args, 1))
4340 return NULL;
4341 name = PyTuple_GET_ITEM(args, 0);
4342 if (!hackcheck(self, func, "__delattr__"))
4343 return NULL;
4344 res = (*func)(self, name, NULL);
4345 if (res < 0)
4346 return NULL;
4347 Py_INCREF(Py_None);
4348 return Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004349}
4350
Tim Peters6d6c1a32001-08-02 04:15:00 +00004351static PyObject *
4352wrap_hashfunc(PyObject *self, PyObject *args, void *wrapped)
4353{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004354 hashfunc func = (hashfunc)wrapped;
Benjamin Peterson8035bc52010-10-23 16:20:50 +00004355 Py_hash_t res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004356
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004357 if (!check_num_args(args, 0))
4358 return NULL;
4359 res = (*func)(self);
4360 if (res == -1 && PyErr_Occurred())
4361 return NULL;
Benjamin Peterson8035bc52010-10-23 16:20:50 +00004362 return PyLong_FromSsize_t(res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004363}
4364
Tim Peters6d6c1a32001-08-02 04:15:00 +00004365static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00004366wrap_call(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004367{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004368 ternaryfunc func = (ternaryfunc)wrapped;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004369
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004370 return (*func)(self, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004371}
4372
Tim Peters6d6c1a32001-08-02 04:15:00 +00004373static PyObject *
4374wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op)
4375{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004376 richcmpfunc func = (richcmpfunc)wrapped;
4377 PyObject *other;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004378
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004379 if (!check_num_args(args, 1))
4380 return NULL;
4381 other = PyTuple_GET_ITEM(args, 0);
4382 return (*func)(self, other, op);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004383}
4384
4385#undef RICHCMP_WRAPPER
4386#define RICHCMP_WRAPPER(NAME, OP) \
4387static PyObject * \
4388richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \
4389{ \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004390 return wrap_richcmpfunc(self, args, wrapped, OP); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004391}
4392
Jack Jansen8e938b42001-08-08 15:29:49 +00004393RICHCMP_WRAPPER(lt, Py_LT)
4394RICHCMP_WRAPPER(le, Py_LE)
4395RICHCMP_WRAPPER(eq, Py_EQ)
4396RICHCMP_WRAPPER(ne, Py_NE)
4397RICHCMP_WRAPPER(gt, Py_GT)
4398RICHCMP_WRAPPER(ge, Py_GE)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004399
Tim Peters6d6c1a32001-08-02 04:15:00 +00004400static PyObject *
4401wrap_next(PyObject *self, PyObject *args, void *wrapped)
4402{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004403 unaryfunc func = (unaryfunc)wrapped;
4404 PyObject *res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004405
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004406 if (!check_num_args(args, 0))
4407 return NULL;
4408 res = (*func)(self);
4409 if (res == NULL && !PyErr_Occurred())
4410 PyErr_SetNone(PyExc_StopIteration);
4411 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004412}
4413
Tim Peters6d6c1a32001-08-02 04:15:00 +00004414static PyObject *
4415wrap_descr_get(PyObject *self, PyObject *args, void *wrapped)
4416{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004417 descrgetfunc func = (descrgetfunc)wrapped;
4418 PyObject *obj;
4419 PyObject *type = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004420
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004421 if (!PyArg_UnpackTuple(args, "", 1, 2, &obj, &type))
4422 return NULL;
4423 if (obj == Py_None)
4424 obj = NULL;
4425 if (type == Py_None)
4426 type = NULL;
4427 if (type == NULL &&obj == NULL) {
4428 PyErr_SetString(PyExc_TypeError,
4429 "__get__(None, None) is invalid");
4430 return NULL;
4431 }
4432 return (*func)(self, obj, type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004433}
4434
Tim Peters6d6c1a32001-08-02 04:15:00 +00004435static PyObject *
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004436wrap_descr_set(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004437{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004438 descrsetfunc func = (descrsetfunc)wrapped;
4439 PyObject *obj, *value;
4440 int ret;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004441
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004442 if (!PyArg_UnpackTuple(args, "", 2, 2, &obj, &value))
4443 return NULL;
4444 ret = (*func)(self, obj, value);
4445 if (ret < 0)
4446 return NULL;
4447 Py_INCREF(Py_None);
4448 return Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004449}
Guido van Rossum22b13872002-08-06 21:41:44 +00004450
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00004451static PyObject *
4452wrap_descr_delete(PyObject *self, PyObject *args, void *wrapped)
4453{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004454 descrsetfunc func = (descrsetfunc)wrapped;
4455 PyObject *obj;
4456 int ret;
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00004457
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004458 if (!check_num_args(args, 1))
4459 return NULL;
4460 obj = PyTuple_GET_ITEM(args, 0);
4461 ret = (*func)(self, obj, NULL);
4462 if (ret < 0)
4463 return NULL;
4464 Py_INCREF(Py_None);
4465 return Py_None;
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00004466}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004467
Tim Peters6d6c1a32001-08-02 04:15:00 +00004468static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00004469wrap_init(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004470{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004471 initproc func = (initproc)wrapped;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004472
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004473 if (func(self, args, kwds) < 0)
4474 return NULL;
4475 Py_INCREF(Py_None);
4476 return Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004477}
4478
Tim Peters6d6c1a32001-08-02 04:15:00 +00004479static PyObject *
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004480tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004481{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004482 PyTypeObject *type, *subtype, *staticbase;
4483 PyObject *arg0, *res;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004484
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004485 if (self == NULL || !PyType_Check(self))
4486 Py_FatalError("__new__() called with non-type 'self'");
4487 type = (PyTypeObject *)self;
4488 if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) {
4489 PyErr_Format(PyExc_TypeError,
4490 "%s.__new__(): not enough arguments",
4491 type->tp_name);
4492 return NULL;
4493 }
4494 arg0 = PyTuple_GET_ITEM(args, 0);
4495 if (!PyType_Check(arg0)) {
4496 PyErr_Format(PyExc_TypeError,
4497 "%s.__new__(X): X is not a type object (%s)",
4498 type->tp_name,
4499 Py_TYPE(arg0)->tp_name);
4500 return NULL;
4501 }
4502 subtype = (PyTypeObject *)arg0;
4503 if (!PyType_IsSubtype(subtype, type)) {
4504 PyErr_Format(PyExc_TypeError,
4505 "%s.__new__(%s): %s is not a subtype of %s",
4506 type->tp_name,
4507 subtype->tp_name,
4508 subtype->tp_name,
4509 type->tp_name);
4510 return NULL;
4511 }
Barry Warsaw60f01882001-08-22 19:24:42 +00004512
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004513 /* Check that the use doesn't do something silly and unsafe like
4514 object.__new__(dict). To do this, we check that the
4515 most derived base that's not a heap type is this type. */
4516 staticbase = subtype;
4517 while (staticbase && (staticbase->tp_flags & Py_TPFLAGS_HEAPTYPE))
4518 staticbase = staticbase->tp_base;
4519 /* If staticbase is NULL now, it is a really weird type.
4520 In the spirit of backwards compatibility (?), just shut up. */
4521 if (staticbase && staticbase->tp_new != type->tp_new) {
4522 PyErr_Format(PyExc_TypeError,
4523 "%s.__new__(%s) is not safe, use %s.__new__()",
4524 type->tp_name,
4525 subtype->tp_name,
4526 staticbase == NULL ? "?" : staticbase->tp_name);
4527 return NULL;
4528 }
Barry Warsaw60f01882001-08-22 19:24:42 +00004529
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004530 args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
4531 if (args == NULL)
4532 return NULL;
4533 res = type->tp_new(subtype, args, kwds);
4534 Py_DECREF(args);
4535 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004536}
4537
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004538static struct PyMethodDef tp_new_methoddef[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004539 {"__new__", (PyCFunction)tp_new_wrapper, METH_VARARGS|METH_KEYWORDS,
4540 PyDoc_STR("T.__new__(S, ...) -> "
4541 "a new object with type S, a subtype of T")},
4542 {0}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004543};
4544
4545static int
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004546add_tp_new_wrapper(PyTypeObject *type)
4547{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004548 PyObject *func;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004549
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004550 if (PyDict_GetItemString(type->tp_dict, "__new__") != NULL)
4551 return 0;
4552 func = PyCFunction_New(tp_new_methoddef, (PyObject *)type);
4553 if (func == NULL)
4554 return -1;
4555 if (PyDict_SetItemString(type->tp_dict, "__new__", func)) {
4556 Py_DECREF(func);
4557 return -1;
4558 }
4559 Py_DECREF(func);
4560 return 0;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004561}
4562
Guido van Rossumf040ede2001-08-07 16:40:56 +00004563/* Slot wrappers that call the corresponding __foo__ slot. See comments
4564 below at override_slots() for more explanation. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004565
Guido van Rossumdc91b992001-08-08 22:26:22 +00004566#define SLOT0(FUNCNAME, OPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004567static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004568FUNCNAME(PyObject *self) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004569{ \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004570 static PyObject *cache_str; \
4571 return call_method(self, OPSTR, &cache_str, "()"); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004572}
4573
Guido van Rossumdc91b992001-08-08 22:26:22 +00004574#define SLOT1(FUNCNAME, OPSTR, ARG1TYPE, ARGCODES) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004575static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004576FUNCNAME(PyObject *self, ARG1TYPE arg1) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004577{ \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004578 static PyObject *cache_str; \
4579 return call_method(self, OPSTR, &cache_str, "(" ARGCODES ")", arg1); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004580}
4581
Guido van Rossumcd118802003-01-06 22:57:47 +00004582/* Boolean helper for SLOT1BINFULL().
4583 right.__class__ is a nontrivial subclass of left.__class__. */
4584static int
4585method_is_overloaded(PyObject *left, PyObject *right, char *name)
4586{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004587 PyObject *a, *b;
4588 int ok;
Guido van Rossumcd118802003-01-06 22:57:47 +00004589
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004590 b = PyObject_GetAttrString((PyObject *)(Py_TYPE(right)), name);
4591 if (b == NULL) {
4592 PyErr_Clear();
4593 /* If right doesn't have it, it's not overloaded */
4594 return 0;
4595 }
Guido van Rossumcd118802003-01-06 22:57:47 +00004596
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004597 a = PyObject_GetAttrString((PyObject *)(Py_TYPE(left)), name);
4598 if (a == NULL) {
4599 PyErr_Clear();
4600 Py_DECREF(b);
4601 /* If right has it but left doesn't, it's overloaded */
4602 return 1;
4603 }
Guido van Rossumcd118802003-01-06 22:57:47 +00004604
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004605 ok = PyObject_RichCompareBool(a, b, Py_NE);
4606 Py_DECREF(a);
4607 Py_DECREF(b);
4608 if (ok < 0) {
4609 PyErr_Clear();
4610 return 0;
4611 }
Guido van Rossumcd118802003-01-06 22:57:47 +00004612
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004613 return ok;
Guido van Rossumcd118802003-01-06 22:57:47 +00004614}
4615
Guido van Rossumdc91b992001-08-08 22:26:22 +00004616
4617#define SLOT1BINFULL(FUNCNAME, TESTFUNC, SLOTNAME, OPSTR, ROPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004618static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004619FUNCNAME(PyObject *self, PyObject *other) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004620{ \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004621 static PyObject *cache_str, *rcache_str; \
4622 int do_other = Py_TYPE(self) != Py_TYPE(other) && \
4623 Py_TYPE(other)->tp_as_number != NULL && \
4624 Py_TYPE(other)->tp_as_number->SLOTNAME == TESTFUNC; \
4625 if (Py_TYPE(self)->tp_as_number != NULL && \
4626 Py_TYPE(self)->tp_as_number->SLOTNAME == TESTFUNC) { \
4627 PyObject *r; \
4628 if (do_other && \
4629 PyType_IsSubtype(Py_TYPE(other), Py_TYPE(self)) && \
4630 method_is_overloaded(self, other, ROPSTR)) { \
4631 r = call_maybe( \
4632 other, ROPSTR, &rcache_str, "(O)", self); \
4633 if (r != Py_NotImplemented) \
4634 return r; \
4635 Py_DECREF(r); \
4636 do_other = 0; \
4637 } \
4638 r = call_maybe( \
4639 self, OPSTR, &cache_str, "(O)", other); \
4640 if (r != Py_NotImplemented || \
4641 Py_TYPE(other) == Py_TYPE(self)) \
4642 return r; \
4643 Py_DECREF(r); \
4644 } \
4645 if (do_other) { \
4646 return call_maybe( \
4647 other, ROPSTR, &rcache_str, "(O)", self); \
4648 } \
4649 Py_INCREF(Py_NotImplemented); \
4650 return Py_NotImplemented; \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004651}
4652
4653#define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004654 SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR)
Guido van Rossumdc91b992001-08-08 22:26:22 +00004655
4656#define SLOT2(FUNCNAME, OPSTR, ARG1TYPE, ARG2TYPE, ARGCODES) \
4657static PyObject * \
4658FUNCNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \
4659{ \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004660 static PyObject *cache_str; \
4661 return call_method(self, OPSTR, &cache_str, \
4662 "(" ARGCODES ")", arg1, arg2); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004663}
4664
Martin v. Löwis18e16552006-02-15 17:27:45 +00004665static Py_ssize_t
Tim Peters6d6c1a32001-08-02 04:15:00 +00004666slot_sq_length(PyObject *self)
4667{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004668 static PyObject *len_str;
4669 PyObject *res = call_method(self, "__len__", &len_str, "()");
4670 Py_ssize_t len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004671
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004672 if (res == NULL)
4673 return -1;
4674 len = PyNumber_AsSsize_t(res, PyExc_OverflowError);
4675 Py_DECREF(res);
4676 if (len < 0) {
4677 if (!PyErr_Occurred())
4678 PyErr_SetString(PyExc_ValueError,
4679 "__len__() should return >= 0");
4680 return -1;
4681 }
4682 return len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004683}
4684
Guido van Rossumf4593e02001-10-03 12:09:30 +00004685/* Super-optimized version of slot_sq_item.
4686 Other slots could do the same... */
4687static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00004688slot_sq_item(PyObject *self, Py_ssize_t i)
Guido van Rossumf4593e02001-10-03 12:09:30 +00004689{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004690 static PyObject *getitem_str;
4691 PyObject *func, *args = NULL, *ival = NULL, *retval = NULL;
4692 descrgetfunc f;
Guido van Rossumf4593e02001-10-03 12:09:30 +00004693
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004694 if (getitem_str == NULL) {
4695 getitem_str = PyUnicode_InternFromString("__getitem__");
4696 if (getitem_str == NULL)
4697 return NULL;
4698 }
4699 func = _PyType_Lookup(Py_TYPE(self), getitem_str);
4700 if (func != NULL) {
4701 if ((f = Py_TYPE(func)->tp_descr_get) == NULL)
4702 Py_INCREF(func);
4703 else {
4704 func = f(func, self, (PyObject *)(Py_TYPE(self)));
4705 if (func == NULL) {
4706 return NULL;
4707 }
4708 }
4709 ival = PyLong_FromSsize_t(i);
4710 if (ival != NULL) {
4711 args = PyTuple_New(1);
4712 if (args != NULL) {
4713 PyTuple_SET_ITEM(args, 0, ival);
4714 retval = PyObject_Call(func, args, NULL);
4715 Py_XDECREF(args);
4716 Py_XDECREF(func);
4717 return retval;
4718 }
4719 }
4720 }
4721 else {
4722 PyErr_SetObject(PyExc_AttributeError, getitem_str);
4723 }
4724 Py_XDECREF(args);
4725 Py_XDECREF(ival);
4726 Py_XDECREF(func);
4727 return NULL;
Guido van Rossumf4593e02001-10-03 12:09:30 +00004728}
4729
Tim Peters6d6c1a32001-08-02 04:15:00 +00004730static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00004731slot_sq_ass_item(PyObject *self, Py_ssize_t index, PyObject *value)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004732{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004733 PyObject *res;
4734 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004735
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004736 if (value == NULL)
4737 res = call_method(self, "__delitem__", &delitem_str,
4738 "(n)", index);
4739 else
4740 res = call_method(self, "__setitem__", &setitem_str,
4741 "(nO)", index, value);
4742 if (res == NULL)
4743 return -1;
4744 Py_DECREF(res);
4745 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004746}
4747
4748static int
Tim Peters6d6c1a32001-08-02 04:15:00 +00004749slot_sq_contains(PyObject *self, PyObject *value)
4750{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004751 PyObject *func, *res, *args;
4752 int result = -1;
Tim Petersbf9b2442003-03-23 05:35:36 +00004753
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004754 static PyObject *contains_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004755
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004756 func = lookup_maybe(self, "__contains__", &contains_str);
4757 if (func != NULL) {
4758 args = PyTuple_Pack(1, value);
4759 if (args == NULL)
4760 res = NULL;
4761 else {
4762 res = PyObject_Call(func, args, NULL);
4763 Py_DECREF(args);
4764 }
4765 Py_DECREF(func);
4766 if (res != NULL) {
4767 result = PyObject_IsTrue(res);
4768 Py_DECREF(res);
4769 }
4770 }
4771 else if (! PyErr_Occurred()) {
4772 /* Possible results: -1 and 1 */
4773 result = (int)_PySequence_IterSearch(self, value,
4774 PY_ITERSEARCH_CONTAINS);
4775 }
4776 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004777}
4778
Tim Peters6d6c1a32001-08-02 04:15:00 +00004779#define slot_mp_length slot_sq_length
4780
Guido van Rossumdc91b992001-08-08 22:26:22 +00004781SLOT1(slot_mp_subscript, "__getitem__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004782
4783static int
4784slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value)
4785{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004786 PyObject *res;
4787 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004788
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004789 if (value == NULL)
4790 res = call_method(self, "__delitem__", &delitem_str,
4791 "(O)", key);
4792 else
4793 res = call_method(self, "__setitem__", &setitem_str,
4794 "(OO)", key, value);
4795 if (res == NULL)
4796 return -1;
4797 Py_DECREF(res);
4798 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004799}
4800
Guido van Rossumdc91b992001-08-08 22:26:22 +00004801SLOT1BIN(slot_nb_add, nb_add, "__add__", "__radd__")
4802SLOT1BIN(slot_nb_subtract, nb_subtract, "__sub__", "__rsub__")
4803SLOT1BIN(slot_nb_multiply, nb_multiply, "__mul__", "__rmul__")
Guido van Rossumdc91b992001-08-08 22:26:22 +00004804SLOT1BIN(slot_nb_remainder, nb_remainder, "__mod__", "__rmod__")
4805SLOT1BIN(slot_nb_divmod, nb_divmod, "__divmod__", "__rdivmod__")
4806
Jeremy Hylton938ace62002-07-17 16:30:39 +00004807static PyObject *slot_nb_power(PyObject *, PyObject *, PyObject *);
Guido van Rossumdc91b992001-08-08 22:26:22 +00004808
4809SLOT1BINFULL(slot_nb_power_binary, slot_nb_power,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004810 nb_power, "__pow__", "__rpow__")
Guido van Rossumdc91b992001-08-08 22:26:22 +00004811
4812static PyObject *
4813slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus)
4814{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004815 static PyObject *pow_str;
Guido van Rossum2730b132001-08-28 18:22:14 +00004816
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004817 if (modulus == Py_None)
4818 return slot_nb_power_binary(self, other);
4819 /* Three-arg power doesn't use __rpow__. But ternary_op
4820 can call this when the second argument's type uses
4821 slot_nb_power, so check before calling self.__pow__. */
4822 if (Py_TYPE(self)->tp_as_number != NULL &&
4823 Py_TYPE(self)->tp_as_number->nb_power == slot_nb_power) {
4824 return call_method(self, "__pow__", &pow_str,
4825 "(OO)", other, modulus);
4826 }
4827 Py_INCREF(Py_NotImplemented);
4828 return Py_NotImplemented;
Guido van Rossumdc91b992001-08-08 22:26:22 +00004829}
4830
4831SLOT0(slot_nb_negative, "__neg__")
4832SLOT0(slot_nb_positive, "__pos__")
4833SLOT0(slot_nb_absolute, "__abs__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004834
4835static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00004836slot_nb_bool(PyObject *self)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004837{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004838 PyObject *func, *args;
4839 static PyObject *bool_str, *len_str;
4840 int result = -1;
4841 int using_len = 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004842
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004843 func = lookup_maybe(self, "__bool__", &bool_str);
4844 if (func == NULL) {
4845 if (PyErr_Occurred())
4846 return -1;
4847 func = lookup_maybe(self, "__len__", &len_str);
4848 if (func == NULL)
4849 return PyErr_Occurred() ? -1 : 1;
4850 using_len = 1;
4851 }
4852 args = PyTuple_New(0);
4853 if (args != NULL) {
4854 PyObject *temp = PyObject_Call(func, args, NULL);
4855 Py_DECREF(args);
4856 if (temp != NULL) {
4857 if (using_len) {
4858 /* enforced by slot_nb_len */
4859 result = PyObject_IsTrue(temp);
4860 }
4861 else if (PyBool_Check(temp)) {
4862 result = PyObject_IsTrue(temp);
4863 }
4864 else {
4865 PyErr_Format(PyExc_TypeError,
4866 "__bool__ should return "
4867 "bool, returned %s",
4868 Py_TYPE(temp)->tp_name);
4869 result = -1;
4870 }
4871 Py_DECREF(temp);
4872 }
4873 }
4874 Py_DECREF(func);
4875 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004876}
4877
Guido van Rossum38fff8c2006-03-07 18:50:55 +00004878
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00004879static PyObject *
Guido van Rossum38fff8c2006-03-07 18:50:55 +00004880slot_nb_index(PyObject *self)
4881{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004882 static PyObject *index_str;
4883 return call_method(self, "__index__", &index_str, "()");
Guido van Rossum38fff8c2006-03-07 18:50:55 +00004884}
4885
4886
Guido van Rossumdc91b992001-08-08 22:26:22 +00004887SLOT0(slot_nb_invert, "__invert__")
4888SLOT1BIN(slot_nb_lshift, nb_lshift, "__lshift__", "__rlshift__")
4889SLOT1BIN(slot_nb_rshift, nb_rshift, "__rshift__", "__rrshift__")
4890SLOT1BIN(slot_nb_and, nb_and, "__and__", "__rand__")
4891SLOT1BIN(slot_nb_xor, nb_xor, "__xor__", "__rxor__")
4892SLOT1BIN(slot_nb_or, nb_or, "__or__", "__ror__")
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004893
Guido van Rossumdc91b992001-08-08 22:26:22 +00004894SLOT0(slot_nb_int, "__int__")
Guido van Rossumdc91b992001-08-08 22:26:22 +00004895SLOT0(slot_nb_float, "__float__")
Guido van Rossumdc91b992001-08-08 22:26:22 +00004896SLOT1(slot_nb_inplace_add, "__iadd__", PyObject *, "O")
4897SLOT1(slot_nb_inplace_subtract, "__isub__", PyObject *, "O")
4898SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *, "O")
Guido van Rossumdc91b992001-08-08 22:26:22 +00004899SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *, "O")
Thomas Wouterscf297e42007-02-23 15:07:44 +00004900/* Can't use SLOT1 here, because nb_inplace_power is ternary */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004901static PyObject *
4902slot_nb_inplace_power(PyObject *self, PyObject * arg1, PyObject *arg2)
4903{
4904 static PyObject *cache_str;
4905 return call_method(self, "__ipow__", &cache_str, "(" "O" ")", arg1);
Thomas Wouterscf297e42007-02-23 15:07:44 +00004906}
Guido van Rossumdc91b992001-08-08 22:26:22 +00004907SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *, "O")
4908SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *, "O")
4909SLOT1(slot_nb_inplace_and, "__iand__", PyObject *, "O")
4910SLOT1(slot_nb_inplace_xor, "__ixor__", PyObject *, "O")
4911SLOT1(slot_nb_inplace_or, "__ior__", PyObject *, "O")
4912SLOT1BIN(slot_nb_floor_divide, nb_floor_divide,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004913 "__floordiv__", "__rfloordiv__")
Guido van Rossumdc91b992001-08-08 22:26:22 +00004914SLOT1BIN(slot_nb_true_divide, nb_true_divide, "__truediv__", "__rtruediv__")
4915SLOT1(slot_nb_inplace_floor_divide, "__ifloordiv__", PyObject *, "O")
4916SLOT1(slot_nb_inplace_true_divide, "__itruediv__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004917
Guido van Rossumb8f63662001-08-15 23:57:02 +00004918static PyObject *
4919slot_tp_repr(PyObject *self)
4920{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004921 PyObject *func, *res;
4922 static PyObject *repr_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004923
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004924 func = lookup_method(self, "__repr__", &repr_str);
4925 if (func != NULL) {
4926 res = PyEval_CallObject(func, NULL);
4927 Py_DECREF(func);
4928 return res;
4929 }
4930 PyErr_Clear();
4931 return PyUnicode_FromFormat("<%s object at %p>",
4932 Py_TYPE(self)->tp_name, self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004933}
4934
4935static PyObject *
4936slot_tp_str(PyObject *self)
4937{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004938 PyObject *func, *res;
4939 static PyObject *str_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004940
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004941 func = lookup_method(self, "__str__", &str_str);
4942 if (func != NULL) {
4943 res = PyEval_CallObject(func, NULL);
4944 Py_DECREF(func);
4945 return res;
4946 }
4947 else {
4948 PyObject *ress;
4949 PyErr_Clear();
4950 res = slot_tp_repr(self);
4951 if (!res)
4952 return NULL;
4953 ress = _PyUnicode_AsDefaultEncodedString(res, NULL);
4954 Py_DECREF(res);
4955 return ress;
4956 }
Guido van Rossumb8f63662001-08-15 23:57:02 +00004957}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004958
Benjamin Peterson8f67d082010-10-17 20:54:53 +00004959static Py_hash_t
Tim Peters6d6c1a32001-08-02 04:15:00 +00004960slot_tp_hash(PyObject *self)
4961{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004962 PyObject *func, *res;
4963 static PyObject *hash_str;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00004964 Py_ssize_t h;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004965
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004966 func = lookup_method(self, "__hash__", &hash_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004967
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004968 if (func == Py_None) {
4969 Py_DECREF(func);
4970 func = NULL;
4971 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +00004972
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004973 if (func == NULL) {
4974 return PyObject_HashNotImplemented(self);
4975 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +00004976
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004977 res = PyEval_CallObject(func, NULL);
4978 Py_DECREF(func);
4979 if (res == NULL)
4980 return -1;
Mark Dickinsondc787d22010-05-23 13:33:13 +00004981
4982 if (!PyLong_Check(res)) {
4983 PyErr_SetString(PyExc_TypeError,
4984 "__hash__ method should return an integer");
4985 return -1;
4986 }
Benjamin Peterson8f67d082010-10-17 20:54:53 +00004987 /* Transform the PyLong `res` to a Py_hash_t `h`. For an existing
4988 hashable Python object x, hash(x) will always lie within the range of
4989 Py_hash_t. Therefore our transformation must preserve values that
4990 already lie within this range, to ensure that if x.__hash__() returns
4991 hash(y) then hash(x) == hash(y). */
4992 h = PyLong_AsSsize_t(res);
4993 if (h == -1 && PyErr_Occurred()) {
4994 /* res was not within the range of a Py_hash_t, so we're free to
Mark Dickinsondc787d22010-05-23 13:33:13 +00004995 use any sufficiently bit-mixing transformation;
4996 long.__hash__ will do nicely. */
Benjamin Peterson8f67d082010-10-17 20:54:53 +00004997 PyErr_Clear();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004998 h = PyLong_Type.tp_hash(res);
Benjamin Peterson8f67d082010-10-17 20:54:53 +00004999 }
Benjamin Petersone7dfeeb2010-10-17 21:27:01 +00005000 /* -1 is reserved for errors. */
5001 if (h == -1)
5002 h = -2;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005003 Py_DECREF(res);
Mark Dickinsondc787d22010-05-23 13:33:13 +00005004 return h;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005005}
5006
5007static PyObject *
5008slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds)
5009{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005010 static PyObject *call_str;
5011 PyObject *meth = lookup_method(self, "__call__", &call_str);
5012 PyObject *res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005013
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005014 if (meth == NULL)
5015 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005016
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005017 res = PyObject_Call(meth, args, kwds);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005018
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005019 Py_DECREF(meth);
5020 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005021}
5022
Guido van Rossum14a6f832001-10-17 13:59:09 +00005023/* There are two slot dispatch functions for tp_getattro.
5024
5025 - slot_tp_getattro() is used when __getattribute__ is overridden
5026 but no __getattr__ hook is present;
5027
5028 - slot_tp_getattr_hook() is used when a __getattr__ hook is present.
5029
Guido van Rossumc334df52002-04-04 23:44:47 +00005030 The code in update_one_slot() always installs slot_tp_getattr_hook(); this
5031 detects the absence of __getattr__ and then installs the simpler slot if
5032 necessary. */
Guido van Rossum14a6f832001-10-17 13:59:09 +00005033
Tim Peters6d6c1a32001-08-02 04:15:00 +00005034static PyObject *
5035slot_tp_getattro(PyObject *self, PyObject *name)
5036{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005037 static PyObject *getattribute_str = NULL;
5038 return call_method(self, "__getattribute__", &getattribute_str,
5039 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005040}
5041
Guido van Rossum19c1cd52001-09-21 21:24:49 +00005042static PyObject *
Benjamin Peterson9262b842008-11-17 22:45:50 +00005043call_attribute(PyObject *self, PyObject *attr, PyObject *name)
5044{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005045 PyObject *res, *descr = NULL;
5046 descrgetfunc f = Py_TYPE(attr)->tp_descr_get;
Benjamin Peterson9262b842008-11-17 22:45:50 +00005047
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005048 if (f != NULL) {
5049 descr = f(attr, self, (PyObject *)(Py_TYPE(self)));
5050 if (descr == NULL)
5051 return NULL;
5052 else
5053 attr = descr;
5054 }
5055 res = PyObject_CallFunctionObjArgs(attr, name, NULL);
5056 Py_XDECREF(descr);
5057 return res;
Benjamin Peterson9262b842008-11-17 22:45:50 +00005058}
5059
5060static PyObject *
Guido van Rossum19c1cd52001-09-21 21:24:49 +00005061slot_tp_getattr_hook(PyObject *self, PyObject *name)
5062{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005063 PyTypeObject *tp = Py_TYPE(self);
5064 PyObject *getattr, *getattribute, *res;
5065 static PyObject *getattribute_str = NULL;
5066 static PyObject *getattr_str = NULL;
Guido van Rossum19c1cd52001-09-21 21:24:49 +00005067
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005068 if (getattr_str == NULL) {
5069 getattr_str = PyUnicode_InternFromString("__getattr__");
5070 if (getattr_str == NULL)
5071 return NULL;
5072 }
5073 if (getattribute_str == NULL) {
5074 getattribute_str =
5075 PyUnicode_InternFromString("__getattribute__");
5076 if (getattribute_str == NULL)
5077 return NULL;
5078 }
5079 /* speed hack: we could use lookup_maybe, but that would resolve the
5080 method fully for each attribute lookup for classes with
5081 __getattr__, even when the attribute is present. So we use
5082 _PyType_Lookup and create the method only when needed, with
5083 call_attribute. */
5084 getattr = _PyType_Lookup(tp, getattr_str);
5085 if (getattr == NULL) {
5086 /* No __getattr__ hook: use a simpler dispatcher */
5087 tp->tp_getattro = slot_tp_getattro;
5088 return slot_tp_getattro(self, name);
5089 }
5090 Py_INCREF(getattr);
5091 /* speed hack: we could use lookup_maybe, but that would resolve the
5092 method fully for each attribute lookup for classes with
5093 __getattr__, even when self has the default __getattribute__
5094 method. So we use _PyType_Lookup and create the method only when
5095 needed, with call_attribute. */
5096 getattribute = _PyType_Lookup(tp, getattribute_str);
5097 if (getattribute == NULL ||
5098 (Py_TYPE(getattribute) == &PyWrapperDescr_Type &&
5099 ((PyWrapperDescrObject *)getattribute)->d_wrapped ==
5100 (void *)PyObject_GenericGetAttr))
5101 res = PyObject_GenericGetAttr(self, name);
5102 else {
5103 Py_INCREF(getattribute);
5104 res = call_attribute(self, getattribute, name);
5105 Py_DECREF(getattribute);
5106 }
5107 if (res == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) {
5108 PyErr_Clear();
5109 res = call_attribute(self, getattr, name);
5110 }
5111 Py_DECREF(getattr);
5112 return res;
Guido van Rossum19c1cd52001-09-21 21:24:49 +00005113}
5114
Tim Peters6d6c1a32001-08-02 04:15:00 +00005115static int
5116slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value)
5117{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005118 PyObject *res;
5119 static PyObject *delattr_str, *setattr_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005120
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005121 if (value == NULL)
5122 res = call_method(self, "__delattr__", &delattr_str,
5123 "(O)", name);
5124 else
5125 res = call_method(self, "__setattr__", &setattr_str,
5126 "(OO)", name, value);
5127 if (res == NULL)
5128 return -1;
5129 Py_DECREF(res);
5130 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005131}
5132
Guido van Rossumf5243f02008-01-01 04:06:48 +00005133static char *name_op[] = {
5134 "__lt__",
5135 "__le__",
5136 "__eq__",
5137 "__ne__",
5138 "__gt__",
5139 "__ge__",
5140};
5141
Tim Peters6d6c1a32001-08-02 04:15:00 +00005142static PyObject *
Mark Dickinson6f1d0492009-11-15 13:58:49 +00005143slot_tp_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005144{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005145 PyObject *func, *args, *res;
5146 static PyObject *op_str[6];
Tim Peters6d6c1a32001-08-02 04:15:00 +00005147
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005148 func = lookup_method(self, name_op[op], &op_str[op]);
5149 if (func == NULL) {
5150 PyErr_Clear();
5151 Py_INCREF(Py_NotImplemented);
5152 return Py_NotImplemented;
5153 }
5154 args = PyTuple_Pack(1, other);
5155 if (args == NULL)
5156 res = NULL;
5157 else {
5158 res = PyObject_Call(func, args, NULL);
5159 Py_DECREF(args);
5160 }
5161 Py_DECREF(func);
5162 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005163}
5164
Guido van Rossumb8f63662001-08-15 23:57:02 +00005165static PyObject *
Guido van Rossumb8f63662001-08-15 23:57:02 +00005166slot_tp_iter(PyObject *self)
5167{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005168 PyObject *func, *res;
5169 static PyObject *iter_str, *getitem_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00005170
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005171 func = lookup_method(self, "__iter__", &iter_str);
5172 if (func != NULL) {
5173 PyObject *args;
5174 args = res = PyTuple_New(0);
5175 if (args != NULL) {
5176 res = PyObject_Call(func, args, NULL);
5177 Py_DECREF(args);
5178 }
5179 Py_DECREF(func);
5180 return res;
5181 }
5182 PyErr_Clear();
5183 func = lookup_method(self, "__getitem__", &getitem_str);
5184 if (func == NULL) {
5185 PyErr_Format(PyExc_TypeError,
5186 "'%.200s' object is not iterable",
5187 Py_TYPE(self)->tp_name);
5188 return NULL;
5189 }
5190 Py_DECREF(func);
5191 return PySeqIter_New(self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005192}
Tim Peters6d6c1a32001-08-02 04:15:00 +00005193
5194static PyObject *
5195slot_tp_iternext(PyObject *self)
5196{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005197 static PyObject *next_str;
5198 return call_method(self, "__next__", &next_str, "()");
Tim Peters6d6c1a32001-08-02 04:15:00 +00005199}
5200
Guido van Rossum1a493502001-08-17 16:47:50 +00005201static PyObject *
5202slot_tp_descr_get(PyObject *self, PyObject *obj, PyObject *type)
5203{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005204 PyTypeObject *tp = Py_TYPE(self);
5205 PyObject *get;
5206 static PyObject *get_str = NULL;
Guido van Rossum1a493502001-08-17 16:47:50 +00005207
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005208 if (get_str == NULL) {
5209 get_str = PyUnicode_InternFromString("__get__");
5210 if (get_str == NULL)
5211 return NULL;
5212 }
5213 get = _PyType_Lookup(tp, get_str);
5214 if (get == NULL) {
5215 /* Avoid further slowdowns */
5216 if (tp->tp_descr_get == slot_tp_descr_get)
5217 tp->tp_descr_get = NULL;
5218 Py_INCREF(self);
5219 return self;
5220 }
5221 if (obj == NULL)
5222 obj = Py_None;
5223 if (type == NULL)
5224 type = Py_None;
5225 return PyObject_CallFunctionObjArgs(get, self, obj, type, NULL);
Guido van Rossum1a493502001-08-17 16:47:50 +00005226}
Tim Peters6d6c1a32001-08-02 04:15:00 +00005227
5228static int
5229slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value)
5230{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005231 PyObject *res;
5232 static PyObject *del_str, *set_str;
Guido van Rossum2c252392001-08-24 10:13:31 +00005233
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005234 if (value == NULL)
5235 res = call_method(self, "__delete__", &del_str,
5236 "(O)", target);
5237 else
5238 res = call_method(self, "__set__", &set_str,
5239 "(OO)", target, value);
5240 if (res == NULL)
5241 return -1;
5242 Py_DECREF(res);
5243 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005244}
5245
5246static int
5247slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds)
5248{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005249 static PyObject *init_str;
5250 PyObject *meth = lookup_method(self, "__init__", &init_str);
5251 PyObject *res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005252
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005253 if (meth == NULL)
5254 return -1;
5255 res = PyObject_Call(meth, args, kwds);
5256 Py_DECREF(meth);
5257 if (res == NULL)
5258 return -1;
5259 if (res != Py_None) {
5260 PyErr_Format(PyExc_TypeError,
5261 "__init__() should return None, not '%.200s'",
5262 Py_TYPE(res)->tp_name);
5263 Py_DECREF(res);
5264 return -1;
5265 }
5266 Py_DECREF(res);
5267 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005268}
5269
5270static PyObject *
5271slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
5272{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005273 static PyObject *new_str;
5274 PyObject *func;
5275 PyObject *newargs, *x;
5276 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005277
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005278 if (new_str == NULL) {
5279 new_str = PyUnicode_InternFromString("__new__");
5280 if (new_str == NULL)
5281 return NULL;
5282 }
5283 func = PyObject_GetAttr((PyObject *)type, new_str);
5284 if (func == NULL)
5285 return NULL;
5286 assert(PyTuple_Check(args));
5287 n = PyTuple_GET_SIZE(args);
5288 newargs = PyTuple_New(n+1);
5289 if (newargs == NULL)
5290 return NULL;
5291 Py_INCREF(type);
5292 PyTuple_SET_ITEM(newargs, 0, (PyObject *)type);
5293 for (i = 0; i < n; i++) {
5294 x = PyTuple_GET_ITEM(args, i);
5295 Py_INCREF(x);
5296 PyTuple_SET_ITEM(newargs, i+1, x);
5297 }
5298 x = PyObject_Call(func, newargs, kwds);
5299 Py_DECREF(newargs);
5300 Py_DECREF(func);
5301 return x;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005302}
5303
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005304static void
5305slot_tp_del(PyObject *self)
5306{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005307 static PyObject *del_str = NULL;
5308 PyObject *del, *res;
5309 PyObject *error_type, *error_value, *error_traceback;
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005310
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005311 /* Temporarily resurrect the object. */
5312 assert(self->ob_refcnt == 0);
5313 self->ob_refcnt = 1;
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005314
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005315 /* Save the current exception, if any. */
5316 PyErr_Fetch(&error_type, &error_value, &error_traceback);
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005317
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005318 /* Execute __del__ method, if any. */
5319 del = lookup_maybe(self, "__del__", &del_str);
5320 if (del != NULL) {
5321 res = PyEval_CallObject(del, NULL);
5322 if (res == NULL)
5323 PyErr_WriteUnraisable(del);
5324 else
5325 Py_DECREF(res);
5326 Py_DECREF(del);
5327 }
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005328
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005329 /* Restore the saved exception. */
5330 PyErr_Restore(error_type, error_value, error_traceback);
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005331
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005332 /* Undo the temporary resurrection; can't use DECREF here, it would
5333 * cause a recursive call.
5334 */
5335 assert(self->ob_refcnt > 0);
5336 if (--self->ob_refcnt == 0)
5337 return; /* this is the normal path out */
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005338
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005339 /* __del__ resurrected it! Make it look like the original Py_DECREF
5340 * never happened.
5341 */
5342 {
5343 Py_ssize_t refcnt = self->ob_refcnt;
5344 _Py_NewReference(self);
5345 self->ob_refcnt = refcnt;
5346 }
5347 assert(!PyType_IS_GC(Py_TYPE(self)) ||
5348 _Py_AS_GC(self)->gc.gc_refs != _PyGC_REFS_UNTRACKED);
5349 /* If Py_REF_DEBUG, _Py_NewReference bumped _Py_RefTotal, so
5350 * we need to undo that. */
5351 _Py_DEC_REFTOTAL;
5352 /* If Py_TRACE_REFS, _Py_NewReference re-added self to the object
5353 * chain, so no more to do there.
5354 * If COUNT_ALLOCS, the original decref bumped tp_frees, and
5355 * _Py_NewReference bumped tp_allocs: both of those need to be
5356 * undone.
5357 */
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005358#ifdef COUNT_ALLOCS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005359 --Py_TYPE(self)->tp_frees;
5360 --Py_TYPE(self)->tp_allocs;
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005361#endif
5362}
5363
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005364
5365/* Table mapping __foo__ names to tp_foo offsets and slot_tp_foo wrapper
Tim Petersbf9b2442003-03-23 05:35:36 +00005366 functions. The offsets here are relative to the 'PyHeapTypeObject'
Guido van Rossume5c691a2003-03-07 15:13:17 +00005367 structure, which incorporates the additional structures used for numbers,
5368 sequences and mappings.
5369 Note that multiple names may map to the same slot (e.g. __eq__,
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005370 __ne__ etc. all map to tp_richcompare) and one name may map to multiple
Guido van Rossumc334df52002-04-04 23:44:47 +00005371 slots (e.g. __str__ affects tp_str as well as tp_repr). The table is
5372 terminated with an all-zero entry. (This table is further initialized and
5373 sorted in init_slotdefs() below.) */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005374
Guido van Rossum6d204072001-10-21 00:44:31 +00005375typedef struct wrapperbase slotdef;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005376
5377#undef TPSLOT
Guido van Rossumc8e56452001-10-22 00:43:43 +00005378#undef FLSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005379#undef ETSLOT
5380#undef SQSLOT
5381#undef MPSLOT
5382#undef NBSLOT
Guido van Rossum6d204072001-10-21 00:44:31 +00005383#undef UNSLOT
5384#undef IBSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005385#undef BINSLOT
5386#undef RBINSLOT
5387
Guido van Rossum6d204072001-10-21 00:44:31 +00005388#define TPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005389 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
5390 PyDoc_STR(DOC)}
Guido van Rossumc8e56452001-10-22 00:43:43 +00005391#define FLSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC, FLAGS) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005392 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
5393 PyDoc_STR(DOC), FLAGS}
Guido van Rossum6d204072001-10-21 00:44:31 +00005394#define ETSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005395 {NAME, offsetof(PyHeapTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
5396 PyDoc_STR(DOC)}
Guido van Rossum6d204072001-10-21 00:44:31 +00005397#define SQSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005398 ETSLOT(NAME, as_sequence.SLOT, FUNCTION, WRAPPER, DOC)
Guido van Rossum6d204072001-10-21 00:44:31 +00005399#define MPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005400 ETSLOT(NAME, as_mapping.SLOT, FUNCTION, WRAPPER, DOC)
Guido van Rossum6d204072001-10-21 00:44:31 +00005401#define NBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005402 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, DOC)
Guido van Rossum6d204072001-10-21 00:44:31 +00005403#define UNSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005404 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
5405 "x." NAME "() <==> " DOC)
Guido van Rossum6d204072001-10-21 00:44:31 +00005406#define IBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005407 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
5408 "x." NAME "(y) <==> x" DOC "y")
Guido van Rossum6d204072001-10-21 00:44:31 +00005409#define BINSLOT(NAME, SLOT, FUNCTION, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005410 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
5411 "x." NAME "(y) <==> x" DOC "y")
Guido van Rossum6d204072001-10-21 00:44:31 +00005412#define RBINSLOT(NAME, SLOT, FUNCTION, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005413 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
5414 "x." NAME "(y) <==> y" DOC "x")
Anthony Baxter56616992005-06-03 14:12:21 +00005415#define BINSLOTNOTINFIX(NAME, SLOT, FUNCTION, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005416 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
5417 "x." NAME "(y) <==> " DOC)
Anthony Baxter56616992005-06-03 14:12:21 +00005418#define RBINSLOTNOTINFIX(NAME, SLOT, FUNCTION, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005419 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
5420 "x." NAME "(y) <==> " DOC)
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005421
5422static slotdef slotdefs[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005423 SQSLOT("__len__", sq_length, slot_sq_length, wrap_lenfunc,
5424 "x.__len__() <==> len(x)"),
5425 /* Heap types defining __add__/__mul__ have sq_concat/sq_repeat == NULL.
5426 The logic in abstract.c always falls back to nb_add/nb_multiply in
5427 this case. Defining both the nb_* and the sq_* slots to call the
5428 user-defined methods has unexpected side-effects, as shown by
5429 test_descr.notimplemented() */
5430 SQSLOT("__add__", sq_concat, NULL, wrap_binaryfunc,
5431 "x.__add__(y) <==> x+y"),
5432 SQSLOT("__mul__", sq_repeat, NULL, wrap_indexargfunc,
5433 "x.__mul__(n) <==> x*n"),
5434 SQSLOT("__rmul__", sq_repeat, NULL, wrap_indexargfunc,
5435 "x.__rmul__(n) <==> n*x"),
5436 SQSLOT("__getitem__", sq_item, slot_sq_item, wrap_sq_item,
5437 "x.__getitem__(y) <==> x[y]"),
5438 SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_setitem,
5439 "x.__setitem__(i, y) <==> x[i]=y"),
5440 SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_delitem,
5441 "x.__delitem__(y) <==> del x[y]"),
5442 SQSLOT("__contains__", sq_contains, slot_sq_contains, wrap_objobjproc,
5443 "x.__contains__(y) <==> y in x"),
5444 SQSLOT("__iadd__", sq_inplace_concat, NULL,
5445 wrap_binaryfunc, "x.__iadd__(y) <==> x+=y"),
5446 SQSLOT("__imul__", sq_inplace_repeat, NULL,
5447 wrap_indexargfunc, "x.__imul__(y) <==> x*=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005448
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005449 MPSLOT("__len__", mp_length, slot_mp_length, wrap_lenfunc,
5450 "x.__len__() <==> len(x)"),
5451 MPSLOT("__getitem__", mp_subscript, slot_mp_subscript,
5452 wrap_binaryfunc,
5453 "x.__getitem__(y) <==> x[y]"),
5454 MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript,
5455 wrap_objobjargproc,
5456 "x.__setitem__(i, y) <==> x[i]=y"),
5457 MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript,
5458 wrap_delitem,
5459 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005460
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005461 BINSLOT("__add__", nb_add, slot_nb_add,
5462 "+"),
5463 RBINSLOT("__radd__", nb_add, slot_nb_add,
5464 "+"),
5465 BINSLOT("__sub__", nb_subtract, slot_nb_subtract,
5466 "-"),
5467 RBINSLOT("__rsub__", nb_subtract, slot_nb_subtract,
5468 "-"),
5469 BINSLOT("__mul__", nb_multiply, slot_nb_multiply,
5470 "*"),
5471 RBINSLOT("__rmul__", nb_multiply, slot_nb_multiply,
5472 "*"),
5473 BINSLOT("__mod__", nb_remainder, slot_nb_remainder,
5474 "%"),
5475 RBINSLOT("__rmod__", nb_remainder, slot_nb_remainder,
5476 "%"),
5477 BINSLOTNOTINFIX("__divmod__", nb_divmod, slot_nb_divmod,
5478 "divmod(x, y)"),
5479 RBINSLOTNOTINFIX("__rdivmod__", nb_divmod, slot_nb_divmod,
5480 "divmod(y, x)"),
5481 NBSLOT("__pow__", nb_power, slot_nb_power, wrap_ternaryfunc,
5482 "x.__pow__(y[, z]) <==> pow(x, y[, z])"),
5483 NBSLOT("__rpow__", nb_power, slot_nb_power, wrap_ternaryfunc_r,
5484 "y.__rpow__(x[, z]) <==> pow(x, y[, z])"),
5485 UNSLOT("__neg__", nb_negative, slot_nb_negative, wrap_unaryfunc, "-x"),
5486 UNSLOT("__pos__", nb_positive, slot_nb_positive, wrap_unaryfunc, "+x"),
5487 UNSLOT("__abs__", nb_absolute, slot_nb_absolute, wrap_unaryfunc,
5488 "abs(x)"),
5489 UNSLOT("__bool__", nb_bool, slot_nb_bool, wrap_inquirypred,
5490 "x != 0"),
5491 UNSLOT("__invert__", nb_invert, slot_nb_invert, wrap_unaryfunc, "~x"),
5492 BINSLOT("__lshift__", nb_lshift, slot_nb_lshift, "<<"),
5493 RBINSLOT("__rlshift__", nb_lshift, slot_nb_lshift, "<<"),
5494 BINSLOT("__rshift__", nb_rshift, slot_nb_rshift, ">>"),
5495 RBINSLOT("__rrshift__", nb_rshift, slot_nb_rshift, ">>"),
5496 BINSLOT("__and__", nb_and, slot_nb_and, "&"),
5497 RBINSLOT("__rand__", nb_and, slot_nb_and, "&"),
5498 BINSLOT("__xor__", nb_xor, slot_nb_xor, "^"),
5499 RBINSLOT("__rxor__", nb_xor, slot_nb_xor, "^"),
5500 BINSLOT("__or__", nb_or, slot_nb_or, "|"),
5501 RBINSLOT("__ror__", nb_or, slot_nb_or, "|"),
5502 UNSLOT("__int__", nb_int, slot_nb_int, wrap_unaryfunc,
5503 "int(x)"),
5504 UNSLOT("__float__", nb_float, slot_nb_float, wrap_unaryfunc,
5505 "float(x)"),
5506 NBSLOT("__index__", nb_index, slot_nb_index, wrap_unaryfunc,
5507 "x[y:z] <==> x[y.__index__():z.__index__()]"),
5508 IBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add,
5509 wrap_binaryfunc, "+"),
5510 IBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract,
5511 wrap_binaryfunc, "-"),
5512 IBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply,
5513 wrap_binaryfunc, "*"),
5514 IBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder,
5515 wrap_binaryfunc, "%"),
5516 IBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power,
5517 wrap_binaryfunc, "**"),
5518 IBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift,
5519 wrap_binaryfunc, "<<"),
5520 IBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift,
5521 wrap_binaryfunc, ">>"),
5522 IBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and,
5523 wrap_binaryfunc, "&"),
5524 IBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor,
5525 wrap_binaryfunc, "^"),
5526 IBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or,
5527 wrap_binaryfunc, "|"),
5528 BINSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
5529 RBINSLOT("__rfloordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
5530 BINSLOT("__truediv__", nb_true_divide, slot_nb_true_divide, "/"),
5531 RBINSLOT("__rtruediv__", nb_true_divide, slot_nb_true_divide, "/"),
5532 IBSLOT("__ifloordiv__", nb_inplace_floor_divide,
5533 slot_nb_inplace_floor_divide, wrap_binaryfunc, "//"),
5534 IBSLOT("__itruediv__", nb_inplace_true_divide,
5535 slot_nb_inplace_true_divide, wrap_binaryfunc, "/"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005536
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005537 TPSLOT("__str__", tp_str, slot_tp_str, wrap_unaryfunc,
5538 "x.__str__() <==> str(x)"),
5539 TPSLOT("__repr__", tp_repr, slot_tp_repr, wrap_unaryfunc,
5540 "x.__repr__() <==> repr(x)"),
5541 TPSLOT("__hash__", tp_hash, slot_tp_hash, wrap_hashfunc,
5542 "x.__hash__() <==> hash(x)"),
5543 FLSLOT("__call__", tp_call, slot_tp_call, (wrapperfunc)wrap_call,
5544 "x.__call__(...) <==> x(...)", PyWrapperFlag_KEYWORDS),
5545 TPSLOT("__getattribute__", tp_getattro, slot_tp_getattr_hook,
5546 wrap_binaryfunc, "x.__getattribute__('name') <==> x.name"),
5547 TPSLOT("__getattribute__", tp_getattr, NULL, NULL, ""),
5548 TPSLOT("__getattr__", tp_getattro, slot_tp_getattr_hook, NULL, ""),
5549 TPSLOT("__getattr__", tp_getattr, NULL, NULL, ""),
5550 TPSLOT("__setattr__", tp_setattro, slot_tp_setattro, wrap_setattr,
5551 "x.__setattr__('name', value) <==> x.name = value"),
5552 TPSLOT("__setattr__", tp_setattr, NULL, NULL, ""),
5553 TPSLOT("__delattr__", tp_setattro, slot_tp_setattro, wrap_delattr,
5554 "x.__delattr__('name') <==> del x.name"),
5555 TPSLOT("__delattr__", tp_setattr, NULL, NULL, ""),
5556 TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare, richcmp_lt,
5557 "x.__lt__(y) <==> x<y"),
5558 TPSLOT("__le__", tp_richcompare, slot_tp_richcompare, richcmp_le,
5559 "x.__le__(y) <==> x<=y"),
5560 TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare, richcmp_eq,
5561 "x.__eq__(y) <==> x==y"),
5562 TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare, richcmp_ne,
5563 "x.__ne__(y) <==> x!=y"),
5564 TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare, richcmp_gt,
5565 "x.__gt__(y) <==> x>y"),
5566 TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare, richcmp_ge,
5567 "x.__ge__(y) <==> x>=y"),
5568 TPSLOT("__iter__", tp_iter, slot_tp_iter, wrap_unaryfunc,
5569 "x.__iter__() <==> iter(x)"),
5570 TPSLOT("__next__", tp_iternext, slot_tp_iternext, wrap_next,
5571 "x.__next__() <==> next(x)"),
5572 TPSLOT("__get__", tp_descr_get, slot_tp_descr_get, wrap_descr_get,
5573 "descr.__get__(obj[, type]) -> value"),
5574 TPSLOT("__set__", tp_descr_set, slot_tp_descr_set, wrap_descr_set,
5575 "descr.__set__(obj, value)"),
5576 TPSLOT("__delete__", tp_descr_set, slot_tp_descr_set,
5577 wrap_descr_delete, "descr.__delete__(obj)"),
5578 FLSLOT("__init__", tp_init, slot_tp_init, (wrapperfunc)wrap_init,
5579 "x.__init__(...) initializes x; "
Alexander Belopolsky977a6842010-08-16 20:17:07 +00005580 "see help(type(x)) for signature",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005581 PyWrapperFlag_KEYWORDS),
5582 TPSLOT("__new__", tp_new, slot_tp_new, NULL, ""),
5583 TPSLOT("__del__", tp_del, slot_tp_del, NULL, ""),
5584 {NULL}
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005585};
5586
Guido van Rossumc334df52002-04-04 23:44:47 +00005587/* Given a type pointer and an offset gotten from a slotdef entry, return a
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005588 pointer to the actual slot. This is not quite the same as simply adding
Guido van Rossumc334df52002-04-04 23:44:47 +00005589 the offset to the type pointer, since it takes care to indirect through the
5590 proper indirection pointer (as_buffer, etc.); it returns NULL if the
5591 indirection pointer is NULL. */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005592static void **
Martin v. Löwis18e16552006-02-15 17:27:45 +00005593slotptr(PyTypeObject *type, int ioffset)
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005594{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005595 char *ptr;
5596 long offset = ioffset;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005597
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005598 /* Note: this depends on the order of the members of PyHeapTypeObject! */
5599 assert(offset >= 0);
5600 assert((size_t)offset < offsetof(PyHeapTypeObject, as_buffer));
5601 if ((size_t)offset >= offsetof(PyHeapTypeObject, as_sequence)) {
5602 ptr = (char *)type->tp_as_sequence;
5603 offset -= offsetof(PyHeapTypeObject, as_sequence);
5604 }
5605 else if ((size_t)offset >= offsetof(PyHeapTypeObject, as_mapping)) {
5606 ptr = (char *)type->tp_as_mapping;
5607 offset -= offsetof(PyHeapTypeObject, as_mapping);
5608 }
5609 else if ((size_t)offset >= offsetof(PyHeapTypeObject, as_number)) {
5610 ptr = (char *)type->tp_as_number;
5611 offset -= offsetof(PyHeapTypeObject, as_number);
5612 }
5613 else {
5614 ptr = (char *)type;
5615 }
5616 if (ptr != NULL)
5617 ptr += offset;
5618 return (void **)ptr;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005619}
Guido van Rossumf040ede2001-08-07 16:40:56 +00005620
Guido van Rossumc334df52002-04-04 23:44:47 +00005621/* Length of array of slotdef pointers used to store slots with the
5622 same __name__. There should be at most MAX_EQUIV-1 slotdef entries with
5623 the same __name__, for any __name__. Since that's a static property, it is
5624 appropriate to declare fixed-size arrays for this. */
5625#define MAX_EQUIV 10
5626
5627/* Return a slot pointer for a given name, but ONLY if the attribute has
5628 exactly one slot function. The name must be an interned string. */
5629static void **
5630resolve_slotdups(PyTypeObject *type, PyObject *name)
5631{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005632 /* XXX Maybe this could be optimized more -- but is it worth it? */
Guido van Rossumc334df52002-04-04 23:44:47 +00005633
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005634 /* pname and ptrs act as a little cache */
5635 static PyObject *pname;
5636 static slotdef *ptrs[MAX_EQUIV];
5637 slotdef *p, **pp;
5638 void **res, **ptr;
Guido van Rossumc334df52002-04-04 23:44:47 +00005639
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005640 if (pname != name) {
5641 /* Collect all slotdefs that match name into ptrs. */
5642 pname = name;
5643 pp = ptrs;
5644 for (p = slotdefs; p->name_strobj; p++) {
5645 if (p->name_strobj == name)
5646 *pp++ = p;
5647 }
5648 *pp = NULL;
5649 }
Guido van Rossumc334df52002-04-04 23:44:47 +00005650
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005651 /* Look in all matching slots of the type; if exactly one of these has
5652 a filled-in slot, return its value. Otherwise return NULL. */
5653 res = NULL;
5654 for (pp = ptrs; *pp; pp++) {
5655 ptr = slotptr(type, (*pp)->offset);
5656 if (ptr == NULL || *ptr == NULL)
5657 continue;
5658 if (res != NULL)
5659 return NULL;
5660 res = ptr;
5661 }
5662 return res;
Guido van Rossumc334df52002-04-04 23:44:47 +00005663}
5664
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005665/* Common code for update_slots_callback() and fixup_slot_dispatchers(). This
Guido van Rossumc334df52002-04-04 23:44:47 +00005666 does some incredibly complex thinking and then sticks something into the
5667 slot. (It sees if the adjacent slotdefs for the same slot have conflicting
5668 interests, and then stores a generic wrapper or a specific function into
5669 the slot.) Return a pointer to the next slotdef with a different offset,
5670 because that's convenient for fixup_slot_dispatchers(). */
5671static slotdef *
5672update_one_slot(PyTypeObject *type, slotdef *p)
5673{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005674 PyObject *descr;
5675 PyWrapperDescrObject *d;
5676 void *generic = NULL, *specific = NULL;
5677 int use_generic = 0;
5678 int offset = p->offset;
5679 void **ptr = slotptr(type, offset);
Guido van Rossumc334df52002-04-04 23:44:47 +00005680
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005681 if (ptr == NULL) {
5682 do {
5683 ++p;
5684 } while (p->offset == offset);
5685 return p;
5686 }
5687 do {
5688 descr = _PyType_Lookup(type, p->name_strobj);
5689 if (descr == NULL) {
5690 if (ptr == (void**)&type->tp_iternext) {
5691 specific = _PyObject_NextNotImplemented;
5692 }
5693 continue;
5694 }
5695 if (Py_TYPE(descr) == &PyWrapperDescr_Type) {
5696 void **tptr = resolve_slotdups(type, p->name_strobj);
5697 if (tptr == NULL || tptr == ptr)
5698 generic = p->function;
5699 d = (PyWrapperDescrObject *)descr;
5700 if (d->d_base->wrapper == p->wrapper &&
5701 PyType_IsSubtype(type, PyDescr_TYPE(d)))
5702 {
5703 if (specific == NULL ||
5704 specific == d->d_wrapped)
5705 specific = d->d_wrapped;
5706 else
5707 use_generic = 1;
5708 }
5709 }
5710 else if (Py_TYPE(descr) == &PyCFunction_Type &&
5711 PyCFunction_GET_FUNCTION(descr) ==
5712 (PyCFunction)tp_new_wrapper &&
5713 ptr == (void**)&type->tp_new)
5714 {
5715 /* The __new__ wrapper is not a wrapper descriptor,
5716 so must be special-cased differently.
5717 If we don't do this, creating an instance will
5718 always use slot_tp_new which will look up
5719 __new__ in the MRO which will call tp_new_wrapper
5720 which will look through the base classes looking
5721 for a static base and call its tp_new (usually
5722 PyType_GenericNew), after performing various
5723 sanity checks and constructing a new argument
5724 list. Cut all that nonsense short -- this speeds
5725 up instance creation tremendously. */
5726 specific = (void *)type->tp_new;
5727 /* XXX I'm not 100% sure that there isn't a hole
5728 in this reasoning that requires additional
5729 sanity checks. I'll buy the first person to
5730 point out a bug in this reasoning a beer. */
5731 }
5732 else if (descr == Py_None &&
5733 ptr == (void**)&type->tp_hash) {
5734 /* We specifically allow __hash__ to be set to None
5735 to prevent inheritance of the default
5736 implementation from object.__hash__ */
5737 specific = PyObject_HashNotImplemented;
5738 }
5739 else {
5740 use_generic = 1;
5741 generic = p->function;
5742 }
5743 } while ((++p)->offset == offset);
5744 if (specific && !use_generic)
5745 *ptr = specific;
5746 else
5747 *ptr = generic;
5748 return p;
Guido van Rossumc334df52002-04-04 23:44:47 +00005749}
5750
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005751/* In the type, update the slots whose slotdefs are gathered in the pp array.
5752 This is a callback for update_subclasses(). */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005753static int
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005754update_slots_callback(PyTypeObject *type, void *data)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005755{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005756 slotdef **pp = (slotdef **)data;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005757
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005758 for (; *pp; pp++)
5759 update_one_slot(type, *pp);
5760 return 0;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005761}
5762
Guido van Rossumc334df52002-04-04 23:44:47 +00005763/* Comparison function for qsort() to compare slotdefs by their offset, and
5764 for equal offset by their address (to force a stable sort). */
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005765static int
5766slotdef_cmp(const void *aa, const void *bb)
5767{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005768 const slotdef *a = (const slotdef *)aa, *b = (const slotdef *)bb;
5769 int c = a->offset - b->offset;
5770 if (c != 0)
5771 return c;
5772 else
5773 /* Cannot use a-b, as this gives off_t,
5774 which may lose precision when converted to int. */
5775 return (a > b) ? 1 : (a < b) ? -1 : 0;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005776}
5777
Guido van Rossumc334df52002-04-04 23:44:47 +00005778/* Initialize the slotdefs table by adding interned string objects for the
5779 names and sorting the entries. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005780static void
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005781init_slotdefs(void)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005782{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005783 slotdef *p;
5784 static int initialized = 0;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005785
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005786 if (initialized)
5787 return;
5788 for (p = slotdefs; p->name; p++) {
5789 p->name_strobj = PyUnicode_InternFromString(p->name);
5790 if (!p->name_strobj)
5791 Py_FatalError("Out of memory interning slotdef names");
5792 }
5793 qsort((void *)slotdefs, (size_t)(p-slotdefs), sizeof(slotdef),
5794 slotdef_cmp);
5795 initialized = 1;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005796}
5797
Guido van Rossumc334df52002-04-04 23:44:47 +00005798/* Update the slots after assignment to a class (type) attribute. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005799static int
5800update_slot(PyTypeObject *type, PyObject *name)
5801{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005802 slotdef *ptrs[MAX_EQUIV];
5803 slotdef *p;
5804 slotdef **pp;
5805 int offset;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005806
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005807 /* Clear the VALID_VERSION flag of 'type' and all its
5808 subclasses. This could possibly be unified with the
5809 update_subclasses() recursion below, but carefully:
5810 they each have their own conditions on which to stop
5811 recursing into subclasses. */
5812 PyType_Modified(type);
Christian Heimesa62da1d2008-01-12 19:39:10 +00005813
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005814 init_slotdefs();
5815 pp = ptrs;
5816 for (p = slotdefs; p->name; p++) {
5817 /* XXX assume name is interned! */
5818 if (p->name_strobj == name)
5819 *pp++ = p;
5820 }
5821 *pp = NULL;
5822 for (pp = ptrs; *pp; pp++) {
5823 p = *pp;
5824 offset = p->offset;
5825 while (p > slotdefs && (p-1)->offset == offset)
5826 --p;
5827 *pp = p;
5828 }
5829 if (ptrs[0] == NULL)
5830 return 0; /* Not an attribute that affects any slots */
5831 return update_subclasses(type, name,
5832 update_slots_callback, (void *)ptrs);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005833}
5834
Guido van Rossumc334df52002-04-04 23:44:47 +00005835/* Store the proper functions in the slot dispatches at class (type)
5836 definition time, based upon which operations the class overrides in its
5837 dict. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00005838static void
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005839fixup_slot_dispatchers(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005840{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005841 slotdef *p;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005842
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005843 init_slotdefs();
5844 for (p = slotdefs; p->name; )
5845 p = update_one_slot(type, p);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005846}
Guido van Rossum705f0f52001-08-24 16:47:00 +00005847
Michael W. Hudson98bbc492002-11-26 14:47:27 +00005848static void
5849update_all_slots(PyTypeObject* type)
5850{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005851 slotdef *p;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00005852
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005853 init_slotdefs();
5854 for (p = slotdefs; p->name; p++) {
5855 /* update_slot returns int but can't actually fail */
5856 update_slot(type, p->name_strobj);
5857 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +00005858}
5859
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005860/* recurse_down_subclasses() and update_subclasses() are mutually
5861 recursive functions to call a callback for all subclasses,
5862 but refraining from recursing into subclasses that define 'name'. */
5863
5864static int
5865update_subclasses(PyTypeObject *type, PyObject *name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005866 update_callback callback, void *data)
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005867{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005868 if (callback(type, data) < 0)
5869 return -1;
5870 return recurse_down_subclasses(type, name, callback, data);
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005871}
5872
5873static int
5874recurse_down_subclasses(PyTypeObject *type, PyObject *name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005875 update_callback callback, void *data)
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005876{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005877 PyTypeObject *subclass;
5878 PyObject *ref, *subclasses, *dict;
5879 Py_ssize_t i, n;
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005880
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005881 subclasses = type->tp_subclasses;
5882 if (subclasses == NULL)
5883 return 0;
5884 assert(PyList_Check(subclasses));
5885 n = PyList_GET_SIZE(subclasses);
5886 for (i = 0; i < n; i++) {
5887 ref = PyList_GET_ITEM(subclasses, i);
5888 assert(PyWeakref_CheckRef(ref));
5889 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
5890 assert(subclass != NULL);
5891 if ((PyObject *)subclass == Py_None)
5892 continue;
5893 assert(PyType_Check(subclass));
5894 /* Avoid recursing down into unaffected classes */
5895 dict = subclass->tp_dict;
5896 if (dict != NULL && PyDict_Check(dict) &&
5897 PyDict_GetItem(dict, name) != NULL)
5898 continue;
5899 if (update_subclasses(subclass, name, callback, data) < 0)
5900 return -1;
5901 }
5902 return 0;
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005903}
5904
Guido van Rossum6d204072001-10-21 00:44:31 +00005905/* This function is called by PyType_Ready() to populate the type's
5906 dictionary with method descriptors for function slots. For each
Guido van Rossum09638c12002-06-13 19:17:46 +00005907 function slot (like tp_repr) that's defined in the type, one or more
5908 corresponding descriptors are added in the type's tp_dict dictionary
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005909 under the appropriate name (like __repr__). Some function slots
Guido van Rossum09638c12002-06-13 19:17:46 +00005910 cause more than one descriptor to be added (for example, the nb_add
5911 slot adds both __add__ and __radd__ descriptors) and some function
5912 slots compete for the same descriptor (for example both sq_item and
5913 mp_subscript generate a __getitem__ descriptor).
5914
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005915 In the latter case, the first slotdef entry encoutered wins. Since
Tim Petersbf9b2442003-03-23 05:35:36 +00005916 slotdef entries are sorted by the offset of the slot in the
Guido van Rossume5c691a2003-03-07 15:13:17 +00005917 PyHeapTypeObject, this gives us some control over disambiguating
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005918 between competing slots: the members of PyHeapTypeObject are listed
5919 from most general to least general, so the most general slot is
5920 preferred. In particular, because as_mapping comes before as_sequence,
5921 for a type that defines both mp_subscript and sq_item, mp_subscript
5922 wins.
Guido van Rossum09638c12002-06-13 19:17:46 +00005923
5924 This only adds new descriptors and doesn't overwrite entries in
5925 tp_dict that were previously defined. The descriptors contain a
5926 reference to the C function they must call, so that it's safe if they
5927 are copied into a subtype's __dict__ and the subtype has a different
5928 C function in its slot -- calling the method defined by the
5929 descriptor will call the C function that was used to create it,
5930 rather than the C function present in the slot when it is called.
5931 (This is important because a subtype may have a C function in the
5932 slot that calls the method from the dictionary, and we want to avoid
5933 infinite recursion here.) */
Guido van Rossum6d204072001-10-21 00:44:31 +00005934
5935static int
5936add_operators(PyTypeObject *type)
5937{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005938 PyObject *dict = type->tp_dict;
5939 slotdef *p;
5940 PyObject *descr;
5941 void **ptr;
Guido van Rossum6d204072001-10-21 00:44:31 +00005942
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005943 init_slotdefs();
5944 for (p = slotdefs; p->name; p++) {
5945 if (p->wrapper == NULL)
5946 continue;
5947 ptr = slotptr(type, p->offset);
5948 if (!ptr || !*ptr)
5949 continue;
5950 if (PyDict_GetItem(dict, p->name_strobj))
5951 continue;
5952 if (*ptr == PyObject_HashNotImplemented) {
5953 /* Classes may prevent the inheritance of the tp_hash
5954 slot by storing PyObject_HashNotImplemented in it. Make it
5955 visible as a None value for the __hash__ attribute. */
5956 if (PyDict_SetItem(dict, p->name_strobj, Py_None) < 0)
5957 return -1;
5958 }
5959 else {
5960 descr = PyDescr_NewWrapper(type, p, *ptr);
5961 if (descr == NULL)
5962 return -1;
5963 if (PyDict_SetItem(dict, p->name_strobj, descr) < 0)
5964 return -1;
5965 Py_DECREF(descr);
5966 }
5967 }
5968 if (type->tp_new != NULL) {
5969 if (add_tp_new_wrapper(type) < 0)
5970 return -1;
5971 }
5972 return 0;
Guido van Rossum6d204072001-10-21 00:44:31 +00005973}
5974
Guido van Rossum705f0f52001-08-24 16:47:00 +00005975
5976/* Cooperative 'super' */
5977
5978typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005979 PyObject_HEAD
5980 PyTypeObject *type;
5981 PyObject *obj;
5982 PyTypeObject *obj_type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005983} superobject;
5984
Guido van Rossum6f799372001-09-20 20:46:19 +00005985static PyMemberDef super_members[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005986 {"__thisclass__", T_OBJECT, offsetof(superobject, type), READONLY,
5987 "the class invoking super()"},
5988 {"__self__", T_OBJECT, offsetof(superobject, obj), READONLY,
5989 "the instance invoking super(); may be None"},
5990 {"__self_class__", T_OBJECT, offsetof(superobject, obj_type), READONLY,
5991 "the type of the instance invoking super(); may be None"},
5992 {0}
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005993};
5994
Guido van Rossum705f0f52001-08-24 16:47:00 +00005995static void
5996super_dealloc(PyObject *self)
5997{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005998 superobject *su = (superobject *)self;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005999
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006000 _PyObject_GC_UNTRACK(self);
6001 Py_XDECREF(su->obj);
6002 Py_XDECREF(su->type);
6003 Py_XDECREF(su->obj_type);
6004 Py_TYPE(self)->tp_free(self);
Guido van Rossum705f0f52001-08-24 16:47:00 +00006005}
6006
6007static PyObject *
Guido van Rossum41eb14d2001-08-30 23:13:11 +00006008super_repr(PyObject *self)
6009{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006010 superobject *su = (superobject *)self;
Guido van Rossum41eb14d2001-08-30 23:13:11 +00006011
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006012 if (su->obj_type)
6013 return PyUnicode_FromFormat(
6014 "<super: <class '%s'>, <%s object>>",
6015 su->type ? su->type->tp_name : "NULL",
6016 su->obj_type->tp_name);
6017 else
6018 return PyUnicode_FromFormat(
6019 "<super: <class '%s'>, NULL>",
6020 su->type ? su->type->tp_name : "NULL");
Guido van Rossum41eb14d2001-08-30 23:13:11 +00006021}
6022
6023static PyObject *
Guido van Rossum705f0f52001-08-24 16:47:00 +00006024super_getattro(PyObject *self, PyObject *name)
6025{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006026 superobject *su = (superobject *)self;
6027 int skip = su->obj_type == NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006028
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006029 if (!skip) {
6030 /* We want __class__ to return the class of the super object
6031 (i.e. super, or a subclass), not the class of su->obj. */
6032 skip = (PyUnicode_Check(name) &&
6033 PyUnicode_GET_SIZE(name) == 9 &&
6034 PyUnicode_CompareWithASCIIString(name, "__class__") == 0);
6035 }
Guido van Rossum76ba09f2003-04-16 19:40:58 +00006036
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006037 if (!skip) {
6038 PyObject *mro, *res, *tmp, *dict;
6039 PyTypeObject *starttype;
6040 descrgetfunc f;
6041 Py_ssize_t i, n;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006042
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006043 starttype = su->obj_type;
6044 mro = starttype->tp_mro;
Guido van Rossum155db9a2002-04-02 17:53:47 +00006045
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006046 if (mro == NULL)
6047 n = 0;
6048 else {
6049 assert(PyTuple_Check(mro));
6050 n = PyTuple_GET_SIZE(mro);
6051 }
6052 for (i = 0; i < n; i++) {
6053 if ((PyObject *)(su->type) == PyTuple_GET_ITEM(mro, i))
6054 break;
6055 }
6056 i++;
6057 res = NULL;
6058 for (; i < n; i++) {
6059 tmp = PyTuple_GET_ITEM(mro, i);
6060 if (PyType_Check(tmp))
6061 dict = ((PyTypeObject *)tmp)->tp_dict;
6062 else
6063 continue;
6064 res = PyDict_GetItem(dict, name);
6065 if (res != NULL) {
6066 Py_INCREF(res);
6067 f = Py_TYPE(res)->tp_descr_get;
6068 if (f != NULL) {
6069 tmp = f(res,
6070 /* Only pass 'obj' param if
6071 this is instance-mode super
6072 (See SF ID #743627)
6073 */
6074 (su->obj == (PyObject *)
6075 su->obj_type
6076 ? (PyObject *)NULL
6077 : su->obj),
6078 (PyObject *)starttype);
6079 Py_DECREF(res);
6080 res = tmp;
6081 }
6082 return res;
6083 }
6084 }
6085 }
6086 return PyObject_GenericGetAttr(self, name);
Guido van Rossum705f0f52001-08-24 16:47:00 +00006087}
6088
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006089static PyTypeObject *
Guido van Rossum5b443c62001-12-03 15:38:28 +00006090supercheck(PyTypeObject *type, PyObject *obj)
6091{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006092 /* Check that a super() call makes sense. Return a type object.
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006093
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006094 obj can be a new-style class, or an instance of one:
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006095
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006096 - If it is a class, it must be a subclass of 'type'. This case is
6097 used for class methods; the return value is obj.
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006098
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006099 - If it is an instance, it must be an instance of 'type'. This is
6100 the normal case; the return value is obj.__class__.
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006101
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006102 But... when obj is an instance, we want to allow for the case where
6103 Py_TYPE(obj) is not a subclass of type, but obj.__class__ is!
6104 This will allow using super() with a proxy for obj.
6105 */
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006106
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006107 /* Check for first bullet above (special case) */
6108 if (PyType_Check(obj) && PyType_IsSubtype((PyTypeObject *)obj, type)) {
6109 Py_INCREF(obj);
6110 return (PyTypeObject *)obj;
6111 }
Guido van Rossum8e80a722003-02-18 19:22:22 +00006112
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006113 /* Normal case */
6114 if (PyType_IsSubtype(Py_TYPE(obj), type)) {
6115 Py_INCREF(Py_TYPE(obj));
6116 return Py_TYPE(obj);
6117 }
6118 else {
6119 /* Try the slow way */
6120 static PyObject *class_str = NULL;
6121 PyObject *class_attr;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006122
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006123 if (class_str == NULL) {
6124 class_str = PyUnicode_FromString("__class__");
6125 if (class_str == NULL)
6126 return NULL;
6127 }
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006128
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006129 class_attr = PyObject_GetAttr(obj, class_str);
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006130
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006131 if (class_attr != NULL &&
6132 PyType_Check(class_attr) &&
6133 (PyTypeObject *)class_attr != Py_TYPE(obj))
6134 {
6135 int ok = PyType_IsSubtype(
6136 (PyTypeObject *)class_attr, type);
6137 if (ok)
6138 return (PyTypeObject *)class_attr;
6139 }
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006140
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006141 if (class_attr == NULL)
6142 PyErr_Clear();
6143 else
6144 Py_DECREF(class_attr);
6145 }
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006146
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006147 PyErr_SetString(PyExc_TypeError,
6148 "super(type, obj): "
6149 "obj must be an instance or subtype of type");
6150 return NULL;
Guido van Rossum5b443c62001-12-03 15:38:28 +00006151}
6152
Guido van Rossum705f0f52001-08-24 16:47:00 +00006153static PyObject *
6154super_descr_get(PyObject *self, PyObject *obj, PyObject *type)
6155{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006156 superobject *su = (superobject *)self;
6157 superobject *newobj;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006158
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006159 if (obj == NULL || obj == Py_None || su->obj != NULL) {
6160 /* Not binding to an object, or already bound */
6161 Py_INCREF(self);
6162 return self;
6163 }
6164 if (Py_TYPE(su) != &PySuper_Type)
6165 /* If su is an instance of a (strict) subclass of super,
6166 call its type */
6167 return PyObject_CallFunctionObjArgs((PyObject *)Py_TYPE(su),
6168 su->type, obj, NULL);
6169 else {
6170 /* Inline the common case */
6171 PyTypeObject *obj_type = supercheck(su->type, obj);
6172 if (obj_type == NULL)
6173 return NULL;
6174 newobj = (superobject *)PySuper_Type.tp_new(&PySuper_Type,
6175 NULL, NULL);
6176 if (newobj == NULL)
6177 return NULL;
6178 Py_INCREF(su->type);
6179 Py_INCREF(obj);
6180 newobj->type = su->type;
6181 newobj->obj = obj;
6182 newobj->obj_type = obj_type;
6183 return (PyObject *)newobj;
6184 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00006185}
6186
6187static int
6188super_init(PyObject *self, PyObject *args, PyObject *kwds)
6189{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006190 superobject *su = (superobject *)self;
6191 PyTypeObject *type = NULL;
6192 PyObject *obj = NULL;
6193 PyTypeObject *obj_type = NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006194
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006195 if (!_PyArg_NoKeywords("super", kwds))
6196 return -1;
6197 if (!PyArg_ParseTuple(args, "|O!O:super", &PyType_Type, &type, &obj))
6198 return -1;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00006199
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006200 if (type == NULL) {
6201 /* Call super(), without args -- fill in from __class__
6202 and first local variable on the stack. */
6203 PyFrameObject *f = PyThreadState_GET()->frame;
6204 PyCodeObject *co = f->f_code;
6205 int i, n;
6206 if (co == NULL) {
6207 PyErr_SetString(PyExc_SystemError,
6208 "super(): no code object");
6209 return -1;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00006210 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006211 if (co->co_argcount == 0) {
6212 PyErr_SetString(PyExc_SystemError,
6213 "super(): no arguments");
6214 return -1;
6215 }
6216 obj = f->f_localsplus[0];
6217 if (obj == NULL) {
6218 PyErr_SetString(PyExc_SystemError,
6219 "super(): arg[0] deleted");
6220 return -1;
6221 }
6222 if (co->co_freevars == NULL)
6223 n = 0;
6224 else {
6225 assert(PyTuple_Check(co->co_freevars));
6226 n = PyTuple_GET_SIZE(co->co_freevars);
6227 }
6228 for (i = 0; i < n; i++) {
6229 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
6230 assert(PyUnicode_Check(name));
6231 if (!PyUnicode_CompareWithASCIIString(name,
6232 "__class__")) {
6233 Py_ssize_t index = co->co_nlocals +
6234 PyTuple_GET_SIZE(co->co_cellvars) + i;
6235 PyObject *cell = f->f_localsplus[index];
6236 if (cell == NULL || !PyCell_Check(cell)) {
6237 PyErr_SetString(PyExc_SystemError,
6238 "super(): bad __class__ cell");
6239 return -1;
6240 }
6241 type = (PyTypeObject *) PyCell_GET(cell);
6242 if (type == NULL) {
6243 PyErr_SetString(PyExc_SystemError,
6244 "super(): empty __class__ cell");
6245 return -1;
6246 }
6247 if (!PyType_Check(type)) {
6248 PyErr_Format(PyExc_SystemError,
6249 "super(): __class__ is not a type (%s)",
6250 Py_TYPE(type)->tp_name);
6251 return -1;
6252 }
6253 break;
6254 }
6255 }
6256 if (type == NULL) {
6257 PyErr_SetString(PyExc_SystemError,
6258 "super(): __class__ cell not found");
6259 return -1;
6260 }
6261 }
Guido van Rossumcd16bf62007-06-13 18:07:49 +00006262
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006263 if (obj == Py_None)
6264 obj = NULL;
6265 if (obj != NULL) {
6266 obj_type = supercheck(type, obj);
6267 if (obj_type == NULL)
6268 return -1;
6269 Py_INCREF(obj);
6270 }
6271 Py_INCREF(type);
6272 su->type = type;
6273 su->obj = obj;
6274 su->obj_type = obj_type;
6275 return 0;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006276}
6277
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00006278PyDoc_STRVAR(super_doc,
Guido van Rossumcd16bf62007-06-13 18:07:49 +00006279"super() -> same as super(__class__, <first argument>)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00006280"super(type) -> unbound super object\n"
6281"super(type, obj) -> bound super object; requires isinstance(obj, type)\n"
Guido van Rossume705ef12001-08-29 15:47:06 +00006282"super(type, type2) -> bound super object; requires issubclass(type2, type)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00006283"Typical use to call a cooperative superclass method:\n"
6284"class C(B):\n"
6285" def meth(self, arg):\n"
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006286" super().meth(arg)\n"
Guido van Rossumcd16bf62007-06-13 18:07:49 +00006287"This works for class methods too:\n"
6288"class C(B):\n"
6289" @classmethod\n"
6290" def cmeth(cls, arg):\n"
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006291" super().cmeth(arg)\n");
Guido van Rossum705f0f52001-08-24 16:47:00 +00006292
Guido van Rossum048eb752001-10-02 21:24:57 +00006293static int
6294super_traverse(PyObject *self, visitproc visit, void *arg)
6295{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006296 superobject *su = (superobject *)self;
Guido van Rossum048eb752001-10-02 21:24:57 +00006297
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006298 Py_VISIT(su->obj);
6299 Py_VISIT(su->type);
6300 Py_VISIT(su->obj_type);
Guido van Rossum048eb752001-10-02 21:24:57 +00006301
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006302 return 0;
Guido van Rossum048eb752001-10-02 21:24:57 +00006303}
6304
Guido van Rossum705f0f52001-08-24 16:47:00 +00006305PyTypeObject PySuper_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006306 PyVarObject_HEAD_INIT(&PyType_Type, 0)
6307 "super", /* tp_name */
6308 sizeof(superobject), /* tp_basicsize */
6309 0, /* tp_itemsize */
6310 /* methods */
6311 super_dealloc, /* tp_dealloc */
6312 0, /* tp_print */
6313 0, /* tp_getattr */
6314 0, /* tp_setattr */
6315 0, /* tp_reserved */
6316 super_repr, /* tp_repr */
6317 0, /* tp_as_number */
6318 0, /* tp_as_sequence */
6319 0, /* tp_as_mapping */
6320 0, /* tp_hash */
6321 0, /* tp_call */
6322 0, /* tp_str */
6323 super_getattro, /* tp_getattro */
6324 0, /* tp_setattro */
6325 0, /* tp_as_buffer */
6326 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
6327 Py_TPFLAGS_BASETYPE, /* tp_flags */
6328 super_doc, /* tp_doc */
6329 super_traverse, /* tp_traverse */
6330 0, /* tp_clear */
6331 0, /* tp_richcompare */
6332 0, /* tp_weaklistoffset */
6333 0, /* tp_iter */
6334 0, /* tp_iternext */
6335 0, /* tp_methods */
6336 super_members, /* tp_members */
6337 0, /* tp_getset */
6338 0, /* tp_base */
6339 0, /* tp_dict */
6340 super_descr_get, /* tp_descr_get */
6341 0, /* tp_descr_set */
6342 0, /* tp_dictoffset */
6343 super_init, /* tp_init */
6344 PyType_GenericAlloc, /* tp_alloc */
6345 PyType_GenericNew, /* tp_new */
6346 PyObject_GC_Del, /* tp_free */
Guido van Rossum705f0f52001-08-24 16:47:00 +00006347};