blob: 434608fd69015fc46021b5b4f6e010bc4c46258b [file] [log] [blame]
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001/* Type object implementation */
2
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003#include "Python.h"
Guido van Rossumcd16bf62007-06-13 18:07:49 +00004#include "frameobject.h"
Tim Peters6d6c1a32001-08-02 04:15:00 +00005#include "structmember.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00006
Guido van Rossum9923ffe2002-06-04 19:52:53 +00007#include <ctype.h>
8
Christian Heimesa62da1d2008-01-12 19:39:10 +00009
10/* Support type attribute cache */
11
12/* The cache can keep references to the names alive for longer than
13 they normally would. This is why the maximum size is limited to
14 MCACHE_MAX_ATTR_SIZE, since it might be a problem if very large
15 strings are used as attribute names. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000016#define MCACHE_MAX_ATTR_SIZE 100
17#define MCACHE_SIZE_EXP 10
18#define MCACHE_HASH(version, name_hash) \
19 (((unsigned int)(version) * (unsigned int)(name_hash)) \
20 >> (8*sizeof(unsigned int) - MCACHE_SIZE_EXP))
Christian Heimesa62da1d2008-01-12 19:39:10 +000021#define MCACHE_HASH_METHOD(type, name) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000022 MCACHE_HASH((type)->tp_version_tag, \
23 ((PyUnicodeObject *)(name))->hash)
Christian Heimesa62da1d2008-01-12 19:39:10 +000024#define MCACHE_CACHEABLE_NAME(name) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000025 PyUnicode_CheckExact(name) && \
26 PyUnicode_GET_SIZE(name) <= MCACHE_MAX_ATTR_SIZE
Christian Heimesa62da1d2008-01-12 19:39:10 +000027
28struct method_cache_entry {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000029 unsigned int version;
30 PyObject *name; /* reference to exactly a str or None */
31 PyObject *value; /* borrowed */
Christian Heimesa62da1d2008-01-12 19:39:10 +000032};
33
34static struct method_cache_entry method_cache[1 << MCACHE_SIZE_EXP];
35static unsigned int next_version_tag = 0;
Christian Heimes26855632008-01-27 23:50:43 +000036
37unsigned int
38PyType_ClearCache(void)
39{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000040 Py_ssize_t i;
41 unsigned int cur_version_tag = next_version_tag - 1;
42
43 for (i = 0; i < (1 << MCACHE_SIZE_EXP); i++) {
44 method_cache[i].version = 0;
45 Py_CLEAR(method_cache[i].name);
46 method_cache[i].value = NULL;
47 }
48 next_version_tag = 0;
49 /* mark all version tags as invalid */
50 PyType_Modified(&PyBaseObject_Type);
51 return cur_version_tag;
Christian Heimes26855632008-01-27 23:50:43 +000052}
Christian Heimesa62da1d2008-01-12 19:39:10 +000053
Georg Brandlf08a9dd2008-06-10 16:57:31 +000054void
55PyType_Modified(PyTypeObject *type)
Christian Heimesa62da1d2008-01-12 19:39:10 +000056{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000057 /* Invalidate any cached data for the specified type and all
58 subclasses. This function is called after the base
59 classes, mro, or attributes of the type are altered.
Christian Heimesa62da1d2008-01-12 19:39:10 +000060
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000061 Invariants:
Christian Heimesa62da1d2008-01-12 19:39:10 +000062
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000063 - Py_TPFLAGS_VALID_VERSION_TAG is never set if
64 Py_TPFLAGS_HAVE_VERSION_TAG is not set (e.g. on type
65 objects coming from non-recompiled extension modules)
Christian Heimesa62da1d2008-01-12 19:39:10 +000066
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000067 - before Py_TPFLAGS_VALID_VERSION_TAG can be set on a type,
68 it must first be set on all super types.
Christian Heimesa62da1d2008-01-12 19:39:10 +000069
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000070 This function clears the Py_TPFLAGS_VALID_VERSION_TAG of a
71 type (so it must first clear it on all subclasses). The
72 tp_version_tag value is meaningless unless this flag is set.
73 We don't assign new version tags eagerly, but only as
74 needed.
75 */
76 PyObject *raw, *ref;
77 Py_ssize_t i, n;
Christian Heimesa62da1d2008-01-12 19:39:10 +000078
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000079 if (!PyType_HasFeature(type, Py_TPFLAGS_VALID_VERSION_TAG))
80 return;
Christian Heimesa62da1d2008-01-12 19:39:10 +000081
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000082 raw = type->tp_subclasses;
83 if (raw != NULL) {
84 n = PyList_GET_SIZE(raw);
85 for (i = 0; i < n; i++) {
86 ref = PyList_GET_ITEM(raw, i);
87 ref = PyWeakref_GET_OBJECT(ref);
88 if (ref != Py_None) {
89 PyType_Modified((PyTypeObject *)ref);
90 }
91 }
92 }
93 type->tp_flags &= ~Py_TPFLAGS_VALID_VERSION_TAG;
Christian Heimesa62da1d2008-01-12 19:39:10 +000094}
95
96static void
97type_mro_modified(PyTypeObject *type, PyObject *bases) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000098 /*
99 Check that all base classes or elements of the mro of type are
100 able to be cached. This function is called after the base
101 classes or mro of the type are altered.
Christian Heimesa62da1d2008-01-12 19:39:10 +0000102
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000103 Unset HAVE_VERSION_TAG and VALID_VERSION_TAG if the type
104 inherits from an old-style class, either directly or if it
105 appears in the MRO of a new-style class. No support either for
106 custom MROs that include types that are not officially super
107 types.
Christian Heimesa62da1d2008-01-12 19:39:10 +0000108
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000109 Called from mro_internal, which will subsequently be called on
110 each subclass when their mro is recursively updated.
111 */
112 Py_ssize_t i, n;
113 int clear = 0;
Christian Heimesa62da1d2008-01-12 19:39:10 +0000114
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000115 if (!PyType_HasFeature(type, Py_TPFLAGS_HAVE_VERSION_TAG))
116 return;
Christian Heimesa62da1d2008-01-12 19:39:10 +0000117
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000118 n = PyTuple_GET_SIZE(bases);
119 for (i = 0; i < n; i++) {
120 PyObject *b = PyTuple_GET_ITEM(bases, i);
121 PyTypeObject *cls;
Christian Heimesa62da1d2008-01-12 19:39:10 +0000122
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000123 if (!PyType_Check(b) ) {
124 clear = 1;
125 break;
126 }
Christian Heimesa62da1d2008-01-12 19:39:10 +0000127
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000128 cls = (PyTypeObject *)b;
Christian Heimesa62da1d2008-01-12 19:39:10 +0000129
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000130 if (!PyType_HasFeature(cls, Py_TPFLAGS_HAVE_VERSION_TAG) ||
131 !PyType_IsSubtype(type, cls)) {
132 clear = 1;
133 break;
134 }
135 }
Christian Heimesa62da1d2008-01-12 19:39:10 +0000136
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000137 if (clear)
138 type->tp_flags &= ~(Py_TPFLAGS_HAVE_VERSION_TAG|
139 Py_TPFLAGS_VALID_VERSION_TAG);
Christian Heimesa62da1d2008-01-12 19:39:10 +0000140}
141
142static int
143assign_version_tag(PyTypeObject *type)
144{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000145 /* Ensure that the tp_version_tag is valid and set
146 Py_TPFLAGS_VALID_VERSION_TAG. To respect the invariant, this
147 must first be done on all super classes. Return 0 if this
148 cannot be done, 1 if Py_TPFLAGS_VALID_VERSION_TAG.
149 */
150 Py_ssize_t i, n;
151 PyObject *bases;
Christian Heimesa62da1d2008-01-12 19:39:10 +0000152
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000153 if (PyType_HasFeature(type, Py_TPFLAGS_VALID_VERSION_TAG))
154 return 1;
155 if (!PyType_HasFeature(type, Py_TPFLAGS_HAVE_VERSION_TAG))
156 return 0;
157 if (!PyType_HasFeature(type, Py_TPFLAGS_READY))
158 return 0;
Christian Heimesa62da1d2008-01-12 19:39:10 +0000159
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000160 type->tp_version_tag = next_version_tag++;
161 /* for stress-testing: next_version_tag &= 0xFF; */
Christian Heimesa62da1d2008-01-12 19:39:10 +0000162
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000163 if (type->tp_version_tag == 0) {
164 /* wrap-around or just starting Python - clear the whole
165 cache by filling names with references to Py_None.
166 Values are also set to NULL for added protection, as they
167 are borrowed reference */
168 for (i = 0; i < (1 << MCACHE_SIZE_EXP); i++) {
169 method_cache[i].value = NULL;
170 Py_XDECREF(method_cache[i].name);
171 method_cache[i].name = Py_None;
172 Py_INCREF(Py_None);
173 }
174 /* mark all version tags as invalid */
175 PyType_Modified(&PyBaseObject_Type);
176 return 1;
177 }
178 bases = type->tp_bases;
179 n = PyTuple_GET_SIZE(bases);
180 for (i = 0; i < n; i++) {
181 PyObject *b = PyTuple_GET_ITEM(bases, i);
182 assert(PyType_Check(b));
183 if (!assign_version_tag((PyTypeObject *)b))
184 return 0;
185 }
186 type->tp_flags |= Py_TPFLAGS_VALID_VERSION_TAG;
187 return 1;
Christian Heimesa62da1d2008-01-12 19:39:10 +0000188}
189
190
Guido van Rossum6f799372001-09-20 20:46:19 +0000191static PyMemberDef type_members[] = {
Benjamin Peterson0e102062010-08-25 23:13:17 +0000192 {"__basicsize__", T_PYSSIZET, offsetof(PyTypeObject,tp_basicsize),READONLY},
193 {"__itemsize__", T_PYSSIZET, offsetof(PyTypeObject, tp_itemsize), READONLY},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000194 {"__flags__", T_LONG, offsetof(PyTypeObject, tp_flags), READONLY},
195 {"__weakrefoffset__", T_LONG,
196 offsetof(PyTypeObject, tp_weaklistoffset), READONLY},
197 {"__base__", T_OBJECT, offsetof(PyTypeObject, tp_base), READONLY},
198 {"__dictoffset__", T_LONG,
199 offsetof(PyTypeObject, tp_dictoffset), READONLY},
200 {"__mro__", T_OBJECT, offsetof(PyTypeObject, tp_mro), READONLY},
201 {0}
Tim Peters6d6c1a32001-08-02 04:15:00 +0000202};
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000203
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000204static PyObject *
Guido van Rossumc3542212001-08-16 09:18:56 +0000205type_name(PyTypeObject *type, void *context)
206{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000207 const char *s;
Guido van Rossumc3542212001-08-16 09:18:56 +0000208
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000209 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
210 PyHeapTypeObject* et = (PyHeapTypeObject*)type;
Tim Petersea7f75d2002-12-07 21:39:16 +0000211
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000212 Py_INCREF(et->ht_name);
213 return et->ht_name;
214 }
215 else {
216 s = strrchr(type->tp_name, '.');
217 if (s == NULL)
218 s = type->tp_name;
219 else
220 s++;
221 return PyUnicode_FromString(s);
222 }
Guido van Rossumc3542212001-08-16 09:18:56 +0000223}
224
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000225static int
226type_set_name(PyTypeObject *type, PyObject *value, void *context)
227{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000228 PyHeapTypeObject* et;
229 char *tp_name;
230 PyObject *tmp;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000231
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000232 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
233 PyErr_Format(PyExc_TypeError,
234 "can't set %s.__name__", type->tp_name);
235 return -1;
236 }
237 if (!value) {
238 PyErr_Format(PyExc_TypeError,
239 "can't delete %s.__name__", type->tp_name);
240 return -1;
241 }
242 if (!PyUnicode_Check(value)) {
243 PyErr_Format(PyExc_TypeError,
244 "can only assign string to %s.__name__, not '%s'",
245 type->tp_name, Py_TYPE(value)->tp_name);
246 return -1;
247 }
Guido van Rossume845c0f2007-11-02 23:07:07 +0000248
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000249 /* Check absence of null characters */
250 tmp = PyUnicode_FromStringAndSize("\0", 1);
251 if (tmp == NULL)
252 return -1;
253 if (PyUnicode_Contains(value, tmp) != 0) {
254 Py_DECREF(tmp);
255 PyErr_Format(PyExc_ValueError,
256 "__name__ must not contain null bytes");
257 return -1;
258 }
259 Py_DECREF(tmp);
Guido van Rossume845c0f2007-11-02 23:07:07 +0000260
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000261 tp_name = _PyUnicode_AsString(value);
262 if (tp_name == NULL)
263 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000264
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000265 et = (PyHeapTypeObject*)type;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000266
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000267 Py_INCREF(value);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000268
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000269 Py_DECREF(et->ht_name);
270 et->ht_name = value;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000271
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000272 type->tp_name = tp_name;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000273
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000274 return 0;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000275}
276
Guido van Rossumc3542212001-08-16 09:18:56 +0000277static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000278type_module(PyTypeObject *type, void *context)
Guido van Rossum29ca26e1995-01-07 11:58:15 +0000279{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000280 PyObject *mod;
281 char *s;
Guido van Rossumc3542212001-08-16 09:18:56 +0000282
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000283 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
284 mod = PyDict_GetItemString(type->tp_dict, "__module__");
285 if (!mod) {
286 PyErr_Format(PyExc_AttributeError, "__module__");
287 return 0;
288 }
289 Py_XINCREF(mod);
290 return mod;
291 }
292 else {
293 s = strrchr(type->tp_name, '.');
294 if (s != NULL)
295 return PyUnicode_FromStringAndSize(
296 type->tp_name, (Py_ssize_t)(s - type->tp_name));
297 return PyUnicode_FromString("builtins");
298 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000299}
300
Guido van Rossum3926a632001-09-25 16:25:58 +0000301static int
302type_set_module(PyTypeObject *type, PyObject *value, void *context)
303{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000304 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
305 PyErr_Format(PyExc_TypeError,
306 "can't set %s.__module__", type->tp_name);
307 return -1;
308 }
309 if (!value) {
310 PyErr_Format(PyExc_TypeError,
311 "can't delete %s.__module__", type->tp_name);
312 return -1;
313 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000314
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000315 PyType_Modified(type);
Christian Heimesa62da1d2008-01-12 19:39:10 +0000316
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000317 return PyDict_SetItemString(type->tp_dict, "__module__", value);
Guido van Rossum3926a632001-09-25 16:25:58 +0000318}
319
Tim Peters6d6c1a32001-08-02 04:15:00 +0000320static PyObject *
Christian Heimes9e7f1d22008-02-28 12:27:11 +0000321type_abstractmethods(PyTypeObject *type, void *context)
322{
Benjamin Petersonaec5fd12010-10-02 00:03:31 +0000323 PyObject *mod = NULL;
Benjamin Peterson84060b82010-10-03 02:13:39 +0000324 /* type itself has an __abstractmethods__ descriptor (this). Don't return
325 that. */
Benjamin Petersonaec5fd12010-10-02 00:03:31 +0000326 if (type != &PyType_Type)
327 mod = PyDict_GetItemString(type->tp_dict, "__abstractmethods__");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000328 if (!mod) {
Benjamin Peterson23b628e2011-01-12 18:56:07 +0000329 PyErr_SetString(PyExc_AttributeError, "__abstractmethods__");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000330 return NULL;
331 }
332 Py_XINCREF(mod);
333 return mod;
Christian Heimes9e7f1d22008-02-28 12:27:11 +0000334}
335
336static int
337type_set_abstractmethods(PyTypeObject *type, PyObject *value, void *context)
338{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000339 /* __abstractmethods__ should only be set once on a type, in
340 abc.ABCMeta.__new__, so this function doesn't do anything
341 special to update subclasses.
342 */
Benjamin Peterson477ba912011-01-12 15:34:01 +0000343 int res;
344 if (value != NULL) {
345 res = PyDict_SetItemString(type->tp_dict, "__abstractmethods__", value);
346 }
347 else {
348 res = PyDict_DelItemString(type->tp_dict, "__abstractmethods__");
349 if (res && PyErr_ExceptionMatches(PyExc_KeyError)) {
Benjamin Peterson23b628e2011-01-12 18:56:07 +0000350 PyErr_SetString(PyExc_AttributeError, "__abstractmethods__");
Benjamin Peterson477ba912011-01-12 15:34:01 +0000351 return -1;
352 }
353 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000354 if (res == 0) {
355 PyType_Modified(type);
356 if (value && PyObject_IsTrue(value)) {
357 type->tp_flags |= Py_TPFLAGS_IS_ABSTRACT;
358 }
359 else {
360 type->tp_flags &= ~Py_TPFLAGS_IS_ABSTRACT;
361 }
362 }
363 return res;
Christian Heimes9e7f1d22008-02-28 12:27:11 +0000364}
365
366static PyObject *
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000367type_get_bases(PyTypeObject *type, void *context)
368{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000369 Py_INCREF(type->tp_bases);
370 return type->tp_bases;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000371}
372
373static PyTypeObject *best_base(PyObject *);
374static int mro_internal(PyTypeObject *);
375static int compatible_for_assignment(PyTypeObject *, PyTypeObject *, char *);
376static int add_subclass(PyTypeObject*, PyTypeObject*);
377static void remove_subclass(PyTypeObject *, PyTypeObject *);
378static void update_all_slots(PyTypeObject *);
379
Guido van Rossum8d24ee92003-03-24 23:49:49 +0000380typedef int (*update_callback)(PyTypeObject *, void *);
381static int update_subclasses(PyTypeObject *type, PyObject *name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000382 update_callback callback, void *data);
Guido van Rossum8d24ee92003-03-24 23:49:49 +0000383static int recurse_down_subclasses(PyTypeObject *type, PyObject *name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000384 update_callback callback, void *data);
Guido van Rossum8d24ee92003-03-24 23:49:49 +0000385
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000386static int
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000387mro_subclasses(PyTypeObject *type, PyObject* temp)
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000388{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000389 PyTypeObject *subclass;
390 PyObject *ref, *subclasses, *old_mro;
391 Py_ssize_t i, n;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000392
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000393 subclasses = type->tp_subclasses;
394 if (subclasses == NULL)
395 return 0;
396 assert(PyList_Check(subclasses));
397 n = PyList_GET_SIZE(subclasses);
398 for (i = 0; i < n; i++) {
399 ref = PyList_GET_ITEM(subclasses, i);
400 assert(PyWeakref_CheckRef(ref));
401 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
402 assert(subclass != NULL);
403 if ((PyObject *)subclass == Py_None)
404 continue;
405 assert(PyType_Check(subclass));
406 old_mro = subclass->tp_mro;
407 if (mro_internal(subclass) < 0) {
408 subclass->tp_mro = old_mro;
409 return -1;
410 }
411 else {
412 PyObject* tuple;
413 tuple = PyTuple_Pack(2, subclass, old_mro);
414 Py_DECREF(old_mro);
415 if (!tuple)
416 return -1;
417 if (PyList_Append(temp, tuple) < 0)
418 return -1;
419 Py_DECREF(tuple);
420 }
421 if (mro_subclasses(subclass, temp) < 0)
422 return -1;
423 }
424 return 0;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000425}
426
427static int
428type_set_bases(PyTypeObject *type, PyObject *value, void *context)
429{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000430 Py_ssize_t i;
431 int r = 0;
432 PyObject *ob, *temp;
433 PyTypeObject *new_base, *old_base;
434 PyObject *old_bases, *old_mro;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000435
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000436 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
437 PyErr_Format(PyExc_TypeError,
438 "can't set %s.__bases__", type->tp_name);
439 return -1;
440 }
441 if (!value) {
442 PyErr_Format(PyExc_TypeError,
443 "can't delete %s.__bases__", type->tp_name);
444 return -1;
445 }
446 if (!PyTuple_Check(value)) {
447 PyErr_Format(PyExc_TypeError,
448 "can only assign tuple to %s.__bases__, not %s",
449 type->tp_name, Py_TYPE(value)->tp_name);
450 return -1;
451 }
452 if (PyTuple_GET_SIZE(value) == 0) {
453 PyErr_Format(PyExc_TypeError,
454 "can only assign non-empty tuple to %s.__bases__, not ()",
455 type->tp_name);
456 return -1;
457 }
458 for (i = 0; i < PyTuple_GET_SIZE(value); i++) {
459 ob = PyTuple_GET_ITEM(value, i);
460 if (!PyType_Check(ob)) {
461 PyErr_Format(
462 PyExc_TypeError,
463 "%s.__bases__ must be tuple of old- or new-style classes, not '%s'",
464 type->tp_name, Py_TYPE(ob)->tp_name);
465 return -1;
466 }
467 if (PyType_Check(ob)) {
468 if (PyType_IsSubtype((PyTypeObject*)ob, type)) {
469 PyErr_SetString(PyExc_TypeError,
470 "a __bases__ item causes an inheritance cycle");
471 return -1;
472 }
473 }
474 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000475
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000476 new_base = best_base(value);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000477
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000478 if (!new_base) {
479 return -1;
480 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000481
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000482 if (!compatible_for_assignment(type->tp_base, new_base, "__bases__"))
483 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000484
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000485 Py_INCREF(new_base);
486 Py_INCREF(value);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000487
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000488 old_bases = type->tp_bases;
489 old_base = type->tp_base;
490 old_mro = type->tp_mro;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000491
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000492 type->tp_bases = value;
493 type->tp_base = new_base;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000494
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000495 if (mro_internal(type) < 0) {
496 goto bail;
497 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000498
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000499 temp = PyList_New(0);
500 if (!temp)
501 goto bail;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000502
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000503 r = mro_subclasses(type, temp);
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000504
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000505 if (r < 0) {
506 for (i = 0; i < PyList_Size(temp); i++) {
507 PyTypeObject* cls;
508 PyObject* mro;
509 PyArg_UnpackTuple(PyList_GET_ITEM(temp, i),
510 "", 2, 2, &cls, &mro);
511 Py_INCREF(mro);
512 ob = cls->tp_mro;
513 cls->tp_mro = mro;
514 Py_DECREF(ob);
515 }
516 Py_DECREF(temp);
517 goto bail;
518 }
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000519
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000520 Py_DECREF(temp);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000521
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000522 /* any base that was in __bases__ but now isn't, we
523 need to remove |type| from its tp_subclasses.
524 conversely, any class now in __bases__ that wasn't
525 needs to have |type| added to its subclasses. */
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000526
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000527 /* for now, sod that: just remove from all old_bases,
528 add to all new_bases */
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000529
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000530 for (i = PyTuple_GET_SIZE(old_bases) - 1; i >= 0; i--) {
531 ob = PyTuple_GET_ITEM(old_bases, i);
532 if (PyType_Check(ob)) {
533 remove_subclass(
534 (PyTypeObject*)ob, type);
535 }
536 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000537
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000538 for (i = PyTuple_GET_SIZE(value) - 1; i >= 0; i--) {
539 ob = PyTuple_GET_ITEM(value, i);
540 if (PyType_Check(ob)) {
541 if (add_subclass((PyTypeObject*)ob, type) < 0)
542 r = -1;
543 }
544 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000545
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000546 update_all_slots(type);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000547
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000548 Py_DECREF(old_bases);
549 Py_DECREF(old_base);
550 Py_DECREF(old_mro);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000551
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000552 return r;
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000553
554 bail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000555 Py_DECREF(type->tp_bases);
556 Py_DECREF(type->tp_base);
557 if (type->tp_mro != old_mro) {
558 Py_DECREF(type->tp_mro);
559 }
Michael W. Hudsone723e452003-08-07 14:58:10 +0000560
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000561 type->tp_bases = old_bases;
562 type->tp_base = old_base;
563 type->tp_mro = old_mro;
Tim Petersea7f75d2002-12-07 21:39:16 +0000564
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000565 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000566}
567
568static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000569type_dict(PyTypeObject *type, void *context)
570{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000571 if (type->tp_dict == NULL) {
572 Py_INCREF(Py_None);
573 return Py_None;
574 }
575 return PyDictProxy_New(type->tp_dict);
Guido van Rossum29ca26e1995-01-07 11:58:15 +0000576}
577
Tim Peters24008312002-03-17 18:56:20 +0000578static PyObject *
579type_get_doc(PyTypeObject *type, void *context)
580{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000581 PyObject *result;
582 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE) && type->tp_doc != NULL)
583 return PyUnicode_FromString(type->tp_doc);
584 result = PyDict_GetItemString(type->tp_dict, "__doc__");
585 if (result == NULL) {
586 result = Py_None;
587 Py_INCREF(result);
588 }
589 else if (Py_TYPE(result)->tp_descr_get) {
590 result = Py_TYPE(result)->tp_descr_get(result, NULL,
591 (PyObject *)type);
592 }
593 else {
594 Py_INCREF(result);
595 }
596 return result;
Tim Peters24008312002-03-17 18:56:20 +0000597}
598
Antoine Pitrouec569b72008-08-26 22:40:48 +0000599static PyObject *
600type___instancecheck__(PyObject *type, PyObject *inst)
601{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000602 switch (_PyObject_RealIsInstance(inst, type)) {
603 case -1:
604 return NULL;
605 case 0:
606 Py_RETURN_FALSE;
607 default:
608 Py_RETURN_TRUE;
609 }
Antoine Pitrouec569b72008-08-26 22:40:48 +0000610}
611
612
613static PyObject *
Antoine Pitrouec569b72008-08-26 22:40:48 +0000614type___subclasscheck__(PyObject *type, PyObject *inst)
615{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000616 switch (_PyObject_RealIsSubclass(inst, type)) {
617 case -1:
618 return NULL;
619 case 0:
620 Py_RETURN_FALSE;
621 default:
622 Py_RETURN_TRUE;
623 }
Antoine Pitrouec569b72008-08-26 22:40:48 +0000624}
625
Antoine Pitrouec569b72008-08-26 22:40:48 +0000626
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000627static PyGetSetDef type_getsets[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000628 {"__name__", (getter)type_name, (setter)type_set_name, NULL},
629 {"__bases__", (getter)type_get_bases, (setter)type_set_bases, NULL},
630 {"__module__", (getter)type_module, (setter)type_set_module, NULL},
631 {"__abstractmethods__", (getter)type_abstractmethods,
632 (setter)type_set_abstractmethods, NULL},
633 {"__dict__", (getter)type_dict, NULL, NULL},
634 {"__doc__", (getter)type_get_doc, NULL, NULL},
635 {0}
Tim Peters6d6c1a32001-08-02 04:15:00 +0000636};
637
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000638static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000639type_repr(PyTypeObject *type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000640{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000641 PyObject *mod, *name, *rtn;
Guido van Rossumc3542212001-08-16 09:18:56 +0000642
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000643 mod = type_module(type, NULL);
644 if (mod == NULL)
645 PyErr_Clear();
646 else if (!PyUnicode_Check(mod)) {
647 Py_DECREF(mod);
648 mod = NULL;
649 }
650 name = type_name(type, NULL);
651 if (name == NULL)
652 return NULL;
Barry Warsaw7ce36942001-08-24 18:34:26 +0000653
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000654 if (mod != NULL && PyUnicode_CompareWithASCIIString(mod, "builtins"))
655 rtn = PyUnicode_FromFormat("<class '%U.%U'>", mod, name);
656 else
657 rtn = PyUnicode_FromFormat("<class '%s'>", type->tp_name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000658
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000659 Py_XDECREF(mod);
660 Py_DECREF(name);
661 return rtn;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000662}
663
Tim Peters6d6c1a32001-08-02 04:15:00 +0000664static PyObject *
665type_call(PyTypeObject *type, PyObject *args, PyObject *kwds)
666{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000667 PyObject *obj;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000668
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000669 if (type->tp_new == NULL) {
670 PyErr_Format(PyExc_TypeError,
671 "cannot create '%.100s' instances",
672 type->tp_name);
673 return NULL;
674 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000675
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000676 obj = type->tp_new(type, args, kwds);
677 if (obj != NULL) {
678 /* Ugly exception: when the call was type(something),
679 don't call tp_init on the result. */
680 if (type == &PyType_Type &&
681 PyTuple_Check(args) && PyTuple_GET_SIZE(args) == 1 &&
682 (kwds == NULL ||
683 (PyDict_Check(kwds) && PyDict_Size(kwds) == 0)))
684 return obj;
685 /* If the returned object is not an instance of type,
686 it won't be initialized. */
687 if (!PyType_IsSubtype(Py_TYPE(obj), type))
688 return obj;
689 type = Py_TYPE(obj);
690 if (type->tp_init != NULL &&
691 type->tp_init(obj, args, kwds) < 0) {
692 Py_DECREF(obj);
693 obj = NULL;
694 }
695 }
696 return obj;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000697}
698
699PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000700PyType_GenericAlloc(PyTypeObject *type, Py_ssize_t nitems)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000701{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000702 PyObject *obj;
703 const size_t size = _PyObject_VAR_SIZE(type, nitems+1);
704 /* note that we need to add one, for the sentinel */
Tim Peters406fe3b2001-10-06 19:04:01 +0000705
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000706 if (PyType_IS_GC(type))
707 obj = _PyObject_GC_Malloc(size);
708 else
709 obj = (PyObject *)PyObject_MALLOC(size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000710
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000711 if (obj == NULL)
712 return PyErr_NoMemory();
Tim Peters406fe3b2001-10-06 19:04:01 +0000713
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000714 memset(obj, '\0', size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000715
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000716 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
717 Py_INCREF(type);
Tim Peters406fe3b2001-10-06 19:04:01 +0000718
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000719 if (type->tp_itemsize == 0)
720 PyObject_INIT(obj, type);
721 else
722 (void) PyObject_INIT_VAR((PyVarObject *)obj, type, nitems);
Tim Peters406fe3b2001-10-06 19:04:01 +0000723
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000724 if (PyType_IS_GC(type))
725 _PyObject_GC_TRACK(obj);
726 return obj;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000727}
728
729PyObject *
730PyType_GenericNew(PyTypeObject *type, PyObject *args, PyObject *kwds)
731{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000732 return type->tp_alloc(type, 0);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000733}
734
Guido van Rossum9475a232001-10-05 20:51:39 +0000735/* Helpers for subtyping */
736
737static int
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000738traverse_slots(PyTypeObject *type, PyObject *self, visitproc visit, void *arg)
739{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000740 Py_ssize_t i, n;
741 PyMemberDef *mp;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000742
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000743 n = Py_SIZE(type);
744 mp = PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type);
745 for (i = 0; i < n; i++, mp++) {
746 if (mp->type == T_OBJECT_EX) {
747 char *addr = (char *)self + mp->offset;
748 PyObject *obj = *(PyObject **)addr;
749 if (obj != NULL) {
750 int err = visit(obj, arg);
751 if (err)
752 return err;
753 }
754 }
755 }
756 return 0;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000757}
758
759static int
Guido van Rossum9475a232001-10-05 20:51:39 +0000760subtype_traverse(PyObject *self, visitproc visit, void *arg)
761{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000762 PyTypeObject *type, *base;
763 traverseproc basetraverse;
Guido van Rossum9475a232001-10-05 20:51:39 +0000764
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000765 /* Find the nearest base with a different tp_traverse,
766 and traverse slots while we're at it */
767 type = Py_TYPE(self);
768 base = type;
769 while ((basetraverse = base->tp_traverse) == subtype_traverse) {
770 if (Py_SIZE(base)) {
771 int err = traverse_slots(base, self, visit, arg);
772 if (err)
773 return err;
774 }
775 base = base->tp_base;
776 assert(base);
777 }
Guido van Rossum9475a232001-10-05 20:51:39 +0000778
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000779 if (type->tp_dictoffset != base->tp_dictoffset) {
780 PyObject **dictptr = _PyObject_GetDictPtr(self);
781 if (dictptr && *dictptr)
782 Py_VISIT(*dictptr);
783 }
Guido van Rossum9475a232001-10-05 20:51:39 +0000784
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000785 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
786 /* For a heaptype, the instances count as references
787 to the type. Traverse the type so the collector
788 can find cycles involving this link. */
789 Py_VISIT(type);
Guido van Rossuma3862092002-06-10 15:24:42 +0000790
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000791 if (basetraverse)
792 return basetraverse(self, visit, arg);
793 return 0;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000794}
795
796static void
797clear_slots(PyTypeObject *type, PyObject *self)
798{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000799 Py_ssize_t i, n;
800 PyMemberDef *mp;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000801
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000802 n = Py_SIZE(type);
803 mp = PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type);
804 for (i = 0; i < n; i++, mp++) {
805 if (mp->type == T_OBJECT_EX && !(mp->flags & READONLY)) {
806 char *addr = (char *)self + mp->offset;
807 PyObject *obj = *(PyObject **)addr;
808 if (obj != NULL) {
809 *(PyObject **)addr = NULL;
810 Py_DECREF(obj);
811 }
812 }
813 }
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000814}
815
816static int
817subtype_clear(PyObject *self)
818{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000819 PyTypeObject *type, *base;
820 inquiry baseclear;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000821
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000822 /* Find the nearest base with a different tp_clear
823 and clear slots while we're at it */
824 type = Py_TYPE(self);
825 base = type;
826 while ((baseclear = base->tp_clear) == subtype_clear) {
827 if (Py_SIZE(base))
828 clear_slots(base, self);
829 base = base->tp_base;
830 assert(base);
831 }
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000832
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000833 /* There's no need to clear the instance dict (if any);
834 the collector will call its tp_clear handler. */
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000835
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000836 if (baseclear)
837 return baseclear(self);
838 return 0;
Guido van Rossum9475a232001-10-05 20:51:39 +0000839}
Tim Peters6d6c1a32001-08-02 04:15:00 +0000840
841static void
842subtype_dealloc(PyObject *self)
843{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000844 PyTypeObject *type, *base;
845 destructor basedealloc;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000846
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000847 /* Extract the type; we expect it to be a heap type */
848 type = Py_TYPE(self);
849 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000850
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000851 /* Test whether the type has GC exactly once */
Guido van Rossum22b13872002-08-06 21:41:44 +0000852
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000853 if (!PyType_IS_GC(type)) {
854 /* It's really rare to find a dynamic type that doesn't have
855 GC; it can only happen when deriving from 'object' and not
856 adding any slots or instance variables. This allows
857 certain simplifications: there's no need to call
858 clear_slots(), or DECREF the dict, or clear weakrefs. */
Guido van Rossum22b13872002-08-06 21:41:44 +0000859
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000860 /* Maybe call finalizer; exit early if resurrected */
861 if (type->tp_del) {
862 type->tp_del(self);
863 if (self->ob_refcnt > 0)
864 return;
865 }
Guido van Rossum22b13872002-08-06 21:41:44 +0000866
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000867 /* Find the nearest base with a different tp_dealloc */
868 base = type;
869 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
870 assert(Py_SIZE(base) == 0);
871 base = base->tp_base;
872 assert(base);
873 }
Guido van Rossum22b13872002-08-06 21:41:44 +0000874
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000875 /* Extract the type again; tp_del may have changed it */
876 type = Py_TYPE(self);
Benjamin Peterson193152c2009-04-25 01:08:45 +0000877
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000878 /* Call the base tp_dealloc() */
879 assert(basedealloc);
880 basedealloc(self);
Guido van Rossum22b13872002-08-06 21:41:44 +0000881
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000882 /* Can't reference self beyond this point */
883 Py_DECREF(type);
Guido van Rossum22b13872002-08-06 21:41:44 +0000884
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000885 /* Done */
886 return;
887 }
Guido van Rossum22b13872002-08-06 21:41:44 +0000888
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000889 /* We get here only if the type has GC */
Guido van Rossum22b13872002-08-06 21:41:44 +0000890
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000891 /* UnTrack and re-Track around the trashcan macro, alas */
892 /* See explanation at end of function for full disclosure */
893 PyObject_GC_UnTrack(self);
894 ++_PyTrash_delete_nesting;
895 Py_TRASHCAN_SAFE_BEGIN(self);
896 --_PyTrash_delete_nesting;
897 /* DO NOT restore GC tracking at this point. weakref callbacks
898 * (if any, and whether directly here or indirectly in something we
899 * call) may trigger GC, and if self is tracked at that point, it
900 * will look like trash to GC and GC will try to delete self again.
901 */
Guido van Rossum22b13872002-08-06 21:41:44 +0000902
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000903 /* Find the nearest base with a different tp_dealloc */
904 base = type;
Brett Cannonb94767f2011-02-22 20:15:44 +0000905 while ((/*basedealloc =*/ base->tp_dealloc) == subtype_dealloc) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000906 base = base->tp_base;
907 assert(base);
908 }
Guido van Rossum14227b42001-12-06 02:35:58 +0000909
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000910 /* If we added a weaklist, we clear it. Do this *before* calling
911 the finalizer (__del__), clearing slots, or clearing the instance
912 dict. */
Guido van Rossum59195fd2003-06-13 20:54:40 +0000913
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000914 if (type->tp_weaklistoffset && !base->tp_weaklistoffset)
915 PyObject_ClearWeakRefs(self);
Guido van Rossum1987c662003-05-29 14:29:23 +0000916
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000917 /* Maybe call finalizer; exit early if resurrected */
918 if (type->tp_del) {
919 _PyObject_GC_TRACK(self);
920 type->tp_del(self);
921 if (self->ob_refcnt > 0)
922 goto endlabel; /* resurrected */
923 else
924 _PyObject_GC_UNTRACK(self);
925 /* New weakrefs could be created during the finalizer call.
926 If this occurs, clear them out without calling their
927 finalizers since they might rely on part of the object
928 being finalized that has already been destroyed. */
929 if (type->tp_weaklistoffset && !base->tp_weaklistoffset) {
930 /* Modeled after GET_WEAKREFS_LISTPTR() */
931 PyWeakReference **list = (PyWeakReference **) \
932 PyObject_GET_WEAKREFS_LISTPTR(self);
933 while (*list)
934 _PyWeakref_ClearRef(*list);
935 }
936 }
Guido van Rossum1987c662003-05-29 14:29:23 +0000937
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000938 /* Clear slots up to the nearest base with a different tp_dealloc */
939 base = type;
940 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
941 if (Py_SIZE(base))
942 clear_slots(base, self);
943 base = base->tp_base;
944 assert(base);
945 }
Guido van Rossum59195fd2003-06-13 20:54:40 +0000946
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000947 /* If we added a dict, DECREF it */
948 if (type->tp_dictoffset && !base->tp_dictoffset) {
949 PyObject **dictptr = _PyObject_GetDictPtr(self);
950 if (dictptr != NULL) {
951 PyObject *dict = *dictptr;
952 if (dict != NULL) {
953 Py_DECREF(dict);
954 *dictptr = NULL;
955 }
956 }
957 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000958
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000959 /* Extract the type again; tp_del may have changed it */
960 type = Py_TYPE(self);
Benjamin Peterson193152c2009-04-25 01:08:45 +0000961
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000962 /* Call the base tp_dealloc(); first retrack self if
963 * basedealloc knows about gc.
964 */
965 if (PyType_IS_GC(base))
966 _PyObject_GC_TRACK(self);
967 assert(basedealloc);
968 basedealloc(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000969
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000970 /* Can't reference self beyond this point */
971 Py_DECREF(type);
Guido van Rossum22b13872002-08-06 21:41:44 +0000972
Guido van Rossum0906e072002-08-07 20:42:09 +0000973 endlabel:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000974 ++_PyTrash_delete_nesting;
975 Py_TRASHCAN_SAFE_END(self);
976 --_PyTrash_delete_nesting;
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000977
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000978 /* Explanation of the weirdness around the trashcan macros:
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000979
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000980 Q. What do the trashcan macros do?
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000981
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000982 A. Read the comment titled "Trashcan mechanism" in object.h.
983 For one, this explains why there must be a call to GC-untrack
984 before the trashcan begin macro. Without understanding the
985 trashcan code, the answers to the following questions don't make
986 sense.
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000987
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000988 Q. Why do we GC-untrack before the trashcan and then immediately
989 GC-track again afterward?
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000990
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000991 A. In the case that the base class is GC-aware, the base class
992 probably GC-untracks the object. If it does that using the
993 UNTRACK macro, this will crash when the object is already
994 untracked. Because we don't know what the base class does, the
995 only safe thing is to make sure the object is tracked when we
996 call the base class dealloc. But... The trashcan begin macro
997 requires that the object is *untracked* before it is called. So
998 the dance becomes:
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000999
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001000 GC untrack
1001 trashcan begin
1002 GC track
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001003
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001004 Q. Why did the last question say "immediately GC-track again"?
1005 It's nowhere near immediately.
Tim Petersf7f9e992003-11-13 21:59:32 +00001006
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001007 A. Because the code *used* to re-track immediately. Bad Idea.
1008 self has a refcount of 0, and if gc ever gets its hands on it
1009 (which can happen if any weakref callback gets invoked), it
1010 looks like trash to gc too, and gc also tries to delete self
Ezio Melotti13925002011-03-16 11:05:33 +02001011 then. But we're already deleting self. Double deallocation is
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001012 a subtle disaster.
Tim Petersf7f9e992003-11-13 21:59:32 +00001013
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001014 Q. Why the bizarre (net-zero) manipulation of
1015 _PyTrash_delete_nesting around the trashcan macros?
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001016
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001017 A. Some base classes (e.g. list) also use the trashcan mechanism.
1018 The following scenario used to be possible:
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001019
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001020 - suppose the trashcan level is one below the trashcan limit
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001021
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001022 - subtype_dealloc() is called
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001023
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001024 - the trashcan limit is not yet reached, so the trashcan level
1025 is incremented and the code between trashcan begin and end is
1026 executed
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001027
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001028 - this destroys much of the object's contents, including its
1029 slots and __dict__
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001030
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001031 - basedealloc() is called; this is really list_dealloc(), or
1032 some other type which also uses the trashcan macros
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001033
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001034 - the trashcan limit is now reached, so the object is put on the
1035 trashcan's to-be-deleted-later list
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001036
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001037 - basedealloc() returns
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001038
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001039 - subtype_dealloc() decrefs the object's type
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001040
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001041 - subtype_dealloc() returns
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001042
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001043 - later, the trashcan code starts deleting the objects from its
1044 to-be-deleted-later list
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001045
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001046 - subtype_dealloc() is called *AGAIN* for the same object
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001047
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001048 - at the very least (if the destroyed slots and __dict__ don't
1049 cause problems) the object's type gets decref'ed a second
1050 time, which is *BAD*!!!
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001051
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001052 The remedy is to make sure that if the code between trashcan
1053 begin and end in subtype_dealloc() is called, the code between
1054 trashcan begin and end in basedealloc() will also be called.
1055 This is done by decrementing the level after passing into the
1056 trashcan block, and incrementing it just before leaving the
1057 block.
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001058
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001059 But now it's possible that a chain of objects consisting solely
1060 of objects whose deallocator is subtype_dealloc() will defeat
1061 the trashcan mechanism completely: the decremented level means
1062 that the effective level never reaches the limit. Therefore, we
1063 *increment* the level *before* entering the trashcan block, and
1064 matchingly decrement it after leaving. This means the trashcan
1065 code will trigger a little early, but that's no big deal.
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001066
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001067 Q. Are there any live examples of code in need of all this
1068 complexity?
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001069
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001070 A. Yes. See SF bug 668433 for code that crashed (when Python was
1071 compiled in debug mode) before the trashcan level manipulations
1072 were added. For more discussion, see SF patches 581742, 575073
1073 and bug 574207.
1074 */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001075}
1076
Jeremy Hylton938ace62002-07-17 16:30:39 +00001077static PyTypeObject *solid_base(PyTypeObject *type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001078
Tim Peters6d6c1a32001-08-02 04:15:00 +00001079/* type test with subclassing support */
1080
1081int
1082PyType_IsSubtype(PyTypeObject *a, PyTypeObject *b)
1083{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001084 PyObject *mro;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001085
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001086 mro = a->tp_mro;
1087 if (mro != NULL) {
1088 /* Deal with multiple inheritance without recursion
1089 by walking the MRO tuple */
1090 Py_ssize_t i, n;
1091 assert(PyTuple_Check(mro));
1092 n = PyTuple_GET_SIZE(mro);
1093 for (i = 0; i < n; i++) {
1094 if (PyTuple_GET_ITEM(mro, i) == (PyObject *)b)
1095 return 1;
1096 }
1097 return 0;
1098 }
1099 else {
1100 /* a is not completely initilized yet; follow tp_base */
1101 do {
1102 if (a == b)
1103 return 1;
1104 a = a->tp_base;
1105 } while (a != NULL);
1106 return b == &PyBaseObject_Type;
1107 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001108}
1109
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001110/* Internal routines to do a method lookup in the type
Guido van Rossum60718732001-08-28 17:47:51 +00001111 without looking in the instance dictionary
1112 (so we can't use PyObject_GetAttr) but still binding
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001113 it to the instance. The arguments are the object,
Guido van Rossum60718732001-08-28 17:47:51 +00001114 the method name as a C string, and the address of a
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001115 static variable used to cache the interned Python string.
1116
1117 Two variants:
1118
1119 - lookup_maybe() returns NULL without raising an exception
1120 when the _PyType_Lookup() call fails;
1121
1122 - lookup_method() always raises an exception upon errors.
Benjamin Peterson224205f2009-05-08 03:25:19 +00001123
1124 - _PyObject_LookupSpecial() exported for the benefit of other places.
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001125*/
Guido van Rossum60718732001-08-28 17:47:51 +00001126
1127static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001128lookup_maybe(PyObject *self, char *attrstr, PyObject **attrobj)
Guido van Rossum60718732001-08-28 17:47:51 +00001129{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001130 PyObject *res;
Guido van Rossum60718732001-08-28 17:47:51 +00001131
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001132 if (*attrobj == NULL) {
1133 *attrobj = PyUnicode_InternFromString(attrstr);
1134 if (*attrobj == NULL)
1135 return NULL;
1136 }
1137 res = _PyType_Lookup(Py_TYPE(self), *attrobj);
1138 if (res != NULL) {
1139 descrgetfunc f;
1140 if ((f = Py_TYPE(res)->tp_descr_get) == NULL)
1141 Py_INCREF(res);
1142 else
1143 res = f(res, self, (PyObject *)(Py_TYPE(self)));
1144 }
1145 return res;
Guido van Rossum60718732001-08-28 17:47:51 +00001146}
1147
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001148static PyObject *
1149lookup_method(PyObject *self, char *attrstr, PyObject **attrobj)
1150{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001151 PyObject *res = lookup_maybe(self, attrstr, attrobj);
1152 if (res == NULL && !PyErr_Occurred())
1153 PyErr_SetObject(PyExc_AttributeError, *attrobj);
1154 return res;
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001155}
1156
Benjamin Peterson224205f2009-05-08 03:25:19 +00001157PyObject *
1158_PyObject_LookupSpecial(PyObject *self, char *attrstr, PyObject **attrobj)
1159{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001160 return lookup_maybe(self, attrstr, attrobj);
Benjamin Peterson224205f2009-05-08 03:25:19 +00001161}
1162
Guido van Rossum2730b132001-08-28 18:22:14 +00001163/* A variation of PyObject_CallMethod that uses lookup_method()
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001164 instead of PyObject_GetAttrString(). This uses the same convention
Guido van Rossum2730b132001-08-28 18:22:14 +00001165 as lookup_method to cache the interned name string object. */
1166
Neil Schemenauerf23473f2001-10-21 22:28:58 +00001167static PyObject *
Guido van Rossum2730b132001-08-28 18:22:14 +00001168call_method(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
1169{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001170 va_list va;
1171 PyObject *args, *func = 0, *retval;
1172 va_start(va, format);
Guido van Rossum2730b132001-08-28 18:22:14 +00001173
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001174 func = lookup_maybe(o, name, nameobj);
1175 if (func == NULL) {
1176 va_end(va);
1177 if (!PyErr_Occurred())
1178 PyErr_SetObject(PyExc_AttributeError, *nameobj);
1179 return NULL;
1180 }
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001181
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001182 if (format && *format)
1183 args = Py_VaBuildValue(format, va);
1184 else
1185 args = PyTuple_New(0);
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001186
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001187 va_end(va);
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001188
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001189 if (args == NULL)
1190 return NULL;
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001191
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001192 assert(PyTuple_Check(args));
1193 retval = PyObject_Call(func, args, NULL);
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001194
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001195 Py_DECREF(args);
1196 Py_DECREF(func);
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001197
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001198 return retval;
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001199}
1200
1201/* Clone of call_method() that returns NotImplemented when the lookup fails. */
1202
Neil Schemenauerf23473f2001-10-21 22:28:58 +00001203static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001204call_maybe(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
1205{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001206 va_list va;
1207 PyObject *args, *func = 0, *retval;
1208 va_start(va, format);
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001209
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001210 func = lookup_maybe(o, name, nameobj);
1211 if (func == NULL) {
1212 va_end(va);
1213 if (!PyErr_Occurred()) {
1214 Py_INCREF(Py_NotImplemented);
1215 return Py_NotImplemented;
1216 }
1217 return NULL;
1218 }
Guido van Rossum2730b132001-08-28 18:22:14 +00001219
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001220 if (format && *format)
1221 args = Py_VaBuildValue(format, va);
1222 else
1223 args = PyTuple_New(0);
Guido van Rossum2730b132001-08-28 18:22:14 +00001224
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001225 va_end(va);
Guido van Rossum2730b132001-08-28 18:22:14 +00001226
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001227 if (args == NULL)
1228 return NULL;
Guido van Rossum2730b132001-08-28 18:22:14 +00001229
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001230 assert(PyTuple_Check(args));
1231 retval = PyObject_Call(func, args, NULL);
Guido van Rossum2730b132001-08-28 18:22:14 +00001232
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001233 Py_DECREF(args);
1234 Py_DECREF(func);
Guido van Rossum2730b132001-08-28 18:22:14 +00001235
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001236 return retval;
Guido van Rossum2730b132001-08-28 18:22:14 +00001237}
1238
Tim Petersea7f75d2002-12-07 21:39:16 +00001239/*
Guido van Rossum1f121312002-11-14 19:49:16 +00001240 Method resolution order algorithm C3 described in
1241 "A Monotonic Superclass Linearization for Dylan",
1242 by Kim Barrett, Bob Cassel, Paul Haahr,
Tim Petersea7f75d2002-12-07 21:39:16 +00001243 David A. Moon, Keith Playford, and P. Tucker Withington.
Guido van Rossum1f121312002-11-14 19:49:16 +00001244 (OOPSLA 1996)
1245
Guido van Rossum98f33732002-11-25 21:36:54 +00001246 Some notes about the rules implied by C3:
1247
Tim Petersea7f75d2002-12-07 21:39:16 +00001248 No duplicate bases.
Guido van Rossum98f33732002-11-25 21:36:54 +00001249 It isn't legal to repeat a class in a list of base classes.
1250
1251 The next three properties are the 3 constraints in "C3".
1252
Tim Petersea7f75d2002-12-07 21:39:16 +00001253 Local precendece order.
Guido van Rossum98f33732002-11-25 21:36:54 +00001254 If A precedes B in C's MRO, then A will precede B in the MRO of all
1255 subclasses of C.
1256
1257 Monotonicity.
1258 The MRO of a class must be an extension without reordering of the
1259 MRO of each of its superclasses.
1260
1261 Extended Precedence Graph (EPG).
1262 Linearization is consistent if there is a path in the EPG from
1263 each class to all its successors in the linearization. See
1264 the paper for definition of EPG.
Guido van Rossum1f121312002-11-14 19:49:16 +00001265 */
1266
Tim Petersea7f75d2002-12-07 21:39:16 +00001267static int
Guido van Rossum1f121312002-11-14 19:49:16 +00001268tail_contains(PyObject *list, int whence, PyObject *o) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001269 Py_ssize_t j, size;
1270 size = PyList_GET_SIZE(list);
Guido van Rossum1f121312002-11-14 19:49:16 +00001271
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001272 for (j = whence+1; j < size; j++) {
1273 if (PyList_GET_ITEM(list, j) == o)
1274 return 1;
1275 }
1276 return 0;
Guido van Rossum1f121312002-11-14 19:49:16 +00001277}
1278
Guido van Rossum98f33732002-11-25 21:36:54 +00001279static PyObject *
1280class_name(PyObject *cls)
1281{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001282 PyObject *name = PyObject_GetAttrString(cls, "__name__");
1283 if (name == NULL) {
1284 PyErr_Clear();
1285 Py_XDECREF(name);
1286 name = PyObject_Repr(cls);
1287 }
1288 if (name == NULL)
1289 return NULL;
1290 if (!PyUnicode_Check(name)) {
1291 Py_DECREF(name);
1292 return NULL;
1293 }
1294 return name;
Guido van Rossum98f33732002-11-25 21:36:54 +00001295}
1296
1297static int
1298check_duplicates(PyObject *list)
1299{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001300 Py_ssize_t i, j, n;
1301 /* Let's use a quadratic time algorithm,
1302 assuming that the bases lists is short.
1303 */
1304 n = PyList_GET_SIZE(list);
1305 for (i = 0; i < n; i++) {
1306 PyObject *o = PyList_GET_ITEM(list, i);
1307 for (j = i + 1; j < n; j++) {
1308 if (PyList_GET_ITEM(list, j) == o) {
1309 o = class_name(o);
1310 if (o != NULL) {
1311 PyErr_Format(PyExc_TypeError,
1312 "duplicate base class %U",
1313 o);
1314 Py_DECREF(o);
1315 } else {
1316 PyErr_SetString(PyExc_TypeError,
1317 "duplicate base class");
1318 }
1319 return -1;
1320 }
1321 }
1322 }
1323 return 0;
Guido van Rossum98f33732002-11-25 21:36:54 +00001324}
1325
1326/* Raise a TypeError for an MRO order disagreement.
1327
1328 It's hard to produce a good error message. In the absence of better
1329 insight into error reporting, report the classes that were candidates
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001330 to be put next into the MRO. There is some conflict between the
Guido van Rossum98f33732002-11-25 21:36:54 +00001331 order in which they should be put in the MRO, but it's hard to
1332 diagnose what constraint can't be satisfied.
1333*/
1334
1335static void
1336set_mro_error(PyObject *to_merge, int *remain)
1337{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001338 Py_ssize_t i, n, off, to_merge_size;
1339 char buf[1000];
1340 PyObject *k, *v;
1341 PyObject *set = PyDict_New();
1342 if (!set) return;
Guido van Rossum98f33732002-11-25 21:36:54 +00001343
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001344 to_merge_size = PyList_GET_SIZE(to_merge);
1345 for (i = 0; i < to_merge_size; i++) {
1346 PyObject *L = PyList_GET_ITEM(to_merge, i);
1347 if (remain[i] < PyList_GET_SIZE(L)) {
1348 PyObject *c = PyList_GET_ITEM(L, remain[i]);
1349 if (PyDict_SetItem(set, c, Py_None) < 0) {
1350 Py_DECREF(set);
1351 return;
1352 }
1353 }
1354 }
1355 n = PyDict_Size(set);
Guido van Rossum98f33732002-11-25 21:36:54 +00001356
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001357 off = PyOS_snprintf(buf, sizeof(buf), "Cannot create a \
Raymond Hettingerf394df42003-04-06 19:13:41 +00001358consistent method resolution\norder (MRO) for bases");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001359 i = 0;
1360 while (PyDict_Next(set, &i, &k, &v) && (size_t)off < sizeof(buf)) {
1361 PyObject *name = class_name(k);
Victor Stinnere5f99f32010-05-19 01:42:46 +00001362 char *name_str;
1363 if (name != NULL) {
1364 name_str = _PyUnicode_AsString(name);
1365 if (name_str == NULL)
Victor Stinnerba644a62010-05-19 01:50:45 +00001366 name_str = "?";
Victor Stinnere5f99f32010-05-19 01:42:46 +00001367 } else
Victor Stinnerba644a62010-05-19 01:50:45 +00001368 name_str = "?";
Victor Stinnere5f99f32010-05-19 01:42:46 +00001369 off += PyOS_snprintf(buf + off, sizeof(buf) - off, " %s", name_str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001370 Py_XDECREF(name);
1371 if (--n && (size_t)(off+1) < sizeof(buf)) {
1372 buf[off++] = ',';
1373 buf[off] = '\0';
1374 }
1375 }
1376 PyErr_SetString(PyExc_TypeError, buf);
1377 Py_DECREF(set);
Guido van Rossum98f33732002-11-25 21:36:54 +00001378}
1379
Tim Petersea7f75d2002-12-07 21:39:16 +00001380static int
Guido van Rossum1f121312002-11-14 19:49:16 +00001381pmerge(PyObject *acc, PyObject* to_merge) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001382 Py_ssize_t i, j, to_merge_size, empty_cnt;
1383 int *remain;
1384 int ok;
Tim Petersea7f75d2002-12-07 21:39:16 +00001385
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001386 to_merge_size = PyList_GET_SIZE(to_merge);
Guido van Rossum1f121312002-11-14 19:49:16 +00001387
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001388 /* remain stores an index into each sublist of to_merge.
1389 remain[i] is the index of the next base in to_merge[i]
1390 that is not included in acc.
1391 */
1392 remain = (int *)PyMem_MALLOC(SIZEOF_INT*to_merge_size);
1393 if (remain == NULL)
1394 return -1;
1395 for (i = 0; i < to_merge_size; i++)
1396 remain[i] = 0;
Guido van Rossum1f121312002-11-14 19:49:16 +00001397
1398 again:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001399 empty_cnt = 0;
1400 for (i = 0; i < to_merge_size; i++) {
1401 PyObject *candidate;
Tim Petersea7f75d2002-12-07 21:39:16 +00001402
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001403 PyObject *cur_list = PyList_GET_ITEM(to_merge, i);
Guido van Rossum1f121312002-11-14 19:49:16 +00001404
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001405 if (remain[i] >= PyList_GET_SIZE(cur_list)) {
1406 empty_cnt++;
1407 continue;
1408 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001409
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001410 /* Choose next candidate for MRO.
Guido van Rossum98f33732002-11-25 21:36:54 +00001411
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001412 The input sequences alone can determine the choice.
1413 If not, choose the class which appears in the MRO
1414 of the earliest direct superclass of the new class.
1415 */
Guido van Rossum98f33732002-11-25 21:36:54 +00001416
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001417 candidate = PyList_GET_ITEM(cur_list, remain[i]);
1418 for (j = 0; j < to_merge_size; j++) {
1419 PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
1420 if (tail_contains(j_lst, remain[j], candidate)) {
1421 goto skip; /* continue outer loop */
1422 }
1423 }
1424 ok = PyList_Append(acc, candidate);
1425 if (ok < 0) {
1426 PyMem_Free(remain);
1427 return -1;
1428 }
1429 for (j = 0; j < to_merge_size; j++) {
1430 PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
1431 if (remain[j] < PyList_GET_SIZE(j_lst) &&
1432 PyList_GET_ITEM(j_lst, remain[j]) == candidate) {
1433 remain[j]++;
1434 }
1435 }
1436 goto again;
1437 skip: ;
1438 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001439
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001440 if (empty_cnt == to_merge_size) {
1441 PyMem_FREE(remain);
1442 return 0;
1443 }
1444 set_mro_error(to_merge, remain);
1445 PyMem_FREE(remain);
1446 return -1;
Guido van Rossum1f121312002-11-14 19:49:16 +00001447}
1448
Tim Peters6d6c1a32001-08-02 04:15:00 +00001449static PyObject *
1450mro_implementation(PyTypeObject *type)
1451{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001452 Py_ssize_t i, n;
1453 int ok;
1454 PyObject *bases, *result;
1455 PyObject *to_merge, *bases_aslist;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001456
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001457 if (type->tp_dict == NULL) {
1458 if (PyType_Ready(type) < 0)
1459 return NULL;
1460 }
Guido van Rossum63517572002-06-18 16:44:57 +00001461
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001462 /* Find a superclass linearization that honors the constraints
1463 of the explicit lists of bases and the constraints implied by
1464 each base class.
Guido van Rossum98f33732002-11-25 21:36:54 +00001465
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001466 to_merge is a list of lists, where each list is a superclass
1467 linearization implied by a base class. The last element of
1468 to_merge is the declared list of bases.
1469 */
Guido van Rossum98f33732002-11-25 21:36:54 +00001470
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001471 bases = type->tp_bases;
1472 n = PyTuple_GET_SIZE(bases);
Guido van Rossum1f121312002-11-14 19:49:16 +00001473
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001474 to_merge = PyList_New(n+1);
1475 if (to_merge == NULL)
1476 return NULL;
Guido van Rossum1f121312002-11-14 19:49:16 +00001477
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001478 for (i = 0; i < n; i++) {
1479 PyObject *base = PyTuple_GET_ITEM(bases, i);
1480 PyObject *parentMRO;
1481 parentMRO = PySequence_List(((PyTypeObject*)base)->tp_mro);
1482 if (parentMRO == NULL) {
1483 Py_DECREF(to_merge);
1484 return NULL;
1485 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001486
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001487 PyList_SET_ITEM(to_merge, i, parentMRO);
1488 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001489
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001490 bases_aslist = PySequence_List(bases);
1491 if (bases_aslist == NULL) {
1492 Py_DECREF(to_merge);
1493 return NULL;
1494 }
1495 /* This is just a basic sanity check. */
1496 if (check_duplicates(bases_aslist) < 0) {
1497 Py_DECREF(to_merge);
1498 Py_DECREF(bases_aslist);
1499 return NULL;
1500 }
1501 PyList_SET_ITEM(to_merge, n, bases_aslist);
Guido van Rossum1f121312002-11-14 19:49:16 +00001502
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001503 result = Py_BuildValue("[O]", (PyObject *)type);
1504 if (result == NULL) {
1505 Py_DECREF(to_merge);
1506 return NULL;
1507 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001508
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001509 ok = pmerge(result, to_merge);
1510 Py_DECREF(to_merge);
1511 if (ok < 0) {
1512 Py_DECREF(result);
1513 return NULL;
1514 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001515
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001516 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001517}
1518
1519static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001520mro_external(PyObject *self)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001521{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001522 PyTypeObject *type = (PyTypeObject *)self;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001523
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001524 return mro_implementation(type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001525}
1526
1527static int
1528mro_internal(PyTypeObject *type)
1529{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001530 PyObject *mro, *result, *tuple;
1531 int checkit = 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001532
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001533 if (Py_TYPE(type) == &PyType_Type) {
1534 result = mro_implementation(type);
1535 }
1536 else {
1537 static PyObject *mro_str;
1538 checkit = 1;
1539 mro = lookup_method((PyObject *)type, "mro", &mro_str);
1540 if (mro == NULL)
1541 return -1;
1542 result = PyObject_CallObject(mro, NULL);
1543 Py_DECREF(mro);
1544 }
1545 if (result == NULL)
1546 return -1;
1547 tuple = PySequence_Tuple(result);
1548 Py_DECREF(result);
1549 if (tuple == NULL)
1550 return -1;
1551 if (checkit) {
1552 Py_ssize_t i, len;
1553 PyObject *cls;
1554 PyTypeObject *solid;
Armin Rigo037d1e02005-12-29 17:07:39 +00001555
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001556 solid = solid_base(type);
Armin Rigo037d1e02005-12-29 17:07:39 +00001557
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001558 len = PyTuple_GET_SIZE(tuple);
Armin Rigo037d1e02005-12-29 17:07:39 +00001559
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001560 for (i = 0; i < len; i++) {
1561 PyTypeObject *t;
1562 cls = PyTuple_GET_ITEM(tuple, i);
1563 if (!PyType_Check(cls)) {
1564 PyErr_Format(PyExc_TypeError,
1565 "mro() returned a non-class ('%.500s')",
1566 Py_TYPE(cls)->tp_name);
1567 Py_DECREF(tuple);
1568 return -1;
1569 }
1570 t = (PyTypeObject*)cls;
1571 if (!PyType_IsSubtype(solid, solid_base(t))) {
1572 PyErr_Format(PyExc_TypeError,
1573 "mro() returned base with unsuitable layout ('%.500s')",
1574 t->tp_name);
1575 Py_DECREF(tuple);
1576 return -1;
1577 }
1578 }
1579 }
1580 type->tp_mro = tuple;
Christian Heimesa62da1d2008-01-12 19:39:10 +00001581
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001582 type_mro_modified(type, type->tp_mro);
1583 /* corner case: the old-style super class might have been hidden
1584 from the custom MRO */
1585 type_mro_modified(type, type->tp_bases);
Christian Heimesa62da1d2008-01-12 19:39:10 +00001586
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001587 PyType_Modified(type);
Christian Heimesa62da1d2008-01-12 19:39:10 +00001588
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001589 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001590}
1591
1592
1593/* Calculate the best base amongst multiple base classes.
1594 This is the first one that's on the path to the "solid base". */
1595
1596static PyTypeObject *
1597best_base(PyObject *bases)
1598{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001599 Py_ssize_t i, n;
1600 PyTypeObject *base, *winner, *candidate, *base_i;
1601 PyObject *base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001602
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001603 assert(PyTuple_Check(bases));
1604 n = PyTuple_GET_SIZE(bases);
1605 assert(n > 0);
1606 base = NULL;
1607 winner = NULL;
1608 for (i = 0; i < n; i++) {
1609 base_proto = PyTuple_GET_ITEM(bases, i);
1610 if (!PyType_Check(base_proto)) {
1611 PyErr_SetString(
1612 PyExc_TypeError,
1613 "bases must be types");
1614 return NULL;
1615 }
1616 base_i = (PyTypeObject *)base_proto;
1617 if (base_i->tp_dict == NULL) {
1618 if (PyType_Ready(base_i) < 0)
1619 return NULL;
1620 }
1621 candidate = solid_base(base_i);
1622 if (winner == NULL) {
1623 winner = candidate;
1624 base = base_i;
1625 }
1626 else if (PyType_IsSubtype(winner, candidate))
1627 ;
1628 else if (PyType_IsSubtype(candidate, winner)) {
1629 winner = candidate;
1630 base = base_i;
1631 }
1632 else {
1633 PyErr_SetString(
1634 PyExc_TypeError,
1635 "multiple bases have "
1636 "instance lay-out conflict");
1637 return NULL;
1638 }
1639 }
1640 if (base == NULL)
1641 PyErr_SetString(PyExc_TypeError,
1642 "a new-style class can't have only classic bases");
1643 return base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001644}
1645
1646static int
1647extra_ivars(PyTypeObject *type, PyTypeObject *base)
1648{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001649 size_t t_size = type->tp_basicsize;
1650 size_t b_size = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001651
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001652 assert(t_size >= b_size); /* Else type smaller than base! */
1653 if (type->tp_itemsize || base->tp_itemsize) {
1654 /* If itemsize is involved, stricter rules */
1655 return t_size != b_size ||
1656 type->tp_itemsize != base->tp_itemsize;
1657 }
1658 if (type->tp_weaklistoffset && base->tp_weaklistoffset == 0 &&
1659 type->tp_weaklistoffset + sizeof(PyObject *) == t_size &&
1660 type->tp_flags & Py_TPFLAGS_HEAPTYPE)
1661 t_size -= sizeof(PyObject *);
1662 if (type->tp_dictoffset && base->tp_dictoffset == 0 &&
1663 type->tp_dictoffset + sizeof(PyObject *) == t_size &&
1664 type->tp_flags & Py_TPFLAGS_HEAPTYPE)
1665 t_size -= sizeof(PyObject *);
Guido van Rossum9676b222001-08-17 20:32:36 +00001666
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001667 return t_size != b_size;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001668}
1669
1670static PyTypeObject *
1671solid_base(PyTypeObject *type)
1672{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001673 PyTypeObject *base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001674
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001675 if (type->tp_base)
1676 base = solid_base(type->tp_base);
1677 else
1678 base = &PyBaseObject_Type;
1679 if (extra_ivars(type, base))
1680 return type;
1681 else
1682 return base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001683}
1684
Jeremy Hylton938ace62002-07-17 16:30:39 +00001685static void object_dealloc(PyObject *);
1686static int object_init(PyObject *, PyObject *, PyObject *);
1687static int update_slot(PyTypeObject *, PyObject *);
1688static void fixup_slot_dispatchers(PyTypeObject *);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001689
Guido van Rossum360e4b82007-05-14 22:51:27 +00001690/*
1691 * Helpers for __dict__ descriptor. We don't want to expose the dicts
1692 * inherited from various builtin types. The builtin base usually provides
1693 * its own __dict__ descriptor, so we use that when we can.
1694 */
1695static PyTypeObject *
1696get_builtin_base_with_dict(PyTypeObject *type)
1697{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001698 while (type->tp_base != NULL) {
1699 if (type->tp_dictoffset != 0 &&
1700 !(type->tp_flags & Py_TPFLAGS_HEAPTYPE))
1701 return type;
1702 type = type->tp_base;
1703 }
1704 return NULL;
Guido van Rossum360e4b82007-05-14 22:51:27 +00001705}
1706
1707static PyObject *
1708get_dict_descriptor(PyTypeObject *type)
1709{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001710 static PyObject *dict_str;
1711 PyObject *descr;
Guido van Rossum360e4b82007-05-14 22:51:27 +00001712
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001713 if (dict_str == NULL) {
1714 dict_str = PyUnicode_InternFromString("__dict__");
1715 if (dict_str == NULL)
1716 return NULL;
1717 }
1718 descr = _PyType_Lookup(type, dict_str);
1719 if (descr == NULL || !PyDescr_IsData(descr))
1720 return NULL;
Guido van Rossum360e4b82007-05-14 22:51:27 +00001721
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001722 return descr;
Guido van Rossum360e4b82007-05-14 22:51:27 +00001723}
1724
1725static void
1726raise_dict_descr_error(PyObject *obj)
1727{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001728 PyErr_Format(PyExc_TypeError,
1729 "this __dict__ descriptor does not support "
1730 "'%.200s' objects", Py_TYPE(obj)->tp_name);
Guido van Rossum360e4b82007-05-14 22:51:27 +00001731}
1732
Tim Peters6d6c1a32001-08-02 04:15:00 +00001733static PyObject *
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001734subtype_dict(PyObject *obj, void *context)
1735{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001736 PyObject **dictptr;
1737 PyObject *dict;
1738 PyTypeObject *base;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001739
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001740 base = get_builtin_base_with_dict(Py_TYPE(obj));
1741 if (base != NULL) {
1742 descrgetfunc func;
1743 PyObject *descr = get_dict_descriptor(base);
1744 if (descr == NULL) {
1745 raise_dict_descr_error(obj);
1746 return NULL;
1747 }
1748 func = Py_TYPE(descr)->tp_descr_get;
1749 if (func == NULL) {
1750 raise_dict_descr_error(obj);
1751 return NULL;
1752 }
1753 return func(descr, obj, (PyObject *)(Py_TYPE(obj)));
1754 }
Guido van Rossum360e4b82007-05-14 22:51:27 +00001755
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001756 dictptr = _PyObject_GetDictPtr(obj);
1757 if (dictptr == NULL) {
1758 PyErr_SetString(PyExc_AttributeError,
1759 "This object has no __dict__");
1760 return NULL;
1761 }
1762 dict = *dictptr;
1763 if (dict == NULL)
1764 *dictptr = dict = PyDict_New();
1765 Py_XINCREF(dict);
1766 return dict;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001767}
1768
Guido van Rossum6661be32001-10-26 04:26:12 +00001769static int
1770subtype_setdict(PyObject *obj, PyObject *value, void *context)
1771{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001772 PyObject **dictptr;
1773 PyObject *dict;
1774 PyTypeObject *base;
Guido van Rossum6661be32001-10-26 04:26:12 +00001775
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001776 base = get_builtin_base_with_dict(Py_TYPE(obj));
1777 if (base != NULL) {
1778 descrsetfunc func;
1779 PyObject *descr = get_dict_descriptor(base);
1780 if (descr == NULL) {
1781 raise_dict_descr_error(obj);
1782 return -1;
1783 }
1784 func = Py_TYPE(descr)->tp_descr_set;
1785 if (func == NULL) {
1786 raise_dict_descr_error(obj);
1787 return -1;
1788 }
1789 return func(descr, obj, value);
1790 }
Guido van Rossum360e4b82007-05-14 22:51:27 +00001791
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001792 dictptr = _PyObject_GetDictPtr(obj);
1793 if (dictptr == NULL) {
1794 PyErr_SetString(PyExc_AttributeError,
1795 "This object has no __dict__");
1796 return -1;
1797 }
1798 if (value != NULL && !PyDict_Check(value)) {
1799 PyErr_Format(PyExc_TypeError,
1800 "__dict__ must be set to a dictionary, "
1801 "not a '%.200s'", Py_TYPE(value)->tp_name);
1802 return -1;
1803 }
1804 dict = *dictptr;
1805 Py_XINCREF(value);
1806 *dictptr = value;
1807 Py_XDECREF(dict);
1808 return 0;
Guido van Rossum6661be32001-10-26 04:26:12 +00001809}
1810
Guido van Rossumad47da02002-08-12 19:05:44 +00001811static PyObject *
1812subtype_getweakref(PyObject *obj, void *context)
1813{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001814 PyObject **weaklistptr;
1815 PyObject *result;
Guido van Rossumad47da02002-08-12 19:05:44 +00001816
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001817 if (Py_TYPE(obj)->tp_weaklistoffset == 0) {
1818 PyErr_SetString(PyExc_AttributeError,
1819 "This object has no __weakref__");
1820 return NULL;
1821 }
1822 assert(Py_TYPE(obj)->tp_weaklistoffset > 0);
1823 assert(Py_TYPE(obj)->tp_weaklistoffset + sizeof(PyObject *) <=
1824 (size_t)(Py_TYPE(obj)->tp_basicsize));
1825 weaklistptr = (PyObject **)
1826 ((char *)obj + Py_TYPE(obj)->tp_weaklistoffset);
1827 if (*weaklistptr == NULL)
1828 result = Py_None;
1829 else
1830 result = *weaklistptr;
1831 Py_INCREF(result);
1832 return result;
Guido van Rossumad47da02002-08-12 19:05:44 +00001833}
1834
Guido van Rossum373c7412003-01-07 13:41:37 +00001835/* Three variants on the subtype_getsets list. */
1836
1837static PyGetSetDef subtype_getsets_full[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001838 {"__dict__", subtype_dict, subtype_setdict,
1839 PyDoc_STR("dictionary for instance variables (if defined)")},
1840 {"__weakref__", subtype_getweakref, NULL,
1841 PyDoc_STR("list of weak references to the object (if defined)")},
1842 {0}
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001843};
1844
Guido van Rossum373c7412003-01-07 13:41:37 +00001845static PyGetSetDef subtype_getsets_dict_only[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001846 {"__dict__", subtype_dict, subtype_setdict,
1847 PyDoc_STR("dictionary for instance variables (if defined)")},
1848 {0}
Guido van Rossum373c7412003-01-07 13:41:37 +00001849};
1850
1851static PyGetSetDef subtype_getsets_weakref_only[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001852 {"__weakref__", subtype_getweakref, NULL,
1853 PyDoc_STR("list of weak references to the object (if defined)")},
1854 {0}
Guido van Rossum373c7412003-01-07 13:41:37 +00001855};
1856
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001857static int
1858valid_identifier(PyObject *s)
1859{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001860 if (!PyUnicode_Check(s)) {
1861 PyErr_Format(PyExc_TypeError,
1862 "__slots__ items must be strings, not '%.200s'",
1863 Py_TYPE(s)->tp_name);
1864 return 0;
1865 }
1866 if (!PyUnicode_IsIdentifier(s)) {
1867 PyErr_SetString(PyExc_TypeError,
1868 "__slots__ must be identifiers");
1869 return 0;
1870 }
1871 return 1;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001872}
1873
Guido van Rossumd8faa362007-04-27 19:54:29 +00001874/* Forward */
1875static int
1876object_init(PyObject *self, PyObject *args, PyObject *kwds);
1877
1878static int
1879type_init(PyObject *cls, PyObject *args, PyObject *kwds)
1880{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001881 int res;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001882
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001883 assert(args != NULL && PyTuple_Check(args));
1884 assert(kwds == NULL || PyDict_Check(kwds));
Guido van Rossumd8faa362007-04-27 19:54:29 +00001885
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001886 if (kwds != NULL && PyDict_Check(kwds) && PyDict_Size(kwds) != 0) {
1887 PyErr_SetString(PyExc_TypeError,
1888 "type.__init__() takes no keyword arguments");
1889 return -1;
1890 }
Guido van Rossumd8faa362007-04-27 19:54:29 +00001891
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001892 if (args != NULL && PyTuple_Check(args) &&
1893 (PyTuple_GET_SIZE(args) != 1 && PyTuple_GET_SIZE(args) != 3)) {
1894 PyErr_SetString(PyExc_TypeError,
1895 "type.__init__() takes 1 or 3 arguments");
1896 return -1;
1897 }
Guido van Rossumd8faa362007-04-27 19:54:29 +00001898
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001899 /* Call object.__init__(self) now. */
1900 /* XXX Could call super(type, cls).__init__() but what's the point? */
1901 args = PyTuple_GetSlice(args, 0, 0);
1902 res = object_init(cls, args, NULL);
1903 Py_DECREF(args);
1904 return res;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001905}
1906
Martin v. Löwis738236d2011-02-05 20:35:29 +00001907long
1908PyType_GetFlags(PyTypeObject *type)
1909{
1910 return type->tp_flags;
1911}
1912
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001913static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00001914type_new(PyTypeObject *metatype, PyObject *args, PyObject *kwds)
1915{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001916 PyObject *name, *bases, *dict;
1917 static char *kwlist[] = {"name", "bases", "dict", 0};
1918 PyObject *slots, *tmp, *newslots;
1919 PyTypeObject *type, *base, *tmptype, *winner;
1920 PyHeapTypeObject *et;
1921 PyMemberDef *mp;
1922 Py_ssize_t i, nbases, nslots, slotoffset, add_dict, add_weak;
1923 int j, may_add_dict, may_add_weak;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001924
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001925 assert(args != NULL && PyTuple_Check(args));
1926 assert(kwds == NULL || PyDict_Check(kwds));
Tim Peters3abca122001-10-27 19:37:48 +00001927
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001928 /* Special case: type(x) should return x->ob_type */
1929 {
1930 const Py_ssize_t nargs = PyTuple_GET_SIZE(args);
1931 const Py_ssize_t nkwds = kwds == NULL ? 0 : PyDict_Size(kwds);
Tim Peters3abca122001-10-27 19:37:48 +00001932
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001933 if (PyType_CheckExact(metatype) && nargs == 1 && nkwds == 0) {
1934 PyObject *x = PyTuple_GET_ITEM(args, 0);
1935 Py_INCREF(Py_TYPE(x));
1936 return (PyObject *) Py_TYPE(x);
1937 }
Tim Peters3abca122001-10-27 19:37:48 +00001938
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001939 /* SF bug 475327 -- if that didn't trigger, we need 3
1940 arguments. but PyArg_ParseTupleAndKeywords below may give
1941 a msg saying type() needs exactly 3. */
1942 if (nargs + nkwds != 3) {
1943 PyErr_SetString(PyExc_TypeError,
1944 "type() takes 1 or 3 arguments");
1945 return NULL;
1946 }
1947 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001948
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001949 /* Check arguments: (name, bases, dict) */
1950 if (!PyArg_ParseTupleAndKeywords(args, kwds, "UO!O!:type", kwlist,
1951 &name,
1952 &PyTuple_Type, &bases,
1953 &PyDict_Type, &dict))
1954 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001955
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001956 /* Determine the proper metatype to deal with this,
1957 and check for metatype conflicts while we're at it.
1958 Note that if some other metatype wins to contract,
1959 it's possible that its instances are not types. */
1960 nbases = PyTuple_GET_SIZE(bases);
1961 winner = metatype;
1962 for (i = 0; i < nbases; i++) {
1963 tmp = PyTuple_GET_ITEM(bases, i);
1964 tmptype = Py_TYPE(tmp);
1965 if (PyType_IsSubtype(winner, tmptype))
1966 continue;
1967 if (PyType_IsSubtype(tmptype, winner)) {
1968 winner = tmptype;
1969 continue;
1970 }
1971 PyErr_SetString(PyExc_TypeError,
1972 "metaclass conflict: "
1973 "the metaclass of a derived class "
1974 "must be a (non-strict) subclass "
1975 "of the metaclasses of all its bases");
1976 return NULL;
1977 }
1978 if (winner != metatype) {
1979 if (winner->tp_new != type_new) /* Pass it to the winner */
1980 return winner->tp_new(winner, args, kwds);
1981 metatype = winner;
1982 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001983
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001984 /* Adjust for empty tuple bases */
1985 if (nbases == 0) {
1986 bases = PyTuple_Pack(1, &PyBaseObject_Type);
1987 if (bases == NULL)
1988 return NULL;
1989 nbases = 1;
1990 }
1991 else
1992 Py_INCREF(bases);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001993
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001994 /* XXX From here until type is allocated, "return NULL" leaks bases! */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001995
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001996 /* Calculate best base, and check that all bases are type objects */
1997 base = best_base(bases);
1998 if (base == NULL) {
1999 Py_DECREF(bases);
2000 return NULL;
2001 }
2002 if (!PyType_HasFeature(base, Py_TPFLAGS_BASETYPE)) {
2003 PyErr_Format(PyExc_TypeError,
2004 "type '%.100s' is not an acceptable base type",
2005 base->tp_name);
2006 Py_DECREF(bases);
2007 return NULL;
2008 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002009
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002010 /* Check for a __slots__ sequence variable in dict, and count it */
2011 slots = PyDict_GetItemString(dict, "__slots__");
2012 nslots = 0;
2013 add_dict = 0;
2014 add_weak = 0;
2015 may_add_dict = base->tp_dictoffset == 0;
2016 may_add_weak = base->tp_weaklistoffset == 0 && base->tp_itemsize == 0;
2017 if (slots == NULL) {
2018 if (may_add_dict) {
2019 add_dict++;
2020 }
2021 if (may_add_weak) {
2022 add_weak++;
2023 }
2024 }
2025 else {
2026 /* Have slots */
Guido van Rossumad47da02002-08-12 19:05:44 +00002027
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002028 /* Make it into a tuple */
2029 if (PyUnicode_Check(slots))
2030 slots = PyTuple_Pack(1, slots);
2031 else
2032 slots = PySequence_Tuple(slots);
2033 if (slots == NULL) {
2034 Py_DECREF(bases);
2035 return NULL;
2036 }
2037 assert(PyTuple_Check(slots));
Guido van Rossumad47da02002-08-12 19:05:44 +00002038
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002039 /* Are slots allowed? */
2040 nslots = PyTuple_GET_SIZE(slots);
2041 if (nslots > 0 && base->tp_itemsize != 0) {
2042 PyErr_Format(PyExc_TypeError,
2043 "nonempty __slots__ "
2044 "not supported for subtype of '%s'",
2045 base->tp_name);
2046 bad_slots:
2047 Py_DECREF(bases);
2048 Py_DECREF(slots);
2049 return NULL;
2050 }
Guido van Rossumad47da02002-08-12 19:05:44 +00002051
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002052 /* Check for valid slot names and two special cases */
2053 for (i = 0; i < nslots; i++) {
2054 PyObject *tmp = PyTuple_GET_ITEM(slots, i);
2055 if (!valid_identifier(tmp))
2056 goto bad_slots;
2057 assert(PyUnicode_Check(tmp));
2058 if (PyUnicode_CompareWithASCIIString(tmp, "__dict__") == 0) {
2059 if (!may_add_dict || add_dict) {
2060 PyErr_SetString(PyExc_TypeError,
2061 "__dict__ slot disallowed: "
2062 "we already got one");
2063 goto bad_slots;
2064 }
2065 add_dict++;
2066 }
2067 if (PyUnicode_CompareWithASCIIString(tmp, "__weakref__") == 0) {
2068 if (!may_add_weak || add_weak) {
2069 PyErr_SetString(PyExc_TypeError,
2070 "__weakref__ slot disallowed: "
2071 "either we already got one, "
2072 "or __itemsize__ != 0");
2073 goto bad_slots;
2074 }
2075 add_weak++;
2076 }
2077 }
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00002078
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002079 /* Copy slots into a list, mangle names and sort them.
2080 Sorted names are needed for __class__ assignment.
2081 Convert them back to tuple at the end.
2082 */
2083 newslots = PyList_New(nslots - add_dict - add_weak);
2084 if (newslots == NULL)
2085 goto bad_slots;
2086 for (i = j = 0; i < nslots; i++) {
2087 tmp = PyTuple_GET_ITEM(slots, i);
2088 if ((add_dict &&
2089 PyUnicode_CompareWithASCIIString(tmp, "__dict__") == 0) ||
2090 (add_weak &&
2091 PyUnicode_CompareWithASCIIString(tmp, "__weakref__") == 0))
2092 continue;
2093 tmp =_Py_Mangle(name, tmp);
2094 if (!tmp)
2095 goto bad_slots;
2096 PyList_SET_ITEM(newslots, j, tmp);
2097 j++;
2098 }
2099 assert(j == nslots - add_dict - add_weak);
2100 nslots = j;
2101 Py_DECREF(slots);
2102 if (PyList_Sort(newslots) == -1) {
2103 Py_DECREF(bases);
2104 Py_DECREF(newslots);
2105 return NULL;
2106 }
2107 slots = PyList_AsTuple(newslots);
2108 Py_DECREF(newslots);
2109 if (slots == NULL) {
2110 Py_DECREF(bases);
2111 return NULL;
2112 }
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00002113
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002114 /* Secondary bases may provide weakrefs or dict */
2115 if (nbases > 1 &&
2116 ((may_add_dict && !add_dict) ||
2117 (may_add_weak && !add_weak))) {
2118 for (i = 0; i < nbases; i++) {
2119 tmp = PyTuple_GET_ITEM(bases, i);
2120 if (tmp == (PyObject *)base)
2121 continue; /* Skip primary base */
2122 assert(PyType_Check(tmp));
2123 tmptype = (PyTypeObject *)tmp;
2124 if (may_add_dict && !add_dict &&
2125 tmptype->tp_dictoffset != 0)
2126 add_dict++;
2127 if (may_add_weak && !add_weak &&
2128 tmptype->tp_weaklistoffset != 0)
2129 add_weak++;
2130 if (may_add_dict && !add_dict)
2131 continue;
2132 if (may_add_weak && !add_weak)
2133 continue;
2134 /* Nothing more to check */
2135 break;
2136 }
2137 }
2138 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002139
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002140 /* XXX From here until type is safely allocated,
2141 "return NULL" may leak slots! */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002142
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002143 /* Allocate the type object */
2144 type = (PyTypeObject *)metatype->tp_alloc(metatype, nslots);
2145 if (type == NULL) {
2146 Py_XDECREF(slots);
2147 Py_DECREF(bases);
2148 return NULL;
2149 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002150
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002151 /* Keep name and slots alive in the extended type object */
2152 et = (PyHeapTypeObject *)type;
2153 Py_INCREF(name);
2154 et->ht_name = name;
2155 et->ht_slots = slots;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002156
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002157 /* Initialize tp_flags */
2158 type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE |
2159 Py_TPFLAGS_BASETYPE;
2160 if (base->tp_flags & Py_TPFLAGS_HAVE_GC)
2161 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossumdc91b992001-08-08 22:26:22 +00002162
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002163 /* Initialize essential fields */
2164 type->tp_as_number = &et->as_number;
2165 type->tp_as_sequence = &et->as_sequence;
2166 type->tp_as_mapping = &et->as_mapping;
2167 type->tp_as_buffer = &et->as_buffer;
2168 type->tp_name = _PyUnicode_AsString(name);
2169 if (!type->tp_name) {
2170 Py_DECREF(type);
2171 return NULL;
2172 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002173
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002174 /* Set tp_base and tp_bases */
2175 type->tp_bases = bases;
2176 Py_INCREF(base);
2177 type->tp_base = base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002178
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002179 /* Initialize tp_dict from passed-in dict */
2180 type->tp_dict = dict = PyDict_Copy(dict);
2181 if (dict == NULL) {
2182 Py_DECREF(type);
2183 return NULL;
2184 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002185
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002186 /* Set __module__ in the dict */
2187 if (PyDict_GetItemString(dict, "__module__") == NULL) {
2188 tmp = PyEval_GetGlobals();
2189 if (tmp != NULL) {
2190 tmp = PyDict_GetItemString(tmp, "__name__");
2191 if (tmp != NULL) {
2192 if (PyDict_SetItemString(dict, "__module__",
2193 tmp) < 0)
2194 return NULL;
2195 }
2196 }
2197 }
Guido van Rossumc3542212001-08-16 09:18:56 +00002198
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002199 /* Set tp_doc to a copy of dict['__doc__'], if the latter is there
2200 and is a string. The __doc__ accessor will first look for tp_doc;
2201 if that fails, it will still look into __dict__.
2202 */
2203 {
2204 PyObject *doc = PyDict_GetItemString(dict, "__doc__");
2205 if (doc != NULL && PyUnicode_Check(doc)) {
2206 Py_ssize_t len;
2207 char *doc_str;
2208 char *tp_doc;
Alexandre Vassalottia85998a2008-05-03 18:24:43 +00002209
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002210 doc_str = _PyUnicode_AsString(doc);
2211 if (doc_str == NULL) {
2212 Py_DECREF(type);
2213 return NULL;
2214 }
2215 /* Silently truncate the docstring if it contains null bytes. */
2216 len = strlen(doc_str);
2217 tp_doc = (char *)PyObject_MALLOC(len + 1);
2218 if (tp_doc == NULL) {
2219 Py_DECREF(type);
2220 return NULL;
2221 }
2222 memcpy(tp_doc, doc_str, len + 1);
2223 type->tp_doc = tp_doc;
2224 }
2225 }
Tim Peters2f93e282001-10-04 05:27:00 +00002226
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002227 /* Special-case __new__: if it's a plain function,
2228 make it a static function */
2229 tmp = PyDict_GetItemString(dict, "__new__");
2230 if (tmp != NULL && PyFunction_Check(tmp)) {
2231 tmp = PyStaticMethod_New(tmp);
2232 if (tmp == NULL) {
2233 Py_DECREF(type);
2234 return NULL;
2235 }
2236 PyDict_SetItemString(dict, "__new__", tmp);
2237 Py_DECREF(tmp);
2238 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002239
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002240 /* Add descriptors for custom slots from __slots__, or for __dict__ */
2241 mp = PyHeapType_GET_MEMBERS(et);
2242 slotoffset = base->tp_basicsize;
2243 if (slots != NULL) {
2244 for (i = 0; i < nslots; i++, mp++) {
2245 mp->name = _PyUnicode_AsString(
2246 PyTuple_GET_ITEM(slots, i));
Victor Stinnere5f99f32010-05-19 01:42:46 +00002247 if (mp->name == NULL) {
2248 Py_DECREF(type);
2249 return NULL;
2250 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002251 mp->type = T_OBJECT_EX;
2252 mp->offset = slotoffset;
Guido van Rossumd8faa362007-04-27 19:54:29 +00002253
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002254 /* __dict__ and __weakref__ are already filtered out */
2255 assert(strcmp(mp->name, "__dict__") != 0);
2256 assert(strcmp(mp->name, "__weakref__") != 0);
Guido van Rossumd8faa362007-04-27 19:54:29 +00002257
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002258 slotoffset += sizeof(PyObject *);
2259 }
2260 }
2261 if (add_dict) {
2262 if (base->tp_itemsize)
2263 type->tp_dictoffset = -(long)sizeof(PyObject *);
2264 else
2265 type->tp_dictoffset = slotoffset;
2266 slotoffset += sizeof(PyObject *);
2267 }
2268 if (add_weak) {
2269 assert(!base->tp_itemsize);
2270 type->tp_weaklistoffset = slotoffset;
2271 slotoffset += sizeof(PyObject *);
2272 }
2273 type->tp_basicsize = slotoffset;
2274 type->tp_itemsize = base->tp_itemsize;
2275 type->tp_members = PyHeapType_GET_MEMBERS(et);
Guido van Rossum373c7412003-01-07 13:41:37 +00002276
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002277 if (type->tp_weaklistoffset && type->tp_dictoffset)
2278 type->tp_getset = subtype_getsets_full;
2279 else if (type->tp_weaklistoffset && !type->tp_dictoffset)
2280 type->tp_getset = subtype_getsets_weakref_only;
2281 else if (!type->tp_weaklistoffset && type->tp_dictoffset)
2282 type->tp_getset = subtype_getsets_dict_only;
2283 else
2284 type->tp_getset = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002285
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002286 /* Special case some slots */
2287 if (type->tp_dictoffset != 0 || nslots > 0) {
2288 if (base->tp_getattr == NULL && base->tp_getattro == NULL)
2289 type->tp_getattro = PyObject_GenericGetAttr;
2290 if (base->tp_setattr == NULL && base->tp_setattro == NULL)
2291 type->tp_setattro = PyObject_GenericSetAttr;
2292 }
2293 type->tp_dealloc = subtype_dealloc;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002294
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002295 /* Enable GC unless there are really no instance variables possible */
2296 if (!(type->tp_basicsize == sizeof(PyObject) &&
2297 type->tp_itemsize == 0))
2298 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossum9475a232001-10-05 20:51:39 +00002299
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002300 /* Always override allocation strategy to use regular heap */
2301 type->tp_alloc = PyType_GenericAlloc;
2302 if (type->tp_flags & Py_TPFLAGS_HAVE_GC) {
2303 type->tp_free = PyObject_GC_Del;
2304 type->tp_traverse = subtype_traverse;
2305 type->tp_clear = subtype_clear;
2306 }
2307 else
2308 type->tp_free = PyObject_Del;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002309
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002310 /* Initialize the rest */
2311 if (PyType_Ready(type) < 0) {
2312 Py_DECREF(type);
2313 return NULL;
2314 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002315
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002316 /* Put the proper slots in place */
2317 fixup_slot_dispatchers(type);
Guido van Rossumf040ede2001-08-07 16:40:56 +00002318
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002319 return (PyObject *)type;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002320}
2321
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002322static short slotoffsets[] = {
2323 -1, /* invalid slot */
2324#include "typeslots.inc"
2325};
2326
2327PyObject* PyType_FromSpec(PyType_Spec *spec)
2328{
2329 PyHeapTypeObject *res = (PyHeapTypeObject*)PyType_GenericAlloc(&PyType_Type, 0);
2330 char *res_start = (char*)res;
2331 PyType_Slot *slot;
2332
Martin v. Löwis5e06a5d2011-02-21 16:24:00 +00002333 if (res == NULL)
2334 return NULL;
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002335 res->ht_name = PyUnicode_FromString(spec->name);
2336 if (!res->ht_name)
2337 goto fail;
2338 res->ht_type.tp_name = _PyUnicode_AsString(res->ht_name);
2339 if (!res->ht_type.tp_name)
2340 goto fail;
2341
2342 res->ht_type.tp_basicsize = spec->basicsize;
2343 res->ht_type.tp_itemsize = spec->itemsize;
2344 res->ht_type.tp_flags = spec->flags | Py_TPFLAGS_HEAPTYPE;
Victor Stinner0fcab4a2011-01-04 12:59:15 +00002345
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002346 for (slot = spec->slots; slot->slot; slot++) {
2347 if (slot->slot >= sizeof(slotoffsets)/sizeof(slotoffsets[0])) {
2348 PyErr_SetString(PyExc_RuntimeError, "invalid slot offset");
2349 goto fail;
2350 }
2351 *(void**)(res_start + slotoffsets[slot->slot]) = slot->pfunc;
Georg Brandl032400b2011-02-19 21:47:02 +00002352
2353 /* need to make a copy of the docstring slot, which usually
2354 points to a static string literal */
2355 if (slot->slot == Py_tp_doc) {
2356 ssize_t len = strlen(slot->pfunc)+1;
2357 char *tp_doc = PyObject_MALLOC(len);
2358 if (tp_doc == NULL)
2359 goto fail;
2360 memcpy(tp_doc, slot->pfunc, len);
2361 res->ht_type.tp_doc = tp_doc;
2362 }
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002363 }
2364
2365 return (PyObject*)res;
Victor Stinner0fcab4a2011-01-04 12:59:15 +00002366
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002367 fail:
2368 Py_DECREF(res);
2369 return NULL;
2370}
2371
2372
Tim Peters6d6c1a32001-08-02 04:15:00 +00002373/* Internal API to look for a name through the MRO.
2374 This returns a borrowed reference, and doesn't set an exception! */
2375PyObject *
2376_PyType_Lookup(PyTypeObject *type, PyObject *name)
2377{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002378 Py_ssize_t i, n;
2379 PyObject *mro, *res, *base, *dict;
2380 unsigned int h;
Christian Heimesa62da1d2008-01-12 19:39:10 +00002381
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002382 if (MCACHE_CACHEABLE_NAME(name) &&
2383 PyType_HasFeature(type, Py_TPFLAGS_VALID_VERSION_TAG)) {
2384 /* fast path */
2385 h = MCACHE_HASH_METHOD(type, name);
2386 if (method_cache[h].version == type->tp_version_tag &&
2387 method_cache[h].name == name)
2388 return method_cache[h].value;
2389 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002390
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002391 /* Look in tp_dict of types in MRO */
2392 mro = type->tp_mro;
Guido van Rossum23094982002-06-10 14:30:43 +00002393
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002394 /* If mro is NULL, the type is either not yet initialized
2395 by PyType_Ready(), or already cleared by type_clear().
2396 Either way the safest thing to do is to return NULL. */
2397 if (mro == NULL)
2398 return NULL;
Guido van Rossum23094982002-06-10 14:30:43 +00002399
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002400 res = NULL;
2401 assert(PyTuple_Check(mro));
2402 n = PyTuple_GET_SIZE(mro);
2403 for (i = 0; i < n; i++) {
2404 base = PyTuple_GET_ITEM(mro, i);
2405 assert(PyType_Check(base));
2406 dict = ((PyTypeObject *)base)->tp_dict;
2407 assert(dict && PyDict_Check(dict));
2408 res = PyDict_GetItem(dict, name);
2409 if (res != NULL)
2410 break;
2411 }
Christian Heimesa62da1d2008-01-12 19:39:10 +00002412
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002413 if (MCACHE_CACHEABLE_NAME(name) && assign_version_tag(type)) {
2414 h = MCACHE_HASH_METHOD(type, name);
2415 method_cache[h].version = type->tp_version_tag;
2416 method_cache[h].value = res; /* borrowed */
2417 Py_INCREF(name);
2418 Py_DECREF(method_cache[h].name);
2419 method_cache[h].name = name;
2420 }
2421 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002422}
2423
2424/* This is similar to PyObject_GenericGetAttr(),
2425 but uses _PyType_Lookup() instead of just looking in type->tp_dict. */
2426static PyObject *
2427type_getattro(PyTypeObject *type, PyObject *name)
2428{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002429 PyTypeObject *metatype = Py_TYPE(type);
2430 PyObject *meta_attribute, *attribute;
2431 descrgetfunc meta_get;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002432
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002433 /* Initialize this type (we'll assume the metatype is initialized) */
2434 if (type->tp_dict == NULL) {
2435 if (PyType_Ready(type) < 0)
2436 return NULL;
2437 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002438
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002439 /* No readable descriptor found yet */
2440 meta_get = NULL;
Tim Peters34592512002-07-11 06:23:50 +00002441
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002442 /* Look for the attribute in the metatype */
2443 meta_attribute = _PyType_Lookup(metatype, name);
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002444
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002445 if (meta_attribute != NULL) {
2446 meta_get = Py_TYPE(meta_attribute)->tp_descr_get;
Tim Peters34592512002-07-11 06:23:50 +00002447
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002448 if (meta_get != NULL && PyDescr_IsData(meta_attribute)) {
2449 /* Data descriptors implement tp_descr_set to intercept
2450 * writes. Assume the attribute is not overridden in
2451 * type's tp_dict (and bases): call the descriptor now.
2452 */
2453 return meta_get(meta_attribute, (PyObject *)type,
2454 (PyObject *)metatype);
2455 }
2456 Py_INCREF(meta_attribute);
2457 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002458
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002459 /* No data descriptor found on metatype. Look in tp_dict of this
2460 * type and its bases */
2461 attribute = _PyType_Lookup(type, name);
2462 if (attribute != NULL) {
2463 /* Implement descriptor functionality, if any */
2464 descrgetfunc local_get = Py_TYPE(attribute)->tp_descr_get;
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00002465
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002466 Py_XDECREF(meta_attribute);
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00002467
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002468 if (local_get != NULL) {
2469 /* NULL 2nd argument indicates the descriptor was
2470 * found on the target object itself (or a base) */
2471 return local_get(attribute, (PyObject *)NULL,
2472 (PyObject *)type);
2473 }
Tim Peters34592512002-07-11 06:23:50 +00002474
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002475 Py_INCREF(attribute);
2476 return attribute;
2477 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002478
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002479 /* No attribute found in local __dict__ (or bases): use the
2480 * descriptor from the metatype, if any */
2481 if (meta_get != NULL) {
2482 PyObject *res;
2483 res = meta_get(meta_attribute, (PyObject *)type,
2484 (PyObject *)metatype);
2485 Py_DECREF(meta_attribute);
2486 return res;
2487 }
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002488
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002489 /* If an ordinary attribute was found on the metatype, return it now */
2490 if (meta_attribute != NULL) {
2491 return meta_attribute;
2492 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002493
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002494 /* Give up */
2495 PyErr_Format(PyExc_AttributeError,
2496 "type object '%.50s' has no attribute '%U'",
2497 type->tp_name, name);
2498 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002499}
2500
2501static int
2502type_setattro(PyTypeObject *type, PyObject *name, PyObject *value)
2503{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002504 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
2505 PyErr_Format(
2506 PyExc_TypeError,
2507 "can't set attributes of built-in/extension type '%s'",
2508 type->tp_name);
2509 return -1;
2510 }
2511 if (PyObject_GenericSetAttr((PyObject *)type, name, value) < 0)
2512 return -1;
2513 return update_slot(type, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002514}
2515
2516static void
2517type_dealloc(PyTypeObject *type)
2518{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002519 PyHeapTypeObject *et;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002520
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002521 /* Assert this is a heap-allocated type object */
2522 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
2523 _PyObject_GC_UNTRACK(type);
2524 PyObject_ClearWeakRefs((PyObject *)type);
2525 et = (PyHeapTypeObject *)type;
2526 Py_XDECREF(type->tp_base);
2527 Py_XDECREF(type->tp_dict);
2528 Py_XDECREF(type->tp_bases);
2529 Py_XDECREF(type->tp_mro);
2530 Py_XDECREF(type->tp_cache);
2531 Py_XDECREF(type->tp_subclasses);
2532 /* A type's tp_doc is heap allocated, unlike the tp_doc slots
2533 * of most other objects. It's okay to cast it to char *.
2534 */
2535 PyObject_Free((char *)type->tp_doc);
2536 Py_XDECREF(et->ht_name);
2537 Py_XDECREF(et->ht_slots);
2538 Py_TYPE(type)->tp_free((PyObject *)type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002539}
2540
Guido van Rossum1c450732001-10-08 15:18:27 +00002541static PyObject *
2542type_subclasses(PyTypeObject *type, PyObject *args_ignored)
2543{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002544 PyObject *list, *raw, *ref;
2545 Py_ssize_t i, n;
Guido van Rossum1c450732001-10-08 15:18:27 +00002546
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002547 list = PyList_New(0);
2548 if (list == NULL)
2549 return NULL;
2550 raw = type->tp_subclasses;
2551 if (raw == NULL)
2552 return list;
2553 assert(PyList_Check(raw));
2554 n = PyList_GET_SIZE(raw);
2555 for (i = 0; i < n; i++) {
2556 ref = PyList_GET_ITEM(raw, i);
2557 assert(PyWeakref_CheckRef(ref));
2558 ref = PyWeakref_GET_OBJECT(ref);
2559 if (ref != Py_None) {
2560 if (PyList_Append(list, ref) < 0) {
2561 Py_DECREF(list);
2562 return NULL;
2563 }
2564 }
2565 }
2566 return list;
Guido van Rossum1c450732001-10-08 15:18:27 +00002567}
2568
Guido van Rossum47374822007-08-02 16:48:17 +00002569static PyObject *
2570type_prepare(PyObject *self, PyObject *args, PyObject *kwds)
2571{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002572 return PyDict_New();
Guido van Rossum47374822007-08-02 16:48:17 +00002573}
2574
Tim Peters6d6c1a32001-08-02 04:15:00 +00002575static PyMethodDef type_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002576 {"mro", (PyCFunction)mro_external, METH_NOARGS,
2577 PyDoc_STR("mro() -> list\nreturn a type's method resolution order")},
2578 {"__subclasses__", (PyCFunction)type_subclasses, METH_NOARGS,
2579 PyDoc_STR("__subclasses__() -> list of immediate subclasses")},
2580 {"__prepare__", (PyCFunction)type_prepare,
2581 METH_VARARGS | METH_KEYWORDS | METH_CLASS,
2582 PyDoc_STR("__prepare__() -> dict\n"
2583 "used to create the namespace for the class statement")},
2584 {"__instancecheck__", type___instancecheck__, METH_O,
2585 PyDoc_STR("__instancecheck__() -> check if an object is an instance")},
2586 {"__subclasscheck__", type___subclasscheck__, METH_O,
Alexander Belopolsky977a6842010-08-16 20:17:07 +00002587 PyDoc_STR("__subclasscheck__() -> check if a class is a subclass")},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002588 {0}
Tim Peters6d6c1a32001-08-02 04:15:00 +00002589};
2590
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002591PyDoc_STRVAR(type_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00002592"type(object) -> the object's type\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002593"type(name, bases, dict) -> a new type");
Tim Peters6d6c1a32001-08-02 04:15:00 +00002594
Guido van Rossum048eb752001-10-02 21:24:57 +00002595static int
2596type_traverse(PyTypeObject *type, visitproc visit, void *arg)
2597{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002598 /* Because of type_is_gc(), the collector only calls this
2599 for heaptypes. */
2600 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002601
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002602 Py_VISIT(type->tp_dict);
2603 Py_VISIT(type->tp_cache);
2604 Py_VISIT(type->tp_mro);
2605 Py_VISIT(type->tp_bases);
2606 Py_VISIT(type->tp_base);
Guido van Rossuma3862092002-06-10 15:24:42 +00002607
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002608 /* There's no need to visit type->tp_subclasses or
2609 ((PyHeapTypeObject *)type)->ht_slots, because they can't be involved
2610 in cycles; tp_subclasses is a list of weak references,
2611 and slots is a tuple of strings. */
Guido van Rossum048eb752001-10-02 21:24:57 +00002612
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002613 return 0;
Guido van Rossum048eb752001-10-02 21:24:57 +00002614}
2615
2616static int
2617type_clear(PyTypeObject *type)
2618{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002619 /* Because of type_is_gc(), the collector only calls this
2620 for heaptypes. */
2621 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002622
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002623 /* The only field we need to clear is tp_mro, which is part of a
2624 hard cycle (its first element is the class itself) that won't
2625 be broken otherwise (it's a tuple and tuples don't have a
2626 tp_clear handler). None of the other fields need to be
2627 cleared, and here's why:
Guido van Rossum048eb752001-10-02 21:24:57 +00002628
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002629 tp_dict:
2630 It is a dict, so the collector will call its tp_clear.
Guido van Rossuma3862092002-06-10 15:24:42 +00002631
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002632 tp_cache:
2633 Not used; if it were, it would be a dict.
Guido van Rossuma3862092002-06-10 15:24:42 +00002634
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002635 tp_bases, tp_base:
2636 If these are involved in a cycle, there must be at least
2637 one other, mutable object in the cycle, e.g. a base
2638 class's dict; the cycle will be broken that way.
Guido van Rossuma3862092002-06-10 15:24:42 +00002639
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002640 tp_subclasses:
2641 A list of weak references can't be part of a cycle; and
2642 lists have their own tp_clear.
Guido van Rossuma3862092002-06-10 15:24:42 +00002643
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002644 slots (in PyHeapTypeObject):
2645 A tuple of strings can't be part of a cycle.
2646 */
Guido van Rossuma3862092002-06-10 15:24:42 +00002647
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002648 Py_CLEAR(type->tp_mro);
Guido van Rossum048eb752001-10-02 21:24:57 +00002649
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002650 return 0;
Guido van Rossum048eb752001-10-02 21:24:57 +00002651}
2652
2653static int
2654type_is_gc(PyTypeObject *type)
2655{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002656 return type->tp_flags & Py_TPFLAGS_HEAPTYPE;
Guido van Rossum048eb752001-10-02 21:24:57 +00002657}
2658
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002659PyTypeObject PyType_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002660 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2661 "type", /* tp_name */
2662 sizeof(PyHeapTypeObject), /* tp_basicsize */
2663 sizeof(PyMemberDef), /* tp_itemsize */
2664 (destructor)type_dealloc, /* tp_dealloc */
2665 0, /* tp_print */
2666 0, /* tp_getattr */
2667 0, /* tp_setattr */
2668 0, /* tp_reserved */
2669 (reprfunc)type_repr, /* tp_repr */
2670 0, /* tp_as_number */
2671 0, /* tp_as_sequence */
2672 0, /* tp_as_mapping */
2673 0, /* tp_hash */
2674 (ternaryfunc)type_call, /* tp_call */
2675 0, /* tp_str */
2676 (getattrofunc)type_getattro, /* tp_getattro */
2677 (setattrofunc)type_setattro, /* tp_setattro */
2678 0, /* tp_as_buffer */
2679 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
2680 Py_TPFLAGS_BASETYPE | Py_TPFLAGS_TYPE_SUBCLASS, /* tp_flags */
2681 type_doc, /* tp_doc */
2682 (traverseproc)type_traverse, /* tp_traverse */
2683 (inquiry)type_clear, /* tp_clear */
2684 0, /* tp_richcompare */
2685 offsetof(PyTypeObject, tp_weaklist), /* tp_weaklistoffset */
2686 0, /* tp_iter */
2687 0, /* tp_iternext */
2688 type_methods, /* tp_methods */
2689 type_members, /* tp_members */
2690 type_getsets, /* tp_getset */
2691 0, /* tp_base */
2692 0, /* tp_dict */
2693 0, /* tp_descr_get */
2694 0, /* tp_descr_set */
2695 offsetof(PyTypeObject, tp_dict), /* tp_dictoffset */
2696 type_init, /* tp_init */
2697 0, /* tp_alloc */
2698 type_new, /* tp_new */
2699 PyObject_GC_Del, /* tp_free */
2700 (inquiry)type_is_gc, /* tp_is_gc */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002701};
Tim Peters6d6c1a32001-08-02 04:15:00 +00002702
2703
2704/* The base type of all types (eventually)... except itself. */
2705
Guido van Rossumd8faa362007-04-27 19:54:29 +00002706/* You may wonder why object.__new__() only complains about arguments
2707 when object.__init__() is not overridden, and vice versa.
2708
2709 Consider the use cases:
2710
2711 1. When neither is overridden, we want to hear complaints about
2712 excess (i.e., any) arguments, since their presence could
2713 indicate there's a bug.
2714
2715 2. When defining an Immutable type, we are likely to override only
2716 __new__(), since __init__() is called too late to initialize an
2717 Immutable object. Since __new__() defines the signature for the
2718 type, it would be a pain to have to override __init__() just to
2719 stop it from complaining about excess arguments.
2720
2721 3. When defining a Mutable type, we are likely to override only
2722 __init__(). So here the converse reasoning applies: we don't
2723 want to have to override __new__() just to stop it from
2724 complaining.
2725
2726 4. When __init__() is overridden, and the subclass __init__() calls
2727 object.__init__(), the latter should complain about excess
2728 arguments; ditto for __new__().
2729
2730 Use cases 2 and 3 make it unattractive to unconditionally check for
2731 excess arguments. The best solution that addresses all four use
2732 cases is as follows: __init__() complains about excess arguments
2733 unless __new__() is overridden and __init__() is not overridden
2734 (IOW, if __init__() is overridden or __new__() is not overridden);
2735 symmetrically, __new__() complains about excess arguments unless
2736 __init__() is overridden and __new__() is not overridden
2737 (IOW, if __new__() is overridden or __init__() is not overridden).
2738
2739 However, for backwards compatibility, this breaks too much code.
2740 Therefore, in 2.6, we'll *warn* about excess arguments when both
2741 methods are overridden; for all other cases we'll use the above
2742 rules.
2743
2744*/
2745
2746/* Forward */
2747static PyObject *
2748object_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
2749
2750static int
2751excess_args(PyObject *args, PyObject *kwds)
2752{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002753 return PyTuple_GET_SIZE(args) ||
2754 (kwds && PyDict_Check(kwds) && PyDict_Size(kwds));
Guido van Rossumd8faa362007-04-27 19:54:29 +00002755}
2756
Tim Peters6d6c1a32001-08-02 04:15:00 +00002757static int
2758object_init(PyObject *self, PyObject *args, PyObject *kwds)
2759{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002760 int err = 0;
2761 if (excess_args(args, kwds)) {
2762 PyTypeObject *type = Py_TYPE(self);
2763 if (type->tp_init != object_init &&
2764 type->tp_new != object_new)
2765 {
2766 err = PyErr_WarnEx(PyExc_DeprecationWarning,
2767 "object.__init__() takes no parameters",
2768 1);
2769 }
2770 else if (type->tp_init != object_init ||
2771 type->tp_new == object_new)
2772 {
2773 PyErr_SetString(PyExc_TypeError,
2774 "object.__init__() takes no parameters");
2775 err = -1;
2776 }
2777 }
2778 return err;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002779}
2780
Guido van Rossum298e4212003-02-13 16:30:16 +00002781static PyObject *
2782object_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2783{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002784 int err = 0;
2785 if (excess_args(args, kwds)) {
2786 if (type->tp_new != object_new &&
2787 type->tp_init != object_init)
2788 {
2789 err = PyErr_WarnEx(PyExc_DeprecationWarning,
2790 "object.__new__() takes no parameters",
2791 1);
2792 }
2793 else if (type->tp_new != object_new ||
2794 type->tp_init == object_init)
2795 {
2796 PyErr_SetString(PyExc_TypeError,
2797 "object.__new__() takes no parameters");
2798 err = -1;
2799 }
2800 }
2801 if (err < 0)
2802 return NULL;
Christian Heimes9e7f1d22008-02-28 12:27:11 +00002803
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002804 if (type->tp_flags & Py_TPFLAGS_IS_ABSTRACT) {
2805 static PyObject *comma = NULL;
2806 PyObject *abstract_methods = NULL;
2807 PyObject *builtins;
2808 PyObject *sorted;
2809 PyObject *sorted_methods = NULL;
2810 PyObject *joined = NULL;
Christian Heimes9e7f1d22008-02-28 12:27:11 +00002811
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002812 /* Compute ", ".join(sorted(type.__abstractmethods__))
2813 into joined. */
2814 abstract_methods = type_abstractmethods(type, NULL);
2815 if (abstract_methods == NULL)
2816 goto error;
2817 builtins = PyEval_GetBuiltins();
2818 if (builtins == NULL)
2819 goto error;
2820 sorted = PyDict_GetItemString(builtins, "sorted");
2821 if (sorted == NULL)
2822 goto error;
2823 sorted_methods = PyObject_CallFunctionObjArgs(sorted,
2824 abstract_methods,
2825 NULL);
2826 if (sorted_methods == NULL)
2827 goto error;
2828 if (comma == NULL) {
2829 comma = PyUnicode_InternFromString(", ");
2830 if (comma == NULL)
2831 goto error;
2832 }
2833 joined = PyObject_CallMethod(comma, "join",
2834 "O", sorted_methods);
2835 if (joined == NULL)
2836 goto error;
Christian Heimes9e7f1d22008-02-28 12:27:11 +00002837
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002838 PyErr_Format(PyExc_TypeError,
2839 "Can't instantiate abstract class %s "
2840 "with abstract methods %U",
2841 type->tp_name,
2842 joined);
2843 error:
2844 Py_XDECREF(joined);
2845 Py_XDECREF(sorted_methods);
2846 Py_XDECREF(abstract_methods);
2847 return NULL;
2848 }
2849 return type->tp_alloc(type, 0);
Guido van Rossum298e4212003-02-13 16:30:16 +00002850}
2851
Tim Peters6d6c1a32001-08-02 04:15:00 +00002852static void
2853object_dealloc(PyObject *self)
2854{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002855 Py_TYPE(self)->tp_free(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002856}
2857
Guido van Rossum8e248182001-08-12 05:17:56 +00002858static PyObject *
2859object_repr(PyObject *self)
2860{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002861 PyTypeObject *type;
2862 PyObject *mod, *name, *rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00002863
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002864 type = Py_TYPE(self);
2865 mod = type_module(type, NULL);
2866 if (mod == NULL)
2867 PyErr_Clear();
2868 else if (!PyUnicode_Check(mod)) {
2869 Py_DECREF(mod);
2870 mod = NULL;
2871 }
2872 name = type_name(type, NULL);
2873 if (name == NULL)
2874 return NULL;
2875 if (mod != NULL && PyUnicode_CompareWithASCIIString(mod, "builtins"))
2876 rtn = PyUnicode_FromFormat("<%U.%U object at %p>", mod, name, self);
2877 else
2878 rtn = PyUnicode_FromFormat("<%s object at %p>",
2879 type->tp_name, self);
2880 Py_XDECREF(mod);
2881 Py_DECREF(name);
2882 return rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00002883}
2884
Guido van Rossumb8f63662001-08-15 23:57:02 +00002885static PyObject *
2886object_str(PyObject *self)
2887{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002888 unaryfunc f;
Guido van Rossumb8f63662001-08-15 23:57:02 +00002889
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002890 f = Py_TYPE(self)->tp_repr;
2891 if (f == NULL)
2892 f = object_repr;
2893 return f(self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002894}
2895
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002896static PyObject *
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002897object_richcompare(PyObject *self, PyObject *other, int op)
2898{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002899 PyObject *res;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002900
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002901 switch (op) {
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002902
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002903 case Py_EQ:
2904 /* Return NotImplemented instead of False, so if two
2905 objects are compared, both get a chance at the
2906 comparison. See issue #1393. */
2907 res = (self == other) ? Py_True : Py_NotImplemented;
2908 Py_INCREF(res);
2909 break;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002910
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002911 case Py_NE:
2912 /* By default, != returns the opposite of ==,
2913 unless the latter returns NotImplemented. */
2914 res = PyObject_RichCompare(self, other, Py_EQ);
2915 if (res != NULL && res != Py_NotImplemented) {
2916 int ok = PyObject_IsTrue(res);
2917 Py_DECREF(res);
2918 if (ok < 0)
2919 res = NULL;
2920 else {
2921 if (ok)
2922 res = Py_False;
2923 else
2924 res = Py_True;
2925 Py_INCREF(res);
2926 }
2927 }
2928 break;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002929
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002930 default:
2931 res = Py_NotImplemented;
2932 Py_INCREF(res);
2933 break;
2934 }
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002935
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002936 return res;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002937}
2938
2939static PyObject *
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002940object_get_class(PyObject *self, void *closure)
2941{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002942 Py_INCREF(Py_TYPE(self));
2943 return (PyObject *)(Py_TYPE(self));
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002944}
2945
2946static int
2947equiv_structs(PyTypeObject *a, PyTypeObject *b)
2948{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002949 return a == b ||
2950 (a != NULL &&
2951 b != NULL &&
2952 a->tp_basicsize == b->tp_basicsize &&
2953 a->tp_itemsize == b->tp_itemsize &&
2954 a->tp_dictoffset == b->tp_dictoffset &&
2955 a->tp_weaklistoffset == b->tp_weaklistoffset &&
2956 ((a->tp_flags & Py_TPFLAGS_HAVE_GC) ==
2957 (b->tp_flags & Py_TPFLAGS_HAVE_GC)));
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002958}
2959
2960static int
2961same_slots_added(PyTypeObject *a, PyTypeObject *b)
2962{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002963 PyTypeObject *base = a->tp_base;
2964 Py_ssize_t size;
2965 PyObject *slots_a, *slots_b;
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002966
Benjamin Peterson67641d22011-01-17 19:24:34 +00002967 assert(base == b->tp_base);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002968 size = base->tp_basicsize;
2969 if (a->tp_dictoffset == size && b->tp_dictoffset == size)
2970 size += sizeof(PyObject *);
2971 if (a->tp_weaklistoffset == size && b->tp_weaklistoffset == size)
2972 size += sizeof(PyObject *);
Guido van Rossumd8faa362007-04-27 19:54:29 +00002973
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002974 /* Check slots compliance */
2975 slots_a = ((PyHeapTypeObject *)a)->ht_slots;
2976 slots_b = ((PyHeapTypeObject *)b)->ht_slots;
2977 if (slots_a && slots_b) {
2978 if (PyObject_RichCompareBool(slots_a, slots_b, Py_EQ) != 1)
2979 return 0;
2980 size += sizeof(PyObject *) * PyTuple_GET_SIZE(slots_a);
2981 }
2982 return size == a->tp_basicsize && size == b->tp_basicsize;
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002983}
2984
2985static int
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002986compatible_for_assignment(PyTypeObject* oldto, PyTypeObject* newto, char* attr)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002987{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002988 PyTypeObject *newbase, *oldbase;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002989
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002990 if (newto->tp_dealloc != oldto->tp_dealloc ||
2991 newto->tp_free != oldto->tp_free)
2992 {
2993 PyErr_Format(PyExc_TypeError,
2994 "%s assignment: "
2995 "'%s' deallocator differs from '%s'",
2996 attr,
2997 newto->tp_name,
2998 oldto->tp_name);
2999 return 0;
3000 }
3001 newbase = newto;
3002 oldbase = oldto;
3003 while (equiv_structs(newbase, newbase->tp_base))
3004 newbase = newbase->tp_base;
3005 while (equiv_structs(oldbase, oldbase->tp_base))
3006 oldbase = oldbase->tp_base;
3007 if (newbase != oldbase &&
3008 (newbase->tp_base != oldbase->tp_base ||
3009 !same_slots_added(newbase, oldbase))) {
3010 PyErr_Format(PyExc_TypeError,
3011 "%s assignment: "
3012 "'%s' object layout differs from '%s'",
3013 attr,
3014 newto->tp_name,
3015 oldto->tp_name);
3016 return 0;
3017 }
Tim Petersea7f75d2002-12-07 21:39:16 +00003018
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003019 return 1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003020}
3021
3022static int
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003023object_set_class(PyObject *self, PyObject *value, void *closure)
3024{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003025 PyTypeObject *oldto = Py_TYPE(self);
3026 PyTypeObject *newto;
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003027
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003028 if (value == NULL) {
3029 PyErr_SetString(PyExc_TypeError,
3030 "can't delete __class__ attribute");
3031 return -1;
3032 }
3033 if (!PyType_Check(value)) {
3034 PyErr_Format(PyExc_TypeError,
3035 "__class__ must be set to new-style class, not '%s' object",
3036 Py_TYPE(value)->tp_name);
3037 return -1;
3038 }
3039 newto = (PyTypeObject *)value;
3040 if (!(newto->tp_flags & Py_TPFLAGS_HEAPTYPE) ||
3041 !(oldto->tp_flags & Py_TPFLAGS_HEAPTYPE))
3042 {
3043 PyErr_Format(PyExc_TypeError,
3044 "__class__ assignment: only for heap types");
3045 return -1;
3046 }
3047 if (compatible_for_assignment(newto, oldto, "__class__")) {
3048 Py_INCREF(newto);
3049 Py_TYPE(self) = newto;
3050 Py_DECREF(oldto);
3051 return 0;
3052 }
3053 else {
3054 return -1;
3055 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003056}
3057
3058static PyGetSetDef object_getsets[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003059 {"__class__", object_get_class, object_set_class,
3060 PyDoc_STR("the object's class")},
3061 {0}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003062};
3063
Guido van Rossumc53f0092003-02-18 22:05:12 +00003064
Guido van Rossum036f9992003-02-21 22:02:54 +00003065/* Stuff to implement __reduce_ex__ for pickle protocols >= 2.
Alexandre Vassalottif7fa63d2008-05-11 08:55:36 +00003066 We fall back to helpers in copyreg for:
Guido van Rossum036f9992003-02-21 22:02:54 +00003067 - pickle protocols < 2
3068 - calculating the list of slot names (done only once per class)
3069 - the __newobj__ function (which is used as a token but never called)
3070*/
3071
3072static PyObject *
Alexandre Vassalottif7fa63d2008-05-11 08:55:36 +00003073import_copyreg(void)
Guido van Rossum036f9992003-02-21 22:02:54 +00003074{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003075 static PyObject *copyreg_str;
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003076 static PyObject *mod_copyreg = NULL;
Guido van Rossum3926a632001-09-25 16:25:58 +00003077
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003078 if (!copyreg_str) {
3079 copyreg_str = PyUnicode_InternFromString("copyreg");
3080 if (copyreg_str == NULL)
3081 return NULL;
3082 }
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003083 if (!mod_copyreg) {
3084 mod_copyreg = PyImport_Import(copyreg_str);
3085 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003086
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003087 Py_XINCREF(mod_copyreg);
3088 return mod_copyreg;
Guido van Rossum036f9992003-02-21 22:02:54 +00003089}
3090
3091static PyObject *
3092slotnames(PyObject *cls)
3093{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003094 PyObject *clsdict;
3095 PyObject *copyreg;
3096 PyObject *slotnames;
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003097 static PyObject *str_slotnames;
Guido van Rossum036f9992003-02-21 22:02:54 +00003098
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003099 if (str_slotnames == NULL) {
3100 str_slotnames = PyUnicode_InternFromString("__slotnames__");
3101 if (str_slotnames == NULL)
3102 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003103 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003104
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003105 clsdict = ((PyTypeObject *)cls)->tp_dict;
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003106 slotnames = PyDict_GetItem(clsdict, str_slotnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003107 if (slotnames != NULL && PyList_Check(slotnames)) {
3108 Py_INCREF(slotnames);
3109 return slotnames;
3110 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003111
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003112 copyreg = import_copyreg();
3113 if (copyreg == NULL)
3114 return NULL;
Guido van Rossum036f9992003-02-21 22:02:54 +00003115
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003116 slotnames = PyObject_CallMethod(copyreg, "_slotnames", "O", cls);
3117 Py_DECREF(copyreg);
3118 if (slotnames != NULL &&
3119 slotnames != Py_None &&
3120 !PyList_Check(slotnames))
3121 {
3122 PyErr_SetString(PyExc_TypeError,
3123 "copyreg._slotnames didn't return a list or None");
3124 Py_DECREF(slotnames);
3125 slotnames = NULL;
3126 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003127
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003128 return slotnames;
Guido van Rossum036f9992003-02-21 22:02:54 +00003129}
3130
3131static PyObject *
3132reduce_2(PyObject *obj)
3133{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003134 PyObject *cls, *getnewargs;
3135 PyObject *args = NULL, *args2 = NULL;
3136 PyObject *getstate = NULL, *state = NULL, *names = NULL;
3137 PyObject *slots = NULL, *listitems = NULL, *dictitems = NULL;
3138 PyObject *copyreg = NULL, *newobj = NULL, *res = NULL;
3139 Py_ssize_t i, n;
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003140 static PyObject *str_getnewargs = NULL, *str_getstate = NULL,
3141 *str_newobj = NULL;
Guido van Rossum036f9992003-02-21 22:02:54 +00003142
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003143 if (str_getnewargs == NULL) {
3144 str_getnewargs = PyUnicode_InternFromString("__getnewargs__");
3145 str_getstate = PyUnicode_InternFromString("__getstate__");
3146 str_newobj = PyUnicode_InternFromString("__newobj__");
3147 if (!str_getnewargs || !str_getstate || !str_newobj)
3148 return NULL;
3149 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003150
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003151 cls = (PyObject *) Py_TYPE(obj);
3152
3153 getnewargs = PyObject_GetAttr(obj, str_getnewargs);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003154 if (getnewargs != NULL) {
3155 args = PyObject_CallObject(getnewargs, NULL);
3156 Py_DECREF(getnewargs);
3157 if (args != NULL && !PyTuple_Check(args)) {
3158 PyErr_Format(PyExc_TypeError,
3159 "__getnewargs__ should return a tuple, "
3160 "not '%.200s'", Py_TYPE(args)->tp_name);
3161 goto end;
3162 }
3163 }
3164 else {
3165 PyErr_Clear();
3166 args = PyTuple_New(0);
3167 }
3168 if (args == NULL)
3169 goto end;
Guido van Rossum036f9992003-02-21 22:02:54 +00003170
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003171 getstate = PyObject_GetAttr(obj, str_getstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003172 if (getstate != NULL) {
3173 state = PyObject_CallObject(getstate, NULL);
3174 Py_DECREF(getstate);
3175 if (state == NULL)
3176 goto end;
3177 }
3178 else {
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003179 PyObject **dict;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003180 PyErr_Clear();
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003181 dict = _PyObject_GetDictPtr(obj);
3182 if (dict && *dict)
3183 state = *dict;
3184 else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003185 state = Py_None;
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003186 Py_INCREF(state);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003187 names = slotnames(cls);
3188 if (names == NULL)
3189 goto end;
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003190 if (names != Py_None && PyList_GET_SIZE(names) > 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003191 assert(PyList_Check(names));
3192 slots = PyDict_New();
3193 if (slots == NULL)
3194 goto end;
3195 n = 0;
3196 /* Can't pre-compute the list size; the list
3197 is stored on the class so accessible to other
3198 threads, which may be run by DECREF */
3199 for (i = 0; i < PyList_GET_SIZE(names); i++) {
3200 PyObject *name, *value;
3201 name = PyList_GET_ITEM(names, i);
3202 value = PyObject_GetAttr(obj, name);
3203 if (value == NULL)
3204 PyErr_Clear();
3205 else {
3206 int err = PyDict_SetItem(slots, name,
3207 value);
3208 Py_DECREF(value);
3209 if (err)
3210 goto end;
3211 n++;
3212 }
3213 }
3214 if (n) {
3215 state = Py_BuildValue("(NO)", state, slots);
3216 if (state == NULL)
3217 goto end;
3218 }
3219 }
3220 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003221
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003222 if (!PyList_Check(obj)) {
3223 listitems = Py_None;
3224 Py_INCREF(listitems);
3225 }
3226 else {
3227 listitems = PyObject_GetIter(obj);
3228 if (listitems == NULL)
3229 goto end;
3230 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003231
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003232 if (!PyDict_Check(obj)) {
3233 dictitems = Py_None;
3234 Py_INCREF(dictitems);
3235 }
3236 else {
3237 PyObject *items = PyObject_CallMethod(obj, "items", "");
3238 if (items == NULL)
3239 goto end;
3240 dictitems = PyObject_GetIter(items);
3241 Py_DECREF(items);
3242 if (dictitems == NULL)
3243 goto end;
3244 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003245
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003246 copyreg = import_copyreg();
3247 if (copyreg == NULL)
3248 goto end;
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003249 newobj = PyObject_GetAttr(copyreg, str_newobj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003250 if (newobj == NULL)
3251 goto end;
Guido van Rossum036f9992003-02-21 22:02:54 +00003252
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003253 n = PyTuple_GET_SIZE(args);
3254 args2 = PyTuple_New(n+1);
3255 if (args2 == NULL)
3256 goto end;
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003257 Py_INCREF(cls);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003258 PyTuple_SET_ITEM(args2, 0, cls);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003259 for (i = 0; i < n; i++) {
3260 PyObject *v = PyTuple_GET_ITEM(args, i);
3261 Py_INCREF(v);
3262 PyTuple_SET_ITEM(args2, i+1, v);
3263 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003264
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003265 res = PyTuple_Pack(5, newobj, args2, state, listitems, dictitems);
Guido van Rossum036f9992003-02-21 22:02:54 +00003266
3267 end:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003268 Py_XDECREF(args);
3269 Py_XDECREF(args2);
3270 Py_XDECREF(slots);
3271 Py_XDECREF(state);
3272 Py_XDECREF(names);
3273 Py_XDECREF(listitems);
3274 Py_XDECREF(dictitems);
3275 Py_XDECREF(copyreg);
3276 Py_XDECREF(newobj);
3277 return res;
Guido van Rossum036f9992003-02-21 22:02:54 +00003278}
3279
Guido van Rossumd8faa362007-04-27 19:54:29 +00003280/*
3281 * There were two problems when object.__reduce__ and object.__reduce_ex__
3282 * were implemented in the same function:
3283 * - trying to pickle an object with a custom __reduce__ method that
3284 * fell back to object.__reduce__ in certain circumstances led to
3285 * infinite recursion at Python level and eventual RuntimeError.
3286 * - Pickling objects that lied about their type by overwriting the
3287 * __class__ descriptor could lead to infinite recursion at C level
3288 * and eventual segfault.
3289 *
3290 * Because of backwards compatibility, the two methods still have to
3291 * behave in the same way, even if this is not required by the pickle
3292 * protocol. This common functionality was moved to the _common_reduce
3293 * function.
3294 */
3295static PyObject *
3296_common_reduce(PyObject *self, int proto)
3297{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003298 PyObject *copyreg, *res;
Guido van Rossumd8faa362007-04-27 19:54:29 +00003299
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003300 if (proto >= 2)
3301 return reduce_2(self);
Guido van Rossumd8faa362007-04-27 19:54:29 +00003302
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003303 copyreg = import_copyreg();
3304 if (!copyreg)
3305 return NULL;
Guido van Rossumd8faa362007-04-27 19:54:29 +00003306
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003307 res = PyEval_CallMethod(copyreg, "_reduce_ex", "(Oi)", self, proto);
3308 Py_DECREF(copyreg);
Guido van Rossumd8faa362007-04-27 19:54:29 +00003309
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003310 return res;
Guido van Rossumd8faa362007-04-27 19:54:29 +00003311}
3312
3313static PyObject *
3314object_reduce(PyObject *self, PyObject *args)
3315{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003316 int proto = 0;
Guido van Rossumd8faa362007-04-27 19:54:29 +00003317
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003318 if (!PyArg_ParseTuple(args, "|i:__reduce__", &proto))
3319 return NULL;
Guido van Rossumd8faa362007-04-27 19:54:29 +00003320
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003321 return _common_reduce(self, proto);
Guido van Rossumd8faa362007-04-27 19:54:29 +00003322}
3323
Guido van Rossum036f9992003-02-21 22:02:54 +00003324static PyObject *
3325object_reduce_ex(PyObject *self, PyObject *args)
3326{
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003327 static PyObject *str_reduce = NULL, *objreduce;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003328 PyObject *reduce, *res;
3329 int proto = 0;
Guido van Rossum036f9992003-02-21 22:02:54 +00003330
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003331 if (!PyArg_ParseTuple(args, "|i:__reduce_ex__", &proto))
3332 return NULL;
Guido van Rossum036f9992003-02-21 22:02:54 +00003333
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003334 if (str_reduce == NULL) {
3335 str_reduce = PyUnicode_InternFromString("__reduce__");
3336 objreduce = PyDict_GetItemString(PyBaseObject_Type.tp_dict,
3337 "__reduce__");
3338 if (str_reduce == NULL || objreduce == NULL)
3339 return NULL;
3340 }
3341
3342 reduce = PyObject_GetAttr(self, str_reduce);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003343 if (reduce == NULL)
3344 PyErr_Clear();
3345 else {
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003346 PyObject *cls, *clsreduce;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003347 int override;
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003348
3349 cls = (PyObject *) Py_TYPE(self);
3350 clsreduce = PyObject_GetAttr(cls, str_reduce);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003351 if (clsreduce == NULL) {
3352 Py_DECREF(reduce);
3353 return NULL;
3354 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003355 override = (clsreduce != objreduce);
3356 Py_DECREF(clsreduce);
3357 if (override) {
3358 res = PyObject_CallObject(reduce, NULL);
3359 Py_DECREF(reduce);
3360 return res;
3361 }
3362 else
3363 Py_DECREF(reduce);
3364 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003365
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003366 return _common_reduce(self, proto);
Guido van Rossum3926a632001-09-25 16:25:58 +00003367}
3368
Christian Heimes9e7f1d22008-02-28 12:27:11 +00003369static PyObject *
3370object_subclasshook(PyObject *cls, PyObject *args)
3371{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003372 Py_INCREF(Py_NotImplemented);
3373 return Py_NotImplemented;
Christian Heimes9e7f1d22008-02-28 12:27:11 +00003374}
3375
3376PyDoc_STRVAR(object_subclasshook_doc,
3377"Abstract classes can override this to customize issubclass().\n"
3378"\n"
3379"This is invoked early on by abc.ABCMeta.__subclasscheck__().\n"
3380"It should return True, False or NotImplemented. If it returns\n"
3381"NotImplemented, the normal algorithm is used. Otherwise, it\n"
3382"overrides the normal algorithm (and the outcome is cached).\n");
Eric Smith8c663262007-08-25 02:26:07 +00003383
3384/*
3385 from PEP 3101, this code implements:
3386
3387 class object:
3388 def __format__(self, format_spec):
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003389 return format(str(self), format_spec)
Eric Smith8c663262007-08-25 02:26:07 +00003390*/
3391static PyObject *
3392object_format(PyObject *self, PyObject *args)
3393{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003394 PyObject *format_spec;
3395 PyObject *self_as_str = NULL;
3396 PyObject *result = NULL;
Eric Smith8c663262007-08-25 02:26:07 +00003397
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003398 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
3399 return NULL;
Eric Smith8c663262007-08-25 02:26:07 +00003400
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003401 self_as_str = PyObject_Str(self);
Eric Smithe4d63172010-09-13 20:48:43 +00003402 if (self_as_str != NULL) {
3403 /* Issue 7994: If we're converting to a string, we
Eric V. Smithb9cd3532011-03-12 10:08:48 -05003404 should reject format specifications */
Eric Smithe4d63172010-09-13 20:48:43 +00003405 if (PyUnicode_GET_SIZE(format_spec) > 0) {
Eric V. Smithb9cd3532011-03-12 10:08:48 -05003406 if (PyErr_WarnEx(PyExc_DeprecationWarning,
3407 "object.__format__ with a non-empty format "
3408 "string is deprecated", 1) < 0) {
3409 goto done;
3410 }
3411 /* Eventually this will become an error:
3412 PyErr_Format(PyExc_TypeError,
3413 "non-empty format string passed to object.__format__");
3414 goto done;
3415 */
3416 }
Eric Smith8c663262007-08-25 02:26:07 +00003417
Eric V. Smithb9cd3532011-03-12 10:08:48 -05003418 result = PyObject_Format(self_as_str, format_spec);
Eric Smithe4d63172010-09-13 20:48:43 +00003419 }
3420
3421done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003422 Py_XDECREF(self_as_str);
Eric Smith8c663262007-08-25 02:26:07 +00003423
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003424 return result;
Eric Smith8c663262007-08-25 02:26:07 +00003425}
3426
Martin v. Löwis00709aa2008-06-04 14:18:43 +00003427static PyObject *
3428object_sizeof(PyObject *self, PyObject *args)
3429{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003430 Py_ssize_t res, isize;
Martin v. Löwis00709aa2008-06-04 14:18:43 +00003431
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003432 res = 0;
3433 isize = self->ob_type->tp_itemsize;
3434 if (isize > 0)
3435 res = Py_SIZE(self->ob_type) * isize;
3436 res += self->ob_type->tp_basicsize;
Martin v. Löwis00709aa2008-06-04 14:18:43 +00003437
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003438 return PyLong_FromSsize_t(res);
Martin v. Löwis00709aa2008-06-04 14:18:43 +00003439}
3440
Guido van Rossum3926a632001-09-25 16:25:58 +00003441static PyMethodDef object_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003442 {"__reduce_ex__", object_reduce_ex, METH_VARARGS,
3443 PyDoc_STR("helper for pickle")},
3444 {"__reduce__", object_reduce, METH_VARARGS,
3445 PyDoc_STR("helper for pickle")},
3446 {"__subclasshook__", object_subclasshook, METH_CLASS | METH_VARARGS,
3447 object_subclasshook_doc},
3448 {"__format__", object_format, METH_VARARGS,
3449 PyDoc_STR("default object formatter")},
3450 {"__sizeof__", object_sizeof, METH_NOARGS,
3451 PyDoc_STR("__sizeof__() -> size of object in memory, in bytes")},
3452 {0}
Guido van Rossum3926a632001-09-25 16:25:58 +00003453};
3454
Guido van Rossum036f9992003-02-21 22:02:54 +00003455
Tim Peters6d6c1a32001-08-02 04:15:00 +00003456PyTypeObject PyBaseObject_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003457 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3458 "object", /* tp_name */
3459 sizeof(PyObject), /* tp_basicsize */
3460 0, /* tp_itemsize */
3461 object_dealloc, /* tp_dealloc */
3462 0, /* tp_print */
3463 0, /* tp_getattr */
3464 0, /* tp_setattr */
3465 0, /* tp_reserved */
3466 object_repr, /* tp_repr */
3467 0, /* tp_as_number */
3468 0, /* tp_as_sequence */
3469 0, /* tp_as_mapping */
3470 (hashfunc)_Py_HashPointer, /* tp_hash */
3471 0, /* tp_call */
3472 object_str, /* tp_str */
3473 PyObject_GenericGetAttr, /* tp_getattro */
3474 PyObject_GenericSetAttr, /* tp_setattro */
3475 0, /* tp_as_buffer */
3476 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
3477 PyDoc_STR("The most base type"), /* tp_doc */
3478 0, /* tp_traverse */
3479 0, /* tp_clear */
3480 object_richcompare, /* tp_richcompare */
3481 0, /* tp_weaklistoffset */
3482 0, /* tp_iter */
3483 0, /* tp_iternext */
3484 object_methods, /* tp_methods */
3485 0, /* tp_members */
3486 object_getsets, /* tp_getset */
3487 0, /* tp_base */
3488 0, /* tp_dict */
3489 0, /* tp_descr_get */
3490 0, /* tp_descr_set */
3491 0, /* tp_dictoffset */
3492 object_init, /* tp_init */
3493 PyType_GenericAlloc, /* tp_alloc */
3494 object_new, /* tp_new */
3495 PyObject_Del, /* tp_free */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003496};
3497
3498
Guido van Rossum50e9fb92006-08-17 05:42:55 +00003499/* Add the methods from tp_methods to the __dict__ in a type object */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003500
3501static int
3502add_methods(PyTypeObject *type, PyMethodDef *meth)
3503{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003504 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003505
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003506 for (; meth->ml_name != NULL; meth++) {
3507 PyObject *descr;
3508 if (PyDict_GetItemString(dict, meth->ml_name) &&
3509 !(meth->ml_flags & METH_COEXIST))
3510 continue;
3511 if (meth->ml_flags & METH_CLASS) {
3512 if (meth->ml_flags & METH_STATIC) {
3513 PyErr_SetString(PyExc_ValueError,
3514 "method cannot be both class and static");
3515 return -1;
3516 }
3517 descr = PyDescr_NewClassMethod(type, meth);
3518 }
3519 else if (meth->ml_flags & METH_STATIC) {
3520 PyObject *cfunc = PyCFunction_New(meth, NULL);
3521 if (cfunc == NULL)
3522 return -1;
3523 descr = PyStaticMethod_New(cfunc);
3524 Py_DECREF(cfunc);
3525 }
3526 else {
3527 descr = PyDescr_NewMethod(type, meth);
3528 }
3529 if (descr == NULL)
3530 return -1;
3531 if (PyDict_SetItemString(dict, meth->ml_name, descr) < 0)
3532 return -1;
3533 Py_DECREF(descr);
3534 }
3535 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003536}
3537
3538static int
Guido van Rossum6f799372001-09-20 20:46:19 +00003539add_members(PyTypeObject *type, PyMemberDef *memb)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003540{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003541 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003542
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003543 for (; memb->name != NULL; memb++) {
3544 PyObject *descr;
3545 if (PyDict_GetItemString(dict, memb->name))
3546 continue;
3547 descr = PyDescr_NewMember(type, memb);
3548 if (descr == NULL)
3549 return -1;
3550 if (PyDict_SetItemString(dict, memb->name, descr) < 0)
3551 return -1;
3552 Py_DECREF(descr);
3553 }
3554 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003555}
3556
3557static int
Guido van Rossum32d34c82001-09-20 21:45:26 +00003558add_getset(PyTypeObject *type, PyGetSetDef *gsp)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003559{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003560 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003561
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003562 for (; gsp->name != NULL; gsp++) {
3563 PyObject *descr;
3564 if (PyDict_GetItemString(dict, gsp->name))
3565 continue;
3566 descr = PyDescr_NewGetSet(type, gsp);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003567
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003568 if (descr == NULL)
3569 return -1;
3570 if (PyDict_SetItemString(dict, gsp->name, descr) < 0)
3571 return -1;
3572 Py_DECREF(descr);
3573 }
3574 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003575}
3576
Guido van Rossum13d52f02001-08-10 21:24:08 +00003577static void
3578inherit_special(PyTypeObject *type, PyTypeObject *base)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003579{
Tim Peters6d6c1a32001-08-02 04:15:00 +00003580
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003581 /* Copying basicsize is connected to the GC flags */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003582 if (!(type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
3583 (base->tp_flags & Py_TPFLAGS_HAVE_GC) &&
3584 (!type->tp_traverse && !type->tp_clear)) {
3585 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
3586 if (type->tp_traverse == NULL)
3587 type->tp_traverse = base->tp_traverse;
3588 if (type->tp_clear == NULL)
3589 type->tp_clear = base->tp_clear;
3590 }
3591 {
3592 /* The condition below could use some explanation.
3593 It appears that tp_new is not inherited for static types
3594 whose base class is 'object'; this seems to be a precaution
3595 so that old extension types don't suddenly become
3596 callable (object.__new__ wouldn't insure the invariants
3597 that the extension type's own factory function ensures).
3598 Heap types, of course, are under our control, so they do
3599 inherit tp_new; static extension types that specify some
3600 other built-in type as the default are considered
3601 new-style-aware so they also inherit object.__new__. */
3602 if (base != &PyBaseObject_Type ||
3603 (type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
3604 if (type->tp_new == NULL)
3605 type->tp_new = base->tp_new;
3606 }
3607 }
Benjamin Petersona7465e22010-07-05 15:01:22 +00003608 if (type->tp_basicsize == 0)
3609 type->tp_basicsize = base->tp_basicsize;
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00003610
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003611 /* Copy other non-function slots */
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00003612
3613#undef COPYVAL
3614#define COPYVAL(SLOT) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003615 if (type->SLOT == 0) type->SLOT = base->SLOT
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00003616
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003617 COPYVAL(tp_itemsize);
3618 COPYVAL(tp_weaklistoffset);
3619 COPYVAL(tp_dictoffset);
Thomas Wouters27d517b2007-02-25 20:39:11 +00003620
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003621 /* Setup fast subclass flags */
3622 if (PyType_IsSubtype(base, (PyTypeObject*)PyExc_BaseException))
3623 type->tp_flags |= Py_TPFLAGS_BASE_EXC_SUBCLASS;
3624 else if (PyType_IsSubtype(base, &PyType_Type))
3625 type->tp_flags |= Py_TPFLAGS_TYPE_SUBCLASS;
3626 else if (PyType_IsSubtype(base, &PyLong_Type))
3627 type->tp_flags |= Py_TPFLAGS_LONG_SUBCLASS;
3628 else if (PyType_IsSubtype(base, &PyBytes_Type))
3629 type->tp_flags |= Py_TPFLAGS_BYTES_SUBCLASS;
3630 else if (PyType_IsSubtype(base, &PyUnicode_Type))
3631 type->tp_flags |= Py_TPFLAGS_UNICODE_SUBCLASS;
3632 else if (PyType_IsSubtype(base, &PyTuple_Type))
3633 type->tp_flags |= Py_TPFLAGS_TUPLE_SUBCLASS;
3634 else if (PyType_IsSubtype(base, &PyList_Type))
3635 type->tp_flags |= Py_TPFLAGS_LIST_SUBCLASS;
3636 else if (PyType_IsSubtype(base, &PyDict_Type))
3637 type->tp_flags |= Py_TPFLAGS_DICT_SUBCLASS;
Guido van Rossum13d52f02001-08-10 21:24:08 +00003638}
3639
Guido van Rossumf5243f02008-01-01 04:06:48 +00003640static char *hash_name_op[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003641 "__eq__",
3642 "__hash__",
3643 NULL
Guido van Rossum38938152006-08-21 23:36:26 +00003644};
3645
3646static int
Guido van Rossumf5243f02008-01-01 04:06:48 +00003647overrides_hash(PyTypeObject *type)
Guido van Rossum38938152006-08-21 23:36:26 +00003648{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003649 char **p;
3650 PyObject *dict = type->tp_dict;
Guido van Rossum38938152006-08-21 23:36:26 +00003651
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003652 assert(dict != NULL);
3653 for (p = hash_name_op; *p; p++) {
3654 if (PyDict_GetItemString(dict, *p) != NULL)
3655 return 1;
3656 }
3657 return 0;
Guido van Rossum38938152006-08-21 23:36:26 +00003658}
3659
Guido van Rossum13d52f02001-08-10 21:24:08 +00003660static void
3661inherit_slots(PyTypeObject *type, PyTypeObject *base)
3662{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003663 PyTypeObject *basebase;
Guido van Rossum13d52f02001-08-10 21:24:08 +00003664
3665#undef SLOTDEFINED
Tim Peters6d6c1a32001-08-02 04:15:00 +00003666#undef COPYSLOT
3667#undef COPYNUM
3668#undef COPYSEQ
3669#undef COPYMAP
Guido van Rossum5af588b2001-10-12 14:13:21 +00003670#undef COPYBUF
Guido van Rossum13d52f02001-08-10 21:24:08 +00003671
3672#define SLOTDEFINED(SLOT) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003673 (base->SLOT != 0 && \
3674 (basebase == NULL || base->SLOT != basebase->SLOT))
Guido van Rossum13d52f02001-08-10 21:24:08 +00003675
Tim Peters6d6c1a32001-08-02 04:15:00 +00003676#define COPYSLOT(SLOT) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003677 if (!type->SLOT && SLOTDEFINED(SLOT)) type->SLOT = base->SLOT
Tim Peters6d6c1a32001-08-02 04:15:00 +00003678
3679#define COPYNUM(SLOT) COPYSLOT(tp_as_number->SLOT)
3680#define COPYSEQ(SLOT) COPYSLOT(tp_as_sequence->SLOT)
3681#define COPYMAP(SLOT) COPYSLOT(tp_as_mapping->SLOT)
Tim Petersfc57ccb2001-10-12 02:38:24 +00003682#define COPYBUF(SLOT) COPYSLOT(tp_as_buffer->SLOT)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003683
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003684 /* This won't inherit indirect slots (from tp_as_number etc.)
3685 if type doesn't provide the space. */
Guido van Rossum13d52f02001-08-10 21:24:08 +00003686
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003687 if (type->tp_as_number != NULL && base->tp_as_number != NULL) {
3688 basebase = base->tp_base;
3689 if (basebase->tp_as_number == NULL)
3690 basebase = NULL;
3691 COPYNUM(nb_add);
3692 COPYNUM(nb_subtract);
3693 COPYNUM(nb_multiply);
3694 COPYNUM(nb_remainder);
3695 COPYNUM(nb_divmod);
3696 COPYNUM(nb_power);
3697 COPYNUM(nb_negative);
3698 COPYNUM(nb_positive);
3699 COPYNUM(nb_absolute);
3700 COPYNUM(nb_bool);
3701 COPYNUM(nb_invert);
3702 COPYNUM(nb_lshift);
3703 COPYNUM(nb_rshift);
3704 COPYNUM(nb_and);
3705 COPYNUM(nb_xor);
3706 COPYNUM(nb_or);
3707 COPYNUM(nb_int);
3708 COPYNUM(nb_float);
3709 COPYNUM(nb_inplace_add);
3710 COPYNUM(nb_inplace_subtract);
3711 COPYNUM(nb_inplace_multiply);
3712 COPYNUM(nb_inplace_remainder);
3713 COPYNUM(nb_inplace_power);
3714 COPYNUM(nb_inplace_lshift);
3715 COPYNUM(nb_inplace_rshift);
3716 COPYNUM(nb_inplace_and);
3717 COPYNUM(nb_inplace_xor);
3718 COPYNUM(nb_inplace_or);
3719 COPYNUM(nb_true_divide);
3720 COPYNUM(nb_floor_divide);
3721 COPYNUM(nb_inplace_true_divide);
3722 COPYNUM(nb_inplace_floor_divide);
3723 COPYNUM(nb_index);
3724 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003725
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003726 if (type->tp_as_sequence != NULL && base->tp_as_sequence != NULL) {
3727 basebase = base->tp_base;
3728 if (basebase->tp_as_sequence == NULL)
3729 basebase = NULL;
3730 COPYSEQ(sq_length);
3731 COPYSEQ(sq_concat);
3732 COPYSEQ(sq_repeat);
3733 COPYSEQ(sq_item);
3734 COPYSEQ(sq_ass_item);
3735 COPYSEQ(sq_contains);
3736 COPYSEQ(sq_inplace_concat);
3737 COPYSEQ(sq_inplace_repeat);
3738 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003739
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003740 if (type->tp_as_mapping != NULL && base->tp_as_mapping != NULL) {
3741 basebase = base->tp_base;
3742 if (basebase->tp_as_mapping == NULL)
3743 basebase = NULL;
3744 COPYMAP(mp_length);
3745 COPYMAP(mp_subscript);
3746 COPYMAP(mp_ass_subscript);
3747 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003748
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003749 if (type->tp_as_buffer != NULL && base->tp_as_buffer != NULL) {
3750 basebase = base->tp_base;
3751 if (basebase->tp_as_buffer == NULL)
3752 basebase = NULL;
3753 COPYBUF(bf_getbuffer);
3754 COPYBUF(bf_releasebuffer);
3755 }
Tim Petersfc57ccb2001-10-12 02:38:24 +00003756
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003757 basebase = base->tp_base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003758
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003759 COPYSLOT(tp_dealloc);
3760 if (type->tp_getattr == NULL && type->tp_getattro == NULL) {
3761 type->tp_getattr = base->tp_getattr;
3762 type->tp_getattro = base->tp_getattro;
3763 }
3764 if (type->tp_setattr == NULL && type->tp_setattro == NULL) {
3765 type->tp_setattr = base->tp_setattr;
3766 type->tp_setattro = base->tp_setattro;
3767 }
3768 /* tp_reserved is ignored */
3769 COPYSLOT(tp_repr);
3770 /* tp_hash see tp_richcompare */
3771 COPYSLOT(tp_call);
3772 COPYSLOT(tp_str);
3773 {
3774 /* Copy comparison-related slots only when
3775 not overriding them anywhere */
3776 if (type->tp_richcompare == NULL &&
3777 type->tp_hash == NULL &&
3778 !overrides_hash(type))
3779 {
3780 type->tp_richcompare = base->tp_richcompare;
3781 type->tp_hash = base->tp_hash;
3782 }
3783 }
3784 {
3785 COPYSLOT(tp_iter);
3786 COPYSLOT(tp_iternext);
3787 }
3788 {
3789 COPYSLOT(tp_descr_get);
3790 COPYSLOT(tp_descr_set);
3791 COPYSLOT(tp_dictoffset);
3792 COPYSLOT(tp_init);
3793 COPYSLOT(tp_alloc);
3794 COPYSLOT(tp_is_gc);
3795 if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) ==
3796 (base->tp_flags & Py_TPFLAGS_HAVE_GC)) {
3797 /* They agree about gc. */
3798 COPYSLOT(tp_free);
3799 }
3800 else if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
3801 type->tp_free == NULL &&
3802 base->tp_free == PyObject_Free) {
3803 /* A bit of magic to plug in the correct default
3804 * tp_free function when a derived class adds gc,
3805 * didn't define tp_free, and the base uses the
3806 * default non-gc tp_free.
3807 */
3808 type->tp_free = PyObject_GC_Del;
3809 }
3810 /* else they didn't agree about gc, and there isn't something
3811 * obvious to be done -- the type is on its own.
3812 */
3813 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003814}
3815
Jeremy Hylton938ace62002-07-17 16:30:39 +00003816static int add_operators(PyTypeObject *);
Guido van Rossum13d52f02001-08-10 21:24:08 +00003817
Tim Peters6d6c1a32001-08-02 04:15:00 +00003818int
Guido van Rossum528b7eb2001-08-07 17:24:28 +00003819PyType_Ready(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003820{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003821 PyObject *dict, *bases;
3822 PyTypeObject *base;
3823 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003824
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003825 if (type->tp_flags & Py_TPFLAGS_READY) {
3826 assert(type->tp_dict != NULL);
3827 return 0;
3828 }
3829 assert((type->tp_flags & Py_TPFLAGS_READYING) == 0);
Guido van Rossumd614f972001-08-10 17:39:49 +00003830
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003831 type->tp_flags |= Py_TPFLAGS_READYING;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003832
Tim Peters36eb4df2003-03-23 03:33:13 +00003833#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003834 /* PyType_Ready is the closest thing we have to a choke point
3835 * for type objects, so is the best place I can think of to try
3836 * to get type objects into the doubly-linked list of all objects.
3837 * Still, not all type objects go thru PyType_Ready.
3838 */
3839 _Py_AddToAllObjects((PyObject *)type, 0);
Tim Peters36eb4df2003-03-23 03:33:13 +00003840#endif
3841
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003842 /* Initialize tp_base (defaults to BaseObject unless that's us) */
3843 base = type->tp_base;
3844 if (base == NULL && type != &PyBaseObject_Type) {
3845 base = type->tp_base = &PyBaseObject_Type;
3846 Py_INCREF(base);
3847 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003848
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003849 /* Now the only way base can still be NULL is if type is
3850 * &PyBaseObject_Type.
3851 */
Guido van Rossum692cdbc2006-03-10 02:04:28 +00003852
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003853 /* Initialize the base class */
3854 if (base != NULL && base->tp_dict == NULL) {
3855 if (PyType_Ready(base) < 0)
3856 goto error;
3857 }
Guido van Rossum323a9cf2002-08-14 17:26:30 +00003858
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003859 /* Initialize ob_type if NULL. This means extensions that want to be
3860 compilable separately on Windows can call PyType_Ready() instead of
3861 initializing the ob_type field of their type objects. */
3862 /* The test for base != NULL is really unnecessary, since base is only
3863 NULL when type is &PyBaseObject_Type, and we know its ob_type is
3864 not NULL (it's initialized to &PyType_Type). But coverity doesn't
3865 know that. */
3866 if (Py_TYPE(type) == NULL && base != NULL)
3867 Py_TYPE(type) = Py_TYPE(base);
Guido van Rossum0986d822002-04-08 01:38:42 +00003868
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003869 /* Initialize tp_bases */
3870 bases = type->tp_bases;
3871 if (bases == NULL) {
3872 if (base == NULL)
3873 bases = PyTuple_New(0);
3874 else
3875 bases = PyTuple_Pack(1, base);
3876 if (bases == NULL)
3877 goto error;
3878 type->tp_bases = bases;
3879 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003880
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003881 /* Initialize tp_dict */
3882 dict = type->tp_dict;
3883 if (dict == NULL) {
3884 dict = PyDict_New();
3885 if (dict == NULL)
3886 goto error;
3887 type->tp_dict = dict;
3888 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003889
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003890 /* Add type-specific descriptors to tp_dict */
3891 if (add_operators(type) < 0)
3892 goto error;
3893 if (type->tp_methods != NULL) {
3894 if (add_methods(type, type->tp_methods) < 0)
3895 goto error;
3896 }
3897 if (type->tp_members != NULL) {
3898 if (add_members(type, type->tp_members) < 0)
3899 goto error;
3900 }
3901 if (type->tp_getset != NULL) {
3902 if (add_getset(type, type->tp_getset) < 0)
3903 goto error;
3904 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003905
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003906 /* Calculate method resolution order */
3907 if (mro_internal(type) < 0) {
3908 goto error;
3909 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003910
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003911 /* Inherit special flags from dominant base */
3912 if (type->tp_base != NULL)
3913 inherit_special(type, type->tp_base);
Guido van Rossum13d52f02001-08-10 21:24:08 +00003914
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003915 /* Initialize tp_dict properly */
3916 bases = type->tp_mro;
3917 assert(bases != NULL);
3918 assert(PyTuple_Check(bases));
3919 n = PyTuple_GET_SIZE(bases);
3920 for (i = 1; i < n; i++) {
3921 PyObject *b = PyTuple_GET_ITEM(bases, i);
3922 if (PyType_Check(b))
3923 inherit_slots(type, (PyTypeObject *)b);
3924 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003925
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003926 /* Sanity check for tp_free. */
3927 if (PyType_IS_GC(type) && (type->tp_flags & Py_TPFLAGS_BASETYPE) &&
3928 (type->tp_free == NULL || type->tp_free == PyObject_Del)) {
3929 /* This base class needs to call tp_free, but doesn't have
3930 * one, or its tp_free is for non-gc'ed objects.
3931 */
3932 PyErr_Format(PyExc_TypeError, "type '%.100s' participates in "
3933 "gc and is a base type but has inappropriate "
3934 "tp_free slot",
3935 type->tp_name);
3936 goto error;
3937 }
Tim Peters3cfe7542003-05-21 21:29:48 +00003938
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003939 /* if the type dictionary doesn't contain a __doc__, set it from
3940 the tp_doc slot.
3941 */
3942 if (PyDict_GetItemString(type->tp_dict, "__doc__") == NULL) {
3943 if (type->tp_doc != NULL) {
3944 PyObject *doc = PyUnicode_FromString(type->tp_doc);
3945 if (doc == NULL)
3946 goto error;
3947 PyDict_SetItemString(type->tp_dict, "__doc__", doc);
3948 Py_DECREF(doc);
3949 } else {
3950 PyDict_SetItemString(type->tp_dict,
3951 "__doc__", Py_None);
3952 }
3953 }
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00003954
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003955 /* Hack for tp_hash and __hash__.
3956 If after all that, tp_hash is still NULL, and __hash__ is not in
3957 tp_dict, set tp_hash to PyObject_HashNotImplemented and
3958 tp_dict['__hash__'] equal to None.
3959 This signals that __hash__ is not inherited.
3960 */
3961 if (type->tp_hash == NULL) {
3962 if (PyDict_GetItemString(type->tp_dict, "__hash__") == NULL) {
3963 if (PyDict_SetItemString(type->tp_dict, "__hash__", Py_None) < 0)
3964 goto error;
3965 type->tp_hash = PyObject_HashNotImplemented;
3966 }
3967 }
Guido van Rossum38938152006-08-21 23:36:26 +00003968
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003969 /* Some more special stuff */
3970 base = type->tp_base;
3971 if (base != NULL) {
3972 if (type->tp_as_number == NULL)
3973 type->tp_as_number = base->tp_as_number;
3974 if (type->tp_as_sequence == NULL)
3975 type->tp_as_sequence = base->tp_as_sequence;
3976 if (type->tp_as_mapping == NULL)
3977 type->tp_as_mapping = base->tp_as_mapping;
3978 if (type->tp_as_buffer == NULL)
3979 type->tp_as_buffer = base->tp_as_buffer;
3980 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003981
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003982 /* Link into each base class's list of subclasses */
3983 bases = type->tp_bases;
3984 n = PyTuple_GET_SIZE(bases);
3985 for (i = 0; i < n; i++) {
3986 PyObject *b = PyTuple_GET_ITEM(bases, i);
3987 if (PyType_Check(b) &&
3988 add_subclass((PyTypeObject *)b, type) < 0)
3989 goto error;
3990 }
Guido van Rossum1c450732001-10-08 15:18:27 +00003991
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003992 /* Warn for a type that implements tp_compare (now known as
3993 tp_reserved) but not tp_richcompare. */
3994 if (type->tp_reserved && !type->tp_richcompare) {
3995 int error;
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003996 error = PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
3997 "Type %.100s defines tp_reserved (formerly tp_compare) "
3998 "but not tp_richcompare. Comparisons may not behave as intended.",
3999 type->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004000 if (error == -1)
4001 goto error;
4002 }
Mark Dickinson2a7d45b2009-02-08 11:02:10 +00004003
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004004 /* All done -- set the ready flag */
4005 assert(type->tp_dict != NULL);
4006 type->tp_flags =
4007 (type->tp_flags & ~Py_TPFLAGS_READYING) | Py_TPFLAGS_READY;
4008 return 0;
Guido van Rossumd614f972001-08-10 17:39:49 +00004009
4010 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004011 type->tp_flags &= ~Py_TPFLAGS_READYING;
4012 return -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004013}
4014
Guido van Rossum1c450732001-10-08 15:18:27 +00004015static int
4016add_subclass(PyTypeObject *base, PyTypeObject *type)
4017{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004018 Py_ssize_t i;
4019 int result;
4020 PyObject *list, *ref, *newobj;
Guido van Rossum1c450732001-10-08 15:18:27 +00004021
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004022 list = base->tp_subclasses;
4023 if (list == NULL) {
4024 base->tp_subclasses = list = PyList_New(0);
4025 if (list == NULL)
4026 return -1;
4027 }
4028 assert(PyList_Check(list));
4029 newobj = PyWeakref_NewRef((PyObject *)type, NULL);
4030 i = PyList_GET_SIZE(list);
4031 while (--i >= 0) {
4032 ref = PyList_GET_ITEM(list, i);
4033 assert(PyWeakref_CheckRef(ref));
4034 if (PyWeakref_GET_OBJECT(ref) == Py_None)
4035 return PyList_SetItem(list, i, newobj);
4036 }
4037 result = PyList_Append(list, newobj);
4038 Py_DECREF(newobj);
4039 return result;
Guido van Rossum1c450732001-10-08 15:18:27 +00004040}
4041
Michael W. Hudson98bbc492002-11-26 14:47:27 +00004042static void
4043remove_subclass(PyTypeObject *base, PyTypeObject *type)
4044{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004045 Py_ssize_t i;
4046 PyObject *list, *ref;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00004047
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004048 list = base->tp_subclasses;
4049 if (list == NULL) {
4050 return;
4051 }
4052 assert(PyList_Check(list));
4053 i = PyList_GET_SIZE(list);
4054 while (--i >= 0) {
4055 ref = PyList_GET_ITEM(list, i);
4056 assert(PyWeakref_CheckRef(ref));
4057 if (PyWeakref_GET_OBJECT(ref) == (PyObject*)type) {
4058 /* this can't fail, right? */
4059 PySequence_DelItem(list, i);
4060 return;
4061 }
4062 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +00004063}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004064
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004065static int
4066check_num_args(PyObject *ob, int n)
4067{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004068 if (!PyTuple_CheckExact(ob)) {
4069 PyErr_SetString(PyExc_SystemError,
4070 "PyArg_UnpackTuple() argument list is not a tuple");
4071 return 0;
4072 }
4073 if (n == PyTuple_GET_SIZE(ob))
4074 return 1;
4075 PyErr_Format(
4076 PyExc_TypeError,
4077 "expected %d arguments, got %zd", n, PyTuple_GET_SIZE(ob));
4078 return 0;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004079}
4080
Tim Peters6d6c1a32001-08-02 04:15:00 +00004081/* Generic wrappers for overloadable 'operators' such as __getitem__ */
4082
4083/* There's a wrapper *function* for each distinct function typedef used
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004084 for type object slots (e.g. binaryfunc, ternaryfunc, etc.). There's a
Tim Peters6d6c1a32001-08-02 04:15:00 +00004085 wrapper *table* for each distinct operation (e.g. __len__, __add__).
4086 Most tables have only one entry; the tables for binary operators have two
4087 entries, one regular and one with reversed arguments. */
4088
4089static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00004090wrap_lenfunc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004091{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004092 lenfunc func = (lenfunc)wrapped;
4093 Py_ssize_t res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004094
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004095 if (!check_num_args(args, 0))
4096 return NULL;
4097 res = (*func)(self);
4098 if (res == -1 && PyErr_Occurred())
4099 return NULL;
4100 return PyLong_FromLong((long)res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004101}
4102
Tim Peters6d6c1a32001-08-02 04:15:00 +00004103static PyObject *
Raymond Hettingerf34f2642003-10-11 17:29:04 +00004104wrap_inquirypred(PyObject *self, PyObject *args, void *wrapped)
4105{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004106 inquiry func = (inquiry)wrapped;
4107 int res;
Raymond Hettingerf34f2642003-10-11 17:29:04 +00004108
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004109 if (!check_num_args(args, 0))
4110 return NULL;
4111 res = (*func)(self);
4112 if (res == -1 && PyErr_Occurred())
4113 return NULL;
4114 return PyBool_FromLong((long)res);
Raymond Hettingerf34f2642003-10-11 17:29:04 +00004115}
4116
4117static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00004118wrap_binaryfunc(PyObject *self, PyObject *args, void *wrapped)
4119{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004120 binaryfunc func = (binaryfunc)wrapped;
4121 PyObject *other;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004122
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004123 if (!check_num_args(args, 1))
4124 return NULL;
4125 other = PyTuple_GET_ITEM(args, 0);
4126 return (*func)(self, other);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004127}
4128
4129static PyObject *
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00004130wrap_binaryfunc_l(PyObject *self, PyObject *args, void *wrapped)
4131{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004132 binaryfunc func = (binaryfunc)wrapped;
4133 PyObject *other;
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00004134
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004135 if (!check_num_args(args, 1))
4136 return NULL;
4137 other = PyTuple_GET_ITEM(args, 0);
4138 return (*func)(self, other);
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00004139}
4140
4141static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00004142wrap_binaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
4143{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004144 binaryfunc func = (binaryfunc)wrapped;
4145 PyObject *other;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004146
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004147 if (!check_num_args(args, 1))
4148 return NULL;
4149 other = PyTuple_GET_ITEM(args, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004150 return (*func)(other, self);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004151}
4152
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004153static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00004154wrap_ternaryfunc(PyObject *self, PyObject *args, void *wrapped)
4155{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004156 ternaryfunc func = (ternaryfunc)wrapped;
4157 PyObject *other;
4158 PyObject *third = Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004159
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004160 /* Note: This wrapper only works for __pow__() */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004161
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004162 if (!PyArg_UnpackTuple(args, "", 1, 2, &other, &third))
4163 return NULL;
4164 return (*func)(self, other, third);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004165}
4166
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00004167static PyObject *
4168wrap_ternaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
4169{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004170 ternaryfunc func = (ternaryfunc)wrapped;
4171 PyObject *other;
4172 PyObject *third = Py_None;
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00004173
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004174 /* Note: This wrapper only works for __pow__() */
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00004175
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004176 if (!PyArg_UnpackTuple(args, "", 1, 2, &other, &third))
4177 return NULL;
4178 return (*func)(other, self, third);
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00004179}
4180
Tim Peters6d6c1a32001-08-02 04:15:00 +00004181static PyObject *
4182wrap_unaryfunc(PyObject *self, PyObject *args, void *wrapped)
4183{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004184 unaryfunc func = (unaryfunc)wrapped;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004185
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004186 if (!check_num_args(args, 0))
4187 return NULL;
4188 return (*func)(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004189}
4190
Tim Peters6d6c1a32001-08-02 04:15:00 +00004191static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004192wrap_indexargfunc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004193{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004194 ssizeargfunc func = (ssizeargfunc)wrapped;
4195 PyObject* o;
4196 Py_ssize_t i;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004197
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004198 if (!PyArg_UnpackTuple(args, "", 1, 1, &o))
4199 return NULL;
4200 i = PyNumber_AsSsize_t(o, PyExc_OverflowError);
4201 if (i == -1 && PyErr_Occurred())
4202 return NULL;
4203 return (*func)(self, i);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004204}
4205
Martin v. Löwis18e16552006-02-15 17:27:45 +00004206static Py_ssize_t
Guido van Rossum5d815f32001-08-17 21:57:47 +00004207getindex(PyObject *self, PyObject *arg)
4208{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004209 Py_ssize_t i;
Guido van Rossum5d815f32001-08-17 21:57:47 +00004210
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004211 i = PyNumber_AsSsize_t(arg, PyExc_OverflowError);
4212 if (i == -1 && PyErr_Occurred())
4213 return -1;
4214 if (i < 0) {
4215 PySequenceMethods *sq = Py_TYPE(self)->tp_as_sequence;
4216 if (sq && sq->sq_length) {
4217 Py_ssize_t n = (*sq->sq_length)(self);
4218 if (n < 0)
4219 return -1;
4220 i += n;
4221 }
4222 }
4223 return i;
Guido van Rossum5d815f32001-08-17 21:57:47 +00004224}
4225
4226static PyObject *
4227wrap_sq_item(PyObject *self, PyObject *args, void *wrapped)
4228{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004229 ssizeargfunc func = (ssizeargfunc)wrapped;
4230 PyObject *arg;
4231 Py_ssize_t i;
Guido van Rossum5d815f32001-08-17 21:57:47 +00004232
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004233 if (PyTuple_GET_SIZE(args) == 1) {
4234 arg = PyTuple_GET_ITEM(args, 0);
4235 i = getindex(self, arg);
4236 if (i == -1 && PyErr_Occurred())
4237 return NULL;
4238 return (*func)(self, i);
4239 }
4240 check_num_args(args, 1);
4241 assert(PyErr_Occurred());
4242 return NULL;
Guido van Rossum5d815f32001-08-17 21:57:47 +00004243}
4244
Tim Peters6d6c1a32001-08-02 04:15:00 +00004245static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00004246wrap_sq_setitem(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004247{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004248 ssizeobjargproc func = (ssizeobjargproc)wrapped;
4249 Py_ssize_t i;
4250 int res;
4251 PyObject *arg, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004252
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004253 if (!PyArg_UnpackTuple(args, "", 2, 2, &arg, &value))
4254 return NULL;
4255 i = getindex(self, arg);
4256 if (i == -1 && PyErr_Occurred())
4257 return NULL;
4258 res = (*func)(self, i, value);
4259 if (res == -1 && PyErr_Occurred())
4260 return NULL;
4261 Py_INCREF(Py_None);
4262 return Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004263}
4264
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004265static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00004266wrap_sq_delitem(PyObject *self, PyObject *args, void *wrapped)
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004267{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004268 ssizeobjargproc func = (ssizeobjargproc)wrapped;
4269 Py_ssize_t i;
4270 int res;
4271 PyObject *arg;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004272
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004273 if (!check_num_args(args, 1))
4274 return NULL;
4275 arg = PyTuple_GET_ITEM(args, 0);
4276 i = getindex(self, arg);
4277 if (i == -1 && PyErr_Occurred())
4278 return NULL;
4279 res = (*func)(self, i, NULL);
4280 if (res == -1 && PyErr_Occurred())
4281 return NULL;
4282 Py_INCREF(Py_None);
4283 return Py_None;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004284}
4285
Tim Peters6d6c1a32001-08-02 04:15:00 +00004286/* XXX objobjproc is a misnomer; should be objargpred */
4287static PyObject *
4288wrap_objobjproc(PyObject *self, PyObject *args, void *wrapped)
4289{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004290 objobjproc func = (objobjproc)wrapped;
4291 int res;
4292 PyObject *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004293
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004294 if (!check_num_args(args, 1))
4295 return NULL;
4296 value = PyTuple_GET_ITEM(args, 0);
4297 res = (*func)(self, value);
4298 if (res == -1 && PyErr_Occurred())
4299 return NULL;
4300 else
4301 return PyBool_FromLong(res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004302}
4303
Tim Peters6d6c1a32001-08-02 04:15:00 +00004304static PyObject *
4305wrap_objobjargproc(PyObject *self, PyObject *args, void *wrapped)
4306{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004307 objobjargproc func = (objobjargproc)wrapped;
4308 int res;
4309 PyObject *key, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004310
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004311 if (!PyArg_UnpackTuple(args, "", 2, 2, &key, &value))
4312 return NULL;
4313 res = (*func)(self, key, value);
4314 if (res == -1 && PyErr_Occurred())
4315 return NULL;
4316 Py_INCREF(Py_None);
4317 return Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004318}
4319
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004320static PyObject *
4321wrap_delitem(PyObject *self, PyObject *args, void *wrapped)
4322{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004323 objobjargproc func = (objobjargproc)wrapped;
4324 int res;
4325 PyObject *key;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004326
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004327 if (!check_num_args(args, 1))
4328 return NULL;
4329 key = PyTuple_GET_ITEM(args, 0);
4330 res = (*func)(self, key, NULL);
4331 if (res == -1 && PyErr_Occurred())
4332 return NULL;
4333 Py_INCREF(Py_None);
4334 return Py_None;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004335}
4336
Guido van Rossum4dcdb782003-04-14 21:46:03 +00004337/* Helper to check for object.__setattr__ or __delattr__ applied to a type.
Guido van Rossum52b27052003-04-15 20:05:10 +00004338 This is called the Carlo Verre hack after its discoverer. */
Guido van Rossum4dcdb782003-04-14 21:46:03 +00004339static int
4340hackcheck(PyObject *self, setattrofunc func, char *what)
4341{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004342 PyTypeObject *type = Py_TYPE(self);
4343 while (type && type->tp_flags & Py_TPFLAGS_HEAPTYPE)
4344 type = type->tp_base;
4345 /* If type is NULL now, this is a really weird type.
4346 In the spirit of backwards compatibility (?), just shut up. */
4347 if (type && type->tp_setattro != func) {
4348 PyErr_Format(PyExc_TypeError,
4349 "can't apply this %s to %s object",
4350 what,
4351 type->tp_name);
4352 return 0;
4353 }
4354 return 1;
Guido van Rossum4dcdb782003-04-14 21:46:03 +00004355}
4356
Tim Peters6d6c1a32001-08-02 04:15:00 +00004357static PyObject *
4358wrap_setattr(PyObject *self, PyObject *args, void *wrapped)
4359{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004360 setattrofunc func = (setattrofunc)wrapped;
4361 int res;
4362 PyObject *name, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004363
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004364 if (!PyArg_UnpackTuple(args, "", 2, 2, &name, &value))
4365 return NULL;
4366 if (!hackcheck(self, func, "__setattr__"))
4367 return NULL;
4368 res = (*func)(self, name, value);
4369 if (res < 0)
4370 return NULL;
4371 Py_INCREF(Py_None);
4372 return Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004373}
4374
4375static PyObject *
4376wrap_delattr(PyObject *self, PyObject *args, void *wrapped)
4377{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004378 setattrofunc func = (setattrofunc)wrapped;
4379 int res;
4380 PyObject *name;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004381
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004382 if (!check_num_args(args, 1))
4383 return NULL;
4384 name = PyTuple_GET_ITEM(args, 0);
4385 if (!hackcheck(self, func, "__delattr__"))
4386 return NULL;
4387 res = (*func)(self, name, NULL);
4388 if (res < 0)
4389 return NULL;
4390 Py_INCREF(Py_None);
4391 return Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004392}
4393
Tim Peters6d6c1a32001-08-02 04:15:00 +00004394static PyObject *
4395wrap_hashfunc(PyObject *self, PyObject *args, void *wrapped)
4396{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004397 hashfunc func = (hashfunc)wrapped;
Benjamin Peterson8035bc52010-10-23 16:20:50 +00004398 Py_hash_t res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004399
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004400 if (!check_num_args(args, 0))
4401 return NULL;
4402 res = (*func)(self);
4403 if (res == -1 && PyErr_Occurred())
4404 return NULL;
Benjamin Peterson8035bc52010-10-23 16:20:50 +00004405 return PyLong_FromSsize_t(res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004406}
4407
Tim Peters6d6c1a32001-08-02 04:15:00 +00004408static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00004409wrap_call(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004410{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004411 ternaryfunc func = (ternaryfunc)wrapped;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004412
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004413 return (*func)(self, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004414}
4415
Tim Peters6d6c1a32001-08-02 04:15:00 +00004416static PyObject *
4417wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op)
4418{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004419 richcmpfunc func = (richcmpfunc)wrapped;
4420 PyObject *other;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004421
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004422 if (!check_num_args(args, 1))
4423 return NULL;
4424 other = PyTuple_GET_ITEM(args, 0);
4425 return (*func)(self, other, op);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004426}
4427
4428#undef RICHCMP_WRAPPER
4429#define RICHCMP_WRAPPER(NAME, OP) \
4430static PyObject * \
4431richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \
4432{ \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004433 return wrap_richcmpfunc(self, args, wrapped, OP); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004434}
4435
Jack Jansen8e938b42001-08-08 15:29:49 +00004436RICHCMP_WRAPPER(lt, Py_LT)
4437RICHCMP_WRAPPER(le, Py_LE)
4438RICHCMP_WRAPPER(eq, Py_EQ)
4439RICHCMP_WRAPPER(ne, Py_NE)
4440RICHCMP_WRAPPER(gt, Py_GT)
4441RICHCMP_WRAPPER(ge, Py_GE)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004442
Tim Peters6d6c1a32001-08-02 04:15:00 +00004443static PyObject *
4444wrap_next(PyObject *self, PyObject *args, void *wrapped)
4445{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004446 unaryfunc func = (unaryfunc)wrapped;
4447 PyObject *res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004448
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004449 if (!check_num_args(args, 0))
4450 return NULL;
4451 res = (*func)(self);
4452 if (res == NULL && !PyErr_Occurred())
4453 PyErr_SetNone(PyExc_StopIteration);
4454 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004455}
4456
Tim Peters6d6c1a32001-08-02 04:15:00 +00004457static PyObject *
4458wrap_descr_get(PyObject *self, PyObject *args, void *wrapped)
4459{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004460 descrgetfunc func = (descrgetfunc)wrapped;
4461 PyObject *obj;
4462 PyObject *type = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004463
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004464 if (!PyArg_UnpackTuple(args, "", 1, 2, &obj, &type))
4465 return NULL;
4466 if (obj == Py_None)
4467 obj = NULL;
4468 if (type == Py_None)
4469 type = NULL;
4470 if (type == NULL &&obj == NULL) {
4471 PyErr_SetString(PyExc_TypeError,
4472 "__get__(None, None) is invalid");
4473 return NULL;
4474 }
4475 return (*func)(self, obj, type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004476}
4477
Tim Peters6d6c1a32001-08-02 04:15:00 +00004478static PyObject *
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004479wrap_descr_set(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004480{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004481 descrsetfunc func = (descrsetfunc)wrapped;
4482 PyObject *obj, *value;
4483 int ret;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004484
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004485 if (!PyArg_UnpackTuple(args, "", 2, 2, &obj, &value))
4486 return NULL;
4487 ret = (*func)(self, obj, value);
4488 if (ret < 0)
4489 return NULL;
4490 Py_INCREF(Py_None);
4491 return Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004492}
Guido van Rossum22b13872002-08-06 21:41:44 +00004493
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00004494static PyObject *
4495wrap_descr_delete(PyObject *self, PyObject *args, void *wrapped)
4496{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004497 descrsetfunc func = (descrsetfunc)wrapped;
4498 PyObject *obj;
4499 int ret;
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00004500
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004501 if (!check_num_args(args, 1))
4502 return NULL;
4503 obj = PyTuple_GET_ITEM(args, 0);
4504 ret = (*func)(self, obj, NULL);
4505 if (ret < 0)
4506 return NULL;
4507 Py_INCREF(Py_None);
4508 return Py_None;
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00004509}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004510
Tim Peters6d6c1a32001-08-02 04:15:00 +00004511static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00004512wrap_init(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004513{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004514 initproc func = (initproc)wrapped;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004515
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004516 if (func(self, args, kwds) < 0)
4517 return NULL;
4518 Py_INCREF(Py_None);
4519 return Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004520}
4521
Tim Peters6d6c1a32001-08-02 04:15:00 +00004522static PyObject *
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004523tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004524{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004525 PyTypeObject *type, *subtype, *staticbase;
4526 PyObject *arg0, *res;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004527
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004528 if (self == NULL || !PyType_Check(self))
4529 Py_FatalError("__new__() called with non-type 'self'");
4530 type = (PyTypeObject *)self;
4531 if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) {
4532 PyErr_Format(PyExc_TypeError,
4533 "%s.__new__(): not enough arguments",
4534 type->tp_name);
4535 return NULL;
4536 }
4537 arg0 = PyTuple_GET_ITEM(args, 0);
4538 if (!PyType_Check(arg0)) {
4539 PyErr_Format(PyExc_TypeError,
4540 "%s.__new__(X): X is not a type object (%s)",
4541 type->tp_name,
4542 Py_TYPE(arg0)->tp_name);
4543 return NULL;
4544 }
4545 subtype = (PyTypeObject *)arg0;
4546 if (!PyType_IsSubtype(subtype, type)) {
4547 PyErr_Format(PyExc_TypeError,
4548 "%s.__new__(%s): %s is not a subtype of %s",
4549 type->tp_name,
4550 subtype->tp_name,
4551 subtype->tp_name,
4552 type->tp_name);
4553 return NULL;
4554 }
Barry Warsaw60f01882001-08-22 19:24:42 +00004555
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004556 /* Check that the use doesn't do something silly and unsafe like
4557 object.__new__(dict). To do this, we check that the
4558 most derived base that's not a heap type is this type. */
4559 staticbase = subtype;
4560 while (staticbase && (staticbase->tp_flags & Py_TPFLAGS_HEAPTYPE))
4561 staticbase = staticbase->tp_base;
4562 /* If staticbase is NULL now, it is a really weird type.
4563 In the spirit of backwards compatibility (?), just shut up. */
4564 if (staticbase && staticbase->tp_new != type->tp_new) {
4565 PyErr_Format(PyExc_TypeError,
4566 "%s.__new__(%s) is not safe, use %s.__new__()",
4567 type->tp_name,
4568 subtype->tp_name,
4569 staticbase == NULL ? "?" : staticbase->tp_name);
4570 return NULL;
4571 }
Barry Warsaw60f01882001-08-22 19:24:42 +00004572
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004573 args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
4574 if (args == NULL)
4575 return NULL;
4576 res = type->tp_new(subtype, args, kwds);
4577 Py_DECREF(args);
4578 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004579}
4580
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004581static struct PyMethodDef tp_new_methoddef[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004582 {"__new__", (PyCFunction)tp_new_wrapper, METH_VARARGS|METH_KEYWORDS,
4583 PyDoc_STR("T.__new__(S, ...) -> "
4584 "a new object with type S, a subtype of T")},
4585 {0}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004586};
4587
4588static int
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004589add_tp_new_wrapper(PyTypeObject *type)
4590{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004591 PyObject *func;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004592
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004593 if (PyDict_GetItemString(type->tp_dict, "__new__") != NULL)
4594 return 0;
4595 func = PyCFunction_New(tp_new_methoddef, (PyObject *)type);
4596 if (func == NULL)
4597 return -1;
4598 if (PyDict_SetItemString(type->tp_dict, "__new__", func)) {
4599 Py_DECREF(func);
4600 return -1;
4601 }
4602 Py_DECREF(func);
4603 return 0;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004604}
4605
Guido van Rossumf040ede2001-08-07 16:40:56 +00004606/* Slot wrappers that call the corresponding __foo__ slot. See comments
4607 below at override_slots() for more explanation. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004608
Guido van Rossumdc91b992001-08-08 22:26:22 +00004609#define SLOT0(FUNCNAME, OPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004610static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004611FUNCNAME(PyObject *self) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004612{ \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004613 static PyObject *cache_str; \
4614 return call_method(self, OPSTR, &cache_str, "()"); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004615}
4616
Guido van Rossumdc91b992001-08-08 22:26:22 +00004617#define SLOT1(FUNCNAME, OPSTR, ARG1TYPE, ARGCODES) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004618static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004619FUNCNAME(PyObject *self, ARG1TYPE arg1) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004620{ \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004621 static PyObject *cache_str; \
4622 return call_method(self, OPSTR, &cache_str, "(" ARGCODES ")", arg1); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004623}
4624
Guido van Rossumcd118802003-01-06 22:57:47 +00004625/* Boolean helper for SLOT1BINFULL().
4626 right.__class__ is a nontrivial subclass of left.__class__. */
4627static int
4628method_is_overloaded(PyObject *left, PyObject *right, char *name)
4629{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004630 PyObject *a, *b;
4631 int ok;
Guido van Rossumcd118802003-01-06 22:57:47 +00004632
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004633 b = PyObject_GetAttrString((PyObject *)(Py_TYPE(right)), name);
4634 if (b == NULL) {
4635 PyErr_Clear();
4636 /* If right doesn't have it, it's not overloaded */
4637 return 0;
4638 }
Guido van Rossumcd118802003-01-06 22:57:47 +00004639
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004640 a = PyObject_GetAttrString((PyObject *)(Py_TYPE(left)), name);
4641 if (a == NULL) {
4642 PyErr_Clear();
4643 Py_DECREF(b);
4644 /* If right has it but left doesn't, it's overloaded */
4645 return 1;
4646 }
Guido van Rossumcd118802003-01-06 22:57:47 +00004647
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004648 ok = PyObject_RichCompareBool(a, b, Py_NE);
4649 Py_DECREF(a);
4650 Py_DECREF(b);
4651 if (ok < 0) {
4652 PyErr_Clear();
4653 return 0;
4654 }
Guido van Rossumcd118802003-01-06 22:57:47 +00004655
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004656 return ok;
Guido van Rossumcd118802003-01-06 22:57:47 +00004657}
4658
Guido van Rossumdc91b992001-08-08 22:26:22 +00004659
4660#define SLOT1BINFULL(FUNCNAME, TESTFUNC, SLOTNAME, OPSTR, ROPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004661static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004662FUNCNAME(PyObject *self, PyObject *other) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004663{ \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004664 static PyObject *cache_str, *rcache_str; \
4665 int do_other = Py_TYPE(self) != Py_TYPE(other) && \
4666 Py_TYPE(other)->tp_as_number != NULL && \
4667 Py_TYPE(other)->tp_as_number->SLOTNAME == TESTFUNC; \
4668 if (Py_TYPE(self)->tp_as_number != NULL && \
4669 Py_TYPE(self)->tp_as_number->SLOTNAME == TESTFUNC) { \
4670 PyObject *r; \
4671 if (do_other && \
4672 PyType_IsSubtype(Py_TYPE(other), Py_TYPE(self)) && \
4673 method_is_overloaded(self, other, ROPSTR)) { \
4674 r = call_maybe( \
4675 other, ROPSTR, &rcache_str, "(O)", self); \
4676 if (r != Py_NotImplemented) \
4677 return r; \
4678 Py_DECREF(r); \
4679 do_other = 0; \
4680 } \
4681 r = call_maybe( \
4682 self, OPSTR, &cache_str, "(O)", other); \
4683 if (r != Py_NotImplemented || \
4684 Py_TYPE(other) == Py_TYPE(self)) \
4685 return r; \
4686 Py_DECREF(r); \
4687 } \
4688 if (do_other) { \
4689 return call_maybe( \
4690 other, ROPSTR, &rcache_str, "(O)", self); \
4691 } \
4692 Py_INCREF(Py_NotImplemented); \
4693 return Py_NotImplemented; \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004694}
4695
4696#define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004697 SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR)
Guido van Rossumdc91b992001-08-08 22:26:22 +00004698
4699#define SLOT2(FUNCNAME, OPSTR, ARG1TYPE, ARG2TYPE, ARGCODES) \
4700static PyObject * \
4701FUNCNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \
4702{ \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004703 static PyObject *cache_str; \
4704 return call_method(self, OPSTR, &cache_str, \
4705 "(" ARGCODES ")", arg1, arg2); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004706}
4707
Martin v. Löwis18e16552006-02-15 17:27:45 +00004708static Py_ssize_t
Tim Peters6d6c1a32001-08-02 04:15:00 +00004709slot_sq_length(PyObject *self)
4710{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004711 static PyObject *len_str;
4712 PyObject *res = call_method(self, "__len__", &len_str, "()");
4713 Py_ssize_t len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004714
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004715 if (res == NULL)
4716 return -1;
4717 len = PyNumber_AsSsize_t(res, PyExc_OverflowError);
4718 Py_DECREF(res);
4719 if (len < 0) {
4720 if (!PyErr_Occurred())
4721 PyErr_SetString(PyExc_ValueError,
4722 "__len__() should return >= 0");
4723 return -1;
4724 }
4725 return len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004726}
4727
Guido van Rossumf4593e02001-10-03 12:09:30 +00004728/* Super-optimized version of slot_sq_item.
4729 Other slots could do the same... */
4730static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00004731slot_sq_item(PyObject *self, Py_ssize_t i)
Guido van Rossumf4593e02001-10-03 12:09:30 +00004732{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004733 static PyObject *getitem_str;
4734 PyObject *func, *args = NULL, *ival = NULL, *retval = NULL;
4735 descrgetfunc f;
Guido van Rossumf4593e02001-10-03 12:09:30 +00004736
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004737 if (getitem_str == NULL) {
4738 getitem_str = PyUnicode_InternFromString("__getitem__");
4739 if (getitem_str == NULL)
4740 return NULL;
4741 }
4742 func = _PyType_Lookup(Py_TYPE(self), getitem_str);
4743 if (func != NULL) {
4744 if ((f = Py_TYPE(func)->tp_descr_get) == NULL)
4745 Py_INCREF(func);
4746 else {
4747 func = f(func, self, (PyObject *)(Py_TYPE(self)));
4748 if (func == NULL) {
4749 return NULL;
4750 }
4751 }
4752 ival = PyLong_FromSsize_t(i);
4753 if (ival != NULL) {
4754 args = PyTuple_New(1);
4755 if (args != NULL) {
4756 PyTuple_SET_ITEM(args, 0, ival);
4757 retval = PyObject_Call(func, args, NULL);
4758 Py_XDECREF(args);
4759 Py_XDECREF(func);
4760 return retval;
4761 }
4762 }
4763 }
4764 else {
4765 PyErr_SetObject(PyExc_AttributeError, getitem_str);
4766 }
4767 Py_XDECREF(args);
4768 Py_XDECREF(ival);
4769 Py_XDECREF(func);
4770 return NULL;
Guido van Rossumf4593e02001-10-03 12:09:30 +00004771}
4772
Tim Peters6d6c1a32001-08-02 04:15:00 +00004773static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00004774slot_sq_ass_item(PyObject *self, Py_ssize_t index, PyObject *value)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004775{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004776 PyObject *res;
4777 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004778
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004779 if (value == NULL)
4780 res = call_method(self, "__delitem__", &delitem_str,
4781 "(n)", index);
4782 else
4783 res = call_method(self, "__setitem__", &setitem_str,
4784 "(nO)", index, value);
4785 if (res == NULL)
4786 return -1;
4787 Py_DECREF(res);
4788 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004789}
4790
4791static int
Tim Peters6d6c1a32001-08-02 04:15:00 +00004792slot_sq_contains(PyObject *self, PyObject *value)
4793{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004794 PyObject *func, *res, *args;
4795 int result = -1;
Tim Petersbf9b2442003-03-23 05:35:36 +00004796
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004797 static PyObject *contains_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004798
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004799 func = lookup_maybe(self, "__contains__", &contains_str);
4800 if (func != NULL) {
4801 args = PyTuple_Pack(1, value);
4802 if (args == NULL)
4803 res = NULL;
4804 else {
4805 res = PyObject_Call(func, args, NULL);
4806 Py_DECREF(args);
4807 }
4808 Py_DECREF(func);
4809 if (res != NULL) {
4810 result = PyObject_IsTrue(res);
4811 Py_DECREF(res);
4812 }
4813 }
4814 else if (! PyErr_Occurred()) {
4815 /* Possible results: -1 and 1 */
4816 result = (int)_PySequence_IterSearch(self, value,
4817 PY_ITERSEARCH_CONTAINS);
4818 }
4819 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004820}
4821
Tim Peters6d6c1a32001-08-02 04:15:00 +00004822#define slot_mp_length slot_sq_length
4823
Guido van Rossumdc91b992001-08-08 22:26:22 +00004824SLOT1(slot_mp_subscript, "__getitem__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004825
4826static int
4827slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value)
4828{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004829 PyObject *res;
4830 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004831
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004832 if (value == NULL)
4833 res = call_method(self, "__delitem__", &delitem_str,
4834 "(O)", key);
4835 else
4836 res = call_method(self, "__setitem__", &setitem_str,
4837 "(OO)", key, value);
4838 if (res == NULL)
4839 return -1;
4840 Py_DECREF(res);
4841 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004842}
4843
Guido van Rossumdc91b992001-08-08 22:26:22 +00004844SLOT1BIN(slot_nb_add, nb_add, "__add__", "__radd__")
4845SLOT1BIN(slot_nb_subtract, nb_subtract, "__sub__", "__rsub__")
4846SLOT1BIN(slot_nb_multiply, nb_multiply, "__mul__", "__rmul__")
Guido van Rossumdc91b992001-08-08 22:26:22 +00004847SLOT1BIN(slot_nb_remainder, nb_remainder, "__mod__", "__rmod__")
4848SLOT1BIN(slot_nb_divmod, nb_divmod, "__divmod__", "__rdivmod__")
4849
Jeremy Hylton938ace62002-07-17 16:30:39 +00004850static PyObject *slot_nb_power(PyObject *, PyObject *, PyObject *);
Guido van Rossumdc91b992001-08-08 22:26:22 +00004851
4852SLOT1BINFULL(slot_nb_power_binary, slot_nb_power,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004853 nb_power, "__pow__", "__rpow__")
Guido van Rossumdc91b992001-08-08 22:26:22 +00004854
4855static PyObject *
4856slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus)
4857{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004858 static PyObject *pow_str;
Guido van Rossum2730b132001-08-28 18:22:14 +00004859
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004860 if (modulus == Py_None)
4861 return slot_nb_power_binary(self, other);
4862 /* Three-arg power doesn't use __rpow__. But ternary_op
4863 can call this when the second argument's type uses
4864 slot_nb_power, so check before calling self.__pow__. */
4865 if (Py_TYPE(self)->tp_as_number != NULL &&
4866 Py_TYPE(self)->tp_as_number->nb_power == slot_nb_power) {
4867 return call_method(self, "__pow__", &pow_str,
4868 "(OO)", other, modulus);
4869 }
4870 Py_INCREF(Py_NotImplemented);
4871 return Py_NotImplemented;
Guido van Rossumdc91b992001-08-08 22:26:22 +00004872}
4873
4874SLOT0(slot_nb_negative, "__neg__")
4875SLOT0(slot_nb_positive, "__pos__")
4876SLOT0(slot_nb_absolute, "__abs__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004877
4878static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00004879slot_nb_bool(PyObject *self)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004880{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004881 PyObject *func, *args;
4882 static PyObject *bool_str, *len_str;
4883 int result = -1;
4884 int using_len = 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004885
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004886 func = lookup_maybe(self, "__bool__", &bool_str);
4887 if (func == NULL) {
4888 if (PyErr_Occurred())
4889 return -1;
4890 func = lookup_maybe(self, "__len__", &len_str);
4891 if (func == NULL)
4892 return PyErr_Occurred() ? -1 : 1;
4893 using_len = 1;
4894 }
4895 args = PyTuple_New(0);
4896 if (args != NULL) {
4897 PyObject *temp = PyObject_Call(func, args, NULL);
4898 Py_DECREF(args);
4899 if (temp != NULL) {
4900 if (using_len) {
4901 /* enforced by slot_nb_len */
4902 result = PyObject_IsTrue(temp);
4903 }
4904 else if (PyBool_Check(temp)) {
4905 result = PyObject_IsTrue(temp);
4906 }
4907 else {
4908 PyErr_Format(PyExc_TypeError,
4909 "__bool__ should return "
4910 "bool, returned %s",
4911 Py_TYPE(temp)->tp_name);
4912 result = -1;
4913 }
4914 Py_DECREF(temp);
4915 }
4916 }
4917 Py_DECREF(func);
4918 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004919}
4920
Guido van Rossum38fff8c2006-03-07 18:50:55 +00004921
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00004922static PyObject *
Guido van Rossum38fff8c2006-03-07 18:50:55 +00004923slot_nb_index(PyObject *self)
4924{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004925 static PyObject *index_str;
4926 return call_method(self, "__index__", &index_str, "()");
Guido van Rossum38fff8c2006-03-07 18:50:55 +00004927}
4928
4929
Guido van Rossumdc91b992001-08-08 22:26:22 +00004930SLOT0(slot_nb_invert, "__invert__")
4931SLOT1BIN(slot_nb_lshift, nb_lshift, "__lshift__", "__rlshift__")
4932SLOT1BIN(slot_nb_rshift, nb_rshift, "__rshift__", "__rrshift__")
4933SLOT1BIN(slot_nb_and, nb_and, "__and__", "__rand__")
4934SLOT1BIN(slot_nb_xor, nb_xor, "__xor__", "__rxor__")
4935SLOT1BIN(slot_nb_or, nb_or, "__or__", "__ror__")
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004936
Guido van Rossumdc91b992001-08-08 22:26:22 +00004937SLOT0(slot_nb_int, "__int__")
Guido van Rossumdc91b992001-08-08 22:26:22 +00004938SLOT0(slot_nb_float, "__float__")
Guido van Rossumdc91b992001-08-08 22:26:22 +00004939SLOT1(slot_nb_inplace_add, "__iadd__", PyObject *, "O")
4940SLOT1(slot_nb_inplace_subtract, "__isub__", PyObject *, "O")
4941SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *, "O")
Guido van Rossumdc91b992001-08-08 22:26:22 +00004942SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *, "O")
Thomas Wouterscf297e42007-02-23 15:07:44 +00004943/* Can't use SLOT1 here, because nb_inplace_power is ternary */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004944static PyObject *
4945slot_nb_inplace_power(PyObject *self, PyObject * arg1, PyObject *arg2)
4946{
4947 static PyObject *cache_str;
4948 return call_method(self, "__ipow__", &cache_str, "(" "O" ")", arg1);
Thomas Wouterscf297e42007-02-23 15:07:44 +00004949}
Guido van Rossumdc91b992001-08-08 22:26:22 +00004950SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *, "O")
4951SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *, "O")
4952SLOT1(slot_nb_inplace_and, "__iand__", PyObject *, "O")
4953SLOT1(slot_nb_inplace_xor, "__ixor__", PyObject *, "O")
4954SLOT1(slot_nb_inplace_or, "__ior__", PyObject *, "O")
4955SLOT1BIN(slot_nb_floor_divide, nb_floor_divide,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004956 "__floordiv__", "__rfloordiv__")
Guido van Rossumdc91b992001-08-08 22:26:22 +00004957SLOT1BIN(slot_nb_true_divide, nb_true_divide, "__truediv__", "__rtruediv__")
4958SLOT1(slot_nb_inplace_floor_divide, "__ifloordiv__", PyObject *, "O")
4959SLOT1(slot_nb_inplace_true_divide, "__itruediv__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004960
Guido van Rossumb8f63662001-08-15 23:57:02 +00004961static PyObject *
4962slot_tp_repr(PyObject *self)
4963{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004964 PyObject *func, *res;
4965 static PyObject *repr_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004966
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004967 func = lookup_method(self, "__repr__", &repr_str);
4968 if (func != NULL) {
4969 res = PyEval_CallObject(func, NULL);
4970 Py_DECREF(func);
4971 return res;
4972 }
4973 PyErr_Clear();
4974 return PyUnicode_FromFormat("<%s object at %p>",
4975 Py_TYPE(self)->tp_name, self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004976}
4977
4978static PyObject *
4979slot_tp_str(PyObject *self)
4980{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004981 PyObject *func, *res;
4982 static PyObject *str_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004983
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004984 func = lookup_method(self, "__str__", &str_str);
4985 if (func != NULL) {
4986 res = PyEval_CallObject(func, NULL);
4987 Py_DECREF(func);
4988 return res;
4989 }
4990 else {
4991 PyObject *ress;
4992 PyErr_Clear();
4993 res = slot_tp_repr(self);
4994 if (!res)
4995 return NULL;
Victor Stinnerf3fd7332011-03-02 01:03:11 +00004996 ress = _PyUnicode_AsDefaultEncodedString(res);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004997 Py_DECREF(res);
4998 return ress;
4999 }
Guido van Rossumb8f63662001-08-15 23:57:02 +00005000}
Tim Peters6d6c1a32001-08-02 04:15:00 +00005001
Benjamin Peterson8f67d082010-10-17 20:54:53 +00005002static Py_hash_t
Tim Peters6d6c1a32001-08-02 04:15:00 +00005003slot_tp_hash(PyObject *self)
5004{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005005 PyObject *func, *res;
5006 static PyObject *hash_str;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00005007 Py_ssize_t h;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005008
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005009 func = lookup_method(self, "__hash__", &hash_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005010
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005011 if (func == Py_None) {
5012 Py_DECREF(func);
5013 func = NULL;
5014 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +00005015
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005016 if (func == NULL) {
5017 return PyObject_HashNotImplemented(self);
5018 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +00005019
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005020 res = PyEval_CallObject(func, NULL);
5021 Py_DECREF(func);
5022 if (res == NULL)
5023 return -1;
Mark Dickinsondc787d22010-05-23 13:33:13 +00005024
5025 if (!PyLong_Check(res)) {
5026 PyErr_SetString(PyExc_TypeError,
5027 "__hash__ method should return an integer");
5028 return -1;
5029 }
Benjamin Peterson8f67d082010-10-17 20:54:53 +00005030 /* Transform the PyLong `res` to a Py_hash_t `h`. For an existing
5031 hashable Python object x, hash(x) will always lie within the range of
5032 Py_hash_t. Therefore our transformation must preserve values that
5033 already lie within this range, to ensure that if x.__hash__() returns
5034 hash(y) then hash(x) == hash(y). */
5035 h = PyLong_AsSsize_t(res);
5036 if (h == -1 && PyErr_Occurred()) {
5037 /* res was not within the range of a Py_hash_t, so we're free to
Mark Dickinsondc787d22010-05-23 13:33:13 +00005038 use any sufficiently bit-mixing transformation;
5039 long.__hash__ will do nicely. */
Benjamin Peterson8f67d082010-10-17 20:54:53 +00005040 PyErr_Clear();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005041 h = PyLong_Type.tp_hash(res);
Benjamin Peterson8f67d082010-10-17 20:54:53 +00005042 }
Benjamin Petersone7dfeeb2010-10-17 21:27:01 +00005043 /* -1 is reserved for errors. */
5044 if (h == -1)
5045 h = -2;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005046 Py_DECREF(res);
Mark Dickinsondc787d22010-05-23 13:33:13 +00005047 return h;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005048}
5049
5050static PyObject *
5051slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds)
5052{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005053 static PyObject *call_str;
5054 PyObject *meth = lookup_method(self, "__call__", &call_str);
5055 PyObject *res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005056
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005057 if (meth == NULL)
5058 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005059
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005060 res = PyObject_Call(meth, args, kwds);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005061
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005062 Py_DECREF(meth);
5063 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005064}
5065
Guido van Rossum14a6f832001-10-17 13:59:09 +00005066/* There are two slot dispatch functions for tp_getattro.
5067
5068 - slot_tp_getattro() is used when __getattribute__ is overridden
5069 but no __getattr__ hook is present;
5070
5071 - slot_tp_getattr_hook() is used when a __getattr__ hook is present.
5072
Guido van Rossumc334df52002-04-04 23:44:47 +00005073 The code in update_one_slot() always installs slot_tp_getattr_hook(); this
5074 detects the absence of __getattr__ and then installs the simpler slot if
5075 necessary. */
Guido van Rossum14a6f832001-10-17 13:59:09 +00005076
Tim Peters6d6c1a32001-08-02 04:15:00 +00005077static PyObject *
5078slot_tp_getattro(PyObject *self, PyObject *name)
5079{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005080 static PyObject *getattribute_str = NULL;
5081 return call_method(self, "__getattribute__", &getattribute_str,
5082 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005083}
5084
Guido van Rossum19c1cd52001-09-21 21:24:49 +00005085static PyObject *
Benjamin Peterson9262b842008-11-17 22:45:50 +00005086call_attribute(PyObject *self, PyObject *attr, PyObject *name)
5087{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005088 PyObject *res, *descr = NULL;
5089 descrgetfunc f = Py_TYPE(attr)->tp_descr_get;
Benjamin Peterson9262b842008-11-17 22:45:50 +00005090
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005091 if (f != NULL) {
5092 descr = f(attr, self, (PyObject *)(Py_TYPE(self)));
5093 if (descr == NULL)
5094 return NULL;
5095 else
5096 attr = descr;
5097 }
5098 res = PyObject_CallFunctionObjArgs(attr, name, NULL);
5099 Py_XDECREF(descr);
5100 return res;
Benjamin Peterson9262b842008-11-17 22:45:50 +00005101}
5102
5103static PyObject *
Guido van Rossum19c1cd52001-09-21 21:24:49 +00005104slot_tp_getattr_hook(PyObject *self, PyObject *name)
5105{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005106 PyTypeObject *tp = Py_TYPE(self);
5107 PyObject *getattr, *getattribute, *res;
5108 static PyObject *getattribute_str = NULL;
5109 static PyObject *getattr_str = NULL;
Guido van Rossum19c1cd52001-09-21 21:24:49 +00005110
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005111 if (getattr_str == NULL) {
5112 getattr_str = PyUnicode_InternFromString("__getattr__");
5113 if (getattr_str == NULL)
5114 return NULL;
5115 }
5116 if (getattribute_str == NULL) {
5117 getattribute_str =
5118 PyUnicode_InternFromString("__getattribute__");
5119 if (getattribute_str == NULL)
5120 return NULL;
5121 }
5122 /* speed hack: we could use lookup_maybe, but that would resolve the
5123 method fully for each attribute lookup for classes with
5124 __getattr__, even when the attribute is present. So we use
5125 _PyType_Lookup and create the method only when needed, with
5126 call_attribute. */
5127 getattr = _PyType_Lookup(tp, getattr_str);
5128 if (getattr == NULL) {
5129 /* No __getattr__ hook: use a simpler dispatcher */
5130 tp->tp_getattro = slot_tp_getattro;
5131 return slot_tp_getattro(self, name);
5132 }
5133 Py_INCREF(getattr);
5134 /* speed hack: we could use lookup_maybe, but that would resolve the
5135 method fully for each attribute lookup for classes with
5136 __getattr__, even when self has the default __getattribute__
5137 method. So we use _PyType_Lookup and create the method only when
5138 needed, with call_attribute. */
5139 getattribute = _PyType_Lookup(tp, getattribute_str);
5140 if (getattribute == NULL ||
5141 (Py_TYPE(getattribute) == &PyWrapperDescr_Type &&
5142 ((PyWrapperDescrObject *)getattribute)->d_wrapped ==
5143 (void *)PyObject_GenericGetAttr))
5144 res = PyObject_GenericGetAttr(self, name);
5145 else {
5146 Py_INCREF(getattribute);
5147 res = call_attribute(self, getattribute, name);
5148 Py_DECREF(getattribute);
5149 }
5150 if (res == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) {
5151 PyErr_Clear();
5152 res = call_attribute(self, getattr, name);
5153 }
5154 Py_DECREF(getattr);
5155 return res;
Guido van Rossum19c1cd52001-09-21 21:24:49 +00005156}
5157
Tim Peters6d6c1a32001-08-02 04:15:00 +00005158static int
5159slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value)
5160{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005161 PyObject *res;
5162 static PyObject *delattr_str, *setattr_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005163
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005164 if (value == NULL)
5165 res = call_method(self, "__delattr__", &delattr_str,
5166 "(O)", name);
5167 else
5168 res = call_method(self, "__setattr__", &setattr_str,
5169 "(OO)", name, value);
5170 if (res == NULL)
5171 return -1;
5172 Py_DECREF(res);
5173 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005174}
5175
Guido van Rossumf5243f02008-01-01 04:06:48 +00005176static char *name_op[] = {
5177 "__lt__",
5178 "__le__",
5179 "__eq__",
5180 "__ne__",
5181 "__gt__",
5182 "__ge__",
5183};
5184
Tim Peters6d6c1a32001-08-02 04:15:00 +00005185static PyObject *
Mark Dickinson6f1d0492009-11-15 13:58:49 +00005186slot_tp_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005187{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005188 PyObject *func, *args, *res;
5189 static PyObject *op_str[6];
Tim Peters6d6c1a32001-08-02 04:15:00 +00005190
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005191 func = lookup_method(self, name_op[op], &op_str[op]);
5192 if (func == NULL) {
5193 PyErr_Clear();
5194 Py_INCREF(Py_NotImplemented);
5195 return Py_NotImplemented;
5196 }
5197 args = PyTuple_Pack(1, other);
5198 if (args == NULL)
5199 res = NULL;
5200 else {
5201 res = PyObject_Call(func, args, NULL);
5202 Py_DECREF(args);
5203 }
5204 Py_DECREF(func);
5205 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005206}
5207
Guido van Rossumb8f63662001-08-15 23:57:02 +00005208static PyObject *
Guido van Rossumb8f63662001-08-15 23:57:02 +00005209slot_tp_iter(PyObject *self)
5210{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005211 PyObject *func, *res;
5212 static PyObject *iter_str, *getitem_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00005213
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005214 func = lookup_method(self, "__iter__", &iter_str);
5215 if (func != NULL) {
5216 PyObject *args;
5217 args = res = PyTuple_New(0);
5218 if (args != NULL) {
5219 res = PyObject_Call(func, args, NULL);
5220 Py_DECREF(args);
5221 }
5222 Py_DECREF(func);
5223 return res;
5224 }
5225 PyErr_Clear();
5226 func = lookup_method(self, "__getitem__", &getitem_str);
5227 if (func == NULL) {
5228 PyErr_Format(PyExc_TypeError,
5229 "'%.200s' object is not iterable",
5230 Py_TYPE(self)->tp_name);
5231 return NULL;
5232 }
5233 Py_DECREF(func);
5234 return PySeqIter_New(self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005235}
Tim Peters6d6c1a32001-08-02 04:15:00 +00005236
5237static PyObject *
5238slot_tp_iternext(PyObject *self)
5239{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005240 static PyObject *next_str;
5241 return call_method(self, "__next__", &next_str, "()");
Tim Peters6d6c1a32001-08-02 04:15:00 +00005242}
5243
Guido van Rossum1a493502001-08-17 16:47:50 +00005244static PyObject *
5245slot_tp_descr_get(PyObject *self, PyObject *obj, PyObject *type)
5246{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005247 PyTypeObject *tp = Py_TYPE(self);
5248 PyObject *get;
5249 static PyObject *get_str = NULL;
Guido van Rossum1a493502001-08-17 16:47:50 +00005250
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005251 if (get_str == NULL) {
5252 get_str = PyUnicode_InternFromString("__get__");
5253 if (get_str == NULL)
5254 return NULL;
5255 }
5256 get = _PyType_Lookup(tp, get_str);
5257 if (get == NULL) {
5258 /* Avoid further slowdowns */
5259 if (tp->tp_descr_get == slot_tp_descr_get)
5260 tp->tp_descr_get = NULL;
5261 Py_INCREF(self);
5262 return self;
5263 }
5264 if (obj == NULL)
5265 obj = Py_None;
5266 if (type == NULL)
5267 type = Py_None;
5268 return PyObject_CallFunctionObjArgs(get, self, obj, type, NULL);
Guido van Rossum1a493502001-08-17 16:47:50 +00005269}
Tim Peters6d6c1a32001-08-02 04:15:00 +00005270
5271static int
5272slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value)
5273{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005274 PyObject *res;
5275 static PyObject *del_str, *set_str;
Guido van Rossum2c252392001-08-24 10:13:31 +00005276
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005277 if (value == NULL)
5278 res = call_method(self, "__delete__", &del_str,
5279 "(O)", target);
5280 else
5281 res = call_method(self, "__set__", &set_str,
5282 "(OO)", target, value);
5283 if (res == NULL)
5284 return -1;
5285 Py_DECREF(res);
5286 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005287}
5288
5289static int
5290slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds)
5291{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005292 static PyObject *init_str;
5293 PyObject *meth = lookup_method(self, "__init__", &init_str);
5294 PyObject *res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005295
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005296 if (meth == NULL)
5297 return -1;
5298 res = PyObject_Call(meth, args, kwds);
5299 Py_DECREF(meth);
5300 if (res == NULL)
5301 return -1;
5302 if (res != Py_None) {
5303 PyErr_Format(PyExc_TypeError,
5304 "__init__() should return None, not '%.200s'",
5305 Py_TYPE(res)->tp_name);
5306 Py_DECREF(res);
5307 return -1;
5308 }
5309 Py_DECREF(res);
5310 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005311}
5312
5313static PyObject *
5314slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
5315{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005316 static PyObject *new_str;
5317 PyObject *func;
5318 PyObject *newargs, *x;
5319 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005320
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005321 if (new_str == NULL) {
5322 new_str = PyUnicode_InternFromString("__new__");
5323 if (new_str == NULL)
5324 return NULL;
5325 }
5326 func = PyObject_GetAttr((PyObject *)type, new_str);
5327 if (func == NULL)
5328 return NULL;
5329 assert(PyTuple_Check(args));
5330 n = PyTuple_GET_SIZE(args);
5331 newargs = PyTuple_New(n+1);
5332 if (newargs == NULL)
5333 return NULL;
5334 Py_INCREF(type);
5335 PyTuple_SET_ITEM(newargs, 0, (PyObject *)type);
5336 for (i = 0; i < n; i++) {
5337 x = PyTuple_GET_ITEM(args, i);
5338 Py_INCREF(x);
5339 PyTuple_SET_ITEM(newargs, i+1, x);
5340 }
5341 x = PyObject_Call(func, newargs, kwds);
5342 Py_DECREF(newargs);
5343 Py_DECREF(func);
5344 return x;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005345}
5346
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005347static void
5348slot_tp_del(PyObject *self)
5349{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005350 static PyObject *del_str = NULL;
5351 PyObject *del, *res;
5352 PyObject *error_type, *error_value, *error_traceback;
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005353
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005354 /* Temporarily resurrect the object. */
5355 assert(self->ob_refcnt == 0);
5356 self->ob_refcnt = 1;
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005357
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005358 /* Save the current exception, if any. */
5359 PyErr_Fetch(&error_type, &error_value, &error_traceback);
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005360
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005361 /* Execute __del__ method, if any. */
5362 del = lookup_maybe(self, "__del__", &del_str);
5363 if (del != NULL) {
5364 res = PyEval_CallObject(del, NULL);
5365 if (res == NULL)
5366 PyErr_WriteUnraisable(del);
5367 else
5368 Py_DECREF(res);
5369 Py_DECREF(del);
5370 }
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005371
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005372 /* Restore the saved exception. */
5373 PyErr_Restore(error_type, error_value, error_traceback);
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005374
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005375 /* Undo the temporary resurrection; can't use DECREF here, it would
5376 * cause a recursive call.
5377 */
5378 assert(self->ob_refcnt > 0);
5379 if (--self->ob_refcnt == 0)
5380 return; /* this is the normal path out */
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005381
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005382 /* __del__ resurrected it! Make it look like the original Py_DECREF
5383 * never happened.
5384 */
5385 {
5386 Py_ssize_t refcnt = self->ob_refcnt;
5387 _Py_NewReference(self);
5388 self->ob_refcnt = refcnt;
5389 }
5390 assert(!PyType_IS_GC(Py_TYPE(self)) ||
5391 _Py_AS_GC(self)->gc.gc_refs != _PyGC_REFS_UNTRACKED);
5392 /* If Py_REF_DEBUG, _Py_NewReference bumped _Py_RefTotal, so
5393 * we need to undo that. */
5394 _Py_DEC_REFTOTAL;
5395 /* If Py_TRACE_REFS, _Py_NewReference re-added self to the object
5396 * chain, so no more to do there.
5397 * If COUNT_ALLOCS, the original decref bumped tp_frees, and
5398 * _Py_NewReference bumped tp_allocs: both of those need to be
5399 * undone.
5400 */
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005401#ifdef COUNT_ALLOCS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005402 --Py_TYPE(self)->tp_frees;
5403 --Py_TYPE(self)->tp_allocs;
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005404#endif
5405}
5406
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005407
5408/* Table mapping __foo__ names to tp_foo offsets and slot_tp_foo wrapper
Tim Petersbf9b2442003-03-23 05:35:36 +00005409 functions. The offsets here are relative to the 'PyHeapTypeObject'
Guido van Rossume5c691a2003-03-07 15:13:17 +00005410 structure, which incorporates the additional structures used for numbers,
5411 sequences and mappings.
5412 Note that multiple names may map to the same slot (e.g. __eq__,
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005413 __ne__ etc. all map to tp_richcompare) and one name may map to multiple
Guido van Rossumc334df52002-04-04 23:44:47 +00005414 slots (e.g. __str__ affects tp_str as well as tp_repr). The table is
5415 terminated with an all-zero entry. (This table is further initialized and
5416 sorted in init_slotdefs() below.) */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005417
Guido van Rossum6d204072001-10-21 00:44:31 +00005418typedef struct wrapperbase slotdef;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005419
5420#undef TPSLOT
Guido van Rossumc8e56452001-10-22 00:43:43 +00005421#undef FLSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005422#undef ETSLOT
5423#undef SQSLOT
5424#undef MPSLOT
5425#undef NBSLOT
Guido van Rossum6d204072001-10-21 00:44:31 +00005426#undef UNSLOT
5427#undef IBSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005428#undef BINSLOT
5429#undef RBINSLOT
5430
Guido van Rossum6d204072001-10-21 00:44:31 +00005431#define TPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005432 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
5433 PyDoc_STR(DOC)}
Guido van Rossumc8e56452001-10-22 00:43:43 +00005434#define FLSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC, FLAGS) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005435 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
5436 PyDoc_STR(DOC), FLAGS}
Guido van Rossum6d204072001-10-21 00:44:31 +00005437#define ETSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005438 {NAME, offsetof(PyHeapTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
5439 PyDoc_STR(DOC)}
Guido van Rossum6d204072001-10-21 00:44:31 +00005440#define SQSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005441 ETSLOT(NAME, as_sequence.SLOT, FUNCTION, WRAPPER, DOC)
Guido van Rossum6d204072001-10-21 00:44:31 +00005442#define MPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005443 ETSLOT(NAME, as_mapping.SLOT, FUNCTION, WRAPPER, DOC)
Guido van Rossum6d204072001-10-21 00:44:31 +00005444#define NBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005445 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, DOC)
Guido van Rossum6d204072001-10-21 00:44:31 +00005446#define UNSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005447 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
5448 "x." NAME "() <==> " DOC)
Guido van Rossum6d204072001-10-21 00:44:31 +00005449#define IBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005450 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
5451 "x." NAME "(y) <==> x" DOC "y")
Guido van Rossum6d204072001-10-21 00:44:31 +00005452#define BINSLOT(NAME, SLOT, FUNCTION, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005453 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
5454 "x." NAME "(y) <==> x" DOC "y")
Guido van Rossum6d204072001-10-21 00:44:31 +00005455#define RBINSLOT(NAME, SLOT, FUNCTION, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005456 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
5457 "x." NAME "(y) <==> y" DOC "x")
Anthony Baxter56616992005-06-03 14:12:21 +00005458#define BINSLOTNOTINFIX(NAME, SLOT, FUNCTION, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005459 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
5460 "x." NAME "(y) <==> " DOC)
Anthony Baxter56616992005-06-03 14:12:21 +00005461#define RBINSLOTNOTINFIX(NAME, SLOT, FUNCTION, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005462 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
5463 "x." NAME "(y) <==> " DOC)
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005464
5465static slotdef slotdefs[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005466 SQSLOT("__len__", sq_length, slot_sq_length, wrap_lenfunc,
5467 "x.__len__() <==> len(x)"),
5468 /* Heap types defining __add__/__mul__ have sq_concat/sq_repeat == NULL.
5469 The logic in abstract.c always falls back to nb_add/nb_multiply in
5470 this case. Defining both the nb_* and the sq_* slots to call the
5471 user-defined methods has unexpected side-effects, as shown by
5472 test_descr.notimplemented() */
5473 SQSLOT("__add__", sq_concat, NULL, wrap_binaryfunc,
5474 "x.__add__(y) <==> x+y"),
5475 SQSLOT("__mul__", sq_repeat, NULL, wrap_indexargfunc,
5476 "x.__mul__(n) <==> x*n"),
5477 SQSLOT("__rmul__", sq_repeat, NULL, wrap_indexargfunc,
5478 "x.__rmul__(n) <==> n*x"),
5479 SQSLOT("__getitem__", sq_item, slot_sq_item, wrap_sq_item,
5480 "x.__getitem__(y) <==> x[y]"),
5481 SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_setitem,
5482 "x.__setitem__(i, y) <==> x[i]=y"),
5483 SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_delitem,
5484 "x.__delitem__(y) <==> del x[y]"),
5485 SQSLOT("__contains__", sq_contains, slot_sq_contains, wrap_objobjproc,
5486 "x.__contains__(y) <==> y in x"),
5487 SQSLOT("__iadd__", sq_inplace_concat, NULL,
5488 wrap_binaryfunc, "x.__iadd__(y) <==> x+=y"),
5489 SQSLOT("__imul__", sq_inplace_repeat, NULL,
5490 wrap_indexargfunc, "x.__imul__(y) <==> x*=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005491
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005492 MPSLOT("__len__", mp_length, slot_mp_length, wrap_lenfunc,
5493 "x.__len__() <==> len(x)"),
5494 MPSLOT("__getitem__", mp_subscript, slot_mp_subscript,
5495 wrap_binaryfunc,
5496 "x.__getitem__(y) <==> x[y]"),
5497 MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript,
5498 wrap_objobjargproc,
5499 "x.__setitem__(i, y) <==> x[i]=y"),
5500 MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript,
5501 wrap_delitem,
5502 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005503
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005504 BINSLOT("__add__", nb_add, slot_nb_add,
5505 "+"),
5506 RBINSLOT("__radd__", nb_add, slot_nb_add,
5507 "+"),
5508 BINSLOT("__sub__", nb_subtract, slot_nb_subtract,
5509 "-"),
5510 RBINSLOT("__rsub__", nb_subtract, slot_nb_subtract,
5511 "-"),
5512 BINSLOT("__mul__", nb_multiply, slot_nb_multiply,
5513 "*"),
5514 RBINSLOT("__rmul__", nb_multiply, slot_nb_multiply,
5515 "*"),
5516 BINSLOT("__mod__", nb_remainder, slot_nb_remainder,
5517 "%"),
5518 RBINSLOT("__rmod__", nb_remainder, slot_nb_remainder,
5519 "%"),
5520 BINSLOTNOTINFIX("__divmod__", nb_divmod, slot_nb_divmod,
5521 "divmod(x, y)"),
5522 RBINSLOTNOTINFIX("__rdivmod__", nb_divmod, slot_nb_divmod,
5523 "divmod(y, x)"),
5524 NBSLOT("__pow__", nb_power, slot_nb_power, wrap_ternaryfunc,
5525 "x.__pow__(y[, z]) <==> pow(x, y[, z])"),
5526 NBSLOT("__rpow__", nb_power, slot_nb_power, wrap_ternaryfunc_r,
5527 "y.__rpow__(x[, z]) <==> pow(x, y[, z])"),
5528 UNSLOT("__neg__", nb_negative, slot_nb_negative, wrap_unaryfunc, "-x"),
5529 UNSLOT("__pos__", nb_positive, slot_nb_positive, wrap_unaryfunc, "+x"),
5530 UNSLOT("__abs__", nb_absolute, slot_nb_absolute, wrap_unaryfunc,
5531 "abs(x)"),
5532 UNSLOT("__bool__", nb_bool, slot_nb_bool, wrap_inquirypred,
5533 "x != 0"),
5534 UNSLOT("__invert__", nb_invert, slot_nb_invert, wrap_unaryfunc, "~x"),
5535 BINSLOT("__lshift__", nb_lshift, slot_nb_lshift, "<<"),
5536 RBINSLOT("__rlshift__", nb_lshift, slot_nb_lshift, "<<"),
5537 BINSLOT("__rshift__", nb_rshift, slot_nb_rshift, ">>"),
5538 RBINSLOT("__rrshift__", nb_rshift, slot_nb_rshift, ">>"),
5539 BINSLOT("__and__", nb_and, slot_nb_and, "&"),
5540 RBINSLOT("__rand__", nb_and, slot_nb_and, "&"),
5541 BINSLOT("__xor__", nb_xor, slot_nb_xor, "^"),
5542 RBINSLOT("__rxor__", nb_xor, slot_nb_xor, "^"),
5543 BINSLOT("__or__", nb_or, slot_nb_or, "|"),
5544 RBINSLOT("__ror__", nb_or, slot_nb_or, "|"),
5545 UNSLOT("__int__", nb_int, slot_nb_int, wrap_unaryfunc,
5546 "int(x)"),
5547 UNSLOT("__float__", nb_float, slot_nb_float, wrap_unaryfunc,
5548 "float(x)"),
5549 NBSLOT("__index__", nb_index, slot_nb_index, wrap_unaryfunc,
5550 "x[y:z] <==> x[y.__index__():z.__index__()]"),
5551 IBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add,
5552 wrap_binaryfunc, "+"),
5553 IBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract,
5554 wrap_binaryfunc, "-"),
5555 IBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply,
5556 wrap_binaryfunc, "*"),
5557 IBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder,
5558 wrap_binaryfunc, "%"),
5559 IBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power,
5560 wrap_binaryfunc, "**"),
5561 IBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift,
5562 wrap_binaryfunc, "<<"),
5563 IBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift,
5564 wrap_binaryfunc, ">>"),
5565 IBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and,
5566 wrap_binaryfunc, "&"),
5567 IBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor,
5568 wrap_binaryfunc, "^"),
5569 IBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or,
5570 wrap_binaryfunc, "|"),
5571 BINSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
5572 RBINSLOT("__rfloordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
5573 BINSLOT("__truediv__", nb_true_divide, slot_nb_true_divide, "/"),
5574 RBINSLOT("__rtruediv__", nb_true_divide, slot_nb_true_divide, "/"),
5575 IBSLOT("__ifloordiv__", nb_inplace_floor_divide,
5576 slot_nb_inplace_floor_divide, wrap_binaryfunc, "//"),
5577 IBSLOT("__itruediv__", nb_inplace_true_divide,
5578 slot_nb_inplace_true_divide, wrap_binaryfunc, "/"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005579
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005580 TPSLOT("__str__", tp_str, slot_tp_str, wrap_unaryfunc,
5581 "x.__str__() <==> str(x)"),
5582 TPSLOT("__repr__", tp_repr, slot_tp_repr, wrap_unaryfunc,
5583 "x.__repr__() <==> repr(x)"),
5584 TPSLOT("__hash__", tp_hash, slot_tp_hash, wrap_hashfunc,
5585 "x.__hash__() <==> hash(x)"),
5586 FLSLOT("__call__", tp_call, slot_tp_call, (wrapperfunc)wrap_call,
5587 "x.__call__(...) <==> x(...)", PyWrapperFlag_KEYWORDS),
5588 TPSLOT("__getattribute__", tp_getattro, slot_tp_getattr_hook,
5589 wrap_binaryfunc, "x.__getattribute__('name') <==> x.name"),
5590 TPSLOT("__getattribute__", tp_getattr, NULL, NULL, ""),
5591 TPSLOT("__getattr__", tp_getattro, slot_tp_getattr_hook, NULL, ""),
5592 TPSLOT("__getattr__", tp_getattr, NULL, NULL, ""),
5593 TPSLOT("__setattr__", tp_setattro, slot_tp_setattro, wrap_setattr,
5594 "x.__setattr__('name', value) <==> x.name = value"),
5595 TPSLOT("__setattr__", tp_setattr, NULL, NULL, ""),
5596 TPSLOT("__delattr__", tp_setattro, slot_tp_setattro, wrap_delattr,
5597 "x.__delattr__('name') <==> del x.name"),
5598 TPSLOT("__delattr__", tp_setattr, NULL, NULL, ""),
5599 TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare, richcmp_lt,
5600 "x.__lt__(y) <==> x<y"),
5601 TPSLOT("__le__", tp_richcompare, slot_tp_richcompare, richcmp_le,
5602 "x.__le__(y) <==> x<=y"),
5603 TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare, richcmp_eq,
5604 "x.__eq__(y) <==> x==y"),
5605 TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare, richcmp_ne,
5606 "x.__ne__(y) <==> x!=y"),
5607 TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare, richcmp_gt,
5608 "x.__gt__(y) <==> x>y"),
5609 TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare, richcmp_ge,
5610 "x.__ge__(y) <==> x>=y"),
5611 TPSLOT("__iter__", tp_iter, slot_tp_iter, wrap_unaryfunc,
5612 "x.__iter__() <==> iter(x)"),
5613 TPSLOT("__next__", tp_iternext, slot_tp_iternext, wrap_next,
5614 "x.__next__() <==> next(x)"),
5615 TPSLOT("__get__", tp_descr_get, slot_tp_descr_get, wrap_descr_get,
5616 "descr.__get__(obj[, type]) -> value"),
5617 TPSLOT("__set__", tp_descr_set, slot_tp_descr_set, wrap_descr_set,
5618 "descr.__set__(obj, value)"),
5619 TPSLOT("__delete__", tp_descr_set, slot_tp_descr_set,
5620 wrap_descr_delete, "descr.__delete__(obj)"),
5621 FLSLOT("__init__", tp_init, slot_tp_init, (wrapperfunc)wrap_init,
5622 "x.__init__(...) initializes x; "
Alexander Belopolsky977a6842010-08-16 20:17:07 +00005623 "see help(type(x)) for signature",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005624 PyWrapperFlag_KEYWORDS),
5625 TPSLOT("__new__", tp_new, slot_tp_new, NULL, ""),
5626 TPSLOT("__del__", tp_del, slot_tp_del, NULL, ""),
5627 {NULL}
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005628};
5629
Guido van Rossumc334df52002-04-04 23:44:47 +00005630/* Given a type pointer and an offset gotten from a slotdef entry, return a
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005631 pointer to the actual slot. This is not quite the same as simply adding
Guido van Rossumc334df52002-04-04 23:44:47 +00005632 the offset to the type pointer, since it takes care to indirect through the
5633 proper indirection pointer (as_buffer, etc.); it returns NULL if the
5634 indirection pointer is NULL. */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005635static void **
Martin v. Löwis18e16552006-02-15 17:27:45 +00005636slotptr(PyTypeObject *type, int ioffset)
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005637{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005638 char *ptr;
5639 long offset = ioffset;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005640
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005641 /* Note: this depends on the order of the members of PyHeapTypeObject! */
5642 assert(offset >= 0);
5643 assert((size_t)offset < offsetof(PyHeapTypeObject, as_buffer));
5644 if ((size_t)offset >= offsetof(PyHeapTypeObject, as_sequence)) {
5645 ptr = (char *)type->tp_as_sequence;
5646 offset -= offsetof(PyHeapTypeObject, as_sequence);
5647 }
5648 else if ((size_t)offset >= offsetof(PyHeapTypeObject, as_mapping)) {
5649 ptr = (char *)type->tp_as_mapping;
5650 offset -= offsetof(PyHeapTypeObject, as_mapping);
5651 }
5652 else if ((size_t)offset >= offsetof(PyHeapTypeObject, as_number)) {
5653 ptr = (char *)type->tp_as_number;
5654 offset -= offsetof(PyHeapTypeObject, as_number);
5655 }
5656 else {
5657 ptr = (char *)type;
5658 }
5659 if (ptr != NULL)
5660 ptr += offset;
5661 return (void **)ptr;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005662}
Guido van Rossumf040ede2001-08-07 16:40:56 +00005663
Guido van Rossumc334df52002-04-04 23:44:47 +00005664/* Length of array of slotdef pointers used to store slots with the
5665 same __name__. There should be at most MAX_EQUIV-1 slotdef entries with
5666 the same __name__, for any __name__. Since that's a static property, it is
5667 appropriate to declare fixed-size arrays for this. */
5668#define MAX_EQUIV 10
5669
5670/* Return a slot pointer for a given name, but ONLY if the attribute has
5671 exactly one slot function. The name must be an interned string. */
5672static void **
5673resolve_slotdups(PyTypeObject *type, PyObject *name)
5674{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005675 /* XXX Maybe this could be optimized more -- but is it worth it? */
Guido van Rossumc334df52002-04-04 23:44:47 +00005676
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005677 /* pname and ptrs act as a little cache */
5678 static PyObject *pname;
5679 static slotdef *ptrs[MAX_EQUIV];
5680 slotdef *p, **pp;
5681 void **res, **ptr;
Guido van Rossumc334df52002-04-04 23:44:47 +00005682
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005683 if (pname != name) {
5684 /* Collect all slotdefs that match name into ptrs. */
5685 pname = name;
5686 pp = ptrs;
5687 for (p = slotdefs; p->name_strobj; p++) {
5688 if (p->name_strobj == name)
5689 *pp++ = p;
5690 }
5691 *pp = NULL;
5692 }
Guido van Rossumc334df52002-04-04 23:44:47 +00005693
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005694 /* Look in all matching slots of the type; if exactly one of these has
5695 a filled-in slot, return its value. Otherwise return NULL. */
5696 res = NULL;
5697 for (pp = ptrs; *pp; pp++) {
5698 ptr = slotptr(type, (*pp)->offset);
5699 if (ptr == NULL || *ptr == NULL)
5700 continue;
5701 if (res != NULL)
5702 return NULL;
5703 res = ptr;
5704 }
5705 return res;
Guido van Rossumc334df52002-04-04 23:44:47 +00005706}
5707
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005708/* Common code for update_slots_callback() and fixup_slot_dispatchers(). This
Guido van Rossumc334df52002-04-04 23:44:47 +00005709 does some incredibly complex thinking and then sticks something into the
5710 slot. (It sees if the adjacent slotdefs for the same slot have conflicting
5711 interests, and then stores a generic wrapper or a specific function into
5712 the slot.) Return a pointer to the next slotdef with a different offset,
5713 because that's convenient for fixup_slot_dispatchers(). */
5714static slotdef *
5715update_one_slot(PyTypeObject *type, slotdef *p)
5716{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005717 PyObject *descr;
5718 PyWrapperDescrObject *d;
5719 void *generic = NULL, *specific = NULL;
5720 int use_generic = 0;
5721 int offset = p->offset;
5722 void **ptr = slotptr(type, offset);
Guido van Rossumc334df52002-04-04 23:44:47 +00005723
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005724 if (ptr == NULL) {
5725 do {
5726 ++p;
5727 } while (p->offset == offset);
5728 return p;
5729 }
5730 do {
5731 descr = _PyType_Lookup(type, p->name_strobj);
5732 if (descr == NULL) {
5733 if (ptr == (void**)&type->tp_iternext) {
5734 specific = _PyObject_NextNotImplemented;
5735 }
5736 continue;
5737 }
5738 if (Py_TYPE(descr) == &PyWrapperDescr_Type) {
5739 void **tptr = resolve_slotdups(type, p->name_strobj);
5740 if (tptr == NULL || tptr == ptr)
5741 generic = p->function;
5742 d = (PyWrapperDescrObject *)descr;
5743 if (d->d_base->wrapper == p->wrapper &&
5744 PyType_IsSubtype(type, PyDescr_TYPE(d)))
5745 {
5746 if (specific == NULL ||
5747 specific == d->d_wrapped)
5748 specific = d->d_wrapped;
5749 else
5750 use_generic = 1;
5751 }
5752 }
5753 else if (Py_TYPE(descr) == &PyCFunction_Type &&
5754 PyCFunction_GET_FUNCTION(descr) ==
5755 (PyCFunction)tp_new_wrapper &&
5756 ptr == (void**)&type->tp_new)
5757 {
5758 /* The __new__ wrapper is not a wrapper descriptor,
5759 so must be special-cased differently.
5760 If we don't do this, creating an instance will
5761 always use slot_tp_new which will look up
5762 __new__ in the MRO which will call tp_new_wrapper
5763 which will look through the base classes looking
5764 for a static base and call its tp_new (usually
5765 PyType_GenericNew), after performing various
5766 sanity checks and constructing a new argument
5767 list. Cut all that nonsense short -- this speeds
5768 up instance creation tremendously. */
5769 specific = (void *)type->tp_new;
5770 /* XXX I'm not 100% sure that there isn't a hole
5771 in this reasoning that requires additional
5772 sanity checks. I'll buy the first person to
5773 point out a bug in this reasoning a beer. */
5774 }
5775 else if (descr == Py_None &&
5776 ptr == (void**)&type->tp_hash) {
5777 /* We specifically allow __hash__ to be set to None
5778 to prevent inheritance of the default
5779 implementation from object.__hash__ */
5780 specific = PyObject_HashNotImplemented;
5781 }
5782 else {
5783 use_generic = 1;
5784 generic = p->function;
5785 }
5786 } while ((++p)->offset == offset);
5787 if (specific && !use_generic)
5788 *ptr = specific;
5789 else
5790 *ptr = generic;
5791 return p;
Guido van Rossumc334df52002-04-04 23:44:47 +00005792}
5793
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005794/* In the type, update the slots whose slotdefs are gathered in the pp array.
5795 This is a callback for update_subclasses(). */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005796static int
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005797update_slots_callback(PyTypeObject *type, void *data)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005798{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005799 slotdef **pp = (slotdef **)data;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005800
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005801 for (; *pp; pp++)
5802 update_one_slot(type, *pp);
5803 return 0;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005804}
5805
Guido van Rossumc334df52002-04-04 23:44:47 +00005806/* Comparison function for qsort() to compare slotdefs by their offset, and
5807 for equal offset by their address (to force a stable sort). */
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005808static int
5809slotdef_cmp(const void *aa, const void *bb)
5810{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005811 const slotdef *a = (const slotdef *)aa, *b = (const slotdef *)bb;
5812 int c = a->offset - b->offset;
5813 if (c != 0)
5814 return c;
5815 else
5816 /* Cannot use a-b, as this gives off_t,
5817 which may lose precision when converted to int. */
5818 return (a > b) ? 1 : (a < b) ? -1 : 0;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005819}
5820
Guido van Rossumc334df52002-04-04 23:44:47 +00005821/* Initialize the slotdefs table by adding interned string objects for the
5822 names and sorting the entries. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005823static void
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005824init_slotdefs(void)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005825{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005826 slotdef *p;
5827 static int initialized = 0;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005828
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005829 if (initialized)
5830 return;
5831 for (p = slotdefs; p->name; p++) {
5832 p->name_strobj = PyUnicode_InternFromString(p->name);
5833 if (!p->name_strobj)
5834 Py_FatalError("Out of memory interning slotdef names");
5835 }
5836 qsort((void *)slotdefs, (size_t)(p-slotdefs), sizeof(slotdef),
5837 slotdef_cmp);
5838 initialized = 1;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005839}
5840
Guido van Rossumc334df52002-04-04 23:44:47 +00005841/* Update the slots after assignment to a class (type) attribute. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005842static int
5843update_slot(PyTypeObject *type, PyObject *name)
5844{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005845 slotdef *ptrs[MAX_EQUIV];
5846 slotdef *p;
5847 slotdef **pp;
5848 int offset;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005849
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005850 /* Clear the VALID_VERSION flag of 'type' and all its
5851 subclasses. This could possibly be unified with the
5852 update_subclasses() recursion below, but carefully:
5853 they each have their own conditions on which to stop
5854 recursing into subclasses. */
5855 PyType_Modified(type);
Christian Heimesa62da1d2008-01-12 19:39:10 +00005856
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005857 init_slotdefs();
5858 pp = ptrs;
5859 for (p = slotdefs; p->name; p++) {
5860 /* XXX assume name is interned! */
5861 if (p->name_strobj == name)
5862 *pp++ = p;
5863 }
5864 *pp = NULL;
5865 for (pp = ptrs; *pp; pp++) {
5866 p = *pp;
5867 offset = p->offset;
5868 while (p > slotdefs && (p-1)->offset == offset)
5869 --p;
5870 *pp = p;
5871 }
5872 if (ptrs[0] == NULL)
5873 return 0; /* Not an attribute that affects any slots */
5874 return update_subclasses(type, name,
5875 update_slots_callback, (void *)ptrs);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005876}
5877
Guido van Rossumc334df52002-04-04 23:44:47 +00005878/* Store the proper functions in the slot dispatches at class (type)
5879 definition time, based upon which operations the class overrides in its
5880 dict. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00005881static void
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005882fixup_slot_dispatchers(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005883{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005884 slotdef *p;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005885
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005886 init_slotdefs();
5887 for (p = slotdefs; p->name; )
5888 p = update_one_slot(type, p);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005889}
Guido van Rossum705f0f52001-08-24 16:47:00 +00005890
Michael W. Hudson98bbc492002-11-26 14:47:27 +00005891static void
5892update_all_slots(PyTypeObject* type)
5893{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005894 slotdef *p;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00005895
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005896 init_slotdefs();
5897 for (p = slotdefs; p->name; p++) {
5898 /* update_slot returns int but can't actually fail */
5899 update_slot(type, p->name_strobj);
5900 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +00005901}
5902
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005903/* recurse_down_subclasses() and update_subclasses() are mutually
5904 recursive functions to call a callback for all subclasses,
5905 but refraining from recursing into subclasses that define 'name'. */
5906
5907static int
5908update_subclasses(PyTypeObject *type, PyObject *name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005909 update_callback callback, void *data)
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005910{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005911 if (callback(type, data) < 0)
5912 return -1;
5913 return recurse_down_subclasses(type, name, callback, data);
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005914}
5915
5916static int
5917recurse_down_subclasses(PyTypeObject *type, PyObject *name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005918 update_callback callback, void *data)
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005919{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005920 PyTypeObject *subclass;
5921 PyObject *ref, *subclasses, *dict;
5922 Py_ssize_t i, n;
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005923
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005924 subclasses = type->tp_subclasses;
5925 if (subclasses == NULL)
5926 return 0;
5927 assert(PyList_Check(subclasses));
5928 n = PyList_GET_SIZE(subclasses);
5929 for (i = 0; i < n; i++) {
5930 ref = PyList_GET_ITEM(subclasses, i);
5931 assert(PyWeakref_CheckRef(ref));
5932 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
5933 assert(subclass != NULL);
5934 if ((PyObject *)subclass == Py_None)
5935 continue;
5936 assert(PyType_Check(subclass));
5937 /* Avoid recursing down into unaffected classes */
5938 dict = subclass->tp_dict;
5939 if (dict != NULL && PyDict_Check(dict) &&
5940 PyDict_GetItem(dict, name) != NULL)
5941 continue;
5942 if (update_subclasses(subclass, name, callback, data) < 0)
5943 return -1;
5944 }
5945 return 0;
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005946}
5947
Guido van Rossum6d204072001-10-21 00:44:31 +00005948/* This function is called by PyType_Ready() to populate the type's
5949 dictionary with method descriptors for function slots. For each
Guido van Rossum09638c12002-06-13 19:17:46 +00005950 function slot (like tp_repr) that's defined in the type, one or more
5951 corresponding descriptors are added in the type's tp_dict dictionary
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005952 under the appropriate name (like __repr__). Some function slots
Guido van Rossum09638c12002-06-13 19:17:46 +00005953 cause more than one descriptor to be added (for example, the nb_add
5954 slot adds both __add__ and __radd__ descriptors) and some function
5955 slots compete for the same descriptor (for example both sq_item and
5956 mp_subscript generate a __getitem__ descriptor).
5957
Ezio Melotti13925002011-03-16 11:05:33 +02005958 In the latter case, the first slotdef entry encountered wins. Since
Tim Petersbf9b2442003-03-23 05:35:36 +00005959 slotdef entries are sorted by the offset of the slot in the
Guido van Rossume5c691a2003-03-07 15:13:17 +00005960 PyHeapTypeObject, this gives us some control over disambiguating
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005961 between competing slots: the members of PyHeapTypeObject are listed
5962 from most general to least general, so the most general slot is
5963 preferred. In particular, because as_mapping comes before as_sequence,
5964 for a type that defines both mp_subscript and sq_item, mp_subscript
5965 wins.
Guido van Rossum09638c12002-06-13 19:17:46 +00005966
5967 This only adds new descriptors and doesn't overwrite entries in
5968 tp_dict that were previously defined. The descriptors contain a
5969 reference to the C function they must call, so that it's safe if they
5970 are copied into a subtype's __dict__ and the subtype has a different
5971 C function in its slot -- calling the method defined by the
5972 descriptor will call the C function that was used to create it,
5973 rather than the C function present in the slot when it is called.
5974 (This is important because a subtype may have a C function in the
5975 slot that calls the method from the dictionary, and we want to avoid
5976 infinite recursion here.) */
Guido van Rossum6d204072001-10-21 00:44:31 +00005977
5978static int
5979add_operators(PyTypeObject *type)
5980{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005981 PyObject *dict = type->tp_dict;
5982 slotdef *p;
5983 PyObject *descr;
5984 void **ptr;
Guido van Rossum6d204072001-10-21 00:44:31 +00005985
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005986 init_slotdefs();
5987 for (p = slotdefs; p->name; p++) {
5988 if (p->wrapper == NULL)
5989 continue;
5990 ptr = slotptr(type, p->offset);
5991 if (!ptr || !*ptr)
5992 continue;
5993 if (PyDict_GetItem(dict, p->name_strobj))
5994 continue;
5995 if (*ptr == PyObject_HashNotImplemented) {
5996 /* Classes may prevent the inheritance of the tp_hash
5997 slot by storing PyObject_HashNotImplemented in it. Make it
5998 visible as a None value for the __hash__ attribute. */
5999 if (PyDict_SetItem(dict, p->name_strobj, Py_None) < 0)
6000 return -1;
6001 }
6002 else {
6003 descr = PyDescr_NewWrapper(type, p, *ptr);
6004 if (descr == NULL)
6005 return -1;
6006 if (PyDict_SetItem(dict, p->name_strobj, descr) < 0)
6007 return -1;
6008 Py_DECREF(descr);
6009 }
6010 }
6011 if (type->tp_new != NULL) {
6012 if (add_tp_new_wrapper(type) < 0)
6013 return -1;
6014 }
6015 return 0;
Guido van Rossum6d204072001-10-21 00:44:31 +00006016}
6017
Guido van Rossum705f0f52001-08-24 16:47:00 +00006018
6019/* Cooperative 'super' */
6020
6021typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006022 PyObject_HEAD
6023 PyTypeObject *type;
6024 PyObject *obj;
6025 PyTypeObject *obj_type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006026} superobject;
6027
Guido van Rossum6f799372001-09-20 20:46:19 +00006028static PyMemberDef super_members[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006029 {"__thisclass__", T_OBJECT, offsetof(superobject, type), READONLY,
6030 "the class invoking super()"},
6031 {"__self__", T_OBJECT, offsetof(superobject, obj), READONLY,
6032 "the instance invoking super(); may be None"},
6033 {"__self_class__", T_OBJECT, offsetof(superobject, obj_type), READONLY,
6034 "the type of the instance invoking super(); may be None"},
6035 {0}
Guido van Rossum41eb14d2001-08-30 23:13:11 +00006036};
6037
Guido van Rossum705f0f52001-08-24 16:47:00 +00006038static void
6039super_dealloc(PyObject *self)
6040{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006041 superobject *su = (superobject *)self;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006042
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006043 _PyObject_GC_UNTRACK(self);
6044 Py_XDECREF(su->obj);
6045 Py_XDECREF(su->type);
6046 Py_XDECREF(su->obj_type);
6047 Py_TYPE(self)->tp_free(self);
Guido van Rossum705f0f52001-08-24 16:47:00 +00006048}
6049
6050static PyObject *
Guido van Rossum41eb14d2001-08-30 23:13:11 +00006051super_repr(PyObject *self)
6052{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006053 superobject *su = (superobject *)self;
Guido van Rossum41eb14d2001-08-30 23:13:11 +00006054
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006055 if (su->obj_type)
6056 return PyUnicode_FromFormat(
6057 "<super: <class '%s'>, <%s object>>",
6058 su->type ? su->type->tp_name : "NULL",
6059 su->obj_type->tp_name);
6060 else
6061 return PyUnicode_FromFormat(
6062 "<super: <class '%s'>, NULL>",
6063 su->type ? su->type->tp_name : "NULL");
Guido van Rossum41eb14d2001-08-30 23:13:11 +00006064}
6065
6066static PyObject *
Guido van Rossum705f0f52001-08-24 16:47:00 +00006067super_getattro(PyObject *self, PyObject *name)
6068{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006069 superobject *su = (superobject *)self;
6070 int skip = su->obj_type == NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006071
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006072 if (!skip) {
6073 /* We want __class__ to return the class of the super object
6074 (i.e. super, or a subclass), not the class of su->obj. */
6075 skip = (PyUnicode_Check(name) &&
6076 PyUnicode_GET_SIZE(name) == 9 &&
6077 PyUnicode_CompareWithASCIIString(name, "__class__") == 0);
6078 }
Guido van Rossum76ba09f2003-04-16 19:40:58 +00006079
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006080 if (!skip) {
6081 PyObject *mro, *res, *tmp, *dict;
6082 PyTypeObject *starttype;
6083 descrgetfunc f;
6084 Py_ssize_t i, n;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006085
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006086 starttype = su->obj_type;
6087 mro = starttype->tp_mro;
Guido van Rossum155db9a2002-04-02 17:53:47 +00006088
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006089 if (mro == NULL)
6090 n = 0;
6091 else {
6092 assert(PyTuple_Check(mro));
6093 n = PyTuple_GET_SIZE(mro);
6094 }
6095 for (i = 0; i < n; i++) {
6096 if ((PyObject *)(su->type) == PyTuple_GET_ITEM(mro, i))
6097 break;
6098 }
6099 i++;
6100 res = NULL;
6101 for (; i < n; i++) {
6102 tmp = PyTuple_GET_ITEM(mro, i);
6103 if (PyType_Check(tmp))
6104 dict = ((PyTypeObject *)tmp)->tp_dict;
6105 else
6106 continue;
6107 res = PyDict_GetItem(dict, name);
6108 if (res != NULL) {
6109 Py_INCREF(res);
6110 f = Py_TYPE(res)->tp_descr_get;
6111 if (f != NULL) {
6112 tmp = f(res,
6113 /* Only pass 'obj' param if
6114 this is instance-mode super
6115 (See SF ID #743627)
6116 */
6117 (su->obj == (PyObject *)
6118 su->obj_type
6119 ? (PyObject *)NULL
6120 : su->obj),
6121 (PyObject *)starttype);
6122 Py_DECREF(res);
6123 res = tmp;
6124 }
6125 return res;
6126 }
6127 }
6128 }
6129 return PyObject_GenericGetAttr(self, name);
Guido van Rossum705f0f52001-08-24 16:47:00 +00006130}
6131
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006132static PyTypeObject *
Guido van Rossum5b443c62001-12-03 15:38:28 +00006133supercheck(PyTypeObject *type, PyObject *obj)
6134{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006135 /* Check that a super() call makes sense. Return a type object.
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006136
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006137 obj can be a new-style class, or an instance of one:
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006138
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006139 - If it is a class, it must be a subclass of 'type'. This case is
6140 used for class methods; the return value is obj.
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006141
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006142 - If it is an instance, it must be an instance of 'type'. This is
6143 the normal case; the return value is obj.__class__.
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006144
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006145 But... when obj is an instance, we want to allow for the case where
6146 Py_TYPE(obj) is not a subclass of type, but obj.__class__ is!
6147 This will allow using super() with a proxy for obj.
6148 */
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006149
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006150 /* Check for first bullet above (special case) */
6151 if (PyType_Check(obj) && PyType_IsSubtype((PyTypeObject *)obj, type)) {
6152 Py_INCREF(obj);
6153 return (PyTypeObject *)obj;
6154 }
Guido van Rossum8e80a722003-02-18 19:22:22 +00006155
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006156 /* Normal case */
6157 if (PyType_IsSubtype(Py_TYPE(obj), type)) {
6158 Py_INCREF(Py_TYPE(obj));
6159 return Py_TYPE(obj);
6160 }
6161 else {
6162 /* Try the slow way */
6163 static PyObject *class_str = NULL;
6164 PyObject *class_attr;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006165
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006166 if (class_str == NULL) {
6167 class_str = PyUnicode_FromString("__class__");
6168 if (class_str == NULL)
6169 return NULL;
6170 }
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006171
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006172 class_attr = PyObject_GetAttr(obj, class_str);
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006173
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006174 if (class_attr != NULL &&
6175 PyType_Check(class_attr) &&
6176 (PyTypeObject *)class_attr != Py_TYPE(obj))
6177 {
6178 int ok = PyType_IsSubtype(
6179 (PyTypeObject *)class_attr, type);
6180 if (ok)
6181 return (PyTypeObject *)class_attr;
6182 }
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006183
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006184 if (class_attr == NULL)
6185 PyErr_Clear();
6186 else
6187 Py_DECREF(class_attr);
6188 }
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006189
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006190 PyErr_SetString(PyExc_TypeError,
6191 "super(type, obj): "
6192 "obj must be an instance or subtype of type");
6193 return NULL;
Guido van Rossum5b443c62001-12-03 15:38:28 +00006194}
6195
Guido van Rossum705f0f52001-08-24 16:47:00 +00006196static PyObject *
6197super_descr_get(PyObject *self, PyObject *obj, PyObject *type)
6198{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006199 superobject *su = (superobject *)self;
6200 superobject *newobj;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006201
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006202 if (obj == NULL || obj == Py_None || su->obj != NULL) {
6203 /* Not binding to an object, or already bound */
6204 Py_INCREF(self);
6205 return self;
6206 }
6207 if (Py_TYPE(su) != &PySuper_Type)
6208 /* If su is an instance of a (strict) subclass of super,
6209 call its type */
6210 return PyObject_CallFunctionObjArgs((PyObject *)Py_TYPE(su),
6211 su->type, obj, NULL);
6212 else {
6213 /* Inline the common case */
6214 PyTypeObject *obj_type = supercheck(su->type, obj);
6215 if (obj_type == NULL)
6216 return NULL;
6217 newobj = (superobject *)PySuper_Type.tp_new(&PySuper_Type,
6218 NULL, NULL);
6219 if (newobj == NULL)
6220 return NULL;
6221 Py_INCREF(su->type);
6222 Py_INCREF(obj);
6223 newobj->type = su->type;
6224 newobj->obj = obj;
6225 newobj->obj_type = obj_type;
6226 return (PyObject *)newobj;
6227 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00006228}
6229
6230static int
6231super_init(PyObject *self, PyObject *args, PyObject *kwds)
6232{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006233 superobject *su = (superobject *)self;
6234 PyTypeObject *type = NULL;
6235 PyObject *obj = NULL;
6236 PyTypeObject *obj_type = NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006237
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006238 if (!_PyArg_NoKeywords("super", kwds))
6239 return -1;
6240 if (!PyArg_ParseTuple(args, "|O!O:super", &PyType_Type, &type, &obj))
6241 return -1;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00006242
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006243 if (type == NULL) {
6244 /* Call super(), without args -- fill in from __class__
6245 and first local variable on the stack. */
6246 PyFrameObject *f = PyThreadState_GET()->frame;
6247 PyCodeObject *co = f->f_code;
Victor Stinner0fcab4a2011-01-04 12:59:15 +00006248 Py_ssize_t i, n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006249 if (co == NULL) {
6250 PyErr_SetString(PyExc_SystemError,
6251 "super(): no code object");
6252 return -1;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00006253 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006254 if (co->co_argcount == 0) {
6255 PyErr_SetString(PyExc_SystemError,
6256 "super(): no arguments");
6257 return -1;
6258 }
6259 obj = f->f_localsplus[0];
6260 if (obj == NULL) {
6261 PyErr_SetString(PyExc_SystemError,
6262 "super(): arg[0] deleted");
6263 return -1;
6264 }
6265 if (co->co_freevars == NULL)
6266 n = 0;
6267 else {
6268 assert(PyTuple_Check(co->co_freevars));
6269 n = PyTuple_GET_SIZE(co->co_freevars);
6270 }
6271 for (i = 0; i < n; i++) {
6272 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
6273 assert(PyUnicode_Check(name));
6274 if (!PyUnicode_CompareWithASCIIString(name,
6275 "__class__")) {
6276 Py_ssize_t index = co->co_nlocals +
6277 PyTuple_GET_SIZE(co->co_cellvars) + i;
6278 PyObject *cell = f->f_localsplus[index];
6279 if (cell == NULL || !PyCell_Check(cell)) {
6280 PyErr_SetString(PyExc_SystemError,
6281 "super(): bad __class__ cell");
6282 return -1;
6283 }
6284 type = (PyTypeObject *) PyCell_GET(cell);
6285 if (type == NULL) {
6286 PyErr_SetString(PyExc_SystemError,
6287 "super(): empty __class__ cell");
6288 return -1;
6289 }
6290 if (!PyType_Check(type)) {
6291 PyErr_Format(PyExc_SystemError,
6292 "super(): __class__ is not a type (%s)",
6293 Py_TYPE(type)->tp_name);
6294 return -1;
6295 }
6296 break;
6297 }
6298 }
6299 if (type == NULL) {
6300 PyErr_SetString(PyExc_SystemError,
6301 "super(): __class__ cell not found");
6302 return -1;
6303 }
6304 }
Guido van Rossumcd16bf62007-06-13 18:07:49 +00006305
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006306 if (obj == Py_None)
6307 obj = NULL;
6308 if (obj != NULL) {
6309 obj_type = supercheck(type, obj);
6310 if (obj_type == NULL)
6311 return -1;
6312 Py_INCREF(obj);
6313 }
6314 Py_INCREF(type);
6315 su->type = type;
6316 su->obj = obj;
6317 su->obj_type = obj_type;
6318 return 0;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006319}
6320
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00006321PyDoc_STRVAR(super_doc,
Guido van Rossumcd16bf62007-06-13 18:07:49 +00006322"super() -> same as super(__class__, <first argument>)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00006323"super(type) -> unbound super object\n"
6324"super(type, obj) -> bound super object; requires isinstance(obj, type)\n"
Guido van Rossume705ef12001-08-29 15:47:06 +00006325"super(type, type2) -> bound super object; requires issubclass(type2, type)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00006326"Typical use to call a cooperative superclass method:\n"
6327"class C(B):\n"
6328" def meth(self, arg):\n"
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006329" super().meth(arg)\n"
Guido van Rossumcd16bf62007-06-13 18:07:49 +00006330"This works for class methods too:\n"
6331"class C(B):\n"
6332" @classmethod\n"
6333" def cmeth(cls, arg):\n"
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006334" super().cmeth(arg)\n");
Guido van Rossum705f0f52001-08-24 16:47:00 +00006335
Guido van Rossum048eb752001-10-02 21:24:57 +00006336static int
6337super_traverse(PyObject *self, visitproc visit, void *arg)
6338{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006339 superobject *su = (superobject *)self;
Guido van Rossum048eb752001-10-02 21:24:57 +00006340
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006341 Py_VISIT(su->obj);
6342 Py_VISIT(su->type);
6343 Py_VISIT(su->obj_type);
Guido van Rossum048eb752001-10-02 21:24:57 +00006344
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006345 return 0;
Guido van Rossum048eb752001-10-02 21:24:57 +00006346}
6347
Guido van Rossum705f0f52001-08-24 16:47:00 +00006348PyTypeObject PySuper_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006349 PyVarObject_HEAD_INIT(&PyType_Type, 0)
6350 "super", /* tp_name */
6351 sizeof(superobject), /* tp_basicsize */
6352 0, /* tp_itemsize */
6353 /* methods */
6354 super_dealloc, /* tp_dealloc */
6355 0, /* tp_print */
6356 0, /* tp_getattr */
6357 0, /* tp_setattr */
6358 0, /* tp_reserved */
6359 super_repr, /* tp_repr */
6360 0, /* tp_as_number */
6361 0, /* tp_as_sequence */
6362 0, /* tp_as_mapping */
6363 0, /* tp_hash */
6364 0, /* tp_call */
6365 0, /* tp_str */
6366 super_getattro, /* tp_getattro */
6367 0, /* tp_setattro */
6368 0, /* tp_as_buffer */
6369 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
6370 Py_TPFLAGS_BASETYPE, /* tp_flags */
6371 super_doc, /* tp_doc */
6372 super_traverse, /* tp_traverse */
6373 0, /* tp_clear */
6374 0, /* tp_richcompare */
6375 0, /* tp_weaklistoffset */
6376 0, /* tp_iter */
6377 0, /* tp_iternext */
6378 0, /* tp_methods */
6379 super_members, /* tp_members */
6380 0, /* tp_getset */
6381 0, /* tp_base */
6382 0, /* tp_dict */
6383 super_descr_get, /* tp_descr_get */
6384 0, /* tp_descr_set */
6385 0, /* tp_dictoffset */
6386 super_init, /* tp_init */
6387 PyType_GenericAlloc, /* tp_alloc */
6388 PyType_GenericNew, /* tp_new */
6389 PyObject_GC_Del, /* tp_free */
Guido van Rossum705f0f52001-08-24 16:47:00 +00006390};