blob: 23015b2c804134111260782012fd351e4dbd00bc [file] [log] [blame]
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001/* Type object implementation */
2
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003#include "Python.h"
Guido van Rossumcd16bf62007-06-13 18:07:49 +00004#include "frameobject.h"
Tim Peters6d6c1a32001-08-02 04:15:00 +00005#include "structmember.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00006
Guido van Rossum9923ffe2002-06-04 19:52:53 +00007#include <ctype.h>
8
Christian Heimesa62da1d2008-01-12 19:39:10 +00009
10/* Support type attribute cache */
11
12/* The cache can keep references to the names alive for longer than
13 they normally would. This is why the maximum size is limited to
14 MCACHE_MAX_ATTR_SIZE, since it might be a problem if very large
15 strings are used as attribute names. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000016#define MCACHE_MAX_ATTR_SIZE 100
Benjamin Peterson7d95e402012-04-23 11:24:50 -040017#define MCACHE_SIZE_EXP 9
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000018#define MCACHE_HASH(version, name_hash) \
19 (((unsigned int)(version) * (unsigned int)(name_hash)) \
20 >> (8*sizeof(unsigned int) - MCACHE_SIZE_EXP))
Christian Heimesa62da1d2008-01-12 19:39:10 +000021#define MCACHE_HASH_METHOD(type, name) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000022 MCACHE_HASH((type)->tp_version_tag, \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020023 ((PyASCIIObject *)(name))->hash)
Christian Heimesa62da1d2008-01-12 19:39:10 +000024#define MCACHE_CACHEABLE_NAME(name) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000025 PyUnicode_CheckExact(name) && \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020026 PyUnicode_READY(name) != -1 && \
27 PyUnicode_GET_LENGTH(name) <= MCACHE_MAX_ATTR_SIZE
Christian Heimesa62da1d2008-01-12 19:39:10 +000028
29struct method_cache_entry {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000030 unsigned int version;
31 PyObject *name; /* reference to exactly a str or None */
32 PyObject *value; /* borrowed */
Christian Heimesa62da1d2008-01-12 19:39:10 +000033};
34
35static struct method_cache_entry method_cache[1 << MCACHE_SIZE_EXP];
36static unsigned int next_version_tag = 0;
Christian Heimes26855632008-01-27 23:50:43 +000037
Martin v. Löwise75fc142013-11-07 18:46:53 +010038/* alphabetical order */
39_Py_IDENTIFIER(__abstractmethods__);
Martin v. Löwisbd928fe2011-10-14 10:20:37 +020040_Py_IDENTIFIER(__class__);
Martin v. Löwise75fc142013-11-07 18:46:53 +010041_Py_IDENTIFIER(__delitem__);
Victor Stinner3c1e4812012-03-26 22:10:51 +020042_Py_IDENTIFIER(__dict__);
43_Py_IDENTIFIER(__doc__);
Victor Stinner3c1e4812012-03-26 22:10:51 +020044_Py_IDENTIFIER(__getattribute__);
Martin v. Löwise75fc142013-11-07 18:46:53 +010045_Py_IDENTIFIER(__getitem__);
Victor Stinner3c1e4812012-03-26 22:10:51 +020046_Py_IDENTIFIER(__hash__);
Martin v. Löwise75fc142013-11-07 18:46:53 +010047_Py_IDENTIFIER(__len__);
Victor Stinner3c1e4812012-03-26 22:10:51 +020048_Py_IDENTIFIER(__module__);
49_Py_IDENTIFIER(__name__);
50_Py_IDENTIFIER(__new__);
Martin v. Löwise75fc142013-11-07 18:46:53 +010051_Py_IDENTIFIER(__setitem__);
Victor Stinnerbd303c12013-11-07 23:07:29 +010052_Py_IDENTIFIER(builtins);
Victor Stinner3c1e4812012-03-26 22:10:51 +020053
54static PyObject *
Martin v. Löwis9c564092012-06-23 23:20:45 +020055slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
56
Larry Hastings5c661892014-01-24 06:17:25 -080057/*
58 * finds the docstring's introspection signature.
59 * if present, returns a pointer pointing to the first '('.
60 * otherwise returns NULL.
61 */
62static const char *
Larry Hastings581ee362014-01-28 05:00:08 -080063find_signature(const char *doc)
Larry Hastings5c661892014-01-24 06:17:25 -080064{
Larry Hastings581ee362014-01-28 05:00:08 -080065 if (doc && !strncmp(doc, "sig=(", 5))
66 return doc + 4;
67 return NULL;
Larry Hastings5c661892014-01-24 06:17:25 -080068}
69
70/*
71 * skips to the end of the docstring's instrospection signature.
72 */
73static const char *
74skip_signature(const char *doc)
75{
76 while (*doc && *doc != '\n')
77 doc++;
78 return doc;
79}
80
81static const char *
82skip_eols(const char *trace)
83{
84 while (*trace == '\n')
85 trace++;
86 return trace;
87}
88
89static const char *
Larry Hastings581ee362014-01-28 05:00:08 -080090_PyType_DocWithoutSignature(const char *internal_doc)
Larry Hastings5c661892014-01-24 06:17:25 -080091{
Larry Hastings581ee362014-01-28 05:00:08 -080092 const char *signature = find_signature(internal_doc);
Larry Hastings5c661892014-01-24 06:17:25 -080093
94 if (signature)
95 return skip_eols(skip_signature(signature));
96 return internal_doc;
97}
98
99PyObject *
Larry Hastings581ee362014-01-28 05:00:08 -0800100_PyType_GetDocFromInternalDoc(const char *internal_doc)
Larry Hastings5c661892014-01-24 06:17:25 -0800101{
Larry Hastings581ee362014-01-28 05:00:08 -0800102 const char *doc = _PyType_DocWithoutSignature(internal_doc);
Larry Hastings5c661892014-01-24 06:17:25 -0800103
104 if (!doc) {
105 Py_INCREF(Py_None);
106 return Py_None;
107 }
108
109 return PyUnicode_FromString(doc);
110}
111
112PyObject *
Larry Hastings581ee362014-01-28 05:00:08 -0800113_PyType_GetTextSignatureFromInternalDoc(const char *internal_doc)
Larry Hastings5c661892014-01-24 06:17:25 -0800114{
Larry Hastings581ee362014-01-28 05:00:08 -0800115 const char *signature = find_signature(internal_doc);
Larry Hastings5c661892014-01-24 06:17:25 -0800116 const char *doc;
117
118 if (!signature) {
119 Py_INCREF(Py_None);
120 return Py_None;
121 }
122
123 doc = skip_signature(signature);
124 return PyUnicode_FromStringAndSize(signature, doc - signature);
125}
126
Christian Heimes26855632008-01-27 23:50:43 +0000127unsigned int
128PyType_ClearCache(void)
129{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000130 Py_ssize_t i;
131 unsigned int cur_version_tag = next_version_tag - 1;
132
133 for (i = 0; i < (1 << MCACHE_SIZE_EXP); i++) {
134 method_cache[i].version = 0;
135 Py_CLEAR(method_cache[i].name);
136 method_cache[i].value = NULL;
137 }
138 next_version_tag = 0;
139 /* mark all version tags as invalid */
140 PyType_Modified(&PyBaseObject_Type);
141 return cur_version_tag;
Christian Heimes26855632008-01-27 23:50:43 +0000142}
Christian Heimesa62da1d2008-01-12 19:39:10 +0000143
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000144void
Antoine Pitrou957a23b2013-05-04 20:45:02 +0200145_PyType_Fini(void)
146{
147 PyType_ClearCache();
Antoine Pitrou957a23b2013-05-04 20:45:02 +0200148}
149
150void
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000151PyType_Modified(PyTypeObject *type)
Christian Heimesa62da1d2008-01-12 19:39:10 +0000152{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000153 /* Invalidate any cached data for the specified type and all
154 subclasses. This function is called after the base
155 classes, mro, or attributes of the type are altered.
Christian Heimesa62da1d2008-01-12 19:39:10 +0000156
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000157 Invariants:
Christian Heimesa62da1d2008-01-12 19:39:10 +0000158
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000159 - Py_TPFLAGS_VALID_VERSION_TAG is never set if
160 Py_TPFLAGS_HAVE_VERSION_TAG is not set (e.g. on type
161 objects coming from non-recompiled extension modules)
Christian Heimesa62da1d2008-01-12 19:39:10 +0000162
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000163 - before Py_TPFLAGS_VALID_VERSION_TAG can be set on a type,
164 it must first be set on all super types.
Christian Heimesa62da1d2008-01-12 19:39:10 +0000165
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000166 This function clears the Py_TPFLAGS_VALID_VERSION_TAG of a
167 type (so it must first clear it on all subclasses). The
168 tp_version_tag value is meaningless unless this flag is set.
169 We don't assign new version tags eagerly, but only as
170 needed.
171 */
172 PyObject *raw, *ref;
Antoine Pitrou84745ab2013-10-29 21:31:25 +0100173 Py_ssize_t i;
Christian Heimesa62da1d2008-01-12 19:39:10 +0000174
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000175 if (!PyType_HasFeature(type, Py_TPFLAGS_VALID_VERSION_TAG))
176 return;
Christian Heimesa62da1d2008-01-12 19:39:10 +0000177
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000178 raw = type->tp_subclasses;
179 if (raw != NULL) {
Antoine Pitrou84745ab2013-10-29 21:31:25 +0100180 assert(PyDict_CheckExact(raw));
181 i = 0;
182 while (PyDict_Next(raw, &i, NULL, &ref)) {
183 assert(PyWeakref_CheckRef(ref));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000184 ref = PyWeakref_GET_OBJECT(ref);
185 if (ref != Py_None) {
186 PyType_Modified((PyTypeObject *)ref);
187 }
188 }
189 }
190 type->tp_flags &= ~Py_TPFLAGS_VALID_VERSION_TAG;
Christian Heimesa62da1d2008-01-12 19:39:10 +0000191}
192
193static void
194type_mro_modified(PyTypeObject *type, PyObject *bases) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000195 /*
Florent Xiclunaaa6c1d22011-12-12 18:54:29 +0100196 Check that all base classes or elements of the MRO of type are
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000197 able to be cached. This function is called after the base
198 classes or mro of the type are altered.
Christian Heimesa62da1d2008-01-12 19:39:10 +0000199
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000200 Unset HAVE_VERSION_TAG and VALID_VERSION_TAG if the type
Florent Xiclunaaa6c1d22011-12-12 18:54:29 +0100201 has a custom MRO that includes a type which is not officially
202 super type.
Christian Heimesa62da1d2008-01-12 19:39:10 +0000203
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000204 Called from mro_internal, which will subsequently be called on
205 each subclass when their mro is recursively updated.
206 */
207 Py_ssize_t i, n;
208 int clear = 0;
Christian Heimesa62da1d2008-01-12 19:39:10 +0000209
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000210 if (!PyType_HasFeature(type, Py_TPFLAGS_HAVE_VERSION_TAG))
211 return;
Christian Heimesa62da1d2008-01-12 19:39:10 +0000212
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000213 n = PyTuple_GET_SIZE(bases);
214 for (i = 0; i < n; i++) {
215 PyObject *b = PyTuple_GET_ITEM(bases, i);
216 PyTypeObject *cls;
Christian Heimesa62da1d2008-01-12 19:39:10 +0000217
Florent Xiclunaaa6c1d22011-12-12 18:54:29 +0100218 assert(PyType_Check(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000219 cls = (PyTypeObject *)b;
Christian Heimesa62da1d2008-01-12 19:39:10 +0000220
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000221 if (!PyType_HasFeature(cls, Py_TPFLAGS_HAVE_VERSION_TAG) ||
222 !PyType_IsSubtype(type, cls)) {
223 clear = 1;
224 break;
225 }
226 }
Christian Heimesa62da1d2008-01-12 19:39:10 +0000227
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000228 if (clear)
229 type->tp_flags &= ~(Py_TPFLAGS_HAVE_VERSION_TAG|
230 Py_TPFLAGS_VALID_VERSION_TAG);
Christian Heimesa62da1d2008-01-12 19:39:10 +0000231}
232
233static int
234assign_version_tag(PyTypeObject *type)
235{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000236 /* Ensure that the tp_version_tag is valid and set
237 Py_TPFLAGS_VALID_VERSION_TAG. To respect the invariant, this
238 must first be done on all super classes. Return 0 if this
239 cannot be done, 1 if Py_TPFLAGS_VALID_VERSION_TAG.
240 */
241 Py_ssize_t i, n;
242 PyObject *bases;
Christian Heimesa62da1d2008-01-12 19:39:10 +0000243
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000244 if (PyType_HasFeature(type, Py_TPFLAGS_VALID_VERSION_TAG))
245 return 1;
246 if (!PyType_HasFeature(type, Py_TPFLAGS_HAVE_VERSION_TAG))
247 return 0;
248 if (!PyType_HasFeature(type, Py_TPFLAGS_READY))
249 return 0;
Christian Heimesa62da1d2008-01-12 19:39:10 +0000250
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000251 type->tp_version_tag = next_version_tag++;
252 /* for stress-testing: next_version_tag &= 0xFF; */
Christian Heimesa62da1d2008-01-12 19:39:10 +0000253
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000254 if (type->tp_version_tag == 0) {
255 /* wrap-around or just starting Python - clear the whole
256 cache by filling names with references to Py_None.
257 Values are also set to NULL for added protection, as they
258 are borrowed reference */
259 for (i = 0; i < (1 << MCACHE_SIZE_EXP); i++) {
260 method_cache[i].value = NULL;
261 Py_XDECREF(method_cache[i].name);
262 method_cache[i].name = Py_None;
263 Py_INCREF(Py_None);
264 }
265 /* mark all version tags as invalid */
266 PyType_Modified(&PyBaseObject_Type);
267 return 1;
268 }
269 bases = type->tp_bases;
270 n = PyTuple_GET_SIZE(bases);
271 for (i = 0; i < n; i++) {
272 PyObject *b = PyTuple_GET_ITEM(bases, i);
273 assert(PyType_Check(b));
274 if (!assign_version_tag((PyTypeObject *)b))
275 return 0;
276 }
277 type->tp_flags |= Py_TPFLAGS_VALID_VERSION_TAG;
278 return 1;
Christian Heimesa62da1d2008-01-12 19:39:10 +0000279}
280
281
Guido van Rossum6f799372001-09-20 20:46:19 +0000282static PyMemberDef type_members[] = {
Benjamin Peterson0e102062010-08-25 23:13:17 +0000283 {"__basicsize__", T_PYSSIZET, offsetof(PyTypeObject,tp_basicsize),READONLY},
284 {"__itemsize__", T_PYSSIZET, offsetof(PyTypeObject, tp_itemsize), READONLY},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000285 {"__flags__", T_LONG, offsetof(PyTypeObject, tp_flags), READONLY},
286 {"__weakrefoffset__", T_LONG,
287 offsetof(PyTypeObject, tp_weaklistoffset), READONLY},
288 {"__base__", T_OBJECT, offsetof(PyTypeObject, tp_base), READONLY},
289 {"__dictoffset__", T_LONG,
290 offsetof(PyTypeObject, tp_dictoffset), READONLY},
291 {"__mro__", T_OBJECT, offsetof(PyTypeObject, tp_mro), READONLY},
292 {0}
Tim Peters6d6c1a32001-08-02 04:15:00 +0000293};
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000294
Benjamin Petersond9f23d22011-08-17 11:54:03 -0500295static int
296check_set_special_type_attr(PyTypeObject *type, PyObject *value, const char *name)
297{
298 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
299 PyErr_Format(PyExc_TypeError,
300 "can't set %s.%s", type->tp_name, name);
301 return 0;
302 }
303 if (!value) {
304 PyErr_Format(PyExc_TypeError,
305 "can't delete %s.%s", type->tp_name, name);
306 return 0;
307 }
308 return 1;
309}
310
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000311static PyObject *
Guido van Rossumc3542212001-08-16 09:18:56 +0000312type_name(PyTypeObject *type, void *context)
313{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000314 const char *s;
Guido van Rossumc3542212001-08-16 09:18:56 +0000315
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000316 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
317 PyHeapTypeObject* et = (PyHeapTypeObject*)type;
Tim Petersea7f75d2002-12-07 21:39:16 +0000318
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000319 Py_INCREF(et->ht_name);
320 return et->ht_name;
321 }
322 else {
323 s = strrchr(type->tp_name, '.');
324 if (s == NULL)
325 s = type->tp_name;
326 else
327 s++;
328 return PyUnicode_FromString(s);
329 }
Guido van Rossumc3542212001-08-16 09:18:56 +0000330}
331
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100332static PyObject *
333type_qualname(PyTypeObject *type, void *context)
334{
335 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
336 PyHeapTypeObject* et = (PyHeapTypeObject*)type;
337 Py_INCREF(et->ht_qualname);
338 return et->ht_qualname;
339 }
340 else {
341 return type_name(type, context);
342 }
343}
344
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000345static int
346type_set_name(PyTypeObject *type, PyObject *value, void *context)
347{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000348 PyHeapTypeObject* et;
349 char *tp_name;
350 PyObject *tmp;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000351
Benjamin Petersond9f23d22011-08-17 11:54:03 -0500352 if (!check_set_special_type_attr(type, value, "__name__"))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000353 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000354 if (!PyUnicode_Check(value)) {
355 PyErr_Format(PyExc_TypeError,
356 "can only assign string to %s.__name__, not '%s'",
357 type->tp_name, Py_TYPE(value)->tp_name);
358 return -1;
359 }
Guido van Rossume845c0f2007-11-02 23:07:07 +0000360
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000361 /* Check absence of null characters */
362 tmp = PyUnicode_FromStringAndSize("\0", 1);
363 if (tmp == NULL)
364 return -1;
365 if (PyUnicode_Contains(value, tmp) != 0) {
366 Py_DECREF(tmp);
367 PyErr_Format(PyExc_ValueError,
368 "__name__ must not contain null bytes");
369 return -1;
370 }
371 Py_DECREF(tmp);
Guido van Rossume845c0f2007-11-02 23:07:07 +0000372
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000373 tp_name = _PyUnicode_AsString(value);
374 if (tp_name == NULL)
375 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000376
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000377 et = (PyHeapTypeObject*)type;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000378
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000379 Py_INCREF(value);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000380
Mark Dickinson64aafeb2013-04-13 15:26:58 +0100381 /* Wait until et is a sane state before Py_DECREF'ing the old et->ht_name
382 value. (Bug #16447.) */
383 tmp = et->ht_name;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000384 et->ht_name = value;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000385
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000386 type->tp_name = tp_name;
Mark Dickinson64aafeb2013-04-13 15:26:58 +0100387 Py_DECREF(tmp);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000388
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000389 return 0;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000390}
391
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100392static int
393type_set_qualname(PyTypeObject *type, PyObject *value, void *context)
394{
395 PyHeapTypeObject* et;
396
Benjamin Peterson2c05a2e2012-10-31 00:01:15 -0400397 if (!check_set_special_type_attr(type, value, "__qualname__"))
398 return -1;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100399 if (!PyUnicode_Check(value)) {
400 PyErr_Format(PyExc_TypeError,
401 "can only assign string to %s.__qualname__, not '%s'",
402 type->tp_name, Py_TYPE(value)->tp_name);
403 return -1;
404 }
405
406 et = (PyHeapTypeObject*)type;
407 Py_INCREF(value);
408 Py_DECREF(et->ht_qualname);
409 et->ht_qualname = value;
410 return 0;
411}
412
Guido van Rossumc3542212001-08-16 09:18:56 +0000413static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000414type_module(PyTypeObject *type, void *context)
Guido van Rossum29ca26e1995-01-07 11:58:15 +0000415{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000416 char *s;
Guido van Rossumc3542212001-08-16 09:18:56 +0000417
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000418 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
Victor Stinnerad14ccd2013-11-07 00:46:04 +0100419 PyObject *mod = _PyDict_GetItemId(type->tp_dict, &PyId___module__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000420 if (!mod) {
421 PyErr_Format(PyExc_AttributeError, "__module__");
422 return 0;
423 }
424 Py_XINCREF(mod);
425 return mod;
426 }
427 else {
Victor Stinnerad14ccd2013-11-07 00:46:04 +0100428 PyObject *name;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000429 s = strrchr(type->tp_name, '.');
430 if (s != NULL)
431 return PyUnicode_FromStringAndSize(
432 type->tp_name, (Py_ssize_t)(s - type->tp_name));
Victor Stinnerbd303c12013-11-07 23:07:29 +0100433 name = _PyUnicode_FromId(&PyId_builtins);
Victor Stinnerad14ccd2013-11-07 00:46:04 +0100434 Py_XINCREF(name);
435 return name;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000436 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000437}
438
Guido van Rossum3926a632001-09-25 16:25:58 +0000439static int
440type_set_module(PyTypeObject *type, PyObject *value, void *context)
441{
Benjamin Petersond9f23d22011-08-17 11:54:03 -0500442 if (!check_set_special_type_attr(type, value, "__module__"))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000443 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000444
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000445 PyType_Modified(type);
Christian Heimesa62da1d2008-01-12 19:39:10 +0000446
Victor Stinner3c1e4812012-03-26 22:10:51 +0200447 return _PyDict_SetItemId(type->tp_dict, &PyId___module__, value);
Guido van Rossum3926a632001-09-25 16:25:58 +0000448}
449
Tim Peters6d6c1a32001-08-02 04:15:00 +0000450static PyObject *
Christian Heimes9e7f1d22008-02-28 12:27:11 +0000451type_abstractmethods(PyTypeObject *type, void *context)
452{
Benjamin Petersonaec5fd12010-10-02 00:03:31 +0000453 PyObject *mod = NULL;
Benjamin Peterson84060b82010-10-03 02:13:39 +0000454 /* type itself has an __abstractmethods__ descriptor (this). Don't return
455 that. */
Benjamin Petersonaec5fd12010-10-02 00:03:31 +0000456 if (type != &PyType_Type)
Victor Stinner3688aa92013-11-06 18:59:18 +0100457 mod = _PyDict_GetItemId(type->tp_dict, &PyId___abstractmethods__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000458 if (!mod) {
Victor Stinner3688aa92013-11-06 18:59:18 +0100459 PyObject *message = _PyUnicode_FromId(&PyId___abstractmethods__);
460 if (message)
461 PyErr_SetObject(PyExc_AttributeError, message);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000462 return NULL;
463 }
464 Py_XINCREF(mod);
465 return mod;
Christian Heimes9e7f1d22008-02-28 12:27:11 +0000466}
467
468static int
469type_set_abstractmethods(PyTypeObject *type, PyObject *value, void *context)
470{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000471 /* __abstractmethods__ should only be set once on a type, in
472 abc.ABCMeta.__new__, so this function doesn't do anything
473 special to update subclasses.
474 */
Antoine Pitrou6f430e42012-08-15 23:18:25 +0200475 int abstract, res;
Benjamin Peterson477ba912011-01-12 15:34:01 +0000476 if (value != NULL) {
Antoine Pitrou6f430e42012-08-15 23:18:25 +0200477 abstract = PyObject_IsTrue(value);
478 if (abstract < 0)
479 return -1;
Victor Stinner3688aa92013-11-06 18:59:18 +0100480 res = _PyDict_SetItemId(type->tp_dict, &PyId___abstractmethods__, value);
Benjamin Peterson477ba912011-01-12 15:34:01 +0000481 }
482 else {
Antoine Pitrou6f430e42012-08-15 23:18:25 +0200483 abstract = 0;
Victor Stinner3688aa92013-11-06 18:59:18 +0100484 res = _PyDict_DelItemId(type->tp_dict, &PyId___abstractmethods__);
Benjamin Peterson477ba912011-01-12 15:34:01 +0000485 if (res && PyErr_ExceptionMatches(PyExc_KeyError)) {
Victor Stinner3688aa92013-11-06 18:59:18 +0100486 PyObject *message = _PyUnicode_FromId(&PyId___abstractmethods__);
487 if (message)
488 PyErr_SetObject(PyExc_AttributeError, message);
Benjamin Peterson477ba912011-01-12 15:34:01 +0000489 return -1;
490 }
491 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000492 if (res == 0) {
493 PyType_Modified(type);
Antoine Pitrou6f430e42012-08-15 23:18:25 +0200494 if (abstract)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000495 type->tp_flags |= Py_TPFLAGS_IS_ABSTRACT;
Antoine Pitrou6f430e42012-08-15 23:18:25 +0200496 else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000497 type->tp_flags &= ~Py_TPFLAGS_IS_ABSTRACT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000498 }
499 return res;
Christian Heimes9e7f1d22008-02-28 12:27:11 +0000500}
501
502static PyObject *
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000503type_get_bases(PyTypeObject *type, void *context)
504{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000505 Py_INCREF(type->tp_bases);
506 return type->tp_bases;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000507}
508
509static PyTypeObject *best_base(PyObject *);
510static int mro_internal(PyTypeObject *);
511static int compatible_for_assignment(PyTypeObject *, PyTypeObject *, char *);
512static int add_subclass(PyTypeObject*, PyTypeObject*);
513static void remove_subclass(PyTypeObject *, PyTypeObject *);
Antoine Pitrou84745ab2013-10-29 21:31:25 +0100514static void remove_all_subclasses(PyTypeObject *type, PyObject *bases);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000515static void update_all_slots(PyTypeObject *);
516
Guido van Rossum8d24ee92003-03-24 23:49:49 +0000517typedef int (*update_callback)(PyTypeObject *, void *);
518static int update_subclasses(PyTypeObject *type, PyObject *name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000519 update_callback callback, void *data);
Guido van Rossum8d24ee92003-03-24 23:49:49 +0000520static int recurse_down_subclasses(PyTypeObject *type, PyObject *name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000521 update_callback callback, void *data);
Guido van Rossum8d24ee92003-03-24 23:49:49 +0000522
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000523static int
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000524mro_subclasses(PyTypeObject *type, PyObject* temp)
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000525{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000526 PyTypeObject *subclass;
527 PyObject *ref, *subclasses, *old_mro;
Antoine Pitrou84745ab2013-10-29 21:31:25 +0100528 Py_ssize_t i;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000529
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000530 subclasses = type->tp_subclasses;
531 if (subclasses == NULL)
532 return 0;
Antoine Pitrou84745ab2013-10-29 21:31:25 +0100533 assert(PyDict_CheckExact(subclasses));
534 i = 0;
535
536 while (PyDict_Next(subclasses, &i, NULL, &ref)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000537 assert(PyWeakref_CheckRef(ref));
538 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
539 assert(subclass != NULL);
540 if ((PyObject *)subclass == Py_None)
541 continue;
542 assert(PyType_Check(subclass));
543 old_mro = subclass->tp_mro;
544 if (mro_internal(subclass) < 0) {
545 subclass->tp_mro = old_mro;
546 return -1;
547 }
548 else {
549 PyObject* tuple;
550 tuple = PyTuple_Pack(2, subclass, old_mro);
551 Py_DECREF(old_mro);
552 if (!tuple)
553 return -1;
554 if (PyList_Append(temp, tuple) < 0)
555 return -1;
556 Py_DECREF(tuple);
557 }
558 if (mro_subclasses(subclass, temp) < 0)
559 return -1;
560 }
561 return 0;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000562}
563
564static int
565type_set_bases(PyTypeObject *type, PyObject *value, void *context)
566{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000567 Py_ssize_t i;
568 int r = 0;
569 PyObject *ob, *temp;
570 PyTypeObject *new_base, *old_base;
571 PyObject *old_bases, *old_mro;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000572
Benjamin Petersond9f23d22011-08-17 11:54:03 -0500573 if (!check_set_special_type_attr(type, value, "__bases__"))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000574 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000575 if (!PyTuple_Check(value)) {
576 PyErr_Format(PyExc_TypeError,
577 "can only assign tuple to %s.__bases__, not %s",
578 type->tp_name, Py_TYPE(value)->tp_name);
579 return -1;
580 }
581 if (PyTuple_GET_SIZE(value) == 0) {
582 PyErr_Format(PyExc_TypeError,
583 "can only assign non-empty tuple to %s.__bases__, not ()",
584 type->tp_name);
585 return -1;
586 }
587 for (i = 0; i < PyTuple_GET_SIZE(value); i++) {
588 ob = PyTuple_GET_ITEM(value, i);
589 if (!PyType_Check(ob)) {
Benjamin Petersonb6af60c2012-04-01 18:49:54 -0400590 PyErr_Format(PyExc_TypeError,
Benjamin Peterson9ee601e2012-04-01 18:51:37 -0400591 "%s.__bases__ must be tuple of classes, not '%s'",
Benjamin Petersonb6af60c2012-04-01 18:49:54 -0400592 type->tp_name, Py_TYPE(ob)->tp_name);
593 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000594 }
Benjamin Peterson3471bb62012-04-01 18:48:40 -0400595 if (PyType_IsSubtype((PyTypeObject*)ob, type)) {
596 PyErr_SetString(PyExc_TypeError,
597 "a __bases__ item causes an inheritance cycle");
598 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000599 }
600 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000601
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000602 new_base = best_base(value);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000603
Benjamin Petersonab3c1c12012-04-01 18:48:02 -0400604 if (!new_base)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000605 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000606
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000607 if (!compatible_for_assignment(type->tp_base, new_base, "__bases__"))
608 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000609
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000610 Py_INCREF(new_base);
611 Py_INCREF(value);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000612
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000613 old_bases = type->tp_bases;
614 old_base = type->tp_base;
615 old_mro = type->tp_mro;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000616
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000617 type->tp_bases = value;
618 type->tp_base = new_base;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000619
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000620 if (mro_internal(type) < 0) {
621 goto bail;
622 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000623
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000624 temp = PyList_New(0);
625 if (!temp)
626 goto bail;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000627
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000628 r = mro_subclasses(type, temp);
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000629
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000630 if (r < 0) {
631 for (i = 0; i < PyList_Size(temp); i++) {
632 PyTypeObject* cls;
633 PyObject* mro;
634 PyArg_UnpackTuple(PyList_GET_ITEM(temp, i),
635 "", 2, 2, &cls, &mro);
636 Py_INCREF(mro);
637 ob = cls->tp_mro;
638 cls->tp_mro = mro;
639 Py_DECREF(ob);
640 }
641 Py_DECREF(temp);
642 goto bail;
643 }
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000644
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000645 Py_DECREF(temp);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000646
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000647 /* any base that was in __bases__ but now isn't, we
648 need to remove |type| from its tp_subclasses.
649 conversely, any class now in __bases__ that wasn't
650 needs to have |type| added to its subclasses. */
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000651
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000652 /* for now, sod that: just remove from all old_bases,
653 add to all new_bases */
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000654
Antoine Pitrou84745ab2013-10-29 21:31:25 +0100655 remove_all_subclasses(type, old_bases);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000656
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000657 for (i = PyTuple_GET_SIZE(value) - 1; i >= 0; i--) {
658 ob = PyTuple_GET_ITEM(value, i);
659 if (PyType_Check(ob)) {
660 if (add_subclass((PyTypeObject*)ob, type) < 0)
661 r = -1;
662 }
663 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000664
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000665 update_all_slots(type);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000666
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000667 Py_DECREF(old_bases);
668 Py_DECREF(old_base);
669 Py_DECREF(old_mro);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000670
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000671 return r;
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000672
673 bail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000674 Py_DECREF(type->tp_bases);
675 Py_DECREF(type->tp_base);
676 if (type->tp_mro != old_mro) {
677 Py_DECREF(type->tp_mro);
678 }
Michael W. Hudsone723e452003-08-07 14:58:10 +0000679
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000680 type->tp_bases = old_bases;
681 type->tp_base = old_base;
682 type->tp_mro = old_mro;
Tim Petersea7f75d2002-12-07 21:39:16 +0000683
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000684 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000685}
686
687static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000688type_dict(PyTypeObject *type, void *context)
689{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000690 if (type->tp_dict == NULL) {
691 Py_INCREF(Py_None);
692 return Py_None;
693 }
694 return PyDictProxy_New(type->tp_dict);
Guido van Rossum29ca26e1995-01-07 11:58:15 +0000695}
696
Tim Peters24008312002-03-17 18:56:20 +0000697static PyObject *
698type_get_doc(PyTypeObject *type, void *context)
699{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000700 PyObject *result;
Larry Hastings5c661892014-01-24 06:17:25 -0800701 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE) && type->tp_doc != NULL) {
Larry Hastings581ee362014-01-28 05:00:08 -0800702 return _PyType_GetDocFromInternalDoc(type->tp_doc);
Larry Hastings5c661892014-01-24 06:17:25 -0800703 }
Victor Stinner3c1e4812012-03-26 22:10:51 +0200704 result = _PyDict_GetItemId(type->tp_dict, &PyId___doc__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000705 if (result == NULL) {
706 result = Py_None;
707 Py_INCREF(result);
708 }
709 else if (Py_TYPE(result)->tp_descr_get) {
710 result = Py_TYPE(result)->tp_descr_get(result, NULL,
711 (PyObject *)type);
712 }
713 else {
714 Py_INCREF(result);
715 }
716 return result;
Tim Peters24008312002-03-17 18:56:20 +0000717}
718
Larry Hastings5c661892014-01-24 06:17:25 -0800719static PyObject *
720type_get_text_signature(PyTypeObject *type, void *context)
721{
Larry Hastings581ee362014-01-28 05:00:08 -0800722 return _PyType_GetTextSignatureFromInternalDoc(type->tp_doc);
Larry Hastings5c661892014-01-24 06:17:25 -0800723}
724
Benjamin Peterson01fc6cd2011-08-17 12:03:47 -0500725static int
726type_set_doc(PyTypeObject *type, PyObject *value, void *context)
727{
728 if (!check_set_special_type_attr(type, value, "__doc__"))
729 return -1;
730 PyType_Modified(type);
Victor Stinner3c1e4812012-03-26 22:10:51 +0200731 return _PyDict_SetItemId(type->tp_dict, &PyId___doc__, value);
Benjamin Peterson01fc6cd2011-08-17 12:03:47 -0500732}
733
Antoine Pitrouec569b72008-08-26 22:40:48 +0000734static PyObject *
735type___instancecheck__(PyObject *type, PyObject *inst)
736{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000737 switch (_PyObject_RealIsInstance(inst, type)) {
738 case -1:
739 return NULL;
740 case 0:
741 Py_RETURN_FALSE;
742 default:
743 Py_RETURN_TRUE;
744 }
Antoine Pitrouec569b72008-08-26 22:40:48 +0000745}
746
747
748static PyObject *
Antoine Pitrouec569b72008-08-26 22:40:48 +0000749type___subclasscheck__(PyObject *type, PyObject *inst)
750{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000751 switch (_PyObject_RealIsSubclass(inst, type)) {
752 case -1:
753 return NULL;
754 case 0:
755 Py_RETURN_FALSE;
756 default:
757 Py_RETURN_TRUE;
758 }
Antoine Pitrouec569b72008-08-26 22:40:48 +0000759}
760
Antoine Pitrouec569b72008-08-26 22:40:48 +0000761
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000762static PyGetSetDef type_getsets[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000763 {"__name__", (getter)type_name, (setter)type_set_name, NULL},
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100764 {"__qualname__", (getter)type_qualname, (setter)type_set_qualname, NULL},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000765 {"__bases__", (getter)type_get_bases, (setter)type_set_bases, NULL},
766 {"__module__", (getter)type_module, (setter)type_set_module, NULL},
767 {"__abstractmethods__", (getter)type_abstractmethods,
768 (setter)type_set_abstractmethods, NULL},
769 {"__dict__", (getter)type_dict, NULL, NULL},
Benjamin Peterson01fc6cd2011-08-17 12:03:47 -0500770 {"__doc__", (getter)type_get_doc, (setter)type_set_doc, NULL},
Larry Hastings5c661892014-01-24 06:17:25 -0800771 {"__text_signature__", (getter)type_get_text_signature, NULL, NULL},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000772 {0}
Tim Peters6d6c1a32001-08-02 04:15:00 +0000773};
774
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000775static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000776type_repr(PyTypeObject *type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000777{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000778 PyObject *mod, *name, *rtn;
Guido van Rossumc3542212001-08-16 09:18:56 +0000779
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000780 mod = type_module(type, NULL);
781 if (mod == NULL)
782 PyErr_Clear();
783 else if (!PyUnicode_Check(mod)) {
784 Py_DECREF(mod);
785 mod = NULL;
786 }
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100787 name = type_qualname(type, NULL);
Christian Heimesa0e7e412012-09-10 03:00:14 +0200788 if (name == NULL) {
789 Py_XDECREF(mod);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000790 return NULL;
Christian Heimesa0e7e412012-09-10 03:00:14 +0200791 }
Barry Warsaw7ce36942001-08-24 18:34:26 +0000792
Victor Stinnerbd303c12013-11-07 23:07:29 +0100793 if (mod != NULL && _PyUnicode_CompareWithId(mod, &PyId_builtins))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000794 rtn = PyUnicode_FromFormat("<class '%U.%U'>", mod, name);
795 else
796 rtn = PyUnicode_FromFormat("<class '%s'>", type->tp_name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000797
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000798 Py_XDECREF(mod);
799 Py_DECREF(name);
800 return rtn;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000801}
802
Tim Peters6d6c1a32001-08-02 04:15:00 +0000803static PyObject *
804type_call(PyTypeObject *type, PyObject *args, PyObject *kwds)
805{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000806 PyObject *obj;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000807
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000808 if (type->tp_new == NULL) {
809 PyErr_Format(PyExc_TypeError,
810 "cannot create '%.100s' instances",
811 type->tp_name);
812 return NULL;
813 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000814
Victor Stinner33824f62013-08-26 14:05:19 +0200815#ifdef Py_DEBUG
816 /* type_call() must not be called with an exception set,
817 because it may clear it (directly or indirectly) and so the
818 caller looses its exception */
819 assert(!PyErr_Occurred());
820#endif
821
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000822 obj = type->tp_new(type, args, kwds);
823 if (obj != NULL) {
824 /* Ugly exception: when the call was type(something),
825 don't call tp_init on the result. */
826 if (type == &PyType_Type &&
827 PyTuple_Check(args) && PyTuple_GET_SIZE(args) == 1 &&
828 (kwds == NULL ||
829 (PyDict_Check(kwds) && PyDict_Size(kwds) == 0)))
830 return obj;
831 /* If the returned object is not an instance of type,
832 it won't be initialized. */
833 if (!PyType_IsSubtype(Py_TYPE(obj), type))
834 return obj;
835 type = Py_TYPE(obj);
Victor Stinner3997cfd2013-07-16 22:51:21 +0200836 if (type->tp_init != NULL) {
837 int res = type->tp_init(obj, args, kwds);
838 if (res < 0) {
839 Py_DECREF(obj);
840 obj = NULL;
841 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000842 }
843 }
844 return obj;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000845}
846
847PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000848PyType_GenericAlloc(PyTypeObject *type, Py_ssize_t nitems)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000849{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000850 PyObject *obj;
851 const size_t size = _PyObject_VAR_SIZE(type, nitems+1);
852 /* note that we need to add one, for the sentinel */
Tim Peters406fe3b2001-10-06 19:04:01 +0000853
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000854 if (PyType_IS_GC(type))
855 obj = _PyObject_GC_Malloc(size);
856 else
857 obj = (PyObject *)PyObject_MALLOC(size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000858
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000859 if (obj == NULL)
860 return PyErr_NoMemory();
Tim Peters406fe3b2001-10-06 19:04:01 +0000861
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000862 memset(obj, '\0', size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000863
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000864 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
865 Py_INCREF(type);
Tim Peters406fe3b2001-10-06 19:04:01 +0000866
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000867 if (type->tp_itemsize == 0)
Christian Heimesd3afe782013-12-04 09:27:47 +0100868 (void)PyObject_INIT(obj, type);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000869 else
870 (void) PyObject_INIT_VAR((PyVarObject *)obj, type, nitems);
Tim Peters406fe3b2001-10-06 19:04:01 +0000871
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000872 if (PyType_IS_GC(type))
873 _PyObject_GC_TRACK(obj);
874 return obj;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000875}
876
877PyObject *
878PyType_GenericNew(PyTypeObject *type, PyObject *args, PyObject *kwds)
879{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000880 return type->tp_alloc(type, 0);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000881}
882
Guido van Rossum9475a232001-10-05 20:51:39 +0000883/* Helpers for subtyping */
884
885static int
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000886traverse_slots(PyTypeObject *type, PyObject *self, visitproc visit, void *arg)
887{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000888 Py_ssize_t i, n;
889 PyMemberDef *mp;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000890
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000891 n = Py_SIZE(type);
892 mp = PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type);
893 for (i = 0; i < n; i++, mp++) {
894 if (mp->type == T_OBJECT_EX) {
895 char *addr = (char *)self + mp->offset;
896 PyObject *obj = *(PyObject **)addr;
897 if (obj != NULL) {
898 int err = visit(obj, arg);
899 if (err)
900 return err;
901 }
902 }
903 }
904 return 0;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000905}
906
907static int
Guido van Rossum9475a232001-10-05 20:51:39 +0000908subtype_traverse(PyObject *self, visitproc visit, void *arg)
909{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000910 PyTypeObject *type, *base;
911 traverseproc basetraverse;
Guido van Rossum9475a232001-10-05 20:51:39 +0000912
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000913 /* Find the nearest base with a different tp_traverse,
914 and traverse slots while we're at it */
915 type = Py_TYPE(self);
916 base = type;
917 while ((basetraverse = base->tp_traverse) == subtype_traverse) {
918 if (Py_SIZE(base)) {
919 int err = traverse_slots(base, self, visit, arg);
920 if (err)
921 return err;
922 }
923 base = base->tp_base;
924 assert(base);
925 }
Guido van Rossum9475a232001-10-05 20:51:39 +0000926
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000927 if (type->tp_dictoffset != base->tp_dictoffset) {
928 PyObject **dictptr = _PyObject_GetDictPtr(self);
929 if (dictptr && *dictptr)
930 Py_VISIT(*dictptr);
931 }
Guido van Rossum9475a232001-10-05 20:51:39 +0000932
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000933 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
934 /* For a heaptype, the instances count as references
935 to the type. Traverse the type so the collector
936 can find cycles involving this link. */
937 Py_VISIT(type);
Guido van Rossuma3862092002-06-10 15:24:42 +0000938
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000939 if (basetraverse)
940 return basetraverse(self, visit, arg);
941 return 0;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000942}
943
944static void
945clear_slots(PyTypeObject *type, PyObject *self)
946{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000947 Py_ssize_t i, n;
948 PyMemberDef *mp;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000949
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000950 n = Py_SIZE(type);
951 mp = PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type);
952 for (i = 0; i < n; i++, mp++) {
953 if (mp->type == T_OBJECT_EX && !(mp->flags & READONLY)) {
954 char *addr = (char *)self + mp->offset;
955 PyObject *obj = *(PyObject **)addr;
956 if (obj != NULL) {
957 *(PyObject **)addr = NULL;
958 Py_DECREF(obj);
959 }
960 }
961 }
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000962}
963
964static int
965subtype_clear(PyObject *self)
966{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000967 PyTypeObject *type, *base;
968 inquiry baseclear;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000969
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000970 /* Find the nearest base with a different tp_clear
971 and clear slots while we're at it */
972 type = Py_TYPE(self);
973 base = type;
974 while ((baseclear = base->tp_clear) == subtype_clear) {
975 if (Py_SIZE(base))
976 clear_slots(base, self);
977 base = base->tp_base;
978 assert(base);
979 }
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000980
Benjamin Peterson52c42432012-03-07 18:41:11 -0600981 /* Clear the instance dict (if any), to break cycles involving only
982 __dict__ slots (as in the case 'self.__dict__ is self'). */
983 if (type->tp_dictoffset != base->tp_dictoffset) {
984 PyObject **dictptr = _PyObject_GetDictPtr(self);
985 if (dictptr && *dictptr)
986 Py_CLEAR(*dictptr);
987 }
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000988
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000989 if (baseclear)
990 return baseclear(self);
991 return 0;
Guido van Rossum9475a232001-10-05 20:51:39 +0000992}
Tim Peters6d6c1a32001-08-02 04:15:00 +0000993
994static void
995subtype_dealloc(PyObject *self)
996{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000997 PyTypeObject *type, *base;
998 destructor basedealloc;
Antoine Pitrou56cd62c2012-09-06 00:59:49 +0200999 PyThreadState *tstate = PyThreadState_GET();
Antoine Pitrou796564c2013-07-30 19:59:21 +02001000 int has_finalizer;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001001
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001002 /* Extract the type; we expect it to be a heap type */
1003 type = Py_TYPE(self);
1004 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001005
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001006 /* Test whether the type has GC exactly once */
Guido van Rossum22b13872002-08-06 21:41:44 +00001007
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001008 if (!PyType_IS_GC(type)) {
1009 /* It's really rare to find a dynamic type that doesn't have
1010 GC; it can only happen when deriving from 'object' and not
1011 adding any slots or instance variables. This allows
1012 certain simplifications: there's no need to call
1013 clear_slots(), or DECREF the dict, or clear weakrefs. */
Guido van Rossum22b13872002-08-06 21:41:44 +00001014
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001015 /* Maybe call finalizer; exit early if resurrected */
Antoine Pitrou796564c2013-07-30 19:59:21 +02001016 if (type->tp_finalize) {
1017 if (PyObject_CallFinalizerFromDealloc(self) < 0)
1018 return;
1019 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001020 if (type->tp_del) {
1021 type->tp_del(self);
1022 if (self->ob_refcnt > 0)
1023 return;
1024 }
Guido van Rossum22b13872002-08-06 21:41:44 +00001025
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001026 /* Find the nearest base with a different tp_dealloc */
1027 base = type;
1028 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
1029 assert(Py_SIZE(base) == 0);
1030 base = base->tp_base;
1031 assert(base);
1032 }
Guido van Rossum22b13872002-08-06 21:41:44 +00001033
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001034 /* Extract the type again; tp_del may have changed it */
1035 type = Py_TYPE(self);
Benjamin Peterson193152c2009-04-25 01:08:45 +00001036
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001037 /* Call the base tp_dealloc() */
1038 assert(basedealloc);
1039 basedealloc(self);
Guido van Rossum22b13872002-08-06 21:41:44 +00001040
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001041 /* Can't reference self beyond this point */
1042 Py_DECREF(type);
Guido van Rossum22b13872002-08-06 21:41:44 +00001043
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001044 /* Done */
1045 return;
1046 }
Guido van Rossum22b13872002-08-06 21:41:44 +00001047
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001048 /* We get here only if the type has GC */
Guido van Rossum22b13872002-08-06 21:41:44 +00001049
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001050 /* UnTrack and re-Track around the trashcan macro, alas */
1051 /* See explanation at end of function for full disclosure */
1052 PyObject_GC_UnTrack(self);
1053 ++_PyTrash_delete_nesting;
Antoine Pitrou56cd62c2012-09-06 00:59:49 +02001054 ++ tstate->trash_delete_nesting;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001055 Py_TRASHCAN_SAFE_BEGIN(self);
1056 --_PyTrash_delete_nesting;
Antoine Pitrou56cd62c2012-09-06 00:59:49 +02001057 -- tstate->trash_delete_nesting;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001058 /* DO NOT restore GC tracking at this point. weakref callbacks
1059 * (if any, and whether directly here or indirectly in something we
1060 * call) may trigger GC, and if self is tracked at that point, it
1061 * will look like trash to GC and GC will try to delete self again.
1062 */
Guido van Rossum22b13872002-08-06 21:41:44 +00001063
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001064 /* Find the nearest base with a different tp_dealloc */
1065 base = type;
Brett Cannonb94767f2011-02-22 20:15:44 +00001066 while ((/*basedealloc =*/ base->tp_dealloc) == subtype_dealloc) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001067 base = base->tp_base;
1068 assert(base);
1069 }
Guido van Rossum14227b42001-12-06 02:35:58 +00001070
Antoine Pitrou796564c2013-07-30 19:59:21 +02001071 has_finalizer = type->tp_finalize || type->tp_del;
Guido van Rossum59195fd2003-06-13 20:54:40 +00001072
Antoine Pitrou796564c2013-07-30 19:59:21 +02001073 /* Maybe call finalizer; exit early if resurrected */
1074 if (has_finalizer)
1075 _PyObject_GC_TRACK(self);
1076
1077 if (type->tp_finalize) {
1078 if (PyObject_CallFinalizerFromDealloc(self) < 0) {
1079 /* Resurrected */
1080 goto endlabel;
1081 }
1082 }
1083 /* If we added a weaklist, we clear it. Do this *before* calling
1084 tp_del, clearing slots, or clearing the instance dict. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001085 if (type->tp_weaklistoffset && !base->tp_weaklistoffset)
1086 PyObject_ClearWeakRefs(self);
Guido van Rossum1987c662003-05-29 14:29:23 +00001087
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001088 if (type->tp_del) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001089 type->tp_del(self);
Antoine Pitrou796564c2013-07-30 19:59:21 +02001090 if (self->ob_refcnt > 0) {
1091 /* Resurrected */
1092 goto endlabel;
1093 }
1094 }
1095 if (has_finalizer) {
1096 _PyObject_GC_UNTRACK(self);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001097 /* New weakrefs could be created during the finalizer call.
Antoine Pitrou796564c2013-07-30 19:59:21 +02001098 If this occurs, clear them out without calling their
1099 finalizers since they might rely on part of the object
1100 being finalized that has already been destroyed. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001101 if (type->tp_weaklistoffset && !base->tp_weaklistoffset) {
1102 /* Modeled after GET_WEAKREFS_LISTPTR() */
1103 PyWeakReference **list = (PyWeakReference **) \
1104 PyObject_GET_WEAKREFS_LISTPTR(self);
1105 while (*list)
1106 _PyWeakref_ClearRef(*list);
1107 }
1108 }
Guido van Rossum1987c662003-05-29 14:29:23 +00001109
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001110 /* Clear slots up to the nearest base with a different tp_dealloc */
1111 base = type;
1112 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
1113 if (Py_SIZE(base))
1114 clear_slots(base, self);
1115 base = base->tp_base;
1116 assert(base);
1117 }
Guido van Rossum59195fd2003-06-13 20:54:40 +00001118
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001119 /* If we added a dict, DECREF it */
1120 if (type->tp_dictoffset && !base->tp_dictoffset) {
1121 PyObject **dictptr = _PyObject_GetDictPtr(self);
1122 if (dictptr != NULL) {
1123 PyObject *dict = *dictptr;
1124 if (dict != NULL) {
1125 Py_DECREF(dict);
1126 *dictptr = NULL;
1127 }
1128 }
1129 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001130
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001131 /* Extract the type again; tp_del may have changed it */
1132 type = Py_TYPE(self);
Benjamin Peterson193152c2009-04-25 01:08:45 +00001133
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001134 /* Call the base tp_dealloc(); first retrack self if
1135 * basedealloc knows about gc.
1136 */
1137 if (PyType_IS_GC(base))
1138 _PyObject_GC_TRACK(self);
1139 assert(basedealloc);
1140 basedealloc(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001141
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001142 /* Can't reference self beyond this point */
1143 Py_DECREF(type);
Guido van Rossum22b13872002-08-06 21:41:44 +00001144
Guido van Rossum0906e072002-08-07 20:42:09 +00001145 endlabel:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001146 ++_PyTrash_delete_nesting;
Antoine Pitrou56cd62c2012-09-06 00:59:49 +02001147 ++ tstate->trash_delete_nesting;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001148 Py_TRASHCAN_SAFE_END(self);
1149 --_PyTrash_delete_nesting;
Antoine Pitrou56cd62c2012-09-06 00:59:49 +02001150 -- tstate->trash_delete_nesting;
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001151
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001152 /* Explanation of the weirdness around the trashcan macros:
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001153
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001154 Q. What do the trashcan macros do?
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001155
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001156 A. Read the comment titled "Trashcan mechanism" in object.h.
1157 For one, this explains why there must be a call to GC-untrack
1158 before the trashcan begin macro. Without understanding the
1159 trashcan code, the answers to the following questions don't make
1160 sense.
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001161
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001162 Q. Why do we GC-untrack before the trashcan and then immediately
1163 GC-track again afterward?
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001164
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001165 A. In the case that the base class is GC-aware, the base class
1166 probably GC-untracks the object. If it does that using the
1167 UNTRACK macro, this will crash when the object is already
1168 untracked. Because we don't know what the base class does, the
1169 only safe thing is to make sure the object is tracked when we
1170 call the base class dealloc. But... The trashcan begin macro
1171 requires that the object is *untracked* before it is called. So
1172 the dance becomes:
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001173
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001174 GC untrack
1175 trashcan begin
1176 GC track
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001177
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001178 Q. Why did the last question say "immediately GC-track again"?
1179 It's nowhere near immediately.
Tim Petersf7f9e992003-11-13 21:59:32 +00001180
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001181 A. Because the code *used* to re-track immediately. Bad Idea.
1182 self has a refcount of 0, and if gc ever gets its hands on it
1183 (which can happen if any weakref callback gets invoked), it
1184 looks like trash to gc too, and gc also tries to delete self
Ezio Melotti13925002011-03-16 11:05:33 +02001185 then. But we're already deleting self. Double deallocation is
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001186 a subtle disaster.
Tim Petersf7f9e992003-11-13 21:59:32 +00001187
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001188 Q. Why the bizarre (net-zero) manipulation of
1189 _PyTrash_delete_nesting around the trashcan macros?
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001190
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001191 A. Some base classes (e.g. list) also use the trashcan mechanism.
1192 The following scenario used to be possible:
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001193
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001194 - suppose the trashcan level is one below the trashcan limit
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001195
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001196 - subtype_dealloc() is called
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001197
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001198 - the trashcan limit is not yet reached, so the trashcan level
1199 is incremented and the code between trashcan begin and end is
1200 executed
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001201
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001202 - this destroys much of the object's contents, including its
1203 slots and __dict__
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001204
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001205 - basedealloc() is called; this is really list_dealloc(), or
1206 some other type which also uses the trashcan macros
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001207
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001208 - the trashcan limit is now reached, so the object is put on the
1209 trashcan's to-be-deleted-later list
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001210
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001211 - basedealloc() returns
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001212
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001213 - subtype_dealloc() decrefs the object's type
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001214
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001215 - subtype_dealloc() returns
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001216
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001217 - later, the trashcan code starts deleting the objects from its
1218 to-be-deleted-later list
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001219
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001220 - subtype_dealloc() is called *AGAIN* for the same object
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001221
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001222 - at the very least (if the destroyed slots and __dict__ don't
1223 cause problems) the object's type gets decref'ed a second
1224 time, which is *BAD*!!!
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001225
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001226 The remedy is to make sure that if the code between trashcan
1227 begin and end in subtype_dealloc() is called, the code between
1228 trashcan begin and end in basedealloc() will also be called.
1229 This is done by decrementing the level after passing into the
1230 trashcan block, and incrementing it just before leaving the
1231 block.
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001232
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001233 But now it's possible that a chain of objects consisting solely
1234 of objects whose deallocator is subtype_dealloc() will defeat
1235 the trashcan mechanism completely: the decremented level means
1236 that the effective level never reaches the limit. Therefore, we
1237 *increment* the level *before* entering the trashcan block, and
1238 matchingly decrement it after leaving. This means the trashcan
1239 code will trigger a little early, but that's no big deal.
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001240
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001241 Q. Are there any live examples of code in need of all this
1242 complexity?
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001243
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001244 A. Yes. See SF bug 668433 for code that crashed (when Python was
1245 compiled in debug mode) before the trashcan level manipulations
1246 were added. For more discussion, see SF patches 581742, 575073
1247 and bug 574207.
1248 */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001249}
1250
Jeremy Hylton938ace62002-07-17 16:30:39 +00001251static PyTypeObject *solid_base(PyTypeObject *type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001252
Tim Peters6d6c1a32001-08-02 04:15:00 +00001253/* type test with subclassing support */
1254
1255int
1256PyType_IsSubtype(PyTypeObject *a, PyTypeObject *b)
1257{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001258 PyObject *mro;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001259
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001260 mro = a->tp_mro;
1261 if (mro != NULL) {
1262 /* Deal with multiple inheritance without recursion
1263 by walking the MRO tuple */
1264 Py_ssize_t i, n;
1265 assert(PyTuple_Check(mro));
1266 n = PyTuple_GET_SIZE(mro);
1267 for (i = 0; i < n; i++) {
1268 if (PyTuple_GET_ITEM(mro, i) == (PyObject *)b)
1269 return 1;
1270 }
1271 return 0;
1272 }
1273 else {
1274 /* a is not completely initilized yet; follow tp_base */
1275 do {
1276 if (a == b)
1277 return 1;
1278 a = a->tp_base;
1279 } while (a != NULL);
1280 return b == &PyBaseObject_Type;
1281 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001282}
1283
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001284/* Internal routines to do a method lookup in the type
Guido van Rossum60718732001-08-28 17:47:51 +00001285 without looking in the instance dictionary
1286 (so we can't use PyObject_GetAttr) but still binding
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001287 it to the instance. The arguments are the object,
Guido van Rossum60718732001-08-28 17:47:51 +00001288 the method name as a C string, and the address of a
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001289 static variable used to cache the interned Python string.
1290
1291 Two variants:
1292
1293 - lookup_maybe() returns NULL without raising an exception
1294 when the _PyType_Lookup() call fails;
1295
1296 - lookup_method() always raises an exception upon errors.
Benjamin Peterson224205f2009-05-08 03:25:19 +00001297
1298 - _PyObject_LookupSpecial() exported for the benefit of other places.
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001299*/
Guido van Rossum60718732001-08-28 17:47:51 +00001300
1301static PyObject *
Benjamin Petersonce798522012-01-22 11:24:29 -05001302lookup_maybe(PyObject *self, _Py_Identifier *attrid)
Guido van Rossum60718732001-08-28 17:47:51 +00001303{
Victor Stinner3c1e4812012-03-26 22:10:51 +02001304 PyObject *res;
Guido van Rossum60718732001-08-28 17:47:51 +00001305
Victor Stinner3c1e4812012-03-26 22:10:51 +02001306 res = _PyType_LookupId(Py_TYPE(self), attrid);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001307 if (res != NULL) {
1308 descrgetfunc f;
1309 if ((f = Py_TYPE(res)->tp_descr_get) == NULL)
1310 Py_INCREF(res);
1311 else
1312 res = f(res, self, (PyObject *)(Py_TYPE(self)));
1313 }
1314 return res;
Guido van Rossum60718732001-08-28 17:47:51 +00001315}
1316
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001317static PyObject *
Benjamin Petersonce798522012-01-22 11:24:29 -05001318lookup_method(PyObject *self, _Py_Identifier *attrid)
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001319{
Benjamin Petersonce798522012-01-22 11:24:29 -05001320 PyObject *res = lookup_maybe(self, attrid);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001321 if (res == NULL && !PyErr_Occurred())
Benjamin Petersonce798522012-01-22 11:24:29 -05001322 PyErr_SetObject(PyExc_AttributeError, attrid->object);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001323 return res;
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001324}
1325
Benjamin Peterson224205f2009-05-08 03:25:19 +00001326PyObject *
Benjamin Petersonce798522012-01-22 11:24:29 -05001327_PyObject_LookupSpecial(PyObject *self, _Py_Identifier *attrid)
Benjamin Peterson224205f2009-05-08 03:25:19 +00001328{
Benjamin Petersonce798522012-01-22 11:24:29 -05001329 return lookup_maybe(self, attrid);
Benjamin Peterson224205f2009-05-08 03:25:19 +00001330}
1331
Guido van Rossum2730b132001-08-28 18:22:14 +00001332/* A variation of PyObject_CallMethod that uses lookup_method()
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001333 instead of PyObject_GetAttrString(). This uses the same convention
Guido van Rossum2730b132001-08-28 18:22:14 +00001334 as lookup_method to cache the interned name string object. */
1335
Neil Schemenauerf23473f2001-10-21 22:28:58 +00001336static PyObject *
Benjamin Petersonce798522012-01-22 11:24:29 -05001337call_method(PyObject *o, _Py_Identifier *nameid, char *format, ...)
Guido van Rossum2730b132001-08-28 18:22:14 +00001338{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001339 va_list va;
1340 PyObject *args, *func = 0, *retval;
1341 va_start(va, format);
Guido van Rossum2730b132001-08-28 18:22:14 +00001342
Benjamin Petersonce798522012-01-22 11:24:29 -05001343 func = lookup_maybe(o, nameid);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001344 if (func == NULL) {
1345 va_end(va);
1346 if (!PyErr_Occurred())
Benjamin Petersonce798522012-01-22 11:24:29 -05001347 PyErr_SetObject(PyExc_AttributeError, nameid->object);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001348 return NULL;
1349 }
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001350
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001351 if (format && *format)
1352 args = Py_VaBuildValue(format, va);
1353 else
1354 args = PyTuple_New(0);
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001355
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001356 va_end(va);
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001357
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001358 if (args == NULL)
1359 return NULL;
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001360
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001361 assert(PyTuple_Check(args));
1362 retval = PyObject_Call(func, args, NULL);
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001363
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001364 Py_DECREF(args);
1365 Py_DECREF(func);
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001366
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001367 return retval;
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001368}
1369
1370/* Clone of call_method() that returns NotImplemented when the lookup fails. */
1371
Neil Schemenauerf23473f2001-10-21 22:28:58 +00001372static PyObject *
Benjamin Petersonce798522012-01-22 11:24:29 -05001373call_maybe(PyObject *o, _Py_Identifier *nameid, char *format, ...)
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001374{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001375 va_list va;
1376 PyObject *args, *func = 0, *retval;
1377 va_start(va, format);
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001378
Benjamin Petersonce798522012-01-22 11:24:29 -05001379 func = lookup_maybe(o, nameid);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001380 if (func == NULL) {
1381 va_end(va);
Brian Curtindfc80e32011-08-10 20:28:54 -05001382 if (!PyErr_Occurred())
1383 Py_RETURN_NOTIMPLEMENTED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001384 return NULL;
1385 }
Guido van Rossum2730b132001-08-28 18:22:14 +00001386
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001387 if (format && *format)
1388 args = Py_VaBuildValue(format, va);
1389 else
1390 args = PyTuple_New(0);
Guido van Rossum2730b132001-08-28 18:22:14 +00001391
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001392 va_end(va);
Guido van Rossum2730b132001-08-28 18:22:14 +00001393
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001394 if (args == NULL)
1395 return NULL;
Guido van Rossum2730b132001-08-28 18:22:14 +00001396
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001397 assert(PyTuple_Check(args));
1398 retval = PyObject_Call(func, args, NULL);
Guido van Rossum2730b132001-08-28 18:22:14 +00001399
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001400 Py_DECREF(args);
1401 Py_DECREF(func);
Guido van Rossum2730b132001-08-28 18:22:14 +00001402
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001403 return retval;
Guido van Rossum2730b132001-08-28 18:22:14 +00001404}
1405
Tim Petersea7f75d2002-12-07 21:39:16 +00001406/*
Guido van Rossum1f121312002-11-14 19:49:16 +00001407 Method resolution order algorithm C3 described in
1408 "A Monotonic Superclass Linearization for Dylan",
1409 by Kim Barrett, Bob Cassel, Paul Haahr,
Tim Petersea7f75d2002-12-07 21:39:16 +00001410 David A. Moon, Keith Playford, and P. Tucker Withington.
Guido van Rossum1f121312002-11-14 19:49:16 +00001411 (OOPSLA 1996)
1412
Guido van Rossum98f33732002-11-25 21:36:54 +00001413 Some notes about the rules implied by C3:
1414
Tim Petersea7f75d2002-12-07 21:39:16 +00001415 No duplicate bases.
Guido van Rossum98f33732002-11-25 21:36:54 +00001416 It isn't legal to repeat a class in a list of base classes.
1417
1418 The next three properties are the 3 constraints in "C3".
1419
Tim Petersea7f75d2002-12-07 21:39:16 +00001420 Local precendece order.
Guido van Rossum98f33732002-11-25 21:36:54 +00001421 If A precedes B in C's MRO, then A will precede B in the MRO of all
1422 subclasses of C.
1423
1424 Monotonicity.
1425 The MRO of a class must be an extension without reordering of the
1426 MRO of each of its superclasses.
1427
1428 Extended Precedence Graph (EPG).
1429 Linearization is consistent if there is a path in the EPG from
1430 each class to all its successors in the linearization. See
1431 the paper for definition of EPG.
Guido van Rossum1f121312002-11-14 19:49:16 +00001432 */
1433
Tim Petersea7f75d2002-12-07 21:39:16 +00001434static int
Guido van Rossum1f121312002-11-14 19:49:16 +00001435tail_contains(PyObject *list, int whence, PyObject *o) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001436 Py_ssize_t j, size;
1437 size = PyList_GET_SIZE(list);
Guido van Rossum1f121312002-11-14 19:49:16 +00001438
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001439 for (j = whence+1; j < size; j++) {
1440 if (PyList_GET_ITEM(list, j) == o)
1441 return 1;
1442 }
1443 return 0;
Guido van Rossum1f121312002-11-14 19:49:16 +00001444}
1445
Guido van Rossum98f33732002-11-25 21:36:54 +00001446static PyObject *
1447class_name(PyObject *cls)
1448{
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001449 PyObject *name = _PyObject_GetAttrId(cls, &PyId___name__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001450 if (name == NULL) {
1451 PyErr_Clear();
1452 Py_XDECREF(name);
1453 name = PyObject_Repr(cls);
1454 }
1455 if (name == NULL)
1456 return NULL;
1457 if (!PyUnicode_Check(name)) {
1458 Py_DECREF(name);
1459 return NULL;
1460 }
1461 return name;
Guido van Rossum98f33732002-11-25 21:36:54 +00001462}
1463
1464static int
1465check_duplicates(PyObject *list)
1466{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001467 Py_ssize_t i, j, n;
1468 /* Let's use a quadratic time algorithm,
1469 assuming that the bases lists is short.
1470 */
1471 n = PyList_GET_SIZE(list);
1472 for (i = 0; i < n; i++) {
1473 PyObject *o = PyList_GET_ITEM(list, i);
1474 for (j = i + 1; j < n; j++) {
1475 if (PyList_GET_ITEM(list, j) == o) {
1476 o = class_name(o);
1477 if (o != NULL) {
1478 PyErr_Format(PyExc_TypeError,
1479 "duplicate base class %U",
1480 o);
1481 Py_DECREF(o);
1482 } else {
1483 PyErr_SetString(PyExc_TypeError,
1484 "duplicate base class");
1485 }
1486 return -1;
1487 }
1488 }
1489 }
1490 return 0;
Guido van Rossum98f33732002-11-25 21:36:54 +00001491}
1492
1493/* Raise a TypeError for an MRO order disagreement.
1494
1495 It's hard to produce a good error message. In the absence of better
1496 insight into error reporting, report the classes that were candidates
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001497 to be put next into the MRO. There is some conflict between the
Guido van Rossum98f33732002-11-25 21:36:54 +00001498 order in which they should be put in the MRO, but it's hard to
1499 diagnose what constraint can't be satisfied.
1500*/
1501
1502static void
1503set_mro_error(PyObject *to_merge, int *remain)
1504{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001505 Py_ssize_t i, n, off, to_merge_size;
1506 char buf[1000];
1507 PyObject *k, *v;
1508 PyObject *set = PyDict_New();
1509 if (!set) return;
Guido van Rossum98f33732002-11-25 21:36:54 +00001510
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001511 to_merge_size = PyList_GET_SIZE(to_merge);
1512 for (i = 0; i < to_merge_size; i++) {
1513 PyObject *L = PyList_GET_ITEM(to_merge, i);
1514 if (remain[i] < PyList_GET_SIZE(L)) {
1515 PyObject *c = PyList_GET_ITEM(L, remain[i]);
1516 if (PyDict_SetItem(set, c, Py_None) < 0) {
1517 Py_DECREF(set);
1518 return;
1519 }
1520 }
1521 }
1522 n = PyDict_Size(set);
Guido van Rossum98f33732002-11-25 21:36:54 +00001523
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001524 off = PyOS_snprintf(buf, sizeof(buf), "Cannot create a \
Raymond Hettingerf394df42003-04-06 19:13:41 +00001525consistent method resolution\norder (MRO) for bases");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001526 i = 0;
1527 while (PyDict_Next(set, &i, &k, &v) && (size_t)off < sizeof(buf)) {
1528 PyObject *name = class_name(k);
Victor Stinnere5f99f32010-05-19 01:42:46 +00001529 char *name_str;
1530 if (name != NULL) {
1531 name_str = _PyUnicode_AsString(name);
1532 if (name_str == NULL)
Victor Stinnerba644a62010-05-19 01:50:45 +00001533 name_str = "?";
Victor Stinnere5f99f32010-05-19 01:42:46 +00001534 } else
Victor Stinnerba644a62010-05-19 01:50:45 +00001535 name_str = "?";
Victor Stinnere5f99f32010-05-19 01:42:46 +00001536 off += PyOS_snprintf(buf + off, sizeof(buf) - off, " %s", name_str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001537 Py_XDECREF(name);
1538 if (--n && (size_t)(off+1) < sizeof(buf)) {
1539 buf[off++] = ',';
1540 buf[off] = '\0';
1541 }
1542 }
1543 PyErr_SetString(PyExc_TypeError, buf);
1544 Py_DECREF(set);
Guido van Rossum98f33732002-11-25 21:36:54 +00001545}
1546
Tim Petersea7f75d2002-12-07 21:39:16 +00001547static int
Guido van Rossum1f121312002-11-14 19:49:16 +00001548pmerge(PyObject *acc, PyObject* to_merge) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001549 Py_ssize_t i, j, to_merge_size, empty_cnt;
1550 int *remain;
1551 int ok;
Tim Petersea7f75d2002-12-07 21:39:16 +00001552
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001553 to_merge_size = PyList_GET_SIZE(to_merge);
Guido van Rossum1f121312002-11-14 19:49:16 +00001554
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001555 /* remain stores an index into each sublist of to_merge.
1556 remain[i] is the index of the next base in to_merge[i]
1557 that is not included in acc.
1558 */
1559 remain = (int *)PyMem_MALLOC(SIZEOF_INT*to_merge_size);
Victor Stinnera41f0852013-07-12 00:42:14 +02001560 if (remain == NULL) {
1561 PyErr_NoMemory();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001562 return -1;
Victor Stinnera41f0852013-07-12 00:42:14 +02001563 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001564 for (i = 0; i < to_merge_size; i++)
1565 remain[i] = 0;
Guido van Rossum1f121312002-11-14 19:49:16 +00001566
1567 again:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001568 empty_cnt = 0;
1569 for (i = 0; i < to_merge_size; i++) {
1570 PyObject *candidate;
Tim Petersea7f75d2002-12-07 21:39:16 +00001571
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001572 PyObject *cur_list = PyList_GET_ITEM(to_merge, i);
Guido van Rossum1f121312002-11-14 19:49:16 +00001573
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001574 if (remain[i] >= PyList_GET_SIZE(cur_list)) {
1575 empty_cnt++;
1576 continue;
1577 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001578
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001579 /* Choose next candidate for MRO.
Guido van Rossum98f33732002-11-25 21:36:54 +00001580
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001581 The input sequences alone can determine the choice.
1582 If not, choose the class which appears in the MRO
1583 of the earliest direct superclass of the new class.
1584 */
Guido van Rossum98f33732002-11-25 21:36:54 +00001585
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001586 candidate = PyList_GET_ITEM(cur_list, remain[i]);
1587 for (j = 0; j < to_merge_size; j++) {
1588 PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
1589 if (tail_contains(j_lst, remain[j], candidate)) {
1590 goto skip; /* continue outer loop */
1591 }
1592 }
1593 ok = PyList_Append(acc, candidate);
1594 if (ok < 0) {
Victor Stinnera41f0852013-07-12 00:42:14 +02001595 PyMem_FREE(remain);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001596 return -1;
1597 }
1598 for (j = 0; j < to_merge_size; j++) {
1599 PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
1600 if (remain[j] < PyList_GET_SIZE(j_lst) &&
1601 PyList_GET_ITEM(j_lst, remain[j]) == candidate) {
1602 remain[j]++;
1603 }
1604 }
1605 goto again;
1606 skip: ;
1607 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001608
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001609 if (empty_cnt == to_merge_size) {
1610 PyMem_FREE(remain);
1611 return 0;
1612 }
1613 set_mro_error(to_merge, remain);
1614 PyMem_FREE(remain);
1615 return -1;
Guido van Rossum1f121312002-11-14 19:49:16 +00001616}
1617
Tim Peters6d6c1a32001-08-02 04:15:00 +00001618static PyObject *
1619mro_implementation(PyTypeObject *type)
1620{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001621 Py_ssize_t i, n;
1622 int ok;
1623 PyObject *bases, *result;
1624 PyObject *to_merge, *bases_aslist;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001625
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001626 if (type->tp_dict == NULL) {
1627 if (PyType_Ready(type) < 0)
1628 return NULL;
1629 }
Guido van Rossum63517572002-06-18 16:44:57 +00001630
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001631 /* Find a superclass linearization that honors the constraints
1632 of the explicit lists of bases and the constraints implied by
1633 each base class.
Guido van Rossum98f33732002-11-25 21:36:54 +00001634
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001635 to_merge is a list of lists, where each list is a superclass
1636 linearization implied by a base class. The last element of
1637 to_merge is the declared list of bases.
1638 */
Guido van Rossum98f33732002-11-25 21:36:54 +00001639
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001640 bases = type->tp_bases;
1641 n = PyTuple_GET_SIZE(bases);
Guido van Rossum1f121312002-11-14 19:49:16 +00001642
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001643 to_merge = PyList_New(n+1);
1644 if (to_merge == NULL)
1645 return NULL;
Guido van Rossum1f121312002-11-14 19:49:16 +00001646
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001647 for (i = 0; i < n; i++) {
1648 PyObject *base = PyTuple_GET_ITEM(bases, i);
1649 PyObject *parentMRO;
1650 parentMRO = PySequence_List(((PyTypeObject*)base)->tp_mro);
1651 if (parentMRO == NULL) {
1652 Py_DECREF(to_merge);
1653 return NULL;
1654 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001655
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001656 PyList_SET_ITEM(to_merge, i, parentMRO);
1657 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001658
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001659 bases_aslist = PySequence_List(bases);
1660 if (bases_aslist == NULL) {
1661 Py_DECREF(to_merge);
1662 return NULL;
1663 }
1664 /* This is just a basic sanity check. */
1665 if (check_duplicates(bases_aslist) < 0) {
1666 Py_DECREF(to_merge);
1667 Py_DECREF(bases_aslist);
1668 return NULL;
1669 }
1670 PyList_SET_ITEM(to_merge, n, bases_aslist);
Guido van Rossum1f121312002-11-14 19:49:16 +00001671
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001672 result = Py_BuildValue("[O]", (PyObject *)type);
1673 if (result == NULL) {
1674 Py_DECREF(to_merge);
1675 return NULL;
1676 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001677
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001678 ok = pmerge(result, to_merge);
1679 Py_DECREF(to_merge);
1680 if (ok < 0) {
1681 Py_DECREF(result);
1682 return NULL;
1683 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001684
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001685 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001686}
1687
1688static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001689mro_external(PyObject *self)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001690{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001691 PyTypeObject *type = (PyTypeObject *)self;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001692
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001693 return mro_implementation(type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001694}
1695
1696static int
1697mro_internal(PyTypeObject *type)
1698{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001699 PyObject *mro, *result, *tuple;
1700 int checkit = 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001701
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001702 if (Py_TYPE(type) == &PyType_Type) {
1703 result = mro_implementation(type);
1704 }
1705 else {
Benjamin Petersonce798522012-01-22 11:24:29 -05001706 _Py_IDENTIFIER(mro);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001707 checkit = 1;
Benjamin Petersonce798522012-01-22 11:24:29 -05001708 mro = lookup_method((PyObject *)type, &PyId_mro);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001709 if (mro == NULL)
1710 return -1;
1711 result = PyObject_CallObject(mro, NULL);
1712 Py_DECREF(mro);
1713 }
1714 if (result == NULL)
1715 return -1;
1716 tuple = PySequence_Tuple(result);
1717 Py_DECREF(result);
1718 if (tuple == NULL)
1719 return -1;
1720 if (checkit) {
1721 Py_ssize_t i, len;
1722 PyObject *cls;
1723 PyTypeObject *solid;
Armin Rigo037d1e02005-12-29 17:07:39 +00001724
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001725 solid = solid_base(type);
Armin Rigo037d1e02005-12-29 17:07:39 +00001726
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001727 len = PyTuple_GET_SIZE(tuple);
Armin Rigo037d1e02005-12-29 17:07:39 +00001728
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001729 for (i = 0; i < len; i++) {
1730 PyTypeObject *t;
1731 cls = PyTuple_GET_ITEM(tuple, i);
1732 if (!PyType_Check(cls)) {
1733 PyErr_Format(PyExc_TypeError,
1734 "mro() returned a non-class ('%.500s')",
1735 Py_TYPE(cls)->tp_name);
1736 Py_DECREF(tuple);
1737 return -1;
1738 }
1739 t = (PyTypeObject*)cls;
1740 if (!PyType_IsSubtype(solid, solid_base(t))) {
1741 PyErr_Format(PyExc_TypeError,
1742 "mro() returned base with unsuitable layout ('%.500s')",
1743 t->tp_name);
1744 Py_DECREF(tuple);
1745 return -1;
1746 }
1747 }
1748 }
1749 type->tp_mro = tuple;
Christian Heimesa62da1d2008-01-12 19:39:10 +00001750
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001751 type_mro_modified(type, type->tp_mro);
Florent Xiclunaaa6c1d22011-12-12 18:54:29 +01001752 /* corner case: the super class might have been hidden
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001753 from the custom MRO */
1754 type_mro_modified(type, type->tp_bases);
Christian Heimesa62da1d2008-01-12 19:39:10 +00001755
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001756 PyType_Modified(type);
Christian Heimesa62da1d2008-01-12 19:39:10 +00001757
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001758 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001759}
1760
1761
1762/* Calculate the best base amongst multiple base classes.
1763 This is the first one that's on the path to the "solid base". */
1764
1765static PyTypeObject *
1766best_base(PyObject *bases)
1767{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001768 Py_ssize_t i, n;
1769 PyTypeObject *base, *winner, *candidate, *base_i;
1770 PyObject *base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001771
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001772 assert(PyTuple_Check(bases));
1773 n = PyTuple_GET_SIZE(bases);
1774 assert(n > 0);
1775 base = NULL;
1776 winner = NULL;
1777 for (i = 0; i < n; i++) {
1778 base_proto = PyTuple_GET_ITEM(bases, i);
1779 if (!PyType_Check(base_proto)) {
1780 PyErr_SetString(
1781 PyExc_TypeError,
1782 "bases must be types");
1783 return NULL;
1784 }
1785 base_i = (PyTypeObject *)base_proto;
1786 if (base_i->tp_dict == NULL) {
1787 if (PyType_Ready(base_i) < 0)
1788 return NULL;
1789 }
1790 candidate = solid_base(base_i);
1791 if (winner == NULL) {
1792 winner = candidate;
1793 base = base_i;
1794 }
1795 else if (PyType_IsSubtype(winner, candidate))
1796 ;
1797 else if (PyType_IsSubtype(candidate, winner)) {
1798 winner = candidate;
1799 base = base_i;
1800 }
1801 else {
1802 PyErr_SetString(
1803 PyExc_TypeError,
1804 "multiple bases have "
1805 "instance lay-out conflict");
1806 return NULL;
1807 }
1808 }
Florent Xiclunaaa6c1d22011-12-12 18:54:29 +01001809 assert (base != NULL);
1810
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001811 return base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001812}
1813
1814static int
1815extra_ivars(PyTypeObject *type, PyTypeObject *base)
1816{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001817 size_t t_size = type->tp_basicsize;
1818 size_t b_size = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001819
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001820 assert(t_size >= b_size); /* Else type smaller than base! */
1821 if (type->tp_itemsize || base->tp_itemsize) {
1822 /* If itemsize is involved, stricter rules */
1823 return t_size != b_size ||
1824 type->tp_itemsize != base->tp_itemsize;
1825 }
1826 if (type->tp_weaklistoffset && base->tp_weaklistoffset == 0 &&
1827 type->tp_weaklistoffset + sizeof(PyObject *) == t_size &&
1828 type->tp_flags & Py_TPFLAGS_HEAPTYPE)
1829 t_size -= sizeof(PyObject *);
1830 if (type->tp_dictoffset && base->tp_dictoffset == 0 &&
1831 type->tp_dictoffset + sizeof(PyObject *) == t_size &&
1832 type->tp_flags & Py_TPFLAGS_HEAPTYPE)
1833 t_size -= sizeof(PyObject *);
Guido van Rossum9676b222001-08-17 20:32:36 +00001834
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001835 return t_size != b_size;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001836}
1837
1838static PyTypeObject *
1839solid_base(PyTypeObject *type)
1840{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001841 PyTypeObject *base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001842
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001843 if (type->tp_base)
1844 base = solid_base(type->tp_base);
1845 else
1846 base = &PyBaseObject_Type;
1847 if (extra_ivars(type, base))
1848 return type;
1849 else
1850 return base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001851}
1852
Jeremy Hylton938ace62002-07-17 16:30:39 +00001853static void object_dealloc(PyObject *);
1854static int object_init(PyObject *, PyObject *, PyObject *);
1855static int update_slot(PyTypeObject *, PyObject *);
1856static void fixup_slot_dispatchers(PyTypeObject *);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001857
Guido van Rossum360e4b82007-05-14 22:51:27 +00001858/*
1859 * Helpers for __dict__ descriptor. We don't want to expose the dicts
1860 * inherited from various builtin types. The builtin base usually provides
1861 * its own __dict__ descriptor, so we use that when we can.
1862 */
1863static PyTypeObject *
1864get_builtin_base_with_dict(PyTypeObject *type)
1865{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001866 while (type->tp_base != NULL) {
1867 if (type->tp_dictoffset != 0 &&
1868 !(type->tp_flags & Py_TPFLAGS_HEAPTYPE))
1869 return type;
1870 type = type->tp_base;
1871 }
1872 return NULL;
Guido van Rossum360e4b82007-05-14 22:51:27 +00001873}
1874
1875static PyObject *
1876get_dict_descriptor(PyTypeObject *type)
1877{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001878 PyObject *descr;
Guido van Rossum360e4b82007-05-14 22:51:27 +00001879
Victor Stinner3c1e4812012-03-26 22:10:51 +02001880 descr = _PyType_LookupId(type, &PyId___dict__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001881 if (descr == NULL || !PyDescr_IsData(descr))
1882 return NULL;
Guido van Rossum360e4b82007-05-14 22:51:27 +00001883
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001884 return descr;
Guido van Rossum360e4b82007-05-14 22:51:27 +00001885}
1886
1887static void
1888raise_dict_descr_error(PyObject *obj)
1889{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001890 PyErr_Format(PyExc_TypeError,
1891 "this __dict__ descriptor does not support "
1892 "'%.200s' objects", Py_TYPE(obj)->tp_name);
Guido van Rossum360e4b82007-05-14 22:51:27 +00001893}
1894
Tim Peters6d6c1a32001-08-02 04:15:00 +00001895static PyObject *
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001896subtype_dict(PyObject *obj, void *context)
1897{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001898 PyTypeObject *base;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001899
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001900 base = get_builtin_base_with_dict(Py_TYPE(obj));
1901 if (base != NULL) {
1902 descrgetfunc func;
1903 PyObject *descr = get_dict_descriptor(base);
1904 if (descr == NULL) {
1905 raise_dict_descr_error(obj);
1906 return NULL;
1907 }
1908 func = Py_TYPE(descr)->tp_descr_get;
1909 if (func == NULL) {
1910 raise_dict_descr_error(obj);
1911 return NULL;
1912 }
1913 return func(descr, obj, (PyObject *)(Py_TYPE(obj)));
1914 }
Benjamin Peterson8eb12692012-02-19 19:59:10 -05001915 return PyObject_GenericGetDict(obj, context);
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001916}
1917
Guido van Rossum6661be32001-10-26 04:26:12 +00001918static int
1919subtype_setdict(PyObject *obj, PyObject *value, void *context)
1920{
Benjamin Peterson8eb12692012-02-19 19:59:10 -05001921 PyObject *dict, **dictptr;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001922 PyTypeObject *base;
Guido van Rossum6661be32001-10-26 04:26:12 +00001923
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001924 base = get_builtin_base_with_dict(Py_TYPE(obj));
1925 if (base != NULL) {
1926 descrsetfunc func;
1927 PyObject *descr = get_dict_descriptor(base);
1928 if (descr == NULL) {
1929 raise_dict_descr_error(obj);
1930 return -1;
1931 }
1932 func = Py_TYPE(descr)->tp_descr_set;
1933 if (func == NULL) {
1934 raise_dict_descr_error(obj);
1935 return -1;
1936 }
1937 return func(descr, obj, value);
1938 }
Benjamin Peterson8eb12692012-02-19 19:59:10 -05001939 /* Almost like PyObject_GenericSetDict, but allow __dict__ to be deleted. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001940 dictptr = _PyObject_GetDictPtr(obj);
1941 if (dictptr == NULL) {
1942 PyErr_SetString(PyExc_AttributeError,
1943 "This object has no __dict__");
1944 return -1;
1945 }
Benjamin Peterson006c5a22012-02-19 20:36:12 -05001946 if (value != NULL && !PyDict_Check(value)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001947 PyErr_Format(PyExc_TypeError,
1948 "__dict__ must be set to a dictionary, "
1949 "not a '%.200s'", Py_TYPE(value)->tp_name);
1950 return -1;
1951 }
1952 dict = *dictptr;
1953 Py_XINCREF(value);
1954 *dictptr = value;
1955 Py_XDECREF(dict);
1956 return 0;
Guido van Rossum6661be32001-10-26 04:26:12 +00001957}
1958
Guido van Rossumad47da02002-08-12 19:05:44 +00001959static PyObject *
1960subtype_getweakref(PyObject *obj, void *context)
1961{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001962 PyObject **weaklistptr;
1963 PyObject *result;
Guido van Rossumad47da02002-08-12 19:05:44 +00001964
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001965 if (Py_TYPE(obj)->tp_weaklistoffset == 0) {
1966 PyErr_SetString(PyExc_AttributeError,
1967 "This object has no __weakref__");
1968 return NULL;
1969 }
1970 assert(Py_TYPE(obj)->tp_weaklistoffset > 0);
1971 assert(Py_TYPE(obj)->tp_weaklistoffset + sizeof(PyObject *) <=
1972 (size_t)(Py_TYPE(obj)->tp_basicsize));
1973 weaklistptr = (PyObject **)
1974 ((char *)obj + Py_TYPE(obj)->tp_weaklistoffset);
1975 if (*weaklistptr == NULL)
1976 result = Py_None;
1977 else
1978 result = *weaklistptr;
1979 Py_INCREF(result);
1980 return result;
Guido van Rossumad47da02002-08-12 19:05:44 +00001981}
1982
Guido van Rossum373c7412003-01-07 13:41:37 +00001983/* Three variants on the subtype_getsets list. */
1984
1985static PyGetSetDef subtype_getsets_full[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001986 {"__dict__", subtype_dict, subtype_setdict,
1987 PyDoc_STR("dictionary for instance variables (if defined)")},
1988 {"__weakref__", subtype_getweakref, NULL,
1989 PyDoc_STR("list of weak references to the object (if defined)")},
1990 {0}
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001991};
1992
Guido van Rossum373c7412003-01-07 13:41:37 +00001993static PyGetSetDef subtype_getsets_dict_only[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001994 {"__dict__", subtype_dict, subtype_setdict,
1995 PyDoc_STR("dictionary for instance variables (if defined)")},
1996 {0}
Guido van Rossum373c7412003-01-07 13:41:37 +00001997};
1998
1999static PyGetSetDef subtype_getsets_weakref_only[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002000 {"__weakref__", subtype_getweakref, NULL,
2001 PyDoc_STR("list of weak references to the object (if defined)")},
2002 {0}
Guido van Rossum373c7412003-01-07 13:41:37 +00002003};
2004
Guido van Rossum9923ffe2002-06-04 19:52:53 +00002005static int
2006valid_identifier(PyObject *s)
2007{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002008 if (!PyUnicode_Check(s)) {
2009 PyErr_Format(PyExc_TypeError,
2010 "__slots__ items must be strings, not '%.200s'",
2011 Py_TYPE(s)->tp_name);
2012 return 0;
2013 }
2014 if (!PyUnicode_IsIdentifier(s)) {
2015 PyErr_SetString(PyExc_TypeError,
2016 "__slots__ must be identifiers");
2017 return 0;
2018 }
2019 return 1;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00002020}
2021
Guido van Rossumd8faa362007-04-27 19:54:29 +00002022/* Forward */
2023static int
2024object_init(PyObject *self, PyObject *args, PyObject *kwds);
2025
2026static int
2027type_init(PyObject *cls, PyObject *args, PyObject *kwds)
2028{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002029 int res;
Guido van Rossumd8faa362007-04-27 19:54:29 +00002030
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002031 assert(args != NULL && PyTuple_Check(args));
2032 assert(kwds == NULL || PyDict_Check(kwds));
Guido van Rossumd8faa362007-04-27 19:54:29 +00002033
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002034 if (kwds != NULL && PyDict_Check(kwds) && PyDict_Size(kwds) != 0) {
2035 PyErr_SetString(PyExc_TypeError,
2036 "type.__init__() takes no keyword arguments");
2037 return -1;
2038 }
Guido van Rossumd8faa362007-04-27 19:54:29 +00002039
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002040 if (args != NULL && PyTuple_Check(args) &&
2041 (PyTuple_GET_SIZE(args) != 1 && PyTuple_GET_SIZE(args) != 3)) {
2042 PyErr_SetString(PyExc_TypeError,
2043 "type.__init__() takes 1 or 3 arguments");
2044 return -1;
2045 }
Guido van Rossumd8faa362007-04-27 19:54:29 +00002046
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002047 /* Call object.__init__(self) now. */
2048 /* XXX Could call super(type, cls).__init__() but what's the point? */
2049 args = PyTuple_GetSlice(args, 0, 0);
2050 res = object_init(cls, args, NULL);
2051 Py_DECREF(args);
2052 return res;
Guido van Rossumd8faa362007-04-27 19:54:29 +00002053}
2054
Victor Stinner4ca1cf32012-10-30 23:40:45 +01002055unsigned long
Martin v. Löwis738236d2011-02-05 20:35:29 +00002056PyType_GetFlags(PyTypeObject *type)
2057{
2058 return type->tp_flags;
2059}
2060
Nick Coghlande31b192011-10-23 22:04:16 +10002061/* Determine the most derived metatype. */
2062PyTypeObject *
2063_PyType_CalculateMetaclass(PyTypeObject *metatype, PyObject *bases)
2064{
2065 Py_ssize_t i, nbases;
2066 PyTypeObject *winner;
2067 PyObject *tmp;
2068 PyTypeObject *tmptype;
2069
2070 /* Determine the proper metatype to deal with this,
2071 and check for metatype conflicts while we're at it.
2072 Note that if some other metatype wins to contract,
2073 it's possible that its instances are not types. */
2074
2075 nbases = PyTuple_GET_SIZE(bases);
2076 winner = metatype;
2077 for (i = 0; i < nbases; i++) {
2078 tmp = PyTuple_GET_ITEM(bases, i);
2079 tmptype = Py_TYPE(tmp);
2080 if (PyType_IsSubtype(winner, tmptype))
2081 continue;
2082 if (PyType_IsSubtype(tmptype, winner)) {
2083 winner = tmptype;
2084 continue;
2085 }
2086 /* else: */
2087 PyErr_SetString(PyExc_TypeError,
2088 "metaclass conflict: "
2089 "the metaclass of a derived class "
2090 "must be a (non-strict) subclass "
2091 "of the metaclasses of all its bases");
2092 return NULL;
2093 }
2094 return winner;
2095}
2096
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00002097static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00002098type_new(PyTypeObject *metatype, PyObject *args, PyObject *kwds)
2099{
Victor Stinner6f738742012-02-25 01:22:36 +01002100 PyObject *name, *bases = NULL, *orig_dict, *dict = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002101 static char *kwlist[] = {"name", "bases", "dict", 0};
Victor Stinner6f738742012-02-25 01:22:36 +01002102 PyObject *qualname, *slots = NULL, *tmp, *newslots;
2103 PyTypeObject *type = NULL, *base, *tmptype, *winner;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002104 PyHeapTypeObject *et;
2105 PyMemberDef *mp;
2106 Py_ssize_t i, nbases, nslots, slotoffset, add_dict, add_weak;
2107 int j, may_add_dict, may_add_weak;
Victor Stinner3c1e4812012-03-26 22:10:51 +02002108 _Py_IDENTIFIER(__qualname__);
2109 _Py_IDENTIFIER(__slots__);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002110
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002111 assert(args != NULL && PyTuple_Check(args));
2112 assert(kwds == NULL || PyDict_Check(kwds));
Tim Peters3abca122001-10-27 19:37:48 +00002113
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002114 /* Special case: type(x) should return x->ob_type */
2115 {
2116 const Py_ssize_t nargs = PyTuple_GET_SIZE(args);
2117 const Py_ssize_t nkwds = kwds == NULL ? 0 : PyDict_Size(kwds);
Tim Peters3abca122001-10-27 19:37:48 +00002118
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002119 if (PyType_CheckExact(metatype) && nargs == 1 && nkwds == 0) {
2120 PyObject *x = PyTuple_GET_ITEM(args, 0);
2121 Py_INCREF(Py_TYPE(x));
2122 return (PyObject *) Py_TYPE(x);
2123 }
Tim Peters3abca122001-10-27 19:37:48 +00002124
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002125 /* SF bug 475327 -- if that didn't trigger, we need 3
2126 arguments. but PyArg_ParseTupleAndKeywords below may give
2127 a msg saying type() needs exactly 3. */
2128 if (nargs + nkwds != 3) {
2129 PyErr_SetString(PyExc_TypeError,
2130 "type() takes 1 or 3 arguments");
2131 return NULL;
2132 }
2133 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002134
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002135 /* Check arguments: (name, bases, dict) */
2136 if (!PyArg_ParseTupleAndKeywords(args, kwds, "UO!O!:type", kwlist,
2137 &name,
2138 &PyTuple_Type, &bases,
Victor Stinner6f738742012-02-25 01:22:36 +01002139 &PyDict_Type, &orig_dict))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002140 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002141
Nick Coghlande31b192011-10-23 22:04:16 +10002142 /* Determine the proper metatype to deal with this: */
2143 winner = _PyType_CalculateMetaclass(metatype, bases);
2144 if (winner == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002145 return NULL;
2146 }
Nick Coghlande31b192011-10-23 22:04:16 +10002147
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002148 if (winner != metatype) {
2149 if (winner->tp_new != type_new) /* Pass it to the winner */
2150 return winner->tp_new(winner, args, kwds);
2151 metatype = winner;
2152 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002153
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002154 /* Adjust for empty tuple bases */
Nick Coghlande31b192011-10-23 22:04:16 +10002155 nbases = PyTuple_GET_SIZE(bases);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002156 if (nbases == 0) {
2157 bases = PyTuple_Pack(1, &PyBaseObject_Type);
2158 if (bases == NULL)
Victor Stinner6f738742012-02-25 01:22:36 +01002159 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002160 nbases = 1;
2161 }
2162 else
2163 Py_INCREF(bases);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002164
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002165 /* Calculate best base, and check that all bases are type objects */
2166 base = best_base(bases);
2167 if (base == NULL) {
Victor Stinner6f738742012-02-25 01:22:36 +01002168 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002169 }
2170 if (!PyType_HasFeature(base, Py_TPFLAGS_BASETYPE)) {
2171 PyErr_Format(PyExc_TypeError,
2172 "type '%.100s' is not an acceptable base type",
2173 base->tp_name);
Victor Stinner6f738742012-02-25 01:22:36 +01002174 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002175 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002176
Victor Stinner6f738742012-02-25 01:22:36 +01002177 dict = PyDict_Copy(orig_dict);
2178 if (dict == NULL)
2179 goto error;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002180
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002181 /* Check for a __slots__ sequence variable in dict, and count it */
Victor Stinner3c1e4812012-03-26 22:10:51 +02002182 slots = _PyDict_GetItemId(dict, &PyId___slots__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002183 nslots = 0;
2184 add_dict = 0;
2185 add_weak = 0;
2186 may_add_dict = base->tp_dictoffset == 0;
2187 may_add_weak = base->tp_weaklistoffset == 0 && base->tp_itemsize == 0;
2188 if (slots == NULL) {
2189 if (may_add_dict) {
2190 add_dict++;
2191 }
2192 if (may_add_weak) {
2193 add_weak++;
2194 }
2195 }
2196 else {
2197 /* Have slots */
Guido van Rossumad47da02002-08-12 19:05:44 +00002198
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002199 /* Make it into a tuple */
2200 if (PyUnicode_Check(slots))
2201 slots = PyTuple_Pack(1, slots);
2202 else
2203 slots = PySequence_Tuple(slots);
Victor Stinner6f738742012-02-25 01:22:36 +01002204 if (slots == NULL)
2205 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002206 assert(PyTuple_Check(slots));
Guido van Rossumad47da02002-08-12 19:05:44 +00002207
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002208 /* Are slots allowed? */
2209 nslots = PyTuple_GET_SIZE(slots);
2210 if (nslots > 0 && base->tp_itemsize != 0) {
2211 PyErr_Format(PyExc_TypeError,
2212 "nonempty __slots__ "
2213 "not supported for subtype of '%s'",
2214 base->tp_name);
Victor Stinner6f738742012-02-25 01:22:36 +01002215 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002216 }
Guido van Rossumad47da02002-08-12 19:05:44 +00002217
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002218 /* Check for valid slot names and two special cases */
2219 for (i = 0; i < nslots; i++) {
2220 PyObject *tmp = PyTuple_GET_ITEM(slots, i);
2221 if (!valid_identifier(tmp))
Victor Stinner6f738742012-02-25 01:22:36 +01002222 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002223 assert(PyUnicode_Check(tmp));
Victor Stinnerad14ccd2013-11-07 00:46:04 +01002224 if (_PyUnicode_CompareWithId(tmp, &PyId___dict__) == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002225 if (!may_add_dict || add_dict) {
2226 PyErr_SetString(PyExc_TypeError,
2227 "__dict__ slot disallowed: "
2228 "we already got one");
Victor Stinner6f738742012-02-25 01:22:36 +01002229 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002230 }
2231 add_dict++;
2232 }
2233 if (PyUnicode_CompareWithASCIIString(tmp, "__weakref__") == 0) {
2234 if (!may_add_weak || add_weak) {
2235 PyErr_SetString(PyExc_TypeError,
2236 "__weakref__ slot disallowed: "
2237 "either we already got one, "
2238 "or __itemsize__ != 0");
Victor Stinner6f738742012-02-25 01:22:36 +01002239 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002240 }
2241 add_weak++;
2242 }
2243 }
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00002244
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002245 /* Copy slots into a list, mangle names and sort them.
2246 Sorted names are needed for __class__ assignment.
2247 Convert them back to tuple at the end.
2248 */
2249 newslots = PyList_New(nslots - add_dict - add_weak);
2250 if (newslots == NULL)
Victor Stinner6f738742012-02-25 01:22:36 +01002251 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002252 for (i = j = 0; i < nslots; i++) {
2253 tmp = PyTuple_GET_ITEM(slots, i);
2254 if ((add_dict &&
Victor Stinnerad14ccd2013-11-07 00:46:04 +01002255 _PyUnicode_CompareWithId(tmp, &PyId___dict__) == 0) ||
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002256 (add_weak &&
2257 PyUnicode_CompareWithASCIIString(tmp, "__weakref__") == 0))
2258 continue;
2259 tmp =_Py_Mangle(name, tmp);
Benjamin Petersonae13c882011-08-16 22:26:48 -05002260 if (!tmp) {
2261 Py_DECREF(newslots);
Victor Stinner6f738742012-02-25 01:22:36 +01002262 goto error;
Benjamin Petersonae13c882011-08-16 22:26:48 -05002263 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002264 PyList_SET_ITEM(newslots, j, tmp);
Benjamin Petersonc4085c82011-08-16 18:53:26 -05002265 if (PyDict_GetItem(dict, tmp)) {
2266 PyErr_Format(PyExc_ValueError,
2267 "%R in __slots__ conflicts with class variable",
2268 tmp);
Benjamin Petersond17cefc2011-08-16 22:28:23 -05002269 Py_DECREF(newslots);
Victor Stinner6f738742012-02-25 01:22:36 +01002270 goto error;
Benjamin Petersonc4085c82011-08-16 18:53:26 -05002271 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002272 j++;
2273 }
2274 assert(j == nslots - add_dict - add_weak);
2275 nslots = j;
Victor Stinner6f738742012-02-25 01:22:36 +01002276 Py_CLEAR(slots);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002277 if (PyList_Sort(newslots) == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002278 Py_DECREF(newslots);
Victor Stinner6f738742012-02-25 01:22:36 +01002279 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002280 }
2281 slots = PyList_AsTuple(newslots);
2282 Py_DECREF(newslots);
Victor Stinner6f738742012-02-25 01:22:36 +01002283 if (slots == NULL)
2284 goto error;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00002285
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002286 /* Secondary bases may provide weakrefs or dict */
2287 if (nbases > 1 &&
2288 ((may_add_dict && !add_dict) ||
2289 (may_add_weak && !add_weak))) {
2290 for (i = 0; i < nbases; i++) {
2291 tmp = PyTuple_GET_ITEM(bases, i);
2292 if (tmp == (PyObject *)base)
2293 continue; /* Skip primary base */
2294 assert(PyType_Check(tmp));
2295 tmptype = (PyTypeObject *)tmp;
2296 if (may_add_dict && !add_dict &&
2297 tmptype->tp_dictoffset != 0)
2298 add_dict++;
2299 if (may_add_weak && !add_weak &&
2300 tmptype->tp_weaklistoffset != 0)
2301 add_weak++;
2302 if (may_add_dict && !add_dict)
2303 continue;
2304 if (may_add_weak && !add_weak)
2305 continue;
2306 /* Nothing more to check */
2307 break;
2308 }
2309 }
2310 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002311
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002312 /* Allocate the type object */
2313 type = (PyTypeObject *)metatype->tp_alloc(metatype, nslots);
Victor Stinner6f738742012-02-25 01:22:36 +01002314 if (type == NULL)
2315 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002316
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002317 /* Keep name and slots alive in the extended type object */
2318 et = (PyHeapTypeObject *)type;
2319 Py_INCREF(name);
2320 et->ht_name = name;
2321 et->ht_slots = slots;
Victor Stinner6f738742012-02-25 01:22:36 +01002322 slots = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002323
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002324 /* Initialize tp_flags */
2325 type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE |
Antoine Pitrou796564c2013-07-30 19:59:21 +02002326 Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_FINALIZE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002327 if (base->tp_flags & Py_TPFLAGS_HAVE_GC)
2328 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossumdc91b992001-08-08 22:26:22 +00002329
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002330 /* Initialize essential fields */
2331 type->tp_as_number = &et->as_number;
2332 type->tp_as_sequence = &et->as_sequence;
2333 type->tp_as_mapping = &et->as_mapping;
2334 type->tp_as_buffer = &et->as_buffer;
2335 type->tp_name = _PyUnicode_AsString(name);
Victor Stinner6f738742012-02-25 01:22:36 +01002336 if (!type->tp_name)
2337 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002338
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002339 /* Set tp_base and tp_bases */
2340 type->tp_bases = bases;
Victor Stinner6f738742012-02-25 01:22:36 +01002341 bases = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002342 Py_INCREF(base);
2343 type->tp_base = base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002344
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002345 /* Initialize tp_dict from passed-in dict */
Victor Stinner6f738742012-02-25 01:22:36 +01002346 Py_INCREF(dict);
2347 type->tp_dict = dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002348
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002349 /* Set __module__ in the dict */
Victor Stinner3c1e4812012-03-26 22:10:51 +02002350 if (_PyDict_GetItemId(dict, &PyId___module__) == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002351 tmp = PyEval_GetGlobals();
2352 if (tmp != NULL) {
Victor Stinner3c1e4812012-03-26 22:10:51 +02002353 tmp = _PyDict_GetItemId(tmp, &PyId___name__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002354 if (tmp != NULL) {
Victor Stinner3c1e4812012-03-26 22:10:51 +02002355 if (_PyDict_SetItemId(dict, &PyId___module__,
2356 tmp) < 0)
Victor Stinner6f738742012-02-25 01:22:36 +01002357 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002358 }
2359 }
2360 }
Guido van Rossumc3542212001-08-16 09:18:56 +00002361
Victor Stinner6f738742012-02-25 01:22:36 +01002362 /* Set ht_qualname to dict['__qualname__'] if available, else to
2363 __name__. The __qualname__ accessor will look for ht_qualname.
2364 */
Victor Stinner3c1e4812012-03-26 22:10:51 +02002365 qualname = _PyDict_GetItemId(dict, &PyId___qualname__);
Victor Stinner6f738742012-02-25 01:22:36 +01002366 if (qualname != NULL) {
2367 if (!PyUnicode_Check(qualname)) {
2368 PyErr_Format(PyExc_TypeError,
2369 "type __qualname__ must be a str, not %s",
2370 Py_TYPE(qualname)->tp_name);
2371 goto error;
2372 }
2373 }
Benjamin Peterson8afa7fa2012-10-30 23:51:03 -04002374 et->ht_qualname = qualname ? qualname : et->ht_name;
2375 Py_INCREF(et->ht_qualname);
2376 if (qualname != NULL && PyDict_DelItem(dict, PyId___qualname__.object) < 0)
2377 goto error;
Victor Stinner6f738742012-02-25 01:22:36 +01002378
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002379 /* Set tp_doc to a copy of dict['__doc__'], if the latter is there
2380 and is a string. The __doc__ accessor will first look for tp_doc;
2381 if that fails, it will still look into __dict__.
2382 */
2383 {
Victor Stinner3c1e4812012-03-26 22:10:51 +02002384 PyObject *doc = _PyDict_GetItemId(dict, &PyId___doc__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002385 if (doc != NULL && PyUnicode_Check(doc)) {
2386 Py_ssize_t len;
2387 char *doc_str;
2388 char *tp_doc;
Alexandre Vassalottia85998a2008-05-03 18:24:43 +00002389
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002390 doc_str = _PyUnicode_AsString(doc);
Victor Stinner6f738742012-02-25 01:22:36 +01002391 if (doc_str == NULL)
2392 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002393 /* Silently truncate the docstring if it contains null bytes. */
2394 len = strlen(doc_str);
2395 tp_doc = (char *)PyObject_MALLOC(len + 1);
Victor Stinner53510cd2013-07-15 19:34:20 +02002396 if (tp_doc == NULL) {
2397 PyErr_NoMemory();
Victor Stinner6f738742012-02-25 01:22:36 +01002398 goto error;
Victor Stinner53510cd2013-07-15 19:34:20 +02002399 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002400 memcpy(tp_doc, doc_str, len + 1);
2401 type->tp_doc = tp_doc;
2402 }
2403 }
Tim Peters2f93e282001-10-04 05:27:00 +00002404
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002405 /* Special-case __new__: if it's a plain function,
2406 make it a static function */
Victor Stinner3c1e4812012-03-26 22:10:51 +02002407 tmp = _PyDict_GetItemId(dict, &PyId___new__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002408 if (tmp != NULL && PyFunction_Check(tmp)) {
2409 tmp = PyStaticMethod_New(tmp);
Victor Stinner6f738742012-02-25 01:22:36 +01002410 if (tmp == NULL)
2411 goto error;
Victor Stinner3c1e4812012-03-26 22:10:51 +02002412 if (_PyDict_SetItemId(dict, &PyId___new__, tmp) < 0)
2413 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002414 Py_DECREF(tmp);
2415 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002416
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002417 /* Add descriptors for custom slots from __slots__, or for __dict__ */
2418 mp = PyHeapType_GET_MEMBERS(et);
2419 slotoffset = base->tp_basicsize;
Victor Stinner6f738742012-02-25 01:22:36 +01002420 if (et->ht_slots != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002421 for (i = 0; i < nslots; i++, mp++) {
2422 mp->name = _PyUnicode_AsString(
Victor Stinner6f738742012-02-25 01:22:36 +01002423 PyTuple_GET_ITEM(et->ht_slots, i));
2424 if (mp->name == NULL)
2425 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002426 mp->type = T_OBJECT_EX;
2427 mp->offset = slotoffset;
Guido van Rossumd8faa362007-04-27 19:54:29 +00002428
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002429 /* __dict__ and __weakref__ are already filtered out */
2430 assert(strcmp(mp->name, "__dict__") != 0);
2431 assert(strcmp(mp->name, "__weakref__") != 0);
Guido van Rossumd8faa362007-04-27 19:54:29 +00002432
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002433 slotoffset += sizeof(PyObject *);
2434 }
2435 }
2436 if (add_dict) {
2437 if (base->tp_itemsize)
2438 type->tp_dictoffset = -(long)sizeof(PyObject *);
2439 else
2440 type->tp_dictoffset = slotoffset;
2441 slotoffset += sizeof(PyObject *);
2442 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002443 if (type->tp_dictoffset) {
2444 et->ht_cached_keys = _PyDict_NewKeysForClass();
2445 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002446 if (add_weak) {
2447 assert(!base->tp_itemsize);
2448 type->tp_weaklistoffset = slotoffset;
2449 slotoffset += sizeof(PyObject *);
2450 }
2451 type->tp_basicsize = slotoffset;
2452 type->tp_itemsize = base->tp_itemsize;
2453 type->tp_members = PyHeapType_GET_MEMBERS(et);
Guido van Rossum373c7412003-01-07 13:41:37 +00002454
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002455 if (type->tp_weaklistoffset && type->tp_dictoffset)
2456 type->tp_getset = subtype_getsets_full;
2457 else if (type->tp_weaklistoffset && !type->tp_dictoffset)
2458 type->tp_getset = subtype_getsets_weakref_only;
2459 else if (!type->tp_weaklistoffset && type->tp_dictoffset)
2460 type->tp_getset = subtype_getsets_dict_only;
2461 else
2462 type->tp_getset = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002463
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002464 /* Special case some slots */
2465 if (type->tp_dictoffset != 0 || nslots > 0) {
2466 if (base->tp_getattr == NULL && base->tp_getattro == NULL)
2467 type->tp_getattro = PyObject_GenericGetAttr;
2468 if (base->tp_setattr == NULL && base->tp_setattro == NULL)
2469 type->tp_setattro = PyObject_GenericSetAttr;
2470 }
2471 type->tp_dealloc = subtype_dealloc;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002472
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002473 /* Enable GC unless there are really no instance variables possible */
2474 if (!(type->tp_basicsize == sizeof(PyObject) &&
2475 type->tp_itemsize == 0))
2476 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossum9475a232001-10-05 20:51:39 +00002477
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002478 /* Always override allocation strategy to use regular heap */
2479 type->tp_alloc = PyType_GenericAlloc;
2480 if (type->tp_flags & Py_TPFLAGS_HAVE_GC) {
2481 type->tp_free = PyObject_GC_Del;
2482 type->tp_traverse = subtype_traverse;
2483 type->tp_clear = subtype_clear;
2484 }
2485 else
2486 type->tp_free = PyObject_Del;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002487
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002488 /* Initialize the rest */
Victor Stinner6f738742012-02-25 01:22:36 +01002489 if (PyType_Ready(type) < 0)
2490 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002491
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002492 /* Put the proper slots in place */
2493 fixup_slot_dispatchers(type);
Guido van Rossumf040ede2001-08-07 16:40:56 +00002494
Victor Stinner6f738742012-02-25 01:22:36 +01002495 Py_DECREF(dict);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002496 return (PyObject *)type;
Victor Stinner6f738742012-02-25 01:22:36 +01002497
2498error:
2499 Py_XDECREF(dict);
2500 Py_XDECREF(bases);
2501 Py_XDECREF(slots);
2502 Py_XDECREF(type);
2503 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002504}
2505
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002506static short slotoffsets[] = {
2507 -1, /* invalid slot */
2508#include "typeslots.inc"
2509};
2510
Benjamin Petersone28108c2012-01-29 20:13:18 -05002511PyObject *
Martin v. Löwis9c564092012-06-23 23:20:45 +02002512PyType_FromSpecWithBases(PyType_Spec *spec, PyObject *bases)
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002513{
2514 PyHeapTypeObject *res = (PyHeapTypeObject*)PyType_GenericAlloc(&PyType_Type, 0);
Martin v. Löwis9c564092012-06-23 23:20:45 +02002515 PyTypeObject *type, *base;
2516 char *s;
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002517 char *res_start = (char*)res;
2518 PyType_Slot *slot;
Victor Stinner54e4ca72013-07-11 22:42:25 +02002519
Martin v. Löwis9c564092012-06-23 23:20:45 +02002520 /* Set the type name and qualname */
2521 s = strrchr(spec->name, '.');
2522 if (s == NULL)
2523 s = (char*)spec->name;
2524 else
2525 s++;
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002526
Martin v. Löwis5e06a5d2011-02-21 16:24:00 +00002527 if (res == NULL)
Antoine Pitroubb78f572012-06-24 00:18:27 +02002528 return NULL;
2529 type = &res->ht_type;
Antoine Pitrou66a3a7e2012-06-24 00:42:59 +02002530 /* The flags must be initialized early, before the GC traverses us */
2531 type->tp_flags = spec->flags | Py_TPFLAGS_HEAPTYPE;
Martin v. Löwis9c564092012-06-23 23:20:45 +02002532 res->ht_name = PyUnicode_FromString(s);
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002533 if (!res->ht_name)
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002534 goto fail;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002535 res->ht_qualname = res->ht_name;
2536 Py_INCREF(res->ht_qualname);
Antoine Pitroubb78f572012-06-24 00:18:27 +02002537 type->tp_name = spec->name;
2538 if (!type->tp_name)
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002539 goto fail;
Victor Stinner54e4ca72013-07-11 22:42:25 +02002540
Martin v. Löwis9c564092012-06-23 23:20:45 +02002541 /* Adjust for empty tuple bases */
2542 if (!bases) {
2543 base = &PyBaseObject_Type;
2544 /* See whether Py_tp_base(s) was specified */
2545 for (slot = spec->slots; slot->slot; slot++) {
2546 if (slot->slot == Py_tp_base)
2547 base = slot->pfunc;
2548 else if (slot->slot == Py_tp_bases) {
2549 bases = slot->pfunc;
2550 Py_INCREF(bases);
2551 }
2552 }
2553 if (!bases)
2554 bases = PyTuple_Pack(1, base);
2555 if (!bases)
2556 goto fail;
2557 }
2558 else
2559 Py_INCREF(bases);
2560
2561 /* Calculate best base, and check that all bases are type objects */
2562 base = best_base(bases);
2563 if (base == NULL) {
2564 goto fail;
2565 }
2566 if (!PyType_HasFeature(base, Py_TPFLAGS_BASETYPE)) {
2567 PyErr_Format(PyExc_TypeError,
2568 "type '%.100s' is not an acceptable base type",
2569 base->tp_name);
2570 goto fail;
2571 }
2572
Martin v. Löwis9c564092012-06-23 23:20:45 +02002573 /* Initialize essential fields */
2574 type->tp_as_number = &res->as_number;
2575 type->tp_as_sequence = &res->as_sequence;
2576 type->tp_as_mapping = &res->as_mapping;
2577 type->tp_as_buffer = &res->as_buffer;
2578 /* Set tp_base and tp_bases */
2579 type->tp_bases = bases;
2580 bases = NULL;
2581 Py_INCREF(base);
2582 type->tp_base = base;
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002583
Antoine Pitroubb78f572012-06-24 00:18:27 +02002584 type->tp_basicsize = spec->basicsize;
2585 type->tp_itemsize = spec->itemsize;
Victor Stinner0fcab4a2011-01-04 12:59:15 +00002586
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002587 for (slot = spec->slots; slot->slot; slot++) {
Victor Stinner63941882011-09-29 00:42:28 +02002588 if (slot->slot >= Py_ARRAY_LENGTH(slotoffsets)) {
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002589 PyErr_SetString(PyExc_RuntimeError, "invalid slot offset");
2590 goto fail;
2591 }
Martin v. Löwis9c564092012-06-23 23:20:45 +02002592 if (slot->slot == Py_tp_base || slot->slot == Py_tp_bases)
2593 /* Processed above */
2594 continue;
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002595 *(void**)(res_start + slotoffsets[slot->slot]) = slot->pfunc;
Georg Brandl032400b2011-02-19 21:47:02 +00002596
2597 /* need to make a copy of the docstring slot, which usually
2598 points to a static string literal */
2599 if (slot->slot == Py_tp_doc) {
Larry Hastings581ee362014-01-28 05:00:08 -08002600 const char *old_doc = _PyType_DocWithoutSignature(slot->pfunc);
Larry Hastings5c661892014-01-24 06:17:25 -08002601 size_t len = strlen(old_doc)+1;
Georg Brandl032400b2011-02-19 21:47:02 +00002602 char *tp_doc = PyObject_MALLOC(len);
Victor Stinner53510cd2013-07-15 19:34:20 +02002603 if (tp_doc == NULL) {
2604 PyErr_NoMemory();
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002605 goto fail;
Victor Stinner53510cd2013-07-15 19:34:20 +02002606 }
Larry Hastings5c661892014-01-24 06:17:25 -08002607 memcpy(tp_doc, old_doc, len);
Antoine Pitroubb78f572012-06-24 00:18:27 +02002608 type->tp_doc = tp_doc;
Georg Brandl032400b2011-02-19 21:47:02 +00002609 }
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002610 }
Antoine Pitroubb78f572012-06-24 00:18:27 +02002611 if (type->tp_dictoffset) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002612 res->ht_cached_keys = _PyDict_NewKeysForClass();
2613 }
Antoine Pitroubb78f572012-06-24 00:18:27 +02002614 if (type->tp_dealloc == NULL) {
Antoine Pitrou99cc6292012-06-23 14:42:38 +02002615 /* It's a heap type, so needs the heap types' dealloc.
2616 subtype_dealloc will call the base type's tp_dealloc, if
2617 necessary. */
Antoine Pitroubb78f572012-06-24 00:18:27 +02002618 type->tp_dealloc = subtype_dealloc;
Antoine Pitrou99cc6292012-06-23 14:42:38 +02002619 }
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002620
Antoine Pitroubb78f572012-06-24 00:18:27 +02002621 if (PyType_Ready(type) < 0)
Benjamin Peterson2652d252012-01-29 20:16:37 -05002622 goto fail;
2623
Martin v. Löwis9c564092012-06-23 23:20:45 +02002624 /* Set type.__module__ */
2625 s = strrchr(spec->name, '.');
2626 if (s != NULL)
Victor Stinner54e4ca72013-07-11 22:42:25 +02002627 _PyDict_SetItemId(type->tp_dict, &PyId___module__,
Martin v. Löwis9c564092012-06-23 23:20:45 +02002628 PyUnicode_FromStringAndSize(
2629 spec->name, (Py_ssize_t)(s - spec->name)));
2630
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002631 return (PyObject*)res;
Victor Stinner0fcab4a2011-01-04 12:59:15 +00002632
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002633 fail:
2634 Py_DECREF(res);
2635 return NULL;
2636}
2637
Martin v. Löwis9c564092012-06-23 23:20:45 +02002638PyObject *
2639PyType_FromSpec(PyType_Spec *spec)
2640{
2641 return PyType_FromSpecWithBases(spec, NULL);
2642}
2643
Martin v. Löwisca7b0462014-02-04 09:33:05 +01002644void *
2645PyType_GetSlot(PyTypeObject *type, int slot)
2646{
Victor Stinner1ea4e412014-02-04 09:49:14 +01002647 if (!PyType_HasFeature(type, Py_TPFLAGS_HEAPTYPE)) {
Martin v. Löwisca7b0462014-02-04 09:33:05 +01002648 PyErr_BadInternalCall();
2649 return NULL;
2650 }
2651 if (slot >= Py_ARRAY_LENGTH(slotoffsets)) {
2652 /* Extension module requesting slot from a future version */
2653 return NULL;
2654 }
2655 return *(void**)(((char*)type) + slotoffsets[slot]);
2656}
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002657
Tim Peters6d6c1a32001-08-02 04:15:00 +00002658/* Internal API to look for a name through the MRO.
2659 This returns a borrowed reference, and doesn't set an exception! */
2660PyObject *
2661_PyType_Lookup(PyTypeObject *type, PyObject *name)
2662{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002663 Py_ssize_t i, n;
2664 PyObject *mro, *res, *base, *dict;
2665 unsigned int h;
Christian Heimesa62da1d2008-01-12 19:39:10 +00002666
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002667 if (MCACHE_CACHEABLE_NAME(name) &&
2668 PyType_HasFeature(type, Py_TPFLAGS_VALID_VERSION_TAG)) {
2669 /* fast path */
2670 h = MCACHE_HASH_METHOD(type, name);
2671 if (method_cache[h].version == type->tp_version_tag &&
2672 method_cache[h].name == name)
2673 return method_cache[h].value;
2674 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002675
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002676 /* Look in tp_dict of types in MRO */
2677 mro = type->tp_mro;
Guido van Rossum23094982002-06-10 14:30:43 +00002678
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002679 /* If mro is NULL, the type is either not yet initialized
2680 by PyType_Ready(), or already cleared by type_clear().
2681 Either way the safest thing to do is to return NULL. */
2682 if (mro == NULL)
2683 return NULL;
Guido van Rossum23094982002-06-10 14:30:43 +00002684
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002685 res = NULL;
Victor Stinnerd74782b2012-03-09 00:39:08 +01002686 /* keep a strong reference to mro because type->tp_mro can be replaced
2687 during PyDict_GetItem(dict, name) */
2688 Py_INCREF(mro);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002689 assert(PyTuple_Check(mro));
2690 n = PyTuple_GET_SIZE(mro);
2691 for (i = 0; i < n; i++) {
2692 base = PyTuple_GET_ITEM(mro, i);
2693 assert(PyType_Check(base));
2694 dict = ((PyTypeObject *)base)->tp_dict;
2695 assert(dict && PyDict_Check(dict));
2696 res = PyDict_GetItem(dict, name);
2697 if (res != NULL)
2698 break;
2699 }
Victor Stinnerd74782b2012-03-09 00:39:08 +01002700 Py_DECREF(mro);
Christian Heimesa62da1d2008-01-12 19:39:10 +00002701
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002702 if (MCACHE_CACHEABLE_NAME(name) && assign_version_tag(type)) {
2703 h = MCACHE_HASH_METHOD(type, name);
2704 method_cache[h].version = type->tp_version_tag;
2705 method_cache[h].value = res; /* borrowed */
2706 Py_INCREF(name);
2707 Py_DECREF(method_cache[h].name);
2708 method_cache[h].name = name;
2709 }
2710 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002711}
2712
Raymond Hettinger2ff21902013-10-01 00:55:43 -07002713PyObject *
Victor Stinner3c1e4812012-03-26 22:10:51 +02002714_PyType_LookupId(PyTypeObject *type, struct _Py_Identifier *name)
2715{
2716 PyObject *oname;
2717 oname = _PyUnicode_FromId(name); /* borrowed */
2718 if (oname == NULL)
2719 return NULL;
2720 return _PyType_Lookup(type, oname);
2721}
2722
Tim Peters6d6c1a32001-08-02 04:15:00 +00002723/* This is similar to PyObject_GenericGetAttr(),
2724 but uses _PyType_Lookup() instead of just looking in type->tp_dict. */
2725static PyObject *
2726type_getattro(PyTypeObject *type, PyObject *name)
2727{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002728 PyTypeObject *metatype = Py_TYPE(type);
2729 PyObject *meta_attribute, *attribute;
2730 descrgetfunc meta_get;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002731
Benjamin Peterson16d84ac2012-03-16 09:32:59 -05002732 if (!PyUnicode_Check(name)) {
2733 PyErr_Format(PyExc_TypeError,
2734 "attribute name must be string, not '%.200s'",
2735 name->ob_type->tp_name);
2736 return NULL;
2737 }
2738
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002739 /* Initialize this type (we'll assume the metatype is initialized) */
2740 if (type->tp_dict == NULL) {
2741 if (PyType_Ready(type) < 0)
2742 return NULL;
2743 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002744
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002745 /* No readable descriptor found yet */
2746 meta_get = NULL;
Tim Peters34592512002-07-11 06:23:50 +00002747
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002748 /* Look for the attribute in the metatype */
2749 meta_attribute = _PyType_Lookup(metatype, name);
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002750
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002751 if (meta_attribute != NULL) {
2752 meta_get = Py_TYPE(meta_attribute)->tp_descr_get;
Tim Peters34592512002-07-11 06:23:50 +00002753
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002754 if (meta_get != NULL && PyDescr_IsData(meta_attribute)) {
2755 /* Data descriptors implement tp_descr_set to intercept
2756 * writes. Assume the attribute is not overridden in
2757 * type's tp_dict (and bases): call the descriptor now.
2758 */
2759 return meta_get(meta_attribute, (PyObject *)type,
2760 (PyObject *)metatype);
2761 }
2762 Py_INCREF(meta_attribute);
2763 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002764
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002765 /* No data descriptor found on metatype. Look in tp_dict of this
2766 * type and its bases */
2767 attribute = _PyType_Lookup(type, name);
2768 if (attribute != NULL) {
2769 /* Implement descriptor functionality, if any */
2770 descrgetfunc local_get = Py_TYPE(attribute)->tp_descr_get;
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00002771
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002772 Py_XDECREF(meta_attribute);
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00002773
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002774 if (local_get != NULL) {
2775 /* NULL 2nd argument indicates the descriptor was
2776 * found on the target object itself (or a base) */
2777 return local_get(attribute, (PyObject *)NULL,
2778 (PyObject *)type);
2779 }
Tim Peters34592512002-07-11 06:23:50 +00002780
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002781 Py_INCREF(attribute);
2782 return attribute;
2783 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002784
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002785 /* No attribute found in local __dict__ (or bases): use the
2786 * descriptor from the metatype, if any */
2787 if (meta_get != NULL) {
2788 PyObject *res;
2789 res = meta_get(meta_attribute, (PyObject *)type,
2790 (PyObject *)metatype);
2791 Py_DECREF(meta_attribute);
2792 return res;
2793 }
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002794
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002795 /* If an ordinary attribute was found on the metatype, return it now */
2796 if (meta_attribute != NULL) {
2797 return meta_attribute;
2798 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002799
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002800 /* Give up */
2801 PyErr_Format(PyExc_AttributeError,
2802 "type object '%.50s' has no attribute '%U'",
2803 type->tp_name, name);
2804 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002805}
2806
2807static int
2808type_setattro(PyTypeObject *type, PyObject *name, PyObject *value)
2809{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002810 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
2811 PyErr_Format(
2812 PyExc_TypeError,
2813 "can't set attributes of built-in/extension type '%s'",
2814 type->tp_name);
2815 return -1;
2816 }
2817 if (PyObject_GenericSetAttr((PyObject *)type, name, value) < 0)
2818 return -1;
2819 return update_slot(type, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002820}
2821
Benjamin Peterson64acccf2012-04-27 15:07:36 -04002822extern void
2823_PyDictKeys_DecRef(PyDictKeysObject *keys);
2824
Tim Peters6d6c1a32001-08-02 04:15:00 +00002825static void
2826type_dealloc(PyTypeObject *type)
2827{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002828 PyHeapTypeObject *et;
Antoine Pitrou84745ab2013-10-29 21:31:25 +01002829 PyObject *tp, *val, *tb;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002830
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002831 /* Assert this is a heap-allocated type object */
2832 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
2833 _PyObject_GC_UNTRACK(type);
Antoine Pitrou84745ab2013-10-29 21:31:25 +01002834 PyErr_Fetch(&tp, &val, &tb);
2835 remove_all_subclasses(type, type->tp_bases);
2836 PyErr_Restore(tp, val, tb);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002837 PyObject_ClearWeakRefs((PyObject *)type);
2838 et = (PyHeapTypeObject *)type;
2839 Py_XDECREF(type->tp_base);
2840 Py_XDECREF(type->tp_dict);
2841 Py_XDECREF(type->tp_bases);
2842 Py_XDECREF(type->tp_mro);
2843 Py_XDECREF(type->tp_cache);
2844 Py_XDECREF(type->tp_subclasses);
2845 /* A type's tp_doc is heap allocated, unlike the tp_doc slots
2846 * of most other objects. It's okay to cast it to char *.
2847 */
2848 PyObject_Free((char *)type->tp_doc);
2849 Py_XDECREF(et->ht_name);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002850 Py_XDECREF(et->ht_qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002851 Py_XDECREF(et->ht_slots);
Benjamin Peterson64acccf2012-04-27 15:07:36 -04002852 if (et->ht_cached_keys)
2853 _PyDictKeys_DecRef(et->ht_cached_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002854 Py_TYPE(type)->tp_free((PyObject *)type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002855}
2856
Guido van Rossum1c450732001-10-08 15:18:27 +00002857static PyObject *
2858type_subclasses(PyTypeObject *type, PyObject *args_ignored)
2859{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002860 PyObject *list, *raw, *ref;
Antoine Pitrou84745ab2013-10-29 21:31:25 +01002861 Py_ssize_t i;
Guido van Rossum1c450732001-10-08 15:18:27 +00002862
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002863 list = PyList_New(0);
2864 if (list == NULL)
2865 return NULL;
2866 raw = type->tp_subclasses;
2867 if (raw == NULL)
2868 return list;
Antoine Pitrou84745ab2013-10-29 21:31:25 +01002869 assert(PyDict_CheckExact(raw));
2870 i = 0;
2871 while (PyDict_Next(raw, &i, NULL, &ref)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002872 assert(PyWeakref_CheckRef(ref));
2873 ref = PyWeakref_GET_OBJECT(ref);
2874 if (ref != Py_None) {
2875 if (PyList_Append(list, ref) < 0) {
2876 Py_DECREF(list);
2877 return NULL;
2878 }
2879 }
2880 }
2881 return list;
Guido van Rossum1c450732001-10-08 15:18:27 +00002882}
2883
Guido van Rossum47374822007-08-02 16:48:17 +00002884static PyObject *
2885type_prepare(PyObject *self, PyObject *args, PyObject *kwds)
2886{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002887 return PyDict_New();
Guido van Rossum47374822007-08-02 16:48:17 +00002888}
2889
Victor Stinner63941882011-09-29 00:42:28 +02002890/*
Benjamin Peterson82b00c12011-05-24 11:09:06 -05002891 Merge the __dict__ of aclass into dict, and recursively also all
2892 the __dict__s of aclass's base classes. The order of merging isn't
2893 defined, as it's expected that only the final set of dict keys is
2894 interesting.
2895 Return 0 on success, -1 on error.
2896*/
2897
2898static int
2899merge_class_dict(PyObject *dict, PyObject *aclass)
2900{
2901 PyObject *classdict;
2902 PyObject *bases;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02002903 _Py_IDENTIFIER(__bases__);
Benjamin Peterson82b00c12011-05-24 11:09:06 -05002904
2905 assert(PyDict_Check(dict));
2906 assert(aclass);
2907
2908 /* Merge in the type's dict (if any). */
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002909 classdict = _PyObject_GetAttrId(aclass, &PyId___dict__);
Benjamin Peterson82b00c12011-05-24 11:09:06 -05002910 if (classdict == NULL)
2911 PyErr_Clear();
2912 else {
2913 int status = PyDict_Update(dict, classdict);
2914 Py_DECREF(classdict);
2915 if (status < 0)
2916 return -1;
2917 }
2918
2919 /* Recursively merge in the base types' (if any) dicts. */
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002920 bases = _PyObject_GetAttrId(aclass, &PyId___bases__);
Benjamin Peterson82b00c12011-05-24 11:09:06 -05002921 if (bases == NULL)
2922 PyErr_Clear();
2923 else {
2924 /* We have no guarantee that bases is a real tuple */
2925 Py_ssize_t i, n;
2926 n = PySequence_Size(bases); /* This better be right */
2927 if (n < 0)
2928 PyErr_Clear();
2929 else {
2930 for (i = 0; i < n; i++) {
2931 int status;
2932 PyObject *base = PySequence_GetItem(bases, i);
2933 if (base == NULL) {
2934 Py_DECREF(bases);
2935 return -1;
2936 }
2937 status = merge_class_dict(dict, base);
2938 Py_DECREF(base);
2939 if (status < 0) {
2940 Py_DECREF(bases);
2941 return -1;
2942 }
2943 }
2944 }
2945 Py_DECREF(bases);
2946 }
2947 return 0;
2948}
2949
2950/* __dir__ for type objects: returns __dict__ and __bases__.
2951 We deliberately don't suck up its __class__, as methods belonging to the
2952 metaclass would probably be more confusing than helpful.
2953*/
2954static PyObject *
2955type_dir(PyObject *self, PyObject *args)
2956{
2957 PyObject *result = NULL;
2958 PyObject *dict = PyDict_New();
2959
2960 if (dict != NULL && merge_class_dict(dict, self) == 0)
2961 result = PyDict_Keys(dict);
2962
2963 Py_XDECREF(dict);
2964 return result;
2965}
2966
Martin v. Loewis4f2f3b62012-04-24 19:13:57 +02002967static PyObject*
2968type_sizeof(PyObject *self, PyObject *args_unused)
2969{
2970 Py_ssize_t size;
2971 PyTypeObject *type = (PyTypeObject*)self;
2972 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
2973 PyHeapTypeObject* et = (PyHeapTypeObject*)type;
2974 size = sizeof(PyHeapTypeObject);
2975 if (et->ht_cached_keys)
2976 size += _PyDict_KeysSize(et->ht_cached_keys);
2977 }
2978 else
2979 size = sizeof(PyTypeObject);
2980 return PyLong_FromSsize_t(size);
2981}
2982
Tim Peters6d6c1a32001-08-02 04:15:00 +00002983static PyMethodDef type_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002984 {"mro", (PyCFunction)mro_external, METH_NOARGS,
2985 PyDoc_STR("mro() -> list\nreturn a type's method resolution order")},
2986 {"__subclasses__", (PyCFunction)type_subclasses, METH_NOARGS,
2987 PyDoc_STR("__subclasses__() -> list of immediate subclasses")},
2988 {"__prepare__", (PyCFunction)type_prepare,
2989 METH_VARARGS | METH_KEYWORDS | METH_CLASS,
2990 PyDoc_STR("__prepare__() -> dict\n"
2991 "used to create the namespace for the class statement")},
2992 {"__instancecheck__", type___instancecheck__, METH_O,
Benjamin Petersonfbe56bb2011-05-24 12:42:51 -05002993 PyDoc_STR("__instancecheck__() -> bool\ncheck if an object is an instance")},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002994 {"__subclasscheck__", type___subclasscheck__, METH_O,
Benjamin Petersonfbe56bb2011-05-24 12:42:51 -05002995 PyDoc_STR("__subclasscheck__() -> bool\ncheck if a class is a subclass")},
Benjamin Peterson82b00c12011-05-24 11:09:06 -05002996 {"__dir__", type_dir, METH_NOARGS,
Benjamin Petersonc7284122011-05-24 12:46:15 -05002997 PyDoc_STR("__dir__() -> list\nspecialized __dir__ implementation for types")},
Martin v. Loewis4f2f3b62012-04-24 19:13:57 +02002998 {"__sizeof__", type_sizeof, METH_NOARGS,
2999 "__sizeof__() -> int\nreturn memory consumption of the type object"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003000 {0}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003001};
3002
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003003PyDoc_STRVAR(type_doc,
Larry Hastings5c661892014-01-24 06:17:25 -08003004/* this text signature cannot be accurate yet. will fix. --larry */
Larry Hastings581ee362014-01-28 05:00:08 -08003005"sig=(object_or_name, bases, dict)\n"
Tim Peters6d6c1a32001-08-02 04:15:00 +00003006"type(object) -> the object's type\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003007"type(name, bases, dict) -> a new type");
Tim Peters6d6c1a32001-08-02 04:15:00 +00003008
Guido van Rossum048eb752001-10-02 21:24:57 +00003009static int
3010type_traverse(PyTypeObject *type, visitproc visit, void *arg)
3011{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003012 /* Because of type_is_gc(), the collector only calls this
3013 for heaptypes. */
Antoine Pitrou1351ca62012-06-24 00:30:12 +02003014 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
3015 char msg[200];
3016 sprintf(msg, "type_traverse() called for non-heap type '%.100s'",
3017 type->tp_name);
3018 Py_FatalError(msg);
3019 }
Guido van Rossum048eb752001-10-02 21:24:57 +00003020
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003021 Py_VISIT(type->tp_dict);
3022 Py_VISIT(type->tp_cache);
3023 Py_VISIT(type->tp_mro);
3024 Py_VISIT(type->tp_bases);
3025 Py_VISIT(type->tp_base);
Guido van Rossuma3862092002-06-10 15:24:42 +00003026
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003027 /* There's no need to visit type->tp_subclasses or
3028 ((PyHeapTypeObject *)type)->ht_slots, because they can't be involved
3029 in cycles; tp_subclasses is a list of weak references,
3030 and slots is a tuple of strings. */
Guido van Rossum048eb752001-10-02 21:24:57 +00003031
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003032 return 0;
Guido van Rossum048eb752001-10-02 21:24:57 +00003033}
3034
3035static int
3036type_clear(PyTypeObject *type)
3037{
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003038 PyDictKeysObject *cached_keys;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003039 /* Because of type_is_gc(), the collector only calls this
3040 for heaptypes. */
3041 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00003042
Antoine Pitrou2e872082011-12-15 14:15:31 +01003043 /* We need to invalidate the method cache carefully before clearing
3044 the dict, so that other objects caught in a reference cycle
3045 don't start calling destroyed methods.
3046
3047 Otherwise, the only field we need to clear is tp_mro, which is
3048 part of a hard cycle (its first element is the class itself) that
3049 won't be broken otherwise (it's a tuple and tuples don't have a
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003050 tp_clear handler). None of the other fields need to be
3051 cleared, and here's why:
Guido van Rossum048eb752001-10-02 21:24:57 +00003052
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003053 tp_cache:
3054 Not used; if it were, it would be a dict.
Guido van Rossuma3862092002-06-10 15:24:42 +00003055
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003056 tp_bases, tp_base:
3057 If these are involved in a cycle, there must be at least
3058 one other, mutable object in the cycle, e.g. a base
3059 class's dict; the cycle will be broken that way.
Guido van Rossuma3862092002-06-10 15:24:42 +00003060
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003061 tp_subclasses:
Antoine Pitrou84745ab2013-10-29 21:31:25 +01003062 A dict of weak references can't be part of a cycle; and
3063 dicts have their own tp_clear.
Guido van Rossuma3862092002-06-10 15:24:42 +00003064
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003065 slots (in PyHeapTypeObject):
3066 A tuple of strings can't be part of a cycle.
3067 */
Guido van Rossuma3862092002-06-10 15:24:42 +00003068
Antoine Pitrou2e872082011-12-15 14:15:31 +01003069 PyType_Modified(type);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003070 cached_keys = ((PyHeapTypeObject *)type)->ht_cached_keys;
3071 if (cached_keys != NULL) {
3072 ((PyHeapTypeObject *)type)->ht_cached_keys = NULL;
3073 _PyDictKeys_DecRef(cached_keys);
3074 }
Antoine Pitrou2e872082011-12-15 14:15:31 +01003075 if (type->tp_dict)
3076 PyDict_Clear(type->tp_dict);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003077 Py_CLEAR(type->tp_mro);
Guido van Rossum048eb752001-10-02 21:24:57 +00003078
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003079 return 0;
Guido van Rossum048eb752001-10-02 21:24:57 +00003080}
3081
3082static int
3083type_is_gc(PyTypeObject *type)
3084{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003085 return type->tp_flags & Py_TPFLAGS_HEAPTYPE;
Guido van Rossum048eb752001-10-02 21:24:57 +00003086}
3087
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003088PyTypeObject PyType_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003089 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3090 "type", /* tp_name */
3091 sizeof(PyHeapTypeObject), /* tp_basicsize */
3092 sizeof(PyMemberDef), /* tp_itemsize */
3093 (destructor)type_dealloc, /* tp_dealloc */
3094 0, /* tp_print */
3095 0, /* tp_getattr */
3096 0, /* tp_setattr */
3097 0, /* tp_reserved */
3098 (reprfunc)type_repr, /* tp_repr */
3099 0, /* tp_as_number */
3100 0, /* tp_as_sequence */
3101 0, /* tp_as_mapping */
3102 0, /* tp_hash */
3103 (ternaryfunc)type_call, /* tp_call */
3104 0, /* tp_str */
3105 (getattrofunc)type_getattro, /* tp_getattro */
3106 (setattrofunc)type_setattro, /* tp_setattro */
3107 0, /* tp_as_buffer */
3108 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
3109 Py_TPFLAGS_BASETYPE | Py_TPFLAGS_TYPE_SUBCLASS, /* tp_flags */
3110 type_doc, /* tp_doc */
3111 (traverseproc)type_traverse, /* tp_traverse */
3112 (inquiry)type_clear, /* tp_clear */
3113 0, /* tp_richcompare */
3114 offsetof(PyTypeObject, tp_weaklist), /* tp_weaklistoffset */
3115 0, /* tp_iter */
3116 0, /* tp_iternext */
3117 type_methods, /* tp_methods */
3118 type_members, /* tp_members */
3119 type_getsets, /* tp_getset */
3120 0, /* tp_base */
3121 0, /* tp_dict */
3122 0, /* tp_descr_get */
3123 0, /* tp_descr_set */
3124 offsetof(PyTypeObject, tp_dict), /* tp_dictoffset */
3125 type_init, /* tp_init */
3126 0, /* tp_alloc */
3127 type_new, /* tp_new */
3128 PyObject_GC_Del, /* tp_free */
3129 (inquiry)type_is_gc, /* tp_is_gc */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003130};
Tim Peters6d6c1a32001-08-02 04:15:00 +00003131
3132
3133/* The base type of all types (eventually)... except itself. */
3134
Guido van Rossumd8faa362007-04-27 19:54:29 +00003135/* You may wonder why object.__new__() only complains about arguments
3136 when object.__init__() is not overridden, and vice versa.
3137
3138 Consider the use cases:
3139
3140 1. When neither is overridden, we want to hear complaints about
3141 excess (i.e., any) arguments, since their presence could
3142 indicate there's a bug.
3143
3144 2. When defining an Immutable type, we are likely to override only
3145 __new__(), since __init__() is called too late to initialize an
3146 Immutable object. Since __new__() defines the signature for the
3147 type, it would be a pain to have to override __init__() just to
3148 stop it from complaining about excess arguments.
3149
3150 3. When defining a Mutable type, we are likely to override only
3151 __init__(). So here the converse reasoning applies: we don't
3152 want to have to override __new__() just to stop it from
3153 complaining.
3154
3155 4. When __init__() is overridden, and the subclass __init__() calls
3156 object.__init__(), the latter should complain about excess
3157 arguments; ditto for __new__().
3158
3159 Use cases 2 and 3 make it unattractive to unconditionally check for
3160 excess arguments. The best solution that addresses all four use
3161 cases is as follows: __init__() complains about excess arguments
3162 unless __new__() is overridden and __init__() is not overridden
3163 (IOW, if __init__() is overridden or __new__() is not overridden);
3164 symmetrically, __new__() complains about excess arguments unless
3165 __init__() is overridden and __new__() is not overridden
3166 (IOW, if __new__() is overridden or __init__() is not overridden).
3167
3168 However, for backwards compatibility, this breaks too much code.
3169 Therefore, in 2.6, we'll *warn* about excess arguments when both
3170 methods are overridden; for all other cases we'll use the above
3171 rules.
3172
3173*/
3174
3175/* Forward */
3176static PyObject *
3177object_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
3178
3179static int
3180excess_args(PyObject *args, PyObject *kwds)
3181{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003182 return PyTuple_GET_SIZE(args) ||
3183 (kwds && PyDict_Check(kwds) && PyDict_Size(kwds));
Guido van Rossumd8faa362007-04-27 19:54:29 +00003184}
3185
Tim Peters6d6c1a32001-08-02 04:15:00 +00003186static int
3187object_init(PyObject *self, PyObject *args, PyObject *kwds)
3188{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003189 int err = 0;
Benjamin Peterson96384b92012-03-17 00:05:44 -05003190 PyTypeObject *type = Py_TYPE(self);
3191 if (excess_args(args, kwds) &&
3192 (type->tp_new == object_new || type->tp_init != object_init)) {
3193 PyErr_SetString(PyExc_TypeError, "object.__init__() takes no parameters");
3194 err = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003195 }
3196 return err;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003197}
3198
Guido van Rossum298e4212003-02-13 16:30:16 +00003199static PyObject *
3200object_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3201{
Benjamin Peterson96384b92012-03-17 00:05:44 -05003202 if (excess_args(args, kwds) &&
3203 (type->tp_init == object_init || type->tp_new != object_new)) {
R David Murray702a5dc2013-02-18 21:39:18 -05003204 PyErr_SetString(PyExc_TypeError, "object() takes no parameters");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003205 return NULL;
Benjamin Peterson96384b92012-03-17 00:05:44 -05003206 }
Victor Stinner3c1e4812012-03-26 22:10:51 +02003207
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003208 if (type->tp_flags & Py_TPFLAGS_IS_ABSTRACT) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003209 PyObject *abstract_methods = NULL;
3210 PyObject *builtins;
3211 PyObject *sorted;
3212 PyObject *sorted_methods = NULL;
3213 PyObject *joined = NULL;
Benjamin Peterson9a03ecf2012-03-16 20:15:54 -05003214 PyObject *comma;
3215 _Py_static_string(comma_id, ", ");
Victor Stinner3c1e4812012-03-26 22:10:51 +02003216 _Py_IDENTIFIER(sorted);
Christian Heimes9e7f1d22008-02-28 12:27:11 +00003217
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003218 /* Compute ", ".join(sorted(type.__abstractmethods__))
3219 into joined. */
3220 abstract_methods = type_abstractmethods(type, NULL);
3221 if (abstract_methods == NULL)
3222 goto error;
3223 builtins = PyEval_GetBuiltins();
3224 if (builtins == NULL)
3225 goto error;
Victor Stinner3c1e4812012-03-26 22:10:51 +02003226 sorted = _PyDict_GetItemId(builtins, &PyId_sorted);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003227 if (sorted == NULL)
3228 goto error;
3229 sorted_methods = PyObject_CallFunctionObjArgs(sorted,
3230 abstract_methods,
3231 NULL);
3232 if (sorted_methods == NULL)
3233 goto error;
Benjamin Peterson9a03ecf2012-03-16 20:15:54 -05003234 comma = _PyUnicode_FromId(&comma_id);
3235 if (comma == NULL)
3236 goto error;
3237 joined = PyUnicode_Join(comma, sorted_methods);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003238 if (joined == NULL)
3239 goto error;
Christian Heimes9e7f1d22008-02-28 12:27:11 +00003240
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003241 PyErr_Format(PyExc_TypeError,
3242 "Can't instantiate abstract class %s "
3243 "with abstract methods %U",
3244 type->tp_name,
3245 joined);
3246 error:
3247 Py_XDECREF(joined);
3248 Py_XDECREF(sorted_methods);
3249 Py_XDECREF(abstract_methods);
3250 return NULL;
3251 }
3252 return type->tp_alloc(type, 0);
Guido van Rossum298e4212003-02-13 16:30:16 +00003253}
3254
Tim Peters6d6c1a32001-08-02 04:15:00 +00003255static void
3256object_dealloc(PyObject *self)
3257{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003258 Py_TYPE(self)->tp_free(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003259}
3260
Guido van Rossum8e248182001-08-12 05:17:56 +00003261static PyObject *
3262object_repr(PyObject *self)
3263{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003264 PyTypeObject *type;
3265 PyObject *mod, *name, *rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00003266
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003267 type = Py_TYPE(self);
3268 mod = type_module(type, NULL);
3269 if (mod == NULL)
3270 PyErr_Clear();
3271 else if (!PyUnicode_Check(mod)) {
3272 Py_DECREF(mod);
3273 mod = NULL;
3274 }
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003275 name = type_qualname(type, NULL);
Christian Heimese81dc292012-09-10 16:57:36 +02003276 if (name == NULL) {
3277 Py_XDECREF(mod);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003278 return NULL;
Christian Heimese81dc292012-09-10 16:57:36 +02003279 }
Victor Stinnerbd303c12013-11-07 23:07:29 +01003280 if (mod != NULL && _PyUnicode_CompareWithId(mod, &PyId_builtins))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003281 rtn = PyUnicode_FromFormat("<%U.%U object at %p>", mod, name, self);
3282 else
3283 rtn = PyUnicode_FromFormat("<%s object at %p>",
3284 type->tp_name, self);
3285 Py_XDECREF(mod);
3286 Py_DECREF(name);
3287 return rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00003288}
3289
Guido van Rossumb8f63662001-08-15 23:57:02 +00003290static PyObject *
3291object_str(PyObject *self)
3292{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003293 unaryfunc f;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003294
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003295 f = Py_TYPE(self)->tp_repr;
Benjamin Peterson7b166872012-04-24 11:06:25 -04003296 if (f == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003297 f = object_repr;
3298 return f(self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003299}
3300
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003301static PyObject *
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003302object_richcompare(PyObject *self, PyObject *other, int op)
3303{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003304 PyObject *res;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003305
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003306 switch (op) {
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003307
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003308 case Py_EQ:
3309 /* Return NotImplemented instead of False, so if two
3310 objects are compared, both get a chance at the
3311 comparison. See issue #1393. */
3312 res = (self == other) ? Py_True : Py_NotImplemented;
3313 Py_INCREF(res);
3314 break;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003315
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003316 case Py_NE:
3317 /* By default, != returns the opposite of ==,
3318 unless the latter returns NotImplemented. */
3319 res = PyObject_RichCompare(self, other, Py_EQ);
3320 if (res != NULL && res != Py_NotImplemented) {
3321 int ok = PyObject_IsTrue(res);
3322 Py_DECREF(res);
3323 if (ok < 0)
3324 res = NULL;
3325 else {
3326 if (ok)
3327 res = Py_False;
3328 else
3329 res = Py_True;
3330 Py_INCREF(res);
3331 }
3332 }
3333 break;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003334
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003335 default:
3336 res = Py_NotImplemented;
3337 Py_INCREF(res);
3338 break;
3339 }
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003340
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003341 return res;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003342}
3343
3344static PyObject *
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003345object_get_class(PyObject *self, void *closure)
3346{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003347 Py_INCREF(Py_TYPE(self));
3348 return (PyObject *)(Py_TYPE(self));
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003349}
3350
3351static int
3352equiv_structs(PyTypeObject *a, PyTypeObject *b)
3353{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003354 return a == b ||
3355 (a != NULL &&
3356 b != NULL &&
3357 a->tp_basicsize == b->tp_basicsize &&
3358 a->tp_itemsize == b->tp_itemsize &&
3359 a->tp_dictoffset == b->tp_dictoffset &&
3360 a->tp_weaklistoffset == b->tp_weaklistoffset &&
3361 ((a->tp_flags & Py_TPFLAGS_HAVE_GC) ==
3362 (b->tp_flags & Py_TPFLAGS_HAVE_GC)));
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003363}
3364
3365static int
3366same_slots_added(PyTypeObject *a, PyTypeObject *b)
3367{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003368 PyTypeObject *base = a->tp_base;
3369 Py_ssize_t size;
3370 PyObject *slots_a, *slots_b;
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003371
Benjamin Peterson67641d22011-01-17 19:24:34 +00003372 assert(base == b->tp_base);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003373 size = base->tp_basicsize;
3374 if (a->tp_dictoffset == size && b->tp_dictoffset == size)
3375 size += sizeof(PyObject *);
3376 if (a->tp_weaklistoffset == size && b->tp_weaklistoffset == size)
3377 size += sizeof(PyObject *);
Guido van Rossumd8faa362007-04-27 19:54:29 +00003378
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003379 /* Check slots compliance */
3380 slots_a = ((PyHeapTypeObject *)a)->ht_slots;
3381 slots_b = ((PyHeapTypeObject *)b)->ht_slots;
3382 if (slots_a && slots_b) {
3383 if (PyObject_RichCompareBool(slots_a, slots_b, Py_EQ) != 1)
3384 return 0;
3385 size += sizeof(PyObject *) * PyTuple_GET_SIZE(slots_a);
3386 }
3387 return size == a->tp_basicsize && size == b->tp_basicsize;
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003388}
3389
3390static int
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003391compatible_for_assignment(PyTypeObject* oldto, PyTypeObject* newto, char* attr)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003392{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003393 PyTypeObject *newbase, *oldbase;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003394
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003395 if (newto->tp_dealloc != oldto->tp_dealloc ||
3396 newto->tp_free != oldto->tp_free)
3397 {
3398 PyErr_Format(PyExc_TypeError,
3399 "%s assignment: "
3400 "'%s' deallocator differs from '%s'",
3401 attr,
3402 newto->tp_name,
3403 oldto->tp_name);
3404 return 0;
3405 }
3406 newbase = newto;
3407 oldbase = oldto;
3408 while (equiv_structs(newbase, newbase->tp_base))
3409 newbase = newbase->tp_base;
3410 while (equiv_structs(oldbase, oldbase->tp_base))
3411 oldbase = oldbase->tp_base;
3412 if (newbase != oldbase &&
3413 (newbase->tp_base != oldbase->tp_base ||
3414 !same_slots_added(newbase, oldbase))) {
3415 PyErr_Format(PyExc_TypeError,
3416 "%s assignment: "
3417 "'%s' object layout differs from '%s'",
3418 attr,
3419 newto->tp_name,
3420 oldto->tp_name);
3421 return 0;
3422 }
Tim Petersea7f75d2002-12-07 21:39:16 +00003423
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003424 return 1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003425}
3426
3427static int
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003428object_set_class(PyObject *self, PyObject *value, void *closure)
3429{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003430 PyTypeObject *oldto = Py_TYPE(self);
3431 PyTypeObject *newto;
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003432
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003433 if (value == NULL) {
3434 PyErr_SetString(PyExc_TypeError,
3435 "can't delete __class__ attribute");
3436 return -1;
3437 }
3438 if (!PyType_Check(value)) {
3439 PyErr_Format(PyExc_TypeError,
Florent Xiclunaaa6c1d22011-12-12 18:54:29 +01003440 "__class__ must be set to a class, not '%s' object",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003441 Py_TYPE(value)->tp_name);
3442 return -1;
3443 }
3444 newto = (PyTypeObject *)value;
3445 if (!(newto->tp_flags & Py_TPFLAGS_HEAPTYPE) ||
3446 !(oldto->tp_flags & Py_TPFLAGS_HEAPTYPE))
3447 {
3448 PyErr_Format(PyExc_TypeError,
3449 "__class__ assignment: only for heap types");
3450 return -1;
3451 }
Christian Heimesde4d1832013-07-20 14:19:46 +02003452 if (compatible_for_assignment(oldto, newto, "__class__")) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003453 Py_INCREF(newto);
3454 Py_TYPE(self) = newto;
3455 Py_DECREF(oldto);
3456 return 0;
3457 }
3458 else {
3459 return -1;
3460 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003461}
3462
3463static PyGetSetDef object_getsets[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003464 {"__class__", object_get_class, object_set_class,
3465 PyDoc_STR("the object's class")},
3466 {0}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003467};
3468
Guido van Rossumc53f0092003-02-18 22:05:12 +00003469
Guido van Rossum036f9992003-02-21 22:02:54 +00003470/* Stuff to implement __reduce_ex__ for pickle protocols >= 2.
Alexandre Vassalottif7fa63d2008-05-11 08:55:36 +00003471 We fall back to helpers in copyreg for:
Guido van Rossum036f9992003-02-21 22:02:54 +00003472 - pickle protocols < 2
3473 - calculating the list of slot names (done only once per class)
3474 - the __newobj__ function (which is used as a token but never called)
3475*/
3476
3477static PyObject *
Alexandre Vassalottif7fa63d2008-05-11 08:55:36 +00003478import_copyreg(void)
Guido van Rossum036f9992003-02-21 22:02:54 +00003479{
Alexandre Vassalotti1a830702013-11-30 00:53:09 -08003480 PyObject *copyreg_str;
3481 PyObject *copyreg_module;
3482 PyInterpreterState *interp = PyThreadState_GET()->interp;
3483 _Py_IDENTIFIER(copyreg);
Guido van Rossum3926a632001-09-25 16:25:58 +00003484
Alexandre Vassalotti1a830702013-11-30 00:53:09 -08003485 copyreg_str = _PyUnicode_FromId(&PyId_copyreg);
3486 if (copyreg_str == NULL) {
3487 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003488 }
Alexandre Vassalotti1a830702013-11-30 00:53:09 -08003489 /* Try to fetch cached copy of copyreg from sys.modules first in an
3490 attempt to avoid the import overhead. Previously this was implemented
3491 by storing a reference to the cached module in a static variable, but
3492 this broke when multiple embeded interpreters were in use (see issue
3493 #17408 and #19088). */
3494 copyreg_module = PyDict_GetItemWithError(interp->modules, copyreg_str);
3495 if (copyreg_module != NULL) {
3496 Py_INCREF(copyreg_module);
3497 return copyreg_module;
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003498 }
Alexandre Vassalotti1a830702013-11-30 00:53:09 -08003499 if (PyErr_Occurred()) {
3500 return NULL;
3501 }
3502 return PyImport_Import(copyreg_str);
Guido van Rossum036f9992003-02-21 22:02:54 +00003503}
3504
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01003505Py_LOCAL(PyObject *)
3506_PyType_GetSlotNames(PyTypeObject *cls)
Guido van Rossum036f9992003-02-21 22:02:54 +00003507{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003508 PyObject *copyreg;
3509 PyObject *slotnames;
Victor Stinner3c1e4812012-03-26 22:10:51 +02003510 _Py_IDENTIFIER(__slotnames__);
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02003511 _Py_IDENTIFIER(_slotnames);
Guido van Rossum036f9992003-02-21 22:02:54 +00003512
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01003513 assert(PyType_Check(cls));
3514
3515 /* Get the slot names from the cache in the class if possible. */
3516 slotnames = _PyDict_GetItemIdWithError(cls->tp_dict, &PyId___slotnames__);
3517 if (slotnames != NULL) {
3518 if (slotnames != Py_None && !PyList_Check(slotnames)) {
3519 PyErr_Format(PyExc_TypeError,
3520 "%.200s.__slotnames__ should be a list or None, "
3521 "not %.200s",
3522 cls->tp_name, Py_TYPE(slotnames)->tp_name);
3523 return NULL;
3524 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003525 Py_INCREF(slotnames);
3526 return slotnames;
3527 }
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01003528 else {
3529 if (PyErr_Occurred()) {
3530 return NULL;
3531 }
3532 /* The class does not have the slot names cached yet. */
3533 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003534
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003535 copyreg = import_copyreg();
3536 if (copyreg == NULL)
3537 return NULL;
Guido van Rossum036f9992003-02-21 22:02:54 +00003538
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01003539 /* Use _slotnames function from the copyreg module to find the slots
3540 by this class and its bases. This function will cache the result
3541 in __slotnames__. */
3542 slotnames = _PyObject_CallMethodIdObjArgs(copyreg, &PyId__slotnames,
3543 cls, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003544 Py_DECREF(copyreg);
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01003545 if (slotnames == NULL)
3546 return NULL;
3547
3548 if (slotnames != Py_None && !PyList_Check(slotnames)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003549 PyErr_SetString(PyExc_TypeError,
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01003550 "copyreg._slotnames didn't return a list or None");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003551 Py_DECREF(slotnames);
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01003552 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003553 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003554
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003555 return slotnames;
Guido van Rossum036f9992003-02-21 22:02:54 +00003556}
3557
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01003558Py_LOCAL(PyObject *)
3559_PyObject_GetState(PyObject *obj)
Guido van Rossum036f9992003-02-21 22:02:54 +00003560{
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01003561 PyObject *state;
3562 PyObject *getstate;
Victor Stinner3c1e4812012-03-26 22:10:51 +02003563 _Py_IDENTIFIER(__getstate__);
Guido van Rossum036f9992003-02-21 22:02:54 +00003564
Victor Stinner3c1e4812012-03-26 22:10:51 +02003565 getstate = _PyObject_GetAttrId(obj, &PyId___getstate__);
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01003566 if (getstate == NULL) {
3567 PyObject *slotnames;
3568
3569 if (!PyErr_ExceptionMatches(PyExc_AttributeError)) {
3570 return NULL;
3571 }
3572 PyErr_Clear();
3573
3574 {
3575 PyObject **dict;
3576 dict = _PyObject_GetDictPtr(obj);
Larry Hastings5c661892014-01-24 06:17:25 -08003577 /* It is possible that the object's dict is not initialized
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01003578 yet. In this case, we will return None for the state.
3579 We also return None if the dict is empty to make the behavior
3580 consistent regardless whether the dict was initialized or not.
3581 This make unit testing easier. */
3582 if (dict != NULL && *dict != NULL && PyDict_Size(*dict) > 0) {
3583 state = *dict;
3584 }
3585 else {
3586 state = Py_None;
3587 }
3588 Py_INCREF(state);
3589 }
3590
3591 slotnames = _PyType_GetSlotNames(Py_TYPE(obj));
3592 if (slotnames == NULL) {
3593 Py_DECREF(state);
3594 return NULL;
3595 }
3596
3597 assert(slotnames == Py_None || PyList_Check(slotnames));
3598 if (slotnames != Py_None && Py_SIZE(slotnames) > 0) {
3599 PyObject *slots;
3600 Py_ssize_t slotnames_size, i;
3601
3602 slots = PyDict_New();
3603 if (slots == NULL) {
3604 Py_DECREF(slotnames);
3605 Py_DECREF(state);
3606 return NULL;
3607 }
3608
3609 slotnames_size = Py_SIZE(slotnames);
3610 for (i = 0; i < slotnames_size; i++) {
3611 PyObject *name, *value;
3612
3613 name = PyList_GET_ITEM(slotnames, i);
3614 value = PyObject_GetAttr(obj, name);
3615 if (value == NULL) {
3616 if (!PyErr_ExceptionMatches(PyExc_AttributeError)) {
3617 goto error;
3618 }
3619 /* It is not an error if the attribute is not present. */
3620 PyErr_Clear();
3621 }
3622 else {
3623 int err = PyDict_SetItem(slots, name, value);
3624 Py_DECREF(value);
3625 if (err) {
3626 goto error;
3627 }
3628 }
3629
3630 /* The list is stored on the class so it may mutates while we
3631 iterate over it */
3632 if (slotnames_size != Py_SIZE(slotnames)) {
3633 PyErr_Format(PyExc_RuntimeError,
3634 "__slotsname__ changed size during iteration");
3635 goto error;
3636 }
3637
3638 /* We handle errors within the loop here. */
3639 if (0) {
3640 error:
3641 Py_DECREF(slotnames);
3642 Py_DECREF(slots);
3643 Py_DECREF(state);
3644 return NULL;
3645 }
3646 }
3647
3648 /* If we found some slot attributes, pack them in a tuple along
3649 the orginal attribute dictionary. */
3650 if (PyDict_Size(slots) > 0) {
3651 PyObject *state2;
3652
3653 state2 = PyTuple_Pack(2, state, slots);
3654 Py_DECREF(state);
3655 if (state2 == NULL) {
3656 Py_DECREF(slotnames);
3657 Py_DECREF(slots);
3658 return NULL;
3659 }
3660 state = state2;
3661 }
3662 Py_DECREF(slots);
3663 }
3664 Py_DECREF(slotnames);
3665 }
3666 else { /* getstate != NULL */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003667 state = PyObject_CallObject(getstate, NULL);
3668 Py_DECREF(getstate);
3669 if (state == NULL)
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01003670 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003671 }
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01003672
3673 return state;
3674}
3675
3676Py_LOCAL(int)
3677_PyObject_GetNewArguments(PyObject *obj, PyObject **args, PyObject **kwargs)
3678{
3679 PyObject *getnewargs, *getnewargs_ex;
3680 _Py_IDENTIFIER(__getnewargs_ex__);
3681 _Py_IDENTIFIER(__getnewargs__);
3682
3683 if (args == NULL || kwargs == NULL) {
3684 PyErr_BadInternalCall();
3685 return -1;
3686 }
3687
3688 /* We first attempt to fetch the arguments for __new__ by calling
3689 __getnewargs_ex__ on the object. */
3690 getnewargs_ex = _PyObject_GetAttrId(obj, &PyId___getnewargs_ex__);
3691 if (getnewargs_ex != NULL) {
3692 PyObject *newargs = PyObject_CallObject(getnewargs_ex, NULL);
3693 Py_DECREF(getnewargs_ex);
3694 if (newargs == NULL) {
3695 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003696 }
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01003697 if (!PyTuple_Check(newargs)) {
3698 PyErr_Format(PyExc_TypeError,
3699 "__getnewargs_ex__ should return a tuple, "
3700 "not '%.200s'", Py_TYPE(newargs)->tp_name);
3701 Py_DECREF(newargs);
3702 return -1;
3703 }
3704 if (Py_SIZE(newargs) != 2) {
3705 PyErr_Format(PyExc_ValueError,
3706 "__getnewargs_ex__ should return a tuple of "
3707 "length 2, not %zd", Py_SIZE(newargs));
3708 Py_DECREF(newargs);
3709 return -1;
3710 }
3711 *args = PyTuple_GET_ITEM(newargs, 0);
3712 Py_INCREF(*args);
3713 *kwargs = PyTuple_GET_ITEM(newargs, 1);
3714 Py_INCREF(*kwargs);
3715 Py_DECREF(newargs);
3716
3717 /* XXX We should perhaps allow None to be passed here. */
3718 if (!PyTuple_Check(*args)) {
3719 PyErr_Format(PyExc_TypeError,
3720 "first item of the tuple returned by "
3721 "__getnewargs_ex__ must be a tuple, not '%.200s'",
3722 Py_TYPE(*args)->tp_name);
3723 Py_CLEAR(*args);
3724 Py_CLEAR(*kwargs);
3725 return -1;
3726 }
3727 if (!PyDict_Check(*kwargs)) {
3728 PyErr_Format(PyExc_TypeError,
3729 "second item of the tuple returned by "
3730 "__getnewargs_ex__ must be a dict, not '%.200s'",
3731 Py_TYPE(*kwargs)->tp_name);
3732 Py_CLEAR(*args);
3733 Py_CLEAR(*kwargs);
3734 return -1;
3735 }
3736 return 0;
3737 } else {
3738 if (!PyErr_ExceptionMatches(PyExc_AttributeError)) {
3739 return -1;
3740 }
3741 PyErr_Clear();
3742 }
3743
3744 /* The object does not have __getnewargs_ex__ so we fallback on using
3745 __getnewargs__ instead. */
3746 getnewargs = _PyObject_GetAttrId(obj, &PyId___getnewargs__);
3747 if (getnewargs != NULL) {
3748 *args = PyObject_CallObject(getnewargs, NULL);
3749 Py_DECREF(getnewargs);
3750 if (*args == NULL) {
3751 return -1;
3752 }
3753 if (!PyTuple_Check(*args)) {
3754 PyErr_Format(PyExc_TypeError,
3755 "__getnewargs__ should return a tuple, "
3756 "not '%.200s'", Py_TYPE(*args)->tp_name);
3757 Py_CLEAR(*args);
3758 return -1;
3759 }
3760 *kwargs = NULL;
3761 return 0;
3762 } else {
3763 if (!PyErr_ExceptionMatches(PyExc_AttributeError)) {
3764 return -1;
3765 }
3766 PyErr_Clear();
3767 }
3768
3769 /* The object does not have __getnewargs_ex__ and __getnewargs__. This may
3770 means __new__ does not takes any arguments on this object, or that the
3771 object does not implement the reduce protocol for pickling or
3772 copying. */
3773 *args = NULL;
3774 *kwargs = NULL;
3775 return 0;
3776}
3777
3778Py_LOCAL(int)
3779_PyObject_GetItemsIter(PyObject *obj, PyObject **listitems,
3780 PyObject **dictitems)
3781{
3782 if (listitems == NULL || dictitems == NULL) {
3783 PyErr_BadInternalCall();
3784 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003785 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003786
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003787 if (!PyList_Check(obj)) {
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01003788 *listitems = Py_None;
3789 Py_INCREF(*listitems);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003790 }
3791 else {
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01003792 *listitems = PyObject_GetIter(obj);
Christian Heimes2489bd82013-11-23 21:19:43 +01003793 if (*listitems == NULL)
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01003794 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003795 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003796
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003797 if (!PyDict_Check(obj)) {
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01003798 *dictitems = Py_None;
3799 Py_INCREF(*dictitems);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003800 }
3801 else {
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01003802 PyObject *items;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02003803 _Py_IDENTIFIER(items);
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01003804
3805 items = _PyObject_CallMethodIdObjArgs(obj, &PyId_items, NULL);
3806 if (items == NULL) {
3807 Py_CLEAR(*listitems);
3808 return -1;
3809 }
3810 *dictitems = PyObject_GetIter(items);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003811 Py_DECREF(items);
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01003812 if (*dictitems == NULL) {
3813 Py_CLEAR(*listitems);
3814 return -1;
3815 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003816 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003817
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01003818 assert(*listitems != NULL && *dictitems != NULL);
3819
3820 return 0;
3821}
3822
3823static PyObject *
3824reduce_4(PyObject *obj)
3825{
3826 PyObject *args = NULL, *kwargs = NULL;
3827 PyObject *copyreg;
3828 PyObject *newobj, *newargs, *state, *listitems, *dictitems;
3829 PyObject *result;
3830 _Py_IDENTIFIER(__newobj_ex__);
3831
3832 if (_PyObject_GetNewArguments(obj, &args, &kwargs) < 0) {
3833 return NULL;
3834 }
3835 if (args == NULL) {
3836 args = PyTuple_New(0);
3837 if (args == NULL)
3838 return NULL;
3839 }
3840 if (kwargs == NULL) {
3841 kwargs = PyDict_New();
3842 if (kwargs == NULL)
3843 return NULL;
3844 }
3845
3846 copyreg = import_copyreg();
3847 if (copyreg == NULL) {
3848 Py_DECREF(args);
3849 Py_DECREF(kwargs);
3850 return NULL;
3851 }
3852 newobj = _PyObject_GetAttrId(copyreg, &PyId___newobj_ex__);
3853 Py_DECREF(copyreg);
3854 if (newobj == NULL) {
3855 Py_DECREF(args);
3856 Py_DECREF(kwargs);
3857 return NULL;
3858 }
3859 newargs = PyTuple_Pack(3, Py_TYPE(obj), args, kwargs);
3860 Py_DECREF(args);
3861 Py_DECREF(kwargs);
3862 if (newargs == NULL) {
3863 Py_DECREF(newobj);
3864 return NULL;
3865 }
3866 state = _PyObject_GetState(obj);
3867 if (state == NULL) {
3868 Py_DECREF(newobj);
3869 Py_DECREF(newargs);
3870 return NULL;
3871 }
3872 if (_PyObject_GetItemsIter(obj, &listitems, &dictitems) < 0) {
3873 Py_DECREF(newobj);
3874 Py_DECREF(newargs);
3875 Py_DECREF(state);
3876 return NULL;
3877 }
3878
3879 result = PyTuple_Pack(5, newobj, newargs, state, listitems, dictitems);
3880 Py_DECREF(newobj);
3881 Py_DECREF(newargs);
3882 Py_DECREF(state);
3883 Py_DECREF(listitems);
3884 Py_DECREF(dictitems);
Larry Hastings5c661892014-01-24 06:17:25 -08003885 return result;
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01003886}
3887
3888static PyObject *
3889reduce_2(PyObject *obj)
3890{
3891 PyObject *cls;
3892 PyObject *args = NULL, *args2 = NULL, *kwargs = NULL;
3893 PyObject *state = NULL, *listitems = NULL, *dictitems = NULL;
3894 PyObject *copyreg = NULL, *newobj = NULL, *res = NULL;
3895 Py_ssize_t i, n;
3896 _Py_IDENTIFIER(__newobj__);
3897
3898 if (_PyObject_GetNewArguments(obj, &args, &kwargs) < 0) {
3899 return NULL;
3900 }
3901 if (args == NULL) {
3902 assert(kwargs == NULL);
3903 args = PyTuple_New(0);
3904 if (args == NULL) {
3905 return NULL;
3906 }
3907 }
3908 else if (kwargs != NULL) {
3909 if (PyDict_Size(kwargs) > 0) {
Larry Hastings5c661892014-01-24 06:17:25 -08003910 PyErr_SetString(PyExc_ValueError,
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01003911 "must use protocol 4 or greater to copy this "
3912 "object; since __getnewargs_ex__ returned "
3913 "keyword arguments.");
3914 Py_DECREF(args);
3915 Py_DECREF(kwargs);
3916 return NULL;
3917 }
3918 Py_CLEAR(kwargs);
3919 }
3920
3921 state = _PyObject_GetState(obj);
3922 if (state == NULL)
3923 goto end;
3924
3925 if (_PyObject_GetItemsIter(obj, &listitems, &dictitems) < 0)
3926 goto end;
3927
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003928 copyreg = import_copyreg();
3929 if (copyreg == NULL)
3930 goto end;
Victor Stinner3c1e4812012-03-26 22:10:51 +02003931 newobj = _PyObject_GetAttrId(copyreg, &PyId___newobj__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003932 if (newobj == NULL)
3933 goto end;
Guido van Rossum036f9992003-02-21 22:02:54 +00003934
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003935 n = PyTuple_GET_SIZE(args);
3936 args2 = PyTuple_New(n+1);
3937 if (args2 == NULL)
3938 goto end;
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01003939 cls = (PyObject *) Py_TYPE(obj);
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003940 Py_INCREF(cls);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003941 PyTuple_SET_ITEM(args2, 0, cls);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003942 for (i = 0; i < n; i++) {
3943 PyObject *v = PyTuple_GET_ITEM(args, i);
3944 Py_INCREF(v);
3945 PyTuple_SET_ITEM(args2, i+1, v);
3946 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003947
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003948 res = PyTuple_Pack(5, newobj, args2, state, listitems, dictitems);
Guido van Rossum036f9992003-02-21 22:02:54 +00003949
3950 end:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003951 Py_XDECREF(args);
3952 Py_XDECREF(args2);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003953 Py_XDECREF(state);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003954 Py_XDECREF(listitems);
3955 Py_XDECREF(dictitems);
3956 Py_XDECREF(copyreg);
3957 Py_XDECREF(newobj);
3958 return res;
Guido van Rossum036f9992003-02-21 22:02:54 +00003959}
3960
Guido van Rossumd8faa362007-04-27 19:54:29 +00003961/*
3962 * There were two problems when object.__reduce__ and object.__reduce_ex__
3963 * were implemented in the same function:
3964 * - trying to pickle an object with a custom __reduce__ method that
3965 * fell back to object.__reduce__ in certain circumstances led to
3966 * infinite recursion at Python level and eventual RuntimeError.
3967 * - Pickling objects that lied about their type by overwriting the
3968 * __class__ descriptor could lead to infinite recursion at C level
3969 * and eventual segfault.
3970 *
3971 * Because of backwards compatibility, the two methods still have to
3972 * behave in the same way, even if this is not required by the pickle
3973 * protocol. This common functionality was moved to the _common_reduce
3974 * function.
3975 */
3976static PyObject *
3977_common_reduce(PyObject *self, int proto)
3978{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003979 PyObject *copyreg, *res;
Guido van Rossumd8faa362007-04-27 19:54:29 +00003980
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01003981 if (proto >= 4)
3982 return reduce_4(self);
3983 else if (proto >= 2)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003984 return reduce_2(self);
Guido van Rossumd8faa362007-04-27 19:54:29 +00003985
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003986 copyreg = import_copyreg();
3987 if (!copyreg)
3988 return NULL;
Guido van Rossumd8faa362007-04-27 19:54:29 +00003989
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003990 res = PyEval_CallMethod(copyreg, "_reduce_ex", "(Oi)", self, proto);
3991 Py_DECREF(copyreg);
Guido van Rossumd8faa362007-04-27 19:54:29 +00003992
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003993 return res;
Guido van Rossumd8faa362007-04-27 19:54:29 +00003994}
3995
3996static PyObject *
3997object_reduce(PyObject *self, PyObject *args)
3998{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003999 int proto = 0;
Guido van Rossumd8faa362007-04-27 19:54:29 +00004000
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004001 if (!PyArg_ParseTuple(args, "|i:__reduce__", &proto))
4002 return NULL;
Guido van Rossumd8faa362007-04-27 19:54:29 +00004003
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004004 return _common_reduce(self, proto);
Guido van Rossumd8faa362007-04-27 19:54:29 +00004005}
4006
Guido van Rossum036f9992003-02-21 22:02:54 +00004007static PyObject *
4008object_reduce_ex(PyObject *self, PyObject *args)
4009{
Victor Stinner3c1e4812012-03-26 22:10:51 +02004010 static PyObject *objreduce;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004011 PyObject *reduce, *res;
4012 int proto = 0;
Victor Stinner3c1e4812012-03-26 22:10:51 +02004013 _Py_IDENTIFIER(__reduce__);
Guido van Rossum036f9992003-02-21 22:02:54 +00004014
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004015 if (!PyArg_ParseTuple(args, "|i:__reduce_ex__", &proto))
4016 return NULL;
Guido van Rossum036f9992003-02-21 22:02:54 +00004017
Victor Stinner3c1e4812012-03-26 22:10:51 +02004018 if (objreduce == NULL) {
4019 objreduce = _PyDict_GetItemId(PyBaseObject_Type.tp_dict,
4020 &PyId___reduce__);
4021 if (objreduce == NULL)
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01004022 return NULL;
4023 }
4024
Victor Stinner3c1e4812012-03-26 22:10:51 +02004025 reduce = _PyObject_GetAttrId(self, &PyId___reduce__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004026 if (reduce == NULL)
4027 PyErr_Clear();
4028 else {
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01004029 PyObject *cls, *clsreduce;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004030 int override;
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01004031
4032 cls = (PyObject *) Py_TYPE(self);
Victor Stinner3c1e4812012-03-26 22:10:51 +02004033 clsreduce = _PyObject_GetAttrId(cls, &PyId___reduce__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004034 if (clsreduce == NULL) {
4035 Py_DECREF(reduce);
4036 return NULL;
4037 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004038 override = (clsreduce != objreduce);
4039 Py_DECREF(clsreduce);
4040 if (override) {
4041 res = PyObject_CallObject(reduce, NULL);
4042 Py_DECREF(reduce);
4043 return res;
4044 }
4045 else
4046 Py_DECREF(reduce);
4047 }
Guido van Rossum036f9992003-02-21 22:02:54 +00004048
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004049 return _common_reduce(self, proto);
Guido van Rossum3926a632001-09-25 16:25:58 +00004050}
4051
Christian Heimes9e7f1d22008-02-28 12:27:11 +00004052static PyObject *
4053object_subclasshook(PyObject *cls, PyObject *args)
4054{
Brian Curtindfc80e32011-08-10 20:28:54 -05004055 Py_RETURN_NOTIMPLEMENTED;
Christian Heimes9e7f1d22008-02-28 12:27:11 +00004056}
4057
4058PyDoc_STRVAR(object_subclasshook_doc,
4059"Abstract classes can override this to customize issubclass().\n"
4060"\n"
4061"This is invoked early on by abc.ABCMeta.__subclasscheck__().\n"
4062"It should return True, False or NotImplemented. If it returns\n"
4063"NotImplemented, the normal algorithm is used. Otherwise, it\n"
4064"overrides the normal algorithm (and the outcome is cached).\n");
Eric Smith8c663262007-08-25 02:26:07 +00004065
4066/*
4067 from PEP 3101, this code implements:
4068
4069 class object:
4070 def __format__(self, format_spec):
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004071 return format(str(self), format_spec)
Eric Smith8c663262007-08-25 02:26:07 +00004072*/
4073static PyObject *
4074object_format(PyObject *self, PyObject *args)
4075{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004076 PyObject *format_spec;
4077 PyObject *self_as_str = NULL;
4078 PyObject *result = NULL;
Eric Smith8c663262007-08-25 02:26:07 +00004079
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004080 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
4081 return NULL;
Eric Smith8c663262007-08-25 02:26:07 +00004082
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004083 self_as_str = PyObject_Str(self);
Eric Smithe4d63172010-09-13 20:48:43 +00004084 if (self_as_str != NULL) {
4085 /* Issue 7994: If we're converting to a string, we
Eric V. Smithb9cd3532011-03-12 10:08:48 -05004086 should reject format specifications */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004087 if (PyUnicode_GET_LENGTH(format_spec) > 0) {
Andrew Svetlov2cd8ce42012-12-23 14:27:17 +02004088 PyErr_SetString(PyExc_TypeError,
Eric V. Smithb9cd3532011-03-12 10:08:48 -05004089 "non-empty format string passed to object.__format__");
Andrew Svetlov2cd8ce42012-12-23 14:27:17 +02004090 goto done;
Eric V. Smithb9cd3532011-03-12 10:08:48 -05004091 }
Eric Smith8c663262007-08-25 02:26:07 +00004092
Eric V. Smithb9cd3532011-03-12 10:08:48 -05004093 result = PyObject_Format(self_as_str, format_spec);
Eric Smithe4d63172010-09-13 20:48:43 +00004094 }
4095
4096done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004097 Py_XDECREF(self_as_str);
Eric Smith8c663262007-08-25 02:26:07 +00004098
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004099 return result;
Eric Smith8c663262007-08-25 02:26:07 +00004100}
4101
Martin v. Löwis00709aa2008-06-04 14:18:43 +00004102static PyObject *
4103object_sizeof(PyObject *self, PyObject *args)
4104{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004105 Py_ssize_t res, isize;
Martin v. Löwis00709aa2008-06-04 14:18:43 +00004106
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004107 res = 0;
4108 isize = self->ob_type->tp_itemsize;
4109 if (isize > 0)
4110 res = Py_SIZE(self->ob_type) * isize;
4111 res += self->ob_type->tp_basicsize;
Martin v. Löwis00709aa2008-06-04 14:18:43 +00004112
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004113 return PyLong_FromSsize_t(res);
Martin v. Löwis00709aa2008-06-04 14:18:43 +00004114}
4115
Benjamin Peterson82b00c12011-05-24 11:09:06 -05004116/* __dir__ for generic objects: returns __dict__, __class__,
4117 and recursively up the __class__.__bases__ chain.
4118*/
4119static PyObject *
4120object_dir(PyObject *self, PyObject *args)
4121{
4122 PyObject *result = NULL;
4123 PyObject *dict = NULL;
4124 PyObject *itsclass = NULL;
4125
4126 /* Get __dict__ (which may or may not be a real dict...) */
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02004127 dict = _PyObject_GetAttrId(self, &PyId___dict__);
Benjamin Peterson82b00c12011-05-24 11:09:06 -05004128 if (dict == NULL) {
4129 PyErr_Clear();
4130 dict = PyDict_New();
4131 }
4132 else if (!PyDict_Check(dict)) {
4133 Py_DECREF(dict);
4134 dict = PyDict_New();
4135 }
4136 else {
4137 /* Copy __dict__ to avoid mutating it. */
4138 PyObject *temp = PyDict_Copy(dict);
4139 Py_DECREF(dict);
4140 dict = temp;
4141 }
4142
4143 if (dict == NULL)
4144 goto error;
4145
4146 /* Merge in attrs reachable from its class. */
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02004147 itsclass = _PyObject_GetAttrId(self, &PyId___class__);
Benjamin Peterson82b00c12011-05-24 11:09:06 -05004148 if (itsclass == NULL)
4149 /* XXX(tomer): Perhaps fall back to obj->ob_type if no
4150 __class__ exists? */
4151 PyErr_Clear();
4152 else if (merge_class_dict(dict, itsclass) != 0)
4153 goto error;
4154
4155 result = PyDict_Keys(dict);
4156 /* fall through */
4157error:
4158 Py_XDECREF(itsclass);
4159 Py_XDECREF(dict);
4160 return result;
4161}
4162
Guido van Rossum3926a632001-09-25 16:25:58 +00004163static PyMethodDef object_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004164 {"__reduce_ex__", object_reduce_ex, METH_VARARGS,
4165 PyDoc_STR("helper for pickle")},
4166 {"__reduce__", object_reduce, METH_VARARGS,
4167 PyDoc_STR("helper for pickle")},
4168 {"__subclasshook__", object_subclasshook, METH_CLASS | METH_VARARGS,
4169 object_subclasshook_doc},
4170 {"__format__", object_format, METH_VARARGS,
4171 PyDoc_STR("default object formatter")},
4172 {"__sizeof__", object_sizeof, METH_NOARGS,
Benjamin Petersonfbe56bb2011-05-24 12:42:51 -05004173 PyDoc_STR("__sizeof__() -> int\nsize of object in memory, in bytes")},
Benjamin Peterson82b00c12011-05-24 11:09:06 -05004174 {"__dir__", object_dir, METH_NOARGS,
Benjamin Petersonc7284122011-05-24 12:46:15 -05004175 PyDoc_STR("__dir__() -> list\ndefault dir() implementation")},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004176 {0}
Guido van Rossum3926a632001-09-25 16:25:58 +00004177};
4178
Guido van Rossum036f9992003-02-21 22:02:54 +00004179
Tim Peters6d6c1a32001-08-02 04:15:00 +00004180PyTypeObject PyBaseObject_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004181 PyVarObject_HEAD_INIT(&PyType_Type, 0)
4182 "object", /* tp_name */
4183 sizeof(PyObject), /* tp_basicsize */
4184 0, /* tp_itemsize */
4185 object_dealloc, /* tp_dealloc */
4186 0, /* tp_print */
4187 0, /* tp_getattr */
4188 0, /* tp_setattr */
4189 0, /* tp_reserved */
4190 object_repr, /* tp_repr */
4191 0, /* tp_as_number */
4192 0, /* tp_as_sequence */
4193 0, /* tp_as_mapping */
4194 (hashfunc)_Py_HashPointer, /* tp_hash */
4195 0, /* tp_call */
4196 object_str, /* tp_str */
4197 PyObject_GenericGetAttr, /* tp_getattro */
4198 PyObject_GenericSetAttr, /* tp_setattro */
4199 0, /* tp_as_buffer */
Larry Hastings5c661892014-01-24 06:17:25 -08004200 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Larry Hastings581ee362014-01-28 05:00:08 -08004201 PyDoc_STR("sig=()\nThe most base type"), /* tp_doc */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004202 0, /* tp_traverse */
4203 0, /* tp_clear */
4204 object_richcompare, /* tp_richcompare */
4205 0, /* tp_weaklistoffset */
4206 0, /* tp_iter */
4207 0, /* tp_iternext */
4208 object_methods, /* tp_methods */
4209 0, /* tp_members */
4210 object_getsets, /* tp_getset */
4211 0, /* tp_base */
4212 0, /* tp_dict */
4213 0, /* tp_descr_get */
4214 0, /* tp_descr_set */
4215 0, /* tp_dictoffset */
4216 object_init, /* tp_init */
4217 PyType_GenericAlloc, /* tp_alloc */
4218 object_new, /* tp_new */
4219 PyObject_Del, /* tp_free */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004220};
4221
4222
Guido van Rossum50e9fb92006-08-17 05:42:55 +00004223/* Add the methods from tp_methods to the __dict__ in a type object */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004224
4225static int
4226add_methods(PyTypeObject *type, PyMethodDef *meth)
4227{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004228 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004229
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004230 for (; meth->ml_name != NULL; meth++) {
4231 PyObject *descr;
Benjamin Peterson89a6e9a2012-05-08 09:22:24 -04004232 int err;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004233 if (PyDict_GetItemString(dict, meth->ml_name) &&
4234 !(meth->ml_flags & METH_COEXIST))
4235 continue;
4236 if (meth->ml_flags & METH_CLASS) {
4237 if (meth->ml_flags & METH_STATIC) {
4238 PyErr_SetString(PyExc_ValueError,
4239 "method cannot be both class and static");
4240 return -1;
4241 }
4242 descr = PyDescr_NewClassMethod(type, meth);
4243 }
4244 else if (meth->ml_flags & METH_STATIC) {
Andrew Svetlov3ba3a3e2012-12-25 13:32:35 +02004245 PyObject *cfunc = PyCFunction_NewEx(meth, (PyObject*)type, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004246 if (cfunc == NULL)
4247 return -1;
4248 descr = PyStaticMethod_New(cfunc);
4249 Py_DECREF(cfunc);
4250 }
4251 else {
4252 descr = PyDescr_NewMethod(type, meth);
4253 }
4254 if (descr == NULL)
4255 return -1;
Benjamin Peterson89a6e9a2012-05-08 09:22:24 -04004256 err = PyDict_SetItemString(dict, meth->ml_name, descr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004257 Py_DECREF(descr);
Benjamin Peterson89a6e9a2012-05-08 09:22:24 -04004258 if (err < 0)
4259 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004260 }
4261 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004262}
4263
4264static int
Guido van Rossum6f799372001-09-20 20:46:19 +00004265add_members(PyTypeObject *type, PyMemberDef *memb)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004266{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004267 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004268
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004269 for (; memb->name != NULL; memb++) {
4270 PyObject *descr;
4271 if (PyDict_GetItemString(dict, memb->name))
4272 continue;
4273 descr = PyDescr_NewMember(type, memb);
4274 if (descr == NULL)
4275 return -1;
4276 if (PyDict_SetItemString(dict, memb->name, descr) < 0)
4277 return -1;
4278 Py_DECREF(descr);
4279 }
4280 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004281}
4282
4283static int
Guido van Rossum32d34c82001-09-20 21:45:26 +00004284add_getset(PyTypeObject *type, PyGetSetDef *gsp)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004285{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004286 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004287
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004288 for (; gsp->name != NULL; gsp++) {
4289 PyObject *descr;
4290 if (PyDict_GetItemString(dict, gsp->name))
4291 continue;
4292 descr = PyDescr_NewGetSet(type, gsp);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004293
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004294 if (descr == NULL)
4295 return -1;
4296 if (PyDict_SetItemString(dict, gsp->name, descr) < 0)
4297 return -1;
4298 Py_DECREF(descr);
4299 }
4300 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004301}
4302
Guido van Rossum13d52f02001-08-10 21:24:08 +00004303static void
4304inherit_special(PyTypeObject *type, PyTypeObject *base)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004305{
Tim Peters6d6c1a32001-08-02 04:15:00 +00004306
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004307 /* Copying basicsize is connected to the GC flags */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004308 if (!(type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
4309 (base->tp_flags & Py_TPFLAGS_HAVE_GC) &&
4310 (!type->tp_traverse && !type->tp_clear)) {
4311 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
4312 if (type->tp_traverse == NULL)
4313 type->tp_traverse = base->tp_traverse;
4314 if (type->tp_clear == NULL)
4315 type->tp_clear = base->tp_clear;
4316 }
4317 {
4318 /* The condition below could use some explanation.
4319 It appears that tp_new is not inherited for static types
4320 whose base class is 'object'; this seems to be a precaution
4321 so that old extension types don't suddenly become
4322 callable (object.__new__ wouldn't insure the invariants
4323 that the extension type's own factory function ensures).
4324 Heap types, of course, are under our control, so they do
4325 inherit tp_new; static extension types that specify some
Florent Xiclunaaa6c1d22011-12-12 18:54:29 +01004326 other built-in type as the default also
4327 inherit object.__new__. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004328 if (base != &PyBaseObject_Type ||
4329 (type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
4330 if (type->tp_new == NULL)
4331 type->tp_new = base->tp_new;
4332 }
4333 }
Benjamin Petersona7465e22010-07-05 15:01:22 +00004334 if (type->tp_basicsize == 0)
4335 type->tp_basicsize = base->tp_basicsize;
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00004336
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004337 /* Copy other non-function slots */
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00004338
4339#undef COPYVAL
4340#define COPYVAL(SLOT) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004341 if (type->SLOT == 0) type->SLOT = base->SLOT
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00004342
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004343 COPYVAL(tp_itemsize);
4344 COPYVAL(tp_weaklistoffset);
4345 COPYVAL(tp_dictoffset);
Thomas Wouters27d517b2007-02-25 20:39:11 +00004346
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004347 /* Setup fast subclass flags */
4348 if (PyType_IsSubtype(base, (PyTypeObject*)PyExc_BaseException))
4349 type->tp_flags |= Py_TPFLAGS_BASE_EXC_SUBCLASS;
4350 else if (PyType_IsSubtype(base, &PyType_Type))
4351 type->tp_flags |= Py_TPFLAGS_TYPE_SUBCLASS;
4352 else if (PyType_IsSubtype(base, &PyLong_Type))
4353 type->tp_flags |= Py_TPFLAGS_LONG_SUBCLASS;
4354 else if (PyType_IsSubtype(base, &PyBytes_Type))
4355 type->tp_flags |= Py_TPFLAGS_BYTES_SUBCLASS;
4356 else if (PyType_IsSubtype(base, &PyUnicode_Type))
4357 type->tp_flags |= Py_TPFLAGS_UNICODE_SUBCLASS;
4358 else if (PyType_IsSubtype(base, &PyTuple_Type))
4359 type->tp_flags |= Py_TPFLAGS_TUPLE_SUBCLASS;
4360 else if (PyType_IsSubtype(base, &PyList_Type))
4361 type->tp_flags |= Py_TPFLAGS_LIST_SUBCLASS;
4362 else if (PyType_IsSubtype(base, &PyDict_Type))
4363 type->tp_flags |= Py_TPFLAGS_DICT_SUBCLASS;
Guido van Rossum13d52f02001-08-10 21:24:08 +00004364}
4365
Guido van Rossum38938152006-08-21 23:36:26 +00004366static int
Guido van Rossumf5243f02008-01-01 04:06:48 +00004367overrides_hash(PyTypeObject *type)
Guido van Rossum38938152006-08-21 23:36:26 +00004368{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004369 PyObject *dict = type->tp_dict;
Victor Stinner3c1e4812012-03-26 22:10:51 +02004370 _Py_IDENTIFIER(__eq__);
Guido van Rossum38938152006-08-21 23:36:26 +00004371
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004372 assert(dict != NULL);
Victor Stinner3c1e4812012-03-26 22:10:51 +02004373 if (_PyDict_GetItemId(dict, &PyId___eq__) != NULL)
4374 return 1;
4375 if (_PyDict_GetItemId(dict, &PyId___hash__) != NULL)
4376 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004377 return 0;
Guido van Rossum38938152006-08-21 23:36:26 +00004378}
4379
Guido van Rossum13d52f02001-08-10 21:24:08 +00004380static void
4381inherit_slots(PyTypeObject *type, PyTypeObject *base)
4382{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004383 PyTypeObject *basebase;
Guido van Rossum13d52f02001-08-10 21:24:08 +00004384
4385#undef SLOTDEFINED
Tim Peters6d6c1a32001-08-02 04:15:00 +00004386#undef COPYSLOT
4387#undef COPYNUM
4388#undef COPYSEQ
4389#undef COPYMAP
Guido van Rossum5af588b2001-10-12 14:13:21 +00004390#undef COPYBUF
Guido van Rossum13d52f02001-08-10 21:24:08 +00004391
4392#define SLOTDEFINED(SLOT) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004393 (base->SLOT != 0 && \
4394 (basebase == NULL || base->SLOT != basebase->SLOT))
Guido van Rossum13d52f02001-08-10 21:24:08 +00004395
Tim Peters6d6c1a32001-08-02 04:15:00 +00004396#define COPYSLOT(SLOT) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004397 if (!type->SLOT && SLOTDEFINED(SLOT)) type->SLOT = base->SLOT
Tim Peters6d6c1a32001-08-02 04:15:00 +00004398
4399#define COPYNUM(SLOT) COPYSLOT(tp_as_number->SLOT)
4400#define COPYSEQ(SLOT) COPYSLOT(tp_as_sequence->SLOT)
4401#define COPYMAP(SLOT) COPYSLOT(tp_as_mapping->SLOT)
Tim Petersfc57ccb2001-10-12 02:38:24 +00004402#define COPYBUF(SLOT) COPYSLOT(tp_as_buffer->SLOT)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004403
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004404 /* This won't inherit indirect slots (from tp_as_number etc.)
4405 if type doesn't provide the space. */
Guido van Rossum13d52f02001-08-10 21:24:08 +00004406
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004407 if (type->tp_as_number != NULL && base->tp_as_number != NULL) {
4408 basebase = base->tp_base;
4409 if (basebase->tp_as_number == NULL)
4410 basebase = NULL;
4411 COPYNUM(nb_add);
4412 COPYNUM(nb_subtract);
4413 COPYNUM(nb_multiply);
4414 COPYNUM(nb_remainder);
4415 COPYNUM(nb_divmod);
4416 COPYNUM(nb_power);
4417 COPYNUM(nb_negative);
4418 COPYNUM(nb_positive);
4419 COPYNUM(nb_absolute);
4420 COPYNUM(nb_bool);
4421 COPYNUM(nb_invert);
4422 COPYNUM(nb_lshift);
4423 COPYNUM(nb_rshift);
4424 COPYNUM(nb_and);
4425 COPYNUM(nb_xor);
4426 COPYNUM(nb_or);
4427 COPYNUM(nb_int);
4428 COPYNUM(nb_float);
4429 COPYNUM(nb_inplace_add);
4430 COPYNUM(nb_inplace_subtract);
4431 COPYNUM(nb_inplace_multiply);
4432 COPYNUM(nb_inplace_remainder);
4433 COPYNUM(nb_inplace_power);
4434 COPYNUM(nb_inplace_lshift);
4435 COPYNUM(nb_inplace_rshift);
4436 COPYNUM(nb_inplace_and);
4437 COPYNUM(nb_inplace_xor);
4438 COPYNUM(nb_inplace_or);
4439 COPYNUM(nb_true_divide);
4440 COPYNUM(nb_floor_divide);
4441 COPYNUM(nb_inplace_true_divide);
4442 COPYNUM(nb_inplace_floor_divide);
4443 COPYNUM(nb_index);
4444 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004445
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004446 if (type->tp_as_sequence != NULL && base->tp_as_sequence != NULL) {
4447 basebase = base->tp_base;
4448 if (basebase->tp_as_sequence == NULL)
4449 basebase = NULL;
4450 COPYSEQ(sq_length);
4451 COPYSEQ(sq_concat);
4452 COPYSEQ(sq_repeat);
4453 COPYSEQ(sq_item);
4454 COPYSEQ(sq_ass_item);
4455 COPYSEQ(sq_contains);
4456 COPYSEQ(sq_inplace_concat);
4457 COPYSEQ(sq_inplace_repeat);
4458 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004459
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004460 if (type->tp_as_mapping != NULL && base->tp_as_mapping != NULL) {
4461 basebase = base->tp_base;
4462 if (basebase->tp_as_mapping == NULL)
4463 basebase = NULL;
4464 COPYMAP(mp_length);
4465 COPYMAP(mp_subscript);
4466 COPYMAP(mp_ass_subscript);
4467 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004468
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004469 if (type->tp_as_buffer != NULL && base->tp_as_buffer != NULL) {
4470 basebase = base->tp_base;
4471 if (basebase->tp_as_buffer == NULL)
4472 basebase = NULL;
4473 COPYBUF(bf_getbuffer);
4474 COPYBUF(bf_releasebuffer);
4475 }
Tim Petersfc57ccb2001-10-12 02:38:24 +00004476
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004477 basebase = base->tp_base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004478
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004479 COPYSLOT(tp_dealloc);
4480 if (type->tp_getattr == NULL && type->tp_getattro == NULL) {
4481 type->tp_getattr = base->tp_getattr;
4482 type->tp_getattro = base->tp_getattro;
4483 }
4484 if (type->tp_setattr == NULL && type->tp_setattro == NULL) {
4485 type->tp_setattr = base->tp_setattr;
4486 type->tp_setattro = base->tp_setattro;
4487 }
4488 /* tp_reserved is ignored */
4489 COPYSLOT(tp_repr);
4490 /* tp_hash see tp_richcompare */
4491 COPYSLOT(tp_call);
4492 COPYSLOT(tp_str);
4493 {
4494 /* Copy comparison-related slots only when
4495 not overriding them anywhere */
4496 if (type->tp_richcompare == NULL &&
4497 type->tp_hash == NULL &&
4498 !overrides_hash(type))
4499 {
4500 type->tp_richcompare = base->tp_richcompare;
4501 type->tp_hash = base->tp_hash;
4502 }
4503 }
4504 {
4505 COPYSLOT(tp_iter);
4506 COPYSLOT(tp_iternext);
4507 }
4508 {
4509 COPYSLOT(tp_descr_get);
4510 COPYSLOT(tp_descr_set);
4511 COPYSLOT(tp_dictoffset);
4512 COPYSLOT(tp_init);
4513 COPYSLOT(tp_alloc);
4514 COPYSLOT(tp_is_gc);
Antoine Pitrou796564c2013-07-30 19:59:21 +02004515 if ((type->tp_flags & Py_TPFLAGS_HAVE_FINALIZE) &&
4516 (base->tp_flags & Py_TPFLAGS_HAVE_FINALIZE)) {
4517 COPYSLOT(tp_finalize);
4518 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004519 if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) ==
4520 (base->tp_flags & Py_TPFLAGS_HAVE_GC)) {
4521 /* They agree about gc. */
4522 COPYSLOT(tp_free);
4523 }
4524 else if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
4525 type->tp_free == NULL &&
4526 base->tp_free == PyObject_Free) {
4527 /* A bit of magic to plug in the correct default
4528 * tp_free function when a derived class adds gc,
4529 * didn't define tp_free, and the base uses the
4530 * default non-gc tp_free.
4531 */
4532 type->tp_free = PyObject_GC_Del;
4533 }
4534 /* else they didn't agree about gc, and there isn't something
4535 * obvious to be done -- the type is on its own.
4536 */
4537 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004538}
4539
Jeremy Hylton938ace62002-07-17 16:30:39 +00004540static int add_operators(PyTypeObject *);
Guido van Rossum13d52f02001-08-10 21:24:08 +00004541
Tim Peters6d6c1a32001-08-02 04:15:00 +00004542int
Guido van Rossum528b7eb2001-08-07 17:24:28 +00004543PyType_Ready(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004544{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004545 PyObject *dict, *bases;
4546 PyTypeObject *base;
4547 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004548
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004549 if (type->tp_flags & Py_TPFLAGS_READY) {
4550 assert(type->tp_dict != NULL);
4551 return 0;
4552 }
4553 assert((type->tp_flags & Py_TPFLAGS_READYING) == 0);
Guido van Rossumd614f972001-08-10 17:39:49 +00004554
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004555 type->tp_flags |= Py_TPFLAGS_READYING;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004556
Tim Peters36eb4df2003-03-23 03:33:13 +00004557#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004558 /* PyType_Ready is the closest thing we have to a choke point
4559 * for type objects, so is the best place I can think of to try
4560 * to get type objects into the doubly-linked list of all objects.
4561 * Still, not all type objects go thru PyType_Ready.
4562 */
4563 _Py_AddToAllObjects((PyObject *)type, 0);
Tim Peters36eb4df2003-03-23 03:33:13 +00004564#endif
4565
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004566 /* Initialize tp_base (defaults to BaseObject unless that's us) */
4567 base = type->tp_base;
4568 if (base == NULL && type != &PyBaseObject_Type) {
4569 base = type->tp_base = &PyBaseObject_Type;
4570 Py_INCREF(base);
4571 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004572
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004573 /* Now the only way base can still be NULL is if type is
4574 * &PyBaseObject_Type.
4575 */
Guido van Rossum692cdbc2006-03-10 02:04:28 +00004576
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004577 /* Initialize the base class */
4578 if (base != NULL && base->tp_dict == NULL) {
4579 if (PyType_Ready(base) < 0)
4580 goto error;
4581 }
Guido van Rossum323a9cf2002-08-14 17:26:30 +00004582
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004583 /* Initialize ob_type if NULL. This means extensions that want to be
4584 compilable separately on Windows can call PyType_Ready() instead of
4585 initializing the ob_type field of their type objects. */
4586 /* The test for base != NULL is really unnecessary, since base is only
4587 NULL when type is &PyBaseObject_Type, and we know its ob_type is
4588 not NULL (it's initialized to &PyType_Type). But coverity doesn't
4589 know that. */
4590 if (Py_TYPE(type) == NULL && base != NULL)
4591 Py_TYPE(type) = Py_TYPE(base);
Guido van Rossum0986d822002-04-08 01:38:42 +00004592
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004593 /* Initialize tp_bases */
4594 bases = type->tp_bases;
4595 if (bases == NULL) {
4596 if (base == NULL)
4597 bases = PyTuple_New(0);
4598 else
4599 bases = PyTuple_Pack(1, base);
4600 if (bases == NULL)
4601 goto error;
4602 type->tp_bases = bases;
4603 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004604
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004605 /* Initialize tp_dict */
4606 dict = type->tp_dict;
4607 if (dict == NULL) {
4608 dict = PyDict_New();
4609 if (dict == NULL)
4610 goto error;
4611 type->tp_dict = dict;
4612 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004613
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004614 /* Add type-specific descriptors to tp_dict */
4615 if (add_operators(type) < 0)
4616 goto error;
4617 if (type->tp_methods != NULL) {
4618 if (add_methods(type, type->tp_methods) < 0)
4619 goto error;
4620 }
4621 if (type->tp_members != NULL) {
4622 if (add_members(type, type->tp_members) < 0)
4623 goto error;
4624 }
4625 if (type->tp_getset != NULL) {
4626 if (add_getset(type, type->tp_getset) < 0)
4627 goto error;
4628 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004629
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004630 /* Calculate method resolution order */
4631 if (mro_internal(type) < 0) {
4632 goto error;
4633 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004634
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004635 /* Inherit special flags from dominant base */
4636 if (type->tp_base != NULL)
4637 inherit_special(type, type->tp_base);
Guido van Rossum13d52f02001-08-10 21:24:08 +00004638
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004639 /* Initialize tp_dict properly */
4640 bases = type->tp_mro;
4641 assert(bases != NULL);
4642 assert(PyTuple_Check(bases));
4643 n = PyTuple_GET_SIZE(bases);
4644 for (i = 1; i < n; i++) {
4645 PyObject *b = PyTuple_GET_ITEM(bases, i);
4646 if (PyType_Check(b))
4647 inherit_slots(type, (PyTypeObject *)b);
4648 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004649
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004650 /* Sanity check for tp_free. */
4651 if (PyType_IS_GC(type) && (type->tp_flags & Py_TPFLAGS_BASETYPE) &&
4652 (type->tp_free == NULL || type->tp_free == PyObject_Del)) {
4653 /* This base class needs to call tp_free, but doesn't have
4654 * one, or its tp_free is for non-gc'ed objects.
4655 */
4656 PyErr_Format(PyExc_TypeError, "type '%.100s' participates in "
4657 "gc and is a base type but has inappropriate "
4658 "tp_free slot",
4659 type->tp_name);
4660 goto error;
4661 }
Tim Peters3cfe7542003-05-21 21:29:48 +00004662
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004663 /* if the type dictionary doesn't contain a __doc__, set it from
4664 the tp_doc slot.
4665 */
Victor Stinner3c1e4812012-03-26 22:10:51 +02004666 if (_PyDict_GetItemId(type->tp_dict, &PyId___doc__) == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004667 if (type->tp_doc != NULL) {
Larry Hastings581ee362014-01-28 05:00:08 -08004668 const char *old_doc = _PyType_DocWithoutSignature(type->tp_doc);
Larry Hastings5c661892014-01-24 06:17:25 -08004669 PyObject *doc = PyUnicode_FromString(old_doc);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004670 if (doc == NULL)
4671 goto error;
Victor Stinner5967bf42013-07-17 22:01:37 +02004672 if (_PyDict_SetItemId(type->tp_dict, &PyId___doc__, doc) < 0) {
4673 Py_DECREF(doc);
4674 goto error;
4675 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004676 Py_DECREF(doc);
4677 } else {
Victor Stinner5967bf42013-07-17 22:01:37 +02004678 if (_PyDict_SetItemId(type->tp_dict,
4679 &PyId___doc__, Py_None) < 0)
4680 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004681 }
4682 }
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00004683
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004684 /* Hack for tp_hash and __hash__.
4685 If after all that, tp_hash is still NULL, and __hash__ is not in
4686 tp_dict, set tp_hash to PyObject_HashNotImplemented and
4687 tp_dict['__hash__'] equal to None.
4688 This signals that __hash__ is not inherited.
4689 */
4690 if (type->tp_hash == NULL) {
Victor Stinner3c1e4812012-03-26 22:10:51 +02004691 if (_PyDict_GetItemId(type->tp_dict, &PyId___hash__) == NULL) {
4692 if (_PyDict_SetItemId(type->tp_dict, &PyId___hash__, Py_None) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004693 goto error;
4694 type->tp_hash = PyObject_HashNotImplemented;
4695 }
4696 }
Guido van Rossum38938152006-08-21 23:36:26 +00004697
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004698 /* Some more special stuff */
4699 base = type->tp_base;
4700 if (base != NULL) {
4701 if (type->tp_as_number == NULL)
4702 type->tp_as_number = base->tp_as_number;
4703 if (type->tp_as_sequence == NULL)
4704 type->tp_as_sequence = base->tp_as_sequence;
4705 if (type->tp_as_mapping == NULL)
4706 type->tp_as_mapping = base->tp_as_mapping;
4707 if (type->tp_as_buffer == NULL)
4708 type->tp_as_buffer = base->tp_as_buffer;
4709 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004710
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004711 /* Link into each base class's list of subclasses */
4712 bases = type->tp_bases;
4713 n = PyTuple_GET_SIZE(bases);
4714 for (i = 0; i < n; i++) {
4715 PyObject *b = PyTuple_GET_ITEM(bases, i);
4716 if (PyType_Check(b) &&
4717 add_subclass((PyTypeObject *)b, type) < 0)
4718 goto error;
4719 }
Guido van Rossum1c450732001-10-08 15:18:27 +00004720
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004721 /* Warn for a type that implements tp_compare (now known as
4722 tp_reserved) but not tp_richcompare. */
4723 if (type->tp_reserved && !type->tp_richcompare) {
Andrew Svetlov2cd8ce42012-12-23 14:27:17 +02004724 PyErr_Format(PyExc_TypeError,
Victor Stinner4a2b7a12010-08-13 14:03:48 +00004725 "Type %.100s defines tp_reserved (formerly tp_compare) "
4726 "but not tp_richcompare. Comparisons may not behave as intended.",
4727 type->tp_name);
Andrew Svetlov2cd8ce42012-12-23 14:27:17 +02004728 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004729 }
Mark Dickinson2a7d45b2009-02-08 11:02:10 +00004730
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004731 /* All done -- set the ready flag */
4732 assert(type->tp_dict != NULL);
4733 type->tp_flags =
4734 (type->tp_flags & ~Py_TPFLAGS_READYING) | Py_TPFLAGS_READY;
4735 return 0;
Guido van Rossumd614f972001-08-10 17:39:49 +00004736
4737 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004738 type->tp_flags &= ~Py_TPFLAGS_READYING;
4739 return -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004740}
4741
Guido van Rossum1c450732001-10-08 15:18:27 +00004742static int
4743add_subclass(PyTypeObject *base, PyTypeObject *type)
4744{
Antoine Pitrou84745ab2013-10-29 21:31:25 +01004745 int result = -1;
4746 PyObject *dict, *key, *newobj;
Guido van Rossum1c450732001-10-08 15:18:27 +00004747
Antoine Pitrou84745ab2013-10-29 21:31:25 +01004748 dict = base->tp_subclasses;
4749 if (dict == NULL) {
4750 base->tp_subclasses = dict = PyDict_New();
4751 if (dict == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004752 return -1;
4753 }
Antoine Pitrou84745ab2013-10-29 21:31:25 +01004754 assert(PyDict_CheckExact(dict));
4755 key = PyLong_FromVoidPtr((void *) type);
4756 if (key == NULL)
Victor Stinner9812af82013-07-08 22:25:48 +02004757 return -1;
Antoine Pitrou84745ab2013-10-29 21:31:25 +01004758 newobj = PyWeakref_NewRef((PyObject *)type, NULL);
4759 if (newobj != NULL) {
4760 result = PyDict_SetItem(dict, key, newobj);
4761 Py_DECREF(newobj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004762 }
Antoine Pitrou84745ab2013-10-29 21:31:25 +01004763 Py_DECREF(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004764 return result;
Guido van Rossum1c450732001-10-08 15:18:27 +00004765}
4766
Michael W. Hudson98bbc492002-11-26 14:47:27 +00004767static void
4768remove_subclass(PyTypeObject *base, PyTypeObject *type)
4769{
Antoine Pitrou84745ab2013-10-29 21:31:25 +01004770 PyObject *dict, *key;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00004771
Antoine Pitrou84745ab2013-10-29 21:31:25 +01004772 dict = base->tp_subclasses;
4773 if (dict == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004774 return;
4775 }
Antoine Pitrou84745ab2013-10-29 21:31:25 +01004776 assert(PyDict_CheckExact(dict));
4777 key = PyLong_FromVoidPtr((void *) type);
4778 if (key == NULL || PyDict_DelItem(dict, key)) {
4779 /* This can happen if the type initialization errored out before
4780 the base subclasses were updated (e.g. a non-str __qualname__
4781 was passed in the type dict). */
4782 PyErr_Clear();
4783 }
4784 Py_XDECREF(key);
4785}
4786
4787static void
4788remove_all_subclasses(PyTypeObject *type, PyObject *bases)
4789{
4790 if (bases) {
4791 Py_ssize_t i;
4792 for (i = 0; i < PyTuple_GET_SIZE(bases); i++) {
4793 PyObject *base = PyTuple_GET_ITEM(bases, i);
4794 if (PyType_Check(base))
4795 remove_subclass((PyTypeObject*) base, type);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004796 }
4797 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +00004798}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004799
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004800static int
4801check_num_args(PyObject *ob, int n)
4802{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004803 if (!PyTuple_CheckExact(ob)) {
4804 PyErr_SetString(PyExc_SystemError,
4805 "PyArg_UnpackTuple() argument list is not a tuple");
4806 return 0;
4807 }
4808 if (n == PyTuple_GET_SIZE(ob))
4809 return 1;
4810 PyErr_Format(
4811 PyExc_TypeError,
4812 "expected %d arguments, got %zd", n, PyTuple_GET_SIZE(ob));
4813 return 0;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004814}
4815
Tim Peters6d6c1a32001-08-02 04:15:00 +00004816/* Generic wrappers for overloadable 'operators' such as __getitem__ */
4817
4818/* There's a wrapper *function* for each distinct function typedef used
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004819 for type object slots (e.g. binaryfunc, ternaryfunc, etc.). There's a
Tim Peters6d6c1a32001-08-02 04:15:00 +00004820 wrapper *table* for each distinct operation (e.g. __len__, __add__).
4821 Most tables have only one entry; the tables for binary operators have two
4822 entries, one regular and one with reversed arguments. */
4823
4824static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00004825wrap_lenfunc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004826{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004827 lenfunc func = (lenfunc)wrapped;
4828 Py_ssize_t res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004829
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004830 if (!check_num_args(args, 0))
4831 return NULL;
4832 res = (*func)(self);
4833 if (res == -1 && PyErr_Occurred())
4834 return NULL;
4835 return PyLong_FromLong((long)res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004836}
4837
Tim Peters6d6c1a32001-08-02 04:15:00 +00004838static PyObject *
Raymond Hettingerf34f2642003-10-11 17:29:04 +00004839wrap_inquirypred(PyObject *self, PyObject *args, void *wrapped)
4840{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004841 inquiry func = (inquiry)wrapped;
4842 int res;
Raymond Hettingerf34f2642003-10-11 17:29:04 +00004843
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004844 if (!check_num_args(args, 0))
4845 return NULL;
4846 res = (*func)(self);
4847 if (res == -1 && PyErr_Occurred())
4848 return NULL;
4849 return PyBool_FromLong((long)res);
Raymond Hettingerf34f2642003-10-11 17:29:04 +00004850}
4851
4852static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00004853wrap_binaryfunc(PyObject *self, PyObject *args, void *wrapped)
4854{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004855 binaryfunc func = (binaryfunc)wrapped;
4856 PyObject *other;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004857
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004858 if (!check_num_args(args, 1))
4859 return NULL;
4860 other = PyTuple_GET_ITEM(args, 0);
4861 return (*func)(self, other);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004862}
4863
4864static PyObject *
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00004865wrap_binaryfunc_l(PyObject *self, PyObject *args, void *wrapped)
4866{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004867 binaryfunc func = (binaryfunc)wrapped;
4868 PyObject *other;
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00004869
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004870 if (!check_num_args(args, 1))
4871 return NULL;
4872 other = PyTuple_GET_ITEM(args, 0);
4873 return (*func)(self, other);
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00004874}
4875
4876static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00004877wrap_binaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
4878{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004879 binaryfunc func = (binaryfunc)wrapped;
4880 PyObject *other;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004881
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004882 if (!check_num_args(args, 1))
4883 return NULL;
4884 other = PyTuple_GET_ITEM(args, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004885 return (*func)(other, self);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004886}
4887
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004888static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00004889wrap_ternaryfunc(PyObject *self, PyObject *args, void *wrapped)
4890{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004891 ternaryfunc func = (ternaryfunc)wrapped;
4892 PyObject *other;
4893 PyObject *third = Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004894
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004895 /* Note: This wrapper only works for __pow__() */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004896
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004897 if (!PyArg_UnpackTuple(args, "", 1, 2, &other, &third))
4898 return NULL;
4899 return (*func)(self, other, third);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004900}
4901
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00004902static PyObject *
4903wrap_ternaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
4904{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004905 ternaryfunc func = (ternaryfunc)wrapped;
4906 PyObject *other;
4907 PyObject *third = Py_None;
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00004908
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004909 /* Note: This wrapper only works for __pow__() */
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00004910
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004911 if (!PyArg_UnpackTuple(args, "", 1, 2, &other, &third))
4912 return NULL;
4913 return (*func)(other, self, third);
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00004914}
4915
Tim Peters6d6c1a32001-08-02 04:15:00 +00004916static PyObject *
4917wrap_unaryfunc(PyObject *self, PyObject *args, void *wrapped)
4918{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004919 unaryfunc func = (unaryfunc)wrapped;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004920
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004921 if (!check_num_args(args, 0))
4922 return NULL;
4923 return (*func)(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004924}
4925
Tim Peters6d6c1a32001-08-02 04:15:00 +00004926static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004927wrap_indexargfunc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004928{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004929 ssizeargfunc func = (ssizeargfunc)wrapped;
4930 PyObject* o;
4931 Py_ssize_t i;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004932
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004933 if (!PyArg_UnpackTuple(args, "", 1, 1, &o))
4934 return NULL;
4935 i = PyNumber_AsSsize_t(o, PyExc_OverflowError);
4936 if (i == -1 && PyErr_Occurred())
4937 return NULL;
4938 return (*func)(self, i);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004939}
4940
Martin v. Löwis18e16552006-02-15 17:27:45 +00004941static Py_ssize_t
Guido van Rossum5d815f32001-08-17 21:57:47 +00004942getindex(PyObject *self, PyObject *arg)
4943{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004944 Py_ssize_t i;
Guido van Rossum5d815f32001-08-17 21:57:47 +00004945
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004946 i = PyNumber_AsSsize_t(arg, PyExc_OverflowError);
4947 if (i == -1 && PyErr_Occurred())
4948 return -1;
4949 if (i < 0) {
4950 PySequenceMethods *sq = Py_TYPE(self)->tp_as_sequence;
4951 if (sq && sq->sq_length) {
4952 Py_ssize_t n = (*sq->sq_length)(self);
4953 if (n < 0)
4954 return -1;
4955 i += n;
4956 }
4957 }
4958 return i;
Guido van Rossum5d815f32001-08-17 21:57:47 +00004959}
4960
4961static PyObject *
4962wrap_sq_item(PyObject *self, PyObject *args, void *wrapped)
4963{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004964 ssizeargfunc func = (ssizeargfunc)wrapped;
4965 PyObject *arg;
4966 Py_ssize_t i;
Guido van Rossum5d815f32001-08-17 21:57:47 +00004967
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004968 if (PyTuple_GET_SIZE(args) == 1) {
4969 arg = PyTuple_GET_ITEM(args, 0);
4970 i = getindex(self, arg);
4971 if (i == -1 && PyErr_Occurred())
4972 return NULL;
4973 return (*func)(self, i);
4974 }
4975 check_num_args(args, 1);
4976 assert(PyErr_Occurred());
4977 return NULL;
Guido van Rossum5d815f32001-08-17 21:57:47 +00004978}
4979
Tim Peters6d6c1a32001-08-02 04:15:00 +00004980static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00004981wrap_sq_setitem(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004982{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004983 ssizeobjargproc func = (ssizeobjargproc)wrapped;
4984 Py_ssize_t i;
4985 int res;
4986 PyObject *arg, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004987
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004988 if (!PyArg_UnpackTuple(args, "", 2, 2, &arg, &value))
4989 return NULL;
4990 i = getindex(self, arg);
4991 if (i == -1 && PyErr_Occurred())
4992 return NULL;
4993 res = (*func)(self, i, value);
4994 if (res == -1 && PyErr_Occurred())
4995 return NULL;
4996 Py_INCREF(Py_None);
4997 return Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004998}
4999
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00005000static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00005001wrap_sq_delitem(PyObject *self, PyObject *args, void *wrapped)
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00005002{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005003 ssizeobjargproc func = (ssizeobjargproc)wrapped;
5004 Py_ssize_t i;
5005 int res;
5006 PyObject *arg;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00005007
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005008 if (!check_num_args(args, 1))
5009 return NULL;
5010 arg = PyTuple_GET_ITEM(args, 0);
5011 i = getindex(self, arg);
5012 if (i == -1 && PyErr_Occurred())
5013 return NULL;
5014 res = (*func)(self, i, NULL);
5015 if (res == -1 && PyErr_Occurred())
5016 return NULL;
5017 Py_INCREF(Py_None);
5018 return Py_None;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00005019}
5020
Tim Peters6d6c1a32001-08-02 04:15:00 +00005021/* XXX objobjproc is a misnomer; should be objargpred */
5022static PyObject *
5023wrap_objobjproc(PyObject *self, PyObject *args, void *wrapped)
5024{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005025 objobjproc func = (objobjproc)wrapped;
5026 int res;
5027 PyObject *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005028
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005029 if (!check_num_args(args, 1))
5030 return NULL;
5031 value = PyTuple_GET_ITEM(args, 0);
5032 res = (*func)(self, value);
5033 if (res == -1 && PyErr_Occurred())
5034 return NULL;
5035 else
5036 return PyBool_FromLong(res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005037}
5038
Tim Peters6d6c1a32001-08-02 04:15:00 +00005039static PyObject *
5040wrap_objobjargproc(PyObject *self, PyObject *args, void *wrapped)
5041{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005042 objobjargproc func = (objobjargproc)wrapped;
5043 int res;
5044 PyObject *key, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005045
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005046 if (!PyArg_UnpackTuple(args, "", 2, 2, &key, &value))
5047 return NULL;
5048 res = (*func)(self, key, value);
5049 if (res == -1 && PyErr_Occurred())
5050 return NULL;
5051 Py_INCREF(Py_None);
5052 return Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005053}
5054
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00005055static PyObject *
5056wrap_delitem(PyObject *self, PyObject *args, void *wrapped)
5057{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005058 objobjargproc func = (objobjargproc)wrapped;
5059 int res;
5060 PyObject *key;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00005061
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005062 if (!check_num_args(args, 1))
5063 return NULL;
5064 key = PyTuple_GET_ITEM(args, 0);
5065 res = (*func)(self, key, NULL);
5066 if (res == -1 && PyErr_Occurred())
5067 return NULL;
5068 Py_INCREF(Py_None);
5069 return Py_None;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00005070}
5071
Guido van Rossum4dcdb782003-04-14 21:46:03 +00005072/* Helper to check for object.__setattr__ or __delattr__ applied to a type.
Guido van Rossum52b27052003-04-15 20:05:10 +00005073 This is called the Carlo Verre hack after its discoverer. */
Guido van Rossum4dcdb782003-04-14 21:46:03 +00005074static int
5075hackcheck(PyObject *self, setattrofunc func, char *what)
5076{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005077 PyTypeObject *type = Py_TYPE(self);
5078 while (type && type->tp_flags & Py_TPFLAGS_HEAPTYPE)
5079 type = type->tp_base;
5080 /* If type is NULL now, this is a really weird type.
5081 In the spirit of backwards compatibility (?), just shut up. */
5082 if (type && type->tp_setattro != func) {
5083 PyErr_Format(PyExc_TypeError,
5084 "can't apply this %s to %s object",
5085 what,
5086 type->tp_name);
5087 return 0;
5088 }
5089 return 1;
Guido van Rossum4dcdb782003-04-14 21:46:03 +00005090}
5091
Tim Peters6d6c1a32001-08-02 04:15:00 +00005092static PyObject *
5093wrap_setattr(PyObject *self, PyObject *args, void *wrapped)
5094{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005095 setattrofunc func = (setattrofunc)wrapped;
5096 int res;
5097 PyObject *name, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005098
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005099 if (!PyArg_UnpackTuple(args, "", 2, 2, &name, &value))
5100 return NULL;
5101 if (!hackcheck(self, func, "__setattr__"))
5102 return NULL;
5103 res = (*func)(self, name, value);
5104 if (res < 0)
5105 return NULL;
5106 Py_INCREF(Py_None);
5107 return Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005108}
5109
5110static PyObject *
5111wrap_delattr(PyObject *self, PyObject *args, void *wrapped)
5112{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005113 setattrofunc func = (setattrofunc)wrapped;
5114 int res;
5115 PyObject *name;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005116
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005117 if (!check_num_args(args, 1))
5118 return NULL;
5119 name = PyTuple_GET_ITEM(args, 0);
5120 if (!hackcheck(self, func, "__delattr__"))
5121 return NULL;
5122 res = (*func)(self, name, NULL);
5123 if (res < 0)
5124 return NULL;
5125 Py_INCREF(Py_None);
5126 return Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005127}
5128
Tim Peters6d6c1a32001-08-02 04:15:00 +00005129static PyObject *
5130wrap_hashfunc(PyObject *self, PyObject *args, void *wrapped)
5131{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005132 hashfunc func = (hashfunc)wrapped;
Benjamin Peterson8035bc52010-10-23 16:20:50 +00005133 Py_hash_t res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005134
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005135 if (!check_num_args(args, 0))
5136 return NULL;
5137 res = (*func)(self);
5138 if (res == -1 && PyErr_Occurred())
5139 return NULL;
Benjamin Peterson8035bc52010-10-23 16:20:50 +00005140 return PyLong_FromSsize_t(res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005141}
5142
Tim Peters6d6c1a32001-08-02 04:15:00 +00005143static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00005144wrap_call(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005145{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005146 ternaryfunc func = (ternaryfunc)wrapped;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005147
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005148 return (*func)(self, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005149}
5150
Tim Peters6d6c1a32001-08-02 04:15:00 +00005151static PyObject *
Antoine Pitrou796564c2013-07-30 19:59:21 +02005152wrap_del(PyObject *self, PyObject *args, void *wrapped)
5153{
5154 destructor func = (destructor)wrapped;
5155
5156 if (!check_num_args(args, 0))
5157 return NULL;
5158
5159 (*func)(self);
5160 Py_RETURN_NONE;
5161}
5162
5163static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00005164wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op)
5165{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005166 richcmpfunc func = (richcmpfunc)wrapped;
5167 PyObject *other;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005168
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005169 if (!check_num_args(args, 1))
5170 return NULL;
5171 other = PyTuple_GET_ITEM(args, 0);
5172 return (*func)(self, other, op);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005173}
5174
5175#undef RICHCMP_WRAPPER
5176#define RICHCMP_WRAPPER(NAME, OP) \
5177static PyObject * \
5178richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \
5179{ \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005180 return wrap_richcmpfunc(self, args, wrapped, OP); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00005181}
5182
Jack Jansen8e938b42001-08-08 15:29:49 +00005183RICHCMP_WRAPPER(lt, Py_LT)
5184RICHCMP_WRAPPER(le, Py_LE)
5185RICHCMP_WRAPPER(eq, Py_EQ)
5186RICHCMP_WRAPPER(ne, Py_NE)
5187RICHCMP_WRAPPER(gt, Py_GT)
5188RICHCMP_WRAPPER(ge, Py_GE)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005189
Tim Peters6d6c1a32001-08-02 04:15:00 +00005190static PyObject *
5191wrap_next(PyObject *self, PyObject *args, void *wrapped)
5192{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005193 unaryfunc func = (unaryfunc)wrapped;
5194 PyObject *res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005195
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005196 if (!check_num_args(args, 0))
5197 return NULL;
5198 res = (*func)(self);
5199 if (res == NULL && !PyErr_Occurred())
5200 PyErr_SetNone(PyExc_StopIteration);
5201 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005202}
5203
Tim Peters6d6c1a32001-08-02 04:15:00 +00005204static PyObject *
5205wrap_descr_get(PyObject *self, PyObject *args, void *wrapped)
5206{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005207 descrgetfunc func = (descrgetfunc)wrapped;
5208 PyObject *obj;
5209 PyObject *type = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005210
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005211 if (!PyArg_UnpackTuple(args, "", 1, 2, &obj, &type))
5212 return NULL;
5213 if (obj == Py_None)
5214 obj = NULL;
5215 if (type == Py_None)
5216 type = NULL;
5217 if (type == NULL &&obj == NULL) {
5218 PyErr_SetString(PyExc_TypeError,
5219 "__get__(None, None) is invalid");
5220 return NULL;
5221 }
5222 return (*func)(self, obj, type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005223}
5224
Tim Peters6d6c1a32001-08-02 04:15:00 +00005225static PyObject *
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005226wrap_descr_set(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005227{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005228 descrsetfunc func = (descrsetfunc)wrapped;
5229 PyObject *obj, *value;
5230 int ret;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005231
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005232 if (!PyArg_UnpackTuple(args, "", 2, 2, &obj, &value))
5233 return NULL;
5234 ret = (*func)(self, obj, value);
5235 if (ret < 0)
5236 return NULL;
5237 Py_INCREF(Py_None);
5238 return Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005239}
Guido van Rossum22b13872002-08-06 21:41:44 +00005240
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00005241static PyObject *
5242wrap_descr_delete(PyObject *self, PyObject *args, void *wrapped)
5243{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005244 descrsetfunc func = (descrsetfunc)wrapped;
5245 PyObject *obj;
5246 int ret;
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00005247
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005248 if (!check_num_args(args, 1))
5249 return NULL;
5250 obj = PyTuple_GET_ITEM(args, 0);
5251 ret = (*func)(self, obj, NULL);
5252 if (ret < 0)
5253 return NULL;
5254 Py_INCREF(Py_None);
5255 return Py_None;
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00005256}
Tim Peters6d6c1a32001-08-02 04:15:00 +00005257
Tim Peters6d6c1a32001-08-02 04:15:00 +00005258static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00005259wrap_init(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005260{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005261 initproc func = (initproc)wrapped;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005262
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005263 if (func(self, args, kwds) < 0)
5264 return NULL;
5265 Py_INCREF(Py_None);
5266 return Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005267}
5268
Tim Peters6d6c1a32001-08-02 04:15:00 +00005269static PyObject *
Guido van Rossum0d231ed2001-08-06 16:50:37 +00005270tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005271{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005272 PyTypeObject *type, *subtype, *staticbase;
5273 PyObject *arg0, *res;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00005274
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005275 if (self == NULL || !PyType_Check(self))
5276 Py_FatalError("__new__() called with non-type 'self'");
5277 type = (PyTypeObject *)self;
5278 if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) {
5279 PyErr_Format(PyExc_TypeError,
5280 "%s.__new__(): not enough arguments",
5281 type->tp_name);
5282 return NULL;
5283 }
5284 arg0 = PyTuple_GET_ITEM(args, 0);
5285 if (!PyType_Check(arg0)) {
5286 PyErr_Format(PyExc_TypeError,
5287 "%s.__new__(X): X is not a type object (%s)",
5288 type->tp_name,
5289 Py_TYPE(arg0)->tp_name);
5290 return NULL;
5291 }
5292 subtype = (PyTypeObject *)arg0;
5293 if (!PyType_IsSubtype(subtype, type)) {
5294 PyErr_Format(PyExc_TypeError,
5295 "%s.__new__(%s): %s is not a subtype of %s",
5296 type->tp_name,
5297 subtype->tp_name,
5298 subtype->tp_name,
5299 type->tp_name);
5300 return NULL;
5301 }
Barry Warsaw60f01882001-08-22 19:24:42 +00005302
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005303 /* Check that the use doesn't do something silly and unsafe like
5304 object.__new__(dict). To do this, we check that the
5305 most derived base that's not a heap type is this type. */
5306 staticbase = subtype;
Martin v. Löwis9c564092012-06-23 23:20:45 +02005307 while (staticbase && (staticbase->tp_new == slot_tp_new))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005308 staticbase = staticbase->tp_base;
5309 /* If staticbase is NULL now, it is a really weird type.
5310 In the spirit of backwards compatibility (?), just shut up. */
5311 if (staticbase && staticbase->tp_new != type->tp_new) {
5312 PyErr_Format(PyExc_TypeError,
5313 "%s.__new__(%s) is not safe, use %s.__new__()",
5314 type->tp_name,
5315 subtype->tp_name,
5316 staticbase == NULL ? "?" : staticbase->tp_name);
5317 return NULL;
5318 }
Barry Warsaw60f01882001-08-22 19:24:42 +00005319
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005320 args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
5321 if (args == NULL)
5322 return NULL;
5323 res = type->tp_new(subtype, args, kwds);
5324 Py_DECREF(args);
5325 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005326}
5327
Guido van Rossum0d231ed2001-08-06 16:50:37 +00005328static struct PyMethodDef tp_new_methoddef[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005329 {"__new__", (PyCFunction)tp_new_wrapper, METH_VARARGS|METH_KEYWORDS,
Larry Hastings581ee362014-01-28 05:00:08 -08005330 PyDoc_STR("sig=($type, *args, **kwargs)\n"
5331 "Create and return a new object. "
5332 "See help(type) for accurate signature.")},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005333 {0}
Tim Peters6d6c1a32001-08-02 04:15:00 +00005334};
5335
5336static int
Guido van Rossum0d231ed2001-08-06 16:50:37 +00005337add_tp_new_wrapper(PyTypeObject *type)
5338{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005339 PyObject *func;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00005340
Victor Stinner3c1e4812012-03-26 22:10:51 +02005341 if (_PyDict_GetItemId(type->tp_dict, &PyId___new__) != NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005342 return 0;
Andrew Svetlov3ba3a3e2012-12-25 13:32:35 +02005343 func = PyCFunction_NewEx(tp_new_methoddef, (PyObject *)type, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005344 if (func == NULL)
5345 return -1;
Victor Stinner3c1e4812012-03-26 22:10:51 +02005346 if (_PyDict_SetItemId(type->tp_dict, &PyId___new__, func)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005347 Py_DECREF(func);
5348 return -1;
5349 }
5350 Py_DECREF(func);
5351 return 0;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00005352}
5353
Guido van Rossumf040ede2001-08-07 16:40:56 +00005354/* Slot wrappers that call the corresponding __foo__ slot. See comments
5355 below at override_slots() for more explanation. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00005356
Guido van Rossumdc91b992001-08-08 22:26:22 +00005357#define SLOT0(FUNCNAME, OPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00005358static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00005359FUNCNAME(PyObject *self) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00005360{ \
Benjamin Petersonce798522012-01-22 11:24:29 -05005361 _Py_static_string(id, OPSTR); \
5362 return call_method(self, &id, "()"); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00005363}
5364
Guido van Rossumdc91b992001-08-08 22:26:22 +00005365#define SLOT1(FUNCNAME, OPSTR, ARG1TYPE, ARGCODES) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00005366static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00005367FUNCNAME(PyObject *self, ARG1TYPE arg1) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00005368{ \
Benjamin Petersonce798522012-01-22 11:24:29 -05005369 _Py_static_string(id, OPSTR); \
5370 return call_method(self, &id, "(" ARGCODES ")", arg1); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00005371}
5372
Guido van Rossumcd118802003-01-06 22:57:47 +00005373/* Boolean helper for SLOT1BINFULL().
5374 right.__class__ is a nontrivial subclass of left.__class__. */
5375static int
Victor Stinner3c1e4812012-03-26 22:10:51 +02005376method_is_overloaded(PyObject *left, PyObject *right, struct _Py_Identifier *name)
Guido van Rossumcd118802003-01-06 22:57:47 +00005377{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005378 PyObject *a, *b;
5379 int ok;
Guido van Rossumcd118802003-01-06 22:57:47 +00005380
Victor Stinner3c1e4812012-03-26 22:10:51 +02005381 b = _PyObject_GetAttrId((PyObject *)(Py_TYPE(right)), name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005382 if (b == NULL) {
5383 PyErr_Clear();
5384 /* If right doesn't have it, it's not overloaded */
5385 return 0;
5386 }
Guido van Rossumcd118802003-01-06 22:57:47 +00005387
Victor Stinner3c1e4812012-03-26 22:10:51 +02005388 a = _PyObject_GetAttrId((PyObject *)(Py_TYPE(left)), name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005389 if (a == NULL) {
5390 PyErr_Clear();
5391 Py_DECREF(b);
5392 /* If right has it but left doesn't, it's overloaded */
5393 return 1;
5394 }
Guido van Rossumcd118802003-01-06 22:57:47 +00005395
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005396 ok = PyObject_RichCompareBool(a, b, Py_NE);
5397 Py_DECREF(a);
5398 Py_DECREF(b);
5399 if (ok < 0) {
5400 PyErr_Clear();
5401 return 0;
5402 }
Guido van Rossumcd118802003-01-06 22:57:47 +00005403
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005404 return ok;
Guido van Rossumcd118802003-01-06 22:57:47 +00005405}
5406
Guido van Rossumdc91b992001-08-08 22:26:22 +00005407
5408#define SLOT1BINFULL(FUNCNAME, TESTFUNC, SLOTNAME, OPSTR, ROPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00005409static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00005410FUNCNAME(PyObject *self, PyObject *other) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00005411{ \
Benjamin Petersonce798522012-01-22 11:24:29 -05005412 _Py_static_string(op_id, OPSTR); \
5413 _Py_static_string(rop_id, ROPSTR); \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005414 int do_other = Py_TYPE(self) != Py_TYPE(other) && \
5415 Py_TYPE(other)->tp_as_number != NULL && \
5416 Py_TYPE(other)->tp_as_number->SLOTNAME == TESTFUNC; \
5417 if (Py_TYPE(self)->tp_as_number != NULL && \
5418 Py_TYPE(self)->tp_as_number->SLOTNAME == TESTFUNC) { \
5419 PyObject *r; \
5420 if (do_other && \
5421 PyType_IsSubtype(Py_TYPE(other), Py_TYPE(self)) && \
Victor Stinner3c1e4812012-03-26 22:10:51 +02005422 method_is_overloaded(self, other, &rop_id)) { \
Benjamin Petersonce798522012-01-22 11:24:29 -05005423 r = call_maybe(other, &rop_id, "(O)", self); \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005424 if (r != Py_NotImplemented) \
5425 return r; \
5426 Py_DECREF(r); \
5427 do_other = 0; \
5428 } \
Benjamin Petersonce798522012-01-22 11:24:29 -05005429 r = call_maybe(self, &op_id, "(O)", other); \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005430 if (r != Py_NotImplemented || \
5431 Py_TYPE(other) == Py_TYPE(self)) \
5432 return r; \
5433 Py_DECREF(r); \
5434 } \
5435 if (do_other) { \
Benjamin Petersonce798522012-01-22 11:24:29 -05005436 return call_maybe(other, &rop_id, "(O)", self); \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005437 } \
Brian Curtindfc80e32011-08-10 20:28:54 -05005438 Py_RETURN_NOTIMPLEMENTED; \
Guido van Rossumdc91b992001-08-08 22:26:22 +00005439}
5440
5441#define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005442 SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR)
Guido van Rossumdc91b992001-08-08 22:26:22 +00005443
5444#define SLOT2(FUNCNAME, OPSTR, ARG1TYPE, ARG2TYPE, ARGCODES) \
5445static PyObject * \
5446FUNCNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \
5447{ \
Benjamin Petersonce798522012-01-22 11:24:29 -05005448 _Py_static_string(id, #OPSTR); \
5449 return call_method(self, &id, "(" ARGCODES ")", arg1, arg2); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00005450}
5451
Martin v. Löwis18e16552006-02-15 17:27:45 +00005452static Py_ssize_t
Tim Peters6d6c1a32001-08-02 04:15:00 +00005453slot_sq_length(PyObject *self)
5454{
Benjamin Petersonce798522012-01-22 11:24:29 -05005455 PyObject *res = call_method(self, &PyId___len__, "()");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005456 Py_ssize_t len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005457
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005458 if (res == NULL)
5459 return -1;
5460 len = PyNumber_AsSsize_t(res, PyExc_OverflowError);
5461 Py_DECREF(res);
5462 if (len < 0) {
5463 if (!PyErr_Occurred())
5464 PyErr_SetString(PyExc_ValueError,
5465 "__len__() should return >= 0");
5466 return -1;
5467 }
5468 return len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005469}
5470
Guido van Rossumf4593e02001-10-03 12:09:30 +00005471/* Super-optimized version of slot_sq_item.
5472 Other slots could do the same... */
5473static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00005474slot_sq_item(PyObject *self, Py_ssize_t i)
Guido van Rossumf4593e02001-10-03 12:09:30 +00005475{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005476 PyObject *func, *args = NULL, *ival = NULL, *retval = NULL;
5477 descrgetfunc f;
Guido van Rossumf4593e02001-10-03 12:09:30 +00005478
Victor Stinner3c1e4812012-03-26 22:10:51 +02005479 func = _PyType_LookupId(Py_TYPE(self), &PyId___getitem__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005480 if (func != NULL) {
5481 if ((f = Py_TYPE(func)->tp_descr_get) == NULL)
5482 Py_INCREF(func);
5483 else {
5484 func = f(func, self, (PyObject *)(Py_TYPE(self)));
5485 if (func == NULL) {
5486 return NULL;
5487 }
5488 }
5489 ival = PyLong_FromSsize_t(i);
5490 if (ival != NULL) {
5491 args = PyTuple_New(1);
5492 if (args != NULL) {
5493 PyTuple_SET_ITEM(args, 0, ival);
5494 retval = PyObject_Call(func, args, NULL);
5495 Py_XDECREF(args);
5496 Py_XDECREF(func);
5497 return retval;
5498 }
5499 }
5500 }
5501 else {
Victor Stinner3c1e4812012-03-26 22:10:51 +02005502 PyObject *getitem_str = _PyUnicode_FromId(&PyId___getitem__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005503 PyErr_SetObject(PyExc_AttributeError, getitem_str);
5504 }
5505 Py_XDECREF(args);
5506 Py_XDECREF(ival);
5507 Py_XDECREF(func);
5508 return NULL;
Guido van Rossumf4593e02001-10-03 12:09:30 +00005509}
5510
Tim Peters6d6c1a32001-08-02 04:15:00 +00005511static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00005512slot_sq_ass_item(PyObject *self, Py_ssize_t index, PyObject *value)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005513{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005514 PyObject *res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005515
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005516 if (value == NULL)
Benjamin Petersonce798522012-01-22 11:24:29 -05005517 res = call_method(self, &PyId___delitem__, "(n)", index);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005518 else
Benjamin Petersonce798522012-01-22 11:24:29 -05005519 res = call_method(self, &PyId___setitem__, "(nO)", index, value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005520 if (res == NULL)
5521 return -1;
5522 Py_DECREF(res);
5523 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005524}
5525
5526static int
Tim Peters6d6c1a32001-08-02 04:15:00 +00005527slot_sq_contains(PyObject *self, PyObject *value)
5528{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005529 PyObject *func, *res, *args;
5530 int result = -1;
Benjamin Petersonce798522012-01-22 11:24:29 -05005531 _Py_IDENTIFIER(__contains__);
Tim Petersbf9b2442003-03-23 05:35:36 +00005532
Benjamin Petersonce798522012-01-22 11:24:29 -05005533 func = lookup_maybe(self, &PyId___contains__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005534 if (func != NULL) {
5535 args = PyTuple_Pack(1, value);
5536 if (args == NULL)
5537 res = NULL;
5538 else {
5539 res = PyObject_Call(func, args, NULL);
5540 Py_DECREF(args);
5541 }
5542 Py_DECREF(func);
5543 if (res != NULL) {
5544 result = PyObject_IsTrue(res);
5545 Py_DECREF(res);
5546 }
5547 }
5548 else if (! PyErr_Occurred()) {
5549 /* Possible results: -1 and 1 */
5550 result = (int)_PySequence_IterSearch(self, value,
5551 PY_ITERSEARCH_CONTAINS);
5552 }
5553 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005554}
5555
Tim Peters6d6c1a32001-08-02 04:15:00 +00005556#define slot_mp_length slot_sq_length
5557
Guido van Rossumdc91b992001-08-08 22:26:22 +00005558SLOT1(slot_mp_subscript, "__getitem__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00005559
5560static int
5561slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value)
5562{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005563 PyObject *res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005564
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005565 if (value == NULL)
Benjamin Petersonce798522012-01-22 11:24:29 -05005566 res = call_method(self, &PyId___delitem__, "(O)", key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005567 else
Benjamin Petersonce798522012-01-22 11:24:29 -05005568 res = call_method(self, &PyId___setitem__, "(OO)", key, value);
5569
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005570 if (res == NULL)
5571 return -1;
5572 Py_DECREF(res);
5573 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005574}
5575
Guido van Rossumdc91b992001-08-08 22:26:22 +00005576SLOT1BIN(slot_nb_add, nb_add, "__add__", "__radd__")
5577SLOT1BIN(slot_nb_subtract, nb_subtract, "__sub__", "__rsub__")
5578SLOT1BIN(slot_nb_multiply, nb_multiply, "__mul__", "__rmul__")
Guido van Rossumdc91b992001-08-08 22:26:22 +00005579SLOT1BIN(slot_nb_remainder, nb_remainder, "__mod__", "__rmod__")
5580SLOT1BIN(slot_nb_divmod, nb_divmod, "__divmod__", "__rdivmod__")
5581
Jeremy Hylton938ace62002-07-17 16:30:39 +00005582static PyObject *slot_nb_power(PyObject *, PyObject *, PyObject *);
Guido van Rossumdc91b992001-08-08 22:26:22 +00005583
5584SLOT1BINFULL(slot_nb_power_binary, slot_nb_power,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005585 nb_power, "__pow__", "__rpow__")
Guido van Rossumdc91b992001-08-08 22:26:22 +00005586
5587static PyObject *
5588slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus)
5589{
Benjamin Petersonce798522012-01-22 11:24:29 -05005590 _Py_IDENTIFIER(__pow__);
Guido van Rossum2730b132001-08-28 18:22:14 +00005591
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005592 if (modulus == Py_None)
5593 return slot_nb_power_binary(self, other);
5594 /* Three-arg power doesn't use __rpow__. But ternary_op
5595 can call this when the second argument's type uses
5596 slot_nb_power, so check before calling self.__pow__. */
5597 if (Py_TYPE(self)->tp_as_number != NULL &&
5598 Py_TYPE(self)->tp_as_number->nb_power == slot_nb_power) {
Benjamin Petersonce798522012-01-22 11:24:29 -05005599 return call_method(self, &PyId___pow__, "(OO)", other, modulus);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005600 }
Brian Curtindfc80e32011-08-10 20:28:54 -05005601 Py_RETURN_NOTIMPLEMENTED;
Guido van Rossumdc91b992001-08-08 22:26:22 +00005602}
5603
5604SLOT0(slot_nb_negative, "__neg__")
5605SLOT0(slot_nb_positive, "__pos__")
5606SLOT0(slot_nb_absolute, "__abs__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00005607
5608static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00005609slot_nb_bool(PyObject *self)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005610{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005611 PyObject *func, *args;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005612 int result = -1;
5613 int using_len = 0;
Benjamin Petersonce798522012-01-22 11:24:29 -05005614 _Py_IDENTIFIER(__bool__);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005615
Benjamin Petersonce798522012-01-22 11:24:29 -05005616 func = lookup_maybe(self, &PyId___bool__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005617 if (func == NULL) {
5618 if (PyErr_Occurred())
5619 return -1;
Benjamin Petersonce798522012-01-22 11:24:29 -05005620 func = lookup_maybe(self, &PyId___len__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005621 if (func == NULL)
5622 return PyErr_Occurred() ? -1 : 1;
5623 using_len = 1;
5624 }
5625 args = PyTuple_New(0);
5626 if (args != NULL) {
5627 PyObject *temp = PyObject_Call(func, args, NULL);
5628 Py_DECREF(args);
5629 if (temp != NULL) {
5630 if (using_len) {
5631 /* enforced by slot_nb_len */
5632 result = PyObject_IsTrue(temp);
5633 }
5634 else if (PyBool_Check(temp)) {
5635 result = PyObject_IsTrue(temp);
5636 }
5637 else {
5638 PyErr_Format(PyExc_TypeError,
5639 "__bool__ should return "
5640 "bool, returned %s",
5641 Py_TYPE(temp)->tp_name);
5642 result = -1;
5643 }
5644 Py_DECREF(temp);
5645 }
5646 }
5647 Py_DECREF(func);
5648 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005649}
5650
Guido van Rossum38fff8c2006-03-07 18:50:55 +00005651
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00005652static PyObject *
Guido van Rossum38fff8c2006-03-07 18:50:55 +00005653slot_nb_index(PyObject *self)
5654{
Benjamin Petersonce798522012-01-22 11:24:29 -05005655 _Py_IDENTIFIER(__index__);
5656 return call_method(self, &PyId___index__, "()");
Guido van Rossum38fff8c2006-03-07 18:50:55 +00005657}
5658
5659
Guido van Rossumdc91b992001-08-08 22:26:22 +00005660SLOT0(slot_nb_invert, "__invert__")
5661SLOT1BIN(slot_nb_lshift, nb_lshift, "__lshift__", "__rlshift__")
5662SLOT1BIN(slot_nb_rshift, nb_rshift, "__rshift__", "__rrshift__")
5663SLOT1BIN(slot_nb_and, nb_and, "__and__", "__rand__")
5664SLOT1BIN(slot_nb_xor, nb_xor, "__xor__", "__rxor__")
5665SLOT1BIN(slot_nb_or, nb_or, "__or__", "__ror__")
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00005666
Guido van Rossumdc91b992001-08-08 22:26:22 +00005667SLOT0(slot_nb_int, "__int__")
Guido van Rossumdc91b992001-08-08 22:26:22 +00005668SLOT0(slot_nb_float, "__float__")
Guido van Rossumdc91b992001-08-08 22:26:22 +00005669SLOT1(slot_nb_inplace_add, "__iadd__", PyObject *, "O")
5670SLOT1(slot_nb_inplace_subtract, "__isub__", PyObject *, "O")
5671SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *, "O")
Guido van Rossumdc91b992001-08-08 22:26:22 +00005672SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *, "O")
Thomas Wouterscf297e42007-02-23 15:07:44 +00005673/* Can't use SLOT1 here, because nb_inplace_power is ternary */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005674static PyObject *
5675slot_nb_inplace_power(PyObject *self, PyObject * arg1, PyObject *arg2)
5676{
Benjamin Petersonce798522012-01-22 11:24:29 -05005677 _Py_IDENTIFIER(__ipow__);
5678 return call_method(self, &PyId___ipow__, "(" "O" ")", arg1);
Thomas Wouterscf297e42007-02-23 15:07:44 +00005679}
Guido van Rossumdc91b992001-08-08 22:26:22 +00005680SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *, "O")
5681SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *, "O")
5682SLOT1(slot_nb_inplace_and, "__iand__", PyObject *, "O")
5683SLOT1(slot_nb_inplace_xor, "__ixor__", PyObject *, "O")
5684SLOT1(slot_nb_inplace_or, "__ior__", PyObject *, "O")
5685SLOT1BIN(slot_nb_floor_divide, nb_floor_divide,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005686 "__floordiv__", "__rfloordiv__")
Guido van Rossumdc91b992001-08-08 22:26:22 +00005687SLOT1BIN(slot_nb_true_divide, nb_true_divide, "__truediv__", "__rtruediv__")
5688SLOT1(slot_nb_inplace_floor_divide, "__ifloordiv__", PyObject *, "O")
5689SLOT1(slot_nb_inplace_true_divide, "__itruediv__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00005690
Guido van Rossumb8f63662001-08-15 23:57:02 +00005691static PyObject *
5692slot_tp_repr(PyObject *self)
5693{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005694 PyObject *func, *res;
Benjamin Petersonce798522012-01-22 11:24:29 -05005695 _Py_IDENTIFIER(__repr__);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005696
Benjamin Petersonce798522012-01-22 11:24:29 -05005697 func = lookup_method(self, &PyId___repr__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005698 if (func != NULL) {
5699 res = PyEval_CallObject(func, NULL);
5700 Py_DECREF(func);
5701 return res;
5702 }
5703 PyErr_Clear();
5704 return PyUnicode_FromFormat("<%s object at %p>",
5705 Py_TYPE(self)->tp_name, self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005706}
5707
5708static PyObject *
5709slot_tp_str(PyObject *self)
5710{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005711 PyObject *func, *res;
Benjamin Petersonce798522012-01-22 11:24:29 -05005712 _Py_IDENTIFIER(__str__);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005713
Benjamin Petersonce798522012-01-22 11:24:29 -05005714 func = lookup_method(self, &PyId___str__);
Victor Stinner2e8474d2013-07-11 22:46:11 +02005715 if (func == NULL)
5716 return NULL;
Victor Stinnerbebba502013-10-29 10:56:34 +01005717 res = PyEval_CallObject(func, NULL);
5718 Py_DECREF(func);
5719 return res;
5720}
Tim Peters6d6c1a32001-08-02 04:15:00 +00005721
Benjamin Peterson8f67d082010-10-17 20:54:53 +00005722static Py_hash_t
Tim Peters6d6c1a32001-08-02 04:15:00 +00005723slot_tp_hash(PyObject *self)
5724{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005725 PyObject *func, *res;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00005726 Py_ssize_t h;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005727
Benjamin Petersonce798522012-01-22 11:24:29 -05005728 func = lookup_method(self, &PyId___hash__);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005729
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005730 if (func == Py_None) {
5731 Py_DECREF(func);
5732 func = NULL;
5733 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +00005734
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005735 if (func == NULL) {
5736 return PyObject_HashNotImplemented(self);
5737 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +00005738
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005739 res = PyEval_CallObject(func, NULL);
5740 Py_DECREF(func);
5741 if (res == NULL)
5742 return -1;
Mark Dickinsondc787d22010-05-23 13:33:13 +00005743
5744 if (!PyLong_Check(res)) {
5745 PyErr_SetString(PyExc_TypeError,
5746 "__hash__ method should return an integer");
5747 return -1;
5748 }
Benjamin Peterson8f67d082010-10-17 20:54:53 +00005749 /* Transform the PyLong `res` to a Py_hash_t `h`. For an existing
5750 hashable Python object x, hash(x) will always lie within the range of
5751 Py_hash_t. Therefore our transformation must preserve values that
5752 already lie within this range, to ensure that if x.__hash__() returns
5753 hash(y) then hash(x) == hash(y). */
5754 h = PyLong_AsSsize_t(res);
5755 if (h == -1 && PyErr_Occurred()) {
5756 /* res was not within the range of a Py_hash_t, so we're free to
Mark Dickinsondc787d22010-05-23 13:33:13 +00005757 use any sufficiently bit-mixing transformation;
5758 long.__hash__ will do nicely. */
Benjamin Peterson8f67d082010-10-17 20:54:53 +00005759 PyErr_Clear();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005760 h = PyLong_Type.tp_hash(res);
Benjamin Peterson8f67d082010-10-17 20:54:53 +00005761 }
Benjamin Petersone7dfeeb2010-10-17 21:27:01 +00005762 /* -1 is reserved for errors. */
5763 if (h == -1)
5764 h = -2;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005765 Py_DECREF(res);
Mark Dickinsondc787d22010-05-23 13:33:13 +00005766 return h;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005767}
5768
5769static PyObject *
5770slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds)
5771{
Benjamin Petersonce798522012-01-22 11:24:29 -05005772 _Py_IDENTIFIER(__call__);
5773 PyObject *meth = lookup_method(self, &PyId___call__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005774 PyObject *res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005775
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005776 if (meth == NULL)
5777 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005778
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005779 res = PyObject_Call(meth, args, kwds);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005780
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005781 Py_DECREF(meth);
5782 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005783}
5784
Guido van Rossum14a6f832001-10-17 13:59:09 +00005785/* There are two slot dispatch functions for tp_getattro.
5786
5787 - slot_tp_getattro() is used when __getattribute__ is overridden
5788 but no __getattr__ hook is present;
5789
5790 - slot_tp_getattr_hook() is used when a __getattr__ hook is present.
5791
Guido van Rossumc334df52002-04-04 23:44:47 +00005792 The code in update_one_slot() always installs slot_tp_getattr_hook(); this
5793 detects the absence of __getattr__ and then installs the simpler slot if
5794 necessary. */
Guido van Rossum14a6f832001-10-17 13:59:09 +00005795
Tim Peters6d6c1a32001-08-02 04:15:00 +00005796static PyObject *
5797slot_tp_getattro(PyObject *self, PyObject *name)
5798{
Benjamin Petersonce798522012-01-22 11:24:29 -05005799 return call_method(self, &PyId___getattribute__, "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005800}
5801
Guido van Rossum19c1cd52001-09-21 21:24:49 +00005802static PyObject *
Benjamin Peterson9262b842008-11-17 22:45:50 +00005803call_attribute(PyObject *self, PyObject *attr, PyObject *name)
5804{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005805 PyObject *res, *descr = NULL;
5806 descrgetfunc f = Py_TYPE(attr)->tp_descr_get;
Benjamin Peterson9262b842008-11-17 22:45:50 +00005807
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005808 if (f != NULL) {
5809 descr = f(attr, self, (PyObject *)(Py_TYPE(self)));
5810 if (descr == NULL)
5811 return NULL;
5812 else
5813 attr = descr;
5814 }
5815 res = PyObject_CallFunctionObjArgs(attr, name, NULL);
5816 Py_XDECREF(descr);
5817 return res;
Benjamin Peterson9262b842008-11-17 22:45:50 +00005818}
5819
5820static PyObject *
Guido van Rossum19c1cd52001-09-21 21:24:49 +00005821slot_tp_getattr_hook(PyObject *self, PyObject *name)
5822{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005823 PyTypeObject *tp = Py_TYPE(self);
5824 PyObject *getattr, *getattribute, *res;
Victor Stinner3c1e4812012-03-26 22:10:51 +02005825 _Py_IDENTIFIER(__getattr__);
Guido van Rossum19c1cd52001-09-21 21:24:49 +00005826
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005827 /* speed hack: we could use lookup_maybe, but that would resolve the
5828 method fully for each attribute lookup for classes with
5829 __getattr__, even when the attribute is present. So we use
5830 _PyType_Lookup and create the method only when needed, with
5831 call_attribute. */
Victor Stinner3c1e4812012-03-26 22:10:51 +02005832 getattr = _PyType_LookupId(tp, &PyId___getattr__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005833 if (getattr == NULL) {
5834 /* No __getattr__ hook: use a simpler dispatcher */
5835 tp->tp_getattro = slot_tp_getattro;
5836 return slot_tp_getattro(self, name);
5837 }
5838 Py_INCREF(getattr);
5839 /* speed hack: we could use lookup_maybe, but that would resolve the
5840 method fully for each attribute lookup for classes with
5841 __getattr__, even when self has the default __getattribute__
5842 method. So we use _PyType_Lookup and create the method only when
5843 needed, with call_attribute. */
Victor Stinner3c1e4812012-03-26 22:10:51 +02005844 getattribute = _PyType_LookupId(tp, &PyId___getattribute__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005845 if (getattribute == NULL ||
5846 (Py_TYPE(getattribute) == &PyWrapperDescr_Type &&
5847 ((PyWrapperDescrObject *)getattribute)->d_wrapped ==
5848 (void *)PyObject_GenericGetAttr))
5849 res = PyObject_GenericGetAttr(self, name);
5850 else {
5851 Py_INCREF(getattribute);
5852 res = call_attribute(self, getattribute, name);
5853 Py_DECREF(getattribute);
5854 }
5855 if (res == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) {
5856 PyErr_Clear();
5857 res = call_attribute(self, getattr, name);
5858 }
5859 Py_DECREF(getattr);
5860 return res;
Guido van Rossum19c1cd52001-09-21 21:24:49 +00005861}
5862
Tim Peters6d6c1a32001-08-02 04:15:00 +00005863static int
5864slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value)
5865{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005866 PyObject *res;
Benjamin Petersonce798522012-01-22 11:24:29 -05005867 _Py_IDENTIFIER(__delattr__);
5868 _Py_IDENTIFIER(__setattr__);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005869
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005870 if (value == NULL)
Benjamin Petersonce798522012-01-22 11:24:29 -05005871 res = call_method(self, &PyId___delattr__, "(O)", name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005872 else
Benjamin Petersonce798522012-01-22 11:24:29 -05005873 res = call_method(self, &PyId___setattr__, "(OO)", name, value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005874 if (res == NULL)
5875 return -1;
5876 Py_DECREF(res);
5877 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005878}
5879
Benjamin Petersonce798522012-01-22 11:24:29 -05005880static _Py_Identifier name_op[] = {
5881 {0, "__lt__", 0},
5882 {0, "__le__", 0},
5883 {0, "__eq__", 0},
5884 {0, "__ne__", 0},
5885 {0, "__gt__", 0},
5886 {0, "__ge__", 0}
Guido van Rossumf5243f02008-01-01 04:06:48 +00005887};
5888
Tim Peters6d6c1a32001-08-02 04:15:00 +00005889static PyObject *
Mark Dickinson6f1d0492009-11-15 13:58:49 +00005890slot_tp_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005891{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005892 PyObject *func, *args, *res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005893
Benjamin Petersonce798522012-01-22 11:24:29 -05005894 func = lookup_method(self, &name_op[op]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005895 if (func == NULL) {
5896 PyErr_Clear();
Brian Curtindfc80e32011-08-10 20:28:54 -05005897 Py_RETURN_NOTIMPLEMENTED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005898 }
5899 args = PyTuple_Pack(1, other);
5900 if (args == NULL)
5901 res = NULL;
5902 else {
5903 res = PyObject_Call(func, args, NULL);
5904 Py_DECREF(args);
5905 }
5906 Py_DECREF(func);
5907 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005908}
5909
Guido van Rossumb8f63662001-08-15 23:57:02 +00005910static PyObject *
Guido van Rossumb8f63662001-08-15 23:57:02 +00005911slot_tp_iter(PyObject *self)
5912{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005913 PyObject *func, *res;
Benjamin Petersonce798522012-01-22 11:24:29 -05005914 _Py_IDENTIFIER(__iter__);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005915
Benjamin Petersonce798522012-01-22 11:24:29 -05005916 func = lookup_method(self, &PyId___iter__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005917 if (func != NULL) {
5918 PyObject *args;
5919 args = res = PyTuple_New(0);
5920 if (args != NULL) {
5921 res = PyObject_Call(func, args, NULL);
5922 Py_DECREF(args);
5923 }
5924 Py_DECREF(func);
5925 return res;
5926 }
5927 PyErr_Clear();
Benjamin Petersonce798522012-01-22 11:24:29 -05005928 func = lookup_method(self, &PyId___getitem__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005929 if (func == NULL) {
5930 PyErr_Format(PyExc_TypeError,
5931 "'%.200s' object is not iterable",
5932 Py_TYPE(self)->tp_name);
5933 return NULL;
5934 }
5935 Py_DECREF(func);
5936 return PySeqIter_New(self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005937}
Tim Peters6d6c1a32001-08-02 04:15:00 +00005938
5939static PyObject *
5940slot_tp_iternext(PyObject *self)
5941{
Benjamin Petersonce798522012-01-22 11:24:29 -05005942 _Py_IDENTIFIER(__next__);
5943 return call_method(self, &PyId___next__, "()");
Tim Peters6d6c1a32001-08-02 04:15:00 +00005944}
5945
Guido van Rossum1a493502001-08-17 16:47:50 +00005946static PyObject *
5947slot_tp_descr_get(PyObject *self, PyObject *obj, PyObject *type)
5948{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005949 PyTypeObject *tp = Py_TYPE(self);
5950 PyObject *get;
Victor Stinner3c1e4812012-03-26 22:10:51 +02005951 _Py_IDENTIFIER(__get__);
Guido van Rossum1a493502001-08-17 16:47:50 +00005952
Victor Stinner3c1e4812012-03-26 22:10:51 +02005953 get = _PyType_LookupId(tp, &PyId___get__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005954 if (get == NULL) {
5955 /* Avoid further slowdowns */
5956 if (tp->tp_descr_get == slot_tp_descr_get)
5957 tp->tp_descr_get = NULL;
5958 Py_INCREF(self);
5959 return self;
5960 }
5961 if (obj == NULL)
5962 obj = Py_None;
5963 if (type == NULL)
5964 type = Py_None;
5965 return PyObject_CallFunctionObjArgs(get, self, obj, type, NULL);
Guido van Rossum1a493502001-08-17 16:47:50 +00005966}
Tim Peters6d6c1a32001-08-02 04:15:00 +00005967
5968static int
5969slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value)
5970{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005971 PyObject *res;
Benjamin Petersonce798522012-01-22 11:24:29 -05005972 _Py_IDENTIFIER(__delete__);
5973 _Py_IDENTIFIER(__set__);
Guido van Rossum2c252392001-08-24 10:13:31 +00005974
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005975 if (value == NULL)
Benjamin Petersonce798522012-01-22 11:24:29 -05005976 res = call_method(self, &PyId___delete__, "(O)", target);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005977 else
Benjamin Petersonce798522012-01-22 11:24:29 -05005978 res = call_method(self, &PyId___set__, "(OO)", target, value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005979 if (res == NULL)
5980 return -1;
5981 Py_DECREF(res);
5982 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005983}
5984
5985static int
5986slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds)
5987{
Benjamin Petersonce798522012-01-22 11:24:29 -05005988 _Py_IDENTIFIER(__init__);
5989 PyObject *meth = lookup_method(self, &PyId___init__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005990 PyObject *res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005991
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005992 if (meth == NULL)
5993 return -1;
5994 res = PyObject_Call(meth, args, kwds);
5995 Py_DECREF(meth);
5996 if (res == NULL)
5997 return -1;
5998 if (res != Py_None) {
5999 PyErr_Format(PyExc_TypeError,
6000 "__init__() should return None, not '%.200s'",
6001 Py_TYPE(res)->tp_name);
6002 Py_DECREF(res);
6003 return -1;
6004 }
6005 Py_DECREF(res);
6006 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00006007}
6008
6009static PyObject *
6010slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
6011{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006012 PyObject *func;
6013 PyObject *newargs, *x;
6014 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +00006015
Victor Stinner3c1e4812012-03-26 22:10:51 +02006016 func = _PyObject_GetAttrId((PyObject *)type, &PyId___new__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006017 if (func == NULL)
6018 return NULL;
6019 assert(PyTuple_Check(args));
6020 n = PyTuple_GET_SIZE(args);
6021 newargs = PyTuple_New(n+1);
6022 if (newargs == NULL)
6023 return NULL;
6024 Py_INCREF(type);
6025 PyTuple_SET_ITEM(newargs, 0, (PyObject *)type);
6026 for (i = 0; i < n; i++) {
6027 x = PyTuple_GET_ITEM(args, i);
6028 Py_INCREF(x);
6029 PyTuple_SET_ITEM(newargs, i+1, x);
6030 }
6031 x = PyObject_Call(func, newargs, kwds);
6032 Py_DECREF(newargs);
6033 Py_DECREF(func);
6034 return x;
Tim Peters6d6c1a32001-08-02 04:15:00 +00006035}
6036
Guido van Rossumfebd61d2002-08-08 20:55:20 +00006037static void
Antoine Pitrou796564c2013-07-30 19:59:21 +02006038slot_tp_finalize(PyObject *self)
Guido van Rossumfebd61d2002-08-08 20:55:20 +00006039{
Benjamin Petersonce798522012-01-22 11:24:29 -05006040 _Py_IDENTIFIER(__del__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006041 PyObject *del, *res;
6042 PyObject *error_type, *error_value, *error_traceback;
Guido van Rossumfebd61d2002-08-08 20:55:20 +00006043
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006044 /* Save the current exception, if any. */
6045 PyErr_Fetch(&error_type, &error_value, &error_traceback);
Guido van Rossumfebd61d2002-08-08 20:55:20 +00006046
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006047 /* Execute __del__ method, if any. */
Benjamin Petersonce798522012-01-22 11:24:29 -05006048 del = lookup_maybe(self, &PyId___del__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006049 if (del != NULL) {
6050 res = PyEval_CallObject(del, NULL);
6051 if (res == NULL)
6052 PyErr_WriteUnraisable(del);
6053 else
6054 Py_DECREF(res);
6055 Py_DECREF(del);
6056 }
Guido van Rossumfebd61d2002-08-08 20:55:20 +00006057
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006058 /* Restore the saved exception. */
6059 PyErr_Restore(error_type, error_value, error_traceback);
Guido van Rossumfebd61d2002-08-08 20:55:20 +00006060}
6061
Guido van Rossum7b9144b2001-10-09 19:39:46 +00006062
Benjamin Peterson63952412013-04-01 17:41:41 -04006063/*
6064Table mapping __foo__ names to tp_foo offsets and slot_tp_foo wrapper functions.
6065
6066The table is ordered by offsets relative to the 'PyHeapTypeObject' structure,
6067which incorporates the additional structures used for numbers, sequences and
6068mappings. Note that multiple names may map to the same slot (e.g. __eq__,
6069__ne__ etc. all map to tp_richcompare) and one name may map to multiple slots
6070(e.g. __str__ affects tp_str as well as tp_repr). The table is terminated with
6071an all-zero entry. (This table is further initialized in init_slotdefs().)
6072*/
Guido van Rossum7b9144b2001-10-09 19:39:46 +00006073
Guido van Rossum6d204072001-10-21 00:44:31 +00006074typedef struct wrapperbase slotdef;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00006075
6076#undef TPSLOT
Guido van Rossumc8e56452001-10-22 00:43:43 +00006077#undef FLSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00006078#undef ETSLOT
6079#undef SQSLOT
6080#undef MPSLOT
6081#undef NBSLOT
Guido van Rossum6d204072001-10-21 00:44:31 +00006082#undef UNSLOT
6083#undef IBSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00006084#undef BINSLOT
6085#undef RBINSLOT
6086
Guido van Rossum6d204072001-10-21 00:44:31 +00006087#define TPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006088 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
6089 PyDoc_STR(DOC)}
Guido van Rossumc8e56452001-10-22 00:43:43 +00006090#define FLSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC, FLAGS) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006091 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
6092 PyDoc_STR(DOC), FLAGS}
Guido van Rossum6d204072001-10-21 00:44:31 +00006093#define ETSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006094 {NAME, offsetof(PyHeapTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
6095 PyDoc_STR(DOC)}
Guido van Rossum6d204072001-10-21 00:44:31 +00006096#define SQSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006097 ETSLOT(NAME, as_sequence.SLOT, FUNCTION, WRAPPER, DOC)
Guido van Rossum6d204072001-10-21 00:44:31 +00006098#define MPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006099 ETSLOT(NAME, as_mapping.SLOT, FUNCTION, WRAPPER, DOC)
Guido van Rossum6d204072001-10-21 00:44:31 +00006100#define NBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006101 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, DOC)
Guido van Rossum6d204072001-10-21 00:44:31 +00006102#define UNSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006103 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
Larry Hastings581ee362014-01-28 05:00:08 -08006104 "sig=($self)\n" DOC)
Guido van Rossum6d204072001-10-21 00:44:31 +00006105#define IBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006106 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
Larry Hastings581ee362014-01-28 05:00:08 -08006107 "sig=($self, value)\nReturn self" DOC "value.")
Guido van Rossum6d204072001-10-21 00:44:31 +00006108#define BINSLOT(NAME, SLOT, FUNCTION, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006109 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
Larry Hastings581ee362014-01-28 05:00:08 -08006110 "sig=($self, value)\nReturn self" DOC "value.")
Guido van Rossum6d204072001-10-21 00:44:31 +00006111#define RBINSLOT(NAME, SLOT, FUNCTION, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006112 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
Larry Hastings581ee362014-01-28 05:00:08 -08006113 "sig=($self, value)\nReturn value" DOC "self.")
Anthony Baxter56616992005-06-03 14:12:21 +00006114#define BINSLOTNOTINFIX(NAME, SLOT, FUNCTION, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006115 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
Larry Hastings581ee362014-01-28 05:00:08 -08006116 "sig=($self, value)\n" DOC)
Anthony Baxter56616992005-06-03 14:12:21 +00006117#define RBINSLOTNOTINFIX(NAME, SLOT, FUNCTION, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006118 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
Larry Hastings581ee362014-01-28 05:00:08 -08006119 "sig=($self, value)\n" DOC)
Guido van Rossum7b9144b2001-10-09 19:39:46 +00006120
6121static slotdef slotdefs[] = {
Benjamin Peterson63952412013-04-01 17:41:41 -04006122 TPSLOT("__getattribute__", tp_getattr, NULL, NULL, ""),
6123 TPSLOT("__getattr__", tp_getattr, NULL, NULL, ""),
6124 TPSLOT("__setattr__", tp_setattr, NULL, NULL, ""),
6125 TPSLOT("__delattr__", tp_setattr, NULL, NULL, ""),
6126 TPSLOT("__repr__", tp_repr, slot_tp_repr, wrap_unaryfunc,
Larry Hastings581ee362014-01-28 05:00:08 -08006127 "sig=($self)\nReturn repr(self)."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006128 TPSLOT("__hash__", tp_hash, slot_tp_hash, wrap_hashfunc,
Larry Hastings581ee362014-01-28 05:00:08 -08006129 "sig=($self)\nReturn hash(self)."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006130 FLSLOT("__call__", tp_call, slot_tp_call, (wrapperfunc)wrap_call,
Larry Hastings581ee362014-01-28 05:00:08 -08006131 "sig=($self, *args, **kwargs)\nCall self as a function.",
Larry Hastings5c661892014-01-24 06:17:25 -08006132 PyWrapperFlag_KEYWORDS),
Benjamin Peterson63952412013-04-01 17:41:41 -04006133 TPSLOT("__str__", tp_str, slot_tp_str, wrap_unaryfunc,
Larry Hastings581ee362014-01-28 05:00:08 -08006134 "sig=($self)\nReturn str(self)."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006135 TPSLOT("__getattribute__", tp_getattro, slot_tp_getattr_hook,
Larry Hastings5c661892014-01-24 06:17:25 -08006136 wrap_binaryfunc,
Larry Hastings581ee362014-01-28 05:00:08 -08006137 "sig=($self, name)\nReturn getattr(self, name)."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006138 TPSLOT("__getattr__", tp_getattro, slot_tp_getattr_hook, NULL, ""),
6139 TPSLOT("__setattr__", tp_setattro, slot_tp_setattro, wrap_setattr,
Larry Hastings581ee362014-01-28 05:00:08 -08006140 "sig=($self, name, value)\nImplement setattr(self, name, value)."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006141 TPSLOT("__delattr__", tp_setattro, slot_tp_setattro, wrap_delattr,
Larry Hastings581ee362014-01-28 05:00:08 -08006142 "sig=($self, name)\nImplement delattr(self, name)."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006143 TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare, richcmp_lt,
Larry Hastings581ee362014-01-28 05:00:08 -08006144 "sig=($self, value)\nReturn self<value."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006145 TPSLOT("__le__", tp_richcompare, slot_tp_richcompare, richcmp_le,
Larry Hastings581ee362014-01-28 05:00:08 -08006146 "sig=($self, value)\nReturn self<=value."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006147 TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare, richcmp_eq,
Larry Hastings581ee362014-01-28 05:00:08 -08006148 "sig=($self, value)\nReturn self==value."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006149 TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare, richcmp_ne,
Larry Hastings581ee362014-01-28 05:00:08 -08006150 "sig=($self, value)\nReturn self!=value."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006151 TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare, richcmp_gt,
Larry Hastings581ee362014-01-28 05:00:08 -08006152 "sig=($self, value)\nReturn self>value."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006153 TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare, richcmp_ge,
Larry Hastings581ee362014-01-28 05:00:08 -08006154 "sig=($self, value)\nReturn self>=value."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006155 TPSLOT("__iter__", tp_iter, slot_tp_iter, wrap_unaryfunc,
Larry Hastings581ee362014-01-28 05:00:08 -08006156 "sig=($self)\nImplement iter(self)."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006157 TPSLOT("__next__", tp_iternext, slot_tp_iternext, wrap_next,
Larry Hastings581ee362014-01-28 05:00:08 -08006158 "sig=($self)\nImplement next(self)."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006159 TPSLOT("__get__", tp_descr_get, slot_tp_descr_get, wrap_descr_get,
Larry Hastings581ee362014-01-28 05:00:08 -08006160 "sig=($self, instance, owner)\nReturn an attribute of instance, which is of type owner."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006161 TPSLOT("__set__", tp_descr_set, slot_tp_descr_set, wrap_descr_set,
Larry Hastings581ee362014-01-28 05:00:08 -08006162 "sig=($self, instance, value)\nSet an attribute of instance to value."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006163 TPSLOT("__delete__", tp_descr_set, slot_tp_descr_set,
Larry Hastings5c661892014-01-24 06:17:25 -08006164 wrap_descr_delete,
Larry Hastings581ee362014-01-28 05:00:08 -08006165 "sig=(instance)\nDelete an attribute of instance."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006166 FLSLOT("__init__", tp_init, slot_tp_init, (wrapperfunc)wrap_init,
Larry Hastings581ee362014-01-28 05:00:08 -08006167 "sig=($self, *args, **kwargs)\n"
6168 "Initialize self. See help(type(self)) for accurate signature.",
Benjamin Peterson63952412013-04-01 17:41:41 -04006169 PyWrapperFlag_KEYWORDS),
Larry Hastings5c661892014-01-24 06:17:25 -08006170 TPSLOT("__new__", tp_new, slot_tp_new, NULL,
Larry Hastings581ee362014-01-28 05:00:08 -08006171 "sig=(type, *args, **kwargs)\n"
6172 "Create and return new object. See help(type) for accurate signature."),
Antoine Pitrou796564c2013-07-30 19:59:21 +02006173 TPSLOT("__del__", tp_finalize, slot_tp_finalize, (wrapperfunc)wrap_del, ""),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00006174
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006175 BINSLOT("__add__", nb_add, slot_nb_add,
Larry Hastings5c661892014-01-24 06:17:25 -08006176 "+"),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006177 RBINSLOT("__radd__", nb_add, slot_nb_add,
Larry Hastings5c661892014-01-24 06:17:25 -08006178 "+"),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006179 BINSLOT("__sub__", nb_subtract, slot_nb_subtract,
Larry Hastings5c661892014-01-24 06:17:25 -08006180 "-"),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006181 RBINSLOT("__rsub__", nb_subtract, slot_nb_subtract,
Larry Hastings5c661892014-01-24 06:17:25 -08006182 "-"),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006183 BINSLOT("__mul__", nb_multiply, slot_nb_multiply,
Larry Hastings5c661892014-01-24 06:17:25 -08006184 "*"),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006185 RBINSLOT("__rmul__", nb_multiply, slot_nb_multiply,
Larry Hastings5c661892014-01-24 06:17:25 -08006186 "*"),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006187 BINSLOT("__mod__", nb_remainder, slot_nb_remainder,
Larry Hastings5c661892014-01-24 06:17:25 -08006188 "%"),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006189 RBINSLOT("__rmod__", nb_remainder, slot_nb_remainder,
Larry Hastings5c661892014-01-24 06:17:25 -08006190 "%"),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006191 BINSLOTNOTINFIX("__divmod__", nb_divmod, slot_nb_divmod,
Larry Hastings581ee362014-01-28 05:00:08 -08006192 "Return divmod(self, value)."),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006193 RBINSLOTNOTINFIX("__rdivmod__", nb_divmod, slot_nb_divmod,
Larry Hastings581ee362014-01-28 05:00:08 -08006194 "Return divmod(value, self)."),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006195 NBSLOT("__pow__", nb_power, slot_nb_power, wrap_ternaryfunc,
Larry Hastings581ee362014-01-28 05:00:08 -08006196 "sig=($self, value, mod=None)\nReturn pow(self, value, mod)."),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006197 NBSLOT("__rpow__", nb_power, slot_nb_power, wrap_ternaryfunc_r,
Larry Hastings581ee362014-01-28 05:00:08 -08006198 "sig=($self, value, mod=None)\nReturn pow(value, self, mod)."),
Larry Hastings5c661892014-01-24 06:17:25 -08006199 UNSLOT("__neg__", nb_negative, slot_nb_negative, wrap_unaryfunc, "-self"),
6200 UNSLOT("__pos__", nb_positive, slot_nb_positive, wrap_unaryfunc, "+self"),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006201 UNSLOT("__abs__", nb_absolute, slot_nb_absolute, wrap_unaryfunc,
Larry Hastings5c661892014-01-24 06:17:25 -08006202 "abs(self)"),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006203 UNSLOT("__bool__", nb_bool, slot_nb_bool, wrap_inquirypred,
Larry Hastings5c661892014-01-24 06:17:25 -08006204 "self != 0"),
6205 UNSLOT("__invert__", nb_invert, slot_nb_invert, wrap_unaryfunc, "~self"),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006206 BINSLOT("__lshift__", nb_lshift, slot_nb_lshift, "<<"),
6207 RBINSLOT("__rlshift__", nb_lshift, slot_nb_lshift, "<<"),
6208 BINSLOT("__rshift__", nb_rshift, slot_nb_rshift, ">>"),
6209 RBINSLOT("__rrshift__", nb_rshift, slot_nb_rshift, ">>"),
6210 BINSLOT("__and__", nb_and, slot_nb_and, "&"),
6211 RBINSLOT("__rand__", nb_and, slot_nb_and, "&"),
6212 BINSLOT("__xor__", nb_xor, slot_nb_xor, "^"),
6213 RBINSLOT("__rxor__", nb_xor, slot_nb_xor, "^"),
6214 BINSLOT("__or__", nb_or, slot_nb_or, "|"),
6215 RBINSLOT("__ror__", nb_or, slot_nb_or, "|"),
6216 UNSLOT("__int__", nb_int, slot_nb_int, wrap_unaryfunc,
Larry Hastings5c661892014-01-24 06:17:25 -08006217 "int(self)"),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006218 UNSLOT("__float__", nb_float, slot_nb_float, wrap_unaryfunc,
Larry Hastings5c661892014-01-24 06:17:25 -08006219 "float(self)"),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006220 IBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add,
Eli Benderskyd3baae72011-11-11 16:57:05 +02006221 wrap_binaryfunc, "+="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006222 IBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract,
Eli Benderskyd3baae72011-11-11 16:57:05 +02006223 wrap_binaryfunc, "-="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006224 IBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply,
Eli Benderskyd3baae72011-11-11 16:57:05 +02006225 wrap_binaryfunc, "*="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006226 IBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder,
Eli Benderskyd3baae72011-11-11 16:57:05 +02006227 wrap_binaryfunc, "%="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006228 IBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power,
Eli Benderskyd3baae72011-11-11 16:57:05 +02006229 wrap_binaryfunc, "**="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006230 IBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift,
Eli Benderskyd3baae72011-11-11 16:57:05 +02006231 wrap_binaryfunc, "<<="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006232 IBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift,
Eli Benderskyd3baae72011-11-11 16:57:05 +02006233 wrap_binaryfunc, ">>="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006234 IBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and,
Eli Benderskyd3baae72011-11-11 16:57:05 +02006235 wrap_binaryfunc, "&="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006236 IBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor,
Eli Benderskyd3baae72011-11-11 16:57:05 +02006237 wrap_binaryfunc, "^="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006238 IBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or,
Eli Benderskyd3baae72011-11-11 16:57:05 +02006239 wrap_binaryfunc, "|="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006240 BINSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
6241 RBINSLOT("__rfloordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
6242 BINSLOT("__truediv__", nb_true_divide, slot_nb_true_divide, "/"),
6243 RBINSLOT("__rtruediv__", nb_true_divide, slot_nb_true_divide, "/"),
6244 IBSLOT("__ifloordiv__", nb_inplace_floor_divide,
6245 slot_nb_inplace_floor_divide, wrap_binaryfunc, "//"),
6246 IBSLOT("__itruediv__", nb_inplace_true_divide,
6247 slot_nb_inplace_true_divide, wrap_binaryfunc, "/"),
Benjamin Peterson63952412013-04-01 17:41:41 -04006248 NBSLOT("__index__", nb_index, slot_nb_index, wrap_unaryfunc,
Larry Hastings581ee362014-01-28 05:00:08 -08006249 "sig=($self)\n"
6250 "Return self converted to an integer, if self is suitable"
Larry Hastings5c661892014-01-24 06:17:25 -08006251 "for use as an index into a list."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006252 MPSLOT("__len__", mp_length, slot_mp_length, wrap_lenfunc,
Larry Hastings581ee362014-01-28 05:00:08 -08006253 "sig=($self)\nReturn len(self)."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006254 MPSLOT("__getitem__", mp_subscript, slot_mp_subscript,
6255 wrap_binaryfunc,
Larry Hastings581ee362014-01-28 05:00:08 -08006256 "sig=($self, key)\nReturn self[key]."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006257 MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript,
6258 wrap_objobjargproc,
Larry Hastings581ee362014-01-28 05:00:08 -08006259 "sig=($self, key, value)\nSet self[key] to value."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006260 MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript,
6261 wrap_delitem,
Larry Hastings581ee362014-01-28 05:00:08 -08006262 "sig=(key)\nDelete self[key]."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006263
6264 SQSLOT("__len__", sq_length, slot_sq_length, wrap_lenfunc,
Larry Hastings581ee362014-01-28 05:00:08 -08006265 "sig=($self)\nReturn len(self)."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006266 /* Heap types defining __add__/__mul__ have sq_concat/sq_repeat == NULL.
6267 The logic in abstract.c always falls back to nb_add/nb_multiply in
6268 this case. Defining both the nb_* and the sq_* slots to call the
6269 user-defined methods has unexpected side-effects, as shown by
6270 test_descr.notimplemented() */
6271 SQSLOT("__add__", sq_concat, NULL, wrap_binaryfunc,
Larry Hastings581ee362014-01-28 05:00:08 -08006272 "sig=($self, value)\nReturn self+value."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006273 SQSLOT("__mul__", sq_repeat, NULL, wrap_indexargfunc,
Larry Hastings581ee362014-01-28 05:00:08 -08006274 "sig=($self, value)\nReturn self*value.n"),
Benjamin Peterson63952412013-04-01 17:41:41 -04006275 SQSLOT("__rmul__", sq_repeat, NULL, wrap_indexargfunc,
Larry Hastings581ee362014-01-28 05:00:08 -08006276 "sig=($self, value)\nReturn self*value."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006277 SQSLOT("__getitem__", sq_item, slot_sq_item, wrap_sq_item,
Larry Hastings581ee362014-01-28 05:00:08 -08006278 "sig=($self, key)\nReturn self[key]."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006279 SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_setitem,
Larry Hastings581ee362014-01-28 05:00:08 -08006280 "sig=($self, key, value)\nSet self[key] to value."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006281 SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_delitem,
Larry Hastings581ee362014-01-28 05:00:08 -08006282 "sig=($self, key)\nDelete self[key]."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006283 SQSLOT("__contains__", sq_contains, slot_sq_contains, wrap_objobjproc,
Larry Hastings581ee362014-01-28 05:00:08 -08006284 "sig=($self, key)\nReturn key in self."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006285 SQSLOT("__iadd__", sq_inplace_concat, NULL,
Larry Hastings5c661892014-01-24 06:17:25 -08006286 wrap_binaryfunc,
Larry Hastings581ee362014-01-28 05:00:08 -08006287 "sig=($self, value)\nImplement self+=value."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006288 SQSLOT("__imul__", sq_inplace_repeat, NULL,
Larry Hastings5c661892014-01-24 06:17:25 -08006289 wrap_indexargfunc,
Larry Hastings581ee362014-01-28 05:00:08 -08006290 "sig=($self, value)\nImplement self*=value."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006291
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006292 {NULL}
Guido van Rossum7b9144b2001-10-09 19:39:46 +00006293};
6294
Guido van Rossumc334df52002-04-04 23:44:47 +00006295/* Given a type pointer and an offset gotten from a slotdef entry, return a
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006296 pointer to the actual slot. This is not quite the same as simply adding
Guido van Rossumc334df52002-04-04 23:44:47 +00006297 the offset to the type pointer, since it takes care to indirect through the
6298 proper indirection pointer (as_buffer, etc.); it returns NULL if the
6299 indirection pointer is NULL. */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00006300static void **
Martin v. Löwis18e16552006-02-15 17:27:45 +00006301slotptr(PyTypeObject *type, int ioffset)
Guido van Rossum7b9144b2001-10-09 19:39:46 +00006302{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006303 char *ptr;
6304 long offset = ioffset;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00006305
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006306 /* Note: this depends on the order of the members of PyHeapTypeObject! */
6307 assert(offset >= 0);
6308 assert((size_t)offset < offsetof(PyHeapTypeObject, as_buffer));
6309 if ((size_t)offset >= offsetof(PyHeapTypeObject, as_sequence)) {
6310 ptr = (char *)type->tp_as_sequence;
6311 offset -= offsetof(PyHeapTypeObject, as_sequence);
6312 }
6313 else if ((size_t)offset >= offsetof(PyHeapTypeObject, as_mapping)) {
6314 ptr = (char *)type->tp_as_mapping;
6315 offset -= offsetof(PyHeapTypeObject, as_mapping);
6316 }
6317 else if ((size_t)offset >= offsetof(PyHeapTypeObject, as_number)) {
6318 ptr = (char *)type->tp_as_number;
6319 offset -= offsetof(PyHeapTypeObject, as_number);
6320 }
6321 else {
6322 ptr = (char *)type;
6323 }
6324 if (ptr != NULL)
6325 ptr += offset;
6326 return (void **)ptr;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00006327}
Guido van Rossumf040ede2001-08-07 16:40:56 +00006328
Guido van Rossumc334df52002-04-04 23:44:47 +00006329/* Length of array of slotdef pointers used to store slots with the
6330 same __name__. There should be at most MAX_EQUIV-1 slotdef entries with
6331 the same __name__, for any __name__. Since that's a static property, it is
6332 appropriate to declare fixed-size arrays for this. */
6333#define MAX_EQUIV 10
6334
6335/* Return a slot pointer for a given name, but ONLY if the attribute has
6336 exactly one slot function. The name must be an interned string. */
6337static void **
6338resolve_slotdups(PyTypeObject *type, PyObject *name)
6339{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006340 /* XXX Maybe this could be optimized more -- but is it worth it? */
Guido van Rossumc334df52002-04-04 23:44:47 +00006341
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006342 /* pname and ptrs act as a little cache */
6343 static PyObject *pname;
6344 static slotdef *ptrs[MAX_EQUIV];
6345 slotdef *p, **pp;
6346 void **res, **ptr;
Guido van Rossumc334df52002-04-04 23:44:47 +00006347
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006348 if (pname != name) {
6349 /* Collect all slotdefs that match name into ptrs. */
6350 pname = name;
6351 pp = ptrs;
6352 for (p = slotdefs; p->name_strobj; p++) {
6353 if (p->name_strobj == name)
6354 *pp++ = p;
6355 }
6356 *pp = NULL;
6357 }
Guido van Rossumc334df52002-04-04 23:44:47 +00006358
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006359 /* Look in all matching slots of the type; if exactly one of these has
6360 a filled-in slot, return its value. Otherwise return NULL. */
6361 res = NULL;
6362 for (pp = ptrs; *pp; pp++) {
6363 ptr = slotptr(type, (*pp)->offset);
6364 if (ptr == NULL || *ptr == NULL)
6365 continue;
6366 if (res != NULL)
6367 return NULL;
6368 res = ptr;
6369 }
6370 return res;
Guido van Rossumc334df52002-04-04 23:44:47 +00006371}
6372
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006373/* Common code for update_slots_callback() and fixup_slot_dispatchers(). This
Guido van Rossumc334df52002-04-04 23:44:47 +00006374 does some incredibly complex thinking and then sticks something into the
6375 slot. (It sees if the adjacent slotdefs for the same slot have conflicting
6376 interests, and then stores a generic wrapper or a specific function into
6377 the slot.) Return a pointer to the next slotdef with a different offset,
6378 because that's convenient for fixup_slot_dispatchers(). */
6379static slotdef *
6380update_one_slot(PyTypeObject *type, slotdef *p)
6381{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006382 PyObject *descr;
6383 PyWrapperDescrObject *d;
6384 void *generic = NULL, *specific = NULL;
6385 int use_generic = 0;
6386 int offset = p->offset;
6387 void **ptr = slotptr(type, offset);
Guido van Rossumc334df52002-04-04 23:44:47 +00006388
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006389 if (ptr == NULL) {
6390 do {
6391 ++p;
6392 } while (p->offset == offset);
6393 return p;
6394 }
6395 do {
6396 descr = _PyType_Lookup(type, p->name_strobj);
6397 if (descr == NULL) {
6398 if (ptr == (void**)&type->tp_iternext) {
Trent Nelsonab02db22012-09-18 21:58:03 -04006399 specific = (void *)_PyObject_NextNotImplemented;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006400 }
6401 continue;
6402 }
Benjamin Peterson7b166872012-04-24 11:06:25 -04006403 if (Py_TYPE(descr) == &PyWrapperDescr_Type &&
6404 ((PyWrapperDescrObject *)descr)->d_base->name_strobj == p->name_strobj) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006405 void **tptr = resolve_slotdups(type, p->name_strobj);
6406 if (tptr == NULL || tptr == ptr)
6407 generic = p->function;
6408 d = (PyWrapperDescrObject *)descr;
6409 if (d->d_base->wrapper == p->wrapper &&
6410 PyType_IsSubtype(type, PyDescr_TYPE(d)))
6411 {
6412 if (specific == NULL ||
6413 specific == d->d_wrapped)
6414 specific = d->d_wrapped;
6415 else
6416 use_generic = 1;
6417 }
6418 }
6419 else if (Py_TYPE(descr) == &PyCFunction_Type &&
6420 PyCFunction_GET_FUNCTION(descr) ==
6421 (PyCFunction)tp_new_wrapper &&
6422 ptr == (void**)&type->tp_new)
6423 {
6424 /* The __new__ wrapper is not a wrapper descriptor,
6425 so must be special-cased differently.
6426 If we don't do this, creating an instance will
6427 always use slot_tp_new which will look up
6428 __new__ in the MRO which will call tp_new_wrapper
6429 which will look through the base classes looking
6430 for a static base and call its tp_new (usually
6431 PyType_GenericNew), after performing various
6432 sanity checks and constructing a new argument
6433 list. Cut all that nonsense short -- this speeds
6434 up instance creation tremendously. */
6435 specific = (void *)type->tp_new;
6436 /* XXX I'm not 100% sure that there isn't a hole
6437 in this reasoning that requires additional
6438 sanity checks. I'll buy the first person to
6439 point out a bug in this reasoning a beer. */
6440 }
6441 else if (descr == Py_None &&
6442 ptr == (void**)&type->tp_hash) {
6443 /* We specifically allow __hash__ to be set to None
6444 to prevent inheritance of the default
6445 implementation from object.__hash__ */
Trent Nelsonab02db22012-09-18 21:58:03 -04006446 specific = (void *)PyObject_HashNotImplemented;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006447 }
6448 else {
6449 use_generic = 1;
6450 generic = p->function;
6451 }
6452 } while ((++p)->offset == offset);
6453 if (specific && !use_generic)
6454 *ptr = specific;
6455 else
6456 *ptr = generic;
6457 return p;
Guido van Rossumc334df52002-04-04 23:44:47 +00006458}
6459
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006460/* In the type, update the slots whose slotdefs are gathered in the pp array.
6461 This is a callback for update_subclasses(). */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006462static int
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006463update_slots_callback(PyTypeObject *type, void *data)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006464{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006465 slotdef **pp = (slotdef **)data;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006466
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006467 for (; *pp; pp++)
6468 update_one_slot(type, *pp);
6469 return 0;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006470}
6471
Guido van Rossumc334df52002-04-04 23:44:47 +00006472/* Initialize the slotdefs table by adding interned string objects for the
6473 names and sorting the entries. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006474static void
Guido van Rossumd396b9c2001-10-13 20:02:41 +00006475init_slotdefs(void)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006476{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006477 slotdef *p;
6478 static int initialized = 0;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006479
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006480 if (initialized)
6481 return;
6482 for (p = slotdefs; p->name; p++) {
Benjamin Peterson63952412013-04-01 17:41:41 -04006483 /* Slots must be ordered by their offset in the PyHeapTypeObject. */
6484 assert(!p[1].name || p->offset <= p[1].offset);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006485 p->name_strobj = PyUnicode_InternFromString(p->name);
6486 if (!p->name_strobj)
6487 Py_FatalError("Out of memory interning slotdef names");
6488 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006489 initialized = 1;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006490}
6491
Guido van Rossumc334df52002-04-04 23:44:47 +00006492/* Update the slots after assignment to a class (type) attribute. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006493static int
6494update_slot(PyTypeObject *type, PyObject *name)
6495{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006496 slotdef *ptrs[MAX_EQUIV];
6497 slotdef *p;
6498 slotdef **pp;
6499 int offset;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006500
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006501 /* Clear the VALID_VERSION flag of 'type' and all its
6502 subclasses. This could possibly be unified with the
6503 update_subclasses() recursion below, but carefully:
6504 they each have their own conditions on which to stop
6505 recursing into subclasses. */
6506 PyType_Modified(type);
Christian Heimesa62da1d2008-01-12 19:39:10 +00006507
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006508 init_slotdefs();
6509 pp = ptrs;
6510 for (p = slotdefs; p->name; p++) {
6511 /* XXX assume name is interned! */
6512 if (p->name_strobj == name)
6513 *pp++ = p;
6514 }
6515 *pp = NULL;
6516 for (pp = ptrs; *pp; pp++) {
6517 p = *pp;
6518 offset = p->offset;
6519 while (p > slotdefs && (p-1)->offset == offset)
6520 --p;
6521 *pp = p;
6522 }
6523 if (ptrs[0] == NULL)
6524 return 0; /* Not an attribute that affects any slots */
6525 return update_subclasses(type, name,
6526 update_slots_callback, (void *)ptrs);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006527}
6528
Guido van Rossumc334df52002-04-04 23:44:47 +00006529/* Store the proper functions in the slot dispatches at class (type)
6530 definition time, based upon which operations the class overrides in its
6531 dict. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00006532static void
Guido van Rossum7b9144b2001-10-09 19:39:46 +00006533fixup_slot_dispatchers(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00006534{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006535 slotdef *p;
Tim Peters6d6c1a32001-08-02 04:15:00 +00006536
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006537 init_slotdefs();
6538 for (p = slotdefs; p->name; )
6539 p = update_one_slot(type, p);
Tim Peters6d6c1a32001-08-02 04:15:00 +00006540}
Guido van Rossum705f0f52001-08-24 16:47:00 +00006541
Michael W. Hudson98bbc492002-11-26 14:47:27 +00006542static void
6543update_all_slots(PyTypeObject* type)
6544{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006545 slotdef *p;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00006546
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006547 init_slotdefs();
6548 for (p = slotdefs; p->name; p++) {
6549 /* update_slot returns int but can't actually fail */
6550 update_slot(type, p->name_strobj);
6551 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +00006552}
6553
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006554/* recurse_down_subclasses() and update_subclasses() are mutually
6555 recursive functions to call a callback for all subclasses,
6556 but refraining from recursing into subclasses that define 'name'. */
6557
6558static int
6559update_subclasses(PyTypeObject *type, PyObject *name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006560 update_callback callback, void *data)
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006561{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006562 if (callback(type, data) < 0)
6563 return -1;
6564 return recurse_down_subclasses(type, name, callback, data);
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006565}
6566
6567static int
6568recurse_down_subclasses(PyTypeObject *type, PyObject *name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006569 update_callback callback, void *data)
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006570{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006571 PyTypeObject *subclass;
6572 PyObject *ref, *subclasses, *dict;
Antoine Pitrou84745ab2013-10-29 21:31:25 +01006573 Py_ssize_t i;
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006574
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006575 subclasses = type->tp_subclasses;
6576 if (subclasses == NULL)
6577 return 0;
Antoine Pitrou84745ab2013-10-29 21:31:25 +01006578 assert(PyDict_CheckExact(subclasses));
6579 i = 0;
6580 while (PyDict_Next(subclasses, &i, NULL, &ref)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006581 assert(PyWeakref_CheckRef(ref));
6582 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
6583 assert(subclass != NULL);
6584 if ((PyObject *)subclass == Py_None)
6585 continue;
6586 assert(PyType_Check(subclass));
6587 /* Avoid recursing down into unaffected classes */
6588 dict = subclass->tp_dict;
6589 if (dict != NULL && PyDict_Check(dict) &&
6590 PyDict_GetItem(dict, name) != NULL)
6591 continue;
6592 if (update_subclasses(subclass, name, callback, data) < 0)
6593 return -1;
6594 }
6595 return 0;
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006596}
6597
Guido van Rossum6d204072001-10-21 00:44:31 +00006598/* This function is called by PyType_Ready() to populate the type's
6599 dictionary with method descriptors for function slots. For each
Guido van Rossum09638c12002-06-13 19:17:46 +00006600 function slot (like tp_repr) that's defined in the type, one or more
6601 corresponding descriptors are added in the type's tp_dict dictionary
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006602 under the appropriate name (like __repr__). Some function slots
Guido van Rossum09638c12002-06-13 19:17:46 +00006603 cause more than one descriptor to be added (for example, the nb_add
6604 slot adds both __add__ and __radd__ descriptors) and some function
6605 slots compete for the same descriptor (for example both sq_item and
6606 mp_subscript generate a __getitem__ descriptor).
6607
Ezio Melotti13925002011-03-16 11:05:33 +02006608 In the latter case, the first slotdef entry encountered wins. Since
Tim Petersbf9b2442003-03-23 05:35:36 +00006609 slotdef entries are sorted by the offset of the slot in the
Guido van Rossume5c691a2003-03-07 15:13:17 +00006610 PyHeapTypeObject, this gives us some control over disambiguating
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006611 between competing slots: the members of PyHeapTypeObject are listed
6612 from most general to least general, so the most general slot is
6613 preferred. In particular, because as_mapping comes before as_sequence,
6614 for a type that defines both mp_subscript and sq_item, mp_subscript
6615 wins.
Guido van Rossum09638c12002-06-13 19:17:46 +00006616
6617 This only adds new descriptors and doesn't overwrite entries in
6618 tp_dict that were previously defined. The descriptors contain a
6619 reference to the C function they must call, so that it's safe if they
6620 are copied into a subtype's __dict__ and the subtype has a different
6621 C function in its slot -- calling the method defined by the
6622 descriptor will call the C function that was used to create it,
6623 rather than the C function present in the slot when it is called.
6624 (This is important because a subtype may have a C function in the
6625 slot that calls the method from the dictionary, and we want to avoid
6626 infinite recursion here.) */
Guido van Rossum6d204072001-10-21 00:44:31 +00006627
6628static int
6629add_operators(PyTypeObject *type)
6630{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006631 PyObject *dict = type->tp_dict;
6632 slotdef *p;
6633 PyObject *descr;
6634 void **ptr;
Guido van Rossum6d204072001-10-21 00:44:31 +00006635
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006636 init_slotdefs();
6637 for (p = slotdefs; p->name; p++) {
6638 if (p->wrapper == NULL)
6639 continue;
6640 ptr = slotptr(type, p->offset);
6641 if (!ptr || !*ptr)
6642 continue;
6643 if (PyDict_GetItem(dict, p->name_strobj))
6644 continue;
Trent Nelsonab02db22012-09-18 21:58:03 -04006645 if (*ptr == (void *)PyObject_HashNotImplemented) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006646 /* Classes may prevent the inheritance of the tp_hash
6647 slot by storing PyObject_HashNotImplemented in it. Make it
6648 visible as a None value for the __hash__ attribute. */
6649 if (PyDict_SetItem(dict, p->name_strobj, Py_None) < 0)
6650 return -1;
6651 }
6652 else {
6653 descr = PyDescr_NewWrapper(type, p, *ptr);
6654 if (descr == NULL)
6655 return -1;
6656 if (PyDict_SetItem(dict, p->name_strobj, descr) < 0)
6657 return -1;
6658 Py_DECREF(descr);
6659 }
6660 }
6661 if (type->tp_new != NULL) {
6662 if (add_tp_new_wrapper(type) < 0)
6663 return -1;
6664 }
6665 return 0;
Guido van Rossum6d204072001-10-21 00:44:31 +00006666}
6667
Guido van Rossum705f0f52001-08-24 16:47:00 +00006668
6669/* Cooperative 'super' */
6670
6671typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006672 PyObject_HEAD
6673 PyTypeObject *type;
6674 PyObject *obj;
6675 PyTypeObject *obj_type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006676} superobject;
6677
Guido van Rossum6f799372001-09-20 20:46:19 +00006678static PyMemberDef super_members[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006679 {"__thisclass__", T_OBJECT, offsetof(superobject, type), READONLY,
6680 "the class invoking super()"},
6681 {"__self__", T_OBJECT, offsetof(superobject, obj), READONLY,
6682 "the instance invoking super(); may be None"},
6683 {"__self_class__", T_OBJECT, offsetof(superobject, obj_type), READONLY,
6684 "the type of the instance invoking super(); may be None"},
6685 {0}
Guido van Rossum41eb14d2001-08-30 23:13:11 +00006686};
6687
Guido van Rossum705f0f52001-08-24 16:47:00 +00006688static void
6689super_dealloc(PyObject *self)
6690{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006691 superobject *su = (superobject *)self;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006692
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006693 _PyObject_GC_UNTRACK(self);
6694 Py_XDECREF(su->obj);
6695 Py_XDECREF(su->type);
6696 Py_XDECREF(su->obj_type);
6697 Py_TYPE(self)->tp_free(self);
Guido van Rossum705f0f52001-08-24 16:47:00 +00006698}
6699
6700static PyObject *
Guido van Rossum41eb14d2001-08-30 23:13:11 +00006701super_repr(PyObject *self)
6702{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006703 superobject *su = (superobject *)self;
Guido van Rossum41eb14d2001-08-30 23:13:11 +00006704
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006705 if (su->obj_type)
6706 return PyUnicode_FromFormat(
6707 "<super: <class '%s'>, <%s object>>",
6708 su->type ? su->type->tp_name : "NULL",
6709 su->obj_type->tp_name);
6710 else
6711 return PyUnicode_FromFormat(
6712 "<super: <class '%s'>, NULL>",
6713 su->type ? su->type->tp_name : "NULL");
Guido van Rossum41eb14d2001-08-30 23:13:11 +00006714}
6715
6716static PyObject *
Guido van Rossum705f0f52001-08-24 16:47:00 +00006717super_getattro(PyObject *self, PyObject *name)
6718{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006719 superobject *su = (superobject *)self;
6720 int skip = su->obj_type == NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006721
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006722 if (!skip) {
6723 /* We want __class__ to return the class of the super object
6724 (i.e. super, or a subclass), not the class of su->obj. */
6725 skip = (PyUnicode_Check(name) &&
Victor Stinnerad14ccd2013-11-07 00:46:04 +01006726 PyUnicode_GET_LENGTH(name) == 9 &&
6727 _PyUnicode_CompareWithId(name, &PyId___class__) == 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006728 }
Guido van Rossum76ba09f2003-04-16 19:40:58 +00006729
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006730 if (!skip) {
6731 PyObject *mro, *res, *tmp, *dict;
6732 PyTypeObject *starttype;
6733 descrgetfunc f;
6734 Py_ssize_t i, n;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006735
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006736 starttype = su->obj_type;
6737 mro = starttype->tp_mro;
Guido van Rossum155db9a2002-04-02 17:53:47 +00006738
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006739 if (mro == NULL)
6740 n = 0;
6741 else {
6742 assert(PyTuple_Check(mro));
6743 n = PyTuple_GET_SIZE(mro);
6744 }
6745 for (i = 0; i < n; i++) {
6746 if ((PyObject *)(su->type) == PyTuple_GET_ITEM(mro, i))
6747 break;
6748 }
6749 i++;
6750 res = NULL;
Victor Stinnerd74782b2012-03-09 00:39:08 +01006751 /* keep a strong reference to mro because starttype->tp_mro can be
6752 replaced during PyDict_GetItem(dict, name) */
6753 Py_INCREF(mro);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006754 for (; i < n; i++) {
6755 tmp = PyTuple_GET_ITEM(mro, i);
6756 if (PyType_Check(tmp))
6757 dict = ((PyTypeObject *)tmp)->tp_dict;
6758 else
6759 continue;
6760 res = PyDict_GetItem(dict, name);
6761 if (res != NULL) {
6762 Py_INCREF(res);
6763 f = Py_TYPE(res)->tp_descr_get;
6764 if (f != NULL) {
6765 tmp = f(res,
6766 /* Only pass 'obj' param if
6767 this is instance-mode super
6768 (See SF ID #743627)
6769 */
6770 (su->obj == (PyObject *)
6771 su->obj_type
6772 ? (PyObject *)NULL
6773 : su->obj),
6774 (PyObject *)starttype);
6775 Py_DECREF(res);
6776 res = tmp;
6777 }
Victor Stinnerd74782b2012-03-09 00:39:08 +01006778 Py_DECREF(mro);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006779 return res;
6780 }
6781 }
Victor Stinnerd74782b2012-03-09 00:39:08 +01006782 Py_DECREF(mro);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006783 }
6784 return PyObject_GenericGetAttr(self, name);
Guido van Rossum705f0f52001-08-24 16:47:00 +00006785}
6786
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006787static PyTypeObject *
Guido van Rossum5b443c62001-12-03 15:38:28 +00006788supercheck(PyTypeObject *type, PyObject *obj)
6789{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006790 /* Check that a super() call makes sense. Return a type object.
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006791
Florent Xiclunaaa6c1d22011-12-12 18:54:29 +01006792 obj can be a class, or an instance of one:
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006793
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006794 - If it is a class, it must be a subclass of 'type'. This case is
6795 used for class methods; the return value is obj.
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006796
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006797 - If it is an instance, it must be an instance of 'type'. This is
6798 the normal case; the return value is obj.__class__.
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006799
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006800 But... when obj is an instance, we want to allow for the case where
6801 Py_TYPE(obj) is not a subclass of type, but obj.__class__ is!
6802 This will allow using super() with a proxy for obj.
6803 */
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006804
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006805 /* Check for first bullet above (special case) */
6806 if (PyType_Check(obj) && PyType_IsSubtype((PyTypeObject *)obj, type)) {
6807 Py_INCREF(obj);
6808 return (PyTypeObject *)obj;
6809 }
Guido van Rossum8e80a722003-02-18 19:22:22 +00006810
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006811 /* Normal case */
6812 if (PyType_IsSubtype(Py_TYPE(obj), type)) {
6813 Py_INCREF(Py_TYPE(obj));
6814 return Py_TYPE(obj);
6815 }
6816 else {
6817 /* Try the slow way */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006818 PyObject *class_attr;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006819
Martin v. Löwisbfc6d742011-10-13 20:03:57 +02006820 class_attr = _PyObject_GetAttrId(obj, &PyId___class__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006821 if (class_attr != NULL &&
6822 PyType_Check(class_attr) &&
6823 (PyTypeObject *)class_attr != Py_TYPE(obj))
6824 {
6825 int ok = PyType_IsSubtype(
6826 (PyTypeObject *)class_attr, type);
6827 if (ok)
6828 return (PyTypeObject *)class_attr;
6829 }
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006830
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006831 if (class_attr == NULL)
6832 PyErr_Clear();
6833 else
6834 Py_DECREF(class_attr);
6835 }
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006836
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006837 PyErr_SetString(PyExc_TypeError,
6838 "super(type, obj): "
6839 "obj must be an instance or subtype of type");
6840 return NULL;
Guido van Rossum5b443c62001-12-03 15:38:28 +00006841}
6842
Guido van Rossum705f0f52001-08-24 16:47:00 +00006843static PyObject *
6844super_descr_get(PyObject *self, PyObject *obj, PyObject *type)
6845{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006846 superobject *su = (superobject *)self;
6847 superobject *newobj;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006848
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006849 if (obj == NULL || obj == Py_None || su->obj != NULL) {
6850 /* Not binding to an object, or already bound */
6851 Py_INCREF(self);
6852 return self;
6853 }
6854 if (Py_TYPE(su) != &PySuper_Type)
6855 /* If su is an instance of a (strict) subclass of super,
6856 call its type */
6857 return PyObject_CallFunctionObjArgs((PyObject *)Py_TYPE(su),
6858 su->type, obj, NULL);
6859 else {
6860 /* Inline the common case */
6861 PyTypeObject *obj_type = supercheck(su->type, obj);
6862 if (obj_type == NULL)
6863 return NULL;
6864 newobj = (superobject *)PySuper_Type.tp_new(&PySuper_Type,
6865 NULL, NULL);
6866 if (newobj == NULL)
6867 return NULL;
6868 Py_INCREF(su->type);
6869 Py_INCREF(obj);
6870 newobj->type = su->type;
6871 newobj->obj = obj;
6872 newobj->obj_type = obj_type;
6873 return (PyObject *)newobj;
6874 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00006875}
6876
6877static int
6878super_init(PyObject *self, PyObject *args, PyObject *kwds)
6879{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006880 superobject *su = (superobject *)self;
6881 PyTypeObject *type = NULL;
6882 PyObject *obj = NULL;
6883 PyTypeObject *obj_type = NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006884
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006885 if (!_PyArg_NoKeywords("super", kwds))
6886 return -1;
6887 if (!PyArg_ParseTuple(args, "|O!O:super", &PyType_Type, &type, &obj))
6888 return -1;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00006889
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006890 if (type == NULL) {
6891 /* Call super(), without args -- fill in from __class__
6892 and first local variable on the stack. */
6893 PyFrameObject *f = PyThreadState_GET()->frame;
6894 PyCodeObject *co = f->f_code;
Victor Stinner0fcab4a2011-01-04 12:59:15 +00006895 Py_ssize_t i, n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006896 if (co == NULL) {
Benjamin Peterson6a42bd62012-09-01 23:04:38 -04006897 PyErr_SetString(PyExc_RuntimeError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006898 "super(): no code object");
6899 return -1;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00006900 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006901 if (co->co_argcount == 0) {
Benjamin Peterson6a42bd62012-09-01 23:04:38 -04006902 PyErr_SetString(PyExc_RuntimeError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006903 "super(): no arguments");
6904 return -1;
6905 }
6906 obj = f->f_localsplus[0];
Benjamin Peterson159ae412013-05-12 18:16:06 -05006907 if (obj == NULL && co->co_cell2arg) {
6908 /* The first argument might be a cell. */
6909 n = PyTuple_GET_SIZE(co->co_cellvars);
6910 for (i = 0; i < n; i++) {
6911 if (co->co_cell2arg[i] == 0) {
6912 PyObject *cell = f->f_localsplus[co->co_nlocals + i];
6913 assert(PyCell_Check(cell));
6914 obj = PyCell_GET(cell);
6915 break;
6916 }
6917 }
Guido van Rossum6832c812013-05-10 08:47:42 -07006918 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006919 if (obj == NULL) {
Benjamin Peterson6a42bd62012-09-01 23:04:38 -04006920 PyErr_SetString(PyExc_RuntimeError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006921 "super(): arg[0] deleted");
6922 return -1;
6923 }
6924 if (co->co_freevars == NULL)
6925 n = 0;
6926 else {
6927 assert(PyTuple_Check(co->co_freevars));
6928 n = PyTuple_GET_SIZE(co->co_freevars);
6929 }
6930 for (i = 0; i < n; i++) {
6931 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
6932 assert(PyUnicode_Check(name));
Victor Stinnerad14ccd2013-11-07 00:46:04 +01006933 if (!_PyUnicode_CompareWithId(name, &PyId___class__)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006934 Py_ssize_t index = co->co_nlocals +
6935 PyTuple_GET_SIZE(co->co_cellvars) + i;
6936 PyObject *cell = f->f_localsplus[index];
6937 if (cell == NULL || !PyCell_Check(cell)) {
Benjamin Peterson6a42bd62012-09-01 23:04:38 -04006938 PyErr_SetString(PyExc_RuntimeError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006939 "super(): bad __class__ cell");
6940 return -1;
6941 }
6942 type = (PyTypeObject *) PyCell_GET(cell);
6943 if (type == NULL) {
Benjamin Peterson6a42bd62012-09-01 23:04:38 -04006944 PyErr_SetString(PyExc_RuntimeError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006945 "super(): empty __class__ cell");
6946 return -1;
6947 }
6948 if (!PyType_Check(type)) {
Benjamin Peterson6a42bd62012-09-01 23:04:38 -04006949 PyErr_Format(PyExc_RuntimeError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006950 "super(): __class__ is not a type (%s)",
6951 Py_TYPE(type)->tp_name);
6952 return -1;
6953 }
6954 break;
6955 }
6956 }
6957 if (type == NULL) {
Benjamin Peterson6a42bd62012-09-01 23:04:38 -04006958 PyErr_SetString(PyExc_RuntimeError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006959 "super(): __class__ cell not found");
6960 return -1;
6961 }
6962 }
Guido van Rossumcd16bf62007-06-13 18:07:49 +00006963
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006964 if (obj == Py_None)
6965 obj = NULL;
6966 if (obj != NULL) {
6967 obj_type = supercheck(type, obj);
6968 if (obj_type == NULL)
6969 return -1;
6970 Py_INCREF(obj);
6971 }
6972 Py_INCREF(type);
6973 su->type = type;
6974 su->obj = obj;
6975 su->obj_type = obj_type;
6976 return 0;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006977}
6978
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00006979PyDoc_STRVAR(super_doc,
Guido van Rossumcd16bf62007-06-13 18:07:49 +00006980"super() -> same as super(__class__, <first argument>)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00006981"super(type) -> unbound super object\n"
6982"super(type, obj) -> bound super object; requires isinstance(obj, type)\n"
Guido van Rossume705ef12001-08-29 15:47:06 +00006983"super(type, type2) -> bound super object; requires issubclass(type2, type)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00006984"Typical use to call a cooperative superclass method:\n"
6985"class C(B):\n"
6986" def meth(self, arg):\n"
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006987" super().meth(arg)\n"
Guido van Rossumcd16bf62007-06-13 18:07:49 +00006988"This works for class methods too:\n"
6989"class C(B):\n"
6990" @classmethod\n"
6991" def cmeth(cls, arg):\n"
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006992" super().cmeth(arg)\n");
Guido van Rossum705f0f52001-08-24 16:47:00 +00006993
Guido van Rossum048eb752001-10-02 21:24:57 +00006994static int
6995super_traverse(PyObject *self, visitproc visit, void *arg)
6996{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006997 superobject *su = (superobject *)self;
Guido van Rossum048eb752001-10-02 21:24:57 +00006998
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006999 Py_VISIT(su->obj);
7000 Py_VISIT(su->type);
7001 Py_VISIT(su->obj_type);
Guido van Rossum048eb752001-10-02 21:24:57 +00007002
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007003 return 0;
Guido van Rossum048eb752001-10-02 21:24:57 +00007004}
7005
Guido van Rossum705f0f52001-08-24 16:47:00 +00007006PyTypeObject PySuper_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007007 PyVarObject_HEAD_INIT(&PyType_Type, 0)
7008 "super", /* tp_name */
7009 sizeof(superobject), /* tp_basicsize */
7010 0, /* tp_itemsize */
7011 /* methods */
7012 super_dealloc, /* tp_dealloc */
7013 0, /* tp_print */
7014 0, /* tp_getattr */
7015 0, /* tp_setattr */
7016 0, /* tp_reserved */
7017 super_repr, /* tp_repr */
7018 0, /* tp_as_number */
7019 0, /* tp_as_sequence */
7020 0, /* tp_as_mapping */
7021 0, /* tp_hash */
7022 0, /* tp_call */
7023 0, /* tp_str */
7024 super_getattro, /* tp_getattro */
7025 0, /* tp_setattro */
7026 0, /* tp_as_buffer */
7027 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
7028 Py_TPFLAGS_BASETYPE, /* tp_flags */
7029 super_doc, /* tp_doc */
7030 super_traverse, /* tp_traverse */
7031 0, /* tp_clear */
7032 0, /* tp_richcompare */
7033 0, /* tp_weaklistoffset */
7034 0, /* tp_iter */
7035 0, /* tp_iternext */
7036 0, /* tp_methods */
7037 super_members, /* tp_members */
7038 0, /* tp_getset */
7039 0, /* tp_base */
7040 0, /* tp_dict */
7041 super_descr_get, /* tp_descr_get */
7042 0, /* tp_descr_set */
7043 0, /* tp_dictoffset */
7044 super_init, /* tp_init */
7045 PyType_GenericAlloc, /* tp_alloc */
7046 PyType_GenericNew, /* tp_new */
7047 PyObject_GC_Del, /* tp_free */
Guido van Rossum705f0f52001-08-24 16:47:00 +00007048};