blob: 1dd534866b4d65c27e9f37cc9e3fd905fb1e958c [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"
Eric Snow2ebc5ce2017-09-07 23:51:28 -06004#include "internal/pystate.h"
Guido van Rossumcd16bf62007-06-13 18:07:49 +00005#include "frameobject.h"
Tim Peters6d6c1a32001-08-02 04:15:00 +00006#include "structmember.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00007
Guido van Rossum9923ffe2002-06-04 19:52:53 +00008#include <ctype.h>
9
Serhiy Storchaka5c643a02017-03-19 08:46:44 +020010/*[clinic input]
11class type "PyTypeObject *" "&PyType_Type"
12class object "PyObject *" "&PyBaseObject_Type"
13[clinic start generated code]*/
14/*[clinic end generated code: output=da39a3ee5e6b4b0d input=4b94608d231c434b]*/
15
16#include "clinic/typeobject.c.h"
Christian Heimesa62da1d2008-01-12 19:39:10 +000017
18/* Support type attribute cache */
19
20/* The cache can keep references to the names alive for longer than
21 they normally would. This is why the maximum size is limited to
22 MCACHE_MAX_ATTR_SIZE, since it might be a problem if very large
23 strings are used as attribute names. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000024#define MCACHE_MAX_ATTR_SIZE 100
Antoine Pitrou2a40e362014-11-15 00:56:27 +010025#define MCACHE_SIZE_EXP 12
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000026#define MCACHE_HASH(version, name_hash) \
Antoine Pitrou2a40e362014-11-15 00:56:27 +010027 (((unsigned int)(version) ^ (unsigned int)(name_hash)) \
28 & ((1 << MCACHE_SIZE_EXP) - 1))
29
Christian Heimesa62da1d2008-01-12 19:39:10 +000030#define MCACHE_HASH_METHOD(type, name) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000031 MCACHE_HASH((type)->tp_version_tag, \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020032 ((PyASCIIObject *)(name))->hash)
Serhiy Storchakae3b2b4b2017-09-08 09:58:51 +030033#define MCACHE_CACHEABLE_NAME(name) \
34 PyUnicode_CheckExact(name) && \
35 PyUnicode_IS_READY(name) && \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020036 PyUnicode_GET_LENGTH(name) <= MCACHE_MAX_ATTR_SIZE
Christian Heimesa62da1d2008-01-12 19:39:10 +000037
38struct method_cache_entry {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000039 unsigned int version;
40 PyObject *name; /* reference to exactly a str or None */
41 PyObject *value; /* borrowed */
Christian Heimesa62da1d2008-01-12 19:39:10 +000042};
43
44static struct method_cache_entry method_cache[1 << MCACHE_SIZE_EXP];
45static unsigned int next_version_tag = 0;
Christian Heimes26855632008-01-27 23:50:43 +000046
Antoine Pitrou2a40e362014-11-15 00:56:27 +010047#define MCACHE_STATS 0
48
49#if MCACHE_STATS
50static size_t method_cache_hits = 0;
51static size_t method_cache_misses = 0;
52static size_t method_cache_collisions = 0;
53#endif
54
Martin v. Löwise75fc142013-11-07 18:46:53 +010055/* alphabetical order */
56_Py_IDENTIFIER(__abstractmethods__);
Martin v. Löwisbd928fe2011-10-14 10:20:37 +020057_Py_IDENTIFIER(__class__);
Serhiy Storchakace5b0e92018-01-05 00:21:41 +020058_Py_IDENTIFIER(__class_getitem__);
Martin v. Löwise75fc142013-11-07 18:46:53 +010059_Py_IDENTIFIER(__delitem__);
Victor Stinner3c1e4812012-03-26 22:10:51 +020060_Py_IDENTIFIER(__dict__);
61_Py_IDENTIFIER(__doc__);
Victor Stinner3c1e4812012-03-26 22:10:51 +020062_Py_IDENTIFIER(__getattribute__);
Martin v. Löwise75fc142013-11-07 18:46:53 +010063_Py_IDENTIFIER(__getitem__);
Victor Stinner3c1e4812012-03-26 22:10:51 +020064_Py_IDENTIFIER(__hash__);
Nick Coghland78448e2016-07-30 16:26:03 +100065_Py_IDENTIFIER(__init_subclass__);
Martin v. Löwise75fc142013-11-07 18:46:53 +010066_Py_IDENTIFIER(__len__);
Victor Stinner3c1e4812012-03-26 22:10:51 +020067_Py_IDENTIFIER(__module__);
68_Py_IDENTIFIER(__name__);
69_Py_IDENTIFIER(__new__);
Nick Coghland78448e2016-07-30 16:26:03 +100070_Py_IDENTIFIER(__set_name__);
Martin v. Löwise75fc142013-11-07 18:46:53 +010071_Py_IDENTIFIER(__setitem__);
Victor Stinnerbd303c12013-11-07 23:07:29 +010072_Py_IDENTIFIER(builtins);
Victor Stinner3c1e4812012-03-26 22:10:51 +020073
74static PyObject *
Martin v. Löwis9c564092012-06-23 23:20:45 +020075slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
76
Martin v. Löwis996b6712014-07-26 16:44:07 +020077static void
Victor Stinner331a7262014-07-27 16:11:30 +020078clear_slotdefs(void);
Martin v. Löwis996b6712014-07-26 16:44:07 +020079
Larry Hastings5c661892014-01-24 06:17:25 -080080/*
Larry Hastings2623c8c2014-02-08 22:15:29 -080081 * finds the beginning of the docstring's introspection signature.
Larry Hastings5c661892014-01-24 06:17:25 -080082 * if present, returns a pointer pointing to the first '('.
83 * otherwise returns NULL.
Larry Hastings2623c8c2014-02-08 22:15:29 -080084 *
85 * doesn't guarantee that the signature is valid, only that it
86 * has a valid prefix. (the signature must also pass skip_signature.)
Larry Hastings5c661892014-01-24 06:17:25 -080087 */
88static const char *
Larry Hastings2623c8c2014-02-08 22:15:29 -080089find_signature(const char *name, const char *doc)
Larry Hastings5c661892014-01-24 06:17:25 -080090{
Larry Hastings2623c8c2014-02-08 22:15:29 -080091 const char *dot;
92 size_t length;
93
94 if (!doc)
95 return NULL;
96
97 assert(name != NULL);
98
99 /* for dotted names like classes, only use the last component */
100 dot = strrchr(name, '.');
101 if (dot)
102 name = dot + 1;
103
104 length = strlen(name);
105 if (strncmp(doc, name, length))
106 return NULL;
107 doc += length;
108 if (*doc != '(')
109 return NULL;
110 return doc;
Larry Hastings5c661892014-01-24 06:17:25 -0800111}
112
Larry Hastings2623c8c2014-02-08 22:15:29 -0800113#define SIGNATURE_END_MARKER ")\n--\n\n"
114#define SIGNATURE_END_MARKER_LENGTH 6
Larry Hastings5c661892014-01-24 06:17:25 -0800115/*
Larry Hastings2623c8c2014-02-08 22:15:29 -0800116 * skips past the end of the docstring's instrospection signature.
117 * (assumes doc starts with a valid signature prefix.)
Larry Hastings5c661892014-01-24 06:17:25 -0800118 */
119static const char *
120skip_signature(const char *doc)
121{
Larry Hastings2623c8c2014-02-08 22:15:29 -0800122 while (*doc) {
123 if ((*doc == *SIGNATURE_END_MARKER) &&
124 !strncmp(doc, SIGNATURE_END_MARKER, SIGNATURE_END_MARKER_LENGTH))
125 return doc + SIGNATURE_END_MARKER_LENGTH;
126 if ((*doc == '\n') && (doc[1] == '\n'))
127 return NULL;
Larry Hastings5c661892014-01-24 06:17:25 -0800128 doc++;
Larry Hastings2623c8c2014-02-08 22:15:29 -0800129 }
130 return NULL;
Larry Hastings5c661892014-01-24 06:17:25 -0800131}
132
T. Woutersa00c3fd2017-03-31 09:14:41 -0700133#ifndef NDEBUG
Victor Stinnerbda5a2b2017-01-25 23:33:27 +0100134static int
135_PyType_CheckConsistency(PyTypeObject *type)
136{
137 if (!(type->tp_flags & Py_TPFLAGS_READY)) {
138 /* don't check types before PyType_Ready() */
139 return 1;
140 }
141
142 assert(!(type->tp_flags & Py_TPFLAGS_READYING));
143 assert(type->tp_mro != NULL && PyTuple_Check(type->tp_mro));
144 assert(type->tp_dict != NULL);
145 return 1;
146}
147#endif
148
Larry Hastings5c661892014-01-24 06:17:25 -0800149static const char *
Larry Hastings2623c8c2014-02-08 22:15:29 -0800150_PyType_DocWithoutSignature(const char *name, const char *internal_doc)
Larry Hastings5c661892014-01-24 06:17:25 -0800151{
Larry Hastings2623c8c2014-02-08 22:15:29 -0800152 const char *doc = find_signature(name, internal_doc);
Larry Hastings5c661892014-01-24 06:17:25 -0800153
Larry Hastings2623c8c2014-02-08 22:15:29 -0800154 if (doc) {
155 doc = skip_signature(doc);
156 if (doc)
157 return doc;
158 }
Larry Hastings5c661892014-01-24 06:17:25 -0800159 return internal_doc;
160}
161
162PyObject *
Larry Hastings2623c8c2014-02-08 22:15:29 -0800163_PyType_GetDocFromInternalDoc(const char *name, const char *internal_doc)
Larry Hastings5c661892014-01-24 06:17:25 -0800164{
Larry Hastings2623c8c2014-02-08 22:15:29 -0800165 const char *doc = _PyType_DocWithoutSignature(name, internal_doc);
Larry Hastings5c661892014-01-24 06:17:25 -0800166
Zachary Ware8ef887c2015-04-13 18:22:35 -0500167 if (!doc || *doc == '\0') {
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200168 Py_RETURN_NONE;
Larry Hastings5c661892014-01-24 06:17:25 -0800169 }
170
171 return PyUnicode_FromString(doc);
172}
173
174PyObject *
Larry Hastings2623c8c2014-02-08 22:15:29 -0800175_PyType_GetTextSignatureFromInternalDoc(const char *name, const char *internal_doc)
Larry Hastings5c661892014-01-24 06:17:25 -0800176{
Larry Hastings2623c8c2014-02-08 22:15:29 -0800177 const char *start = find_signature(name, internal_doc);
178 const char *end;
Larry Hastings5c661892014-01-24 06:17:25 -0800179
Larry Hastings2623c8c2014-02-08 22:15:29 -0800180 if (start)
181 end = skip_signature(start);
182 else
183 end = NULL;
184 if (!end) {
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200185 Py_RETURN_NONE;
Larry Hastings5c661892014-01-24 06:17:25 -0800186 }
187
Larry Hastings2623c8c2014-02-08 22:15:29 -0800188 /* back "end" up until it points just past the final ')' */
189 end -= SIGNATURE_END_MARKER_LENGTH - 1;
190 assert((end - start) >= 2); /* should be "()" at least */
191 assert(end[-1] == ')');
192 assert(end[0] == '\n');
193 return PyUnicode_FromStringAndSize(start, end - start);
Larry Hastings5c661892014-01-24 06:17:25 -0800194}
195
Christian Heimes26855632008-01-27 23:50:43 +0000196unsigned int
197PyType_ClearCache(void)
198{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000199 Py_ssize_t i;
200 unsigned int cur_version_tag = next_version_tag - 1;
201
Antoine Pitrou2a40e362014-11-15 00:56:27 +0100202#if MCACHE_STATS
203 size_t total = method_cache_hits + method_cache_collisions + method_cache_misses;
204 fprintf(stderr, "-- Method cache hits = %zd (%d%%)\n",
205 method_cache_hits, (int) (100.0 * method_cache_hits / total));
206 fprintf(stderr, "-- Method cache true misses = %zd (%d%%)\n",
207 method_cache_misses, (int) (100.0 * method_cache_misses / total));
208 fprintf(stderr, "-- Method cache collisions = %zd (%d%%)\n",
209 method_cache_collisions, (int) (100.0 * method_cache_collisions / total));
Victor Stinner8c663fd2017-11-08 14:44:44 -0800210 fprintf(stderr, "-- Method cache size = %zd KiB\n",
Antoine Pitrou2a40e362014-11-15 00:56:27 +0100211 sizeof(method_cache) / 1024);
212#endif
213
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000214 for (i = 0; i < (1 << MCACHE_SIZE_EXP); i++) {
215 method_cache[i].version = 0;
216 Py_CLEAR(method_cache[i].name);
217 method_cache[i].value = NULL;
218 }
219 next_version_tag = 0;
220 /* mark all version tags as invalid */
221 PyType_Modified(&PyBaseObject_Type);
222 return cur_version_tag;
Christian Heimes26855632008-01-27 23:50:43 +0000223}
Christian Heimesa62da1d2008-01-12 19:39:10 +0000224
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000225void
Antoine Pitrou957a23b2013-05-04 20:45:02 +0200226_PyType_Fini(void)
227{
228 PyType_ClearCache();
Martin v. Löwis996b6712014-07-26 16:44:07 +0200229 clear_slotdefs();
Antoine Pitrou957a23b2013-05-04 20:45:02 +0200230}
231
232void
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000233PyType_Modified(PyTypeObject *type)
Christian Heimesa62da1d2008-01-12 19:39:10 +0000234{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000235 /* Invalidate any cached data for the specified type and all
236 subclasses. This function is called after the base
237 classes, mro, or attributes of the type are altered.
Christian Heimesa62da1d2008-01-12 19:39:10 +0000238
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000239 Invariants:
Christian Heimesa62da1d2008-01-12 19:39:10 +0000240
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000241 - Py_TPFLAGS_VALID_VERSION_TAG is never set if
242 Py_TPFLAGS_HAVE_VERSION_TAG is not set (e.g. on type
243 objects coming from non-recompiled extension modules)
Christian Heimesa62da1d2008-01-12 19:39:10 +0000244
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000245 - before Py_TPFLAGS_VALID_VERSION_TAG can be set on a type,
246 it must first be set on all super types.
Christian Heimesa62da1d2008-01-12 19:39:10 +0000247
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000248 This function clears the Py_TPFLAGS_VALID_VERSION_TAG of a
249 type (so it must first clear it on all subclasses). The
250 tp_version_tag value is meaningless unless this flag is set.
251 We don't assign new version tags eagerly, but only as
252 needed.
253 */
254 PyObject *raw, *ref;
Antoine Pitrou84745ab2013-10-29 21:31:25 +0100255 Py_ssize_t i;
Christian Heimesa62da1d2008-01-12 19:39:10 +0000256
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000257 if (!PyType_HasFeature(type, Py_TPFLAGS_VALID_VERSION_TAG))
258 return;
Christian Heimesa62da1d2008-01-12 19:39:10 +0000259
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000260 raw = type->tp_subclasses;
261 if (raw != NULL) {
Antoine Pitrou84745ab2013-10-29 21:31:25 +0100262 assert(PyDict_CheckExact(raw));
263 i = 0;
264 while (PyDict_Next(raw, &i, NULL, &ref)) {
265 assert(PyWeakref_CheckRef(ref));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000266 ref = PyWeakref_GET_OBJECT(ref);
267 if (ref != Py_None) {
268 PyType_Modified((PyTypeObject *)ref);
269 }
270 }
271 }
272 type->tp_flags &= ~Py_TPFLAGS_VALID_VERSION_TAG;
Christian Heimesa62da1d2008-01-12 19:39:10 +0000273}
274
275static void
276type_mro_modified(PyTypeObject *type, PyObject *bases) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000277 /*
Florent Xiclunaaa6c1d22011-12-12 18:54:29 +0100278 Check that all base classes or elements of the MRO of type are
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000279 able to be cached. This function is called after the base
280 classes or mro of the type are altered.
Christian Heimesa62da1d2008-01-12 19:39:10 +0000281
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000282 Unset HAVE_VERSION_TAG and VALID_VERSION_TAG if the type
Florent Xiclunaaa6c1d22011-12-12 18:54:29 +0100283 has a custom MRO that includes a type which is not officially
284 super type.
Christian Heimesa62da1d2008-01-12 19:39:10 +0000285
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000286 Called from mro_internal, which will subsequently be called on
287 each subclass when their mro is recursively updated.
288 */
289 Py_ssize_t i, n;
290 int clear = 0;
Christian Heimesa62da1d2008-01-12 19:39:10 +0000291
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000292 if (!PyType_HasFeature(type, Py_TPFLAGS_HAVE_VERSION_TAG))
293 return;
Christian Heimesa62da1d2008-01-12 19:39:10 +0000294
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000295 n = PyTuple_GET_SIZE(bases);
296 for (i = 0; i < n; i++) {
297 PyObject *b = PyTuple_GET_ITEM(bases, i);
298 PyTypeObject *cls;
Christian Heimesa62da1d2008-01-12 19:39:10 +0000299
Florent Xiclunaaa6c1d22011-12-12 18:54:29 +0100300 assert(PyType_Check(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000301 cls = (PyTypeObject *)b;
Christian Heimesa62da1d2008-01-12 19:39:10 +0000302
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000303 if (!PyType_HasFeature(cls, Py_TPFLAGS_HAVE_VERSION_TAG) ||
304 !PyType_IsSubtype(type, cls)) {
305 clear = 1;
306 break;
307 }
308 }
Christian Heimesa62da1d2008-01-12 19:39:10 +0000309
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000310 if (clear)
311 type->tp_flags &= ~(Py_TPFLAGS_HAVE_VERSION_TAG|
312 Py_TPFLAGS_VALID_VERSION_TAG);
Christian Heimesa62da1d2008-01-12 19:39:10 +0000313}
314
315static int
316assign_version_tag(PyTypeObject *type)
317{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000318 /* Ensure that the tp_version_tag is valid and set
319 Py_TPFLAGS_VALID_VERSION_TAG. To respect the invariant, this
320 must first be done on all super classes. Return 0 if this
321 cannot be done, 1 if Py_TPFLAGS_VALID_VERSION_TAG.
322 */
323 Py_ssize_t i, n;
324 PyObject *bases;
Christian Heimesa62da1d2008-01-12 19:39:10 +0000325
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000326 if (PyType_HasFeature(type, Py_TPFLAGS_VALID_VERSION_TAG))
327 return 1;
328 if (!PyType_HasFeature(type, Py_TPFLAGS_HAVE_VERSION_TAG))
329 return 0;
330 if (!PyType_HasFeature(type, Py_TPFLAGS_READY))
331 return 0;
Christian Heimesa62da1d2008-01-12 19:39:10 +0000332
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000333 type->tp_version_tag = next_version_tag++;
334 /* for stress-testing: next_version_tag &= 0xFF; */
Christian Heimesa62da1d2008-01-12 19:39:10 +0000335
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000336 if (type->tp_version_tag == 0) {
337 /* wrap-around or just starting Python - clear the whole
338 cache by filling names with references to Py_None.
339 Values are also set to NULL for added protection, as they
340 are borrowed reference */
341 for (i = 0; i < (1 << MCACHE_SIZE_EXP); i++) {
342 method_cache[i].value = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000343 Py_INCREF(Py_None);
Serhiy Storchaka48842712016-04-06 09:45:48 +0300344 Py_XSETREF(method_cache[i].name, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000345 }
346 /* mark all version tags as invalid */
347 PyType_Modified(&PyBaseObject_Type);
348 return 1;
349 }
350 bases = type->tp_bases;
351 n = PyTuple_GET_SIZE(bases);
352 for (i = 0; i < n; i++) {
353 PyObject *b = PyTuple_GET_ITEM(bases, i);
354 assert(PyType_Check(b));
355 if (!assign_version_tag((PyTypeObject *)b))
356 return 0;
357 }
358 type->tp_flags |= Py_TPFLAGS_VALID_VERSION_TAG;
359 return 1;
Christian Heimesa62da1d2008-01-12 19:39:10 +0000360}
361
362
Guido van Rossum6f799372001-09-20 20:46:19 +0000363static PyMemberDef type_members[] = {
Benjamin Peterson0e102062010-08-25 23:13:17 +0000364 {"__basicsize__", T_PYSSIZET, offsetof(PyTypeObject,tp_basicsize),READONLY},
365 {"__itemsize__", T_PYSSIZET, offsetof(PyTypeObject, tp_itemsize), READONLY},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000366 {"__flags__", T_LONG, offsetof(PyTypeObject, tp_flags), READONLY},
367 {"__weakrefoffset__", T_LONG,
368 offsetof(PyTypeObject, tp_weaklistoffset), READONLY},
369 {"__base__", T_OBJECT, offsetof(PyTypeObject, tp_base), READONLY},
370 {"__dictoffset__", T_LONG,
371 offsetof(PyTypeObject, tp_dictoffset), READONLY},
372 {"__mro__", T_OBJECT, offsetof(PyTypeObject, tp_mro), READONLY},
373 {0}
Tim Peters6d6c1a32001-08-02 04:15:00 +0000374};
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000375
Benjamin Petersond9f23d22011-08-17 11:54:03 -0500376static int
377check_set_special_type_attr(PyTypeObject *type, PyObject *value, const char *name)
378{
379 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
380 PyErr_Format(PyExc_TypeError,
381 "can't set %s.%s", type->tp_name, name);
382 return 0;
383 }
384 if (!value) {
385 PyErr_Format(PyExc_TypeError,
386 "can't delete %s.%s", type->tp_name, name);
387 return 0;
388 }
389 return 1;
390}
391
Serhiy Storchaka4ab46d72017-09-17 21:11:04 +0300392const char *
393_PyType_Name(PyTypeObject *type)
394{
395 const char *s = strrchr(type->tp_name, '.');
396 if (s == NULL) {
397 s = type->tp_name;
398 }
399 else {
400 s++;
401 }
402 return s;
403}
404
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000405static PyObject *
Guido van Rossumc3542212001-08-16 09:18:56 +0000406type_name(PyTypeObject *type, void *context)
407{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000408 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
409 PyHeapTypeObject* et = (PyHeapTypeObject*)type;
Tim Petersea7f75d2002-12-07 21:39:16 +0000410
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000411 Py_INCREF(et->ht_name);
412 return et->ht_name;
413 }
414 else {
Serhiy Storchaka4ab46d72017-09-17 21:11:04 +0300415 return PyUnicode_FromString(_PyType_Name(type));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000416 }
Guido van Rossumc3542212001-08-16 09:18:56 +0000417}
418
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100419static PyObject *
420type_qualname(PyTypeObject *type, void *context)
421{
422 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
423 PyHeapTypeObject* et = (PyHeapTypeObject*)type;
424 Py_INCREF(et->ht_qualname);
425 return et->ht_qualname;
426 }
427 else {
Serhiy Storchaka4ab46d72017-09-17 21:11:04 +0300428 return PyUnicode_FromString(_PyType_Name(type));
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100429 }
430}
431
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000432static int
433type_set_name(PyTypeObject *type, PyObject *value, void *context)
434{
Serhiy Storchaka42bf8fc2015-12-30 21:40:49 +0200435 const char *tp_name;
436 Py_ssize_t name_size;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000437
Benjamin Petersond9f23d22011-08-17 11:54:03 -0500438 if (!check_set_special_type_attr(type, value, "__name__"))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000439 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000440 if (!PyUnicode_Check(value)) {
441 PyErr_Format(PyExc_TypeError,
442 "can only assign string to %s.__name__, not '%s'",
443 type->tp_name, Py_TYPE(value)->tp_name);
444 return -1;
445 }
Guido van Rossume845c0f2007-11-02 23:07:07 +0000446
Serhiy Storchaka42bf8fc2015-12-30 21:40:49 +0200447 tp_name = PyUnicode_AsUTF8AndSize(value, &name_size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000448 if (tp_name == NULL)
449 return -1;
Serhiy Storchaka42bf8fc2015-12-30 21:40:49 +0200450 if (strlen(tp_name) != (size_t)name_size) {
451 PyErr_SetString(PyExc_ValueError,
452 "type name must not contain null characters");
453 return -1;
454 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000455
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000456 type->tp_name = tp_name;
Serhiy Storchaka1ed017a2015-12-27 15:51:32 +0200457 Py_INCREF(value);
Serhiy Storchaka57a01d32016-04-10 18:05:40 +0300458 Py_SETREF(((PyHeapTypeObject*)type)->ht_name, value);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000459
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000460 return 0;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000461}
462
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100463static int
464type_set_qualname(PyTypeObject *type, PyObject *value, void *context)
465{
466 PyHeapTypeObject* et;
467
Benjamin Peterson2c05a2e2012-10-31 00:01:15 -0400468 if (!check_set_special_type_attr(type, value, "__qualname__"))
469 return -1;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100470 if (!PyUnicode_Check(value)) {
471 PyErr_Format(PyExc_TypeError,
472 "can only assign string to %s.__qualname__, not '%s'",
473 type->tp_name, Py_TYPE(value)->tp_name);
474 return -1;
475 }
476
477 et = (PyHeapTypeObject*)type;
478 Py_INCREF(value);
Serhiy Storchaka57a01d32016-04-10 18:05:40 +0300479 Py_SETREF(et->ht_qualname, value);
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100480 return 0;
481}
482
Guido van Rossumc3542212001-08-16 09:18:56 +0000483static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000484type_module(PyTypeObject *type, void *context)
Guido van Rossum29ca26e1995-01-07 11:58:15 +0000485{
Serhiy Storchaka7c19aff2016-09-10 00:53:02 +0300486 PyObject *mod;
Guido van Rossumc3542212001-08-16 09:18:56 +0000487
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000488 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
Serhiy Storchaka7c19aff2016-09-10 00:53:02 +0300489 mod = _PyDict_GetItemId(type->tp_dict, &PyId___module__);
490 if (mod == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000491 PyErr_Format(PyExc_AttributeError, "__module__");
Serhiy Storchaka7c19aff2016-09-10 00:53:02 +0300492 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000493 }
Serhiy Storchaka27ba8862016-05-25 16:14:55 +0300494 Py_INCREF(mod);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000495 }
496 else {
Serhiy Storchaka7c19aff2016-09-10 00:53:02 +0300497 const char *s = strrchr(type->tp_name, '.');
498 if (s != NULL) {
499 mod = PyUnicode_FromStringAndSize(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000500 type->tp_name, (Py_ssize_t)(s - type->tp_name));
Serhiy Storchaka7c19aff2016-09-10 00:53:02 +0300501 if (mod != NULL)
502 PyUnicode_InternInPlace(&mod);
503 }
504 else {
505 mod = _PyUnicode_FromId(&PyId_builtins);
506 Py_XINCREF(mod);
507 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000508 }
Serhiy Storchaka7c19aff2016-09-10 00:53:02 +0300509 return mod;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000510}
511
Guido van Rossum3926a632001-09-25 16:25:58 +0000512static int
513type_set_module(PyTypeObject *type, PyObject *value, void *context)
514{
Benjamin Petersond9f23d22011-08-17 11:54:03 -0500515 if (!check_set_special_type_attr(type, value, "__module__"))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000516 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000517
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000518 PyType_Modified(type);
Christian Heimesa62da1d2008-01-12 19:39:10 +0000519
Victor Stinner3c1e4812012-03-26 22:10:51 +0200520 return _PyDict_SetItemId(type->tp_dict, &PyId___module__, value);
Guido van Rossum3926a632001-09-25 16:25:58 +0000521}
522
Tim Peters6d6c1a32001-08-02 04:15:00 +0000523static PyObject *
Christian Heimes9e7f1d22008-02-28 12:27:11 +0000524type_abstractmethods(PyTypeObject *type, void *context)
525{
Benjamin Petersonaec5fd12010-10-02 00:03:31 +0000526 PyObject *mod = NULL;
Benjamin Peterson84060b82010-10-03 02:13:39 +0000527 /* type itself has an __abstractmethods__ descriptor (this). Don't return
528 that. */
Benjamin Petersonaec5fd12010-10-02 00:03:31 +0000529 if (type != &PyType_Type)
Victor Stinner3688aa92013-11-06 18:59:18 +0100530 mod = _PyDict_GetItemId(type->tp_dict, &PyId___abstractmethods__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000531 if (!mod) {
Victor Stinner3688aa92013-11-06 18:59:18 +0100532 PyObject *message = _PyUnicode_FromId(&PyId___abstractmethods__);
533 if (message)
534 PyErr_SetObject(PyExc_AttributeError, message);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000535 return NULL;
536 }
Serhiy Storchaka27ba8862016-05-25 16:14:55 +0300537 Py_INCREF(mod);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000538 return mod;
Christian Heimes9e7f1d22008-02-28 12:27:11 +0000539}
540
541static int
542type_set_abstractmethods(PyTypeObject *type, PyObject *value, void *context)
543{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000544 /* __abstractmethods__ should only be set once on a type, in
545 abc.ABCMeta.__new__, so this function doesn't do anything
546 special to update subclasses.
547 */
Antoine Pitrou6f430e42012-08-15 23:18:25 +0200548 int abstract, res;
Benjamin Peterson477ba912011-01-12 15:34:01 +0000549 if (value != NULL) {
Antoine Pitrou6f430e42012-08-15 23:18:25 +0200550 abstract = PyObject_IsTrue(value);
551 if (abstract < 0)
552 return -1;
Victor Stinner3688aa92013-11-06 18:59:18 +0100553 res = _PyDict_SetItemId(type->tp_dict, &PyId___abstractmethods__, value);
Benjamin Peterson477ba912011-01-12 15:34:01 +0000554 }
555 else {
Antoine Pitrou6f430e42012-08-15 23:18:25 +0200556 abstract = 0;
Victor Stinner3688aa92013-11-06 18:59:18 +0100557 res = _PyDict_DelItemId(type->tp_dict, &PyId___abstractmethods__);
Benjamin Peterson477ba912011-01-12 15:34:01 +0000558 if (res && PyErr_ExceptionMatches(PyExc_KeyError)) {
Victor Stinner3688aa92013-11-06 18:59:18 +0100559 PyObject *message = _PyUnicode_FromId(&PyId___abstractmethods__);
560 if (message)
561 PyErr_SetObject(PyExc_AttributeError, message);
Benjamin Peterson477ba912011-01-12 15:34:01 +0000562 return -1;
563 }
564 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000565 if (res == 0) {
566 PyType_Modified(type);
Antoine Pitrou6f430e42012-08-15 23:18:25 +0200567 if (abstract)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000568 type->tp_flags |= Py_TPFLAGS_IS_ABSTRACT;
Antoine Pitrou6f430e42012-08-15 23:18:25 +0200569 else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000570 type->tp_flags &= ~Py_TPFLAGS_IS_ABSTRACT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000571 }
572 return res;
Christian Heimes9e7f1d22008-02-28 12:27:11 +0000573}
574
575static PyObject *
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000576type_get_bases(PyTypeObject *type, void *context)
577{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000578 Py_INCREF(type->tp_bases);
579 return type->tp_bases;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000580}
581
582static PyTypeObject *best_base(PyObject *);
Benjamin Peterson104b9e02015-02-05 22:29:14 -0500583static int mro_internal(PyTypeObject *, PyObject **);
Benjamin Peterson6cb526e2016-09-09 12:42:51 -0700584static int type_is_subtype_base_chain(PyTypeObject *, PyTypeObject *);
Serhiy Storchakaef1585e2015-12-25 20:01:53 +0200585static int compatible_for_assignment(PyTypeObject *, PyTypeObject *, const char *);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000586static int add_subclass(PyTypeObject*, PyTypeObject*);
Benjamin Peterson104b9e02015-02-05 22:29:14 -0500587static int add_all_subclasses(PyTypeObject *type, PyObject *bases);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000588static void remove_subclass(PyTypeObject *, PyTypeObject *);
Antoine Pitrou84745ab2013-10-29 21:31:25 +0100589static void remove_all_subclasses(PyTypeObject *type, PyObject *bases);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000590static void update_all_slots(PyTypeObject *);
591
Guido van Rossum8d24ee92003-03-24 23:49:49 +0000592typedef int (*update_callback)(PyTypeObject *, void *);
593static int update_subclasses(PyTypeObject *type, PyObject *name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000594 update_callback callback, void *data);
Guido van Rossum8d24ee92003-03-24 23:49:49 +0000595static int recurse_down_subclasses(PyTypeObject *type, PyObject *name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000596 update_callback callback, void *data);
Guido van Rossum8d24ee92003-03-24 23:49:49 +0000597
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000598static int
Benjamin Peterson104b9e02015-02-05 22:29:14 -0500599mro_hierarchy(PyTypeObject *type, PyObject *temp)
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000600{
Benjamin Peterson104b9e02015-02-05 22:29:14 -0500601 int res;
602 PyObject *new_mro, *old_mro;
603 PyObject *tuple;
604 PyObject *subclasses;
605 Py_ssize_t i, n;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000606
Benjamin Peterson104b9e02015-02-05 22:29:14 -0500607 res = mro_internal(type, &old_mro);
608 if (res <= 0)
609 /* error / reentrance */
610 return res;
611 new_mro = type->tp_mro;
Antoine Pitrou84745ab2013-10-29 21:31:25 +0100612
Benjamin Peterson104b9e02015-02-05 22:29:14 -0500613 if (old_mro != NULL)
614 tuple = PyTuple_Pack(3, type, new_mro, old_mro);
615 else
616 tuple = PyTuple_Pack(2, type, new_mro);
617
618 if (tuple != NULL)
619 res = PyList_Append(temp, tuple);
620 else
621 res = -1;
622 Py_XDECREF(tuple);
623
624 if (res < 0) {
625 type->tp_mro = old_mro;
626 Py_DECREF(new_mro);
627 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000628 }
Benjamin Peterson104b9e02015-02-05 22:29:14 -0500629 Py_XDECREF(old_mro);
630
631 /* Obtain a copy of subclasses list to iterate over.
632
633 Otherwise type->tp_subclasses might be altered
634 in the middle of the loop, for example, through a custom mro(),
635 by invoking type_set_bases on some subclass of the type
636 which in turn calls remove_subclass/add_subclass on this type.
637
638 Finally, this makes things simple avoiding the need to deal
639 with dictionary iterators and weak references.
640 */
Serhiy Storchaka5c643a02017-03-19 08:46:44 +0200641 subclasses = type___subclasses___impl(type);
Benjamin Peterson104b9e02015-02-05 22:29:14 -0500642 if (subclasses == NULL)
643 return -1;
644 n = PyList_GET_SIZE(subclasses);
645 for (i = 0; i < n; i++) {
646 PyTypeObject *subclass;
647 subclass = (PyTypeObject *)PyList_GET_ITEM(subclasses, i);
648 res = mro_hierarchy(subclass, temp);
649 if (res < 0)
650 break;
651 }
652 Py_DECREF(subclasses);
653
654 return res;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000655}
656
657static int
Benjamin Peterson104b9e02015-02-05 22:29:14 -0500658type_set_bases(PyTypeObject *type, PyObject *new_bases, void *context)
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000659{
Benjamin Peterson104b9e02015-02-05 22:29:14 -0500660 int res = 0;
661 PyObject *temp;
662 PyObject *old_bases;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000663 PyTypeObject *new_base, *old_base;
Benjamin Peterson104b9e02015-02-05 22:29:14 -0500664 Py_ssize_t i;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000665
Benjamin Peterson104b9e02015-02-05 22:29:14 -0500666 if (!check_set_special_type_attr(type, new_bases, "__bases__"))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000667 return -1;
Benjamin Peterson104b9e02015-02-05 22:29:14 -0500668 if (!PyTuple_Check(new_bases)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000669 PyErr_Format(PyExc_TypeError,
670 "can only assign tuple to %s.__bases__, not %s",
Benjamin Peterson104b9e02015-02-05 22:29:14 -0500671 type->tp_name, Py_TYPE(new_bases)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000672 return -1;
673 }
Benjamin Peterson104b9e02015-02-05 22:29:14 -0500674 if (PyTuple_GET_SIZE(new_bases) == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000675 PyErr_Format(PyExc_TypeError,
676 "can only assign non-empty tuple to %s.__bases__, not ()",
677 type->tp_name);
678 return -1;
679 }
Benjamin Peterson104b9e02015-02-05 22:29:14 -0500680 for (i = 0; i < PyTuple_GET_SIZE(new_bases); i++) {
681 PyObject *ob;
682 PyTypeObject *base;
683
684 ob = PyTuple_GET_ITEM(new_bases, i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000685 if (!PyType_Check(ob)) {
Benjamin Petersonb6af60c2012-04-01 18:49:54 -0400686 PyErr_Format(PyExc_TypeError,
Benjamin Peterson9ee601e2012-04-01 18:51:37 -0400687 "%s.__bases__ must be tuple of classes, not '%s'",
Benjamin Petersonb6af60c2012-04-01 18:49:54 -0400688 type->tp_name, Py_TYPE(ob)->tp_name);
689 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000690 }
Benjamin Peterson104b9e02015-02-05 22:29:14 -0500691
692 base = (PyTypeObject*)ob;
693 if (PyType_IsSubtype(base, type) ||
694 /* In case of reentering here again through a custom mro()
695 the above check is not enough since it relies on
696 base->tp_mro which would gonna be updated inside
697 mro_internal only upon returning from the mro().
698
699 However, base->tp_base has already been assigned (see
700 below), which in turn may cause an inheritance cycle
701 through tp_base chain. And this is definitely
702 not what you want to ever happen. */
703 (base->tp_mro != NULL && type_is_subtype_base_chain(base, type))) {
704
Benjamin Peterson3471bb62012-04-01 18:48:40 -0400705 PyErr_SetString(PyExc_TypeError,
706 "a __bases__ item causes an inheritance cycle");
707 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000708 }
709 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000710
Benjamin Peterson104b9e02015-02-05 22:29:14 -0500711 new_base = best_base(new_bases);
712 if (new_base == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000713 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000714
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000715 if (!compatible_for_assignment(type->tp_base, new_base, "__bases__"))
716 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000717
Benjamin Peterson104b9e02015-02-05 22:29:14 -0500718 Py_INCREF(new_bases);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000719 Py_INCREF(new_base);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000720
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000721 old_bases = type->tp_bases;
722 old_base = type->tp_base;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000723
Benjamin Peterson104b9e02015-02-05 22:29:14 -0500724 type->tp_bases = new_bases;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000725 type->tp_base = new_base;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000726
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000727 temp = PyList_New(0);
Benjamin Peterson104b9e02015-02-05 22:29:14 -0500728 if (temp == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000729 goto bail;
Benjamin Peterson104b9e02015-02-05 22:29:14 -0500730 if (mro_hierarchy(type, temp) < 0)
731 goto undo;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000732 Py_DECREF(temp);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000733
Benjamin Peterson104b9e02015-02-05 22:29:14 -0500734 /* Take no action in case if type->tp_bases has been replaced
735 through reentrance. */
736 if (type->tp_bases == new_bases) {
737 /* any base that was in __bases__ but now isn't, we
738 need to remove |type| from its tp_subclasses.
739 conversely, any class now in __bases__ that wasn't
740 needs to have |type| added to its subclasses. */
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000741
Benjamin Peterson104b9e02015-02-05 22:29:14 -0500742 /* for now, sod that: just remove from all old_bases,
743 add to all new_bases */
744 remove_all_subclasses(type, old_bases);
745 res = add_all_subclasses(type, new_bases);
746 update_all_slots(type);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000747 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000748
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000749 Py_DECREF(old_bases);
750 Py_DECREF(old_base);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000751
Victor Stinnerbda5a2b2017-01-25 23:33:27 +0100752 assert(_PyType_CheckConsistency(type));
Benjamin Peterson104b9e02015-02-05 22:29:14 -0500753 return res;
754
755 undo:
756 for (i = PyList_GET_SIZE(temp) - 1; i >= 0; i--) {
757 PyTypeObject *cls;
758 PyObject *new_mro, *old_mro = NULL;
759
760 PyArg_UnpackTuple(PyList_GET_ITEM(temp, i),
761 "", 2, 3, &cls, &new_mro, &old_mro);
762 /* Do not rollback if cls has a newer version of MRO. */
763 if (cls->tp_mro == new_mro) {
764 Py_XINCREF(old_mro);
765 cls->tp_mro = old_mro;
766 Py_DECREF(new_mro);
767 }
768 }
769 Py_DECREF(temp);
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000770
771 bail:
Benjamin Peterson104b9e02015-02-05 22:29:14 -0500772 if (type->tp_bases == new_bases) {
773 assert(type->tp_base == new_base);
Michael W. Hudsone723e452003-08-07 14:58:10 +0000774
Benjamin Peterson104b9e02015-02-05 22:29:14 -0500775 type->tp_bases = old_bases;
776 type->tp_base = old_base;
777
778 Py_DECREF(new_bases);
779 Py_DECREF(new_base);
780 }
781 else {
782 Py_DECREF(old_bases);
783 Py_DECREF(old_base);
784 }
Tim Petersea7f75d2002-12-07 21:39:16 +0000785
Victor Stinnerbda5a2b2017-01-25 23:33:27 +0100786 assert(_PyType_CheckConsistency(type));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000787 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000788}
789
790static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000791type_dict(PyTypeObject *type, void *context)
792{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000793 if (type->tp_dict == NULL) {
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200794 Py_RETURN_NONE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000795 }
796 return PyDictProxy_New(type->tp_dict);
Guido van Rossum29ca26e1995-01-07 11:58:15 +0000797}
798
Tim Peters24008312002-03-17 18:56:20 +0000799static PyObject *
800type_get_doc(PyTypeObject *type, void *context)
801{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000802 PyObject *result;
Larry Hastings5c661892014-01-24 06:17:25 -0800803 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE) && type->tp_doc != NULL) {
Larry Hastings2623c8c2014-02-08 22:15:29 -0800804 return _PyType_GetDocFromInternalDoc(type->tp_name, type->tp_doc);
Larry Hastings5c661892014-01-24 06:17:25 -0800805 }
Victor Stinner3c1e4812012-03-26 22:10:51 +0200806 result = _PyDict_GetItemId(type->tp_dict, &PyId___doc__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000807 if (result == NULL) {
808 result = Py_None;
809 Py_INCREF(result);
810 }
811 else if (Py_TYPE(result)->tp_descr_get) {
812 result = Py_TYPE(result)->tp_descr_get(result, NULL,
813 (PyObject *)type);
814 }
815 else {
816 Py_INCREF(result);
817 }
818 return result;
Tim Peters24008312002-03-17 18:56:20 +0000819}
820
Larry Hastings5c661892014-01-24 06:17:25 -0800821static PyObject *
822type_get_text_signature(PyTypeObject *type, void *context)
823{
Larry Hastings2623c8c2014-02-08 22:15:29 -0800824 return _PyType_GetTextSignatureFromInternalDoc(type->tp_name, type->tp_doc);
Larry Hastings5c661892014-01-24 06:17:25 -0800825}
826
Benjamin Peterson01fc6cd2011-08-17 12:03:47 -0500827static int
828type_set_doc(PyTypeObject *type, PyObject *value, void *context)
829{
830 if (!check_set_special_type_attr(type, value, "__doc__"))
831 return -1;
832 PyType_Modified(type);
Victor Stinner3c1e4812012-03-26 22:10:51 +0200833 return _PyDict_SetItemId(type->tp_dict, &PyId___doc__, value);
Benjamin Peterson01fc6cd2011-08-17 12:03:47 -0500834}
835
Serhiy Storchaka5c643a02017-03-19 08:46:44 +0200836/*[clinic input]
837type.__instancecheck__ -> bool
838
839 instance: object
840 /
841
842Check if an object is an instance.
843[clinic start generated code]*/
844
845static int
846type___instancecheck___impl(PyTypeObject *self, PyObject *instance)
847/*[clinic end generated code: output=08b6bf5f591c3618 input=cdbfeaee82c01a0f]*/
Antoine Pitrouec569b72008-08-26 22:40:48 +0000848{
Serhiy Storchaka5c643a02017-03-19 08:46:44 +0200849 return _PyObject_RealIsInstance(instance, (PyObject *)self);
Antoine Pitrouec569b72008-08-26 22:40:48 +0000850}
851
Serhiy Storchaka5c643a02017-03-19 08:46:44 +0200852/*[clinic input]
853type.__subclasscheck__ -> bool
Antoine Pitrouec569b72008-08-26 22:40:48 +0000854
Serhiy Storchaka5c643a02017-03-19 08:46:44 +0200855 subclass: object
856 /
857
858Check if a class is a subclass.
859[clinic start generated code]*/
860
861static int
862type___subclasscheck___impl(PyTypeObject *self, PyObject *subclass)
863/*[clinic end generated code: output=97a4e51694500941 input=071b2ca9e03355f4]*/
Antoine Pitrouec569b72008-08-26 22:40:48 +0000864{
Serhiy Storchaka5c643a02017-03-19 08:46:44 +0200865 return _PyObject_RealIsSubclass(subclass, (PyObject *)self);
Antoine Pitrouec569b72008-08-26 22:40:48 +0000866}
867
Antoine Pitrouec569b72008-08-26 22:40:48 +0000868
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000869static PyGetSetDef type_getsets[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000870 {"__name__", (getter)type_name, (setter)type_set_name, NULL},
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100871 {"__qualname__", (getter)type_qualname, (setter)type_set_qualname, NULL},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000872 {"__bases__", (getter)type_get_bases, (setter)type_set_bases, NULL},
873 {"__module__", (getter)type_module, (setter)type_set_module, NULL},
874 {"__abstractmethods__", (getter)type_abstractmethods,
875 (setter)type_set_abstractmethods, NULL},
876 {"__dict__", (getter)type_dict, NULL, NULL},
Benjamin Peterson01fc6cd2011-08-17 12:03:47 -0500877 {"__doc__", (getter)type_get_doc, (setter)type_set_doc, NULL},
Larry Hastings5c661892014-01-24 06:17:25 -0800878 {"__text_signature__", (getter)type_get_text_signature, NULL, NULL},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000879 {0}
Tim Peters6d6c1a32001-08-02 04:15:00 +0000880};
881
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000882static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000883type_repr(PyTypeObject *type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000884{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000885 PyObject *mod, *name, *rtn;
Guido van Rossumc3542212001-08-16 09:18:56 +0000886
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000887 mod = type_module(type, NULL);
888 if (mod == NULL)
889 PyErr_Clear();
890 else if (!PyUnicode_Check(mod)) {
891 Py_DECREF(mod);
892 mod = NULL;
893 }
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100894 name = type_qualname(type, NULL);
Christian Heimesa0e7e412012-09-10 03:00:14 +0200895 if (name == NULL) {
896 Py_XDECREF(mod);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000897 return NULL;
Christian Heimesa0e7e412012-09-10 03:00:14 +0200898 }
Barry Warsaw7ce36942001-08-24 18:34:26 +0000899
Serhiy Storchakaf5894dd2016-11-16 15:40:39 +0200900 if (mod != NULL && !_PyUnicode_EqualToASCIIId(mod, &PyId_builtins))
Benjamin Petersonab078e92016-07-13 21:13:29 -0700901 rtn = PyUnicode_FromFormat("<class '%U.%U'>", mod, name);
902 else
903 rtn = PyUnicode_FromFormat("<class '%s'>", type->tp_name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000904
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000905 Py_XDECREF(mod);
906 Py_DECREF(name);
907 return rtn;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000908}
909
Tim Peters6d6c1a32001-08-02 04:15:00 +0000910static PyObject *
911type_call(PyTypeObject *type, PyObject *args, PyObject *kwds)
912{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000913 PyObject *obj;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000914
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000915 if (type->tp_new == NULL) {
916 PyErr_Format(PyExc_TypeError,
917 "cannot create '%.100s' instances",
918 type->tp_name);
919 return NULL;
920 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000921
Victor Stinner33824f62013-08-26 14:05:19 +0200922#ifdef Py_DEBUG
923 /* type_call() must not be called with an exception set,
Victor Stinnera8cb5152017-01-18 14:12:51 +0100924 because it can clear it (directly or indirectly) and so the
Martin Panter9955a372015-10-07 10:26:23 +0000925 caller loses its exception */
Victor Stinner33824f62013-08-26 14:05:19 +0200926 assert(!PyErr_Occurred());
927#endif
928
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000929 obj = type->tp_new(type, args, kwds);
Victor Stinner99bb14b2015-09-03 12:16:49 +0200930 obj = _Py_CheckFunctionResult((PyObject*)type, obj, NULL);
931 if (obj == NULL)
932 return NULL;
933
934 /* Ugly exception: when the call was type(something),
935 don't call tp_init on the result. */
936 if (type == &PyType_Type &&
937 PyTuple_Check(args) && PyTuple_GET_SIZE(args) == 1 &&
938 (kwds == NULL ||
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +0200939 (PyDict_Check(kwds) && PyDict_GET_SIZE(kwds) == 0)))
Victor Stinner99bb14b2015-09-03 12:16:49 +0200940 return obj;
941
942 /* If the returned object is not an instance of type,
943 it won't be initialized. */
944 if (!PyType_IsSubtype(Py_TYPE(obj), type))
945 return obj;
946
947 type = Py_TYPE(obj);
948 if (type->tp_init != NULL) {
949 int res = type->tp_init(obj, args, kwds);
950 if (res < 0) {
951 assert(PyErr_Occurred());
952 Py_DECREF(obj);
953 obj = NULL;
954 }
955 else {
956 assert(!PyErr_Occurred());
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000957 }
958 }
959 return obj;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000960}
961
962PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000963PyType_GenericAlloc(PyTypeObject *type, Py_ssize_t nitems)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000964{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000965 PyObject *obj;
966 const size_t size = _PyObject_VAR_SIZE(type, nitems+1);
967 /* note that we need to add one, for the sentinel */
Tim Peters406fe3b2001-10-06 19:04:01 +0000968
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000969 if (PyType_IS_GC(type))
970 obj = _PyObject_GC_Malloc(size);
971 else
972 obj = (PyObject *)PyObject_MALLOC(size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000973
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000974 if (obj == NULL)
975 return PyErr_NoMemory();
Tim Peters406fe3b2001-10-06 19:04:01 +0000976
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000977 memset(obj, '\0', size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000978
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000979 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
980 Py_INCREF(type);
Tim Peters406fe3b2001-10-06 19:04:01 +0000981
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000982 if (type->tp_itemsize == 0)
Christian Heimesd3afe782013-12-04 09:27:47 +0100983 (void)PyObject_INIT(obj, type);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000984 else
985 (void) PyObject_INIT_VAR((PyVarObject *)obj, type, nitems);
Tim Peters406fe3b2001-10-06 19:04:01 +0000986
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000987 if (PyType_IS_GC(type))
988 _PyObject_GC_TRACK(obj);
989 return obj;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000990}
991
992PyObject *
993PyType_GenericNew(PyTypeObject *type, PyObject *args, PyObject *kwds)
994{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000995 return type->tp_alloc(type, 0);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000996}
997
Guido van Rossum9475a232001-10-05 20:51:39 +0000998/* Helpers for subtyping */
999
1000static int
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001001traverse_slots(PyTypeObject *type, PyObject *self, visitproc visit, void *arg)
1002{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001003 Py_ssize_t i, n;
1004 PyMemberDef *mp;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001005
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001006 n = Py_SIZE(type);
1007 mp = PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type);
1008 for (i = 0; i < n; i++, mp++) {
1009 if (mp->type == T_OBJECT_EX) {
1010 char *addr = (char *)self + mp->offset;
1011 PyObject *obj = *(PyObject **)addr;
1012 if (obj != NULL) {
1013 int err = visit(obj, arg);
1014 if (err)
1015 return err;
1016 }
1017 }
1018 }
1019 return 0;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001020}
1021
1022static int
Guido van Rossum9475a232001-10-05 20:51:39 +00001023subtype_traverse(PyObject *self, visitproc visit, void *arg)
1024{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001025 PyTypeObject *type, *base;
1026 traverseproc basetraverse;
Guido van Rossum9475a232001-10-05 20:51:39 +00001027
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001028 /* Find the nearest base with a different tp_traverse,
1029 and traverse slots while we're at it */
1030 type = Py_TYPE(self);
1031 base = type;
1032 while ((basetraverse = base->tp_traverse) == subtype_traverse) {
1033 if (Py_SIZE(base)) {
1034 int err = traverse_slots(base, self, visit, arg);
1035 if (err)
1036 return err;
1037 }
1038 base = base->tp_base;
1039 assert(base);
1040 }
Guido van Rossum9475a232001-10-05 20:51:39 +00001041
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001042 if (type->tp_dictoffset != base->tp_dictoffset) {
1043 PyObject **dictptr = _PyObject_GetDictPtr(self);
1044 if (dictptr && *dictptr)
1045 Py_VISIT(*dictptr);
1046 }
Guido van Rossum9475a232001-10-05 20:51:39 +00001047
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001048 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
1049 /* For a heaptype, the instances count as references
1050 to the type. Traverse the type so the collector
1051 can find cycles involving this link. */
1052 Py_VISIT(type);
Guido van Rossuma3862092002-06-10 15:24:42 +00001053
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001054 if (basetraverse)
1055 return basetraverse(self, visit, arg);
1056 return 0;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001057}
1058
1059static void
1060clear_slots(PyTypeObject *type, PyObject *self)
1061{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001062 Py_ssize_t i, n;
1063 PyMemberDef *mp;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001064
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001065 n = Py_SIZE(type);
1066 mp = PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type);
1067 for (i = 0; i < n; i++, mp++) {
1068 if (mp->type == T_OBJECT_EX && !(mp->flags & READONLY)) {
1069 char *addr = (char *)self + mp->offset;
1070 PyObject *obj = *(PyObject **)addr;
1071 if (obj != NULL) {
1072 *(PyObject **)addr = NULL;
1073 Py_DECREF(obj);
1074 }
1075 }
1076 }
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001077}
1078
1079static int
1080subtype_clear(PyObject *self)
1081{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001082 PyTypeObject *type, *base;
1083 inquiry baseclear;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001084
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001085 /* Find the nearest base with a different tp_clear
1086 and clear slots while we're at it */
1087 type = Py_TYPE(self);
1088 base = type;
1089 while ((baseclear = base->tp_clear) == subtype_clear) {
1090 if (Py_SIZE(base))
1091 clear_slots(base, self);
1092 base = base->tp_base;
1093 assert(base);
1094 }
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001095
Benjamin Peterson52c42432012-03-07 18:41:11 -06001096 /* Clear the instance dict (if any), to break cycles involving only
1097 __dict__ slots (as in the case 'self.__dict__ is self'). */
1098 if (type->tp_dictoffset != base->tp_dictoffset) {
1099 PyObject **dictptr = _PyObject_GetDictPtr(self);
1100 if (dictptr && *dictptr)
1101 Py_CLEAR(*dictptr);
1102 }
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001103
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001104 if (baseclear)
1105 return baseclear(self);
1106 return 0;
Guido van Rossum9475a232001-10-05 20:51:39 +00001107}
Tim Peters6d6c1a32001-08-02 04:15:00 +00001108
1109static void
1110subtype_dealloc(PyObject *self)
1111{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001112 PyTypeObject *type, *base;
1113 destructor basedealloc;
Antoine Pitrou56cd62c2012-09-06 00:59:49 +02001114 PyThreadState *tstate = PyThreadState_GET();
Antoine Pitrou796564c2013-07-30 19:59:21 +02001115 int has_finalizer;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001116
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001117 /* Extract the type; we expect it to be a heap type */
1118 type = Py_TYPE(self);
1119 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001120
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001121 /* Test whether the type has GC exactly once */
Guido van Rossum22b13872002-08-06 21:41:44 +00001122
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001123 if (!PyType_IS_GC(type)) {
1124 /* It's really rare to find a dynamic type that doesn't have
1125 GC; it can only happen when deriving from 'object' and not
1126 adding any slots or instance variables. This allows
1127 certain simplifications: there's no need to call
1128 clear_slots(), or DECREF the dict, or clear weakrefs. */
Guido van Rossum22b13872002-08-06 21:41:44 +00001129
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001130 /* Maybe call finalizer; exit early if resurrected */
Antoine Pitrou796564c2013-07-30 19:59:21 +02001131 if (type->tp_finalize) {
1132 if (PyObject_CallFinalizerFromDealloc(self) < 0)
1133 return;
1134 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001135 if (type->tp_del) {
1136 type->tp_del(self);
1137 if (self->ob_refcnt > 0)
1138 return;
1139 }
Guido van Rossum22b13872002-08-06 21:41:44 +00001140
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001141 /* Find the nearest base with a different tp_dealloc */
1142 base = type;
1143 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
1144 assert(Py_SIZE(base) == 0);
1145 base = base->tp_base;
1146 assert(base);
1147 }
Guido van Rossum22b13872002-08-06 21:41:44 +00001148
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001149 /* Extract the type again; tp_del may have changed it */
1150 type = Py_TYPE(self);
Benjamin Peterson193152c2009-04-25 01:08:45 +00001151
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001152 /* Call the base tp_dealloc() */
1153 assert(basedealloc);
1154 basedealloc(self);
Guido van Rossum22b13872002-08-06 21:41:44 +00001155
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001156 /* Can't reference self beyond this point */
1157 Py_DECREF(type);
Guido van Rossum22b13872002-08-06 21:41:44 +00001158
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001159 /* Done */
1160 return;
1161 }
Guido van Rossum22b13872002-08-06 21:41:44 +00001162
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001163 /* We get here only if the type has GC */
Guido van Rossum22b13872002-08-06 21:41:44 +00001164
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001165 /* UnTrack and re-Track around the trashcan macro, alas */
1166 /* See explanation at end of function for full disclosure */
1167 PyObject_GC_UnTrack(self);
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001168 ++_PyRuntime.gc.trash_delete_nesting;
Antoine Pitrou56cd62c2012-09-06 00:59:49 +02001169 ++ tstate->trash_delete_nesting;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001170 Py_TRASHCAN_SAFE_BEGIN(self);
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001171 --_PyRuntime.gc.trash_delete_nesting;
Antoine Pitrou56cd62c2012-09-06 00:59:49 +02001172 -- tstate->trash_delete_nesting;
Guido van Rossum22b13872002-08-06 21:41:44 +00001173
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001174 /* Find the nearest base with a different tp_dealloc */
1175 base = type;
Brett Cannonb94767f2011-02-22 20:15:44 +00001176 while ((/*basedealloc =*/ base->tp_dealloc) == subtype_dealloc) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001177 base = base->tp_base;
1178 assert(base);
1179 }
Guido van Rossum14227b42001-12-06 02:35:58 +00001180
Antoine Pitrou796564c2013-07-30 19:59:21 +02001181 has_finalizer = type->tp_finalize || type->tp_del;
Guido van Rossum59195fd2003-06-13 20:54:40 +00001182
Antoine Pitrou796564c2013-07-30 19:59:21 +02001183 if (type->tp_finalize) {
Benjamin Peterson8f657c32016-10-04 00:00:02 -07001184 _PyObject_GC_TRACK(self);
Antoine Pitrou796564c2013-07-30 19:59:21 +02001185 if (PyObject_CallFinalizerFromDealloc(self) < 0) {
1186 /* Resurrected */
1187 goto endlabel;
1188 }
Benjamin Peterson8f657c32016-10-04 00:00:02 -07001189 _PyObject_GC_UNTRACK(self);
Antoine Pitrou796564c2013-07-30 19:59:21 +02001190 }
Benjamin Peterson8f657c32016-10-04 00:00:02 -07001191 /*
1192 If we added a weaklist, we clear it. Do this *before* calling tp_del,
1193 clearing slots, or clearing the instance dict.
1194
1195 GC tracking must be off at this point. weakref callbacks (if any, and
1196 whether directly here or indirectly in something we call) may trigger GC,
1197 and if self is tracked at that point, it will look like trash to GC and GC
1198 will try to delete self again.
1199 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001200 if (type->tp_weaklistoffset && !base->tp_weaklistoffset)
1201 PyObject_ClearWeakRefs(self);
Guido van Rossum1987c662003-05-29 14:29:23 +00001202
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001203 if (type->tp_del) {
Benjamin Peterson8f657c32016-10-04 00:00:02 -07001204 _PyObject_GC_TRACK(self);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001205 type->tp_del(self);
Antoine Pitrou796564c2013-07-30 19:59:21 +02001206 if (self->ob_refcnt > 0) {
1207 /* Resurrected */
1208 goto endlabel;
1209 }
Benjamin Peterson8f657c32016-10-04 00:00:02 -07001210 _PyObject_GC_UNTRACK(self);
Antoine Pitrou796564c2013-07-30 19:59:21 +02001211 }
1212 if (has_finalizer) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001213 /* New weakrefs could be created during the finalizer call.
Antoine Pitrou796564c2013-07-30 19:59:21 +02001214 If this occurs, clear them out without calling their
1215 finalizers since they might rely on part of the object
1216 being finalized that has already been destroyed. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001217 if (type->tp_weaklistoffset && !base->tp_weaklistoffset) {
1218 /* Modeled after GET_WEAKREFS_LISTPTR() */
1219 PyWeakReference **list = (PyWeakReference **) \
1220 PyObject_GET_WEAKREFS_LISTPTR(self);
1221 while (*list)
1222 _PyWeakref_ClearRef(*list);
1223 }
1224 }
Guido van Rossum1987c662003-05-29 14:29:23 +00001225
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001226 /* Clear slots up to the nearest base with a different tp_dealloc */
1227 base = type;
1228 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
1229 if (Py_SIZE(base))
1230 clear_slots(base, self);
1231 base = base->tp_base;
1232 assert(base);
1233 }
Guido van Rossum59195fd2003-06-13 20:54:40 +00001234
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001235 /* If we added a dict, DECREF it */
1236 if (type->tp_dictoffset && !base->tp_dictoffset) {
1237 PyObject **dictptr = _PyObject_GetDictPtr(self);
1238 if (dictptr != NULL) {
1239 PyObject *dict = *dictptr;
1240 if (dict != NULL) {
1241 Py_DECREF(dict);
1242 *dictptr = NULL;
1243 }
1244 }
1245 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001246
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001247 /* Extract the type again; tp_del may have changed it */
1248 type = Py_TYPE(self);
Benjamin Peterson193152c2009-04-25 01:08:45 +00001249
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001250 /* Call the base tp_dealloc(); first retrack self if
1251 * basedealloc knows about gc.
1252 */
1253 if (PyType_IS_GC(base))
1254 _PyObject_GC_TRACK(self);
1255 assert(basedealloc);
1256 basedealloc(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001257
Benjamin Peterson9d4cbcc2015-01-30 13:33:42 -05001258 /* Can't reference self beyond this point. It's possible tp_del switched
1259 our type from a HEAPTYPE to a non-HEAPTYPE, so be careful about
1260 reference counting. */
1261 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
1262 Py_DECREF(type);
Guido van Rossum22b13872002-08-06 21:41:44 +00001263
Guido van Rossum0906e072002-08-07 20:42:09 +00001264 endlabel:
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001265 ++_PyRuntime.gc.trash_delete_nesting;
Antoine Pitrou56cd62c2012-09-06 00:59:49 +02001266 ++ tstate->trash_delete_nesting;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001267 Py_TRASHCAN_SAFE_END(self);
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001268 --_PyRuntime.gc.trash_delete_nesting;
Antoine Pitrou56cd62c2012-09-06 00:59:49 +02001269 -- tstate->trash_delete_nesting;
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001270
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001271 /* Explanation of the weirdness around the trashcan macros:
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001272
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001273 Q. What do the trashcan macros do?
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001274
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001275 A. Read the comment titled "Trashcan mechanism" in object.h.
1276 For one, this explains why there must be a call to GC-untrack
1277 before the trashcan begin macro. Without understanding the
1278 trashcan code, the answers to the following questions don't make
1279 sense.
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001280
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001281 Q. Why do we GC-untrack before the trashcan and then immediately
1282 GC-track again afterward?
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001283
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001284 A. In the case that the base class is GC-aware, the base class
1285 probably GC-untracks the object. If it does that using the
1286 UNTRACK macro, this will crash when the object is already
1287 untracked. Because we don't know what the base class does, the
1288 only safe thing is to make sure the object is tracked when we
1289 call the base class dealloc. But... The trashcan begin macro
1290 requires that the object is *untracked* before it is called. So
1291 the dance becomes:
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001292
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001293 GC untrack
1294 trashcan begin
1295 GC track
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001296
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001297 Q. Why did the last question say "immediately GC-track again"?
1298 It's nowhere near immediately.
Tim Petersf7f9e992003-11-13 21:59:32 +00001299
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001300 A. Because the code *used* to re-track immediately. Bad Idea.
1301 self has a refcount of 0, and if gc ever gets its hands on it
1302 (which can happen if any weakref callback gets invoked), it
1303 looks like trash to gc too, and gc also tries to delete self
Ezio Melotti13925002011-03-16 11:05:33 +02001304 then. But we're already deleting self. Double deallocation is
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001305 a subtle disaster.
Tim Petersf7f9e992003-11-13 21:59:32 +00001306
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001307 Q. Why the bizarre (net-zero) manipulation of
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001308 _PyRuntime.trash_delete_nesting around the trashcan macros?
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001309
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001310 A. Some base classes (e.g. list) also use the trashcan mechanism.
1311 The following scenario used to be possible:
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001312
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001313 - suppose the trashcan level is one below the trashcan limit
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001314
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001315 - subtype_dealloc() is called
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001316
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001317 - the trashcan limit is not yet reached, so the trashcan level
1318 is incremented and the code between trashcan begin and end is
1319 executed
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001320
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001321 - this destroys much of the object's contents, including its
1322 slots and __dict__
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001323
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001324 - basedealloc() is called; this is really list_dealloc(), or
1325 some other type which also uses the trashcan macros
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001326
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001327 - the trashcan limit is now reached, so the object is put on the
1328 trashcan's to-be-deleted-later list
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001329
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001330 - basedealloc() returns
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001331
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001332 - subtype_dealloc() decrefs the object's type
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001333
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001334 - subtype_dealloc() returns
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001335
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001336 - later, the trashcan code starts deleting the objects from its
1337 to-be-deleted-later list
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001338
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001339 - subtype_dealloc() is called *AGAIN* for the same object
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001340
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001341 - at the very least (if the destroyed slots and __dict__ don't
1342 cause problems) the object's type gets decref'ed a second
1343 time, which is *BAD*!!!
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001344
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001345 The remedy is to make sure that if the code between trashcan
1346 begin and end in subtype_dealloc() is called, the code between
1347 trashcan begin and end in basedealloc() will also be called.
1348 This is done by decrementing the level after passing into the
1349 trashcan block, and incrementing it just before leaving the
1350 block.
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001351
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001352 But now it's possible that a chain of objects consisting solely
1353 of objects whose deallocator is subtype_dealloc() will defeat
1354 the trashcan mechanism completely: the decremented level means
1355 that the effective level never reaches the limit. Therefore, we
1356 *increment* the level *before* entering the trashcan block, and
1357 matchingly decrement it after leaving. This means the trashcan
1358 code will trigger a little early, but that's no big deal.
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001359
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001360 Q. Are there any live examples of code in need of all this
1361 complexity?
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001362
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001363 A. Yes. See SF bug 668433 for code that crashed (when Python was
1364 compiled in debug mode) before the trashcan level manipulations
1365 were added. For more discussion, see SF patches 581742, 575073
1366 and bug 574207.
1367 */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001368}
1369
Jeremy Hylton938ace62002-07-17 16:30:39 +00001370static PyTypeObject *solid_base(PyTypeObject *type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001371
Tim Peters6d6c1a32001-08-02 04:15:00 +00001372/* type test with subclassing support */
1373
Benjamin Peterson6cb526e2016-09-09 12:42:51 -07001374static int
Benjamin Peterson104b9e02015-02-05 22:29:14 -05001375type_is_subtype_base_chain(PyTypeObject *a, PyTypeObject *b)
1376{
1377 do {
1378 if (a == b)
1379 return 1;
1380 a = a->tp_base;
1381 } while (a != NULL);
1382
1383 return (b == &PyBaseObject_Type);
1384}
1385
Tim Peters6d6c1a32001-08-02 04:15:00 +00001386int
1387PyType_IsSubtype(PyTypeObject *a, PyTypeObject *b)
1388{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001389 PyObject *mro;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001390
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001391 mro = a->tp_mro;
1392 if (mro != NULL) {
1393 /* Deal with multiple inheritance without recursion
1394 by walking the MRO tuple */
1395 Py_ssize_t i, n;
1396 assert(PyTuple_Check(mro));
1397 n = PyTuple_GET_SIZE(mro);
1398 for (i = 0; i < n; i++) {
1399 if (PyTuple_GET_ITEM(mro, i) == (PyObject *)b)
1400 return 1;
1401 }
1402 return 0;
1403 }
Benjamin Peterson104b9e02015-02-05 22:29:14 -05001404 else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001405 /* a is not completely initilized yet; follow tp_base */
Benjamin Peterson104b9e02015-02-05 22:29:14 -05001406 return type_is_subtype_base_chain(a, b);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001407}
1408
Serhiy Storchaka4e624ca2017-06-01 08:18:25 +03001409/* Routines to do a method lookup in the type without looking in the
1410 instance dictionary (so we can't use PyObject_GetAttr) but still
1411 binding it to the instance.
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001412
Victor Stinner516b9812017-02-09 22:53:47 +01001413 Variants:
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001414
Serhiy Storchaka4e624ca2017-06-01 08:18:25 +03001415 - _PyObject_LookupSpecial() returns NULL without raising an exception
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001416 when the _PyType_Lookup() call fails;
1417
Serhiy Storchaka4e624ca2017-06-01 08:18:25 +03001418 - lookup_maybe_method() and lookup_method() are internal routines similar
1419 to _PyObject_LookupSpecial(), but can return unbound PyFunction
Victor Stinner516b9812017-02-09 22:53:47 +01001420 to avoid temporary method object. Pass self as first argument when
1421 unbound == 1.
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001422*/
Guido van Rossum60718732001-08-28 17:47:51 +00001423
Serhiy Storchaka4e624ca2017-06-01 08:18:25 +03001424PyObject *
1425_PyObject_LookupSpecial(PyObject *self, _Py_Identifier *attrid)
Guido van Rossum60718732001-08-28 17:47:51 +00001426{
Victor Stinner3c1e4812012-03-26 22:10:51 +02001427 PyObject *res;
Guido van Rossum60718732001-08-28 17:47:51 +00001428
Victor Stinner3c1e4812012-03-26 22:10:51 +02001429 res = _PyType_LookupId(Py_TYPE(self), attrid);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001430 if (res != NULL) {
1431 descrgetfunc f;
1432 if ((f = Py_TYPE(res)->tp_descr_get) == NULL)
1433 Py_INCREF(res);
1434 else
1435 res = f(res, self, (PyObject *)(Py_TYPE(self)));
1436 }
1437 return res;
Guido van Rossum60718732001-08-28 17:47:51 +00001438}
1439
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001440static PyObject *
Victor Stinner516b9812017-02-09 22:53:47 +01001441lookup_maybe_method(PyObject *self, _Py_Identifier *attrid, int *unbound)
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001442{
Victor Stinner516b9812017-02-09 22:53:47 +01001443 PyObject *res = _PyType_LookupId(Py_TYPE(self), attrid);
1444 if (res == NULL) {
1445 return NULL;
1446 }
1447
1448 if (PyFunction_Check(res)) {
1449 /* Avoid temporary PyMethodObject */
1450 *unbound = 1;
1451 Py_INCREF(res);
1452 }
1453 else {
1454 *unbound = 0;
1455 descrgetfunc f = Py_TYPE(res)->tp_descr_get;
1456 if (f == NULL) {
1457 Py_INCREF(res);
1458 }
1459 else {
1460 res = f(res, self, (PyObject *)(Py_TYPE(self)));
1461 }
1462 }
1463 return res;
1464}
1465
1466static PyObject *
1467lookup_method(PyObject *self, _Py_Identifier *attrid, int *unbound)
1468{
1469 PyObject *res = lookup_maybe_method(self, attrid, unbound);
1470 if (res == NULL && !PyErr_Occurred()) {
Benjamin Petersonce798522012-01-22 11:24:29 -05001471 PyErr_SetObject(PyExc_AttributeError, attrid->object);
Victor Stinner516b9812017-02-09 22:53:47 +01001472 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001473 return res;
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001474}
1475
Victor Stinner516b9812017-02-09 22:53:47 +01001476static PyObject*
1477call_unbound(int unbound, PyObject *func, PyObject *self,
1478 PyObject **args, Py_ssize_t nargs)
1479{
1480 if (unbound) {
1481 return _PyObject_FastCall_Prepend(func, self, args, nargs);
1482 }
1483 else {
1484 return _PyObject_FastCall(func, args, nargs);
1485 }
1486}
Guido van Rossum2730b132001-08-28 18:22:14 +00001487
Victor Stinner516b9812017-02-09 22:53:47 +01001488static PyObject*
1489call_unbound_noarg(int unbound, PyObject *func, PyObject *self)
1490{
1491 if (unbound) {
1492 PyObject *args[1] = {self};
1493 return _PyObject_FastCall(func, args, 1);
1494 }
1495 else {
1496 return _PyObject_CallNoArg(func);
1497 }
1498}
1499
Serhiy Storchaka4e624ca2017-06-01 08:18:25 +03001500/* A variation of PyObject_CallMethod* that uses lookup_maybe_method()
1501 instead of PyObject_GetAttrString(). */
Neil Schemenauerf23473f2001-10-21 22:28:58 +00001502static PyObject *
Victor Stinner434723f2017-01-11 00:07:40 +01001503call_method(PyObject *obj, _Py_Identifier *name,
1504 PyObject **args, Py_ssize_t nargs)
Guido van Rossum2730b132001-08-28 18:22:14 +00001505{
Victor Stinner516b9812017-02-09 22:53:47 +01001506 int unbound;
Victor Stinner887b4302016-12-09 00:41:46 +01001507 PyObject *func, *retval;
Guido van Rossum2730b132001-08-28 18:22:14 +00001508
Serhiy Storchaka4e624ca2017-06-01 08:18:25 +03001509 func = lookup_method(obj, name, &unbound);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001510 if (func == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001511 return NULL;
1512 }
Victor Stinner516b9812017-02-09 22:53:47 +01001513 retval = call_unbound(unbound, func, obj, args, nargs);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001514 Py_DECREF(func);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001515 return retval;
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001516}
1517
1518/* Clone of call_method() that returns NotImplemented when the lookup fails. */
1519
Neil Schemenauerf23473f2001-10-21 22:28:58 +00001520static PyObject *
Victor Stinner434723f2017-01-11 00:07:40 +01001521call_maybe(PyObject *obj, _Py_Identifier *name,
1522 PyObject **args, Py_ssize_t nargs)
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001523{
Victor Stinner516b9812017-02-09 22:53:47 +01001524 int unbound;
Victor Stinner887b4302016-12-09 00:41:46 +01001525 PyObject *func, *retval;
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001526
Victor Stinner516b9812017-02-09 22:53:47 +01001527 func = lookup_maybe_method(obj, name, &unbound);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001528 if (func == NULL) {
Brian Curtindfc80e32011-08-10 20:28:54 -05001529 if (!PyErr_Occurred())
1530 Py_RETURN_NOTIMPLEMENTED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001531 return NULL;
1532 }
Guido van Rossum2730b132001-08-28 18:22:14 +00001533
Victor Stinner516b9812017-02-09 22:53:47 +01001534 retval = call_unbound(unbound, func, obj, args, nargs);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001535 Py_DECREF(func);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001536 return retval;
Guido van Rossum2730b132001-08-28 18:22:14 +00001537}
1538
Tim Petersea7f75d2002-12-07 21:39:16 +00001539/*
Guido van Rossum1f121312002-11-14 19:49:16 +00001540 Method resolution order algorithm C3 described in
1541 "A Monotonic Superclass Linearization for Dylan",
1542 by Kim Barrett, Bob Cassel, Paul Haahr,
Tim Petersea7f75d2002-12-07 21:39:16 +00001543 David A. Moon, Keith Playford, and P. Tucker Withington.
Guido van Rossum1f121312002-11-14 19:49:16 +00001544 (OOPSLA 1996)
1545
Guido van Rossum98f33732002-11-25 21:36:54 +00001546 Some notes about the rules implied by C3:
1547
Tim Petersea7f75d2002-12-07 21:39:16 +00001548 No duplicate bases.
Guido van Rossum98f33732002-11-25 21:36:54 +00001549 It isn't legal to repeat a class in a list of base classes.
1550
1551 The next three properties are the 3 constraints in "C3".
1552
Martin Panter69332c12016-08-04 13:07:31 +00001553 Local precedence order.
Guido van Rossum98f33732002-11-25 21:36:54 +00001554 If A precedes B in C's MRO, then A will precede B in the MRO of all
1555 subclasses of C.
1556
1557 Monotonicity.
1558 The MRO of a class must be an extension without reordering of the
1559 MRO of each of its superclasses.
1560
1561 Extended Precedence Graph (EPG).
1562 Linearization is consistent if there is a path in the EPG from
1563 each class to all its successors in the linearization. See
1564 the paper for definition of EPG.
Guido van Rossum1f121312002-11-14 19:49:16 +00001565 */
1566
Tim Petersea7f75d2002-12-07 21:39:16 +00001567static int
Serhiy Storchaka6b91a592017-12-20 19:21:02 +02001568tail_contains(PyObject *tuple, int whence, PyObject *o)
1569{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001570 Py_ssize_t j, size;
Serhiy Storchaka6b91a592017-12-20 19:21:02 +02001571 size = PyTuple_GET_SIZE(tuple);
Guido van Rossum1f121312002-11-14 19:49:16 +00001572
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001573 for (j = whence+1; j < size; j++) {
Serhiy Storchaka6b91a592017-12-20 19:21:02 +02001574 if (PyTuple_GET_ITEM(tuple, j) == o)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001575 return 1;
1576 }
1577 return 0;
Guido van Rossum1f121312002-11-14 19:49:16 +00001578}
1579
Guido van Rossum98f33732002-11-25 21:36:54 +00001580static PyObject *
1581class_name(PyObject *cls)
1582{
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001583 PyObject *name = _PyObject_GetAttrId(cls, &PyId___name__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001584 if (name == NULL) {
1585 PyErr_Clear();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001586 name = PyObject_Repr(cls);
1587 }
1588 if (name == NULL)
1589 return NULL;
1590 if (!PyUnicode_Check(name)) {
1591 Py_DECREF(name);
1592 return NULL;
1593 }
1594 return name;
Guido van Rossum98f33732002-11-25 21:36:54 +00001595}
1596
1597static int
Serhiy Storchaka6b91a592017-12-20 19:21:02 +02001598check_duplicates(PyObject *tuple)
Guido van Rossum98f33732002-11-25 21:36:54 +00001599{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001600 Py_ssize_t i, j, n;
1601 /* Let's use a quadratic time algorithm,
Serhiy Storchaka6b91a592017-12-20 19:21:02 +02001602 assuming that the bases tuples is short.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001603 */
Serhiy Storchaka6b91a592017-12-20 19:21:02 +02001604 n = PyTuple_GET_SIZE(tuple);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001605 for (i = 0; i < n; i++) {
Serhiy Storchaka6b91a592017-12-20 19:21:02 +02001606 PyObject *o = PyTuple_GET_ITEM(tuple, i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001607 for (j = i + 1; j < n; j++) {
Serhiy Storchaka6b91a592017-12-20 19:21:02 +02001608 if (PyTuple_GET_ITEM(tuple, j) == o) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001609 o = class_name(o);
1610 if (o != NULL) {
1611 PyErr_Format(PyExc_TypeError,
1612 "duplicate base class %U",
1613 o);
1614 Py_DECREF(o);
1615 } else {
1616 PyErr_SetString(PyExc_TypeError,
1617 "duplicate base class");
1618 }
1619 return -1;
1620 }
1621 }
1622 }
1623 return 0;
Guido van Rossum98f33732002-11-25 21:36:54 +00001624}
1625
1626/* Raise a TypeError for an MRO order disagreement.
1627
1628 It's hard to produce a good error message. In the absence of better
1629 insight into error reporting, report the classes that were candidates
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001630 to be put next into the MRO. There is some conflict between the
Guido van Rossum98f33732002-11-25 21:36:54 +00001631 order in which they should be put in the MRO, but it's hard to
1632 diagnose what constraint can't be satisfied.
1633*/
1634
1635static void
Serhiy Storchaka6b91a592017-12-20 19:21:02 +02001636set_mro_error(PyObject **to_merge, Py_ssize_t to_merge_size, int *remain)
Guido van Rossum98f33732002-11-25 21:36:54 +00001637{
Serhiy Storchaka6b91a592017-12-20 19:21:02 +02001638 Py_ssize_t i, n, off;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001639 char buf[1000];
1640 PyObject *k, *v;
1641 PyObject *set = PyDict_New();
1642 if (!set) return;
Guido van Rossum98f33732002-11-25 21:36:54 +00001643
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001644 for (i = 0; i < to_merge_size; i++) {
Serhiy Storchaka6b91a592017-12-20 19:21:02 +02001645 PyObject *L = to_merge[i];
1646 if (remain[i] < PyTuple_GET_SIZE(L)) {
1647 PyObject *c = PyTuple_GET_ITEM(L, remain[i]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001648 if (PyDict_SetItem(set, c, Py_None) < 0) {
1649 Py_DECREF(set);
1650 return;
1651 }
1652 }
1653 }
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02001654 n = PyDict_GET_SIZE(set);
Guido van Rossum98f33732002-11-25 21:36:54 +00001655
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001656 off = PyOS_snprintf(buf, sizeof(buf), "Cannot create a \
Raymond Hettingerf394df42003-04-06 19:13:41 +00001657consistent method resolution\norder (MRO) for bases");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001658 i = 0;
1659 while (PyDict_Next(set, &i, &k, &v) && (size_t)off < sizeof(buf)) {
1660 PyObject *name = class_name(k);
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02001661 const char *name_str;
Victor Stinnere5f99f32010-05-19 01:42:46 +00001662 if (name != NULL) {
Serhiy Storchaka06515832016-11-20 09:13:07 +02001663 name_str = PyUnicode_AsUTF8(name);
Victor Stinnere5f99f32010-05-19 01:42:46 +00001664 if (name_str == NULL)
Victor Stinnerba644a62010-05-19 01:50:45 +00001665 name_str = "?";
Victor Stinnere5f99f32010-05-19 01:42:46 +00001666 } else
Victor Stinnerba644a62010-05-19 01:50:45 +00001667 name_str = "?";
Victor Stinnere5f99f32010-05-19 01:42:46 +00001668 off += PyOS_snprintf(buf + off, sizeof(buf) - off, " %s", name_str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001669 Py_XDECREF(name);
1670 if (--n && (size_t)(off+1) < sizeof(buf)) {
1671 buf[off++] = ',';
1672 buf[off] = '\0';
1673 }
1674 }
1675 PyErr_SetString(PyExc_TypeError, buf);
1676 Py_DECREF(set);
Guido van Rossum98f33732002-11-25 21:36:54 +00001677}
1678
Tim Petersea7f75d2002-12-07 21:39:16 +00001679static int
Serhiy Storchaka6b91a592017-12-20 19:21:02 +02001680pmerge(PyObject *acc, PyObject **to_merge, Py_ssize_t to_merge_size)
Benjamin Peterson104b9e02015-02-05 22:29:14 -05001681{
1682 int res = 0;
Serhiy Storchaka6b91a592017-12-20 19:21:02 +02001683 Py_ssize_t i, j, empty_cnt;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001684 int *remain;
Tim Petersea7f75d2002-12-07 21:39:16 +00001685
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001686 /* remain stores an index into each sublist of to_merge.
1687 remain[i] is the index of the next base in to_merge[i]
1688 that is not included in acc.
1689 */
Serhiy Storchaka6b91a592017-12-20 19:21:02 +02001690 remain = PyMem_New(int, to_merge_size);
Victor Stinnera41f0852013-07-12 00:42:14 +02001691 if (remain == NULL) {
1692 PyErr_NoMemory();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001693 return -1;
Victor Stinnera41f0852013-07-12 00:42:14 +02001694 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001695 for (i = 0; i < to_merge_size; i++)
1696 remain[i] = 0;
Guido van Rossum1f121312002-11-14 19:49:16 +00001697
1698 again:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001699 empty_cnt = 0;
1700 for (i = 0; i < to_merge_size; i++) {
1701 PyObject *candidate;
Tim Petersea7f75d2002-12-07 21:39:16 +00001702
Serhiy Storchaka6b91a592017-12-20 19:21:02 +02001703 PyObject *cur_tuple = to_merge[i];
Guido van Rossum1f121312002-11-14 19:49:16 +00001704
Serhiy Storchaka6b91a592017-12-20 19:21:02 +02001705 if (remain[i] >= PyTuple_GET_SIZE(cur_tuple)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001706 empty_cnt++;
1707 continue;
1708 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001709
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001710 /* Choose next candidate for MRO.
Guido van Rossum98f33732002-11-25 21:36:54 +00001711
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001712 The input sequences alone can determine the choice.
1713 If not, choose the class which appears in the MRO
1714 of the earliest direct superclass of the new class.
1715 */
Guido van Rossum98f33732002-11-25 21:36:54 +00001716
Serhiy Storchaka6b91a592017-12-20 19:21:02 +02001717 candidate = PyTuple_GET_ITEM(cur_tuple, remain[i]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001718 for (j = 0; j < to_merge_size; j++) {
Serhiy Storchaka6b91a592017-12-20 19:21:02 +02001719 PyObject *j_lst = to_merge[j];
Benjamin Peterson104b9e02015-02-05 22:29:14 -05001720 if (tail_contains(j_lst, remain[j], candidate))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001721 goto skip; /* continue outer loop */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001722 }
Benjamin Peterson104b9e02015-02-05 22:29:14 -05001723 res = PyList_Append(acc, candidate);
1724 if (res < 0)
1725 goto out;
1726
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001727 for (j = 0; j < to_merge_size; j++) {
Serhiy Storchaka6b91a592017-12-20 19:21:02 +02001728 PyObject *j_lst = to_merge[j];
1729 if (remain[j] < PyTuple_GET_SIZE(j_lst) &&
1730 PyTuple_GET_ITEM(j_lst, remain[j]) == candidate) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001731 remain[j]++;
1732 }
1733 }
1734 goto again;
1735 skip: ;
1736 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001737
Benjamin Peterson104b9e02015-02-05 22:29:14 -05001738 if (empty_cnt != to_merge_size) {
Serhiy Storchaka6b91a592017-12-20 19:21:02 +02001739 set_mro_error(to_merge, to_merge_size, remain);
Benjamin Peterson104b9e02015-02-05 22:29:14 -05001740 res = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001741 }
Benjamin Peterson104b9e02015-02-05 22:29:14 -05001742
1743 out:
Serhiy Storchaka6b91a592017-12-20 19:21:02 +02001744 PyMem_Del(remain);
Benjamin Peterson104b9e02015-02-05 22:29:14 -05001745
1746 return res;
Guido van Rossum1f121312002-11-14 19:49:16 +00001747}
1748
Tim Peters6d6c1a32001-08-02 04:15:00 +00001749static PyObject *
1750mro_implementation(PyTypeObject *type)
1751{
Serhiy Storchaka6b91a592017-12-20 19:21:02 +02001752 PyObject *result;
Benjamin Peterson104b9e02015-02-05 22:29:14 -05001753 PyObject *bases;
Serhiy Storchaka6b91a592017-12-20 19:21:02 +02001754 PyObject **to_merge;
Benjamin Peterson104b9e02015-02-05 22:29:14 -05001755 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001756
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001757 if (type->tp_dict == NULL) {
1758 if (PyType_Ready(type) < 0)
1759 return NULL;
1760 }
Guido van Rossum63517572002-06-18 16:44:57 +00001761
Antoine Pitrou1f1a34c2017-12-20 15:58:21 +01001762 bases = type->tp_bases;
Serhiy Storchaka6b91a592017-12-20 19:21:02 +02001763 assert(PyTuple_Check(bases));
Antoine Pitrou1f1a34c2017-12-20 15:58:21 +01001764 n = PyTuple_GET_SIZE(bases);
Serhiy Storchaka6b91a592017-12-20 19:21:02 +02001765 for (i = 0; i < n; i++) {
1766 PyTypeObject *base = (PyTypeObject *)PyTuple_GET_ITEM(bases, i);
Antoine Pitrou1f1a34c2017-12-20 15:58:21 +01001767 if (base->tp_mro == NULL) {
1768 PyErr_Format(PyExc_TypeError,
1769 "Cannot extend an incomplete type '%.100s'",
1770 base->tp_name);
1771 return NULL;
1772 }
Serhiy Storchaka6b91a592017-12-20 19:21:02 +02001773 assert(PyTuple_Check(base->tp_mro));
1774 }
1775
1776 if (n == 1) {
1777 /* Fast path: if there is a single base, constructing the MRO
1778 * is trivial.
1779 */
1780 PyTypeObject *base = (PyTypeObject *)PyTuple_GET_ITEM(bases, 0);
1781 Py_ssize_t k = PyTuple_GET_SIZE(base->tp_mro);
Antoine Pitrou1f1a34c2017-12-20 15:58:21 +01001782 result = PyTuple_New(k + 1);
1783 if (result == NULL) {
1784 return NULL;
1785 }
1786 Py_INCREF(type);
1787 PyTuple_SET_ITEM(result, 0, (PyObject *) type);
1788 for (i = 0; i < k; i++) {
1789 PyObject *cls = PyTuple_GET_ITEM(base->tp_mro, i);
1790 Py_INCREF(cls);
1791 PyTuple_SET_ITEM(result, i + 1, cls);
1792 }
1793 return result;
1794 }
1795
Serhiy Storchaka6b91a592017-12-20 19:21:02 +02001796 /* This is just a basic sanity check. */
1797 if (check_duplicates(bases) < 0) {
1798 return NULL;
1799 }
1800
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001801 /* Find a superclass linearization that honors the constraints
Serhiy Storchaka6b91a592017-12-20 19:21:02 +02001802 of the explicit tuples of bases and the constraints implied by
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001803 each base class.
Guido van Rossum98f33732002-11-25 21:36:54 +00001804
Serhiy Storchaka6b91a592017-12-20 19:21:02 +02001805 to_merge is an array of tuples, where each tuple is a superclass
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001806 linearization implied by a base class. The last element of
Serhiy Storchaka6b91a592017-12-20 19:21:02 +02001807 to_merge is the declared tuple of bases.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001808 */
Guido van Rossum98f33732002-11-25 21:36:54 +00001809
Serhiy Storchaka6b91a592017-12-20 19:21:02 +02001810 to_merge = PyMem_New(PyObject *, n + 1);
1811 if (to_merge == NULL) {
1812 PyErr_NoMemory();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001813 return NULL;
Serhiy Storchaka6b91a592017-12-20 19:21:02 +02001814 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001815
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001816 for (i = 0; i < n; i++) {
Serhiy Storchaka6b91a592017-12-20 19:21:02 +02001817 PyTypeObject *base = (PyTypeObject *)PyTuple_GET_ITEM(bases, i);
1818 to_merge[i] = base->tp_mro;
1819 }
1820 to_merge[n] = bases;
Benjamin Peterson104b9e02015-02-05 22:29:14 -05001821
Serhiy Storchaka6b91a592017-12-20 19:21:02 +02001822 result = PyList_New(1);
1823 if (result == NULL) {
1824 PyMem_Del(to_merge);
1825 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001826 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001827
Serhiy Storchaka6b91a592017-12-20 19:21:02 +02001828 Py_INCREF(type);
1829 PyList_SET_ITEM(result, 0, (PyObject *)type);
1830 if (pmerge(result, to_merge, n + 1) < 0) {
Benjamin Peterson104b9e02015-02-05 22:29:14 -05001831 Py_CLEAR(result);
Serhiy Storchaka6b91a592017-12-20 19:21:02 +02001832 }
Benjamin Peterson104b9e02015-02-05 22:29:14 -05001833
Serhiy Storchaka6b91a592017-12-20 19:21:02 +02001834 PyMem_Del(to_merge);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001835 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001836}
1837
Serhiy Storchaka5c643a02017-03-19 08:46:44 +02001838/*[clinic input]
1839type.mro
Tim Peters6d6c1a32001-08-02 04:15:00 +00001840
Serhiy Storchaka5c643a02017-03-19 08:46:44 +02001841Return a type's method resolution order.
1842[clinic start generated code]*/
1843
1844static PyObject *
1845type_mro_impl(PyTypeObject *self)
1846/*[clinic end generated code: output=bffc4a39b5b57027 input=28414f4e156db28d]*/
1847{
Antoine Pitrou1f1a34c2017-12-20 15:58:21 +01001848 PyObject *seq;
1849 seq = mro_implementation(self);
1850 if (seq != NULL && !PyList_Check(seq)) {
1851 Py_SETREF(seq, PySequence_List(seq));
1852 }
1853 return seq;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001854}
1855
1856static int
Benjamin Peterson104b9e02015-02-05 22:29:14 -05001857mro_check(PyTypeObject *type, PyObject *mro)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001858{
Benjamin Peterson104b9e02015-02-05 22:29:14 -05001859 PyTypeObject *solid;
1860 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001861
Benjamin Peterson104b9e02015-02-05 22:29:14 -05001862 solid = solid_base(type);
1863
1864 n = PyTuple_GET_SIZE(mro);
1865 for (i = 0; i < n; i++) {
1866 PyTypeObject *base;
1867 PyObject *tmp;
1868
1869 tmp = PyTuple_GET_ITEM(mro, i);
1870 if (!PyType_Check(tmp)) {
1871 PyErr_Format(
1872 PyExc_TypeError,
1873 "mro() returned a non-class ('%.500s')",
1874 Py_TYPE(tmp)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001875 return -1;
Benjamin Peterson104b9e02015-02-05 22:29:14 -05001876 }
Armin Rigo037d1e02005-12-29 17:07:39 +00001877
Benjamin Peterson104b9e02015-02-05 22:29:14 -05001878 base = (PyTypeObject*)tmp;
1879 if (!PyType_IsSubtype(solid, solid_base(base))) {
1880 PyErr_Format(
1881 PyExc_TypeError,
1882 "mro() returned base with unsuitable layout ('%.500s')",
1883 base->tp_name);
1884 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001885 }
1886 }
Benjamin Peterson104b9e02015-02-05 22:29:14 -05001887
1888 return 0;
1889}
1890
1891/* Lookups an mcls.mro method, invokes it and checks the result (if needed,
1892 in case of a custom mro() implementation).
1893
1894 Keep in mind that during execution of this function type->tp_mro
1895 can be replaced due to possible reentrance (for example,
1896 through type_set_bases):
1897
1898 - when looking up the mcls.mro attribute (it could be
1899 a user-provided descriptor);
1900
1901 - from inside a custom mro() itself;
1902
1903 - through a finalizer of the return value of mro().
1904*/
1905static PyObject *
1906mro_invoke(PyTypeObject *type)
1907{
1908 PyObject *mro_result;
1909 PyObject *new_mro;
1910 int custom = (Py_TYPE(type) != &PyType_Type);
1911
1912 if (custom) {
1913 _Py_IDENTIFIER(mro);
Victor Stinner516b9812017-02-09 22:53:47 +01001914 int unbound;
1915 PyObject *mro_meth = lookup_method((PyObject *)type, &PyId_mro,
1916 &unbound);
Benjamin Peterson104b9e02015-02-05 22:29:14 -05001917 if (mro_meth == NULL)
1918 return NULL;
Victor Stinner516b9812017-02-09 22:53:47 +01001919 mro_result = call_unbound_noarg(unbound, mro_meth, (PyObject *)type);
Benjamin Peterson104b9e02015-02-05 22:29:14 -05001920 Py_DECREF(mro_meth);
1921 }
1922 else {
1923 mro_result = mro_implementation(type);
1924 }
1925 if (mro_result == NULL)
1926 return NULL;
1927
1928 new_mro = PySequence_Tuple(mro_result);
1929 Py_DECREF(mro_result);
1930 if (new_mro == NULL)
1931 return NULL;
1932
1933 if (custom && mro_check(type, new_mro) < 0) {
1934 Py_DECREF(new_mro);
1935 return NULL;
1936 }
1937
1938 return new_mro;
1939}
1940
1941/* Calculates and assigns a new MRO to type->tp_mro.
1942 Return values and invariants:
1943
1944 - Returns 1 if a new MRO value has been set to type->tp_mro due to
1945 this call of mro_internal (no tricky reentrancy and no errors).
1946
1947 In case if p_old_mro argument is not NULL, a previous value
1948 of type->tp_mro is put there, and the ownership of this
1949 reference is transferred to a caller.
1950 Otherwise, the previous value (if any) is decref'ed.
1951
1952 - Returns 0 in case when type->tp_mro gets changed because of
1953 reentering here through a custom mro() (see a comment to mro_invoke).
1954
1955 In this case, a refcount of an old type->tp_mro is adjusted
1956 somewhere deeper in the call stack (by the innermost mro_internal
1957 or its caller) and may become zero upon returning from here.
1958 This also implies that the whole hierarchy of subclasses of the type
1959 has seen the new value and updated their MRO accordingly.
1960
1961 - Returns -1 in case of an error.
1962*/
1963static int
1964mro_internal(PyTypeObject *type, PyObject **p_old_mro)
1965{
1966 PyObject *new_mro, *old_mro;
1967 int reent;
1968
1969 /* Keep a reference to be able to do a reentrancy check below.
1970 Don't let old_mro be GC'ed and its address be reused for
1971 another object, like (suddenly!) a new tp_mro. */
1972 old_mro = type->tp_mro;
1973 Py_XINCREF(old_mro);
1974 new_mro = mro_invoke(type); /* might cause reentrance */
1975 reent = (type->tp_mro != old_mro);
1976 Py_XDECREF(old_mro);
1977 if (new_mro == NULL)
1978 return -1;
1979
1980 if (reent) {
1981 Py_DECREF(new_mro);
1982 return 0;
1983 }
1984
1985 type->tp_mro = new_mro;
Christian Heimesa62da1d2008-01-12 19:39:10 +00001986
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001987 type_mro_modified(type, type->tp_mro);
Florent Xiclunaaa6c1d22011-12-12 18:54:29 +01001988 /* corner case: the super class might have been hidden
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001989 from the custom MRO */
1990 type_mro_modified(type, type->tp_bases);
Christian Heimesa62da1d2008-01-12 19:39:10 +00001991
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001992 PyType_Modified(type);
Christian Heimesa62da1d2008-01-12 19:39:10 +00001993
Benjamin Peterson104b9e02015-02-05 22:29:14 -05001994 if (p_old_mro != NULL)
1995 *p_old_mro = old_mro; /* transfer the ownership */
1996 else
1997 Py_XDECREF(old_mro);
1998
1999 return 1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002000}
2001
2002
2003/* Calculate the best base amongst multiple base classes.
2004 This is the first one that's on the path to the "solid base". */
2005
2006static PyTypeObject *
2007best_base(PyObject *bases)
2008{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002009 Py_ssize_t i, n;
2010 PyTypeObject *base, *winner, *candidate, *base_i;
2011 PyObject *base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002012
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002013 assert(PyTuple_Check(bases));
2014 n = PyTuple_GET_SIZE(bases);
2015 assert(n > 0);
2016 base = NULL;
2017 winner = NULL;
2018 for (i = 0; i < n; i++) {
2019 base_proto = PyTuple_GET_ITEM(bases, i);
2020 if (!PyType_Check(base_proto)) {
2021 PyErr_SetString(
2022 PyExc_TypeError,
2023 "bases must be types");
2024 return NULL;
2025 }
2026 base_i = (PyTypeObject *)base_proto;
2027 if (base_i->tp_dict == NULL) {
2028 if (PyType_Ready(base_i) < 0)
2029 return NULL;
2030 }
Benjamin Petersonbd6c41a2015-10-06 19:36:54 -07002031 if (!PyType_HasFeature(base_i, Py_TPFLAGS_BASETYPE)) {
2032 PyErr_Format(PyExc_TypeError,
2033 "type '%.100s' is not an acceptable base type",
2034 base_i->tp_name);
2035 return NULL;
2036 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002037 candidate = solid_base(base_i);
2038 if (winner == NULL) {
2039 winner = candidate;
2040 base = base_i;
2041 }
2042 else if (PyType_IsSubtype(winner, candidate))
2043 ;
2044 else if (PyType_IsSubtype(candidate, winner)) {
2045 winner = candidate;
2046 base = base_i;
2047 }
2048 else {
2049 PyErr_SetString(
2050 PyExc_TypeError,
2051 "multiple bases have "
2052 "instance lay-out conflict");
2053 return NULL;
2054 }
2055 }
Florent Xiclunaaa6c1d22011-12-12 18:54:29 +01002056 assert (base != NULL);
2057
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002058 return base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002059}
2060
2061static int
2062extra_ivars(PyTypeObject *type, PyTypeObject *base)
2063{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002064 size_t t_size = type->tp_basicsize;
2065 size_t b_size = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002066
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002067 assert(t_size >= b_size); /* Else type smaller than base! */
2068 if (type->tp_itemsize || base->tp_itemsize) {
2069 /* If itemsize is involved, stricter rules */
2070 return t_size != b_size ||
2071 type->tp_itemsize != base->tp_itemsize;
2072 }
2073 if (type->tp_weaklistoffset && base->tp_weaklistoffset == 0 &&
2074 type->tp_weaklistoffset + sizeof(PyObject *) == t_size &&
2075 type->tp_flags & Py_TPFLAGS_HEAPTYPE)
2076 t_size -= sizeof(PyObject *);
2077 if (type->tp_dictoffset && base->tp_dictoffset == 0 &&
2078 type->tp_dictoffset + sizeof(PyObject *) == t_size &&
2079 type->tp_flags & Py_TPFLAGS_HEAPTYPE)
2080 t_size -= sizeof(PyObject *);
Guido van Rossum9676b222001-08-17 20:32:36 +00002081
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002082 return t_size != b_size;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002083}
2084
2085static PyTypeObject *
2086solid_base(PyTypeObject *type)
2087{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002088 PyTypeObject *base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002089
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002090 if (type->tp_base)
2091 base = solid_base(type->tp_base);
2092 else
2093 base = &PyBaseObject_Type;
2094 if (extra_ivars(type, base))
2095 return type;
2096 else
2097 return base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002098}
2099
Jeremy Hylton938ace62002-07-17 16:30:39 +00002100static void object_dealloc(PyObject *);
2101static int object_init(PyObject *, PyObject *, PyObject *);
2102static int update_slot(PyTypeObject *, PyObject *);
2103static void fixup_slot_dispatchers(PyTypeObject *);
Nick Coghland78448e2016-07-30 16:26:03 +10002104static int set_names(PyTypeObject *);
2105static int init_subclass(PyTypeObject *, PyObject *);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002106
Guido van Rossum360e4b82007-05-14 22:51:27 +00002107/*
2108 * Helpers for __dict__ descriptor. We don't want to expose the dicts
2109 * inherited from various builtin types. The builtin base usually provides
2110 * its own __dict__ descriptor, so we use that when we can.
2111 */
2112static PyTypeObject *
2113get_builtin_base_with_dict(PyTypeObject *type)
2114{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002115 while (type->tp_base != NULL) {
2116 if (type->tp_dictoffset != 0 &&
2117 !(type->tp_flags & Py_TPFLAGS_HEAPTYPE))
2118 return type;
2119 type = type->tp_base;
2120 }
2121 return NULL;
Guido van Rossum360e4b82007-05-14 22:51:27 +00002122}
2123
2124static PyObject *
2125get_dict_descriptor(PyTypeObject *type)
2126{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002127 PyObject *descr;
Guido van Rossum360e4b82007-05-14 22:51:27 +00002128
Victor Stinner3c1e4812012-03-26 22:10:51 +02002129 descr = _PyType_LookupId(type, &PyId___dict__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002130 if (descr == NULL || !PyDescr_IsData(descr))
2131 return NULL;
Guido van Rossum360e4b82007-05-14 22:51:27 +00002132
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002133 return descr;
Guido van Rossum360e4b82007-05-14 22:51:27 +00002134}
2135
2136static void
2137raise_dict_descr_error(PyObject *obj)
2138{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002139 PyErr_Format(PyExc_TypeError,
2140 "this __dict__ descriptor does not support "
2141 "'%.200s' objects", Py_TYPE(obj)->tp_name);
Guido van Rossum360e4b82007-05-14 22:51:27 +00002142}
2143
Tim Peters6d6c1a32001-08-02 04:15:00 +00002144static PyObject *
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00002145subtype_dict(PyObject *obj, void *context)
2146{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002147 PyTypeObject *base;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00002148
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002149 base = get_builtin_base_with_dict(Py_TYPE(obj));
2150 if (base != NULL) {
2151 descrgetfunc func;
2152 PyObject *descr = get_dict_descriptor(base);
2153 if (descr == NULL) {
2154 raise_dict_descr_error(obj);
2155 return NULL;
2156 }
2157 func = Py_TYPE(descr)->tp_descr_get;
2158 if (func == NULL) {
2159 raise_dict_descr_error(obj);
2160 return NULL;
2161 }
2162 return func(descr, obj, (PyObject *)(Py_TYPE(obj)));
2163 }
Benjamin Peterson8eb12692012-02-19 19:59:10 -05002164 return PyObject_GenericGetDict(obj, context);
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00002165}
2166
Guido van Rossum6661be32001-10-26 04:26:12 +00002167static int
2168subtype_setdict(PyObject *obj, PyObject *value, void *context)
2169{
Serhiy Storchaka576f1322016-01-05 21:27:54 +02002170 PyObject **dictptr;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002171 PyTypeObject *base;
Guido van Rossum6661be32001-10-26 04:26:12 +00002172
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002173 base = get_builtin_base_with_dict(Py_TYPE(obj));
2174 if (base != NULL) {
2175 descrsetfunc func;
2176 PyObject *descr = get_dict_descriptor(base);
2177 if (descr == NULL) {
2178 raise_dict_descr_error(obj);
2179 return -1;
2180 }
2181 func = Py_TYPE(descr)->tp_descr_set;
2182 if (func == NULL) {
2183 raise_dict_descr_error(obj);
2184 return -1;
2185 }
2186 return func(descr, obj, value);
2187 }
Benjamin Peterson8eb12692012-02-19 19:59:10 -05002188 /* Almost like PyObject_GenericSetDict, but allow __dict__ to be deleted. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002189 dictptr = _PyObject_GetDictPtr(obj);
2190 if (dictptr == NULL) {
2191 PyErr_SetString(PyExc_AttributeError,
2192 "This object has no __dict__");
2193 return -1;
2194 }
Benjamin Peterson006c5a22012-02-19 20:36:12 -05002195 if (value != NULL && !PyDict_Check(value)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002196 PyErr_Format(PyExc_TypeError,
2197 "__dict__ must be set to a dictionary, "
2198 "not a '%.200s'", Py_TYPE(value)->tp_name);
2199 return -1;
2200 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002201 Py_XINCREF(value);
Serhiy Storchakaec397562016-04-06 09:50:03 +03002202 Py_XSETREF(*dictptr, value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002203 return 0;
Guido van Rossum6661be32001-10-26 04:26:12 +00002204}
2205
Guido van Rossumad47da02002-08-12 19:05:44 +00002206static PyObject *
2207subtype_getweakref(PyObject *obj, void *context)
2208{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002209 PyObject **weaklistptr;
2210 PyObject *result;
Guido van Rossumad47da02002-08-12 19:05:44 +00002211
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002212 if (Py_TYPE(obj)->tp_weaklistoffset == 0) {
2213 PyErr_SetString(PyExc_AttributeError,
2214 "This object has no __weakref__");
2215 return NULL;
2216 }
2217 assert(Py_TYPE(obj)->tp_weaklistoffset > 0);
2218 assert(Py_TYPE(obj)->tp_weaklistoffset + sizeof(PyObject *) <=
2219 (size_t)(Py_TYPE(obj)->tp_basicsize));
2220 weaklistptr = (PyObject **)
2221 ((char *)obj + Py_TYPE(obj)->tp_weaklistoffset);
2222 if (*weaklistptr == NULL)
2223 result = Py_None;
2224 else
2225 result = *weaklistptr;
2226 Py_INCREF(result);
2227 return result;
Guido van Rossumad47da02002-08-12 19:05:44 +00002228}
2229
Guido van Rossum373c7412003-01-07 13:41:37 +00002230/* Three variants on the subtype_getsets list. */
2231
2232static PyGetSetDef subtype_getsets_full[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002233 {"__dict__", subtype_dict, subtype_setdict,
2234 PyDoc_STR("dictionary for instance variables (if defined)")},
2235 {"__weakref__", subtype_getweakref, NULL,
2236 PyDoc_STR("list of weak references to the object (if defined)")},
2237 {0}
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00002238};
2239
Guido van Rossum373c7412003-01-07 13:41:37 +00002240static PyGetSetDef subtype_getsets_dict_only[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002241 {"__dict__", subtype_dict, subtype_setdict,
2242 PyDoc_STR("dictionary for instance variables (if defined)")},
2243 {0}
Guido van Rossum373c7412003-01-07 13:41:37 +00002244};
2245
2246static PyGetSetDef subtype_getsets_weakref_only[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002247 {"__weakref__", subtype_getweakref, NULL,
2248 PyDoc_STR("list of weak references to the object (if defined)")},
2249 {0}
Guido van Rossum373c7412003-01-07 13:41:37 +00002250};
2251
Guido van Rossum9923ffe2002-06-04 19:52:53 +00002252static int
2253valid_identifier(PyObject *s)
2254{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002255 if (!PyUnicode_Check(s)) {
2256 PyErr_Format(PyExc_TypeError,
2257 "__slots__ items must be strings, not '%.200s'",
2258 Py_TYPE(s)->tp_name);
2259 return 0;
2260 }
2261 if (!PyUnicode_IsIdentifier(s)) {
2262 PyErr_SetString(PyExc_TypeError,
2263 "__slots__ must be identifiers");
2264 return 0;
2265 }
2266 return 1;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00002267}
2268
Guido van Rossumd8faa362007-04-27 19:54:29 +00002269/* Forward */
2270static int
2271object_init(PyObject *self, PyObject *args, PyObject *kwds);
2272
2273static int
2274type_init(PyObject *cls, PyObject *args, PyObject *kwds)
2275{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002276 int res;
Guido van Rossumd8faa362007-04-27 19:54:29 +00002277
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002278 assert(args != NULL && PyTuple_Check(args));
2279 assert(kwds == NULL || PyDict_Check(kwds));
Guido van Rossumd8faa362007-04-27 19:54:29 +00002280
Nick Coghland78448e2016-07-30 16:26:03 +10002281 if (kwds != NULL && PyTuple_Check(args) && PyTuple_GET_SIZE(args) == 1 &&
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02002282 PyDict_Check(kwds) && PyDict_GET_SIZE(kwds) != 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002283 PyErr_SetString(PyExc_TypeError,
2284 "type.__init__() takes no keyword arguments");
2285 return -1;
2286 }
Guido van Rossumd8faa362007-04-27 19:54:29 +00002287
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002288 if (args != NULL && PyTuple_Check(args) &&
2289 (PyTuple_GET_SIZE(args) != 1 && PyTuple_GET_SIZE(args) != 3)) {
2290 PyErr_SetString(PyExc_TypeError,
2291 "type.__init__() takes 1 or 3 arguments");
2292 return -1;
2293 }
Guido van Rossumd8faa362007-04-27 19:54:29 +00002294
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002295 /* Call object.__init__(self) now. */
2296 /* XXX Could call super(type, cls).__init__() but what's the point? */
2297 args = PyTuple_GetSlice(args, 0, 0);
2298 res = object_init(cls, args, NULL);
2299 Py_DECREF(args);
2300 return res;
Guido van Rossumd8faa362007-04-27 19:54:29 +00002301}
2302
Victor Stinner4ca1cf32012-10-30 23:40:45 +01002303unsigned long
Martin v. Löwis738236d2011-02-05 20:35:29 +00002304PyType_GetFlags(PyTypeObject *type)
2305{
2306 return type->tp_flags;
2307}
2308
Nick Coghlande31b192011-10-23 22:04:16 +10002309/* Determine the most derived metatype. */
2310PyTypeObject *
2311_PyType_CalculateMetaclass(PyTypeObject *metatype, PyObject *bases)
2312{
2313 Py_ssize_t i, nbases;
2314 PyTypeObject *winner;
2315 PyObject *tmp;
2316 PyTypeObject *tmptype;
2317
2318 /* Determine the proper metatype to deal with this,
2319 and check for metatype conflicts while we're at it.
2320 Note that if some other metatype wins to contract,
2321 it's possible that its instances are not types. */
2322
2323 nbases = PyTuple_GET_SIZE(bases);
2324 winner = metatype;
2325 for (i = 0; i < nbases; i++) {
2326 tmp = PyTuple_GET_ITEM(bases, i);
2327 tmptype = Py_TYPE(tmp);
2328 if (PyType_IsSubtype(winner, tmptype))
2329 continue;
2330 if (PyType_IsSubtype(tmptype, winner)) {
2331 winner = tmptype;
2332 continue;
2333 }
2334 /* else: */
2335 PyErr_SetString(PyExc_TypeError,
2336 "metaclass conflict: "
2337 "the metaclass of a derived class "
2338 "must be a (non-strict) subclass "
2339 "of the metaclasses of all its bases");
2340 return NULL;
2341 }
2342 return winner;
2343}
2344
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00002345static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00002346type_new(PyTypeObject *metatype, PyObject *args, PyObject *kwds)
2347{
Victor Stinner6f738742012-02-25 01:22:36 +01002348 PyObject *name, *bases = NULL, *orig_dict, *dict = NULL;
Nick Coghlan944368e2016-09-11 14:45:49 +10002349 PyObject *qualname, *slots = NULL, *tmp, *newslots, *cell;
Victor Stinner6f738742012-02-25 01:22:36 +01002350 PyTypeObject *type = NULL, *base, *tmptype, *winner;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002351 PyHeapTypeObject *et;
2352 PyMemberDef *mp;
Serhiy Storchaka42bf8fc2015-12-30 21:40:49 +02002353 Py_ssize_t i, nbases, nslots, slotoffset, name_size;
2354 int j, may_add_dict, may_add_weak, add_dict, add_weak;
Victor Stinner3c1e4812012-03-26 22:10:51 +02002355 _Py_IDENTIFIER(__qualname__);
2356 _Py_IDENTIFIER(__slots__);
Nick Coghlan944368e2016-09-11 14:45:49 +10002357 _Py_IDENTIFIER(__classcell__);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002358
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002359 assert(args != NULL && PyTuple_Check(args));
2360 assert(kwds == NULL || PyDict_Check(kwds));
Tim Peters3abca122001-10-27 19:37:48 +00002361
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002362 /* Special case: type(x) should return x->ob_type */
Berker Peksag3f015a62016-08-19 11:04:07 +03002363 /* We only want type itself to accept the one-argument form (#27157)
2364 Note: We don't call PyType_CheckExact as that also allows subclasses */
2365 if (metatype == &PyType_Type) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002366 const Py_ssize_t nargs = PyTuple_GET_SIZE(args);
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02002367 const Py_ssize_t nkwds = kwds == NULL ? 0 : PyDict_GET_SIZE(kwds);
Tim Peters3abca122001-10-27 19:37:48 +00002368
Berker Peksag3f015a62016-08-19 11:04:07 +03002369 if (nargs == 1 && nkwds == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002370 PyObject *x = PyTuple_GET_ITEM(args, 0);
2371 Py_INCREF(Py_TYPE(x));
2372 return (PyObject *) Py_TYPE(x);
2373 }
Tim Peters3abca122001-10-27 19:37:48 +00002374
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002375 /* SF bug 475327 -- if that didn't trigger, we need 3
Berker Peksag78e24d42018-01-04 13:24:45 +03002376 arguments. but PyArg_ParseTuple below may give
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002377 a msg saying type() needs exactly 3. */
Nick Coghland78448e2016-07-30 16:26:03 +10002378 if (nargs != 3) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002379 PyErr_SetString(PyExc_TypeError,
2380 "type() takes 1 or 3 arguments");
2381 return NULL;
2382 }
2383 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002384
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002385 /* Check arguments: (name, bases, dict) */
Berker Peksag3f015a62016-08-19 11:04:07 +03002386 if (!PyArg_ParseTuple(args, "UO!O!:type.__new__", &name, &PyTuple_Type,
2387 &bases, &PyDict_Type, &orig_dict))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002388 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002389
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002390 /* Adjust for empty tuple bases */
Nick Coghlande31b192011-10-23 22:04:16 +10002391 nbases = PyTuple_GET_SIZE(bases);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002392 if (nbases == 0) {
scoder2102c782017-10-01 10:37:47 +02002393 base = &PyBaseObject_Type;
2394 bases = PyTuple_Pack(1, base);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002395 if (bases == NULL)
scoder2102c782017-10-01 10:37:47 +02002396 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002397 nbases = 1;
2398 }
scoder2102c782017-10-01 10:37:47 +02002399 else {
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +01002400 _Py_IDENTIFIER(__mro_entries__);
2401 for (i = 0; i < nbases; i++) {
2402 tmp = PyTuple_GET_ITEM(bases, i);
2403 if (PyType_Check(tmp)) {
2404 continue;
2405 }
Serhiy Storchakaf320be72018-01-25 10:49:40 +02002406 if (_PyObject_LookupAttrId(tmp, &PyId___mro_entries__, &tmp) < 0) {
2407 return NULL;
2408 }
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +01002409 if (tmp != NULL) {
2410 PyErr_SetString(PyExc_TypeError,
2411 "type() doesn't support MRO entry resolution; "
2412 "use types.new_class()");
2413 Py_DECREF(tmp);
2414 return NULL;
2415 }
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +01002416 }
scoder2102c782017-10-01 10:37:47 +02002417 /* Search the bases for the proper metatype to deal with this: */
2418 winner = _PyType_CalculateMetaclass(metatype, bases);
2419 if (winner == NULL) {
2420 return NULL;
2421 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002422
scoder2102c782017-10-01 10:37:47 +02002423 if (winner != metatype) {
2424 if (winner->tp_new != type_new) /* Pass it to the winner */
2425 return winner->tp_new(winner, args, kwds);
2426 metatype = winner;
2427 }
2428
2429 /* Calculate best base, and check that all bases are type objects */
2430 base = best_base(bases);
2431 if (base == NULL) {
2432 return NULL;
2433 }
2434
2435 Py_INCREF(bases);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002436 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002437
scoder2102c782017-10-01 10:37:47 +02002438 /* Use "goto error" from this point on as we now own the reference to "bases". */
2439
Victor Stinner6f738742012-02-25 01:22:36 +01002440 dict = PyDict_Copy(orig_dict);
2441 if (dict == NULL)
2442 goto error;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002443
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002444 /* Check for a __slots__ sequence variable in dict, and count it */
Victor Stinner3c1e4812012-03-26 22:10:51 +02002445 slots = _PyDict_GetItemId(dict, &PyId___slots__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002446 nslots = 0;
2447 add_dict = 0;
2448 add_weak = 0;
2449 may_add_dict = base->tp_dictoffset == 0;
2450 may_add_weak = base->tp_weaklistoffset == 0 && base->tp_itemsize == 0;
2451 if (slots == NULL) {
2452 if (may_add_dict) {
2453 add_dict++;
2454 }
2455 if (may_add_weak) {
2456 add_weak++;
2457 }
2458 }
2459 else {
2460 /* Have slots */
Guido van Rossumad47da02002-08-12 19:05:44 +00002461
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002462 /* Make it into a tuple */
2463 if (PyUnicode_Check(slots))
2464 slots = PyTuple_Pack(1, slots);
2465 else
2466 slots = PySequence_Tuple(slots);
Victor Stinner6f738742012-02-25 01:22:36 +01002467 if (slots == NULL)
2468 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002469 assert(PyTuple_Check(slots));
Guido van Rossumad47da02002-08-12 19:05:44 +00002470
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002471 /* Are slots allowed? */
2472 nslots = PyTuple_GET_SIZE(slots);
2473 if (nslots > 0 && base->tp_itemsize != 0) {
2474 PyErr_Format(PyExc_TypeError,
2475 "nonempty __slots__ "
2476 "not supported for subtype of '%s'",
2477 base->tp_name);
Victor Stinner6f738742012-02-25 01:22:36 +01002478 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002479 }
Guido van Rossumad47da02002-08-12 19:05:44 +00002480
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002481 /* Check for valid slot names and two special cases */
2482 for (i = 0; i < nslots; i++) {
2483 PyObject *tmp = PyTuple_GET_ITEM(slots, i);
2484 if (!valid_identifier(tmp))
Victor Stinner6f738742012-02-25 01:22:36 +01002485 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002486 assert(PyUnicode_Check(tmp));
Serhiy Storchakaf5894dd2016-11-16 15:40:39 +02002487 if (_PyUnicode_EqualToASCIIId(tmp, &PyId___dict__)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002488 if (!may_add_dict || add_dict) {
2489 PyErr_SetString(PyExc_TypeError,
2490 "__dict__ slot disallowed: "
2491 "we already got one");
Victor Stinner6f738742012-02-25 01:22:36 +01002492 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002493 }
2494 add_dict++;
2495 }
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02002496 if (_PyUnicode_EqualToASCIIString(tmp, "__weakref__")) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002497 if (!may_add_weak || add_weak) {
2498 PyErr_SetString(PyExc_TypeError,
2499 "__weakref__ slot disallowed: "
2500 "either we already got one, "
2501 "or __itemsize__ != 0");
Victor Stinner6f738742012-02-25 01:22:36 +01002502 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002503 }
2504 add_weak++;
2505 }
2506 }
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00002507
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002508 /* Copy slots into a list, mangle names and sort them.
2509 Sorted names are needed for __class__ assignment.
2510 Convert them back to tuple at the end.
2511 */
2512 newslots = PyList_New(nslots - add_dict - add_weak);
2513 if (newslots == NULL)
Victor Stinner6f738742012-02-25 01:22:36 +01002514 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002515 for (i = j = 0; i < nslots; i++) {
2516 tmp = PyTuple_GET_ITEM(slots, i);
2517 if ((add_dict &&
Serhiy Storchakaf5894dd2016-11-16 15:40:39 +02002518 _PyUnicode_EqualToASCIIId(tmp, &PyId___dict__)) ||
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002519 (add_weak &&
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02002520 _PyUnicode_EqualToASCIIString(tmp, "__weakref__")))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002521 continue;
2522 tmp =_Py_Mangle(name, tmp);
Benjamin Petersonae13c882011-08-16 22:26:48 -05002523 if (!tmp) {
2524 Py_DECREF(newslots);
Victor Stinner6f738742012-02-25 01:22:36 +01002525 goto error;
Benjamin Petersonae13c882011-08-16 22:26:48 -05002526 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002527 PyList_SET_ITEM(newslots, j, tmp);
Benjamin Petersonc4085c82011-08-16 18:53:26 -05002528 if (PyDict_GetItem(dict, tmp)) {
Xiang Zhangc393ee82017-03-08 11:18:49 +08002529 /* CPython inserts __qualname__ and __classcell__ (when needed)
2530 into the namespace when creating a class. They will be deleted
2531 below so won't act as class variables. */
2532 if (!_PyUnicode_EqualToASCIIId(tmp, &PyId___qualname__) &&
2533 !_PyUnicode_EqualToASCIIId(tmp, &PyId___classcell__)) {
2534 PyErr_Format(PyExc_ValueError,
2535 "%R in __slots__ conflicts with class variable",
2536 tmp);
2537 Py_DECREF(newslots);
2538 goto error;
2539 }
Benjamin Petersonc4085c82011-08-16 18:53:26 -05002540 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002541 j++;
2542 }
2543 assert(j == nslots - add_dict - add_weak);
2544 nslots = j;
Victor Stinner6f738742012-02-25 01:22:36 +01002545 Py_CLEAR(slots);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002546 if (PyList_Sort(newslots) == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002547 Py_DECREF(newslots);
Victor Stinner6f738742012-02-25 01:22:36 +01002548 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002549 }
2550 slots = PyList_AsTuple(newslots);
2551 Py_DECREF(newslots);
Victor Stinner6f738742012-02-25 01:22:36 +01002552 if (slots == NULL)
2553 goto error;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00002554
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002555 /* Secondary bases may provide weakrefs or dict */
2556 if (nbases > 1 &&
2557 ((may_add_dict && !add_dict) ||
2558 (may_add_weak && !add_weak))) {
2559 for (i = 0; i < nbases; i++) {
2560 tmp = PyTuple_GET_ITEM(bases, i);
2561 if (tmp == (PyObject *)base)
2562 continue; /* Skip primary base */
2563 assert(PyType_Check(tmp));
2564 tmptype = (PyTypeObject *)tmp;
2565 if (may_add_dict && !add_dict &&
2566 tmptype->tp_dictoffset != 0)
2567 add_dict++;
2568 if (may_add_weak && !add_weak &&
2569 tmptype->tp_weaklistoffset != 0)
2570 add_weak++;
2571 if (may_add_dict && !add_dict)
2572 continue;
2573 if (may_add_weak && !add_weak)
2574 continue;
2575 /* Nothing more to check */
2576 break;
2577 }
2578 }
2579 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002580
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002581 /* Allocate the type object */
2582 type = (PyTypeObject *)metatype->tp_alloc(metatype, nslots);
Victor Stinner6f738742012-02-25 01:22:36 +01002583 if (type == NULL)
2584 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002585
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002586 /* Keep name and slots alive in the extended type object */
2587 et = (PyHeapTypeObject *)type;
2588 Py_INCREF(name);
2589 et->ht_name = name;
2590 et->ht_slots = slots;
Victor Stinner6f738742012-02-25 01:22:36 +01002591 slots = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002592
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002593 /* Initialize tp_flags */
2594 type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE |
Antoine Pitrou796564c2013-07-30 19:59:21 +02002595 Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_FINALIZE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002596 if (base->tp_flags & Py_TPFLAGS_HAVE_GC)
2597 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossumdc91b992001-08-08 22:26:22 +00002598
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002599 /* Initialize essential fields */
Yury Selivanov75445082015-05-11 22:57:16 -04002600 type->tp_as_async = &et->as_async;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002601 type->tp_as_number = &et->as_number;
2602 type->tp_as_sequence = &et->as_sequence;
2603 type->tp_as_mapping = &et->as_mapping;
2604 type->tp_as_buffer = &et->as_buffer;
Serhiy Storchaka42bf8fc2015-12-30 21:40:49 +02002605 type->tp_name = PyUnicode_AsUTF8AndSize(name, &name_size);
Victor Stinner6f738742012-02-25 01:22:36 +01002606 if (!type->tp_name)
2607 goto error;
Serhiy Storchaka42bf8fc2015-12-30 21:40:49 +02002608 if (strlen(type->tp_name) != (size_t)name_size) {
2609 PyErr_SetString(PyExc_ValueError,
2610 "type name must not contain null characters");
2611 goto error;
2612 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002613
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002614 /* Set tp_base and tp_bases */
2615 type->tp_bases = bases;
Victor Stinner6f738742012-02-25 01:22:36 +01002616 bases = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002617 Py_INCREF(base);
2618 type->tp_base = base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002619
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002620 /* Initialize tp_dict from passed-in dict */
Victor Stinner6f738742012-02-25 01:22:36 +01002621 Py_INCREF(dict);
2622 type->tp_dict = dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002623
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002624 /* Set __module__ in the dict */
Victor Stinner3c1e4812012-03-26 22:10:51 +02002625 if (_PyDict_GetItemId(dict, &PyId___module__) == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002626 tmp = PyEval_GetGlobals();
2627 if (tmp != NULL) {
Victor Stinner3c1e4812012-03-26 22:10:51 +02002628 tmp = _PyDict_GetItemId(tmp, &PyId___name__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002629 if (tmp != NULL) {
Victor Stinner3c1e4812012-03-26 22:10:51 +02002630 if (_PyDict_SetItemId(dict, &PyId___module__,
2631 tmp) < 0)
Victor Stinner6f738742012-02-25 01:22:36 +01002632 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002633 }
2634 }
2635 }
Guido van Rossumc3542212001-08-16 09:18:56 +00002636
Victor Stinner6f738742012-02-25 01:22:36 +01002637 /* Set ht_qualname to dict['__qualname__'] if available, else to
2638 __name__. The __qualname__ accessor will look for ht_qualname.
2639 */
Victor Stinner3c1e4812012-03-26 22:10:51 +02002640 qualname = _PyDict_GetItemId(dict, &PyId___qualname__);
Victor Stinner6f738742012-02-25 01:22:36 +01002641 if (qualname != NULL) {
2642 if (!PyUnicode_Check(qualname)) {
2643 PyErr_Format(PyExc_TypeError,
2644 "type __qualname__ must be a str, not %s",
2645 Py_TYPE(qualname)->tp_name);
2646 goto error;
2647 }
2648 }
Benjamin Peterson8afa7fa2012-10-30 23:51:03 -04002649 et->ht_qualname = qualname ? qualname : et->ht_name;
2650 Py_INCREF(et->ht_qualname);
Nick Coghlan944368e2016-09-11 14:45:49 +10002651 if (qualname != NULL && _PyDict_DelItemId(dict, &PyId___qualname__) < 0)
Benjamin Peterson8afa7fa2012-10-30 23:51:03 -04002652 goto error;
Victor Stinner6f738742012-02-25 01:22:36 +01002653
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002654 /* Set tp_doc to a copy of dict['__doc__'], if the latter is there
2655 and is a string. The __doc__ accessor will first look for tp_doc;
2656 if that fails, it will still look into __dict__.
2657 */
2658 {
Victor Stinner3c1e4812012-03-26 22:10:51 +02002659 PyObject *doc = _PyDict_GetItemId(dict, &PyId___doc__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002660 if (doc != NULL && PyUnicode_Check(doc)) {
2661 Py_ssize_t len;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02002662 const char *doc_str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002663 char *tp_doc;
Alexandre Vassalottia85998a2008-05-03 18:24:43 +00002664
Serhiy Storchaka06515832016-11-20 09:13:07 +02002665 doc_str = PyUnicode_AsUTF8(doc);
Victor Stinner6f738742012-02-25 01:22:36 +01002666 if (doc_str == NULL)
2667 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002668 /* Silently truncate the docstring if it contains null bytes. */
2669 len = strlen(doc_str);
2670 tp_doc = (char *)PyObject_MALLOC(len + 1);
Victor Stinner53510cd2013-07-15 19:34:20 +02002671 if (tp_doc == NULL) {
2672 PyErr_NoMemory();
Victor Stinner6f738742012-02-25 01:22:36 +01002673 goto error;
Victor Stinner53510cd2013-07-15 19:34:20 +02002674 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002675 memcpy(tp_doc, doc_str, len + 1);
2676 type->tp_doc = tp_doc;
2677 }
2678 }
Tim Peters2f93e282001-10-04 05:27:00 +00002679
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002680 /* Special-case __new__: if it's a plain function,
2681 make it a static function */
Victor Stinner3c1e4812012-03-26 22:10:51 +02002682 tmp = _PyDict_GetItemId(dict, &PyId___new__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002683 if (tmp != NULL && PyFunction_Check(tmp)) {
2684 tmp = PyStaticMethod_New(tmp);
Victor Stinner6f738742012-02-25 01:22:36 +01002685 if (tmp == NULL)
2686 goto error;
Serhiy Storchaka484c9132016-06-05 10:48:36 +03002687 if (_PyDict_SetItemId(dict, &PyId___new__, tmp) < 0) {
2688 Py_DECREF(tmp);
Victor Stinner3c1e4812012-03-26 22:10:51 +02002689 goto error;
Serhiy Storchaka484c9132016-06-05 10:48:36 +03002690 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002691 Py_DECREF(tmp);
2692 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002693
Serhiy Storchakace5b0e92018-01-05 00:21:41 +02002694 /* Special-case __init_subclass__ and __class_getitem__:
2695 if they are plain functions, make them classmethods */
Nick Coghland78448e2016-07-30 16:26:03 +10002696 tmp = _PyDict_GetItemId(dict, &PyId___init_subclass__);
2697 if (tmp != NULL && PyFunction_Check(tmp)) {
2698 tmp = PyClassMethod_New(tmp);
2699 if (tmp == NULL)
2700 goto error;
2701 if (_PyDict_SetItemId(dict, &PyId___init_subclass__, tmp) < 0) {
2702 Py_DECREF(tmp);
2703 goto error;
2704 }
2705 Py_DECREF(tmp);
2706 }
2707
Serhiy Storchakace5b0e92018-01-05 00:21:41 +02002708 tmp = _PyDict_GetItemId(dict, &PyId___class_getitem__);
2709 if (tmp != NULL && PyFunction_Check(tmp)) {
2710 tmp = PyClassMethod_New(tmp);
2711 if (tmp == NULL)
2712 goto error;
2713 if (_PyDict_SetItemId(dict, &PyId___class_getitem__, tmp) < 0) {
2714 Py_DECREF(tmp);
2715 goto error;
2716 }
2717 Py_DECREF(tmp);
2718 }
2719
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002720 /* Add descriptors for custom slots from __slots__, or for __dict__ */
2721 mp = PyHeapType_GET_MEMBERS(et);
2722 slotoffset = base->tp_basicsize;
Victor Stinner6f738742012-02-25 01:22:36 +01002723 if (et->ht_slots != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002724 for (i = 0; i < nslots; i++, mp++) {
Serhiy Storchaka06515832016-11-20 09:13:07 +02002725 mp->name = PyUnicode_AsUTF8(
Victor Stinner6f738742012-02-25 01:22:36 +01002726 PyTuple_GET_ITEM(et->ht_slots, i));
2727 if (mp->name == NULL)
2728 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002729 mp->type = T_OBJECT_EX;
2730 mp->offset = slotoffset;
Guido van Rossumd8faa362007-04-27 19:54:29 +00002731
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002732 /* __dict__ and __weakref__ are already filtered out */
2733 assert(strcmp(mp->name, "__dict__") != 0);
2734 assert(strcmp(mp->name, "__weakref__") != 0);
Guido van Rossumd8faa362007-04-27 19:54:29 +00002735
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002736 slotoffset += sizeof(PyObject *);
2737 }
2738 }
2739 if (add_dict) {
2740 if (base->tp_itemsize)
2741 type->tp_dictoffset = -(long)sizeof(PyObject *);
2742 else
2743 type->tp_dictoffset = slotoffset;
2744 slotoffset += sizeof(PyObject *);
2745 }
2746 if (add_weak) {
2747 assert(!base->tp_itemsize);
2748 type->tp_weaklistoffset = slotoffset;
2749 slotoffset += sizeof(PyObject *);
2750 }
2751 type->tp_basicsize = slotoffset;
2752 type->tp_itemsize = base->tp_itemsize;
2753 type->tp_members = PyHeapType_GET_MEMBERS(et);
Guido van Rossum373c7412003-01-07 13:41:37 +00002754
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002755 if (type->tp_weaklistoffset && type->tp_dictoffset)
2756 type->tp_getset = subtype_getsets_full;
2757 else if (type->tp_weaklistoffset && !type->tp_dictoffset)
2758 type->tp_getset = subtype_getsets_weakref_only;
2759 else if (!type->tp_weaklistoffset && type->tp_dictoffset)
2760 type->tp_getset = subtype_getsets_dict_only;
2761 else
2762 type->tp_getset = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002763
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002764 /* Special case some slots */
2765 if (type->tp_dictoffset != 0 || nslots > 0) {
2766 if (base->tp_getattr == NULL && base->tp_getattro == NULL)
2767 type->tp_getattro = PyObject_GenericGetAttr;
2768 if (base->tp_setattr == NULL && base->tp_setattro == NULL)
2769 type->tp_setattro = PyObject_GenericSetAttr;
2770 }
2771 type->tp_dealloc = subtype_dealloc;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002772
Antoine Pitroua63cc212015-04-13 20:10:06 +02002773 /* Enable GC unless this class is not adding new instance variables and
2774 the base class did not use GC. */
2775 if ((base->tp_flags & Py_TPFLAGS_HAVE_GC) ||
2776 type->tp_basicsize > base->tp_basicsize)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002777 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossum9475a232001-10-05 20:51:39 +00002778
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002779 /* Always override allocation strategy to use regular heap */
2780 type->tp_alloc = PyType_GenericAlloc;
2781 if (type->tp_flags & Py_TPFLAGS_HAVE_GC) {
2782 type->tp_free = PyObject_GC_Del;
2783 type->tp_traverse = subtype_traverse;
2784 type->tp_clear = subtype_clear;
2785 }
2786 else
2787 type->tp_free = PyObject_Del;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002788
Nick Coghlan19d24672016-12-05 16:47:55 +10002789 /* store type in class' cell if one is supplied */
Nick Coghlan944368e2016-09-11 14:45:49 +10002790 cell = _PyDict_GetItemId(dict, &PyId___classcell__);
Nick Coghlan19d24672016-12-05 16:47:55 +10002791 if (cell != NULL) {
2792 /* At least one method requires a reference to its defining class */
2793 if (!PyCell_Check(cell)) {
2794 PyErr_Format(PyExc_TypeError,
2795 "__classcell__ must be a nonlocal cell, not %.200R",
2796 Py_TYPE(cell));
2797 goto error;
2798 }
Nick Coghlan944368e2016-09-11 14:45:49 +10002799 PyCell_Set(cell, (PyObject *) type);
2800 _PyDict_DelItemId(dict, &PyId___classcell__);
2801 PyErr_Clear();
2802 }
2803
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002804 /* Initialize the rest */
Victor Stinner6f738742012-02-25 01:22:36 +01002805 if (PyType_Ready(type) < 0)
2806 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002807
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002808 /* Put the proper slots in place */
2809 fixup_slot_dispatchers(type);
Guido van Rossumf040ede2001-08-07 16:40:56 +00002810
Benjamin Petersondf813792014-03-17 15:57:17 -05002811 if (type->tp_dictoffset) {
2812 et->ht_cached_keys = _PyDict_NewKeysForClass();
2813 }
2814
Nick Coghland78448e2016-07-30 16:26:03 +10002815 if (set_names(type) < 0)
2816 goto error;
2817
2818 if (init_subclass(type, kwds) < 0)
2819 goto error;
2820
Victor Stinner6f738742012-02-25 01:22:36 +01002821 Py_DECREF(dict);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002822 return (PyObject *)type;
Victor Stinner6f738742012-02-25 01:22:36 +01002823
2824error:
2825 Py_XDECREF(dict);
2826 Py_XDECREF(bases);
2827 Py_XDECREF(slots);
2828 Py_XDECREF(type);
2829 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002830}
2831
Serhiy Storchaka2d06e842015-12-25 19:53:18 +02002832static const short slotoffsets[] = {
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002833 -1, /* invalid slot */
2834#include "typeslots.inc"
2835};
2836
Benjamin Petersone28108c2012-01-29 20:13:18 -05002837PyObject *
Martin v. Löwis9c564092012-06-23 23:20:45 +02002838PyType_FromSpecWithBases(PyType_Spec *spec, PyObject *bases)
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002839{
2840 PyHeapTypeObject *res = (PyHeapTypeObject*)PyType_GenericAlloc(&PyType_Type, 0);
Martin v. Löwis9c564092012-06-23 23:20:45 +02002841 PyTypeObject *type, *base;
Nick Coghlana48db2b2015-05-24 01:03:46 +10002842 PyObject *modname;
Martin v. Löwis9c564092012-06-23 23:20:45 +02002843 char *s;
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002844 char *res_start = (char*)res;
2845 PyType_Slot *slot;
Victor Stinner54e4ca72013-07-11 22:42:25 +02002846
Martin v. Löwis9c564092012-06-23 23:20:45 +02002847 /* Set the type name and qualname */
2848 s = strrchr(spec->name, '.');
2849 if (s == NULL)
2850 s = (char*)spec->name;
2851 else
2852 s++;
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002853
Martin v. Löwis5e06a5d2011-02-21 16:24:00 +00002854 if (res == NULL)
Antoine Pitroubb78f572012-06-24 00:18:27 +02002855 return NULL;
2856 type = &res->ht_type;
Antoine Pitrou66a3a7e2012-06-24 00:42:59 +02002857 /* The flags must be initialized early, before the GC traverses us */
2858 type->tp_flags = spec->flags | Py_TPFLAGS_HEAPTYPE;
Martin v. Löwis9c564092012-06-23 23:20:45 +02002859 res->ht_name = PyUnicode_FromString(s);
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002860 if (!res->ht_name)
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002861 goto fail;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002862 res->ht_qualname = res->ht_name;
2863 Py_INCREF(res->ht_qualname);
Antoine Pitroubb78f572012-06-24 00:18:27 +02002864 type->tp_name = spec->name;
2865 if (!type->tp_name)
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002866 goto fail;
Victor Stinner54e4ca72013-07-11 22:42:25 +02002867
Martin v. Löwis9c564092012-06-23 23:20:45 +02002868 /* Adjust for empty tuple bases */
2869 if (!bases) {
2870 base = &PyBaseObject_Type;
2871 /* See whether Py_tp_base(s) was specified */
2872 for (slot = spec->slots; slot->slot; slot++) {
2873 if (slot->slot == Py_tp_base)
2874 base = slot->pfunc;
2875 else if (slot->slot == Py_tp_bases) {
2876 bases = slot->pfunc;
2877 Py_INCREF(bases);
2878 }
2879 }
2880 if (!bases)
2881 bases = PyTuple_Pack(1, base);
2882 if (!bases)
2883 goto fail;
2884 }
2885 else
2886 Py_INCREF(bases);
2887
2888 /* Calculate best base, and check that all bases are type objects */
2889 base = best_base(bases);
2890 if (base == NULL) {
2891 goto fail;
2892 }
2893 if (!PyType_HasFeature(base, Py_TPFLAGS_BASETYPE)) {
2894 PyErr_Format(PyExc_TypeError,
2895 "type '%.100s' is not an acceptable base type",
2896 base->tp_name);
2897 goto fail;
2898 }
2899
Martin v. Löwis9c564092012-06-23 23:20:45 +02002900 /* Initialize essential fields */
Yury Selivanov75445082015-05-11 22:57:16 -04002901 type->tp_as_async = &res->as_async;
Martin v. Löwis9c564092012-06-23 23:20:45 +02002902 type->tp_as_number = &res->as_number;
2903 type->tp_as_sequence = &res->as_sequence;
2904 type->tp_as_mapping = &res->as_mapping;
2905 type->tp_as_buffer = &res->as_buffer;
2906 /* Set tp_base and tp_bases */
2907 type->tp_bases = bases;
2908 bases = NULL;
2909 Py_INCREF(base);
2910 type->tp_base = base;
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002911
Antoine Pitroubb78f572012-06-24 00:18:27 +02002912 type->tp_basicsize = spec->basicsize;
2913 type->tp_itemsize = spec->itemsize;
Victor Stinner0fcab4a2011-01-04 12:59:15 +00002914
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002915 for (slot = spec->slots; slot->slot; slot++) {
Victor Stinner12174a52014-08-15 23:17:38 +02002916 if (slot->slot < 0
2917 || (size_t)slot->slot >= Py_ARRAY_LENGTH(slotoffsets)) {
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002918 PyErr_SetString(PyExc_RuntimeError, "invalid slot offset");
2919 goto fail;
2920 }
Martin v. Löwis9c564092012-06-23 23:20:45 +02002921 if (slot->slot == Py_tp_base || slot->slot == Py_tp_bases)
2922 /* Processed above */
2923 continue;
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002924 *(void**)(res_start + slotoffsets[slot->slot]) = slot->pfunc;
Georg Brandl032400b2011-02-19 21:47:02 +00002925
2926 /* need to make a copy of the docstring slot, which usually
2927 points to a static string literal */
2928 if (slot->slot == Py_tp_doc) {
Larry Hastings2623c8c2014-02-08 22:15:29 -08002929 const char *old_doc = _PyType_DocWithoutSignature(type->tp_name, slot->pfunc);
Larry Hastings5c661892014-01-24 06:17:25 -08002930 size_t len = strlen(old_doc)+1;
Georg Brandl032400b2011-02-19 21:47:02 +00002931 char *tp_doc = PyObject_MALLOC(len);
Victor Stinner53510cd2013-07-15 19:34:20 +02002932 if (tp_doc == NULL) {
2933 PyErr_NoMemory();
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002934 goto fail;
Victor Stinner53510cd2013-07-15 19:34:20 +02002935 }
Larry Hastings5c661892014-01-24 06:17:25 -08002936 memcpy(tp_doc, old_doc, len);
Antoine Pitroubb78f572012-06-24 00:18:27 +02002937 type->tp_doc = tp_doc;
Georg Brandl032400b2011-02-19 21:47:02 +00002938 }
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002939 }
Antoine Pitroubb78f572012-06-24 00:18:27 +02002940 if (type->tp_dealloc == NULL) {
Antoine Pitrou99cc6292012-06-23 14:42:38 +02002941 /* It's a heap type, so needs the heap types' dealloc.
2942 subtype_dealloc will call the base type's tp_dealloc, if
2943 necessary. */
Antoine Pitroubb78f572012-06-24 00:18:27 +02002944 type->tp_dealloc = subtype_dealloc;
Antoine Pitrou99cc6292012-06-23 14:42:38 +02002945 }
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002946
Antoine Pitroubb78f572012-06-24 00:18:27 +02002947 if (PyType_Ready(type) < 0)
Benjamin Peterson2652d252012-01-29 20:16:37 -05002948 goto fail;
2949
Benjamin Petersondf813792014-03-17 15:57:17 -05002950 if (type->tp_dictoffset) {
2951 res->ht_cached_keys = _PyDict_NewKeysForClass();
2952 }
2953
Martin v. Löwis9c564092012-06-23 23:20:45 +02002954 /* Set type.__module__ */
2955 s = strrchr(spec->name, '.');
Nick Coghlana48db2b2015-05-24 01:03:46 +10002956 if (s != NULL) {
Christian Heimes5cade882016-10-13 21:10:31 +02002957 int err;
Nick Coghlana48db2b2015-05-24 01:03:46 +10002958 modname = PyUnicode_FromStringAndSize(
2959 spec->name, (Py_ssize_t)(s - spec->name));
2960 if (modname == NULL) {
2961 goto fail;
2962 }
Christian Heimes5cade882016-10-13 21:10:31 +02002963 err = _PyDict_SetItemId(type->tp_dict, &PyId___module__, modname);
Nick Coghlana48db2b2015-05-24 01:03:46 +10002964 Py_DECREF(modname);
Christian Heimes5cade882016-10-13 21:10:31 +02002965 if (err != 0)
2966 goto fail;
Nick Coghlana48db2b2015-05-24 01:03:46 +10002967 } else {
Serhiy Storchaka490055a2015-03-01 10:03:02 +02002968 if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
Serhiy Storchaka71c6f442015-03-01 14:39:20 +02002969 "builtin type %.200s has no __module__ attribute",
Serhiy Storchaka490055a2015-03-01 10:03:02 +02002970 spec->name))
2971 goto fail;
2972 }
Martin v. Löwis9c564092012-06-23 23:20:45 +02002973
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002974 return (PyObject*)res;
Victor Stinner0fcab4a2011-01-04 12:59:15 +00002975
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002976 fail:
2977 Py_DECREF(res);
2978 return NULL;
2979}
2980
Martin v. Löwis9c564092012-06-23 23:20:45 +02002981PyObject *
2982PyType_FromSpec(PyType_Spec *spec)
2983{
2984 return PyType_FromSpecWithBases(spec, NULL);
2985}
2986
Martin v. Löwisca7b0462014-02-04 09:33:05 +01002987void *
2988PyType_GetSlot(PyTypeObject *type, int slot)
2989{
Victor Stinner12174a52014-08-15 23:17:38 +02002990 if (!PyType_HasFeature(type, Py_TPFLAGS_HEAPTYPE) || slot < 0) {
Martin v. Löwisca7b0462014-02-04 09:33:05 +01002991 PyErr_BadInternalCall();
2992 return NULL;
2993 }
Victor Stinner12174a52014-08-15 23:17:38 +02002994 if ((size_t)slot >= Py_ARRAY_LENGTH(slotoffsets)) {
Martin v. Löwisca7b0462014-02-04 09:33:05 +01002995 /* Extension module requesting slot from a future version */
2996 return NULL;
2997 }
2998 return *(void**)(((char*)type) + slotoffsets[slot]);
2999}
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00003000
scoder2102c782017-10-01 10:37:47 +02003001/* Internal API to look for a name through the MRO, bypassing the method cache.
3002 This returns a borrowed reference, and might set an exception.
3003 'error' is set to: -1: error with exception; 1: error without exception; 0: ok */
3004static PyObject *
3005find_name_in_mro(PyTypeObject *type, PyObject *name, int *error)
3006{
3007 Py_ssize_t i, n;
3008 PyObject *mro, *res, *base, *dict;
3009 Py_hash_t hash;
3010
3011 if (!PyUnicode_CheckExact(name) ||
3012 (hash = ((PyASCIIObject *) name)->hash) == -1)
3013 {
3014 hash = PyObject_Hash(name);
3015 if (hash == -1) {
3016 *error = -1;
3017 return NULL;
3018 }
3019 }
3020
3021 /* Look in tp_dict of types in MRO */
3022 mro = type->tp_mro;
3023
3024 if (mro == NULL) {
3025 if ((type->tp_flags & Py_TPFLAGS_READYING) == 0) {
3026 if (PyType_Ready(type) < 0) {
3027 *error = -1;
3028 return NULL;
3029 }
3030 mro = type->tp_mro;
3031 }
3032 if (mro == NULL) {
3033 *error = 1;
3034 return NULL;
3035 }
3036 }
3037
3038 res = NULL;
3039 /* Keep a strong reference to mro because type->tp_mro can be replaced
3040 during dict lookup, e.g. when comparing to non-string keys. */
3041 Py_INCREF(mro);
3042 assert(PyTuple_Check(mro));
3043 n = PyTuple_GET_SIZE(mro);
3044 for (i = 0; i < n; i++) {
3045 base = PyTuple_GET_ITEM(mro, i);
3046 assert(PyType_Check(base));
3047 dict = ((PyTypeObject *)base)->tp_dict;
3048 assert(dict && PyDict_Check(dict));
3049 res = _PyDict_GetItem_KnownHash(dict, name, hash);
3050 if (res != NULL)
3051 break;
3052 if (PyErr_Occurred()) {
3053 *error = -1;
3054 goto done;
3055 }
3056 }
3057 *error = 0;
3058done:
3059 Py_DECREF(mro);
3060 return res;
3061}
3062
Tim Peters6d6c1a32001-08-02 04:15:00 +00003063/* Internal API to look for a name through the MRO.
3064 This returns a borrowed reference, and doesn't set an exception! */
3065PyObject *
3066_PyType_Lookup(PyTypeObject *type, PyObject *name)
3067{
scoder2102c782017-10-01 10:37:47 +02003068 PyObject *res;
3069 int error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003070 unsigned int h;
Christian Heimesa62da1d2008-01-12 19:39:10 +00003071
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003072 if (MCACHE_CACHEABLE_NAME(name) &&
3073 PyType_HasFeature(type, Py_TPFLAGS_VALID_VERSION_TAG)) {
3074 /* fast path */
3075 h = MCACHE_HASH_METHOD(type, name);
3076 if (method_cache[h].version == type->tp_version_tag &&
Antoine Pitrou2a40e362014-11-15 00:56:27 +01003077 method_cache[h].name == name) {
3078#if MCACHE_STATS
3079 method_cache_hits++;
3080#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003081 return method_cache[h].value;
Antoine Pitrou2a40e362014-11-15 00:56:27 +01003082 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003083 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003084
scoder2102c782017-10-01 10:37:47 +02003085 /* We may end up clearing live exceptions below, so make sure it's ours. */
3086 assert(!PyErr_Occurred());
Guido van Rossum23094982002-06-10 14:30:43 +00003087
scoder2102c782017-10-01 10:37:47 +02003088 res = find_name_in_mro(type, name, &error);
3089 /* Only put NULL results into cache if there was no error. */
3090 if (error) {
3091 /* It's not ideal to clear the error condition,
3092 but this function is documented as not setting
3093 an exception, and I don't want to change that.
3094 E.g., when PyType_Ready() can't proceed, it won't
3095 set the "ready" flag, so future attempts to ready
3096 the same type will call it again -- hopefully
3097 in a context that propagates the exception out.
3098 */
3099 if (error == -1) {
Serhiy Storchaka8ef34602016-10-08 12:24:09 +03003100 PyErr_Clear();
Serhiy Storchaka8ef34602016-10-08 12:24:09 +03003101 }
scoder2102c782017-10-01 10:37:47 +02003102 return NULL;
Serhiy Storchaka8ef34602016-10-08 12:24:09 +03003103 }
Guido van Rossum23094982002-06-10 14:30:43 +00003104
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003105 if (MCACHE_CACHEABLE_NAME(name) && assign_version_tag(type)) {
3106 h = MCACHE_HASH_METHOD(type, name);
3107 method_cache[h].version = type->tp_version_tag;
3108 method_cache[h].value = res; /* borrowed */
3109 Py_INCREF(name);
Antoine Pitrou2a40e362014-11-15 00:56:27 +01003110 assert(((PyASCIIObject *)(name))->hash != -1);
3111#if MCACHE_STATS
3112 if (method_cache[h].name != Py_None && method_cache[h].name != name)
3113 method_cache_collisions++;
3114 else
3115 method_cache_misses++;
3116#endif
Serhiy Storchaka57a01d32016-04-10 18:05:40 +03003117 Py_SETREF(method_cache[h].name, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003118 }
3119 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003120}
3121
Raymond Hettinger2ff21902013-10-01 00:55:43 -07003122PyObject *
Victor Stinner3c1e4812012-03-26 22:10:51 +02003123_PyType_LookupId(PyTypeObject *type, struct _Py_Identifier *name)
3124{
3125 PyObject *oname;
3126 oname = _PyUnicode_FromId(name); /* borrowed */
3127 if (oname == NULL)
3128 return NULL;
3129 return _PyType_Lookup(type, oname);
3130}
3131
Tim Peters6d6c1a32001-08-02 04:15:00 +00003132/* This is similar to PyObject_GenericGetAttr(),
3133 but uses _PyType_Lookup() instead of just looking in type->tp_dict. */
3134static PyObject *
3135type_getattro(PyTypeObject *type, PyObject *name)
3136{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003137 PyTypeObject *metatype = Py_TYPE(type);
3138 PyObject *meta_attribute, *attribute;
3139 descrgetfunc meta_get;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003140
Benjamin Peterson16d84ac2012-03-16 09:32:59 -05003141 if (!PyUnicode_Check(name)) {
3142 PyErr_Format(PyExc_TypeError,
3143 "attribute name must be string, not '%.200s'",
3144 name->ob_type->tp_name);
3145 return NULL;
3146 }
3147
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003148 /* Initialize this type (we'll assume the metatype is initialized) */
3149 if (type->tp_dict == NULL) {
3150 if (PyType_Ready(type) < 0)
3151 return NULL;
3152 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003153
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003154 /* No readable descriptor found yet */
3155 meta_get = NULL;
Tim Peters34592512002-07-11 06:23:50 +00003156
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003157 /* Look for the attribute in the metatype */
3158 meta_attribute = _PyType_Lookup(metatype, name);
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00003159
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003160 if (meta_attribute != NULL) {
3161 meta_get = Py_TYPE(meta_attribute)->tp_descr_get;
Tim Peters34592512002-07-11 06:23:50 +00003162
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003163 if (meta_get != NULL && PyDescr_IsData(meta_attribute)) {
3164 /* Data descriptors implement tp_descr_set to intercept
3165 * writes. Assume the attribute is not overridden in
3166 * type's tp_dict (and bases): call the descriptor now.
3167 */
3168 return meta_get(meta_attribute, (PyObject *)type,
3169 (PyObject *)metatype);
3170 }
3171 Py_INCREF(meta_attribute);
3172 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003173
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003174 /* No data descriptor found on metatype. Look in tp_dict of this
3175 * type and its bases */
3176 attribute = _PyType_Lookup(type, name);
3177 if (attribute != NULL) {
3178 /* Implement descriptor functionality, if any */
3179 descrgetfunc local_get = Py_TYPE(attribute)->tp_descr_get;
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00003180
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003181 Py_XDECREF(meta_attribute);
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00003182
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003183 if (local_get != NULL) {
3184 /* NULL 2nd argument indicates the descriptor was
3185 * found on the target object itself (or a base) */
3186 return local_get(attribute, (PyObject *)NULL,
3187 (PyObject *)type);
3188 }
Tim Peters34592512002-07-11 06:23:50 +00003189
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003190 Py_INCREF(attribute);
3191 return attribute;
3192 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003193
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003194 /* No attribute found in local __dict__ (or bases): use the
3195 * descriptor from the metatype, if any */
3196 if (meta_get != NULL) {
3197 PyObject *res;
3198 res = meta_get(meta_attribute, (PyObject *)type,
3199 (PyObject *)metatype);
3200 Py_DECREF(meta_attribute);
3201 return res;
3202 }
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00003203
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003204 /* If an ordinary attribute was found on the metatype, return it now */
3205 if (meta_attribute != NULL) {
3206 return meta_attribute;
3207 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003208
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003209 /* Give up */
3210 PyErr_Format(PyExc_AttributeError,
3211 "type object '%.50s' has no attribute '%U'",
3212 type->tp_name, name);
3213 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003214}
3215
3216static int
3217type_setattro(PyTypeObject *type, PyObject *name, PyObject *value)
3218{
Victor Stinnerbda5a2b2017-01-25 23:33:27 +01003219 int res;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003220 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
3221 PyErr_Format(
3222 PyExc_TypeError,
3223 "can't set attributes of built-in/extension type '%s'",
3224 type->tp_name);
3225 return -1;
3226 }
Serhiy Storchakad8969852017-05-20 08:48:06 +03003227 if (PyUnicode_Check(name)) {
3228 if (PyUnicode_CheckExact(name)) {
3229 if (PyUnicode_READY(name) == -1)
3230 return -1;
3231 Py_INCREF(name);
3232 }
3233 else {
3234 name = _PyUnicode_Copy(name);
3235 if (name == NULL)
3236 return -1;
3237 }
3238 PyUnicode_InternInPlace(&name);
3239 if (!PyUnicode_CHECK_INTERNED(name)) {
3240 PyErr_SetString(PyExc_MemoryError,
3241 "Out of memory interning an attribute name");
3242 Py_DECREF(name);
3243 return -1;
3244 }
3245 }
3246 else {
3247 /* Will fail in _PyObject_GenericSetAttrWithDict. */
3248 Py_INCREF(name);
3249 }
3250 res = _PyObject_GenericSetAttrWithDict((PyObject *)type, name, value, NULL);
3251 if (res == 0) {
3252 res = update_slot(type, name);
3253 assert(_PyType_CheckConsistency(type));
3254 }
3255 Py_DECREF(name);
Victor Stinnerbda5a2b2017-01-25 23:33:27 +01003256 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003257}
3258
Benjamin Peterson64acccf2012-04-27 15:07:36 -04003259extern void
3260_PyDictKeys_DecRef(PyDictKeysObject *keys);
3261
Tim Peters6d6c1a32001-08-02 04:15:00 +00003262static void
3263type_dealloc(PyTypeObject *type)
3264{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003265 PyHeapTypeObject *et;
Antoine Pitrou84745ab2013-10-29 21:31:25 +01003266 PyObject *tp, *val, *tb;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003267
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003268 /* Assert this is a heap-allocated type object */
3269 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
3270 _PyObject_GC_UNTRACK(type);
Antoine Pitrou84745ab2013-10-29 21:31:25 +01003271 PyErr_Fetch(&tp, &val, &tb);
3272 remove_all_subclasses(type, type->tp_bases);
3273 PyErr_Restore(tp, val, tb);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003274 PyObject_ClearWeakRefs((PyObject *)type);
3275 et = (PyHeapTypeObject *)type;
3276 Py_XDECREF(type->tp_base);
3277 Py_XDECREF(type->tp_dict);
3278 Py_XDECREF(type->tp_bases);
3279 Py_XDECREF(type->tp_mro);
3280 Py_XDECREF(type->tp_cache);
3281 Py_XDECREF(type->tp_subclasses);
3282 /* A type's tp_doc is heap allocated, unlike the tp_doc slots
3283 * of most other objects. It's okay to cast it to char *.
3284 */
3285 PyObject_Free((char *)type->tp_doc);
3286 Py_XDECREF(et->ht_name);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003287 Py_XDECREF(et->ht_qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003288 Py_XDECREF(et->ht_slots);
Benjamin Peterson64acccf2012-04-27 15:07:36 -04003289 if (et->ht_cached_keys)
3290 _PyDictKeys_DecRef(et->ht_cached_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003291 Py_TYPE(type)->tp_free((PyObject *)type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003292}
3293
Serhiy Storchaka5c643a02017-03-19 08:46:44 +02003294/*[clinic input]
3295type.__subclasses__
3296
3297Return a list of immediate subclasses.
3298[clinic start generated code]*/
3299
Guido van Rossum1c450732001-10-08 15:18:27 +00003300static PyObject *
Serhiy Storchaka5c643a02017-03-19 08:46:44 +02003301type___subclasses___impl(PyTypeObject *self)
3302/*[clinic end generated code: output=eb5eb54485942819 input=5af66132436f9a7b]*/
Guido van Rossum1c450732001-10-08 15:18:27 +00003303{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003304 PyObject *list, *raw, *ref;
Antoine Pitrou84745ab2013-10-29 21:31:25 +01003305 Py_ssize_t i;
Guido van Rossum1c450732001-10-08 15:18:27 +00003306
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003307 list = PyList_New(0);
3308 if (list == NULL)
3309 return NULL;
Serhiy Storchaka5c643a02017-03-19 08:46:44 +02003310 raw = self->tp_subclasses;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003311 if (raw == NULL)
3312 return list;
Antoine Pitrou84745ab2013-10-29 21:31:25 +01003313 assert(PyDict_CheckExact(raw));
3314 i = 0;
3315 while (PyDict_Next(raw, &i, NULL, &ref)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003316 assert(PyWeakref_CheckRef(ref));
3317 ref = PyWeakref_GET_OBJECT(ref);
3318 if (ref != Py_None) {
3319 if (PyList_Append(list, ref) < 0) {
3320 Py_DECREF(list);
3321 return NULL;
3322 }
3323 }
3324 }
3325 return list;
Guido van Rossum1c450732001-10-08 15:18:27 +00003326}
3327
Guido van Rossum47374822007-08-02 16:48:17 +00003328static PyObject *
Serhiy Storchakaa5552f02017-12-15 13:11:11 +02003329type_prepare(PyObject *self, PyObject *const *args, Py_ssize_t nargs,
Victor Stinnerd526cfe2017-01-16 23:52:00 +01003330 PyObject *kwnames)
Guido van Rossum47374822007-08-02 16:48:17 +00003331{
Eric Snow4f29e752016-09-08 15:11:11 -07003332 return PyDict_New();
Guido van Rossum47374822007-08-02 16:48:17 +00003333}
3334
Victor Stinner63941882011-09-29 00:42:28 +02003335/*
Benjamin Peterson82b00c12011-05-24 11:09:06 -05003336 Merge the __dict__ of aclass into dict, and recursively also all
3337 the __dict__s of aclass's base classes. The order of merging isn't
3338 defined, as it's expected that only the final set of dict keys is
3339 interesting.
3340 Return 0 on success, -1 on error.
3341*/
3342
3343static int
3344merge_class_dict(PyObject *dict, PyObject *aclass)
3345{
3346 PyObject *classdict;
3347 PyObject *bases;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02003348 _Py_IDENTIFIER(__bases__);
Benjamin Peterson82b00c12011-05-24 11:09:06 -05003349
3350 assert(PyDict_Check(dict));
3351 assert(aclass);
3352
3353 /* Merge in the type's dict (if any). */
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02003354 classdict = _PyObject_GetAttrId(aclass, &PyId___dict__);
Benjamin Peterson82b00c12011-05-24 11:09:06 -05003355 if (classdict == NULL)
3356 PyErr_Clear();
3357 else {
3358 int status = PyDict_Update(dict, classdict);
3359 Py_DECREF(classdict);
3360 if (status < 0)
3361 return -1;
3362 }
3363
3364 /* Recursively merge in the base types' (if any) dicts. */
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02003365 bases = _PyObject_GetAttrId(aclass, &PyId___bases__);
Benjamin Peterson82b00c12011-05-24 11:09:06 -05003366 if (bases == NULL)
3367 PyErr_Clear();
3368 else {
3369 /* We have no guarantee that bases is a real tuple */
3370 Py_ssize_t i, n;
3371 n = PySequence_Size(bases); /* This better be right */
3372 if (n < 0)
3373 PyErr_Clear();
3374 else {
3375 for (i = 0; i < n; i++) {
3376 int status;
3377 PyObject *base = PySequence_GetItem(bases, i);
3378 if (base == NULL) {
3379 Py_DECREF(bases);
3380 return -1;
3381 }
3382 status = merge_class_dict(dict, base);
3383 Py_DECREF(base);
3384 if (status < 0) {
3385 Py_DECREF(bases);
3386 return -1;
3387 }
3388 }
3389 }
3390 Py_DECREF(bases);
3391 }
3392 return 0;
3393}
3394
3395/* __dir__ for type objects: returns __dict__ and __bases__.
3396 We deliberately don't suck up its __class__, as methods belonging to the
3397 metaclass would probably be more confusing than helpful.
3398*/
Serhiy Storchaka5c643a02017-03-19 08:46:44 +02003399/*[clinic input]
3400type.__dir__
3401
3402Specialized __dir__ implementation for types.
3403[clinic start generated code]*/
3404
Benjamin Peterson82b00c12011-05-24 11:09:06 -05003405static PyObject *
Serhiy Storchaka5c643a02017-03-19 08:46:44 +02003406type___dir___impl(PyTypeObject *self)
3407/*[clinic end generated code: output=69d02fe92c0f15fa input=7733befbec645968]*/
Benjamin Peterson82b00c12011-05-24 11:09:06 -05003408{
3409 PyObject *result = NULL;
3410 PyObject *dict = PyDict_New();
3411
Serhiy Storchaka5c643a02017-03-19 08:46:44 +02003412 if (dict != NULL && merge_class_dict(dict, (PyObject *)self) == 0)
Benjamin Peterson82b00c12011-05-24 11:09:06 -05003413 result = PyDict_Keys(dict);
3414
3415 Py_XDECREF(dict);
3416 return result;
3417}
3418
Serhiy Storchaka5c643a02017-03-19 08:46:44 +02003419/*[clinic input]
3420type.__sizeof__
3421
3422Return memory consumption of the type object.
3423[clinic start generated code]*/
3424
3425static PyObject *
3426type___sizeof___impl(PyTypeObject *self)
3427/*[clinic end generated code: output=766f4f16cd3b1854 input=99398f24b9cf45d6]*/
Martin v. Loewis4f2f3b62012-04-24 19:13:57 +02003428{
3429 Py_ssize_t size;
Serhiy Storchaka5c643a02017-03-19 08:46:44 +02003430 if (self->tp_flags & Py_TPFLAGS_HEAPTYPE) {
3431 PyHeapTypeObject* et = (PyHeapTypeObject*)self;
Martin v. Loewis4f2f3b62012-04-24 19:13:57 +02003432 size = sizeof(PyHeapTypeObject);
3433 if (et->ht_cached_keys)
3434 size += _PyDict_KeysSize(et->ht_cached_keys);
3435 }
3436 else
3437 size = sizeof(PyTypeObject);
3438 return PyLong_FromSsize_t(size);
3439}
3440
Tim Peters6d6c1a32001-08-02 04:15:00 +00003441static PyMethodDef type_methods[] = {
Serhiy Storchaka5c643a02017-03-19 08:46:44 +02003442 TYPE_MRO_METHODDEF
3443 TYPE___SUBCLASSES___METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003444 {"__prepare__", (PyCFunction)type_prepare,
Serhiy Storchaka6969eaf2017-07-03 21:20:15 +03003445 METH_FASTCALL | METH_KEYWORDS | METH_CLASS,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003446 PyDoc_STR("__prepare__() -> dict\n"
3447 "used to create the namespace for the class statement")},
Serhiy Storchaka5c643a02017-03-19 08:46:44 +02003448 TYPE___INSTANCECHECK___METHODDEF
3449 TYPE___SUBCLASSCHECK___METHODDEF
3450 TYPE___DIR___METHODDEF
3451 TYPE___SIZEOF___METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003452 {0}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003453};
3454
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003455PyDoc_STRVAR(type_doc,
Larry Hastings5c661892014-01-24 06:17:25 -08003456/* this text signature cannot be accurate yet. will fix. --larry */
Larry Hastings2623c8c2014-02-08 22:15:29 -08003457"type(object_or_name, bases, dict)\n"
Tim Peters6d6c1a32001-08-02 04:15:00 +00003458"type(object) -> the object's type\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003459"type(name, bases, dict) -> a new type");
Tim Peters6d6c1a32001-08-02 04:15:00 +00003460
Guido van Rossum048eb752001-10-02 21:24:57 +00003461static int
3462type_traverse(PyTypeObject *type, visitproc visit, void *arg)
3463{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003464 /* Because of type_is_gc(), the collector only calls this
3465 for heaptypes. */
Antoine Pitrou1351ca62012-06-24 00:30:12 +02003466 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
3467 char msg[200];
3468 sprintf(msg, "type_traverse() called for non-heap type '%.100s'",
3469 type->tp_name);
3470 Py_FatalError(msg);
3471 }
Guido van Rossum048eb752001-10-02 21:24:57 +00003472
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003473 Py_VISIT(type->tp_dict);
3474 Py_VISIT(type->tp_cache);
3475 Py_VISIT(type->tp_mro);
3476 Py_VISIT(type->tp_bases);
3477 Py_VISIT(type->tp_base);
Guido van Rossuma3862092002-06-10 15:24:42 +00003478
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003479 /* There's no need to visit type->tp_subclasses or
3480 ((PyHeapTypeObject *)type)->ht_slots, because they can't be involved
3481 in cycles; tp_subclasses is a list of weak references,
3482 and slots is a tuple of strings. */
Guido van Rossum048eb752001-10-02 21:24:57 +00003483
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003484 return 0;
Guido van Rossum048eb752001-10-02 21:24:57 +00003485}
3486
3487static int
3488type_clear(PyTypeObject *type)
3489{
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003490 PyDictKeysObject *cached_keys;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003491 /* Because of type_is_gc(), the collector only calls this
3492 for heaptypes. */
3493 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00003494
Antoine Pitrou2e872082011-12-15 14:15:31 +01003495 /* We need to invalidate the method cache carefully before clearing
3496 the dict, so that other objects caught in a reference cycle
3497 don't start calling destroyed methods.
3498
3499 Otherwise, the only field we need to clear is tp_mro, which is
3500 part of a hard cycle (its first element is the class itself) that
3501 won't be broken otherwise (it's a tuple and tuples don't have a
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003502 tp_clear handler). None of the other fields need to be
3503 cleared, and here's why:
Guido van Rossum048eb752001-10-02 21:24:57 +00003504
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003505 tp_cache:
3506 Not used; if it were, it would be a dict.
Guido van Rossuma3862092002-06-10 15:24:42 +00003507
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003508 tp_bases, tp_base:
3509 If these are involved in a cycle, there must be at least
3510 one other, mutable object in the cycle, e.g. a base
3511 class's dict; the cycle will be broken that way.
Guido van Rossuma3862092002-06-10 15:24:42 +00003512
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003513 tp_subclasses:
Antoine Pitrou84745ab2013-10-29 21:31:25 +01003514 A dict of weak references can't be part of a cycle; and
3515 dicts have their own tp_clear.
Guido van Rossuma3862092002-06-10 15:24:42 +00003516
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003517 slots (in PyHeapTypeObject):
3518 A tuple of strings can't be part of a cycle.
3519 */
Guido van Rossuma3862092002-06-10 15:24:42 +00003520
Antoine Pitrou2e872082011-12-15 14:15:31 +01003521 PyType_Modified(type);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003522 cached_keys = ((PyHeapTypeObject *)type)->ht_cached_keys;
3523 if (cached_keys != NULL) {
3524 ((PyHeapTypeObject *)type)->ht_cached_keys = NULL;
3525 _PyDictKeys_DecRef(cached_keys);
3526 }
Antoine Pitrou2e872082011-12-15 14:15:31 +01003527 if (type->tp_dict)
3528 PyDict_Clear(type->tp_dict);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003529 Py_CLEAR(type->tp_mro);
Guido van Rossum048eb752001-10-02 21:24:57 +00003530
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003531 return 0;
Guido van Rossum048eb752001-10-02 21:24:57 +00003532}
3533
3534static int
3535type_is_gc(PyTypeObject *type)
3536{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003537 return type->tp_flags & Py_TPFLAGS_HEAPTYPE;
Guido van Rossum048eb752001-10-02 21:24:57 +00003538}
3539
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003540PyTypeObject PyType_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003541 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3542 "type", /* tp_name */
3543 sizeof(PyHeapTypeObject), /* tp_basicsize */
3544 sizeof(PyMemberDef), /* tp_itemsize */
3545 (destructor)type_dealloc, /* tp_dealloc */
3546 0, /* tp_print */
3547 0, /* tp_getattr */
3548 0, /* tp_setattr */
3549 0, /* tp_reserved */
3550 (reprfunc)type_repr, /* tp_repr */
3551 0, /* tp_as_number */
3552 0, /* tp_as_sequence */
3553 0, /* tp_as_mapping */
3554 0, /* tp_hash */
3555 (ternaryfunc)type_call, /* tp_call */
3556 0, /* tp_str */
3557 (getattrofunc)type_getattro, /* tp_getattro */
3558 (setattrofunc)type_setattro, /* tp_setattro */
3559 0, /* tp_as_buffer */
3560 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
3561 Py_TPFLAGS_BASETYPE | Py_TPFLAGS_TYPE_SUBCLASS, /* tp_flags */
3562 type_doc, /* tp_doc */
3563 (traverseproc)type_traverse, /* tp_traverse */
3564 (inquiry)type_clear, /* tp_clear */
3565 0, /* tp_richcompare */
3566 offsetof(PyTypeObject, tp_weaklist), /* tp_weaklistoffset */
3567 0, /* tp_iter */
3568 0, /* tp_iternext */
3569 type_methods, /* tp_methods */
3570 type_members, /* tp_members */
3571 type_getsets, /* tp_getset */
3572 0, /* tp_base */
3573 0, /* tp_dict */
3574 0, /* tp_descr_get */
3575 0, /* tp_descr_set */
3576 offsetof(PyTypeObject, tp_dict), /* tp_dictoffset */
3577 type_init, /* tp_init */
3578 0, /* tp_alloc */
3579 type_new, /* tp_new */
3580 PyObject_GC_Del, /* tp_free */
3581 (inquiry)type_is_gc, /* tp_is_gc */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003582};
Tim Peters6d6c1a32001-08-02 04:15:00 +00003583
3584
3585/* The base type of all types (eventually)... except itself. */
3586
Guido van Rossumd8faa362007-04-27 19:54:29 +00003587/* You may wonder why object.__new__() only complains about arguments
3588 when object.__init__() is not overridden, and vice versa.
3589
3590 Consider the use cases:
3591
3592 1. When neither is overridden, we want to hear complaints about
3593 excess (i.e., any) arguments, since their presence could
3594 indicate there's a bug.
3595
3596 2. When defining an Immutable type, we are likely to override only
3597 __new__(), since __init__() is called too late to initialize an
3598 Immutable object. Since __new__() defines the signature for the
3599 type, it would be a pain to have to override __init__() just to
3600 stop it from complaining about excess arguments.
3601
3602 3. When defining a Mutable type, we are likely to override only
3603 __init__(). So here the converse reasoning applies: we don't
3604 want to have to override __new__() just to stop it from
3605 complaining.
3606
3607 4. When __init__() is overridden, and the subclass __init__() calls
3608 object.__init__(), the latter should complain about excess
3609 arguments; ditto for __new__().
3610
3611 Use cases 2 and 3 make it unattractive to unconditionally check for
3612 excess arguments. The best solution that addresses all four use
3613 cases is as follows: __init__() complains about excess arguments
3614 unless __new__() is overridden and __init__() is not overridden
3615 (IOW, if __init__() is overridden or __new__() is not overridden);
3616 symmetrically, __new__() complains about excess arguments unless
3617 __init__() is overridden and __new__() is not overridden
3618 (IOW, if __new__() is overridden or __init__() is not overridden).
3619
3620 However, for backwards compatibility, this breaks too much code.
3621 Therefore, in 2.6, we'll *warn* about excess arguments when both
3622 methods are overridden; for all other cases we'll use the above
3623 rules.
3624
3625*/
3626
3627/* Forward */
3628static PyObject *
3629object_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
3630
3631static int
3632excess_args(PyObject *args, PyObject *kwds)
3633{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003634 return PyTuple_GET_SIZE(args) ||
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02003635 (kwds && PyDict_Check(kwds) && PyDict_GET_SIZE(kwds));
Guido van Rossumd8faa362007-04-27 19:54:29 +00003636}
3637
Tim Peters6d6c1a32001-08-02 04:15:00 +00003638static int
3639object_init(PyObject *self, PyObject *args, PyObject *kwds)
3640{
Benjamin Peterson96384b92012-03-17 00:05:44 -05003641 PyTypeObject *type = Py_TYPE(self);
Serhiy Storchakaa6c0c062017-09-20 06:44:32 +03003642 if (excess_args(args, kwds)) {
3643 if (type->tp_init != object_init) {
Sanyam Khurana780acc82017-12-10 05:44:22 +05303644 PyErr_SetString(PyExc_TypeError, "object.__init__() takes no arguments");
Serhiy Storchakaa6c0c062017-09-20 06:44:32 +03003645 return -1;
3646 }
3647 if (type->tp_new == object_new) {
Sanyam Khurana780acc82017-12-10 05:44:22 +05303648 PyErr_Format(PyExc_TypeError, "%.200s().__init__() takes no arguments",
Serhiy Storchakaa6c0c062017-09-20 06:44:32 +03003649 type->tp_name);
3650 return -1;
3651 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003652 }
Serhiy Storchakaa6c0c062017-09-20 06:44:32 +03003653 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003654}
3655
Guido van Rossum298e4212003-02-13 16:30:16 +00003656static PyObject *
3657object_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3658{
Serhiy Storchakaa6c0c062017-09-20 06:44:32 +03003659 if (excess_args(args, kwds)) {
3660 if (type->tp_new != object_new) {
Sanyam Khurana780acc82017-12-10 05:44:22 +05303661 PyErr_SetString(PyExc_TypeError, "object.__new__() takes no arguments");
Serhiy Storchakaa6c0c062017-09-20 06:44:32 +03003662 return NULL;
3663 }
3664 if (type->tp_init == object_init) {
3665 PyErr_Format(PyExc_TypeError, "%.200s() takes no arguments",
3666 type->tp_name);
3667 return NULL;
3668 }
Benjamin Peterson96384b92012-03-17 00:05:44 -05003669 }
Victor Stinner3c1e4812012-03-26 22:10:51 +02003670
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003671 if (type->tp_flags & Py_TPFLAGS_IS_ABSTRACT) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003672 PyObject *abstract_methods = NULL;
3673 PyObject *builtins;
3674 PyObject *sorted;
3675 PyObject *sorted_methods = NULL;
3676 PyObject *joined = NULL;
Benjamin Peterson9a03ecf2012-03-16 20:15:54 -05003677 PyObject *comma;
3678 _Py_static_string(comma_id, ", ");
Victor Stinner3c1e4812012-03-26 22:10:51 +02003679 _Py_IDENTIFIER(sorted);
Christian Heimes9e7f1d22008-02-28 12:27:11 +00003680
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003681 /* Compute ", ".join(sorted(type.__abstractmethods__))
3682 into joined. */
3683 abstract_methods = type_abstractmethods(type, NULL);
3684 if (abstract_methods == NULL)
3685 goto error;
3686 builtins = PyEval_GetBuiltins();
3687 if (builtins == NULL)
3688 goto error;
Victor Stinner3c1e4812012-03-26 22:10:51 +02003689 sorted = _PyDict_GetItemId(builtins, &PyId_sorted);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003690 if (sorted == NULL)
3691 goto error;
Victor Stinnerde4ae3d2016-12-04 22:59:09 +01003692 sorted_methods = PyObject_CallFunctionObjArgs(sorted,
3693 abstract_methods,
3694 NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003695 if (sorted_methods == NULL)
3696 goto error;
Benjamin Peterson9a03ecf2012-03-16 20:15:54 -05003697 comma = _PyUnicode_FromId(&comma_id);
3698 if (comma == NULL)
3699 goto error;
3700 joined = PyUnicode_Join(comma, sorted_methods);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003701 if (joined == NULL)
3702 goto error;
Christian Heimes9e7f1d22008-02-28 12:27:11 +00003703
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003704 PyErr_Format(PyExc_TypeError,
3705 "Can't instantiate abstract class %s "
3706 "with abstract methods %U",
3707 type->tp_name,
3708 joined);
3709 error:
3710 Py_XDECREF(joined);
3711 Py_XDECREF(sorted_methods);
3712 Py_XDECREF(abstract_methods);
3713 return NULL;
3714 }
3715 return type->tp_alloc(type, 0);
Guido van Rossum298e4212003-02-13 16:30:16 +00003716}
3717
Tim Peters6d6c1a32001-08-02 04:15:00 +00003718static void
3719object_dealloc(PyObject *self)
3720{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003721 Py_TYPE(self)->tp_free(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003722}
3723
Guido van Rossum8e248182001-08-12 05:17:56 +00003724static PyObject *
3725object_repr(PyObject *self)
3726{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003727 PyTypeObject *type;
3728 PyObject *mod, *name, *rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00003729
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003730 type = Py_TYPE(self);
3731 mod = type_module(type, NULL);
3732 if (mod == NULL)
3733 PyErr_Clear();
3734 else if (!PyUnicode_Check(mod)) {
3735 Py_DECREF(mod);
3736 mod = NULL;
3737 }
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003738 name = type_qualname(type, NULL);
Christian Heimese81dc292012-09-10 16:57:36 +02003739 if (name == NULL) {
3740 Py_XDECREF(mod);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003741 return NULL;
Christian Heimese81dc292012-09-10 16:57:36 +02003742 }
Serhiy Storchakaf5894dd2016-11-16 15:40:39 +02003743 if (mod != NULL && !_PyUnicode_EqualToASCIIId(mod, &PyId_builtins))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003744 rtn = PyUnicode_FromFormat("<%U.%U object at %p>", mod, name, self);
3745 else
3746 rtn = PyUnicode_FromFormat("<%s object at %p>",
3747 type->tp_name, self);
3748 Py_XDECREF(mod);
3749 Py_DECREF(name);
3750 return rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00003751}
3752
Guido van Rossumb8f63662001-08-15 23:57:02 +00003753static PyObject *
3754object_str(PyObject *self)
3755{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003756 unaryfunc f;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003757
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003758 f = Py_TYPE(self)->tp_repr;
Benjamin Peterson7b166872012-04-24 11:06:25 -04003759 if (f == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003760 f = object_repr;
3761 return f(self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003762}
3763
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003764static PyObject *
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003765object_richcompare(PyObject *self, PyObject *other, int op)
3766{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003767 PyObject *res;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003768
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003769 switch (op) {
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003770
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003771 case Py_EQ:
3772 /* Return NotImplemented instead of False, so if two
3773 objects are compared, both get a chance at the
3774 comparison. See issue #1393. */
3775 res = (self == other) ? Py_True : Py_NotImplemented;
3776 Py_INCREF(res);
3777 break;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003778
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003779 case Py_NE:
Serhiy Storchakaf4b7a022015-01-26 09:57:07 +02003780 /* By default, __ne__() delegates to __eq__() and inverts the result,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003781 unless the latter returns NotImplemented. */
Serhiy Storchakaf4b7a022015-01-26 09:57:07 +02003782 if (self->ob_type->tp_richcompare == NULL) {
3783 res = Py_NotImplemented;
3784 Py_INCREF(res);
3785 break;
3786 }
3787 res = (*self->ob_type->tp_richcompare)(self, other, Py_EQ);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003788 if (res != NULL && res != Py_NotImplemented) {
3789 int ok = PyObject_IsTrue(res);
3790 Py_DECREF(res);
3791 if (ok < 0)
3792 res = NULL;
3793 else {
3794 if (ok)
3795 res = Py_False;
3796 else
3797 res = Py_True;
3798 Py_INCREF(res);
3799 }
3800 }
3801 break;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003802
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003803 default:
3804 res = Py_NotImplemented;
3805 Py_INCREF(res);
3806 break;
3807 }
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003808
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003809 return res;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003810}
3811
3812static PyObject *
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003813object_get_class(PyObject *self, void *closure)
3814{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003815 Py_INCREF(Py_TYPE(self));
3816 return (PyObject *)(Py_TYPE(self));
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003817}
3818
3819static int
Benjamin Peterson9d4cbcc2015-01-30 13:33:42 -05003820compatible_with_tp_base(PyTypeObject *child)
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003821{
Benjamin Peterson9d4cbcc2015-01-30 13:33:42 -05003822 PyTypeObject *parent = child->tp_base;
3823 return (parent != NULL &&
3824 child->tp_basicsize == parent->tp_basicsize &&
3825 child->tp_itemsize == parent->tp_itemsize &&
3826 child->tp_dictoffset == parent->tp_dictoffset &&
3827 child->tp_weaklistoffset == parent->tp_weaklistoffset &&
3828 ((child->tp_flags & Py_TPFLAGS_HAVE_GC) ==
3829 (parent->tp_flags & Py_TPFLAGS_HAVE_GC)) &&
3830 (child->tp_dealloc == subtype_dealloc ||
3831 child->tp_dealloc == parent->tp_dealloc));
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003832}
3833
3834static int
3835same_slots_added(PyTypeObject *a, PyTypeObject *b)
3836{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003837 PyTypeObject *base = a->tp_base;
3838 Py_ssize_t size;
3839 PyObject *slots_a, *slots_b;
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003840
Benjamin Peterson67641d22011-01-17 19:24:34 +00003841 assert(base == b->tp_base);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003842 size = base->tp_basicsize;
3843 if (a->tp_dictoffset == size && b->tp_dictoffset == size)
3844 size += sizeof(PyObject *);
3845 if (a->tp_weaklistoffset == size && b->tp_weaklistoffset == size)
3846 size += sizeof(PyObject *);
Guido van Rossumd8faa362007-04-27 19:54:29 +00003847
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003848 /* Check slots compliance */
Benjamin Peterson9d4cbcc2015-01-30 13:33:42 -05003849 if (!(a->tp_flags & Py_TPFLAGS_HEAPTYPE) ||
3850 !(b->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
3851 return 0;
3852 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003853 slots_a = ((PyHeapTypeObject *)a)->ht_slots;
3854 slots_b = ((PyHeapTypeObject *)b)->ht_slots;
3855 if (slots_a && slots_b) {
3856 if (PyObject_RichCompareBool(slots_a, slots_b, Py_EQ) != 1)
3857 return 0;
3858 size += sizeof(PyObject *) * PyTuple_GET_SIZE(slots_a);
3859 }
3860 return size == a->tp_basicsize && size == b->tp_basicsize;
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003861}
3862
3863static int
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02003864compatible_for_assignment(PyTypeObject* oldto, PyTypeObject* newto, const char* attr)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003865{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003866 PyTypeObject *newbase, *oldbase;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003867
Benjamin Peterson9d4cbcc2015-01-30 13:33:42 -05003868 if (newto->tp_free != oldto->tp_free) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003869 PyErr_Format(PyExc_TypeError,
3870 "%s assignment: "
3871 "'%s' deallocator differs from '%s'",
3872 attr,
3873 newto->tp_name,
3874 oldto->tp_name);
3875 return 0;
3876 }
Benjamin Peterson9d4cbcc2015-01-30 13:33:42 -05003877 /*
3878 It's tricky to tell if two arbitrary types are sufficiently compatible as
3879 to be interchangeable; e.g., even if they have the same tp_basicsize, they
3880 might have totally different struct fields. It's much easier to tell if a
3881 type and its supertype are compatible; e.g., if they have the same
3882 tp_basicsize, then that means they have identical fields. So to check
3883 whether two arbitrary types are compatible, we first find the highest
3884 supertype that each is compatible with, and then if those supertypes are
3885 compatible then the original types must also be compatible.
3886 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003887 newbase = newto;
3888 oldbase = oldto;
Benjamin Peterson9d4cbcc2015-01-30 13:33:42 -05003889 while (compatible_with_tp_base(newbase))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003890 newbase = newbase->tp_base;
Benjamin Peterson9d4cbcc2015-01-30 13:33:42 -05003891 while (compatible_with_tp_base(oldbase))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003892 oldbase = oldbase->tp_base;
3893 if (newbase != oldbase &&
3894 (newbase->tp_base != oldbase->tp_base ||
3895 !same_slots_added(newbase, oldbase))) {
3896 PyErr_Format(PyExc_TypeError,
3897 "%s assignment: "
3898 "'%s' object layout differs from '%s'",
3899 attr,
3900 newto->tp_name,
3901 oldto->tp_name);
3902 return 0;
3903 }
Tim Petersea7f75d2002-12-07 21:39:16 +00003904
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003905 return 1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003906}
3907
3908static int
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003909object_set_class(PyObject *self, PyObject *value, void *closure)
3910{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003911 PyTypeObject *oldto = Py_TYPE(self);
3912 PyTypeObject *newto;
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003913
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003914 if (value == NULL) {
3915 PyErr_SetString(PyExc_TypeError,
3916 "can't delete __class__ attribute");
3917 return -1;
3918 }
3919 if (!PyType_Check(value)) {
3920 PyErr_Format(PyExc_TypeError,
Florent Xiclunaaa6c1d22011-12-12 18:54:29 +01003921 "__class__ must be set to a class, not '%s' object",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003922 Py_TYPE(value)->tp_name);
3923 return -1;
3924 }
3925 newto = (PyTypeObject *)value;
Guido van Rossum7d293ee2015-09-04 20:54:07 -07003926 /* In versions of CPython prior to 3.5, the code in
3927 compatible_for_assignment was not set up to correctly check for memory
3928 layout / slot / etc. compatibility for non-HEAPTYPE classes, so we just
3929 disallowed __class__ assignment in any case that wasn't HEAPTYPE ->
3930 HEAPTYPE.
3931
3932 During the 3.5 development cycle, we fixed the code in
3933 compatible_for_assignment to correctly check compatibility between
3934 arbitrary types, and started allowing __class__ assignment in all cases
3935 where the old and new types did in fact have compatible slots and
3936 memory layout (regardless of whether they were implemented as HEAPTYPEs
3937 or not).
3938
3939 Just before 3.5 was released, though, we discovered that this led to
3940 problems with immutable types like int, where the interpreter assumes
3941 they are immutable and interns some values. Formerly this wasn't a
3942 problem, because they really were immutable -- in particular, all the
3943 types where the interpreter applied this interning trick happened to
3944 also be statically allocated, so the old HEAPTYPE rules were
3945 "accidentally" stopping them from allowing __class__ assignment. But
3946 with the changes to __class__ assignment, we started allowing code like
3947
3948 class MyInt(int):
3949 ...
3950 # Modifies the type of *all* instances of 1 in the whole program,
3951 # including future instances (!), because the 1 object is interned.
3952 (1).__class__ = MyInt
3953
3954 (see https://bugs.python.org/issue24912).
3955
3956 In theory the proper fix would be to identify which classes rely on
3957 this invariant and somehow disallow __class__ assignment only for them,
3958 perhaps via some mechanism like a new Py_TPFLAGS_IMMUTABLE flag (a
3959 "blacklisting" approach). But in practice, since this problem wasn't
3960 noticed late in the 3.5 RC cycle, we're taking the conservative
3961 approach and reinstating the same HEAPTYPE->HEAPTYPE check that we used
3962 to have, plus a "whitelist". For now, the whitelist consists only of
3963 ModuleType subtypes, since those are the cases that motivated the patch
3964 in the first place -- see https://bugs.python.org/issue22986 -- and
3965 since module objects are mutable we can be sure that they are
3966 definitely not being interned. So now we allow HEAPTYPE->HEAPTYPE *or*
3967 ModuleType subtype -> ModuleType subtype.
3968
3969 So far as we know, all the code beyond the following 'if' statement
3970 will correctly handle non-HEAPTYPE classes, and the HEAPTYPE check is
3971 needed only to protect that subset of non-HEAPTYPE classes for which
3972 the interpreter has baked in the assumption that all instances are
3973 truly immutable.
3974 */
3975 if (!(PyType_IsSubtype(newto, &PyModule_Type) &&
3976 PyType_IsSubtype(oldto, &PyModule_Type)) &&
3977 (!(newto->tp_flags & Py_TPFLAGS_HEAPTYPE) ||
3978 !(oldto->tp_flags & Py_TPFLAGS_HEAPTYPE))) {
3979 PyErr_Format(PyExc_TypeError,
3980 "__class__ assignment only supported for heap types "
3981 "or ModuleType subclasses");
3982 return -1;
3983 }
3984
Christian Heimesde4d1832013-07-20 14:19:46 +02003985 if (compatible_for_assignment(oldto, newto, "__class__")) {
Benjamin Peterson9d4cbcc2015-01-30 13:33:42 -05003986 if (newto->tp_flags & Py_TPFLAGS_HEAPTYPE)
3987 Py_INCREF(newto);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003988 Py_TYPE(self) = newto;
Benjamin Peterson9d4cbcc2015-01-30 13:33:42 -05003989 if (oldto->tp_flags & Py_TPFLAGS_HEAPTYPE)
3990 Py_DECREF(oldto);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003991 return 0;
3992 }
3993 else {
3994 return -1;
3995 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003996}
3997
3998static PyGetSetDef object_getsets[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003999 {"__class__", object_get_class, object_set_class,
4000 PyDoc_STR("the object's class")},
4001 {0}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004002};
4003
Guido van Rossumc53f0092003-02-18 22:05:12 +00004004
Guido van Rossum036f9992003-02-21 22:02:54 +00004005/* Stuff to implement __reduce_ex__ for pickle protocols >= 2.
Alexandre Vassalottif7fa63d2008-05-11 08:55:36 +00004006 We fall back to helpers in copyreg for:
Guido van Rossum036f9992003-02-21 22:02:54 +00004007 - pickle protocols < 2
4008 - calculating the list of slot names (done only once per class)
4009 - the __newobj__ function (which is used as a token but never called)
4010*/
4011
4012static PyObject *
Alexandre Vassalottif7fa63d2008-05-11 08:55:36 +00004013import_copyreg(void)
Guido van Rossum036f9992003-02-21 22:02:54 +00004014{
Alexandre Vassalotti1a830702013-11-30 00:53:09 -08004015 PyObject *copyreg_str;
4016 PyObject *copyreg_module;
Alexandre Vassalotti1a830702013-11-30 00:53:09 -08004017 _Py_IDENTIFIER(copyreg);
Guido van Rossum3926a632001-09-25 16:25:58 +00004018
Alexandre Vassalotti1a830702013-11-30 00:53:09 -08004019 copyreg_str = _PyUnicode_FromId(&PyId_copyreg);
4020 if (copyreg_str == NULL) {
4021 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004022 }
Alexandre Vassalotti1a830702013-11-30 00:53:09 -08004023 /* Try to fetch cached copy of copyreg from sys.modules first in an
4024 attempt to avoid the import overhead. Previously this was implemented
4025 by storing a reference to the cached module in a static variable, but
Raymond Hettinger15f44ab2016-08-30 10:47:49 -07004026 this broke when multiple embedded interpreters were in use (see issue
Alexandre Vassalotti1a830702013-11-30 00:53:09 -08004027 #17408 and #19088). */
Eric Snow3f9eee62017-09-15 16:35:20 -06004028 copyreg_module = PyImport_GetModule(copyreg_str);
Alexandre Vassalotti1a830702013-11-30 00:53:09 -08004029 if (copyreg_module != NULL) {
Alexandre Vassalotti1a830702013-11-30 00:53:09 -08004030 return copyreg_module;
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01004031 }
Alexandre Vassalotti1a830702013-11-30 00:53:09 -08004032 if (PyErr_Occurred()) {
4033 return NULL;
4034 }
4035 return PyImport_Import(copyreg_str);
Guido van Rossum036f9992003-02-21 22:02:54 +00004036}
4037
Benjamin Peterson6cb526e2016-09-09 12:42:51 -07004038static PyObject *
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004039_PyType_GetSlotNames(PyTypeObject *cls)
Guido van Rossum036f9992003-02-21 22:02:54 +00004040{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004041 PyObject *copyreg;
4042 PyObject *slotnames;
Victor Stinner3c1e4812012-03-26 22:10:51 +02004043 _Py_IDENTIFIER(__slotnames__);
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02004044 _Py_IDENTIFIER(_slotnames);
Guido van Rossum036f9992003-02-21 22:02:54 +00004045
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004046 assert(PyType_Check(cls));
4047
4048 /* Get the slot names from the cache in the class if possible. */
4049 slotnames = _PyDict_GetItemIdWithError(cls->tp_dict, &PyId___slotnames__);
4050 if (slotnames != NULL) {
4051 if (slotnames != Py_None && !PyList_Check(slotnames)) {
4052 PyErr_Format(PyExc_TypeError,
4053 "%.200s.__slotnames__ should be a list or None, "
4054 "not %.200s",
4055 cls->tp_name, Py_TYPE(slotnames)->tp_name);
4056 return NULL;
4057 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004058 Py_INCREF(slotnames);
4059 return slotnames;
4060 }
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004061 else {
4062 if (PyErr_Occurred()) {
4063 return NULL;
4064 }
4065 /* The class does not have the slot names cached yet. */
4066 }
Guido van Rossum036f9992003-02-21 22:02:54 +00004067
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004068 copyreg = import_copyreg();
4069 if (copyreg == NULL)
4070 return NULL;
Guido van Rossum036f9992003-02-21 22:02:54 +00004071
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004072 /* Use _slotnames function from the copyreg module to find the slots
4073 by this class and its bases. This function will cache the result
4074 in __slotnames__. */
4075 slotnames = _PyObject_CallMethodIdObjArgs(copyreg, &PyId__slotnames,
4076 cls, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004077 Py_DECREF(copyreg);
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004078 if (slotnames == NULL)
4079 return NULL;
4080
4081 if (slotnames != Py_None && !PyList_Check(slotnames)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004082 PyErr_SetString(PyExc_TypeError,
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004083 "copyreg._slotnames didn't return a list or None");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004084 Py_DECREF(slotnames);
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004085 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004086 }
Guido van Rossum036f9992003-02-21 22:02:54 +00004087
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004088 return slotnames;
Guido van Rossum036f9992003-02-21 22:02:54 +00004089}
4090
Benjamin Peterson6cb526e2016-09-09 12:42:51 -07004091static PyObject *
Serhiy Storchakaf81be8a2015-12-25 21:04:29 +02004092_PyObject_GetState(PyObject *obj, int required)
Guido van Rossum036f9992003-02-21 22:02:54 +00004093{
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004094 PyObject *state;
4095 PyObject *getstate;
Victor Stinner3c1e4812012-03-26 22:10:51 +02004096 _Py_IDENTIFIER(__getstate__);
Guido van Rossum036f9992003-02-21 22:02:54 +00004097
Serhiy Storchakaf320be72018-01-25 10:49:40 +02004098 if (_PyObject_LookupAttrId(obj, &PyId___getstate__, &getstate) < 0) {
4099 return NULL;
4100 }
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004101 if (getstate == NULL) {
4102 PyObject *slotnames;
4103
Serhiy Storchakaf81be8a2015-12-25 21:04:29 +02004104 if (required && obj->ob_type->tp_itemsize) {
4105 PyErr_Format(PyExc_TypeError,
4106 "can't pickle %.200s objects",
4107 Py_TYPE(obj)->tp_name);
4108 return NULL;
4109 }
4110
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004111 {
4112 PyObject **dict;
4113 dict = _PyObject_GetDictPtr(obj);
Larry Hastings5c661892014-01-24 06:17:25 -08004114 /* It is possible that the object's dict is not initialized
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004115 yet. In this case, we will return None for the state.
4116 We also return None if the dict is empty to make the behavior
4117 consistent regardless whether the dict was initialized or not.
4118 This make unit testing easier. */
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02004119 if (dict != NULL && *dict != NULL && PyDict_GET_SIZE(*dict)) {
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004120 state = *dict;
4121 }
4122 else {
4123 state = Py_None;
4124 }
4125 Py_INCREF(state);
4126 }
4127
4128 slotnames = _PyType_GetSlotNames(Py_TYPE(obj));
4129 if (slotnames == NULL) {
4130 Py_DECREF(state);
4131 return NULL;
4132 }
4133
4134 assert(slotnames == Py_None || PyList_Check(slotnames));
Serhiy Storchakaf81be8a2015-12-25 21:04:29 +02004135 if (required) {
4136 Py_ssize_t basicsize = PyBaseObject_Type.tp_basicsize;
4137 if (obj->ob_type->tp_dictoffset)
4138 basicsize += sizeof(PyObject *);
4139 if (obj->ob_type->tp_weaklistoffset)
4140 basicsize += sizeof(PyObject *);
4141 if (slotnames != Py_None)
Serhiy Storchakafff9a312017-03-21 08:53:25 +02004142 basicsize += sizeof(PyObject *) * PyList_GET_SIZE(slotnames);
Serhiy Storchakaf81be8a2015-12-25 21:04:29 +02004143 if (obj->ob_type->tp_basicsize > basicsize) {
4144 Py_DECREF(slotnames);
4145 Py_DECREF(state);
4146 PyErr_Format(PyExc_TypeError,
4147 "can't pickle %.200s objects",
4148 Py_TYPE(obj)->tp_name);
4149 return NULL;
4150 }
4151 }
4152
Serhiy Storchakafff9a312017-03-21 08:53:25 +02004153 if (slotnames != Py_None && PyList_GET_SIZE(slotnames) > 0) {
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004154 PyObject *slots;
4155 Py_ssize_t slotnames_size, i;
4156
4157 slots = PyDict_New();
4158 if (slots == NULL) {
4159 Py_DECREF(slotnames);
4160 Py_DECREF(state);
4161 return NULL;
4162 }
4163
Serhiy Storchakafff9a312017-03-21 08:53:25 +02004164 slotnames_size = PyList_GET_SIZE(slotnames);
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004165 for (i = 0; i < slotnames_size; i++) {
4166 PyObject *name, *value;
4167
4168 name = PyList_GET_ITEM(slotnames, i);
Serhiy Storchakad28bb622015-11-25 18:33:29 +02004169 Py_INCREF(name);
Serhiy Storchakaf320be72018-01-25 10:49:40 +02004170 if (_PyObject_LookupAttr(obj, name, &value) < 0) {
4171 goto error;
4172 }
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004173 if (value == NULL) {
Serhiy Storchakad28bb622015-11-25 18:33:29 +02004174 Py_DECREF(name);
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004175 /* It is not an error if the attribute is not present. */
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004176 }
4177 else {
4178 int err = PyDict_SetItem(slots, name, value);
Serhiy Storchakad28bb622015-11-25 18:33:29 +02004179 Py_DECREF(name);
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004180 Py_DECREF(value);
4181 if (err) {
4182 goto error;
4183 }
4184 }
4185
Martin Panter8f265652016-04-19 04:03:41 +00004186 /* The list is stored on the class so it may mutate while we
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004187 iterate over it */
Serhiy Storchakafff9a312017-03-21 08:53:25 +02004188 if (slotnames_size != PyList_GET_SIZE(slotnames)) {
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004189 PyErr_Format(PyExc_RuntimeError,
4190 "__slotsname__ changed size during iteration");
4191 goto error;
4192 }
4193
4194 /* We handle errors within the loop here. */
4195 if (0) {
4196 error:
4197 Py_DECREF(slotnames);
4198 Py_DECREF(slots);
4199 Py_DECREF(state);
4200 return NULL;
4201 }
4202 }
4203
4204 /* If we found some slot attributes, pack them in a tuple along
Berker Peksag0ac70c02016-04-29 16:54:10 +03004205 the original attribute dictionary. */
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02004206 if (PyDict_GET_SIZE(slots) > 0) {
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004207 PyObject *state2;
4208
4209 state2 = PyTuple_Pack(2, state, slots);
4210 Py_DECREF(state);
4211 if (state2 == NULL) {
4212 Py_DECREF(slotnames);
4213 Py_DECREF(slots);
4214 return NULL;
4215 }
4216 state = state2;
4217 }
4218 Py_DECREF(slots);
4219 }
4220 Py_DECREF(slotnames);
4221 }
4222 else { /* getstate != NULL */
Victor Stinnera5ed5f02016-12-06 18:45:50 +01004223 state = _PyObject_CallNoArg(getstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004224 Py_DECREF(getstate);
4225 if (state == NULL)
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004226 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004227 }
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004228
4229 return state;
4230}
4231
Benjamin Peterson6cb526e2016-09-09 12:42:51 -07004232static int
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004233_PyObject_GetNewArguments(PyObject *obj, PyObject **args, PyObject **kwargs)
4234{
4235 PyObject *getnewargs, *getnewargs_ex;
4236 _Py_IDENTIFIER(__getnewargs_ex__);
4237 _Py_IDENTIFIER(__getnewargs__);
4238
4239 if (args == NULL || kwargs == NULL) {
4240 PyErr_BadInternalCall();
4241 return -1;
4242 }
4243
4244 /* We first attempt to fetch the arguments for __new__ by calling
4245 __getnewargs_ex__ on the object. */
Benjamin Petersone686c5c2014-02-16 13:49:16 -05004246 getnewargs_ex = _PyObject_LookupSpecial(obj, &PyId___getnewargs_ex__);
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004247 if (getnewargs_ex != NULL) {
Victor Stinnera5ed5f02016-12-06 18:45:50 +01004248 PyObject *newargs = _PyObject_CallNoArg(getnewargs_ex);
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004249 Py_DECREF(getnewargs_ex);
4250 if (newargs == NULL) {
4251 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004252 }
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004253 if (!PyTuple_Check(newargs)) {
4254 PyErr_Format(PyExc_TypeError,
4255 "__getnewargs_ex__ should return a tuple, "
4256 "not '%.200s'", Py_TYPE(newargs)->tp_name);
4257 Py_DECREF(newargs);
4258 return -1;
4259 }
Serhiy Storchakafff9a312017-03-21 08:53:25 +02004260 if (PyTuple_GET_SIZE(newargs) != 2) {
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004261 PyErr_Format(PyExc_ValueError,
4262 "__getnewargs_ex__ should return a tuple of "
Serhiy Storchakafff9a312017-03-21 08:53:25 +02004263 "length 2, not %zd", PyTuple_GET_SIZE(newargs));
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004264 Py_DECREF(newargs);
4265 return -1;
4266 }
4267 *args = PyTuple_GET_ITEM(newargs, 0);
4268 Py_INCREF(*args);
4269 *kwargs = PyTuple_GET_ITEM(newargs, 1);
4270 Py_INCREF(*kwargs);
4271 Py_DECREF(newargs);
4272
4273 /* XXX We should perhaps allow None to be passed here. */
4274 if (!PyTuple_Check(*args)) {
4275 PyErr_Format(PyExc_TypeError,
4276 "first item of the tuple returned by "
4277 "__getnewargs_ex__ must be a tuple, not '%.200s'",
4278 Py_TYPE(*args)->tp_name);
4279 Py_CLEAR(*args);
4280 Py_CLEAR(*kwargs);
4281 return -1;
4282 }
4283 if (!PyDict_Check(*kwargs)) {
4284 PyErr_Format(PyExc_TypeError,
4285 "second item of the tuple returned by "
4286 "__getnewargs_ex__ must be a dict, not '%.200s'",
4287 Py_TYPE(*kwargs)->tp_name);
4288 Py_CLEAR(*args);
4289 Py_CLEAR(*kwargs);
4290 return -1;
4291 }
4292 return 0;
Benjamin Petersone686c5c2014-02-16 13:49:16 -05004293 } else if (PyErr_Occurred()) {
4294 return -1;
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004295 }
4296
4297 /* The object does not have __getnewargs_ex__ so we fallback on using
4298 __getnewargs__ instead. */
Benjamin Petersone686c5c2014-02-16 13:49:16 -05004299 getnewargs = _PyObject_LookupSpecial(obj, &PyId___getnewargs__);
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004300 if (getnewargs != NULL) {
Victor Stinnera5ed5f02016-12-06 18:45:50 +01004301 *args = _PyObject_CallNoArg(getnewargs);
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004302 Py_DECREF(getnewargs);
4303 if (*args == NULL) {
4304 return -1;
4305 }
4306 if (!PyTuple_Check(*args)) {
4307 PyErr_Format(PyExc_TypeError,
4308 "__getnewargs__ should return a tuple, "
4309 "not '%.200s'", Py_TYPE(*args)->tp_name);
4310 Py_CLEAR(*args);
4311 return -1;
4312 }
4313 *kwargs = NULL;
4314 return 0;
Benjamin Petersone686c5c2014-02-16 13:49:16 -05004315 } else if (PyErr_Occurred()) {
4316 return -1;
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004317 }
4318
4319 /* The object does not have __getnewargs_ex__ and __getnewargs__. This may
Martin Panter8f265652016-04-19 04:03:41 +00004320 mean __new__ does not takes any arguments on this object, or that the
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004321 object does not implement the reduce protocol for pickling or
4322 copying. */
4323 *args = NULL;
4324 *kwargs = NULL;
4325 return 0;
4326}
4327
Benjamin Peterson6cb526e2016-09-09 12:42:51 -07004328static int
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004329_PyObject_GetItemsIter(PyObject *obj, PyObject **listitems,
4330 PyObject **dictitems)
4331{
4332 if (listitems == NULL || dictitems == NULL) {
4333 PyErr_BadInternalCall();
4334 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004335 }
Guido van Rossum036f9992003-02-21 22:02:54 +00004336
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004337 if (!PyList_Check(obj)) {
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004338 *listitems = Py_None;
4339 Py_INCREF(*listitems);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004340 }
4341 else {
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004342 *listitems = PyObject_GetIter(obj);
Christian Heimes2489bd82013-11-23 21:19:43 +01004343 if (*listitems == NULL)
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004344 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004345 }
Guido van Rossum036f9992003-02-21 22:02:54 +00004346
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004347 if (!PyDict_Check(obj)) {
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004348 *dictitems = Py_None;
4349 Py_INCREF(*dictitems);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004350 }
4351 else {
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004352 PyObject *items;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02004353 _Py_IDENTIFIER(items);
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004354
4355 items = _PyObject_CallMethodIdObjArgs(obj, &PyId_items, NULL);
4356 if (items == NULL) {
4357 Py_CLEAR(*listitems);
4358 return -1;
4359 }
4360 *dictitems = PyObject_GetIter(items);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004361 Py_DECREF(items);
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004362 if (*dictitems == NULL) {
4363 Py_CLEAR(*listitems);
4364 return -1;
4365 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004366 }
Guido van Rossum036f9992003-02-21 22:02:54 +00004367
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004368 assert(*listitems != NULL && *dictitems != NULL);
4369
4370 return 0;
4371}
4372
4373static PyObject *
Serhiy Storchaka0d554d72015-10-10 22:42:18 +03004374reduce_newobj(PyObject *obj)
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004375{
4376 PyObject *args = NULL, *kwargs = NULL;
4377 PyObject *copyreg;
4378 PyObject *newobj, *newargs, *state, *listitems, *dictitems;
4379 PyObject *result;
Serhiy Storchakaf81be8a2015-12-25 21:04:29 +02004380 int hasargs;
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004381
Serhiy Storchakad7a44152015-11-12 11:23:04 +02004382 if (Py_TYPE(obj)->tp_new == NULL) {
4383 PyErr_Format(PyExc_TypeError,
Serhiy Storchakaf81be8a2015-12-25 21:04:29 +02004384 "can't pickle %.200s objects",
Serhiy Storchakad7a44152015-11-12 11:23:04 +02004385 Py_TYPE(obj)->tp_name);
4386 return NULL;
4387 }
Serhiy Storchaka707b5cc2014-12-16 19:43:46 +02004388 if (_PyObject_GetNewArguments(obj, &args, &kwargs) < 0)
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004389 return NULL;
Serhiy Storchaka707b5cc2014-12-16 19:43:46 +02004390
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004391 copyreg = import_copyreg();
4392 if (copyreg == NULL) {
Serhiy Storchakaf81be8a2015-12-25 21:04:29 +02004393 Py_XDECREF(args);
Serhiy Storchaka707b5cc2014-12-16 19:43:46 +02004394 Py_XDECREF(kwargs);
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004395 return NULL;
4396 }
Serhiy Storchakaf81be8a2015-12-25 21:04:29 +02004397 hasargs = (args != NULL);
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02004398 if (kwargs == NULL || PyDict_GET_SIZE(kwargs) == 0) {
Serhiy Storchaka707b5cc2014-12-16 19:43:46 +02004399 _Py_IDENTIFIER(__newobj__);
4400 PyObject *cls;
4401 Py_ssize_t i, n;
4402
4403 Py_XDECREF(kwargs);
4404 newobj = _PyObject_GetAttrId(copyreg, &PyId___newobj__);
4405 Py_DECREF(copyreg);
4406 if (newobj == NULL) {
Serhiy Storchakaf81be8a2015-12-25 21:04:29 +02004407 Py_XDECREF(args);
Serhiy Storchaka707b5cc2014-12-16 19:43:46 +02004408 return NULL;
4409 }
Serhiy Storchakaf81be8a2015-12-25 21:04:29 +02004410 n = args ? PyTuple_GET_SIZE(args) : 0;
Serhiy Storchaka707b5cc2014-12-16 19:43:46 +02004411 newargs = PyTuple_New(n+1);
4412 if (newargs == NULL) {
Serhiy Storchakaf81be8a2015-12-25 21:04:29 +02004413 Py_XDECREF(args);
Serhiy Storchaka707b5cc2014-12-16 19:43:46 +02004414 Py_DECREF(newobj);
4415 return NULL;
4416 }
4417 cls = (PyObject *) Py_TYPE(obj);
4418 Py_INCREF(cls);
4419 PyTuple_SET_ITEM(newargs, 0, cls);
4420 for (i = 0; i < n; i++) {
4421 PyObject *v = PyTuple_GET_ITEM(args, i);
4422 Py_INCREF(v);
4423 PyTuple_SET_ITEM(newargs, i+1, v);
4424 }
Serhiy Storchakaf81be8a2015-12-25 21:04:29 +02004425 Py_XDECREF(args);
Serhiy Storchaka707b5cc2014-12-16 19:43:46 +02004426 }
Christian Heimes07a2a1b2016-09-09 00:21:22 +02004427 else if (args != NULL) {
Serhiy Storchaka707b5cc2014-12-16 19:43:46 +02004428 _Py_IDENTIFIER(__newobj_ex__);
4429
4430 newobj = _PyObject_GetAttrId(copyreg, &PyId___newobj_ex__);
4431 Py_DECREF(copyreg);
4432 if (newobj == NULL) {
4433 Py_DECREF(args);
4434 Py_DECREF(kwargs);
4435 return NULL;
4436 }
4437 newargs = PyTuple_Pack(3, Py_TYPE(obj), args, kwargs);
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004438 Py_DECREF(args);
4439 Py_DECREF(kwargs);
Serhiy Storchaka707b5cc2014-12-16 19:43:46 +02004440 if (newargs == NULL) {
4441 Py_DECREF(newobj);
4442 return NULL;
4443 }
4444 }
Christian Heimes07a2a1b2016-09-09 00:21:22 +02004445 else {
4446 /* args == NULL */
4447 Py_DECREF(kwargs);
4448 PyErr_BadInternalCall();
4449 return NULL;
4450 }
Serhiy Storchaka707b5cc2014-12-16 19:43:46 +02004451
Serhiy Storchakaf81be8a2015-12-25 21:04:29 +02004452 state = _PyObject_GetState(obj,
4453 !hasargs && !PyList_Check(obj) && !PyDict_Check(obj));
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004454 if (state == NULL) {
4455 Py_DECREF(newobj);
4456 Py_DECREF(newargs);
4457 return NULL;
4458 }
4459 if (_PyObject_GetItemsIter(obj, &listitems, &dictitems) < 0) {
4460 Py_DECREF(newobj);
4461 Py_DECREF(newargs);
4462 Py_DECREF(state);
4463 return NULL;
4464 }
4465
4466 result = PyTuple_Pack(5, newobj, newargs, state, listitems, dictitems);
4467 Py_DECREF(newobj);
4468 Py_DECREF(newargs);
4469 Py_DECREF(state);
4470 Py_DECREF(listitems);
4471 Py_DECREF(dictitems);
Larry Hastings5c661892014-01-24 06:17:25 -08004472 return result;
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004473}
4474
Guido van Rossumd8faa362007-04-27 19:54:29 +00004475/*
4476 * There were two problems when object.__reduce__ and object.__reduce_ex__
4477 * were implemented in the same function:
4478 * - trying to pickle an object with a custom __reduce__ method that
4479 * fell back to object.__reduce__ in certain circumstances led to
Yury Selivanovf488fb42015-07-03 01:04:23 -04004480 * infinite recursion at Python level and eventual RecursionError.
Guido van Rossumd8faa362007-04-27 19:54:29 +00004481 * - Pickling objects that lied about their type by overwriting the
4482 * __class__ descriptor could lead to infinite recursion at C level
4483 * and eventual segfault.
4484 *
4485 * Because of backwards compatibility, the two methods still have to
4486 * behave in the same way, even if this is not required by the pickle
4487 * protocol. This common functionality was moved to the _common_reduce
4488 * function.
4489 */
4490static PyObject *
4491_common_reduce(PyObject *self, int proto)
4492{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004493 PyObject *copyreg, *res;
Guido van Rossumd8faa362007-04-27 19:54:29 +00004494
Serhiy Storchaka707b5cc2014-12-16 19:43:46 +02004495 if (proto >= 2)
Serhiy Storchaka0d554d72015-10-10 22:42:18 +03004496 return reduce_newobj(self);
Guido van Rossumd8faa362007-04-27 19:54:29 +00004497
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004498 copyreg = import_copyreg();
4499 if (!copyreg)
4500 return NULL;
Guido van Rossumd8faa362007-04-27 19:54:29 +00004501
INADA Naoki72dccde2017-02-16 09:26:01 +09004502 res = PyObject_CallMethod(copyreg, "_reduce_ex", "Oi", self, proto);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004503 Py_DECREF(copyreg);
Guido van Rossumd8faa362007-04-27 19:54:29 +00004504
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004505 return res;
Guido van Rossumd8faa362007-04-27 19:54:29 +00004506}
4507
Serhiy Storchaka5c643a02017-03-19 08:46:44 +02004508/*[clinic input]
4509object.__reduce__
4510
Serhiy Storchaka5c643a02017-03-19 08:46:44 +02004511Helper for pickle.
4512[clinic start generated code]*/
4513
Guido van Rossumd8faa362007-04-27 19:54:29 +00004514static PyObject *
Serhiy Storchaka205e00c2017-04-08 09:52:59 +03004515object___reduce___impl(PyObject *self)
4516/*[clinic end generated code: output=d4ca691f891c6e2f input=11562e663947e18b]*/
Guido van Rossumd8faa362007-04-27 19:54:29 +00004517{
Serhiy Storchaka205e00c2017-04-08 09:52:59 +03004518 return _common_reduce(self, 0);
Guido van Rossumd8faa362007-04-27 19:54:29 +00004519}
4520
Serhiy Storchaka5c643a02017-03-19 08:46:44 +02004521/*[clinic input]
4522object.__reduce_ex__
4523
Serhiy Storchaka205e00c2017-04-08 09:52:59 +03004524 protocol: int
Serhiy Storchaka5c643a02017-03-19 08:46:44 +02004525 /
4526
4527Helper for pickle.
4528[clinic start generated code]*/
4529
Guido van Rossum036f9992003-02-21 22:02:54 +00004530static PyObject *
Serhiy Storchaka5c643a02017-03-19 08:46:44 +02004531object___reduce_ex___impl(PyObject *self, int protocol)
Serhiy Storchaka205e00c2017-04-08 09:52:59 +03004532/*[clinic end generated code: output=2e157766f6b50094 input=f326b43fb8a4c5ff]*/
Guido van Rossum036f9992003-02-21 22:02:54 +00004533{
Victor Stinner3c1e4812012-03-26 22:10:51 +02004534 static PyObject *objreduce;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004535 PyObject *reduce, *res;
Victor Stinner3c1e4812012-03-26 22:10:51 +02004536 _Py_IDENTIFIER(__reduce__);
Guido van Rossum036f9992003-02-21 22:02:54 +00004537
Victor Stinner3c1e4812012-03-26 22:10:51 +02004538 if (objreduce == NULL) {
4539 objreduce = _PyDict_GetItemId(PyBaseObject_Type.tp_dict,
4540 &PyId___reduce__);
4541 if (objreduce == NULL)
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01004542 return NULL;
4543 }
4544
Victor Stinner3c1e4812012-03-26 22:10:51 +02004545 reduce = _PyObject_GetAttrId(self, &PyId___reduce__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004546 if (reduce == NULL)
4547 PyErr_Clear();
4548 else {
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01004549 PyObject *cls, *clsreduce;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004550 int override;
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01004551
4552 cls = (PyObject *) Py_TYPE(self);
Victor Stinner3c1e4812012-03-26 22:10:51 +02004553 clsreduce = _PyObject_GetAttrId(cls, &PyId___reduce__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004554 if (clsreduce == NULL) {
4555 Py_DECREF(reduce);
4556 return NULL;
4557 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004558 override = (clsreduce != objreduce);
4559 Py_DECREF(clsreduce);
4560 if (override) {
Victor Stinnera5ed5f02016-12-06 18:45:50 +01004561 res = _PyObject_CallNoArg(reduce);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004562 Py_DECREF(reduce);
4563 return res;
4564 }
4565 else
4566 Py_DECREF(reduce);
4567 }
Guido van Rossum036f9992003-02-21 22:02:54 +00004568
Serhiy Storchaka5c643a02017-03-19 08:46:44 +02004569 return _common_reduce(self, protocol);
Guido van Rossum3926a632001-09-25 16:25:58 +00004570}
4571
Christian Heimes9e7f1d22008-02-28 12:27:11 +00004572static PyObject *
4573object_subclasshook(PyObject *cls, PyObject *args)
4574{
Brian Curtindfc80e32011-08-10 20:28:54 -05004575 Py_RETURN_NOTIMPLEMENTED;
Christian Heimes9e7f1d22008-02-28 12:27:11 +00004576}
4577
4578PyDoc_STRVAR(object_subclasshook_doc,
4579"Abstract classes can override this to customize issubclass().\n"
4580"\n"
4581"This is invoked early on by abc.ABCMeta.__subclasscheck__().\n"
4582"It should return True, False or NotImplemented. If it returns\n"
4583"NotImplemented, the normal algorithm is used. Otherwise, it\n"
4584"overrides the normal algorithm (and the outcome is cached).\n");
Eric Smith8c663262007-08-25 02:26:07 +00004585
Nick Coghland78448e2016-07-30 16:26:03 +10004586static PyObject *
4587object_init_subclass(PyObject *cls, PyObject *arg)
4588{
4589 Py_RETURN_NONE;
4590}
4591
4592PyDoc_STRVAR(object_init_subclass_doc,
Berker Peksag01d17192016-07-30 14:06:15 +03004593"This method is called when a class is subclassed.\n"
Nick Coghland78448e2016-07-30 16:26:03 +10004594"\n"
Berker Peksag01d17192016-07-30 14:06:15 +03004595"The default implementation does nothing. It may be\n"
4596"overridden to extend subclasses.\n");
Nick Coghland78448e2016-07-30 16:26:03 +10004597
Serhiy Storchaka5c643a02017-03-19 08:46:44 +02004598/*[clinic input]
4599object.__format__
4600
4601 format_spec: unicode
4602 /
4603
4604Default object formatter.
4605[clinic start generated code]*/
4606
Eric Smith8c663262007-08-25 02:26:07 +00004607static PyObject *
Serhiy Storchaka5c643a02017-03-19 08:46:44 +02004608object___format___impl(PyObject *self, PyObject *format_spec)
4609/*[clinic end generated code: output=34897efb543a974b input=7c3b3bc53a6fb7fa]*/
Eric Smith8c663262007-08-25 02:26:07 +00004610{
Serhiy Storchakad1af5ef2016-10-30 19:33:54 +02004611 /* Issue 7994: If we're converting to a string, we
4612 should reject format specifications */
4613 if (PyUnicode_GET_LENGTH(format_spec) > 0) {
4614 PyErr_Format(PyExc_TypeError,
4615 "unsupported format string passed to %.200s.__format__",
4616 self->ob_type->tp_name);
4617 return NULL;
4618 }
Serhiy Storchaka7e19dbc2017-05-13 12:40:52 +03004619 return PyObject_Str(self);
Eric Smith8c663262007-08-25 02:26:07 +00004620}
4621
Serhiy Storchaka5c643a02017-03-19 08:46:44 +02004622/*[clinic input]
4623object.__sizeof__
4624
4625Size of object in memory, in bytes.
4626[clinic start generated code]*/
4627
Martin v. Löwis00709aa2008-06-04 14:18:43 +00004628static PyObject *
Serhiy Storchaka5c643a02017-03-19 08:46:44 +02004629object___sizeof___impl(PyObject *self)
4630/*[clinic end generated code: output=73edab332f97d550 input=1200ff3dfe485306]*/
Martin v. Löwis00709aa2008-06-04 14:18:43 +00004631{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004632 Py_ssize_t res, isize;
Martin v. Löwis00709aa2008-06-04 14:18:43 +00004633
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004634 res = 0;
4635 isize = self->ob_type->tp_itemsize;
4636 if (isize > 0)
Antoine Pitroua6545102015-03-10 22:32:00 +01004637 res = Py_SIZE(self) * isize;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004638 res += self->ob_type->tp_basicsize;
Martin v. Löwis00709aa2008-06-04 14:18:43 +00004639
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004640 return PyLong_FromSsize_t(res);
Martin v. Löwis00709aa2008-06-04 14:18:43 +00004641}
4642
Benjamin Peterson82b00c12011-05-24 11:09:06 -05004643/* __dir__ for generic objects: returns __dict__, __class__,
4644 and recursively up the __class__.__bases__ chain.
4645*/
Serhiy Storchaka5c643a02017-03-19 08:46:44 +02004646/*[clinic input]
4647object.__dir__
4648
4649Default dir() implementation.
4650[clinic start generated code]*/
4651
Benjamin Peterson82b00c12011-05-24 11:09:06 -05004652static PyObject *
Serhiy Storchaka5c643a02017-03-19 08:46:44 +02004653object___dir___impl(PyObject *self)
4654/*[clinic end generated code: output=66dd48ea62f26c90 input=0a89305bec669b10]*/
Benjamin Peterson82b00c12011-05-24 11:09:06 -05004655{
4656 PyObject *result = NULL;
4657 PyObject *dict = NULL;
4658 PyObject *itsclass = NULL;
4659
4660 /* Get __dict__ (which may or may not be a real dict...) */
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02004661 dict = _PyObject_GetAttrId(self, &PyId___dict__);
Benjamin Peterson82b00c12011-05-24 11:09:06 -05004662 if (dict == NULL) {
4663 PyErr_Clear();
4664 dict = PyDict_New();
4665 }
4666 else if (!PyDict_Check(dict)) {
4667 Py_DECREF(dict);
4668 dict = PyDict_New();
4669 }
4670 else {
4671 /* Copy __dict__ to avoid mutating it. */
4672 PyObject *temp = PyDict_Copy(dict);
4673 Py_DECREF(dict);
4674 dict = temp;
4675 }
4676
4677 if (dict == NULL)
4678 goto error;
4679
4680 /* Merge in attrs reachable from its class. */
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02004681 itsclass = _PyObject_GetAttrId(self, &PyId___class__);
Benjamin Peterson82b00c12011-05-24 11:09:06 -05004682 if (itsclass == NULL)
4683 /* XXX(tomer): Perhaps fall back to obj->ob_type if no
4684 __class__ exists? */
4685 PyErr_Clear();
4686 else if (merge_class_dict(dict, itsclass) != 0)
4687 goto error;
4688
4689 result = PyDict_Keys(dict);
4690 /* fall through */
4691error:
4692 Py_XDECREF(itsclass);
4693 Py_XDECREF(dict);
4694 return result;
4695}
4696
Guido van Rossum3926a632001-09-25 16:25:58 +00004697static PyMethodDef object_methods[] = {
Serhiy Storchaka5c643a02017-03-19 08:46:44 +02004698 OBJECT___REDUCE_EX___METHODDEF
4699 OBJECT___REDUCE___METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004700 {"__subclasshook__", object_subclasshook, METH_CLASS | METH_VARARGS,
4701 object_subclasshook_doc},
Nick Coghland78448e2016-07-30 16:26:03 +10004702 {"__init_subclass__", object_init_subclass, METH_CLASS | METH_NOARGS,
4703 object_init_subclass_doc},
Serhiy Storchaka5c643a02017-03-19 08:46:44 +02004704 OBJECT___FORMAT___METHODDEF
4705 OBJECT___SIZEOF___METHODDEF
4706 OBJECT___DIR___METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004707 {0}
Guido van Rossum3926a632001-09-25 16:25:58 +00004708};
4709
Guido van Rossum036f9992003-02-21 22:02:54 +00004710
Tim Peters6d6c1a32001-08-02 04:15:00 +00004711PyTypeObject PyBaseObject_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004712 PyVarObject_HEAD_INIT(&PyType_Type, 0)
4713 "object", /* tp_name */
4714 sizeof(PyObject), /* tp_basicsize */
4715 0, /* tp_itemsize */
4716 object_dealloc, /* tp_dealloc */
4717 0, /* tp_print */
4718 0, /* tp_getattr */
4719 0, /* tp_setattr */
4720 0, /* tp_reserved */
4721 object_repr, /* tp_repr */
4722 0, /* tp_as_number */
4723 0, /* tp_as_sequence */
4724 0, /* tp_as_mapping */
4725 (hashfunc)_Py_HashPointer, /* tp_hash */
4726 0, /* tp_call */
4727 object_str, /* tp_str */
4728 PyObject_GenericGetAttr, /* tp_getattro */
4729 PyObject_GenericSetAttr, /* tp_setattro */
4730 0, /* tp_as_buffer */
Larry Hastings5c661892014-01-24 06:17:25 -08004731 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Larry Hastings2623c8c2014-02-08 22:15:29 -08004732 PyDoc_STR("object()\n--\n\nThe most base type"), /* tp_doc */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004733 0, /* tp_traverse */
4734 0, /* tp_clear */
4735 object_richcompare, /* tp_richcompare */
4736 0, /* tp_weaklistoffset */
4737 0, /* tp_iter */
4738 0, /* tp_iternext */
4739 object_methods, /* tp_methods */
4740 0, /* tp_members */
4741 object_getsets, /* tp_getset */
4742 0, /* tp_base */
4743 0, /* tp_dict */
4744 0, /* tp_descr_get */
4745 0, /* tp_descr_set */
4746 0, /* tp_dictoffset */
4747 object_init, /* tp_init */
4748 PyType_GenericAlloc, /* tp_alloc */
4749 object_new, /* tp_new */
4750 PyObject_Del, /* tp_free */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004751};
4752
4753
Guido van Rossum50e9fb92006-08-17 05:42:55 +00004754/* Add the methods from tp_methods to the __dict__ in a type object */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004755
4756static int
4757add_methods(PyTypeObject *type, PyMethodDef *meth)
4758{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004759 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004760
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004761 for (; meth->ml_name != NULL; meth++) {
4762 PyObject *descr;
Benjamin Peterson89a6e9a2012-05-08 09:22:24 -04004763 int err;
INADA Naoki35a96a22017-01-28 16:35:44 +09004764 int isdescr = 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004765 if (PyDict_GetItemString(dict, meth->ml_name) &&
4766 !(meth->ml_flags & METH_COEXIST))
4767 continue;
4768 if (meth->ml_flags & METH_CLASS) {
4769 if (meth->ml_flags & METH_STATIC) {
4770 PyErr_SetString(PyExc_ValueError,
4771 "method cannot be both class and static");
4772 return -1;
4773 }
4774 descr = PyDescr_NewClassMethod(type, meth);
4775 }
4776 else if (meth->ml_flags & METH_STATIC) {
Andrew Svetlov3ba3a3e2012-12-25 13:32:35 +02004777 PyObject *cfunc = PyCFunction_NewEx(meth, (PyObject*)type, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004778 if (cfunc == NULL)
4779 return -1;
4780 descr = PyStaticMethod_New(cfunc);
INADA Naoki35a96a22017-01-28 16:35:44 +09004781 isdescr = 0; // PyStaticMethod is not PyDescrObject
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004782 Py_DECREF(cfunc);
4783 }
4784 else {
4785 descr = PyDescr_NewMethod(type, meth);
4786 }
4787 if (descr == NULL)
4788 return -1;
INADA Naoki35a96a22017-01-28 16:35:44 +09004789 if (isdescr) {
4790 err = PyDict_SetItem(dict, PyDescr_NAME(descr), descr);
4791 }
4792 else {
4793 err = PyDict_SetItemString(dict, meth->ml_name, descr);
4794 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004795 Py_DECREF(descr);
Benjamin Peterson89a6e9a2012-05-08 09:22:24 -04004796 if (err < 0)
4797 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004798 }
4799 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004800}
4801
4802static int
Guido van Rossum6f799372001-09-20 20:46:19 +00004803add_members(PyTypeObject *type, PyMemberDef *memb)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004804{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004805 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004806
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004807 for (; memb->name != NULL; memb++) {
4808 PyObject *descr;
4809 if (PyDict_GetItemString(dict, memb->name))
4810 continue;
4811 descr = PyDescr_NewMember(type, memb);
4812 if (descr == NULL)
4813 return -1;
INADA Naoki35a96a22017-01-28 16:35:44 +09004814 if (PyDict_SetItem(dict, PyDescr_NAME(descr), descr) < 0) {
Benjamin Peterson27007dc2016-07-06 23:26:32 -07004815 Py_DECREF(descr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004816 return -1;
Benjamin Peterson27007dc2016-07-06 23:26:32 -07004817 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004818 Py_DECREF(descr);
4819 }
4820 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004821}
4822
4823static int
Guido van Rossum32d34c82001-09-20 21:45:26 +00004824add_getset(PyTypeObject *type, PyGetSetDef *gsp)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004825{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004826 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004827
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004828 for (; gsp->name != NULL; gsp++) {
4829 PyObject *descr;
4830 if (PyDict_GetItemString(dict, gsp->name))
4831 continue;
4832 descr = PyDescr_NewGetSet(type, gsp);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004833
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004834 if (descr == NULL)
4835 return -1;
INADA Naoki35a96a22017-01-28 16:35:44 +09004836 if (PyDict_SetItem(dict, PyDescr_NAME(descr), descr) < 0) {
Benjamin Peterson27007dc2016-07-06 23:26:32 -07004837 Py_DECREF(descr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004838 return -1;
Benjamin Peterson27007dc2016-07-06 23:26:32 -07004839 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004840 Py_DECREF(descr);
4841 }
4842 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004843}
4844
Guido van Rossum13d52f02001-08-10 21:24:08 +00004845static void
4846inherit_special(PyTypeObject *type, PyTypeObject *base)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004847{
Tim Peters6d6c1a32001-08-02 04:15:00 +00004848
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004849 /* Copying basicsize is connected to the GC flags */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004850 if (!(type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
4851 (base->tp_flags & Py_TPFLAGS_HAVE_GC) &&
4852 (!type->tp_traverse && !type->tp_clear)) {
4853 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
4854 if (type->tp_traverse == NULL)
4855 type->tp_traverse = base->tp_traverse;
4856 if (type->tp_clear == NULL)
4857 type->tp_clear = base->tp_clear;
4858 }
4859 {
4860 /* The condition below could use some explanation.
4861 It appears that tp_new is not inherited for static types
4862 whose base class is 'object'; this seems to be a precaution
4863 so that old extension types don't suddenly become
4864 callable (object.__new__ wouldn't insure the invariants
4865 that the extension type's own factory function ensures).
4866 Heap types, of course, are under our control, so they do
4867 inherit tp_new; static extension types that specify some
Florent Xiclunaaa6c1d22011-12-12 18:54:29 +01004868 other built-in type as the default also
4869 inherit object.__new__. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004870 if (base != &PyBaseObject_Type ||
4871 (type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
4872 if (type->tp_new == NULL)
4873 type->tp_new = base->tp_new;
4874 }
4875 }
Benjamin Petersona7465e22010-07-05 15:01:22 +00004876 if (type->tp_basicsize == 0)
4877 type->tp_basicsize = base->tp_basicsize;
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00004878
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004879 /* Copy other non-function slots */
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00004880
4881#undef COPYVAL
4882#define COPYVAL(SLOT) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004883 if (type->SLOT == 0) type->SLOT = base->SLOT
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00004884
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004885 COPYVAL(tp_itemsize);
4886 COPYVAL(tp_weaklistoffset);
4887 COPYVAL(tp_dictoffset);
Thomas Wouters27d517b2007-02-25 20:39:11 +00004888
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004889 /* Setup fast subclass flags */
4890 if (PyType_IsSubtype(base, (PyTypeObject*)PyExc_BaseException))
4891 type->tp_flags |= Py_TPFLAGS_BASE_EXC_SUBCLASS;
4892 else if (PyType_IsSubtype(base, &PyType_Type))
4893 type->tp_flags |= Py_TPFLAGS_TYPE_SUBCLASS;
4894 else if (PyType_IsSubtype(base, &PyLong_Type))
4895 type->tp_flags |= Py_TPFLAGS_LONG_SUBCLASS;
4896 else if (PyType_IsSubtype(base, &PyBytes_Type))
4897 type->tp_flags |= Py_TPFLAGS_BYTES_SUBCLASS;
4898 else if (PyType_IsSubtype(base, &PyUnicode_Type))
4899 type->tp_flags |= Py_TPFLAGS_UNICODE_SUBCLASS;
4900 else if (PyType_IsSubtype(base, &PyTuple_Type))
4901 type->tp_flags |= Py_TPFLAGS_TUPLE_SUBCLASS;
4902 else if (PyType_IsSubtype(base, &PyList_Type))
4903 type->tp_flags |= Py_TPFLAGS_LIST_SUBCLASS;
4904 else if (PyType_IsSubtype(base, &PyDict_Type))
4905 type->tp_flags |= Py_TPFLAGS_DICT_SUBCLASS;
Guido van Rossum13d52f02001-08-10 21:24:08 +00004906}
4907
Guido van Rossum38938152006-08-21 23:36:26 +00004908static int
Guido van Rossumf5243f02008-01-01 04:06:48 +00004909overrides_hash(PyTypeObject *type)
Guido van Rossum38938152006-08-21 23:36:26 +00004910{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004911 PyObject *dict = type->tp_dict;
Victor Stinner3c1e4812012-03-26 22:10:51 +02004912 _Py_IDENTIFIER(__eq__);
Guido van Rossum38938152006-08-21 23:36:26 +00004913
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004914 assert(dict != NULL);
Victor Stinner3c1e4812012-03-26 22:10:51 +02004915 if (_PyDict_GetItemId(dict, &PyId___eq__) != NULL)
4916 return 1;
4917 if (_PyDict_GetItemId(dict, &PyId___hash__) != NULL)
4918 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004919 return 0;
Guido van Rossum38938152006-08-21 23:36:26 +00004920}
4921
Guido van Rossum13d52f02001-08-10 21:24:08 +00004922static void
4923inherit_slots(PyTypeObject *type, PyTypeObject *base)
4924{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004925 PyTypeObject *basebase;
Guido van Rossum13d52f02001-08-10 21:24:08 +00004926
4927#undef SLOTDEFINED
Tim Peters6d6c1a32001-08-02 04:15:00 +00004928#undef COPYSLOT
4929#undef COPYNUM
4930#undef COPYSEQ
4931#undef COPYMAP
Guido van Rossum5af588b2001-10-12 14:13:21 +00004932#undef COPYBUF
Guido van Rossum13d52f02001-08-10 21:24:08 +00004933
4934#define SLOTDEFINED(SLOT) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004935 (base->SLOT != 0 && \
4936 (basebase == NULL || base->SLOT != basebase->SLOT))
Guido van Rossum13d52f02001-08-10 21:24:08 +00004937
Tim Peters6d6c1a32001-08-02 04:15:00 +00004938#define COPYSLOT(SLOT) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004939 if (!type->SLOT && SLOTDEFINED(SLOT)) type->SLOT = base->SLOT
Tim Peters6d6c1a32001-08-02 04:15:00 +00004940
Yury Selivanov75445082015-05-11 22:57:16 -04004941#define COPYASYNC(SLOT) COPYSLOT(tp_as_async->SLOT)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004942#define COPYNUM(SLOT) COPYSLOT(tp_as_number->SLOT)
4943#define COPYSEQ(SLOT) COPYSLOT(tp_as_sequence->SLOT)
4944#define COPYMAP(SLOT) COPYSLOT(tp_as_mapping->SLOT)
Tim Petersfc57ccb2001-10-12 02:38:24 +00004945#define COPYBUF(SLOT) COPYSLOT(tp_as_buffer->SLOT)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004946
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004947 /* This won't inherit indirect slots (from tp_as_number etc.)
4948 if type doesn't provide the space. */
Guido van Rossum13d52f02001-08-10 21:24:08 +00004949
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004950 if (type->tp_as_number != NULL && base->tp_as_number != NULL) {
4951 basebase = base->tp_base;
4952 if (basebase->tp_as_number == NULL)
4953 basebase = NULL;
4954 COPYNUM(nb_add);
4955 COPYNUM(nb_subtract);
4956 COPYNUM(nb_multiply);
4957 COPYNUM(nb_remainder);
4958 COPYNUM(nb_divmod);
4959 COPYNUM(nb_power);
4960 COPYNUM(nb_negative);
4961 COPYNUM(nb_positive);
4962 COPYNUM(nb_absolute);
4963 COPYNUM(nb_bool);
4964 COPYNUM(nb_invert);
4965 COPYNUM(nb_lshift);
4966 COPYNUM(nb_rshift);
4967 COPYNUM(nb_and);
4968 COPYNUM(nb_xor);
4969 COPYNUM(nb_or);
4970 COPYNUM(nb_int);
4971 COPYNUM(nb_float);
4972 COPYNUM(nb_inplace_add);
4973 COPYNUM(nb_inplace_subtract);
4974 COPYNUM(nb_inplace_multiply);
4975 COPYNUM(nb_inplace_remainder);
4976 COPYNUM(nb_inplace_power);
4977 COPYNUM(nb_inplace_lshift);
4978 COPYNUM(nb_inplace_rshift);
4979 COPYNUM(nb_inplace_and);
4980 COPYNUM(nb_inplace_xor);
4981 COPYNUM(nb_inplace_or);
4982 COPYNUM(nb_true_divide);
4983 COPYNUM(nb_floor_divide);
4984 COPYNUM(nb_inplace_true_divide);
4985 COPYNUM(nb_inplace_floor_divide);
4986 COPYNUM(nb_index);
Benjamin Petersond51374e2014-04-09 23:55:56 -04004987 COPYNUM(nb_matrix_multiply);
4988 COPYNUM(nb_inplace_matrix_multiply);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004989 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004990
Yury Selivanov75445082015-05-11 22:57:16 -04004991 if (type->tp_as_async != NULL && base->tp_as_async != NULL) {
4992 basebase = base->tp_base;
4993 if (basebase->tp_as_async == NULL)
4994 basebase = NULL;
4995 COPYASYNC(am_await);
4996 COPYASYNC(am_aiter);
4997 COPYASYNC(am_anext);
4998 }
4999
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005000 if (type->tp_as_sequence != NULL && base->tp_as_sequence != NULL) {
5001 basebase = base->tp_base;
5002 if (basebase->tp_as_sequence == NULL)
5003 basebase = NULL;
5004 COPYSEQ(sq_length);
5005 COPYSEQ(sq_concat);
5006 COPYSEQ(sq_repeat);
5007 COPYSEQ(sq_item);
5008 COPYSEQ(sq_ass_item);
5009 COPYSEQ(sq_contains);
5010 COPYSEQ(sq_inplace_concat);
5011 COPYSEQ(sq_inplace_repeat);
5012 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00005013
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005014 if (type->tp_as_mapping != NULL && base->tp_as_mapping != NULL) {
5015 basebase = base->tp_base;
5016 if (basebase->tp_as_mapping == NULL)
5017 basebase = NULL;
5018 COPYMAP(mp_length);
5019 COPYMAP(mp_subscript);
5020 COPYMAP(mp_ass_subscript);
5021 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00005022
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005023 if (type->tp_as_buffer != NULL && base->tp_as_buffer != NULL) {
5024 basebase = base->tp_base;
5025 if (basebase->tp_as_buffer == NULL)
5026 basebase = NULL;
5027 COPYBUF(bf_getbuffer);
5028 COPYBUF(bf_releasebuffer);
5029 }
Tim Petersfc57ccb2001-10-12 02:38:24 +00005030
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005031 basebase = base->tp_base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005032
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005033 COPYSLOT(tp_dealloc);
5034 if (type->tp_getattr == NULL && type->tp_getattro == NULL) {
5035 type->tp_getattr = base->tp_getattr;
5036 type->tp_getattro = base->tp_getattro;
5037 }
5038 if (type->tp_setattr == NULL && type->tp_setattro == NULL) {
5039 type->tp_setattr = base->tp_setattr;
5040 type->tp_setattro = base->tp_setattro;
5041 }
5042 /* tp_reserved is ignored */
5043 COPYSLOT(tp_repr);
5044 /* tp_hash see tp_richcompare */
5045 COPYSLOT(tp_call);
5046 COPYSLOT(tp_str);
5047 {
5048 /* Copy comparison-related slots only when
5049 not overriding them anywhere */
5050 if (type->tp_richcompare == NULL &&
5051 type->tp_hash == NULL &&
5052 !overrides_hash(type))
5053 {
5054 type->tp_richcompare = base->tp_richcompare;
5055 type->tp_hash = base->tp_hash;
5056 }
5057 }
5058 {
5059 COPYSLOT(tp_iter);
5060 COPYSLOT(tp_iternext);
5061 }
5062 {
5063 COPYSLOT(tp_descr_get);
5064 COPYSLOT(tp_descr_set);
5065 COPYSLOT(tp_dictoffset);
5066 COPYSLOT(tp_init);
5067 COPYSLOT(tp_alloc);
5068 COPYSLOT(tp_is_gc);
Antoine Pitrou796564c2013-07-30 19:59:21 +02005069 if ((type->tp_flags & Py_TPFLAGS_HAVE_FINALIZE) &&
5070 (base->tp_flags & Py_TPFLAGS_HAVE_FINALIZE)) {
5071 COPYSLOT(tp_finalize);
5072 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005073 if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) ==
5074 (base->tp_flags & Py_TPFLAGS_HAVE_GC)) {
5075 /* They agree about gc. */
5076 COPYSLOT(tp_free);
5077 }
5078 else if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
5079 type->tp_free == NULL &&
5080 base->tp_free == PyObject_Free) {
5081 /* A bit of magic to plug in the correct default
5082 * tp_free function when a derived class adds gc,
5083 * didn't define tp_free, and the base uses the
5084 * default non-gc tp_free.
5085 */
5086 type->tp_free = PyObject_GC_Del;
5087 }
5088 /* else they didn't agree about gc, and there isn't something
5089 * obvious to be done -- the type is on its own.
5090 */
5091 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00005092}
5093
Jeremy Hylton938ace62002-07-17 16:30:39 +00005094static int add_operators(PyTypeObject *);
Guido van Rossum13d52f02001-08-10 21:24:08 +00005095
Tim Peters6d6c1a32001-08-02 04:15:00 +00005096int
Guido van Rossum528b7eb2001-08-07 17:24:28 +00005097PyType_Ready(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005098{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005099 PyObject *dict, *bases;
5100 PyTypeObject *base;
5101 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005102
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005103 if (type->tp_flags & Py_TPFLAGS_READY) {
Victor Stinnerbda5a2b2017-01-25 23:33:27 +01005104 assert(_PyType_CheckConsistency(type));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005105 return 0;
5106 }
5107 assert((type->tp_flags & Py_TPFLAGS_READYING) == 0);
Guido van Rossumd614f972001-08-10 17:39:49 +00005108
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005109 type->tp_flags |= Py_TPFLAGS_READYING;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005110
Tim Peters36eb4df2003-03-23 03:33:13 +00005111#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005112 /* PyType_Ready is the closest thing we have to a choke point
5113 * for type objects, so is the best place I can think of to try
5114 * to get type objects into the doubly-linked list of all objects.
Leo Ariasc3d95082018-02-03 18:36:10 -06005115 * Still, not all type objects go through PyType_Ready.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005116 */
5117 _Py_AddToAllObjects((PyObject *)type, 0);
Tim Peters36eb4df2003-03-23 03:33:13 +00005118#endif
5119
Serhiy Storchakade0574b2016-10-07 23:24:35 +03005120 if (type->tp_name == NULL) {
5121 PyErr_Format(PyExc_SystemError,
5122 "Type does not define the tp_name field.");
5123 goto error;
5124 }
5125
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005126 /* Initialize tp_base (defaults to BaseObject unless that's us) */
5127 base = type->tp_base;
5128 if (base == NULL && type != &PyBaseObject_Type) {
5129 base = type->tp_base = &PyBaseObject_Type;
5130 Py_INCREF(base);
5131 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00005132
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005133 /* Now the only way base can still be NULL is if type is
5134 * &PyBaseObject_Type.
5135 */
Guido van Rossum692cdbc2006-03-10 02:04:28 +00005136
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005137 /* Initialize the base class */
5138 if (base != NULL && base->tp_dict == NULL) {
5139 if (PyType_Ready(base) < 0)
5140 goto error;
5141 }
Guido van Rossum323a9cf2002-08-14 17:26:30 +00005142
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005143 /* Initialize ob_type if NULL. This means extensions that want to be
5144 compilable separately on Windows can call PyType_Ready() instead of
5145 initializing the ob_type field of their type objects. */
5146 /* The test for base != NULL is really unnecessary, since base is only
5147 NULL when type is &PyBaseObject_Type, and we know its ob_type is
5148 not NULL (it's initialized to &PyType_Type). But coverity doesn't
5149 know that. */
5150 if (Py_TYPE(type) == NULL && base != NULL)
5151 Py_TYPE(type) = Py_TYPE(base);
Guido van Rossum0986d822002-04-08 01:38:42 +00005152
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005153 /* Initialize tp_bases */
5154 bases = type->tp_bases;
5155 if (bases == NULL) {
5156 if (base == NULL)
5157 bases = PyTuple_New(0);
5158 else
5159 bases = PyTuple_Pack(1, base);
5160 if (bases == NULL)
5161 goto error;
5162 type->tp_bases = bases;
5163 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00005164
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005165 /* Initialize tp_dict */
5166 dict = type->tp_dict;
5167 if (dict == NULL) {
5168 dict = PyDict_New();
5169 if (dict == NULL)
5170 goto error;
5171 type->tp_dict = dict;
5172 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00005173
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005174 /* Add type-specific descriptors to tp_dict */
5175 if (add_operators(type) < 0)
5176 goto error;
5177 if (type->tp_methods != NULL) {
5178 if (add_methods(type, type->tp_methods) < 0)
5179 goto error;
5180 }
5181 if (type->tp_members != NULL) {
5182 if (add_members(type, type->tp_members) < 0)
5183 goto error;
5184 }
5185 if (type->tp_getset != NULL) {
5186 if (add_getset(type, type->tp_getset) < 0)
5187 goto error;
5188 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00005189
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005190 /* Calculate method resolution order */
Benjamin Peterson104b9e02015-02-05 22:29:14 -05005191 if (mro_internal(type, NULL) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005192 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005193
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005194 /* Inherit special flags from dominant base */
5195 if (type->tp_base != NULL)
5196 inherit_special(type, type->tp_base);
Guido van Rossum13d52f02001-08-10 21:24:08 +00005197
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005198 /* Initialize tp_dict properly */
5199 bases = type->tp_mro;
5200 assert(bases != NULL);
5201 assert(PyTuple_Check(bases));
5202 n = PyTuple_GET_SIZE(bases);
5203 for (i = 1; i < n; i++) {
5204 PyObject *b = PyTuple_GET_ITEM(bases, i);
5205 if (PyType_Check(b))
5206 inherit_slots(type, (PyTypeObject *)b);
5207 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00005208
Serhiy Storchakae09bcc82015-01-28 11:03:33 +02005209 /* All bases of statically allocated type should be statically allocated */
5210 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE))
5211 for (i = 0; i < n; i++) {
5212 PyObject *b = PyTuple_GET_ITEM(bases, i);
5213 if (PyType_Check(b) &&
5214 (((PyTypeObject *)b)->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
5215 PyErr_Format(PyExc_TypeError,
5216 "type '%.100s' is not dynamically allocated but "
5217 "its base type '%.100s' is dynamically allocated",
5218 type->tp_name, ((PyTypeObject *)b)->tp_name);
5219 goto error;
5220 }
5221 }
5222
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005223 /* Sanity check for tp_free. */
5224 if (PyType_IS_GC(type) && (type->tp_flags & Py_TPFLAGS_BASETYPE) &&
5225 (type->tp_free == NULL || type->tp_free == PyObject_Del)) {
5226 /* This base class needs to call tp_free, but doesn't have
5227 * one, or its tp_free is for non-gc'ed objects.
5228 */
5229 PyErr_Format(PyExc_TypeError, "type '%.100s' participates in "
5230 "gc and is a base type but has inappropriate "
5231 "tp_free slot",
5232 type->tp_name);
5233 goto error;
5234 }
Tim Peters3cfe7542003-05-21 21:29:48 +00005235
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005236 /* if the type dictionary doesn't contain a __doc__, set it from
5237 the tp_doc slot.
5238 */
Victor Stinner3c1e4812012-03-26 22:10:51 +02005239 if (_PyDict_GetItemId(type->tp_dict, &PyId___doc__) == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005240 if (type->tp_doc != NULL) {
Larry Hastings2623c8c2014-02-08 22:15:29 -08005241 const char *old_doc = _PyType_DocWithoutSignature(type->tp_name,
5242 type->tp_doc);
Larry Hastings5c661892014-01-24 06:17:25 -08005243 PyObject *doc = PyUnicode_FromString(old_doc);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005244 if (doc == NULL)
5245 goto error;
Victor Stinner5967bf42013-07-17 22:01:37 +02005246 if (_PyDict_SetItemId(type->tp_dict, &PyId___doc__, doc) < 0) {
5247 Py_DECREF(doc);
5248 goto error;
5249 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005250 Py_DECREF(doc);
5251 } else {
Victor Stinner5967bf42013-07-17 22:01:37 +02005252 if (_PyDict_SetItemId(type->tp_dict,
5253 &PyId___doc__, Py_None) < 0)
5254 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005255 }
5256 }
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00005257
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005258 /* Hack for tp_hash and __hash__.
5259 If after all that, tp_hash is still NULL, and __hash__ is not in
5260 tp_dict, set tp_hash to PyObject_HashNotImplemented and
5261 tp_dict['__hash__'] equal to None.
5262 This signals that __hash__ is not inherited.
5263 */
5264 if (type->tp_hash == NULL) {
Victor Stinner3c1e4812012-03-26 22:10:51 +02005265 if (_PyDict_GetItemId(type->tp_dict, &PyId___hash__) == NULL) {
5266 if (_PyDict_SetItemId(type->tp_dict, &PyId___hash__, Py_None) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005267 goto error;
5268 type->tp_hash = PyObject_HashNotImplemented;
5269 }
5270 }
Guido van Rossum38938152006-08-21 23:36:26 +00005271
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005272 /* Some more special stuff */
5273 base = type->tp_base;
5274 if (base != NULL) {
Yury Selivanov75445082015-05-11 22:57:16 -04005275 if (type->tp_as_async == NULL)
5276 type->tp_as_async = base->tp_as_async;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005277 if (type->tp_as_number == NULL)
5278 type->tp_as_number = base->tp_as_number;
5279 if (type->tp_as_sequence == NULL)
5280 type->tp_as_sequence = base->tp_as_sequence;
5281 if (type->tp_as_mapping == NULL)
5282 type->tp_as_mapping = base->tp_as_mapping;
5283 if (type->tp_as_buffer == NULL)
5284 type->tp_as_buffer = base->tp_as_buffer;
5285 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00005286
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005287 /* Link into each base class's list of subclasses */
5288 bases = type->tp_bases;
5289 n = PyTuple_GET_SIZE(bases);
5290 for (i = 0; i < n; i++) {
5291 PyObject *b = PyTuple_GET_ITEM(bases, i);
5292 if (PyType_Check(b) &&
5293 add_subclass((PyTypeObject *)b, type) < 0)
5294 goto error;
5295 }
Guido van Rossum1c450732001-10-08 15:18:27 +00005296
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005297 /* All done -- set the ready flag */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005298 type->tp_flags =
5299 (type->tp_flags & ~Py_TPFLAGS_READYING) | Py_TPFLAGS_READY;
Victor Stinnerbda5a2b2017-01-25 23:33:27 +01005300 assert(_PyType_CheckConsistency(type));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005301 return 0;
Guido van Rossumd614f972001-08-10 17:39:49 +00005302
5303 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005304 type->tp_flags &= ~Py_TPFLAGS_READYING;
5305 return -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005306}
5307
Guido van Rossum1c450732001-10-08 15:18:27 +00005308static int
5309add_subclass(PyTypeObject *base, PyTypeObject *type)
5310{
Antoine Pitrou84745ab2013-10-29 21:31:25 +01005311 int result = -1;
5312 PyObject *dict, *key, *newobj;
Guido van Rossum1c450732001-10-08 15:18:27 +00005313
Antoine Pitrou84745ab2013-10-29 21:31:25 +01005314 dict = base->tp_subclasses;
5315 if (dict == NULL) {
5316 base->tp_subclasses = dict = PyDict_New();
5317 if (dict == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005318 return -1;
5319 }
Antoine Pitrou84745ab2013-10-29 21:31:25 +01005320 assert(PyDict_CheckExact(dict));
5321 key = PyLong_FromVoidPtr((void *) type);
5322 if (key == NULL)
Victor Stinner9812af82013-07-08 22:25:48 +02005323 return -1;
Antoine Pitrou84745ab2013-10-29 21:31:25 +01005324 newobj = PyWeakref_NewRef((PyObject *)type, NULL);
5325 if (newobj != NULL) {
5326 result = PyDict_SetItem(dict, key, newobj);
5327 Py_DECREF(newobj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005328 }
Antoine Pitrou84745ab2013-10-29 21:31:25 +01005329 Py_DECREF(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005330 return result;
Guido van Rossum1c450732001-10-08 15:18:27 +00005331}
5332
Benjamin Peterson104b9e02015-02-05 22:29:14 -05005333static int
5334add_all_subclasses(PyTypeObject *type, PyObject *bases)
5335{
5336 int res = 0;
5337
5338 if (bases) {
5339 Py_ssize_t i;
5340 for (i = 0; i < PyTuple_GET_SIZE(bases); i++) {
5341 PyObject *base = PyTuple_GET_ITEM(bases, i);
5342 if (PyType_Check(base) &&
5343 add_subclass((PyTypeObject*)base, type) < 0)
5344 res = -1;
5345 }
5346 }
5347
5348 return res;
5349}
5350
Michael W. Hudson98bbc492002-11-26 14:47:27 +00005351static void
5352remove_subclass(PyTypeObject *base, PyTypeObject *type)
5353{
Antoine Pitrou84745ab2013-10-29 21:31:25 +01005354 PyObject *dict, *key;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00005355
Antoine Pitrou84745ab2013-10-29 21:31:25 +01005356 dict = base->tp_subclasses;
5357 if (dict == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005358 return;
5359 }
Antoine Pitrou84745ab2013-10-29 21:31:25 +01005360 assert(PyDict_CheckExact(dict));
5361 key = PyLong_FromVoidPtr((void *) type);
5362 if (key == NULL || PyDict_DelItem(dict, key)) {
5363 /* This can happen if the type initialization errored out before
5364 the base subclasses were updated (e.g. a non-str __qualname__
5365 was passed in the type dict). */
5366 PyErr_Clear();
5367 }
5368 Py_XDECREF(key);
5369}
5370
5371static void
5372remove_all_subclasses(PyTypeObject *type, PyObject *bases)
5373{
5374 if (bases) {
5375 Py_ssize_t i;
5376 for (i = 0; i < PyTuple_GET_SIZE(bases); i++) {
5377 PyObject *base = PyTuple_GET_ITEM(bases, i);
5378 if (PyType_Check(base))
5379 remove_subclass((PyTypeObject*) base, type);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005380 }
5381 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +00005382}
Tim Peters6d6c1a32001-08-02 04:15:00 +00005383
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00005384static int
5385check_num_args(PyObject *ob, int n)
5386{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005387 if (!PyTuple_CheckExact(ob)) {
5388 PyErr_SetString(PyExc_SystemError,
5389 "PyArg_UnpackTuple() argument list is not a tuple");
5390 return 0;
5391 }
5392 if (n == PyTuple_GET_SIZE(ob))
5393 return 1;
5394 PyErr_Format(
5395 PyExc_TypeError,
5396 "expected %d arguments, got %zd", n, PyTuple_GET_SIZE(ob));
5397 return 0;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00005398}
5399
Tim Peters6d6c1a32001-08-02 04:15:00 +00005400/* Generic wrappers for overloadable 'operators' such as __getitem__ */
5401
5402/* There's a wrapper *function* for each distinct function typedef used
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005403 for type object slots (e.g. binaryfunc, ternaryfunc, etc.). There's a
Tim Peters6d6c1a32001-08-02 04:15:00 +00005404 wrapper *table* for each distinct operation (e.g. __len__, __add__).
5405 Most tables have only one entry; the tables for binary operators have two
5406 entries, one regular and one with reversed arguments. */
5407
5408static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00005409wrap_lenfunc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005410{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005411 lenfunc func = (lenfunc)wrapped;
5412 Py_ssize_t res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005413
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005414 if (!check_num_args(args, 0))
5415 return NULL;
5416 res = (*func)(self);
5417 if (res == -1 && PyErr_Occurred())
5418 return NULL;
5419 return PyLong_FromLong((long)res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005420}
5421
Tim Peters6d6c1a32001-08-02 04:15:00 +00005422static PyObject *
Raymond Hettingerf34f2642003-10-11 17:29:04 +00005423wrap_inquirypred(PyObject *self, PyObject *args, void *wrapped)
5424{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005425 inquiry func = (inquiry)wrapped;
5426 int res;
Raymond Hettingerf34f2642003-10-11 17:29:04 +00005427
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005428 if (!check_num_args(args, 0))
5429 return NULL;
5430 res = (*func)(self);
5431 if (res == -1 && PyErr_Occurred())
5432 return NULL;
5433 return PyBool_FromLong((long)res);
Raymond Hettingerf34f2642003-10-11 17:29:04 +00005434}
5435
5436static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00005437wrap_binaryfunc(PyObject *self, PyObject *args, void *wrapped)
5438{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005439 binaryfunc func = (binaryfunc)wrapped;
5440 PyObject *other;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005441
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005442 if (!check_num_args(args, 1))
5443 return NULL;
5444 other = PyTuple_GET_ITEM(args, 0);
5445 return (*func)(self, other);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005446}
5447
5448static PyObject *
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00005449wrap_binaryfunc_l(PyObject *self, PyObject *args, void *wrapped)
5450{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005451 binaryfunc func = (binaryfunc)wrapped;
5452 PyObject *other;
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00005453
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005454 if (!check_num_args(args, 1))
5455 return NULL;
5456 other = PyTuple_GET_ITEM(args, 0);
5457 return (*func)(self, other);
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00005458}
5459
5460static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00005461wrap_binaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
5462{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005463 binaryfunc func = (binaryfunc)wrapped;
5464 PyObject *other;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005465
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005466 if (!check_num_args(args, 1))
5467 return NULL;
5468 other = PyTuple_GET_ITEM(args, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005469 return (*func)(other, self);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005470}
5471
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00005472static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00005473wrap_ternaryfunc(PyObject *self, PyObject *args, void *wrapped)
5474{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005475 ternaryfunc func = (ternaryfunc)wrapped;
5476 PyObject *other;
5477 PyObject *third = Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005478
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005479 /* Note: This wrapper only works for __pow__() */
Tim Peters6d6c1a32001-08-02 04:15:00 +00005480
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005481 if (!PyArg_UnpackTuple(args, "", 1, 2, &other, &third))
5482 return NULL;
5483 return (*func)(self, other, third);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005484}
5485
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00005486static PyObject *
5487wrap_ternaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
5488{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005489 ternaryfunc func = (ternaryfunc)wrapped;
5490 PyObject *other;
5491 PyObject *third = Py_None;
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00005492
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005493 /* Note: This wrapper only works for __pow__() */
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00005494
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005495 if (!PyArg_UnpackTuple(args, "", 1, 2, &other, &third))
5496 return NULL;
5497 return (*func)(other, self, third);
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00005498}
5499
Tim Peters6d6c1a32001-08-02 04:15:00 +00005500static PyObject *
5501wrap_unaryfunc(PyObject *self, PyObject *args, void *wrapped)
5502{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005503 unaryfunc func = (unaryfunc)wrapped;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005504
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005505 if (!check_num_args(args, 0))
5506 return NULL;
5507 return (*func)(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005508}
5509
Tim Peters6d6c1a32001-08-02 04:15:00 +00005510static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00005511wrap_indexargfunc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005512{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005513 ssizeargfunc func = (ssizeargfunc)wrapped;
5514 PyObject* o;
5515 Py_ssize_t i;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005516
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005517 if (!PyArg_UnpackTuple(args, "", 1, 1, &o))
5518 return NULL;
5519 i = PyNumber_AsSsize_t(o, PyExc_OverflowError);
5520 if (i == -1 && PyErr_Occurred())
5521 return NULL;
5522 return (*func)(self, i);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005523}
5524
Martin v. Löwis18e16552006-02-15 17:27:45 +00005525static Py_ssize_t
Guido van Rossum5d815f32001-08-17 21:57:47 +00005526getindex(PyObject *self, PyObject *arg)
5527{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005528 Py_ssize_t i;
Guido van Rossum5d815f32001-08-17 21:57:47 +00005529
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005530 i = PyNumber_AsSsize_t(arg, PyExc_OverflowError);
5531 if (i == -1 && PyErr_Occurred())
5532 return -1;
5533 if (i < 0) {
5534 PySequenceMethods *sq = Py_TYPE(self)->tp_as_sequence;
5535 if (sq && sq->sq_length) {
5536 Py_ssize_t n = (*sq->sq_length)(self);
Serhiy Storchaka813f9432017-04-16 09:21:44 +03005537 if (n < 0) {
5538 assert(PyErr_Occurred());
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005539 return -1;
Serhiy Storchaka813f9432017-04-16 09:21:44 +03005540 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005541 i += n;
5542 }
5543 }
5544 return i;
Guido van Rossum5d815f32001-08-17 21:57:47 +00005545}
5546
5547static PyObject *
5548wrap_sq_item(PyObject *self, PyObject *args, void *wrapped)
5549{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005550 ssizeargfunc func = (ssizeargfunc)wrapped;
5551 PyObject *arg;
5552 Py_ssize_t i;
Guido van Rossum5d815f32001-08-17 21:57:47 +00005553
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005554 if (PyTuple_GET_SIZE(args) == 1) {
5555 arg = PyTuple_GET_ITEM(args, 0);
5556 i = getindex(self, arg);
5557 if (i == -1 && PyErr_Occurred())
5558 return NULL;
5559 return (*func)(self, i);
5560 }
5561 check_num_args(args, 1);
5562 assert(PyErr_Occurred());
5563 return NULL;
Guido van Rossum5d815f32001-08-17 21:57:47 +00005564}
5565
Tim Peters6d6c1a32001-08-02 04:15:00 +00005566static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00005567wrap_sq_setitem(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005568{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005569 ssizeobjargproc func = (ssizeobjargproc)wrapped;
5570 Py_ssize_t i;
5571 int res;
5572 PyObject *arg, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005573
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005574 if (!PyArg_UnpackTuple(args, "", 2, 2, &arg, &value))
5575 return NULL;
5576 i = getindex(self, arg);
5577 if (i == -1 && PyErr_Occurred())
5578 return NULL;
5579 res = (*func)(self, i, value);
5580 if (res == -1 && PyErr_Occurred())
5581 return NULL;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02005582 Py_RETURN_NONE;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005583}
5584
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00005585static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00005586wrap_sq_delitem(PyObject *self, PyObject *args, void *wrapped)
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00005587{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005588 ssizeobjargproc func = (ssizeobjargproc)wrapped;
5589 Py_ssize_t i;
5590 int res;
5591 PyObject *arg;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00005592
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005593 if (!check_num_args(args, 1))
5594 return NULL;
5595 arg = PyTuple_GET_ITEM(args, 0);
5596 i = getindex(self, arg);
5597 if (i == -1 && PyErr_Occurred())
5598 return NULL;
5599 res = (*func)(self, i, NULL);
5600 if (res == -1 && PyErr_Occurred())
5601 return NULL;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02005602 Py_RETURN_NONE;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00005603}
5604
Tim Peters6d6c1a32001-08-02 04:15:00 +00005605/* XXX objobjproc is a misnomer; should be objargpred */
5606static PyObject *
5607wrap_objobjproc(PyObject *self, PyObject *args, void *wrapped)
5608{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005609 objobjproc func = (objobjproc)wrapped;
5610 int res;
5611 PyObject *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005612
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005613 if (!check_num_args(args, 1))
5614 return NULL;
5615 value = PyTuple_GET_ITEM(args, 0);
5616 res = (*func)(self, value);
5617 if (res == -1 && PyErr_Occurred())
5618 return NULL;
5619 else
5620 return PyBool_FromLong(res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005621}
5622
Tim Peters6d6c1a32001-08-02 04:15:00 +00005623static PyObject *
5624wrap_objobjargproc(PyObject *self, PyObject *args, void *wrapped)
5625{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005626 objobjargproc func = (objobjargproc)wrapped;
5627 int res;
5628 PyObject *key, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005629
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005630 if (!PyArg_UnpackTuple(args, "", 2, 2, &key, &value))
5631 return NULL;
5632 res = (*func)(self, key, value);
5633 if (res == -1 && PyErr_Occurred())
5634 return NULL;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02005635 Py_RETURN_NONE;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005636}
5637
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00005638static PyObject *
5639wrap_delitem(PyObject *self, PyObject *args, void *wrapped)
5640{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005641 objobjargproc func = (objobjargproc)wrapped;
5642 int res;
5643 PyObject *key;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00005644
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005645 if (!check_num_args(args, 1))
5646 return NULL;
5647 key = PyTuple_GET_ITEM(args, 0);
5648 res = (*func)(self, key, NULL);
5649 if (res == -1 && PyErr_Occurred())
5650 return NULL;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02005651 Py_RETURN_NONE;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00005652}
5653
Guido van Rossum4dcdb782003-04-14 21:46:03 +00005654/* Helper to check for object.__setattr__ or __delattr__ applied to a type.
Guido van Rossum52b27052003-04-15 20:05:10 +00005655 This is called the Carlo Verre hack after its discoverer. */
Guido van Rossum4dcdb782003-04-14 21:46:03 +00005656static int
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02005657hackcheck(PyObject *self, setattrofunc func, const char *what)
Guido van Rossum4dcdb782003-04-14 21:46:03 +00005658{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005659 PyTypeObject *type = Py_TYPE(self);
5660 while (type && type->tp_flags & Py_TPFLAGS_HEAPTYPE)
5661 type = type->tp_base;
5662 /* If type is NULL now, this is a really weird type.
5663 In the spirit of backwards compatibility (?), just shut up. */
5664 if (type && type->tp_setattro != func) {
5665 PyErr_Format(PyExc_TypeError,
5666 "can't apply this %s to %s object",
5667 what,
5668 type->tp_name);
5669 return 0;
5670 }
5671 return 1;
Guido van Rossum4dcdb782003-04-14 21:46:03 +00005672}
5673
Tim Peters6d6c1a32001-08-02 04:15:00 +00005674static PyObject *
5675wrap_setattr(PyObject *self, PyObject *args, void *wrapped)
5676{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005677 setattrofunc func = (setattrofunc)wrapped;
5678 int res;
5679 PyObject *name, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005680
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005681 if (!PyArg_UnpackTuple(args, "", 2, 2, &name, &value))
5682 return NULL;
5683 if (!hackcheck(self, func, "__setattr__"))
5684 return NULL;
5685 res = (*func)(self, name, value);
5686 if (res < 0)
5687 return NULL;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02005688 Py_RETURN_NONE;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005689}
5690
5691static PyObject *
5692wrap_delattr(PyObject *self, PyObject *args, void *wrapped)
5693{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005694 setattrofunc func = (setattrofunc)wrapped;
5695 int res;
5696 PyObject *name;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005697
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005698 if (!check_num_args(args, 1))
5699 return NULL;
5700 name = PyTuple_GET_ITEM(args, 0);
5701 if (!hackcheck(self, func, "__delattr__"))
5702 return NULL;
5703 res = (*func)(self, name, NULL);
5704 if (res < 0)
5705 return NULL;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02005706 Py_RETURN_NONE;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005707}
5708
Tim Peters6d6c1a32001-08-02 04:15:00 +00005709static PyObject *
5710wrap_hashfunc(PyObject *self, PyObject *args, void *wrapped)
5711{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005712 hashfunc func = (hashfunc)wrapped;
Benjamin Peterson8035bc52010-10-23 16:20:50 +00005713 Py_hash_t res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005714
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005715 if (!check_num_args(args, 0))
5716 return NULL;
5717 res = (*func)(self);
5718 if (res == -1 && PyErr_Occurred())
5719 return NULL;
Benjamin Peterson8035bc52010-10-23 16:20:50 +00005720 return PyLong_FromSsize_t(res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005721}
5722
Tim Peters6d6c1a32001-08-02 04:15:00 +00005723static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00005724wrap_call(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005725{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005726 ternaryfunc func = (ternaryfunc)wrapped;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005727
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005728 return (*func)(self, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005729}
5730
Tim Peters6d6c1a32001-08-02 04:15:00 +00005731static PyObject *
Antoine Pitrou796564c2013-07-30 19:59:21 +02005732wrap_del(PyObject *self, PyObject *args, void *wrapped)
5733{
5734 destructor func = (destructor)wrapped;
5735
5736 if (!check_num_args(args, 0))
5737 return NULL;
5738
5739 (*func)(self);
5740 Py_RETURN_NONE;
5741}
5742
5743static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00005744wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op)
5745{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005746 richcmpfunc func = (richcmpfunc)wrapped;
5747 PyObject *other;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005748
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005749 if (!check_num_args(args, 1))
5750 return NULL;
5751 other = PyTuple_GET_ITEM(args, 0);
5752 return (*func)(self, other, op);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005753}
5754
5755#undef RICHCMP_WRAPPER
5756#define RICHCMP_WRAPPER(NAME, OP) \
5757static PyObject * \
5758richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \
5759{ \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005760 return wrap_richcmpfunc(self, args, wrapped, OP); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00005761}
5762
Jack Jansen8e938b42001-08-08 15:29:49 +00005763RICHCMP_WRAPPER(lt, Py_LT)
5764RICHCMP_WRAPPER(le, Py_LE)
5765RICHCMP_WRAPPER(eq, Py_EQ)
5766RICHCMP_WRAPPER(ne, Py_NE)
5767RICHCMP_WRAPPER(gt, Py_GT)
5768RICHCMP_WRAPPER(ge, Py_GE)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005769
Tim Peters6d6c1a32001-08-02 04:15:00 +00005770static PyObject *
5771wrap_next(PyObject *self, PyObject *args, void *wrapped)
5772{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005773 unaryfunc func = (unaryfunc)wrapped;
5774 PyObject *res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005775
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005776 if (!check_num_args(args, 0))
5777 return NULL;
5778 res = (*func)(self);
5779 if (res == NULL && !PyErr_Occurred())
5780 PyErr_SetNone(PyExc_StopIteration);
5781 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005782}
5783
Tim Peters6d6c1a32001-08-02 04:15:00 +00005784static PyObject *
5785wrap_descr_get(PyObject *self, PyObject *args, void *wrapped)
5786{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005787 descrgetfunc func = (descrgetfunc)wrapped;
5788 PyObject *obj;
5789 PyObject *type = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005790
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005791 if (!PyArg_UnpackTuple(args, "", 1, 2, &obj, &type))
5792 return NULL;
5793 if (obj == Py_None)
5794 obj = NULL;
5795 if (type == Py_None)
5796 type = NULL;
5797 if (type == NULL &&obj == NULL) {
5798 PyErr_SetString(PyExc_TypeError,
5799 "__get__(None, None) is invalid");
5800 return NULL;
5801 }
5802 return (*func)(self, obj, type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005803}
5804
Tim Peters6d6c1a32001-08-02 04:15:00 +00005805static PyObject *
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005806wrap_descr_set(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005807{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005808 descrsetfunc func = (descrsetfunc)wrapped;
5809 PyObject *obj, *value;
5810 int ret;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005811
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005812 if (!PyArg_UnpackTuple(args, "", 2, 2, &obj, &value))
5813 return NULL;
5814 ret = (*func)(self, obj, value);
5815 if (ret < 0)
5816 return NULL;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02005817 Py_RETURN_NONE;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005818}
Guido van Rossum22b13872002-08-06 21:41:44 +00005819
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00005820static PyObject *
5821wrap_descr_delete(PyObject *self, PyObject *args, void *wrapped)
5822{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005823 descrsetfunc func = (descrsetfunc)wrapped;
5824 PyObject *obj;
5825 int ret;
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00005826
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005827 if (!check_num_args(args, 1))
5828 return NULL;
5829 obj = PyTuple_GET_ITEM(args, 0);
5830 ret = (*func)(self, obj, NULL);
5831 if (ret < 0)
5832 return NULL;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02005833 Py_RETURN_NONE;
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00005834}
Tim Peters6d6c1a32001-08-02 04:15:00 +00005835
Tim Peters6d6c1a32001-08-02 04:15:00 +00005836static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00005837wrap_init(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005838{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005839 initproc func = (initproc)wrapped;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005840
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005841 if (func(self, args, kwds) < 0)
5842 return NULL;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02005843 Py_RETURN_NONE;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005844}
5845
Tim Peters6d6c1a32001-08-02 04:15:00 +00005846static PyObject *
Guido van Rossum0d231ed2001-08-06 16:50:37 +00005847tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005848{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005849 PyTypeObject *type, *subtype, *staticbase;
5850 PyObject *arg0, *res;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00005851
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005852 if (self == NULL || !PyType_Check(self))
5853 Py_FatalError("__new__() called with non-type 'self'");
5854 type = (PyTypeObject *)self;
5855 if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) {
5856 PyErr_Format(PyExc_TypeError,
5857 "%s.__new__(): not enough arguments",
5858 type->tp_name);
5859 return NULL;
5860 }
5861 arg0 = PyTuple_GET_ITEM(args, 0);
5862 if (!PyType_Check(arg0)) {
5863 PyErr_Format(PyExc_TypeError,
5864 "%s.__new__(X): X is not a type object (%s)",
5865 type->tp_name,
5866 Py_TYPE(arg0)->tp_name);
5867 return NULL;
5868 }
5869 subtype = (PyTypeObject *)arg0;
5870 if (!PyType_IsSubtype(subtype, type)) {
5871 PyErr_Format(PyExc_TypeError,
5872 "%s.__new__(%s): %s is not a subtype of %s",
5873 type->tp_name,
5874 subtype->tp_name,
5875 subtype->tp_name,
5876 type->tp_name);
5877 return NULL;
5878 }
Barry Warsaw60f01882001-08-22 19:24:42 +00005879
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005880 /* Check that the use doesn't do something silly and unsafe like
5881 object.__new__(dict). To do this, we check that the
5882 most derived base that's not a heap type is this type. */
5883 staticbase = subtype;
Martin v. Löwis9c564092012-06-23 23:20:45 +02005884 while (staticbase && (staticbase->tp_new == slot_tp_new))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005885 staticbase = staticbase->tp_base;
5886 /* If staticbase is NULL now, it is a really weird type.
5887 In the spirit of backwards compatibility (?), just shut up. */
5888 if (staticbase && staticbase->tp_new != type->tp_new) {
5889 PyErr_Format(PyExc_TypeError,
5890 "%s.__new__(%s) is not safe, use %s.__new__()",
5891 type->tp_name,
5892 subtype->tp_name,
Benjamin Petersone8239332014-11-26 23:03:11 -06005893 staticbase->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005894 return NULL;
5895 }
Barry Warsaw60f01882001-08-22 19:24:42 +00005896
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005897 args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
5898 if (args == NULL)
5899 return NULL;
5900 res = type->tp_new(subtype, args, kwds);
5901 Py_DECREF(args);
5902 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005903}
5904
Guido van Rossum0d231ed2001-08-06 16:50:37 +00005905static struct PyMethodDef tp_new_methoddef[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005906 {"__new__", (PyCFunction)tp_new_wrapper, METH_VARARGS|METH_KEYWORDS,
Larry Hastings2623c8c2014-02-08 22:15:29 -08005907 PyDoc_STR("__new__($type, *args, **kwargs)\n--\n\n"
Larry Hastings581ee362014-01-28 05:00:08 -08005908 "Create and return a new object. "
5909 "See help(type) for accurate signature.")},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005910 {0}
Tim Peters6d6c1a32001-08-02 04:15:00 +00005911};
5912
5913static int
Guido van Rossum0d231ed2001-08-06 16:50:37 +00005914add_tp_new_wrapper(PyTypeObject *type)
5915{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005916 PyObject *func;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00005917
Victor Stinner3c1e4812012-03-26 22:10:51 +02005918 if (_PyDict_GetItemId(type->tp_dict, &PyId___new__) != NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005919 return 0;
Andrew Svetlov3ba3a3e2012-12-25 13:32:35 +02005920 func = PyCFunction_NewEx(tp_new_methoddef, (PyObject *)type, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005921 if (func == NULL)
5922 return -1;
Victor Stinner3c1e4812012-03-26 22:10:51 +02005923 if (_PyDict_SetItemId(type->tp_dict, &PyId___new__, func)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005924 Py_DECREF(func);
5925 return -1;
5926 }
5927 Py_DECREF(func);
5928 return 0;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00005929}
5930
Guido van Rossumf040ede2001-08-07 16:40:56 +00005931/* Slot wrappers that call the corresponding __foo__ slot. See comments
5932 below at override_slots() for more explanation. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00005933
Guido van Rossumdc91b992001-08-08 22:26:22 +00005934#define SLOT0(FUNCNAME, OPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00005935static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00005936FUNCNAME(PyObject *self) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00005937{ \
Benjamin Petersonce798522012-01-22 11:24:29 -05005938 _Py_static_string(id, OPSTR); \
Victor Stinner434723f2017-01-11 00:07:40 +01005939 return call_method(self, &id, NULL, 0); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00005940}
5941
Victor Stinner887b4302016-12-09 00:41:46 +01005942#define SLOT1(FUNCNAME, OPSTR, ARG1TYPE) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00005943static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00005944FUNCNAME(PyObject *self, ARG1TYPE arg1) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00005945{ \
Victor Stinner434723f2017-01-11 00:07:40 +01005946 PyObject* stack[1] = {arg1}; \
Benjamin Petersonce798522012-01-22 11:24:29 -05005947 _Py_static_string(id, OPSTR); \
Victor Stinner434723f2017-01-11 00:07:40 +01005948 return call_method(self, &id, stack, 1); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00005949}
5950
Guido van Rossumcd118802003-01-06 22:57:47 +00005951/* Boolean helper for SLOT1BINFULL().
5952 right.__class__ is a nontrivial subclass of left.__class__. */
5953static int
Victor Stinner3c1e4812012-03-26 22:10:51 +02005954method_is_overloaded(PyObject *left, PyObject *right, struct _Py_Identifier *name)
Guido van Rossumcd118802003-01-06 22:57:47 +00005955{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005956 PyObject *a, *b;
5957 int ok;
Guido van Rossumcd118802003-01-06 22:57:47 +00005958
Victor Stinner3c1e4812012-03-26 22:10:51 +02005959 b = _PyObject_GetAttrId((PyObject *)(Py_TYPE(right)), name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005960 if (b == NULL) {
5961 PyErr_Clear();
5962 /* If right doesn't have it, it's not overloaded */
5963 return 0;
5964 }
Guido van Rossumcd118802003-01-06 22:57:47 +00005965
Victor Stinner3c1e4812012-03-26 22:10:51 +02005966 a = _PyObject_GetAttrId((PyObject *)(Py_TYPE(left)), name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005967 if (a == NULL) {
5968 PyErr_Clear();
5969 Py_DECREF(b);
5970 /* If right has it but left doesn't, it's overloaded */
5971 return 1;
5972 }
Guido van Rossumcd118802003-01-06 22:57:47 +00005973
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005974 ok = PyObject_RichCompareBool(a, b, Py_NE);
5975 Py_DECREF(a);
5976 Py_DECREF(b);
5977 if (ok < 0) {
5978 PyErr_Clear();
5979 return 0;
5980 }
Guido van Rossumcd118802003-01-06 22:57:47 +00005981
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005982 return ok;
Guido van Rossumcd118802003-01-06 22:57:47 +00005983}
5984
Guido van Rossumdc91b992001-08-08 22:26:22 +00005985
5986#define SLOT1BINFULL(FUNCNAME, TESTFUNC, SLOTNAME, OPSTR, ROPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00005987static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00005988FUNCNAME(PyObject *self, PyObject *other) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00005989{ \
Victor Stinner434723f2017-01-11 00:07:40 +01005990 PyObject* stack[1]; \
Benjamin Petersonce798522012-01-22 11:24:29 -05005991 _Py_static_string(op_id, OPSTR); \
5992 _Py_static_string(rop_id, ROPSTR); \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005993 int do_other = Py_TYPE(self) != Py_TYPE(other) && \
5994 Py_TYPE(other)->tp_as_number != NULL && \
5995 Py_TYPE(other)->tp_as_number->SLOTNAME == TESTFUNC; \
5996 if (Py_TYPE(self)->tp_as_number != NULL && \
5997 Py_TYPE(self)->tp_as_number->SLOTNAME == TESTFUNC) { \
5998 PyObject *r; \
5999 if (do_other && \
6000 PyType_IsSubtype(Py_TYPE(other), Py_TYPE(self)) && \
Victor Stinner3c1e4812012-03-26 22:10:51 +02006001 method_is_overloaded(self, other, &rop_id)) { \
Victor Stinner434723f2017-01-11 00:07:40 +01006002 stack[0] = self; \
6003 r = call_maybe(other, &rop_id, stack, 1); \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006004 if (r != Py_NotImplemented) \
6005 return r; \
6006 Py_DECREF(r); \
6007 do_other = 0; \
6008 } \
Victor Stinner434723f2017-01-11 00:07:40 +01006009 stack[0] = other; \
6010 r = call_maybe(self, &op_id, stack, 1); \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006011 if (r != Py_NotImplemented || \
6012 Py_TYPE(other) == Py_TYPE(self)) \
6013 return r; \
6014 Py_DECREF(r); \
6015 } \
6016 if (do_other) { \
Victor Stinner434723f2017-01-11 00:07:40 +01006017 stack[0] = self; \
6018 return call_maybe(other, &rop_id, stack, 1); \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006019 } \
Brian Curtindfc80e32011-08-10 20:28:54 -05006020 Py_RETURN_NOTIMPLEMENTED; \
Guido van Rossumdc91b992001-08-08 22:26:22 +00006021}
6022
6023#define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006024 SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR)
Guido van Rossumdc91b992001-08-08 22:26:22 +00006025
Martin v. Löwis18e16552006-02-15 17:27:45 +00006026static Py_ssize_t
Tim Peters6d6c1a32001-08-02 04:15:00 +00006027slot_sq_length(PyObject *self)
6028{
Victor Stinner434723f2017-01-11 00:07:40 +01006029 PyObject *res = call_method(self, &PyId___len__, NULL, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006030 Py_ssize_t len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00006031
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006032 if (res == NULL)
6033 return -1;
Serhiy Storchakabaf9f292017-04-16 09:37:18 +03006034
6035 Py_SETREF(res, PyNumber_Index(res));
6036 if (res == NULL)
6037 return -1;
6038
6039 assert(PyLong_Check(res));
6040 if (Py_SIZE(res) < 0) {
Xiang Zhang8e1ddbd2017-04-17 00:54:21 +08006041 Py_DECREF(res);
Serhiy Storchakabaf9f292017-04-16 09:37:18 +03006042 PyErr_SetString(PyExc_ValueError,
6043 "__len__() should return >= 0");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006044 return -1;
6045 }
Serhiy Storchakabaf9f292017-04-16 09:37:18 +03006046
6047 len = PyNumber_AsSsize_t(res, PyExc_OverflowError);
6048 assert(len >= 0 || PyErr_ExceptionMatches(PyExc_OverflowError));
6049 Py_DECREF(res);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006050 return len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00006051}
6052
Guido van Rossumf4593e02001-10-03 12:09:30 +00006053static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00006054slot_sq_item(PyObject *self, Py_ssize_t i)
Guido van Rossumf4593e02001-10-03 12:09:30 +00006055{
Serhiy Storchaka4e624ca2017-06-01 08:18:25 +03006056 PyObject *retval;
6057 PyObject *args[1];
6058 PyObject *ival = PyLong_FromSsize_t(i);
6059 if (ival == NULL) {
Victor Stinner018016d2016-08-19 18:17:37 +02006060 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006061 }
Serhiy Storchaka4e624ca2017-06-01 08:18:25 +03006062 args[0] = ival;
6063 retval = call_method(self, &PyId___getitem__, args, 1);
Victor Stinner5e877492016-08-19 18:19:42 +02006064 Py_DECREF(ival);
Victor Stinner018016d2016-08-19 18:17:37 +02006065 return retval;
Guido van Rossumf4593e02001-10-03 12:09:30 +00006066}
6067
Tim Peters6d6c1a32001-08-02 04:15:00 +00006068static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00006069slot_sq_ass_item(PyObject *self, Py_ssize_t index, PyObject *value)
Tim Peters6d6c1a32001-08-02 04:15:00 +00006070{
Victor Stinner434723f2017-01-11 00:07:40 +01006071 PyObject *stack[2];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006072 PyObject *res;
Victor Stinner887b4302016-12-09 00:41:46 +01006073 PyObject *index_obj;
6074
6075 index_obj = PyLong_FromSsize_t(index);
6076 if (index_obj == NULL) {
6077 return -1;
6078 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00006079
Victor Stinner434723f2017-01-11 00:07:40 +01006080 stack[0] = index_obj;
6081 if (value == NULL) {
6082 res = call_method(self, &PyId___delitem__, stack, 1);
6083 }
6084 else {
6085 stack[1] = value;
6086 res = call_method(self, &PyId___setitem__, stack, 2);
6087 }
Victor Stinner887b4302016-12-09 00:41:46 +01006088 Py_DECREF(index_obj);
6089
6090 if (res == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006091 return -1;
Victor Stinner887b4302016-12-09 00:41:46 +01006092 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006093 Py_DECREF(res);
6094 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00006095}
6096
6097static int
Tim Peters6d6c1a32001-08-02 04:15:00 +00006098slot_sq_contains(PyObject *self, PyObject *value)
6099{
Victor Stinnera7720f62016-08-19 17:48:51 +02006100 PyObject *func, *res;
Victor Stinner516b9812017-02-09 22:53:47 +01006101 int result = -1, unbound;
Benjamin Petersonce798522012-01-22 11:24:29 -05006102 _Py_IDENTIFIER(__contains__);
Tim Petersbf9b2442003-03-23 05:35:36 +00006103
Victor Stinner516b9812017-02-09 22:53:47 +01006104 func = lookup_maybe_method(self, &PyId___contains__, &unbound);
Guido van Rossum97c1adf2016-08-18 09:22:23 -07006105 if (func == Py_None) {
6106 Py_DECREF(func);
6107 PyErr_Format(PyExc_TypeError,
6108 "'%.200s' object is not a container",
6109 Py_TYPE(self)->tp_name);
6110 return -1;
6111 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006112 if (func != NULL) {
Victor Stinner516b9812017-02-09 22:53:47 +01006113 PyObject *args[1] = {value};
6114 res = call_unbound(unbound, func, self, args, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006115 Py_DECREF(func);
6116 if (res != NULL) {
6117 result = PyObject_IsTrue(res);
6118 Py_DECREF(res);
6119 }
6120 }
6121 else if (! PyErr_Occurred()) {
6122 /* Possible results: -1 and 1 */
6123 result = (int)_PySequence_IterSearch(self, value,
6124 PY_ITERSEARCH_CONTAINS);
6125 }
6126 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00006127}
6128
Tim Peters6d6c1a32001-08-02 04:15:00 +00006129#define slot_mp_length slot_sq_length
6130
Victor Stinner887b4302016-12-09 00:41:46 +01006131SLOT1(slot_mp_subscript, "__getitem__", PyObject *)
Tim Peters6d6c1a32001-08-02 04:15:00 +00006132
6133static int
6134slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value)
6135{
Victor Stinner434723f2017-01-11 00:07:40 +01006136 PyObject *stack[2];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006137 PyObject *res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00006138
Victor Stinner434723f2017-01-11 00:07:40 +01006139 stack[0] = key;
6140 if (value == NULL) {
6141 res = call_method(self, &PyId___delitem__, stack, 1);
6142 }
6143 else {
6144 stack[1] = value;
6145 res = call_method(self, &PyId___setitem__, stack, 2);
6146 }
Benjamin Petersonce798522012-01-22 11:24:29 -05006147
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006148 if (res == NULL)
6149 return -1;
6150 Py_DECREF(res);
6151 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00006152}
6153
Guido van Rossumdc91b992001-08-08 22:26:22 +00006154SLOT1BIN(slot_nb_add, nb_add, "__add__", "__radd__")
6155SLOT1BIN(slot_nb_subtract, nb_subtract, "__sub__", "__rsub__")
6156SLOT1BIN(slot_nb_multiply, nb_multiply, "__mul__", "__rmul__")
Benjamin Petersond51374e2014-04-09 23:55:56 -04006157SLOT1BIN(slot_nb_matrix_multiply, nb_matrix_multiply, "__matmul__", "__rmatmul__")
Guido van Rossumdc91b992001-08-08 22:26:22 +00006158SLOT1BIN(slot_nb_remainder, nb_remainder, "__mod__", "__rmod__")
6159SLOT1BIN(slot_nb_divmod, nb_divmod, "__divmod__", "__rdivmod__")
6160
Jeremy Hylton938ace62002-07-17 16:30:39 +00006161static PyObject *slot_nb_power(PyObject *, PyObject *, PyObject *);
Guido van Rossumdc91b992001-08-08 22:26:22 +00006162
6163SLOT1BINFULL(slot_nb_power_binary, slot_nb_power,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006164 nb_power, "__pow__", "__rpow__")
Guido van Rossumdc91b992001-08-08 22:26:22 +00006165
6166static PyObject *
6167slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus)
6168{
Benjamin Petersonce798522012-01-22 11:24:29 -05006169 _Py_IDENTIFIER(__pow__);
Guido van Rossum2730b132001-08-28 18:22:14 +00006170
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006171 if (modulus == Py_None)
6172 return slot_nb_power_binary(self, other);
6173 /* Three-arg power doesn't use __rpow__. But ternary_op
6174 can call this when the second argument's type uses
6175 slot_nb_power, so check before calling self.__pow__. */
6176 if (Py_TYPE(self)->tp_as_number != NULL &&
6177 Py_TYPE(self)->tp_as_number->nb_power == slot_nb_power) {
Victor Stinner434723f2017-01-11 00:07:40 +01006178 PyObject* stack[2] = {other, modulus};
6179 return call_method(self, &PyId___pow__, stack, 2);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006180 }
Brian Curtindfc80e32011-08-10 20:28:54 -05006181 Py_RETURN_NOTIMPLEMENTED;
Guido van Rossumdc91b992001-08-08 22:26:22 +00006182}
6183
6184SLOT0(slot_nb_negative, "__neg__")
6185SLOT0(slot_nb_positive, "__pos__")
6186SLOT0(slot_nb_absolute, "__abs__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00006187
6188static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00006189slot_nb_bool(PyObject *self)
Tim Peters6d6c1a32001-08-02 04:15:00 +00006190{
Victor Stinner20a30072016-08-19 18:28:25 +02006191 PyObject *func, *value;
Victor Stinner516b9812017-02-09 22:53:47 +01006192 int result, unbound;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006193 int using_len = 0;
Benjamin Petersonce798522012-01-22 11:24:29 -05006194 _Py_IDENTIFIER(__bool__);
Tim Peters6d6c1a32001-08-02 04:15:00 +00006195
Victor Stinner516b9812017-02-09 22:53:47 +01006196 func = lookup_maybe_method(self, &PyId___bool__, &unbound);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006197 if (func == NULL) {
Victor Stinnera12eec42016-08-19 18:26:05 +02006198 if (PyErr_Occurred()) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006199 return -1;
Victor Stinnera12eec42016-08-19 18:26:05 +02006200 }
6201
Victor Stinner516b9812017-02-09 22:53:47 +01006202 func = lookup_maybe_method(self, &PyId___len__, &unbound);
Victor Stinnera12eec42016-08-19 18:26:05 +02006203 if (func == NULL) {
6204 if (PyErr_Occurred()) {
6205 return -1;
6206 }
6207 return 1;
6208 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006209 using_len = 1;
6210 }
Victor Stinnera12eec42016-08-19 18:26:05 +02006211
Victor Stinner516b9812017-02-09 22:53:47 +01006212 value = call_unbound_noarg(unbound, func, self);
Victor Stinnera12eec42016-08-19 18:26:05 +02006213 if (value == NULL) {
6214 goto error;
6215 }
6216
6217 if (using_len) {
6218 /* bool type enforced by slot_nb_len */
6219 result = PyObject_IsTrue(value);
6220 }
6221 else if (PyBool_Check(value)) {
6222 result = PyObject_IsTrue(value);
6223 }
6224 else {
6225 PyErr_Format(PyExc_TypeError,
6226 "__bool__ should return "
6227 "bool, returned %s",
6228 Py_TYPE(value)->tp_name);
6229 result = -1;
6230 }
6231
6232 Py_DECREF(value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006233 Py_DECREF(func);
6234 return result;
Victor Stinnera12eec42016-08-19 18:26:05 +02006235
6236error:
6237 Py_DECREF(func);
6238 return -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00006239}
6240
Guido van Rossum38fff8c2006-03-07 18:50:55 +00006241
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00006242static PyObject *
Guido van Rossum38fff8c2006-03-07 18:50:55 +00006243slot_nb_index(PyObject *self)
6244{
Benjamin Petersonce798522012-01-22 11:24:29 -05006245 _Py_IDENTIFIER(__index__);
Victor Stinner434723f2017-01-11 00:07:40 +01006246 return call_method(self, &PyId___index__, NULL, 0);
Guido van Rossum38fff8c2006-03-07 18:50:55 +00006247}
6248
6249
Guido van Rossumdc91b992001-08-08 22:26:22 +00006250SLOT0(slot_nb_invert, "__invert__")
6251SLOT1BIN(slot_nb_lshift, nb_lshift, "__lshift__", "__rlshift__")
6252SLOT1BIN(slot_nb_rshift, nb_rshift, "__rshift__", "__rrshift__")
6253SLOT1BIN(slot_nb_and, nb_and, "__and__", "__rand__")
6254SLOT1BIN(slot_nb_xor, nb_xor, "__xor__", "__rxor__")
6255SLOT1BIN(slot_nb_or, nb_or, "__or__", "__ror__")
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00006256
Guido van Rossumdc91b992001-08-08 22:26:22 +00006257SLOT0(slot_nb_int, "__int__")
Guido van Rossumdc91b992001-08-08 22:26:22 +00006258SLOT0(slot_nb_float, "__float__")
Victor Stinner887b4302016-12-09 00:41:46 +01006259SLOT1(slot_nb_inplace_add, "__iadd__", PyObject *)
6260SLOT1(slot_nb_inplace_subtract, "__isub__", PyObject *)
6261SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *)
6262SLOT1(slot_nb_inplace_matrix_multiply, "__imatmul__", PyObject *)
6263SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *)
Thomas Wouterscf297e42007-02-23 15:07:44 +00006264/* Can't use SLOT1 here, because nb_inplace_power is ternary */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006265static PyObject *
6266slot_nb_inplace_power(PyObject *self, PyObject * arg1, PyObject *arg2)
6267{
Victor Stinner434723f2017-01-11 00:07:40 +01006268 PyObject *stack[1] = {arg1};
Benjamin Petersonce798522012-01-22 11:24:29 -05006269 _Py_IDENTIFIER(__ipow__);
Victor Stinner434723f2017-01-11 00:07:40 +01006270 return call_method(self, &PyId___ipow__, stack, 1);
Thomas Wouterscf297e42007-02-23 15:07:44 +00006271}
Victor Stinner887b4302016-12-09 00:41:46 +01006272SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *)
6273SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *)
6274SLOT1(slot_nb_inplace_and, "__iand__", PyObject *)
6275SLOT1(slot_nb_inplace_xor, "__ixor__", PyObject *)
6276SLOT1(slot_nb_inplace_or, "__ior__", PyObject *)
Guido van Rossumdc91b992001-08-08 22:26:22 +00006277SLOT1BIN(slot_nb_floor_divide, nb_floor_divide,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006278 "__floordiv__", "__rfloordiv__")
Guido van Rossumdc91b992001-08-08 22:26:22 +00006279SLOT1BIN(slot_nb_true_divide, nb_true_divide, "__truediv__", "__rtruediv__")
Victor Stinner887b4302016-12-09 00:41:46 +01006280SLOT1(slot_nb_inplace_floor_divide, "__ifloordiv__", PyObject *)
6281SLOT1(slot_nb_inplace_true_divide, "__itruediv__", PyObject *)
Tim Peters6d6c1a32001-08-02 04:15:00 +00006282
Guido van Rossumb8f63662001-08-15 23:57:02 +00006283static PyObject *
6284slot_tp_repr(PyObject *self)
6285{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006286 PyObject *func, *res;
Benjamin Petersonce798522012-01-22 11:24:29 -05006287 _Py_IDENTIFIER(__repr__);
Victor Stinner516b9812017-02-09 22:53:47 +01006288 int unbound;
Guido van Rossumb8f63662001-08-15 23:57:02 +00006289
Serhiy Storchaka4e624ca2017-06-01 08:18:25 +03006290 func = lookup_maybe_method(self, &PyId___repr__, &unbound);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006291 if (func != NULL) {
Victor Stinner516b9812017-02-09 22:53:47 +01006292 res = call_unbound_noarg(unbound, func, self);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006293 Py_DECREF(func);
6294 return res;
6295 }
6296 PyErr_Clear();
6297 return PyUnicode_FromFormat("<%s object at %p>",
6298 Py_TYPE(self)->tp_name, self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00006299}
6300
Victor Stinner516b9812017-02-09 22:53:47 +01006301SLOT0(slot_tp_str, "__str__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00006302
Benjamin Peterson8f67d082010-10-17 20:54:53 +00006303static Py_hash_t
Tim Peters6d6c1a32001-08-02 04:15:00 +00006304slot_tp_hash(PyObject *self)
6305{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006306 PyObject *func, *res;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00006307 Py_ssize_t h;
Victor Stinner516b9812017-02-09 22:53:47 +01006308 int unbound;
Tim Peters6d6c1a32001-08-02 04:15:00 +00006309
Serhiy Storchaka4e624ca2017-06-01 08:18:25 +03006310 func = lookup_maybe_method(self, &PyId___hash__, &unbound);
Guido van Rossumb8f63662001-08-15 23:57:02 +00006311
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006312 if (func == Py_None) {
6313 Py_DECREF(func);
6314 func = NULL;
6315 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +00006316
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006317 if (func == NULL) {
6318 return PyObject_HashNotImplemented(self);
6319 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +00006320
Victor Stinner516b9812017-02-09 22:53:47 +01006321 res = call_unbound_noarg(unbound, func, self);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006322 Py_DECREF(func);
6323 if (res == NULL)
6324 return -1;
Mark Dickinsondc787d22010-05-23 13:33:13 +00006325
6326 if (!PyLong_Check(res)) {
6327 PyErr_SetString(PyExc_TypeError,
6328 "__hash__ method should return an integer");
6329 return -1;
6330 }
Benjamin Peterson8f67d082010-10-17 20:54:53 +00006331 /* Transform the PyLong `res` to a Py_hash_t `h`. For an existing
6332 hashable Python object x, hash(x) will always lie within the range of
6333 Py_hash_t. Therefore our transformation must preserve values that
6334 already lie within this range, to ensure that if x.__hash__() returns
6335 hash(y) then hash(x) == hash(y). */
6336 h = PyLong_AsSsize_t(res);
6337 if (h == -1 && PyErr_Occurred()) {
6338 /* res was not within the range of a Py_hash_t, so we're free to
Mark Dickinsondc787d22010-05-23 13:33:13 +00006339 use any sufficiently bit-mixing transformation;
6340 long.__hash__ will do nicely. */
Benjamin Peterson8f67d082010-10-17 20:54:53 +00006341 PyErr_Clear();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006342 h = PyLong_Type.tp_hash(res);
Benjamin Peterson8f67d082010-10-17 20:54:53 +00006343 }
Benjamin Petersone7dfeeb2010-10-17 21:27:01 +00006344 /* -1 is reserved for errors. */
6345 if (h == -1)
6346 h = -2;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006347 Py_DECREF(res);
Mark Dickinsondc787d22010-05-23 13:33:13 +00006348 return h;
Tim Peters6d6c1a32001-08-02 04:15:00 +00006349}
6350
6351static PyObject *
6352slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds)
6353{
Benjamin Petersonce798522012-01-22 11:24:29 -05006354 _Py_IDENTIFIER(__call__);
Victor Stinner516b9812017-02-09 22:53:47 +01006355 int unbound;
6356 PyObject *meth = lookup_method(self, &PyId___call__, &unbound);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006357 PyObject *res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00006358
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006359 if (meth == NULL)
6360 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006361
Victor Stinner516b9812017-02-09 22:53:47 +01006362 if (unbound) {
6363 res = _PyObject_Call_Prepend(meth, self, args, kwds);
6364 }
6365 else {
6366 res = PyObject_Call(meth, args, kwds);
6367 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006368
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006369 Py_DECREF(meth);
6370 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00006371}
6372
Guido van Rossum14a6f832001-10-17 13:59:09 +00006373/* There are two slot dispatch functions for tp_getattro.
6374
6375 - slot_tp_getattro() is used when __getattribute__ is overridden
6376 but no __getattr__ hook is present;
6377
6378 - slot_tp_getattr_hook() is used when a __getattr__ hook is present.
6379
Guido van Rossumc334df52002-04-04 23:44:47 +00006380 The code in update_one_slot() always installs slot_tp_getattr_hook(); this
6381 detects the absence of __getattr__ and then installs the simpler slot if
6382 necessary. */
Guido van Rossum14a6f832001-10-17 13:59:09 +00006383
Tim Peters6d6c1a32001-08-02 04:15:00 +00006384static PyObject *
6385slot_tp_getattro(PyObject *self, PyObject *name)
6386{
Victor Stinner434723f2017-01-11 00:07:40 +01006387 PyObject *stack[1] = {name};
6388 return call_method(self, &PyId___getattribute__, stack, 1);
Tim Peters6d6c1a32001-08-02 04:15:00 +00006389}
6390
Guido van Rossum19c1cd52001-09-21 21:24:49 +00006391static PyObject *
Benjamin Peterson9262b842008-11-17 22:45:50 +00006392call_attribute(PyObject *self, PyObject *attr, PyObject *name)
6393{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006394 PyObject *res, *descr = NULL;
6395 descrgetfunc f = Py_TYPE(attr)->tp_descr_get;
Benjamin Peterson9262b842008-11-17 22:45:50 +00006396
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006397 if (f != NULL) {
6398 descr = f(attr, self, (PyObject *)(Py_TYPE(self)));
6399 if (descr == NULL)
6400 return NULL;
6401 else
6402 attr = descr;
6403 }
Victor Stinnerde4ae3d2016-12-04 22:59:09 +01006404 res = PyObject_CallFunctionObjArgs(attr, name, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006405 Py_XDECREF(descr);
6406 return res;
Benjamin Peterson9262b842008-11-17 22:45:50 +00006407}
6408
6409static PyObject *
Guido van Rossum19c1cd52001-09-21 21:24:49 +00006410slot_tp_getattr_hook(PyObject *self, PyObject *name)
6411{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006412 PyTypeObject *tp = Py_TYPE(self);
6413 PyObject *getattr, *getattribute, *res;
Victor Stinner3c1e4812012-03-26 22:10:51 +02006414 _Py_IDENTIFIER(__getattr__);
Guido van Rossum19c1cd52001-09-21 21:24:49 +00006415
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006416 /* speed hack: we could use lookup_maybe, but that would resolve the
6417 method fully for each attribute lookup for classes with
6418 __getattr__, even when the attribute is present. So we use
6419 _PyType_Lookup and create the method only when needed, with
6420 call_attribute. */
Victor Stinner3c1e4812012-03-26 22:10:51 +02006421 getattr = _PyType_LookupId(tp, &PyId___getattr__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006422 if (getattr == NULL) {
6423 /* No __getattr__ hook: use a simpler dispatcher */
6424 tp->tp_getattro = slot_tp_getattro;
6425 return slot_tp_getattro(self, name);
6426 }
6427 Py_INCREF(getattr);
6428 /* speed hack: we could use lookup_maybe, but that would resolve the
6429 method fully for each attribute lookup for classes with
6430 __getattr__, even when self has the default __getattribute__
6431 method. So we use _PyType_Lookup and create the method only when
6432 needed, with call_attribute. */
Victor Stinner3c1e4812012-03-26 22:10:51 +02006433 getattribute = _PyType_LookupId(tp, &PyId___getattribute__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006434 if (getattribute == NULL ||
6435 (Py_TYPE(getattribute) == &PyWrapperDescr_Type &&
6436 ((PyWrapperDescrObject *)getattribute)->d_wrapped ==
6437 (void *)PyObject_GenericGetAttr))
6438 res = PyObject_GenericGetAttr(self, name);
6439 else {
6440 Py_INCREF(getattribute);
6441 res = call_attribute(self, getattribute, name);
6442 Py_DECREF(getattribute);
6443 }
6444 if (res == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) {
6445 PyErr_Clear();
6446 res = call_attribute(self, getattr, name);
6447 }
6448 Py_DECREF(getattr);
6449 return res;
Guido van Rossum19c1cd52001-09-21 21:24:49 +00006450}
6451
Tim Peters6d6c1a32001-08-02 04:15:00 +00006452static int
6453slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value)
6454{
Victor Stinner434723f2017-01-11 00:07:40 +01006455 PyObject *stack[2];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006456 PyObject *res;
Benjamin Petersonce798522012-01-22 11:24:29 -05006457 _Py_IDENTIFIER(__delattr__);
6458 _Py_IDENTIFIER(__setattr__);
Tim Peters6d6c1a32001-08-02 04:15:00 +00006459
Victor Stinner434723f2017-01-11 00:07:40 +01006460 stack[0] = name;
6461 if (value == NULL) {
6462 res = call_method(self, &PyId___delattr__, stack, 1);
6463 }
6464 else {
6465 stack[1] = value;
6466 res = call_method(self, &PyId___setattr__, stack, 2);
6467 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006468 if (res == NULL)
6469 return -1;
6470 Py_DECREF(res);
6471 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00006472}
6473
Benjamin Petersonce798522012-01-22 11:24:29 -05006474static _Py_Identifier name_op[] = {
6475 {0, "__lt__", 0},
6476 {0, "__le__", 0},
6477 {0, "__eq__", 0},
6478 {0, "__ne__", 0},
6479 {0, "__gt__", 0},
6480 {0, "__ge__", 0}
Guido van Rossumf5243f02008-01-01 04:06:48 +00006481};
6482
Tim Peters6d6c1a32001-08-02 04:15:00 +00006483static PyObject *
Mark Dickinson6f1d0492009-11-15 13:58:49 +00006484slot_tp_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters6d6c1a32001-08-02 04:15:00 +00006485{
Victor Stinner516b9812017-02-09 22:53:47 +01006486 int unbound;
Victor Stinnera7720f62016-08-19 17:48:51 +02006487 PyObject *func, *res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00006488
Serhiy Storchaka4e624ca2017-06-01 08:18:25 +03006489 func = lookup_maybe_method(self, &name_op[op], &unbound);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006490 if (func == NULL) {
6491 PyErr_Clear();
Brian Curtindfc80e32011-08-10 20:28:54 -05006492 Py_RETURN_NOTIMPLEMENTED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006493 }
Victor Stinner516b9812017-02-09 22:53:47 +01006494
6495 PyObject *args[1] = {other};
6496 res = call_unbound(unbound, func, self, args, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006497 Py_DECREF(func);
6498 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00006499}
6500
Guido van Rossumb8f63662001-08-15 23:57:02 +00006501static PyObject *
Guido van Rossumb8f63662001-08-15 23:57:02 +00006502slot_tp_iter(PyObject *self)
6503{
Victor Stinner516b9812017-02-09 22:53:47 +01006504 int unbound;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006505 PyObject *func, *res;
Benjamin Petersonce798522012-01-22 11:24:29 -05006506 _Py_IDENTIFIER(__iter__);
Guido van Rossumb8f63662001-08-15 23:57:02 +00006507
Serhiy Storchaka4e624ca2017-06-01 08:18:25 +03006508 func = lookup_maybe_method(self, &PyId___iter__, &unbound);
Guido van Rossum97c1adf2016-08-18 09:22:23 -07006509 if (func == Py_None) {
6510 Py_DECREF(func);
6511 PyErr_Format(PyExc_TypeError,
6512 "'%.200s' object is not iterable",
6513 Py_TYPE(self)->tp_name);
6514 return NULL;
6515 }
Victor Stinner69112672016-08-19 18:41:02 +02006516
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006517 if (func != NULL) {
Victor Stinner516b9812017-02-09 22:53:47 +01006518 res = call_unbound_noarg(unbound, func, self);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006519 Py_DECREF(func);
6520 return res;
6521 }
Victor Stinner69112672016-08-19 18:41:02 +02006522
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006523 PyErr_Clear();
Serhiy Storchaka4e624ca2017-06-01 08:18:25 +03006524 func = lookup_maybe_method(self, &PyId___getitem__, &unbound);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006525 if (func == NULL) {
6526 PyErr_Format(PyExc_TypeError,
6527 "'%.200s' object is not iterable",
6528 Py_TYPE(self)->tp_name);
6529 return NULL;
6530 }
6531 Py_DECREF(func);
6532 return PySeqIter_New(self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00006533}
Tim Peters6d6c1a32001-08-02 04:15:00 +00006534
6535static PyObject *
6536slot_tp_iternext(PyObject *self)
6537{
Benjamin Petersonce798522012-01-22 11:24:29 -05006538 _Py_IDENTIFIER(__next__);
Victor Stinner434723f2017-01-11 00:07:40 +01006539 return call_method(self, &PyId___next__, NULL, 0);
Tim Peters6d6c1a32001-08-02 04:15:00 +00006540}
6541
Guido van Rossum1a493502001-08-17 16:47:50 +00006542static PyObject *
6543slot_tp_descr_get(PyObject *self, PyObject *obj, PyObject *type)
6544{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006545 PyTypeObject *tp = Py_TYPE(self);
6546 PyObject *get;
Victor Stinner3c1e4812012-03-26 22:10:51 +02006547 _Py_IDENTIFIER(__get__);
Guido van Rossum1a493502001-08-17 16:47:50 +00006548
Victor Stinner3c1e4812012-03-26 22:10:51 +02006549 get = _PyType_LookupId(tp, &PyId___get__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006550 if (get == NULL) {
6551 /* Avoid further slowdowns */
6552 if (tp->tp_descr_get == slot_tp_descr_get)
6553 tp->tp_descr_get = NULL;
6554 Py_INCREF(self);
6555 return self;
6556 }
6557 if (obj == NULL)
6558 obj = Py_None;
6559 if (type == NULL)
6560 type = Py_None;
6561 return PyObject_CallFunctionObjArgs(get, self, obj, type, NULL);
Guido van Rossum1a493502001-08-17 16:47:50 +00006562}
Tim Peters6d6c1a32001-08-02 04:15:00 +00006563
6564static int
6565slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value)
6566{
Victor Stinner434723f2017-01-11 00:07:40 +01006567 PyObject* stack[2];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006568 PyObject *res;
Benjamin Petersonce798522012-01-22 11:24:29 -05006569 _Py_IDENTIFIER(__delete__);
6570 _Py_IDENTIFIER(__set__);
Guido van Rossum2c252392001-08-24 10:13:31 +00006571
Victor Stinner434723f2017-01-11 00:07:40 +01006572 stack[0] = target;
6573 if (value == NULL) {
6574 res = call_method(self, &PyId___delete__, stack, 1);
6575 }
6576 else {
6577 stack[1] = value;
6578 res = call_method(self, &PyId___set__, stack, 2);
6579 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006580 if (res == NULL)
6581 return -1;
6582 Py_DECREF(res);
6583 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00006584}
6585
6586static int
6587slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds)
6588{
Benjamin Petersonce798522012-01-22 11:24:29 -05006589 _Py_IDENTIFIER(__init__);
Victor Stinner516b9812017-02-09 22:53:47 +01006590 int unbound;
6591 PyObject *meth = lookup_method(self, &PyId___init__, &unbound);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006592 PyObject *res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00006593
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006594 if (meth == NULL)
6595 return -1;
Victor Stinner516b9812017-02-09 22:53:47 +01006596 if (unbound) {
6597 res = _PyObject_Call_Prepend(meth, self, args, kwds);
6598 }
6599 else {
6600 res = PyObject_Call(meth, args, kwds);
6601 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006602 Py_DECREF(meth);
6603 if (res == NULL)
6604 return -1;
6605 if (res != Py_None) {
6606 PyErr_Format(PyExc_TypeError,
6607 "__init__() should return None, not '%.200s'",
6608 Py_TYPE(res)->tp_name);
6609 Py_DECREF(res);
6610 return -1;
6611 }
6612 Py_DECREF(res);
6613 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00006614}
6615
6616static PyObject *
6617slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
6618{
Victor Stinner3f1057a2016-08-25 01:04:14 +02006619 PyObject *func, *result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00006620
Victor Stinner3c1e4812012-03-26 22:10:51 +02006621 func = _PyObject_GetAttrId((PyObject *)type, &PyId___new__);
Victor Stinner3f1057a2016-08-25 01:04:14 +02006622 if (func == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006623 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006624 }
Victor Stinner3f1057a2016-08-25 01:04:14 +02006625
6626 result = _PyObject_Call_Prepend(func, (PyObject *)type, args, kwds);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006627 Py_DECREF(func);
Victor Stinner3f1057a2016-08-25 01:04:14 +02006628 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00006629}
6630
Guido van Rossumfebd61d2002-08-08 20:55:20 +00006631static void
Antoine Pitrou796564c2013-07-30 19:59:21 +02006632slot_tp_finalize(PyObject *self)
Guido van Rossumfebd61d2002-08-08 20:55:20 +00006633{
Benjamin Petersonce798522012-01-22 11:24:29 -05006634 _Py_IDENTIFIER(__del__);
Victor Stinner516b9812017-02-09 22:53:47 +01006635 int unbound;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006636 PyObject *del, *res;
6637 PyObject *error_type, *error_value, *error_traceback;
Guido van Rossumfebd61d2002-08-08 20:55:20 +00006638
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006639 /* Save the current exception, if any. */
6640 PyErr_Fetch(&error_type, &error_value, &error_traceback);
Guido van Rossumfebd61d2002-08-08 20:55:20 +00006641
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006642 /* Execute __del__ method, if any. */
Victor Stinner516b9812017-02-09 22:53:47 +01006643 del = lookup_maybe_method(self, &PyId___del__, &unbound);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006644 if (del != NULL) {
Victor Stinner516b9812017-02-09 22:53:47 +01006645 res = call_unbound_noarg(unbound, del, self);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006646 if (res == NULL)
6647 PyErr_WriteUnraisable(del);
6648 else
6649 Py_DECREF(res);
6650 Py_DECREF(del);
6651 }
Guido van Rossumfebd61d2002-08-08 20:55:20 +00006652
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006653 /* Restore the saved exception. */
6654 PyErr_Restore(error_type, error_value, error_traceback);
Guido van Rossumfebd61d2002-08-08 20:55:20 +00006655}
6656
Yury Selivanov75445082015-05-11 22:57:16 -04006657static PyObject *
6658slot_am_await(PyObject *self)
6659{
Victor Stinner516b9812017-02-09 22:53:47 +01006660 int unbound;
Yury Selivanov75445082015-05-11 22:57:16 -04006661 PyObject *func, *res;
6662 _Py_IDENTIFIER(__await__);
6663
Serhiy Storchaka4e624ca2017-06-01 08:18:25 +03006664 func = lookup_maybe_method(self, &PyId___await__, &unbound);
Yury Selivanov75445082015-05-11 22:57:16 -04006665 if (func != NULL) {
Victor Stinner516b9812017-02-09 22:53:47 +01006666 res = call_unbound_noarg(unbound, func, self);
Yury Selivanov75445082015-05-11 22:57:16 -04006667 Py_DECREF(func);
6668 return res;
6669 }
6670 PyErr_Format(PyExc_AttributeError,
6671 "object %.50s does not have __await__ method",
6672 Py_TYPE(self)->tp_name);
6673 return NULL;
6674}
6675
6676static PyObject *
6677slot_am_aiter(PyObject *self)
6678{
Victor Stinner516b9812017-02-09 22:53:47 +01006679 int unbound;
Yury Selivanov75445082015-05-11 22:57:16 -04006680 PyObject *func, *res;
6681 _Py_IDENTIFIER(__aiter__);
6682
Serhiy Storchaka4e624ca2017-06-01 08:18:25 +03006683 func = lookup_maybe_method(self, &PyId___aiter__, &unbound);
Yury Selivanov75445082015-05-11 22:57:16 -04006684 if (func != NULL) {
Victor Stinner516b9812017-02-09 22:53:47 +01006685 res = call_unbound_noarg(unbound, func, self);
Yury Selivanov75445082015-05-11 22:57:16 -04006686 Py_DECREF(func);
6687 return res;
6688 }
6689 PyErr_Format(PyExc_AttributeError,
6690 "object %.50s does not have __aiter__ method",
6691 Py_TYPE(self)->tp_name);
6692 return NULL;
6693}
6694
6695static PyObject *
6696slot_am_anext(PyObject *self)
6697{
Victor Stinner516b9812017-02-09 22:53:47 +01006698 int unbound;
Yury Selivanov75445082015-05-11 22:57:16 -04006699 PyObject *func, *res;
6700 _Py_IDENTIFIER(__anext__);
6701
Serhiy Storchaka4e624ca2017-06-01 08:18:25 +03006702 func = lookup_maybe_method(self, &PyId___anext__, &unbound);
Yury Selivanov75445082015-05-11 22:57:16 -04006703 if (func != NULL) {
Victor Stinner516b9812017-02-09 22:53:47 +01006704 res = call_unbound_noarg(unbound, func, self);
Yury Selivanov75445082015-05-11 22:57:16 -04006705 Py_DECREF(func);
6706 return res;
6707 }
6708 PyErr_Format(PyExc_AttributeError,
6709 "object %.50s does not have __anext__ method",
6710 Py_TYPE(self)->tp_name);
6711 return NULL;
6712}
Guido van Rossum7b9144b2001-10-09 19:39:46 +00006713
Benjamin Peterson63952412013-04-01 17:41:41 -04006714/*
6715Table mapping __foo__ names to tp_foo offsets and slot_tp_foo wrapper functions.
6716
6717The table is ordered by offsets relative to the 'PyHeapTypeObject' structure,
6718which incorporates the additional structures used for numbers, sequences and
6719mappings. Note that multiple names may map to the same slot (e.g. __eq__,
6720__ne__ etc. all map to tp_richcompare) and one name may map to multiple slots
6721(e.g. __str__ affects tp_str as well as tp_repr). The table is terminated with
6722an all-zero entry. (This table is further initialized in init_slotdefs().)
6723*/
Guido van Rossum7b9144b2001-10-09 19:39:46 +00006724
Guido van Rossum6d204072001-10-21 00:44:31 +00006725typedef struct wrapperbase slotdef;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00006726
6727#undef TPSLOT
Guido van Rossumc8e56452001-10-22 00:43:43 +00006728#undef FLSLOT
Yury Selivanov75445082015-05-11 22:57:16 -04006729#undef AMSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00006730#undef ETSLOT
6731#undef SQSLOT
6732#undef MPSLOT
6733#undef NBSLOT
Guido van Rossum6d204072001-10-21 00:44:31 +00006734#undef UNSLOT
6735#undef IBSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00006736#undef BINSLOT
6737#undef RBINSLOT
6738
Guido van Rossum6d204072001-10-21 00:44:31 +00006739#define TPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006740 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
6741 PyDoc_STR(DOC)}
Guido van Rossumc8e56452001-10-22 00:43:43 +00006742#define FLSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC, FLAGS) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006743 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
6744 PyDoc_STR(DOC), FLAGS}
Guido van Rossum6d204072001-10-21 00:44:31 +00006745#define ETSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006746 {NAME, offsetof(PyHeapTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
6747 PyDoc_STR(DOC)}
Yury Selivanov75445082015-05-11 22:57:16 -04006748#define AMSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
6749 ETSLOT(NAME, as_async.SLOT, FUNCTION, WRAPPER, DOC)
Guido van Rossum6d204072001-10-21 00:44:31 +00006750#define SQSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006751 ETSLOT(NAME, as_sequence.SLOT, FUNCTION, WRAPPER, DOC)
Guido van Rossum6d204072001-10-21 00:44:31 +00006752#define MPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006753 ETSLOT(NAME, as_mapping.SLOT, FUNCTION, WRAPPER, DOC)
Guido van Rossum6d204072001-10-21 00:44:31 +00006754#define NBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006755 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, DOC)
Guido van Rossum6d204072001-10-21 00:44:31 +00006756#define UNSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006757 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
Larry Hastings69a25472014-02-09 22:22:38 -08006758 NAME "($self, /)\n--\n\n" DOC)
Guido van Rossum6d204072001-10-21 00:44:31 +00006759#define IBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006760 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
Larry Hastings69a25472014-02-09 22:22:38 -08006761 NAME "($self, value, /)\n--\n\nReturn self" DOC "value.")
Guido van Rossum6d204072001-10-21 00:44:31 +00006762#define BINSLOT(NAME, SLOT, FUNCTION, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006763 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
Larry Hastings69a25472014-02-09 22:22:38 -08006764 NAME "($self, value, /)\n--\n\nReturn self" DOC "value.")
Guido van Rossum6d204072001-10-21 00:44:31 +00006765#define RBINSLOT(NAME, SLOT, FUNCTION, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006766 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
Larry Hastings69a25472014-02-09 22:22:38 -08006767 NAME "($self, value, /)\n--\n\nReturn value" DOC "self.")
Anthony Baxter56616992005-06-03 14:12:21 +00006768#define BINSLOTNOTINFIX(NAME, SLOT, FUNCTION, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006769 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
Larry Hastings69a25472014-02-09 22:22:38 -08006770 NAME "($self, value, /)\n--\n\n" DOC)
Anthony Baxter56616992005-06-03 14:12:21 +00006771#define RBINSLOTNOTINFIX(NAME, SLOT, FUNCTION, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006772 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
Larry Hastings69a25472014-02-09 22:22:38 -08006773 NAME "($self, value, /)\n--\n\n" DOC)
Guido van Rossum7b9144b2001-10-09 19:39:46 +00006774
6775static slotdef slotdefs[] = {
Benjamin Peterson63952412013-04-01 17:41:41 -04006776 TPSLOT("__getattribute__", tp_getattr, NULL, NULL, ""),
6777 TPSLOT("__getattr__", tp_getattr, NULL, NULL, ""),
6778 TPSLOT("__setattr__", tp_setattr, NULL, NULL, ""),
6779 TPSLOT("__delattr__", tp_setattr, NULL, NULL, ""),
6780 TPSLOT("__repr__", tp_repr, slot_tp_repr, wrap_unaryfunc,
Larry Hastings69a25472014-02-09 22:22:38 -08006781 "__repr__($self, /)\n--\n\nReturn repr(self)."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006782 TPSLOT("__hash__", tp_hash, slot_tp_hash, wrap_hashfunc,
Larry Hastings69a25472014-02-09 22:22:38 -08006783 "__hash__($self, /)\n--\n\nReturn hash(self)."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006784 FLSLOT("__call__", tp_call, slot_tp_call, (wrapperfunc)wrap_call,
Larry Hastings69a25472014-02-09 22:22:38 -08006785 "__call__($self, /, *args, **kwargs)\n--\n\nCall self as a function.",
Larry Hastings5c661892014-01-24 06:17:25 -08006786 PyWrapperFlag_KEYWORDS),
Benjamin Peterson63952412013-04-01 17:41:41 -04006787 TPSLOT("__str__", tp_str, slot_tp_str, wrap_unaryfunc,
Larry Hastings69a25472014-02-09 22:22:38 -08006788 "__str__($self, /)\n--\n\nReturn str(self)."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006789 TPSLOT("__getattribute__", tp_getattro, slot_tp_getattr_hook,
Larry Hastings5c661892014-01-24 06:17:25 -08006790 wrap_binaryfunc,
Larry Hastings69a25472014-02-09 22:22:38 -08006791 "__getattribute__($self, name, /)\n--\n\nReturn getattr(self, name)."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006792 TPSLOT("__getattr__", tp_getattro, slot_tp_getattr_hook, NULL, ""),
6793 TPSLOT("__setattr__", tp_setattro, slot_tp_setattro, wrap_setattr,
Larry Hastings69a25472014-02-09 22:22:38 -08006794 "__setattr__($self, name, value, /)\n--\n\nImplement setattr(self, name, value)."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006795 TPSLOT("__delattr__", tp_setattro, slot_tp_setattro, wrap_delattr,
Larry Hastings69a25472014-02-09 22:22:38 -08006796 "__delattr__($self, name, /)\n--\n\nImplement delattr(self, name)."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006797 TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare, richcmp_lt,
Larry Hastings69a25472014-02-09 22:22:38 -08006798 "__lt__($self, value, /)\n--\n\nReturn self<value."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006799 TPSLOT("__le__", tp_richcompare, slot_tp_richcompare, richcmp_le,
Larry Hastings69a25472014-02-09 22:22:38 -08006800 "__le__($self, value, /)\n--\n\nReturn self<=value."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006801 TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare, richcmp_eq,
Larry Hastings69a25472014-02-09 22:22:38 -08006802 "__eq__($self, value, /)\n--\n\nReturn self==value."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006803 TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare, richcmp_ne,
Larry Hastings69a25472014-02-09 22:22:38 -08006804 "__ne__($self, value, /)\n--\n\nReturn self!=value."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006805 TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare, richcmp_gt,
Larry Hastings69a25472014-02-09 22:22:38 -08006806 "__gt__($self, value, /)\n--\n\nReturn self>value."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006807 TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare, richcmp_ge,
Zachary Wareea42b4c2014-04-18 09:14:31 -05006808 "__ge__($self, value, /)\n--\n\nReturn self>=value."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006809 TPSLOT("__iter__", tp_iter, slot_tp_iter, wrap_unaryfunc,
Larry Hastings69a25472014-02-09 22:22:38 -08006810 "__iter__($self, /)\n--\n\nImplement iter(self)."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006811 TPSLOT("__next__", tp_iternext, slot_tp_iternext, wrap_next,
Larry Hastings69a25472014-02-09 22:22:38 -08006812 "__next__($self, /)\n--\n\nImplement next(self)."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006813 TPSLOT("__get__", tp_descr_get, slot_tp_descr_get, wrap_descr_get,
Larry Hastings69a25472014-02-09 22:22:38 -08006814 "__get__($self, instance, owner, /)\n--\n\nReturn an attribute of instance, which is of type owner."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006815 TPSLOT("__set__", tp_descr_set, slot_tp_descr_set, wrap_descr_set,
Larry Hastings69a25472014-02-09 22:22:38 -08006816 "__set__($self, instance, value, /)\n--\n\nSet an attribute of instance to value."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006817 TPSLOT("__delete__", tp_descr_set, slot_tp_descr_set,
Larry Hastings5c661892014-01-24 06:17:25 -08006818 wrap_descr_delete,
Yury Selivanov056e2652014-03-02 12:25:27 -05006819 "__delete__($self, instance, /)\n--\n\nDelete an attribute of instance."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006820 FLSLOT("__init__", tp_init, slot_tp_init, (wrapperfunc)wrap_init,
Larry Hastings69a25472014-02-09 22:22:38 -08006821 "__init__($self, /, *args, **kwargs)\n--\n\n"
Larry Hastings581ee362014-01-28 05:00:08 -08006822 "Initialize self. See help(type(self)) for accurate signature.",
Benjamin Peterson63952412013-04-01 17:41:41 -04006823 PyWrapperFlag_KEYWORDS),
Larry Hastings5c661892014-01-24 06:17:25 -08006824 TPSLOT("__new__", tp_new, slot_tp_new, NULL,
Larry Hastings69a25472014-02-09 22:22:38 -08006825 "__new__(type, /, *args, **kwargs)\n--\n\n"
Larry Hastings581ee362014-01-28 05:00:08 -08006826 "Create and return new object. See help(type) for accurate signature."),
Antoine Pitrou796564c2013-07-30 19:59:21 +02006827 TPSLOT("__del__", tp_finalize, slot_tp_finalize, (wrapperfunc)wrap_del, ""),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00006828
Yury Selivanov75445082015-05-11 22:57:16 -04006829 AMSLOT("__await__", am_await, slot_am_await, wrap_unaryfunc,
6830 "__await__($self, /)\n--\n\nReturn an iterator to be used in await expression."),
6831 AMSLOT("__aiter__", am_aiter, slot_am_aiter, wrap_unaryfunc,
6832 "__aiter__($self, /)\n--\n\nReturn an awaitable, that resolves in asynchronous iterator."),
6833 AMSLOT("__anext__", am_anext, slot_am_anext, wrap_unaryfunc,
6834 "__anext__($self, /)\n--\n\nReturn a value or raise StopAsyncIteration."),
6835
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006836 BINSLOT("__add__", nb_add, slot_nb_add,
Larry Hastings5c661892014-01-24 06:17:25 -08006837 "+"),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006838 RBINSLOT("__radd__", nb_add, slot_nb_add,
Larry Hastings5c661892014-01-24 06:17:25 -08006839 "+"),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006840 BINSLOT("__sub__", nb_subtract, slot_nb_subtract,
Larry Hastings5c661892014-01-24 06:17:25 -08006841 "-"),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006842 RBINSLOT("__rsub__", nb_subtract, slot_nb_subtract,
Larry Hastings5c661892014-01-24 06:17:25 -08006843 "-"),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006844 BINSLOT("__mul__", nb_multiply, slot_nb_multiply,
Larry Hastings5c661892014-01-24 06:17:25 -08006845 "*"),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006846 RBINSLOT("__rmul__", nb_multiply, slot_nb_multiply,
Larry Hastings5c661892014-01-24 06:17:25 -08006847 "*"),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006848 BINSLOT("__mod__", nb_remainder, slot_nb_remainder,
Larry Hastings5c661892014-01-24 06:17:25 -08006849 "%"),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006850 RBINSLOT("__rmod__", nb_remainder, slot_nb_remainder,
Larry Hastings5c661892014-01-24 06:17:25 -08006851 "%"),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006852 BINSLOTNOTINFIX("__divmod__", nb_divmod, slot_nb_divmod,
Larry Hastings581ee362014-01-28 05:00:08 -08006853 "Return divmod(self, value)."),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006854 RBINSLOTNOTINFIX("__rdivmod__", nb_divmod, slot_nb_divmod,
Larry Hastings581ee362014-01-28 05:00:08 -08006855 "Return divmod(value, self)."),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006856 NBSLOT("__pow__", nb_power, slot_nb_power, wrap_ternaryfunc,
Larry Hastings69a25472014-02-09 22:22:38 -08006857 "__pow__($self, value, mod=None, /)\n--\n\nReturn pow(self, value, mod)."),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006858 NBSLOT("__rpow__", nb_power, slot_nb_power, wrap_ternaryfunc_r,
Larry Hastings69a25472014-02-09 22:22:38 -08006859 "__rpow__($self, value, mod=None, /)\n--\n\nReturn pow(value, self, mod)."),
Larry Hastings5c661892014-01-24 06:17:25 -08006860 UNSLOT("__neg__", nb_negative, slot_nb_negative, wrap_unaryfunc, "-self"),
6861 UNSLOT("__pos__", nb_positive, slot_nb_positive, wrap_unaryfunc, "+self"),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006862 UNSLOT("__abs__", nb_absolute, slot_nb_absolute, wrap_unaryfunc,
Larry Hastings5c661892014-01-24 06:17:25 -08006863 "abs(self)"),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006864 UNSLOT("__bool__", nb_bool, slot_nb_bool, wrap_inquirypred,
Larry Hastings5c661892014-01-24 06:17:25 -08006865 "self != 0"),
6866 UNSLOT("__invert__", nb_invert, slot_nb_invert, wrap_unaryfunc, "~self"),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006867 BINSLOT("__lshift__", nb_lshift, slot_nb_lshift, "<<"),
6868 RBINSLOT("__rlshift__", nb_lshift, slot_nb_lshift, "<<"),
6869 BINSLOT("__rshift__", nb_rshift, slot_nb_rshift, ">>"),
6870 RBINSLOT("__rrshift__", nb_rshift, slot_nb_rshift, ">>"),
6871 BINSLOT("__and__", nb_and, slot_nb_and, "&"),
6872 RBINSLOT("__rand__", nb_and, slot_nb_and, "&"),
6873 BINSLOT("__xor__", nb_xor, slot_nb_xor, "^"),
6874 RBINSLOT("__rxor__", nb_xor, slot_nb_xor, "^"),
6875 BINSLOT("__or__", nb_or, slot_nb_or, "|"),
6876 RBINSLOT("__ror__", nb_or, slot_nb_or, "|"),
6877 UNSLOT("__int__", nb_int, slot_nb_int, wrap_unaryfunc,
Larry Hastings5c661892014-01-24 06:17:25 -08006878 "int(self)"),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006879 UNSLOT("__float__", nb_float, slot_nb_float, wrap_unaryfunc,
Larry Hastings5c661892014-01-24 06:17:25 -08006880 "float(self)"),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006881 IBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add,
Eli Benderskyd3baae72011-11-11 16:57:05 +02006882 wrap_binaryfunc, "+="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006883 IBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract,
Eli Benderskyd3baae72011-11-11 16:57:05 +02006884 wrap_binaryfunc, "-="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006885 IBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply,
Eli Benderskyd3baae72011-11-11 16:57:05 +02006886 wrap_binaryfunc, "*="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006887 IBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder,
Eli Benderskyd3baae72011-11-11 16:57:05 +02006888 wrap_binaryfunc, "%="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006889 IBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power,
Eli Benderskyd3baae72011-11-11 16:57:05 +02006890 wrap_binaryfunc, "**="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006891 IBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift,
Eli Benderskyd3baae72011-11-11 16:57:05 +02006892 wrap_binaryfunc, "<<="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006893 IBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift,
Eli Benderskyd3baae72011-11-11 16:57:05 +02006894 wrap_binaryfunc, ">>="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006895 IBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and,
Eli Benderskyd3baae72011-11-11 16:57:05 +02006896 wrap_binaryfunc, "&="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006897 IBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor,
Eli Benderskyd3baae72011-11-11 16:57:05 +02006898 wrap_binaryfunc, "^="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006899 IBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or,
Eli Benderskyd3baae72011-11-11 16:57:05 +02006900 wrap_binaryfunc, "|="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006901 BINSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
6902 RBINSLOT("__rfloordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
6903 BINSLOT("__truediv__", nb_true_divide, slot_nb_true_divide, "/"),
6904 RBINSLOT("__rtruediv__", nb_true_divide, slot_nb_true_divide, "/"),
6905 IBSLOT("__ifloordiv__", nb_inplace_floor_divide,
Georg Brandle1d26f32014-10-31 13:12:57 +01006906 slot_nb_inplace_floor_divide, wrap_binaryfunc, "//="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006907 IBSLOT("__itruediv__", nb_inplace_true_divide,
Georg Brandle1d26f32014-10-31 13:12:57 +01006908 slot_nb_inplace_true_divide, wrap_binaryfunc, "/="),
Benjamin Peterson63952412013-04-01 17:41:41 -04006909 NBSLOT("__index__", nb_index, slot_nb_index, wrap_unaryfunc,
Larry Hastings69a25472014-02-09 22:22:38 -08006910 "__index__($self, /)\n--\n\n"
Zachary Ware715ef022014-04-18 09:23:14 -05006911 "Return self converted to an integer, if self is suitable "
Larry Hastings5c661892014-01-24 06:17:25 -08006912 "for use as an index into a list."),
Benjamin Petersond51374e2014-04-09 23:55:56 -04006913 BINSLOT("__matmul__", nb_matrix_multiply, slot_nb_matrix_multiply,
6914 "@"),
6915 RBINSLOT("__rmatmul__", nb_matrix_multiply, slot_nb_matrix_multiply,
6916 "@"),
6917 IBSLOT("__imatmul__", nb_inplace_matrix_multiply, slot_nb_inplace_matrix_multiply,
6918 wrap_binaryfunc, "@="),
Benjamin Peterson63952412013-04-01 17:41:41 -04006919 MPSLOT("__len__", mp_length, slot_mp_length, wrap_lenfunc,
Larry Hastings69a25472014-02-09 22:22:38 -08006920 "__len__($self, /)\n--\n\nReturn len(self)."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006921 MPSLOT("__getitem__", mp_subscript, slot_mp_subscript,
6922 wrap_binaryfunc,
Larry Hastings69a25472014-02-09 22:22:38 -08006923 "__getitem__($self, key, /)\n--\n\nReturn self[key]."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006924 MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript,
6925 wrap_objobjargproc,
Larry Hastings69a25472014-02-09 22:22:38 -08006926 "__setitem__($self, key, value, /)\n--\n\nSet self[key] to value."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006927 MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript,
6928 wrap_delitem,
Yury Selivanov056e2652014-03-02 12:25:27 -05006929 "__delitem__($self, key, /)\n--\n\nDelete self[key]."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006930
6931 SQSLOT("__len__", sq_length, slot_sq_length, wrap_lenfunc,
Larry Hastings69a25472014-02-09 22:22:38 -08006932 "__len__($self, /)\n--\n\nReturn len(self)."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006933 /* Heap types defining __add__/__mul__ have sq_concat/sq_repeat == NULL.
6934 The logic in abstract.c always falls back to nb_add/nb_multiply in
6935 this case. Defining both the nb_* and the sq_* slots to call the
6936 user-defined methods has unexpected side-effects, as shown by
6937 test_descr.notimplemented() */
6938 SQSLOT("__add__", sq_concat, NULL, wrap_binaryfunc,
Larry Hastings69a25472014-02-09 22:22:38 -08006939 "__add__($self, value, /)\n--\n\nReturn self+value."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006940 SQSLOT("__mul__", sq_repeat, NULL, wrap_indexargfunc,
Larry Hastings69a25472014-02-09 22:22:38 -08006941 "__mul__($self, value, /)\n--\n\nReturn self*value.n"),
Benjamin Peterson63952412013-04-01 17:41:41 -04006942 SQSLOT("__rmul__", sq_repeat, NULL, wrap_indexargfunc,
Larry Hastings69a25472014-02-09 22:22:38 -08006943 "__rmul__($self, value, /)\n--\n\nReturn self*value."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006944 SQSLOT("__getitem__", sq_item, slot_sq_item, wrap_sq_item,
Larry Hastings69a25472014-02-09 22:22:38 -08006945 "__getitem__($self, key, /)\n--\n\nReturn self[key]."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006946 SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_setitem,
Larry Hastings69a25472014-02-09 22:22:38 -08006947 "__setitem__($self, key, value, /)\n--\n\nSet self[key] to value."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006948 SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_delitem,
Larry Hastings69a25472014-02-09 22:22:38 -08006949 "__delitem__($self, key, /)\n--\n\nDelete self[key]."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006950 SQSLOT("__contains__", sq_contains, slot_sq_contains, wrap_objobjproc,
Larry Hastings69a25472014-02-09 22:22:38 -08006951 "__contains__($self, key, /)\n--\n\nReturn key in self."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006952 SQSLOT("__iadd__", sq_inplace_concat, NULL,
Larry Hastings5c661892014-01-24 06:17:25 -08006953 wrap_binaryfunc,
Larry Hastings69a25472014-02-09 22:22:38 -08006954 "__iadd__($self, value, /)\n--\n\nImplement self+=value."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006955 SQSLOT("__imul__", sq_inplace_repeat, NULL,
Larry Hastings5c661892014-01-24 06:17:25 -08006956 wrap_indexargfunc,
Larry Hastings69a25472014-02-09 22:22:38 -08006957 "__imul__($self, value, /)\n--\n\nImplement self*=value."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006958
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006959 {NULL}
Guido van Rossum7b9144b2001-10-09 19:39:46 +00006960};
6961
Guido van Rossumc334df52002-04-04 23:44:47 +00006962/* Given a type pointer and an offset gotten from a slotdef entry, return a
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006963 pointer to the actual slot. This is not quite the same as simply adding
Guido van Rossumc334df52002-04-04 23:44:47 +00006964 the offset to the type pointer, since it takes care to indirect through the
6965 proper indirection pointer (as_buffer, etc.); it returns NULL if the
6966 indirection pointer is NULL. */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00006967static void **
Martin v. Löwis18e16552006-02-15 17:27:45 +00006968slotptr(PyTypeObject *type, int ioffset)
Guido van Rossum7b9144b2001-10-09 19:39:46 +00006969{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006970 char *ptr;
6971 long offset = ioffset;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00006972
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006973 /* Note: this depends on the order of the members of PyHeapTypeObject! */
6974 assert(offset >= 0);
6975 assert((size_t)offset < offsetof(PyHeapTypeObject, as_buffer));
6976 if ((size_t)offset >= offsetof(PyHeapTypeObject, as_sequence)) {
6977 ptr = (char *)type->tp_as_sequence;
6978 offset -= offsetof(PyHeapTypeObject, as_sequence);
6979 }
6980 else if ((size_t)offset >= offsetof(PyHeapTypeObject, as_mapping)) {
6981 ptr = (char *)type->tp_as_mapping;
6982 offset -= offsetof(PyHeapTypeObject, as_mapping);
6983 }
6984 else if ((size_t)offset >= offsetof(PyHeapTypeObject, as_number)) {
6985 ptr = (char *)type->tp_as_number;
6986 offset -= offsetof(PyHeapTypeObject, as_number);
6987 }
Yury Selivanov75445082015-05-11 22:57:16 -04006988 else if ((size_t)offset >= offsetof(PyHeapTypeObject, as_async)) {
6989 ptr = (char *)type->tp_as_async;
6990 offset -= offsetof(PyHeapTypeObject, as_async);
6991 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006992 else {
6993 ptr = (char *)type;
6994 }
6995 if (ptr != NULL)
6996 ptr += offset;
6997 return (void **)ptr;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00006998}
Guido van Rossumf040ede2001-08-07 16:40:56 +00006999
Guido van Rossumc334df52002-04-04 23:44:47 +00007000/* Length of array of slotdef pointers used to store slots with the
7001 same __name__. There should be at most MAX_EQUIV-1 slotdef entries with
7002 the same __name__, for any __name__. Since that's a static property, it is
7003 appropriate to declare fixed-size arrays for this. */
7004#define MAX_EQUIV 10
7005
7006/* Return a slot pointer for a given name, but ONLY if the attribute has
7007 exactly one slot function. The name must be an interned string. */
7008static void **
7009resolve_slotdups(PyTypeObject *type, PyObject *name)
7010{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007011 /* XXX Maybe this could be optimized more -- but is it worth it? */
Guido van Rossumc334df52002-04-04 23:44:47 +00007012
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007013 /* pname and ptrs act as a little cache */
7014 static PyObject *pname;
7015 static slotdef *ptrs[MAX_EQUIV];
7016 slotdef *p, **pp;
7017 void **res, **ptr;
Guido van Rossumc334df52002-04-04 23:44:47 +00007018
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007019 if (pname != name) {
7020 /* Collect all slotdefs that match name into ptrs. */
7021 pname = name;
7022 pp = ptrs;
7023 for (p = slotdefs; p->name_strobj; p++) {
7024 if (p->name_strobj == name)
7025 *pp++ = p;
7026 }
7027 *pp = NULL;
7028 }
Guido van Rossumc334df52002-04-04 23:44:47 +00007029
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007030 /* Look in all matching slots of the type; if exactly one of these has
7031 a filled-in slot, return its value. Otherwise return NULL. */
7032 res = NULL;
7033 for (pp = ptrs; *pp; pp++) {
7034 ptr = slotptr(type, (*pp)->offset);
7035 if (ptr == NULL || *ptr == NULL)
7036 continue;
7037 if (res != NULL)
7038 return NULL;
7039 res = ptr;
7040 }
7041 return res;
Guido van Rossumc334df52002-04-04 23:44:47 +00007042}
7043
Guido van Rossum8d24ee92003-03-24 23:49:49 +00007044/* Common code for update_slots_callback() and fixup_slot_dispatchers(). This
Guido van Rossumc334df52002-04-04 23:44:47 +00007045 does some incredibly complex thinking and then sticks something into the
7046 slot. (It sees if the adjacent slotdefs for the same slot have conflicting
7047 interests, and then stores a generic wrapper or a specific function into
7048 the slot.) Return a pointer to the next slotdef with a different offset,
7049 because that's convenient for fixup_slot_dispatchers(). */
7050static slotdef *
7051update_one_slot(PyTypeObject *type, slotdef *p)
7052{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007053 PyObject *descr;
7054 PyWrapperDescrObject *d;
7055 void *generic = NULL, *specific = NULL;
7056 int use_generic = 0;
7057 int offset = p->offset;
scoder2102c782017-10-01 10:37:47 +02007058 int error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007059 void **ptr = slotptr(type, offset);
Guido van Rossumc334df52002-04-04 23:44:47 +00007060
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007061 if (ptr == NULL) {
7062 do {
7063 ++p;
7064 } while (p->offset == offset);
7065 return p;
7066 }
scoder2102c782017-10-01 10:37:47 +02007067 /* We may end up clearing live exceptions below, so make sure it's ours. */
7068 assert(!PyErr_Occurred());
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007069 do {
scoder2102c782017-10-01 10:37:47 +02007070 /* Use faster uncached lookup as we won't get any cache hits during type setup. */
7071 descr = find_name_in_mro(type, p->name_strobj, &error);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007072 if (descr == NULL) {
scoder2102c782017-10-01 10:37:47 +02007073 if (error == -1) {
7074 /* It is unlikely by not impossible that there has been an exception
7075 during lookup. Since this function originally expected no errors,
7076 we ignore them here in order to keep up the interface. */
7077 PyErr_Clear();
7078 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007079 if (ptr == (void**)&type->tp_iternext) {
Trent Nelsonab02db22012-09-18 21:58:03 -04007080 specific = (void *)_PyObject_NextNotImplemented;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007081 }
7082 continue;
7083 }
Benjamin Peterson7b166872012-04-24 11:06:25 -04007084 if (Py_TYPE(descr) == &PyWrapperDescr_Type &&
7085 ((PyWrapperDescrObject *)descr)->d_base->name_strobj == p->name_strobj) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007086 void **tptr = resolve_slotdups(type, p->name_strobj);
7087 if (tptr == NULL || tptr == ptr)
7088 generic = p->function;
7089 d = (PyWrapperDescrObject *)descr;
7090 if (d->d_base->wrapper == p->wrapper &&
7091 PyType_IsSubtype(type, PyDescr_TYPE(d)))
7092 {
7093 if (specific == NULL ||
7094 specific == d->d_wrapped)
7095 specific = d->d_wrapped;
7096 else
7097 use_generic = 1;
7098 }
7099 }
7100 else if (Py_TYPE(descr) == &PyCFunction_Type &&
7101 PyCFunction_GET_FUNCTION(descr) ==
7102 (PyCFunction)tp_new_wrapper &&
7103 ptr == (void**)&type->tp_new)
7104 {
7105 /* The __new__ wrapper is not a wrapper descriptor,
7106 so must be special-cased differently.
7107 If we don't do this, creating an instance will
7108 always use slot_tp_new which will look up
7109 __new__ in the MRO which will call tp_new_wrapper
7110 which will look through the base classes looking
7111 for a static base and call its tp_new (usually
7112 PyType_GenericNew), after performing various
7113 sanity checks and constructing a new argument
7114 list. Cut all that nonsense short -- this speeds
7115 up instance creation tremendously. */
Serhiy Storchaka49010ee2016-12-14 19:52:17 +02007116 specific = (void *)type->tp_new;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007117 /* XXX I'm not 100% sure that there isn't a hole
7118 in this reasoning that requires additional
7119 sanity checks. I'll buy the first person to
7120 point out a bug in this reasoning a beer. */
7121 }
7122 else if (descr == Py_None &&
7123 ptr == (void**)&type->tp_hash) {
7124 /* We specifically allow __hash__ to be set to None
7125 to prevent inheritance of the default
7126 implementation from object.__hash__ */
Trent Nelsonab02db22012-09-18 21:58:03 -04007127 specific = (void *)PyObject_HashNotImplemented;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007128 }
7129 else {
7130 use_generic = 1;
7131 generic = p->function;
7132 }
7133 } while ((++p)->offset == offset);
7134 if (specific && !use_generic)
7135 *ptr = specific;
7136 else
7137 *ptr = generic;
7138 return p;
Guido van Rossumc334df52002-04-04 23:44:47 +00007139}
7140
Guido van Rossum8d24ee92003-03-24 23:49:49 +00007141/* In the type, update the slots whose slotdefs are gathered in the pp array.
7142 This is a callback for update_subclasses(). */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00007143static int
Guido van Rossum8d24ee92003-03-24 23:49:49 +00007144update_slots_callback(PyTypeObject *type, void *data)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00007145{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007146 slotdef **pp = (slotdef **)data;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00007147
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007148 for (; *pp; pp++)
7149 update_one_slot(type, *pp);
7150 return 0;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00007151}
7152
Martin v. Löwis996b6712014-07-26 16:44:07 +02007153static int slotdefs_initialized = 0;
Guido van Rossumc334df52002-04-04 23:44:47 +00007154/* Initialize the slotdefs table by adding interned string objects for the
Martin v. Löwis5b561502014-07-26 15:25:04 +02007155 names. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00007156static void
Guido van Rossumd396b9c2001-10-13 20:02:41 +00007157init_slotdefs(void)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00007158{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007159 slotdef *p;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00007160
Martin v. Löwis996b6712014-07-26 16:44:07 +02007161 if (slotdefs_initialized)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007162 return;
7163 for (p = slotdefs; p->name; p++) {
Benjamin Peterson63952412013-04-01 17:41:41 -04007164 /* Slots must be ordered by their offset in the PyHeapTypeObject. */
7165 assert(!p[1].name || p->offset <= p[1].offset);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007166 p->name_strobj = PyUnicode_InternFromString(p->name);
Serhiy Storchakad8969852017-05-20 08:48:06 +03007167 if (!p->name_strobj || !PyUnicode_CHECK_INTERNED(p->name_strobj))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007168 Py_FatalError("Out of memory interning slotdef names");
7169 }
Martin v. Löwis996b6712014-07-26 16:44:07 +02007170 slotdefs_initialized = 1;
7171}
7172
7173/* Undo init_slotdefs, releasing the interned strings. */
Victor Stinner331a7262014-07-27 16:11:30 +02007174static void clear_slotdefs(void)
Martin v. Löwis996b6712014-07-26 16:44:07 +02007175{
7176 slotdef *p;
7177 for (p = slotdefs; p->name; p++) {
7178 Py_CLEAR(p->name_strobj);
7179 }
7180 slotdefs_initialized = 0;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00007181}
7182
Guido van Rossumc334df52002-04-04 23:44:47 +00007183/* Update the slots after assignment to a class (type) attribute. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00007184static int
7185update_slot(PyTypeObject *type, PyObject *name)
7186{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007187 slotdef *ptrs[MAX_EQUIV];
7188 slotdef *p;
7189 slotdef **pp;
7190 int offset;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00007191
Serhiy Storchakad8969852017-05-20 08:48:06 +03007192 assert(PyUnicode_CheckExact(name));
7193 assert(PyUnicode_CHECK_INTERNED(name));
7194
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007195 /* Clear the VALID_VERSION flag of 'type' and all its
7196 subclasses. This could possibly be unified with the
7197 update_subclasses() recursion below, but carefully:
7198 they each have their own conditions on which to stop
7199 recursing into subclasses. */
7200 PyType_Modified(type);
Christian Heimesa62da1d2008-01-12 19:39:10 +00007201
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007202 init_slotdefs();
7203 pp = ptrs;
7204 for (p = slotdefs; p->name; p++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007205 if (p->name_strobj == name)
7206 *pp++ = p;
7207 }
7208 *pp = NULL;
7209 for (pp = ptrs; *pp; pp++) {
7210 p = *pp;
7211 offset = p->offset;
7212 while (p > slotdefs && (p-1)->offset == offset)
7213 --p;
7214 *pp = p;
7215 }
7216 if (ptrs[0] == NULL)
7217 return 0; /* Not an attribute that affects any slots */
7218 return update_subclasses(type, name,
7219 update_slots_callback, (void *)ptrs);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00007220}
7221
Guido van Rossumc334df52002-04-04 23:44:47 +00007222/* Store the proper functions in the slot dispatches at class (type)
7223 definition time, based upon which operations the class overrides in its
7224 dict. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00007225static void
Guido van Rossum7b9144b2001-10-09 19:39:46 +00007226fixup_slot_dispatchers(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00007227{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007228 slotdef *p;
Tim Peters6d6c1a32001-08-02 04:15:00 +00007229
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007230 init_slotdefs();
7231 for (p = slotdefs; p->name; )
7232 p = update_one_slot(type, p);
Tim Peters6d6c1a32001-08-02 04:15:00 +00007233}
Guido van Rossum705f0f52001-08-24 16:47:00 +00007234
Michael W. Hudson98bbc492002-11-26 14:47:27 +00007235static void
7236update_all_slots(PyTypeObject* type)
7237{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007238 slotdef *p;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00007239
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007240 init_slotdefs();
7241 for (p = slotdefs; p->name; p++) {
7242 /* update_slot returns int but can't actually fail */
7243 update_slot(type, p->name_strobj);
7244 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +00007245}
7246
Nick Coghland78448e2016-07-30 16:26:03 +10007247/* Call __set_name__ on all descriptors in a newly generated type */
7248static int
7249set_names(PyTypeObject *type)
7250{
Serhiy Storchaka9ec07722016-11-29 09:54:17 +02007251 PyObject *names_to_set, *key, *value, *set_name, *tmp;
Nick Coghland78448e2016-07-30 16:26:03 +10007252 Py_ssize_t i = 0;
7253
Serhiy Storchaka9ec07722016-11-29 09:54:17 +02007254 names_to_set = PyDict_Copy(type->tp_dict);
7255 if (names_to_set == NULL)
7256 return -1;
7257
7258 while (PyDict_Next(names_to_set, &i, &key, &value)) {
Serhiy Storchaka4e624ca2017-06-01 08:18:25 +03007259 set_name = _PyObject_LookupSpecial(value, &PyId___set_name__);
Serhiy Storchakaafd02a42016-09-21 15:54:59 +03007260 if (set_name != NULL) {
7261 tmp = PyObject_CallFunctionObjArgs(set_name, type, key, NULL);
7262 Py_DECREF(set_name);
Serhiy Storchakad5d32d22016-10-21 17:13:31 +03007263 if (tmp == NULL) {
7264 _PyErr_FormatFromCause(PyExc_RuntimeError,
7265 "Error calling __set_name__ on '%.100s' instance %R "
7266 "in '%.100s'",
7267 value->ob_type->tp_name, key, type->tp_name);
Serhiy Storchaka9ec07722016-11-29 09:54:17 +02007268 Py_DECREF(names_to_set);
Nick Coghland78448e2016-07-30 16:26:03 +10007269 return -1;
Serhiy Storchakad5d32d22016-10-21 17:13:31 +03007270 }
Nick Coghland78448e2016-07-30 16:26:03 +10007271 else
7272 Py_DECREF(tmp);
7273 }
Serhiy Storchaka9ec07722016-11-29 09:54:17 +02007274 else if (PyErr_Occurred()) {
7275 Py_DECREF(names_to_set);
Serhiy Storchakaafd02a42016-09-21 15:54:59 +03007276 return -1;
Serhiy Storchaka9ec07722016-11-29 09:54:17 +02007277 }
Nick Coghland78448e2016-07-30 16:26:03 +10007278 }
7279
Serhiy Storchaka9ec07722016-11-29 09:54:17 +02007280 Py_DECREF(names_to_set);
Nick Coghland78448e2016-07-30 16:26:03 +10007281 return 0;
7282}
7283
7284/* Call __init_subclass__ on the parent of a newly generated type */
7285static int
7286init_subclass(PyTypeObject *type, PyObject *kwds)
7287{
Victor Stinner463b86a2016-08-22 23:33:13 +02007288 PyObject *super, *func, *result;
7289 PyObject *args[2] = {(PyObject *)type, (PyObject *)type};
Nick Coghland78448e2016-07-30 16:26:03 +10007290
Victor Stinner463b86a2016-08-22 23:33:13 +02007291 super = _PyObject_FastCall((PyObject *)&PySuper_Type, args, 2);
7292 if (super == NULL) {
Nick Coghland78448e2016-07-30 16:26:03 +10007293 return -1;
Victor Stinner253021d2016-08-20 02:37:41 +02007294 }
7295
Victor Stinner463b86a2016-08-22 23:33:13 +02007296 func = _PyObject_GetAttrId(super, &PyId___init_subclass__);
7297 Py_DECREF(super);
7298 if (func == NULL) {
Nick Coghland78448e2016-07-30 16:26:03 +10007299 return -1;
Victor Stinner463b86a2016-08-22 23:33:13 +02007300 }
Nick Coghland78448e2016-07-30 16:26:03 +10007301
Victor Stinner463b86a2016-08-22 23:33:13 +02007302
7303 result = _PyObject_FastCallDict(func, NULL, 0, kwds);
7304 Py_DECREF(func);
7305 if (result == NULL) {
7306 return -1;
7307 }
7308
7309 Py_DECREF(result);
Nick Coghland78448e2016-07-30 16:26:03 +10007310 return 0;
7311}
7312
Guido van Rossum8d24ee92003-03-24 23:49:49 +00007313/* recurse_down_subclasses() and update_subclasses() are mutually
7314 recursive functions to call a callback for all subclasses,
7315 but refraining from recursing into subclasses that define 'name'. */
7316
7317static int
7318update_subclasses(PyTypeObject *type, PyObject *name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007319 update_callback callback, void *data)
Guido van Rossum8d24ee92003-03-24 23:49:49 +00007320{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007321 if (callback(type, data) < 0)
7322 return -1;
7323 return recurse_down_subclasses(type, name, callback, data);
Guido van Rossum8d24ee92003-03-24 23:49:49 +00007324}
7325
7326static int
7327recurse_down_subclasses(PyTypeObject *type, PyObject *name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007328 update_callback callback, void *data)
Guido van Rossum8d24ee92003-03-24 23:49:49 +00007329{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007330 PyTypeObject *subclass;
7331 PyObject *ref, *subclasses, *dict;
Antoine Pitrou84745ab2013-10-29 21:31:25 +01007332 Py_ssize_t i;
Guido van Rossum8d24ee92003-03-24 23:49:49 +00007333
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007334 subclasses = type->tp_subclasses;
7335 if (subclasses == NULL)
7336 return 0;
Antoine Pitrou84745ab2013-10-29 21:31:25 +01007337 assert(PyDict_CheckExact(subclasses));
7338 i = 0;
7339 while (PyDict_Next(subclasses, &i, NULL, &ref)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007340 assert(PyWeakref_CheckRef(ref));
7341 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
7342 assert(subclass != NULL);
7343 if ((PyObject *)subclass == Py_None)
7344 continue;
7345 assert(PyType_Check(subclass));
7346 /* Avoid recursing down into unaffected classes */
7347 dict = subclass->tp_dict;
7348 if (dict != NULL && PyDict_Check(dict) &&
7349 PyDict_GetItem(dict, name) != NULL)
7350 continue;
7351 if (update_subclasses(subclass, name, callback, data) < 0)
7352 return -1;
7353 }
7354 return 0;
Guido van Rossum8d24ee92003-03-24 23:49:49 +00007355}
7356
Guido van Rossum6d204072001-10-21 00:44:31 +00007357/* This function is called by PyType_Ready() to populate the type's
7358 dictionary with method descriptors for function slots. For each
Guido van Rossum09638c12002-06-13 19:17:46 +00007359 function slot (like tp_repr) that's defined in the type, one or more
7360 corresponding descriptors are added in the type's tp_dict dictionary
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007361 under the appropriate name (like __repr__). Some function slots
Guido van Rossum09638c12002-06-13 19:17:46 +00007362 cause more than one descriptor to be added (for example, the nb_add
7363 slot adds both __add__ and __radd__ descriptors) and some function
7364 slots compete for the same descriptor (for example both sq_item and
7365 mp_subscript generate a __getitem__ descriptor).
7366
Ezio Melotti13925002011-03-16 11:05:33 +02007367 In the latter case, the first slotdef entry encountered wins. Since
Tim Petersbf9b2442003-03-23 05:35:36 +00007368 slotdef entries are sorted by the offset of the slot in the
Guido van Rossume5c691a2003-03-07 15:13:17 +00007369 PyHeapTypeObject, this gives us some control over disambiguating
Guido van Rossum8d24ee92003-03-24 23:49:49 +00007370 between competing slots: the members of PyHeapTypeObject are listed
7371 from most general to least general, so the most general slot is
7372 preferred. In particular, because as_mapping comes before as_sequence,
7373 for a type that defines both mp_subscript and sq_item, mp_subscript
7374 wins.
Guido van Rossum09638c12002-06-13 19:17:46 +00007375
7376 This only adds new descriptors and doesn't overwrite entries in
7377 tp_dict that were previously defined. The descriptors contain a
7378 reference to the C function they must call, so that it's safe if they
7379 are copied into a subtype's __dict__ and the subtype has a different
7380 C function in its slot -- calling the method defined by the
7381 descriptor will call the C function that was used to create it,
7382 rather than the C function present in the slot when it is called.
7383 (This is important because a subtype may have a C function in the
7384 slot that calls the method from the dictionary, and we want to avoid
7385 infinite recursion here.) */
Guido van Rossum6d204072001-10-21 00:44:31 +00007386
7387static int
7388add_operators(PyTypeObject *type)
7389{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007390 PyObject *dict = type->tp_dict;
7391 slotdef *p;
7392 PyObject *descr;
7393 void **ptr;
Guido van Rossum6d204072001-10-21 00:44:31 +00007394
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007395 init_slotdefs();
7396 for (p = slotdefs; p->name; p++) {
7397 if (p->wrapper == NULL)
7398 continue;
7399 ptr = slotptr(type, p->offset);
7400 if (!ptr || !*ptr)
7401 continue;
7402 if (PyDict_GetItem(dict, p->name_strobj))
7403 continue;
Trent Nelsonab02db22012-09-18 21:58:03 -04007404 if (*ptr == (void *)PyObject_HashNotImplemented) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007405 /* Classes may prevent the inheritance of the tp_hash
7406 slot by storing PyObject_HashNotImplemented in it. Make it
7407 visible as a None value for the __hash__ attribute. */
7408 if (PyDict_SetItem(dict, p->name_strobj, Py_None) < 0)
7409 return -1;
7410 }
7411 else {
7412 descr = PyDescr_NewWrapper(type, p, *ptr);
7413 if (descr == NULL)
7414 return -1;
Benjamin Peterson27007dc2016-07-06 23:26:32 -07007415 if (PyDict_SetItem(dict, p->name_strobj, descr) < 0) {
7416 Py_DECREF(descr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007417 return -1;
Benjamin Peterson27007dc2016-07-06 23:26:32 -07007418 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007419 Py_DECREF(descr);
7420 }
7421 }
7422 if (type->tp_new != NULL) {
7423 if (add_tp_new_wrapper(type) < 0)
7424 return -1;
7425 }
7426 return 0;
Guido van Rossum6d204072001-10-21 00:44:31 +00007427}
7428
Guido van Rossum705f0f52001-08-24 16:47:00 +00007429
7430/* Cooperative 'super' */
7431
7432typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007433 PyObject_HEAD
7434 PyTypeObject *type;
7435 PyObject *obj;
7436 PyTypeObject *obj_type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00007437} superobject;
7438
Guido van Rossum6f799372001-09-20 20:46:19 +00007439static PyMemberDef super_members[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007440 {"__thisclass__", T_OBJECT, offsetof(superobject, type), READONLY,
7441 "the class invoking super()"},
7442 {"__self__", T_OBJECT, offsetof(superobject, obj), READONLY,
7443 "the instance invoking super(); may be None"},
7444 {"__self_class__", T_OBJECT, offsetof(superobject, obj_type), READONLY,
7445 "the type of the instance invoking super(); may be None"},
7446 {0}
Guido van Rossum41eb14d2001-08-30 23:13:11 +00007447};
7448
Guido van Rossum705f0f52001-08-24 16:47:00 +00007449static void
7450super_dealloc(PyObject *self)
7451{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007452 superobject *su = (superobject *)self;
Guido van Rossum705f0f52001-08-24 16:47:00 +00007453
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007454 _PyObject_GC_UNTRACK(self);
7455 Py_XDECREF(su->obj);
7456 Py_XDECREF(su->type);
7457 Py_XDECREF(su->obj_type);
7458 Py_TYPE(self)->tp_free(self);
Guido van Rossum705f0f52001-08-24 16:47:00 +00007459}
7460
7461static PyObject *
Guido van Rossum41eb14d2001-08-30 23:13:11 +00007462super_repr(PyObject *self)
7463{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007464 superobject *su = (superobject *)self;
Guido van Rossum41eb14d2001-08-30 23:13:11 +00007465
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007466 if (su->obj_type)
7467 return PyUnicode_FromFormat(
7468 "<super: <class '%s'>, <%s object>>",
7469 su->type ? su->type->tp_name : "NULL",
7470 su->obj_type->tp_name);
7471 else
7472 return PyUnicode_FromFormat(
7473 "<super: <class '%s'>, NULL>",
7474 su->type ? su->type->tp_name : "NULL");
Guido van Rossum41eb14d2001-08-30 23:13:11 +00007475}
7476
7477static PyObject *
Guido van Rossum705f0f52001-08-24 16:47:00 +00007478super_getattro(PyObject *self, PyObject *name)
7479{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007480 superobject *su = (superobject *)self;
Benjamin Peterson104b9e02015-02-05 22:29:14 -05007481 PyTypeObject *starttype;
7482 PyObject *mro;
7483 Py_ssize_t i, n;
Guido van Rossum705f0f52001-08-24 16:47:00 +00007484
Benjamin Peterson104b9e02015-02-05 22:29:14 -05007485 starttype = su->obj_type;
7486 if (starttype == NULL)
7487 goto skip;
7488
7489 /* We want __class__ to return the class of the super object
7490 (i.e. super, or a subclass), not the class of su->obj. */
7491 if (PyUnicode_Check(name) &&
7492 PyUnicode_GET_LENGTH(name) == 9 &&
Serhiy Storchakaf5894dd2016-11-16 15:40:39 +02007493 _PyUnicode_EqualToASCIIId(name, &PyId___class__))
Benjamin Peterson104b9e02015-02-05 22:29:14 -05007494 goto skip;
7495
7496 mro = starttype->tp_mro;
7497 if (mro == NULL)
7498 goto skip;
7499
7500 assert(PyTuple_Check(mro));
7501 n = PyTuple_GET_SIZE(mro);
7502
7503 /* No need to check the last one: it's gonna be skipped anyway. */
7504 for (i = 0; i+1 < n; i++) {
7505 if ((PyObject *)(su->type) == PyTuple_GET_ITEM(mro, i))
7506 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007507 }
Benjamin Peterson104b9e02015-02-05 22:29:14 -05007508 i++; /* skip su->type (if any) */
7509 if (i >= n)
7510 goto skip;
Guido van Rossum76ba09f2003-04-16 19:40:58 +00007511
Benjamin Peterson104b9e02015-02-05 22:29:14 -05007512 /* keep a strong reference to mro because starttype->tp_mro can be
7513 replaced during PyDict_GetItem(dict, name) */
7514 Py_INCREF(mro);
7515 do {
7516 PyObject *res, *tmp, *dict;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007517 descrgetfunc f;
Guido van Rossum705f0f52001-08-24 16:47:00 +00007518
Benjamin Peterson104b9e02015-02-05 22:29:14 -05007519 tmp = PyTuple_GET_ITEM(mro, i);
7520 assert(PyType_Check(tmp));
Guido van Rossum155db9a2002-04-02 17:53:47 +00007521
Benjamin Peterson104b9e02015-02-05 22:29:14 -05007522 dict = ((PyTypeObject *)tmp)->tp_dict;
7523 assert(dict != NULL && PyDict_Check(dict));
7524
7525 res = PyDict_GetItem(dict, name);
7526 if (res != NULL) {
7527 Py_INCREF(res);
7528
7529 f = Py_TYPE(res)->tp_descr_get;
7530 if (f != NULL) {
7531 tmp = f(res,
7532 /* Only pass 'obj' param if this is instance-mode super
7533 (See SF ID #743627) */
7534 (su->obj == (PyObject *)starttype) ? NULL : su->obj,
7535 (PyObject *)starttype);
7536 Py_DECREF(res);
7537 res = tmp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007538 }
Benjamin Peterson104b9e02015-02-05 22:29:14 -05007539
7540 Py_DECREF(mro);
7541 return res;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007542 }
Benjamin Peterson104b9e02015-02-05 22:29:14 -05007543
7544 i++;
7545 } while (i < n);
7546 Py_DECREF(mro);
7547
7548 skip:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007549 return PyObject_GenericGetAttr(self, name);
Guido van Rossum705f0f52001-08-24 16:47:00 +00007550}
7551
Guido van Rossuma89d10e2003-02-12 03:58:38 +00007552static PyTypeObject *
Guido van Rossum5b443c62001-12-03 15:38:28 +00007553supercheck(PyTypeObject *type, PyObject *obj)
7554{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007555 /* Check that a super() call makes sense. Return a type object.
Guido van Rossuma89d10e2003-02-12 03:58:38 +00007556
Florent Xiclunaaa6c1d22011-12-12 18:54:29 +01007557 obj can be a class, or an instance of one:
Guido van Rossuma89d10e2003-02-12 03:58:38 +00007558
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007559 - If it is a class, it must be a subclass of 'type'. This case is
7560 used for class methods; the return value is obj.
Guido van Rossuma89d10e2003-02-12 03:58:38 +00007561
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007562 - If it is an instance, it must be an instance of 'type'. This is
7563 the normal case; the return value is obj.__class__.
Guido van Rossuma89d10e2003-02-12 03:58:38 +00007564
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007565 But... when obj is an instance, we want to allow for the case where
7566 Py_TYPE(obj) is not a subclass of type, but obj.__class__ is!
7567 This will allow using super() with a proxy for obj.
7568 */
Guido van Rossuma89d10e2003-02-12 03:58:38 +00007569
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007570 /* Check for first bullet above (special case) */
7571 if (PyType_Check(obj) && PyType_IsSubtype((PyTypeObject *)obj, type)) {
7572 Py_INCREF(obj);
7573 return (PyTypeObject *)obj;
7574 }
Guido van Rossum8e80a722003-02-18 19:22:22 +00007575
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007576 /* Normal case */
7577 if (PyType_IsSubtype(Py_TYPE(obj), type)) {
7578 Py_INCREF(Py_TYPE(obj));
7579 return Py_TYPE(obj);
7580 }
7581 else {
7582 /* Try the slow way */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007583 PyObject *class_attr;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00007584
Martin v. Löwisbfc6d742011-10-13 20:03:57 +02007585 class_attr = _PyObject_GetAttrId(obj, &PyId___class__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007586 if (class_attr != NULL &&
7587 PyType_Check(class_attr) &&
7588 (PyTypeObject *)class_attr != Py_TYPE(obj))
7589 {
7590 int ok = PyType_IsSubtype(
7591 (PyTypeObject *)class_attr, type);
7592 if (ok)
7593 return (PyTypeObject *)class_attr;
7594 }
Guido van Rossuma89d10e2003-02-12 03:58:38 +00007595
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007596 if (class_attr == NULL)
7597 PyErr_Clear();
7598 else
7599 Py_DECREF(class_attr);
7600 }
Guido van Rossuma89d10e2003-02-12 03:58:38 +00007601
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007602 PyErr_SetString(PyExc_TypeError,
7603 "super(type, obj): "
7604 "obj must be an instance or subtype of type");
7605 return NULL;
Guido van Rossum5b443c62001-12-03 15:38:28 +00007606}
7607
Guido van Rossum705f0f52001-08-24 16:47:00 +00007608static PyObject *
7609super_descr_get(PyObject *self, PyObject *obj, PyObject *type)
7610{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007611 superobject *su = (superobject *)self;
7612 superobject *newobj;
Guido van Rossum705f0f52001-08-24 16:47:00 +00007613
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007614 if (obj == NULL || obj == Py_None || su->obj != NULL) {
7615 /* Not binding to an object, or already bound */
7616 Py_INCREF(self);
7617 return self;
7618 }
7619 if (Py_TYPE(su) != &PySuper_Type)
7620 /* If su is an instance of a (strict) subclass of super,
7621 call its type */
7622 return PyObject_CallFunctionObjArgs((PyObject *)Py_TYPE(su),
7623 su->type, obj, NULL);
7624 else {
7625 /* Inline the common case */
7626 PyTypeObject *obj_type = supercheck(su->type, obj);
7627 if (obj_type == NULL)
7628 return NULL;
7629 newobj = (superobject *)PySuper_Type.tp_new(&PySuper_Type,
7630 NULL, NULL);
7631 if (newobj == NULL)
7632 return NULL;
7633 Py_INCREF(su->type);
7634 Py_INCREF(obj);
7635 newobj->type = su->type;
7636 newobj->obj = obj;
7637 newobj->obj_type = obj_type;
7638 return (PyObject *)newobj;
7639 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00007640}
7641
7642static int
7643super_init(PyObject *self, PyObject *args, PyObject *kwds)
7644{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007645 superobject *su = (superobject *)self;
7646 PyTypeObject *type = NULL;
7647 PyObject *obj = NULL;
7648 PyTypeObject *obj_type = NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00007649
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007650 if (!_PyArg_NoKeywords("super", kwds))
7651 return -1;
7652 if (!PyArg_ParseTuple(args, "|O!O:super", &PyType_Type, &type, &obj))
7653 return -1;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00007654
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007655 if (type == NULL) {
7656 /* Call super(), without args -- fill in from __class__
7657 and first local variable on the stack. */
Victor Stinner1c6970f2014-05-13 01:32:36 +02007658 PyFrameObject *f;
7659 PyCodeObject *co;
Victor Stinner0fcab4a2011-01-04 12:59:15 +00007660 Py_ssize_t i, n;
Victor Stinner1c6970f2014-05-13 01:32:36 +02007661 f = PyThreadState_GET()->frame;
7662 if (f == NULL) {
7663 PyErr_SetString(PyExc_RuntimeError,
7664 "super(): no current frame");
7665 return -1;
7666 }
7667 co = f->f_code;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007668 if (co == NULL) {
Benjamin Peterson6a42bd62012-09-01 23:04:38 -04007669 PyErr_SetString(PyExc_RuntimeError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007670 "super(): no code object");
7671 return -1;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00007672 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007673 if (co->co_argcount == 0) {
Benjamin Peterson6a42bd62012-09-01 23:04:38 -04007674 PyErr_SetString(PyExc_RuntimeError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007675 "super(): no arguments");
7676 return -1;
7677 }
7678 obj = f->f_localsplus[0];
Benjamin Peterson159ae412013-05-12 18:16:06 -05007679 if (obj == NULL && co->co_cell2arg) {
7680 /* The first argument might be a cell. */
7681 n = PyTuple_GET_SIZE(co->co_cellvars);
7682 for (i = 0; i < n; i++) {
7683 if (co->co_cell2arg[i] == 0) {
7684 PyObject *cell = f->f_localsplus[co->co_nlocals + i];
7685 assert(PyCell_Check(cell));
7686 obj = PyCell_GET(cell);
7687 break;
7688 }
7689 }
Guido van Rossum6832c812013-05-10 08:47:42 -07007690 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007691 if (obj == NULL) {
Benjamin Peterson6a42bd62012-09-01 23:04:38 -04007692 PyErr_SetString(PyExc_RuntimeError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007693 "super(): arg[0] deleted");
7694 return -1;
7695 }
7696 if (co->co_freevars == NULL)
7697 n = 0;
7698 else {
7699 assert(PyTuple_Check(co->co_freevars));
7700 n = PyTuple_GET_SIZE(co->co_freevars);
7701 }
7702 for (i = 0; i < n; i++) {
7703 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
7704 assert(PyUnicode_Check(name));
Serhiy Storchakaf5894dd2016-11-16 15:40:39 +02007705 if (_PyUnicode_EqualToASCIIId(name, &PyId___class__)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007706 Py_ssize_t index = co->co_nlocals +
7707 PyTuple_GET_SIZE(co->co_cellvars) + i;
7708 PyObject *cell = f->f_localsplus[index];
7709 if (cell == NULL || !PyCell_Check(cell)) {
Benjamin Peterson6a42bd62012-09-01 23:04:38 -04007710 PyErr_SetString(PyExc_RuntimeError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007711 "super(): bad __class__ cell");
7712 return -1;
7713 }
7714 type = (PyTypeObject *) PyCell_GET(cell);
7715 if (type == NULL) {
Benjamin Peterson6a42bd62012-09-01 23:04:38 -04007716 PyErr_SetString(PyExc_RuntimeError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007717 "super(): empty __class__ cell");
7718 return -1;
7719 }
7720 if (!PyType_Check(type)) {
Benjamin Peterson6a42bd62012-09-01 23:04:38 -04007721 PyErr_Format(PyExc_RuntimeError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007722 "super(): __class__ is not a type (%s)",
7723 Py_TYPE(type)->tp_name);
7724 return -1;
7725 }
7726 break;
7727 }
7728 }
7729 if (type == NULL) {
Benjamin Peterson6a42bd62012-09-01 23:04:38 -04007730 PyErr_SetString(PyExc_RuntimeError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007731 "super(): __class__ cell not found");
7732 return -1;
7733 }
7734 }
Guido van Rossumcd16bf62007-06-13 18:07:49 +00007735
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007736 if (obj == Py_None)
7737 obj = NULL;
7738 if (obj != NULL) {
7739 obj_type = supercheck(type, obj);
7740 if (obj_type == NULL)
7741 return -1;
7742 Py_INCREF(obj);
7743 }
7744 Py_INCREF(type);
Serhiy Storchaka3d749762016-04-13 15:27:33 +03007745 Py_XSETREF(su->type, type);
7746 Py_XSETREF(su->obj, obj);
7747 Py_XSETREF(su->obj_type, obj_type);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007748 return 0;
Guido van Rossum705f0f52001-08-24 16:47:00 +00007749}
7750
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007751PyDoc_STRVAR(super_doc,
Guido van Rossumcd16bf62007-06-13 18:07:49 +00007752"super() -> same as super(__class__, <first argument>)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00007753"super(type) -> unbound super object\n"
7754"super(type, obj) -> bound super object; requires isinstance(obj, type)\n"
Guido van Rossume705ef12001-08-29 15:47:06 +00007755"super(type, type2) -> bound super object; requires issubclass(type2, type)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00007756"Typical use to call a cooperative superclass method:\n"
7757"class C(B):\n"
7758" def meth(self, arg):\n"
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007759" super().meth(arg)\n"
Guido van Rossumcd16bf62007-06-13 18:07:49 +00007760"This works for class methods too:\n"
7761"class C(B):\n"
7762" @classmethod\n"
7763" def cmeth(cls, arg):\n"
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007764" super().cmeth(arg)\n");
Guido van Rossum705f0f52001-08-24 16:47:00 +00007765
Guido van Rossum048eb752001-10-02 21:24:57 +00007766static int
7767super_traverse(PyObject *self, visitproc visit, void *arg)
7768{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007769 superobject *su = (superobject *)self;
Guido van Rossum048eb752001-10-02 21:24:57 +00007770
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007771 Py_VISIT(su->obj);
7772 Py_VISIT(su->type);
7773 Py_VISIT(su->obj_type);
Guido van Rossum048eb752001-10-02 21:24:57 +00007774
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007775 return 0;
Guido van Rossum048eb752001-10-02 21:24:57 +00007776}
7777
Guido van Rossum705f0f52001-08-24 16:47:00 +00007778PyTypeObject PySuper_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007779 PyVarObject_HEAD_INIT(&PyType_Type, 0)
7780 "super", /* tp_name */
7781 sizeof(superobject), /* tp_basicsize */
7782 0, /* tp_itemsize */
7783 /* methods */
7784 super_dealloc, /* tp_dealloc */
7785 0, /* tp_print */
7786 0, /* tp_getattr */
7787 0, /* tp_setattr */
7788 0, /* tp_reserved */
7789 super_repr, /* tp_repr */
7790 0, /* tp_as_number */
7791 0, /* tp_as_sequence */
7792 0, /* tp_as_mapping */
7793 0, /* tp_hash */
7794 0, /* tp_call */
7795 0, /* tp_str */
7796 super_getattro, /* tp_getattro */
7797 0, /* tp_setattro */
7798 0, /* tp_as_buffer */
7799 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
7800 Py_TPFLAGS_BASETYPE, /* tp_flags */
7801 super_doc, /* tp_doc */
7802 super_traverse, /* tp_traverse */
7803 0, /* tp_clear */
7804 0, /* tp_richcompare */
7805 0, /* tp_weaklistoffset */
7806 0, /* tp_iter */
7807 0, /* tp_iternext */
7808 0, /* tp_methods */
7809 super_members, /* tp_members */
7810 0, /* tp_getset */
7811 0, /* tp_base */
7812 0, /* tp_dict */
7813 super_descr_get, /* tp_descr_get */
7814 0, /* tp_descr_set */
7815 0, /* tp_dictoffset */
7816 super_init, /* tp_init */
7817 PyType_GenericAlloc, /* tp_alloc */
7818 PyType_GenericNew, /* tp_new */
7819 PyObject_GC_Del, /* tp_free */
Guido van Rossum705f0f52001-08-24 16:47:00 +00007820};