blob: b6ffe9237932c275cbacbfd4a8b519bde9fc28ca [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. */
16#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))
21#define MCACHE_HASH_METHOD(type, name) \
22 MCACHE_HASH((type)->tp_version_tag, \
Georg Brandl1bcf35a2008-05-25 09:32:09 +000023 ((PyUnicodeObject *)(name))->hash)
Christian Heimesa62da1d2008-01-12 19:39:10 +000024#define MCACHE_CACHEABLE_NAME(name) \
Georg Brandl1bcf35a2008-05-25 09:32:09 +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 {
29 unsigned int version;
30 PyObject *name; /* reference to exactly a str or None */
31 PyObject *value; /* borrowed */
32};
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{
40 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 */
Georg Brandlf08a9dd2008-06-10 16:57:31 +000050 PyType_Modified(&PyBaseObject_Type);
Christian Heimes26855632008-01-27 23:50:43 +000051 return cur_version_tag;
52}
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{
57 /* 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.
60
61 Invariants:
62
63 - 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)
66
67 - before Py_TPFLAGS_VALID_VERSION_TAG can be set on a type,
68 it must first be set on all super types.
69
70 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;
78
Christian Heimes412dc9c2008-01-27 18:55:54 +000079 if (!PyType_HasFeature(type, Py_TPFLAGS_VALID_VERSION_TAG))
Christian Heimesa62da1d2008-01-12 19:39:10 +000080 return;
81
82 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) {
Georg Brandlf08a9dd2008-06-10 16:57:31 +000089 PyType_Modified((PyTypeObject *)ref);
Christian Heimesa62da1d2008-01-12 19:39:10 +000090 }
91 }
92 }
93 type->tp_flags &= ~Py_TPFLAGS_VALID_VERSION_TAG;
94}
95
96static void
97type_mro_modified(PyTypeObject *type, PyObject *bases) {
98 /*
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.
102
103 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.
108
109 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;
114
Christian Heimes412dc9c2008-01-27 18:55:54 +0000115 if (!PyType_HasFeature(type, Py_TPFLAGS_HAVE_VERSION_TAG))
Christian Heimesa62da1d2008-01-12 19:39:10 +0000116 return;
117
118 n = PyTuple_GET_SIZE(bases);
119 for (i = 0; i < n; i++) {
120 PyObject *b = PyTuple_GET_ITEM(bases, i);
121 PyTypeObject *cls;
122
123 if (!PyType_Check(b) ) {
124 clear = 1;
125 break;
126 }
127
128 cls = (PyTypeObject *)b;
129
130 if (!PyType_HasFeature(cls, Py_TPFLAGS_HAVE_VERSION_TAG) ||
131 !PyType_IsSubtype(type, cls)) {
132 clear = 1;
133 break;
134 }
135 }
136
137 if (clear)
138 type->tp_flags &= ~(Py_TPFLAGS_HAVE_VERSION_TAG|
139 Py_TPFLAGS_VALID_VERSION_TAG);
140}
141
142static int
143assign_version_tag(PyTypeObject *type)
144{
145 /* 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;
152
153 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;
159
160 type->tp_version_tag = next_version_tag++;
161 /* for stress-testing: next_version_tag &= 0xFF; */
162
163 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 */
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000175 PyType_Modified(&PyBaseObject_Type);
Christian Heimesa62da1d2008-01-12 19:39:10 +0000176 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;
188}
189
190
Guido van Rossum6f799372001-09-20 20:46:19 +0000191static PyMemberDef type_members[] = {
Tim Peters6d6c1a32001-08-02 04:15:00 +0000192 {"__basicsize__", T_INT, offsetof(PyTypeObject,tp_basicsize),READONLY},
193 {"__itemsize__", T_INT, offsetof(PyTypeObject, tp_itemsize), READONLY},
194 {"__flags__", T_LONG, offsetof(PyTypeObject, tp_flags), READONLY},
Guido van Rossum9676b222001-08-17 20:32:36 +0000195 {"__weakrefoffset__", T_LONG,
Tim Peters6d6c1a32001-08-02 04:15:00 +0000196 offsetof(PyTypeObject, tp_weaklistoffset), READONLY},
197 {"__base__", T_OBJECT, offsetof(PyTypeObject, tp_base), READONLY},
198 {"__dictoffset__", T_LONG,
199 offsetof(PyTypeObject, tp_dictoffset), READONLY},
Tim Peters6d6c1a32001-08-02 04:15:00 +0000200 {"__mro__", T_OBJECT, offsetof(PyTypeObject, tp_mro), READONLY},
201 {0}
202};
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{
Jeremy Hyltonaf68c872005-12-10 18:50:16 +0000207 const char *s;
Guido van Rossumc3542212001-08-16 09:18:56 +0000208
Michael W. Hudsonade8c8b22002-11-27 16:29:26 +0000209 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
Guido van Rossume5c691a2003-03-07 15:13:17 +0000210 PyHeapTypeObject* et = (PyHeapTypeObject*)type;
Tim Petersea7f75d2002-12-07 21:39:16 +0000211
Georg Brandlc255c7b2006-02-20 22:27:28 +0000212 Py_INCREF(et->ht_name);
213 return et->ht_name;
Michael W. Hudsonade8c8b22002-11-27 16:29:26 +0000214 }
215 else {
216 s = strrchr(type->tp_name, '.');
217 if (s == NULL)
218 s = type->tp_name;
219 else
220 s++;
Martin v. Löwis5b222132007-06-10 09:51:05 +0000221 return PyUnicode_FromString(s);
Michael W. Hudsonade8c8b22002-11-27 16:29:26 +0000222 }
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{
Guido van Rossume5c691a2003-03-07 15:13:17 +0000228 PyHeapTypeObject* et;
Neal Norwitz80e7f272007-08-26 06:45:23 +0000229 char *tp_name;
Guido van Rossume845c0f2007-11-02 23:07:07 +0000230 PyObject *tmp;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000231
232 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 }
Neal Norwitz6ea45d32007-08-26 04:19:43 +0000242 if (!PyUnicode_Check(value)) {
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000243 PyErr_Format(PyExc_TypeError,
244 "can only assign string to %s.__name__, not '%s'",
Christian Heimes90aa7642007-12-19 02:45:37 +0000245 type->tp_name, Py_TYPE(value)->tp_name);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000246 return -1;
247 }
Guido van Rossume845c0f2007-11-02 23:07:07 +0000248
249 /* Check absence of null characters */
250 tmp = PyUnicode_FromStringAndSize("\0", 1);
251 if (tmp == NULL)
Neal Norwitz6ea45d32007-08-26 04:19:43 +0000252 return -1;
Guido van Rossume845c0f2007-11-02 23:07:07 +0000253 if (PyUnicode_Contains(value, tmp) != 0) {
254 Py_DECREF(tmp);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000255 PyErr_Format(PyExc_ValueError,
256 "__name__ must not contain null bytes");
257 return -1;
258 }
Guido van Rossume845c0f2007-11-02 23:07:07 +0000259 Py_DECREF(tmp);
260
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +0000261 tp_name = _PyUnicode_AsString(value);
Guido van Rossume845c0f2007-11-02 23:07:07 +0000262 if (tp_name == NULL)
263 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000264
Guido van Rossume5c691a2003-03-07 15:13:17 +0000265 et = (PyHeapTypeObject*)type;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000266
267 Py_INCREF(value);
268
Georg Brandlc255c7b2006-02-20 22:27:28 +0000269 Py_DECREF(et->ht_name);
270 et->ht_name = value;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000271
Neal Norwitz80e7f272007-08-26 06:45:23 +0000272 type->tp_name = tp_name;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000273
274 return 0;
275}
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{
Guido van Rossumc3542212001-08-16 09:18:56 +0000280 PyObject *mod;
281 char *s;
282
Michael W. Hudsonade8c8b22002-11-27 16:29:26 +0000283 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
284 mod = PyDict_GetItemString(type->tp_dict, "__module__");
Anthony Baxter3ecdb252004-06-11 14:41:18 +0000285 if (!mod) {
286 PyErr_Format(PyExc_AttributeError, "__module__");
287 return 0;
288 }
Michael W. Hudsonade8c8b22002-11-27 16:29:26 +0000289 Py_XINCREF(mod);
Guido van Rossumc3542212001-08-16 09:18:56 +0000290 return mod;
291 }
Michael W. Hudsonade8c8b22002-11-27 16:29:26 +0000292 else {
293 s = strrchr(type->tp_name, '.');
294 if (s != NULL)
Martin v. Löwis5b222132007-06-10 09:51:05 +0000295 return PyUnicode_FromStringAndSize(
Thomas Wouters89f507f2006-12-13 04:49:30 +0000296 type->tp_name, (Py_ssize_t)(s - type->tp_name));
Georg Brandl1a3284e2007-12-02 09:40:06 +0000297 return PyUnicode_FromString("builtins");
Michael W. Hudsonade8c8b22002-11-27 16:29:26 +0000298 }
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{
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000304 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
Guido van Rossum3926a632001-09-25 16:25:58 +0000305 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
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000315 PyType_Modified(type);
Christian Heimesa62da1d2008-01-12 19:39:10 +0000316
Guido van Rossum3926a632001-09-25 16:25:58 +0000317 return PyDict_SetItemString(type->tp_dict, "__module__", value);
318}
319
Tim Peters6d6c1a32001-08-02 04:15:00 +0000320static PyObject *
Christian Heimes9e7f1d22008-02-28 12:27:11 +0000321type_abstractmethods(PyTypeObject *type, void *context)
322{
323 PyObject *mod = PyDict_GetItemString(type->tp_dict,
324 "__abstractmethods__");
325 if (!mod) {
326 PyErr_Format(PyExc_AttributeError, "__abstractmethods__");
327 return NULL;
328 }
329 Py_XINCREF(mod);
330 return mod;
331}
332
333static int
334type_set_abstractmethods(PyTypeObject *type, PyObject *value, void *context)
335{
336 /* __abstractmethods__ should only be set once on a type, in
337 abc.ABCMeta.__new__, so this function doesn't do anything
338 special to update subclasses.
339 */
340 int res = PyDict_SetItemString(type->tp_dict,
341 "__abstractmethods__", value);
342 if (res == 0) {
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000343 PyType_Modified(type);
Christian Heimes9e7f1d22008-02-28 12:27:11 +0000344 if (value && PyObject_IsTrue(value)) {
345 type->tp_flags |= Py_TPFLAGS_IS_ABSTRACT;
346 }
347 else {
348 type->tp_flags &= ~Py_TPFLAGS_IS_ABSTRACT;
349 }
350 }
351 return res;
352}
353
354static PyObject *
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000355type_get_bases(PyTypeObject *type, void *context)
356{
357 Py_INCREF(type->tp_bases);
358 return type->tp_bases;
359}
360
361static PyTypeObject *best_base(PyObject *);
362static int mro_internal(PyTypeObject *);
363static int compatible_for_assignment(PyTypeObject *, PyTypeObject *, char *);
364static int add_subclass(PyTypeObject*, PyTypeObject*);
365static void remove_subclass(PyTypeObject *, PyTypeObject *);
366static void update_all_slots(PyTypeObject *);
367
Guido van Rossum8d24ee92003-03-24 23:49:49 +0000368typedef int (*update_callback)(PyTypeObject *, void *);
369static int update_subclasses(PyTypeObject *type, PyObject *name,
370 update_callback callback, void *data);
371static int recurse_down_subclasses(PyTypeObject *type, PyObject *name,
372 update_callback callback, void *data);
373
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000374static int
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000375mro_subclasses(PyTypeObject *type, PyObject* temp)
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000376{
377 PyTypeObject *subclass;
378 PyObject *ref, *subclasses, *old_mro;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000379 Py_ssize_t i, n;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000380
381 subclasses = type->tp_subclasses;
382 if (subclasses == NULL)
383 return 0;
384 assert(PyList_Check(subclasses));
385 n = PyList_GET_SIZE(subclasses);
386 for (i = 0; i < n; i++) {
387 ref = PyList_GET_ITEM(subclasses, i);
388 assert(PyWeakref_CheckRef(ref));
389 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
390 assert(subclass != NULL);
391 if ((PyObject *)subclass == Py_None)
392 continue;
393 assert(PyType_Check(subclass));
394 old_mro = subclass->tp_mro;
395 if (mro_internal(subclass) < 0) {
396 subclass->tp_mro = old_mro;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000397 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000398 }
399 else {
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000400 PyObject* tuple;
Raymond Hettinger8ae46892003-10-12 19:09:37 +0000401 tuple = PyTuple_Pack(2, subclass, old_mro);
Guido van Rossum19a02ba2003-04-15 22:09:45 +0000402 Py_DECREF(old_mro);
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000403 if (!tuple)
404 return -1;
405 if (PyList_Append(temp, tuple) < 0)
406 return -1;
Guido van Rossum19a02ba2003-04-15 22:09:45 +0000407 Py_DECREF(tuple);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000408 }
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000409 if (mro_subclasses(subclass, temp) < 0)
410 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000411 }
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000412 return 0;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000413}
414
415static int
416type_set_bases(PyTypeObject *type, PyObject *value, void *context)
417{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000418 Py_ssize_t i;
419 int r = 0;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000420 PyObject *ob, *temp;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000421 PyTypeObject *new_base, *old_base;
422 PyObject *old_bases, *old_mro;
423
424 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
425 PyErr_Format(PyExc_TypeError,
426 "can't set %s.__bases__", type->tp_name);
427 return -1;
428 }
429 if (!value) {
430 PyErr_Format(PyExc_TypeError,
431 "can't delete %s.__bases__", type->tp_name);
432 return -1;
433 }
434 if (!PyTuple_Check(value)) {
435 PyErr_Format(PyExc_TypeError,
436 "can only assign tuple to %s.__bases__, not %s",
Christian Heimes90aa7642007-12-19 02:45:37 +0000437 type->tp_name, Py_TYPE(value)->tp_name);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000438 return -1;
439 }
Guido van Rossum3bbc0ee2002-12-13 17:49:38 +0000440 if (PyTuple_GET_SIZE(value) == 0) {
441 PyErr_Format(PyExc_TypeError,
442 "can only assign non-empty tuple to %s.__bases__, not ()",
443 type->tp_name);
444 return -1;
445 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000446 for (i = 0; i < PyTuple_GET_SIZE(value); i++) {
447 ob = PyTuple_GET_ITEM(value, i);
Guido van Rossum50e9fb92006-08-17 05:42:55 +0000448 if (!PyType_Check(ob)) {
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000449 PyErr_Format(
450 PyExc_TypeError,
451 "%s.__bases__ must be tuple of old- or new-style classes, not '%s'",
Christian Heimes90aa7642007-12-19 02:45:37 +0000452 type->tp_name, Py_TYPE(ob)->tp_name);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000453 return -1;
454 }
Michael W. Hudsoncaf17be2002-11-27 10:24:44 +0000455 if (PyType_Check(ob)) {
456 if (PyType_IsSubtype((PyTypeObject*)ob, type)) {
457 PyErr_SetString(PyExc_TypeError,
458 "a __bases__ item causes an inheritance cycle");
459 return -1;
460 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000461 }
462 }
463
464 new_base = best_base(value);
465
466 if (!new_base) {
467 return -1;
468 }
469
470 if (!compatible_for_assignment(type->tp_base, new_base, "__bases__"))
471 return -1;
472
473 Py_INCREF(new_base);
474 Py_INCREF(value);
475
476 old_bases = type->tp_bases;
477 old_base = type->tp_base;
478 old_mro = type->tp_mro;
479
480 type->tp_bases = value;
481 type->tp_base = new_base;
482
483 if (mro_internal(type) < 0) {
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000484 goto bail;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000485 }
486
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000487 temp = PyList_New(0);
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000488 if (!temp)
489 goto bail;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000490
491 r = mro_subclasses(type, temp);
492
493 if (r < 0) {
494 for (i = 0; i < PyList_Size(temp); i++) {
495 PyTypeObject* cls;
496 PyObject* mro;
Raymond Hettinger8ae46892003-10-12 19:09:37 +0000497 PyArg_UnpackTuple(PyList_GET_ITEM(temp, i),
498 "", 2, 2, &cls, &mro);
Guido van Rossumd8faa362007-04-27 19:54:29 +0000499 Py_INCREF(mro);
500 ob = cls->tp_mro;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000501 cls->tp_mro = mro;
Guido van Rossumd8faa362007-04-27 19:54:29 +0000502 Py_DECREF(ob);
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000503 }
504 Py_DECREF(temp);
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000505 goto bail;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000506 }
507
508 Py_DECREF(temp);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000509
510 /* any base that was in __bases__ but now isn't, we
Raymond Hettingera8285862002-12-14 17:17:56 +0000511 need to remove |type| from its tp_subclasses.
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000512 conversely, any class now in __bases__ that wasn't
Raymond Hettingera8285862002-12-14 17:17:56 +0000513 needs to have |type| added to its subclasses. */
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000514
515 /* for now, sod that: just remove from all old_bases,
516 add to all new_bases */
517
518 for (i = PyTuple_GET_SIZE(old_bases) - 1; i >= 0; i--) {
519 ob = PyTuple_GET_ITEM(old_bases, i);
520 if (PyType_Check(ob)) {
521 remove_subclass(
522 (PyTypeObject*)ob, type);
523 }
524 }
525
526 for (i = PyTuple_GET_SIZE(value) - 1; i >= 0; i--) {
527 ob = PyTuple_GET_ITEM(value, i);
528 if (PyType_Check(ob)) {
529 if (add_subclass((PyTypeObject*)ob, type) < 0)
530 r = -1;
531 }
532 }
533
534 update_all_slots(type);
535
536 Py_DECREF(old_bases);
537 Py_DECREF(old_base);
538 Py_DECREF(old_mro);
539
540 return r;
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000541
542 bail:
Michael W. Hudsone723e452003-08-07 14:58:10 +0000543 Py_DECREF(type->tp_bases);
544 Py_DECREF(type->tp_base);
545 if (type->tp_mro != old_mro) {
546 Py_DECREF(type->tp_mro);
547 }
548
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000549 type->tp_bases = old_bases;
550 type->tp_base = old_base;
551 type->tp_mro = old_mro;
Tim Petersea7f75d2002-12-07 21:39:16 +0000552
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000553 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000554}
555
556static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000557type_dict(PyTypeObject *type, void *context)
558{
559 if (type->tp_dict == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000560 Py_INCREF(Py_None);
561 return Py_None;
Guido van Rossum29ca26e1995-01-07 11:58:15 +0000562 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000563 return PyDictProxy_New(type->tp_dict);
Guido van Rossum29ca26e1995-01-07 11:58:15 +0000564}
565
Tim Peters24008312002-03-17 18:56:20 +0000566static PyObject *
567type_get_doc(PyTypeObject *type, void *context)
568{
569 PyObject *result;
Guido van Rossum6ca7d412002-04-18 00:22:00 +0000570 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE) && type->tp_doc != NULL)
Neal Norwitza369c5a2007-08-25 07:41:59 +0000571 return PyUnicode_FromString(type->tp_doc);
Tim Peters24008312002-03-17 18:56:20 +0000572 result = PyDict_GetItemString(type->tp_dict, "__doc__");
Guido van Rossum6ca7d412002-04-18 00:22:00 +0000573 if (result == NULL) {
574 result = Py_None;
575 Py_INCREF(result);
576 }
Christian Heimes90aa7642007-12-19 02:45:37 +0000577 else if (Py_TYPE(result)->tp_descr_get) {
578 result = Py_TYPE(result)->tp_descr_get(result, NULL,
Tim Peters2b858972002-04-18 04:12:28 +0000579 (PyObject *)type);
Guido van Rossum6ca7d412002-04-18 00:22:00 +0000580 }
581 else {
582 Py_INCREF(result);
583 }
Tim Peters24008312002-03-17 18:56:20 +0000584 return result;
585}
586
Antoine Pitrouec569b72008-08-26 22:40:48 +0000587static PyObject *
588type___instancecheck__(PyObject *type, PyObject *inst)
589{
590 switch (_PyObject_RealIsInstance(inst, type)) {
591 case -1:
592 return NULL;
593 case 0:
594 Py_RETURN_FALSE;
595 default:
596 Py_RETURN_TRUE;
597 }
598}
599
600
601static PyObject *
602type_get_instancecheck(PyObject *type, void *context)
603{
604 static PyMethodDef ml = {"__instancecheck__",
605 type___instancecheck__, METH_O };
606 return PyCFunction_New(&ml, type);
607}
608
609static PyObject *
610type___subclasscheck__(PyObject *type, PyObject *inst)
611{
612 switch (_PyObject_RealIsSubclass(inst, type)) {
613 case -1:
614 return NULL;
615 case 0:
616 Py_RETURN_FALSE;
617 default:
618 Py_RETURN_TRUE;
619 }
620}
621
622static PyObject *
623type_get_subclasscheck(PyObject *type, void *context)
624{
625 static PyMethodDef ml = {"__subclasscheck__",
626 type___subclasscheck__, METH_O };
627 return PyCFunction_New(&ml, type);
628}
629
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000630static PyGetSetDef type_getsets[] = {
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000631 {"__name__", (getter)type_name, (setter)type_set_name, NULL},
632 {"__bases__", (getter)type_get_bases, (setter)type_set_bases, NULL},
Guido van Rossum3926a632001-09-25 16:25:58 +0000633 {"__module__", (getter)type_module, (setter)type_set_module, NULL},
Christian Heimes9e7f1d22008-02-28 12:27:11 +0000634 {"__abstractmethods__", (getter)type_abstractmethods,
635 (setter)type_set_abstractmethods, NULL},
Tim Peters6d6c1a32001-08-02 04:15:00 +0000636 {"__dict__", (getter)type_dict, NULL, NULL},
Tim Peters24008312002-03-17 18:56:20 +0000637 {"__doc__", (getter)type_get_doc, NULL, NULL},
Antoine Pitrouec569b72008-08-26 22:40:48 +0000638 {"__instancecheck__", (getter)type_get_instancecheck, NULL, NULL},
639 {"__subclasscheck__", (getter)type_get_subclasscheck, NULL, NULL},
Tim Peters6d6c1a32001-08-02 04:15:00 +0000640 {0}
641};
642
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000643static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000644type_repr(PyTypeObject *type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000645{
Barry Warsaw7ce36942001-08-24 18:34:26 +0000646 PyObject *mod, *name, *rtn;
Guido van Rossumc3542212001-08-16 09:18:56 +0000647
648 mod = type_module(type, NULL);
649 if (mod == NULL)
650 PyErr_Clear();
Martin v. Löwis5b222132007-06-10 09:51:05 +0000651 else if (!PyUnicode_Check(mod)) {
Guido van Rossumc3542212001-08-16 09:18:56 +0000652 Py_DECREF(mod);
653 mod = NULL;
654 }
655 name = type_name(type, NULL);
656 if (name == NULL)
657 return NULL;
Barry Warsaw7ce36942001-08-24 18:34:26 +0000658
Georg Brandl1a3284e2007-12-02 09:40:06 +0000659 if (mod != NULL && PyUnicode_CompareWithASCIIString(mod, "builtins"))
Martin v. Löwis250ad612008-04-07 05:43:42 +0000660 rtn = PyUnicode_FromFormat("<class '%U.%U'>", mod, name);
Guido van Rossumc3542212001-08-16 09:18:56 +0000661 else
Martin v. Löwis250ad612008-04-07 05:43:42 +0000662 rtn = PyUnicode_FromFormat("<class '%s'>", type->tp_name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000663
Guido van Rossumc3542212001-08-16 09:18:56 +0000664 Py_XDECREF(mod);
665 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000666 return rtn;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000667}
668
Tim Peters6d6c1a32001-08-02 04:15:00 +0000669static PyObject *
670type_call(PyTypeObject *type, PyObject *args, PyObject *kwds)
671{
672 PyObject *obj;
673
674 if (type->tp_new == NULL) {
675 PyErr_Format(PyExc_TypeError,
676 "cannot create '%.100s' instances",
677 type->tp_name);
678 return NULL;
679 }
680
Tim Peters3f996e72001-09-13 19:18:27 +0000681 obj = type->tp_new(type, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000682 if (obj != NULL) {
Guido van Rossumf76de622001-10-18 15:49:21 +0000683 /* Ugly exception: when the call was type(something),
684 don't call tp_init on the result. */
685 if (type == &PyType_Type &&
686 PyTuple_Check(args) && PyTuple_GET_SIZE(args) == 1 &&
687 (kwds == NULL ||
688 (PyDict_Check(kwds) && PyDict_Size(kwds) == 0)))
689 return obj;
Guido van Rossum8ace1ab2002-04-06 01:05:01 +0000690 /* If the returned object is not an instance of type,
691 it won't be initialized. */
Christian Heimes90aa7642007-12-19 02:45:37 +0000692 if (!PyType_IsSubtype(Py_TYPE(obj), type))
Guido van Rossum8ace1ab2002-04-06 01:05:01 +0000693 return obj;
Christian Heimes90aa7642007-12-19 02:45:37 +0000694 type = Py_TYPE(obj);
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +0000695 if (type->tp_init != NULL &&
Tim Peters6d6c1a32001-08-02 04:15:00 +0000696 type->tp_init(obj, args, kwds) < 0) {
697 Py_DECREF(obj);
698 obj = NULL;
699 }
700 }
701 return obj;
702}
703
704PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000705PyType_GenericAlloc(PyTypeObject *type, Py_ssize_t nitems)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000706{
Tim Peters6d6c1a32001-08-02 04:15:00 +0000707 PyObject *obj;
Guido van Rossume5c691a2003-03-07 15:13:17 +0000708 const size_t size = _PyObject_VAR_SIZE(type, nitems+1);
709 /* note that we need to add one, for the sentinel */
Tim Peters406fe3b2001-10-06 19:04:01 +0000710
711 if (PyType_IS_GC(type))
Neil Schemenauer09a2ae52002-04-12 03:06:53 +0000712 obj = _PyObject_GC_Malloc(size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000713 else
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000714 obj = (PyObject *)PyObject_MALLOC(size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000715
Neil Schemenauerc806c882001-08-29 23:54:54 +0000716 if (obj == NULL)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000717 return PyErr_NoMemory();
Tim Peters406fe3b2001-10-06 19:04:01 +0000718
Neil Schemenauerc806c882001-08-29 23:54:54 +0000719 memset(obj, '\0', size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000720
Tim Peters6d6c1a32001-08-02 04:15:00 +0000721 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
722 Py_INCREF(type);
Tim Peters406fe3b2001-10-06 19:04:01 +0000723
Tim Peters6d6c1a32001-08-02 04:15:00 +0000724 if (type->tp_itemsize == 0)
725 PyObject_INIT(obj, type);
726 else
727 (void) PyObject_INIT_VAR((PyVarObject *)obj, type, nitems);
Tim Peters406fe3b2001-10-06 19:04:01 +0000728
Tim Peters6d6c1a32001-08-02 04:15:00 +0000729 if (PyType_IS_GC(type))
Neil Schemenauerc806c882001-08-29 23:54:54 +0000730 _PyObject_GC_TRACK(obj);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000731 return obj;
732}
733
734PyObject *
735PyType_GenericNew(PyTypeObject *type, PyObject *args, PyObject *kwds)
736{
737 return type->tp_alloc(type, 0);
738}
739
Guido van Rossum9475a232001-10-05 20:51:39 +0000740/* Helpers for subtyping */
741
742static int
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000743traverse_slots(PyTypeObject *type, PyObject *self, visitproc visit, void *arg)
744{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000745 Py_ssize_t i, n;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000746 PyMemberDef *mp;
747
Christian Heimes90aa7642007-12-19 02:45:37 +0000748 n = Py_SIZE(type);
Guido van Rossume5c691a2003-03-07 15:13:17 +0000749 mp = PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000750 for (i = 0; i < n; i++, mp++) {
751 if (mp->type == T_OBJECT_EX) {
752 char *addr = (char *)self + mp->offset;
753 PyObject *obj = *(PyObject **)addr;
754 if (obj != NULL) {
755 int err = visit(obj, arg);
756 if (err)
757 return err;
758 }
759 }
760 }
761 return 0;
762}
763
764static int
Guido van Rossum9475a232001-10-05 20:51:39 +0000765subtype_traverse(PyObject *self, visitproc visit, void *arg)
766{
767 PyTypeObject *type, *base;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000768 traverseproc basetraverse;
Guido van Rossum9475a232001-10-05 20:51:39 +0000769
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000770 /* Find the nearest base with a different tp_traverse,
771 and traverse slots while we're at it */
Christian Heimes90aa7642007-12-19 02:45:37 +0000772 type = Py_TYPE(self);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000773 base = type;
774 while ((basetraverse = base->tp_traverse) == subtype_traverse) {
Christian Heimes90aa7642007-12-19 02:45:37 +0000775 if (Py_SIZE(base)) {
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000776 int err = traverse_slots(base, self, visit, arg);
777 if (err)
778 return err;
779 }
Guido van Rossum9475a232001-10-05 20:51:39 +0000780 base = base->tp_base;
781 assert(base);
782 }
783
784 if (type->tp_dictoffset != base->tp_dictoffset) {
785 PyObject **dictptr = _PyObject_GetDictPtr(self);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000786 if (dictptr && *dictptr)
787 Py_VISIT(*dictptr);
Guido van Rossum9475a232001-10-05 20:51:39 +0000788 }
789
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000790 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
Guido van Rossuma3862092002-06-10 15:24:42 +0000791 /* For a heaptype, the instances count as references
Guido van Rossumd8faa362007-04-27 19:54:29 +0000792 to the type. Traverse the type so the collector
Guido van Rossuma3862092002-06-10 15:24:42 +0000793 can find cycles involving this link. */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000794 Py_VISIT(type);
Guido van Rossuma3862092002-06-10 15:24:42 +0000795
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000796 if (basetraverse)
797 return basetraverse(self, visit, arg);
798 return 0;
799}
800
801static void
802clear_slots(PyTypeObject *type, PyObject *self)
803{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000804 Py_ssize_t i, n;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000805 PyMemberDef *mp;
806
Christian Heimes90aa7642007-12-19 02:45:37 +0000807 n = Py_SIZE(type);
Guido van Rossume5c691a2003-03-07 15:13:17 +0000808 mp = PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000809 for (i = 0; i < n; i++, mp++) {
810 if (mp->type == T_OBJECT_EX && !(mp->flags & READONLY)) {
811 char *addr = (char *)self + mp->offset;
812 PyObject *obj = *(PyObject **)addr;
813 if (obj != NULL) {
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000814 *(PyObject **)addr = NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000815 Py_DECREF(obj);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000816 }
817 }
818 }
819}
820
821static int
822subtype_clear(PyObject *self)
823{
824 PyTypeObject *type, *base;
825 inquiry baseclear;
826
827 /* Find the nearest base with a different tp_clear
828 and clear slots while we're at it */
Christian Heimes90aa7642007-12-19 02:45:37 +0000829 type = Py_TYPE(self);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000830 base = type;
831 while ((baseclear = base->tp_clear) == subtype_clear) {
Christian Heimes90aa7642007-12-19 02:45:37 +0000832 if (Py_SIZE(base))
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000833 clear_slots(base, self);
834 base = base->tp_base;
835 assert(base);
836 }
837
Guido van Rossuma3862092002-06-10 15:24:42 +0000838 /* There's no need to clear the instance dict (if any);
839 the collector will call its tp_clear handler. */
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000840
841 if (baseclear)
842 return baseclear(self);
Guido van Rossum9475a232001-10-05 20:51:39 +0000843 return 0;
844}
Tim Peters6d6c1a32001-08-02 04:15:00 +0000845
846static void
847subtype_dealloc(PyObject *self)
848{
Guido van Rossum14227b42001-12-06 02:35:58 +0000849 PyTypeObject *type, *base;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000850 destructor basedealloc;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000851
Guido van Rossum22b13872002-08-06 21:41:44 +0000852 /* Extract the type; we expect it to be a heap type */
Christian Heimes90aa7642007-12-19 02:45:37 +0000853 type = Py_TYPE(self);
Guido van Rossum22b13872002-08-06 21:41:44 +0000854 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000855
Guido van Rossum22b13872002-08-06 21:41:44 +0000856 /* Test whether the type has GC exactly once */
857
858 if (!PyType_IS_GC(type)) {
859 /* It's really rare to find a dynamic type that doesn't have
860 GC; it can only happen when deriving from 'object' and not
861 adding any slots or instance variables. This allows
862 certain simplifications: there's no need to call
863 clear_slots(), or DECREF the dict, or clear weakrefs. */
864
865 /* Maybe call finalizer; exit early if resurrected */
Guido van Rossumfebd61d2002-08-08 20:55:20 +0000866 if (type->tp_del) {
867 type->tp_del(self);
868 if (self->ob_refcnt > 0)
869 return;
870 }
Guido van Rossum22b13872002-08-06 21:41:44 +0000871
872 /* Find the nearest base with a different tp_dealloc */
873 base = type;
874 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
Christian Heimes90aa7642007-12-19 02:45:37 +0000875 assert(Py_SIZE(base) == 0);
Guido van Rossum22b13872002-08-06 21:41:44 +0000876 base = base->tp_base;
877 assert(base);
878 }
879
880 /* Call the base tp_dealloc() */
881 assert(basedealloc);
882 basedealloc(self);
883
884 /* Can't reference self beyond this point */
885 Py_DECREF(type);
886
887 /* Done */
888 return;
889 }
890
891 /* We get here only if the type has GC */
892
893 /* UnTrack and re-Track around the trashcan macro, alas */
Andrew M. Kuchlingc9172d32003-02-06 15:22:49 +0000894 /* See explanation at end of function for full disclosure */
Guido van Rossum0906e072002-08-07 20:42:09 +0000895 PyObject_GC_UnTrack(self);
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000896 ++_PyTrash_delete_nesting;
Guido van Rossum22b13872002-08-06 21:41:44 +0000897 Py_TRASHCAN_SAFE_BEGIN(self);
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000898 --_PyTrash_delete_nesting;
Tim Petersf7f9e992003-11-13 21:59:32 +0000899 /* DO NOT restore GC tracking at this point. weakref callbacks
900 * (if any, and whether directly here or indirectly in something we
901 * call) may trigger GC, and if self is tracked at that point, it
902 * will look like trash to GC and GC will try to delete self again.
Tim Petersadd09b42003-11-12 20:43:28 +0000903 */
Guido van Rossum22b13872002-08-06 21:41:44 +0000904
Guido van Rossum59195fd2003-06-13 20:54:40 +0000905 /* Find the nearest base with a different tp_dealloc */
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000906 base = type;
907 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
Tim Peters6d6c1a32001-08-02 04:15:00 +0000908 base = base->tp_base;
909 assert(base);
Guido van Rossum14227b42001-12-06 02:35:58 +0000910 }
911
Guido van Rossumd8faa362007-04-27 19:54:29 +0000912 /* If we added a weaklist, we clear it. Do this *before* calling
Guido van Rossum59195fd2003-06-13 20:54:40 +0000913 the finalizer (__del__), clearing slots, or clearing the instance
914 dict. */
915
Guido van Rossum1987c662003-05-29 14:29:23 +0000916 if (type->tp_weaklistoffset && !base->tp_weaklistoffset)
917 PyObject_ClearWeakRefs(self);
918
919 /* Maybe call finalizer; exit early if resurrected */
920 if (type->tp_del) {
Tim Petersf7f9e992003-11-13 21:59:32 +0000921 _PyObject_GC_TRACK(self);
Guido van Rossum1987c662003-05-29 14:29:23 +0000922 type->tp_del(self);
923 if (self->ob_refcnt > 0)
Tim Petersf7f9e992003-11-13 21:59:32 +0000924 goto endlabel; /* resurrected */
925 else
926 _PyObject_GC_UNTRACK(self);
Thomas Woutersb2137042007-02-01 18:02:27 +0000927 /* New weakrefs could be created during the finalizer call.
928 If this occurs, clear them out without calling their
929 finalizers since they might rely on part of the object
930 being finalized that has already been destroyed. */
931 if (type->tp_weaklistoffset && !base->tp_weaklistoffset) {
932 /* Modeled after GET_WEAKREFS_LISTPTR() */
933 PyWeakReference **list = (PyWeakReference **) \
934 PyObject_GET_WEAKREFS_LISTPTR(self);
935 while (*list)
936 _PyWeakref_ClearRef(*list);
937 }
Guido van Rossum1987c662003-05-29 14:29:23 +0000938 }
939
Guido van Rossum59195fd2003-06-13 20:54:40 +0000940 /* Clear slots up to the nearest base with a different tp_dealloc */
941 base = type;
942 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
Christian Heimes90aa7642007-12-19 02:45:37 +0000943 if (Py_SIZE(base))
Guido van Rossum59195fd2003-06-13 20:54:40 +0000944 clear_slots(base, self);
945 base = base->tp_base;
946 assert(base);
947 }
948
Tim Peters6d6c1a32001-08-02 04:15:00 +0000949 /* If we added a dict, DECREF it */
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000950 if (type->tp_dictoffset && !base->tp_dictoffset) {
951 PyObject **dictptr = _PyObject_GetDictPtr(self);
952 if (dictptr != NULL) {
953 PyObject *dict = *dictptr;
954 if (dict != NULL) {
955 Py_DECREF(dict);
956 *dictptr = NULL;
957 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000958 }
959 }
960
Tim Peters0bd743c2003-11-13 22:50:00 +0000961 /* Call the base tp_dealloc(); first retrack self if
962 * basedealloc knows about gc.
963 */
964 if (PyType_IS_GC(base))
965 _PyObject_GC_TRACK(self);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000966 assert(basedealloc);
967 basedealloc(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000968
969 /* Can't reference self beyond this point */
Guido van Rossum22b13872002-08-06 21:41:44 +0000970 Py_DECREF(type);
971
Guido van Rossum0906e072002-08-07 20:42:09 +0000972 endlabel:
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000973 ++_PyTrash_delete_nesting;
Guido van Rossum22b13872002-08-06 21:41:44 +0000974 Py_TRASHCAN_SAFE_END(self);
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000975 --_PyTrash_delete_nesting;
976
977 /* Explanation of the weirdness around the trashcan macros:
978
979 Q. What do the trashcan macros do?
980
981 A. Read the comment titled "Trashcan mechanism" in object.h.
982 For one, this explains why there must be a call to GC-untrack
Guido van Rossumd8faa362007-04-27 19:54:29 +0000983 before the trashcan begin macro. Without understanding the
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000984 trashcan code, the answers to the following questions don't make
985 sense.
986
987 Q. Why do we GC-untrack before the trashcan and then immediately
988 GC-track again afterward?
989
990 A. In the case that the base class is GC-aware, the base class
Guido van Rossumd8faa362007-04-27 19:54:29 +0000991 probably GC-untracks the object. If it does that using the
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000992 UNTRACK macro, this will crash when the object is already
993 untracked. Because we don't know what the base class does, the
994 only safe thing is to make sure the object is tracked when we
995 call the base class dealloc. But... The trashcan begin macro
996 requires that the object is *untracked* before it is called. So
997 the dance becomes:
998
Guido van Rossumd8faa362007-04-27 19:54:29 +0000999 GC untrack
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001000 trashcan begin
1001 GC track
1002
Guido van Rossumd8faa362007-04-27 19:54:29 +00001003 Q. Why did the last question say "immediately GC-track again"?
1004 It's nowhere near immediately.
Tim Petersf7f9e992003-11-13 21:59:32 +00001005
Guido van Rossumd8faa362007-04-27 19:54:29 +00001006 A. Because the code *used* to re-track immediately. Bad Idea.
1007 self has a refcount of 0, and if gc ever gets its hands on it
1008 (which can happen if any weakref callback gets invoked), it
1009 looks like trash to gc too, and gc also tries to delete self
1010 then. But we're already deleting self. Double dealloction is
1011 a subtle disaster.
Tim Petersf7f9e992003-11-13 21:59:32 +00001012
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001013 Q. Why the bizarre (net-zero) manipulation of
1014 _PyTrash_delete_nesting around the trashcan macros?
1015
1016 A. Some base classes (e.g. list) also use the trashcan mechanism.
1017 The following scenario used to be possible:
1018
1019 - suppose the trashcan level is one below the trashcan limit
1020
1021 - subtype_dealloc() is called
1022
1023 - the trashcan limit is not yet reached, so the trashcan level
Guido van Rossumd8faa362007-04-27 19:54:29 +00001024 is incremented and the code between trashcan begin and end is
1025 executed
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001026
1027 - this destroys much of the object's contents, including its
Guido van Rossumd8faa362007-04-27 19:54:29 +00001028 slots and __dict__
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001029
1030 - basedealloc() is called; this is really list_dealloc(), or
Guido van Rossumd8faa362007-04-27 19:54:29 +00001031 some other type which also uses the trashcan macros
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001032
1033 - the trashcan limit is now reached, so the object is put on the
Guido van Rossumd8faa362007-04-27 19:54:29 +00001034 trashcan's to-be-deleted-later list
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001035
1036 - basedealloc() returns
1037
1038 - subtype_dealloc() decrefs the object's type
1039
1040 - subtype_dealloc() returns
1041
1042 - later, the trashcan code starts deleting the objects from its
Guido van Rossumd8faa362007-04-27 19:54:29 +00001043 to-be-deleted-later list
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001044
1045 - subtype_dealloc() is called *AGAIN* for the same object
1046
1047 - at the very least (if the destroyed slots and __dict__ don't
Guido van Rossumd8faa362007-04-27 19:54:29 +00001048 cause problems) the object's type gets decref'ed a second
1049 time, which is *BAD*!!!
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001050
1051 The remedy is to make sure that if the code between trashcan
1052 begin and end in subtype_dealloc() is called, the code between
1053 trashcan begin and end in basedealloc() will also be called.
1054 This is done by decrementing the level after passing into the
1055 trashcan block, and incrementing it just before leaving the
1056 block.
1057
1058 But now it's possible that a chain of objects consisting solely
1059 of objects whose deallocator is subtype_dealloc() will defeat
1060 the trashcan mechanism completely: the decremented level means
Guido van Rossumd8faa362007-04-27 19:54:29 +00001061 that the effective level never reaches the limit. Therefore, we
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001062 *increment* the level *before* entering the trashcan block, and
1063 matchingly decrement it after leaving. This means the trashcan
1064 code will trigger a little early, but that's no big deal.
1065
1066 Q. Are there any live examples of code in need of all this
1067 complexity?
1068
1069 A. Yes. See SF bug 668433 for code that crashed (when Python was
1070 compiled in debug mode) before the trashcan level manipulations
1071 were added. For more discussion, see SF patches 581742, 575073
1072 and bug 574207.
1073 */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001074}
1075
Jeremy Hylton938ace62002-07-17 16:30:39 +00001076static PyTypeObject *solid_base(PyTypeObject *type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001077
Tim Peters6d6c1a32001-08-02 04:15:00 +00001078/* type test with subclassing support */
1079
1080int
1081PyType_IsSubtype(PyTypeObject *a, PyTypeObject *b)
1082{
1083 PyObject *mro;
1084
1085 mro = a->tp_mro;
1086 if (mro != NULL) {
1087 /* Deal with multiple inheritance without recursion
1088 by walking the MRO tuple */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001089 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001090 assert(PyTuple_Check(mro));
1091 n = PyTuple_GET_SIZE(mro);
1092 for (i = 0; i < n; i++) {
1093 if (PyTuple_GET_ITEM(mro, i) == (PyObject *)b)
1094 return 1;
1095 }
1096 return 0;
1097 }
1098 else {
1099 /* a is not completely initilized yet; follow tp_base */
1100 do {
1101 if (a == b)
1102 return 1;
1103 a = a->tp_base;
1104 } while (a != NULL);
1105 return b == &PyBaseObject_Type;
1106 }
1107}
1108
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001109/* Internal routines to do a method lookup in the type
Guido van Rossum60718732001-08-28 17:47:51 +00001110 without looking in the instance dictionary
1111 (so we can't use PyObject_GetAttr) but still binding
Guido van Rossumd8faa362007-04-27 19:54:29 +00001112 it to the instance. The arguments are the object,
Guido van Rossum60718732001-08-28 17:47:51 +00001113 the method name as a C string, and the address of a
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001114 static variable used to cache the interned Python string.
1115
1116 Two variants:
1117
1118 - lookup_maybe() returns NULL without raising an exception
1119 when the _PyType_Lookup() call fails;
1120
1121 - lookup_method() always raises an exception upon errors.
1122*/
Guido van Rossum60718732001-08-28 17:47:51 +00001123
1124static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001125lookup_maybe(PyObject *self, char *attrstr, PyObject **attrobj)
Guido van Rossum60718732001-08-28 17:47:51 +00001126{
1127 PyObject *res;
1128
1129 if (*attrobj == NULL) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00001130 *attrobj = PyUnicode_InternFromString(attrstr);
Guido van Rossum60718732001-08-28 17:47:51 +00001131 if (*attrobj == NULL)
1132 return NULL;
1133 }
Christian Heimes90aa7642007-12-19 02:45:37 +00001134 res = _PyType_Lookup(Py_TYPE(self), *attrobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001135 if (res != NULL) {
Guido van Rossum60718732001-08-28 17:47:51 +00001136 descrgetfunc f;
Christian Heimes90aa7642007-12-19 02:45:37 +00001137 if ((f = Py_TYPE(res)->tp_descr_get) == NULL)
Guido van Rossum60718732001-08-28 17:47:51 +00001138 Py_INCREF(res);
1139 else
Christian Heimes90aa7642007-12-19 02:45:37 +00001140 res = f(res, self, (PyObject *)(Py_TYPE(self)));
Guido van Rossum60718732001-08-28 17:47:51 +00001141 }
1142 return res;
1143}
1144
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001145static PyObject *
1146lookup_method(PyObject *self, char *attrstr, PyObject **attrobj)
1147{
1148 PyObject *res = lookup_maybe(self, attrstr, attrobj);
1149 if (res == NULL && !PyErr_Occurred())
1150 PyErr_SetObject(PyExc_AttributeError, *attrobj);
1151 return res;
1152}
1153
Guido van Rossum2730b132001-08-28 18:22:14 +00001154/* A variation of PyObject_CallMethod that uses lookup_method()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001155 instead of PyObject_GetAttrString(). This uses the same convention
Guido van Rossum2730b132001-08-28 18:22:14 +00001156 as lookup_method to cache the interned name string object. */
1157
Neil Schemenauerf23473f2001-10-21 22:28:58 +00001158static PyObject *
Guido van Rossum2730b132001-08-28 18:22:14 +00001159call_method(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
1160{
1161 va_list va;
1162 PyObject *args, *func = 0, *retval;
Guido van Rossum2730b132001-08-28 18:22:14 +00001163 va_start(va, format);
1164
Guido van Rossumda21c012001-10-03 00:50:18 +00001165 func = lookup_maybe(o, name, nameobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001166 if (func == NULL) {
1167 va_end(va);
1168 if (!PyErr_Occurred())
Guido van Rossumda21c012001-10-03 00:50:18 +00001169 PyErr_SetObject(PyExc_AttributeError, *nameobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001170 return NULL;
1171 }
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001172
1173 if (format && *format)
1174 args = Py_VaBuildValue(format, va);
1175 else
1176 args = PyTuple_New(0);
1177
1178 va_end(va);
1179
1180 if (args == NULL)
1181 return NULL;
1182
1183 assert(PyTuple_Check(args));
1184 retval = PyObject_Call(func, args, NULL);
1185
1186 Py_DECREF(args);
1187 Py_DECREF(func);
1188
1189 return retval;
1190}
1191
1192/* Clone of call_method() that returns NotImplemented when the lookup fails. */
1193
Neil Schemenauerf23473f2001-10-21 22:28:58 +00001194static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001195call_maybe(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
1196{
1197 va_list va;
1198 PyObject *args, *func = 0, *retval;
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001199 va_start(va, format);
1200
Guido van Rossumda21c012001-10-03 00:50:18 +00001201 func = lookup_maybe(o, name, nameobj);
Guido van Rossum2730b132001-08-28 18:22:14 +00001202 if (func == NULL) {
1203 va_end(va);
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001204 if (!PyErr_Occurred()) {
1205 Py_INCREF(Py_NotImplemented);
1206 return Py_NotImplemented;
1207 }
Guido van Rossum717ce002001-09-14 16:58:08 +00001208 return NULL;
Guido van Rossum2730b132001-08-28 18:22:14 +00001209 }
1210
1211 if (format && *format)
1212 args = Py_VaBuildValue(format, va);
1213 else
1214 args = PyTuple_New(0);
1215
1216 va_end(va);
1217
Guido van Rossum717ce002001-09-14 16:58:08 +00001218 if (args == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00001219 return NULL;
1220
Guido van Rossum717ce002001-09-14 16:58:08 +00001221 assert(PyTuple_Check(args));
1222 retval = PyObject_Call(func, args, NULL);
Guido van Rossum2730b132001-08-28 18:22:14 +00001223
1224 Py_DECREF(args);
1225 Py_DECREF(func);
1226
1227 return retval;
1228}
1229
Tim Petersea7f75d2002-12-07 21:39:16 +00001230/*
Guido van Rossum1f121312002-11-14 19:49:16 +00001231 Method resolution order algorithm C3 described in
1232 "A Monotonic Superclass Linearization for Dylan",
1233 by Kim Barrett, Bob Cassel, Paul Haahr,
Tim Petersea7f75d2002-12-07 21:39:16 +00001234 David A. Moon, Keith Playford, and P. Tucker Withington.
Guido van Rossum1f121312002-11-14 19:49:16 +00001235 (OOPSLA 1996)
1236
Guido van Rossum98f33732002-11-25 21:36:54 +00001237 Some notes about the rules implied by C3:
1238
Tim Petersea7f75d2002-12-07 21:39:16 +00001239 No duplicate bases.
Guido van Rossum98f33732002-11-25 21:36:54 +00001240 It isn't legal to repeat a class in a list of base classes.
1241
1242 The next three properties are the 3 constraints in "C3".
1243
Tim Petersea7f75d2002-12-07 21:39:16 +00001244 Local precendece order.
Guido van Rossum98f33732002-11-25 21:36:54 +00001245 If A precedes B in C's MRO, then A will precede B in the MRO of all
1246 subclasses of C.
1247
1248 Monotonicity.
1249 The MRO of a class must be an extension without reordering of the
1250 MRO of each of its superclasses.
1251
1252 Extended Precedence Graph (EPG).
1253 Linearization is consistent if there is a path in the EPG from
1254 each class to all its successors in the linearization. See
1255 the paper for definition of EPG.
Guido van Rossum1f121312002-11-14 19:49:16 +00001256 */
1257
Tim Petersea7f75d2002-12-07 21:39:16 +00001258static int
Guido van Rossum1f121312002-11-14 19:49:16 +00001259tail_contains(PyObject *list, int whence, PyObject *o) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001260 Py_ssize_t j, size;
Guido van Rossum1f121312002-11-14 19:49:16 +00001261 size = PyList_GET_SIZE(list);
1262
1263 for (j = whence+1; j < size; j++) {
1264 if (PyList_GET_ITEM(list, j) == o)
1265 return 1;
1266 }
1267 return 0;
1268}
1269
Guido van Rossum98f33732002-11-25 21:36:54 +00001270static PyObject *
1271class_name(PyObject *cls)
1272{
1273 PyObject *name = PyObject_GetAttrString(cls, "__name__");
1274 if (name == NULL) {
1275 PyErr_Clear();
1276 Py_XDECREF(name);
Guido van Rossum98297ee2007-11-06 21:34:58 +00001277 name = PyObject_Repr(cls);
Guido van Rossum98f33732002-11-25 21:36:54 +00001278 }
1279 if (name == NULL)
1280 return NULL;
Martin v. Löwis9b9905b2007-06-10 21:13:34 +00001281 if (!PyUnicode_Check(name)) {
Guido van Rossum98f33732002-11-25 21:36:54 +00001282 Py_DECREF(name);
1283 return NULL;
1284 }
1285 return name;
1286}
1287
1288static int
1289check_duplicates(PyObject *list)
1290{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001291 Py_ssize_t i, j, n;
Guido van Rossum98f33732002-11-25 21:36:54 +00001292 /* Let's use a quadratic time algorithm,
1293 assuming that the bases lists is short.
1294 */
1295 n = PyList_GET_SIZE(list);
1296 for (i = 0; i < n; i++) {
1297 PyObject *o = PyList_GET_ITEM(list, i);
1298 for (j = i + 1; j < n; j++) {
1299 if (PyList_GET_ITEM(list, j) == o) {
1300 o = class_name(o);
1301 PyErr_Format(PyExc_TypeError,
Alexandre Vassalottia85998a2008-05-03 18:24:43 +00001302 "duplicate base class %.400s",
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +00001303 o ? _PyUnicode_AsString(o) : "?");
Guido van Rossum98f33732002-11-25 21:36:54 +00001304 Py_XDECREF(o);
1305 return -1;
1306 }
1307 }
1308 }
1309 return 0;
1310}
1311
1312/* Raise a TypeError for an MRO order disagreement.
1313
1314 It's hard to produce a good error message. In the absence of better
1315 insight into error reporting, report the classes that were candidates
Guido van Rossumd8faa362007-04-27 19:54:29 +00001316 to be put next into the MRO. There is some conflict between the
Guido van Rossum98f33732002-11-25 21:36:54 +00001317 order in which they should be put in the MRO, but it's hard to
1318 diagnose what constraint can't be satisfied.
1319*/
1320
1321static void
1322set_mro_error(PyObject *to_merge, int *remain)
1323{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001324 Py_ssize_t i, n, off, to_merge_size;
Guido van Rossum98f33732002-11-25 21:36:54 +00001325 char buf[1000];
1326 PyObject *k, *v;
1327 PyObject *set = PyDict_New();
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001328 if (!set) return;
Guido van Rossum98f33732002-11-25 21:36:54 +00001329
1330 to_merge_size = PyList_GET_SIZE(to_merge);
1331 for (i = 0; i < to_merge_size; i++) {
1332 PyObject *L = PyList_GET_ITEM(to_merge, i);
1333 if (remain[i] < PyList_GET_SIZE(L)) {
1334 PyObject *c = PyList_GET_ITEM(L, remain[i]);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001335 if (PyDict_SetItem(set, c, Py_None) < 0) {
1336 Py_DECREF(set);
Guido van Rossum98f33732002-11-25 21:36:54 +00001337 return;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001338 }
Guido van Rossum98f33732002-11-25 21:36:54 +00001339 }
1340 }
1341 n = PyDict_Size(set);
1342
Raymond Hettingerf394df42003-04-06 19:13:41 +00001343 off = PyOS_snprintf(buf, sizeof(buf), "Cannot create a \
1344consistent method resolution\norder (MRO) for bases");
Guido van Rossum98f33732002-11-25 21:36:54 +00001345 i = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001346 while (PyDict_Next(set, &i, &k, &v) && (size_t)off < sizeof(buf)) {
Guido van Rossum98f33732002-11-25 21:36:54 +00001347 PyObject *name = class_name(k);
1348 off += PyOS_snprintf(buf + off, sizeof(buf) - off, " %s",
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +00001349 name ? _PyUnicode_AsString(name) : "?");
Guido van Rossum98f33732002-11-25 21:36:54 +00001350 Py_XDECREF(name);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001351 if (--n && (size_t)(off+1) < sizeof(buf)) {
Guido van Rossum98f33732002-11-25 21:36:54 +00001352 buf[off++] = ',';
1353 buf[off] = '\0';
1354 }
1355 }
1356 PyErr_SetString(PyExc_TypeError, buf);
1357 Py_DECREF(set);
1358}
1359
Tim Petersea7f75d2002-12-07 21:39:16 +00001360static int
Guido van Rossum1f121312002-11-14 19:49:16 +00001361pmerge(PyObject *acc, PyObject* to_merge) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001362 Py_ssize_t i, j, to_merge_size, empty_cnt;
Guido van Rossum1f121312002-11-14 19:49:16 +00001363 int *remain;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001364 int ok;
Tim Petersea7f75d2002-12-07 21:39:16 +00001365
Guido van Rossum1f121312002-11-14 19:49:16 +00001366 to_merge_size = PyList_GET_SIZE(to_merge);
1367
Guido van Rossum98f33732002-11-25 21:36:54 +00001368 /* remain stores an index into each sublist of to_merge.
1369 remain[i] is the index of the next base in to_merge[i]
1370 that is not included in acc.
1371 */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001372 remain = (int *)PyMem_MALLOC(SIZEOF_INT*to_merge_size);
Guido van Rossum1f121312002-11-14 19:49:16 +00001373 if (remain == NULL)
1374 return -1;
1375 for (i = 0; i < to_merge_size; i++)
1376 remain[i] = 0;
1377
1378 again:
1379 empty_cnt = 0;
1380 for (i = 0; i < to_merge_size; i++) {
1381 PyObject *candidate;
Tim Petersea7f75d2002-12-07 21:39:16 +00001382
Guido van Rossum1f121312002-11-14 19:49:16 +00001383 PyObject *cur_list = PyList_GET_ITEM(to_merge, i);
1384
1385 if (remain[i] >= PyList_GET_SIZE(cur_list)) {
1386 empty_cnt++;
1387 continue;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001388 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001389
Guido van Rossum98f33732002-11-25 21:36:54 +00001390 /* Choose next candidate for MRO.
1391
1392 The input sequences alone can determine the choice.
1393 If not, choose the class which appears in the MRO
1394 of the earliest direct superclass of the new class.
1395 */
1396
Guido van Rossum1f121312002-11-14 19:49:16 +00001397 candidate = PyList_GET_ITEM(cur_list, remain[i]);
1398 for (j = 0; j < to_merge_size; j++) {
1399 PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
Guido van Rossum98f33732002-11-25 21:36:54 +00001400 if (tail_contains(j_lst, remain[j], candidate)) {
Guido van Rossum1f121312002-11-14 19:49:16 +00001401 goto skip; /* continue outer loop */
Guido van Rossum98f33732002-11-25 21:36:54 +00001402 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001403 }
1404 ok = PyList_Append(acc, candidate);
1405 if (ok < 0) {
1406 PyMem_Free(remain);
1407 return -1;
1408 }
1409 for (j = 0; j < to_merge_size; j++) {
1410 PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
Guido van Rossum768158c2002-12-31 16:33:01 +00001411 if (remain[j] < PyList_GET_SIZE(j_lst) &&
1412 PyList_GET_ITEM(j_lst, remain[j]) == candidate) {
Guido van Rossum1f121312002-11-14 19:49:16 +00001413 remain[j]++;
1414 }
1415 }
1416 goto again;
Tim Peters9a6b8d82002-11-14 23:22:33 +00001417 skip: ;
Guido van Rossum1f121312002-11-14 19:49:16 +00001418 }
1419
Guido van Rossum98f33732002-11-25 21:36:54 +00001420 if (empty_cnt == to_merge_size) {
1421 PyMem_FREE(remain);
Guido van Rossum1f121312002-11-14 19:49:16 +00001422 return 0;
Guido van Rossum98f33732002-11-25 21:36:54 +00001423 }
1424 set_mro_error(to_merge, remain);
1425 PyMem_FREE(remain);
Guido van Rossum1f121312002-11-14 19:49:16 +00001426 return -1;
1427}
1428
Tim Peters6d6c1a32001-08-02 04:15:00 +00001429static PyObject *
1430mro_implementation(PyTypeObject *type)
1431{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001432 Py_ssize_t i, n;
1433 int ok;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001434 PyObject *bases, *result;
Guido van Rossum1f121312002-11-14 19:49:16 +00001435 PyObject *to_merge, *bases_aslist;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001436
Christian Heimes412dc9c2008-01-27 18:55:54 +00001437 if (type->tp_dict == NULL) {
1438 if (PyType_Ready(type) < 0)
Guido van Rossum63517572002-06-18 16:44:57 +00001439 return NULL;
1440 }
1441
Guido van Rossum98f33732002-11-25 21:36:54 +00001442 /* Find a superclass linearization that honors the constraints
1443 of the explicit lists of bases and the constraints implied by
Tim Petersea7f75d2002-12-07 21:39:16 +00001444 each base class.
Guido van Rossum98f33732002-11-25 21:36:54 +00001445
1446 to_merge is a list of lists, where each list is a superclass
1447 linearization implied by a base class. The last element of
1448 to_merge is the declared list of bases.
1449 */
1450
Tim Peters6d6c1a32001-08-02 04:15:00 +00001451 bases = type->tp_bases;
1452 n = PyTuple_GET_SIZE(bases);
Guido van Rossum1f121312002-11-14 19:49:16 +00001453
1454 to_merge = PyList_New(n+1);
1455 if (to_merge == NULL)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001456 return NULL;
Guido van Rossum1f121312002-11-14 19:49:16 +00001457
Tim Peters6d6c1a32001-08-02 04:15:00 +00001458 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00001459 PyObject *base = PyTuple_GET_ITEM(bases, i);
1460 PyObject *parentMRO;
Guido van Rossum50e9fb92006-08-17 05:42:55 +00001461 parentMRO = PySequence_List(((PyTypeObject*)base)->tp_mro);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001462 if (parentMRO == NULL) {
Guido van Rossum1f121312002-11-14 19:49:16 +00001463 Py_DECREF(to_merge);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001464 return NULL;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001465 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001466
1467 PyList_SET_ITEM(to_merge, i, parentMRO);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001468 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001469
1470 bases_aslist = PySequence_List(bases);
1471 if (bases_aslist == NULL) {
1472 Py_DECREF(to_merge);
1473 return NULL;
1474 }
Guido van Rossum98f33732002-11-25 21:36:54 +00001475 /* This is just a basic sanity check. */
1476 if (check_duplicates(bases_aslist) < 0) {
1477 Py_DECREF(to_merge);
1478 Py_DECREF(bases_aslist);
1479 return NULL;
1480 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001481 PyList_SET_ITEM(to_merge, n, bases_aslist);
1482
1483 result = Py_BuildValue("[O]", (PyObject *)type);
1484 if (result == NULL) {
1485 Py_DECREF(to_merge);
1486 return NULL;
1487 }
1488
1489 ok = pmerge(result, to_merge);
1490 Py_DECREF(to_merge);
1491 if (ok < 0) {
1492 Py_DECREF(result);
1493 return NULL;
1494 }
1495
Tim Peters6d6c1a32001-08-02 04:15:00 +00001496 return result;
1497}
1498
1499static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001500mro_external(PyObject *self)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001501{
1502 PyTypeObject *type = (PyTypeObject *)self;
1503
Tim Peters6d6c1a32001-08-02 04:15:00 +00001504 return mro_implementation(type);
1505}
1506
1507static int
1508mro_internal(PyTypeObject *type)
1509{
1510 PyObject *mro, *result, *tuple;
Armin Rigo037d1e02005-12-29 17:07:39 +00001511 int checkit = 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001512
Christian Heimes90aa7642007-12-19 02:45:37 +00001513 if (Py_TYPE(type) == &PyType_Type) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001514 result = mro_implementation(type);
1515 }
1516 else {
Guido van Rossum60718732001-08-28 17:47:51 +00001517 static PyObject *mro_str;
Armin Rigo037d1e02005-12-29 17:07:39 +00001518 checkit = 1;
Guido van Rossum60718732001-08-28 17:47:51 +00001519 mro = lookup_method((PyObject *)type, "mro", &mro_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001520 if (mro == NULL)
1521 return -1;
1522 result = PyObject_CallObject(mro, NULL);
1523 Py_DECREF(mro);
1524 }
1525 if (result == NULL)
1526 return -1;
1527 tuple = PySequence_Tuple(result);
1528 Py_DECREF(result);
Armin Rigo037d1e02005-12-29 17:07:39 +00001529 if (tuple == NULL)
1530 return -1;
1531 if (checkit) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001532 Py_ssize_t i, len;
Armin Rigo037d1e02005-12-29 17:07:39 +00001533 PyObject *cls;
1534 PyTypeObject *solid;
1535
1536 solid = solid_base(type);
1537
1538 len = PyTuple_GET_SIZE(tuple);
1539
1540 for (i = 0; i < len; i++) {
1541 PyTypeObject *t;
1542 cls = PyTuple_GET_ITEM(tuple, i);
Guido van Rossum50e9fb92006-08-17 05:42:55 +00001543 if (!PyType_Check(cls)) {
Armin Rigo037d1e02005-12-29 17:07:39 +00001544 PyErr_Format(PyExc_TypeError,
1545 "mro() returned a non-class ('%.500s')",
Christian Heimes90aa7642007-12-19 02:45:37 +00001546 Py_TYPE(cls)->tp_name);
Neal Norwitz50bf51a2006-01-02 02:46:54 +00001547 Py_DECREF(tuple);
Armin Rigo037d1e02005-12-29 17:07:39 +00001548 return -1;
1549 }
1550 t = (PyTypeObject*)cls;
1551 if (!PyType_IsSubtype(solid, solid_base(t))) {
1552 PyErr_Format(PyExc_TypeError,
1553 "mro() returned base with unsuitable layout ('%.500s')",
1554 t->tp_name);
Neal Norwitz50bf51a2006-01-02 02:46:54 +00001555 Py_DECREF(tuple);
Armin Rigo037d1e02005-12-29 17:07:39 +00001556 return -1;
1557 }
1558 }
1559 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001560 type->tp_mro = tuple;
Christian Heimesa62da1d2008-01-12 19:39:10 +00001561
1562 type_mro_modified(type, type->tp_mro);
1563 /* corner case: the old-style super class might have been hidden
1564 from the custom MRO */
1565 type_mro_modified(type, type->tp_bases);
1566
Georg Brandlf08a9dd2008-06-10 16:57:31 +00001567 PyType_Modified(type);
Christian Heimesa62da1d2008-01-12 19:39:10 +00001568
Tim Peters6d6c1a32001-08-02 04:15:00 +00001569 return 0;
1570}
1571
1572
1573/* Calculate the best base amongst multiple base classes.
1574 This is the first one that's on the path to the "solid base". */
1575
1576static PyTypeObject *
1577best_base(PyObject *bases)
1578{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001579 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001580 PyTypeObject *base, *winner, *candidate, *base_i;
Tim Petersa91e9642001-11-14 23:32:33 +00001581 PyObject *base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001582
1583 assert(PyTuple_Check(bases));
1584 n = PyTuple_GET_SIZE(bases);
1585 assert(n > 0);
Tim Petersa91e9642001-11-14 23:32:33 +00001586 base = NULL;
1587 winner = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001588 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00001589 base_proto = PyTuple_GET_ITEM(bases, i);
Tim Petersa91e9642001-11-14 23:32:33 +00001590 if (!PyType_Check(base_proto)) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001591 PyErr_SetString(
1592 PyExc_TypeError,
1593 "bases must be types");
1594 return NULL;
1595 }
Tim Petersa91e9642001-11-14 23:32:33 +00001596 base_i = (PyTypeObject *)base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001597 if (base_i->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001598 if (PyType_Ready(base_i) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001599 return NULL;
1600 }
1601 candidate = solid_base(base_i);
Tim Petersa91e9642001-11-14 23:32:33 +00001602 if (winner == NULL) {
1603 winner = candidate;
1604 base = base_i;
1605 }
1606 else if (PyType_IsSubtype(winner, candidate))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001607 ;
1608 else if (PyType_IsSubtype(candidate, winner)) {
1609 winner = candidate;
1610 base = base_i;
1611 }
1612 else {
1613 PyErr_SetString(
1614 PyExc_TypeError,
1615 "multiple bases have "
1616 "instance lay-out conflict");
1617 return NULL;
1618 }
1619 }
Guido van Rossume54616c2001-12-14 04:19:56 +00001620 if (base == NULL)
1621 PyErr_SetString(PyExc_TypeError,
1622 "a new-style class can't have only classic bases");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001623 return base;
1624}
1625
1626static int
1627extra_ivars(PyTypeObject *type, PyTypeObject *base)
1628{
Neil Schemenauerc806c882001-08-29 23:54:54 +00001629 size_t t_size = type->tp_basicsize;
1630 size_t b_size = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001631
Guido van Rossum9676b222001-08-17 20:32:36 +00001632 assert(t_size >= b_size); /* Else type smaller than base! */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001633 if (type->tp_itemsize || base->tp_itemsize) {
1634 /* If itemsize is involved, stricter rules */
1635 return t_size != b_size ||
1636 type->tp_itemsize != base->tp_itemsize;
1637 }
Guido van Rossum9676b222001-08-17 20:32:36 +00001638 if (type->tp_weaklistoffset && base->tp_weaklistoffset == 0 &&
Guido van Rossum360e4b82007-05-14 22:51:27 +00001639 type->tp_weaklistoffset + sizeof(PyObject *) == t_size &&
1640 type->tp_flags & Py_TPFLAGS_HEAPTYPE)
Guido van Rossum9676b222001-08-17 20:32:36 +00001641 t_size -= sizeof(PyObject *);
1642 if (type->tp_dictoffset && base->tp_dictoffset == 0 &&
Guido van Rossum360e4b82007-05-14 22:51:27 +00001643 type->tp_dictoffset + sizeof(PyObject *) == t_size &&
1644 type->tp_flags & Py_TPFLAGS_HEAPTYPE)
Guido van Rossum9676b222001-08-17 20:32:36 +00001645 t_size -= sizeof(PyObject *);
1646
1647 return t_size != b_size;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001648}
1649
1650static PyTypeObject *
1651solid_base(PyTypeObject *type)
1652{
1653 PyTypeObject *base;
1654
1655 if (type->tp_base)
1656 base = solid_base(type->tp_base);
1657 else
1658 base = &PyBaseObject_Type;
1659 if (extra_ivars(type, base))
1660 return type;
1661 else
1662 return base;
1663}
1664
Jeremy Hylton938ace62002-07-17 16:30:39 +00001665static void object_dealloc(PyObject *);
1666static int object_init(PyObject *, PyObject *, PyObject *);
1667static int update_slot(PyTypeObject *, PyObject *);
1668static void fixup_slot_dispatchers(PyTypeObject *);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001669
Guido van Rossum360e4b82007-05-14 22:51:27 +00001670/*
1671 * Helpers for __dict__ descriptor. We don't want to expose the dicts
1672 * inherited from various builtin types. The builtin base usually provides
1673 * its own __dict__ descriptor, so we use that when we can.
1674 */
1675static PyTypeObject *
1676get_builtin_base_with_dict(PyTypeObject *type)
1677{
1678 while (type->tp_base != NULL) {
1679 if (type->tp_dictoffset != 0 &&
1680 !(type->tp_flags & Py_TPFLAGS_HEAPTYPE))
1681 return type;
1682 type = type->tp_base;
1683 }
1684 return NULL;
1685}
1686
1687static PyObject *
1688get_dict_descriptor(PyTypeObject *type)
1689{
1690 static PyObject *dict_str;
1691 PyObject *descr;
1692
1693 if (dict_str == NULL) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00001694 dict_str = PyUnicode_InternFromString("__dict__");
Guido van Rossum360e4b82007-05-14 22:51:27 +00001695 if (dict_str == NULL)
1696 return NULL;
1697 }
1698 descr = _PyType_Lookup(type, dict_str);
1699 if (descr == NULL || !PyDescr_IsData(descr))
1700 return NULL;
1701
1702 return descr;
1703}
1704
1705static void
1706raise_dict_descr_error(PyObject *obj)
1707{
1708 PyErr_Format(PyExc_TypeError,
1709 "this __dict__ descriptor does not support "
Christian Heimes90aa7642007-12-19 02:45:37 +00001710 "'%.200s' objects", Py_TYPE(obj)->tp_name);
Guido van Rossum360e4b82007-05-14 22:51:27 +00001711}
1712
Tim Peters6d6c1a32001-08-02 04:15:00 +00001713static PyObject *
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001714subtype_dict(PyObject *obj, void *context)
1715{
Guido van Rossum360e4b82007-05-14 22:51:27 +00001716 PyObject **dictptr;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001717 PyObject *dict;
Guido van Rossum360e4b82007-05-14 22:51:27 +00001718 PyTypeObject *base;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001719
Christian Heimes90aa7642007-12-19 02:45:37 +00001720 base = get_builtin_base_with_dict(Py_TYPE(obj));
Guido van Rossum360e4b82007-05-14 22:51:27 +00001721 if (base != NULL) {
1722 descrgetfunc func;
1723 PyObject *descr = get_dict_descriptor(base);
1724 if (descr == NULL) {
1725 raise_dict_descr_error(obj);
1726 return NULL;
1727 }
Christian Heimes90aa7642007-12-19 02:45:37 +00001728 func = Py_TYPE(descr)->tp_descr_get;
Guido van Rossum360e4b82007-05-14 22:51:27 +00001729 if (func == NULL) {
1730 raise_dict_descr_error(obj);
1731 return NULL;
1732 }
Christian Heimes90aa7642007-12-19 02:45:37 +00001733 return func(descr, obj, (PyObject *)(Py_TYPE(obj)));
Guido van Rossum360e4b82007-05-14 22:51:27 +00001734 }
1735
1736 dictptr = _PyObject_GetDictPtr(obj);
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001737 if (dictptr == NULL) {
1738 PyErr_SetString(PyExc_AttributeError,
1739 "This object has no __dict__");
1740 return NULL;
1741 }
1742 dict = *dictptr;
Guido van Rossum3926a632001-09-25 16:25:58 +00001743 if (dict == NULL)
1744 *dictptr = dict = PyDict_New();
1745 Py_XINCREF(dict);
1746 return dict;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001747}
1748
Guido van Rossum6661be32001-10-26 04:26:12 +00001749static int
1750subtype_setdict(PyObject *obj, PyObject *value, void *context)
1751{
Guido van Rossum360e4b82007-05-14 22:51:27 +00001752 PyObject **dictptr;
Guido van Rossum6661be32001-10-26 04:26:12 +00001753 PyObject *dict;
Guido van Rossum360e4b82007-05-14 22:51:27 +00001754 PyTypeObject *base;
Guido van Rossum6661be32001-10-26 04:26:12 +00001755
Christian Heimes90aa7642007-12-19 02:45:37 +00001756 base = get_builtin_base_with_dict(Py_TYPE(obj));
Guido van Rossum360e4b82007-05-14 22:51:27 +00001757 if (base != NULL) {
1758 descrsetfunc func;
1759 PyObject *descr = get_dict_descriptor(base);
1760 if (descr == NULL) {
1761 raise_dict_descr_error(obj);
1762 return -1;
1763 }
Christian Heimes90aa7642007-12-19 02:45:37 +00001764 func = Py_TYPE(descr)->tp_descr_set;
Guido van Rossum360e4b82007-05-14 22:51:27 +00001765 if (func == NULL) {
1766 raise_dict_descr_error(obj);
1767 return -1;
1768 }
1769 return func(descr, obj, value);
1770 }
1771
1772 dictptr = _PyObject_GetDictPtr(obj);
Guido van Rossum6661be32001-10-26 04:26:12 +00001773 if (dictptr == NULL) {
1774 PyErr_SetString(PyExc_AttributeError,
1775 "This object has no __dict__");
1776 return -1;
1777 }
Guido van Rossumd331cb52001-12-05 19:46:42 +00001778 if (value != NULL && !PyDict_Check(value)) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001779 PyErr_Format(PyExc_TypeError,
1780 "__dict__ must be set to a dictionary, "
Christian Heimes90aa7642007-12-19 02:45:37 +00001781 "not a '%.200s'", Py_TYPE(value)->tp_name);
Guido van Rossum6661be32001-10-26 04:26:12 +00001782 return -1;
1783 }
1784 dict = *dictptr;
Guido van Rossumd331cb52001-12-05 19:46:42 +00001785 Py_XINCREF(value);
Guido van Rossum6661be32001-10-26 04:26:12 +00001786 *dictptr = value;
1787 Py_XDECREF(dict);
1788 return 0;
1789}
1790
Guido van Rossumad47da02002-08-12 19:05:44 +00001791static PyObject *
1792subtype_getweakref(PyObject *obj, void *context)
1793{
1794 PyObject **weaklistptr;
1795 PyObject *result;
1796
Christian Heimes90aa7642007-12-19 02:45:37 +00001797 if (Py_TYPE(obj)->tp_weaklistoffset == 0) {
Guido van Rossumad47da02002-08-12 19:05:44 +00001798 PyErr_SetString(PyExc_AttributeError,
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001799 "This object has no __weakref__");
Guido van Rossumad47da02002-08-12 19:05:44 +00001800 return NULL;
1801 }
Christian Heimes90aa7642007-12-19 02:45:37 +00001802 assert(Py_TYPE(obj)->tp_weaklistoffset > 0);
1803 assert(Py_TYPE(obj)->tp_weaklistoffset + sizeof(PyObject *) <=
1804 (size_t)(Py_TYPE(obj)->tp_basicsize));
Guido van Rossumad47da02002-08-12 19:05:44 +00001805 weaklistptr = (PyObject **)
Christian Heimes90aa7642007-12-19 02:45:37 +00001806 ((char *)obj + Py_TYPE(obj)->tp_weaklistoffset);
Guido van Rossumad47da02002-08-12 19:05:44 +00001807 if (*weaklistptr == NULL)
1808 result = Py_None;
1809 else
1810 result = *weaklistptr;
1811 Py_INCREF(result);
1812 return result;
1813}
1814
Guido van Rossum373c7412003-01-07 13:41:37 +00001815/* Three variants on the subtype_getsets list. */
1816
1817static PyGetSetDef subtype_getsets_full[] = {
Guido van Rossumad47da02002-08-12 19:05:44 +00001818 {"__dict__", subtype_dict, subtype_setdict,
Neal Norwitz858e34f2002-08-13 17:18:45 +00001819 PyDoc_STR("dictionary for instance variables (if defined)")},
Guido van Rossumad47da02002-08-12 19:05:44 +00001820 {"__weakref__", subtype_getweakref, NULL,
Neal Norwitz858e34f2002-08-13 17:18:45 +00001821 PyDoc_STR("list of weak references to the object (if defined)")},
Guido van Rossumad47da02002-08-12 19:05:44 +00001822 {0}
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001823};
1824
Guido van Rossum373c7412003-01-07 13:41:37 +00001825static PyGetSetDef subtype_getsets_dict_only[] = {
1826 {"__dict__", subtype_dict, subtype_setdict,
1827 PyDoc_STR("dictionary for instance variables (if defined)")},
1828 {0}
1829};
1830
1831static PyGetSetDef subtype_getsets_weakref_only[] = {
1832 {"__weakref__", subtype_getweakref, NULL,
1833 PyDoc_STR("list of weak references to the object (if defined)")},
1834 {0}
1835};
1836
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001837static int
1838valid_identifier(PyObject *s)
1839{
Martin v. Löwis5b222132007-06-10 09:51:05 +00001840 if (!PyUnicode_Check(s)) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001841 PyErr_Format(PyExc_TypeError,
1842 "__slots__ items must be strings, not '%.200s'",
Christian Heimes90aa7642007-12-19 02:45:37 +00001843 Py_TYPE(s)->tp_name);
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001844 return 0;
1845 }
Georg Brandlf4780d02007-08-30 18:29:48 +00001846 if (!PyUnicode_IsIdentifier(s)) {
1847 PyErr_SetString(PyExc_TypeError,
1848 "__slots__ must be identifiers");
1849 return 0;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001850 }
1851 return 1;
1852}
1853
Guido van Rossumd8faa362007-04-27 19:54:29 +00001854/* Forward */
1855static int
1856object_init(PyObject *self, PyObject *args, PyObject *kwds);
1857
1858static int
1859type_init(PyObject *cls, PyObject *args, PyObject *kwds)
1860{
1861 int res;
1862
1863 assert(args != NULL && PyTuple_Check(args));
1864 assert(kwds == NULL || PyDict_Check(kwds));
1865
1866 if (kwds != NULL && PyDict_Check(kwds) && PyDict_Size(kwds) != 0) {
1867 PyErr_SetString(PyExc_TypeError,
1868 "type.__init__() takes no keyword arguments");
1869 return -1;
1870 }
1871
1872 if (args != NULL && PyTuple_Check(args) &&
1873 (PyTuple_GET_SIZE(args) != 1 && PyTuple_GET_SIZE(args) != 3)) {
1874 PyErr_SetString(PyExc_TypeError,
1875 "type.__init__() takes 1 or 3 arguments");
1876 return -1;
1877 }
1878
1879 /* Call object.__init__(self) now. */
1880 /* XXX Could call super(type, cls).__init__() but what's the point? */
1881 args = PyTuple_GetSlice(args, 0, 0);
1882 res = object_init(cls, args, NULL);
1883 Py_DECREF(args);
1884 return res;
1885}
1886
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001887static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00001888type_new(PyTypeObject *metatype, PyObject *args, PyObject *kwds)
1889{
1890 PyObject *name, *bases, *dict;
Martin v. Löwis15e62742006-02-27 16:46:16 +00001891 static char *kwlist[] = {"name", "bases", "dict", 0};
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001892 PyObject *slots, *tmp, *newslots;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001893 PyTypeObject *type, *base, *tmptype, *winner;
Guido van Rossume5c691a2003-03-07 15:13:17 +00001894 PyHeapTypeObject *et;
Guido van Rossum6f799372001-09-20 20:46:19 +00001895 PyMemberDef *mp;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001896 Py_ssize_t i, nbases, nslots, slotoffset, add_dict, add_weak;
Guido van Rossumad47da02002-08-12 19:05:44 +00001897 int j, may_add_dict, may_add_weak;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001898
Tim Peters3abca122001-10-27 19:37:48 +00001899 assert(args != NULL && PyTuple_Check(args));
1900 assert(kwds == NULL || PyDict_Check(kwds));
1901
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001902 /* Special case: type(x) should return x->ob_type */
Tim Peters3abca122001-10-27 19:37:48 +00001903 {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001904 const Py_ssize_t nargs = PyTuple_GET_SIZE(args);
1905 const Py_ssize_t nkwds = kwds == NULL ? 0 : PyDict_Size(kwds);
Tim Peters3abca122001-10-27 19:37:48 +00001906
1907 if (PyType_CheckExact(metatype) && nargs == 1 && nkwds == 0) {
1908 PyObject *x = PyTuple_GET_ITEM(args, 0);
Christian Heimes90aa7642007-12-19 02:45:37 +00001909 Py_INCREF(Py_TYPE(x));
1910 return (PyObject *) Py_TYPE(x);
Tim Peters3abca122001-10-27 19:37:48 +00001911 }
1912
1913 /* SF bug 475327 -- if that didn't trigger, we need 3
1914 arguments. but PyArg_ParseTupleAndKeywords below may give
1915 a msg saying type() needs exactly 3. */
1916 if (nargs + nkwds != 3) {
1917 PyErr_SetString(PyExc_TypeError,
1918 "type() takes 1 or 3 arguments");
1919 return NULL;
1920 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001921 }
1922
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001923 /* Check arguments: (name, bases, dict) */
Guido van Rossum98297ee2007-11-06 21:34:58 +00001924 if (!PyArg_ParseTupleAndKeywords(args, kwds, "UO!O!:type", kwlist,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001925 &name,
1926 &PyTuple_Type, &bases,
1927 &PyDict_Type, &dict))
1928 return NULL;
1929
1930 /* Determine the proper metatype to deal with this,
1931 and check for metatype conflicts while we're at it.
1932 Note that if some other metatype wins to contract,
1933 it's possible that its instances are not types. */
1934 nbases = PyTuple_GET_SIZE(bases);
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001935 winner = metatype;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001936 for (i = 0; i < nbases; i++) {
1937 tmp = PyTuple_GET_ITEM(bases, i);
Christian Heimes90aa7642007-12-19 02:45:37 +00001938 tmptype = Py_TYPE(tmp);
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001939 if (PyType_IsSubtype(winner, tmptype))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001940 continue;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001941 if (PyType_IsSubtype(tmptype, winner)) {
1942 winner = tmptype;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001943 continue;
1944 }
1945 PyErr_SetString(PyExc_TypeError,
Guido van Rossum636688d2003-04-23 12:07:22 +00001946 "metaclass conflict: "
1947 "the metaclass of a derived class "
1948 "must be a (non-strict) subclass "
1949 "of the metaclasses of all its bases");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001950 return NULL;
1951 }
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001952 if (winner != metatype) {
1953 if (winner->tp_new != type_new) /* Pass it to the winner */
1954 return winner->tp_new(winner, args, kwds);
1955 metatype = winner;
1956 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001957
1958 /* Adjust for empty tuple bases */
1959 if (nbases == 0) {
Raymond Hettinger8ae46892003-10-12 19:09:37 +00001960 bases = PyTuple_Pack(1, &PyBaseObject_Type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001961 if (bases == NULL)
1962 return NULL;
1963 nbases = 1;
1964 }
1965 else
1966 Py_INCREF(bases);
1967
1968 /* XXX From here until type is allocated, "return NULL" leaks bases! */
1969
1970 /* Calculate best base, and check that all bases are type objects */
1971 base = best_base(bases);
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001972 if (base == NULL) {
1973 Py_DECREF(bases);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001974 return NULL;
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001975 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001976 if (!PyType_HasFeature(base, Py_TPFLAGS_BASETYPE)) {
1977 PyErr_Format(PyExc_TypeError,
1978 "type '%.100s' is not an acceptable base type",
1979 base->tp_name);
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001980 Py_DECREF(bases);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001981 return NULL;
1982 }
1983
Tim Peters6d6c1a32001-08-02 04:15:00 +00001984 /* Check for a __slots__ sequence variable in dict, and count it */
1985 slots = PyDict_GetItemString(dict, "__slots__");
1986 nslots = 0;
Guido van Rossum9676b222001-08-17 20:32:36 +00001987 add_dict = 0;
1988 add_weak = 0;
Guido van Rossumad47da02002-08-12 19:05:44 +00001989 may_add_dict = base->tp_dictoffset == 0;
1990 may_add_weak = base->tp_weaklistoffset == 0 && base->tp_itemsize == 0;
1991 if (slots == NULL) {
1992 if (may_add_dict) {
1993 add_dict++;
1994 }
1995 if (may_add_weak) {
1996 add_weak++;
1997 }
1998 }
1999 else {
2000 /* Have slots */
2001
Tim Peters6d6c1a32001-08-02 04:15:00 +00002002 /* Make it into a tuple */
Neal Norwitz80e7f272007-08-26 06:45:23 +00002003 if (PyUnicode_Check(slots))
Raymond Hettinger8ae46892003-10-12 19:09:37 +00002004 slots = PyTuple_Pack(1, slots);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002005 else
2006 slots = PySequence_Tuple(slots);
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00002007 if (slots == NULL) {
2008 Py_DECREF(bases);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002009 return NULL;
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00002010 }
Guido van Rossumad47da02002-08-12 19:05:44 +00002011 assert(PyTuple_Check(slots));
2012
2013 /* Are slots allowed? */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002014 nslots = PyTuple_GET_SIZE(slots);
Jeremy Hylton1c7a0ea2003-07-16 16:08:23 +00002015 if (nslots > 0 && base->tp_itemsize != 0) {
Guido van Rossumc4141872001-08-30 04:43:35 +00002016 PyErr_Format(PyExc_TypeError,
2017 "nonempty __slots__ "
2018 "not supported for subtype of '%s'",
2019 base->tp_name);
Guido van Rossumad47da02002-08-12 19:05:44 +00002020 bad_slots:
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00002021 Py_DECREF(bases);
Guido van Rossumad47da02002-08-12 19:05:44 +00002022 Py_DECREF(slots);
Guido van Rossumc4141872001-08-30 04:43:35 +00002023 return NULL;
2024 }
Guido van Rossumad47da02002-08-12 19:05:44 +00002025
2026 /* Check for valid slot names and two special cases */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002027 for (i = 0; i < nslots; i++) {
Guido van Rossumad47da02002-08-12 19:05:44 +00002028 PyObject *tmp = PyTuple_GET_ITEM(slots, i);
Guido van Rossumad47da02002-08-12 19:05:44 +00002029 if (!valid_identifier(tmp))
2030 goto bad_slots;
Martin v. Löwis5b222132007-06-10 09:51:05 +00002031 assert(PyUnicode_Check(tmp));
2032 if (PyUnicode_CompareWithASCIIString(tmp, "__dict__") == 0) {
Guido van Rossumad47da02002-08-12 19:05:44 +00002033 if (!may_add_dict || add_dict) {
2034 PyErr_SetString(PyExc_TypeError,
2035 "__dict__ slot disallowed: "
2036 "we already got one");
2037 goto bad_slots;
2038 }
2039 add_dict++;
2040 }
Martin v. Löwis5b222132007-06-10 09:51:05 +00002041 if (PyUnicode_CompareWithASCIIString(tmp, "__weakref__") == 0) {
Guido van Rossumad47da02002-08-12 19:05:44 +00002042 if (!may_add_weak || add_weak) {
2043 PyErr_SetString(PyExc_TypeError,
2044 "__weakref__ slot disallowed: "
2045 "either we already got one, "
2046 "or __itemsize__ != 0");
2047 goto bad_slots;
2048 }
2049 add_weak++;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002050 }
2051 }
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00002052
Guido van Rossumd8faa362007-04-27 19:54:29 +00002053 /* Copy slots into a list, mangle names and sort them.
2054 Sorted names are needed for __class__ assignment.
2055 Convert them back to tuple at the end.
2056 */
2057 newslots = PyList_New(nslots - add_dict - add_weak);
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00002058 if (newslots == NULL)
Guido van Rossumad47da02002-08-12 19:05:44 +00002059 goto bad_slots;
2060 for (i = j = 0; i < nslots; i++) {
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00002061 tmp = PyTuple_GET_ITEM(slots, i);
Martin v. Löwis5b222132007-06-10 09:51:05 +00002062 if ((add_dict &&
2063 PyUnicode_CompareWithASCIIString(tmp, "__dict__") == 0) ||
2064 (add_weak &&
2065 PyUnicode_CompareWithASCIIString(tmp, "__weakref__") == 0))
Guido van Rossumad47da02002-08-12 19:05:44 +00002066 continue;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002067 tmp =_Py_Mangle(name, tmp);
Guido van Rossumd8faa362007-04-27 19:54:29 +00002068 if (!tmp)
2069 goto bad_slots;
2070 PyList_SET_ITEM(newslots, j, tmp);
Guido van Rossumad47da02002-08-12 19:05:44 +00002071 j++;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00002072 }
Guido van Rossumad47da02002-08-12 19:05:44 +00002073 assert(j == nslots - add_dict - add_weak);
2074 nslots = j;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00002075 Py_DECREF(slots);
Guido van Rossumd8faa362007-04-27 19:54:29 +00002076 if (PyList_Sort(newslots) == -1) {
2077 Py_DECREF(bases);
2078 Py_DECREF(newslots);
2079 return NULL;
2080 }
2081 slots = PyList_AsTuple(newslots);
2082 Py_DECREF(newslots);
2083 if (slots == NULL) {
2084 Py_DECREF(bases);
2085 return NULL;
2086 }
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00002087
Guido van Rossumad47da02002-08-12 19:05:44 +00002088 /* Secondary bases may provide weakrefs or dict */
2089 if (nbases > 1 &&
2090 ((may_add_dict && !add_dict) ||
2091 (may_add_weak && !add_weak))) {
2092 for (i = 0; i < nbases; i++) {
2093 tmp = PyTuple_GET_ITEM(bases, i);
2094 if (tmp == (PyObject *)base)
2095 continue; /* Skip primary base */
Guido van Rossumad47da02002-08-12 19:05:44 +00002096 assert(PyType_Check(tmp));
2097 tmptype = (PyTypeObject *)tmp;
2098 if (may_add_dict && !add_dict &&
2099 tmptype->tp_dictoffset != 0)
2100 add_dict++;
2101 if (may_add_weak && !add_weak &&
2102 tmptype->tp_weaklistoffset != 0)
2103 add_weak++;
2104 if (may_add_dict && !add_dict)
2105 continue;
2106 if (may_add_weak && !add_weak)
2107 continue;
2108 /* Nothing more to check */
2109 break;
2110 }
2111 }
Guido van Rossum9676b222001-08-17 20:32:36 +00002112 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002113
2114 /* XXX From here until type is safely allocated,
2115 "return NULL" may leak slots! */
2116
2117 /* Allocate the type object */
2118 type = (PyTypeObject *)metatype->tp_alloc(metatype, nslots);
Guido van Rossumad47da02002-08-12 19:05:44 +00002119 if (type == NULL) {
2120 Py_XDECREF(slots);
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00002121 Py_DECREF(bases);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002122 return NULL;
Guido van Rossumad47da02002-08-12 19:05:44 +00002123 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002124
2125 /* Keep name and slots alive in the extended type object */
Guido van Rossume5c691a2003-03-07 15:13:17 +00002126 et = (PyHeapTypeObject *)type;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002127 Py_INCREF(name);
Georg Brandlc255c7b2006-02-20 22:27:28 +00002128 et->ht_name = name;
2129 et->ht_slots = slots;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002130
Guido van Rossumdc91b992001-08-08 22:26:22 +00002131 /* Initialize tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002132 type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE |
2133 Py_TPFLAGS_BASETYPE;
Guido van Rossum048eb752001-10-02 21:24:57 +00002134 if (base->tp_flags & Py_TPFLAGS_HAVE_GC)
2135 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossumdc91b992001-08-08 22:26:22 +00002136
Guido van Rossumdc91b992001-08-08 22:26:22 +00002137 /* Initialize essential fields */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002138 type->tp_as_number = &et->as_number;
2139 type->tp_as_sequence = &et->as_sequence;
2140 type->tp_as_mapping = &et->as_mapping;
2141 type->tp_as_buffer = &et->as_buffer;
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +00002142 type->tp_name = _PyUnicode_AsString(name);
Neal Norwitz80e7f272007-08-26 06:45:23 +00002143 if (!type->tp_name) {
2144 Py_DECREF(type);
2145 return NULL;
Martin v. Löwis5b222132007-06-10 09:51:05 +00002146 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002147
2148 /* Set tp_base and tp_bases */
2149 type->tp_bases = bases;
2150 Py_INCREF(base);
2151 type->tp_base = base;
2152
Guido van Rossum687ae002001-10-15 22:03:32 +00002153 /* Initialize tp_dict from passed-in dict */
2154 type->tp_dict = dict = PyDict_Copy(dict);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002155 if (dict == NULL) {
2156 Py_DECREF(type);
2157 return NULL;
2158 }
2159
Guido van Rossumc3542212001-08-16 09:18:56 +00002160 /* Set __module__ in the dict */
2161 if (PyDict_GetItemString(dict, "__module__") == NULL) {
2162 tmp = PyEval_GetGlobals();
2163 if (tmp != NULL) {
2164 tmp = PyDict_GetItemString(tmp, "__name__");
2165 if (tmp != NULL) {
2166 if (PyDict_SetItemString(dict, "__module__",
2167 tmp) < 0)
2168 return NULL;
2169 }
2170 }
2171 }
2172
Tim Peters2f93e282001-10-04 05:27:00 +00002173 /* Set tp_doc to a copy of dict['__doc__'], if the latter is there
Tim Peters24008312002-03-17 18:56:20 +00002174 and is a string. The __doc__ accessor will first look for tp_doc;
2175 if that fails, it will still look into __dict__.
Tim Peters2f93e282001-10-04 05:27:00 +00002176 */
2177 {
2178 PyObject *doc = PyDict_GetItemString(dict, "__doc__");
Neal Norwitz6ea45d32007-08-26 04:19:43 +00002179 if (doc != NULL && PyUnicode_Check(doc)) {
Alexandre Vassalottia85998a2008-05-03 18:24:43 +00002180 Py_ssize_t len;
2181 char *doc_str;
Neal Norwitz6ea45d32007-08-26 04:19:43 +00002182 char *tp_doc;
Alexandre Vassalottia85998a2008-05-03 18:24:43 +00002183
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +00002184 doc_str = _PyUnicode_AsStringAndSize(doc, &len);
Alexandre Vassalottia85998a2008-05-03 18:24:43 +00002185 if (doc_str == NULL) {
Neal Norwitz6ea45d32007-08-26 04:19:43 +00002186 Py_DECREF(type);
2187 return NULL;
Tim Peters2f93e282001-10-04 05:27:00 +00002188 }
Alexandre Vassalottia85998a2008-05-03 18:24:43 +00002189 if ((Py_ssize_t)strlen(doc_str) != len) {
2190 PyErr_SetString(PyExc_TypeError,
2191 "__doc__ contains null-bytes");
2192 Py_DECREF(type);
2193 return NULL;
2194 }
2195 tp_doc = (char *)PyObject_MALLOC(len + 1);
Neal Norwitz6ea45d32007-08-26 04:19:43 +00002196 if (tp_doc == NULL) {
2197 Py_DECREF(type);
2198 return NULL;
Neal Norwitza369c5a2007-08-25 07:41:59 +00002199 }
Alexandre Vassalottia85998a2008-05-03 18:24:43 +00002200 memcpy(tp_doc, doc_str, len + 1);
Neal Norwitz6ea45d32007-08-26 04:19:43 +00002201 type->tp_doc = tp_doc;
Tim Peters2f93e282001-10-04 05:27:00 +00002202 }
2203 }
2204
Tim Peters6d6c1a32001-08-02 04:15:00 +00002205 /* Special-case __new__: if it's a plain function,
2206 make it a static function */
2207 tmp = PyDict_GetItemString(dict, "__new__");
2208 if (tmp != NULL && PyFunction_Check(tmp)) {
2209 tmp = PyStaticMethod_New(tmp);
2210 if (tmp == NULL) {
2211 Py_DECREF(type);
2212 return NULL;
2213 }
2214 PyDict_SetItemString(dict, "__new__", tmp);
2215 Py_DECREF(tmp);
2216 }
2217
2218 /* Add descriptors for custom slots from __slots__, or for __dict__ */
Guido van Rossume5c691a2003-03-07 15:13:17 +00002219 mp = PyHeapType_GET_MEMBERS(et);
Neil Schemenauerc806c882001-08-29 23:54:54 +00002220 slotoffset = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002221 if (slots != NULL) {
2222 for (i = 0; i < nslots; i++, mp++) {
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +00002223 mp->name = _PyUnicode_AsString(
Tim Peters6d6c1a32001-08-02 04:15:00 +00002224 PyTuple_GET_ITEM(slots, i));
Guido van Rossum64b206c2001-12-04 17:13:22 +00002225 mp->type = T_OBJECT_EX;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002226 mp->offset = slotoffset;
Guido van Rossumd8faa362007-04-27 19:54:29 +00002227
2228 /* __dict__ and __weakref__ are already filtered out */
2229 assert(strcmp(mp->name, "__dict__") != 0);
2230 assert(strcmp(mp->name, "__weakref__") != 0);
2231
Tim Peters6d6c1a32001-08-02 04:15:00 +00002232 slotoffset += sizeof(PyObject *);
2233 }
2234 }
Guido van Rossumad47da02002-08-12 19:05:44 +00002235 if (add_dict) {
2236 if (base->tp_itemsize)
2237 type->tp_dictoffset = -(long)sizeof(PyObject *);
2238 else
2239 type->tp_dictoffset = slotoffset;
2240 slotoffset += sizeof(PyObject *);
2241 }
2242 if (add_weak) {
2243 assert(!base->tp_itemsize);
2244 type->tp_weaklistoffset = slotoffset;
2245 slotoffset += sizeof(PyObject *);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002246 }
2247 type->tp_basicsize = slotoffset;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00002248 type->tp_itemsize = base->tp_itemsize;
Guido van Rossume5c691a2003-03-07 15:13:17 +00002249 type->tp_members = PyHeapType_GET_MEMBERS(et);
Guido van Rossum373c7412003-01-07 13:41:37 +00002250
2251 if (type->tp_weaklistoffset && type->tp_dictoffset)
2252 type->tp_getset = subtype_getsets_full;
2253 else if (type->tp_weaklistoffset && !type->tp_dictoffset)
2254 type->tp_getset = subtype_getsets_weakref_only;
2255 else if (!type->tp_weaklistoffset && type->tp_dictoffset)
2256 type->tp_getset = subtype_getsets_dict_only;
2257 else
2258 type->tp_getset = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002259
2260 /* Special case some slots */
2261 if (type->tp_dictoffset != 0 || nslots > 0) {
2262 if (base->tp_getattr == NULL && base->tp_getattro == NULL)
2263 type->tp_getattro = PyObject_GenericGetAttr;
2264 if (base->tp_setattr == NULL && base->tp_setattro == NULL)
2265 type->tp_setattro = PyObject_GenericSetAttr;
2266 }
2267 type->tp_dealloc = subtype_dealloc;
2268
Guido van Rossum9475a232001-10-05 20:51:39 +00002269 /* Enable GC unless there are really no instance variables possible */
2270 if (!(type->tp_basicsize == sizeof(PyObject) &&
2271 type->tp_itemsize == 0))
2272 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
2273
Tim Peters6d6c1a32001-08-02 04:15:00 +00002274 /* Always override allocation strategy to use regular heap */
2275 type->tp_alloc = PyType_GenericAlloc;
Guido van Rossum048eb752001-10-02 21:24:57 +00002276 if (type->tp_flags & Py_TPFLAGS_HAVE_GC) {
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00002277 type->tp_free = PyObject_GC_Del;
Guido van Rossum9475a232001-10-05 20:51:39 +00002278 type->tp_traverse = subtype_traverse;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00002279 type->tp_clear = subtype_clear;
Guido van Rossum048eb752001-10-02 21:24:57 +00002280 }
2281 else
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00002282 type->tp_free = PyObject_Del;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002283
2284 /* Initialize the rest */
Guido van Rossum528b7eb2001-08-07 17:24:28 +00002285 if (PyType_Ready(type) < 0) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00002286 Py_DECREF(type);
2287 return NULL;
2288 }
2289
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002290 /* Put the proper slots in place */
2291 fixup_slot_dispatchers(type);
Guido van Rossumf040ede2001-08-07 16:40:56 +00002292
Tim Peters6d6c1a32001-08-02 04:15:00 +00002293 return (PyObject *)type;
2294}
2295
2296/* Internal API to look for a name through the MRO.
2297 This returns a borrowed reference, and doesn't set an exception! */
2298PyObject *
2299_PyType_Lookup(PyTypeObject *type, PyObject *name)
2300{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002301 Py_ssize_t i, n;
Tim Petersa91e9642001-11-14 23:32:33 +00002302 PyObject *mro, *res, *base, *dict;
Christian Heimesa62da1d2008-01-12 19:39:10 +00002303 unsigned int h;
2304
2305 if (MCACHE_CACHEABLE_NAME(name) &&
Christian Heimes412dc9c2008-01-27 18:55:54 +00002306 PyType_HasFeature(type, Py_TPFLAGS_VALID_VERSION_TAG)) {
Christian Heimesa62da1d2008-01-12 19:39:10 +00002307 /* fast path */
2308 h = MCACHE_HASH_METHOD(type, name);
2309 if (method_cache[h].version == type->tp_version_tag &&
2310 method_cache[h].name == name)
2311 return method_cache[h].value;
2312 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002313
Guido van Rossum687ae002001-10-15 22:03:32 +00002314 /* Look in tp_dict of types in MRO */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002315 mro = type->tp_mro;
Guido van Rossum23094982002-06-10 14:30:43 +00002316
2317 /* If mro is NULL, the type is either not yet initialized
2318 by PyType_Ready(), or already cleared by type_clear().
2319 Either way the safest thing to do is to return NULL. */
2320 if (mro == NULL)
2321 return NULL;
2322
Christian Heimesa62da1d2008-01-12 19:39:10 +00002323 res = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002324 assert(PyTuple_Check(mro));
2325 n = PyTuple_GET_SIZE(mro);
2326 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00002327 base = PyTuple_GET_ITEM(mro, i);
Guido van Rossum50e9fb92006-08-17 05:42:55 +00002328 assert(PyType_Check(base));
2329 dict = ((PyTypeObject *)base)->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002330 assert(dict && PyDict_Check(dict));
2331 res = PyDict_GetItem(dict, name);
2332 if (res != NULL)
Christian Heimesa62da1d2008-01-12 19:39:10 +00002333 break;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002334 }
Christian Heimesa62da1d2008-01-12 19:39:10 +00002335
2336 if (MCACHE_CACHEABLE_NAME(name) && assign_version_tag(type)) {
2337 h = MCACHE_HASH_METHOD(type, name);
2338 method_cache[h].version = type->tp_version_tag;
2339 method_cache[h].value = res; /* borrowed */
2340 Py_INCREF(name);
2341 Py_DECREF(method_cache[h].name);
2342 method_cache[h].name = name;
2343 }
2344 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002345}
2346
2347/* This is similar to PyObject_GenericGetAttr(),
2348 but uses _PyType_Lookup() instead of just looking in type->tp_dict. */
2349static PyObject *
2350type_getattro(PyTypeObject *type, PyObject *name)
2351{
Christian Heimes90aa7642007-12-19 02:45:37 +00002352 PyTypeObject *metatype = Py_TYPE(type);
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002353 PyObject *meta_attribute, *attribute;
2354 descrgetfunc meta_get;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002355
2356 /* Initialize this type (we'll assume the metatype is initialized) */
2357 if (type->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00002358 if (PyType_Ready(type) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002359 return NULL;
2360 }
2361
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002362 /* No readable descriptor found yet */
2363 meta_get = NULL;
Tim Peters34592512002-07-11 06:23:50 +00002364
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002365 /* Look for the attribute in the metatype */
2366 meta_attribute = _PyType_Lookup(metatype, name);
2367
2368 if (meta_attribute != NULL) {
Christian Heimes90aa7642007-12-19 02:45:37 +00002369 meta_get = Py_TYPE(meta_attribute)->tp_descr_get;
Tim Peters34592512002-07-11 06:23:50 +00002370
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002371 if (meta_get != NULL && PyDescr_IsData(meta_attribute)) {
2372 /* Data descriptors implement tp_descr_set to intercept
2373 * writes. Assume the attribute is not overridden in
2374 * type's tp_dict (and bases): call the descriptor now.
2375 */
2376 return meta_get(meta_attribute, (PyObject *)type,
2377 (PyObject *)metatype);
2378 }
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00002379 Py_INCREF(meta_attribute);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002380 }
2381
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002382 /* No data descriptor found on metatype. Look in tp_dict of this
2383 * type and its bases */
2384 attribute = _PyType_Lookup(type, name);
2385 if (attribute != NULL) {
2386 /* Implement descriptor functionality, if any */
Christian Heimes90aa7642007-12-19 02:45:37 +00002387 descrgetfunc local_get = Py_TYPE(attribute)->tp_descr_get;
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00002388
2389 Py_XDECREF(meta_attribute);
2390
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002391 if (local_get != NULL) {
2392 /* NULL 2nd argument indicates the descriptor was
2393 * found on the target object itself (or a base) */
2394 return local_get(attribute, (PyObject *)NULL,
2395 (PyObject *)type);
2396 }
Tim Peters34592512002-07-11 06:23:50 +00002397
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002398 Py_INCREF(attribute);
2399 return attribute;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002400 }
2401
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002402 /* No attribute found in local __dict__ (or bases): use the
2403 * descriptor from the metatype, if any */
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00002404 if (meta_get != NULL) {
2405 PyObject *res;
2406 res = meta_get(meta_attribute, (PyObject *)type,
2407 (PyObject *)metatype);
2408 Py_DECREF(meta_attribute);
2409 return res;
2410 }
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002411
2412 /* If an ordinary attribute was found on the metatype, return it now */
2413 if (meta_attribute != NULL) {
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002414 return meta_attribute;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002415 }
2416
2417 /* Give up */
2418 PyErr_Format(PyExc_AttributeError,
Walter Dörwald75163602007-06-11 15:47:13 +00002419 "type object '%.50s' has no attribute '%U'",
2420 type->tp_name, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002421 return NULL;
2422}
2423
2424static int
2425type_setattro(PyTypeObject *type, PyObject *name, PyObject *value)
2426{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002427 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
2428 PyErr_Format(
2429 PyExc_TypeError,
2430 "can't set attributes of built-in/extension type '%s'",
2431 type->tp_name);
2432 return -1;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002433 }
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002434 if (PyObject_GenericSetAttr((PyObject *)type, name, value) < 0)
2435 return -1;
2436 return update_slot(type, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002437}
2438
2439static void
2440type_dealloc(PyTypeObject *type)
2441{
Guido van Rossume5c691a2003-03-07 15:13:17 +00002442 PyHeapTypeObject *et;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002443
2444 /* Assert this is a heap-allocated type object */
2445 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002446 _PyObject_GC_UNTRACK(type);
Guido van Rossum1c450732001-10-08 15:18:27 +00002447 PyObject_ClearWeakRefs((PyObject *)type);
Guido van Rossume5c691a2003-03-07 15:13:17 +00002448 et = (PyHeapTypeObject *)type;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002449 Py_XDECREF(type->tp_base);
2450 Py_XDECREF(type->tp_dict);
2451 Py_XDECREF(type->tp_bases);
2452 Py_XDECREF(type->tp_mro);
Guido van Rossum687ae002001-10-15 22:03:32 +00002453 Py_XDECREF(type->tp_cache);
Guido van Rossum1c450732001-10-08 15:18:27 +00002454 Py_XDECREF(type->tp_subclasses);
Guido van Rossumd8faa362007-04-27 19:54:29 +00002455 /* A type's tp_doc is heap allocated, unlike the tp_doc slots
2456 * of most other objects. It's okay to cast it to char *.
2457 */
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00002458 PyObject_Free((char *)type->tp_doc);
Georg Brandlc255c7b2006-02-20 22:27:28 +00002459 Py_XDECREF(et->ht_name);
2460 Py_XDECREF(et->ht_slots);
Christian Heimes90aa7642007-12-19 02:45:37 +00002461 Py_TYPE(type)->tp_free((PyObject *)type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002462}
2463
Guido van Rossum1c450732001-10-08 15:18:27 +00002464static PyObject *
2465type_subclasses(PyTypeObject *type, PyObject *args_ignored)
2466{
2467 PyObject *list, *raw, *ref;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002468 Py_ssize_t i, n;
Guido van Rossum1c450732001-10-08 15:18:27 +00002469
2470 list = PyList_New(0);
2471 if (list == NULL)
2472 return NULL;
2473 raw = type->tp_subclasses;
2474 if (raw == NULL)
2475 return list;
2476 assert(PyList_Check(raw));
2477 n = PyList_GET_SIZE(raw);
2478 for (i = 0; i < n; i++) {
2479 ref = PyList_GET_ITEM(raw, i);
Tim Peters44383382001-10-08 16:49:26 +00002480 assert(PyWeakref_CheckRef(ref));
Guido van Rossum1c450732001-10-08 15:18:27 +00002481 ref = PyWeakref_GET_OBJECT(ref);
2482 if (ref != Py_None) {
2483 if (PyList_Append(list, ref) < 0) {
2484 Py_DECREF(list);
2485 return NULL;
2486 }
2487 }
2488 }
2489 return list;
2490}
2491
Guido van Rossum47374822007-08-02 16:48:17 +00002492static PyObject *
2493type_prepare(PyObject *self, PyObject *args, PyObject *kwds)
2494{
2495 return PyDict_New();
2496}
2497
Tim Peters6d6c1a32001-08-02 04:15:00 +00002498static PyMethodDef type_methods[] = {
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002499 {"mro", (PyCFunction)mro_external, METH_NOARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002500 PyDoc_STR("mro() -> list\nreturn a type's method resolution order")},
Guido van Rossum1c450732001-10-08 15:18:27 +00002501 {"__subclasses__", (PyCFunction)type_subclasses, METH_NOARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002502 PyDoc_STR("__subclasses__() -> list of immediate subclasses")},
Guido van Rossum47374822007-08-02 16:48:17 +00002503 {"__prepare__", (PyCFunction)type_prepare,
2504 METH_VARARGS | METH_KEYWORDS | METH_CLASS,
2505 PyDoc_STR("__prepare__() -> dict\n"
2506 "used to create the namespace for the class statement")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002507 {0}
2508};
2509
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002510PyDoc_STRVAR(type_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00002511"type(object) -> the object's type\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002512"type(name, bases, dict) -> a new type");
Tim Peters6d6c1a32001-08-02 04:15:00 +00002513
Guido van Rossum048eb752001-10-02 21:24:57 +00002514static int
2515type_traverse(PyTypeObject *type, visitproc visit, void *arg)
2516{
Guido van Rossuma3862092002-06-10 15:24:42 +00002517 /* Because of type_is_gc(), the collector only calls this
2518 for heaptypes. */
2519 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002520
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002521 Py_VISIT(type->tp_dict);
2522 Py_VISIT(type->tp_cache);
2523 Py_VISIT(type->tp_mro);
2524 Py_VISIT(type->tp_bases);
2525 Py_VISIT(type->tp_base);
Guido van Rossuma3862092002-06-10 15:24:42 +00002526
2527 /* There's no need to visit type->tp_subclasses or
Georg Brandlc255c7b2006-02-20 22:27:28 +00002528 ((PyHeapTypeObject *)type)->ht_slots, because they can't be involved
Guido van Rossuma3862092002-06-10 15:24:42 +00002529 in cycles; tp_subclasses is a list of weak references,
2530 and slots is a tuple of strings. */
Guido van Rossum048eb752001-10-02 21:24:57 +00002531
Guido van Rossum048eb752001-10-02 21:24:57 +00002532 return 0;
2533}
2534
2535static int
2536type_clear(PyTypeObject *type)
2537{
Guido van Rossuma3862092002-06-10 15:24:42 +00002538 /* Because of type_is_gc(), the collector only calls this
2539 for heaptypes. */
2540 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002541
Guido van Rossuma3862092002-06-10 15:24:42 +00002542 /* The only field we need to clear is tp_mro, which is part of a
2543 hard cycle (its first element is the class itself) that won't
2544 be broken otherwise (it's a tuple and tuples don't have a
2545 tp_clear handler). None of the other fields need to be
2546 cleared, and here's why:
Guido van Rossum048eb752001-10-02 21:24:57 +00002547
Guido van Rossuma3862092002-06-10 15:24:42 +00002548 tp_dict:
2549 It is a dict, so the collector will call its tp_clear.
2550
2551 tp_cache:
2552 Not used; if it were, it would be a dict.
2553
2554 tp_bases, tp_base:
2555 If these are involved in a cycle, there must be at least
2556 one other, mutable object in the cycle, e.g. a base
2557 class's dict; the cycle will be broken that way.
2558
2559 tp_subclasses:
2560 A list of weak references can't be part of a cycle; and
2561 lists have their own tp_clear.
2562
Guido van Rossume5c691a2003-03-07 15:13:17 +00002563 slots (in PyHeapTypeObject):
Guido van Rossuma3862092002-06-10 15:24:42 +00002564 A tuple of strings can't be part of a cycle.
2565 */
2566
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002567 Py_CLEAR(type->tp_mro);
Guido van Rossum048eb752001-10-02 21:24:57 +00002568
2569 return 0;
2570}
2571
2572static int
2573type_is_gc(PyTypeObject *type)
2574{
2575 return type->tp_flags & Py_TPFLAGS_HEAPTYPE;
2576}
2577
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002578PyTypeObject PyType_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002579 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002580 "type", /* tp_name */
Guido van Rossume5c691a2003-03-07 15:13:17 +00002581 sizeof(PyHeapTypeObject), /* tp_basicsize */
Guido van Rossum6f799372001-09-20 20:46:19 +00002582 sizeof(PyMemberDef), /* tp_itemsize */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002583 (destructor)type_dealloc, /* tp_dealloc */
2584 0, /* tp_print */
Guido van Rossumd8faa362007-04-27 19:54:29 +00002585 0, /* tp_getattr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002586 0, /* tp_setattr */
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002587 0, /* tp_compare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002588 (reprfunc)type_repr, /* tp_repr */
2589 0, /* tp_as_number */
2590 0, /* tp_as_sequence */
2591 0, /* tp_as_mapping */
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002592 0, /* tp_hash */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002593 (ternaryfunc)type_call, /* tp_call */
2594 0, /* tp_str */
2595 (getattrofunc)type_getattro, /* tp_getattro */
2596 (setattrofunc)type_setattro, /* tp_setattro */
2597 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00002598 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
Thomas Wouters27d517b2007-02-25 20:39:11 +00002599 Py_TPFLAGS_BASETYPE | Py_TPFLAGS_TYPE_SUBCLASS, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002600 type_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00002601 (traverseproc)type_traverse, /* tp_traverse */
2602 (inquiry)type_clear, /* tp_clear */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002603 0, /* tp_richcompare */
Guido van Rossum1c450732001-10-08 15:18:27 +00002604 offsetof(PyTypeObject, tp_weaklist), /* tp_weaklistoffset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002605 0, /* tp_iter */
2606 0, /* tp_iternext */
2607 type_methods, /* tp_methods */
2608 type_members, /* tp_members */
2609 type_getsets, /* tp_getset */
2610 0, /* tp_base */
2611 0, /* tp_dict */
2612 0, /* tp_descr_get */
2613 0, /* tp_descr_set */
2614 offsetof(PyTypeObject, tp_dict), /* tp_dictoffset */
Guido van Rossumd8faa362007-04-27 19:54:29 +00002615 type_init, /* tp_init */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002616 0, /* tp_alloc */
2617 type_new, /* tp_new */
Guido van Rossumd8faa362007-04-27 19:54:29 +00002618 PyObject_GC_Del, /* tp_free */
Guido van Rossum048eb752001-10-02 21:24:57 +00002619 (inquiry)type_is_gc, /* tp_is_gc */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002620};
Tim Peters6d6c1a32001-08-02 04:15:00 +00002621
2622
2623/* The base type of all types (eventually)... except itself. */
2624
Guido van Rossumd8faa362007-04-27 19:54:29 +00002625/* You may wonder why object.__new__() only complains about arguments
2626 when object.__init__() is not overridden, and vice versa.
2627
2628 Consider the use cases:
2629
2630 1. When neither is overridden, we want to hear complaints about
2631 excess (i.e., any) arguments, since their presence could
2632 indicate there's a bug.
2633
2634 2. When defining an Immutable type, we are likely to override only
2635 __new__(), since __init__() is called too late to initialize an
2636 Immutable object. Since __new__() defines the signature for the
2637 type, it would be a pain to have to override __init__() just to
2638 stop it from complaining about excess arguments.
2639
2640 3. When defining a Mutable type, we are likely to override only
2641 __init__(). So here the converse reasoning applies: we don't
2642 want to have to override __new__() just to stop it from
2643 complaining.
2644
2645 4. When __init__() is overridden, and the subclass __init__() calls
2646 object.__init__(), the latter should complain about excess
2647 arguments; ditto for __new__().
2648
2649 Use cases 2 and 3 make it unattractive to unconditionally check for
2650 excess arguments. The best solution that addresses all four use
2651 cases is as follows: __init__() complains about excess arguments
2652 unless __new__() is overridden and __init__() is not overridden
2653 (IOW, if __init__() is overridden or __new__() is not overridden);
2654 symmetrically, __new__() complains about excess arguments unless
2655 __init__() is overridden and __new__() is not overridden
2656 (IOW, if __new__() is overridden or __init__() is not overridden).
2657
2658 However, for backwards compatibility, this breaks too much code.
2659 Therefore, in 2.6, we'll *warn* about excess arguments when both
2660 methods are overridden; for all other cases we'll use the above
2661 rules.
2662
2663*/
2664
2665/* Forward */
2666static PyObject *
2667object_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
2668
2669static int
2670excess_args(PyObject *args, PyObject *kwds)
2671{
2672 return PyTuple_GET_SIZE(args) ||
2673 (kwds && PyDict_Check(kwds) && PyDict_Size(kwds));
2674}
2675
Tim Peters6d6c1a32001-08-02 04:15:00 +00002676static int
2677object_init(PyObject *self, PyObject *args, PyObject *kwds)
2678{
Guido van Rossumd8faa362007-04-27 19:54:29 +00002679 int err = 0;
2680 if (excess_args(args, kwds)) {
Christian Heimes90aa7642007-12-19 02:45:37 +00002681 PyTypeObject *type = Py_TYPE(self);
Guido van Rossumd8faa362007-04-27 19:54:29 +00002682 if (type->tp_init != object_init &&
2683 type->tp_new != object_new)
2684 {
2685 err = PyErr_WarnEx(PyExc_DeprecationWarning,
2686 "object.__init__() takes no parameters",
2687 1);
2688 }
2689 else if (type->tp_init != object_init ||
2690 type->tp_new == object_new)
2691 {
2692 PyErr_SetString(PyExc_TypeError,
2693 "object.__init__() takes no parameters");
2694 err = -1;
2695 }
2696 }
2697 return err;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002698}
2699
Guido van Rossum298e4212003-02-13 16:30:16 +00002700static PyObject *
2701object_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2702{
Guido van Rossumd8faa362007-04-27 19:54:29 +00002703 int err = 0;
2704 if (excess_args(args, kwds)) {
2705 if (type->tp_new != object_new &&
2706 type->tp_init != object_init)
2707 {
2708 err = PyErr_WarnEx(PyExc_DeprecationWarning,
2709 "object.__new__() takes no parameters",
2710 1);
2711 }
2712 else if (type->tp_new != object_new ||
2713 type->tp_init == object_init)
2714 {
2715 PyErr_SetString(PyExc_TypeError,
2716 "object.__new__() takes no parameters");
2717 err = -1;
2718 }
Guido van Rossum298e4212003-02-13 16:30:16 +00002719 }
Guido van Rossumd8faa362007-04-27 19:54:29 +00002720 if (err < 0)
2721 return NULL;
Christian Heimes9e7f1d22008-02-28 12:27:11 +00002722
2723 if (type->tp_flags & Py_TPFLAGS_IS_ABSTRACT) {
2724 static PyObject *comma = NULL;
2725 PyObject *abstract_methods = NULL;
2726 PyObject *builtins;
2727 PyObject *sorted;
2728 PyObject *sorted_methods = NULL;
2729 PyObject *joined = NULL;
2730
2731 /* Compute ", ".join(sorted(type.__abstractmethods__))
2732 into joined. */
2733 abstract_methods = type_abstractmethods(type, NULL);
2734 if (abstract_methods == NULL)
2735 goto error;
2736 builtins = PyEval_GetBuiltins();
2737 if (builtins == NULL)
2738 goto error;
2739 sorted = PyDict_GetItemString(builtins, "sorted");
2740 if (sorted == NULL)
2741 goto error;
2742 sorted_methods = PyObject_CallFunctionObjArgs(sorted,
2743 abstract_methods,
2744 NULL);
2745 if (sorted_methods == NULL)
2746 goto error;
2747 if (comma == NULL) {
2748 comma = PyUnicode_InternFromString(", ");
2749 if (comma == NULL)
2750 goto error;
2751 }
2752 joined = PyObject_CallMethod(comma, "join",
2753 "O", sorted_methods);
2754 if (joined == NULL)
2755 goto error;
2756
2757 PyErr_Format(PyExc_TypeError,
2758 "Can't instantiate abstract class %s "
2759 "with abstract methods %U",
2760 type->tp_name,
2761 joined);
2762 error:
2763 Py_XDECREF(joined);
2764 Py_XDECREF(sorted_methods);
2765 Py_XDECREF(abstract_methods);
2766 return NULL;
2767 }
Guido van Rossum298e4212003-02-13 16:30:16 +00002768 return type->tp_alloc(type, 0);
2769}
2770
Tim Peters6d6c1a32001-08-02 04:15:00 +00002771static void
2772object_dealloc(PyObject *self)
2773{
Christian Heimes90aa7642007-12-19 02:45:37 +00002774 Py_TYPE(self)->tp_free(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002775}
2776
Guido van Rossum8e248182001-08-12 05:17:56 +00002777static PyObject *
2778object_repr(PyObject *self)
2779{
Guido van Rossum76e69632001-08-16 18:52:43 +00002780 PyTypeObject *type;
Barry Warsaw7ce36942001-08-24 18:34:26 +00002781 PyObject *mod, *name, *rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00002782
Christian Heimes90aa7642007-12-19 02:45:37 +00002783 type = Py_TYPE(self);
Guido van Rossum76e69632001-08-16 18:52:43 +00002784 mod = type_module(type, NULL);
2785 if (mod == NULL)
2786 PyErr_Clear();
Martin v. Löwis5b222132007-06-10 09:51:05 +00002787 else if (!PyUnicode_Check(mod)) {
Guido van Rossum76e69632001-08-16 18:52:43 +00002788 Py_DECREF(mod);
2789 mod = NULL;
2790 }
2791 name = type_name(type, NULL);
2792 if (name == NULL)
2793 return NULL;
Georg Brandl1a3284e2007-12-02 09:40:06 +00002794 if (mod != NULL && PyUnicode_CompareWithASCIIString(mod, "builtins"))
Walter Dörwald4dbd01b2007-06-11 14:03:45 +00002795 rtn = PyUnicode_FromFormat("<%U.%U object at %p>", mod, name, self);
Guido van Rossum76e69632001-08-16 18:52:43 +00002796 else
Walter Dörwald1ab83302007-05-18 17:15:44 +00002797 rtn = PyUnicode_FromFormat("<%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00002798 type->tp_name, self);
Guido van Rossum76e69632001-08-16 18:52:43 +00002799 Py_XDECREF(mod);
2800 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +00002801 return rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00002802}
2803
Guido van Rossumb8f63662001-08-15 23:57:02 +00002804static PyObject *
2805object_str(PyObject *self)
2806{
2807 unaryfunc f;
2808
Christian Heimes90aa7642007-12-19 02:45:37 +00002809 f = Py_TYPE(self)->tp_repr;
Guido van Rossumb8f63662001-08-15 23:57:02 +00002810 if (f == NULL)
2811 f = object_repr;
2812 return f(self);
2813}
2814
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002815static PyObject *
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002816object_richcompare(PyObject *self, PyObject *other, int op)
2817{
2818 PyObject *res;
2819
2820 switch (op) {
2821
2822 case Py_EQ:
Guido van Rossumab078dd2008-01-06 00:09:11 +00002823 /* Return NotImplemented instead of False, so if two
2824 objects are compared, both get a chance at the
2825 comparison. See issue #1393. */
2826 res = (self == other) ? Py_True : Py_NotImplemented;
Guido van Rossum6b18a5b2007-03-29 20:49:57 +00002827 Py_INCREF(res);
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002828 break;
2829
2830 case Py_NE:
Guido van Rossume27dc722007-03-27 22:37:34 +00002831 /* By default, != returns the opposite of ==,
2832 unless the latter returns NotImplemented. */
2833 res = PyObject_RichCompare(self, other, Py_EQ);
2834 if (res != NULL && res != Py_NotImplemented) {
2835 int ok = PyObject_IsTrue(res);
2836 Py_DECREF(res);
2837 if (ok < 0)
2838 res = NULL;
2839 else {
2840 if (ok)
2841 res = Py_False;
2842 else
2843 res = Py_True;
2844 Py_INCREF(res);
2845 }
2846 }
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002847 break;
2848
2849 default:
2850 res = Py_NotImplemented;
Guido van Rossum6b18a5b2007-03-29 20:49:57 +00002851 Py_INCREF(res);
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002852 break;
2853 }
2854
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002855 return res;
2856}
2857
2858static PyObject *
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002859object_get_class(PyObject *self, void *closure)
2860{
Christian Heimes90aa7642007-12-19 02:45:37 +00002861 Py_INCREF(Py_TYPE(self));
2862 return (PyObject *)(Py_TYPE(self));
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002863}
2864
2865static int
2866equiv_structs(PyTypeObject *a, PyTypeObject *b)
2867{
2868 return a == b ||
2869 (a != NULL &&
2870 b != NULL &&
2871 a->tp_basicsize == b->tp_basicsize &&
2872 a->tp_itemsize == b->tp_itemsize &&
2873 a->tp_dictoffset == b->tp_dictoffset &&
2874 a->tp_weaklistoffset == b->tp_weaklistoffset &&
2875 ((a->tp_flags & Py_TPFLAGS_HAVE_GC) ==
2876 (b->tp_flags & Py_TPFLAGS_HAVE_GC)));
2877}
2878
2879static int
2880same_slots_added(PyTypeObject *a, PyTypeObject *b)
2881{
2882 PyTypeObject *base = a->tp_base;
Martin v. Löwiseb079f12006-02-16 14:32:27 +00002883 Py_ssize_t size;
Guido van Rossumd8faa362007-04-27 19:54:29 +00002884 PyObject *slots_a, *slots_b;
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002885
2886 if (base != b->tp_base)
2887 return 0;
2888 if (equiv_structs(a, base) && equiv_structs(b, base))
2889 return 1;
2890 size = base->tp_basicsize;
2891 if (a->tp_dictoffset == size && b->tp_dictoffset == size)
2892 size += sizeof(PyObject *);
2893 if (a->tp_weaklistoffset == size && b->tp_weaklistoffset == size)
2894 size += sizeof(PyObject *);
Guido van Rossumd8faa362007-04-27 19:54:29 +00002895
2896 /* Check slots compliance */
2897 slots_a = ((PyHeapTypeObject *)a)->ht_slots;
2898 slots_b = ((PyHeapTypeObject *)b)->ht_slots;
2899 if (slots_a && slots_b) {
2900 if (PyObject_Compare(slots_a, slots_b) != 0)
2901 return 0;
2902 size += sizeof(PyObject *) * PyTuple_GET_SIZE(slots_a);
2903 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002904 return size == a->tp_basicsize && size == b->tp_basicsize;
2905}
2906
2907static int
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002908compatible_for_assignment(PyTypeObject* oldto, PyTypeObject* newto, char* attr)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002909{
2910 PyTypeObject *newbase, *oldbase;
2911
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002912 if (newto->tp_dealloc != oldto->tp_dealloc ||
2913 newto->tp_free != oldto->tp_free)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002914 {
2915 PyErr_Format(PyExc_TypeError,
2916 "%s assignment: "
2917 "'%s' deallocator differs from '%s'",
2918 attr,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002919 newto->tp_name,
2920 oldto->tp_name);
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002921 return 0;
2922 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002923 newbase = newto;
2924 oldbase = oldto;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002925 while (equiv_structs(newbase, newbase->tp_base))
2926 newbase = newbase->tp_base;
2927 while (equiv_structs(oldbase, oldbase->tp_base))
2928 oldbase = oldbase->tp_base;
2929 if (newbase != oldbase &&
2930 (newbase->tp_base != oldbase->tp_base ||
2931 !same_slots_added(newbase, oldbase))) {
2932 PyErr_Format(PyExc_TypeError,
2933 "%s assignment: "
2934 "'%s' object layout differs from '%s'",
2935 attr,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002936 newto->tp_name,
2937 oldto->tp_name);
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002938 return 0;
2939 }
Tim Petersea7f75d2002-12-07 21:39:16 +00002940
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002941 return 1;
2942}
2943
2944static int
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002945object_set_class(PyObject *self, PyObject *value, void *closure)
2946{
Christian Heimes90aa7642007-12-19 02:45:37 +00002947 PyTypeObject *oldto = Py_TYPE(self);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002948 PyTypeObject *newto;
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002949
Guido van Rossumb6b89422002-04-15 01:03:30 +00002950 if (value == NULL) {
2951 PyErr_SetString(PyExc_TypeError,
2952 "can't delete __class__ attribute");
2953 return -1;
2954 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002955 if (!PyType_Check(value)) {
2956 PyErr_Format(PyExc_TypeError,
2957 "__class__ must be set to new-style class, not '%s' object",
Christian Heimes90aa7642007-12-19 02:45:37 +00002958 Py_TYPE(value)->tp_name);
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002959 return -1;
2960 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002961 newto = (PyTypeObject *)value;
2962 if (!(newto->tp_flags & Py_TPFLAGS_HEAPTYPE) ||
2963 !(oldto->tp_flags & Py_TPFLAGS_HEAPTYPE))
Guido van Rossum40af8892002-08-10 05:42:07 +00002964 {
2965 PyErr_Format(PyExc_TypeError,
2966 "__class__ assignment: only for heap types");
2967 return -1;
2968 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002969 if (compatible_for_assignment(newto, oldto, "__class__")) {
2970 Py_INCREF(newto);
Christian Heimes90aa7642007-12-19 02:45:37 +00002971 Py_TYPE(self) = newto;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002972 Py_DECREF(oldto);
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002973 return 0;
2974 }
2975 else {
Guido van Rossum9ee4b942002-05-24 18:47:47 +00002976 return -1;
2977 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002978}
2979
2980static PyGetSetDef object_getsets[] = {
2981 {"__class__", object_get_class, object_set_class,
Neal Norwitz858e34f2002-08-13 17:18:45 +00002982 PyDoc_STR("the object's class")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002983 {0}
2984};
2985
Guido van Rossumc53f0092003-02-18 22:05:12 +00002986
Guido van Rossum036f9992003-02-21 22:02:54 +00002987/* Stuff to implement __reduce_ex__ for pickle protocols >= 2.
Alexandre Vassalottif7fa63d2008-05-11 08:55:36 +00002988 We fall back to helpers in copyreg for:
Guido van Rossum036f9992003-02-21 22:02:54 +00002989 - pickle protocols < 2
2990 - calculating the list of slot names (done only once per class)
2991 - the __newobj__ function (which is used as a token but never called)
2992*/
2993
2994static PyObject *
Alexandre Vassalottif7fa63d2008-05-11 08:55:36 +00002995import_copyreg(void)
Guido van Rossum036f9992003-02-21 22:02:54 +00002996{
Alexandre Vassalottif7fa63d2008-05-11 08:55:36 +00002997 static PyObject *copyreg_str;
Guido van Rossum3926a632001-09-25 16:25:58 +00002998
Alexandre Vassalottif7fa63d2008-05-11 08:55:36 +00002999 if (!copyreg_str) {
3000 copyreg_str = PyUnicode_InternFromString("copyreg");
3001 if (copyreg_str == NULL)
Guido van Rossum3926a632001-09-25 16:25:58 +00003002 return NULL;
3003 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003004
Alexandre Vassalottif7fa63d2008-05-11 08:55:36 +00003005 return PyImport_Import(copyreg_str);
Guido van Rossum036f9992003-02-21 22:02:54 +00003006}
3007
3008static PyObject *
3009slotnames(PyObject *cls)
3010{
3011 PyObject *clsdict;
Alexandre Vassalottif7fa63d2008-05-11 08:55:36 +00003012 PyObject *copyreg;
Guido van Rossum036f9992003-02-21 22:02:54 +00003013 PyObject *slotnames;
3014
3015 if (!PyType_Check(cls)) {
3016 Py_INCREF(Py_None);
3017 return Py_None;
3018 }
3019
3020 clsdict = ((PyTypeObject *)cls)->tp_dict;
3021 slotnames = PyDict_GetItemString(clsdict, "__slotnames__");
Armin Rigoec862b92005-09-24 22:58:41 +00003022 if (slotnames != NULL && PyList_Check(slotnames)) {
Guido van Rossum036f9992003-02-21 22:02:54 +00003023 Py_INCREF(slotnames);
3024 return slotnames;
3025 }
3026
Alexandre Vassalottif7fa63d2008-05-11 08:55:36 +00003027 copyreg = import_copyreg();
3028 if (copyreg == NULL)
Guido van Rossum036f9992003-02-21 22:02:54 +00003029 return NULL;
3030
Alexandre Vassalottif7fa63d2008-05-11 08:55:36 +00003031 slotnames = PyObject_CallMethod(copyreg, "_slotnames", "O", cls);
3032 Py_DECREF(copyreg);
Guido van Rossum036f9992003-02-21 22:02:54 +00003033 if (slotnames != NULL &&
3034 slotnames != Py_None &&
3035 !PyList_Check(slotnames))
3036 {
3037 PyErr_SetString(PyExc_TypeError,
Alexandre Vassalottif7fa63d2008-05-11 08:55:36 +00003038 "copyreg._slotnames didn't return a list or None");
Guido van Rossum036f9992003-02-21 22:02:54 +00003039 Py_DECREF(slotnames);
3040 slotnames = NULL;
3041 }
3042
3043 return slotnames;
3044}
3045
3046static PyObject *
3047reduce_2(PyObject *obj)
3048{
3049 PyObject *cls, *getnewargs;
3050 PyObject *args = NULL, *args2 = NULL;
3051 PyObject *getstate = NULL, *state = NULL, *names = NULL;
3052 PyObject *slots = NULL, *listitems = NULL, *dictitems = NULL;
Alexandre Vassalottif7fa63d2008-05-11 08:55:36 +00003053 PyObject *copyreg = NULL, *newobj = NULL, *res = NULL;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003054 Py_ssize_t i, n;
Guido van Rossum036f9992003-02-21 22:02:54 +00003055
3056 cls = PyObject_GetAttrString(obj, "__class__");
3057 if (cls == NULL)
3058 return NULL;
3059
3060 getnewargs = PyObject_GetAttrString(obj, "__getnewargs__");
3061 if (getnewargs != NULL) {
3062 args = PyObject_CallObject(getnewargs, NULL);
3063 Py_DECREF(getnewargs);
3064 if (args != NULL && !PyTuple_Check(args)) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003065 PyErr_Format(PyExc_TypeError,
3066 "__getnewargs__ should return a tuple, "
Christian Heimes90aa7642007-12-19 02:45:37 +00003067 "not '%.200s'", Py_TYPE(args)->tp_name);
Guido van Rossum036f9992003-02-21 22:02:54 +00003068 goto end;
3069 }
3070 }
3071 else {
3072 PyErr_Clear();
3073 args = PyTuple_New(0);
3074 }
3075 if (args == NULL)
3076 goto end;
3077
3078 getstate = PyObject_GetAttrString(obj, "__getstate__");
3079 if (getstate != NULL) {
3080 state = PyObject_CallObject(getstate, NULL);
3081 Py_DECREF(getstate);
Neal Norwitze2fdc612003-06-08 13:19:58 +00003082 if (state == NULL)
3083 goto end;
Guido van Rossum036f9992003-02-21 22:02:54 +00003084 }
3085 else {
Jim Fulton8a1a5942004-02-08 04:21:26 +00003086 PyErr_Clear();
Guido van Rossum036f9992003-02-21 22:02:54 +00003087 state = PyObject_GetAttrString(obj, "__dict__");
3088 if (state == NULL) {
3089 PyErr_Clear();
3090 state = Py_None;
3091 Py_INCREF(state);
3092 }
3093 names = slotnames(cls);
3094 if (names == NULL)
3095 goto end;
3096 if (names != Py_None) {
3097 assert(PyList_Check(names));
3098 slots = PyDict_New();
3099 if (slots == NULL)
3100 goto end;
3101 n = 0;
3102 /* Can't pre-compute the list size; the list
3103 is stored on the class so accessible to other
3104 threads, which may be run by DECREF */
3105 for (i = 0; i < PyList_GET_SIZE(names); i++) {
3106 PyObject *name, *value;
3107 name = PyList_GET_ITEM(names, i);
3108 value = PyObject_GetAttr(obj, name);
3109 if (value == NULL)
3110 PyErr_Clear();
3111 else {
3112 int err = PyDict_SetItem(slots, name,
3113 value);
3114 Py_DECREF(value);
3115 if (err)
3116 goto end;
3117 n++;
3118 }
3119 }
3120 if (n) {
3121 state = Py_BuildValue("(NO)", state, slots);
3122 if (state == NULL)
3123 goto end;
3124 }
3125 }
3126 }
3127
3128 if (!PyList_Check(obj)) {
3129 listitems = Py_None;
3130 Py_INCREF(listitems);
3131 }
3132 else {
3133 listitems = PyObject_GetIter(obj);
3134 if (listitems == NULL)
3135 goto end;
3136 }
3137
3138 if (!PyDict_Check(obj)) {
3139 dictitems = Py_None;
3140 Py_INCREF(dictitems);
3141 }
3142 else {
Guido van Rossumcc2b0162007-02-11 06:12:03 +00003143 PyObject *items = PyObject_CallMethod(obj, "items", "");
3144 if (items == NULL)
3145 goto end;
3146 dictitems = PyObject_GetIter(items);
3147 Py_DECREF(items);
Guido van Rossum036f9992003-02-21 22:02:54 +00003148 if (dictitems == NULL)
3149 goto end;
3150 }
3151
Alexandre Vassalottif7fa63d2008-05-11 08:55:36 +00003152 copyreg = import_copyreg();
3153 if (copyreg == NULL)
Guido van Rossum036f9992003-02-21 22:02:54 +00003154 goto end;
Alexandre Vassalottif7fa63d2008-05-11 08:55:36 +00003155 newobj = PyObject_GetAttrString(copyreg, "__newobj__");
Guido van Rossum036f9992003-02-21 22:02:54 +00003156 if (newobj == NULL)
3157 goto end;
3158
3159 n = PyTuple_GET_SIZE(args);
3160 args2 = PyTuple_New(n+1);
3161 if (args2 == NULL)
3162 goto end;
3163 PyTuple_SET_ITEM(args2, 0, cls);
3164 cls = NULL;
3165 for (i = 0; i < n; i++) {
3166 PyObject *v = PyTuple_GET_ITEM(args, i);
3167 Py_INCREF(v);
3168 PyTuple_SET_ITEM(args2, i+1, v);
3169 }
3170
Raymond Hettinger8ae46892003-10-12 19:09:37 +00003171 res = PyTuple_Pack(5, newobj, args2, state, listitems, dictitems);
Guido van Rossum036f9992003-02-21 22:02:54 +00003172
3173 end:
3174 Py_XDECREF(cls);
3175 Py_XDECREF(args);
3176 Py_XDECREF(args2);
Jeremy Hyltond06483c2003-04-09 21:01:42 +00003177 Py_XDECREF(slots);
Guido van Rossum036f9992003-02-21 22:02:54 +00003178 Py_XDECREF(state);
3179 Py_XDECREF(names);
3180 Py_XDECREF(listitems);
3181 Py_XDECREF(dictitems);
Alexandre Vassalottif7fa63d2008-05-11 08:55:36 +00003182 Py_XDECREF(copyreg);
Guido van Rossum036f9992003-02-21 22:02:54 +00003183 Py_XDECREF(newobj);
3184 return res;
3185}
3186
Guido van Rossumd8faa362007-04-27 19:54:29 +00003187/*
3188 * There were two problems when object.__reduce__ and object.__reduce_ex__
3189 * were implemented in the same function:
3190 * - trying to pickle an object with a custom __reduce__ method that
3191 * fell back to object.__reduce__ in certain circumstances led to
3192 * infinite recursion at Python level and eventual RuntimeError.
3193 * - Pickling objects that lied about their type by overwriting the
3194 * __class__ descriptor could lead to infinite recursion at C level
3195 * and eventual segfault.
3196 *
3197 * Because of backwards compatibility, the two methods still have to
3198 * behave in the same way, even if this is not required by the pickle
3199 * protocol. This common functionality was moved to the _common_reduce
3200 * function.
3201 */
3202static PyObject *
3203_common_reduce(PyObject *self, int proto)
3204{
Alexandre Vassalottif7fa63d2008-05-11 08:55:36 +00003205 PyObject *copyreg, *res;
Guido van Rossumd8faa362007-04-27 19:54:29 +00003206
3207 if (proto >= 2)
3208 return reduce_2(self);
3209
Alexandre Vassalottif7fa63d2008-05-11 08:55:36 +00003210 copyreg = import_copyreg();
3211 if (!copyreg)
Guido van Rossumd8faa362007-04-27 19:54:29 +00003212 return NULL;
3213
Alexandre Vassalottif7fa63d2008-05-11 08:55:36 +00003214 res = PyEval_CallMethod(copyreg, "_reduce_ex", "(Oi)", self, proto);
3215 Py_DECREF(copyreg);
Guido van Rossumd8faa362007-04-27 19:54:29 +00003216
3217 return res;
3218}
3219
3220static PyObject *
3221object_reduce(PyObject *self, PyObject *args)
3222{
3223 int proto = 0;
3224
3225 if (!PyArg_ParseTuple(args, "|i:__reduce__", &proto))
3226 return NULL;
3227
3228 return _common_reduce(self, proto);
3229}
3230
Guido van Rossum036f9992003-02-21 22:02:54 +00003231static PyObject *
3232object_reduce_ex(PyObject *self, PyObject *args)
3233{
Guido van Rossumd8faa362007-04-27 19:54:29 +00003234 PyObject *reduce, *res;
Guido van Rossum036f9992003-02-21 22:02:54 +00003235 int proto = 0;
3236
3237 if (!PyArg_ParseTuple(args, "|i:__reduce_ex__", &proto))
3238 return NULL;
3239
3240 reduce = PyObject_GetAttrString(self, "__reduce__");
3241 if (reduce == NULL)
3242 PyErr_Clear();
3243 else {
3244 PyObject *cls, *clsreduce, *objreduce;
3245 int override;
3246 cls = PyObject_GetAttrString(self, "__class__");
3247 if (cls == NULL) {
3248 Py_DECREF(reduce);
3249 return NULL;
3250 }
3251 clsreduce = PyObject_GetAttrString(cls, "__reduce__");
3252 Py_DECREF(cls);
3253 if (clsreduce == NULL) {
3254 Py_DECREF(reduce);
3255 return NULL;
3256 }
3257 objreduce = PyDict_GetItemString(PyBaseObject_Type.tp_dict,
3258 "__reduce__");
3259 override = (clsreduce != objreduce);
3260 Py_DECREF(clsreduce);
3261 if (override) {
3262 res = PyObject_CallObject(reduce, NULL);
3263 Py_DECREF(reduce);
3264 return res;
3265 }
3266 else
3267 Py_DECREF(reduce);
3268 }
3269
Guido van Rossumd8faa362007-04-27 19:54:29 +00003270 return _common_reduce(self, proto);
Guido van Rossum3926a632001-09-25 16:25:58 +00003271}
3272
Christian Heimes9e7f1d22008-02-28 12:27:11 +00003273static PyObject *
3274object_subclasshook(PyObject *cls, PyObject *args)
3275{
3276 Py_INCREF(Py_NotImplemented);
3277 return Py_NotImplemented;
3278}
3279
3280PyDoc_STRVAR(object_subclasshook_doc,
3281"Abstract classes can override this to customize issubclass().\n"
3282"\n"
3283"This is invoked early on by abc.ABCMeta.__subclasscheck__().\n"
3284"It should return True, False or NotImplemented. If it returns\n"
3285"NotImplemented, the normal algorithm is used. Otherwise, it\n"
3286"overrides the normal algorithm (and the outcome is cached).\n");
Eric Smith8c663262007-08-25 02:26:07 +00003287
3288/*
3289 from PEP 3101, this code implements:
3290
3291 class object:
3292 def __format__(self, format_spec):
3293 return format(str(self), format_spec)
3294*/
3295static PyObject *
3296object_format(PyObject *self, PyObject *args)
3297{
3298 PyObject *format_spec;
3299 PyObject *self_as_str = NULL;
3300 PyObject *result = NULL;
3301 PyObject *format_meth = NULL;
3302
Eric Smithfc6e8fe2008-01-11 00:17:22 +00003303 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
Eric Smith8c663262007-08-25 02:26:07 +00003304 return NULL;
Eric Smith8c663262007-08-25 02:26:07 +00003305
Thomas Heller519a0422007-11-15 20:48:54 +00003306 self_as_str = PyObject_Str(self);
Eric Smith8c663262007-08-25 02:26:07 +00003307 if (self_as_str != NULL) {
3308 /* find the format function */
3309 format_meth = PyObject_GetAttrString(self_as_str, "__format__");
3310 if (format_meth != NULL) {
3311 /* and call it */
3312 result = PyObject_CallFunctionObjArgs(format_meth, format_spec, NULL);
3313 }
3314 }
3315
3316 Py_XDECREF(self_as_str);
3317 Py_XDECREF(format_meth);
3318
3319 return result;
3320}
3321
Martin v. Löwis00709aa2008-06-04 14:18:43 +00003322static PyObject *
3323object_sizeof(PyObject *self, PyObject *args)
3324{
3325 Py_ssize_t res, isize;
3326
3327 res = 0;
3328 isize = self->ob_type->tp_itemsize;
3329 if (isize > 0)
3330 res = Py_SIZE(self->ob_type) * isize;
3331 res += self->ob_type->tp_basicsize;
3332
3333 return PyLong_FromSsize_t(res);
3334}
3335
Guido van Rossum3926a632001-09-25 16:25:58 +00003336static PyMethodDef object_methods[] = {
Guido van Rossumc53f0092003-02-18 22:05:12 +00003337 {"__reduce_ex__", object_reduce_ex, METH_VARARGS,
3338 PyDoc_STR("helper for pickle")},
Guido van Rossumd8faa362007-04-27 19:54:29 +00003339 {"__reduce__", object_reduce, METH_VARARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00003340 PyDoc_STR("helper for pickle")},
Christian Heimes9e7f1d22008-02-28 12:27:11 +00003341 {"__subclasshook__", object_subclasshook, METH_CLASS | METH_VARARGS,
3342 object_subclasshook_doc},
Eric Smith8c663262007-08-25 02:26:07 +00003343 {"__format__", object_format, METH_VARARGS,
3344 PyDoc_STR("default object formatter")},
Martin v. Löwis00709aa2008-06-04 14:18:43 +00003345 {"__sizeof__", object_sizeof, METH_NOARGS,
3346 PyDoc_STR("__sizeof__() -> size of object in memory, in bytes")},
Guido van Rossum3926a632001-09-25 16:25:58 +00003347 {0}
3348};
3349
Guido van Rossum036f9992003-02-21 22:02:54 +00003350
Tim Peters6d6c1a32001-08-02 04:15:00 +00003351PyTypeObject PyBaseObject_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003352 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003353 "object", /* tp_name */
3354 sizeof(PyObject), /* tp_basicsize */
3355 0, /* tp_itemsize */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003356 object_dealloc, /* tp_dealloc */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003357 0, /* tp_print */
Guido van Rossumd8faa362007-04-27 19:54:29 +00003358 0, /* tp_getattr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003359 0, /* tp_setattr */
3360 0, /* tp_compare */
Guido van Rossumb8f63662001-08-15 23:57:02 +00003361 object_repr, /* tp_repr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003362 0, /* tp_as_number */
3363 0, /* tp_as_sequence */
3364 0, /* tp_as_mapping */
Guido van Rossum50e9fb92006-08-17 05:42:55 +00003365 (hashfunc)_Py_HashPointer, /* tp_hash */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003366 0, /* tp_call */
Guido van Rossumb8f63662001-08-15 23:57:02 +00003367 object_str, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003368 PyObject_GenericGetAttr, /* tp_getattro */
Guido van Rossum13d52f02001-08-10 21:24:08 +00003369 PyObject_GenericSetAttr, /* tp_setattro */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003370 0, /* tp_as_buffer */
3371 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Neal Norwitz5dc2a372002-08-13 22:19:13 +00003372 PyDoc_STR("The most base type"), /* tp_doc */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003373 0, /* tp_traverse */
3374 0, /* tp_clear */
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003375 object_richcompare, /* tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003376 0, /* tp_weaklistoffset */
3377 0, /* tp_iter */
3378 0, /* tp_iternext */
Guido van Rossum3926a632001-09-25 16:25:58 +00003379 object_methods, /* tp_methods */
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003380 0, /* tp_members */
3381 object_getsets, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003382 0, /* tp_base */
3383 0, /* tp_dict */
3384 0, /* tp_descr_get */
3385 0, /* tp_descr_set */
3386 0, /* tp_dictoffset */
3387 object_init, /* tp_init */
3388 PyType_GenericAlloc, /* tp_alloc */
Guido van Rossum298e4212003-02-13 16:30:16 +00003389 object_new, /* tp_new */
Guido van Rossumd8faa362007-04-27 19:54:29 +00003390 PyObject_Del, /* tp_free */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003391};
3392
3393
Guido van Rossum50e9fb92006-08-17 05:42:55 +00003394/* Add the methods from tp_methods to the __dict__ in a type object */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003395
3396static int
3397add_methods(PyTypeObject *type, PyMethodDef *meth)
3398{
Guido van Rossum687ae002001-10-15 22:03:32 +00003399 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003400
3401 for (; meth->ml_name != NULL; meth++) {
3402 PyObject *descr;
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00003403 if (PyDict_GetItemString(dict, meth->ml_name) &&
3404 !(meth->ml_flags & METH_COEXIST))
3405 continue;
Fred Drake7bf97152002-03-28 05:33:33 +00003406 if (meth->ml_flags & METH_CLASS) {
3407 if (meth->ml_flags & METH_STATIC) {
3408 PyErr_SetString(PyExc_ValueError,
3409 "method cannot be both class and static");
3410 return -1;
3411 }
Tim Petersbca1cbc2002-12-09 22:56:13 +00003412 descr = PyDescr_NewClassMethod(type, meth);
Fred Drake7bf97152002-03-28 05:33:33 +00003413 }
3414 else if (meth->ml_flags & METH_STATIC) {
Guido van Rossum9af48ff2003-02-11 17:12:46 +00003415 PyObject *cfunc = PyCFunction_New(meth, NULL);
3416 if (cfunc == NULL)
3417 return -1;
3418 descr = PyStaticMethod_New(cfunc);
3419 Py_DECREF(cfunc);
Fred Drake7bf97152002-03-28 05:33:33 +00003420 }
3421 else {
3422 descr = PyDescr_NewMethod(type, meth);
3423 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003424 if (descr == NULL)
3425 return -1;
Fred Drake7bf97152002-03-28 05:33:33 +00003426 if (PyDict_SetItemString(dict, meth->ml_name, descr) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003427 return -1;
3428 Py_DECREF(descr);
3429 }
3430 return 0;
3431}
3432
3433static int
Guido van Rossum6f799372001-09-20 20:46:19 +00003434add_members(PyTypeObject *type, PyMemberDef *memb)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003435{
Guido van Rossum687ae002001-10-15 22:03:32 +00003436 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003437
3438 for (; memb->name != NULL; memb++) {
3439 PyObject *descr;
3440 if (PyDict_GetItemString(dict, memb->name))
3441 continue;
3442 descr = PyDescr_NewMember(type, memb);
3443 if (descr == NULL)
3444 return -1;
3445 if (PyDict_SetItemString(dict, memb->name, descr) < 0)
3446 return -1;
3447 Py_DECREF(descr);
3448 }
3449 return 0;
3450}
3451
3452static int
Guido van Rossum32d34c82001-09-20 21:45:26 +00003453add_getset(PyTypeObject *type, PyGetSetDef *gsp)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003454{
Guido van Rossum687ae002001-10-15 22:03:32 +00003455 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003456
3457 for (; gsp->name != NULL; gsp++) {
3458 PyObject *descr;
3459 if (PyDict_GetItemString(dict, gsp->name))
3460 continue;
3461 descr = PyDescr_NewGetSet(type, gsp);
3462
3463 if (descr == NULL)
3464 return -1;
3465 if (PyDict_SetItemString(dict, gsp->name, descr) < 0)
3466 return -1;
3467 Py_DECREF(descr);
3468 }
3469 return 0;
3470}
3471
Guido van Rossum13d52f02001-08-10 21:24:08 +00003472static void
3473inherit_special(PyTypeObject *type, PyTypeObject *base)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003474{
Martin v. Löwiseb079f12006-02-16 14:32:27 +00003475 Py_ssize_t oldsize, newsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003476
Guido van Rossum13d52f02001-08-10 21:24:08 +00003477 /* Copying basicsize is connected to the GC flags */
Neil Schemenauerc806c882001-08-29 23:54:54 +00003478 oldsize = base->tp_basicsize;
3479 newsize = type->tp_basicsize ? type->tp_basicsize : oldsize;
3480 if (!(type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
3481 (base->tp_flags & Py_TPFLAGS_HAVE_GC) &&
Guido van Rossum13d52f02001-08-10 21:24:08 +00003482 (!type->tp_traverse && !type->tp_clear)) {
Neil Schemenauerc806c882001-08-29 23:54:54 +00003483 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossum13d52f02001-08-10 21:24:08 +00003484 if (type->tp_traverse == NULL)
3485 type->tp_traverse = base->tp_traverse;
3486 if (type->tp_clear == NULL)
3487 type->tp_clear = base->tp_clear;
3488 }
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00003489 {
Guido van Rossumf884b742001-12-17 17:14:22 +00003490 /* The condition below could use some explanation.
3491 It appears that tp_new is not inherited for static types
3492 whose base class is 'object'; this seems to be a precaution
3493 so that old extension types don't suddenly become
3494 callable (object.__new__ wouldn't insure the invariants
3495 that the extension type's own factory function ensures).
3496 Heap types, of course, are under our control, so they do
3497 inherit tp_new; static extension types that specify some
3498 other built-in type as the default are considered
3499 new-style-aware so they also inherit object.__new__. */
Guido van Rossum13d52f02001-08-10 21:24:08 +00003500 if (base != &PyBaseObject_Type ||
3501 (type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
3502 if (type->tp_new == NULL)
3503 type->tp_new = base->tp_new;
3504 }
3505 }
Neil Schemenauerc806c882001-08-29 23:54:54 +00003506 type->tp_basicsize = newsize;
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00003507
3508 /* Copy other non-function slots */
3509
3510#undef COPYVAL
3511#define COPYVAL(SLOT) \
3512 if (type->SLOT == 0) type->SLOT = base->SLOT
3513
3514 COPYVAL(tp_itemsize);
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00003515 COPYVAL(tp_weaklistoffset);
3516 COPYVAL(tp_dictoffset);
Thomas Wouters27d517b2007-02-25 20:39:11 +00003517
3518 /* Setup fast subclass flags */
3519 if (PyType_IsSubtype(base, (PyTypeObject*)PyExc_BaseException))
3520 type->tp_flags |= Py_TPFLAGS_BASE_EXC_SUBCLASS;
3521 else if (PyType_IsSubtype(base, &PyType_Type))
3522 type->tp_flags |= Py_TPFLAGS_TYPE_SUBCLASS;
3523 else if (PyType_IsSubtype(base, &PyLong_Type))
3524 type->tp_flags |= Py_TPFLAGS_LONG_SUBCLASS;
Christian Heimes72b710a2008-05-26 13:28:38 +00003525 else if (PyType_IsSubtype(base, &PyBytes_Type))
3526 type->tp_flags |= Py_TPFLAGS_BYTES_SUBCLASS;
Thomas Wouters27d517b2007-02-25 20:39:11 +00003527 else if (PyType_IsSubtype(base, &PyUnicode_Type))
3528 type->tp_flags |= Py_TPFLAGS_UNICODE_SUBCLASS;
3529 else if (PyType_IsSubtype(base, &PyTuple_Type))
3530 type->tp_flags |= Py_TPFLAGS_TUPLE_SUBCLASS;
3531 else if (PyType_IsSubtype(base, &PyList_Type))
3532 type->tp_flags |= Py_TPFLAGS_LIST_SUBCLASS;
3533 else if (PyType_IsSubtype(base, &PyDict_Type))
3534 type->tp_flags |= Py_TPFLAGS_DICT_SUBCLASS;
Guido van Rossum13d52f02001-08-10 21:24:08 +00003535}
3536
Guido van Rossumf5243f02008-01-01 04:06:48 +00003537static char *hash_name_op[] = {
Guido van Rossum38938152006-08-21 23:36:26 +00003538 "__eq__",
Guido van Rossum38938152006-08-21 23:36:26 +00003539 "__hash__",
Guido van Rossumf5243f02008-01-01 04:06:48 +00003540 NULL
Guido van Rossum38938152006-08-21 23:36:26 +00003541};
3542
3543static int
Guido van Rossumf5243f02008-01-01 04:06:48 +00003544overrides_hash(PyTypeObject *type)
Guido van Rossum38938152006-08-21 23:36:26 +00003545{
Guido van Rossumf5243f02008-01-01 04:06:48 +00003546 char **p;
Guido van Rossum38938152006-08-21 23:36:26 +00003547 PyObject *dict = type->tp_dict;
3548
3549 assert(dict != NULL);
Guido van Rossumf5243f02008-01-01 04:06:48 +00003550 for (p = hash_name_op; *p; p++) {
3551 if (PyDict_GetItemString(dict, *p) != NULL)
Guido van Rossum38938152006-08-21 23:36:26 +00003552 return 1;
3553 }
3554 return 0;
3555}
3556
Guido van Rossum13d52f02001-08-10 21:24:08 +00003557static void
3558inherit_slots(PyTypeObject *type, PyTypeObject *base)
3559{
3560 PyTypeObject *basebase;
3561
3562#undef SLOTDEFINED
Tim Peters6d6c1a32001-08-02 04:15:00 +00003563#undef COPYSLOT
3564#undef COPYNUM
3565#undef COPYSEQ
3566#undef COPYMAP
Guido van Rossum5af588b2001-10-12 14:13:21 +00003567#undef COPYBUF
Guido van Rossum13d52f02001-08-10 21:24:08 +00003568
3569#define SLOTDEFINED(SLOT) \
3570 (base->SLOT != 0 && \
3571 (basebase == NULL || base->SLOT != basebase->SLOT))
3572
Tim Peters6d6c1a32001-08-02 04:15:00 +00003573#define COPYSLOT(SLOT) \
Guido van Rossum13d52f02001-08-10 21:24:08 +00003574 if (!type->SLOT && SLOTDEFINED(SLOT)) type->SLOT = base->SLOT
Tim Peters6d6c1a32001-08-02 04:15:00 +00003575
3576#define COPYNUM(SLOT) COPYSLOT(tp_as_number->SLOT)
3577#define COPYSEQ(SLOT) COPYSLOT(tp_as_sequence->SLOT)
3578#define COPYMAP(SLOT) COPYSLOT(tp_as_mapping->SLOT)
Tim Petersfc57ccb2001-10-12 02:38:24 +00003579#define COPYBUF(SLOT) COPYSLOT(tp_as_buffer->SLOT)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003580
Guido van Rossum13d52f02001-08-10 21:24:08 +00003581 /* This won't inherit indirect slots (from tp_as_number etc.)
3582 if type doesn't provide the space. */
3583
3584 if (type->tp_as_number != NULL && base->tp_as_number != NULL) {
3585 basebase = base->tp_base;
3586 if (basebase->tp_as_number == NULL)
3587 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003588 COPYNUM(nb_add);
3589 COPYNUM(nb_subtract);
3590 COPYNUM(nb_multiply);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003591 COPYNUM(nb_remainder);
3592 COPYNUM(nb_divmod);
3593 COPYNUM(nb_power);
3594 COPYNUM(nb_negative);
3595 COPYNUM(nb_positive);
3596 COPYNUM(nb_absolute);
Jack Diederich4dafcc42006-11-28 19:15:13 +00003597 COPYNUM(nb_bool);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003598 COPYNUM(nb_invert);
3599 COPYNUM(nb_lshift);
3600 COPYNUM(nb_rshift);
3601 COPYNUM(nb_and);
3602 COPYNUM(nb_xor);
3603 COPYNUM(nb_or);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003604 COPYNUM(nb_int);
3605 COPYNUM(nb_long);
3606 COPYNUM(nb_float);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003607 COPYNUM(nb_inplace_add);
3608 COPYNUM(nb_inplace_subtract);
3609 COPYNUM(nb_inplace_multiply);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003610 COPYNUM(nb_inplace_remainder);
3611 COPYNUM(nb_inplace_power);
3612 COPYNUM(nb_inplace_lshift);
3613 COPYNUM(nb_inplace_rshift);
3614 COPYNUM(nb_inplace_and);
3615 COPYNUM(nb_inplace_xor);
3616 COPYNUM(nb_inplace_or);
Neal Norwitzbcc0db82006-03-24 08:14:36 +00003617 COPYNUM(nb_true_divide);
3618 COPYNUM(nb_floor_divide);
3619 COPYNUM(nb_inplace_true_divide);
3620 COPYNUM(nb_inplace_floor_divide);
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00003621 COPYNUM(nb_index);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003622 }
3623
Guido van Rossum13d52f02001-08-10 21:24:08 +00003624 if (type->tp_as_sequence != NULL && base->tp_as_sequence != NULL) {
3625 basebase = base->tp_base;
3626 if (basebase->tp_as_sequence == NULL)
3627 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003628 COPYSEQ(sq_length);
3629 COPYSEQ(sq_concat);
3630 COPYSEQ(sq_repeat);
3631 COPYSEQ(sq_item);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003632 COPYSEQ(sq_ass_item);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003633 COPYSEQ(sq_contains);
3634 COPYSEQ(sq_inplace_concat);
3635 COPYSEQ(sq_inplace_repeat);
3636 }
3637
Guido van Rossum13d52f02001-08-10 21:24:08 +00003638 if (type->tp_as_mapping != NULL && base->tp_as_mapping != NULL) {
3639 basebase = base->tp_base;
3640 if (basebase->tp_as_mapping == NULL)
3641 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003642 COPYMAP(mp_length);
3643 COPYMAP(mp_subscript);
3644 COPYMAP(mp_ass_subscript);
3645 }
3646
Tim Petersfc57ccb2001-10-12 02:38:24 +00003647 if (type->tp_as_buffer != NULL && base->tp_as_buffer != NULL) {
3648 basebase = base->tp_base;
3649 if (basebase->tp_as_buffer == NULL)
3650 basebase = NULL;
Travis E. Oliphantb99f7622007-08-18 11:21:56 +00003651 COPYBUF(bf_getbuffer);
3652 COPYBUF(bf_releasebuffer);
Tim Petersfc57ccb2001-10-12 02:38:24 +00003653 }
3654
Guido van Rossum13d52f02001-08-10 21:24:08 +00003655 basebase = base->tp_base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003656
Tim Peters6d6c1a32001-08-02 04:15:00 +00003657 COPYSLOT(tp_dealloc);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003658 if (type->tp_getattr == NULL && type->tp_getattro == NULL) {
3659 type->tp_getattr = base->tp_getattr;
3660 type->tp_getattro = base->tp_getattro;
3661 }
3662 if (type->tp_setattr == NULL && type->tp_setattro == NULL) {
3663 type->tp_setattr = base->tp_setattr;
3664 type->tp_setattro = base->tp_setattro;
3665 }
3666 /* tp_compare see tp_richcompare */
3667 COPYSLOT(tp_repr);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003668 /* tp_hash see tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003669 COPYSLOT(tp_call);
3670 COPYSLOT(tp_str);
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00003671 {
Guido van Rossum38938152006-08-21 23:36:26 +00003672 /* Copy comparison-related slots only when
3673 not overriding them anywhere */
Guido van Rossumb8f63662001-08-15 23:57:02 +00003674 if (type->tp_compare == NULL &&
3675 type->tp_richcompare == NULL &&
Guido van Rossum38938152006-08-21 23:36:26 +00003676 type->tp_hash == NULL &&
Guido van Rossumf5243f02008-01-01 04:06:48 +00003677 !overrides_hash(type))
Guido van Rossumb8f63662001-08-15 23:57:02 +00003678 {
Tim Peters6d6c1a32001-08-02 04:15:00 +00003679 type->tp_compare = base->tp_compare;
3680 type->tp_richcompare = base->tp_richcompare;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003681 type->tp_hash = base->tp_hash;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003682 }
3683 }
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00003684 {
Tim Peters6d6c1a32001-08-02 04:15:00 +00003685 COPYSLOT(tp_iter);
3686 COPYSLOT(tp_iternext);
3687 }
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00003688 {
Tim Peters6d6c1a32001-08-02 04:15:00 +00003689 COPYSLOT(tp_descr_get);
3690 COPYSLOT(tp_descr_set);
3691 COPYSLOT(tp_dictoffset);
3692 COPYSLOT(tp_init);
3693 COPYSLOT(tp_alloc);
Guido van Rossumcc8fe042002-04-05 17:10:16 +00003694 COPYSLOT(tp_is_gc);
Tim Peters3cfe7542003-05-21 21:29:48 +00003695 if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) ==
3696 (base->tp_flags & Py_TPFLAGS_HAVE_GC)) {
3697 /* They agree about gc. */
3698 COPYSLOT(tp_free);
3699 }
3700 else if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
3701 type->tp_free == NULL &&
Neal Norwitz30d1c512007-08-19 22:48:23 +00003702 base->tp_free == PyObject_Free) {
Tim Peters3cfe7542003-05-21 21:29:48 +00003703 /* A bit of magic to plug in the correct default
3704 * tp_free function when a derived class adds gc,
3705 * didn't define tp_free, and the base uses the
3706 * default non-gc tp_free.
3707 */
3708 type->tp_free = PyObject_GC_Del;
3709 }
3710 /* else they didn't agree about gc, and there isn't something
3711 * obvious to be done -- the type is on its own.
3712 */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003713 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003714}
3715
Jeremy Hylton938ace62002-07-17 16:30:39 +00003716static int add_operators(PyTypeObject *);
Guido van Rossum13d52f02001-08-10 21:24:08 +00003717
Tim Peters6d6c1a32001-08-02 04:15:00 +00003718int
Guido van Rossum528b7eb2001-08-07 17:24:28 +00003719PyType_Ready(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003720{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00003721 PyObject *dict, *bases;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003722 PyTypeObject *base;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003723 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003724
Guido van Rossumcab05802002-06-10 15:29:03 +00003725 if (type->tp_flags & Py_TPFLAGS_READY) {
3726 assert(type->tp_dict != NULL);
Guido van Rossumd614f972001-08-10 17:39:49 +00003727 return 0;
Guido van Rossumcab05802002-06-10 15:29:03 +00003728 }
Guido van Rossumd614f972001-08-10 17:39:49 +00003729 assert((type->tp_flags & Py_TPFLAGS_READYING) == 0);
Guido van Rossumd614f972001-08-10 17:39:49 +00003730
3731 type->tp_flags |= Py_TPFLAGS_READYING;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003732
Tim Peters36eb4df2003-03-23 03:33:13 +00003733#ifdef Py_TRACE_REFS
3734 /* PyType_Ready is the closest thing we have to a choke point
3735 * for type objects, so is the best place I can think of to try
3736 * to get type objects into the doubly-linked list of all objects.
3737 * Still, not all type objects go thru PyType_Ready.
3738 */
Tim Peters7571a0f2003-03-23 17:52:28 +00003739 _Py_AddToAllObjects((PyObject *)type, 0);
Tim Peters36eb4df2003-03-23 03:33:13 +00003740#endif
3741
Tim Peters6d6c1a32001-08-02 04:15:00 +00003742 /* Initialize tp_base (defaults to BaseObject unless that's us) */
3743 base = type->tp_base;
Martin v. Löwisbf608752004-08-18 13:16:54 +00003744 if (base == NULL && type != &PyBaseObject_Type) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00003745 base = type->tp_base = &PyBaseObject_Type;
Martin v. Löwisbf608752004-08-18 13:16:54 +00003746 Py_INCREF(base);
3747 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003748
Guido van Rossumd8faa362007-04-27 19:54:29 +00003749 /* Now the only way base can still be NULL is if type is
3750 * &PyBaseObject_Type.
3751 */
Guido van Rossum692cdbc2006-03-10 02:04:28 +00003752
Guido van Rossum323a9cf2002-08-14 17:26:30 +00003753 /* Initialize the base class */
Guido van Rossum50e9fb92006-08-17 05:42:55 +00003754 if (base != NULL && base->tp_dict == NULL) {
Guido van Rossum323a9cf2002-08-14 17:26:30 +00003755 if (PyType_Ready(base) < 0)
3756 goto error;
3757 }
3758
Guido van Rossumd8faa362007-04-27 19:54:29 +00003759 /* Initialize ob_type if NULL. This means extensions that want to be
Guido van Rossum0986d822002-04-08 01:38:42 +00003760 compilable separately on Windows can call PyType_Ready() instead of
3761 initializing the ob_type field of their type objects. */
Guido van Rossumd8faa362007-04-27 19:54:29 +00003762 /* The test for base != NULL is really unnecessary, since base is only
3763 NULL when type is &PyBaseObject_Type, and we know its ob_type is
3764 not NULL (it's initialized to &PyType_Type). But coverity doesn't
3765 know that. */
Christian Heimes90aa7642007-12-19 02:45:37 +00003766 if (Py_TYPE(type) == NULL && base != NULL)
3767 Py_TYPE(type) = Py_TYPE(base);
Guido van Rossum0986d822002-04-08 01:38:42 +00003768
Tim Peters6d6c1a32001-08-02 04:15:00 +00003769 /* Initialize tp_bases */
3770 bases = type->tp_bases;
3771 if (bases == NULL) {
3772 if (base == NULL)
3773 bases = PyTuple_New(0);
3774 else
Raymond Hettinger8ae46892003-10-12 19:09:37 +00003775 bases = PyTuple_Pack(1, base);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003776 if (bases == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00003777 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003778 type->tp_bases = bases;
3779 }
3780
Guido van Rossum687ae002001-10-15 22:03:32 +00003781 /* Initialize tp_dict */
3782 dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003783 if (dict == NULL) {
3784 dict = PyDict_New();
3785 if (dict == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00003786 goto error;
Guido van Rossum687ae002001-10-15 22:03:32 +00003787 type->tp_dict = dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003788 }
3789
Guido van Rossum687ae002001-10-15 22:03:32 +00003790 /* Add type-specific descriptors to tp_dict */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003791 if (add_operators(type) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003792 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003793 if (type->tp_methods != NULL) {
3794 if (add_methods(type, type->tp_methods) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003795 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003796 }
3797 if (type->tp_members != NULL) {
3798 if (add_members(type, type->tp_members) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003799 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003800 }
3801 if (type->tp_getset != NULL) {
3802 if (add_getset(type, type->tp_getset) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003803 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003804 }
3805
Tim Peters6d6c1a32001-08-02 04:15:00 +00003806 /* Calculate method resolution order */
3807 if (mro_internal(type) < 0) {
Guido van Rossumd614f972001-08-10 17:39:49 +00003808 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003809 }
3810
Guido van Rossum13d52f02001-08-10 21:24:08 +00003811 /* Inherit special flags from dominant base */
3812 if (type->tp_base != NULL)
3813 inherit_special(type, type->tp_base);
3814
Tim Peters6d6c1a32001-08-02 04:15:00 +00003815 /* Initialize tp_dict properly */
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00003816 bases = type->tp_mro;
3817 assert(bases != NULL);
3818 assert(PyTuple_Check(bases));
3819 n = PyTuple_GET_SIZE(bases);
3820 for (i = 1; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00003821 PyObject *b = PyTuple_GET_ITEM(bases, i);
3822 if (PyType_Check(b))
3823 inherit_slots(type, (PyTypeObject *)b);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003824 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003825
Tim Peters3cfe7542003-05-21 21:29:48 +00003826 /* Sanity check for tp_free. */
3827 if (PyType_IS_GC(type) && (type->tp_flags & Py_TPFLAGS_BASETYPE) &&
3828 (type->tp_free == NULL || type->tp_free == PyObject_Del)) {
Guido van Rossumd8faa362007-04-27 19:54:29 +00003829 /* This base class needs to call tp_free, but doesn't have
3830 * one, or its tp_free is for non-gc'ed objects.
3831 */
Tim Peters3cfe7542003-05-21 21:29:48 +00003832 PyErr_Format(PyExc_TypeError, "type '%.100s' participates in "
3833 "gc and is a base type but has inappropriate "
3834 "tp_free slot",
3835 type->tp_name);
3836 goto error;
3837 }
3838
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00003839 /* if the type dictionary doesn't contain a __doc__, set it from
3840 the tp_doc slot.
3841 */
3842 if (PyDict_GetItemString(type->tp_dict, "__doc__") == NULL) {
3843 if (type->tp_doc != NULL) {
Neal Norwitza369c5a2007-08-25 07:41:59 +00003844 PyObject *doc = PyUnicode_FromString(type->tp_doc);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003845 if (doc == NULL)
3846 goto error;
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00003847 PyDict_SetItemString(type->tp_dict, "__doc__", doc);
3848 Py_DECREF(doc);
3849 } else {
Guido van Rossumd4641072002-04-03 02:13:37 +00003850 PyDict_SetItemString(type->tp_dict,
3851 "__doc__", Py_None);
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00003852 }
3853 }
3854
Guido van Rossum38938152006-08-21 23:36:26 +00003855 /* Hack for tp_hash and __hash__.
3856 If after all that, tp_hash is still NULL, and __hash__ is not in
Nick Coghland1abd252008-07-15 15:46:38 +00003857 tp_dict, set tp_hash to PyObject_HashNotImplemented and
3858 tp_dict['__hash__'] equal to None.
Guido van Rossum38938152006-08-21 23:36:26 +00003859 This signals that __hash__ is not inherited.
3860 */
3861 if (type->tp_hash == NULL) {
3862 if (PyDict_GetItemString(type->tp_dict, "__hash__") == NULL) {
3863 if (PyDict_SetItemString(type->tp_dict, "__hash__", Py_None) < 0)
3864 goto error;
Nick Coghland1abd252008-07-15 15:46:38 +00003865 type->tp_hash = PyObject_HashNotImplemented;
Guido van Rossum38938152006-08-21 23:36:26 +00003866 }
3867 }
3868
Guido van Rossum13d52f02001-08-10 21:24:08 +00003869 /* Some more special stuff */
3870 base = type->tp_base;
3871 if (base != NULL) {
3872 if (type->tp_as_number == NULL)
3873 type->tp_as_number = base->tp_as_number;
3874 if (type->tp_as_sequence == NULL)
3875 type->tp_as_sequence = base->tp_as_sequence;
3876 if (type->tp_as_mapping == NULL)
3877 type->tp_as_mapping = base->tp_as_mapping;
Guido van Rossumeea47182003-02-11 20:39:59 +00003878 if (type->tp_as_buffer == NULL)
3879 type->tp_as_buffer = base->tp_as_buffer;
Guido van Rossum13d52f02001-08-10 21:24:08 +00003880 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003881
Guido van Rossum1c450732001-10-08 15:18:27 +00003882 /* Link into each base class's list of subclasses */
3883 bases = type->tp_bases;
3884 n = PyTuple_GET_SIZE(bases);
3885 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00003886 PyObject *b = PyTuple_GET_ITEM(bases, i);
3887 if (PyType_Check(b) &&
3888 add_subclass((PyTypeObject *)b, type) < 0)
Guido van Rossum1c450732001-10-08 15:18:27 +00003889 goto error;
3890 }
3891
Guido van Rossum13d52f02001-08-10 21:24:08 +00003892 /* All done -- set the ready flag */
Guido van Rossumd614f972001-08-10 17:39:49 +00003893 assert(type->tp_dict != NULL);
3894 type->tp_flags =
3895 (type->tp_flags & ~Py_TPFLAGS_READYING) | Py_TPFLAGS_READY;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003896 return 0;
Guido van Rossumd614f972001-08-10 17:39:49 +00003897
3898 error:
3899 type->tp_flags &= ~Py_TPFLAGS_READYING;
3900 return -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003901}
3902
Guido van Rossum1c450732001-10-08 15:18:27 +00003903static int
3904add_subclass(PyTypeObject *base, PyTypeObject *type)
3905{
Martin v. Löwiseb079f12006-02-16 14:32:27 +00003906 Py_ssize_t i;
3907 int result;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003908 PyObject *list, *ref, *newobj;
Guido van Rossum1c450732001-10-08 15:18:27 +00003909
3910 list = base->tp_subclasses;
3911 if (list == NULL) {
3912 base->tp_subclasses = list = PyList_New(0);
3913 if (list == NULL)
3914 return -1;
3915 }
3916 assert(PyList_Check(list));
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003917 newobj = PyWeakref_NewRef((PyObject *)type, NULL);
Guido van Rossum1c450732001-10-08 15:18:27 +00003918 i = PyList_GET_SIZE(list);
3919 while (--i >= 0) {
3920 ref = PyList_GET_ITEM(list, i);
3921 assert(PyWeakref_CheckRef(ref));
Guido van Rossum3930bc32002-10-18 13:51:49 +00003922 if (PyWeakref_GET_OBJECT(ref) == Py_None)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003923 return PyList_SetItem(list, i, newobj);
Guido van Rossum1c450732001-10-08 15:18:27 +00003924 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003925 result = PyList_Append(list, newobj);
3926 Py_DECREF(newobj);
Martin v. Löwiseb079f12006-02-16 14:32:27 +00003927 return result;
Guido van Rossum1c450732001-10-08 15:18:27 +00003928}
3929
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003930static void
3931remove_subclass(PyTypeObject *base, PyTypeObject *type)
3932{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003933 Py_ssize_t i;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003934 PyObject *list, *ref;
3935
3936 list = base->tp_subclasses;
3937 if (list == NULL) {
3938 return;
3939 }
3940 assert(PyList_Check(list));
3941 i = PyList_GET_SIZE(list);
3942 while (--i >= 0) {
3943 ref = PyList_GET_ITEM(list, i);
3944 assert(PyWeakref_CheckRef(ref));
3945 if (PyWeakref_GET_OBJECT(ref) == (PyObject*)type) {
3946 /* this can't fail, right? */
3947 PySequence_DelItem(list, i);
3948 return;
3949 }
3950 }
3951}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003952
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003953static int
3954check_num_args(PyObject *ob, int n)
3955{
3956 if (!PyTuple_CheckExact(ob)) {
3957 PyErr_SetString(PyExc_SystemError,
3958 "PyArg_UnpackTuple() argument list is not a tuple");
3959 return 0;
3960 }
3961 if (n == PyTuple_GET_SIZE(ob))
3962 return 1;
3963 PyErr_Format(
3964 PyExc_TypeError,
Martin v. Löwis2c95cc62006-02-16 06:54:25 +00003965 "expected %d arguments, got %zd", n, PyTuple_GET_SIZE(ob));
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003966 return 0;
3967}
3968
Tim Peters6d6c1a32001-08-02 04:15:00 +00003969/* Generic wrappers for overloadable 'operators' such as __getitem__ */
3970
3971/* There's a wrapper *function* for each distinct function typedef used
Guido van Rossumd8faa362007-04-27 19:54:29 +00003972 for type object slots (e.g. binaryfunc, ternaryfunc, etc.). There's a
Tim Peters6d6c1a32001-08-02 04:15:00 +00003973 wrapper *table* for each distinct operation (e.g. __len__, __add__).
3974 Most tables have only one entry; the tables for binary operators have two
3975 entries, one regular and one with reversed arguments. */
3976
3977static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00003978wrap_lenfunc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003979{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003980 lenfunc func = (lenfunc)wrapped;
3981 Py_ssize_t res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003982
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003983 if (!check_num_args(args, 0))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003984 return NULL;
3985 res = (*func)(self);
3986 if (res == -1 && PyErr_Occurred())
3987 return NULL;
Christian Heimes217cfd12007-12-02 14:31:20 +00003988 return PyLong_FromLong((long)res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003989}
3990
Tim Peters6d6c1a32001-08-02 04:15:00 +00003991static PyObject *
Raymond Hettingerf34f2642003-10-11 17:29:04 +00003992wrap_inquirypred(PyObject *self, PyObject *args, void *wrapped)
3993{
3994 inquiry func = (inquiry)wrapped;
3995 int res;
3996
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003997 if (!check_num_args(args, 0))
Raymond Hettingerf34f2642003-10-11 17:29:04 +00003998 return NULL;
3999 res = (*func)(self);
4000 if (res == -1 && PyErr_Occurred())
4001 return NULL;
4002 return PyBool_FromLong((long)res);
4003}
4004
4005static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00004006wrap_binaryfunc(PyObject *self, PyObject *args, void *wrapped)
4007{
4008 binaryfunc func = (binaryfunc)wrapped;
4009 PyObject *other;
4010
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004011 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004012 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004013 other = PyTuple_GET_ITEM(args, 0);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004014 return (*func)(self, other);
4015}
4016
4017static PyObject *
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00004018wrap_binaryfunc_l(PyObject *self, PyObject *args, void *wrapped)
4019{
4020 binaryfunc func = (binaryfunc)wrapped;
4021 PyObject *other;
4022
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004023 if (!check_num_args(args, 1))
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00004024 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004025 other = PyTuple_GET_ITEM(args, 0);
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00004026 return (*func)(self, other);
4027}
4028
4029static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00004030wrap_binaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
4031{
4032 binaryfunc func = (binaryfunc)wrapped;
4033 PyObject *other;
4034
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004035 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004036 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004037 other = PyTuple_GET_ITEM(args, 0);
Christian Heimes90aa7642007-12-19 02:45:37 +00004038 if (!PyType_IsSubtype(Py_TYPE(other), Py_TYPE(self))) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00004039 Py_INCREF(Py_NotImplemented);
4040 return Py_NotImplemented;
4041 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004042 return (*func)(other, self);
4043}
4044
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004045static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00004046wrap_ternaryfunc(PyObject *self, PyObject *args, void *wrapped)
4047{
4048 ternaryfunc func = (ternaryfunc)wrapped;
4049 PyObject *other;
4050 PyObject *third = Py_None;
4051
4052 /* Note: This wrapper only works for __pow__() */
4053
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00004054 if (!PyArg_UnpackTuple(args, "", 1, 2, &other, &third))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004055 return NULL;
4056 return (*func)(self, other, third);
4057}
4058
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00004059static PyObject *
4060wrap_ternaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
4061{
4062 ternaryfunc func = (ternaryfunc)wrapped;
4063 PyObject *other;
4064 PyObject *third = Py_None;
4065
4066 /* Note: This wrapper only works for __pow__() */
4067
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00004068 if (!PyArg_UnpackTuple(args, "", 1, 2, &other, &third))
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00004069 return NULL;
4070 return (*func)(other, self, third);
4071}
4072
Tim Peters6d6c1a32001-08-02 04:15:00 +00004073static PyObject *
4074wrap_unaryfunc(PyObject *self, PyObject *args, void *wrapped)
4075{
4076 unaryfunc func = (unaryfunc)wrapped;
4077
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004078 if (!check_num_args(args, 0))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004079 return NULL;
4080 return (*func)(self);
4081}
4082
Tim Peters6d6c1a32001-08-02 04:15:00 +00004083static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004084wrap_indexargfunc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004085{
Martin v. Löwis18e16552006-02-15 17:27:45 +00004086 ssizeargfunc func = (ssizeargfunc)wrapped;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004087 PyObject* o;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004088 Py_ssize_t i;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004089
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004090 if (!PyArg_UnpackTuple(args, "", 1, 1, &o))
4091 return NULL;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00004092 i = PyNumber_AsSsize_t(o, PyExc_OverflowError);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004093 if (i == -1 && PyErr_Occurred())
Tim Peters6d6c1a32001-08-02 04:15:00 +00004094 return NULL;
4095 return (*func)(self, i);
4096}
4097
Martin v. Löwis18e16552006-02-15 17:27:45 +00004098static Py_ssize_t
Guido van Rossum5d815f32001-08-17 21:57:47 +00004099getindex(PyObject *self, PyObject *arg)
4100{
Martin v. Löwis18e16552006-02-15 17:27:45 +00004101 Py_ssize_t i;
Guido van Rossum5d815f32001-08-17 21:57:47 +00004102
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00004103 i = PyNumber_AsSsize_t(arg, PyExc_OverflowError);
Guido van Rossum5d815f32001-08-17 21:57:47 +00004104 if (i == -1 && PyErr_Occurred())
4105 return -1;
4106 if (i < 0) {
Christian Heimes90aa7642007-12-19 02:45:37 +00004107 PySequenceMethods *sq = Py_TYPE(self)->tp_as_sequence;
Guido van Rossum5d815f32001-08-17 21:57:47 +00004108 if (sq && sq->sq_length) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00004109 Py_ssize_t n = (*sq->sq_length)(self);
Guido van Rossum5d815f32001-08-17 21:57:47 +00004110 if (n < 0)
4111 return -1;
4112 i += n;
4113 }
4114 }
4115 return i;
4116}
4117
4118static PyObject *
4119wrap_sq_item(PyObject *self, PyObject *args, void *wrapped)
4120{
Martin v. Löwis18e16552006-02-15 17:27:45 +00004121 ssizeargfunc func = (ssizeargfunc)wrapped;
Guido van Rossum5d815f32001-08-17 21:57:47 +00004122 PyObject *arg;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004123 Py_ssize_t i;
Guido van Rossum5d815f32001-08-17 21:57:47 +00004124
Guido van Rossumf4593e02001-10-03 12:09:30 +00004125 if (PyTuple_GET_SIZE(args) == 1) {
4126 arg = PyTuple_GET_ITEM(args, 0);
4127 i = getindex(self, arg);
4128 if (i == -1 && PyErr_Occurred())
4129 return NULL;
4130 return (*func)(self, i);
4131 }
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004132 check_num_args(args, 1);
Guido van Rossumf4593e02001-10-03 12:09:30 +00004133 assert(PyErr_Occurred());
4134 return NULL;
Guido van Rossum5d815f32001-08-17 21:57:47 +00004135}
4136
Tim Peters6d6c1a32001-08-02 04:15:00 +00004137static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00004138wrap_sq_setitem(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004139{
Martin v. Löwis18e16552006-02-15 17:27:45 +00004140 ssizeobjargproc func = (ssizeobjargproc)wrapped;
4141 Py_ssize_t i;
4142 int res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00004143 PyObject *arg, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004144
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00004145 if (!PyArg_UnpackTuple(args, "", 2, 2, &arg, &value))
Guido van Rossum5d815f32001-08-17 21:57:47 +00004146 return NULL;
4147 i = getindex(self, arg);
4148 if (i == -1 && PyErr_Occurred())
Tim Peters6d6c1a32001-08-02 04:15:00 +00004149 return NULL;
4150 res = (*func)(self, i, value);
4151 if (res == -1 && PyErr_Occurred())
4152 return NULL;
4153 Py_INCREF(Py_None);
4154 return Py_None;
4155}
4156
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004157static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00004158wrap_sq_delitem(PyObject *self, PyObject *args, void *wrapped)
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004159{
Martin v. Löwis18e16552006-02-15 17:27:45 +00004160 ssizeobjargproc func = (ssizeobjargproc)wrapped;
4161 Py_ssize_t i;
4162 int res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00004163 PyObject *arg;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004164
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004165 if (!check_num_args(args, 1))
Guido van Rossum5d815f32001-08-17 21:57:47 +00004166 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004167 arg = PyTuple_GET_ITEM(args, 0);
Guido van Rossum5d815f32001-08-17 21:57:47 +00004168 i = getindex(self, arg);
4169 if (i == -1 && PyErr_Occurred())
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004170 return NULL;
4171 res = (*func)(self, i, NULL);
4172 if (res == -1 && PyErr_Occurred())
4173 return NULL;
4174 Py_INCREF(Py_None);
4175 return Py_None;
4176}
4177
Tim Peters6d6c1a32001-08-02 04:15:00 +00004178/* XXX objobjproc is a misnomer; should be objargpred */
4179static PyObject *
4180wrap_objobjproc(PyObject *self, PyObject *args, void *wrapped)
4181{
4182 objobjproc func = (objobjproc)wrapped;
4183 int res;
Guido van Rossum22c3dda2003-10-09 03:46:35 +00004184 PyObject *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004185
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004186 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004187 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004188 value = PyTuple_GET_ITEM(args, 0);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004189 res = (*func)(self, value);
4190 if (res == -1 && PyErr_Occurred())
4191 return NULL;
Guido van Rossum22c3dda2003-10-09 03:46:35 +00004192 else
4193 return PyBool_FromLong(res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004194}
4195
Tim Peters6d6c1a32001-08-02 04:15:00 +00004196static PyObject *
4197wrap_objobjargproc(PyObject *self, PyObject *args, void *wrapped)
4198{
4199 objobjargproc func = (objobjargproc)wrapped;
4200 int res;
4201 PyObject *key, *value;
4202
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00004203 if (!PyArg_UnpackTuple(args, "", 2, 2, &key, &value))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004204 return NULL;
4205 res = (*func)(self, key, value);
4206 if (res == -1 && PyErr_Occurred())
4207 return NULL;
4208 Py_INCREF(Py_None);
4209 return Py_None;
4210}
4211
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004212static PyObject *
4213wrap_delitem(PyObject *self, PyObject *args, void *wrapped)
4214{
4215 objobjargproc func = (objobjargproc)wrapped;
4216 int res;
4217 PyObject *key;
4218
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004219 if (!check_num_args(args, 1))
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004220 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004221 key = PyTuple_GET_ITEM(args, 0);
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004222 res = (*func)(self, key, NULL);
4223 if (res == -1 && PyErr_Occurred())
4224 return NULL;
4225 Py_INCREF(Py_None);
4226 return Py_None;
4227}
4228
Guido van Rossum4dcdb782003-04-14 21:46:03 +00004229/* Helper to check for object.__setattr__ or __delattr__ applied to a type.
Guido van Rossum52b27052003-04-15 20:05:10 +00004230 This is called the Carlo Verre hack after its discoverer. */
Guido van Rossum4dcdb782003-04-14 21:46:03 +00004231static int
4232hackcheck(PyObject *self, setattrofunc func, char *what)
4233{
Christian Heimes90aa7642007-12-19 02:45:37 +00004234 PyTypeObject *type = Py_TYPE(self);
Guido van Rossum4dcdb782003-04-14 21:46:03 +00004235 while (type && type->tp_flags & Py_TPFLAGS_HEAPTYPE)
4236 type = type->tp_base;
Guido van Rossumd8faa362007-04-27 19:54:29 +00004237 /* If type is NULL now, this is a really weird type.
4238 In the spirit of backwards compatibility (?), just shut up. */
Guido van Rossum692cdbc2006-03-10 02:04:28 +00004239 if (type && type->tp_setattro != func) {
Guido van Rossum4dcdb782003-04-14 21:46:03 +00004240 PyErr_Format(PyExc_TypeError,
4241 "can't apply this %s to %s object",
4242 what,
4243 type->tp_name);
4244 return 0;
4245 }
4246 return 1;
4247}
4248
Tim Peters6d6c1a32001-08-02 04:15:00 +00004249static PyObject *
4250wrap_setattr(PyObject *self, PyObject *args, void *wrapped)
4251{
4252 setattrofunc func = (setattrofunc)wrapped;
4253 int res;
4254 PyObject *name, *value;
4255
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00004256 if (!PyArg_UnpackTuple(args, "", 2, 2, &name, &value))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004257 return NULL;
Guido van Rossum4dcdb782003-04-14 21:46:03 +00004258 if (!hackcheck(self, func, "__setattr__"))
4259 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004260 res = (*func)(self, name, value);
4261 if (res < 0)
4262 return NULL;
4263 Py_INCREF(Py_None);
4264 return Py_None;
4265}
4266
4267static PyObject *
4268wrap_delattr(PyObject *self, PyObject *args, void *wrapped)
4269{
4270 setattrofunc func = (setattrofunc)wrapped;
4271 int res;
4272 PyObject *name;
4273
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004274 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004275 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004276 name = PyTuple_GET_ITEM(args, 0);
Guido van Rossum4dcdb782003-04-14 21:46:03 +00004277 if (!hackcheck(self, func, "__delattr__"))
4278 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004279 res = (*func)(self, name, NULL);
4280 if (res < 0)
4281 return NULL;
4282 Py_INCREF(Py_None);
4283 return Py_None;
4284}
4285
Tim Peters6d6c1a32001-08-02 04:15:00 +00004286static PyObject *
4287wrap_hashfunc(PyObject *self, PyObject *args, void *wrapped)
4288{
4289 hashfunc func = (hashfunc)wrapped;
4290 long res;
4291
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004292 if (!check_num_args(args, 0))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004293 return NULL;
4294 res = (*func)(self);
4295 if (res == -1 && PyErr_Occurred())
4296 return NULL;
Christian Heimes217cfd12007-12-02 14:31:20 +00004297 return PyLong_FromLong(res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004298}
4299
Tim Peters6d6c1a32001-08-02 04:15:00 +00004300static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00004301wrap_call(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004302{
4303 ternaryfunc func = (ternaryfunc)wrapped;
4304
Guido van Rossumc8e56452001-10-22 00:43:43 +00004305 return (*func)(self, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004306}
4307
Tim Peters6d6c1a32001-08-02 04:15:00 +00004308static PyObject *
4309wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op)
4310{
4311 richcmpfunc func = (richcmpfunc)wrapped;
4312 PyObject *other;
4313
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004314 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004315 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004316 other = PyTuple_GET_ITEM(args, 0);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004317 return (*func)(self, other, op);
4318}
4319
4320#undef RICHCMP_WRAPPER
4321#define RICHCMP_WRAPPER(NAME, OP) \
4322static PyObject * \
4323richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \
4324{ \
4325 return wrap_richcmpfunc(self, args, wrapped, OP); \
4326}
4327
Jack Jansen8e938b42001-08-08 15:29:49 +00004328RICHCMP_WRAPPER(lt, Py_LT)
4329RICHCMP_WRAPPER(le, Py_LE)
4330RICHCMP_WRAPPER(eq, Py_EQ)
4331RICHCMP_WRAPPER(ne, Py_NE)
4332RICHCMP_WRAPPER(gt, Py_GT)
4333RICHCMP_WRAPPER(ge, Py_GE)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004334
Tim Peters6d6c1a32001-08-02 04:15:00 +00004335static PyObject *
4336wrap_next(PyObject *self, PyObject *args, void *wrapped)
4337{
4338 unaryfunc func = (unaryfunc)wrapped;
4339 PyObject *res;
4340
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004341 if (!check_num_args(args, 0))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004342 return NULL;
4343 res = (*func)(self);
4344 if (res == NULL && !PyErr_Occurred())
4345 PyErr_SetNone(PyExc_StopIteration);
4346 return res;
4347}
4348
Tim Peters6d6c1a32001-08-02 04:15:00 +00004349static PyObject *
4350wrap_descr_get(PyObject *self, PyObject *args, void *wrapped)
4351{
4352 descrgetfunc func = (descrgetfunc)wrapped;
4353 PyObject *obj;
4354 PyObject *type = NULL;
4355
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00004356 if (!PyArg_UnpackTuple(args, "", 1, 2, &obj, &type))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004357 return NULL;
Guido van Rossum82ed25c2003-02-11 16:25:43 +00004358 if (obj == Py_None)
4359 obj = NULL;
4360 if (type == Py_None)
4361 type = NULL;
4362 if (type == NULL &&obj == NULL) {
4363 PyErr_SetString(PyExc_TypeError,
4364 "__get__(None, None) is invalid");
4365 return NULL;
4366 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004367 return (*func)(self, obj, type);
4368}
4369
Tim Peters6d6c1a32001-08-02 04:15:00 +00004370static PyObject *
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004371wrap_descr_set(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004372{
4373 descrsetfunc func = (descrsetfunc)wrapped;
4374 PyObject *obj, *value;
4375 int ret;
4376
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00004377 if (!PyArg_UnpackTuple(args, "", 2, 2, &obj, &value))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004378 return NULL;
4379 ret = (*func)(self, obj, value);
4380 if (ret < 0)
4381 return NULL;
4382 Py_INCREF(Py_None);
4383 return Py_None;
4384}
Guido van Rossum22b13872002-08-06 21:41:44 +00004385
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00004386static PyObject *
4387wrap_descr_delete(PyObject *self, PyObject *args, void *wrapped)
4388{
4389 descrsetfunc func = (descrsetfunc)wrapped;
4390 PyObject *obj;
4391 int ret;
4392
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004393 if (!check_num_args(args, 1))
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00004394 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004395 obj = PyTuple_GET_ITEM(args, 0);
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00004396 ret = (*func)(self, obj, NULL);
4397 if (ret < 0)
4398 return NULL;
4399 Py_INCREF(Py_None);
4400 return Py_None;
4401}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004402
Tim Peters6d6c1a32001-08-02 04:15:00 +00004403static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00004404wrap_init(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004405{
4406 initproc func = (initproc)wrapped;
4407
Guido van Rossumc8e56452001-10-22 00:43:43 +00004408 if (func(self, args, kwds) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004409 return NULL;
4410 Py_INCREF(Py_None);
4411 return Py_None;
4412}
4413
Tim Peters6d6c1a32001-08-02 04:15:00 +00004414static PyObject *
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004415tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004416{
Barry Warsaw60f01882001-08-22 19:24:42 +00004417 PyTypeObject *type, *subtype, *staticbase;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004418 PyObject *arg0, *res;
4419
4420 if (self == NULL || !PyType_Check(self))
4421 Py_FatalError("__new__() called with non-type 'self'");
4422 type = (PyTypeObject *)self;
4423 if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) {
Barry Warsaw60f01882001-08-22 19:24:42 +00004424 PyErr_Format(PyExc_TypeError,
4425 "%s.__new__(): not enough arguments",
4426 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004427 return NULL;
4428 }
4429 arg0 = PyTuple_GET_ITEM(args, 0);
4430 if (!PyType_Check(arg0)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00004431 PyErr_Format(PyExc_TypeError,
4432 "%s.__new__(X): X is not a type object (%s)",
4433 type->tp_name,
Christian Heimes90aa7642007-12-19 02:45:37 +00004434 Py_TYPE(arg0)->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004435 return NULL;
4436 }
4437 subtype = (PyTypeObject *)arg0;
4438 if (!PyType_IsSubtype(subtype, type)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00004439 PyErr_Format(PyExc_TypeError,
4440 "%s.__new__(%s): %s is not a subtype of %s",
4441 type->tp_name,
4442 subtype->tp_name,
4443 subtype->tp_name,
4444 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004445 return NULL;
4446 }
Barry Warsaw60f01882001-08-22 19:24:42 +00004447
4448 /* Check that the use doesn't do something silly and unsafe like
Tim Petersa427a2b2001-10-29 22:25:45 +00004449 object.__new__(dict). To do this, we check that the
Barry Warsaw60f01882001-08-22 19:24:42 +00004450 most derived base that's not a heap type is this type. */
4451 staticbase = subtype;
4452 while (staticbase && (staticbase->tp_flags & Py_TPFLAGS_HEAPTYPE))
4453 staticbase = staticbase->tp_base;
Guido van Rossumd8faa362007-04-27 19:54:29 +00004454 /* If staticbase is NULL now, it is a really weird type.
4455 In the spirit of backwards compatibility (?), just shut up. */
Guido van Rossum692cdbc2006-03-10 02:04:28 +00004456 if (staticbase && staticbase->tp_new != type->tp_new) {
Barry Warsaw60f01882001-08-22 19:24:42 +00004457 PyErr_Format(PyExc_TypeError,
4458 "%s.__new__(%s) is not safe, use %s.__new__()",
4459 type->tp_name,
4460 subtype->tp_name,
4461 staticbase == NULL ? "?" : staticbase->tp_name);
4462 return NULL;
4463 }
4464
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004465 args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
4466 if (args == NULL)
4467 return NULL;
4468 res = type->tp_new(subtype, args, kwds);
4469 Py_DECREF(args);
4470 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004471}
4472
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004473static struct PyMethodDef tp_new_methoddef[] = {
Guido van Rossumd59da4b2007-05-22 18:11:13 +00004474 {"__new__", (PyCFunction)tp_new_wrapper, METH_VARARGS|METH_KEYWORDS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00004475 PyDoc_STR("T.__new__(S, ...) -> "
Guido van Rossumd8faa362007-04-27 19:54:29 +00004476 "a new object with type S, a subtype of T")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00004477 {0}
4478};
4479
4480static int
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004481add_tp_new_wrapper(PyTypeObject *type)
4482{
Guido van Rossumf040ede2001-08-07 16:40:56 +00004483 PyObject *func;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004484
Guido van Rossum687ae002001-10-15 22:03:32 +00004485 if (PyDict_GetItemString(type->tp_dict, "__new__") != NULL)
Guido van Rossumf040ede2001-08-07 16:40:56 +00004486 return 0;
4487 func = PyCFunction_New(tp_new_methoddef, (PyObject *)type);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004488 if (func == NULL)
4489 return -1;
Raymond Hettinger8d726ee2004-06-25 22:24:35 +00004490 if (PyDict_SetItemString(type->tp_dict, "__new__", func)) {
Raymond Hettingerd56cbe52004-06-25 22:17:39 +00004491 Py_DECREF(func);
4492 return -1;
4493 }
4494 Py_DECREF(func);
4495 return 0;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004496}
4497
Guido van Rossumf040ede2001-08-07 16:40:56 +00004498/* Slot wrappers that call the corresponding __foo__ slot. See comments
4499 below at override_slots() for more explanation. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004500
Guido van Rossumdc91b992001-08-08 22:26:22 +00004501#define SLOT0(FUNCNAME, OPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004502static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004503FUNCNAME(PyObject *self) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004504{ \
Guido van Rossum5592e4d2001-08-28 18:28:21 +00004505 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00004506 return call_method(self, OPSTR, &cache_str, "()"); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004507}
4508
Guido van Rossumdc91b992001-08-08 22:26:22 +00004509#define SLOT1(FUNCNAME, OPSTR, ARG1TYPE, ARGCODES) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004510static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004511FUNCNAME(PyObject *self, ARG1TYPE arg1) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004512{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00004513 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00004514 return call_method(self, OPSTR, &cache_str, "(" ARGCODES ")", arg1); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004515}
4516
Guido van Rossumcd118802003-01-06 22:57:47 +00004517/* Boolean helper for SLOT1BINFULL().
4518 right.__class__ is a nontrivial subclass of left.__class__. */
4519static int
4520method_is_overloaded(PyObject *left, PyObject *right, char *name)
4521{
4522 PyObject *a, *b;
4523 int ok;
4524
Christian Heimes90aa7642007-12-19 02:45:37 +00004525 b = PyObject_GetAttrString((PyObject *)(Py_TYPE(right)), name);
Guido van Rossumcd118802003-01-06 22:57:47 +00004526 if (b == NULL) {
4527 PyErr_Clear();
4528 /* If right doesn't have it, it's not overloaded */
4529 return 0;
4530 }
4531
Christian Heimes90aa7642007-12-19 02:45:37 +00004532 a = PyObject_GetAttrString((PyObject *)(Py_TYPE(left)), name);
Guido van Rossumcd118802003-01-06 22:57:47 +00004533 if (a == NULL) {
4534 PyErr_Clear();
4535 Py_DECREF(b);
4536 /* If right has it but left doesn't, it's overloaded */
4537 return 1;
4538 }
4539
4540 ok = PyObject_RichCompareBool(a, b, Py_NE);
4541 Py_DECREF(a);
4542 Py_DECREF(b);
4543 if (ok < 0) {
4544 PyErr_Clear();
4545 return 0;
4546 }
4547
4548 return ok;
4549}
4550
Guido van Rossumdc91b992001-08-08 22:26:22 +00004551
4552#define SLOT1BINFULL(FUNCNAME, TESTFUNC, SLOTNAME, OPSTR, ROPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004553static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004554FUNCNAME(PyObject *self, PyObject *other) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004555{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00004556 static PyObject *cache_str, *rcache_str; \
Christian Heimes90aa7642007-12-19 02:45:37 +00004557 int do_other = Py_TYPE(self) != Py_TYPE(other) && \
4558 Py_TYPE(other)->tp_as_number != NULL && \
4559 Py_TYPE(other)->tp_as_number->SLOTNAME == TESTFUNC; \
4560 if (Py_TYPE(self)->tp_as_number != NULL && \
4561 Py_TYPE(self)->tp_as_number->SLOTNAME == TESTFUNC) { \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004562 PyObject *r; \
Guido van Rossum55f20992001-10-01 17:18:22 +00004563 if (do_other && \
Christian Heimes90aa7642007-12-19 02:45:37 +00004564 PyType_IsSubtype(Py_TYPE(other), Py_TYPE(self)) && \
Guido van Rossumcd118802003-01-06 22:57:47 +00004565 method_is_overloaded(self, other, ROPSTR)) { \
Guido van Rossum55f20992001-10-01 17:18:22 +00004566 r = call_maybe( \
4567 other, ROPSTR, &rcache_str, "(O)", self); \
4568 if (r != Py_NotImplemented) \
4569 return r; \
4570 Py_DECREF(r); \
4571 do_other = 0; \
4572 } \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00004573 r = call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00004574 self, OPSTR, &cache_str, "(O)", other); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004575 if (r != Py_NotImplemented || \
Christian Heimes90aa7642007-12-19 02:45:37 +00004576 Py_TYPE(other) == Py_TYPE(self)) \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004577 return r; \
4578 Py_DECREF(r); \
4579 } \
Guido van Rossum55f20992001-10-01 17:18:22 +00004580 if (do_other) { \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00004581 return call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00004582 other, ROPSTR, &rcache_str, "(O)", self); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004583 } \
4584 Py_INCREF(Py_NotImplemented); \
4585 return Py_NotImplemented; \
4586}
4587
4588#define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) \
4589 SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR)
4590
4591#define SLOT2(FUNCNAME, OPSTR, ARG1TYPE, ARG2TYPE, ARGCODES) \
4592static PyObject * \
4593FUNCNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \
4594{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00004595 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00004596 return call_method(self, OPSTR, &cache_str, \
4597 "(" ARGCODES ")", arg1, arg2); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004598}
4599
Martin v. Löwis18e16552006-02-15 17:27:45 +00004600static Py_ssize_t
Tim Peters6d6c1a32001-08-02 04:15:00 +00004601slot_sq_length(PyObject *self)
4602{
Guido van Rossum2730b132001-08-28 18:22:14 +00004603 static PyObject *len_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00004604 PyObject *res = call_method(self, "__len__", &len_str, "()");
Martin v. Löwis18e16552006-02-15 17:27:45 +00004605 Py_ssize_t len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004606
4607 if (res == NULL)
4608 return -1;
Christian Heimes217cfd12007-12-02 14:31:20 +00004609 len = PyLong_AsSsize_t(res);
Guido van Rossum26111622001-10-01 16:42:49 +00004610 Py_DECREF(res);
Jeremy Hyltonf20fcf92002-07-25 16:06:15 +00004611 if (len < 0) {
Thomas Wouters89f507f2006-12-13 04:49:30 +00004612 if (!PyErr_Occurred())
4613 PyErr_SetString(PyExc_ValueError,
4614 "__len__() should return >= 0");
Jeremy Hyltonf20fcf92002-07-25 16:06:15 +00004615 return -1;
4616 }
Guido van Rossum26111622001-10-01 16:42:49 +00004617 return len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004618}
4619
Guido van Rossumf4593e02001-10-03 12:09:30 +00004620/* Super-optimized version of slot_sq_item.
4621 Other slots could do the same... */
4622static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00004623slot_sq_item(PyObject *self, Py_ssize_t i)
Guido van Rossumf4593e02001-10-03 12:09:30 +00004624{
4625 static PyObject *getitem_str;
4626 PyObject *func, *args = NULL, *ival = NULL, *retval = NULL;
4627 descrgetfunc f;
4628
4629 if (getitem_str == NULL) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00004630 getitem_str = PyUnicode_InternFromString("__getitem__");
Guido van Rossumf4593e02001-10-03 12:09:30 +00004631 if (getitem_str == NULL)
4632 return NULL;
4633 }
Christian Heimes90aa7642007-12-19 02:45:37 +00004634 func = _PyType_Lookup(Py_TYPE(self), getitem_str);
Guido van Rossumf4593e02001-10-03 12:09:30 +00004635 if (func != NULL) {
Christian Heimes90aa7642007-12-19 02:45:37 +00004636 if ((f = Py_TYPE(func)->tp_descr_get) == NULL)
Guido van Rossumf4593e02001-10-03 12:09:30 +00004637 Py_INCREF(func);
Neal Norwitz673cd822002-10-18 16:33:13 +00004638 else {
Christian Heimes90aa7642007-12-19 02:45:37 +00004639 func = f(func, self, (PyObject *)(Py_TYPE(self)));
Neal Norwitz673cd822002-10-18 16:33:13 +00004640 if (func == NULL) {
4641 return NULL;
4642 }
4643 }
Christian Heimes217cfd12007-12-02 14:31:20 +00004644 ival = PyLong_FromSsize_t(i);
Guido van Rossumf4593e02001-10-03 12:09:30 +00004645 if (ival != NULL) {
4646 args = PyTuple_New(1);
4647 if (args != NULL) {
4648 PyTuple_SET_ITEM(args, 0, ival);
4649 retval = PyObject_Call(func, args, NULL);
4650 Py_XDECREF(args);
4651 Py_XDECREF(func);
4652 return retval;
4653 }
4654 }
4655 }
4656 else {
4657 PyErr_SetObject(PyExc_AttributeError, getitem_str);
4658 }
4659 Py_XDECREF(args);
4660 Py_XDECREF(ival);
4661 Py_XDECREF(func);
4662 return NULL;
4663}
4664
Tim Peters6d6c1a32001-08-02 04:15:00 +00004665static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00004666slot_sq_ass_item(PyObject *self, Py_ssize_t index, PyObject *value)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004667{
4668 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004669 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004670
4671 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004672 res = call_method(self, "__delitem__", &delitem_str,
Thomas Wouters3fc2ca32006-04-21 11:28:17 +00004673 "(n)", index);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004674 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004675 res = call_method(self, "__setitem__", &setitem_str,
Thomas Wouters3fc2ca32006-04-21 11:28:17 +00004676 "(nO)", index, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004677 if (res == NULL)
4678 return -1;
4679 Py_DECREF(res);
4680 return 0;
4681}
4682
4683static int
Tim Peters6d6c1a32001-08-02 04:15:00 +00004684slot_sq_contains(PyObject *self, PyObject *value)
4685{
Guido van Rossumb8f63662001-08-15 23:57:02 +00004686 PyObject *func, *res, *args;
Tim Petersbf9b2442003-03-23 05:35:36 +00004687 int result = -1;
4688
Guido van Rossum60718732001-08-28 17:47:51 +00004689 static PyObject *contains_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004690
Guido van Rossum55f20992001-10-01 17:18:22 +00004691 func = lookup_maybe(self, "__contains__", &contains_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004692 if (func != NULL) {
Raymond Hettinger8ae46892003-10-12 19:09:37 +00004693 args = PyTuple_Pack(1, value);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004694 if (args == NULL)
4695 res = NULL;
4696 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00004697 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004698 Py_DECREF(args);
4699 }
4700 Py_DECREF(func);
Tim Petersbf9b2442003-03-23 05:35:36 +00004701 if (res != NULL) {
4702 result = PyObject_IsTrue(res);
4703 Py_DECREF(res);
4704 }
Guido van Rossumb8f63662001-08-15 23:57:02 +00004705 }
Tim Petersbf9b2442003-03-23 05:35:36 +00004706 else if (! PyErr_Occurred()) {
Martin v. Löwis725507b2006-03-07 12:08:51 +00004707 /* Possible results: -1 and 1 */
4708 result = (int)_PySequence_IterSearch(self, value,
Tim Petersbf9b2442003-03-23 05:35:36 +00004709 PY_ITERSEARCH_CONTAINS);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004710 }
Tim Petersbf9b2442003-03-23 05:35:36 +00004711 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004712}
4713
Tim Peters6d6c1a32001-08-02 04:15:00 +00004714#define slot_mp_length slot_sq_length
4715
Guido van Rossumdc91b992001-08-08 22:26:22 +00004716SLOT1(slot_mp_subscript, "__getitem__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004717
4718static int
4719slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value)
4720{
4721 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004722 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004723
4724 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004725 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004726 "(O)", key);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004727 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004728 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004729 "(OO)", key, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004730 if (res == NULL)
4731 return -1;
4732 Py_DECREF(res);
4733 return 0;
4734}
4735
Guido van Rossumdc91b992001-08-08 22:26:22 +00004736SLOT1BIN(slot_nb_add, nb_add, "__add__", "__radd__")
4737SLOT1BIN(slot_nb_subtract, nb_subtract, "__sub__", "__rsub__")
4738SLOT1BIN(slot_nb_multiply, nb_multiply, "__mul__", "__rmul__")
Guido van Rossumdc91b992001-08-08 22:26:22 +00004739SLOT1BIN(slot_nb_remainder, nb_remainder, "__mod__", "__rmod__")
4740SLOT1BIN(slot_nb_divmod, nb_divmod, "__divmod__", "__rdivmod__")
4741
Jeremy Hylton938ace62002-07-17 16:30:39 +00004742static PyObject *slot_nb_power(PyObject *, PyObject *, PyObject *);
Guido van Rossumdc91b992001-08-08 22:26:22 +00004743
4744SLOT1BINFULL(slot_nb_power_binary, slot_nb_power,
4745 nb_power, "__pow__", "__rpow__")
4746
4747static PyObject *
4748slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus)
4749{
Guido van Rossum2730b132001-08-28 18:22:14 +00004750 static PyObject *pow_str;
4751
Guido van Rossumdc91b992001-08-08 22:26:22 +00004752 if (modulus == Py_None)
4753 return slot_nb_power_binary(self, other);
Guido van Rossum23094982002-06-10 14:30:43 +00004754 /* Three-arg power doesn't use __rpow__. But ternary_op
4755 can call this when the second argument's type uses
4756 slot_nb_power, so check before calling self.__pow__. */
Christian Heimes90aa7642007-12-19 02:45:37 +00004757 if (Py_TYPE(self)->tp_as_number != NULL &&
4758 Py_TYPE(self)->tp_as_number->nb_power == slot_nb_power) {
Guido van Rossum23094982002-06-10 14:30:43 +00004759 return call_method(self, "__pow__", &pow_str,
4760 "(OO)", other, modulus);
4761 }
4762 Py_INCREF(Py_NotImplemented);
4763 return Py_NotImplemented;
Guido van Rossumdc91b992001-08-08 22:26:22 +00004764}
4765
4766SLOT0(slot_nb_negative, "__neg__")
4767SLOT0(slot_nb_positive, "__pos__")
4768SLOT0(slot_nb_absolute, "__abs__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004769
4770static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00004771slot_nb_bool(PyObject *self)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004772{
Tim Petersea7f75d2002-12-07 21:39:16 +00004773 PyObject *func, *args;
Jack Diederich4dafcc42006-11-28 19:15:13 +00004774 static PyObject *bool_str, *len_str;
Tim Petersea7f75d2002-12-07 21:39:16 +00004775 int result = -1;
Jack Diederich4dafcc42006-11-28 19:15:13 +00004776 int from_len = 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004777
Jack Diederich4dafcc42006-11-28 19:15:13 +00004778 func = lookup_maybe(self, "__bool__", &bool_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004779 if (func == NULL) {
Guido van Rossum55f20992001-10-01 17:18:22 +00004780 if (PyErr_Occurred())
Guido van Rossumb8f63662001-08-15 23:57:02 +00004781 return -1;
Guido van Rossum55f20992001-10-01 17:18:22 +00004782 func = lookup_maybe(self, "__len__", &len_str);
Tim Petersea7f75d2002-12-07 21:39:16 +00004783 if (func == NULL)
4784 return PyErr_Occurred() ? -1 : 1;
Jack Diederich4dafcc42006-11-28 19:15:13 +00004785 from_len = 1;
Tim Petersea7f75d2002-12-07 21:39:16 +00004786 }
4787 args = PyTuple_New(0);
4788 if (args != NULL) {
4789 PyObject *temp = PyObject_Call(func, args, NULL);
4790 Py_DECREF(args);
4791 if (temp != NULL) {
Jack Diederich4dafcc42006-11-28 19:15:13 +00004792 if (from_len) {
4793 /* enforced by slot_nb_len */
Jeremy Hylton090a3492003-06-27 16:46:45 +00004794 result = PyObject_IsTrue(temp);
Jack Diederich4dafcc42006-11-28 19:15:13 +00004795 }
4796 else if (PyBool_Check(temp)) {
4797 result = PyObject_IsTrue(temp);
4798 }
Jeremy Hylton090a3492003-06-27 16:46:45 +00004799 else {
4800 PyErr_Format(PyExc_TypeError,
Jack Diederich4dafcc42006-11-28 19:15:13 +00004801 "__bool__ should return "
4802 "bool, returned %s",
Christian Heimes90aa7642007-12-19 02:45:37 +00004803 Py_TYPE(temp)->tp_name);
Jeremy Hylton3e3159c2003-06-27 17:38:27 +00004804 result = -1;
Jeremy Hylton090a3492003-06-27 16:46:45 +00004805 }
Tim Petersea7f75d2002-12-07 21:39:16 +00004806 Py_DECREF(temp);
Guido van Rossum55f20992001-10-01 17:18:22 +00004807 }
Guido van Rossumb8f63662001-08-15 23:57:02 +00004808 }
Guido van Rossum55f20992001-10-01 17:18:22 +00004809 Py_DECREF(func);
Tim Petersea7f75d2002-12-07 21:39:16 +00004810 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004811}
4812
Guido van Rossum38fff8c2006-03-07 18:50:55 +00004813
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00004814static PyObject *
Guido van Rossum38fff8c2006-03-07 18:50:55 +00004815slot_nb_index(PyObject *self)
4816{
Guido van Rossum38fff8c2006-03-07 18:50:55 +00004817 static PyObject *index_str;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00004818 return call_method(self, "__index__", &index_str, "()");
Guido van Rossum38fff8c2006-03-07 18:50:55 +00004819}
4820
4821
Guido van Rossumdc91b992001-08-08 22:26:22 +00004822SLOT0(slot_nb_invert, "__invert__")
4823SLOT1BIN(slot_nb_lshift, nb_lshift, "__lshift__", "__rlshift__")
4824SLOT1BIN(slot_nb_rshift, nb_rshift, "__rshift__", "__rrshift__")
4825SLOT1BIN(slot_nb_and, nb_and, "__and__", "__rand__")
4826SLOT1BIN(slot_nb_xor, nb_xor, "__xor__", "__rxor__")
4827SLOT1BIN(slot_nb_or, nb_or, "__or__", "__ror__")
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004828
Guido van Rossumdc91b992001-08-08 22:26:22 +00004829SLOT0(slot_nb_int, "__int__")
4830SLOT0(slot_nb_long, "__long__")
4831SLOT0(slot_nb_float, "__float__")
Guido van Rossumdc91b992001-08-08 22:26:22 +00004832SLOT1(slot_nb_inplace_add, "__iadd__", PyObject *, "O")
4833SLOT1(slot_nb_inplace_subtract, "__isub__", PyObject *, "O")
4834SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *, "O")
Guido van Rossumdc91b992001-08-08 22:26:22 +00004835SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *, "O")
Thomas Wouterscf297e42007-02-23 15:07:44 +00004836/* Can't use SLOT1 here, because nb_inplace_power is ternary */
4837static PyObject *
4838slot_nb_inplace_power(PyObject *self, PyObject * arg1, PyObject *arg2)
4839{
4840 static PyObject *cache_str;
4841 return call_method(self, "__ipow__", &cache_str, "(" "O" ")", arg1);
4842}
Guido van Rossumdc91b992001-08-08 22:26:22 +00004843SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *, "O")
4844SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *, "O")
4845SLOT1(slot_nb_inplace_and, "__iand__", PyObject *, "O")
4846SLOT1(slot_nb_inplace_xor, "__ixor__", PyObject *, "O")
4847SLOT1(slot_nb_inplace_or, "__ior__", PyObject *, "O")
4848SLOT1BIN(slot_nb_floor_divide, nb_floor_divide,
4849 "__floordiv__", "__rfloordiv__")
4850SLOT1BIN(slot_nb_true_divide, nb_true_divide, "__truediv__", "__rtruediv__")
4851SLOT1(slot_nb_inplace_floor_divide, "__ifloordiv__", PyObject *, "O")
4852SLOT1(slot_nb_inplace_true_divide, "__itruediv__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004853
Guido van Rossumb8f63662001-08-15 23:57:02 +00004854static PyObject *
4855slot_tp_repr(PyObject *self)
4856{
4857 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004858 static PyObject *repr_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004859
Guido van Rossum60718732001-08-28 17:47:51 +00004860 func = lookup_method(self, "__repr__", &repr_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004861 if (func != NULL) {
4862 res = PyEval_CallObject(func, NULL);
4863 Py_DECREF(func);
4864 return res;
4865 }
Barry Warsaw7ce36942001-08-24 18:34:26 +00004866 PyErr_Clear();
Walter Dörwald1ab83302007-05-18 17:15:44 +00004867 return PyUnicode_FromFormat("<%s object at %p>",
Christian Heimes90aa7642007-12-19 02:45:37 +00004868 Py_TYPE(self)->tp_name, self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004869}
4870
4871static PyObject *
4872slot_tp_str(PyObject *self)
4873{
4874 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004875 static PyObject *str_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004876
Guido van Rossum60718732001-08-28 17:47:51 +00004877 func = lookup_method(self, "__str__", &str_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004878 if (func != NULL) {
4879 res = PyEval_CallObject(func, NULL);
4880 Py_DECREF(func);
4881 return res;
4882 }
4883 else {
Walter Dörwald1ab83302007-05-18 17:15:44 +00004884 PyObject *ress;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004885 PyErr_Clear();
Walter Dörwald1ab83302007-05-18 17:15:44 +00004886 res = slot_tp_repr(self);
4887 if (!res)
4888 return NULL;
4889 ress = _PyUnicode_AsDefaultEncodedString(res, NULL);
4890 Py_DECREF(res);
4891 return ress;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004892 }
4893}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004894
4895static long
4896slot_tp_hash(PyObject *self)
4897{
Guido van Rossum4011a242006-08-17 23:09:57 +00004898 PyObject *func, *res;
Guido van Rossum50e9fb92006-08-17 05:42:55 +00004899 static PyObject *hash_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004900 long h;
4901
Guido van Rossum60718732001-08-28 17:47:51 +00004902 func = lookup_method(self, "__hash__", &hash_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004903
Guido van Rossum50e9fb92006-08-17 05:42:55 +00004904 if (func == Py_None) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00004905 Py_DECREF(func);
Guido van Rossum50e9fb92006-08-17 05:42:55 +00004906 func = NULL;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004907 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +00004908
4909 if (func == NULL) {
Nick Coghland1abd252008-07-15 15:46:38 +00004910 return PyObject_HashNotImplemented(self);
Guido van Rossum50e9fb92006-08-17 05:42:55 +00004911 }
4912
Guido van Rossum4011a242006-08-17 23:09:57 +00004913 res = PyEval_CallObject(func, NULL);
Guido van Rossum50e9fb92006-08-17 05:42:55 +00004914 Py_DECREF(func);
4915 if (res == NULL)
4916 return -1;
4917 if (PyLong_Check(res))
4918 h = PyLong_Type.tp_hash(res);
4919 else
Christian Heimes217cfd12007-12-02 14:31:20 +00004920 h = PyLong_AsLong(res);
Guido van Rossum50e9fb92006-08-17 05:42:55 +00004921 Py_DECREF(res);
4922 if (h == -1 && !PyErr_Occurred())
4923 h = -2;
4924 return h;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004925}
4926
4927static PyObject *
4928slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds)
4929{
Guido van Rossum60718732001-08-28 17:47:51 +00004930 static PyObject *call_str;
4931 PyObject *meth = lookup_method(self, "__call__", &call_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004932 PyObject *res;
4933
4934 if (meth == NULL)
4935 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004936
Tim Peters6d6c1a32001-08-02 04:15:00 +00004937 res = PyObject_Call(meth, args, kwds);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004938
Tim Peters6d6c1a32001-08-02 04:15:00 +00004939 Py_DECREF(meth);
4940 return res;
4941}
4942
Guido van Rossum14a6f832001-10-17 13:59:09 +00004943/* There are two slot dispatch functions for tp_getattro.
4944
4945 - slot_tp_getattro() is used when __getattribute__ is overridden
4946 but no __getattr__ hook is present;
4947
4948 - slot_tp_getattr_hook() is used when a __getattr__ hook is present.
4949
Guido van Rossumc334df52002-04-04 23:44:47 +00004950 The code in update_one_slot() always installs slot_tp_getattr_hook(); this
4951 detects the absence of __getattr__ and then installs the simpler slot if
4952 necessary. */
Guido van Rossum14a6f832001-10-17 13:59:09 +00004953
Tim Peters6d6c1a32001-08-02 04:15:00 +00004954static PyObject *
4955slot_tp_getattro(PyObject *self, PyObject *name)
4956{
Guido van Rossum14a6f832001-10-17 13:59:09 +00004957 static PyObject *getattribute_str = NULL;
4958 return call_method(self, "__getattribute__", &getattribute_str,
4959 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004960}
4961
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004962static PyObject *
Benjamin Peterson9262b842008-11-17 22:45:50 +00004963call_attribute(PyObject *self, PyObject *attr, PyObject *name)
4964{
4965 PyObject *res, *descr = NULL;
4966 descrgetfunc f = Py_TYPE(attr)->tp_descr_get;
4967
4968 if (f != NULL) {
4969 descr = f(attr, self, (PyObject *)(Py_TYPE(self)));
4970 if (descr == NULL)
4971 return NULL;
4972 else
4973 attr = descr;
4974 }
4975 res = PyObject_CallFunctionObjArgs(attr, name, NULL);
4976 Py_XDECREF(descr);
4977 return res;
4978}
4979
4980static PyObject *
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004981slot_tp_getattr_hook(PyObject *self, PyObject *name)
4982{
Christian Heimes90aa7642007-12-19 02:45:37 +00004983 PyTypeObject *tp = Py_TYPE(self);
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004984 PyObject *getattr, *getattribute, *res;
4985 static PyObject *getattribute_str = NULL;
4986 static PyObject *getattr_str = NULL;
4987
4988 if (getattr_str == NULL) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00004989 getattr_str = PyUnicode_InternFromString("__getattr__");
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004990 if (getattr_str == NULL)
4991 return NULL;
4992 }
4993 if (getattribute_str == NULL) {
4994 getattribute_str =
Martin v. Löwis5b222132007-06-10 09:51:05 +00004995 PyUnicode_InternFromString("__getattribute__");
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004996 if (getattribute_str == NULL)
4997 return NULL;
4998 }
Benjamin Peterson9262b842008-11-17 22:45:50 +00004999 /* speed hack: we could use lookup_maybe, but that would resolve the
5000 method fully for each attribute lookup for classes with
5001 __getattr__, even when the attribute is present. So we use
5002 _PyType_Lookup and create the method only when needed, with
5003 call_attribute. */
Guido van Rossum19c1cd52001-09-21 21:24:49 +00005004 getattr = _PyType_Lookup(tp, getattr_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00005005 if (getattr == NULL) {
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005006 /* No __getattr__ hook: use a simpler dispatcher */
5007 tp->tp_getattro = slot_tp_getattro;
5008 return slot_tp_getattro(self, name);
5009 }
Benjamin Peterson9262b842008-11-17 22:45:50 +00005010 Py_INCREF(getattr);
5011 /* speed hack: we could use lookup_maybe, but that would resolve the
5012 method fully for each attribute lookup for classes with
5013 __getattr__, even when self has the default __getattribute__
5014 method. So we use _PyType_Lookup and create the method only when
5015 needed, with call_attribute. */
Guido van Rossum19c1cd52001-09-21 21:24:49 +00005016 getattribute = _PyType_Lookup(tp, getattribute_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00005017 if (getattribute == NULL ||
Christian Heimes90aa7642007-12-19 02:45:37 +00005018 (Py_TYPE(getattribute) == &PyWrapperDescr_Type &&
Guido van Rossum14a6f832001-10-17 13:59:09 +00005019 ((PyWrapperDescrObject *)getattribute)->d_wrapped ==
5020 (void *)PyObject_GenericGetAttr))
Guido van Rossum19c1cd52001-09-21 21:24:49 +00005021 res = PyObject_GenericGetAttr(self, name);
Benjamin Peterson9262b842008-11-17 22:45:50 +00005022 else {
5023 Py_INCREF(getattribute);
5024 res = call_attribute(self, getattribute, name);
5025 Py_DECREF(getattribute);
5026 }
Guido van Rossum14a6f832001-10-17 13:59:09 +00005027 if (res == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) {
Guido van Rossum19c1cd52001-09-21 21:24:49 +00005028 PyErr_Clear();
Benjamin Peterson9262b842008-11-17 22:45:50 +00005029 res = call_attribute(self, getattr, name);
Guido van Rossum19c1cd52001-09-21 21:24:49 +00005030 }
Benjamin Peterson9262b842008-11-17 22:45:50 +00005031 Py_DECREF(getattr);
Guido van Rossum19c1cd52001-09-21 21:24:49 +00005032 return res;
5033}
5034
Tim Peters6d6c1a32001-08-02 04:15:00 +00005035static int
5036slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value)
5037{
5038 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00005039 static PyObject *delattr_str, *setattr_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005040
5041 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00005042 res = call_method(self, "__delattr__", &delattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00005043 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005044 else
Guido van Rossum2730b132001-08-28 18:22:14 +00005045 res = call_method(self, "__setattr__", &setattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00005046 "(OO)", name, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005047 if (res == NULL)
5048 return -1;
5049 Py_DECREF(res);
5050 return 0;
5051}
5052
Guido van Rossumf5243f02008-01-01 04:06:48 +00005053static char *name_op[] = {
5054 "__lt__",
5055 "__le__",
5056 "__eq__",
5057 "__ne__",
5058 "__gt__",
5059 "__ge__",
5060};
5061
Tim Peters6d6c1a32001-08-02 04:15:00 +00005062static PyObject *
Guido van Rossumb8f63662001-08-15 23:57:02 +00005063half_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005064{
Guido van Rossumb8f63662001-08-15 23:57:02 +00005065 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00005066 static PyObject *op_str[6];
Tim Peters6d6c1a32001-08-02 04:15:00 +00005067
Guido van Rossum60718732001-08-28 17:47:51 +00005068 func = lookup_method(self, name_op[op], &op_str[op]);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005069 if (func == NULL) {
5070 PyErr_Clear();
5071 Py_INCREF(Py_NotImplemented);
5072 return Py_NotImplemented;
5073 }
Raymond Hettinger8ae46892003-10-12 19:09:37 +00005074 args = PyTuple_Pack(1, other);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005075 if (args == NULL)
5076 res = NULL;
5077 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00005078 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005079 Py_DECREF(args);
5080 }
5081 Py_DECREF(func);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005082 return res;
5083}
5084
Guido van Rossumb8f63662001-08-15 23:57:02 +00005085static PyObject *
5086slot_tp_richcompare(PyObject *self, PyObject *other, int op)
5087{
5088 PyObject *res;
5089
Christian Heimes90aa7642007-12-19 02:45:37 +00005090 if (Py_TYPE(self)->tp_richcompare == slot_tp_richcompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00005091 res = half_richcompare(self, other, op);
5092 if (res != Py_NotImplemented)
5093 return res;
5094 Py_DECREF(res);
5095 }
Christian Heimes90aa7642007-12-19 02:45:37 +00005096 if (Py_TYPE(other)->tp_richcompare == slot_tp_richcompare) {
Tim Petersf4aca752004-09-23 02:39:37 +00005097 res = half_richcompare(other, self, _Py_SwappedOp[op]);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005098 if (res != Py_NotImplemented) {
5099 return res;
5100 }
5101 Py_DECREF(res);
5102 }
5103 Py_INCREF(Py_NotImplemented);
5104 return Py_NotImplemented;
5105}
5106
5107static PyObject *
5108slot_tp_iter(PyObject *self)
5109{
5110 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00005111 static PyObject *iter_str, *getitem_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00005112
Guido van Rossum60718732001-08-28 17:47:51 +00005113 func = lookup_method(self, "__iter__", &iter_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005114 if (func != NULL) {
Guido van Rossum84b2bed2002-08-16 17:01:09 +00005115 PyObject *args;
5116 args = res = PyTuple_New(0);
5117 if (args != NULL) {
5118 res = PyObject_Call(func, args, NULL);
5119 Py_DECREF(args);
5120 }
5121 Py_DECREF(func);
5122 return res;
Guido van Rossumb8f63662001-08-15 23:57:02 +00005123 }
5124 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00005125 func = lookup_method(self, "__getitem__", &getitem_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005126 if (func == NULL) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005127 PyErr_Format(PyExc_TypeError,
5128 "'%.200s' object is not iterable",
Christian Heimes90aa7642007-12-19 02:45:37 +00005129 Py_TYPE(self)->tp_name);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005130 return NULL;
5131 }
5132 Py_DECREF(func);
5133 return PySeqIter_New(self);
5134}
Tim Peters6d6c1a32001-08-02 04:15:00 +00005135
5136static PyObject *
5137slot_tp_iternext(PyObject *self)
5138{
Guido van Rossum2730b132001-08-28 18:22:14 +00005139 static PyObject *next_str;
Georg Brandla18af4e2007-04-21 15:47:16 +00005140 return call_method(self, "__next__", &next_str, "()");
Tim Peters6d6c1a32001-08-02 04:15:00 +00005141}
5142
Guido van Rossum1a493502001-08-17 16:47:50 +00005143static PyObject *
5144slot_tp_descr_get(PyObject *self, PyObject *obj, PyObject *type)
5145{
Christian Heimes90aa7642007-12-19 02:45:37 +00005146 PyTypeObject *tp = Py_TYPE(self);
Guido van Rossum1a493502001-08-17 16:47:50 +00005147 PyObject *get;
5148 static PyObject *get_str = NULL;
5149
5150 if (get_str == NULL) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00005151 get_str = PyUnicode_InternFromString("__get__");
Guido van Rossum1a493502001-08-17 16:47:50 +00005152 if (get_str == NULL)
5153 return NULL;
5154 }
5155 get = _PyType_Lookup(tp, get_str);
5156 if (get == NULL) {
5157 /* Avoid further slowdowns */
5158 if (tp->tp_descr_get == slot_tp_descr_get)
5159 tp->tp_descr_get = NULL;
5160 Py_INCREF(self);
5161 return self;
5162 }
Guido van Rossum2c252392001-08-24 10:13:31 +00005163 if (obj == NULL)
5164 obj = Py_None;
5165 if (type == NULL)
5166 type = Py_None;
Thomas Wouters477c8d52006-05-27 19:21:47 +00005167 return PyObject_CallFunctionObjArgs(get, self, obj, type, NULL);
Guido van Rossum1a493502001-08-17 16:47:50 +00005168}
Tim Peters6d6c1a32001-08-02 04:15:00 +00005169
5170static int
5171slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value)
5172{
Guido van Rossum2c252392001-08-24 10:13:31 +00005173 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00005174 static PyObject *del_str, *set_str;
Guido van Rossum2c252392001-08-24 10:13:31 +00005175
5176 if (value == NULL)
Guido van Rossum1d5b3f22001-12-03 00:08:33 +00005177 res = call_method(self, "__delete__", &del_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00005178 "(O)", target);
Guido van Rossum2c252392001-08-24 10:13:31 +00005179 else
Guido van Rossum2730b132001-08-28 18:22:14 +00005180 res = call_method(self, "__set__", &set_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00005181 "(OO)", target, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005182 if (res == NULL)
5183 return -1;
5184 Py_DECREF(res);
5185 return 0;
5186}
5187
5188static int
5189slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds)
5190{
Guido van Rossum60718732001-08-28 17:47:51 +00005191 static PyObject *init_str;
5192 PyObject *meth = lookup_method(self, "__init__", &init_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005193 PyObject *res;
5194
5195 if (meth == NULL)
5196 return -1;
5197 res = PyObject_Call(meth, args, kwds);
5198 Py_DECREF(meth);
5199 if (res == NULL)
5200 return -1;
Raymond Hettingerb67cc802005-03-03 16:45:19 +00005201 if (res != Py_None) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005202 PyErr_Format(PyExc_TypeError,
5203 "__init__() should return None, not '%.200s'",
Christian Heimes90aa7642007-12-19 02:45:37 +00005204 Py_TYPE(res)->tp_name);
Raymond Hettingerb67cc802005-03-03 16:45:19 +00005205 Py_DECREF(res);
5206 return -1;
5207 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00005208 Py_DECREF(res);
5209 return 0;
5210}
5211
5212static PyObject *
5213slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
5214{
Guido van Rossum7bed2132002-08-08 21:57:53 +00005215 static PyObject *new_str;
5216 PyObject *func;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005217 PyObject *newargs, *x;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005218 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005219
Guido van Rossum7bed2132002-08-08 21:57:53 +00005220 if (new_str == NULL) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00005221 new_str = PyUnicode_InternFromString("__new__");
Guido van Rossum7bed2132002-08-08 21:57:53 +00005222 if (new_str == NULL)
5223 return NULL;
5224 }
5225 func = PyObject_GetAttr((PyObject *)type, new_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005226 if (func == NULL)
5227 return NULL;
5228 assert(PyTuple_Check(args));
5229 n = PyTuple_GET_SIZE(args);
5230 newargs = PyTuple_New(n+1);
5231 if (newargs == NULL)
5232 return NULL;
5233 Py_INCREF(type);
5234 PyTuple_SET_ITEM(newargs, 0, (PyObject *)type);
5235 for (i = 0; i < n; i++) {
5236 x = PyTuple_GET_ITEM(args, i);
5237 Py_INCREF(x);
5238 PyTuple_SET_ITEM(newargs, i+1, x);
5239 }
5240 x = PyObject_Call(func, newargs, kwds);
Guido van Rossum25d18072001-10-01 15:55:28 +00005241 Py_DECREF(newargs);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005242 Py_DECREF(func);
5243 return x;
5244}
5245
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005246static void
5247slot_tp_del(PyObject *self)
5248{
5249 static PyObject *del_str = NULL;
5250 PyObject *del, *res;
5251 PyObject *error_type, *error_value, *error_traceback;
5252
5253 /* Temporarily resurrect the object. */
5254 assert(self->ob_refcnt == 0);
5255 self->ob_refcnt = 1;
5256
5257 /* Save the current exception, if any. */
5258 PyErr_Fetch(&error_type, &error_value, &error_traceback);
5259
5260 /* Execute __del__ method, if any. */
5261 del = lookup_maybe(self, "__del__", &del_str);
5262 if (del != NULL) {
5263 res = PyEval_CallObject(del, NULL);
5264 if (res == NULL)
5265 PyErr_WriteUnraisable(del);
5266 else
5267 Py_DECREF(res);
5268 Py_DECREF(del);
5269 }
5270
5271 /* Restore the saved exception. */
5272 PyErr_Restore(error_type, error_value, error_traceback);
5273
5274 /* Undo the temporary resurrection; can't use DECREF here, it would
5275 * cause a recursive call.
5276 */
5277 assert(self->ob_refcnt > 0);
5278 if (--self->ob_refcnt == 0)
5279 return; /* this is the normal path out */
5280
5281 /* __del__ resurrected it! Make it look like the original Py_DECREF
5282 * never happened.
5283 */
5284 {
Martin v. Löwis725507b2006-03-07 12:08:51 +00005285 Py_ssize_t refcnt = self->ob_refcnt;
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005286 _Py_NewReference(self);
5287 self->ob_refcnt = refcnt;
5288 }
Christian Heimes90aa7642007-12-19 02:45:37 +00005289 assert(!PyType_IS_GC(Py_TYPE(self)) ||
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005290 _Py_AS_GC(self)->gc.gc_refs != _PyGC_REFS_UNTRACKED);
Michael W. Hudson3f3b6682004-08-03 10:21:03 +00005291 /* If Py_REF_DEBUG, _Py_NewReference bumped _Py_RefTotal, so
5292 * we need to undo that. */
5293 _Py_DEC_REFTOTAL;
5294 /* If Py_TRACE_REFS, _Py_NewReference re-added self to the object
5295 * chain, so no more to do there.
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005296 * If COUNT_ALLOCS, the original decref bumped tp_frees, and
5297 * _Py_NewReference bumped tp_allocs: both of those need to be
5298 * undone.
5299 */
5300#ifdef COUNT_ALLOCS
Christian Heimes90aa7642007-12-19 02:45:37 +00005301 --Py_TYPE(self)->tp_frees;
5302 --Py_TYPE(self)->tp_allocs;
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005303#endif
5304}
5305
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005306
5307/* Table mapping __foo__ names to tp_foo offsets and slot_tp_foo wrapper
Tim Petersbf9b2442003-03-23 05:35:36 +00005308 functions. The offsets here are relative to the 'PyHeapTypeObject'
Guido van Rossume5c691a2003-03-07 15:13:17 +00005309 structure, which incorporates the additional structures used for numbers,
5310 sequences and mappings.
5311 Note that multiple names may map to the same slot (e.g. __eq__,
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005312 __ne__ etc. all map to tp_richcompare) and one name may map to multiple
Guido van Rossumc334df52002-04-04 23:44:47 +00005313 slots (e.g. __str__ affects tp_str as well as tp_repr). The table is
5314 terminated with an all-zero entry. (This table is further initialized and
5315 sorted in init_slotdefs() below.) */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005316
Guido van Rossum6d204072001-10-21 00:44:31 +00005317typedef struct wrapperbase slotdef;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005318
5319#undef TPSLOT
Guido van Rossumc8e56452001-10-22 00:43:43 +00005320#undef FLSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005321#undef ETSLOT
5322#undef SQSLOT
5323#undef MPSLOT
5324#undef NBSLOT
Guido van Rossum6d204072001-10-21 00:44:31 +00005325#undef UNSLOT
5326#undef IBSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005327#undef BINSLOT
5328#undef RBINSLOT
5329
Guido van Rossum6d204072001-10-21 00:44:31 +00005330#define TPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Neal Norwitzd47714a2002-08-13 19:01:38 +00005331 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
5332 PyDoc_STR(DOC)}
Guido van Rossumc8e56452001-10-22 00:43:43 +00005333#define FLSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC, FLAGS) \
5334 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
Neal Norwitzd47714a2002-08-13 19:01:38 +00005335 PyDoc_STR(DOC), FLAGS}
Guido van Rossum6d204072001-10-21 00:44:31 +00005336#define ETSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Guido van Rossume5c691a2003-03-07 15:13:17 +00005337 {NAME, offsetof(PyHeapTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
Neal Norwitzd47714a2002-08-13 19:01:38 +00005338 PyDoc_STR(DOC)}
Guido van Rossum6d204072001-10-21 00:44:31 +00005339#define SQSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
5340 ETSLOT(NAME, as_sequence.SLOT, FUNCTION, WRAPPER, DOC)
5341#define MPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
5342 ETSLOT(NAME, as_mapping.SLOT, FUNCTION, WRAPPER, DOC)
5343#define NBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
5344 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, DOC)
5345#define UNSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
5346 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
5347 "x." NAME "() <==> " DOC)
5348#define IBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
5349 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
5350 "x." NAME "(y) <==> x" DOC "y")
5351#define BINSLOT(NAME, SLOT, FUNCTION, DOC) \
5352 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
5353 "x." NAME "(y) <==> x" DOC "y")
5354#define RBINSLOT(NAME, SLOT, FUNCTION, DOC) \
5355 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
5356 "x." NAME "(y) <==> y" DOC "x")
Anthony Baxter56616992005-06-03 14:12:21 +00005357#define BINSLOTNOTINFIX(NAME, SLOT, FUNCTION, DOC) \
5358 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
5359 "x." NAME "(y) <==> " DOC)
5360#define RBINSLOTNOTINFIX(NAME, SLOT, FUNCTION, DOC) \
5361 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
5362 "x." NAME "(y) <==> " DOC)
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005363
5364static slotdef slotdefs[] = {
Martin v. Löwis18e16552006-02-15 17:27:45 +00005365 SQSLOT("__len__", sq_length, slot_sq_length, wrap_lenfunc,
Guido van Rossum6d204072001-10-21 00:44:31 +00005366 "x.__len__() <==> len(x)"),
Armin Rigofd163f92005-12-29 15:59:19 +00005367 /* Heap types defining __add__/__mul__ have sq_concat/sq_repeat == NULL.
5368 The logic in abstract.c always falls back to nb_add/nb_multiply in
5369 this case. Defining both the nb_* and the sq_* slots to call the
5370 user-defined methods has unexpected side-effects, as shown by
5371 test_descr.notimplemented() */
5372 SQSLOT("__add__", sq_concat, NULL, wrap_binaryfunc,
Guido van Rossumd8faa362007-04-27 19:54:29 +00005373 "x.__add__(y) <==> x+y"),
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00005374 SQSLOT("__mul__", sq_repeat, NULL, wrap_indexargfunc,
Guido van Rossumd8faa362007-04-27 19:54:29 +00005375 "x.__mul__(n) <==> x*n"),
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00005376 SQSLOT("__rmul__", sq_repeat, NULL, wrap_indexargfunc,
Guido van Rossumd8faa362007-04-27 19:54:29 +00005377 "x.__rmul__(n) <==> n*x"),
Guido van Rossum6d204072001-10-21 00:44:31 +00005378 SQSLOT("__getitem__", sq_item, slot_sq_item, wrap_sq_item,
5379 "x.__getitem__(y) <==> x[y]"),
Guido van Rossum6d204072001-10-21 00:44:31 +00005380 SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_setitem,
Brett Cannonbe67d872003-05-20 02:40:12 +00005381 "x.__setitem__(i, y) <==> x[i]=y"),
Guido van Rossum6d204072001-10-21 00:44:31 +00005382 SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_delitem,
Brett Cannonbe67d872003-05-20 02:40:12 +00005383 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum6d204072001-10-21 00:44:31 +00005384 SQSLOT("__contains__", sq_contains, slot_sq_contains, wrap_objobjproc,
5385 "x.__contains__(y) <==> y in x"),
Armin Rigofd163f92005-12-29 15:59:19 +00005386 SQSLOT("__iadd__", sq_inplace_concat, NULL,
Guido van Rossumd8faa362007-04-27 19:54:29 +00005387 wrap_binaryfunc, "x.__iadd__(y) <==> x+=y"),
Armin Rigofd163f92005-12-29 15:59:19 +00005388 SQSLOT("__imul__", sq_inplace_repeat, NULL,
Guido van Rossumd8faa362007-04-27 19:54:29 +00005389 wrap_indexargfunc, "x.__imul__(y) <==> x*=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005390
Martin v. Löwis18e16552006-02-15 17:27:45 +00005391 MPSLOT("__len__", mp_length, slot_mp_length, wrap_lenfunc,
Guido van Rossum6d204072001-10-21 00:44:31 +00005392 "x.__len__() <==> len(x)"),
Guido van Rossumfd38f8e2001-10-09 20:17:57 +00005393 MPSLOT("__getitem__", mp_subscript, slot_mp_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00005394 wrap_binaryfunc,
5395 "x.__getitem__(y) <==> x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005396 MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00005397 wrap_objobjargproc,
5398 "x.__setitem__(i, y) <==> x[i]=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005399 MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00005400 wrap_delitem,
5401 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005402
Guido van Rossum6d204072001-10-21 00:44:31 +00005403 BINSLOT("__add__", nb_add, slot_nb_add,
5404 "+"),
5405 RBINSLOT("__radd__", nb_add, slot_nb_add,
5406 "+"),
5407 BINSLOT("__sub__", nb_subtract, slot_nb_subtract,
5408 "-"),
5409 RBINSLOT("__rsub__", nb_subtract, slot_nb_subtract,
5410 "-"),
5411 BINSLOT("__mul__", nb_multiply, slot_nb_multiply,
5412 "*"),
5413 RBINSLOT("__rmul__", nb_multiply, slot_nb_multiply,
5414 "*"),
Guido van Rossum6d204072001-10-21 00:44:31 +00005415 BINSLOT("__mod__", nb_remainder, slot_nb_remainder,
5416 "%"),
5417 RBINSLOT("__rmod__", nb_remainder, slot_nb_remainder,
5418 "%"),
Anthony Baxter56616992005-06-03 14:12:21 +00005419 BINSLOTNOTINFIX("__divmod__", nb_divmod, slot_nb_divmod,
Guido van Rossum6d204072001-10-21 00:44:31 +00005420 "divmod(x, y)"),
Anthony Baxter56616992005-06-03 14:12:21 +00005421 RBINSLOTNOTINFIX("__rdivmod__", nb_divmod, slot_nb_divmod,
Guido van Rossum6d204072001-10-21 00:44:31 +00005422 "divmod(y, x)"),
5423 NBSLOT("__pow__", nb_power, slot_nb_power, wrap_ternaryfunc,
5424 "x.__pow__(y[, z]) <==> pow(x, y[, z])"),
5425 NBSLOT("__rpow__", nb_power, slot_nb_power, wrap_ternaryfunc_r,
5426 "y.__rpow__(x[, z]) <==> pow(x, y[, z])"),
5427 UNSLOT("__neg__", nb_negative, slot_nb_negative, wrap_unaryfunc, "-x"),
5428 UNSLOT("__pos__", nb_positive, slot_nb_positive, wrap_unaryfunc, "+x"),
5429 UNSLOT("__abs__", nb_absolute, slot_nb_absolute, wrap_unaryfunc,
5430 "abs(x)"),
Jack Diederich4dafcc42006-11-28 19:15:13 +00005431 UNSLOT("__bool__", nb_bool, slot_nb_bool, wrap_inquirypred,
Guido van Rossum6d204072001-10-21 00:44:31 +00005432 "x != 0"),
5433 UNSLOT("__invert__", nb_invert, slot_nb_invert, wrap_unaryfunc, "~x"),
5434 BINSLOT("__lshift__", nb_lshift, slot_nb_lshift, "<<"),
5435 RBINSLOT("__rlshift__", nb_lshift, slot_nb_lshift, "<<"),
5436 BINSLOT("__rshift__", nb_rshift, slot_nb_rshift, ">>"),
5437 RBINSLOT("__rrshift__", nb_rshift, slot_nb_rshift, ">>"),
5438 BINSLOT("__and__", nb_and, slot_nb_and, "&"),
5439 RBINSLOT("__rand__", nb_and, slot_nb_and, "&"),
5440 BINSLOT("__xor__", nb_xor, slot_nb_xor, "^"),
5441 RBINSLOT("__rxor__", nb_xor, slot_nb_xor, "^"),
5442 BINSLOT("__or__", nb_or, slot_nb_or, "|"),
5443 RBINSLOT("__ror__", nb_or, slot_nb_or, "|"),
Guido van Rossum6d204072001-10-21 00:44:31 +00005444 UNSLOT("__int__", nb_int, slot_nb_int, wrap_unaryfunc,
5445 "int(x)"),
5446 UNSLOT("__long__", nb_long, slot_nb_long, wrap_unaryfunc,
5447 "long(x)"),
5448 UNSLOT("__float__", nb_float, slot_nb_float, wrap_unaryfunc,
5449 "float(x)"),
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00005450 NBSLOT("__index__", nb_index, slot_nb_index, wrap_unaryfunc,
Guido van Rossum38fff8c2006-03-07 18:50:55 +00005451 "x[y:z] <==> x[y.__index__():z.__index__()]"),
Guido van Rossum6d204072001-10-21 00:44:31 +00005452 IBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add,
5453 wrap_binaryfunc, "+"),
5454 IBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract,
5455 wrap_binaryfunc, "-"),
5456 IBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply,
5457 wrap_binaryfunc, "*"),
Guido van Rossum6d204072001-10-21 00:44:31 +00005458 IBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder,
5459 wrap_binaryfunc, "%"),
5460 IBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power,
Guido van Rossum6e5680f2002-10-15 01:01:53 +00005461 wrap_binaryfunc, "**"),
Guido van Rossum6d204072001-10-21 00:44:31 +00005462 IBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift,
5463 wrap_binaryfunc, "<<"),
5464 IBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift,
5465 wrap_binaryfunc, ">>"),
5466 IBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and,
5467 wrap_binaryfunc, "&"),
5468 IBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor,
5469 wrap_binaryfunc, "^"),
5470 IBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or,
5471 wrap_binaryfunc, "|"),
5472 BINSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
5473 RBINSLOT("__rfloordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
5474 BINSLOT("__truediv__", nb_true_divide, slot_nb_true_divide, "/"),
5475 RBINSLOT("__rtruediv__", nb_true_divide, slot_nb_true_divide, "/"),
5476 IBSLOT("__ifloordiv__", nb_inplace_floor_divide,
5477 slot_nb_inplace_floor_divide, wrap_binaryfunc, "//"),
5478 IBSLOT("__itruediv__", nb_inplace_true_divide,
5479 slot_nb_inplace_true_divide, wrap_binaryfunc, "/"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005480
Guido van Rossum6d204072001-10-21 00:44:31 +00005481 TPSLOT("__str__", tp_str, slot_tp_str, wrap_unaryfunc,
5482 "x.__str__() <==> str(x)"),
5483 TPSLOT("__repr__", tp_repr, slot_tp_repr, wrap_unaryfunc,
5484 "x.__repr__() <==> repr(x)"),
Guido van Rossum6d204072001-10-21 00:44:31 +00005485 TPSLOT("__hash__", tp_hash, slot_tp_hash, wrap_hashfunc,
5486 "x.__hash__() <==> hash(x)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00005487 FLSLOT("__call__", tp_call, slot_tp_call, (wrapperfunc)wrap_call,
5488 "x.__call__(...) <==> x(...)", PyWrapperFlag_KEYWORDS),
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005489 TPSLOT("__getattribute__", tp_getattro, slot_tp_getattr_hook,
Guido van Rossum6d204072001-10-21 00:44:31 +00005490 wrap_binaryfunc, "x.__getattribute__('name') <==> x.name"),
5491 TPSLOT("__getattribute__", tp_getattr, NULL, NULL, ""),
5492 TPSLOT("__getattr__", tp_getattro, slot_tp_getattr_hook, NULL, ""),
5493 TPSLOT("__getattr__", tp_getattr, NULL, NULL, ""),
5494 TPSLOT("__setattr__", tp_setattro, slot_tp_setattro, wrap_setattr,
5495 "x.__setattr__('name', value) <==> x.name = value"),
5496 TPSLOT("__setattr__", tp_setattr, NULL, NULL, ""),
5497 TPSLOT("__delattr__", tp_setattro, slot_tp_setattro, wrap_delattr,
5498 "x.__delattr__('name') <==> del x.name"),
5499 TPSLOT("__delattr__", tp_setattr, NULL, NULL, ""),
5500 TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare, richcmp_lt,
5501 "x.__lt__(y) <==> x<y"),
5502 TPSLOT("__le__", tp_richcompare, slot_tp_richcompare, richcmp_le,
5503 "x.__le__(y) <==> x<=y"),
5504 TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare, richcmp_eq,
5505 "x.__eq__(y) <==> x==y"),
5506 TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare, richcmp_ne,
5507 "x.__ne__(y) <==> x!=y"),
5508 TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare, richcmp_gt,
5509 "x.__gt__(y) <==> x>y"),
5510 TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare, richcmp_ge,
5511 "x.__ge__(y) <==> x>=y"),
5512 TPSLOT("__iter__", tp_iter, slot_tp_iter, wrap_unaryfunc,
5513 "x.__iter__() <==> iter(x)"),
Georg Brandla18af4e2007-04-21 15:47:16 +00005514 TPSLOT("__next__", tp_iternext, slot_tp_iternext, wrap_next,
5515 "x.__next__() <==> next(x)"),
Guido van Rossum6d204072001-10-21 00:44:31 +00005516 TPSLOT("__get__", tp_descr_get, slot_tp_descr_get, wrap_descr_get,
5517 "descr.__get__(obj[, type]) -> value"),
5518 TPSLOT("__set__", tp_descr_set, slot_tp_descr_set, wrap_descr_set,
5519 "descr.__set__(obj, value)"),
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00005520 TPSLOT("__delete__", tp_descr_set, slot_tp_descr_set,
5521 wrap_descr_delete, "descr.__delete__(obj)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00005522 FLSLOT("__init__", tp_init, slot_tp_init, (wrapperfunc)wrap_init,
Guido van Rossum6d204072001-10-21 00:44:31 +00005523 "x.__init__(...) initializes x; "
Guido van Rossumc8e56452001-10-22 00:43:43 +00005524 "see x.__class__.__doc__ for signature",
5525 PyWrapperFlag_KEYWORDS),
5526 TPSLOT("__new__", tp_new, slot_tp_new, NULL, ""),
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005527 TPSLOT("__del__", tp_del, slot_tp_del, NULL, ""),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005528 {NULL}
5529};
5530
Guido van Rossumc334df52002-04-04 23:44:47 +00005531/* Given a type pointer and an offset gotten from a slotdef entry, return a
Guido van Rossumd8faa362007-04-27 19:54:29 +00005532 pointer to the actual slot. This is not quite the same as simply adding
Guido van Rossumc334df52002-04-04 23:44:47 +00005533 the offset to the type pointer, since it takes care to indirect through the
5534 proper indirection pointer (as_buffer, etc.); it returns NULL if the
5535 indirection pointer is NULL. */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005536static void **
Martin v. Löwis18e16552006-02-15 17:27:45 +00005537slotptr(PyTypeObject *type, int ioffset)
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005538{
5539 char *ptr;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005540 long offset = ioffset;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005541
Guido van Rossume5c691a2003-03-07 15:13:17 +00005542 /* Note: this depends on the order of the members of PyHeapTypeObject! */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005543 assert(offset >= 0);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00005544 assert((size_t)offset < offsetof(PyHeapTypeObject, as_buffer));
5545 if ((size_t)offset >= offsetof(PyHeapTypeObject, as_sequence)) {
5546 ptr = (char *)type->tp_as_sequence;
Guido van Rossume5c691a2003-03-07 15:13:17 +00005547 offset -= offsetof(PyHeapTypeObject, as_sequence);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005548 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00005549 else if ((size_t)offset >= offsetof(PyHeapTypeObject, as_mapping)) {
5550 ptr = (char *)type->tp_as_mapping;
Guido van Rossume5c691a2003-03-07 15:13:17 +00005551 offset -= offsetof(PyHeapTypeObject, as_mapping);
Guido van Rossum09638c12002-06-13 19:17:46 +00005552 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00005553 else if ((size_t)offset >= offsetof(PyHeapTypeObject, as_number)) {
5554 ptr = (char *)type->tp_as_number;
Guido van Rossume5c691a2003-03-07 15:13:17 +00005555 offset -= offsetof(PyHeapTypeObject, as_number);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005556 }
5557 else {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00005558 ptr = (char *)type;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005559 }
5560 if (ptr != NULL)
5561 ptr += offset;
5562 return (void **)ptr;
5563}
Guido van Rossumf040ede2001-08-07 16:40:56 +00005564
Guido van Rossumc334df52002-04-04 23:44:47 +00005565/* Length of array of slotdef pointers used to store slots with the
5566 same __name__. There should be at most MAX_EQUIV-1 slotdef entries with
5567 the same __name__, for any __name__. Since that's a static property, it is
5568 appropriate to declare fixed-size arrays for this. */
5569#define MAX_EQUIV 10
5570
5571/* Return a slot pointer for a given name, but ONLY if the attribute has
5572 exactly one slot function. The name must be an interned string. */
5573static void **
5574resolve_slotdups(PyTypeObject *type, PyObject *name)
5575{
5576 /* XXX Maybe this could be optimized more -- but is it worth it? */
5577
5578 /* pname and ptrs act as a little cache */
5579 static PyObject *pname;
5580 static slotdef *ptrs[MAX_EQUIV];
5581 slotdef *p, **pp;
5582 void **res, **ptr;
5583
5584 if (pname != name) {
5585 /* Collect all slotdefs that match name into ptrs. */
5586 pname = name;
5587 pp = ptrs;
5588 for (p = slotdefs; p->name_strobj; p++) {
5589 if (p->name_strobj == name)
5590 *pp++ = p;
5591 }
5592 *pp = NULL;
5593 }
5594
5595 /* Look in all matching slots of the type; if exactly one of these has
Guido van Rossumd8faa362007-04-27 19:54:29 +00005596 a filled-in slot, return its value. Otherwise return NULL. */
Guido van Rossumc334df52002-04-04 23:44:47 +00005597 res = NULL;
5598 for (pp = ptrs; *pp; pp++) {
5599 ptr = slotptr(type, (*pp)->offset);
5600 if (ptr == NULL || *ptr == NULL)
5601 continue;
5602 if (res != NULL)
5603 return NULL;
5604 res = ptr;
5605 }
5606 return res;
5607}
5608
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005609/* Common code for update_slots_callback() and fixup_slot_dispatchers(). This
Guido van Rossumc334df52002-04-04 23:44:47 +00005610 does some incredibly complex thinking and then sticks something into the
5611 slot. (It sees if the adjacent slotdefs for the same slot have conflicting
5612 interests, and then stores a generic wrapper or a specific function into
5613 the slot.) Return a pointer to the next slotdef with a different offset,
5614 because that's convenient for fixup_slot_dispatchers(). */
5615static slotdef *
5616update_one_slot(PyTypeObject *type, slotdef *p)
5617{
5618 PyObject *descr;
5619 PyWrapperDescrObject *d;
5620 void *generic = NULL, *specific = NULL;
5621 int use_generic = 0;
5622 int offset = p->offset;
5623 void **ptr = slotptr(type, offset);
5624
5625 if (ptr == NULL) {
5626 do {
5627 ++p;
5628 } while (p->offset == offset);
5629 return p;
5630 }
5631 do {
5632 descr = _PyType_Lookup(type, p->name_strobj);
5633 if (descr == NULL)
5634 continue;
Christian Heimes90aa7642007-12-19 02:45:37 +00005635 if (Py_TYPE(descr) == &PyWrapperDescr_Type) {
Guido van Rossumc334df52002-04-04 23:44:47 +00005636 void **tptr = resolve_slotdups(type, p->name_strobj);
5637 if (tptr == NULL || tptr == ptr)
5638 generic = p->function;
5639 d = (PyWrapperDescrObject *)descr;
5640 if (d->d_base->wrapper == p->wrapper &&
5641 PyType_IsSubtype(type, d->d_type))
5642 {
5643 if (specific == NULL ||
5644 specific == d->d_wrapped)
5645 specific = d->d_wrapped;
5646 else
5647 use_generic = 1;
5648 }
5649 }
Christian Heimes90aa7642007-12-19 02:45:37 +00005650 else if (Py_TYPE(descr) == &PyCFunction_Type &&
Guido van Rossum721f62e2002-08-09 02:14:34 +00005651 PyCFunction_GET_FUNCTION(descr) ==
5652 (PyCFunction)tp_new_wrapper &&
5653 strcmp(p->name, "__new__") == 0)
5654 {
5655 /* The __new__ wrapper is not a wrapper descriptor,
5656 so must be special-cased differently.
5657 If we don't do this, creating an instance will
5658 always use slot_tp_new which will look up
5659 __new__ in the MRO which will call tp_new_wrapper
5660 which will look through the base classes looking
5661 for a static base and call its tp_new (usually
5662 PyType_GenericNew), after performing various
5663 sanity checks and constructing a new argument
5664 list. Cut all that nonsense short -- this speeds
5665 up instance creation tremendously. */
Martin v. Löwisa94568a2003-05-10 07:36:56 +00005666 specific = (void *)type->tp_new;
Guido van Rossum721f62e2002-08-09 02:14:34 +00005667 /* XXX I'm not 100% sure that there isn't a hole
5668 in this reasoning that requires additional
5669 sanity checks. I'll buy the first person to
5670 point out a bug in this reasoning a beer. */
5671 }
Nick Coghland1abd252008-07-15 15:46:38 +00005672 else if (descr == Py_None &&
5673 strcmp(p->name, "__hash__") == 0) {
5674 /* We specifically allow __hash__ to be set to None
5675 to prevent inheritance of the default
5676 implementation from object.__hash__ */
5677 specific = PyObject_HashNotImplemented;
5678 }
Guido van Rossumc334df52002-04-04 23:44:47 +00005679 else {
5680 use_generic = 1;
5681 generic = p->function;
5682 }
5683 } while ((++p)->offset == offset);
5684 if (specific && !use_generic)
5685 *ptr = specific;
5686 else
5687 *ptr = generic;
5688 return p;
5689}
5690
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005691/* In the type, update the slots whose slotdefs are gathered in the pp array.
5692 This is a callback for update_subclasses(). */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005693static int
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005694update_slots_callback(PyTypeObject *type, void *data)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005695{
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005696 slotdef **pp = (slotdef **)data;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005697
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005698 for (; *pp; pp++)
Guido van Rossumc334df52002-04-04 23:44:47 +00005699 update_one_slot(type, *pp);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005700 return 0;
5701}
5702
Guido van Rossumc334df52002-04-04 23:44:47 +00005703/* Comparison function for qsort() to compare slotdefs by their offset, and
5704 for equal offset by their address (to force a stable sort). */
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005705static int
5706slotdef_cmp(const void *aa, const void *bb)
5707{
5708 const slotdef *a = (const slotdef *)aa, *b = (const slotdef *)bb;
5709 int c = a->offset - b->offset;
5710 if (c != 0)
5711 return c;
5712 else
Martin v. Löwis18e16552006-02-15 17:27:45 +00005713 /* Cannot use a-b, as this gives off_t,
5714 which may lose precision when converted to int. */
5715 return (a > b) ? 1 : (a < b) ? -1 : 0;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005716}
5717
Guido van Rossumc334df52002-04-04 23:44:47 +00005718/* Initialize the slotdefs table by adding interned string objects for the
5719 names and sorting the entries. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005720static void
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005721init_slotdefs(void)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005722{
5723 slotdef *p;
5724 static int initialized = 0;
5725
5726 if (initialized)
5727 return;
5728 for (p = slotdefs; p->name; p++) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00005729 p->name_strobj = PyUnicode_InternFromString(p->name);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005730 if (!p->name_strobj)
Guido van Rossumc334df52002-04-04 23:44:47 +00005731 Py_FatalError("Out of memory interning slotdef names");
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005732 }
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005733 qsort((void *)slotdefs, (size_t)(p-slotdefs), sizeof(slotdef),
5734 slotdef_cmp);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005735 initialized = 1;
5736}
5737
Guido van Rossumc334df52002-04-04 23:44:47 +00005738/* Update the slots after assignment to a class (type) attribute. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005739static int
5740update_slot(PyTypeObject *type, PyObject *name)
5741{
Guido van Rossumc334df52002-04-04 23:44:47 +00005742 slotdef *ptrs[MAX_EQUIV];
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005743 slotdef *p;
5744 slotdef **pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005745 int offset;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005746
Christian Heimesa62da1d2008-01-12 19:39:10 +00005747 /* Clear the VALID_VERSION flag of 'type' and all its
5748 subclasses. This could possibly be unified with the
5749 update_subclasses() recursion below, but carefully:
5750 they each have their own conditions on which to stop
5751 recursing into subclasses. */
Georg Brandlf08a9dd2008-06-10 16:57:31 +00005752 PyType_Modified(type);
Christian Heimesa62da1d2008-01-12 19:39:10 +00005753
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005754 init_slotdefs();
5755 pp = ptrs;
5756 for (p = slotdefs; p->name; p++) {
5757 /* XXX assume name is interned! */
5758 if (p->name_strobj == name)
5759 *pp++ = p;
5760 }
5761 *pp = NULL;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005762 for (pp = ptrs; *pp; pp++) {
5763 p = *pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005764 offset = p->offset;
5765 while (p > slotdefs && (p-1)->offset == offset)
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005766 --p;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005767 *pp = p;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005768 }
Guido van Rossumc334df52002-04-04 23:44:47 +00005769 if (ptrs[0] == NULL)
5770 return 0; /* Not an attribute that affects any slots */
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005771 return update_subclasses(type, name,
5772 update_slots_callback, (void *)ptrs);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005773}
5774
Guido van Rossumc334df52002-04-04 23:44:47 +00005775/* Store the proper functions in the slot dispatches at class (type)
5776 definition time, based upon which operations the class overrides in its
5777 dict. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00005778static void
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005779fixup_slot_dispatchers(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005780{
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005781 slotdef *p;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005782
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005783 init_slotdefs();
Guido van Rossumc334df52002-04-04 23:44:47 +00005784 for (p = slotdefs; p->name; )
5785 p = update_one_slot(type, p);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005786}
Guido van Rossum705f0f52001-08-24 16:47:00 +00005787
Michael W. Hudson98bbc492002-11-26 14:47:27 +00005788static void
5789update_all_slots(PyTypeObject* type)
5790{
5791 slotdef *p;
5792
5793 init_slotdefs();
5794 for (p = slotdefs; p->name; p++) {
5795 /* update_slot returns int but can't actually fail */
5796 update_slot(type, p->name_strobj);
5797 }
5798}
5799
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005800/* recurse_down_subclasses() and update_subclasses() are mutually
5801 recursive functions to call a callback for all subclasses,
5802 but refraining from recursing into subclasses that define 'name'. */
5803
5804static int
5805update_subclasses(PyTypeObject *type, PyObject *name,
5806 update_callback callback, void *data)
5807{
5808 if (callback(type, data) < 0)
5809 return -1;
5810 return recurse_down_subclasses(type, name, callback, data);
5811}
5812
5813static int
5814recurse_down_subclasses(PyTypeObject *type, PyObject *name,
5815 update_callback callback, void *data)
5816{
5817 PyTypeObject *subclass;
5818 PyObject *ref, *subclasses, *dict;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005819 Py_ssize_t i, n;
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005820
5821 subclasses = type->tp_subclasses;
5822 if (subclasses == NULL)
5823 return 0;
5824 assert(PyList_Check(subclasses));
5825 n = PyList_GET_SIZE(subclasses);
5826 for (i = 0; i < n; i++) {
5827 ref = PyList_GET_ITEM(subclasses, i);
5828 assert(PyWeakref_CheckRef(ref));
5829 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
5830 assert(subclass != NULL);
5831 if ((PyObject *)subclass == Py_None)
5832 continue;
5833 assert(PyType_Check(subclass));
5834 /* Avoid recursing down into unaffected classes */
5835 dict = subclass->tp_dict;
5836 if (dict != NULL && PyDict_Check(dict) &&
5837 PyDict_GetItem(dict, name) != NULL)
5838 continue;
5839 if (update_subclasses(subclass, name, callback, data) < 0)
5840 return -1;
5841 }
5842 return 0;
5843}
5844
Guido van Rossum6d204072001-10-21 00:44:31 +00005845/* This function is called by PyType_Ready() to populate the type's
5846 dictionary with method descriptors for function slots. For each
Guido van Rossum09638c12002-06-13 19:17:46 +00005847 function slot (like tp_repr) that's defined in the type, one or more
5848 corresponding descriptors are added in the type's tp_dict dictionary
Guido van Rossumd8faa362007-04-27 19:54:29 +00005849 under the appropriate name (like __repr__). Some function slots
Guido van Rossum09638c12002-06-13 19:17:46 +00005850 cause more than one descriptor to be added (for example, the nb_add
5851 slot adds both __add__ and __radd__ descriptors) and some function
5852 slots compete for the same descriptor (for example both sq_item and
5853 mp_subscript generate a __getitem__ descriptor).
5854
Guido van Rossumd8faa362007-04-27 19:54:29 +00005855 In the latter case, the first slotdef entry encoutered wins. Since
Tim Petersbf9b2442003-03-23 05:35:36 +00005856 slotdef entries are sorted by the offset of the slot in the
Guido van Rossume5c691a2003-03-07 15:13:17 +00005857 PyHeapTypeObject, this gives us some control over disambiguating
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005858 between competing slots: the members of PyHeapTypeObject are listed
5859 from most general to least general, so the most general slot is
5860 preferred. In particular, because as_mapping comes before as_sequence,
5861 for a type that defines both mp_subscript and sq_item, mp_subscript
5862 wins.
Guido van Rossum09638c12002-06-13 19:17:46 +00005863
5864 This only adds new descriptors and doesn't overwrite entries in
5865 tp_dict that were previously defined. The descriptors contain a
5866 reference to the C function they must call, so that it's safe if they
5867 are copied into a subtype's __dict__ and the subtype has a different
5868 C function in its slot -- calling the method defined by the
5869 descriptor will call the C function that was used to create it,
5870 rather than the C function present in the slot when it is called.
5871 (This is important because a subtype may have a C function in the
5872 slot that calls the method from the dictionary, and we want to avoid
5873 infinite recursion here.) */
Guido van Rossum6d204072001-10-21 00:44:31 +00005874
5875static int
5876add_operators(PyTypeObject *type)
5877{
5878 PyObject *dict = type->tp_dict;
5879 slotdef *p;
5880 PyObject *descr;
5881 void **ptr;
5882
5883 init_slotdefs();
5884 for (p = slotdefs; p->name; p++) {
5885 if (p->wrapper == NULL)
5886 continue;
5887 ptr = slotptr(type, p->offset);
5888 if (!ptr || !*ptr)
5889 continue;
5890 if (PyDict_GetItem(dict, p->name_strobj))
5891 continue;
Nick Coghland1abd252008-07-15 15:46:38 +00005892 if (*ptr == PyObject_HashNotImplemented) {
5893 /* Classes may prevent the inheritance of the tp_hash
5894 slot by storing PyObject_HashNotImplemented in it. Make it
5895 visible as a None value for the __hash__ attribute. */
5896 if (PyDict_SetItem(dict, p->name_strobj, Py_None) < 0)
5897 return -1;
5898 }
5899 else {
5900 descr = PyDescr_NewWrapper(type, p, *ptr);
5901 if (descr == NULL)
5902 return -1;
5903 if (PyDict_SetItem(dict, p->name_strobj, descr) < 0)
5904 return -1;
5905 Py_DECREF(descr);
5906 }
Guido van Rossum6d204072001-10-21 00:44:31 +00005907 }
5908 if (type->tp_new != NULL) {
5909 if (add_tp_new_wrapper(type) < 0)
5910 return -1;
5911 }
5912 return 0;
5913}
5914
Guido van Rossum705f0f52001-08-24 16:47:00 +00005915
5916/* Cooperative 'super' */
5917
5918typedef struct {
5919 PyObject_HEAD
Guido van Rossume705ef12001-08-29 15:47:06 +00005920 PyTypeObject *type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005921 PyObject *obj;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005922 PyTypeObject *obj_type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005923} superobject;
5924
Guido van Rossum6f799372001-09-20 20:46:19 +00005925static PyMemberDef super_members[] = {
5926 {"__thisclass__", T_OBJECT, offsetof(superobject, type), READONLY,
5927 "the class invoking super()"},
5928 {"__self__", T_OBJECT, offsetof(superobject, obj), READONLY,
5929 "the instance invoking super(); may be None"},
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005930 {"__self_class__", T_OBJECT, offsetof(superobject, obj_type), READONLY,
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +00005931 "the type of the instance invoking super(); may be None"},
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005932 {0}
5933};
5934
Guido van Rossum705f0f52001-08-24 16:47:00 +00005935static void
5936super_dealloc(PyObject *self)
5937{
5938 superobject *su = (superobject *)self;
5939
Guido van Rossum048eb752001-10-02 21:24:57 +00005940 _PyObject_GC_UNTRACK(self);
Guido van Rossum705f0f52001-08-24 16:47:00 +00005941 Py_XDECREF(su->obj);
5942 Py_XDECREF(su->type);
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005943 Py_XDECREF(su->obj_type);
Christian Heimes90aa7642007-12-19 02:45:37 +00005944 Py_TYPE(self)->tp_free(self);
Guido van Rossum705f0f52001-08-24 16:47:00 +00005945}
5946
5947static PyObject *
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005948super_repr(PyObject *self)
5949{
5950 superobject *su = (superobject *)self;
5951
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005952 if (su->obj_type)
Walter Dörwald1ab83302007-05-18 17:15:44 +00005953 return PyUnicode_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00005954 "<super: <class '%s'>, <%s object>>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005955 su->type ? su->type->tp_name : "NULL",
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005956 su->obj_type->tp_name);
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005957 else
Walter Dörwald1ab83302007-05-18 17:15:44 +00005958 return PyUnicode_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00005959 "<super: <class '%s'>, NULL>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005960 su->type ? su->type->tp_name : "NULL");
5961}
5962
5963static PyObject *
Guido van Rossum705f0f52001-08-24 16:47:00 +00005964super_getattro(PyObject *self, PyObject *name)
5965{
5966 superobject *su = (superobject *)self;
Guido van Rossum76ba09f2003-04-16 19:40:58 +00005967 int skip = su->obj_type == NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005968
Guido van Rossum76ba09f2003-04-16 19:40:58 +00005969 if (!skip) {
5970 /* We want __class__ to return the class of the super object
5971 (i.e. super, or a subclass), not the class of su->obj. */
Martin v. Löwis5b222132007-06-10 09:51:05 +00005972 skip = (PyUnicode_Check(name) &&
5973 PyUnicode_GET_SIZE(name) == 9 &&
5974 PyUnicode_CompareWithASCIIString(name, "__class__") == 0);
Guido van Rossum76ba09f2003-04-16 19:40:58 +00005975 }
5976
5977 if (!skip) {
Tim Petersa91e9642001-11-14 23:32:33 +00005978 PyObject *mro, *res, *tmp, *dict;
Guido van Rossum155db9a2002-04-02 17:53:47 +00005979 PyTypeObject *starttype;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005980 descrgetfunc f;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005981 Py_ssize_t i, n;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005982
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005983 starttype = su->obj_type;
Guido van Rossum155db9a2002-04-02 17:53:47 +00005984 mro = starttype->tp_mro;
5985
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005986 if (mro == NULL)
5987 n = 0;
5988 else {
5989 assert(PyTuple_Check(mro));
5990 n = PyTuple_GET_SIZE(mro);
5991 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00005992 for (i = 0; i < n; i++) {
Guido van Rossume705ef12001-08-29 15:47:06 +00005993 if ((PyObject *)(su->type) == PyTuple_GET_ITEM(mro, i))
Guido van Rossum705f0f52001-08-24 16:47:00 +00005994 break;
5995 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00005996 i++;
5997 res = NULL;
5998 for (; i < n; i++) {
5999 tmp = PyTuple_GET_ITEM(mro, i);
Tim Petersa91e9642001-11-14 23:32:33 +00006000 if (PyType_Check(tmp))
6001 dict = ((PyTypeObject *)tmp)->tp_dict;
Tim Petersa91e9642001-11-14 23:32:33 +00006002 else
6003 continue;
6004 res = PyDict_GetItem(dict, name);
Guido van Rossum6cc5bb62003-04-16 20:01:36 +00006005 if (res != NULL) {
Guido van Rossum705f0f52001-08-24 16:47:00 +00006006 Py_INCREF(res);
Christian Heimes90aa7642007-12-19 02:45:37 +00006007 f = Py_TYPE(res)->tp_descr_get;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006008 if (f != NULL) {
Phillip J. Eby91a968a2004-03-25 02:19:34 +00006009 tmp = f(res,
6010 /* Only pass 'obj' param if
6011 this is instance-mode super
6012 (See SF ID #743627)
6013 */
Hye-Shik Changff365c92004-03-25 16:37:03 +00006014 (su->obj == (PyObject *)
6015 su->obj_type
Phillip J. Eby91a968a2004-03-25 02:19:34 +00006016 ? (PyObject *)NULL
6017 : su->obj),
Guido van Rossumd4641072002-04-03 02:13:37 +00006018 (PyObject *)starttype);
Guido van Rossum705f0f52001-08-24 16:47:00 +00006019 Py_DECREF(res);
6020 res = tmp;
6021 }
6022 return res;
6023 }
6024 }
6025 }
6026 return PyObject_GenericGetAttr(self, name);
6027}
6028
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006029static PyTypeObject *
Guido van Rossum5b443c62001-12-03 15:38:28 +00006030supercheck(PyTypeObject *type, PyObject *obj)
6031{
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006032 /* Check that a super() call makes sense. Return a type object.
6033
6034 obj can be a new-style class, or an instance of one:
6035
Guido van Rossumd8faa362007-04-27 19:54:29 +00006036 - If it is a class, it must be a subclass of 'type'. This case is
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006037 used for class methods; the return value is obj.
6038
6039 - If it is an instance, it must be an instance of 'type'. This is
6040 the normal case; the return value is obj.__class__.
6041
6042 But... when obj is an instance, we want to allow for the case where
Christian Heimes90aa7642007-12-19 02:45:37 +00006043 Py_TYPE(obj) is not a subclass of type, but obj.__class__ is!
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006044 This will allow using super() with a proxy for obj.
6045 */
6046
Guido van Rossum8e80a722003-02-18 19:22:22 +00006047 /* Check for first bullet above (special case) */
6048 if (PyType_Check(obj) && PyType_IsSubtype((PyTypeObject *)obj, type)) {
6049 Py_INCREF(obj);
6050 return (PyTypeObject *)obj;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006051 }
Guido van Rossum8e80a722003-02-18 19:22:22 +00006052
6053 /* Normal case */
Christian Heimes90aa7642007-12-19 02:45:37 +00006054 if (PyType_IsSubtype(Py_TYPE(obj), type)) {
6055 Py_INCREF(Py_TYPE(obj));
6056 return Py_TYPE(obj);
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006057 }
6058 else {
6059 /* Try the slow way */
6060 static PyObject *class_str = NULL;
6061 PyObject *class_attr;
6062
6063 if (class_str == NULL) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00006064 class_str = PyUnicode_FromString("__class__");
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006065 if (class_str == NULL)
6066 return NULL;
6067 }
6068
6069 class_attr = PyObject_GetAttr(obj, class_str);
6070
6071 if (class_attr != NULL &&
6072 PyType_Check(class_attr) &&
Christian Heimes90aa7642007-12-19 02:45:37 +00006073 (PyTypeObject *)class_attr != Py_TYPE(obj))
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006074 {
6075 int ok = PyType_IsSubtype(
6076 (PyTypeObject *)class_attr, type);
6077 if (ok)
6078 return (PyTypeObject *)class_attr;
6079 }
6080
6081 if (class_attr == NULL)
6082 PyErr_Clear();
6083 else
6084 Py_DECREF(class_attr);
6085 }
6086
Guido van Rossumd8faa362007-04-27 19:54:29 +00006087 PyErr_SetString(PyExc_TypeError,
Guido van Rossum5b443c62001-12-03 15:38:28 +00006088 "super(type, obj): "
6089 "obj must be an instance or subtype of type");
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006090 return NULL;
Guido van Rossum5b443c62001-12-03 15:38:28 +00006091}
6092
Guido van Rossum705f0f52001-08-24 16:47:00 +00006093static PyObject *
6094super_descr_get(PyObject *self, PyObject *obj, PyObject *type)
6095{
6096 superobject *su = (superobject *)self;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00006097 superobject *newobj;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006098
6099 if (obj == NULL || obj == Py_None || su->obj != NULL) {
6100 /* Not binding to an object, or already bound */
6101 Py_INCREF(self);
6102 return self;
6103 }
Christian Heimes90aa7642007-12-19 02:45:37 +00006104 if (Py_TYPE(su) != &PySuper_Type)
Armin Rigo7726dc02005-05-15 15:32:08 +00006105 /* If su is an instance of a (strict) subclass of super,
Guido van Rossum5b443c62001-12-03 15:38:28 +00006106 call its type */
Christian Heimes90aa7642007-12-19 02:45:37 +00006107 return PyObject_CallFunctionObjArgs((PyObject *)Py_TYPE(su),
Guido van Rossumd8faa362007-04-27 19:54:29 +00006108 su->type, obj, NULL);
Guido van Rossum5b443c62001-12-03 15:38:28 +00006109 else {
6110 /* Inline the common case */
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006111 PyTypeObject *obj_type = supercheck(su->type, obj);
6112 if (obj_type == NULL)
Guido van Rossum5b443c62001-12-03 15:38:28 +00006113 return NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00006114 newobj = (superobject *)PySuper_Type.tp_new(&PySuper_Type,
Guido van Rossum5b443c62001-12-03 15:38:28 +00006115 NULL, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00006116 if (newobj == NULL)
Guido van Rossum5b443c62001-12-03 15:38:28 +00006117 return NULL;
6118 Py_INCREF(su->type);
6119 Py_INCREF(obj);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00006120 newobj->type = su->type;
6121 newobj->obj = obj;
6122 newobj->obj_type = obj_type;
6123 return (PyObject *)newobj;
Guido van Rossum5b443c62001-12-03 15:38:28 +00006124 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00006125}
6126
6127static int
6128super_init(PyObject *self, PyObject *args, PyObject *kwds)
6129{
6130 superobject *su = (superobject *)self;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00006131 PyTypeObject *type = NULL;
Guido van Rossume705ef12001-08-29 15:47:06 +00006132 PyObject *obj = NULL;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006133 PyTypeObject *obj_type = NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006134
Thomas Wouters89f507f2006-12-13 04:49:30 +00006135 if (!_PyArg_NoKeywords("super", kwds))
6136 return -1;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00006137 if (!PyArg_ParseTuple(args, "|O!O:super", &PyType_Type, &type, &obj))
Guido van Rossum705f0f52001-08-24 16:47:00 +00006138 return -1;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00006139
6140 if (type == NULL) {
6141 /* Call super(), without args -- fill in from __class__
6142 and first local variable on the stack. */
6143 PyFrameObject *f = PyThreadState_GET()->frame;
6144 PyCodeObject *co = f->f_code;
6145 int i, n;
6146 if (co == NULL) {
6147 PyErr_SetString(PyExc_SystemError,
6148 "super(): no code object");
6149 return -1;
6150 }
6151 if (co->co_argcount == 0) {
6152 PyErr_SetString(PyExc_SystemError,
6153 "super(): no arguments");
6154 return -1;
6155 }
6156 obj = f->f_localsplus[0];
6157 if (obj == NULL) {
6158 PyErr_SetString(PyExc_SystemError,
6159 "super(): arg[0] deleted");
6160 return -1;
6161 }
6162 if (co->co_freevars == NULL)
6163 n = 0;
6164 else {
6165 assert(PyTuple_Check(co->co_freevars));
6166 n = PyTuple_GET_SIZE(co->co_freevars);
6167 }
6168 for (i = 0; i < n; i++) {
6169 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
6170 assert(PyUnicode_Check(name));
6171 if (!PyUnicode_CompareWithASCIIString(name,
6172 "__class__")) {
Barry Warsaw91cc8fb2008-11-20 20:01:57 +00006173 Py_ssize_t index = co->co_nlocals +
6174 PyTuple_GET_SIZE(co->co_cellvars) + i;
6175 PyObject *cell = f->f_localsplus[index];
Guido van Rossumcd16bf62007-06-13 18:07:49 +00006176 if (cell == NULL || !PyCell_Check(cell)) {
6177 PyErr_SetString(PyExc_SystemError,
6178 "super(): bad __class__ cell");
6179 return -1;
6180 }
6181 type = (PyTypeObject *) PyCell_GET(cell);
6182 if (type == NULL) {
6183 PyErr_SetString(PyExc_SystemError,
6184 "super(): empty __class__ cell");
6185 return -1;
6186 }
6187 if (!PyType_Check(type)) {
6188 PyErr_Format(PyExc_SystemError,
6189 "super(): __class__ is not a type (%s)",
Christian Heimes90aa7642007-12-19 02:45:37 +00006190 Py_TYPE(type)->tp_name);
Guido van Rossumcd16bf62007-06-13 18:07:49 +00006191 return -1;
6192 }
6193 break;
6194 }
6195 }
6196 if (type == NULL) {
6197 PyErr_SetString(PyExc_SystemError,
6198 "super(): __class__ cell not found");
6199 return -1;
6200 }
6201 }
6202
Guido van Rossum705f0f52001-08-24 16:47:00 +00006203 if (obj == Py_None)
6204 obj = NULL;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006205 if (obj != NULL) {
6206 obj_type = supercheck(type, obj);
6207 if (obj_type == NULL)
6208 return -1;
6209 Py_INCREF(obj);
6210 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00006211 Py_INCREF(type);
Guido van Rossum705f0f52001-08-24 16:47:00 +00006212 su->type = type;
6213 su->obj = obj;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006214 su->obj_type = obj_type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006215 return 0;
6216}
6217
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00006218PyDoc_STRVAR(super_doc,
Guido van Rossumcd16bf62007-06-13 18:07:49 +00006219"super() -> same as super(__class__, <first argument>)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00006220"super(type) -> unbound super object\n"
6221"super(type, obj) -> bound super object; requires isinstance(obj, type)\n"
Guido van Rossume705ef12001-08-29 15:47:06 +00006222"super(type, type2) -> bound super object; requires issubclass(type2, type)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00006223"Typical use to call a cooperative superclass method:\n"
6224"class C(B):\n"
6225" def meth(self, arg):\n"
Guido van Rossumcd16bf62007-06-13 18:07:49 +00006226" super().meth(arg)\n"
6227"This works for class methods too:\n"
6228"class C(B):\n"
6229" @classmethod\n"
6230" def cmeth(cls, arg):\n"
6231" super().cmeth(arg)\n");
Guido van Rossum705f0f52001-08-24 16:47:00 +00006232
Guido van Rossum048eb752001-10-02 21:24:57 +00006233static int
6234super_traverse(PyObject *self, visitproc visit, void *arg)
6235{
6236 superobject *su = (superobject *)self;
Guido van Rossum048eb752001-10-02 21:24:57 +00006237
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00006238 Py_VISIT(su->obj);
6239 Py_VISIT(su->type);
6240 Py_VISIT(su->obj_type);
Guido van Rossum048eb752001-10-02 21:24:57 +00006241
6242 return 0;
6243}
6244
Guido van Rossum705f0f52001-08-24 16:47:00 +00006245PyTypeObject PySuper_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00006246 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Guido van Rossum705f0f52001-08-24 16:47:00 +00006247 "super", /* tp_name */
6248 sizeof(superobject), /* tp_basicsize */
6249 0, /* tp_itemsize */
6250 /* methods */
Guido van Rossumd8faa362007-04-27 19:54:29 +00006251 super_dealloc, /* tp_dealloc */
Guido van Rossum705f0f52001-08-24 16:47:00 +00006252 0, /* tp_print */
6253 0, /* tp_getattr */
6254 0, /* tp_setattr */
6255 0, /* tp_compare */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00006256 super_repr, /* tp_repr */
Guido van Rossum705f0f52001-08-24 16:47:00 +00006257 0, /* tp_as_number */
6258 0, /* tp_as_sequence */
Guido van Rossumd8faa362007-04-27 19:54:29 +00006259 0, /* tp_as_mapping */
Guido van Rossum705f0f52001-08-24 16:47:00 +00006260 0, /* tp_hash */
6261 0, /* tp_call */
6262 0, /* tp_str */
6263 super_getattro, /* tp_getattro */
6264 0, /* tp_setattro */
6265 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00006266 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
6267 Py_TPFLAGS_BASETYPE, /* tp_flags */
Guido van Rossumd8faa362007-04-27 19:54:29 +00006268 super_doc, /* tp_doc */
6269 super_traverse, /* tp_traverse */
6270 0, /* tp_clear */
Guido van Rossum705f0f52001-08-24 16:47:00 +00006271 0, /* tp_richcompare */
6272 0, /* tp_weaklistoffset */
6273 0, /* tp_iter */
6274 0, /* tp_iternext */
6275 0, /* tp_methods */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00006276 super_members, /* tp_members */
Guido van Rossum705f0f52001-08-24 16:47:00 +00006277 0, /* tp_getset */
6278 0, /* tp_base */
6279 0, /* tp_dict */
6280 super_descr_get, /* tp_descr_get */
6281 0, /* tp_descr_set */
6282 0, /* tp_dictoffset */
6283 super_init, /* tp_init */
6284 PyType_GenericAlloc, /* tp_alloc */
6285 PyType_GenericNew, /* tp_new */
Guido van Rossumd8faa362007-04-27 19:54:29 +00006286 PyObject_GC_Del, /* tp_free */
Guido van Rossum705f0f52001-08-24 16:47:00 +00006287};