blob: fd2ae67d860f598242c3c205470f2315c12886c8 [file] [log] [blame]
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001/* Type object implementation */
2
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003#include "Python.h"
Guido van Rossumcd16bf62007-06-13 18:07:49 +00004#include "frameobject.h"
Tim Peters6d6c1a32001-08-02 04:15:00 +00005#include "structmember.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00006
Guido van Rossum9923ffe2002-06-04 19:52:53 +00007#include <ctype.h>
8
Christian Heimesa62da1d2008-01-12 19:39:10 +00009
10/* Support type attribute cache */
11
12/* The cache can keep references to the names alive for longer than
13 they normally would. This is why the maximum size is limited to
14 MCACHE_MAX_ATTR_SIZE, since it might be a problem if very large
15 strings are used as attribute names. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000016#define MCACHE_MAX_ATTR_SIZE 100
17#define MCACHE_SIZE_EXP 10
18#define MCACHE_HASH(version, name_hash) \
19 (((unsigned int)(version) * (unsigned int)(name_hash)) \
20 >> (8*sizeof(unsigned int) - MCACHE_SIZE_EXP))
Christian Heimesa62da1d2008-01-12 19:39:10 +000021#define MCACHE_HASH_METHOD(type, name) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000022 MCACHE_HASH((type)->tp_version_tag, \
23 ((PyUnicodeObject *)(name))->hash)
Christian Heimesa62da1d2008-01-12 19:39:10 +000024#define MCACHE_CACHEABLE_NAME(name) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000025 PyUnicode_CheckExact(name) && \
26 PyUnicode_GET_SIZE(name) <= MCACHE_MAX_ATTR_SIZE
Christian Heimesa62da1d2008-01-12 19:39:10 +000027
28struct method_cache_entry {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000029 unsigned int version;
30 PyObject *name; /* reference to exactly a str or None */
31 PyObject *value; /* borrowed */
Christian Heimesa62da1d2008-01-12 19:39:10 +000032};
33
34static struct method_cache_entry method_cache[1 << MCACHE_SIZE_EXP];
35static unsigned int next_version_tag = 0;
Christian Heimes26855632008-01-27 23:50:43 +000036
37unsigned int
38PyType_ClearCache(void)
39{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000040 Py_ssize_t i;
41 unsigned int cur_version_tag = next_version_tag - 1;
42
43 for (i = 0; i < (1 << MCACHE_SIZE_EXP); i++) {
44 method_cache[i].version = 0;
45 Py_CLEAR(method_cache[i].name);
46 method_cache[i].value = NULL;
47 }
48 next_version_tag = 0;
49 /* mark all version tags as invalid */
50 PyType_Modified(&PyBaseObject_Type);
51 return cur_version_tag;
Christian Heimes26855632008-01-27 23:50:43 +000052}
Christian Heimesa62da1d2008-01-12 19:39:10 +000053
Georg Brandlf08a9dd2008-06-10 16:57:31 +000054void
55PyType_Modified(PyTypeObject *type)
Christian Heimesa62da1d2008-01-12 19:39:10 +000056{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000057 /* Invalidate any cached data for the specified type and all
58 subclasses. This function is called after the base
59 classes, mro, or attributes of the type are altered.
Christian Heimesa62da1d2008-01-12 19:39:10 +000060
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000061 Invariants:
Christian Heimesa62da1d2008-01-12 19:39:10 +000062
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000063 - Py_TPFLAGS_VALID_VERSION_TAG is never set if
64 Py_TPFLAGS_HAVE_VERSION_TAG is not set (e.g. on type
65 objects coming from non-recompiled extension modules)
Christian Heimesa62da1d2008-01-12 19:39:10 +000066
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000067 - before Py_TPFLAGS_VALID_VERSION_TAG can be set on a type,
68 it must first be set on all super types.
Christian Heimesa62da1d2008-01-12 19:39:10 +000069
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000070 This function clears the Py_TPFLAGS_VALID_VERSION_TAG of a
71 type (so it must first clear it on all subclasses). The
72 tp_version_tag value is meaningless unless this flag is set.
73 We don't assign new version tags eagerly, but only as
74 needed.
75 */
76 PyObject *raw, *ref;
77 Py_ssize_t i, n;
Christian Heimesa62da1d2008-01-12 19:39:10 +000078
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000079 if (!PyType_HasFeature(type, Py_TPFLAGS_VALID_VERSION_TAG))
80 return;
Christian Heimesa62da1d2008-01-12 19:39:10 +000081
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000082 raw = type->tp_subclasses;
83 if (raw != NULL) {
84 n = PyList_GET_SIZE(raw);
85 for (i = 0; i < n; i++) {
86 ref = PyList_GET_ITEM(raw, i);
87 ref = PyWeakref_GET_OBJECT(ref);
88 if (ref != Py_None) {
89 PyType_Modified((PyTypeObject *)ref);
90 }
91 }
92 }
93 type->tp_flags &= ~Py_TPFLAGS_VALID_VERSION_TAG;
Christian Heimesa62da1d2008-01-12 19:39:10 +000094}
95
96static void
97type_mro_modified(PyTypeObject *type, PyObject *bases) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000098 /*
99 Check that all base classes or elements of the mro of type are
100 able to be cached. This function is called after the base
101 classes or mro of the type are altered.
Christian Heimesa62da1d2008-01-12 19:39:10 +0000102
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000103 Unset HAVE_VERSION_TAG and VALID_VERSION_TAG if the type
104 inherits from an old-style class, either directly or if it
105 appears in the MRO of a new-style class. No support either for
106 custom MROs that include types that are not officially super
107 types.
Christian Heimesa62da1d2008-01-12 19:39:10 +0000108
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000109 Called from mro_internal, which will subsequently be called on
110 each subclass when their mro is recursively updated.
111 */
112 Py_ssize_t i, n;
113 int clear = 0;
Christian Heimesa62da1d2008-01-12 19:39:10 +0000114
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000115 if (!PyType_HasFeature(type, Py_TPFLAGS_HAVE_VERSION_TAG))
116 return;
Christian Heimesa62da1d2008-01-12 19:39:10 +0000117
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000118 n = PyTuple_GET_SIZE(bases);
119 for (i = 0; i < n; i++) {
120 PyObject *b = PyTuple_GET_ITEM(bases, i);
121 PyTypeObject *cls;
Christian Heimesa62da1d2008-01-12 19:39:10 +0000122
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000123 if (!PyType_Check(b) ) {
124 clear = 1;
125 break;
126 }
Christian Heimesa62da1d2008-01-12 19:39:10 +0000127
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000128 cls = (PyTypeObject *)b;
Christian Heimesa62da1d2008-01-12 19:39:10 +0000129
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000130 if (!PyType_HasFeature(cls, Py_TPFLAGS_HAVE_VERSION_TAG) ||
131 !PyType_IsSubtype(type, cls)) {
132 clear = 1;
133 break;
134 }
135 }
Christian Heimesa62da1d2008-01-12 19:39:10 +0000136
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000137 if (clear)
138 type->tp_flags &= ~(Py_TPFLAGS_HAVE_VERSION_TAG|
139 Py_TPFLAGS_VALID_VERSION_TAG);
Christian Heimesa62da1d2008-01-12 19:39:10 +0000140}
141
142static int
143assign_version_tag(PyTypeObject *type)
144{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000145 /* Ensure that the tp_version_tag is valid and set
146 Py_TPFLAGS_VALID_VERSION_TAG. To respect the invariant, this
147 must first be done on all super classes. Return 0 if this
148 cannot be done, 1 if Py_TPFLAGS_VALID_VERSION_TAG.
149 */
150 Py_ssize_t i, n;
151 PyObject *bases;
Christian Heimesa62da1d2008-01-12 19:39:10 +0000152
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000153 if (PyType_HasFeature(type, Py_TPFLAGS_VALID_VERSION_TAG))
154 return 1;
155 if (!PyType_HasFeature(type, Py_TPFLAGS_HAVE_VERSION_TAG))
156 return 0;
157 if (!PyType_HasFeature(type, Py_TPFLAGS_READY))
158 return 0;
Christian Heimesa62da1d2008-01-12 19:39:10 +0000159
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000160 type->tp_version_tag = next_version_tag++;
161 /* for stress-testing: next_version_tag &= 0xFF; */
Christian Heimesa62da1d2008-01-12 19:39:10 +0000162
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000163 if (type->tp_version_tag == 0) {
164 /* wrap-around or just starting Python - clear the whole
165 cache by filling names with references to Py_None.
166 Values are also set to NULL for added protection, as they
167 are borrowed reference */
168 for (i = 0; i < (1 << MCACHE_SIZE_EXP); i++) {
169 method_cache[i].value = NULL;
170 Py_XDECREF(method_cache[i].name);
171 method_cache[i].name = Py_None;
172 Py_INCREF(Py_None);
173 }
174 /* mark all version tags as invalid */
175 PyType_Modified(&PyBaseObject_Type);
176 return 1;
177 }
178 bases = type->tp_bases;
179 n = PyTuple_GET_SIZE(bases);
180 for (i = 0; i < n; i++) {
181 PyObject *b = PyTuple_GET_ITEM(bases, i);
182 assert(PyType_Check(b));
183 if (!assign_version_tag((PyTypeObject *)b))
184 return 0;
185 }
186 type->tp_flags |= Py_TPFLAGS_VALID_VERSION_TAG;
187 return 1;
Christian Heimesa62da1d2008-01-12 19:39:10 +0000188}
189
190
Guido van Rossum6f799372001-09-20 20:46:19 +0000191static PyMemberDef type_members[] = {
Benjamin Peterson0e102062010-08-25 23:13:17 +0000192 {"__basicsize__", T_PYSSIZET, offsetof(PyTypeObject,tp_basicsize),READONLY},
193 {"__itemsize__", T_PYSSIZET, offsetof(PyTypeObject, tp_itemsize), READONLY},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000194 {"__flags__", T_LONG, offsetof(PyTypeObject, tp_flags), READONLY},
195 {"__weakrefoffset__", T_LONG,
196 offsetof(PyTypeObject, tp_weaklistoffset), READONLY},
197 {"__base__", T_OBJECT, offsetof(PyTypeObject, tp_base), READONLY},
198 {"__dictoffset__", T_LONG,
199 offsetof(PyTypeObject, tp_dictoffset), READONLY},
200 {"__mro__", T_OBJECT, offsetof(PyTypeObject, tp_mro), READONLY},
201 {0}
Tim Peters6d6c1a32001-08-02 04:15:00 +0000202};
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000203
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000204static PyObject *
Guido van Rossumc3542212001-08-16 09:18:56 +0000205type_name(PyTypeObject *type, void *context)
206{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000207 const char *s;
Guido van Rossumc3542212001-08-16 09:18:56 +0000208
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000209 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
210 PyHeapTypeObject* et = (PyHeapTypeObject*)type;
Tim Petersea7f75d2002-12-07 21:39:16 +0000211
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000212 Py_INCREF(et->ht_name);
213 return et->ht_name;
214 }
215 else {
216 s = strrchr(type->tp_name, '.');
217 if (s == NULL)
218 s = type->tp_name;
219 else
220 s++;
221 return PyUnicode_FromString(s);
222 }
Guido van Rossumc3542212001-08-16 09:18:56 +0000223}
224
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000225static int
226type_set_name(PyTypeObject *type, PyObject *value, void *context)
227{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000228 PyHeapTypeObject* et;
229 char *tp_name;
230 PyObject *tmp;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000231
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000232 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
233 PyErr_Format(PyExc_TypeError,
234 "can't set %s.__name__", type->tp_name);
235 return -1;
236 }
237 if (!value) {
238 PyErr_Format(PyExc_TypeError,
239 "can't delete %s.__name__", type->tp_name);
240 return -1;
241 }
242 if (!PyUnicode_Check(value)) {
243 PyErr_Format(PyExc_TypeError,
244 "can only assign string to %s.__name__, not '%s'",
245 type->tp_name, Py_TYPE(value)->tp_name);
246 return -1;
247 }
Guido van Rossume845c0f2007-11-02 23:07:07 +0000248
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000249 /* Check absence of null characters */
250 tmp = PyUnicode_FromStringAndSize("\0", 1);
251 if (tmp == NULL)
252 return -1;
253 if (PyUnicode_Contains(value, tmp) != 0) {
254 Py_DECREF(tmp);
255 PyErr_Format(PyExc_ValueError,
256 "__name__ must not contain null bytes");
257 return -1;
258 }
259 Py_DECREF(tmp);
Guido van Rossume845c0f2007-11-02 23:07:07 +0000260
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000261 tp_name = _PyUnicode_AsString(value);
262 if (tp_name == NULL)
263 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000264
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000265 et = (PyHeapTypeObject*)type;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000266
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000267 Py_INCREF(value);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000268
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000269 Py_DECREF(et->ht_name);
270 et->ht_name = value;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000271
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000272 type->tp_name = tp_name;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000273
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000274 return 0;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000275}
276
Guido van Rossumc3542212001-08-16 09:18:56 +0000277static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000278type_module(PyTypeObject *type, void *context)
Guido van Rossum29ca26e1995-01-07 11:58:15 +0000279{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000280 PyObject *mod;
281 char *s;
Guido van Rossumc3542212001-08-16 09:18:56 +0000282
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000283 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
284 mod = PyDict_GetItemString(type->tp_dict, "__module__");
285 if (!mod) {
286 PyErr_Format(PyExc_AttributeError, "__module__");
287 return 0;
288 }
289 Py_XINCREF(mod);
290 return mod;
291 }
292 else {
293 s = strrchr(type->tp_name, '.');
294 if (s != NULL)
295 return PyUnicode_FromStringAndSize(
296 type->tp_name, (Py_ssize_t)(s - type->tp_name));
297 return PyUnicode_FromString("builtins");
298 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000299}
300
Guido van Rossum3926a632001-09-25 16:25:58 +0000301static int
302type_set_module(PyTypeObject *type, PyObject *value, void *context)
303{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000304 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
305 PyErr_Format(PyExc_TypeError,
306 "can't set %s.__module__", type->tp_name);
307 return -1;
308 }
309 if (!value) {
310 PyErr_Format(PyExc_TypeError,
311 "can't delete %s.__module__", type->tp_name);
312 return -1;
313 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000314
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000315 PyType_Modified(type);
Christian Heimesa62da1d2008-01-12 19:39:10 +0000316
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000317 return PyDict_SetItemString(type->tp_dict, "__module__", value);
Guido van Rossum3926a632001-09-25 16:25:58 +0000318}
319
Tim Peters6d6c1a32001-08-02 04:15:00 +0000320static PyObject *
Christian Heimes9e7f1d22008-02-28 12:27:11 +0000321type_abstractmethods(PyTypeObject *type, void *context)
322{
Benjamin Petersonaec5fd12010-10-02 00:03:31 +0000323 PyObject *mod = NULL;
Benjamin Peterson84060b82010-10-03 02:13:39 +0000324 /* type itself has an __abstractmethods__ descriptor (this). Don't return
325 that. */
Benjamin Petersonaec5fd12010-10-02 00:03:31 +0000326 if (type != &PyType_Type)
327 mod = PyDict_GetItemString(type->tp_dict, "__abstractmethods__");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000328 if (!mod) {
Benjamin Peterson23b628e2011-01-12 18:56:07 +0000329 PyErr_SetString(PyExc_AttributeError, "__abstractmethods__");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000330 return NULL;
331 }
332 Py_XINCREF(mod);
333 return mod;
Christian Heimes9e7f1d22008-02-28 12:27:11 +0000334}
335
336static int
337type_set_abstractmethods(PyTypeObject *type, PyObject *value, void *context)
338{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000339 /* __abstractmethods__ should only be set once on a type, in
340 abc.ABCMeta.__new__, so this function doesn't do anything
341 special to update subclasses.
342 */
Antoine Pitrou6f430e42012-08-15 23:18:25 +0200343 int abstract, res;
Benjamin Peterson477ba912011-01-12 15:34:01 +0000344 if (value != NULL) {
Antoine Pitrou6f430e42012-08-15 23:18:25 +0200345 abstract = PyObject_IsTrue(value);
346 if (abstract < 0)
347 return -1;
Benjamin Peterson477ba912011-01-12 15:34:01 +0000348 res = PyDict_SetItemString(type->tp_dict, "__abstractmethods__", value);
349 }
350 else {
Antoine Pitrou6f430e42012-08-15 23:18:25 +0200351 abstract = 0;
Benjamin Peterson477ba912011-01-12 15:34:01 +0000352 res = PyDict_DelItemString(type->tp_dict, "__abstractmethods__");
353 if (res && PyErr_ExceptionMatches(PyExc_KeyError)) {
Benjamin Peterson23b628e2011-01-12 18:56:07 +0000354 PyErr_SetString(PyExc_AttributeError, "__abstractmethods__");
Benjamin Peterson477ba912011-01-12 15:34:01 +0000355 return -1;
356 }
357 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000358 if (res == 0) {
359 PyType_Modified(type);
Antoine Pitrou6f430e42012-08-15 23:18:25 +0200360 if (abstract)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000361 type->tp_flags |= Py_TPFLAGS_IS_ABSTRACT;
Antoine Pitrou6f430e42012-08-15 23:18:25 +0200362 else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000363 type->tp_flags &= ~Py_TPFLAGS_IS_ABSTRACT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000364 }
365 return res;
Christian Heimes9e7f1d22008-02-28 12:27:11 +0000366}
367
368static PyObject *
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000369type_get_bases(PyTypeObject *type, void *context)
370{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000371 Py_INCREF(type->tp_bases);
372 return type->tp_bases;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000373}
374
375static PyTypeObject *best_base(PyObject *);
376static int mro_internal(PyTypeObject *);
377static int compatible_for_assignment(PyTypeObject *, PyTypeObject *, char *);
378static int add_subclass(PyTypeObject*, PyTypeObject*);
379static void remove_subclass(PyTypeObject *, PyTypeObject *);
380static void update_all_slots(PyTypeObject *);
381
Guido van Rossum8d24ee92003-03-24 23:49:49 +0000382typedef int (*update_callback)(PyTypeObject *, void *);
383static int update_subclasses(PyTypeObject *type, PyObject *name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000384 update_callback callback, void *data);
Guido van Rossum8d24ee92003-03-24 23:49:49 +0000385static int recurse_down_subclasses(PyTypeObject *type, PyObject *name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000386 update_callback callback, void *data);
Guido van Rossum8d24ee92003-03-24 23:49:49 +0000387
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000388static int
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000389mro_subclasses(PyTypeObject *type, PyObject* temp)
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000390{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000391 PyTypeObject *subclass;
392 PyObject *ref, *subclasses, *old_mro;
393 Py_ssize_t i, n;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000394
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000395 subclasses = type->tp_subclasses;
396 if (subclasses == NULL)
397 return 0;
398 assert(PyList_Check(subclasses));
399 n = PyList_GET_SIZE(subclasses);
400 for (i = 0; i < n; i++) {
401 ref = PyList_GET_ITEM(subclasses, i);
402 assert(PyWeakref_CheckRef(ref));
403 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
404 assert(subclass != NULL);
405 if ((PyObject *)subclass == Py_None)
406 continue;
407 assert(PyType_Check(subclass));
408 old_mro = subclass->tp_mro;
409 if (mro_internal(subclass) < 0) {
410 subclass->tp_mro = old_mro;
411 return -1;
412 }
413 else {
414 PyObject* tuple;
415 tuple = PyTuple_Pack(2, subclass, old_mro);
416 Py_DECREF(old_mro);
417 if (!tuple)
418 return -1;
419 if (PyList_Append(temp, tuple) < 0)
420 return -1;
421 Py_DECREF(tuple);
422 }
423 if (mro_subclasses(subclass, temp) < 0)
424 return -1;
425 }
426 return 0;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000427}
428
429static int
430type_set_bases(PyTypeObject *type, PyObject *value, void *context)
431{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000432 Py_ssize_t i;
433 int r = 0;
434 PyObject *ob, *temp;
435 PyTypeObject *new_base, *old_base;
436 PyObject *old_bases, *old_mro;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000437
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000438 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
439 PyErr_Format(PyExc_TypeError,
440 "can't set %s.__bases__", type->tp_name);
441 return -1;
442 }
443 if (!value) {
444 PyErr_Format(PyExc_TypeError,
445 "can't delete %s.__bases__", type->tp_name);
446 return -1;
447 }
448 if (!PyTuple_Check(value)) {
449 PyErr_Format(PyExc_TypeError,
450 "can only assign tuple to %s.__bases__, not %s",
451 type->tp_name, Py_TYPE(value)->tp_name);
452 return -1;
453 }
454 if (PyTuple_GET_SIZE(value) == 0) {
455 PyErr_Format(PyExc_TypeError,
456 "can only assign non-empty tuple to %s.__bases__, not ()",
457 type->tp_name);
458 return -1;
459 }
460 for (i = 0; i < PyTuple_GET_SIZE(value); i++) {
461 ob = PyTuple_GET_ITEM(value, i);
462 if (!PyType_Check(ob)) {
Benjamin Petersonb6af60c2012-04-01 18:49:54 -0400463 PyErr_Format(PyExc_TypeError,
464 "%s.__bases__ must be tuple of old- or "
465 "new-style classes, not '%s'",
466 type->tp_name, Py_TYPE(ob)->tp_name);
467 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000468 }
Benjamin Peterson3471bb62012-04-01 18:48:40 -0400469 if (PyType_IsSubtype((PyTypeObject*)ob, type)) {
470 PyErr_SetString(PyExc_TypeError,
471 "a __bases__ item causes an inheritance cycle");
472 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000473 }
474 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000475
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000476 new_base = best_base(value);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000477
Benjamin Petersonab3c1c12012-04-01 18:48:02 -0400478 if (!new_base)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000479 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000480
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000481 if (!compatible_for_assignment(type->tp_base, new_base, "__bases__"))
482 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000483
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000484 Py_INCREF(new_base);
485 Py_INCREF(value);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000486
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000487 old_bases = type->tp_bases;
488 old_base = type->tp_base;
489 old_mro = type->tp_mro;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000490
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000491 type->tp_bases = value;
492 type->tp_base = new_base;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000493
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000494 if (mro_internal(type) < 0) {
495 goto bail;
496 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000497
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000498 temp = PyList_New(0);
499 if (!temp)
500 goto bail;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000501
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000502 r = mro_subclasses(type, temp);
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000503
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000504 if (r < 0) {
505 for (i = 0; i < PyList_Size(temp); i++) {
506 PyTypeObject* cls;
507 PyObject* mro;
508 PyArg_UnpackTuple(PyList_GET_ITEM(temp, i),
509 "", 2, 2, &cls, &mro);
510 Py_INCREF(mro);
511 ob = cls->tp_mro;
512 cls->tp_mro = mro;
513 Py_DECREF(ob);
514 }
515 Py_DECREF(temp);
516 goto bail;
517 }
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000518
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000519 Py_DECREF(temp);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000520
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000521 /* any base that was in __bases__ but now isn't, we
522 need to remove |type| from its tp_subclasses.
523 conversely, any class now in __bases__ that wasn't
524 needs to have |type| added to its subclasses. */
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000525
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000526 /* for now, sod that: just remove from all old_bases,
527 add to all new_bases */
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000528
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000529 for (i = PyTuple_GET_SIZE(old_bases) - 1; i >= 0; i--) {
530 ob = PyTuple_GET_ITEM(old_bases, i);
531 if (PyType_Check(ob)) {
532 remove_subclass(
533 (PyTypeObject*)ob, type);
534 }
535 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000536
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000537 for (i = PyTuple_GET_SIZE(value) - 1; i >= 0; i--) {
538 ob = PyTuple_GET_ITEM(value, i);
539 if (PyType_Check(ob)) {
540 if (add_subclass((PyTypeObject*)ob, type) < 0)
541 r = -1;
542 }
543 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000544
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000545 update_all_slots(type);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000546
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000547 Py_DECREF(old_bases);
548 Py_DECREF(old_base);
549 Py_DECREF(old_mro);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000550
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000551 return r;
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000552
553 bail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000554 Py_DECREF(type->tp_bases);
555 Py_DECREF(type->tp_base);
556 if (type->tp_mro != old_mro) {
557 Py_DECREF(type->tp_mro);
558 }
Michael W. Hudsone723e452003-08-07 14:58:10 +0000559
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000560 type->tp_bases = old_bases;
561 type->tp_base = old_base;
562 type->tp_mro = old_mro;
Tim Petersea7f75d2002-12-07 21:39:16 +0000563
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000564 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000565}
566
567static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000568type_dict(PyTypeObject *type, void *context)
569{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000570 if (type->tp_dict == NULL) {
571 Py_INCREF(Py_None);
572 return Py_None;
573 }
574 return PyDictProxy_New(type->tp_dict);
Guido van Rossum29ca26e1995-01-07 11:58:15 +0000575}
576
Tim Peters24008312002-03-17 18:56:20 +0000577static PyObject *
578type_get_doc(PyTypeObject *type, void *context)
579{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000580 PyObject *result;
581 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE) && type->tp_doc != NULL)
582 return PyUnicode_FromString(type->tp_doc);
583 result = PyDict_GetItemString(type->tp_dict, "__doc__");
584 if (result == NULL) {
585 result = Py_None;
586 Py_INCREF(result);
587 }
588 else if (Py_TYPE(result)->tp_descr_get) {
589 result = Py_TYPE(result)->tp_descr_get(result, NULL,
590 (PyObject *)type);
591 }
592 else {
593 Py_INCREF(result);
594 }
595 return result;
Tim Peters24008312002-03-17 18:56:20 +0000596}
597
Antoine Pitrouec569b72008-08-26 22:40:48 +0000598static PyObject *
599type___instancecheck__(PyObject *type, PyObject *inst)
600{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000601 switch (_PyObject_RealIsInstance(inst, type)) {
602 case -1:
603 return NULL;
604 case 0:
605 Py_RETURN_FALSE;
606 default:
607 Py_RETURN_TRUE;
608 }
Antoine Pitrouec569b72008-08-26 22:40:48 +0000609}
610
611
612static PyObject *
Antoine Pitrouec569b72008-08-26 22:40:48 +0000613type___subclasscheck__(PyObject *type, PyObject *inst)
614{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000615 switch (_PyObject_RealIsSubclass(inst, type)) {
616 case -1:
617 return NULL;
618 case 0:
619 Py_RETURN_FALSE;
620 default:
621 Py_RETURN_TRUE;
622 }
Antoine Pitrouec569b72008-08-26 22:40:48 +0000623}
624
Antoine Pitrouec569b72008-08-26 22:40:48 +0000625
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000626static PyGetSetDef type_getsets[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000627 {"__name__", (getter)type_name, (setter)type_set_name, NULL},
628 {"__bases__", (getter)type_get_bases, (setter)type_set_bases, NULL},
629 {"__module__", (getter)type_module, (setter)type_set_module, NULL},
630 {"__abstractmethods__", (getter)type_abstractmethods,
631 (setter)type_set_abstractmethods, NULL},
632 {"__dict__", (getter)type_dict, NULL, NULL},
633 {"__doc__", (getter)type_get_doc, NULL, NULL},
634 {0}
Tim Peters6d6c1a32001-08-02 04:15:00 +0000635};
636
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000637static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000638type_repr(PyTypeObject *type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000639{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000640 PyObject *mod, *name, *rtn;
Guido van Rossumc3542212001-08-16 09:18:56 +0000641
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000642 mod = type_module(type, NULL);
643 if (mod == NULL)
644 PyErr_Clear();
645 else if (!PyUnicode_Check(mod)) {
646 Py_DECREF(mod);
647 mod = NULL;
648 }
649 name = type_name(type, NULL);
Christian Heimesa0e7e412012-09-10 03:00:14 +0200650 if (name == NULL) {
651 Py_XDECREF(mod);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000652 return NULL;
Christian Heimesa0e7e412012-09-10 03:00:14 +0200653 }
Barry Warsaw7ce36942001-08-24 18:34:26 +0000654
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000655 if (mod != NULL && PyUnicode_CompareWithASCIIString(mod, "builtins"))
656 rtn = PyUnicode_FromFormat("<class '%U.%U'>", mod, name);
657 else
658 rtn = PyUnicode_FromFormat("<class '%s'>", type->tp_name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000659
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000660 Py_XDECREF(mod);
661 Py_DECREF(name);
662 return rtn;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000663}
664
Tim Peters6d6c1a32001-08-02 04:15:00 +0000665static PyObject *
666type_call(PyTypeObject *type, PyObject *args, PyObject *kwds)
667{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000668 PyObject *obj;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000669
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000670 if (type->tp_new == NULL) {
671 PyErr_Format(PyExc_TypeError,
672 "cannot create '%.100s' instances",
673 type->tp_name);
674 return NULL;
675 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000676
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000677 obj = type->tp_new(type, args, kwds);
678 if (obj != NULL) {
679 /* Ugly exception: when the call was type(something),
680 don't call tp_init on the result. */
681 if (type == &PyType_Type &&
682 PyTuple_Check(args) && PyTuple_GET_SIZE(args) == 1 &&
683 (kwds == NULL ||
684 (PyDict_Check(kwds) && PyDict_Size(kwds) == 0)))
685 return obj;
686 /* If the returned object is not an instance of type,
687 it won't be initialized. */
688 if (!PyType_IsSubtype(Py_TYPE(obj), type))
689 return obj;
690 type = Py_TYPE(obj);
691 if (type->tp_init != NULL &&
692 type->tp_init(obj, args, kwds) < 0) {
693 Py_DECREF(obj);
694 obj = NULL;
695 }
696 }
697 return obj;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000698}
699
700PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000701PyType_GenericAlloc(PyTypeObject *type, Py_ssize_t nitems)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000702{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000703 PyObject *obj;
704 const size_t size = _PyObject_VAR_SIZE(type, nitems+1);
705 /* note that we need to add one, for the sentinel */
Tim Peters406fe3b2001-10-06 19:04:01 +0000706
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000707 if (PyType_IS_GC(type))
708 obj = _PyObject_GC_Malloc(size);
709 else
710 obj = (PyObject *)PyObject_MALLOC(size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000711
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000712 if (obj == NULL)
713 return PyErr_NoMemory();
Tim Peters406fe3b2001-10-06 19:04:01 +0000714
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000715 memset(obj, '\0', size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000716
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000717 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
718 Py_INCREF(type);
Tim Peters406fe3b2001-10-06 19:04:01 +0000719
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000720 if (type->tp_itemsize == 0)
721 PyObject_INIT(obj, type);
722 else
723 (void) PyObject_INIT_VAR((PyVarObject *)obj, type, nitems);
Tim Peters406fe3b2001-10-06 19:04:01 +0000724
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000725 if (PyType_IS_GC(type))
726 _PyObject_GC_TRACK(obj);
727 return obj;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000728}
729
730PyObject *
731PyType_GenericNew(PyTypeObject *type, PyObject *args, PyObject *kwds)
732{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000733 return type->tp_alloc(type, 0);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000734}
735
Guido van Rossum9475a232001-10-05 20:51:39 +0000736/* Helpers for subtyping */
737
738static int
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000739traverse_slots(PyTypeObject *type, PyObject *self, visitproc visit, void *arg)
740{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000741 Py_ssize_t i, n;
742 PyMemberDef *mp;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000743
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000744 n = Py_SIZE(type);
745 mp = PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type);
746 for (i = 0; i < n; i++, mp++) {
747 if (mp->type == T_OBJECT_EX) {
748 char *addr = (char *)self + mp->offset;
749 PyObject *obj = *(PyObject **)addr;
750 if (obj != NULL) {
751 int err = visit(obj, arg);
752 if (err)
753 return err;
754 }
755 }
756 }
757 return 0;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000758}
759
760static int
Guido van Rossum9475a232001-10-05 20:51:39 +0000761subtype_traverse(PyObject *self, visitproc visit, void *arg)
762{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000763 PyTypeObject *type, *base;
764 traverseproc basetraverse;
Guido van Rossum9475a232001-10-05 20:51:39 +0000765
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000766 /* Find the nearest base with a different tp_traverse,
767 and traverse slots while we're at it */
768 type = Py_TYPE(self);
769 base = type;
770 while ((basetraverse = base->tp_traverse) == subtype_traverse) {
771 if (Py_SIZE(base)) {
772 int err = traverse_slots(base, self, visit, arg);
773 if (err)
774 return err;
775 }
776 base = base->tp_base;
777 assert(base);
778 }
Guido van Rossum9475a232001-10-05 20:51:39 +0000779
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000780 if (type->tp_dictoffset != base->tp_dictoffset) {
781 PyObject **dictptr = _PyObject_GetDictPtr(self);
782 if (dictptr && *dictptr)
783 Py_VISIT(*dictptr);
784 }
Guido van Rossum9475a232001-10-05 20:51:39 +0000785
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000786 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
787 /* For a heaptype, the instances count as references
788 to the type. Traverse the type so the collector
789 can find cycles involving this link. */
790 Py_VISIT(type);
Guido van Rossuma3862092002-06-10 15:24:42 +0000791
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000792 if (basetraverse)
793 return basetraverse(self, visit, arg);
794 return 0;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000795}
796
797static void
798clear_slots(PyTypeObject *type, PyObject *self)
799{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000800 Py_ssize_t i, n;
801 PyMemberDef *mp;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000802
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000803 n = Py_SIZE(type);
804 mp = PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type);
805 for (i = 0; i < n; i++, mp++) {
806 if (mp->type == T_OBJECT_EX && !(mp->flags & READONLY)) {
807 char *addr = (char *)self + mp->offset;
808 PyObject *obj = *(PyObject **)addr;
809 if (obj != NULL) {
810 *(PyObject **)addr = NULL;
811 Py_DECREF(obj);
812 }
813 }
814 }
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000815}
816
817static int
818subtype_clear(PyObject *self)
819{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000820 PyTypeObject *type, *base;
821 inquiry baseclear;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000822
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000823 /* Find the nearest base with a different tp_clear
824 and clear slots while we're at it */
825 type = Py_TYPE(self);
826 base = type;
827 while ((baseclear = base->tp_clear) == subtype_clear) {
828 if (Py_SIZE(base))
829 clear_slots(base, self);
830 base = base->tp_base;
831 assert(base);
832 }
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000833
Benjamin Peterson52c42432012-03-07 18:41:11 -0600834 /* Clear the instance dict (if any), to break cycles involving only
835 __dict__ slots (as in the case 'self.__dict__ is self'). */
836 if (type->tp_dictoffset != base->tp_dictoffset) {
837 PyObject **dictptr = _PyObject_GetDictPtr(self);
838 if (dictptr && *dictptr)
839 Py_CLEAR(*dictptr);
840 }
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000841
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000842 if (baseclear)
843 return baseclear(self);
844 return 0;
Guido van Rossum9475a232001-10-05 20:51:39 +0000845}
Tim Peters6d6c1a32001-08-02 04:15:00 +0000846
847static void
848subtype_dealloc(PyObject *self)
849{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000850 PyTypeObject *type, *base;
851 destructor basedealloc;
Antoine Pitrou56cd62c2012-09-06 00:59:49 +0200852 PyThreadState *tstate = PyThreadState_GET();
Tim Peters6d6c1a32001-08-02 04:15:00 +0000853
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000854 /* Extract the type; we expect it to be a heap type */
855 type = Py_TYPE(self);
856 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000857
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000858 /* Test whether the type has GC exactly once */
Guido van Rossum22b13872002-08-06 21:41:44 +0000859
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000860 if (!PyType_IS_GC(type)) {
861 /* It's really rare to find a dynamic type that doesn't have
862 GC; it can only happen when deriving from 'object' and not
863 adding any slots or instance variables. This allows
864 certain simplifications: there's no need to call
865 clear_slots(), or DECREF the dict, or clear weakrefs. */
Guido van Rossum22b13872002-08-06 21:41:44 +0000866
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000867 /* Maybe call finalizer; exit early if resurrected */
868 if (type->tp_del) {
869 type->tp_del(self);
870 if (self->ob_refcnt > 0)
871 return;
872 }
Guido van Rossum22b13872002-08-06 21:41:44 +0000873
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000874 /* Find the nearest base with a different tp_dealloc */
875 base = type;
876 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
877 assert(Py_SIZE(base) == 0);
878 base = base->tp_base;
879 assert(base);
880 }
Guido van Rossum22b13872002-08-06 21:41:44 +0000881
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000882 /* Extract the type again; tp_del may have changed it */
883 type = Py_TYPE(self);
Benjamin Peterson193152c2009-04-25 01:08:45 +0000884
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000885 /* Call the base tp_dealloc() */
886 assert(basedealloc);
887 basedealloc(self);
Guido van Rossum22b13872002-08-06 21:41:44 +0000888
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000889 /* Can't reference self beyond this point */
890 Py_DECREF(type);
Guido van Rossum22b13872002-08-06 21:41:44 +0000891
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000892 /* Done */
893 return;
894 }
Guido van Rossum22b13872002-08-06 21:41:44 +0000895
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000896 /* We get here only if the type has GC */
Guido van Rossum22b13872002-08-06 21:41:44 +0000897
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000898 /* UnTrack and re-Track around the trashcan macro, alas */
899 /* See explanation at end of function for full disclosure */
900 PyObject_GC_UnTrack(self);
901 ++_PyTrash_delete_nesting;
Antoine Pitrou56cd62c2012-09-06 00:59:49 +0200902 ++ tstate->trash_delete_nesting;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000903 Py_TRASHCAN_SAFE_BEGIN(self);
904 --_PyTrash_delete_nesting;
Antoine Pitrou56cd62c2012-09-06 00:59:49 +0200905 -- tstate->trash_delete_nesting;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000906 /* DO NOT restore GC tracking at this point. weakref callbacks
907 * (if any, and whether directly here or indirectly in something we
908 * call) may trigger GC, and if self is tracked at that point, it
909 * will look like trash to GC and GC will try to delete self again.
910 */
Guido van Rossum22b13872002-08-06 21:41:44 +0000911
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000912 /* Find the nearest base with a different tp_dealloc */
913 base = type;
914 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
915 base = base->tp_base;
916 assert(base);
917 }
Guido van Rossum14227b42001-12-06 02:35:58 +0000918
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000919 /* If we added a weaklist, we clear it. Do this *before* calling
920 the finalizer (__del__), clearing slots, or clearing the instance
921 dict. */
Guido van Rossum59195fd2003-06-13 20:54:40 +0000922
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000923 if (type->tp_weaklistoffset && !base->tp_weaklistoffset)
924 PyObject_ClearWeakRefs(self);
Guido van Rossum1987c662003-05-29 14:29:23 +0000925
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000926 /* Maybe call finalizer; exit early if resurrected */
927 if (type->tp_del) {
928 _PyObject_GC_TRACK(self);
929 type->tp_del(self);
930 if (self->ob_refcnt > 0)
931 goto endlabel; /* resurrected */
932 else
933 _PyObject_GC_UNTRACK(self);
934 /* New weakrefs could be created during the finalizer call.
935 If this occurs, clear them out without calling their
936 finalizers since they might rely on part of the object
937 being finalized that has already been destroyed. */
938 if (type->tp_weaklistoffset && !base->tp_weaklistoffset) {
939 /* Modeled after GET_WEAKREFS_LISTPTR() */
940 PyWeakReference **list = (PyWeakReference **) \
941 PyObject_GET_WEAKREFS_LISTPTR(self);
942 while (*list)
943 _PyWeakref_ClearRef(*list);
944 }
945 }
Guido van Rossum1987c662003-05-29 14:29:23 +0000946
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000947 /* Clear slots up to the nearest base with a different tp_dealloc */
948 base = type;
949 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
950 if (Py_SIZE(base))
951 clear_slots(base, self);
952 base = base->tp_base;
953 assert(base);
954 }
Guido van Rossum59195fd2003-06-13 20:54:40 +0000955
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000956 /* If we added a dict, DECREF it */
957 if (type->tp_dictoffset && !base->tp_dictoffset) {
958 PyObject **dictptr = _PyObject_GetDictPtr(self);
959 if (dictptr != NULL) {
960 PyObject *dict = *dictptr;
961 if (dict != NULL) {
962 Py_DECREF(dict);
963 *dictptr = NULL;
964 }
965 }
966 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000967
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000968 /* Extract the type again; tp_del may have changed it */
969 type = Py_TYPE(self);
Benjamin Peterson193152c2009-04-25 01:08:45 +0000970
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000971 /* Call the base tp_dealloc(); first retrack self if
972 * basedealloc knows about gc.
973 */
974 if (PyType_IS_GC(base))
975 _PyObject_GC_TRACK(self);
976 assert(basedealloc);
977 basedealloc(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000978
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000979 /* Can't reference self beyond this point */
980 Py_DECREF(type);
Guido van Rossum22b13872002-08-06 21:41:44 +0000981
Guido van Rossum0906e072002-08-07 20:42:09 +0000982 endlabel:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000983 ++_PyTrash_delete_nesting;
Antoine Pitrou56cd62c2012-09-06 00:59:49 +0200984 ++ tstate->trash_delete_nesting;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000985 Py_TRASHCAN_SAFE_END(self);
986 --_PyTrash_delete_nesting;
Antoine Pitrou56cd62c2012-09-06 00:59:49 +0200987 -- tstate->trash_delete_nesting;
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000988
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000989 /* Explanation of the weirdness around the trashcan macros:
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000990
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000991 Q. What do the trashcan macros do?
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000992
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000993 A. Read the comment titled "Trashcan mechanism" in object.h.
994 For one, this explains why there must be a call to GC-untrack
995 before the trashcan begin macro. Without understanding the
996 trashcan code, the answers to the following questions don't make
997 sense.
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000998
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000999 Q. Why do we GC-untrack before the trashcan and then immediately
1000 GC-track again afterward?
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001001
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001002 A. In the case that the base class is GC-aware, the base class
1003 probably GC-untracks the object. If it does that using the
1004 UNTRACK macro, this will crash when the object is already
1005 untracked. Because we don't know what the base class does, the
1006 only safe thing is to make sure the object is tracked when we
1007 call the base class dealloc. But... The trashcan begin macro
1008 requires that the object is *untracked* before it is called. So
1009 the dance becomes:
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001010
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001011 GC untrack
1012 trashcan begin
1013 GC track
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001014
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001015 Q. Why did the last question say "immediately GC-track again"?
1016 It's nowhere near immediately.
Tim Petersf7f9e992003-11-13 21:59:32 +00001017
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001018 A. Because the code *used* to re-track immediately. Bad Idea.
1019 self has a refcount of 0, and if gc ever gets its hands on it
1020 (which can happen if any weakref callback gets invoked), it
1021 looks like trash to gc too, and gc also tries to delete self
Ezio Melotti13925002011-03-16 11:05:33 +02001022 then. But we're already deleting self. Double deallocation is
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001023 a subtle disaster.
Tim Petersf7f9e992003-11-13 21:59:32 +00001024
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001025 Q. Why the bizarre (net-zero) manipulation of
1026 _PyTrash_delete_nesting around the trashcan macros?
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001027
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001028 A. Some base classes (e.g. list) also use the trashcan mechanism.
1029 The following scenario used to be possible:
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001030
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001031 - suppose the trashcan level is one below the trashcan limit
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001032
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001033 - subtype_dealloc() is called
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001034
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001035 - the trashcan limit is not yet reached, so the trashcan level
1036 is incremented and the code between trashcan begin and end is
1037 executed
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001038
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001039 - this destroys much of the object's contents, including its
1040 slots and __dict__
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001041
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001042 - basedealloc() is called; this is really list_dealloc(), or
1043 some other type which also uses the trashcan macros
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001044
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001045 - the trashcan limit is now reached, so the object is put on the
1046 trashcan's to-be-deleted-later list
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001047
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001048 - basedealloc() returns
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001049
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001050 - subtype_dealloc() decrefs the object's type
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001051
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001052 - subtype_dealloc() returns
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001053
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001054 - later, the trashcan code starts deleting the objects from its
1055 to-be-deleted-later list
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001056
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001057 - subtype_dealloc() is called *AGAIN* for the same object
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001058
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001059 - at the very least (if the destroyed slots and __dict__ don't
1060 cause problems) the object's type gets decref'ed a second
1061 time, which is *BAD*!!!
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001062
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001063 The remedy is to make sure that if the code between trashcan
1064 begin and end in subtype_dealloc() is called, the code between
1065 trashcan begin and end in basedealloc() will also be called.
1066 This is done by decrementing the level after passing into the
1067 trashcan block, and incrementing it just before leaving the
1068 block.
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001069
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001070 But now it's possible that a chain of objects consisting solely
1071 of objects whose deallocator is subtype_dealloc() will defeat
1072 the trashcan mechanism completely: the decremented level means
1073 that the effective level never reaches the limit. Therefore, we
1074 *increment* the level *before* entering the trashcan block, and
1075 matchingly decrement it after leaving. This means the trashcan
1076 code will trigger a little early, but that's no big deal.
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001077
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001078 Q. Are there any live examples of code in need of all this
1079 complexity?
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001080
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001081 A. Yes. See SF bug 668433 for code that crashed (when Python was
1082 compiled in debug mode) before the trashcan level manipulations
1083 were added. For more discussion, see SF patches 581742, 575073
1084 and bug 574207.
1085 */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001086}
1087
Jeremy Hylton938ace62002-07-17 16:30:39 +00001088static PyTypeObject *solid_base(PyTypeObject *type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001089
Tim Peters6d6c1a32001-08-02 04:15:00 +00001090/* type test with subclassing support */
1091
1092int
1093PyType_IsSubtype(PyTypeObject *a, PyTypeObject *b)
1094{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001095 PyObject *mro;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001096
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001097 mro = a->tp_mro;
1098 if (mro != NULL) {
1099 /* Deal with multiple inheritance without recursion
1100 by walking the MRO tuple */
1101 Py_ssize_t i, n;
1102 assert(PyTuple_Check(mro));
1103 n = PyTuple_GET_SIZE(mro);
1104 for (i = 0; i < n; i++) {
1105 if (PyTuple_GET_ITEM(mro, i) == (PyObject *)b)
1106 return 1;
1107 }
1108 return 0;
1109 }
1110 else {
1111 /* a is not completely initilized yet; follow tp_base */
1112 do {
1113 if (a == b)
1114 return 1;
1115 a = a->tp_base;
1116 } while (a != NULL);
1117 return b == &PyBaseObject_Type;
1118 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001119}
1120
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001121/* Internal routines to do a method lookup in the type
Guido van Rossum60718732001-08-28 17:47:51 +00001122 without looking in the instance dictionary
1123 (so we can't use PyObject_GetAttr) but still binding
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001124 it to the instance. The arguments are the object,
Guido van Rossum60718732001-08-28 17:47:51 +00001125 the method name as a C string, and the address of a
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001126 static variable used to cache the interned Python string.
1127
1128 Two variants:
1129
1130 - lookup_maybe() returns NULL without raising an exception
1131 when the _PyType_Lookup() call fails;
1132
1133 - lookup_method() always raises an exception upon errors.
Benjamin Peterson224205f2009-05-08 03:25:19 +00001134
1135 - _PyObject_LookupSpecial() exported for the benefit of other places.
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001136*/
Guido van Rossum60718732001-08-28 17:47:51 +00001137
1138static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001139lookup_maybe(PyObject *self, char *attrstr, PyObject **attrobj)
Guido van Rossum60718732001-08-28 17:47:51 +00001140{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001141 PyObject *res;
Guido van Rossum60718732001-08-28 17:47:51 +00001142
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001143 if (*attrobj == NULL) {
1144 *attrobj = PyUnicode_InternFromString(attrstr);
1145 if (*attrobj == NULL)
1146 return NULL;
1147 }
1148 res = _PyType_Lookup(Py_TYPE(self), *attrobj);
1149 if (res != NULL) {
1150 descrgetfunc f;
1151 if ((f = Py_TYPE(res)->tp_descr_get) == NULL)
1152 Py_INCREF(res);
1153 else
1154 res = f(res, self, (PyObject *)(Py_TYPE(self)));
1155 }
1156 return res;
Guido van Rossum60718732001-08-28 17:47:51 +00001157}
1158
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001159static PyObject *
1160lookup_method(PyObject *self, char *attrstr, PyObject **attrobj)
1161{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001162 PyObject *res = lookup_maybe(self, attrstr, attrobj);
1163 if (res == NULL && !PyErr_Occurred())
1164 PyErr_SetObject(PyExc_AttributeError, *attrobj);
1165 return res;
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001166}
1167
Benjamin Peterson224205f2009-05-08 03:25:19 +00001168PyObject *
1169_PyObject_LookupSpecial(PyObject *self, char *attrstr, PyObject **attrobj)
1170{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001171 return lookup_maybe(self, attrstr, attrobj);
Benjamin Peterson224205f2009-05-08 03:25:19 +00001172}
1173
Guido van Rossum2730b132001-08-28 18:22:14 +00001174/* A variation of PyObject_CallMethod that uses lookup_method()
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001175 instead of PyObject_GetAttrString(). This uses the same convention
Guido van Rossum2730b132001-08-28 18:22:14 +00001176 as lookup_method to cache the interned name string object. */
1177
Neil Schemenauerf23473f2001-10-21 22:28:58 +00001178static PyObject *
Guido van Rossum2730b132001-08-28 18:22:14 +00001179call_method(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
1180{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001181 va_list va;
1182 PyObject *args, *func = 0, *retval;
1183 va_start(va, format);
Guido van Rossum2730b132001-08-28 18:22:14 +00001184
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001185 func = lookup_maybe(o, name, nameobj);
1186 if (func == NULL) {
1187 va_end(va);
1188 if (!PyErr_Occurred())
1189 PyErr_SetObject(PyExc_AttributeError, *nameobj);
1190 return NULL;
1191 }
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001192
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001193 if (format && *format)
1194 args = Py_VaBuildValue(format, va);
1195 else
1196 args = PyTuple_New(0);
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001197
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001198 va_end(va);
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001199
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001200 if (args == NULL)
1201 return NULL;
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001202
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001203 assert(PyTuple_Check(args));
1204 retval = PyObject_Call(func, args, NULL);
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001205
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001206 Py_DECREF(args);
1207 Py_DECREF(func);
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001208
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001209 return retval;
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001210}
1211
1212/* Clone of call_method() that returns NotImplemented when the lookup fails. */
1213
Neil Schemenauerf23473f2001-10-21 22:28:58 +00001214static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001215call_maybe(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
1216{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001217 va_list va;
1218 PyObject *args, *func = 0, *retval;
1219 va_start(va, format);
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001220
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001221 func = lookup_maybe(o, name, nameobj);
1222 if (func == NULL) {
1223 va_end(va);
1224 if (!PyErr_Occurred()) {
1225 Py_INCREF(Py_NotImplemented);
1226 return Py_NotImplemented;
1227 }
1228 return NULL;
1229 }
Guido van Rossum2730b132001-08-28 18:22:14 +00001230
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001231 if (format && *format)
1232 args = Py_VaBuildValue(format, va);
1233 else
1234 args = PyTuple_New(0);
Guido van Rossum2730b132001-08-28 18:22:14 +00001235
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001236 va_end(va);
Guido van Rossum2730b132001-08-28 18:22:14 +00001237
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001238 if (args == NULL)
1239 return NULL;
Guido van Rossum2730b132001-08-28 18:22:14 +00001240
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001241 assert(PyTuple_Check(args));
1242 retval = PyObject_Call(func, args, NULL);
Guido van Rossum2730b132001-08-28 18:22:14 +00001243
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001244 Py_DECREF(args);
1245 Py_DECREF(func);
Guido van Rossum2730b132001-08-28 18:22:14 +00001246
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001247 return retval;
Guido van Rossum2730b132001-08-28 18:22:14 +00001248}
1249
Tim Petersea7f75d2002-12-07 21:39:16 +00001250/*
Guido van Rossum1f121312002-11-14 19:49:16 +00001251 Method resolution order algorithm C3 described in
1252 "A Monotonic Superclass Linearization for Dylan",
1253 by Kim Barrett, Bob Cassel, Paul Haahr,
Tim Petersea7f75d2002-12-07 21:39:16 +00001254 David A. Moon, Keith Playford, and P. Tucker Withington.
Guido van Rossum1f121312002-11-14 19:49:16 +00001255 (OOPSLA 1996)
1256
Guido van Rossum98f33732002-11-25 21:36:54 +00001257 Some notes about the rules implied by C3:
1258
Tim Petersea7f75d2002-12-07 21:39:16 +00001259 No duplicate bases.
Guido van Rossum98f33732002-11-25 21:36:54 +00001260 It isn't legal to repeat a class in a list of base classes.
1261
1262 The next three properties are the 3 constraints in "C3".
1263
Tim Petersea7f75d2002-12-07 21:39:16 +00001264 Local precendece order.
Guido van Rossum98f33732002-11-25 21:36:54 +00001265 If A precedes B in C's MRO, then A will precede B in the MRO of all
1266 subclasses of C.
1267
1268 Monotonicity.
1269 The MRO of a class must be an extension without reordering of the
1270 MRO of each of its superclasses.
1271
1272 Extended Precedence Graph (EPG).
1273 Linearization is consistent if there is a path in the EPG from
1274 each class to all its successors in the linearization. See
1275 the paper for definition of EPG.
Guido van Rossum1f121312002-11-14 19:49:16 +00001276 */
1277
Tim Petersea7f75d2002-12-07 21:39:16 +00001278static int
Guido van Rossum1f121312002-11-14 19:49:16 +00001279tail_contains(PyObject *list, int whence, PyObject *o) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001280 Py_ssize_t j, size;
1281 size = PyList_GET_SIZE(list);
Guido van Rossum1f121312002-11-14 19:49:16 +00001282
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001283 for (j = whence+1; j < size; j++) {
1284 if (PyList_GET_ITEM(list, j) == o)
1285 return 1;
1286 }
1287 return 0;
Guido van Rossum1f121312002-11-14 19:49:16 +00001288}
1289
Guido van Rossum98f33732002-11-25 21:36:54 +00001290static PyObject *
1291class_name(PyObject *cls)
1292{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001293 PyObject *name = PyObject_GetAttrString(cls, "__name__");
1294 if (name == NULL) {
1295 PyErr_Clear();
1296 Py_XDECREF(name);
1297 name = PyObject_Repr(cls);
1298 }
1299 if (name == NULL)
1300 return NULL;
1301 if (!PyUnicode_Check(name)) {
1302 Py_DECREF(name);
1303 return NULL;
1304 }
1305 return name;
Guido van Rossum98f33732002-11-25 21:36:54 +00001306}
1307
1308static int
1309check_duplicates(PyObject *list)
1310{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001311 Py_ssize_t i, j, n;
1312 /* Let's use a quadratic time algorithm,
1313 assuming that the bases lists is short.
1314 */
1315 n = PyList_GET_SIZE(list);
1316 for (i = 0; i < n; i++) {
1317 PyObject *o = PyList_GET_ITEM(list, i);
1318 for (j = i + 1; j < n; j++) {
1319 if (PyList_GET_ITEM(list, j) == o) {
1320 o = class_name(o);
1321 if (o != NULL) {
1322 PyErr_Format(PyExc_TypeError,
1323 "duplicate base class %U",
1324 o);
1325 Py_DECREF(o);
1326 } else {
1327 PyErr_SetString(PyExc_TypeError,
1328 "duplicate base class");
1329 }
1330 return -1;
1331 }
1332 }
1333 }
1334 return 0;
Guido van Rossum98f33732002-11-25 21:36:54 +00001335}
1336
1337/* Raise a TypeError for an MRO order disagreement.
1338
1339 It's hard to produce a good error message. In the absence of better
1340 insight into error reporting, report the classes that were candidates
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001341 to be put next into the MRO. There is some conflict between the
Guido van Rossum98f33732002-11-25 21:36:54 +00001342 order in which they should be put in the MRO, but it's hard to
1343 diagnose what constraint can't be satisfied.
1344*/
1345
1346static void
1347set_mro_error(PyObject *to_merge, int *remain)
1348{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001349 Py_ssize_t i, n, off, to_merge_size;
1350 char buf[1000];
1351 PyObject *k, *v;
1352 PyObject *set = PyDict_New();
1353 if (!set) return;
Guido van Rossum98f33732002-11-25 21:36:54 +00001354
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001355 to_merge_size = PyList_GET_SIZE(to_merge);
1356 for (i = 0; i < to_merge_size; i++) {
1357 PyObject *L = PyList_GET_ITEM(to_merge, i);
1358 if (remain[i] < PyList_GET_SIZE(L)) {
1359 PyObject *c = PyList_GET_ITEM(L, remain[i]);
1360 if (PyDict_SetItem(set, c, Py_None) < 0) {
1361 Py_DECREF(set);
1362 return;
1363 }
1364 }
1365 }
1366 n = PyDict_Size(set);
Guido van Rossum98f33732002-11-25 21:36:54 +00001367
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001368 off = PyOS_snprintf(buf, sizeof(buf), "Cannot create a \
Raymond Hettingerf394df42003-04-06 19:13:41 +00001369consistent method resolution\norder (MRO) for bases");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001370 i = 0;
1371 while (PyDict_Next(set, &i, &k, &v) && (size_t)off < sizeof(buf)) {
1372 PyObject *name = class_name(k);
Victor Stinnere5f99f32010-05-19 01:42:46 +00001373 char *name_str;
1374 if (name != NULL) {
1375 name_str = _PyUnicode_AsString(name);
1376 if (name_str == NULL)
Victor Stinnerba644a62010-05-19 01:50:45 +00001377 name_str = "?";
Victor Stinnere5f99f32010-05-19 01:42:46 +00001378 } else
Victor Stinnerba644a62010-05-19 01:50:45 +00001379 name_str = "?";
Victor Stinnere5f99f32010-05-19 01:42:46 +00001380 off += PyOS_snprintf(buf + off, sizeof(buf) - off, " %s", name_str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001381 Py_XDECREF(name);
1382 if (--n && (size_t)(off+1) < sizeof(buf)) {
1383 buf[off++] = ',';
1384 buf[off] = '\0';
1385 }
1386 }
1387 PyErr_SetString(PyExc_TypeError, buf);
1388 Py_DECREF(set);
Guido van Rossum98f33732002-11-25 21:36:54 +00001389}
1390
Tim Petersea7f75d2002-12-07 21:39:16 +00001391static int
Guido van Rossum1f121312002-11-14 19:49:16 +00001392pmerge(PyObject *acc, PyObject* to_merge) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001393 Py_ssize_t i, j, to_merge_size, empty_cnt;
1394 int *remain;
1395 int ok;
Tim Petersea7f75d2002-12-07 21:39:16 +00001396
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001397 to_merge_size = PyList_GET_SIZE(to_merge);
Guido van Rossum1f121312002-11-14 19:49:16 +00001398
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001399 /* remain stores an index into each sublist of to_merge.
1400 remain[i] is the index of the next base in to_merge[i]
1401 that is not included in acc.
1402 */
1403 remain = (int *)PyMem_MALLOC(SIZEOF_INT*to_merge_size);
1404 if (remain == NULL)
1405 return -1;
1406 for (i = 0; i < to_merge_size; i++)
1407 remain[i] = 0;
Guido van Rossum1f121312002-11-14 19:49:16 +00001408
1409 again:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001410 empty_cnt = 0;
1411 for (i = 0; i < to_merge_size; i++) {
1412 PyObject *candidate;
Tim Petersea7f75d2002-12-07 21:39:16 +00001413
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001414 PyObject *cur_list = PyList_GET_ITEM(to_merge, i);
Guido van Rossum1f121312002-11-14 19:49:16 +00001415
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001416 if (remain[i] >= PyList_GET_SIZE(cur_list)) {
1417 empty_cnt++;
1418 continue;
1419 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001420
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001421 /* Choose next candidate for MRO.
Guido van Rossum98f33732002-11-25 21:36:54 +00001422
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001423 The input sequences alone can determine the choice.
1424 If not, choose the class which appears in the MRO
1425 of the earliest direct superclass of the new class.
1426 */
Guido van Rossum98f33732002-11-25 21:36:54 +00001427
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001428 candidate = PyList_GET_ITEM(cur_list, remain[i]);
1429 for (j = 0; j < to_merge_size; j++) {
1430 PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
1431 if (tail_contains(j_lst, remain[j], candidate)) {
1432 goto skip; /* continue outer loop */
1433 }
1434 }
1435 ok = PyList_Append(acc, candidate);
1436 if (ok < 0) {
1437 PyMem_Free(remain);
1438 return -1;
1439 }
1440 for (j = 0; j < to_merge_size; j++) {
1441 PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
1442 if (remain[j] < PyList_GET_SIZE(j_lst) &&
1443 PyList_GET_ITEM(j_lst, remain[j]) == candidate) {
1444 remain[j]++;
1445 }
1446 }
1447 goto again;
1448 skip: ;
1449 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001450
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001451 if (empty_cnt == to_merge_size) {
1452 PyMem_FREE(remain);
1453 return 0;
1454 }
1455 set_mro_error(to_merge, remain);
1456 PyMem_FREE(remain);
1457 return -1;
Guido van Rossum1f121312002-11-14 19:49:16 +00001458}
1459
Tim Peters6d6c1a32001-08-02 04:15:00 +00001460static PyObject *
1461mro_implementation(PyTypeObject *type)
1462{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001463 Py_ssize_t i, n;
1464 int ok;
1465 PyObject *bases, *result;
1466 PyObject *to_merge, *bases_aslist;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001467
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001468 if (type->tp_dict == NULL) {
1469 if (PyType_Ready(type) < 0)
1470 return NULL;
1471 }
Guido van Rossum63517572002-06-18 16:44:57 +00001472
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001473 /* Find a superclass linearization that honors the constraints
1474 of the explicit lists of bases and the constraints implied by
1475 each base class.
Guido van Rossum98f33732002-11-25 21:36:54 +00001476
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001477 to_merge is a list of lists, where each list is a superclass
1478 linearization implied by a base class. The last element of
1479 to_merge is the declared list of bases.
1480 */
Guido van Rossum98f33732002-11-25 21:36:54 +00001481
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001482 bases = type->tp_bases;
1483 n = PyTuple_GET_SIZE(bases);
Guido van Rossum1f121312002-11-14 19:49:16 +00001484
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001485 to_merge = PyList_New(n+1);
1486 if (to_merge == NULL)
1487 return NULL;
Guido van Rossum1f121312002-11-14 19:49:16 +00001488
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001489 for (i = 0; i < n; i++) {
1490 PyObject *base = PyTuple_GET_ITEM(bases, i);
1491 PyObject *parentMRO;
1492 parentMRO = PySequence_List(((PyTypeObject*)base)->tp_mro);
1493 if (parentMRO == NULL) {
1494 Py_DECREF(to_merge);
1495 return NULL;
1496 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001497
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001498 PyList_SET_ITEM(to_merge, i, parentMRO);
1499 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001500
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001501 bases_aslist = PySequence_List(bases);
1502 if (bases_aslist == NULL) {
1503 Py_DECREF(to_merge);
1504 return NULL;
1505 }
1506 /* This is just a basic sanity check. */
1507 if (check_duplicates(bases_aslist) < 0) {
1508 Py_DECREF(to_merge);
1509 Py_DECREF(bases_aslist);
1510 return NULL;
1511 }
1512 PyList_SET_ITEM(to_merge, n, bases_aslist);
Guido van Rossum1f121312002-11-14 19:49:16 +00001513
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001514 result = Py_BuildValue("[O]", (PyObject *)type);
1515 if (result == NULL) {
1516 Py_DECREF(to_merge);
1517 return NULL;
1518 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001519
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001520 ok = pmerge(result, to_merge);
1521 Py_DECREF(to_merge);
1522 if (ok < 0) {
1523 Py_DECREF(result);
1524 return NULL;
1525 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001526
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001527 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001528}
1529
1530static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001531mro_external(PyObject *self)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001532{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001533 PyTypeObject *type = (PyTypeObject *)self;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001534
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001535 return mro_implementation(type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001536}
1537
1538static int
1539mro_internal(PyTypeObject *type)
1540{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001541 PyObject *mro, *result, *tuple;
1542 int checkit = 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001543
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001544 if (Py_TYPE(type) == &PyType_Type) {
1545 result = mro_implementation(type);
1546 }
1547 else {
1548 static PyObject *mro_str;
1549 checkit = 1;
1550 mro = lookup_method((PyObject *)type, "mro", &mro_str);
1551 if (mro == NULL)
1552 return -1;
1553 result = PyObject_CallObject(mro, NULL);
1554 Py_DECREF(mro);
1555 }
1556 if (result == NULL)
1557 return -1;
1558 tuple = PySequence_Tuple(result);
1559 Py_DECREF(result);
1560 if (tuple == NULL)
1561 return -1;
1562 if (checkit) {
1563 Py_ssize_t i, len;
1564 PyObject *cls;
1565 PyTypeObject *solid;
Armin Rigo037d1e02005-12-29 17:07:39 +00001566
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001567 solid = solid_base(type);
Armin Rigo037d1e02005-12-29 17:07:39 +00001568
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001569 len = PyTuple_GET_SIZE(tuple);
Armin Rigo037d1e02005-12-29 17:07:39 +00001570
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001571 for (i = 0; i < len; i++) {
1572 PyTypeObject *t;
1573 cls = PyTuple_GET_ITEM(tuple, i);
1574 if (!PyType_Check(cls)) {
1575 PyErr_Format(PyExc_TypeError,
1576 "mro() returned a non-class ('%.500s')",
1577 Py_TYPE(cls)->tp_name);
1578 Py_DECREF(tuple);
1579 return -1;
1580 }
1581 t = (PyTypeObject*)cls;
1582 if (!PyType_IsSubtype(solid, solid_base(t))) {
1583 PyErr_Format(PyExc_TypeError,
1584 "mro() returned base with unsuitable layout ('%.500s')",
1585 t->tp_name);
1586 Py_DECREF(tuple);
1587 return -1;
1588 }
1589 }
1590 }
1591 type->tp_mro = tuple;
Christian Heimesa62da1d2008-01-12 19:39:10 +00001592
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001593 type_mro_modified(type, type->tp_mro);
1594 /* corner case: the old-style super class might have been hidden
1595 from the custom MRO */
1596 type_mro_modified(type, type->tp_bases);
Christian Heimesa62da1d2008-01-12 19:39:10 +00001597
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001598 PyType_Modified(type);
Christian Heimesa62da1d2008-01-12 19:39:10 +00001599
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001600 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001601}
1602
1603
1604/* Calculate the best base amongst multiple base classes.
1605 This is the first one that's on the path to the "solid base". */
1606
1607static PyTypeObject *
1608best_base(PyObject *bases)
1609{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001610 Py_ssize_t i, n;
1611 PyTypeObject *base, *winner, *candidate, *base_i;
1612 PyObject *base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001613
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001614 assert(PyTuple_Check(bases));
1615 n = PyTuple_GET_SIZE(bases);
1616 assert(n > 0);
1617 base = NULL;
1618 winner = NULL;
1619 for (i = 0; i < n; i++) {
1620 base_proto = PyTuple_GET_ITEM(bases, i);
1621 if (!PyType_Check(base_proto)) {
1622 PyErr_SetString(
1623 PyExc_TypeError,
1624 "bases must be types");
1625 return NULL;
1626 }
1627 base_i = (PyTypeObject *)base_proto;
1628 if (base_i->tp_dict == NULL) {
1629 if (PyType_Ready(base_i) < 0)
1630 return NULL;
1631 }
1632 candidate = solid_base(base_i);
1633 if (winner == NULL) {
1634 winner = candidate;
1635 base = base_i;
1636 }
1637 else if (PyType_IsSubtype(winner, candidate))
1638 ;
1639 else if (PyType_IsSubtype(candidate, winner)) {
1640 winner = candidate;
1641 base = base_i;
1642 }
1643 else {
1644 PyErr_SetString(
1645 PyExc_TypeError,
1646 "multiple bases have "
1647 "instance lay-out conflict");
1648 return NULL;
1649 }
1650 }
1651 if (base == NULL)
1652 PyErr_SetString(PyExc_TypeError,
1653 "a new-style class can't have only classic bases");
1654 return base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001655}
1656
1657static int
1658extra_ivars(PyTypeObject *type, PyTypeObject *base)
1659{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001660 size_t t_size = type->tp_basicsize;
1661 size_t b_size = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001662
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001663 assert(t_size >= b_size); /* Else type smaller than base! */
1664 if (type->tp_itemsize || base->tp_itemsize) {
1665 /* If itemsize is involved, stricter rules */
1666 return t_size != b_size ||
1667 type->tp_itemsize != base->tp_itemsize;
1668 }
1669 if (type->tp_weaklistoffset && base->tp_weaklistoffset == 0 &&
1670 type->tp_weaklistoffset + sizeof(PyObject *) == t_size &&
1671 type->tp_flags & Py_TPFLAGS_HEAPTYPE)
1672 t_size -= sizeof(PyObject *);
1673 if (type->tp_dictoffset && base->tp_dictoffset == 0 &&
1674 type->tp_dictoffset + sizeof(PyObject *) == t_size &&
1675 type->tp_flags & Py_TPFLAGS_HEAPTYPE)
1676 t_size -= sizeof(PyObject *);
Guido van Rossum9676b222001-08-17 20:32:36 +00001677
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001678 return t_size != b_size;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001679}
1680
1681static PyTypeObject *
1682solid_base(PyTypeObject *type)
1683{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001684 PyTypeObject *base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001685
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001686 if (type->tp_base)
1687 base = solid_base(type->tp_base);
1688 else
1689 base = &PyBaseObject_Type;
1690 if (extra_ivars(type, base))
1691 return type;
1692 else
1693 return base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001694}
1695
Jeremy Hylton938ace62002-07-17 16:30:39 +00001696static void object_dealloc(PyObject *);
1697static int object_init(PyObject *, PyObject *, PyObject *);
1698static int update_slot(PyTypeObject *, PyObject *);
1699static void fixup_slot_dispatchers(PyTypeObject *);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001700
Guido van Rossum360e4b82007-05-14 22:51:27 +00001701/*
1702 * Helpers for __dict__ descriptor. We don't want to expose the dicts
1703 * inherited from various builtin types. The builtin base usually provides
1704 * its own __dict__ descriptor, so we use that when we can.
1705 */
1706static PyTypeObject *
1707get_builtin_base_with_dict(PyTypeObject *type)
1708{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001709 while (type->tp_base != NULL) {
1710 if (type->tp_dictoffset != 0 &&
1711 !(type->tp_flags & Py_TPFLAGS_HEAPTYPE))
1712 return type;
1713 type = type->tp_base;
1714 }
1715 return NULL;
Guido van Rossum360e4b82007-05-14 22:51:27 +00001716}
1717
1718static PyObject *
1719get_dict_descriptor(PyTypeObject *type)
1720{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001721 static PyObject *dict_str;
1722 PyObject *descr;
Guido van Rossum360e4b82007-05-14 22:51:27 +00001723
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001724 if (dict_str == NULL) {
1725 dict_str = PyUnicode_InternFromString("__dict__");
1726 if (dict_str == NULL)
1727 return NULL;
1728 }
1729 descr = _PyType_Lookup(type, dict_str);
1730 if (descr == NULL || !PyDescr_IsData(descr))
1731 return NULL;
Guido van Rossum360e4b82007-05-14 22:51:27 +00001732
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001733 return descr;
Guido van Rossum360e4b82007-05-14 22:51:27 +00001734}
1735
1736static void
1737raise_dict_descr_error(PyObject *obj)
1738{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001739 PyErr_Format(PyExc_TypeError,
1740 "this __dict__ descriptor does not support "
1741 "'%.200s' objects", Py_TYPE(obj)->tp_name);
Guido van Rossum360e4b82007-05-14 22:51:27 +00001742}
1743
Tim Peters6d6c1a32001-08-02 04:15:00 +00001744static PyObject *
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001745subtype_dict(PyObject *obj, void *context)
1746{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001747 PyObject **dictptr;
1748 PyObject *dict;
1749 PyTypeObject *base;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001750
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001751 base = get_builtin_base_with_dict(Py_TYPE(obj));
1752 if (base != NULL) {
1753 descrgetfunc func;
1754 PyObject *descr = get_dict_descriptor(base);
1755 if (descr == NULL) {
1756 raise_dict_descr_error(obj);
1757 return NULL;
1758 }
1759 func = Py_TYPE(descr)->tp_descr_get;
1760 if (func == NULL) {
1761 raise_dict_descr_error(obj);
1762 return NULL;
1763 }
1764 return func(descr, obj, (PyObject *)(Py_TYPE(obj)));
1765 }
Guido van Rossum360e4b82007-05-14 22:51:27 +00001766
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001767 dictptr = _PyObject_GetDictPtr(obj);
1768 if (dictptr == NULL) {
1769 PyErr_SetString(PyExc_AttributeError,
1770 "This object has no __dict__");
1771 return NULL;
1772 }
1773 dict = *dictptr;
1774 if (dict == NULL)
1775 *dictptr = dict = PyDict_New();
1776 Py_XINCREF(dict);
1777 return dict;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001778}
1779
Guido van Rossum6661be32001-10-26 04:26:12 +00001780static int
1781subtype_setdict(PyObject *obj, PyObject *value, void *context)
1782{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001783 PyObject **dictptr;
1784 PyObject *dict;
1785 PyTypeObject *base;
Guido van Rossum6661be32001-10-26 04:26:12 +00001786
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001787 base = get_builtin_base_with_dict(Py_TYPE(obj));
1788 if (base != NULL) {
1789 descrsetfunc func;
1790 PyObject *descr = get_dict_descriptor(base);
1791 if (descr == NULL) {
1792 raise_dict_descr_error(obj);
1793 return -1;
1794 }
1795 func = Py_TYPE(descr)->tp_descr_set;
1796 if (func == NULL) {
1797 raise_dict_descr_error(obj);
1798 return -1;
1799 }
1800 return func(descr, obj, value);
1801 }
Guido van Rossum360e4b82007-05-14 22:51:27 +00001802
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001803 dictptr = _PyObject_GetDictPtr(obj);
1804 if (dictptr == NULL) {
1805 PyErr_SetString(PyExc_AttributeError,
1806 "This object has no __dict__");
1807 return -1;
1808 }
1809 if (value != NULL && !PyDict_Check(value)) {
1810 PyErr_Format(PyExc_TypeError,
1811 "__dict__ must be set to a dictionary, "
1812 "not a '%.200s'", Py_TYPE(value)->tp_name);
1813 return -1;
1814 }
1815 dict = *dictptr;
1816 Py_XINCREF(value);
1817 *dictptr = value;
1818 Py_XDECREF(dict);
1819 return 0;
Guido van Rossum6661be32001-10-26 04:26:12 +00001820}
1821
Guido van Rossumad47da02002-08-12 19:05:44 +00001822static PyObject *
1823subtype_getweakref(PyObject *obj, void *context)
1824{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001825 PyObject **weaklistptr;
1826 PyObject *result;
Guido van Rossumad47da02002-08-12 19:05:44 +00001827
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001828 if (Py_TYPE(obj)->tp_weaklistoffset == 0) {
1829 PyErr_SetString(PyExc_AttributeError,
1830 "This object has no __weakref__");
1831 return NULL;
1832 }
1833 assert(Py_TYPE(obj)->tp_weaklistoffset > 0);
1834 assert(Py_TYPE(obj)->tp_weaklistoffset + sizeof(PyObject *) <=
1835 (size_t)(Py_TYPE(obj)->tp_basicsize));
1836 weaklistptr = (PyObject **)
1837 ((char *)obj + Py_TYPE(obj)->tp_weaklistoffset);
1838 if (*weaklistptr == NULL)
1839 result = Py_None;
1840 else
1841 result = *weaklistptr;
1842 Py_INCREF(result);
1843 return result;
Guido van Rossumad47da02002-08-12 19:05:44 +00001844}
1845
Guido van Rossum373c7412003-01-07 13:41:37 +00001846/* Three variants on the subtype_getsets list. */
1847
1848static PyGetSetDef subtype_getsets_full[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001849 {"__dict__", subtype_dict, subtype_setdict,
1850 PyDoc_STR("dictionary for instance variables (if defined)")},
1851 {"__weakref__", subtype_getweakref, NULL,
1852 PyDoc_STR("list of weak references to the object (if defined)")},
1853 {0}
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001854};
1855
Guido van Rossum373c7412003-01-07 13:41:37 +00001856static PyGetSetDef subtype_getsets_dict_only[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001857 {"__dict__", subtype_dict, subtype_setdict,
1858 PyDoc_STR("dictionary for instance variables (if defined)")},
1859 {0}
Guido van Rossum373c7412003-01-07 13:41:37 +00001860};
1861
1862static PyGetSetDef subtype_getsets_weakref_only[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001863 {"__weakref__", subtype_getweakref, NULL,
1864 PyDoc_STR("list of weak references to the object (if defined)")},
1865 {0}
Guido van Rossum373c7412003-01-07 13:41:37 +00001866};
1867
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001868static int
1869valid_identifier(PyObject *s)
1870{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001871 if (!PyUnicode_Check(s)) {
1872 PyErr_Format(PyExc_TypeError,
1873 "__slots__ items must be strings, not '%.200s'",
1874 Py_TYPE(s)->tp_name);
1875 return 0;
1876 }
1877 if (!PyUnicode_IsIdentifier(s)) {
1878 PyErr_SetString(PyExc_TypeError,
1879 "__slots__ must be identifiers");
1880 return 0;
1881 }
1882 return 1;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001883}
1884
Guido van Rossumd8faa362007-04-27 19:54:29 +00001885/* Forward */
1886static int
1887object_init(PyObject *self, PyObject *args, PyObject *kwds);
1888
1889static int
1890type_init(PyObject *cls, PyObject *args, PyObject *kwds)
1891{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001892 int res;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001893
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001894 assert(args != NULL && PyTuple_Check(args));
1895 assert(kwds == NULL || PyDict_Check(kwds));
Guido van Rossumd8faa362007-04-27 19:54:29 +00001896
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001897 if (kwds != NULL && PyDict_Check(kwds) && PyDict_Size(kwds) != 0) {
1898 PyErr_SetString(PyExc_TypeError,
1899 "type.__init__() takes no keyword arguments");
1900 return -1;
1901 }
Guido van Rossumd8faa362007-04-27 19:54:29 +00001902
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001903 if (args != NULL && PyTuple_Check(args) &&
1904 (PyTuple_GET_SIZE(args) != 1 && PyTuple_GET_SIZE(args) != 3)) {
1905 PyErr_SetString(PyExc_TypeError,
1906 "type.__init__() takes 1 or 3 arguments");
1907 return -1;
1908 }
Guido van Rossumd8faa362007-04-27 19:54:29 +00001909
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001910 /* Call object.__init__(self) now. */
1911 /* XXX Could call super(type, cls).__init__() but what's the point? */
1912 args = PyTuple_GetSlice(args, 0, 0);
1913 res = object_init(cls, args, NULL);
1914 Py_DECREF(args);
1915 return res;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001916}
1917
Martin v. Löwis738236d2011-02-05 20:35:29 +00001918long
1919PyType_GetFlags(PyTypeObject *type)
1920{
1921 return type->tp_flags;
1922}
1923
Nick Coghlande31b192011-10-23 22:04:16 +10001924/* Determine the most derived metatype. */
1925PyTypeObject *
1926_PyType_CalculateMetaclass(PyTypeObject *metatype, PyObject *bases)
1927{
1928 Py_ssize_t i, nbases;
1929 PyTypeObject *winner;
1930 PyObject *tmp;
1931 PyTypeObject *tmptype;
1932
1933 /* Determine the proper metatype to deal with this,
1934 and check for metatype conflicts while we're at it.
1935 Note that if some other metatype wins to contract,
1936 it's possible that its instances are not types. */
1937
1938 nbases = PyTuple_GET_SIZE(bases);
1939 winner = metatype;
1940 for (i = 0; i < nbases; i++) {
1941 tmp = PyTuple_GET_ITEM(bases, i);
1942 tmptype = Py_TYPE(tmp);
1943 if (PyType_IsSubtype(winner, tmptype))
1944 continue;
1945 if (PyType_IsSubtype(tmptype, winner)) {
1946 winner = tmptype;
1947 continue;
1948 }
1949 /* else: */
1950 PyErr_SetString(PyExc_TypeError,
1951 "metaclass conflict: "
1952 "the metaclass of a derived class "
1953 "must be a (non-strict) subclass "
1954 "of the metaclasses of all its bases");
1955 return NULL;
1956 }
1957 return winner;
1958}
1959
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001960static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00001961type_new(PyTypeObject *metatype, PyObject *args, PyObject *kwds)
1962{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001963 PyObject *name, *bases, *dict;
1964 static char *kwlist[] = {"name", "bases", "dict", 0};
1965 PyObject *slots, *tmp, *newslots;
1966 PyTypeObject *type, *base, *tmptype, *winner;
1967 PyHeapTypeObject *et;
1968 PyMemberDef *mp;
1969 Py_ssize_t i, nbases, nslots, slotoffset, add_dict, add_weak;
1970 int j, may_add_dict, may_add_weak;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001971
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001972 assert(args != NULL && PyTuple_Check(args));
1973 assert(kwds == NULL || PyDict_Check(kwds));
Tim Peters3abca122001-10-27 19:37:48 +00001974
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001975 /* Special case: type(x) should return x->ob_type */
1976 {
1977 const Py_ssize_t nargs = PyTuple_GET_SIZE(args);
1978 const Py_ssize_t nkwds = kwds == NULL ? 0 : PyDict_Size(kwds);
Tim Peters3abca122001-10-27 19:37:48 +00001979
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001980 if (PyType_CheckExact(metatype) && nargs == 1 && nkwds == 0) {
1981 PyObject *x = PyTuple_GET_ITEM(args, 0);
1982 Py_INCREF(Py_TYPE(x));
1983 return (PyObject *) Py_TYPE(x);
1984 }
Tim Peters3abca122001-10-27 19:37:48 +00001985
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001986 /* SF bug 475327 -- if that didn't trigger, we need 3
1987 arguments. but PyArg_ParseTupleAndKeywords below may give
1988 a msg saying type() needs exactly 3. */
1989 if (nargs + nkwds != 3) {
1990 PyErr_SetString(PyExc_TypeError,
1991 "type() takes 1 or 3 arguments");
1992 return NULL;
1993 }
1994 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001995
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001996 /* Check arguments: (name, bases, dict) */
1997 if (!PyArg_ParseTupleAndKeywords(args, kwds, "UO!O!:type", kwlist,
1998 &name,
1999 &PyTuple_Type, &bases,
2000 &PyDict_Type, &dict))
2001 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002002
Nick Coghlande31b192011-10-23 22:04:16 +10002003 /* Determine the proper metatype to deal with this: */
2004 winner = _PyType_CalculateMetaclass(metatype, bases);
2005 if (winner == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002006 return NULL;
2007 }
Nick Coghlande31b192011-10-23 22:04:16 +10002008
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002009 if (winner != metatype) {
2010 if (winner->tp_new != type_new) /* Pass it to the winner */
2011 return winner->tp_new(winner, args, kwds);
2012 metatype = winner;
2013 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002014
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002015 /* Adjust for empty tuple bases */
Nick Coghlande31b192011-10-23 22:04:16 +10002016 nbases = PyTuple_GET_SIZE(bases);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002017 if (nbases == 0) {
2018 bases = PyTuple_Pack(1, &PyBaseObject_Type);
2019 if (bases == NULL)
2020 return NULL;
2021 nbases = 1;
2022 }
2023 else
2024 Py_INCREF(bases);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002025
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002026 /* XXX From here until type is allocated, "return NULL" leaks bases! */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002027
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002028 /* Calculate best base, and check that all bases are type objects */
2029 base = best_base(bases);
2030 if (base == NULL) {
2031 Py_DECREF(bases);
2032 return NULL;
2033 }
2034 if (!PyType_HasFeature(base, Py_TPFLAGS_BASETYPE)) {
2035 PyErr_Format(PyExc_TypeError,
2036 "type '%.100s' is not an acceptable base type",
2037 base->tp_name);
2038 Py_DECREF(bases);
2039 return NULL;
2040 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002041
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002042 /* Check for a __slots__ sequence variable in dict, and count it */
2043 slots = PyDict_GetItemString(dict, "__slots__");
2044 nslots = 0;
2045 add_dict = 0;
2046 add_weak = 0;
2047 may_add_dict = base->tp_dictoffset == 0;
2048 may_add_weak = base->tp_weaklistoffset == 0 && base->tp_itemsize == 0;
2049 if (slots == NULL) {
2050 if (may_add_dict) {
2051 add_dict++;
2052 }
2053 if (may_add_weak) {
2054 add_weak++;
2055 }
2056 }
2057 else {
2058 /* Have slots */
Guido van Rossumad47da02002-08-12 19:05:44 +00002059
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002060 /* Make it into a tuple */
2061 if (PyUnicode_Check(slots))
2062 slots = PyTuple_Pack(1, slots);
2063 else
2064 slots = PySequence_Tuple(slots);
2065 if (slots == NULL) {
2066 Py_DECREF(bases);
2067 return NULL;
2068 }
2069 assert(PyTuple_Check(slots));
Guido van Rossumad47da02002-08-12 19:05:44 +00002070
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002071 /* Are slots allowed? */
2072 nslots = PyTuple_GET_SIZE(slots);
2073 if (nslots > 0 && base->tp_itemsize != 0) {
2074 PyErr_Format(PyExc_TypeError,
2075 "nonempty __slots__ "
2076 "not supported for subtype of '%s'",
2077 base->tp_name);
2078 bad_slots:
2079 Py_DECREF(bases);
2080 Py_DECREF(slots);
2081 return NULL;
2082 }
Guido van Rossumad47da02002-08-12 19:05:44 +00002083
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002084 /* Check for valid slot names and two special cases */
2085 for (i = 0; i < nslots; i++) {
2086 PyObject *tmp = PyTuple_GET_ITEM(slots, i);
2087 if (!valid_identifier(tmp))
2088 goto bad_slots;
2089 assert(PyUnicode_Check(tmp));
2090 if (PyUnicode_CompareWithASCIIString(tmp, "__dict__") == 0) {
2091 if (!may_add_dict || add_dict) {
2092 PyErr_SetString(PyExc_TypeError,
2093 "__dict__ slot disallowed: "
2094 "we already got one");
2095 goto bad_slots;
2096 }
2097 add_dict++;
2098 }
2099 if (PyUnicode_CompareWithASCIIString(tmp, "__weakref__") == 0) {
2100 if (!may_add_weak || add_weak) {
2101 PyErr_SetString(PyExc_TypeError,
2102 "__weakref__ slot disallowed: "
2103 "either we already got one, "
2104 "or __itemsize__ != 0");
2105 goto bad_slots;
2106 }
2107 add_weak++;
2108 }
2109 }
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00002110
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002111 /* Copy slots into a list, mangle names and sort them.
2112 Sorted names are needed for __class__ assignment.
2113 Convert them back to tuple at the end.
2114 */
2115 newslots = PyList_New(nslots - add_dict - add_weak);
2116 if (newslots == NULL)
2117 goto bad_slots;
2118 for (i = j = 0; i < nslots; i++) {
2119 tmp = PyTuple_GET_ITEM(slots, i);
2120 if ((add_dict &&
2121 PyUnicode_CompareWithASCIIString(tmp, "__dict__") == 0) ||
2122 (add_weak &&
2123 PyUnicode_CompareWithASCIIString(tmp, "__weakref__") == 0))
2124 continue;
2125 tmp =_Py_Mangle(name, tmp);
Benjamin Petersonae13c882011-08-16 22:26:48 -05002126 if (!tmp) {
2127 Py_DECREF(newslots);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002128 goto bad_slots;
Benjamin Petersonae13c882011-08-16 22:26:48 -05002129 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002130 PyList_SET_ITEM(newslots, j, tmp);
2131 j++;
2132 }
2133 assert(j == nslots - add_dict - add_weak);
2134 nslots = j;
2135 Py_DECREF(slots);
2136 if (PyList_Sort(newslots) == -1) {
2137 Py_DECREF(bases);
2138 Py_DECREF(newslots);
2139 return NULL;
2140 }
2141 slots = PyList_AsTuple(newslots);
2142 Py_DECREF(newslots);
2143 if (slots == NULL) {
2144 Py_DECREF(bases);
2145 return NULL;
2146 }
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00002147
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002148 /* Secondary bases may provide weakrefs or dict */
2149 if (nbases > 1 &&
2150 ((may_add_dict && !add_dict) ||
2151 (may_add_weak && !add_weak))) {
2152 for (i = 0; i < nbases; i++) {
2153 tmp = PyTuple_GET_ITEM(bases, i);
2154 if (tmp == (PyObject *)base)
2155 continue; /* Skip primary base */
2156 assert(PyType_Check(tmp));
2157 tmptype = (PyTypeObject *)tmp;
2158 if (may_add_dict && !add_dict &&
2159 tmptype->tp_dictoffset != 0)
2160 add_dict++;
2161 if (may_add_weak && !add_weak &&
2162 tmptype->tp_weaklistoffset != 0)
2163 add_weak++;
2164 if (may_add_dict && !add_dict)
2165 continue;
2166 if (may_add_weak && !add_weak)
2167 continue;
2168 /* Nothing more to check */
2169 break;
2170 }
2171 }
2172 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002173
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002174 /* XXX From here until type is safely allocated,
2175 "return NULL" may leak slots! */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002176
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002177 /* Allocate the type object */
2178 type = (PyTypeObject *)metatype->tp_alloc(metatype, nslots);
2179 if (type == NULL) {
2180 Py_XDECREF(slots);
2181 Py_DECREF(bases);
2182 return NULL;
2183 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002184
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002185 /* Keep name and slots alive in the extended type object */
2186 et = (PyHeapTypeObject *)type;
2187 Py_INCREF(name);
2188 et->ht_name = name;
2189 et->ht_slots = slots;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002190
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002191 /* Initialize tp_flags */
2192 type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE |
2193 Py_TPFLAGS_BASETYPE;
2194 if (base->tp_flags & Py_TPFLAGS_HAVE_GC)
2195 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossumdc91b992001-08-08 22:26:22 +00002196
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002197 /* Initialize essential fields */
2198 type->tp_as_number = &et->as_number;
2199 type->tp_as_sequence = &et->as_sequence;
2200 type->tp_as_mapping = &et->as_mapping;
2201 type->tp_as_buffer = &et->as_buffer;
2202 type->tp_name = _PyUnicode_AsString(name);
2203 if (!type->tp_name) {
2204 Py_DECREF(type);
2205 return NULL;
2206 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002207
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002208 /* Set tp_base and tp_bases */
2209 type->tp_bases = bases;
2210 Py_INCREF(base);
2211 type->tp_base = base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002212
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002213 /* Initialize tp_dict from passed-in dict */
2214 type->tp_dict = dict = PyDict_Copy(dict);
2215 if (dict == NULL) {
2216 Py_DECREF(type);
2217 return NULL;
2218 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002219
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002220 /* Set __module__ in the dict */
2221 if (PyDict_GetItemString(dict, "__module__") == NULL) {
2222 tmp = PyEval_GetGlobals();
2223 if (tmp != NULL) {
2224 tmp = PyDict_GetItemString(tmp, "__name__");
2225 if (tmp != NULL) {
2226 if (PyDict_SetItemString(dict, "__module__",
2227 tmp) < 0)
2228 return NULL;
2229 }
2230 }
2231 }
Guido van Rossumc3542212001-08-16 09:18:56 +00002232
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002233 /* Set tp_doc to a copy of dict['__doc__'], if the latter is there
2234 and is a string. The __doc__ accessor will first look for tp_doc;
2235 if that fails, it will still look into __dict__.
2236 */
2237 {
2238 PyObject *doc = PyDict_GetItemString(dict, "__doc__");
2239 if (doc != NULL && PyUnicode_Check(doc)) {
2240 Py_ssize_t len;
2241 char *doc_str;
2242 char *tp_doc;
Alexandre Vassalottia85998a2008-05-03 18:24:43 +00002243
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002244 doc_str = _PyUnicode_AsString(doc);
2245 if (doc_str == NULL) {
2246 Py_DECREF(type);
2247 return NULL;
2248 }
2249 /* Silently truncate the docstring if it contains null bytes. */
2250 len = strlen(doc_str);
2251 tp_doc = (char *)PyObject_MALLOC(len + 1);
2252 if (tp_doc == NULL) {
2253 Py_DECREF(type);
2254 return NULL;
2255 }
2256 memcpy(tp_doc, doc_str, len + 1);
2257 type->tp_doc = tp_doc;
2258 }
2259 }
Tim Peters2f93e282001-10-04 05:27:00 +00002260
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002261 /* Special-case __new__: if it's a plain function,
2262 make it a static function */
2263 tmp = PyDict_GetItemString(dict, "__new__");
2264 if (tmp != NULL && PyFunction_Check(tmp)) {
2265 tmp = PyStaticMethod_New(tmp);
2266 if (tmp == NULL) {
2267 Py_DECREF(type);
2268 return NULL;
2269 }
2270 PyDict_SetItemString(dict, "__new__", tmp);
2271 Py_DECREF(tmp);
2272 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002273
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002274 /* Add descriptors for custom slots from __slots__, or for __dict__ */
2275 mp = PyHeapType_GET_MEMBERS(et);
2276 slotoffset = base->tp_basicsize;
2277 if (slots != NULL) {
2278 for (i = 0; i < nslots; i++, mp++) {
2279 mp->name = _PyUnicode_AsString(
2280 PyTuple_GET_ITEM(slots, i));
Victor Stinnere5f99f32010-05-19 01:42:46 +00002281 if (mp->name == NULL) {
2282 Py_DECREF(type);
2283 return NULL;
2284 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002285 mp->type = T_OBJECT_EX;
2286 mp->offset = slotoffset;
Guido van Rossumd8faa362007-04-27 19:54:29 +00002287
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002288 /* __dict__ and __weakref__ are already filtered out */
2289 assert(strcmp(mp->name, "__dict__") != 0);
2290 assert(strcmp(mp->name, "__weakref__") != 0);
Guido van Rossumd8faa362007-04-27 19:54:29 +00002291
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002292 slotoffset += sizeof(PyObject *);
2293 }
2294 }
2295 if (add_dict) {
2296 if (base->tp_itemsize)
2297 type->tp_dictoffset = -(long)sizeof(PyObject *);
2298 else
2299 type->tp_dictoffset = slotoffset;
2300 slotoffset += sizeof(PyObject *);
2301 }
2302 if (add_weak) {
2303 assert(!base->tp_itemsize);
2304 type->tp_weaklistoffset = slotoffset;
2305 slotoffset += sizeof(PyObject *);
2306 }
2307 type->tp_basicsize = slotoffset;
2308 type->tp_itemsize = base->tp_itemsize;
2309 type->tp_members = PyHeapType_GET_MEMBERS(et);
Guido van Rossum373c7412003-01-07 13:41:37 +00002310
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002311 if (type->tp_weaklistoffset && type->tp_dictoffset)
2312 type->tp_getset = subtype_getsets_full;
2313 else if (type->tp_weaklistoffset && !type->tp_dictoffset)
2314 type->tp_getset = subtype_getsets_weakref_only;
2315 else if (!type->tp_weaklistoffset && type->tp_dictoffset)
2316 type->tp_getset = subtype_getsets_dict_only;
2317 else
2318 type->tp_getset = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002319
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002320 /* Special case some slots */
2321 if (type->tp_dictoffset != 0 || nslots > 0) {
2322 if (base->tp_getattr == NULL && base->tp_getattro == NULL)
2323 type->tp_getattro = PyObject_GenericGetAttr;
2324 if (base->tp_setattr == NULL && base->tp_setattro == NULL)
2325 type->tp_setattro = PyObject_GenericSetAttr;
2326 }
2327 type->tp_dealloc = subtype_dealloc;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002328
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002329 /* Enable GC unless there are really no instance variables possible */
2330 if (!(type->tp_basicsize == sizeof(PyObject) &&
2331 type->tp_itemsize == 0))
2332 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossum9475a232001-10-05 20:51:39 +00002333
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002334 /* Always override allocation strategy to use regular heap */
2335 type->tp_alloc = PyType_GenericAlloc;
2336 if (type->tp_flags & Py_TPFLAGS_HAVE_GC) {
2337 type->tp_free = PyObject_GC_Del;
2338 type->tp_traverse = subtype_traverse;
2339 type->tp_clear = subtype_clear;
2340 }
2341 else
2342 type->tp_free = PyObject_Del;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002343
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002344 /* Initialize the rest */
2345 if (PyType_Ready(type) < 0) {
2346 Py_DECREF(type);
2347 return NULL;
2348 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002349
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002350 /* Put the proper slots in place */
2351 fixup_slot_dispatchers(type);
Guido van Rossumf040ede2001-08-07 16:40:56 +00002352
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002353 return (PyObject *)type;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002354}
2355
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002356static short slotoffsets[] = {
2357 -1, /* invalid slot */
2358#include "typeslots.inc"
2359};
2360
Benjamin Petersone28108c2012-01-29 20:13:18 -05002361PyObject *
2362PyType_FromSpec(PyType_Spec *spec)
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002363{
2364 PyHeapTypeObject *res = (PyHeapTypeObject*)PyType_GenericAlloc(&PyType_Type, 0);
2365 char *res_start = (char*)res;
2366 PyType_Slot *slot;
2367
Martin v. Löwis7be5b782011-02-21 16:26:47 +00002368 if (res == NULL)
2369 return NULL;
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002370 res->ht_name = PyUnicode_FromString(spec->name);
2371 if (!res->ht_name)
Antoine Pitroua1433fe2012-05-14 14:43:25 +02002372 goto fail;
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002373 res->ht_type.tp_name = _PyUnicode_AsString(res->ht_name);
2374 if (!res->ht_type.tp_name)
Antoine Pitroua1433fe2012-05-14 14:43:25 +02002375 goto fail;
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002376
2377 res->ht_type.tp_basicsize = spec->basicsize;
2378 res->ht_type.tp_itemsize = spec->itemsize;
2379 res->ht_type.tp_flags = spec->flags | Py_TPFLAGS_HEAPTYPE;
Victor Stinner0fcab4a2011-01-04 12:59:15 +00002380
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002381 for (slot = spec->slots; slot->slot; slot++) {
Antoine Pitroua1433fe2012-05-14 14:43:25 +02002382 if (slot->slot >= sizeof(slotoffsets)/sizeof(slotoffsets[0])) {
2383 PyErr_SetString(PyExc_RuntimeError, "invalid slot offset");
2384 goto fail;
2385 }
2386 *(void**)(res_start + slotoffsets[slot->slot]) = slot->pfunc;
Georg Brandl032400b2011-02-19 21:47:02 +00002387
2388 /* need to make a copy of the docstring slot, which usually
2389 points to a static string literal */
2390 if (slot->slot == Py_tp_doc) {
Antoine Pitrou682d94c2012-05-14 14:43:03 +02002391 size_t len = strlen(slot->pfunc)+1;
Georg Brandl032400b2011-02-19 21:47:02 +00002392 char *tp_doc = PyObject_MALLOC(len);
2393 if (tp_doc == NULL)
Antoine Pitroua1433fe2012-05-14 14:43:25 +02002394 goto fail;
Georg Brandl032400b2011-02-19 21:47:02 +00002395 memcpy(tp_doc, slot->pfunc, len);
2396 res->ht_type.tp_doc = tp_doc;
2397 }
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002398 }
Antoine Pitrou99cc6292012-06-23 14:42:38 +02002399 if (res->ht_type.tp_dealloc == NULL) {
2400 /* It's a heap type, so needs the heap types' dealloc.
2401 subtype_dealloc will call the base type's tp_dealloc, if
2402 necessary. */
2403 res->ht_type.tp_dealloc = subtype_dealloc;
2404 }
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002405
Benjamin Peterson2652d252012-01-29 20:16:37 -05002406 if (PyType_Ready(&res->ht_type) < 0)
2407 goto fail;
2408
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002409 return (PyObject*)res;
Victor Stinner0fcab4a2011-01-04 12:59:15 +00002410
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002411 fail:
2412 Py_DECREF(res);
2413 return NULL;
2414}
2415
2416
Tim Peters6d6c1a32001-08-02 04:15:00 +00002417/* Internal API to look for a name through the MRO.
2418 This returns a borrowed reference, and doesn't set an exception! */
2419PyObject *
2420_PyType_Lookup(PyTypeObject *type, PyObject *name)
2421{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002422 Py_ssize_t i, n;
2423 PyObject *mro, *res, *base, *dict;
2424 unsigned int h;
Christian Heimesa62da1d2008-01-12 19:39:10 +00002425
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002426 if (MCACHE_CACHEABLE_NAME(name) &&
2427 PyType_HasFeature(type, Py_TPFLAGS_VALID_VERSION_TAG)) {
2428 /* fast path */
2429 h = MCACHE_HASH_METHOD(type, name);
2430 if (method_cache[h].version == type->tp_version_tag &&
2431 method_cache[h].name == name)
2432 return method_cache[h].value;
2433 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002434
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002435 /* Look in tp_dict of types in MRO */
2436 mro = type->tp_mro;
Guido van Rossum23094982002-06-10 14:30:43 +00002437
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002438 /* If mro is NULL, the type is either not yet initialized
2439 by PyType_Ready(), or already cleared by type_clear().
2440 Either way the safest thing to do is to return NULL. */
2441 if (mro == NULL)
2442 return NULL;
Guido van Rossum23094982002-06-10 14:30:43 +00002443
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002444 res = NULL;
2445 assert(PyTuple_Check(mro));
2446 n = PyTuple_GET_SIZE(mro);
2447 for (i = 0; i < n; i++) {
2448 base = PyTuple_GET_ITEM(mro, i);
2449 assert(PyType_Check(base));
2450 dict = ((PyTypeObject *)base)->tp_dict;
2451 assert(dict && PyDict_Check(dict));
2452 res = PyDict_GetItem(dict, name);
2453 if (res != NULL)
2454 break;
2455 }
Christian Heimesa62da1d2008-01-12 19:39:10 +00002456
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002457 if (MCACHE_CACHEABLE_NAME(name) && assign_version_tag(type)) {
2458 h = MCACHE_HASH_METHOD(type, name);
2459 method_cache[h].version = type->tp_version_tag;
2460 method_cache[h].value = res; /* borrowed */
2461 Py_INCREF(name);
2462 Py_DECREF(method_cache[h].name);
2463 method_cache[h].name = name;
2464 }
2465 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002466}
2467
2468/* This is similar to PyObject_GenericGetAttr(),
2469 but uses _PyType_Lookup() instead of just looking in type->tp_dict. */
2470static PyObject *
2471type_getattro(PyTypeObject *type, PyObject *name)
2472{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002473 PyTypeObject *metatype = Py_TYPE(type);
2474 PyObject *meta_attribute, *attribute;
2475 descrgetfunc meta_get;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002476
Benjamin Peterson16d84ac2012-03-16 09:32:59 -05002477 if (!PyUnicode_Check(name)) {
2478 PyErr_Format(PyExc_TypeError,
2479 "attribute name must be string, not '%.200s'",
2480 name->ob_type->tp_name);
2481 return NULL;
2482 }
2483
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002484 /* Initialize this type (we'll assume the metatype is initialized) */
2485 if (type->tp_dict == NULL) {
2486 if (PyType_Ready(type) < 0)
2487 return NULL;
2488 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002489
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002490 /* No readable descriptor found yet */
2491 meta_get = NULL;
Tim Peters34592512002-07-11 06:23:50 +00002492
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002493 /* Look for the attribute in the metatype */
2494 meta_attribute = _PyType_Lookup(metatype, name);
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002495
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002496 if (meta_attribute != NULL) {
2497 meta_get = Py_TYPE(meta_attribute)->tp_descr_get;
Tim Peters34592512002-07-11 06:23:50 +00002498
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002499 if (meta_get != NULL && PyDescr_IsData(meta_attribute)) {
2500 /* Data descriptors implement tp_descr_set to intercept
2501 * writes. Assume the attribute is not overridden in
2502 * type's tp_dict (and bases): call the descriptor now.
2503 */
2504 return meta_get(meta_attribute, (PyObject *)type,
2505 (PyObject *)metatype);
2506 }
2507 Py_INCREF(meta_attribute);
2508 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002509
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002510 /* No data descriptor found on metatype. Look in tp_dict of this
2511 * type and its bases */
2512 attribute = _PyType_Lookup(type, name);
2513 if (attribute != NULL) {
2514 /* Implement descriptor functionality, if any */
2515 descrgetfunc local_get = Py_TYPE(attribute)->tp_descr_get;
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00002516
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002517 Py_XDECREF(meta_attribute);
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00002518
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002519 if (local_get != NULL) {
2520 /* NULL 2nd argument indicates the descriptor was
2521 * found on the target object itself (or a base) */
2522 return local_get(attribute, (PyObject *)NULL,
2523 (PyObject *)type);
2524 }
Tim Peters34592512002-07-11 06:23:50 +00002525
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002526 Py_INCREF(attribute);
2527 return attribute;
2528 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002529
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002530 /* No attribute found in local __dict__ (or bases): use the
2531 * descriptor from the metatype, if any */
2532 if (meta_get != NULL) {
2533 PyObject *res;
2534 res = meta_get(meta_attribute, (PyObject *)type,
2535 (PyObject *)metatype);
2536 Py_DECREF(meta_attribute);
2537 return res;
2538 }
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002539
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002540 /* If an ordinary attribute was found on the metatype, return it now */
2541 if (meta_attribute != NULL) {
2542 return meta_attribute;
2543 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002544
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002545 /* Give up */
2546 PyErr_Format(PyExc_AttributeError,
2547 "type object '%.50s' has no attribute '%U'",
2548 type->tp_name, name);
2549 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002550}
2551
2552static int
2553type_setattro(PyTypeObject *type, PyObject *name, PyObject *value)
2554{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002555 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
2556 PyErr_Format(
2557 PyExc_TypeError,
2558 "can't set attributes of built-in/extension type '%s'",
2559 type->tp_name);
2560 return -1;
2561 }
2562 if (PyObject_GenericSetAttr((PyObject *)type, name, value) < 0)
2563 return -1;
2564 return update_slot(type, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002565}
2566
2567static void
2568type_dealloc(PyTypeObject *type)
2569{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002570 PyHeapTypeObject *et;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002571
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002572 /* Assert this is a heap-allocated type object */
2573 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
2574 _PyObject_GC_UNTRACK(type);
2575 PyObject_ClearWeakRefs((PyObject *)type);
2576 et = (PyHeapTypeObject *)type;
2577 Py_XDECREF(type->tp_base);
2578 Py_XDECREF(type->tp_dict);
2579 Py_XDECREF(type->tp_bases);
2580 Py_XDECREF(type->tp_mro);
2581 Py_XDECREF(type->tp_cache);
2582 Py_XDECREF(type->tp_subclasses);
2583 /* A type's tp_doc is heap allocated, unlike the tp_doc slots
2584 * of most other objects. It's okay to cast it to char *.
2585 */
2586 PyObject_Free((char *)type->tp_doc);
2587 Py_XDECREF(et->ht_name);
2588 Py_XDECREF(et->ht_slots);
2589 Py_TYPE(type)->tp_free((PyObject *)type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002590}
2591
Guido van Rossum1c450732001-10-08 15:18:27 +00002592static PyObject *
2593type_subclasses(PyTypeObject *type, PyObject *args_ignored)
2594{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002595 PyObject *list, *raw, *ref;
2596 Py_ssize_t i, n;
Guido van Rossum1c450732001-10-08 15:18:27 +00002597
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002598 list = PyList_New(0);
2599 if (list == NULL)
2600 return NULL;
2601 raw = type->tp_subclasses;
2602 if (raw == NULL)
2603 return list;
2604 assert(PyList_Check(raw));
2605 n = PyList_GET_SIZE(raw);
2606 for (i = 0; i < n; i++) {
2607 ref = PyList_GET_ITEM(raw, i);
2608 assert(PyWeakref_CheckRef(ref));
2609 ref = PyWeakref_GET_OBJECT(ref);
2610 if (ref != Py_None) {
2611 if (PyList_Append(list, ref) < 0) {
2612 Py_DECREF(list);
2613 return NULL;
2614 }
2615 }
2616 }
2617 return list;
Guido van Rossum1c450732001-10-08 15:18:27 +00002618}
2619
Guido van Rossum47374822007-08-02 16:48:17 +00002620static PyObject *
2621type_prepare(PyObject *self, PyObject *args, PyObject *kwds)
2622{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002623 return PyDict_New();
Guido van Rossum47374822007-08-02 16:48:17 +00002624}
2625
Tim Peters6d6c1a32001-08-02 04:15:00 +00002626static PyMethodDef type_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002627 {"mro", (PyCFunction)mro_external, METH_NOARGS,
2628 PyDoc_STR("mro() -> list\nreturn a type's method resolution order")},
2629 {"__subclasses__", (PyCFunction)type_subclasses, METH_NOARGS,
2630 PyDoc_STR("__subclasses__() -> list of immediate subclasses")},
2631 {"__prepare__", (PyCFunction)type_prepare,
2632 METH_VARARGS | METH_KEYWORDS | METH_CLASS,
2633 PyDoc_STR("__prepare__() -> dict\n"
2634 "used to create the namespace for the class statement")},
2635 {"__instancecheck__", type___instancecheck__, METH_O,
Benjamin Petersonfbe56bb2011-05-24 12:42:51 -05002636 PyDoc_STR("__instancecheck__() -> bool\ncheck if an object is an instance")},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002637 {"__subclasscheck__", type___subclasscheck__, METH_O,
Benjamin Petersonfbe56bb2011-05-24 12:42:51 -05002638 PyDoc_STR("__subclasscheck__() -> bool\ncheck if a class is a subclass")},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002639 {0}
Tim Peters6d6c1a32001-08-02 04:15:00 +00002640};
2641
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002642PyDoc_STRVAR(type_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00002643"type(object) -> the object's type\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002644"type(name, bases, dict) -> a new type");
Tim Peters6d6c1a32001-08-02 04:15:00 +00002645
Guido van Rossum048eb752001-10-02 21:24:57 +00002646static int
2647type_traverse(PyTypeObject *type, visitproc visit, void *arg)
2648{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002649 /* Because of type_is_gc(), the collector only calls this
2650 for heaptypes. */
2651 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002652
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002653 Py_VISIT(type->tp_dict);
2654 Py_VISIT(type->tp_cache);
2655 Py_VISIT(type->tp_mro);
2656 Py_VISIT(type->tp_bases);
2657 Py_VISIT(type->tp_base);
Guido van Rossuma3862092002-06-10 15:24:42 +00002658
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002659 /* There's no need to visit type->tp_subclasses or
2660 ((PyHeapTypeObject *)type)->ht_slots, because they can't be involved
2661 in cycles; tp_subclasses is a list of weak references,
2662 and slots is a tuple of strings. */
Guido van Rossum048eb752001-10-02 21:24:57 +00002663
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002664 return 0;
Guido van Rossum048eb752001-10-02 21:24:57 +00002665}
2666
2667static int
2668type_clear(PyTypeObject *type)
2669{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002670 /* Because of type_is_gc(), the collector only calls this
2671 for heaptypes. */
2672 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002673
Antoine Pitrou2e872082011-12-15 14:15:31 +01002674 /* We need to invalidate the method cache carefully before clearing
2675 the dict, so that other objects caught in a reference cycle
2676 don't start calling destroyed methods.
2677
2678 Otherwise, the only field we need to clear is tp_mro, which is
2679 part of a hard cycle (its first element is the class itself) that
2680 won't be broken otherwise (it's a tuple and tuples don't have a
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002681 tp_clear handler). None of the other fields need to be
2682 cleared, and here's why:
Guido van Rossum048eb752001-10-02 21:24:57 +00002683
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002684 tp_cache:
2685 Not used; if it were, it would be a dict.
Guido van Rossuma3862092002-06-10 15:24:42 +00002686
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002687 tp_bases, tp_base:
2688 If these are involved in a cycle, there must be at least
2689 one other, mutable object in the cycle, e.g. a base
2690 class's dict; the cycle will be broken that way.
Guido van Rossuma3862092002-06-10 15:24:42 +00002691
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002692 tp_subclasses:
2693 A list of weak references can't be part of a cycle; and
2694 lists have their own tp_clear.
Guido van Rossuma3862092002-06-10 15:24:42 +00002695
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002696 slots (in PyHeapTypeObject):
2697 A tuple of strings can't be part of a cycle.
2698 */
Guido van Rossuma3862092002-06-10 15:24:42 +00002699
Antoine Pitrou2e872082011-12-15 14:15:31 +01002700 PyType_Modified(type);
2701 if (type->tp_dict)
2702 PyDict_Clear(type->tp_dict);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002703 Py_CLEAR(type->tp_mro);
Guido van Rossum048eb752001-10-02 21:24:57 +00002704
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002705 return 0;
Guido van Rossum048eb752001-10-02 21:24:57 +00002706}
2707
2708static int
2709type_is_gc(PyTypeObject *type)
2710{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002711 return type->tp_flags & Py_TPFLAGS_HEAPTYPE;
Guido van Rossum048eb752001-10-02 21:24:57 +00002712}
2713
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002714PyTypeObject PyType_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002715 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2716 "type", /* tp_name */
2717 sizeof(PyHeapTypeObject), /* tp_basicsize */
2718 sizeof(PyMemberDef), /* tp_itemsize */
2719 (destructor)type_dealloc, /* tp_dealloc */
2720 0, /* tp_print */
2721 0, /* tp_getattr */
2722 0, /* tp_setattr */
2723 0, /* tp_reserved */
2724 (reprfunc)type_repr, /* tp_repr */
2725 0, /* tp_as_number */
2726 0, /* tp_as_sequence */
2727 0, /* tp_as_mapping */
2728 0, /* tp_hash */
2729 (ternaryfunc)type_call, /* tp_call */
2730 0, /* tp_str */
2731 (getattrofunc)type_getattro, /* tp_getattro */
2732 (setattrofunc)type_setattro, /* tp_setattro */
2733 0, /* tp_as_buffer */
2734 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
2735 Py_TPFLAGS_BASETYPE | Py_TPFLAGS_TYPE_SUBCLASS, /* tp_flags */
2736 type_doc, /* tp_doc */
2737 (traverseproc)type_traverse, /* tp_traverse */
2738 (inquiry)type_clear, /* tp_clear */
2739 0, /* tp_richcompare */
2740 offsetof(PyTypeObject, tp_weaklist), /* tp_weaklistoffset */
2741 0, /* tp_iter */
2742 0, /* tp_iternext */
2743 type_methods, /* tp_methods */
2744 type_members, /* tp_members */
2745 type_getsets, /* tp_getset */
2746 0, /* tp_base */
2747 0, /* tp_dict */
2748 0, /* tp_descr_get */
2749 0, /* tp_descr_set */
2750 offsetof(PyTypeObject, tp_dict), /* tp_dictoffset */
2751 type_init, /* tp_init */
2752 0, /* tp_alloc */
2753 type_new, /* tp_new */
2754 PyObject_GC_Del, /* tp_free */
2755 (inquiry)type_is_gc, /* tp_is_gc */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002756};
Tim Peters6d6c1a32001-08-02 04:15:00 +00002757
2758
2759/* The base type of all types (eventually)... except itself. */
2760
Guido van Rossumd8faa362007-04-27 19:54:29 +00002761/* You may wonder why object.__new__() only complains about arguments
2762 when object.__init__() is not overridden, and vice versa.
2763
2764 Consider the use cases:
2765
2766 1. When neither is overridden, we want to hear complaints about
2767 excess (i.e., any) arguments, since their presence could
2768 indicate there's a bug.
2769
2770 2. When defining an Immutable type, we are likely to override only
2771 __new__(), since __init__() is called too late to initialize an
2772 Immutable object. Since __new__() defines the signature for the
2773 type, it would be a pain to have to override __init__() just to
2774 stop it from complaining about excess arguments.
2775
2776 3. When defining a Mutable type, we are likely to override only
2777 __init__(). So here the converse reasoning applies: we don't
2778 want to have to override __new__() just to stop it from
2779 complaining.
2780
2781 4. When __init__() is overridden, and the subclass __init__() calls
2782 object.__init__(), the latter should complain about excess
2783 arguments; ditto for __new__().
2784
2785 Use cases 2 and 3 make it unattractive to unconditionally check for
2786 excess arguments. The best solution that addresses all four use
2787 cases is as follows: __init__() complains about excess arguments
2788 unless __new__() is overridden and __init__() is not overridden
2789 (IOW, if __init__() is overridden or __new__() is not overridden);
2790 symmetrically, __new__() complains about excess arguments unless
2791 __init__() is overridden and __new__() is not overridden
2792 (IOW, if __new__() is overridden or __init__() is not overridden).
2793
2794 However, for backwards compatibility, this breaks too much code.
2795 Therefore, in 2.6, we'll *warn* about excess arguments when both
2796 methods are overridden; for all other cases we'll use the above
2797 rules.
2798
2799*/
2800
2801/* Forward */
2802static PyObject *
2803object_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
2804
2805static int
2806excess_args(PyObject *args, PyObject *kwds)
2807{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002808 return PyTuple_GET_SIZE(args) ||
2809 (kwds && PyDict_Check(kwds) && PyDict_Size(kwds));
Guido van Rossumd8faa362007-04-27 19:54:29 +00002810}
2811
Tim Peters6d6c1a32001-08-02 04:15:00 +00002812static int
2813object_init(PyObject *self, PyObject *args, PyObject *kwds)
2814{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002815 int err = 0;
2816 if (excess_args(args, kwds)) {
2817 PyTypeObject *type = Py_TYPE(self);
2818 if (type->tp_init != object_init &&
2819 type->tp_new != object_new)
2820 {
2821 err = PyErr_WarnEx(PyExc_DeprecationWarning,
2822 "object.__init__() takes no parameters",
2823 1);
2824 }
2825 else if (type->tp_init != object_init ||
2826 type->tp_new == object_new)
2827 {
2828 PyErr_SetString(PyExc_TypeError,
2829 "object.__init__() takes no parameters");
2830 err = -1;
2831 }
2832 }
2833 return err;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002834}
2835
Guido van Rossum298e4212003-02-13 16:30:16 +00002836static PyObject *
2837object_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2838{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002839 int err = 0;
2840 if (excess_args(args, kwds)) {
2841 if (type->tp_new != object_new &&
2842 type->tp_init != object_init)
2843 {
2844 err = PyErr_WarnEx(PyExc_DeprecationWarning,
2845 "object.__new__() takes no parameters",
2846 1);
2847 }
2848 else if (type->tp_new != object_new ||
2849 type->tp_init == object_init)
2850 {
2851 PyErr_SetString(PyExc_TypeError,
2852 "object.__new__() takes no parameters");
2853 err = -1;
2854 }
2855 }
2856 if (err < 0)
2857 return NULL;
Christian Heimes9e7f1d22008-02-28 12:27:11 +00002858
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002859 if (type->tp_flags & Py_TPFLAGS_IS_ABSTRACT) {
2860 static PyObject *comma = NULL;
2861 PyObject *abstract_methods = NULL;
2862 PyObject *builtins;
2863 PyObject *sorted;
2864 PyObject *sorted_methods = NULL;
2865 PyObject *joined = NULL;
Christian Heimes9e7f1d22008-02-28 12:27:11 +00002866
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002867 /* Compute ", ".join(sorted(type.__abstractmethods__))
2868 into joined. */
2869 abstract_methods = type_abstractmethods(type, NULL);
2870 if (abstract_methods == NULL)
2871 goto error;
2872 builtins = PyEval_GetBuiltins();
2873 if (builtins == NULL)
2874 goto error;
2875 sorted = PyDict_GetItemString(builtins, "sorted");
2876 if (sorted == NULL)
2877 goto error;
2878 sorted_methods = PyObject_CallFunctionObjArgs(sorted,
2879 abstract_methods,
2880 NULL);
2881 if (sorted_methods == NULL)
2882 goto error;
2883 if (comma == NULL) {
2884 comma = PyUnicode_InternFromString(", ");
2885 if (comma == NULL)
2886 goto error;
2887 }
2888 joined = PyObject_CallMethod(comma, "join",
2889 "O", sorted_methods);
2890 if (joined == NULL)
2891 goto error;
Christian Heimes9e7f1d22008-02-28 12:27:11 +00002892
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002893 PyErr_Format(PyExc_TypeError,
2894 "Can't instantiate abstract class %s "
2895 "with abstract methods %U",
2896 type->tp_name,
2897 joined);
2898 error:
2899 Py_XDECREF(joined);
2900 Py_XDECREF(sorted_methods);
2901 Py_XDECREF(abstract_methods);
2902 return NULL;
2903 }
2904 return type->tp_alloc(type, 0);
Guido van Rossum298e4212003-02-13 16:30:16 +00002905}
2906
Tim Peters6d6c1a32001-08-02 04:15:00 +00002907static void
2908object_dealloc(PyObject *self)
2909{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002910 Py_TYPE(self)->tp_free(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002911}
2912
Guido van Rossum8e248182001-08-12 05:17:56 +00002913static PyObject *
2914object_repr(PyObject *self)
2915{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002916 PyTypeObject *type;
2917 PyObject *mod, *name, *rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00002918
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002919 type = Py_TYPE(self);
2920 mod = type_module(type, NULL);
2921 if (mod == NULL)
2922 PyErr_Clear();
2923 else if (!PyUnicode_Check(mod)) {
2924 Py_DECREF(mod);
2925 mod = NULL;
2926 }
2927 name = type_name(type, NULL);
Christian Heimese81dc292012-09-10 16:57:36 +02002928 if (name == NULL) {
2929 Py_XDECREF(mod);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002930 return NULL;
Christian Heimese81dc292012-09-10 16:57:36 +02002931 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002932 if (mod != NULL && PyUnicode_CompareWithASCIIString(mod, "builtins"))
2933 rtn = PyUnicode_FromFormat("<%U.%U object at %p>", mod, name, self);
2934 else
2935 rtn = PyUnicode_FromFormat("<%s object at %p>",
2936 type->tp_name, self);
2937 Py_XDECREF(mod);
2938 Py_DECREF(name);
2939 return rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00002940}
2941
Guido van Rossumb8f63662001-08-15 23:57:02 +00002942static PyObject *
2943object_str(PyObject *self)
2944{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002945 unaryfunc f;
Guido van Rossumb8f63662001-08-15 23:57:02 +00002946
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002947 f = Py_TYPE(self)->tp_repr;
Benjamin Peterson7b166872012-04-24 11:06:25 -04002948 if (f == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002949 f = object_repr;
2950 return f(self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002951}
2952
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002953static PyObject *
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002954object_richcompare(PyObject *self, PyObject *other, int op)
2955{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002956 PyObject *res;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002957
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002958 switch (op) {
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002959
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002960 case Py_EQ:
2961 /* Return NotImplemented instead of False, so if two
2962 objects are compared, both get a chance at the
2963 comparison. See issue #1393. */
2964 res = (self == other) ? Py_True : Py_NotImplemented;
2965 Py_INCREF(res);
2966 break;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002967
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002968 case Py_NE:
2969 /* By default, != returns the opposite of ==,
2970 unless the latter returns NotImplemented. */
2971 res = PyObject_RichCompare(self, other, Py_EQ);
2972 if (res != NULL && res != Py_NotImplemented) {
2973 int ok = PyObject_IsTrue(res);
2974 Py_DECREF(res);
2975 if (ok < 0)
2976 res = NULL;
2977 else {
2978 if (ok)
2979 res = Py_False;
2980 else
2981 res = Py_True;
2982 Py_INCREF(res);
2983 }
2984 }
2985 break;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002986
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002987 default:
2988 res = Py_NotImplemented;
2989 Py_INCREF(res);
2990 break;
2991 }
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002992
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002993 return res;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002994}
2995
2996static PyObject *
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002997object_get_class(PyObject *self, void *closure)
2998{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002999 Py_INCREF(Py_TYPE(self));
3000 return (PyObject *)(Py_TYPE(self));
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003001}
3002
3003static int
3004equiv_structs(PyTypeObject *a, PyTypeObject *b)
3005{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003006 return a == b ||
3007 (a != NULL &&
3008 b != NULL &&
3009 a->tp_basicsize == b->tp_basicsize &&
3010 a->tp_itemsize == b->tp_itemsize &&
3011 a->tp_dictoffset == b->tp_dictoffset &&
3012 a->tp_weaklistoffset == b->tp_weaklistoffset &&
3013 ((a->tp_flags & Py_TPFLAGS_HAVE_GC) ==
3014 (b->tp_flags & Py_TPFLAGS_HAVE_GC)));
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003015}
3016
3017static int
3018same_slots_added(PyTypeObject *a, PyTypeObject *b)
3019{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003020 PyTypeObject *base = a->tp_base;
3021 Py_ssize_t size;
3022 PyObject *slots_a, *slots_b;
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003023
Benjamin Peterson67641d22011-01-17 19:24:34 +00003024 assert(base == b->tp_base);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003025 size = base->tp_basicsize;
3026 if (a->tp_dictoffset == size && b->tp_dictoffset == size)
3027 size += sizeof(PyObject *);
3028 if (a->tp_weaklistoffset == size && b->tp_weaklistoffset == size)
3029 size += sizeof(PyObject *);
Guido van Rossumd8faa362007-04-27 19:54:29 +00003030
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003031 /* Check slots compliance */
3032 slots_a = ((PyHeapTypeObject *)a)->ht_slots;
3033 slots_b = ((PyHeapTypeObject *)b)->ht_slots;
3034 if (slots_a && slots_b) {
3035 if (PyObject_RichCompareBool(slots_a, slots_b, Py_EQ) != 1)
3036 return 0;
3037 size += sizeof(PyObject *) * PyTuple_GET_SIZE(slots_a);
3038 }
3039 return size == a->tp_basicsize && size == b->tp_basicsize;
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003040}
3041
3042static int
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003043compatible_for_assignment(PyTypeObject* oldto, PyTypeObject* newto, char* attr)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003044{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003045 PyTypeObject *newbase, *oldbase;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003046
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003047 if (newto->tp_dealloc != oldto->tp_dealloc ||
3048 newto->tp_free != oldto->tp_free)
3049 {
3050 PyErr_Format(PyExc_TypeError,
3051 "%s assignment: "
3052 "'%s' deallocator differs from '%s'",
3053 attr,
3054 newto->tp_name,
3055 oldto->tp_name);
3056 return 0;
3057 }
3058 newbase = newto;
3059 oldbase = oldto;
3060 while (equiv_structs(newbase, newbase->tp_base))
3061 newbase = newbase->tp_base;
3062 while (equiv_structs(oldbase, oldbase->tp_base))
3063 oldbase = oldbase->tp_base;
3064 if (newbase != oldbase &&
3065 (newbase->tp_base != oldbase->tp_base ||
3066 !same_slots_added(newbase, oldbase))) {
3067 PyErr_Format(PyExc_TypeError,
3068 "%s assignment: "
3069 "'%s' object layout differs from '%s'",
3070 attr,
3071 newto->tp_name,
3072 oldto->tp_name);
3073 return 0;
3074 }
Tim Petersea7f75d2002-12-07 21:39:16 +00003075
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003076 return 1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003077}
3078
3079static int
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003080object_set_class(PyObject *self, PyObject *value, void *closure)
3081{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003082 PyTypeObject *oldto = Py_TYPE(self);
3083 PyTypeObject *newto;
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003084
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003085 if (value == NULL) {
3086 PyErr_SetString(PyExc_TypeError,
3087 "can't delete __class__ attribute");
3088 return -1;
3089 }
3090 if (!PyType_Check(value)) {
3091 PyErr_Format(PyExc_TypeError,
3092 "__class__ must be set to new-style class, not '%s' object",
3093 Py_TYPE(value)->tp_name);
3094 return -1;
3095 }
3096 newto = (PyTypeObject *)value;
3097 if (!(newto->tp_flags & Py_TPFLAGS_HEAPTYPE) ||
3098 !(oldto->tp_flags & Py_TPFLAGS_HEAPTYPE))
3099 {
3100 PyErr_Format(PyExc_TypeError,
3101 "__class__ assignment: only for heap types");
3102 return -1;
3103 }
3104 if (compatible_for_assignment(newto, oldto, "__class__")) {
3105 Py_INCREF(newto);
3106 Py_TYPE(self) = newto;
3107 Py_DECREF(oldto);
3108 return 0;
3109 }
3110 else {
3111 return -1;
3112 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003113}
3114
3115static PyGetSetDef object_getsets[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003116 {"__class__", object_get_class, object_set_class,
3117 PyDoc_STR("the object's class")},
3118 {0}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003119};
3120
Guido van Rossumc53f0092003-02-18 22:05:12 +00003121
Guido van Rossum036f9992003-02-21 22:02:54 +00003122/* Stuff to implement __reduce_ex__ for pickle protocols >= 2.
Alexandre Vassalottif7fa63d2008-05-11 08:55:36 +00003123 We fall back to helpers in copyreg for:
Guido van Rossum036f9992003-02-21 22:02:54 +00003124 - pickle protocols < 2
3125 - calculating the list of slot names (done only once per class)
3126 - the __newobj__ function (which is used as a token but never called)
3127*/
3128
3129static PyObject *
Alexandre Vassalottif7fa63d2008-05-11 08:55:36 +00003130import_copyreg(void)
Guido van Rossum036f9992003-02-21 22:02:54 +00003131{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003132 static PyObject *copyreg_str;
Guido van Rossum3926a632001-09-25 16:25:58 +00003133
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003134 if (!copyreg_str) {
3135 copyreg_str = PyUnicode_InternFromString("copyreg");
3136 if (copyreg_str == NULL)
3137 return NULL;
3138 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003139
Antoine Pitrouff150f22010-10-22 21:41:05 +00003140 return PyImport_Import(copyreg_str);
Guido van Rossum036f9992003-02-21 22:02:54 +00003141}
3142
3143static PyObject *
3144slotnames(PyObject *cls)
3145{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003146 PyObject *clsdict;
3147 PyObject *copyreg;
3148 PyObject *slotnames;
Guido van Rossum036f9992003-02-21 22:02:54 +00003149
Antoine Pitrouff150f22010-10-22 21:41:05 +00003150 if (!PyType_Check(cls)) {
3151 Py_INCREF(Py_None);
3152 return Py_None;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003153 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003154
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003155 clsdict = ((PyTypeObject *)cls)->tp_dict;
Antoine Pitrouff150f22010-10-22 21:41:05 +00003156 slotnames = PyDict_GetItemString(clsdict, "__slotnames__");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003157 if (slotnames != NULL && PyList_Check(slotnames)) {
3158 Py_INCREF(slotnames);
3159 return slotnames;
3160 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003161
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003162 copyreg = import_copyreg();
3163 if (copyreg == NULL)
3164 return NULL;
Guido van Rossum036f9992003-02-21 22:02:54 +00003165
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003166 slotnames = PyObject_CallMethod(copyreg, "_slotnames", "O", cls);
3167 Py_DECREF(copyreg);
3168 if (slotnames != NULL &&
3169 slotnames != Py_None &&
3170 !PyList_Check(slotnames))
3171 {
3172 PyErr_SetString(PyExc_TypeError,
3173 "copyreg._slotnames didn't return a list or None");
3174 Py_DECREF(slotnames);
3175 slotnames = NULL;
3176 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003177
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003178 return slotnames;
Guido van Rossum036f9992003-02-21 22:02:54 +00003179}
3180
3181static PyObject *
3182reduce_2(PyObject *obj)
3183{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003184 PyObject *cls, *getnewargs;
3185 PyObject *args = NULL, *args2 = NULL;
3186 PyObject *getstate = NULL, *state = NULL, *names = NULL;
3187 PyObject *slots = NULL, *listitems = NULL, *dictitems = NULL;
3188 PyObject *copyreg = NULL, *newobj = NULL, *res = NULL;
3189 Py_ssize_t i, n;
Guido van Rossum036f9992003-02-21 22:02:54 +00003190
Antoine Pitrouff150f22010-10-22 21:41:05 +00003191 cls = PyObject_GetAttrString(obj, "__class__");
3192 if (cls == NULL)
3193 return NULL;
Guido van Rossum036f9992003-02-21 22:02:54 +00003194
Antoine Pitrouff150f22010-10-22 21:41:05 +00003195 getnewargs = PyObject_GetAttrString(obj, "__getnewargs__");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003196 if (getnewargs != NULL) {
3197 args = PyObject_CallObject(getnewargs, NULL);
3198 Py_DECREF(getnewargs);
3199 if (args != NULL && !PyTuple_Check(args)) {
3200 PyErr_Format(PyExc_TypeError,
3201 "__getnewargs__ should return a tuple, "
3202 "not '%.200s'", Py_TYPE(args)->tp_name);
3203 goto end;
3204 }
3205 }
3206 else {
3207 PyErr_Clear();
3208 args = PyTuple_New(0);
3209 }
3210 if (args == NULL)
3211 goto end;
Guido van Rossum036f9992003-02-21 22:02:54 +00003212
Antoine Pitrouff150f22010-10-22 21:41:05 +00003213 getstate = PyObject_GetAttrString(obj, "__getstate__");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003214 if (getstate != NULL) {
3215 state = PyObject_CallObject(getstate, NULL);
3216 Py_DECREF(getstate);
3217 if (state == NULL)
3218 goto end;
3219 }
3220 else {
3221 PyErr_Clear();
Antoine Pitrouff150f22010-10-22 21:41:05 +00003222 state = PyObject_GetAttrString(obj, "__dict__");
3223 if (state == NULL) {
3224 PyErr_Clear();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003225 state = Py_None;
Antoine Pitrouff150f22010-10-22 21:41:05 +00003226 Py_INCREF(state);
3227 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003228 names = slotnames(cls);
3229 if (names == NULL)
3230 goto end;
Antoine Pitrouff150f22010-10-22 21:41:05 +00003231 if (names != Py_None) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003232 assert(PyList_Check(names));
3233 slots = PyDict_New();
3234 if (slots == NULL)
3235 goto end;
3236 n = 0;
3237 /* Can't pre-compute the list size; the list
3238 is stored on the class so accessible to other
3239 threads, which may be run by DECREF */
3240 for (i = 0; i < PyList_GET_SIZE(names); i++) {
3241 PyObject *name, *value;
3242 name = PyList_GET_ITEM(names, i);
3243 value = PyObject_GetAttr(obj, name);
3244 if (value == NULL)
3245 PyErr_Clear();
3246 else {
3247 int err = PyDict_SetItem(slots, name,
3248 value);
3249 Py_DECREF(value);
3250 if (err)
3251 goto end;
3252 n++;
3253 }
3254 }
3255 if (n) {
3256 state = Py_BuildValue("(NO)", state, slots);
3257 if (state == NULL)
3258 goto end;
3259 }
3260 }
3261 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003262
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003263 if (!PyList_Check(obj)) {
3264 listitems = Py_None;
3265 Py_INCREF(listitems);
3266 }
3267 else {
3268 listitems = PyObject_GetIter(obj);
3269 if (listitems == NULL)
3270 goto end;
3271 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003272
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003273 if (!PyDict_Check(obj)) {
3274 dictitems = Py_None;
3275 Py_INCREF(dictitems);
3276 }
3277 else {
3278 PyObject *items = PyObject_CallMethod(obj, "items", "");
3279 if (items == NULL)
3280 goto end;
3281 dictitems = PyObject_GetIter(items);
3282 Py_DECREF(items);
3283 if (dictitems == NULL)
3284 goto end;
3285 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003286
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003287 copyreg = import_copyreg();
3288 if (copyreg == NULL)
3289 goto end;
Antoine Pitrouff150f22010-10-22 21:41:05 +00003290 newobj = PyObject_GetAttrString(copyreg, "__newobj__");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003291 if (newobj == NULL)
3292 goto end;
Guido van Rossum036f9992003-02-21 22:02:54 +00003293
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003294 n = PyTuple_GET_SIZE(args);
3295 args2 = PyTuple_New(n+1);
3296 if (args2 == NULL)
3297 goto end;
3298 PyTuple_SET_ITEM(args2, 0, cls);
Antoine Pitrouff150f22010-10-22 21:41:05 +00003299 cls = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003300 for (i = 0; i < n; i++) {
3301 PyObject *v = PyTuple_GET_ITEM(args, i);
3302 Py_INCREF(v);
3303 PyTuple_SET_ITEM(args2, i+1, v);
3304 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003305
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003306 res = PyTuple_Pack(5, newobj, args2, state, listitems, dictitems);
Guido van Rossum036f9992003-02-21 22:02:54 +00003307
3308 end:
Antoine Pitrouff150f22010-10-22 21:41:05 +00003309 Py_XDECREF(cls);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003310 Py_XDECREF(args);
3311 Py_XDECREF(args2);
3312 Py_XDECREF(slots);
3313 Py_XDECREF(state);
3314 Py_XDECREF(names);
3315 Py_XDECREF(listitems);
3316 Py_XDECREF(dictitems);
3317 Py_XDECREF(copyreg);
3318 Py_XDECREF(newobj);
3319 return res;
Guido van Rossum036f9992003-02-21 22:02:54 +00003320}
3321
Guido van Rossumd8faa362007-04-27 19:54:29 +00003322/*
3323 * There were two problems when object.__reduce__ and object.__reduce_ex__
3324 * were implemented in the same function:
3325 * - trying to pickle an object with a custom __reduce__ method that
3326 * fell back to object.__reduce__ in certain circumstances led to
3327 * infinite recursion at Python level and eventual RuntimeError.
3328 * - Pickling objects that lied about their type by overwriting the
3329 * __class__ descriptor could lead to infinite recursion at C level
3330 * and eventual segfault.
3331 *
3332 * Because of backwards compatibility, the two methods still have to
3333 * behave in the same way, even if this is not required by the pickle
3334 * protocol. This common functionality was moved to the _common_reduce
3335 * function.
3336 */
3337static PyObject *
3338_common_reduce(PyObject *self, int proto)
3339{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003340 PyObject *copyreg, *res;
Guido van Rossumd8faa362007-04-27 19:54:29 +00003341
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003342 if (proto >= 2)
3343 return reduce_2(self);
Guido van Rossumd8faa362007-04-27 19:54:29 +00003344
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003345 copyreg = import_copyreg();
3346 if (!copyreg)
3347 return NULL;
Guido van Rossumd8faa362007-04-27 19:54:29 +00003348
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003349 res = PyEval_CallMethod(copyreg, "_reduce_ex", "(Oi)", self, proto);
3350 Py_DECREF(copyreg);
Guido van Rossumd8faa362007-04-27 19:54:29 +00003351
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003352 return res;
Guido van Rossumd8faa362007-04-27 19:54:29 +00003353}
3354
3355static PyObject *
3356object_reduce(PyObject *self, PyObject *args)
3357{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003358 int proto = 0;
Guido van Rossumd8faa362007-04-27 19:54:29 +00003359
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003360 if (!PyArg_ParseTuple(args, "|i:__reduce__", &proto))
3361 return NULL;
Guido van Rossumd8faa362007-04-27 19:54:29 +00003362
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003363 return _common_reduce(self, proto);
Guido van Rossumd8faa362007-04-27 19:54:29 +00003364}
3365
Guido van Rossum036f9992003-02-21 22:02:54 +00003366static PyObject *
3367object_reduce_ex(PyObject *self, PyObject *args)
3368{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003369 PyObject *reduce, *res;
3370 int proto = 0;
Guido van Rossum036f9992003-02-21 22:02:54 +00003371
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003372 if (!PyArg_ParseTuple(args, "|i:__reduce_ex__", &proto))
3373 return NULL;
Guido van Rossum036f9992003-02-21 22:02:54 +00003374
Antoine Pitrouff150f22010-10-22 21:41:05 +00003375 reduce = PyObject_GetAttrString(self, "__reduce__");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003376 if (reduce == NULL)
3377 PyErr_Clear();
3378 else {
Antoine Pitrouff150f22010-10-22 21:41:05 +00003379 PyObject *cls, *clsreduce, *objreduce;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003380 int override;
Antoine Pitrouff150f22010-10-22 21:41:05 +00003381 cls = PyObject_GetAttrString(self, "__class__");
3382 if (cls == NULL) {
3383 Py_DECREF(reduce);
3384 return NULL;
3385 }
3386 clsreduce = PyObject_GetAttrString(cls, "__reduce__");
3387 Py_DECREF(cls);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003388 if (clsreduce == NULL) {
3389 Py_DECREF(reduce);
3390 return NULL;
3391 }
Antoine Pitrouff150f22010-10-22 21:41:05 +00003392 objreduce = PyDict_GetItemString(PyBaseObject_Type.tp_dict,
3393 "__reduce__");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003394 override = (clsreduce != objreduce);
3395 Py_DECREF(clsreduce);
3396 if (override) {
3397 res = PyObject_CallObject(reduce, NULL);
3398 Py_DECREF(reduce);
3399 return res;
3400 }
3401 else
3402 Py_DECREF(reduce);
3403 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003404
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003405 return _common_reduce(self, proto);
Guido van Rossum3926a632001-09-25 16:25:58 +00003406}
3407
Christian Heimes9e7f1d22008-02-28 12:27:11 +00003408static PyObject *
3409object_subclasshook(PyObject *cls, PyObject *args)
3410{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003411 Py_INCREF(Py_NotImplemented);
3412 return Py_NotImplemented;
Christian Heimes9e7f1d22008-02-28 12:27:11 +00003413}
3414
3415PyDoc_STRVAR(object_subclasshook_doc,
3416"Abstract classes can override this to customize issubclass().\n"
3417"\n"
3418"This is invoked early on by abc.ABCMeta.__subclasscheck__().\n"
3419"It should return True, False or NotImplemented. If it returns\n"
3420"NotImplemented, the normal algorithm is used. Otherwise, it\n"
3421"overrides the normal algorithm (and the outcome is cached).\n");
Eric Smith8c663262007-08-25 02:26:07 +00003422
3423/*
3424 from PEP 3101, this code implements:
3425
3426 class object:
3427 def __format__(self, format_spec):
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003428 return format(str(self), format_spec)
Eric Smith8c663262007-08-25 02:26:07 +00003429*/
3430static PyObject *
3431object_format(PyObject *self, PyObject *args)
3432{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003433 PyObject *format_spec;
3434 PyObject *self_as_str = NULL;
3435 PyObject *result = NULL;
Eric Smith8c663262007-08-25 02:26:07 +00003436
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003437 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
3438 return NULL;
Eric Smith8c663262007-08-25 02:26:07 +00003439
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003440 self_as_str = PyObject_Str(self);
Eric Smithe4d63172010-09-13 20:48:43 +00003441 if (self_as_str != NULL) {
3442 /* Issue 7994: If we're converting to a string, we
3443 should reject format specifications */
3444 if (PyUnicode_GET_SIZE(format_spec) > 0) {
3445 if (PyErr_WarnEx(PyExc_PendingDeprecationWarning,
3446 "object.__format__ with a non-empty format "
3447 "string is deprecated", 1) < 0) {
3448 goto done;
3449 }
3450 /* Eventually this will become an error:
3451 PyErr_Format(PyExc_TypeError,
3452 "non-empty format string passed to object.__format__");
3453 goto done;
3454 */
3455 }
Eric Smith8c663262007-08-25 02:26:07 +00003456
Eric Smithe4d63172010-09-13 20:48:43 +00003457 result = PyObject_Format(self_as_str, format_spec);
3458 }
3459
3460done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003461 Py_XDECREF(self_as_str);
Eric Smith8c663262007-08-25 02:26:07 +00003462
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003463 return result;
Eric Smith8c663262007-08-25 02:26:07 +00003464}
3465
Martin v. Löwis00709aa2008-06-04 14:18:43 +00003466static PyObject *
3467object_sizeof(PyObject *self, PyObject *args)
3468{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003469 Py_ssize_t res, isize;
Martin v. Löwis00709aa2008-06-04 14:18:43 +00003470
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003471 res = 0;
3472 isize = self->ob_type->tp_itemsize;
3473 if (isize > 0)
3474 res = Py_SIZE(self->ob_type) * isize;
3475 res += self->ob_type->tp_basicsize;
Martin v. Löwis00709aa2008-06-04 14:18:43 +00003476
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003477 return PyLong_FromSsize_t(res);
Martin v. Löwis00709aa2008-06-04 14:18:43 +00003478}
3479
Guido van Rossum3926a632001-09-25 16:25:58 +00003480static PyMethodDef object_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003481 {"__reduce_ex__", object_reduce_ex, METH_VARARGS,
3482 PyDoc_STR("helper for pickle")},
3483 {"__reduce__", object_reduce, METH_VARARGS,
3484 PyDoc_STR("helper for pickle")},
3485 {"__subclasshook__", object_subclasshook, METH_CLASS | METH_VARARGS,
3486 object_subclasshook_doc},
3487 {"__format__", object_format, METH_VARARGS,
3488 PyDoc_STR("default object formatter")},
3489 {"__sizeof__", object_sizeof, METH_NOARGS,
Benjamin Petersonfbe56bb2011-05-24 12:42:51 -05003490 PyDoc_STR("__sizeof__() -> int\nsize of object in memory, in bytes")},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003491 {0}
Guido van Rossum3926a632001-09-25 16:25:58 +00003492};
3493
Guido van Rossum036f9992003-02-21 22:02:54 +00003494
Tim Peters6d6c1a32001-08-02 04:15:00 +00003495PyTypeObject PyBaseObject_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003496 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3497 "object", /* tp_name */
3498 sizeof(PyObject), /* tp_basicsize */
3499 0, /* tp_itemsize */
3500 object_dealloc, /* tp_dealloc */
3501 0, /* tp_print */
3502 0, /* tp_getattr */
3503 0, /* tp_setattr */
3504 0, /* tp_reserved */
3505 object_repr, /* tp_repr */
3506 0, /* tp_as_number */
3507 0, /* tp_as_sequence */
3508 0, /* tp_as_mapping */
3509 (hashfunc)_Py_HashPointer, /* tp_hash */
3510 0, /* tp_call */
3511 object_str, /* tp_str */
3512 PyObject_GenericGetAttr, /* tp_getattro */
3513 PyObject_GenericSetAttr, /* tp_setattro */
3514 0, /* tp_as_buffer */
3515 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
3516 PyDoc_STR("The most base type"), /* tp_doc */
3517 0, /* tp_traverse */
3518 0, /* tp_clear */
3519 object_richcompare, /* tp_richcompare */
3520 0, /* tp_weaklistoffset */
3521 0, /* tp_iter */
3522 0, /* tp_iternext */
3523 object_methods, /* tp_methods */
3524 0, /* tp_members */
3525 object_getsets, /* tp_getset */
3526 0, /* tp_base */
3527 0, /* tp_dict */
3528 0, /* tp_descr_get */
3529 0, /* tp_descr_set */
3530 0, /* tp_dictoffset */
3531 object_init, /* tp_init */
3532 PyType_GenericAlloc, /* tp_alloc */
3533 object_new, /* tp_new */
3534 PyObject_Del, /* tp_free */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003535};
3536
3537
Guido van Rossum50e9fb92006-08-17 05:42:55 +00003538/* Add the methods from tp_methods to the __dict__ in a type object */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003539
3540static int
3541add_methods(PyTypeObject *type, PyMethodDef *meth)
3542{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003543 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003544
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003545 for (; meth->ml_name != NULL; meth++) {
3546 PyObject *descr;
Benjamin Peterson89a6e9a2012-05-08 09:22:24 -04003547 int err;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003548 if (PyDict_GetItemString(dict, meth->ml_name) &&
3549 !(meth->ml_flags & METH_COEXIST))
3550 continue;
3551 if (meth->ml_flags & METH_CLASS) {
3552 if (meth->ml_flags & METH_STATIC) {
3553 PyErr_SetString(PyExc_ValueError,
3554 "method cannot be both class and static");
3555 return -1;
3556 }
3557 descr = PyDescr_NewClassMethod(type, meth);
3558 }
3559 else if (meth->ml_flags & METH_STATIC) {
3560 PyObject *cfunc = PyCFunction_New(meth, NULL);
3561 if (cfunc == NULL)
3562 return -1;
3563 descr = PyStaticMethod_New(cfunc);
3564 Py_DECREF(cfunc);
3565 }
3566 else {
3567 descr = PyDescr_NewMethod(type, meth);
3568 }
3569 if (descr == NULL)
3570 return -1;
Benjamin Peterson89a6e9a2012-05-08 09:22:24 -04003571 err = PyDict_SetItemString(dict, meth->ml_name, descr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003572 Py_DECREF(descr);
Benjamin Peterson89a6e9a2012-05-08 09:22:24 -04003573 if (err < 0)
3574 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003575 }
3576 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003577}
3578
3579static int
Guido van Rossum6f799372001-09-20 20:46:19 +00003580add_members(PyTypeObject *type, PyMemberDef *memb)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003581{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003582 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003583
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003584 for (; memb->name != NULL; memb++) {
3585 PyObject *descr;
3586 if (PyDict_GetItemString(dict, memb->name))
3587 continue;
3588 descr = PyDescr_NewMember(type, memb);
3589 if (descr == NULL)
3590 return -1;
3591 if (PyDict_SetItemString(dict, memb->name, descr) < 0)
3592 return -1;
3593 Py_DECREF(descr);
3594 }
3595 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003596}
3597
3598static int
Guido van Rossum32d34c82001-09-20 21:45:26 +00003599add_getset(PyTypeObject *type, PyGetSetDef *gsp)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003600{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003601 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003602
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003603 for (; gsp->name != NULL; gsp++) {
3604 PyObject *descr;
3605 if (PyDict_GetItemString(dict, gsp->name))
3606 continue;
3607 descr = PyDescr_NewGetSet(type, gsp);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003608
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003609 if (descr == NULL)
3610 return -1;
3611 if (PyDict_SetItemString(dict, gsp->name, descr) < 0)
3612 return -1;
3613 Py_DECREF(descr);
3614 }
3615 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003616}
3617
Guido van Rossum13d52f02001-08-10 21:24:08 +00003618static void
3619inherit_special(PyTypeObject *type, PyTypeObject *base)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003620{
Tim Peters6d6c1a32001-08-02 04:15:00 +00003621
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003622 /* Copying basicsize is connected to the GC flags */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003623 if (!(type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
3624 (base->tp_flags & Py_TPFLAGS_HAVE_GC) &&
3625 (!type->tp_traverse && !type->tp_clear)) {
3626 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
3627 if (type->tp_traverse == NULL)
3628 type->tp_traverse = base->tp_traverse;
3629 if (type->tp_clear == NULL)
3630 type->tp_clear = base->tp_clear;
3631 }
3632 {
3633 /* The condition below could use some explanation.
3634 It appears that tp_new is not inherited for static types
3635 whose base class is 'object'; this seems to be a precaution
3636 so that old extension types don't suddenly become
3637 callable (object.__new__ wouldn't insure the invariants
3638 that the extension type's own factory function ensures).
3639 Heap types, of course, are under our control, so they do
3640 inherit tp_new; static extension types that specify some
3641 other built-in type as the default are considered
3642 new-style-aware so they also inherit object.__new__. */
3643 if (base != &PyBaseObject_Type ||
3644 (type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
3645 if (type->tp_new == NULL)
3646 type->tp_new = base->tp_new;
3647 }
3648 }
Benjamin Petersona7465e22010-07-05 15:01:22 +00003649 if (type->tp_basicsize == 0)
3650 type->tp_basicsize = base->tp_basicsize;
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00003651
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003652 /* Copy other non-function slots */
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00003653
3654#undef COPYVAL
3655#define COPYVAL(SLOT) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003656 if (type->SLOT == 0) type->SLOT = base->SLOT
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00003657
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003658 COPYVAL(tp_itemsize);
3659 COPYVAL(tp_weaklistoffset);
3660 COPYVAL(tp_dictoffset);
Thomas Wouters27d517b2007-02-25 20:39:11 +00003661
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003662 /* Setup fast subclass flags */
3663 if (PyType_IsSubtype(base, (PyTypeObject*)PyExc_BaseException))
3664 type->tp_flags |= Py_TPFLAGS_BASE_EXC_SUBCLASS;
3665 else if (PyType_IsSubtype(base, &PyType_Type))
3666 type->tp_flags |= Py_TPFLAGS_TYPE_SUBCLASS;
3667 else if (PyType_IsSubtype(base, &PyLong_Type))
3668 type->tp_flags |= Py_TPFLAGS_LONG_SUBCLASS;
3669 else if (PyType_IsSubtype(base, &PyBytes_Type))
3670 type->tp_flags |= Py_TPFLAGS_BYTES_SUBCLASS;
3671 else if (PyType_IsSubtype(base, &PyUnicode_Type))
3672 type->tp_flags |= Py_TPFLAGS_UNICODE_SUBCLASS;
3673 else if (PyType_IsSubtype(base, &PyTuple_Type))
3674 type->tp_flags |= Py_TPFLAGS_TUPLE_SUBCLASS;
3675 else if (PyType_IsSubtype(base, &PyList_Type))
3676 type->tp_flags |= Py_TPFLAGS_LIST_SUBCLASS;
3677 else if (PyType_IsSubtype(base, &PyDict_Type))
3678 type->tp_flags |= Py_TPFLAGS_DICT_SUBCLASS;
Guido van Rossum13d52f02001-08-10 21:24:08 +00003679}
3680
Guido van Rossumf5243f02008-01-01 04:06:48 +00003681static char *hash_name_op[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003682 "__eq__",
3683 "__hash__",
3684 NULL
Guido van Rossum38938152006-08-21 23:36:26 +00003685};
3686
3687static int
Guido van Rossumf5243f02008-01-01 04:06:48 +00003688overrides_hash(PyTypeObject *type)
Guido van Rossum38938152006-08-21 23:36:26 +00003689{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003690 char **p;
3691 PyObject *dict = type->tp_dict;
Guido van Rossum38938152006-08-21 23:36:26 +00003692
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003693 assert(dict != NULL);
3694 for (p = hash_name_op; *p; p++) {
3695 if (PyDict_GetItemString(dict, *p) != NULL)
3696 return 1;
3697 }
3698 return 0;
Guido van Rossum38938152006-08-21 23:36:26 +00003699}
3700
Guido van Rossum13d52f02001-08-10 21:24:08 +00003701static void
3702inherit_slots(PyTypeObject *type, PyTypeObject *base)
3703{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003704 PyTypeObject *basebase;
Guido van Rossum13d52f02001-08-10 21:24:08 +00003705
3706#undef SLOTDEFINED
Tim Peters6d6c1a32001-08-02 04:15:00 +00003707#undef COPYSLOT
3708#undef COPYNUM
3709#undef COPYSEQ
3710#undef COPYMAP
Guido van Rossum5af588b2001-10-12 14:13:21 +00003711#undef COPYBUF
Guido van Rossum13d52f02001-08-10 21:24:08 +00003712
3713#define SLOTDEFINED(SLOT) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003714 (base->SLOT != 0 && \
3715 (basebase == NULL || base->SLOT != basebase->SLOT))
Guido van Rossum13d52f02001-08-10 21:24:08 +00003716
Tim Peters6d6c1a32001-08-02 04:15:00 +00003717#define COPYSLOT(SLOT) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003718 if (!type->SLOT && SLOTDEFINED(SLOT)) type->SLOT = base->SLOT
Tim Peters6d6c1a32001-08-02 04:15:00 +00003719
3720#define COPYNUM(SLOT) COPYSLOT(tp_as_number->SLOT)
3721#define COPYSEQ(SLOT) COPYSLOT(tp_as_sequence->SLOT)
3722#define COPYMAP(SLOT) COPYSLOT(tp_as_mapping->SLOT)
Tim Petersfc57ccb2001-10-12 02:38:24 +00003723#define COPYBUF(SLOT) COPYSLOT(tp_as_buffer->SLOT)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003724
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003725 /* This won't inherit indirect slots (from tp_as_number etc.)
3726 if type doesn't provide the space. */
Guido van Rossum13d52f02001-08-10 21:24:08 +00003727
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003728 if (type->tp_as_number != NULL && base->tp_as_number != NULL) {
3729 basebase = base->tp_base;
3730 if (basebase->tp_as_number == NULL)
3731 basebase = NULL;
3732 COPYNUM(nb_add);
3733 COPYNUM(nb_subtract);
3734 COPYNUM(nb_multiply);
3735 COPYNUM(nb_remainder);
3736 COPYNUM(nb_divmod);
3737 COPYNUM(nb_power);
3738 COPYNUM(nb_negative);
3739 COPYNUM(nb_positive);
3740 COPYNUM(nb_absolute);
3741 COPYNUM(nb_bool);
3742 COPYNUM(nb_invert);
3743 COPYNUM(nb_lshift);
3744 COPYNUM(nb_rshift);
3745 COPYNUM(nb_and);
3746 COPYNUM(nb_xor);
3747 COPYNUM(nb_or);
3748 COPYNUM(nb_int);
3749 COPYNUM(nb_float);
3750 COPYNUM(nb_inplace_add);
3751 COPYNUM(nb_inplace_subtract);
3752 COPYNUM(nb_inplace_multiply);
3753 COPYNUM(nb_inplace_remainder);
3754 COPYNUM(nb_inplace_power);
3755 COPYNUM(nb_inplace_lshift);
3756 COPYNUM(nb_inplace_rshift);
3757 COPYNUM(nb_inplace_and);
3758 COPYNUM(nb_inplace_xor);
3759 COPYNUM(nb_inplace_or);
3760 COPYNUM(nb_true_divide);
3761 COPYNUM(nb_floor_divide);
3762 COPYNUM(nb_inplace_true_divide);
3763 COPYNUM(nb_inplace_floor_divide);
3764 COPYNUM(nb_index);
3765 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003766
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003767 if (type->tp_as_sequence != NULL && base->tp_as_sequence != NULL) {
3768 basebase = base->tp_base;
3769 if (basebase->tp_as_sequence == NULL)
3770 basebase = NULL;
3771 COPYSEQ(sq_length);
3772 COPYSEQ(sq_concat);
3773 COPYSEQ(sq_repeat);
3774 COPYSEQ(sq_item);
3775 COPYSEQ(sq_ass_item);
3776 COPYSEQ(sq_contains);
3777 COPYSEQ(sq_inplace_concat);
3778 COPYSEQ(sq_inplace_repeat);
3779 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003780
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003781 if (type->tp_as_mapping != NULL && base->tp_as_mapping != NULL) {
3782 basebase = base->tp_base;
3783 if (basebase->tp_as_mapping == NULL)
3784 basebase = NULL;
3785 COPYMAP(mp_length);
3786 COPYMAP(mp_subscript);
3787 COPYMAP(mp_ass_subscript);
3788 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003789
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003790 if (type->tp_as_buffer != NULL && base->tp_as_buffer != NULL) {
3791 basebase = base->tp_base;
3792 if (basebase->tp_as_buffer == NULL)
3793 basebase = NULL;
3794 COPYBUF(bf_getbuffer);
3795 COPYBUF(bf_releasebuffer);
3796 }
Tim Petersfc57ccb2001-10-12 02:38:24 +00003797
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003798 basebase = base->tp_base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003799
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003800 COPYSLOT(tp_dealloc);
3801 if (type->tp_getattr == NULL && type->tp_getattro == NULL) {
3802 type->tp_getattr = base->tp_getattr;
3803 type->tp_getattro = base->tp_getattro;
3804 }
3805 if (type->tp_setattr == NULL && type->tp_setattro == NULL) {
3806 type->tp_setattr = base->tp_setattr;
3807 type->tp_setattro = base->tp_setattro;
3808 }
3809 /* tp_reserved is ignored */
3810 COPYSLOT(tp_repr);
3811 /* tp_hash see tp_richcompare */
3812 COPYSLOT(tp_call);
3813 COPYSLOT(tp_str);
3814 {
3815 /* Copy comparison-related slots only when
3816 not overriding them anywhere */
3817 if (type->tp_richcompare == NULL &&
3818 type->tp_hash == NULL &&
3819 !overrides_hash(type))
3820 {
3821 type->tp_richcompare = base->tp_richcompare;
3822 type->tp_hash = base->tp_hash;
3823 }
3824 }
3825 {
3826 COPYSLOT(tp_iter);
3827 COPYSLOT(tp_iternext);
3828 }
3829 {
3830 COPYSLOT(tp_descr_get);
3831 COPYSLOT(tp_descr_set);
3832 COPYSLOT(tp_dictoffset);
3833 COPYSLOT(tp_init);
3834 COPYSLOT(tp_alloc);
3835 COPYSLOT(tp_is_gc);
3836 if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) ==
3837 (base->tp_flags & Py_TPFLAGS_HAVE_GC)) {
3838 /* They agree about gc. */
3839 COPYSLOT(tp_free);
3840 }
3841 else if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
3842 type->tp_free == NULL &&
3843 base->tp_free == PyObject_Free) {
3844 /* A bit of magic to plug in the correct default
3845 * tp_free function when a derived class adds gc,
3846 * didn't define tp_free, and the base uses the
3847 * default non-gc tp_free.
3848 */
3849 type->tp_free = PyObject_GC_Del;
3850 }
3851 /* else they didn't agree about gc, and there isn't something
3852 * obvious to be done -- the type is on its own.
3853 */
3854 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003855}
3856
Jeremy Hylton938ace62002-07-17 16:30:39 +00003857static int add_operators(PyTypeObject *);
Guido van Rossum13d52f02001-08-10 21:24:08 +00003858
Tim Peters6d6c1a32001-08-02 04:15:00 +00003859int
Guido van Rossum528b7eb2001-08-07 17:24:28 +00003860PyType_Ready(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003861{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003862 PyObject *dict, *bases;
3863 PyTypeObject *base;
3864 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003865
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003866 if (type->tp_flags & Py_TPFLAGS_READY) {
3867 assert(type->tp_dict != NULL);
3868 return 0;
3869 }
3870 assert((type->tp_flags & Py_TPFLAGS_READYING) == 0);
Guido van Rossumd614f972001-08-10 17:39:49 +00003871
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003872 type->tp_flags |= Py_TPFLAGS_READYING;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003873
Tim Peters36eb4df2003-03-23 03:33:13 +00003874#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003875 /* PyType_Ready is the closest thing we have to a choke point
3876 * for type objects, so is the best place I can think of to try
3877 * to get type objects into the doubly-linked list of all objects.
3878 * Still, not all type objects go thru PyType_Ready.
3879 */
3880 _Py_AddToAllObjects((PyObject *)type, 0);
Tim Peters36eb4df2003-03-23 03:33:13 +00003881#endif
3882
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003883 /* Initialize tp_base (defaults to BaseObject unless that's us) */
3884 base = type->tp_base;
3885 if (base == NULL && type != &PyBaseObject_Type) {
3886 base = type->tp_base = &PyBaseObject_Type;
3887 Py_INCREF(base);
3888 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003889
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003890 /* Now the only way base can still be NULL is if type is
3891 * &PyBaseObject_Type.
3892 */
Guido van Rossum692cdbc2006-03-10 02:04:28 +00003893
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003894 /* Initialize the base class */
3895 if (base != NULL && base->tp_dict == NULL) {
3896 if (PyType_Ready(base) < 0)
3897 goto error;
3898 }
Guido van Rossum323a9cf2002-08-14 17:26:30 +00003899
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003900 /* Initialize ob_type if NULL. This means extensions that want to be
3901 compilable separately on Windows can call PyType_Ready() instead of
3902 initializing the ob_type field of their type objects. */
3903 /* The test for base != NULL is really unnecessary, since base is only
3904 NULL when type is &PyBaseObject_Type, and we know its ob_type is
3905 not NULL (it's initialized to &PyType_Type). But coverity doesn't
3906 know that. */
3907 if (Py_TYPE(type) == NULL && base != NULL)
3908 Py_TYPE(type) = Py_TYPE(base);
Guido van Rossum0986d822002-04-08 01:38:42 +00003909
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003910 /* Initialize tp_bases */
3911 bases = type->tp_bases;
3912 if (bases == NULL) {
3913 if (base == NULL)
3914 bases = PyTuple_New(0);
3915 else
3916 bases = PyTuple_Pack(1, base);
3917 if (bases == NULL)
3918 goto error;
3919 type->tp_bases = bases;
3920 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003921
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003922 /* Initialize tp_dict */
3923 dict = type->tp_dict;
3924 if (dict == NULL) {
3925 dict = PyDict_New();
3926 if (dict == NULL)
3927 goto error;
3928 type->tp_dict = dict;
3929 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003930
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003931 /* Add type-specific descriptors to tp_dict */
3932 if (add_operators(type) < 0)
3933 goto error;
3934 if (type->tp_methods != NULL) {
3935 if (add_methods(type, type->tp_methods) < 0)
3936 goto error;
3937 }
3938 if (type->tp_members != NULL) {
3939 if (add_members(type, type->tp_members) < 0)
3940 goto error;
3941 }
3942 if (type->tp_getset != NULL) {
3943 if (add_getset(type, type->tp_getset) < 0)
3944 goto error;
3945 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003946
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003947 /* Calculate method resolution order */
3948 if (mro_internal(type) < 0) {
3949 goto error;
3950 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003951
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003952 /* Inherit special flags from dominant base */
3953 if (type->tp_base != NULL)
3954 inherit_special(type, type->tp_base);
Guido van Rossum13d52f02001-08-10 21:24:08 +00003955
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003956 /* Initialize tp_dict properly */
3957 bases = type->tp_mro;
3958 assert(bases != NULL);
3959 assert(PyTuple_Check(bases));
3960 n = PyTuple_GET_SIZE(bases);
3961 for (i = 1; i < n; i++) {
3962 PyObject *b = PyTuple_GET_ITEM(bases, i);
3963 if (PyType_Check(b))
3964 inherit_slots(type, (PyTypeObject *)b);
3965 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003966
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003967 /* Sanity check for tp_free. */
3968 if (PyType_IS_GC(type) && (type->tp_flags & Py_TPFLAGS_BASETYPE) &&
3969 (type->tp_free == NULL || type->tp_free == PyObject_Del)) {
3970 /* This base class needs to call tp_free, but doesn't have
3971 * one, or its tp_free is for non-gc'ed objects.
3972 */
3973 PyErr_Format(PyExc_TypeError, "type '%.100s' participates in "
3974 "gc and is a base type but has inappropriate "
3975 "tp_free slot",
3976 type->tp_name);
3977 goto error;
3978 }
Tim Peters3cfe7542003-05-21 21:29:48 +00003979
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003980 /* if the type dictionary doesn't contain a __doc__, set it from
3981 the tp_doc slot.
3982 */
3983 if (PyDict_GetItemString(type->tp_dict, "__doc__") == NULL) {
3984 if (type->tp_doc != NULL) {
3985 PyObject *doc = PyUnicode_FromString(type->tp_doc);
3986 if (doc == NULL)
3987 goto error;
3988 PyDict_SetItemString(type->tp_dict, "__doc__", doc);
3989 Py_DECREF(doc);
3990 } else {
3991 PyDict_SetItemString(type->tp_dict,
3992 "__doc__", Py_None);
3993 }
3994 }
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00003995
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003996 /* Hack for tp_hash and __hash__.
3997 If after all that, tp_hash is still NULL, and __hash__ is not in
3998 tp_dict, set tp_hash to PyObject_HashNotImplemented and
3999 tp_dict['__hash__'] equal to None.
4000 This signals that __hash__ is not inherited.
4001 */
4002 if (type->tp_hash == NULL) {
4003 if (PyDict_GetItemString(type->tp_dict, "__hash__") == NULL) {
4004 if (PyDict_SetItemString(type->tp_dict, "__hash__", Py_None) < 0)
4005 goto error;
4006 type->tp_hash = PyObject_HashNotImplemented;
4007 }
4008 }
Guido van Rossum38938152006-08-21 23:36:26 +00004009
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004010 /* Some more special stuff */
4011 base = type->tp_base;
4012 if (base != NULL) {
4013 if (type->tp_as_number == NULL)
4014 type->tp_as_number = base->tp_as_number;
4015 if (type->tp_as_sequence == NULL)
4016 type->tp_as_sequence = base->tp_as_sequence;
4017 if (type->tp_as_mapping == NULL)
4018 type->tp_as_mapping = base->tp_as_mapping;
4019 if (type->tp_as_buffer == NULL)
4020 type->tp_as_buffer = base->tp_as_buffer;
4021 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004022
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004023 /* Link into each base class's list of subclasses */
4024 bases = type->tp_bases;
4025 n = PyTuple_GET_SIZE(bases);
4026 for (i = 0; i < n; i++) {
4027 PyObject *b = PyTuple_GET_ITEM(bases, i);
4028 if (PyType_Check(b) &&
4029 add_subclass((PyTypeObject *)b, type) < 0)
4030 goto error;
4031 }
Guido van Rossum1c450732001-10-08 15:18:27 +00004032
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004033 /* Warn for a type that implements tp_compare (now known as
4034 tp_reserved) but not tp_richcompare. */
4035 if (type->tp_reserved && !type->tp_richcompare) {
4036 int error;
Victor Stinner4a2b7a12010-08-13 14:03:48 +00004037 error = PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
4038 "Type %.100s defines tp_reserved (formerly tp_compare) "
4039 "but not tp_richcompare. Comparisons may not behave as intended.",
4040 type->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004041 if (error == -1)
4042 goto error;
4043 }
Mark Dickinson2a7d45b2009-02-08 11:02:10 +00004044
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004045 /* All done -- set the ready flag */
4046 assert(type->tp_dict != NULL);
4047 type->tp_flags =
4048 (type->tp_flags & ~Py_TPFLAGS_READYING) | Py_TPFLAGS_READY;
4049 return 0;
Guido van Rossumd614f972001-08-10 17:39:49 +00004050
4051 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004052 type->tp_flags &= ~Py_TPFLAGS_READYING;
4053 return -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004054}
4055
Guido van Rossum1c450732001-10-08 15:18:27 +00004056static int
4057add_subclass(PyTypeObject *base, PyTypeObject *type)
4058{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004059 Py_ssize_t i;
4060 int result;
4061 PyObject *list, *ref, *newobj;
Guido van Rossum1c450732001-10-08 15:18:27 +00004062
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004063 list = base->tp_subclasses;
4064 if (list == NULL) {
4065 base->tp_subclasses = list = PyList_New(0);
4066 if (list == NULL)
4067 return -1;
4068 }
4069 assert(PyList_Check(list));
4070 newobj = PyWeakref_NewRef((PyObject *)type, NULL);
4071 i = PyList_GET_SIZE(list);
4072 while (--i >= 0) {
4073 ref = PyList_GET_ITEM(list, i);
4074 assert(PyWeakref_CheckRef(ref));
4075 if (PyWeakref_GET_OBJECT(ref) == Py_None)
4076 return PyList_SetItem(list, i, newobj);
4077 }
4078 result = PyList_Append(list, newobj);
4079 Py_DECREF(newobj);
4080 return result;
Guido van Rossum1c450732001-10-08 15:18:27 +00004081}
4082
Michael W. Hudson98bbc492002-11-26 14:47:27 +00004083static void
4084remove_subclass(PyTypeObject *base, PyTypeObject *type)
4085{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004086 Py_ssize_t i;
4087 PyObject *list, *ref;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00004088
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004089 list = base->tp_subclasses;
4090 if (list == NULL) {
4091 return;
4092 }
4093 assert(PyList_Check(list));
4094 i = PyList_GET_SIZE(list);
4095 while (--i >= 0) {
4096 ref = PyList_GET_ITEM(list, i);
4097 assert(PyWeakref_CheckRef(ref));
4098 if (PyWeakref_GET_OBJECT(ref) == (PyObject*)type) {
4099 /* this can't fail, right? */
4100 PySequence_DelItem(list, i);
4101 return;
4102 }
4103 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +00004104}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004105
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004106static int
4107check_num_args(PyObject *ob, int n)
4108{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004109 if (!PyTuple_CheckExact(ob)) {
4110 PyErr_SetString(PyExc_SystemError,
4111 "PyArg_UnpackTuple() argument list is not a tuple");
4112 return 0;
4113 }
4114 if (n == PyTuple_GET_SIZE(ob))
4115 return 1;
4116 PyErr_Format(
4117 PyExc_TypeError,
4118 "expected %d arguments, got %zd", n, PyTuple_GET_SIZE(ob));
4119 return 0;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004120}
4121
Tim Peters6d6c1a32001-08-02 04:15:00 +00004122/* Generic wrappers for overloadable 'operators' such as __getitem__ */
4123
4124/* There's a wrapper *function* for each distinct function typedef used
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004125 for type object slots (e.g. binaryfunc, ternaryfunc, etc.). There's a
Tim Peters6d6c1a32001-08-02 04:15:00 +00004126 wrapper *table* for each distinct operation (e.g. __len__, __add__).
4127 Most tables have only one entry; the tables for binary operators have two
4128 entries, one regular and one with reversed arguments. */
4129
4130static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00004131wrap_lenfunc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004132{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004133 lenfunc func = (lenfunc)wrapped;
4134 Py_ssize_t res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004135
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004136 if (!check_num_args(args, 0))
4137 return NULL;
4138 res = (*func)(self);
4139 if (res == -1 && PyErr_Occurred())
4140 return NULL;
4141 return PyLong_FromLong((long)res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004142}
4143
Tim Peters6d6c1a32001-08-02 04:15:00 +00004144static PyObject *
Raymond Hettingerf34f2642003-10-11 17:29:04 +00004145wrap_inquirypred(PyObject *self, PyObject *args, void *wrapped)
4146{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004147 inquiry func = (inquiry)wrapped;
4148 int res;
Raymond Hettingerf34f2642003-10-11 17:29:04 +00004149
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004150 if (!check_num_args(args, 0))
4151 return NULL;
4152 res = (*func)(self);
4153 if (res == -1 && PyErr_Occurred())
4154 return NULL;
4155 return PyBool_FromLong((long)res);
Raymond Hettingerf34f2642003-10-11 17:29:04 +00004156}
4157
4158static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00004159wrap_binaryfunc(PyObject *self, PyObject *args, void *wrapped)
4160{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004161 binaryfunc func = (binaryfunc)wrapped;
4162 PyObject *other;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004163
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004164 if (!check_num_args(args, 1))
4165 return NULL;
4166 other = PyTuple_GET_ITEM(args, 0);
4167 return (*func)(self, other);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004168}
4169
4170static PyObject *
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00004171wrap_binaryfunc_l(PyObject *self, PyObject *args, void *wrapped)
4172{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004173 binaryfunc func = (binaryfunc)wrapped;
4174 PyObject *other;
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00004175
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004176 if (!check_num_args(args, 1))
4177 return NULL;
4178 other = PyTuple_GET_ITEM(args, 0);
4179 return (*func)(self, other);
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00004180}
4181
4182static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00004183wrap_binaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
4184{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004185 binaryfunc func = (binaryfunc)wrapped;
4186 PyObject *other;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004187
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004188 if (!check_num_args(args, 1))
4189 return NULL;
4190 other = PyTuple_GET_ITEM(args, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004191 return (*func)(other, self);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004192}
4193
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004194static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00004195wrap_ternaryfunc(PyObject *self, PyObject *args, void *wrapped)
4196{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004197 ternaryfunc func = (ternaryfunc)wrapped;
4198 PyObject *other;
4199 PyObject *third = Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004200
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004201 /* Note: This wrapper only works for __pow__() */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004202
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004203 if (!PyArg_UnpackTuple(args, "", 1, 2, &other, &third))
4204 return NULL;
4205 return (*func)(self, other, third);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004206}
4207
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00004208static PyObject *
4209wrap_ternaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
4210{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004211 ternaryfunc func = (ternaryfunc)wrapped;
4212 PyObject *other;
4213 PyObject *third = Py_None;
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00004214
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004215 /* Note: This wrapper only works for __pow__() */
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00004216
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004217 if (!PyArg_UnpackTuple(args, "", 1, 2, &other, &third))
4218 return NULL;
4219 return (*func)(other, self, third);
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00004220}
4221
Tim Peters6d6c1a32001-08-02 04:15:00 +00004222static PyObject *
4223wrap_unaryfunc(PyObject *self, PyObject *args, void *wrapped)
4224{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004225 unaryfunc func = (unaryfunc)wrapped;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004226
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004227 if (!check_num_args(args, 0))
4228 return NULL;
4229 return (*func)(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004230}
4231
Tim Peters6d6c1a32001-08-02 04:15:00 +00004232static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004233wrap_indexargfunc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004234{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004235 ssizeargfunc func = (ssizeargfunc)wrapped;
4236 PyObject* o;
4237 Py_ssize_t i;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004238
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004239 if (!PyArg_UnpackTuple(args, "", 1, 1, &o))
4240 return NULL;
4241 i = PyNumber_AsSsize_t(o, PyExc_OverflowError);
4242 if (i == -1 && PyErr_Occurred())
4243 return NULL;
4244 return (*func)(self, i);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004245}
4246
Martin v. Löwis18e16552006-02-15 17:27:45 +00004247static Py_ssize_t
Guido van Rossum5d815f32001-08-17 21:57:47 +00004248getindex(PyObject *self, PyObject *arg)
4249{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004250 Py_ssize_t i;
Guido van Rossum5d815f32001-08-17 21:57:47 +00004251
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004252 i = PyNumber_AsSsize_t(arg, PyExc_OverflowError);
4253 if (i == -1 && PyErr_Occurred())
4254 return -1;
4255 if (i < 0) {
4256 PySequenceMethods *sq = Py_TYPE(self)->tp_as_sequence;
4257 if (sq && sq->sq_length) {
4258 Py_ssize_t n = (*sq->sq_length)(self);
4259 if (n < 0)
4260 return -1;
4261 i += n;
4262 }
4263 }
4264 return i;
Guido van Rossum5d815f32001-08-17 21:57:47 +00004265}
4266
4267static PyObject *
4268wrap_sq_item(PyObject *self, PyObject *args, void *wrapped)
4269{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004270 ssizeargfunc func = (ssizeargfunc)wrapped;
4271 PyObject *arg;
4272 Py_ssize_t i;
Guido van Rossum5d815f32001-08-17 21:57:47 +00004273
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004274 if (PyTuple_GET_SIZE(args) == 1) {
4275 arg = PyTuple_GET_ITEM(args, 0);
4276 i = getindex(self, arg);
4277 if (i == -1 && PyErr_Occurred())
4278 return NULL;
4279 return (*func)(self, i);
4280 }
4281 check_num_args(args, 1);
4282 assert(PyErr_Occurred());
4283 return NULL;
Guido van Rossum5d815f32001-08-17 21:57:47 +00004284}
4285
Tim Peters6d6c1a32001-08-02 04:15:00 +00004286static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00004287wrap_sq_setitem(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004288{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004289 ssizeobjargproc func = (ssizeobjargproc)wrapped;
4290 Py_ssize_t i;
4291 int res;
4292 PyObject *arg, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004293
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004294 if (!PyArg_UnpackTuple(args, "", 2, 2, &arg, &value))
4295 return NULL;
4296 i = getindex(self, arg);
4297 if (i == -1 && PyErr_Occurred())
4298 return NULL;
4299 res = (*func)(self, i, value);
4300 if (res == -1 && PyErr_Occurred())
4301 return NULL;
4302 Py_INCREF(Py_None);
4303 return Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004304}
4305
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004306static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00004307wrap_sq_delitem(PyObject *self, PyObject *args, void *wrapped)
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004308{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004309 ssizeobjargproc func = (ssizeobjargproc)wrapped;
4310 Py_ssize_t i;
4311 int res;
4312 PyObject *arg;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004313
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004314 if (!check_num_args(args, 1))
4315 return NULL;
4316 arg = PyTuple_GET_ITEM(args, 0);
4317 i = getindex(self, arg);
4318 if (i == -1 && PyErr_Occurred())
4319 return NULL;
4320 res = (*func)(self, i, NULL);
4321 if (res == -1 && PyErr_Occurred())
4322 return NULL;
4323 Py_INCREF(Py_None);
4324 return Py_None;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004325}
4326
Tim Peters6d6c1a32001-08-02 04:15:00 +00004327/* XXX objobjproc is a misnomer; should be objargpred */
4328static PyObject *
4329wrap_objobjproc(PyObject *self, PyObject *args, void *wrapped)
4330{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004331 objobjproc func = (objobjproc)wrapped;
4332 int res;
4333 PyObject *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004334
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004335 if (!check_num_args(args, 1))
4336 return NULL;
4337 value = PyTuple_GET_ITEM(args, 0);
4338 res = (*func)(self, value);
4339 if (res == -1 && PyErr_Occurred())
4340 return NULL;
4341 else
4342 return PyBool_FromLong(res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004343}
4344
Tim Peters6d6c1a32001-08-02 04:15:00 +00004345static PyObject *
4346wrap_objobjargproc(PyObject *self, PyObject *args, void *wrapped)
4347{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004348 objobjargproc func = (objobjargproc)wrapped;
4349 int res;
4350 PyObject *key, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004351
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004352 if (!PyArg_UnpackTuple(args, "", 2, 2, &key, &value))
4353 return NULL;
4354 res = (*func)(self, key, value);
4355 if (res == -1 && PyErr_Occurred())
4356 return NULL;
4357 Py_INCREF(Py_None);
4358 return Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004359}
4360
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004361static PyObject *
4362wrap_delitem(PyObject *self, PyObject *args, void *wrapped)
4363{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004364 objobjargproc func = (objobjargproc)wrapped;
4365 int res;
4366 PyObject *key;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004367
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004368 if (!check_num_args(args, 1))
4369 return NULL;
4370 key = PyTuple_GET_ITEM(args, 0);
4371 res = (*func)(self, key, NULL);
4372 if (res == -1 && PyErr_Occurred())
4373 return NULL;
4374 Py_INCREF(Py_None);
4375 return Py_None;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004376}
4377
Guido van Rossum4dcdb782003-04-14 21:46:03 +00004378/* Helper to check for object.__setattr__ or __delattr__ applied to a type.
Guido van Rossum52b27052003-04-15 20:05:10 +00004379 This is called the Carlo Verre hack after its discoverer. */
Guido van Rossum4dcdb782003-04-14 21:46:03 +00004380static int
4381hackcheck(PyObject *self, setattrofunc func, char *what)
4382{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004383 PyTypeObject *type = Py_TYPE(self);
4384 while (type && type->tp_flags & Py_TPFLAGS_HEAPTYPE)
4385 type = type->tp_base;
4386 /* If type is NULL now, this is a really weird type.
4387 In the spirit of backwards compatibility (?), just shut up. */
4388 if (type && type->tp_setattro != func) {
4389 PyErr_Format(PyExc_TypeError,
4390 "can't apply this %s to %s object",
4391 what,
4392 type->tp_name);
4393 return 0;
4394 }
4395 return 1;
Guido van Rossum4dcdb782003-04-14 21:46:03 +00004396}
4397
Tim Peters6d6c1a32001-08-02 04:15:00 +00004398static PyObject *
4399wrap_setattr(PyObject *self, PyObject *args, void *wrapped)
4400{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004401 setattrofunc func = (setattrofunc)wrapped;
4402 int res;
4403 PyObject *name, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004404
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004405 if (!PyArg_UnpackTuple(args, "", 2, 2, &name, &value))
4406 return NULL;
4407 if (!hackcheck(self, func, "__setattr__"))
4408 return NULL;
4409 res = (*func)(self, name, value);
4410 if (res < 0)
4411 return NULL;
4412 Py_INCREF(Py_None);
4413 return Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004414}
4415
4416static PyObject *
4417wrap_delattr(PyObject *self, PyObject *args, void *wrapped)
4418{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004419 setattrofunc func = (setattrofunc)wrapped;
4420 int res;
4421 PyObject *name;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004422
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004423 if (!check_num_args(args, 1))
4424 return NULL;
4425 name = PyTuple_GET_ITEM(args, 0);
4426 if (!hackcheck(self, func, "__delattr__"))
4427 return NULL;
4428 res = (*func)(self, name, NULL);
4429 if (res < 0)
4430 return NULL;
4431 Py_INCREF(Py_None);
4432 return Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004433}
4434
Tim Peters6d6c1a32001-08-02 04:15:00 +00004435static PyObject *
4436wrap_hashfunc(PyObject *self, PyObject *args, void *wrapped)
4437{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004438 hashfunc func = (hashfunc)wrapped;
Benjamin Peterson8035bc52010-10-23 16:20:50 +00004439 Py_hash_t res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004440
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004441 if (!check_num_args(args, 0))
4442 return NULL;
4443 res = (*func)(self);
4444 if (res == -1 && PyErr_Occurred())
4445 return NULL;
Benjamin Peterson8035bc52010-10-23 16:20:50 +00004446 return PyLong_FromSsize_t(res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004447}
4448
Tim Peters6d6c1a32001-08-02 04:15:00 +00004449static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00004450wrap_call(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004451{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004452 ternaryfunc func = (ternaryfunc)wrapped;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004453
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004454 return (*func)(self, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004455}
4456
Tim Peters6d6c1a32001-08-02 04:15:00 +00004457static PyObject *
4458wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op)
4459{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004460 richcmpfunc func = (richcmpfunc)wrapped;
4461 PyObject *other;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004462
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004463 if (!check_num_args(args, 1))
4464 return NULL;
4465 other = PyTuple_GET_ITEM(args, 0);
4466 return (*func)(self, other, op);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004467}
4468
4469#undef RICHCMP_WRAPPER
4470#define RICHCMP_WRAPPER(NAME, OP) \
4471static PyObject * \
4472richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \
4473{ \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004474 return wrap_richcmpfunc(self, args, wrapped, OP); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004475}
4476
Jack Jansen8e938b42001-08-08 15:29:49 +00004477RICHCMP_WRAPPER(lt, Py_LT)
4478RICHCMP_WRAPPER(le, Py_LE)
4479RICHCMP_WRAPPER(eq, Py_EQ)
4480RICHCMP_WRAPPER(ne, Py_NE)
4481RICHCMP_WRAPPER(gt, Py_GT)
4482RICHCMP_WRAPPER(ge, Py_GE)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004483
Tim Peters6d6c1a32001-08-02 04:15:00 +00004484static PyObject *
4485wrap_next(PyObject *self, PyObject *args, void *wrapped)
4486{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004487 unaryfunc func = (unaryfunc)wrapped;
4488 PyObject *res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004489
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004490 if (!check_num_args(args, 0))
4491 return NULL;
4492 res = (*func)(self);
4493 if (res == NULL && !PyErr_Occurred())
4494 PyErr_SetNone(PyExc_StopIteration);
4495 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004496}
4497
Tim Peters6d6c1a32001-08-02 04:15:00 +00004498static PyObject *
4499wrap_descr_get(PyObject *self, PyObject *args, void *wrapped)
4500{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004501 descrgetfunc func = (descrgetfunc)wrapped;
4502 PyObject *obj;
4503 PyObject *type = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004504
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004505 if (!PyArg_UnpackTuple(args, "", 1, 2, &obj, &type))
4506 return NULL;
4507 if (obj == Py_None)
4508 obj = NULL;
4509 if (type == Py_None)
4510 type = NULL;
4511 if (type == NULL &&obj == NULL) {
4512 PyErr_SetString(PyExc_TypeError,
4513 "__get__(None, None) is invalid");
4514 return NULL;
4515 }
4516 return (*func)(self, obj, type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004517}
4518
Tim Peters6d6c1a32001-08-02 04:15:00 +00004519static PyObject *
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004520wrap_descr_set(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004521{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004522 descrsetfunc func = (descrsetfunc)wrapped;
4523 PyObject *obj, *value;
4524 int ret;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004525
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004526 if (!PyArg_UnpackTuple(args, "", 2, 2, &obj, &value))
4527 return NULL;
4528 ret = (*func)(self, obj, value);
4529 if (ret < 0)
4530 return NULL;
4531 Py_INCREF(Py_None);
4532 return Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004533}
Guido van Rossum22b13872002-08-06 21:41:44 +00004534
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00004535static PyObject *
4536wrap_descr_delete(PyObject *self, PyObject *args, void *wrapped)
4537{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004538 descrsetfunc func = (descrsetfunc)wrapped;
4539 PyObject *obj;
4540 int ret;
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00004541
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004542 if (!check_num_args(args, 1))
4543 return NULL;
4544 obj = PyTuple_GET_ITEM(args, 0);
4545 ret = (*func)(self, obj, NULL);
4546 if (ret < 0)
4547 return NULL;
4548 Py_INCREF(Py_None);
4549 return Py_None;
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00004550}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004551
Tim Peters6d6c1a32001-08-02 04:15:00 +00004552static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00004553wrap_init(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004554{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004555 initproc func = (initproc)wrapped;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004556
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004557 if (func(self, args, kwds) < 0)
4558 return NULL;
4559 Py_INCREF(Py_None);
4560 return Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004561}
4562
Tim Peters6d6c1a32001-08-02 04:15:00 +00004563static PyObject *
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004564tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004565{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004566 PyTypeObject *type, *subtype, *staticbase;
4567 PyObject *arg0, *res;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004568
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004569 if (self == NULL || !PyType_Check(self))
4570 Py_FatalError("__new__() called with non-type 'self'");
4571 type = (PyTypeObject *)self;
4572 if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) {
4573 PyErr_Format(PyExc_TypeError,
4574 "%s.__new__(): not enough arguments",
4575 type->tp_name);
4576 return NULL;
4577 }
4578 arg0 = PyTuple_GET_ITEM(args, 0);
4579 if (!PyType_Check(arg0)) {
4580 PyErr_Format(PyExc_TypeError,
4581 "%s.__new__(X): X is not a type object (%s)",
4582 type->tp_name,
4583 Py_TYPE(arg0)->tp_name);
4584 return NULL;
4585 }
4586 subtype = (PyTypeObject *)arg0;
4587 if (!PyType_IsSubtype(subtype, type)) {
4588 PyErr_Format(PyExc_TypeError,
4589 "%s.__new__(%s): %s is not a subtype of %s",
4590 type->tp_name,
4591 subtype->tp_name,
4592 subtype->tp_name,
4593 type->tp_name);
4594 return NULL;
4595 }
Barry Warsaw60f01882001-08-22 19:24:42 +00004596
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004597 /* Check that the use doesn't do something silly and unsafe like
4598 object.__new__(dict). To do this, we check that the
4599 most derived base that's not a heap type is this type. */
4600 staticbase = subtype;
4601 while (staticbase && (staticbase->tp_flags & Py_TPFLAGS_HEAPTYPE))
4602 staticbase = staticbase->tp_base;
4603 /* If staticbase is NULL now, it is a really weird type.
4604 In the spirit of backwards compatibility (?), just shut up. */
4605 if (staticbase && staticbase->tp_new != type->tp_new) {
4606 PyErr_Format(PyExc_TypeError,
4607 "%s.__new__(%s) is not safe, use %s.__new__()",
4608 type->tp_name,
4609 subtype->tp_name,
4610 staticbase == NULL ? "?" : staticbase->tp_name);
4611 return NULL;
4612 }
Barry Warsaw60f01882001-08-22 19:24:42 +00004613
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004614 args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
4615 if (args == NULL)
4616 return NULL;
4617 res = type->tp_new(subtype, args, kwds);
4618 Py_DECREF(args);
4619 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004620}
4621
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004622static struct PyMethodDef tp_new_methoddef[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004623 {"__new__", (PyCFunction)tp_new_wrapper, METH_VARARGS|METH_KEYWORDS,
4624 PyDoc_STR("T.__new__(S, ...) -> "
4625 "a new object with type S, a subtype of T")},
4626 {0}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004627};
4628
4629static int
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004630add_tp_new_wrapper(PyTypeObject *type)
4631{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004632 PyObject *func;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004633
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004634 if (PyDict_GetItemString(type->tp_dict, "__new__") != NULL)
4635 return 0;
4636 func = PyCFunction_New(tp_new_methoddef, (PyObject *)type);
4637 if (func == NULL)
4638 return -1;
4639 if (PyDict_SetItemString(type->tp_dict, "__new__", func)) {
4640 Py_DECREF(func);
4641 return -1;
4642 }
4643 Py_DECREF(func);
4644 return 0;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004645}
4646
Guido van Rossumf040ede2001-08-07 16:40:56 +00004647/* Slot wrappers that call the corresponding __foo__ slot. See comments
4648 below at override_slots() for more explanation. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004649
Guido van Rossumdc91b992001-08-08 22:26:22 +00004650#define SLOT0(FUNCNAME, OPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004651static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004652FUNCNAME(PyObject *self) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004653{ \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004654 static PyObject *cache_str; \
4655 return call_method(self, OPSTR, &cache_str, "()"); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004656}
4657
Guido van Rossumdc91b992001-08-08 22:26:22 +00004658#define SLOT1(FUNCNAME, OPSTR, ARG1TYPE, ARGCODES) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004659static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004660FUNCNAME(PyObject *self, ARG1TYPE arg1) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004661{ \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004662 static PyObject *cache_str; \
4663 return call_method(self, OPSTR, &cache_str, "(" ARGCODES ")", arg1); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004664}
4665
Guido van Rossumcd118802003-01-06 22:57:47 +00004666/* Boolean helper for SLOT1BINFULL().
4667 right.__class__ is a nontrivial subclass of left.__class__. */
4668static int
4669method_is_overloaded(PyObject *left, PyObject *right, char *name)
4670{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004671 PyObject *a, *b;
4672 int ok;
Guido van Rossumcd118802003-01-06 22:57:47 +00004673
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004674 b = PyObject_GetAttrString((PyObject *)(Py_TYPE(right)), name);
4675 if (b == NULL) {
4676 PyErr_Clear();
4677 /* If right doesn't have it, it's not overloaded */
4678 return 0;
4679 }
Guido van Rossumcd118802003-01-06 22:57:47 +00004680
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004681 a = PyObject_GetAttrString((PyObject *)(Py_TYPE(left)), name);
4682 if (a == NULL) {
4683 PyErr_Clear();
4684 Py_DECREF(b);
4685 /* If right has it but left doesn't, it's overloaded */
4686 return 1;
4687 }
Guido van Rossumcd118802003-01-06 22:57:47 +00004688
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004689 ok = PyObject_RichCompareBool(a, b, Py_NE);
4690 Py_DECREF(a);
4691 Py_DECREF(b);
4692 if (ok < 0) {
4693 PyErr_Clear();
4694 return 0;
4695 }
Guido van Rossumcd118802003-01-06 22:57:47 +00004696
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004697 return ok;
Guido van Rossumcd118802003-01-06 22:57:47 +00004698}
4699
Guido van Rossumdc91b992001-08-08 22:26:22 +00004700
4701#define SLOT1BINFULL(FUNCNAME, TESTFUNC, SLOTNAME, OPSTR, ROPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004702static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004703FUNCNAME(PyObject *self, PyObject *other) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004704{ \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004705 static PyObject *cache_str, *rcache_str; \
4706 int do_other = Py_TYPE(self) != Py_TYPE(other) && \
4707 Py_TYPE(other)->tp_as_number != NULL && \
4708 Py_TYPE(other)->tp_as_number->SLOTNAME == TESTFUNC; \
4709 if (Py_TYPE(self)->tp_as_number != NULL && \
4710 Py_TYPE(self)->tp_as_number->SLOTNAME == TESTFUNC) { \
4711 PyObject *r; \
4712 if (do_other && \
4713 PyType_IsSubtype(Py_TYPE(other), Py_TYPE(self)) && \
4714 method_is_overloaded(self, other, ROPSTR)) { \
4715 r = call_maybe( \
4716 other, ROPSTR, &rcache_str, "(O)", self); \
4717 if (r != Py_NotImplemented) \
4718 return r; \
4719 Py_DECREF(r); \
4720 do_other = 0; \
4721 } \
4722 r = call_maybe( \
4723 self, OPSTR, &cache_str, "(O)", other); \
4724 if (r != Py_NotImplemented || \
4725 Py_TYPE(other) == Py_TYPE(self)) \
4726 return r; \
4727 Py_DECREF(r); \
4728 } \
4729 if (do_other) { \
4730 return call_maybe( \
4731 other, ROPSTR, &rcache_str, "(O)", self); \
4732 } \
4733 Py_INCREF(Py_NotImplemented); \
4734 return Py_NotImplemented; \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004735}
4736
4737#define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004738 SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR)
Guido van Rossumdc91b992001-08-08 22:26:22 +00004739
4740#define SLOT2(FUNCNAME, OPSTR, ARG1TYPE, ARG2TYPE, ARGCODES) \
4741static PyObject * \
4742FUNCNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \
4743{ \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004744 static PyObject *cache_str; \
4745 return call_method(self, OPSTR, &cache_str, \
4746 "(" ARGCODES ")", arg1, arg2); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004747}
4748
Martin v. Löwis18e16552006-02-15 17:27:45 +00004749static Py_ssize_t
Tim Peters6d6c1a32001-08-02 04:15:00 +00004750slot_sq_length(PyObject *self)
4751{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004752 static PyObject *len_str;
4753 PyObject *res = call_method(self, "__len__", &len_str, "()");
4754 Py_ssize_t len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004755
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004756 if (res == NULL)
4757 return -1;
4758 len = PyNumber_AsSsize_t(res, PyExc_OverflowError);
4759 Py_DECREF(res);
4760 if (len < 0) {
4761 if (!PyErr_Occurred())
4762 PyErr_SetString(PyExc_ValueError,
4763 "__len__() should return >= 0");
4764 return -1;
4765 }
4766 return len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004767}
4768
Guido van Rossumf4593e02001-10-03 12:09:30 +00004769/* Super-optimized version of slot_sq_item.
4770 Other slots could do the same... */
4771static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00004772slot_sq_item(PyObject *self, Py_ssize_t i)
Guido van Rossumf4593e02001-10-03 12:09:30 +00004773{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004774 static PyObject *getitem_str;
4775 PyObject *func, *args = NULL, *ival = NULL, *retval = NULL;
4776 descrgetfunc f;
Guido van Rossumf4593e02001-10-03 12:09:30 +00004777
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004778 if (getitem_str == NULL) {
4779 getitem_str = PyUnicode_InternFromString("__getitem__");
4780 if (getitem_str == NULL)
4781 return NULL;
4782 }
4783 func = _PyType_Lookup(Py_TYPE(self), getitem_str);
4784 if (func != NULL) {
4785 if ((f = Py_TYPE(func)->tp_descr_get) == NULL)
4786 Py_INCREF(func);
4787 else {
4788 func = f(func, self, (PyObject *)(Py_TYPE(self)));
4789 if (func == NULL) {
4790 return NULL;
4791 }
4792 }
4793 ival = PyLong_FromSsize_t(i);
4794 if (ival != NULL) {
4795 args = PyTuple_New(1);
4796 if (args != NULL) {
4797 PyTuple_SET_ITEM(args, 0, ival);
4798 retval = PyObject_Call(func, args, NULL);
4799 Py_XDECREF(args);
4800 Py_XDECREF(func);
4801 return retval;
4802 }
4803 }
4804 }
4805 else {
4806 PyErr_SetObject(PyExc_AttributeError, getitem_str);
4807 }
4808 Py_XDECREF(args);
4809 Py_XDECREF(ival);
4810 Py_XDECREF(func);
4811 return NULL;
Guido van Rossumf4593e02001-10-03 12:09:30 +00004812}
4813
Tim Peters6d6c1a32001-08-02 04:15:00 +00004814static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00004815slot_sq_ass_item(PyObject *self, Py_ssize_t index, PyObject *value)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004816{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004817 PyObject *res;
4818 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004819
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004820 if (value == NULL)
4821 res = call_method(self, "__delitem__", &delitem_str,
4822 "(n)", index);
4823 else
4824 res = call_method(self, "__setitem__", &setitem_str,
4825 "(nO)", index, value);
4826 if (res == NULL)
4827 return -1;
4828 Py_DECREF(res);
4829 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004830}
4831
4832static int
Tim Peters6d6c1a32001-08-02 04:15:00 +00004833slot_sq_contains(PyObject *self, PyObject *value)
4834{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004835 PyObject *func, *res, *args;
4836 int result = -1;
Tim Petersbf9b2442003-03-23 05:35:36 +00004837
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004838 static PyObject *contains_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004839
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004840 func = lookup_maybe(self, "__contains__", &contains_str);
4841 if (func != NULL) {
4842 args = PyTuple_Pack(1, value);
4843 if (args == NULL)
4844 res = NULL;
4845 else {
4846 res = PyObject_Call(func, args, NULL);
4847 Py_DECREF(args);
4848 }
4849 Py_DECREF(func);
4850 if (res != NULL) {
4851 result = PyObject_IsTrue(res);
4852 Py_DECREF(res);
4853 }
4854 }
4855 else if (! PyErr_Occurred()) {
4856 /* Possible results: -1 and 1 */
4857 result = (int)_PySequence_IterSearch(self, value,
4858 PY_ITERSEARCH_CONTAINS);
4859 }
4860 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004861}
4862
Tim Peters6d6c1a32001-08-02 04:15:00 +00004863#define slot_mp_length slot_sq_length
4864
Guido van Rossumdc91b992001-08-08 22:26:22 +00004865SLOT1(slot_mp_subscript, "__getitem__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004866
4867static int
4868slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value)
4869{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004870 PyObject *res;
4871 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004872
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004873 if (value == NULL)
4874 res = call_method(self, "__delitem__", &delitem_str,
4875 "(O)", key);
4876 else
4877 res = call_method(self, "__setitem__", &setitem_str,
4878 "(OO)", key, value);
4879 if (res == NULL)
4880 return -1;
4881 Py_DECREF(res);
4882 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004883}
4884
Guido van Rossumdc91b992001-08-08 22:26:22 +00004885SLOT1BIN(slot_nb_add, nb_add, "__add__", "__radd__")
4886SLOT1BIN(slot_nb_subtract, nb_subtract, "__sub__", "__rsub__")
4887SLOT1BIN(slot_nb_multiply, nb_multiply, "__mul__", "__rmul__")
Guido van Rossumdc91b992001-08-08 22:26:22 +00004888SLOT1BIN(slot_nb_remainder, nb_remainder, "__mod__", "__rmod__")
4889SLOT1BIN(slot_nb_divmod, nb_divmod, "__divmod__", "__rdivmod__")
4890
Jeremy Hylton938ace62002-07-17 16:30:39 +00004891static PyObject *slot_nb_power(PyObject *, PyObject *, PyObject *);
Guido van Rossumdc91b992001-08-08 22:26:22 +00004892
4893SLOT1BINFULL(slot_nb_power_binary, slot_nb_power,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004894 nb_power, "__pow__", "__rpow__")
Guido van Rossumdc91b992001-08-08 22:26:22 +00004895
4896static PyObject *
4897slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus)
4898{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004899 static PyObject *pow_str;
Guido van Rossum2730b132001-08-28 18:22:14 +00004900
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004901 if (modulus == Py_None)
4902 return slot_nb_power_binary(self, other);
4903 /* Three-arg power doesn't use __rpow__. But ternary_op
4904 can call this when the second argument's type uses
4905 slot_nb_power, so check before calling self.__pow__. */
4906 if (Py_TYPE(self)->tp_as_number != NULL &&
4907 Py_TYPE(self)->tp_as_number->nb_power == slot_nb_power) {
4908 return call_method(self, "__pow__", &pow_str,
4909 "(OO)", other, modulus);
4910 }
4911 Py_INCREF(Py_NotImplemented);
4912 return Py_NotImplemented;
Guido van Rossumdc91b992001-08-08 22:26:22 +00004913}
4914
4915SLOT0(slot_nb_negative, "__neg__")
4916SLOT0(slot_nb_positive, "__pos__")
4917SLOT0(slot_nb_absolute, "__abs__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004918
4919static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00004920slot_nb_bool(PyObject *self)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004921{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004922 PyObject *func, *args;
4923 static PyObject *bool_str, *len_str;
4924 int result = -1;
4925 int using_len = 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004926
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004927 func = lookup_maybe(self, "__bool__", &bool_str);
4928 if (func == NULL) {
4929 if (PyErr_Occurred())
4930 return -1;
4931 func = lookup_maybe(self, "__len__", &len_str);
4932 if (func == NULL)
4933 return PyErr_Occurred() ? -1 : 1;
4934 using_len = 1;
4935 }
4936 args = PyTuple_New(0);
4937 if (args != NULL) {
4938 PyObject *temp = PyObject_Call(func, args, NULL);
4939 Py_DECREF(args);
4940 if (temp != NULL) {
4941 if (using_len) {
4942 /* enforced by slot_nb_len */
4943 result = PyObject_IsTrue(temp);
4944 }
4945 else if (PyBool_Check(temp)) {
4946 result = PyObject_IsTrue(temp);
4947 }
4948 else {
4949 PyErr_Format(PyExc_TypeError,
4950 "__bool__ should return "
4951 "bool, returned %s",
4952 Py_TYPE(temp)->tp_name);
4953 result = -1;
4954 }
4955 Py_DECREF(temp);
4956 }
4957 }
4958 Py_DECREF(func);
4959 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004960}
4961
Guido van Rossum38fff8c2006-03-07 18:50:55 +00004962
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00004963static PyObject *
Guido van Rossum38fff8c2006-03-07 18:50:55 +00004964slot_nb_index(PyObject *self)
4965{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004966 static PyObject *index_str;
4967 return call_method(self, "__index__", &index_str, "()");
Guido van Rossum38fff8c2006-03-07 18:50:55 +00004968}
4969
4970
Guido van Rossumdc91b992001-08-08 22:26:22 +00004971SLOT0(slot_nb_invert, "__invert__")
4972SLOT1BIN(slot_nb_lshift, nb_lshift, "__lshift__", "__rlshift__")
4973SLOT1BIN(slot_nb_rshift, nb_rshift, "__rshift__", "__rrshift__")
4974SLOT1BIN(slot_nb_and, nb_and, "__and__", "__rand__")
4975SLOT1BIN(slot_nb_xor, nb_xor, "__xor__", "__rxor__")
4976SLOT1BIN(slot_nb_or, nb_or, "__or__", "__ror__")
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004977
Guido van Rossumdc91b992001-08-08 22:26:22 +00004978SLOT0(slot_nb_int, "__int__")
Guido van Rossumdc91b992001-08-08 22:26:22 +00004979SLOT0(slot_nb_float, "__float__")
Guido van Rossumdc91b992001-08-08 22:26:22 +00004980SLOT1(slot_nb_inplace_add, "__iadd__", PyObject *, "O")
4981SLOT1(slot_nb_inplace_subtract, "__isub__", PyObject *, "O")
4982SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *, "O")
Guido van Rossumdc91b992001-08-08 22:26:22 +00004983SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *, "O")
Thomas Wouterscf297e42007-02-23 15:07:44 +00004984/* Can't use SLOT1 here, because nb_inplace_power is ternary */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004985static PyObject *
4986slot_nb_inplace_power(PyObject *self, PyObject * arg1, PyObject *arg2)
4987{
4988 static PyObject *cache_str;
4989 return call_method(self, "__ipow__", &cache_str, "(" "O" ")", arg1);
Thomas Wouterscf297e42007-02-23 15:07:44 +00004990}
Guido van Rossumdc91b992001-08-08 22:26:22 +00004991SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *, "O")
4992SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *, "O")
4993SLOT1(slot_nb_inplace_and, "__iand__", PyObject *, "O")
4994SLOT1(slot_nb_inplace_xor, "__ixor__", PyObject *, "O")
4995SLOT1(slot_nb_inplace_or, "__ior__", PyObject *, "O")
4996SLOT1BIN(slot_nb_floor_divide, nb_floor_divide,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004997 "__floordiv__", "__rfloordiv__")
Guido van Rossumdc91b992001-08-08 22:26:22 +00004998SLOT1BIN(slot_nb_true_divide, nb_true_divide, "__truediv__", "__rtruediv__")
4999SLOT1(slot_nb_inplace_floor_divide, "__ifloordiv__", PyObject *, "O")
5000SLOT1(slot_nb_inplace_true_divide, "__itruediv__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00005001
Guido van Rossumb8f63662001-08-15 23:57:02 +00005002static PyObject *
5003slot_tp_repr(PyObject *self)
5004{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005005 PyObject *func, *res;
5006 static PyObject *repr_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00005007
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005008 func = lookup_method(self, "__repr__", &repr_str);
5009 if (func != NULL) {
5010 res = PyEval_CallObject(func, NULL);
5011 Py_DECREF(func);
5012 return res;
5013 }
5014 PyErr_Clear();
5015 return PyUnicode_FromFormat("<%s object at %p>",
5016 Py_TYPE(self)->tp_name, self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005017}
5018
5019static PyObject *
5020slot_tp_str(PyObject *self)
5021{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005022 PyObject *func, *res;
5023 static PyObject *str_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00005024
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005025 func = lookup_method(self, "__str__", &str_str);
5026 if (func != NULL) {
5027 res = PyEval_CallObject(func, NULL);
5028 Py_DECREF(func);
5029 return res;
5030 }
5031 else {
5032 PyObject *ress;
5033 PyErr_Clear();
5034 res = slot_tp_repr(self);
5035 if (!res)
5036 return NULL;
5037 ress = _PyUnicode_AsDefaultEncodedString(res, NULL);
5038 Py_DECREF(res);
5039 return ress;
5040 }
Guido van Rossumb8f63662001-08-15 23:57:02 +00005041}
Tim Peters6d6c1a32001-08-02 04:15:00 +00005042
Benjamin Peterson8f67d082010-10-17 20:54:53 +00005043static Py_hash_t
Tim Peters6d6c1a32001-08-02 04:15:00 +00005044slot_tp_hash(PyObject *self)
5045{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005046 PyObject *func, *res;
5047 static PyObject *hash_str;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00005048 Py_ssize_t h;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005049
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005050 func = lookup_method(self, "__hash__", &hash_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005051
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005052 if (func == Py_None) {
5053 Py_DECREF(func);
5054 func = NULL;
5055 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +00005056
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005057 if (func == NULL) {
5058 return PyObject_HashNotImplemented(self);
5059 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +00005060
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005061 res = PyEval_CallObject(func, NULL);
5062 Py_DECREF(func);
5063 if (res == NULL)
5064 return -1;
Mark Dickinsondc787d22010-05-23 13:33:13 +00005065
5066 if (!PyLong_Check(res)) {
5067 PyErr_SetString(PyExc_TypeError,
5068 "__hash__ method should return an integer");
5069 return -1;
5070 }
Benjamin Peterson8f67d082010-10-17 20:54:53 +00005071 /* Transform the PyLong `res` to a Py_hash_t `h`. For an existing
5072 hashable Python object x, hash(x) will always lie within the range of
5073 Py_hash_t. Therefore our transformation must preserve values that
5074 already lie within this range, to ensure that if x.__hash__() returns
5075 hash(y) then hash(x) == hash(y). */
5076 h = PyLong_AsSsize_t(res);
5077 if (h == -1 && PyErr_Occurred()) {
5078 /* res was not within the range of a Py_hash_t, so we're free to
Mark Dickinsondc787d22010-05-23 13:33:13 +00005079 use any sufficiently bit-mixing transformation;
5080 long.__hash__ will do nicely. */
Benjamin Peterson8f67d082010-10-17 20:54:53 +00005081 PyErr_Clear();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005082 h = PyLong_Type.tp_hash(res);
Benjamin Peterson8f67d082010-10-17 20:54:53 +00005083 }
Benjamin Petersone7dfeeb2010-10-17 21:27:01 +00005084 /* -1 is reserved for errors. */
5085 if (h == -1)
5086 h = -2;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005087 Py_DECREF(res);
Mark Dickinsondc787d22010-05-23 13:33:13 +00005088 return h;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005089}
5090
5091static PyObject *
5092slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds)
5093{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005094 static PyObject *call_str;
5095 PyObject *meth = lookup_method(self, "__call__", &call_str);
5096 PyObject *res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005097
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005098 if (meth == NULL)
5099 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005100
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005101 res = PyObject_Call(meth, args, kwds);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005102
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005103 Py_DECREF(meth);
5104 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005105}
5106
Guido van Rossum14a6f832001-10-17 13:59:09 +00005107/* There are two slot dispatch functions for tp_getattro.
5108
5109 - slot_tp_getattro() is used when __getattribute__ is overridden
5110 but no __getattr__ hook is present;
5111
5112 - slot_tp_getattr_hook() is used when a __getattr__ hook is present.
5113
Guido van Rossumc334df52002-04-04 23:44:47 +00005114 The code in update_one_slot() always installs slot_tp_getattr_hook(); this
5115 detects the absence of __getattr__ and then installs the simpler slot if
5116 necessary. */
Guido van Rossum14a6f832001-10-17 13:59:09 +00005117
Tim Peters6d6c1a32001-08-02 04:15:00 +00005118static PyObject *
5119slot_tp_getattro(PyObject *self, PyObject *name)
5120{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005121 static PyObject *getattribute_str = NULL;
5122 return call_method(self, "__getattribute__", &getattribute_str,
5123 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005124}
5125
Guido van Rossum19c1cd52001-09-21 21:24:49 +00005126static PyObject *
Benjamin Peterson9262b842008-11-17 22:45:50 +00005127call_attribute(PyObject *self, PyObject *attr, PyObject *name)
5128{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005129 PyObject *res, *descr = NULL;
5130 descrgetfunc f = Py_TYPE(attr)->tp_descr_get;
Benjamin Peterson9262b842008-11-17 22:45:50 +00005131
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005132 if (f != NULL) {
5133 descr = f(attr, self, (PyObject *)(Py_TYPE(self)));
5134 if (descr == NULL)
5135 return NULL;
5136 else
5137 attr = descr;
5138 }
5139 res = PyObject_CallFunctionObjArgs(attr, name, NULL);
5140 Py_XDECREF(descr);
5141 return res;
Benjamin Peterson9262b842008-11-17 22:45:50 +00005142}
5143
5144static PyObject *
Guido van Rossum19c1cd52001-09-21 21:24:49 +00005145slot_tp_getattr_hook(PyObject *self, PyObject *name)
5146{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005147 PyTypeObject *tp = Py_TYPE(self);
5148 PyObject *getattr, *getattribute, *res;
5149 static PyObject *getattribute_str = NULL;
5150 static PyObject *getattr_str = NULL;
Guido van Rossum19c1cd52001-09-21 21:24:49 +00005151
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005152 if (getattr_str == NULL) {
5153 getattr_str = PyUnicode_InternFromString("__getattr__");
5154 if (getattr_str == NULL)
5155 return NULL;
5156 }
5157 if (getattribute_str == NULL) {
5158 getattribute_str =
5159 PyUnicode_InternFromString("__getattribute__");
5160 if (getattribute_str == NULL)
5161 return NULL;
5162 }
5163 /* speed hack: we could use lookup_maybe, but that would resolve the
5164 method fully for each attribute lookup for classes with
5165 __getattr__, even when the attribute is present. So we use
5166 _PyType_Lookup and create the method only when needed, with
5167 call_attribute. */
5168 getattr = _PyType_Lookup(tp, getattr_str);
5169 if (getattr == NULL) {
5170 /* No __getattr__ hook: use a simpler dispatcher */
5171 tp->tp_getattro = slot_tp_getattro;
5172 return slot_tp_getattro(self, name);
5173 }
5174 Py_INCREF(getattr);
5175 /* speed hack: we could use lookup_maybe, but that would resolve the
5176 method fully for each attribute lookup for classes with
5177 __getattr__, even when self has the default __getattribute__
5178 method. So we use _PyType_Lookup and create the method only when
5179 needed, with call_attribute. */
5180 getattribute = _PyType_Lookup(tp, getattribute_str);
5181 if (getattribute == NULL ||
5182 (Py_TYPE(getattribute) == &PyWrapperDescr_Type &&
5183 ((PyWrapperDescrObject *)getattribute)->d_wrapped ==
5184 (void *)PyObject_GenericGetAttr))
5185 res = PyObject_GenericGetAttr(self, name);
5186 else {
5187 Py_INCREF(getattribute);
5188 res = call_attribute(self, getattribute, name);
5189 Py_DECREF(getattribute);
5190 }
5191 if (res == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) {
5192 PyErr_Clear();
5193 res = call_attribute(self, getattr, name);
5194 }
5195 Py_DECREF(getattr);
5196 return res;
Guido van Rossum19c1cd52001-09-21 21:24:49 +00005197}
5198
Tim Peters6d6c1a32001-08-02 04:15:00 +00005199static int
5200slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value)
5201{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005202 PyObject *res;
5203 static PyObject *delattr_str, *setattr_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005204
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005205 if (value == NULL)
5206 res = call_method(self, "__delattr__", &delattr_str,
5207 "(O)", name);
5208 else
5209 res = call_method(self, "__setattr__", &setattr_str,
5210 "(OO)", name, value);
5211 if (res == NULL)
5212 return -1;
5213 Py_DECREF(res);
5214 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005215}
5216
Guido van Rossumf5243f02008-01-01 04:06:48 +00005217static char *name_op[] = {
5218 "__lt__",
5219 "__le__",
5220 "__eq__",
5221 "__ne__",
5222 "__gt__",
5223 "__ge__",
5224};
5225
Tim Peters6d6c1a32001-08-02 04:15:00 +00005226static PyObject *
Mark Dickinson6f1d0492009-11-15 13:58:49 +00005227slot_tp_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005228{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005229 PyObject *func, *args, *res;
5230 static PyObject *op_str[6];
Tim Peters6d6c1a32001-08-02 04:15:00 +00005231
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005232 func = lookup_method(self, name_op[op], &op_str[op]);
5233 if (func == NULL) {
5234 PyErr_Clear();
5235 Py_INCREF(Py_NotImplemented);
5236 return Py_NotImplemented;
5237 }
5238 args = PyTuple_Pack(1, other);
5239 if (args == NULL)
5240 res = NULL;
5241 else {
5242 res = PyObject_Call(func, args, NULL);
5243 Py_DECREF(args);
5244 }
5245 Py_DECREF(func);
5246 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005247}
5248
Guido van Rossumb8f63662001-08-15 23:57:02 +00005249static PyObject *
Guido van Rossumb8f63662001-08-15 23:57:02 +00005250slot_tp_iter(PyObject *self)
5251{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005252 PyObject *func, *res;
5253 static PyObject *iter_str, *getitem_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00005254
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005255 func = lookup_method(self, "__iter__", &iter_str);
5256 if (func != NULL) {
5257 PyObject *args;
5258 args = res = PyTuple_New(0);
5259 if (args != NULL) {
5260 res = PyObject_Call(func, args, NULL);
5261 Py_DECREF(args);
5262 }
5263 Py_DECREF(func);
5264 return res;
5265 }
5266 PyErr_Clear();
5267 func = lookup_method(self, "__getitem__", &getitem_str);
5268 if (func == NULL) {
5269 PyErr_Format(PyExc_TypeError,
5270 "'%.200s' object is not iterable",
5271 Py_TYPE(self)->tp_name);
5272 return NULL;
5273 }
5274 Py_DECREF(func);
5275 return PySeqIter_New(self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005276}
Tim Peters6d6c1a32001-08-02 04:15:00 +00005277
5278static PyObject *
5279slot_tp_iternext(PyObject *self)
5280{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005281 static PyObject *next_str;
5282 return call_method(self, "__next__", &next_str, "()");
Tim Peters6d6c1a32001-08-02 04:15:00 +00005283}
5284
Guido van Rossum1a493502001-08-17 16:47:50 +00005285static PyObject *
5286slot_tp_descr_get(PyObject *self, PyObject *obj, PyObject *type)
5287{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005288 PyTypeObject *tp = Py_TYPE(self);
5289 PyObject *get;
5290 static PyObject *get_str = NULL;
Guido van Rossum1a493502001-08-17 16:47:50 +00005291
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005292 if (get_str == NULL) {
5293 get_str = PyUnicode_InternFromString("__get__");
5294 if (get_str == NULL)
5295 return NULL;
5296 }
5297 get = _PyType_Lookup(tp, get_str);
5298 if (get == NULL) {
5299 /* Avoid further slowdowns */
5300 if (tp->tp_descr_get == slot_tp_descr_get)
5301 tp->tp_descr_get = NULL;
5302 Py_INCREF(self);
5303 return self;
5304 }
5305 if (obj == NULL)
5306 obj = Py_None;
5307 if (type == NULL)
5308 type = Py_None;
5309 return PyObject_CallFunctionObjArgs(get, self, obj, type, NULL);
Guido van Rossum1a493502001-08-17 16:47:50 +00005310}
Tim Peters6d6c1a32001-08-02 04:15:00 +00005311
5312static int
5313slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value)
5314{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005315 PyObject *res;
5316 static PyObject *del_str, *set_str;
Guido van Rossum2c252392001-08-24 10:13:31 +00005317
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005318 if (value == NULL)
5319 res = call_method(self, "__delete__", &del_str,
5320 "(O)", target);
5321 else
5322 res = call_method(self, "__set__", &set_str,
5323 "(OO)", target, value);
5324 if (res == NULL)
5325 return -1;
5326 Py_DECREF(res);
5327 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005328}
5329
5330static int
5331slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds)
5332{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005333 static PyObject *init_str;
5334 PyObject *meth = lookup_method(self, "__init__", &init_str);
5335 PyObject *res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005336
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005337 if (meth == NULL)
5338 return -1;
5339 res = PyObject_Call(meth, args, kwds);
5340 Py_DECREF(meth);
5341 if (res == NULL)
5342 return -1;
5343 if (res != Py_None) {
5344 PyErr_Format(PyExc_TypeError,
5345 "__init__() should return None, not '%.200s'",
5346 Py_TYPE(res)->tp_name);
5347 Py_DECREF(res);
5348 return -1;
5349 }
5350 Py_DECREF(res);
5351 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005352}
5353
5354static PyObject *
5355slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
5356{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005357 static PyObject *new_str;
5358 PyObject *func;
5359 PyObject *newargs, *x;
5360 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005361
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005362 if (new_str == NULL) {
5363 new_str = PyUnicode_InternFromString("__new__");
5364 if (new_str == NULL)
5365 return NULL;
5366 }
5367 func = PyObject_GetAttr((PyObject *)type, new_str);
5368 if (func == NULL)
5369 return NULL;
5370 assert(PyTuple_Check(args));
5371 n = PyTuple_GET_SIZE(args);
5372 newargs = PyTuple_New(n+1);
5373 if (newargs == NULL)
5374 return NULL;
5375 Py_INCREF(type);
5376 PyTuple_SET_ITEM(newargs, 0, (PyObject *)type);
5377 for (i = 0; i < n; i++) {
5378 x = PyTuple_GET_ITEM(args, i);
5379 Py_INCREF(x);
5380 PyTuple_SET_ITEM(newargs, i+1, x);
5381 }
5382 x = PyObject_Call(func, newargs, kwds);
5383 Py_DECREF(newargs);
5384 Py_DECREF(func);
5385 return x;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005386}
5387
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005388static void
5389slot_tp_del(PyObject *self)
5390{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005391 static PyObject *del_str = NULL;
5392 PyObject *del, *res;
5393 PyObject *error_type, *error_value, *error_traceback;
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005394
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005395 /* Temporarily resurrect the object. */
5396 assert(self->ob_refcnt == 0);
5397 self->ob_refcnt = 1;
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005398
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005399 /* Save the current exception, if any. */
5400 PyErr_Fetch(&error_type, &error_value, &error_traceback);
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005401
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005402 /* Execute __del__ method, if any. */
5403 del = lookup_maybe(self, "__del__", &del_str);
5404 if (del != NULL) {
5405 res = PyEval_CallObject(del, NULL);
5406 if (res == NULL)
5407 PyErr_WriteUnraisable(del);
5408 else
5409 Py_DECREF(res);
5410 Py_DECREF(del);
5411 }
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005412
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005413 /* Restore the saved exception. */
5414 PyErr_Restore(error_type, error_value, error_traceback);
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005415
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005416 /* Undo the temporary resurrection; can't use DECREF here, it would
5417 * cause a recursive call.
5418 */
5419 assert(self->ob_refcnt > 0);
5420 if (--self->ob_refcnt == 0)
5421 return; /* this is the normal path out */
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005422
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005423 /* __del__ resurrected it! Make it look like the original Py_DECREF
5424 * never happened.
5425 */
5426 {
5427 Py_ssize_t refcnt = self->ob_refcnt;
5428 _Py_NewReference(self);
5429 self->ob_refcnt = refcnt;
5430 }
5431 assert(!PyType_IS_GC(Py_TYPE(self)) ||
5432 _Py_AS_GC(self)->gc.gc_refs != _PyGC_REFS_UNTRACKED);
5433 /* If Py_REF_DEBUG, _Py_NewReference bumped _Py_RefTotal, so
5434 * we need to undo that. */
5435 _Py_DEC_REFTOTAL;
5436 /* If Py_TRACE_REFS, _Py_NewReference re-added self to the object
5437 * chain, so no more to do there.
5438 * If COUNT_ALLOCS, the original decref bumped tp_frees, and
5439 * _Py_NewReference bumped tp_allocs: both of those need to be
5440 * undone.
5441 */
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005442#ifdef COUNT_ALLOCS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005443 --Py_TYPE(self)->tp_frees;
5444 --Py_TYPE(self)->tp_allocs;
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005445#endif
5446}
5447
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005448
5449/* Table mapping __foo__ names to tp_foo offsets and slot_tp_foo wrapper
Tim Petersbf9b2442003-03-23 05:35:36 +00005450 functions. The offsets here are relative to the 'PyHeapTypeObject'
Guido van Rossume5c691a2003-03-07 15:13:17 +00005451 structure, which incorporates the additional structures used for numbers,
5452 sequences and mappings.
5453 Note that multiple names may map to the same slot (e.g. __eq__,
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005454 __ne__ etc. all map to tp_richcompare) and one name may map to multiple
Guido van Rossumc334df52002-04-04 23:44:47 +00005455 slots (e.g. __str__ affects tp_str as well as tp_repr). The table is
5456 terminated with an all-zero entry. (This table is further initialized and
5457 sorted in init_slotdefs() below.) */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005458
Guido van Rossum6d204072001-10-21 00:44:31 +00005459typedef struct wrapperbase slotdef;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005460
5461#undef TPSLOT
Guido van Rossumc8e56452001-10-22 00:43:43 +00005462#undef FLSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005463#undef ETSLOT
5464#undef SQSLOT
5465#undef MPSLOT
5466#undef NBSLOT
Guido van Rossum6d204072001-10-21 00:44:31 +00005467#undef UNSLOT
5468#undef IBSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005469#undef BINSLOT
5470#undef RBINSLOT
5471
Guido van Rossum6d204072001-10-21 00:44:31 +00005472#define TPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005473 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
5474 PyDoc_STR(DOC)}
Guido van Rossumc8e56452001-10-22 00:43:43 +00005475#define FLSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC, FLAGS) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005476 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
5477 PyDoc_STR(DOC), FLAGS}
Guido van Rossum6d204072001-10-21 00:44:31 +00005478#define ETSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005479 {NAME, offsetof(PyHeapTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
5480 PyDoc_STR(DOC)}
Guido van Rossum6d204072001-10-21 00:44:31 +00005481#define SQSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005482 ETSLOT(NAME, as_sequence.SLOT, FUNCTION, WRAPPER, DOC)
Guido van Rossum6d204072001-10-21 00:44:31 +00005483#define MPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005484 ETSLOT(NAME, as_mapping.SLOT, FUNCTION, WRAPPER, DOC)
Guido van Rossum6d204072001-10-21 00:44:31 +00005485#define NBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005486 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, DOC)
Guido van Rossum6d204072001-10-21 00:44:31 +00005487#define UNSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005488 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
5489 "x." NAME "() <==> " DOC)
Guido van Rossum6d204072001-10-21 00:44:31 +00005490#define IBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005491 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
5492 "x." NAME "(y) <==> x" DOC "y")
Guido van Rossum6d204072001-10-21 00:44:31 +00005493#define BINSLOT(NAME, SLOT, FUNCTION, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005494 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
5495 "x." NAME "(y) <==> x" DOC "y")
Guido van Rossum6d204072001-10-21 00:44:31 +00005496#define RBINSLOT(NAME, SLOT, FUNCTION, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005497 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
5498 "x." NAME "(y) <==> y" DOC "x")
Anthony Baxter56616992005-06-03 14:12:21 +00005499#define BINSLOTNOTINFIX(NAME, SLOT, FUNCTION, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005500 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
5501 "x." NAME "(y) <==> " DOC)
Anthony Baxter56616992005-06-03 14:12:21 +00005502#define RBINSLOTNOTINFIX(NAME, SLOT, FUNCTION, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005503 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
5504 "x." NAME "(y) <==> " DOC)
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005505
5506static slotdef slotdefs[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005507 SQSLOT("__len__", sq_length, slot_sq_length, wrap_lenfunc,
5508 "x.__len__() <==> len(x)"),
5509 /* Heap types defining __add__/__mul__ have sq_concat/sq_repeat == NULL.
5510 The logic in abstract.c always falls back to nb_add/nb_multiply in
5511 this case. Defining both the nb_* and the sq_* slots to call the
5512 user-defined methods has unexpected side-effects, as shown by
5513 test_descr.notimplemented() */
5514 SQSLOT("__add__", sq_concat, NULL, wrap_binaryfunc,
5515 "x.__add__(y) <==> x+y"),
5516 SQSLOT("__mul__", sq_repeat, NULL, wrap_indexargfunc,
5517 "x.__mul__(n) <==> x*n"),
5518 SQSLOT("__rmul__", sq_repeat, NULL, wrap_indexargfunc,
5519 "x.__rmul__(n) <==> n*x"),
5520 SQSLOT("__getitem__", sq_item, slot_sq_item, wrap_sq_item,
5521 "x.__getitem__(y) <==> x[y]"),
5522 SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_setitem,
5523 "x.__setitem__(i, y) <==> x[i]=y"),
5524 SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_delitem,
5525 "x.__delitem__(y) <==> del x[y]"),
5526 SQSLOT("__contains__", sq_contains, slot_sq_contains, wrap_objobjproc,
5527 "x.__contains__(y) <==> y in x"),
5528 SQSLOT("__iadd__", sq_inplace_concat, NULL,
5529 wrap_binaryfunc, "x.__iadd__(y) <==> x+=y"),
5530 SQSLOT("__imul__", sq_inplace_repeat, NULL,
5531 wrap_indexargfunc, "x.__imul__(y) <==> x*=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005532
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005533 MPSLOT("__len__", mp_length, slot_mp_length, wrap_lenfunc,
5534 "x.__len__() <==> len(x)"),
5535 MPSLOT("__getitem__", mp_subscript, slot_mp_subscript,
5536 wrap_binaryfunc,
5537 "x.__getitem__(y) <==> x[y]"),
5538 MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript,
5539 wrap_objobjargproc,
5540 "x.__setitem__(i, y) <==> x[i]=y"),
5541 MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript,
5542 wrap_delitem,
5543 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005544
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005545 BINSLOT("__add__", nb_add, slot_nb_add,
5546 "+"),
5547 RBINSLOT("__radd__", nb_add, slot_nb_add,
5548 "+"),
5549 BINSLOT("__sub__", nb_subtract, slot_nb_subtract,
5550 "-"),
5551 RBINSLOT("__rsub__", nb_subtract, slot_nb_subtract,
5552 "-"),
5553 BINSLOT("__mul__", nb_multiply, slot_nb_multiply,
5554 "*"),
5555 RBINSLOT("__rmul__", nb_multiply, slot_nb_multiply,
5556 "*"),
5557 BINSLOT("__mod__", nb_remainder, slot_nb_remainder,
5558 "%"),
5559 RBINSLOT("__rmod__", nb_remainder, slot_nb_remainder,
5560 "%"),
5561 BINSLOTNOTINFIX("__divmod__", nb_divmod, slot_nb_divmod,
5562 "divmod(x, y)"),
5563 RBINSLOTNOTINFIX("__rdivmod__", nb_divmod, slot_nb_divmod,
5564 "divmod(y, x)"),
5565 NBSLOT("__pow__", nb_power, slot_nb_power, wrap_ternaryfunc,
5566 "x.__pow__(y[, z]) <==> pow(x, y[, z])"),
5567 NBSLOT("__rpow__", nb_power, slot_nb_power, wrap_ternaryfunc_r,
5568 "y.__rpow__(x[, z]) <==> pow(x, y[, z])"),
5569 UNSLOT("__neg__", nb_negative, slot_nb_negative, wrap_unaryfunc, "-x"),
5570 UNSLOT("__pos__", nb_positive, slot_nb_positive, wrap_unaryfunc, "+x"),
5571 UNSLOT("__abs__", nb_absolute, slot_nb_absolute, wrap_unaryfunc,
5572 "abs(x)"),
5573 UNSLOT("__bool__", nb_bool, slot_nb_bool, wrap_inquirypred,
5574 "x != 0"),
5575 UNSLOT("__invert__", nb_invert, slot_nb_invert, wrap_unaryfunc, "~x"),
5576 BINSLOT("__lshift__", nb_lshift, slot_nb_lshift, "<<"),
5577 RBINSLOT("__rlshift__", nb_lshift, slot_nb_lshift, "<<"),
5578 BINSLOT("__rshift__", nb_rshift, slot_nb_rshift, ">>"),
5579 RBINSLOT("__rrshift__", nb_rshift, slot_nb_rshift, ">>"),
5580 BINSLOT("__and__", nb_and, slot_nb_and, "&"),
5581 RBINSLOT("__rand__", nb_and, slot_nb_and, "&"),
5582 BINSLOT("__xor__", nb_xor, slot_nb_xor, "^"),
5583 RBINSLOT("__rxor__", nb_xor, slot_nb_xor, "^"),
5584 BINSLOT("__or__", nb_or, slot_nb_or, "|"),
5585 RBINSLOT("__ror__", nb_or, slot_nb_or, "|"),
5586 UNSLOT("__int__", nb_int, slot_nb_int, wrap_unaryfunc,
5587 "int(x)"),
5588 UNSLOT("__float__", nb_float, slot_nb_float, wrap_unaryfunc,
5589 "float(x)"),
5590 NBSLOT("__index__", nb_index, slot_nb_index, wrap_unaryfunc,
5591 "x[y:z] <==> x[y.__index__():z.__index__()]"),
5592 IBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add,
Eli Benderskyd3baae72011-11-11 16:57:05 +02005593 wrap_binaryfunc, "+="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005594 IBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract,
Eli Benderskyd3baae72011-11-11 16:57:05 +02005595 wrap_binaryfunc, "-="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005596 IBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply,
Eli Benderskyd3baae72011-11-11 16:57:05 +02005597 wrap_binaryfunc, "*="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005598 IBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder,
Eli Benderskyd3baae72011-11-11 16:57:05 +02005599 wrap_binaryfunc, "%="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005600 IBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power,
Eli Benderskyd3baae72011-11-11 16:57:05 +02005601 wrap_binaryfunc, "**="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005602 IBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift,
Eli Benderskyd3baae72011-11-11 16:57:05 +02005603 wrap_binaryfunc, "<<="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005604 IBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift,
Eli Benderskyd3baae72011-11-11 16:57:05 +02005605 wrap_binaryfunc, ">>="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005606 IBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and,
Eli Benderskyd3baae72011-11-11 16:57:05 +02005607 wrap_binaryfunc, "&="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005608 IBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor,
Eli Benderskyd3baae72011-11-11 16:57:05 +02005609 wrap_binaryfunc, "^="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005610 IBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or,
Eli Benderskyd3baae72011-11-11 16:57:05 +02005611 wrap_binaryfunc, "|="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005612 BINSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
5613 RBINSLOT("__rfloordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
5614 BINSLOT("__truediv__", nb_true_divide, slot_nb_true_divide, "/"),
5615 RBINSLOT("__rtruediv__", nb_true_divide, slot_nb_true_divide, "/"),
5616 IBSLOT("__ifloordiv__", nb_inplace_floor_divide,
5617 slot_nb_inplace_floor_divide, wrap_binaryfunc, "//"),
5618 IBSLOT("__itruediv__", nb_inplace_true_divide,
5619 slot_nb_inplace_true_divide, wrap_binaryfunc, "/"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005620
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005621 TPSLOT("__str__", tp_str, slot_tp_str, wrap_unaryfunc,
5622 "x.__str__() <==> str(x)"),
5623 TPSLOT("__repr__", tp_repr, slot_tp_repr, wrap_unaryfunc,
5624 "x.__repr__() <==> repr(x)"),
5625 TPSLOT("__hash__", tp_hash, slot_tp_hash, wrap_hashfunc,
5626 "x.__hash__() <==> hash(x)"),
5627 FLSLOT("__call__", tp_call, slot_tp_call, (wrapperfunc)wrap_call,
5628 "x.__call__(...) <==> x(...)", PyWrapperFlag_KEYWORDS),
5629 TPSLOT("__getattribute__", tp_getattro, slot_tp_getattr_hook,
5630 wrap_binaryfunc, "x.__getattribute__('name') <==> x.name"),
5631 TPSLOT("__getattribute__", tp_getattr, NULL, NULL, ""),
5632 TPSLOT("__getattr__", tp_getattro, slot_tp_getattr_hook, NULL, ""),
5633 TPSLOT("__getattr__", tp_getattr, NULL, NULL, ""),
5634 TPSLOT("__setattr__", tp_setattro, slot_tp_setattro, wrap_setattr,
5635 "x.__setattr__('name', value) <==> x.name = value"),
5636 TPSLOT("__setattr__", tp_setattr, NULL, NULL, ""),
5637 TPSLOT("__delattr__", tp_setattro, slot_tp_setattro, wrap_delattr,
5638 "x.__delattr__('name') <==> del x.name"),
5639 TPSLOT("__delattr__", tp_setattr, NULL, NULL, ""),
5640 TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare, richcmp_lt,
5641 "x.__lt__(y) <==> x<y"),
5642 TPSLOT("__le__", tp_richcompare, slot_tp_richcompare, richcmp_le,
5643 "x.__le__(y) <==> x<=y"),
5644 TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare, richcmp_eq,
5645 "x.__eq__(y) <==> x==y"),
5646 TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare, richcmp_ne,
5647 "x.__ne__(y) <==> x!=y"),
5648 TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare, richcmp_gt,
5649 "x.__gt__(y) <==> x>y"),
5650 TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare, richcmp_ge,
5651 "x.__ge__(y) <==> x>=y"),
5652 TPSLOT("__iter__", tp_iter, slot_tp_iter, wrap_unaryfunc,
5653 "x.__iter__() <==> iter(x)"),
5654 TPSLOT("__next__", tp_iternext, slot_tp_iternext, wrap_next,
5655 "x.__next__() <==> next(x)"),
5656 TPSLOT("__get__", tp_descr_get, slot_tp_descr_get, wrap_descr_get,
5657 "descr.__get__(obj[, type]) -> value"),
5658 TPSLOT("__set__", tp_descr_set, slot_tp_descr_set, wrap_descr_set,
5659 "descr.__set__(obj, value)"),
5660 TPSLOT("__delete__", tp_descr_set, slot_tp_descr_set,
5661 wrap_descr_delete, "descr.__delete__(obj)"),
5662 FLSLOT("__init__", tp_init, slot_tp_init, (wrapperfunc)wrap_init,
5663 "x.__init__(...) initializes x; "
Alexander Belopolsky977a6842010-08-16 20:17:07 +00005664 "see help(type(x)) for signature",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005665 PyWrapperFlag_KEYWORDS),
5666 TPSLOT("__new__", tp_new, slot_tp_new, NULL, ""),
5667 TPSLOT("__del__", tp_del, slot_tp_del, NULL, ""),
5668 {NULL}
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005669};
5670
Guido van Rossumc334df52002-04-04 23:44:47 +00005671/* Given a type pointer and an offset gotten from a slotdef entry, return a
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005672 pointer to the actual slot. This is not quite the same as simply adding
Guido van Rossumc334df52002-04-04 23:44:47 +00005673 the offset to the type pointer, since it takes care to indirect through the
5674 proper indirection pointer (as_buffer, etc.); it returns NULL if the
5675 indirection pointer is NULL. */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005676static void **
Martin v. Löwis18e16552006-02-15 17:27:45 +00005677slotptr(PyTypeObject *type, int ioffset)
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005678{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005679 char *ptr;
5680 long offset = ioffset;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005681
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005682 /* Note: this depends on the order of the members of PyHeapTypeObject! */
5683 assert(offset >= 0);
5684 assert((size_t)offset < offsetof(PyHeapTypeObject, as_buffer));
5685 if ((size_t)offset >= offsetof(PyHeapTypeObject, as_sequence)) {
5686 ptr = (char *)type->tp_as_sequence;
5687 offset -= offsetof(PyHeapTypeObject, as_sequence);
5688 }
5689 else if ((size_t)offset >= offsetof(PyHeapTypeObject, as_mapping)) {
5690 ptr = (char *)type->tp_as_mapping;
5691 offset -= offsetof(PyHeapTypeObject, as_mapping);
5692 }
5693 else if ((size_t)offset >= offsetof(PyHeapTypeObject, as_number)) {
5694 ptr = (char *)type->tp_as_number;
5695 offset -= offsetof(PyHeapTypeObject, as_number);
5696 }
5697 else {
5698 ptr = (char *)type;
5699 }
5700 if (ptr != NULL)
5701 ptr += offset;
5702 return (void **)ptr;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005703}
Guido van Rossumf040ede2001-08-07 16:40:56 +00005704
Guido van Rossumc334df52002-04-04 23:44:47 +00005705/* Length of array of slotdef pointers used to store slots with the
5706 same __name__. There should be at most MAX_EQUIV-1 slotdef entries with
5707 the same __name__, for any __name__. Since that's a static property, it is
5708 appropriate to declare fixed-size arrays for this. */
5709#define MAX_EQUIV 10
5710
5711/* Return a slot pointer for a given name, but ONLY if the attribute has
5712 exactly one slot function. The name must be an interned string. */
5713static void **
5714resolve_slotdups(PyTypeObject *type, PyObject *name)
5715{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005716 /* XXX Maybe this could be optimized more -- but is it worth it? */
Guido van Rossumc334df52002-04-04 23:44:47 +00005717
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005718 /* pname and ptrs act as a little cache */
5719 static PyObject *pname;
5720 static slotdef *ptrs[MAX_EQUIV];
5721 slotdef *p, **pp;
5722 void **res, **ptr;
Guido van Rossumc334df52002-04-04 23:44:47 +00005723
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005724 if (pname != name) {
5725 /* Collect all slotdefs that match name into ptrs. */
5726 pname = name;
5727 pp = ptrs;
5728 for (p = slotdefs; p->name_strobj; p++) {
5729 if (p->name_strobj == name)
5730 *pp++ = p;
5731 }
5732 *pp = NULL;
5733 }
Guido van Rossumc334df52002-04-04 23:44:47 +00005734
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005735 /* Look in all matching slots of the type; if exactly one of these has
5736 a filled-in slot, return its value. Otherwise return NULL. */
5737 res = NULL;
5738 for (pp = ptrs; *pp; pp++) {
5739 ptr = slotptr(type, (*pp)->offset);
5740 if (ptr == NULL || *ptr == NULL)
5741 continue;
5742 if (res != NULL)
5743 return NULL;
5744 res = ptr;
5745 }
5746 return res;
Guido van Rossumc334df52002-04-04 23:44:47 +00005747}
5748
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005749/* Common code for update_slots_callback() and fixup_slot_dispatchers(). This
Guido van Rossumc334df52002-04-04 23:44:47 +00005750 does some incredibly complex thinking and then sticks something into the
5751 slot. (It sees if the adjacent slotdefs for the same slot have conflicting
5752 interests, and then stores a generic wrapper or a specific function into
5753 the slot.) Return a pointer to the next slotdef with a different offset,
5754 because that's convenient for fixup_slot_dispatchers(). */
5755static slotdef *
5756update_one_slot(PyTypeObject *type, slotdef *p)
5757{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005758 PyObject *descr;
5759 PyWrapperDescrObject *d;
5760 void *generic = NULL, *specific = NULL;
5761 int use_generic = 0;
5762 int offset = p->offset;
5763 void **ptr = slotptr(type, offset);
Guido van Rossumc334df52002-04-04 23:44:47 +00005764
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005765 if (ptr == NULL) {
5766 do {
5767 ++p;
5768 } while (p->offset == offset);
5769 return p;
5770 }
5771 do {
5772 descr = _PyType_Lookup(type, p->name_strobj);
5773 if (descr == NULL) {
5774 if (ptr == (void**)&type->tp_iternext) {
Trent Nelsonab02db22012-09-18 21:58:03 -04005775 specific = (void *)_PyObject_NextNotImplemented;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005776 }
5777 continue;
5778 }
Benjamin Peterson7b166872012-04-24 11:06:25 -04005779 if (Py_TYPE(descr) == &PyWrapperDescr_Type &&
5780 ((PyWrapperDescrObject *)descr)->d_base->name_strobj == p->name_strobj) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005781 void **tptr = resolve_slotdups(type, p->name_strobj);
5782 if (tptr == NULL || tptr == ptr)
5783 generic = p->function;
5784 d = (PyWrapperDescrObject *)descr;
5785 if (d->d_base->wrapper == p->wrapper &&
5786 PyType_IsSubtype(type, PyDescr_TYPE(d)))
5787 {
5788 if (specific == NULL ||
5789 specific == d->d_wrapped)
5790 specific = d->d_wrapped;
5791 else
5792 use_generic = 1;
5793 }
5794 }
5795 else if (Py_TYPE(descr) == &PyCFunction_Type &&
5796 PyCFunction_GET_FUNCTION(descr) ==
5797 (PyCFunction)tp_new_wrapper &&
5798 ptr == (void**)&type->tp_new)
5799 {
5800 /* The __new__ wrapper is not a wrapper descriptor,
5801 so must be special-cased differently.
5802 If we don't do this, creating an instance will
5803 always use slot_tp_new which will look up
5804 __new__ in the MRO which will call tp_new_wrapper
5805 which will look through the base classes looking
5806 for a static base and call its tp_new (usually
5807 PyType_GenericNew), after performing various
5808 sanity checks and constructing a new argument
5809 list. Cut all that nonsense short -- this speeds
5810 up instance creation tremendously. */
5811 specific = (void *)type->tp_new;
5812 /* XXX I'm not 100% sure that there isn't a hole
5813 in this reasoning that requires additional
5814 sanity checks. I'll buy the first person to
5815 point out a bug in this reasoning a beer. */
5816 }
5817 else if (descr == Py_None &&
5818 ptr == (void**)&type->tp_hash) {
5819 /* We specifically allow __hash__ to be set to None
5820 to prevent inheritance of the default
5821 implementation from object.__hash__ */
Trent Nelsonab02db22012-09-18 21:58:03 -04005822 specific = (void *)PyObject_HashNotImplemented;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005823 }
5824 else {
5825 use_generic = 1;
5826 generic = p->function;
5827 }
5828 } while ((++p)->offset == offset);
5829 if (specific && !use_generic)
5830 *ptr = specific;
5831 else
5832 *ptr = generic;
5833 return p;
Guido van Rossumc334df52002-04-04 23:44:47 +00005834}
5835
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005836/* In the type, update the slots whose slotdefs are gathered in the pp array.
5837 This is a callback for update_subclasses(). */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005838static int
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005839update_slots_callback(PyTypeObject *type, void *data)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005840{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005841 slotdef **pp = (slotdef **)data;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005842
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005843 for (; *pp; pp++)
5844 update_one_slot(type, *pp);
5845 return 0;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005846}
5847
Guido van Rossumc334df52002-04-04 23:44:47 +00005848/* Comparison function for qsort() to compare slotdefs by their offset, and
5849 for equal offset by their address (to force a stable sort). */
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005850static int
5851slotdef_cmp(const void *aa, const void *bb)
5852{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005853 const slotdef *a = (const slotdef *)aa, *b = (const slotdef *)bb;
5854 int c = a->offset - b->offset;
5855 if (c != 0)
5856 return c;
5857 else
5858 /* Cannot use a-b, as this gives off_t,
5859 which may lose precision when converted to int. */
5860 return (a > b) ? 1 : (a < b) ? -1 : 0;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005861}
5862
Guido van Rossumc334df52002-04-04 23:44:47 +00005863/* Initialize the slotdefs table by adding interned string objects for the
5864 names and sorting the entries. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005865static void
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005866init_slotdefs(void)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005867{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005868 slotdef *p;
5869 static int initialized = 0;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005870
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005871 if (initialized)
5872 return;
5873 for (p = slotdefs; p->name; p++) {
5874 p->name_strobj = PyUnicode_InternFromString(p->name);
5875 if (!p->name_strobj)
5876 Py_FatalError("Out of memory interning slotdef names");
5877 }
5878 qsort((void *)slotdefs, (size_t)(p-slotdefs), sizeof(slotdef),
5879 slotdef_cmp);
5880 initialized = 1;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005881}
5882
Guido van Rossumc334df52002-04-04 23:44:47 +00005883/* Update the slots after assignment to a class (type) attribute. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005884static int
5885update_slot(PyTypeObject *type, PyObject *name)
5886{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005887 slotdef *ptrs[MAX_EQUIV];
5888 slotdef *p;
5889 slotdef **pp;
5890 int offset;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005891
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005892 /* Clear the VALID_VERSION flag of 'type' and all its
5893 subclasses. This could possibly be unified with the
5894 update_subclasses() recursion below, but carefully:
5895 they each have their own conditions on which to stop
5896 recursing into subclasses. */
5897 PyType_Modified(type);
Christian Heimesa62da1d2008-01-12 19:39:10 +00005898
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005899 init_slotdefs();
5900 pp = ptrs;
5901 for (p = slotdefs; p->name; p++) {
5902 /* XXX assume name is interned! */
5903 if (p->name_strobj == name)
5904 *pp++ = p;
5905 }
5906 *pp = NULL;
5907 for (pp = ptrs; *pp; pp++) {
5908 p = *pp;
5909 offset = p->offset;
5910 while (p > slotdefs && (p-1)->offset == offset)
5911 --p;
5912 *pp = p;
5913 }
5914 if (ptrs[0] == NULL)
5915 return 0; /* Not an attribute that affects any slots */
5916 return update_subclasses(type, name,
5917 update_slots_callback, (void *)ptrs);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005918}
5919
Guido van Rossumc334df52002-04-04 23:44:47 +00005920/* Store the proper functions in the slot dispatches at class (type)
5921 definition time, based upon which operations the class overrides in its
5922 dict. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00005923static void
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005924fixup_slot_dispatchers(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005925{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005926 slotdef *p;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005927
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005928 init_slotdefs();
5929 for (p = slotdefs; p->name; )
5930 p = update_one_slot(type, p);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005931}
Guido van Rossum705f0f52001-08-24 16:47:00 +00005932
Michael W. Hudson98bbc492002-11-26 14:47:27 +00005933static void
5934update_all_slots(PyTypeObject* type)
5935{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005936 slotdef *p;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00005937
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005938 init_slotdefs();
5939 for (p = slotdefs; p->name; p++) {
5940 /* update_slot returns int but can't actually fail */
5941 update_slot(type, p->name_strobj);
5942 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +00005943}
5944
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005945/* recurse_down_subclasses() and update_subclasses() are mutually
5946 recursive functions to call a callback for all subclasses,
5947 but refraining from recursing into subclasses that define 'name'. */
5948
5949static int
5950update_subclasses(PyTypeObject *type, PyObject *name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005951 update_callback callback, void *data)
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005952{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005953 if (callback(type, data) < 0)
5954 return -1;
5955 return recurse_down_subclasses(type, name, callback, data);
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005956}
5957
5958static int
5959recurse_down_subclasses(PyTypeObject *type, PyObject *name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005960 update_callback callback, void *data)
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005961{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005962 PyTypeObject *subclass;
5963 PyObject *ref, *subclasses, *dict;
5964 Py_ssize_t i, n;
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005965
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005966 subclasses = type->tp_subclasses;
5967 if (subclasses == NULL)
5968 return 0;
5969 assert(PyList_Check(subclasses));
5970 n = PyList_GET_SIZE(subclasses);
5971 for (i = 0; i < n; i++) {
5972 ref = PyList_GET_ITEM(subclasses, i);
5973 assert(PyWeakref_CheckRef(ref));
5974 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
5975 assert(subclass != NULL);
5976 if ((PyObject *)subclass == Py_None)
5977 continue;
5978 assert(PyType_Check(subclass));
5979 /* Avoid recursing down into unaffected classes */
5980 dict = subclass->tp_dict;
5981 if (dict != NULL && PyDict_Check(dict) &&
5982 PyDict_GetItem(dict, name) != NULL)
5983 continue;
5984 if (update_subclasses(subclass, name, callback, data) < 0)
5985 return -1;
5986 }
5987 return 0;
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005988}
5989
Guido van Rossum6d204072001-10-21 00:44:31 +00005990/* This function is called by PyType_Ready() to populate the type's
5991 dictionary with method descriptors for function slots. For each
Guido van Rossum09638c12002-06-13 19:17:46 +00005992 function slot (like tp_repr) that's defined in the type, one or more
5993 corresponding descriptors are added in the type's tp_dict dictionary
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005994 under the appropriate name (like __repr__). Some function slots
Guido van Rossum09638c12002-06-13 19:17:46 +00005995 cause more than one descriptor to be added (for example, the nb_add
5996 slot adds both __add__ and __radd__ descriptors) and some function
5997 slots compete for the same descriptor (for example both sq_item and
5998 mp_subscript generate a __getitem__ descriptor).
5999
Ezio Melotti13925002011-03-16 11:05:33 +02006000 In the latter case, the first slotdef entry encountered wins. Since
Tim Petersbf9b2442003-03-23 05:35:36 +00006001 slotdef entries are sorted by the offset of the slot in the
Guido van Rossume5c691a2003-03-07 15:13:17 +00006002 PyHeapTypeObject, this gives us some control over disambiguating
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006003 between competing slots: the members of PyHeapTypeObject are listed
6004 from most general to least general, so the most general slot is
6005 preferred. In particular, because as_mapping comes before as_sequence,
6006 for a type that defines both mp_subscript and sq_item, mp_subscript
6007 wins.
Guido van Rossum09638c12002-06-13 19:17:46 +00006008
6009 This only adds new descriptors and doesn't overwrite entries in
6010 tp_dict that were previously defined. The descriptors contain a
6011 reference to the C function they must call, so that it's safe if they
6012 are copied into a subtype's __dict__ and the subtype has a different
6013 C function in its slot -- calling the method defined by the
6014 descriptor will call the C function that was used to create it,
6015 rather than the C function present in the slot when it is called.
6016 (This is important because a subtype may have a C function in the
6017 slot that calls the method from the dictionary, and we want to avoid
6018 infinite recursion here.) */
Guido van Rossum6d204072001-10-21 00:44:31 +00006019
6020static int
6021add_operators(PyTypeObject *type)
6022{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006023 PyObject *dict = type->tp_dict;
6024 slotdef *p;
6025 PyObject *descr;
6026 void **ptr;
Guido van Rossum6d204072001-10-21 00:44:31 +00006027
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006028 init_slotdefs();
6029 for (p = slotdefs; p->name; p++) {
6030 if (p->wrapper == NULL)
6031 continue;
6032 ptr = slotptr(type, p->offset);
6033 if (!ptr || !*ptr)
6034 continue;
6035 if (PyDict_GetItem(dict, p->name_strobj))
6036 continue;
Trent Nelsonab02db22012-09-18 21:58:03 -04006037 if (*ptr == (void *)PyObject_HashNotImplemented) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006038 /* Classes may prevent the inheritance of the tp_hash
6039 slot by storing PyObject_HashNotImplemented in it. Make it
6040 visible as a None value for the __hash__ attribute. */
6041 if (PyDict_SetItem(dict, p->name_strobj, Py_None) < 0)
6042 return -1;
6043 }
6044 else {
6045 descr = PyDescr_NewWrapper(type, p, *ptr);
6046 if (descr == NULL)
6047 return -1;
6048 if (PyDict_SetItem(dict, p->name_strobj, descr) < 0)
6049 return -1;
6050 Py_DECREF(descr);
6051 }
6052 }
6053 if (type->tp_new != NULL) {
6054 if (add_tp_new_wrapper(type) < 0)
6055 return -1;
6056 }
6057 return 0;
Guido van Rossum6d204072001-10-21 00:44:31 +00006058}
6059
Guido van Rossum705f0f52001-08-24 16:47:00 +00006060
6061/* Cooperative 'super' */
6062
6063typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006064 PyObject_HEAD
6065 PyTypeObject *type;
6066 PyObject *obj;
6067 PyTypeObject *obj_type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006068} superobject;
6069
Guido van Rossum6f799372001-09-20 20:46:19 +00006070static PyMemberDef super_members[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006071 {"__thisclass__", T_OBJECT, offsetof(superobject, type), READONLY,
6072 "the class invoking super()"},
6073 {"__self__", T_OBJECT, offsetof(superobject, obj), READONLY,
6074 "the instance invoking super(); may be None"},
6075 {"__self_class__", T_OBJECT, offsetof(superobject, obj_type), READONLY,
6076 "the type of the instance invoking super(); may be None"},
6077 {0}
Guido van Rossum41eb14d2001-08-30 23:13:11 +00006078};
6079
Guido van Rossum705f0f52001-08-24 16:47:00 +00006080static void
6081super_dealloc(PyObject *self)
6082{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006083 superobject *su = (superobject *)self;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006084
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006085 _PyObject_GC_UNTRACK(self);
6086 Py_XDECREF(su->obj);
6087 Py_XDECREF(su->type);
6088 Py_XDECREF(su->obj_type);
6089 Py_TYPE(self)->tp_free(self);
Guido van Rossum705f0f52001-08-24 16:47:00 +00006090}
6091
6092static PyObject *
Guido van Rossum41eb14d2001-08-30 23:13:11 +00006093super_repr(PyObject *self)
6094{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006095 superobject *su = (superobject *)self;
Guido van Rossum41eb14d2001-08-30 23:13:11 +00006096
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006097 if (su->obj_type)
6098 return PyUnicode_FromFormat(
6099 "<super: <class '%s'>, <%s object>>",
6100 su->type ? su->type->tp_name : "NULL",
6101 su->obj_type->tp_name);
6102 else
6103 return PyUnicode_FromFormat(
6104 "<super: <class '%s'>, NULL>",
6105 su->type ? su->type->tp_name : "NULL");
Guido van Rossum41eb14d2001-08-30 23:13:11 +00006106}
6107
6108static PyObject *
Guido van Rossum705f0f52001-08-24 16:47:00 +00006109super_getattro(PyObject *self, PyObject *name)
6110{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006111 superobject *su = (superobject *)self;
6112 int skip = su->obj_type == NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006113
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006114 if (!skip) {
6115 /* We want __class__ to return the class of the super object
6116 (i.e. super, or a subclass), not the class of su->obj. */
6117 skip = (PyUnicode_Check(name) &&
6118 PyUnicode_GET_SIZE(name) == 9 &&
6119 PyUnicode_CompareWithASCIIString(name, "__class__") == 0);
6120 }
Guido van Rossum76ba09f2003-04-16 19:40:58 +00006121
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006122 if (!skip) {
6123 PyObject *mro, *res, *tmp, *dict;
6124 PyTypeObject *starttype;
6125 descrgetfunc f;
6126 Py_ssize_t i, n;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006127
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006128 starttype = su->obj_type;
6129 mro = starttype->tp_mro;
Guido van Rossum155db9a2002-04-02 17:53:47 +00006130
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006131 if (mro == NULL)
6132 n = 0;
6133 else {
6134 assert(PyTuple_Check(mro));
6135 n = PyTuple_GET_SIZE(mro);
6136 }
6137 for (i = 0; i < n; i++) {
6138 if ((PyObject *)(su->type) == PyTuple_GET_ITEM(mro, i))
6139 break;
6140 }
6141 i++;
6142 res = NULL;
6143 for (; i < n; i++) {
6144 tmp = PyTuple_GET_ITEM(mro, i);
6145 if (PyType_Check(tmp))
6146 dict = ((PyTypeObject *)tmp)->tp_dict;
6147 else
6148 continue;
6149 res = PyDict_GetItem(dict, name);
6150 if (res != NULL) {
6151 Py_INCREF(res);
6152 f = Py_TYPE(res)->tp_descr_get;
6153 if (f != NULL) {
6154 tmp = f(res,
6155 /* Only pass 'obj' param if
6156 this is instance-mode super
6157 (See SF ID #743627)
6158 */
6159 (su->obj == (PyObject *)
6160 su->obj_type
6161 ? (PyObject *)NULL
6162 : su->obj),
6163 (PyObject *)starttype);
6164 Py_DECREF(res);
6165 res = tmp;
6166 }
6167 return res;
6168 }
6169 }
6170 }
6171 return PyObject_GenericGetAttr(self, name);
Guido van Rossum705f0f52001-08-24 16:47:00 +00006172}
6173
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006174static PyTypeObject *
Guido van Rossum5b443c62001-12-03 15:38:28 +00006175supercheck(PyTypeObject *type, PyObject *obj)
6176{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006177 /* Check that a super() call makes sense. Return a type object.
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006178
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006179 obj can be a new-style class, or an instance of one:
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006180
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006181 - If it is a class, it must be a subclass of 'type'. This case is
6182 used for class methods; the return value is obj.
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006183
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006184 - If it is an instance, it must be an instance of 'type'. This is
6185 the normal case; the return value is obj.__class__.
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006186
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006187 But... when obj is an instance, we want to allow for the case where
6188 Py_TYPE(obj) is not a subclass of type, but obj.__class__ is!
6189 This will allow using super() with a proxy for obj.
6190 */
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006191
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006192 /* Check for first bullet above (special case) */
6193 if (PyType_Check(obj) && PyType_IsSubtype((PyTypeObject *)obj, type)) {
6194 Py_INCREF(obj);
6195 return (PyTypeObject *)obj;
6196 }
Guido van Rossum8e80a722003-02-18 19:22:22 +00006197
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006198 /* Normal case */
6199 if (PyType_IsSubtype(Py_TYPE(obj), type)) {
6200 Py_INCREF(Py_TYPE(obj));
6201 return Py_TYPE(obj);
6202 }
6203 else {
6204 /* Try the slow way */
6205 static PyObject *class_str = NULL;
6206 PyObject *class_attr;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006207
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006208 if (class_str == NULL) {
6209 class_str = PyUnicode_FromString("__class__");
6210 if (class_str == NULL)
6211 return NULL;
6212 }
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006213
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006214 class_attr = PyObject_GetAttr(obj, class_str);
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006215
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006216 if (class_attr != NULL &&
6217 PyType_Check(class_attr) &&
6218 (PyTypeObject *)class_attr != Py_TYPE(obj))
6219 {
6220 int ok = PyType_IsSubtype(
6221 (PyTypeObject *)class_attr, type);
6222 if (ok)
6223 return (PyTypeObject *)class_attr;
6224 }
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006225
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006226 if (class_attr == NULL)
6227 PyErr_Clear();
6228 else
6229 Py_DECREF(class_attr);
6230 }
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006231
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006232 PyErr_SetString(PyExc_TypeError,
6233 "super(type, obj): "
6234 "obj must be an instance or subtype of type");
6235 return NULL;
Guido van Rossum5b443c62001-12-03 15:38:28 +00006236}
6237
Guido van Rossum705f0f52001-08-24 16:47:00 +00006238static PyObject *
6239super_descr_get(PyObject *self, PyObject *obj, PyObject *type)
6240{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006241 superobject *su = (superobject *)self;
6242 superobject *newobj;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006243
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006244 if (obj == NULL || obj == Py_None || su->obj != NULL) {
6245 /* Not binding to an object, or already bound */
6246 Py_INCREF(self);
6247 return self;
6248 }
6249 if (Py_TYPE(su) != &PySuper_Type)
6250 /* If su is an instance of a (strict) subclass of super,
6251 call its type */
6252 return PyObject_CallFunctionObjArgs((PyObject *)Py_TYPE(su),
6253 su->type, obj, NULL);
6254 else {
6255 /* Inline the common case */
6256 PyTypeObject *obj_type = supercheck(su->type, obj);
6257 if (obj_type == NULL)
6258 return NULL;
6259 newobj = (superobject *)PySuper_Type.tp_new(&PySuper_Type,
6260 NULL, NULL);
6261 if (newobj == NULL)
6262 return NULL;
6263 Py_INCREF(su->type);
6264 Py_INCREF(obj);
6265 newobj->type = su->type;
6266 newobj->obj = obj;
6267 newobj->obj_type = obj_type;
6268 return (PyObject *)newobj;
6269 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00006270}
6271
6272static int
6273super_init(PyObject *self, PyObject *args, PyObject *kwds)
6274{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006275 superobject *su = (superobject *)self;
6276 PyTypeObject *type = NULL;
6277 PyObject *obj = NULL;
6278 PyTypeObject *obj_type = NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006279
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006280 if (!_PyArg_NoKeywords("super", kwds))
6281 return -1;
6282 if (!PyArg_ParseTuple(args, "|O!O:super", &PyType_Type, &type, &obj))
6283 return -1;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00006284
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006285 if (type == NULL) {
6286 /* Call super(), without args -- fill in from __class__
6287 and first local variable on the stack. */
6288 PyFrameObject *f = PyThreadState_GET()->frame;
6289 PyCodeObject *co = f->f_code;
Victor Stinner0fcab4a2011-01-04 12:59:15 +00006290 Py_ssize_t i, n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006291 if (co == NULL) {
6292 PyErr_SetString(PyExc_SystemError,
6293 "super(): no code object");
6294 return -1;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00006295 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006296 if (co->co_argcount == 0) {
6297 PyErr_SetString(PyExc_SystemError,
6298 "super(): no arguments");
6299 return -1;
6300 }
6301 obj = f->f_localsplus[0];
6302 if (obj == NULL) {
6303 PyErr_SetString(PyExc_SystemError,
6304 "super(): arg[0] deleted");
6305 return -1;
6306 }
6307 if (co->co_freevars == NULL)
6308 n = 0;
6309 else {
6310 assert(PyTuple_Check(co->co_freevars));
6311 n = PyTuple_GET_SIZE(co->co_freevars);
6312 }
6313 for (i = 0; i < n; i++) {
6314 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
6315 assert(PyUnicode_Check(name));
6316 if (!PyUnicode_CompareWithASCIIString(name,
6317 "__class__")) {
6318 Py_ssize_t index = co->co_nlocals +
6319 PyTuple_GET_SIZE(co->co_cellvars) + i;
6320 PyObject *cell = f->f_localsplus[index];
6321 if (cell == NULL || !PyCell_Check(cell)) {
6322 PyErr_SetString(PyExc_SystemError,
6323 "super(): bad __class__ cell");
6324 return -1;
6325 }
6326 type = (PyTypeObject *) PyCell_GET(cell);
6327 if (type == NULL) {
6328 PyErr_SetString(PyExc_SystemError,
6329 "super(): empty __class__ cell");
6330 return -1;
6331 }
6332 if (!PyType_Check(type)) {
6333 PyErr_Format(PyExc_SystemError,
6334 "super(): __class__ is not a type (%s)",
6335 Py_TYPE(type)->tp_name);
6336 return -1;
6337 }
6338 break;
6339 }
6340 }
6341 if (type == NULL) {
6342 PyErr_SetString(PyExc_SystemError,
6343 "super(): __class__ cell not found");
6344 return -1;
6345 }
6346 }
Guido van Rossumcd16bf62007-06-13 18:07:49 +00006347
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006348 if (obj == Py_None)
6349 obj = NULL;
6350 if (obj != NULL) {
6351 obj_type = supercheck(type, obj);
6352 if (obj_type == NULL)
6353 return -1;
6354 Py_INCREF(obj);
6355 }
6356 Py_INCREF(type);
6357 su->type = type;
6358 su->obj = obj;
6359 su->obj_type = obj_type;
6360 return 0;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006361}
6362
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00006363PyDoc_STRVAR(super_doc,
Guido van Rossumcd16bf62007-06-13 18:07:49 +00006364"super() -> same as super(__class__, <first argument>)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00006365"super(type) -> unbound super object\n"
6366"super(type, obj) -> bound super object; requires isinstance(obj, type)\n"
Guido van Rossume705ef12001-08-29 15:47:06 +00006367"super(type, type2) -> bound super object; requires issubclass(type2, type)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00006368"Typical use to call a cooperative superclass method:\n"
6369"class C(B):\n"
6370" def meth(self, arg):\n"
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006371" super().meth(arg)\n"
Guido van Rossumcd16bf62007-06-13 18:07:49 +00006372"This works for class methods too:\n"
6373"class C(B):\n"
6374" @classmethod\n"
6375" def cmeth(cls, arg):\n"
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006376" super().cmeth(arg)\n");
Guido van Rossum705f0f52001-08-24 16:47:00 +00006377
Guido van Rossum048eb752001-10-02 21:24:57 +00006378static int
6379super_traverse(PyObject *self, visitproc visit, void *arg)
6380{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006381 superobject *su = (superobject *)self;
Guido van Rossum048eb752001-10-02 21:24:57 +00006382
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006383 Py_VISIT(su->obj);
6384 Py_VISIT(su->type);
6385 Py_VISIT(su->obj_type);
Guido van Rossum048eb752001-10-02 21:24:57 +00006386
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006387 return 0;
Guido van Rossum048eb752001-10-02 21:24:57 +00006388}
6389
Guido van Rossum705f0f52001-08-24 16:47:00 +00006390PyTypeObject PySuper_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006391 PyVarObject_HEAD_INIT(&PyType_Type, 0)
6392 "super", /* tp_name */
6393 sizeof(superobject), /* tp_basicsize */
6394 0, /* tp_itemsize */
6395 /* methods */
6396 super_dealloc, /* tp_dealloc */
6397 0, /* tp_print */
6398 0, /* tp_getattr */
6399 0, /* tp_setattr */
6400 0, /* tp_reserved */
6401 super_repr, /* tp_repr */
6402 0, /* tp_as_number */
6403 0, /* tp_as_sequence */
6404 0, /* tp_as_mapping */
6405 0, /* tp_hash */
6406 0, /* tp_call */
6407 0, /* tp_str */
6408 super_getattro, /* tp_getattro */
6409 0, /* tp_setattro */
6410 0, /* tp_as_buffer */
6411 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
6412 Py_TPFLAGS_BASETYPE, /* tp_flags */
6413 super_doc, /* tp_doc */
6414 super_traverse, /* tp_traverse */
6415 0, /* tp_clear */
6416 0, /* tp_richcompare */
6417 0, /* tp_weaklistoffset */
6418 0, /* tp_iter */
6419 0, /* tp_iternext */
6420 0, /* tp_methods */
6421 super_members, /* tp_members */
6422 0, /* tp_getset */
6423 0, /* tp_base */
6424 0, /* tp_dict */
6425 super_descr_get, /* tp_descr_get */
6426 0, /* tp_descr_set */
6427 0, /* tp_dictoffset */
6428 super_init, /* tp_init */
6429 PyType_GenericAlloc, /* tp_alloc */
6430 PyType_GenericNew, /* tp_new */
6431 PyObject_GC_Del, /* tp_free */
Guido van Rossum705f0f52001-08-24 16:47:00 +00006432};