blob: 4c3909c098c411a5c5e86bdccf438d2b164bcaaa [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"
Victor Stinnerbcda8f12018-11-21 22:27:47 +01004#include "pycore_object.h"
Victor Stinner621cebe2018-11-12 16:53:38 +01005#include "pycore_pystate.h"
Guido van Rossumcd16bf62007-06-13 18:07:49 +00006#include "frameobject.h"
Tim Peters6d6c1a32001-08-02 04:15:00 +00007#include "structmember.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00008
Guido van Rossum9923ffe2002-06-04 19:52:53 +00009#include <ctype.h>
10
Serhiy Storchaka5c643a02017-03-19 08:46:44 +020011/*[clinic input]
12class type "PyTypeObject *" "&PyType_Type"
13class object "PyObject *" "&PyBaseObject_Type"
14[clinic start generated code]*/
15/*[clinic end generated code: output=da39a3ee5e6b4b0d input=4b94608d231c434b]*/
16
17#include "clinic/typeobject.c.h"
Christian Heimesa62da1d2008-01-12 19:39:10 +000018
19/* Support type attribute cache */
20
21/* The cache can keep references to the names alive for longer than
22 they normally would. This is why the maximum size is limited to
23 MCACHE_MAX_ATTR_SIZE, since it might be a problem if very large
24 strings are used as attribute names. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000025#define MCACHE_MAX_ATTR_SIZE 100
Antoine Pitrou2a40e362014-11-15 00:56:27 +010026#define MCACHE_SIZE_EXP 12
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000027#define MCACHE_HASH(version, name_hash) \
Antoine Pitrou2a40e362014-11-15 00:56:27 +010028 (((unsigned int)(version) ^ (unsigned int)(name_hash)) \
29 & ((1 << MCACHE_SIZE_EXP) - 1))
30
Christian Heimesa62da1d2008-01-12 19:39:10 +000031#define MCACHE_HASH_METHOD(type, name) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000032 MCACHE_HASH((type)->tp_version_tag, \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020033 ((PyASCIIObject *)(name))->hash)
Serhiy Storchakae3b2b4b2017-09-08 09:58:51 +030034#define MCACHE_CACHEABLE_NAME(name) \
35 PyUnicode_CheckExact(name) && \
36 PyUnicode_IS_READY(name) && \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020037 PyUnicode_GET_LENGTH(name) <= MCACHE_MAX_ATTR_SIZE
Christian Heimesa62da1d2008-01-12 19:39:10 +000038
39struct method_cache_entry {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000040 unsigned int version;
41 PyObject *name; /* reference to exactly a str or None */
42 PyObject *value; /* borrowed */
Christian Heimesa62da1d2008-01-12 19:39:10 +000043};
44
45static struct method_cache_entry method_cache[1 << MCACHE_SIZE_EXP];
46static unsigned int next_version_tag = 0;
Christian Heimes26855632008-01-27 23:50:43 +000047
Antoine Pitrou2a40e362014-11-15 00:56:27 +010048#define MCACHE_STATS 0
49
50#if MCACHE_STATS
51static size_t method_cache_hits = 0;
52static size_t method_cache_misses = 0;
53static size_t method_cache_collisions = 0;
54#endif
55
Martin v. Löwise75fc142013-11-07 18:46:53 +010056/* alphabetical order */
57_Py_IDENTIFIER(__abstractmethods__);
Martin v. Löwisbd928fe2011-10-14 10:20:37 +020058_Py_IDENTIFIER(__class__);
Serhiy Storchakace5b0e92018-01-05 00:21:41 +020059_Py_IDENTIFIER(__class_getitem__);
Martin v. Löwise75fc142013-11-07 18:46:53 +010060_Py_IDENTIFIER(__delitem__);
Victor Stinner3c1e4812012-03-26 22:10:51 +020061_Py_IDENTIFIER(__dict__);
62_Py_IDENTIFIER(__doc__);
Victor Stinner3c1e4812012-03-26 22:10:51 +020063_Py_IDENTIFIER(__getattribute__);
Martin v. Löwise75fc142013-11-07 18:46:53 +010064_Py_IDENTIFIER(__getitem__);
Victor Stinner3c1e4812012-03-26 22:10:51 +020065_Py_IDENTIFIER(__hash__);
Nick Coghland78448e2016-07-30 16:26:03 +100066_Py_IDENTIFIER(__init_subclass__);
Martin v. Löwise75fc142013-11-07 18:46:53 +010067_Py_IDENTIFIER(__len__);
Victor Stinner3c1e4812012-03-26 22:10:51 +020068_Py_IDENTIFIER(__module__);
69_Py_IDENTIFIER(__name__);
70_Py_IDENTIFIER(__new__);
Nick Coghland78448e2016-07-30 16:26:03 +100071_Py_IDENTIFIER(__set_name__);
Martin v. Löwise75fc142013-11-07 18:46:53 +010072_Py_IDENTIFIER(__setitem__);
Victor Stinnerbd303c12013-11-07 23:07:29 +010073_Py_IDENTIFIER(builtins);
Victor Stinner3c1e4812012-03-26 22:10:51 +020074
75static PyObject *
Martin v. Löwis9c564092012-06-23 23:20:45 +020076slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
77
Martin v. Löwis996b6712014-07-26 16:44:07 +020078static void
Victor Stinner331a7262014-07-27 16:11:30 +020079clear_slotdefs(void);
Martin v. Löwis996b6712014-07-26 16:44:07 +020080
Larry Hastings5c661892014-01-24 06:17:25 -080081/*
Larry Hastings2623c8c2014-02-08 22:15:29 -080082 * finds the beginning of the docstring's introspection signature.
Larry Hastings5c661892014-01-24 06:17:25 -080083 * if present, returns a pointer pointing to the first '('.
84 * otherwise returns NULL.
Larry Hastings2623c8c2014-02-08 22:15:29 -080085 *
86 * doesn't guarantee that the signature is valid, only that it
87 * has a valid prefix. (the signature must also pass skip_signature.)
Larry Hastings5c661892014-01-24 06:17:25 -080088 */
89static const char *
Larry Hastings2623c8c2014-02-08 22:15:29 -080090find_signature(const char *name, const char *doc)
Larry Hastings5c661892014-01-24 06:17:25 -080091{
Larry Hastings2623c8c2014-02-08 22:15:29 -080092 const char *dot;
93 size_t length;
94
95 if (!doc)
96 return NULL;
97
98 assert(name != NULL);
99
100 /* for dotted names like classes, only use the last component */
101 dot = strrchr(name, '.');
102 if (dot)
103 name = dot + 1;
104
105 length = strlen(name);
106 if (strncmp(doc, name, length))
107 return NULL;
108 doc += length;
109 if (*doc != '(')
110 return NULL;
111 return doc;
Larry Hastings5c661892014-01-24 06:17:25 -0800112}
113
Larry Hastings2623c8c2014-02-08 22:15:29 -0800114#define SIGNATURE_END_MARKER ")\n--\n\n"
115#define SIGNATURE_END_MARKER_LENGTH 6
Larry Hastings5c661892014-01-24 06:17:25 -0800116/*
Larry Hastings2623c8c2014-02-08 22:15:29 -0800117 * skips past the end of the docstring's instrospection signature.
118 * (assumes doc starts with a valid signature prefix.)
Larry Hastings5c661892014-01-24 06:17:25 -0800119 */
120static const char *
121skip_signature(const char *doc)
122{
Larry Hastings2623c8c2014-02-08 22:15:29 -0800123 while (*doc) {
124 if ((*doc == *SIGNATURE_END_MARKER) &&
125 !strncmp(doc, SIGNATURE_END_MARKER, SIGNATURE_END_MARKER_LENGTH))
126 return doc + SIGNATURE_END_MARKER_LENGTH;
127 if ((*doc == '\n') && (doc[1] == '\n'))
128 return NULL;
Larry Hastings5c661892014-01-24 06:17:25 -0800129 doc++;
Larry Hastings2623c8c2014-02-08 22:15:29 -0800130 }
131 return NULL;
Larry Hastings5c661892014-01-24 06:17:25 -0800132}
133
T. Woutersa00c3fd2017-03-31 09:14:41 -0700134#ifndef NDEBUG
Victor Stinnerbda5a2b2017-01-25 23:33:27 +0100135static int
136_PyType_CheckConsistency(PyTypeObject *type)
137{
Victor Stinner50fe3f82018-10-26 18:47:15 +0200138#define ASSERT(expr) _PyObject_ASSERT((PyObject *)type, (expr))
139
Victor Stinnerbda5a2b2017-01-25 23:33:27 +0100140 if (!(type->tp_flags & Py_TPFLAGS_READY)) {
141 /* don't check types before PyType_Ready() */
142 return 1;
143 }
144
Victor Stinner50fe3f82018-10-26 18:47:15 +0200145 ASSERT(!(type->tp_flags & Py_TPFLAGS_READYING));
146 ASSERT(type->tp_mro != NULL && PyTuple_Check(type->tp_mro));
147 ASSERT(type->tp_dict != NULL);
Victor Stinnerbda5a2b2017-01-25 23:33:27 +0100148 return 1;
Victor Stinner50fe3f82018-10-26 18:47:15 +0200149
150#undef ASSERT
Victor Stinnerbda5a2b2017-01-25 23:33:27 +0100151}
152#endif
153
Larry Hastings5c661892014-01-24 06:17:25 -0800154static const char *
Larry Hastings2623c8c2014-02-08 22:15:29 -0800155_PyType_DocWithoutSignature(const char *name, const char *internal_doc)
Larry Hastings5c661892014-01-24 06:17:25 -0800156{
Larry Hastings2623c8c2014-02-08 22:15:29 -0800157 const char *doc = find_signature(name, internal_doc);
Larry Hastings5c661892014-01-24 06:17:25 -0800158
Larry Hastings2623c8c2014-02-08 22:15:29 -0800159 if (doc) {
160 doc = skip_signature(doc);
161 if (doc)
162 return doc;
163 }
Larry Hastings5c661892014-01-24 06:17:25 -0800164 return internal_doc;
165}
166
167PyObject *
Larry Hastings2623c8c2014-02-08 22:15:29 -0800168_PyType_GetDocFromInternalDoc(const char *name, const char *internal_doc)
Larry Hastings5c661892014-01-24 06:17:25 -0800169{
Larry Hastings2623c8c2014-02-08 22:15:29 -0800170 const char *doc = _PyType_DocWithoutSignature(name, internal_doc);
Larry Hastings5c661892014-01-24 06:17:25 -0800171
Zachary Ware8ef887c2015-04-13 18:22:35 -0500172 if (!doc || *doc == '\0') {
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200173 Py_RETURN_NONE;
Larry Hastings5c661892014-01-24 06:17:25 -0800174 }
175
176 return PyUnicode_FromString(doc);
177}
178
179PyObject *
Larry Hastings2623c8c2014-02-08 22:15:29 -0800180_PyType_GetTextSignatureFromInternalDoc(const char *name, const char *internal_doc)
Larry Hastings5c661892014-01-24 06:17:25 -0800181{
Larry Hastings2623c8c2014-02-08 22:15:29 -0800182 const char *start = find_signature(name, internal_doc);
183 const char *end;
Larry Hastings5c661892014-01-24 06:17:25 -0800184
Larry Hastings2623c8c2014-02-08 22:15:29 -0800185 if (start)
186 end = skip_signature(start);
187 else
188 end = NULL;
189 if (!end) {
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200190 Py_RETURN_NONE;
Larry Hastings5c661892014-01-24 06:17:25 -0800191 }
192
Larry Hastings2623c8c2014-02-08 22:15:29 -0800193 /* back "end" up until it points just past the final ')' */
194 end -= SIGNATURE_END_MARKER_LENGTH - 1;
195 assert((end - start) >= 2); /* should be "()" at least */
196 assert(end[-1] == ')');
197 assert(end[0] == '\n');
198 return PyUnicode_FromStringAndSize(start, end - start);
Larry Hastings5c661892014-01-24 06:17:25 -0800199}
200
Christian Heimes26855632008-01-27 23:50:43 +0000201unsigned int
202PyType_ClearCache(void)
203{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000204 Py_ssize_t i;
205 unsigned int cur_version_tag = next_version_tag - 1;
206
Antoine Pitrou2a40e362014-11-15 00:56:27 +0100207#if MCACHE_STATS
208 size_t total = method_cache_hits + method_cache_collisions + method_cache_misses;
209 fprintf(stderr, "-- Method cache hits = %zd (%d%%)\n",
210 method_cache_hits, (int) (100.0 * method_cache_hits / total));
211 fprintf(stderr, "-- Method cache true misses = %zd (%d%%)\n",
212 method_cache_misses, (int) (100.0 * method_cache_misses / total));
213 fprintf(stderr, "-- Method cache collisions = %zd (%d%%)\n",
214 method_cache_collisions, (int) (100.0 * method_cache_collisions / total));
Victor Stinner8c663fd2017-11-08 14:44:44 -0800215 fprintf(stderr, "-- Method cache size = %zd KiB\n",
Antoine Pitrou2a40e362014-11-15 00:56:27 +0100216 sizeof(method_cache) / 1024);
217#endif
218
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000219 for (i = 0; i < (1 << MCACHE_SIZE_EXP); i++) {
220 method_cache[i].version = 0;
221 Py_CLEAR(method_cache[i].name);
222 method_cache[i].value = NULL;
223 }
224 next_version_tag = 0;
225 /* mark all version tags as invalid */
226 PyType_Modified(&PyBaseObject_Type);
227 return cur_version_tag;
Christian Heimes26855632008-01-27 23:50:43 +0000228}
Christian Heimesa62da1d2008-01-12 19:39:10 +0000229
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000230void
Antoine Pitrou957a23b2013-05-04 20:45:02 +0200231_PyType_Fini(void)
232{
233 PyType_ClearCache();
Martin v. Löwis996b6712014-07-26 16:44:07 +0200234 clear_slotdefs();
Antoine Pitrou957a23b2013-05-04 20:45:02 +0200235}
236
237void
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000238PyType_Modified(PyTypeObject *type)
Christian Heimesa62da1d2008-01-12 19:39:10 +0000239{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000240 /* Invalidate any cached data for the specified type and all
241 subclasses. This function is called after the base
242 classes, mro, or attributes of the type are altered.
Christian Heimesa62da1d2008-01-12 19:39:10 +0000243
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000244 Invariants:
Christian Heimesa62da1d2008-01-12 19:39:10 +0000245
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000246 - Py_TPFLAGS_VALID_VERSION_TAG is never set if
247 Py_TPFLAGS_HAVE_VERSION_TAG is not set (e.g. on type
248 objects coming from non-recompiled extension modules)
Christian Heimesa62da1d2008-01-12 19:39:10 +0000249
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000250 - before Py_TPFLAGS_VALID_VERSION_TAG can be set on a type,
251 it must first be set on all super types.
Christian Heimesa62da1d2008-01-12 19:39:10 +0000252
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000253 This function clears the Py_TPFLAGS_VALID_VERSION_TAG of a
254 type (so it must first clear it on all subclasses). The
255 tp_version_tag value is meaningless unless this flag is set.
256 We don't assign new version tags eagerly, but only as
257 needed.
258 */
259 PyObject *raw, *ref;
Antoine Pitrou84745ab2013-10-29 21:31:25 +0100260 Py_ssize_t i;
Christian Heimesa62da1d2008-01-12 19:39:10 +0000261
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000262 if (!PyType_HasFeature(type, Py_TPFLAGS_VALID_VERSION_TAG))
263 return;
Christian Heimesa62da1d2008-01-12 19:39:10 +0000264
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000265 raw = type->tp_subclasses;
266 if (raw != NULL) {
Antoine Pitrou84745ab2013-10-29 21:31:25 +0100267 assert(PyDict_CheckExact(raw));
268 i = 0;
269 while (PyDict_Next(raw, &i, NULL, &ref)) {
270 assert(PyWeakref_CheckRef(ref));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000271 ref = PyWeakref_GET_OBJECT(ref);
272 if (ref != Py_None) {
273 PyType_Modified((PyTypeObject *)ref);
274 }
275 }
276 }
277 type->tp_flags &= ~Py_TPFLAGS_VALID_VERSION_TAG;
Christian Heimesa62da1d2008-01-12 19:39:10 +0000278}
279
280static void
281type_mro_modified(PyTypeObject *type, PyObject *bases) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000282 /*
Florent Xiclunaaa6c1d22011-12-12 18:54:29 +0100283 Check that all base classes or elements of the MRO of type are
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000284 able to be cached. This function is called after the base
285 classes or mro of the type are altered.
Christian Heimesa62da1d2008-01-12 19:39:10 +0000286
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000287 Unset HAVE_VERSION_TAG and VALID_VERSION_TAG if the type
Florent Xiclunaaa6c1d22011-12-12 18:54:29 +0100288 has a custom MRO that includes a type which is not officially
289 super type.
Christian Heimesa62da1d2008-01-12 19:39:10 +0000290
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000291 Called from mro_internal, which will subsequently be called on
292 each subclass when their mro is recursively updated.
293 */
294 Py_ssize_t i, n;
295 int clear = 0;
Christian Heimesa62da1d2008-01-12 19:39:10 +0000296
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000297 if (!PyType_HasFeature(type, Py_TPFLAGS_HAVE_VERSION_TAG))
298 return;
Christian Heimesa62da1d2008-01-12 19:39:10 +0000299
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000300 n = PyTuple_GET_SIZE(bases);
301 for (i = 0; i < n; i++) {
302 PyObject *b = PyTuple_GET_ITEM(bases, i);
303 PyTypeObject *cls;
Christian Heimesa62da1d2008-01-12 19:39:10 +0000304
Florent Xiclunaaa6c1d22011-12-12 18:54:29 +0100305 assert(PyType_Check(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000306 cls = (PyTypeObject *)b;
Christian Heimesa62da1d2008-01-12 19:39:10 +0000307
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000308 if (!PyType_HasFeature(cls, Py_TPFLAGS_HAVE_VERSION_TAG) ||
309 !PyType_IsSubtype(type, cls)) {
310 clear = 1;
311 break;
312 }
313 }
Christian Heimesa62da1d2008-01-12 19:39:10 +0000314
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000315 if (clear)
316 type->tp_flags &= ~(Py_TPFLAGS_HAVE_VERSION_TAG|
317 Py_TPFLAGS_VALID_VERSION_TAG);
Christian Heimesa62da1d2008-01-12 19:39:10 +0000318}
319
320static int
321assign_version_tag(PyTypeObject *type)
322{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000323 /* Ensure that the tp_version_tag is valid and set
324 Py_TPFLAGS_VALID_VERSION_TAG. To respect the invariant, this
325 must first be done on all super classes. Return 0 if this
326 cannot be done, 1 if Py_TPFLAGS_VALID_VERSION_TAG.
327 */
328 Py_ssize_t i, n;
329 PyObject *bases;
Christian Heimesa62da1d2008-01-12 19:39:10 +0000330
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000331 if (PyType_HasFeature(type, Py_TPFLAGS_VALID_VERSION_TAG))
332 return 1;
333 if (!PyType_HasFeature(type, Py_TPFLAGS_HAVE_VERSION_TAG))
334 return 0;
335 if (!PyType_HasFeature(type, Py_TPFLAGS_READY))
336 return 0;
Christian Heimesa62da1d2008-01-12 19:39:10 +0000337
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000338 type->tp_version_tag = next_version_tag++;
339 /* for stress-testing: next_version_tag &= 0xFF; */
Christian Heimesa62da1d2008-01-12 19:39:10 +0000340
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000341 if (type->tp_version_tag == 0) {
342 /* wrap-around or just starting Python - clear the whole
343 cache by filling names with references to Py_None.
344 Values are also set to NULL for added protection, as they
345 are borrowed reference */
346 for (i = 0; i < (1 << MCACHE_SIZE_EXP); i++) {
347 method_cache[i].value = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000348 Py_INCREF(Py_None);
Serhiy Storchaka48842712016-04-06 09:45:48 +0300349 Py_XSETREF(method_cache[i].name, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000350 }
351 /* mark all version tags as invalid */
352 PyType_Modified(&PyBaseObject_Type);
353 return 1;
354 }
355 bases = type->tp_bases;
356 n = PyTuple_GET_SIZE(bases);
357 for (i = 0; i < n; i++) {
358 PyObject *b = PyTuple_GET_ITEM(bases, i);
359 assert(PyType_Check(b));
360 if (!assign_version_tag((PyTypeObject *)b))
361 return 0;
362 }
363 type->tp_flags |= Py_TPFLAGS_VALID_VERSION_TAG;
364 return 1;
Christian Heimesa62da1d2008-01-12 19:39:10 +0000365}
366
367
Guido van Rossum6f799372001-09-20 20:46:19 +0000368static PyMemberDef type_members[] = {
Benjamin Peterson0e102062010-08-25 23:13:17 +0000369 {"__basicsize__", T_PYSSIZET, offsetof(PyTypeObject,tp_basicsize),READONLY},
370 {"__itemsize__", T_PYSSIZET, offsetof(PyTypeObject, tp_itemsize), READONLY},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000371 {"__flags__", T_LONG, offsetof(PyTypeObject, tp_flags), READONLY},
372 {"__weakrefoffset__", T_LONG,
373 offsetof(PyTypeObject, tp_weaklistoffset), READONLY},
374 {"__base__", T_OBJECT, offsetof(PyTypeObject, tp_base), READONLY},
375 {"__dictoffset__", T_LONG,
376 offsetof(PyTypeObject, tp_dictoffset), READONLY},
377 {"__mro__", T_OBJECT, offsetof(PyTypeObject, tp_mro), READONLY},
378 {0}
Tim Peters6d6c1a32001-08-02 04:15:00 +0000379};
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000380
Benjamin Petersond9f23d22011-08-17 11:54:03 -0500381static int
382check_set_special_type_attr(PyTypeObject *type, PyObject *value, const char *name)
383{
384 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
385 PyErr_Format(PyExc_TypeError,
386 "can't set %s.%s", type->tp_name, name);
387 return 0;
388 }
389 if (!value) {
390 PyErr_Format(PyExc_TypeError,
391 "can't delete %s.%s", type->tp_name, name);
392 return 0;
393 }
394 return 1;
395}
396
Serhiy Storchaka4ab46d72017-09-17 21:11:04 +0300397const char *
398_PyType_Name(PyTypeObject *type)
399{
400 const char *s = strrchr(type->tp_name, '.');
401 if (s == NULL) {
402 s = type->tp_name;
403 }
404 else {
405 s++;
406 }
407 return s;
408}
409
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000410static PyObject *
Guido van Rossumc3542212001-08-16 09:18:56 +0000411type_name(PyTypeObject *type, void *context)
412{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000413 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
414 PyHeapTypeObject* et = (PyHeapTypeObject*)type;
Tim Petersea7f75d2002-12-07 21:39:16 +0000415
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000416 Py_INCREF(et->ht_name);
417 return et->ht_name;
418 }
419 else {
Serhiy Storchaka4ab46d72017-09-17 21:11:04 +0300420 return PyUnicode_FromString(_PyType_Name(type));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000421 }
Guido van Rossumc3542212001-08-16 09:18:56 +0000422}
423
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100424static PyObject *
425type_qualname(PyTypeObject *type, void *context)
426{
427 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
428 PyHeapTypeObject* et = (PyHeapTypeObject*)type;
429 Py_INCREF(et->ht_qualname);
430 return et->ht_qualname;
431 }
432 else {
Serhiy Storchaka4ab46d72017-09-17 21:11:04 +0300433 return PyUnicode_FromString(_PyType_Name(type));
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100434 }
435}
436
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000437static int
438type_set_name(PyTypeObject *type, PyObject *value, void *context)
439{
Serhiy Storchaka42bf8fc2015-12-30 21:40:49 +0200440 const char *tp_name;
441 Py_ssize_t name_size;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000442
Benjamin Petersond9f23d22011-08-17 11:54:03 -0500443 if (!check_set_special_type_attr(type, value, "__name__"))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000444 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000445 if (!PyUnicode_Check(value)) {
446 PyErr_Format(PyExc_TypeError,
447 "can only assign string to %s.__name__, not '%s'",
448 type->tp_name, Py_TYPE(value)->tp_name);
449 return -1;
450 }
Guido van Rossume845c0f2007-11-02 23:07:07 +0000451
Serhiy Storchaka42bf8fc2015-12-30 21:40:49 +0200452 tp_name = PyUnicode_AsUTF8AndSize(value, &name_size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000453 if (tp_name == NULL)
454 return -1;
Serhiy Storchaka42bf8fc2015-12-30 21:40:49 +0200455 if (strlen(tp_name) != (size_t)name_size) {
456 PyErr_SetString(PyExc_ValueError,
457 "type name must not contain null characters");
458 return -1;
459 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000460
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000461 type->tp_name = tp_name;
Serhiy Storchaka1ed017a2015-12-27 15:51:32 +0200462 Py_INCREF(value);
Serhiy Storchaka57a01d32016-04-10 18:05:40 +0300463 Py_SETREF(((PyHeapTypeObject*)type)->ht_name, value);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000464
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000465 return 0;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000466}
467
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100468static int
469type_set_qualname(PyTypeObject *type, PyObject *value, void *context)
470{
471 PyHeapTypeObject* et;
472
Benjamin Peterson2c05a2e2012-10-31 00:01:15 -0400473 if (!check_set_special_type_attr(type, value, "__qualname__"))
474 return -1;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100475 if (!PyUnicode_Check(value)) {
476 PyErr_Format(PyExc_TypeError,
477 "can only assign string to %s.__qualname__, not '%s'",
478 type->tp_name, Py_TYPE(value)->tp_name);
479 return -1;
480 }
481
482 et = (PyHeapTypeObject*)type;
483 Py_INCREF(value);
Serhiy Storchaka57a01d32016-04-10 18:05:40 +0300484 Py_SETREF(et->ht_qualname, value);
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100485 return 0;
486}
487
Guido van Rossumc3542212001-08-16 09:18:56 +0000488static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000489type_module(PyTypeObject *type, void *context)
Guido van Rossum29ca26e1995-01-07 11:58:15 +0000490{
Serhiy Storchaka7c19aff2016-09-10 00:53:02 +0300491 PyObject *mod;
Guido van Rossumc3542212001-08-16 09:18:56 +0000492
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000493 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
Serhiy Storchakaa24107b2019-02-25 17:59:46 +0200494 mod = _PyDict_GetItemIdWithError(type->tp_dict, &PyId___module__);
Serhiy Storchaka7c19aff2016-09-10 00:53:02 +0300495 if (mod == NULL) {
Serhiy Storchakaa24107b2019-02-25 17:59:46 +0200496 if (!PyErr_Occurred()) {
497 PyErr_Format(PyExc_AttributeError, "__module__");
498 }
Serhiy Storchaka7c19aff2016-09-10 00:53:02 +0300499 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000500 }
Serhiy Storchaka27ba8862016-05-25 16:14:55 +0300501 Py_INCREF(mod);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000502 }
503 else {
Serhiy Storchaka7c19aff2016-09-10 00:53:02 +0300504 const char *s = strrchr(type->tp_name, '.');
505 if (s != NULL) {
506 mod = PyUnicode_FromStringAndSize(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000507 type->tp_name, (Py_ssize_t)(s - type->tp_name));
Serhiy Storchaka7c19aff2016-09-10 00:53:02 +0300508 if (mod != NULL)
509 PyUnicode_InternInPlace(&mod);
510 }
511 else {
512 mod = _PyUnicode_FromId(&PyId_builtins);
513 Py_XINCREF(mod);
514 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000515 }
Serhiy Storchaka7c19aff2016-09-10 00:53:02 +0300516 return mod;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000517}
518
Guido van Rossum3926a632001-09-25 16:25:58 +0000519static int
520type_set_module(PyTypeObject *type, PyObject *value, void *context)
521{
Benjamin Petersond9f23d22011-08-17 11:54:03 -0500522 if (!check_set_special_type_attr(type, value, "__module__"))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000523 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000524
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000525 PyType_Modified(type);
Christian Heimesa62da1d2008-01-12 19:39:10 +0000526
Victor Stinner3c1e4812012-03-26 22:10:51 +0200527 return _PyDict_SetItemId(type->tp_dict, &PyId___module__, value);
Guido van Rossum3926a632001-09-25 16:25:58 +0000528}
529
Tim Peters6d6c1a32001-08-02 04:15:00 +0000530static PyObject *
Christian Heimes9e7f1d22008-02-28 12:27:11 +0000531type_abstractmethods(PyTypeObject *type, void *context)
532{
Benjamin Petersonaec5fd12010-10-02 00:03:31 +0000533 PyObject *mod = NULL;
Benjamin Peterson84060b82010-10-03 02:13:39 +0000534 /* type itself has an __abstractmethods__ descriptor (this). Don't return
535 that. */
Benjamin Petersonaec5fd12010-10-02 00:03:31 +0000536 if (type != &PyType_Type)
Serhiy Storchakaa24107b2019-02-25 17:59:46 +0200537 mod = _PyDict_GetItemIdWithError(type->tp_dict, &PyId___abstractmethods__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000538 if (!mod) {
Serhiy Storchakaa24107b2019-02-25 17:59:46 +0200539 if (!PyErr_Occurred()) {
540 PyObject *message = _PyUnicode_FromId(&PyId___abstractmethods__);
541 if (message)
542 PyErr_SetObject(PyExc_AttributeError, message);
543 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000544 return NULL;
545 }
Serhiy Storchaka27ba8862016-05-25 16:14:55 +0300546 Py_INCREF(mod);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000547 return mod;
Christian Heimes9e7f1d22008-02-28 12:27:11 +0000548}
549
550static int
551type_set_abstractmethods(PyTypeObject *type, PyObject *value, void *context)
552{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000553 /* __abstractmethods__ should only be set once on a type, in
554 abc.ABCMeta.__new__, so this function doesn't do anything
555 special to update subclasses.
556 */
Antoine Pitrou6f430e42012-08-15 23:18:25 +0200557 int abstract, res;
Benjamin Peterson477ba912011-01-12 15:34:01 +0000558 if (value != NULL) {
Antoine Pitrou6f430e42012-08-15 23:18:25 +0200559 abstract = PyObject_IsTrue(value);
560 if (abstract < 0)
561 return -1;
Victor Stinner3688aa92013-11-06 18:59:18 +0100562 res = _PyDict_SetItemId(type->tp_dict, &PyId___abstractmethods__, value);
Benjamin Peterson477ba912011-01-12 15:34:01 +0000563 }
564 else {
Antoine Pitrou6f430e42012-08-15 23:18:25 +0200565 abstract = 0;
Victor Stinner3688aa92013-11-06 18:59:18 +0100566 res = _PyDict_DelItemId(type->tp_dict, &PyId___abstractmethods__);
Benjamin Peterson477ba912011-01-12 15:34:01 +0000567 if (res && PyErr_ExceptionMatches(PyExc_KeyError)) {
Victor Stinner3688aa92013-11-06 18:59:18 +0100568 PyObject *message = _PyUnicode_FromId(&PyId___abstractmethods__);
569 if (message)
570 PyErr_SetObject(PyExc_AttributeError, message);
Benjamin Peterson477ba912011-01-12 15:34:01 +0000571 return -1;
572 }
573 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000574 if (res == 0) {
575 PyType_Modified(type);
Antoine Pitrou6f430e42012-08-15 23:18:25 +0200576 if (abstract)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000577 type->tp_flags |= Py_TPFLAGS_IS_ABSTRACT;
Antoine Pitrou6f430e42012-08-15 23:18:25 +0200578 else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000579 type->tp_flags &= ~Py_TPFLAGS_IS_ABSTRACT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000580 }
581 return res;
Christian Heimes9e7f1d22008-02-28 12:27:11 +0000582}
583
584static PyObject *
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000585type_get_bases(PyTypeObject *type, void *context)
586{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000587 Py_INCREF(type->tp_bases);
588 return type->tp_bases;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000589}
590
591static PyTypeObject *best_base(PyObject *);
Benjamin Peterson104b9e02015-02-05 22:29:14 -0500592static int mro_internal(PyTypeObject *, PyObject **);
Benjamin Peterson6cb526e2016-09-09 12:42:51 -0700593static int type_is_subtype_base_chain(PyTypeObject *, PyTypeObject *);
Serhiy Storchakaef1585e2015-12-25 20:01:53 +0200594static int compatible_for_assignment(PyTypeObject *, PyTypeObject *, const char *);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000595static int add_subclass(PyTypeObject*, PyTypeObject*);
Benjamin Peterson104b9e02015-02-05 22:29:14 -0500596static int add_all_subclasses(PyTypeObject *type, PyObject *bases);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000597static void remove_subclass(PyTypeObject *, PyTypeObject *);
Antoine Pitrou84745ab2013-10-29 21:31:25 +0100598static void remove_all_subclasses(PyTypeObject *type, PyObject *bases);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000599static void update_all_slots(PyTypeObject *);
600
Guido van Rossum8d24ee92003-03-24 23:49:49 +0000601typedef int (*update_callback)(PyTypeObject *, void *);
602static int update_subclasses(PyTypeObject *type, PyObject *name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000603 update_callback callback, void *data);
Guido van Rossum8d24ee92003-03-24 23:49:49 +0000604static int recurse_down_subclasses(PyTypeObject *type, PyObject *name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000605 update_callback callback, void *data);
Guido van Rossum8d24ee92003-03-24 23:49:49 +0000606
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000607static int
Benjamin Peterson104b9e02015-02-05 22:29:14 -0500608mro_hierarchy(PyTypeObject *type, PyObject *temp)
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000609{
Benjamin Peterson104b9e02015-02-05 22:29:14 -0500610 int res;
611 PyObject *new_mro, *old_mro;
612 PyObject *tuple;
613 PyObject *subclasses;
614 Py_ssize_t i, n;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000615
Benjamin Peterson104b9e02015-02-05 22:29:14 -0500616 res = mro_internal(type, &old_mro);
617 if (res <= 0)
618 /* error / reentrance */
619 return res;
620 new_mro = type->tp_mro;
Antoine Pitrou84745ab2013-10-29 21:31:25 +0100621
Benjamin Peterson104b9e02015-02-05 22:29:14 -0500622 if (old_mro != NULL)
623 tuple = PyTuple_Pack(3, type, new_mro, old_mro);
624 else
625 tuple = PyTuple_Pack(2, type, new_mro);
626
627 if (tuple != NULL)
628 res = PyList_Append(temp, tuple);
629 else
630 res = -1;
631 Py_XDECREF(tuple);
632
633 if (res < 0) {
634 type->tp_mro = old_mro;
635 Py_DECREF(new_mro);
636 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000637 }
Benjamin Peterson104b9e02015-02-05 22:29:14 -0500638 Py_XDECREF(old_mro);
639
640 /* Obtain a copy of subclasses list to iterate over.
641
642 Otherwise type->tp_subclasses might be altered
643 in the middle of the loop, for example, through a custom mro(),
644 by invoking type_set_bases on some subclass of the type
645 which in turn calls remove_subclass/add_subclass on this type.
646
647 Finally, this makes things simple avoiding the need to deal
648 with dictionary iterators and weak references.
649 */
Serhiy Storchaka5c643a02017-03-19 08:46:44 +0200650 subclasses = type___subclasses___impl(type);
Benjamin Peterson104b9e02015-02-05 22:29:14 -0500651 if (subclasses == NULL)
652 return -1;
653 n = PyList_GET_SIZE(subclasses);
654 for (i = 0; i < n; i++) {
655 PyTypeObject *subclass;
656 subclass = (PyTypeObject *)PyList_GET_ITEM(subclasses, i);
657 res = mro_hierarchy(subclass, temp);
658 if (res < 0)
659 break;
660 }
661 Py_DECREF(subclasses);
662
663 return res;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000664}
665
666static int
Benjamin Peterson104b9e02015-02-05 22:29:14 -0500667type_set_bases(PyTypeObject *type, PyObject *new_bases, void *context)
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000668{
Benjamin Peterson104b9e02015-02-05 22:29:14 -0500669 int res = 0;
670 PyObject *temp;
671 PyObject *old_bases;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000672 PyTypeObject *new_base, *old_base;
Benjamin Peterson104b9e02015-02-05 22:29:14 -0500673 Py_ssize_t i;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000674
Benjamin Peterson104b9e02015-02-05 22:29:14 -0500675 if (!check_set_special_type_attr(type, new_bases, "__bases__"))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000676 return -1;
Benjamin Peterson104b9e02015-02-05 22:29:14 -0500677 if (!PyTuple_Check(new_bases)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000678 PyErr_Format(PyExc_TypeError,
679 "can only assign tuple to %s.__bases__, not %s",
Benjamin Peterson104b9e02015-02-05 22:29:14 -0500680 type->tp_name, Py_TYPE(new_bases)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000681 return -1;
682 }
Benjamin Peterson104b9e02015-02-05 22:29:14 -0500683 if (PyTuple_GET_SIZE(new_bases) == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000684 PyErr_Format(PyExc_TypeError,
685 "can only assign non-empty tuple to %s.__bases__, not ()",
686 type->tp_name);
687 return -1;
688 }
Benjamin Peterson104b9e02015-02-05 22:29:14 -0500689 for (i = 0; i < PyTuple_GET_SIZE(new_bases); i++) {
690 PyObject *ob;
691 PyTypeObject *base;
692
693 ob = PyTuple_GET_ITEM(new_bases, i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000694 if (!PyType_Check(ob)) {
Benjamin Petersonb6af60c2012-04-01 18:49:54 -0400695 PyErr_Format(PyExc_TypeError,
Benjamin Peterson9ee601e2012-04-01 18:51:37 -0400696 "%s.__bases__ must be tuple of classes, not '%s'",
Benjamin Petersonb6af60c2012-04-01 18:49:54 -0400697 type->tp_name, Py_TYPE(ob)->tp_name);
698 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000699 }
Benjamin Peterson104b9e02015-02-05 22:29:14 -0500700
701 base = (PyTypeObject*)ob;
702 if (PyType_IsSubtype(base, type) ||
703 /* In case of reentering here again through a custom mro()
704 the above check is not enough since it relies on
705 base->tp_mro which would gonna be updated inside
706 mro_internal only upon returning from the mro().
707
708 However, base->tp_base has already been assigned (see
709 below), which in turn may cause an inheritance cycle
710 through tp_base chain. And this is definitely
711 not what you want to ever happen. */
712 (base->tp_mro != NULL && type_is_subtype_base_chain(base, type))) {
713
Benjamin Peterson3471bb62012-04-01 18:48:40 -0400714 PyErr_SetString(PyExc_TypeError,
715 "a __bases__ item causes an inheritance cycle");
716 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000717 }
718 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000719
Benjamin Peterson104b9e02015-02-05 22:29:14 -0500720 new_base = best_base(new_bases);
721 if (new_base == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000722 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000723
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000724 if (!compatible_for_assignment(type->tp_base, new_base, "__bases__"))
725 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000726
Benjamin Peterson104b9e02015-02-05 22:29:14 -0500727 Py_INCREF(new_bases);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000728 Py_INCREF(new_base);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000729
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000730 old_bases = type->tp_bases;
731 old_base = type->tp_base;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000732
Benjamin Peterson104b9e02015-02-05 22:29:14 -0500733 type->tp_bases = new_bases;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000734 type->tp_base = new_base;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000735
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000736 temp = PyList_New(0);
Benjamin Peterson104b9e02015-02-05 22:29:14 -0500737 if (temp == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000738 goto bail;
Benjamin Peterson104b9e02015-02-05 22:29:14 -0500739 if (mro_hierarchy(type, temp) < 0)
740 goto undo;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000741 Py_DECREF(temp);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000742
Benjamin Peterson104b9e02015-02-05 22:29:14 -0500743 /* Take no action in case if type->tp_bases has been replaced
744 through reentrance. */
745 if (type->tp_bases == new_bases) {
746 /* any base that was in __bases__ but now isn't, we
747 need to remove |type| from its tp_subclasses.
748 conversely, any class now in __bases__ that wasn't
749 needs to have |type| added to its subclasses. */
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000750
Benjamin Peterson104b9e02015-02-05 22:29:14 -0500751 /* for now, sod that: just remove from all old_bases,
752 add to all new_bases */
753 remove_all_subclasses(type, old_bases);
754 res = add_all_subclasses(type, new_bases);
755 update_all_slots(type);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000756 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000757
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000758 Py_DECREF(old_bases);
759 Py_DECREF(old_base);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000760
Victor Stinnerbda5a2b2017-01-25 23:33:27 +0100761 assert(_PyType_CheckConsistency(type));
Benjamin Peterson104b9e02015-02-05 22:29:14 -0500762 return res;
763
764 undo:
765 for (i = PyList_GET_SIZE(temp) - 1; i >= 0; i--) {
766 PyTypeObject *cls;
767 PyObject *new_mro, *old_mro = NULL;
768
769 PyArg_UnpackTuple(PyList_GET_ITEM(temp, i),
770 "", 2, 3, &cls, &new_mro, &old_mro);
771 /* Do not rollback if cls has a newer version of MRO. */
772 if (cls->tp_mro == new_mro) {
773 Py_XINCREF(old_mro);
774 cls->tp_mro = old_mro;
775 Py_DECREF(new_mro);
776 }
777 }
778 Py_DECREF(temp);
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000779
780 bail:
Benjamin Peterson104b9e02015-02-05 22:29:14 -0500781 if (type->tp_bases == new_bases) {
782 assert(type->tp_base == new_base);
Michael W. Hudsone723e452003-08-07 14:58:10 +0000783
Benjamin Peterson104b9e02015-02-05 22:29:14 -0500784 type->tp_bases = old_bases;
785 type->tp_base = old_base;
786
787 Py_DECREF(new_bases);
788 Py_DECREF(new_base);
789 }
790 else {
791 Py_DECREF(old_bases);
792 Py_DECREF(old_base);
793 }
Tim Petersea7f75d2002-12-07 21:39:16 +0000794
Victor Stinnerbda5a2b2017-01-25 23:33:27 +0100795 assert(_PyType_CheckConsistency(type));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000796 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000797}
798
799static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000800type_dict(PyTypeObject *type, void *context)
801{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000802 if (type->tp_dict == NULL) {
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200803 Py_RETURN_NONE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000804 }
805 return PyDictProxy_New(type->tp_dict);
Guido van Rossum29ca26e1995-01-07 11:58:15 +0000806}
807
Tim Peters24008312002-03-17 18:56:20 +0000808static PyObject *
809type_get_doc(PyTypeObject *type, void *context)
810{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000811 PyObject *result;
Larry Hastings5c661892014-01-24 06:17:25 -0800812 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE) && type->tp_doc != NULL) {
Larry Hastings2623c8c2014-02-08 22:15:29 -0800813 return _PyType_GetDocFromInternalDoc(type->tp_name, type->tp_doc);
Larry Hastings5c661892014-01-24 06:17:25 -0800814 }
Serhiy Storchakaa24107b2019-02-25 17:59:46 +0200815 result = _PyDict_GetItemIdWithError(type->tp_dict, &PyId___doc__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000816 if (result == NULL) {
Serhiy Storchakaa24107b2019-02-25 17:59:46 +0200817 if (!PyErr_Occurred()) {
818 result = Py_None;
819 Py_INCREF(result);
820 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000821 }
822 else if (Py_TYPE(result)->tp_descr_get) {
823 result = Py_TYPE(result)->tp_descr_get(result, NULL,
824 (PyObject *)type);
825 }
826 else {
827 Py_INCREF(result);
828 }
829 return result;
Tim Peters24008312002-03-17 18:56:20 +0000830}
831
Larry Hastings5c661892014-01-24 06:17:25 -0800832static PyObject *
833type_get_text_signature(PyTypeObject *type, void *context)
834{
Larry Hastings2623c8c2014-02-08 22:15:29 -0800835 return _PyType_GetTextSignatureFromInternalDoc(type->tp_name, type->tp_doc);
Larry Hastings5c661892014-01-24 06:17:25 -0800836}
837
Benjamin Peterson01fc6cd2011-08-17 12:03:47 -0500838static int
839type_set_doc(PyTypeObject *type, PyObject *value, void *context)
840{
841 if (!check_set_special_type_attr(type, value, "__doc__"))
842 return -1;
843 PyType_Modified(type);
Victor Stinner3c1e4812012-03-26 22:10:51 +0200844 return _PyDict_SetItemId(type->tp_dict, &PyId___doc__, value);
Benjamin Peterson01fc6cd2011-08-17 12:03:47 -0500845}
846
Serhiy Storchaka5c643a02017-03-19 08:46:44 +0200847/*[clinic input]
848type.__instancecheck__ -> bool
849
850 instance: object
851 /
852
853Check if an object is an instance.
854[clinic start generated code]*/
855
856static int
857type___instancecheck___impl(PyTypeObject *self, PyObject *instance)
858/*[clinic end generated code: output=08b6bf5f591c3618 input=cdbfeaee82c01a0f]*/
Antoine Pitrouec569b72008-08-26 22:40:48 +0000859{
Serhiy Storchaka5c643a02017-03-19 08:46:44 +0200860 return _PyObject_RealIsInstance(instance, (PyObject *)self);
Antoine Pitrouec569b72008-08-26 22:40:48 +0000861}
862
Serhiy Storchaka5c643a02017-03-19 08:46:44 +0200863/*[clinic input]
864type.__subclasscheck__ -> bool
Antoine Pitrouec569b72008-08-26 22:40:48 +0000865
Serhiy Storchaka5c643a02017-03-19 08:46:44 +0200866 subclass: object
867 /
868
869Check if a class is a subclass.
870[clinic start generated code]*/
871
872static int
873type___subclasscheck___impl(PyTypeObject *self, PyObject *subclass)
874/*[clinic end generated code: output=97a4e51694500941 input=071b2ca9e03355f4]*/
Antoine Pitrouec569b72008-08-26 22:40:48 +0000875{
Serhiy Storchaka5c643a02017-03-19 08:46:44 +0200876 return _PyObject_RealIsSubclass(subclass, (PyObject *)self);
Antoine Pitrouec569b72008-08-26 22:40:48 +0000877}
878
Antoine Pitrouec569b72008-08-26 22:40:48 +0000879
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000880static PyGetSetDef type_getsets[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000881 {"__name__", (getter)type_name, (setter)type_set_name, NULL},
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100882 {"__qualname__", (getter)type_qualname, (setter)type_set_qualname, NULL},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000883 {"__bases__", (getter)type_get_bases, (setter)type_set_bases, NULL},
884 {"__module__", (getter)type_module, (setter)type_set_module, NULL},
885 {"__abstractmethods__", (getter)type_abstractmethods,
886 (setter)type_set_abstractmethods, NULL},
887 {"__dict__", (getter)type_dict, NULL, NULL},
Benjamin Peterson01fc6cd2011-08-17 12:03:47 -0500888 {"__doc__", (getter)type_get_doc, (setter)type_set_doc, NULL},
Larry Hastings5c661892014-01-24 06:17:25 -0800889 {"__text_signature__", (getter)type_get_text_signature, NULL, NULL},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000890 {0}
Tim Peters6d6c1a32001-08-02 04:15:00 +0000891};
892
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000893static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000894type_repr(PyTypeObject *type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000895{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000896 PyObject *mod, *name, *rtn;
Guido van Rossumc3542212001-08-16 09:18:56 +0000897
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000898 mod = type_module(type, NULL);
899 if (mod == NULL)
900 PyErr_Clear();
901 else if (!PyUnicode_Check(mod)) {
902 Py_DECREF(mod);
903 mod = NULL;
904 }
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100905 name = type_qualname(type, NULL);
Christian Heimesa0e7e412012-09-10 03:00:14 +0200906 if (name == NULL) {
907 Py_XDECREF(mod);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000908 return NULL;
Christian Heimesa0e7e412012-09-10 03:00:14 +0200909 }
Barry Warsaw7ce36942001-08-24 18:34:26 +0000910
Serhiy Storchakaf5894dd2016-11-16 15:40:39 +0200911 if (mod != NULL && !_PyUnicode_EqualToASCIIId(mod, &PyId_builtins))
Benjamin Petersonab078e92016-07-13 21:13:29 -0700912 rtn = PyUnicode_FromFormat("<class '%U.%U'>", mod, name);
913 else
914 rtn = PyUnicode_FromFormat("<class '%s'>", type->tp_name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000915
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000916 Py_XDECREF(mod);
917 Py_DECREF(name);
918 return rtn;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000919}
920
Tim Peters6d6c1a32001-08-02 04:15:00 +0000921static PyObject *
922type_call(PyTypeObject *type, PyObject *args, PyObject *kwds)
923{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000924 PyObject *obj;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000925
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000926 if (type->tp_new == NULL) {
927 PyErr_Format(PyExc_TypeError,
928 "cannot create '%.100s' instances",
929 type->tp_name);
930 return NULL;
931 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000932
Victor Stinner33824f62013-08-26 14:05:19 +0200933#ifdef Py_DEBUG
934 /* type_call() must not be called with an exception set,
Victor Stinnera8cb5152017-01-18 14:12:51 +0100935 because it can clear it (directly or indirectly) and so the
Martin Panter9955a372015-10-07 10:26:23 +0000936 caller loses its exception */
Victor Stinner33824f62013-08-26 14:05:19 +0200937 assert(!PyErr_Occurred());
938#endif
939
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000940 obj = type->tp_new(type, args, kwds);
Victor Stinner99bb14b2015-09-03 12:16:49 +0200941 obj = _Py_CheckFunctionResult((PyObject*)type, obj, NULL);
942 if (obj == NULL)
943 return NULL;
944
945 /* Ugly exception: when the call was type(something),
946 don't call tp_init on the result. */
947 if (type == &PyType_Type &&
948 PyTuple_Check(args) && PyTuple_GET_SIZE(args) == 1 &&
949 (kwds == NULL ||
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +0200950 (PyDict_Check(kwds) && PyDict_GET_SIZE(kwds) == 0)))
Victor Stinner99bb14b2015-09-03 12:16:49 +0200951 return obj;
952
953 /* If the returned object is not an instance of type,
954 it won't be initialized. */
955 if (!PyType_IsSubtype(Py_TYPE(obj), type))
956 return obj;
957
958 type = Py_TYPE(obj);
959 if (type->tp_init != NULL) {
960 int res = type->tp_init(obj, args, kwds);
961 if (res < 0) {
962 assert(PyErr_Occurred());
963 Py_DECREF(obj);
964 obj = NULL;
965 }
966 else {
967 assert(!PyErr_Occurred());
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000968 }
969 }
970 return obj;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000971}
972
973PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000974PyType_GenericAlloc(PyTypeObject *type, Py_ssize_t nitems)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000975{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000976 PyObject *obj;
977 const size_t size = _PyObject_VAR_SIZE(type, nitems+1);
978 /* note that we need to add one, for the sentinel */
Tim Peters406fe3b2001-10-06 19:04:01 +0000979
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000980 if (PyType_IS_GC(type))
981 obj = _PyObject_GC_Malloc(size);
982 else
983 obj = (PyObject *)PyObject_MALLOC(size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000984
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000985 if (obj == NULL)
986 return PyErr_NoMemory();
Tim Peters406fe3b2001-10-06 19:04:01 +0000987
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000988 memset(obj, '\0', size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000989
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000990 if (type->tp_itemsize == 0)
Christian Heimesd3afe782013-12-04 09:27:47 +0100991 (void)PyObject_INIT(obj, type);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000992 else
993 (void) PyObject_INIT_VAR((PyVarObject *)obj, type, nitems);
Tim Peters406fe3b2001-10-06 19:04:01 +0000994
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000995 if (PyType_IS_GC(type))
996 _PyObject_GC_TRACK(obj);
997 return obj;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000998}
999
1000PyObject *
1001PyType_GenericNew(PyTypeObject *type, PyObject *args, PyObject *kwds)
1002{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001003 return type->tp_alloc(type, 0);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001004}
1005
Guido van Rossum9475a232001-10-05 20:51:39 +00001006/* Helpers for subtyping */
1007
1008static int
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001009traverse_slots(PyTypeObject *type, PyObject *self, visitproc visit, void *arg)
1010{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001011 Py_ssize_t i, n;
1012 PyMemberDef *mp;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001013
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001014 n = Py_SIZE(type);
1015 mp = PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type);
1016 for (i = 0; i < n; i++, mp++) {
1017 if (mp->type == T_OBJECT_EX) {
1018 char *addr = (char *)self + mp->offset;
1019 PyObject *obj = *(PyObject **)addr;
1020 if (obj != NULL) {
1021 int err = visit(obj, arg);
1022 if (err)
1023 return err;
1024 }
1025 }
1026 }
1027 return 0;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001028}
1029
1030static int
Guido van Rossum9475a232001-10-05 20:51:39 +00001031subtype_traverse(PyObject *self, visitproc visit, void *arg)
1032{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001033 PyTypeObject *type, *base;
1034 traverseproc basetraverse;
Guido van Rossum9475a232001-10-05 20:51:39 +00001035
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001036 /* Find the nearest base with a different tp_traverse,
1037 and traverse slots while we're at it */
1038 type = Py_TYPE(self);
1039 base = type;
1040 while ((basetraverse = base->tp_traverse) == subtype_traverse) {
1041 if (Py_SIZE(base)) {
1042 int err = traverse_slots(base, self, visit, arg);
1043 if (err)
1044 return err;
1045 }
1046 base = base->tp_base;
1047 assert(base);
1048 }
Guido van Rossum9475a232001-10-05 20:51:39 +00001049
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001050 if (type->tp_dictoffset != base->tp_dictoffset) {
1051 PyObject **dictptr = _PyObject_GetDictPtr(self);
1052 if (dictptr && *dictptr)
1053 Py_VISIT(*dictptr);
1054 }
Guido van Rossum9475a232001-10-05 20:51:39 +00001055
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001056 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
1057 /* For a heaptype, the instances count as references
1058 to the type. Traverse the type so the collector
1059 can find cycles involving this link. */
1060 Py_VISIT(type);
Guido van Rossuma3862092002-06-10 15:24:42 +00001061
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001062 if (basetraverse)
1063 return basetraverse(self, visit, arg);
1064 return 0;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001065}
1066
1067static void
1068clear_slots(PyTypeObject *type, PyObject *self)
1069{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001070 Py_ssize_t i, n;
1071 PyMemberDef *mp;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001072
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001073 n = Py_SIZE(type);
1074 mp = PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type);
1075 for (i = 0; i < n; i++, mp++) {
1076 if (mp->type == T_OBJECT_EX && !(mp->flags & READONLY)) {
1077 char *addr = (char *)self + mp->offset;
1078 PyObject *obj = *(PyObject **)addr;
1079 if (obj != NULL) {
1080 *(PyObject **)addr = NULL;
1081 Py_DECREF(obj);
1082 }
1083 }
1084 }
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001085}
1086
1087static int
1088subtype_clear(PyObject *self)
1089{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001090 PyTypeObject *type, *base;
1091 inquiry baseclear;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001092
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001093 /* Find the nearest base with a different tp_clear
1094 and clear slots while we're at it */
1095 type = Py_TYPE(self);
1096 base = type;
1097 while ((baseclear = base->tp_clear) == subtype_clear) {
1098 if (Py_SIZE(base))
1099 clear_slots(base, self);
1100 base = base->tp_base;
1101 assert(base);
1102 }
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001103
Benjamin Peterson52c42432012-03-07 18:41:11 -06001104 /* Clear the instance dict (if any), to break cycles involving only
1105 __dict__ slots (as in the case 'self.__dict__ is self'). */
1106 if (type->tp_dictoffset != base->tp_dictoffset) {
1107 PyObject **dictptr = _PyObject_GetDictPtr(self);
1108 if (dictptr && *dictptr)
1109 Py_CLEAR(*dictptr);
1110 }
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001111
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001112 if (baseclear)
1113 return baseclear(self);
1114 return 0;
Guido van Rossum9475a232001-10-05 20:51:39 +00001115}
Tim Peters6d6c1a32001-08-02 04:15:00 +00001116
1117static void
1118subtype_dealloc(PyObject *self)
1119{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001120 PyTypeObject *type, *base;
1121 destructor basedealloc;
Victor Stinner50b48572018-11-01 01:51:40 +01001122 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrou796564c2013-07-30 19:59:21 +02001123 int has_finalizer;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001124
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001125 /* Extract the type; we expect it to be a heap type */
1126 type = Py_TYPE(self);
Victor Stinner08625052018-10-26 18:39:11 +02001127 _PyObject_ASSERT((PyObject *)type, type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001128
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001129 /* Test whether the type has GC exactly once */
Guido van Rossum22b13872002-08-06 21:41:44 +00001130
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001131 if (!PyType_IS_GC(type)) {
1132 /* It's really rare to find a dynamic type that doesn't have
1133 GC; it can only happen when deriving from 'object' and not
1134 adding any slots or instance variables. This allows
1135 certain simplifications: there's no need to call
1136 clear_slots(), or DECREF the dict, or clear weakrefs. */
Guido van Rossum22b13872002-08-06 21:41:44 +00001137
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001138 /* Maybe call finalizer; exit early if resurrected */
Antoine Pitrou796564c2013-07-30 19:59:21 +02001139 if (type->tp_finalize) {
1140 if (PyObject_CallFinalizerFromDealloc(self) < 0)
1141 return;
1142 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001143 if (type->tp_del) {
1144 type->tp_del(self);
1145 if (self->ob_refcnt > 0)
1146 return;
1147 }
Guido van Rossum22b13872002-08-06 21:41:44 +00001148
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001149 /* Find the nearest base with a different tp_dealloc */
1150 base = type;
1151 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
1152 assert(Py_SIZE(base) == 0);
1153 base = base->tp_base;
1154 assert(base);
1155 }
Guido van Rossum22b13872002-08-06 21:41:44 +00001156
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001157 /* Extract the type again; tp_del may have changed it */
1158 type = Py_TYPE(self);
Benjamin Peterson193152c2009-04-25 01:08:45 +00001159
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001160 /* Call the base tp_dealloc() */
1161 assert(basedealloc);
1162 basedealloc(self);
Guido van Rossum22b13872002-08-06 21:41:44 +00001163
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001164 /* Can't reference self beyond this point */
1165 Py_DECREF(type);
Guido van Rossum22b13872002-08-06 21:41:44 +00001166
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001167 /* Done */
1168 return;
1169 }
Guido van Rossum22b13872002-08-06 21:41:44 +00001170
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001171 /* We get here only if the type has GC */
Guido van Rossum22b13872002-08-06 21:41:44 +00001172
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001173 /* UnTrack and re-Track around the trashcan macro, alas */
1174 /* See explanation at end of function for full disclosure */
1175 PyObject_GC_UnTrack(self);
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001176 ++_PyRuntime.gc.trash_delete_nesting;
Antoine Pitrou56cd62c2012-09-06 00:59:49 +02001177 ++ tstate->trash_delete_nesting;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001178 Py_TRASHCAN_SAFE_BEGIN(self);
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001179 --_PyRuntime.gc.trash_delete_nesting;
Antoine Pitrou56cd62c2012-09-06 00:59:49 +02001180 -- tstate->trash_delete_nesting;
Guido van Rossum22b13872002-08-06 21:41:44 +00001181
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001182 /* Find the nearest base with a different tp_dealloc */
1183 base = type;
Brett Cannonb94767f2011-02-22 20:15:44 +00001184 while ((/*basedealloc =*/ base->tp_dealloc) == subtype_dealloc) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001185 base = base->tp_base;
1186 assert(base);
1187 }
Guido van Rossum14227b42001-12-06 02:35:58 +00001188
Antoine Pitrou796564c2013-07-30 19:59:21 +02001189 has_finalizer = type->tp_finalize || type->tp_del;
Guido van Rossum59195fd2003-06-13 20:54:40 +00001190
Antoine Pitrou796564c2013-07-30 19:59:21 +02001191 if (type->tp_finalize) {
Benjamin Peterson8f657c32016-10-04 00:00:02 -07001192 _PyObject_GC_TRACK(self);
Antoine Pitrou796564c2013-07-30 19:59:21 +02001193 if (PyObject_CallFinalizerFromDealloc(self) < 0) {
1194 /* Resurrected */
1195 goto endlabel;
1196 }
Benjamin Peterson8f657c32016-10-04 00:00:02 -07001197 _PyObject_GC_UNTRACK(self);
Antoine Pitrou796564c2013-07-30 19:59:21 +02001198 }
Benjamin Peterson8f657c32016-10-04 00:00:02 -07001199 /*
1200 If we added a weaklist, we clear it. Do this *before* calling tp_del,
1201 clearing slots, or clearing the instance dict.
1202
1203 GC tracking must be off at this point. weakref callbacks (if any, and
1204 whether directly here or indirectly in something we call) may trigger GC,
1205 and if self is tracked at that point, it will look like trash to GC and GC
1206 will try to delete self again.
1207 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001208 if (type->tp_weaklistoffset && !base->tp_weaklistoffset)
1209 PyObject_ClearWeakRefs(self);
Guido van Rossum1987c662003-05-29 14:29:23 +00001210
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001211 if (type->tp_del) {
Benjamin Peterson8f657c32016-10-04 00:00:02 -07001212 _PyObject_GC_TRACK(self);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001213 type->tp_del(self);
Antoine Pitrou796564c2013-07-30 19:59:21 +02001214 if (self->ob_refcnt > 0) {
1215 /* Resurrected */
1216 goto endlabel;
1217 }
Benjamin Peterson8f657c32016-10-04 00:00:02 -07001218 _PyObject_GC_UNTRACK(self);
Antoine Pitrou796564c2013-07-30 19:59:21 +02001219 }
1220 if (has_finalizer) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001221 /* New weakrefs could be created during the finalizer call.
Antoine Pitrou796564c2013-07-30 19:59:21 +02001222 If this occurs, clear them out without calling their
1223 finalizers since they might rely on part of the object
1224 being finalized that has already been destroyed. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001225 if (type->tp_weaklistoffset && !base->tp_weaklistoffset) {
1226 /* Modeled after GET_WEAKREFS_LISTPTR() */
1227 PyWeakReference **list = (PyWeakReference **) \
1228 PyObject_GET_WEAKREFS_LISTPTR(self);
1229 while (*list)
1230 _PyWeakref_ClearRef(*list);
1231 }
1232 }
Guido van Rossum1987c662003-05-29 14:29:23 +00001233
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001234 /* Clear slots up to the nearest base with a different tp_dealloc */
1235 base = type;
1236 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
1237 if (Py_SIZE(base))
1238 clear_slots(base, self);
1239 base = base->tp_base;
1240 assert(base);
1241 }
Guido van Rossum59195fd2003-06-13 20:54:40 +00001242
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001243 /* If we added a dict, DECREF it */
1244 if (type->tp_dictoffset && !base->tp_dictoffset) {
1245 PyObject **dictptr = _PyObject_GetDictPtr(self);
1246 if (dictptr != NULL) {
1247 PyObject *dict = *dictptr;
1248 if (dict != NULL) {
1249 Py_DECREF(dict);
1250 *dictptr = NULL;
1251 }
1252 }
1253 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001254
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001255 /* Extract the type again; tp_del may have changed it */
1256 type = Py_TYPE(self);
Benjamin Peterson193152c2009-04-25 01:08:45 +00001257
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001258 /* Call the base tp_dealloc(); first retrack self if
1259 * basedealloc knows about gc.
1260 */
1261 if (PyType_IS_GC(base))
1262 _PyObject_GC_TRACK(self);
1263 assert(basedealloc);
1264 basedealloc(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001265
Benjamin Peterson9d4cbcc2015-01-30 13:33:42 -05001266 /* Can't reference self beyond this point. It's possible tp_del switched
1267 our type from a HEAPTYPE to a non-HEAPTYPE, so be careful about
1268 reference counting. */
1269 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
1270 Py_DECREF(type);
Guido van Rossum22b13872002-08-06 21:41:44 +00001271
Guido van Rossum0906e072002-08-07 20:42:09 +00001272 endlabel:
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001273 ++_PyRuntime.gc.trash_delete_nesting;
Antoine Pitrou56cd62c2012-09-06 00:59:49 +02001274 ++ tstate->trash_delete_nesting;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001275 Py_TRASHCAN_SAFE_END(self);
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001276 --_PyRuntime.gc.trash_delete_nesting;
Antoine Pitrou56cd62c2012-09-06 00:59:49 +02001277 -- tstate->trash_delete_nesting;
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001278
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001279 /* Explanation of the weirdness around the trashcan macros:
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001280
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001281 Q. What do the trashcan macros do?
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001282
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001283 A. Read the comment titled "Trashcan mechanism" in object.h.
1284 For one, this explains why there must be a call to GC-untrack
1285 before the trashcan begin macro. Without understanding the
1286 trashcan code, the answers to the following questions don't make
1287 sense.
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001288
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001289 Q. Why do we GC-untrack before the trashcan and then immediately
1290 GC-track again afterward?
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001291
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001292 A. In the case that the base class is GC-aware, the base class
1293 probably GC-untracks the object. If it does that using the
1294 UNTRACK macro, this will crash when the object is already
1295 untracked. Because we don't know what the base class does, the
1296 only safe thing is to make sure the object is tracked when we
1297 call the base class dealloc. But... The trashcan begin macro
1298 requires that the object is *untracked* before it is called. So
1299 the dance becomes:
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001300
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001301 GC untrack
1302 trashcan begin
1303 GC track
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001304
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001305 Q. Why did the last question say "immediately GC-track again"?
1306 It's nowhere near immediately.
Tim Petersf7f9e992003-11-13 21:59:32 +00001307
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001308 A. Because the code *used* to re-track immediately. Bad Idea.
1309 self has a refcount of 0, and if gc ever gets its hands on it
1310 (which can happen if any weakref callback gets invoked), it
1311 looks like trash to gc too, and gc also tries to delete self
Ezio Melotti13925002011-03-16 11:05:33 +02001312 then. But we're already deleting self. Double deallocation is
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001313 a subtle disaster.
Tim Petersf7f9e992003-11-13 21:59:32 +00001314
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001315 Q. Why the bizarre (net-zero) manipulation of
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001316 _PyRuntime.trash_delete_nesting around the trashcan macros?
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001317
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001318 A. Some base classes (e.g. list) also use the trashcan mechanism.
1319 The following scenario used to be possible:
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001320
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001321 - suppose the trashcan level is one below the trashcan limit
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001322
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001323 - subtype_dealloc() is called
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001324
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001325 - the trashcan limit is not yet reached, so the trashcan level
1326 is incremented and the code between trashcan begin and end is
1327 executed
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001328
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001329 - this destroys much of the object's contents, including its
1330 slots and __dict__
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001331
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001332 - basedealloc() is called; this is really list_dealloc(), or
1333 some other type which also uses the trashcan macros
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001334
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001335 - the trashcan limit is now reached, so the object is put on the
1336 trashcan's to-be-deleted-later list
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001337
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001338 - basedealloc() returns
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001339
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001340 - subtype_dealloc() decrefs the object's type
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001341
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001342 - subtype_dealloc() returns
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001343
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001344 - later, the trashcan code starts deleting the objects from its
1345 to-be-deleted-later list
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001346
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001347 - subtype_dealloc() is called *AGAIN* for the same object
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001348
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001349 - at the very least (if the destroyed slots and __dict__ don't
1350 cause problems) the object's type gets decref'ed a second
1351 time, which is *BAD*!!!
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001352
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001353 The remedy is to make sure that if the code between trashcan
1354 begin and end in subtype_dealloc() is called, the code between
1355 trashcan begin and end in basedealloc() will also be called.
1356 This is done by decrementing the level after passing into the
1357 trashcan block, and incrementing it just before leaving the
1358 block.
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001359
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001360 But now it's possible that a chain of objects consisting solely
1361 of objects whose deallocator is subtype_dealloc() will defeat
1362 the trashcan mechanism completely: the decremented level means
1363 that the effective level never reaches the limit. Therefore, we
1364 *increment* the level *before* entering the trashcan block, and
1365 matchingly decrement it after leaving. This means the trashcan
1366 code will trigger a little early, but that's no big deal.
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001367
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001368 Q. Are there any live examples of code in need of all this
1369 complexity?
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001370
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001371 A. Yes. See SF bug 668433 for code that crashed (when Python was
1372 compiled in debug mode) before the trashcan level manipulations
1373 were added. For more discussion, see SF patches 581742, 575073
1374 and bug 574207.
1375 */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001376}
1377
Jeremy Hylton938ace62002-07-17 16:30:39 +00001378static PyTypeObject *solid_base(PyTypeObject *type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001379
Tim Peters6d6c1a32001-08-02 04:15:00 +00001380/* type test with subclassing support */
1381
Benjamin Peterson6cb526e2016-09-09 12:42:51 -07001382static int
Benjamin Peterson104b9e02015-02-05 22:29:14 -05001383type_is_subtype_base_chain(PyTypeObject *a, PyTypeObject *b)
1384{
1385 do {
1386 if (a == b)
1387 return 1;
1388 a = a->tp_base;
1389 } while (a != NULL);
1390
1391 return (b == &PyBaseObject_Type);
1392}
1393
Tim Peters6d6c1a32001-08-02 04:15:00 +00001394int
1395PyType_IsSubtype(PyTypeObject *a, PyTypeObject *b)
1396{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001397 PyObject *mro;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001398
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001399 mro = a->tp_mro;
1400 if (mro != NULL) {
1401 /* Deal with multiple inheritance without recursion
1402 by walking the MRO tuple */
1403 Py_ssize_t i, n;
1404 assert(PyTuple_Check(mro));
1405 n = PyTuple_GET_SIZE(mro);
1406 for (i = 0; i < n; i++) {
1407 if (PyTuple_GET_ITEM(mro, i) == (PyObject *)b)
1408 return 1;
1409 }
1410 return 0;
1411 }
Benjamin Peterson104b9e02015-02-05 22:29:14 -05001412 else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001413 /* a is not completely initilized yet; follow tp_base */
Benjamin Peterson104b9e02015-02-05 22:29:14 -05001414 return type_is_subtype_base_chain(a, b);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001415}
1416
Serhiy Storchaka4e624ca2017-06-01 08:18:25 +03001417/* Routines to do a method lookup in the type without looking in the
1418 instance dictionary (so we can't use PyObject_GetAttr) but still
1419 binding it to the instance.
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001420
Victor Stinner516b9812017-02-09 22:53:47 +01001421 Variants:
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001422
Serhiy Storchaka4e624ca2017-06-01 08:18:25 +03001423 - _PyObject_LookupSpecial() returns NULL without raising an exception
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001424 when the _PyType_Lookup() call fails;
1425
Serhiy Storchaka4e624ca2017-06-01 08:18:25 +03001426 - lookup_maybe_method() and lookup_method() are internal routines similar
1427 to _PyObject_LookupSpecial(), but can return unbound PyFunction
Victor Stinner516b9812017-02-09 22:53:47 +01001428 to avoid temporary method object. Pass self as first argument when
1429 unbound == 1.
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001430*/
Guido van Rossum60718732001-08-28 17:47:51 +00001431
Serhiy Storchaka4e624ca2017-06-01 08:18:25 +03001432PyObject *
1433_PyObject_LookupSpecial(PyObject *self, _Py_Identifier *attrid)
Guido van Rossum60718732001-08-28 17:47:51 +00001434{
Victor Stinner3c1e4812012-03-26 22:10:51 +02001435 PyObject *res;
Guido van Rossum60718732001-08-28 17:47:51 +00001436
Victor Stinner3c1e4812012-03-26 22:10:51 +02001437 res = _PyType_LookupId(Py_TYPE(self), attrid);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001438 if (res != NULL) {
1439 descrgetfunc f;
1440 if ((f = Py_TYPE(res)->tp_descr_get) == NULL)
1441 Py_INCREF(res);
1442 else
1443 res = f(res, self, (PyObject *)(Py_TYPE(self)));
1444 }
1445 return res;
Guido van Rossum60718732001-08-28 17:47:51 +00001446}
1447
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001448static PyObject *
Victor Stinner516b9812017-02-09 22:53:47 +01001449lookup_maybe_method(PyObject *self, _Py_Identifier *attrid, int *unbound)
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001450{
Victor Stinner516b9812017-02-09 22:53:47 +01001451 PyObject *res = _PyType_LookupId(Py_TYPE(self), attrid);
1452 if (res == NULL) {
1453 return NULL;
1454 }
1455
1456 if (PyFunction_Check(res)) {
1457 /* Avoid temporary PyMethodObject */
1458 *unbound = 1;
1459 Py_INCREF(res);
1460 }
1461 else {
1462 *unbound = 0;
1463 descrgetfunc f = Py_TYPE(res)->tp_descr_get;
1464 if (f == NULL) {
1465 Py_INCREF(res);
1466 }
1467 else {
1468 res = f(res, self, (PyObject *)(Py_TYPE(self)));
1469 }
1470 }
1471 return res;
1472}
1473
1474static PyObject *
1475lookup_method(PyObject *self, _Py_Identifier *attrid, int *unbound)
1476{
1477 PyObject *res = lookup_maybe_method(self, attrid, unbound);
1478 if (res == NULL && !PyErr_Occurred()) {
Benjamin Petersonce798522012-01-22 11:24:29 -05001479 PyErr_SetObject(PyExc_AttributeError, attrid->object);
Victor Stinner516b9812017-02-09 22:53:47 +01001480 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001481 return res;
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001482}
1483
Victor Stinner516b9812017-02-09 22:53:47 +01001484static PyObject*
1485call_unbound(int unbound, PyObject *func, PyObject *self,
1486 PyObject **args, Py_ssize_t nargs)
1487{
1488 if (unbound) {
1489 return _PyObject_FastCall_Prepend(func, self, args, nargs);
1490 }
1491 else {
1492 return _PyObject_FastCall(func, args, nargs);
1493 }
1494}
Guido van Rossum2730b132001-08-28 18:22:14 +00001495
Victor Stinner516b9812017-02-09 22:53:47 +01001496static PyObject*
1497call_unbound_noarg(int unbound, PyObject *func, PyObject *self)
1498{
1499 if (unbound) {
1500 PyObject *args[1] = {self};
1501 return _PyObject_FastCall(func, args, 1);
1502 }
1503 else {
1504 return _PyObject_CallNoArg(func);
1505 }
1506}
1507
Serhiy Storchaka4e624ca2017-06-01 08:18:25 +03001508/* A variation of PyObject_CallMethod* that uses lookup_maybe_method()
1509 instead of PyObject_GetAttrString(). */
Neil Schemenauerf23473f2001-10-21 22:28:58 +00001510static PyObject *
Victor Stinner434723f2017-01-11 00:07:40 +01001511call_method(PyObject *obj, _Py_Identifier *name,
1512 PyObject **args, Py_ssize_t nargs)
Guido van Rossum2730b132001-08-28 18:22:14 +00001513{
Victor Stinner516b9812017-02-09 22:53:47 +01001514 int unbound;
Victor Stinner887b4302016-12-09 00:41:46 +01001515 PyObject *func, *retval;
Guido van Rossum2730b132001-08-28 18:22:14 +00001516
Serhiy Storchaka4e624ca2017-06-01 08:18:25 +03001517 func = lookup_method(obj, name, &unbound);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001518 if (func == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001519 return NULL;
1520 }
Victor Stinner516b9812017-02-09 22:53:47 +01001521 retval = call_unbound(unbound, func, obj, args, nargs);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001522 Py_DECREF(func);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001523 return retval;
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001524}
1525
1526/* Clone of call_method() that returns NotImplemented when the lookup fails. */
1527
Neil Schemenauerf23473f2001-10-21 22:28:58 +00001528static PyObject *
Victor Stinner434723f2017-01-11 00:07:40 +01001529call_maybe(PyObject *obj, _Py_Identifier *name,
1530 PyObject **args, Py_ssize_t nargs)
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001531{
Victor Stinner516b9812017-02-09 22:53:47 +01001532 int unbound;
Victor Stinner887b4302016-12-09 00:41:46 +01001533 PyObject *func, *retval;
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001534
Victor Stinner516b9812017-02-09 22:53:47 +01001535 func = lookup_maybe_method(obj, name, &unbound);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001536 if (func == NULL) {
Brian Curtindfc80e32011-08-10 20:28:54 -05001537 if (!PyErr_Occurred())
1538 Py_RETURN_NOTIMPLEMENTED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001539 return NULL;
1540 }
Guido van Rossum2730b132001-08-28 18:22:14 +00001541
Victor Stinner516b9812017-02-09 22:53:47 +01001542 retval = call_unbound(unbound, func, obj, args, nargs);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001543 Py_DECREF(func);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001544 return retval;
Guido van Rossum2730b132001-08-28 18:22:14 +00001545}
1546
Tim Petersea7f75d2002-12-07 21:39:16 +00001547/*
Guido van Rossum1f121312002-11-14 19:49:16 +00001548 Method resolution order algorithm C3 described in
1549 "A Monotonic Superclass Linearization for Dylan",
1550 by Kim Barrett, Bob Cassel, Paul Haahr,
Tim Petersea7f75d2002-12-07 21:39:16 +00001551 David A. Moon, Keith Playford, and P. Tucker Withington.
Guido van Rossum1f121312002-11-14 19:49:16 +00001552 (OOPSLA 1996)
1553
Guido van Rossum98f33732002-11-25 21:36:54 +00001554 Some notes about the rules implied by C3:
1555
Tim Petersea7f75d2002-12-07 21:39:16 +00001556 No duplicate bases.
Guido van Rossum98f33732002-11-25 21:36:54 +00001557 It isn't legal to repeat a class in a list of base classes.
1558
1559 The next three properties are the 3 constraints in "C3".
1560
Martin Panter69332c12016-08-04 13:07:31 +00001561 Local precedence order.
Guido van Rossum98f33732002-11-25 21:36:54 +00001562 If A precedes B in C's MRO, then A will precede B in the MRO of all
1563 subclasses of C.
1564
1565 Monotonicity.
1566 The MRO of a class must be an extension without reordering of the
1567 MRO of each of its superclasses.
1568
1569 Extended Precedence Graph (EPG).
1570 Linearization is consistent if there is a path in the EPG from
1571 each class to all its successors in the linearization. See
1572 the paper for definition of EPG.
Guido van Rossum1f121312002-11-14 19:49:16 +00001573 */
1574
Tim Petersea7f75d2002-12-07 21:39:16 +00001575static int
Serhiy Storchaka6b91a592017-12-20 19:21:02 +02001576tail_contains(PyObject *tuple, int whence, PyObject *o)
1577{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001578 Py_ssize_t j, size;
Serhiy Storchaka6b91a592017-12-20 19:21:02 +02001579 size = PyTuple_GET_SIZE(tuple);
Guido van Rossum1f121312002-11-14 19:49:16 +00001580
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001581 for (j = whence+1; j < size; j++) {
Serhiy Storchaka6b91a592017-12-20 19:21:02 +02001582 if (PyTuple_GET_ITEM(tuple, j) == o)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001583 return 1;
1584 }
1585 return 0;
Guido van Rossum1f121312002-11-14 19:49:16 +00001586}
1587
Guido van Rossum98f33732002-11-25 21:36:54 +00001588static PyObject *
1589class_name(PyObject *cls)
1590{
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001591 PyObject *name = _PyObject_GetAttrId(cls, &PyId___name__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001592 if (name == NULL) {
1593 PyErr_Clear();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001594 name = PyObject_Repr(cls);
1595 }
1596 if (name == NULL)
1597 return NULL;
1598 if (!PyUnicode_Check(name)) {
1599 Py_DECREF(name);
1600 return NULL;
1601 }
1602 return name;
Guido van Rossum98f33732002-11-25 21:36:54 +00001603}
1604
1605static int
Serhiy Storchaka6b91a592017-12-20 19:21:02 +02001606check_duplicates(PyObject *tuple)
Guido van Rossum98f33732002-11-25 21:36:54 +00001607{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001608 Py_ssize_t i, j, n;
1609 /* Let's use a quadratic time algorithm,
Serhiy Storchaka6b91a592017-12-20 19:21:02 +02001610 assuming that the bases tuples is short.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001611 */
Serhiy Storchaka6b91a592017-12-20 19:21:02 +02001612 n = PyTuple_GET_SIZE(tuple);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001613 for (i = 0; i < n; i++) {
Serhiy Storchaka6b91a592017-12-20 19:21:02 +02001614 PyObject *o = PyTuple_GET_ITEM(tuple, i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001615 for (j = i + 1; j < n; j++) {
Serhiy Storchaka6b91a592017-12-20 19:21:02 +02001616 if (PyTuple_GET_ITEM(tuple, j) == o) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001617 o = class_name(o);
1618 if (o != NULL) {
1619 PyErr_Format(PyExc_TypeError,
1620 "duplicate base class %U",
1621 o);
1622 Py_DECREF(o);
1623 } else {
1624 PyErr_SetString(PyExc_TypeError,
1625 "duplicate base class");
1626 }
1627 return -1;
1628 }
1629 }
1630 }
1631 return 0;
Guido van Rossum98f33732002-11-25 21:36:54 +00001632}
1633
1634/* Raise a TypeError for an MRO order disagreement.
1635
1636 It's hard to produce a good error message. In the absence of better
1637 insight into error reporting, report the classes that were candidates
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001638 to be put next into the MRO. There is some conflict between the
Guido van Rossum98f33732002-11-25 21:36:54 +00001639 order in which they should be put in the MRO, but it's hard to
1640 diagnose what constraint can't be satisfied.
1641*/
1642
1643static void
Serhiy Storchaka6b91a592017-12-20 19:21:02 +02001644set_mro_error(PyObject **to_merge, Py_ssize_t to_merge_size, int *remain)
Guido van Rossum98f33732002-11-25 21:36:54 +00001645{
Serhiy Storchaka6b91a592017-12-20 19:21:02 +02001646 Py_ssize_t i, n, off;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001647 char buf[1000];
1648 PyObject *k, *v;
1649 PyObject *set = PyDict_New();
1650 if (!set) return;
Guido van Rossum98f33732002-11-25 21:36:54 +00001651
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001652 for (i = 0; i < to_merge_size; i++) {
Serhiy Storchaka6b91a592017-12-20 19:21:02 +02001653 PyObject *L = to_merge[i];
1654 if (remain[i] < PyTuple_GET_SIZE(L)) {
1655 PyObject *c = PyTuple_GET_ITEM(L, remain[i]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001656 if (PyDict_SetItem(set, c, Py_None) < 0) {
1657 Py_DECREF(set);
1658 return;
1659 }
1660 }
1661 }
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02001662 n = PyDict_GET_SIZE(set);
Guido van Rossum98f33732002-11-25 21:36:54 +00001663
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001664 off = PyOS_snprintf(buf, sizeof(buf), "Cannot create a \
Raymond Hettingerf394df42003-04-06 19:13:41 +00001665consistent method resolution\norder (MRO) for bases");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001666 i = 0;
1667 while (PyDict_Next(set, &i, &k, &v) && (size_t)off < sizeof(buf)) {
1668 PyObject *name = class_name(k);
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02001669 const char *name_str;
Victor Stinnere5f99f32010-05-19 01:42:46 +00001670 if (name != NULL) {
Serhiy Storchaka06515832016-11-20 09:13:07 +02001671 name_str = PyUnicode_AsUTF8(name);
Victor Stinnere5f99f32010-05-19 01:42:46 +00001672 if (name_str == NULL)
Victor Stinnerba644a62010-05-19 01:50:45 +00001673 name_str = "?";
Victor Stinnere5f99f32010-05-19 01:42:46 +00001674 } else
Victor Stinnerba644a62010-05-19 01:50:45 +00001675 name_str = "?";
Victor Stinnere5f99f32010-05-19 01:42:46 +00001676 off += PyOS_snprintf(buf + off, sizeof(buf) - off, " %s", name_str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001677 Py_XDECREF(name);
1678 if (--n && (size_t)(off+1) < sizeof(buf)) {
1679 buf[off++] = ',';
1680 buf[off] = '\0';
1681 }
1682 }
1683 PyErr_SetString(PyExc_TypeError, buf);
1684 Py_DECREF(set);
Guido van Rossum98f33732002-11-25 21:36:54 +00001685}
1686
Tim Petersea7f75d2002-12-07 21:39:16 +00001687static int
Serhiy Storchaka6b91a592017-12-20 19:21:02 +02001688pmerge(PyObject *acc, PyObject **to_merge, Py_ssize_t to_merge_size)
Benjamin Peterson104b9e02015-02-05 22:29:14 -05001689{
1690 int res = 0;
Serhiy Storchaka6b91a592017-12-20 19:21:02 +02001691 Py_ssize_t i, j, empty_cnt;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001692 int *remain;
Tim Petersea7f75d2002-12-07 21:39:16 +00001693
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001694 /* remain stores an index into each sublist of to_merge.
1695 remain[i] is the index of the next base in to_merge[i]
1696 that is not included in acc.
1697 */
Serhiy Storchaka6b91a592017-12-20 19:21:02 +02001698 remain = PyMem_New(int, to_merge_size);
Victor Stinnera41f0852013-07-12 00:42:14 +02001699 if (remain == NULL) {
1700 PyErr_NoMemory();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001701 return -1;
Victor Stinnera41f0852013-07-12 00:42:14 +02001702 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001703 for (i = 0; i < to_merge_size; i++)
1704 remain[i] = 0;
Guido van Rossum1f121312002-11-14 19:49:16 +00001705
1706 again:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001707 empty_cnt = 0;
1708 for (i = 0; i < to_merge_size; i++) {
1709 PyObject *candidate;
Tim Petersea7f75d2002-12-07 21:39:16 +00001710
Serhiy Storchaka6b91a592017-12-20 19:21:02 +02001711 PyObject *cur_tuple = to_merge[i];
Guido van Rossum1f121312002-11-14 19:49:16 +00001712
Serhiy Storchaka6b91a592017-12-20 19:21:02 +02001713 if (remain[i] >= PyTuple_GET_SIZE(cur_tuple)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001714 empty_cnt++;
1715 continue;
1716 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001717
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001718 /* Choose next candidate for MRO.
Guido van Rossum98f33732002-11-25 21:36:54 +00001719
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001720 The input sequences alone can determine the choice.
1721 If not, choose the class which appears in the MRO
1722 of the earliest direct superclass of the new class.
1723 */
Guido van Rossum98f33732002-11-25 21:36:54 +00001724
Serhiy Storchaka6b91a592017-12-20 19:21:02 +02001725 candidate = PyTuple_GET_ITEM(cur_tuple, remain[i]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001726 for (j = 0; j < to_merge_size; j++) {
Serhiy Storchaka6b91a592017-12-20 19:21:02 +02001727 PyObject *j_lst = to_merge[j];
Benjamin Peterson104b9e02015-02-05 22:29:14 -05001728 if (tail_contains(j_lst, remain[j], candidate))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001729 goto skip; /* continue outer loop */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001730 }
Benjamin Peterson104b9e02015-02-05 22:29:14 -05001731 res = PyList_Append(acc, candidate);
1732 if (res < 0)
1733 goto out;
1734
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001735 for (j = 0; j < to_merge_size; j++) {
Serhiy Storchaka6b91a592017-12-20 19:21:02 +02001736 PyObject *j_lst = to_merge[j];
1737 if (remain[j] < PyTuple_GET_SIZE(j_lst) &&
1738 PyTuple_GET_ITEM(j_lst, remain[j]) == candidate) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001739 remain[j]++;
1740 }
1741 }
1742 goto again;
1743 skip: ;
1744 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001745
Benjamin Peterson104b9e02015-02-05 22:29:14 -05001746 if (empty_cnt != to_merge_size) {
Serhiy Storchaka6b91a592017-12-20 19:21:02 +02001747 set_mro_error(to_merge, to_merge_size, remain);
Benjamin Peterson104b9e02015-02-05 22:29:14 -05001748 res = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001749 }
Benjamin Peterson104b9e02015-02-05 22:29:14 -05001750
1751 out:
Serhiy Storchaka6b91a592017-12-20 19:21:02 +02001752 PyMem_Del(remain);
Benjamin Peterson104b9e02015-02-05 22:29:14 -05001753
1754 return res;
Guido van Rossum1f121312002-11-14 19:49:16 +00001755}
1756
Tim Peters6d6c1a32001-08-02 04:15:00 +00001757static PyObject *
1758mro_implementation(PyTypeObject *type)
1759{
Serhiy Storchaka6b91a592017-12-20 19:21:02 +02001760 PyObject *result;
Benjamin Peterson104b9e02015-02-05 22:29:14 -05001761 PyObject *bases;
Serhiy Storchaka6b91a592017-12-20 19:21:02 +02001762 PyObject **to_merge;
Benjamin Peterson104b9e02015-02-05 22:29:14 -05001763 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001764
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001765 if (type->tp_dict == NULL) {
1766 if (PyType_Ready(type) < 0)
1767 return NULL;
1768 }
Guido van Rossum63517572002-06-18 16:44:57 +00001769
Antoine Pitrou1f1a34c2017-12-20 15:58:21 +01001770 bases = type->tp_bases;
Serhiy Storchaka6b91a592017-12-20 19:21:02 +02001771 assert(PyTuple_Check(bases));
Antoine Pitrou1f1a34c2017-12-20 15:58:21 +01001772 n = PyTuple_GET_SIZE(bases);
Serhiy Storchaka6b91a592017-12-20 19:21:02 +02001773 for (i = 0; i < n; i++) {
1774 PyTypeObject *base = (PyTypeObject *)PyTuple_GET_ITEM(bases, i);
Antoine Pitrou1f1a34c2017-12-20 15:58:21 +01001775 if (base->tp_mro == NULL) {
1776 PyErr_Format(PyExc_TypeError,
1777 "Cannot extend an incomplete type '%.100s'",
1778 base->tp_name);
1779 return NULL;
1780 }
Serhiy Storchaka6b91a592017-12-20 19:21:02 +02001781 assert(PyTuple_Check(base->tp_mro));
1782 }
1783
1784 if (n == 1) {
1785 /* Fast path: if there is a single base, constructing the MRO
1786 * is trivial.
1787 */
1788 PyTypeObject *base = (PyTypeObject *)PyTuple_GET_ITEM(bases, 0);
1789 Py_ssize_t k = PyTuple_GET_SIZE(base->tp_mro);
Antoine Pitrou1f1a34c2017-12-20 15:58:21 +01001790 result = PyTuple_New(k + 1);
1791 if (result == NULL) {
1792 return NULL;
1793 }
1794 Py_INCREF(type);
1795 PyTuple_SET_ITEM(result, 0, (PyObject *) type);
1796 for (i = 0; i < k; i++) {
1797 PyObject *cls = PyTuple_GET_ITEM(base->tp_mro, i);
1798 Py_INCREF(cls);
1799 PyTuple_SET_ITEM(result, i + 1, cls);
1800 }
1801 return result;
1802 }
1803
Serhiy Storchaka6b91a592017-12-20 19:21:02 +02001804 /* This is just a basic sanity check. */
1805 if (check_duplicates(bases) < 0) {
1806 return NULL;
1807 }
1808
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001809 /* Find a superclass linearization that honors the constraints
Serhiy Storchaka6b91a592017-12-20 19:21:02 +02001810 of the explicit tuples of bases and the constraints implied by
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001811 each base class.
Guido van Rossum98f33732002-11-25 21:36:54 +00001812
Serhiy Storchaka6b91a592017-12-20 19:21:02 +02001813 to_merge is an array of tuples, where each tuple is a superclass
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001814 linearization implied by a base class. The last element of
Serhiy Storchaka6b91a592017-12-20 19:21:02 +02001815 to_merge is the declared tuple of bases.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001816 */
Guido van Rossum98f33732002-11-25 21:36:54 +00001817
Serhiy Storchaka6b91a592017-12-20 19:21:02 +02001818 to_merge = PyMem_New(PyObject *, n + 1);
1819 if (to_merge == NULL) {
1820 PyErr_NoMemory();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001821 return NULL;
Serhiy Storchaka6b91a592017-12-20 19:21:02 +02001822 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001823
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001824 for (i = 0; i < n; i++) {
Serhiy Storchaka6b91a592017-12-20 19:21:02 +02001825 PyTypeObject *base = (PyTypeObject *)PyTuple_GET_ITEM(bases, i);
1826 to_merge[i] = base->tp_mro;
1827 }
1828 to_merge[n] = bases;
Benjamin Peterson104b9e02015-02-05 22:29:14 -05001829
Serhiy Storchaka6b91a592017-12-20 19:21:02 +02001830 result = PyList_New(1);
1831 if (result == NULL) {
1832 PyMem_Del(to_merge);
1833 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001834 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001835
Serhiy Storchaka6b91a592017-12-20 19:21:02 +02001836 Py_INCREF(type);
1837 PyList_SET_ITEM(result, 0, (PyObject *)type);
1838 if (pmerge(result, to_merge, n + 1) < 0) {
Benjamin Peterson104b9e02015-02-05 22:29:14 -05001839 Py_CLEAR(result);
Serhiy Storchaka6b91a592017-12-20 19:21:02 +02001840 }
Benjamin Peterson104b9e02015-02-05 22:29:14 -05001841
Serhiy Storchaka6b91a592017-12-20 19:21:02 +02001842 PyMem_Del(to_merge);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001843 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001844}
1845
Serhiy Storchaka5c643a02017-03-19 08:46:44 +02001846/*[clinic input]
1847type.mro
Tim Peters6d6c1a32001-08-02 04:15:00 +00001848
Serhiy Storchaka5c643a02017-03-19 08:46:44 +02001849Return a type's method resolution order.
1850[clinic start generated code]*/
1851
1852static PyObject *
1853type_mro_impl(PyTypeObject *self)
1854/*[clinic end generated code: output=bffc4a39b5b57027 input=28414f4e156db28d]*/
1855{
Antoine Pitrou1f1a34c2017-12-20 15:58:21 +01001856 PyObject *seq;
1857 seq = mro_implementation(self);
1858 if (seq != NULL && !PyList_Check(seq)) {
1859 Py_SETREF(seq, PySequence_List(seq));
1860 }
1861 return seq;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001862}
1863
1864static int
Benjamin Peterson104b9e02015-02-05 22:29:14 -05001865mro_check(PyTypeObject *type, PyObject *mro)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001866{
Benjamin Peterson104b9e02015-02-05 22:29:14 -05001867 PyTypeObject *solid;
1868 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001869
Benjamin Peterson104b9e02015-02-05 22:29:14 -05001870 solid = solid_base(type);
1871
1872 n = PyTuple_GET_SIZE(mro);
1873 for (i = 0; i < n; i++) {
1874 PyTypeObject *base;
1875 PyObject *tmp;
1876
1877 tmp = PyTuple_GET_ITEM(mro, i);
1878 if (!PyType_Check(tmp)) {
1879 PyErr_Format(
1880 PyExc_TypeError,
1881 "mro() returned a non-class ('%.500s')",
1882 Py_TYPE(tmp)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001883 return -1;
Benjamin Peterson104b9e02015-02-05 22:29:14 -05001884 }
Armin Rigo037d1e02005-12-29 17:07:39 +00001885
Benjamin Peterson104b9e02015-02-05 22:29:14 -05001886 base = (PyTypeObject*)tmp;
1887 if (!PyType_IsSubtype(solid, solid_base(base))) {
1888 PyErr_Format(
1889 PyExc_TypeError,
1890 "mro() returned base with unsuitable layout ('%.500s')",
1891 base->tp_name);
1892 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001893 }
1894 }
Benjamin Peterson104b9e02015-02-05 22:29:14 -05001895
1896 return 0;
1897}
1898
1899/* Lookups an mcls.mro method, invokes it and checks the result (if needed,
1900 in case of a custom mro() implementation).
1901
1902 Keep in mind that during execution of this function type->tp_mro
1903 can be replaced due to possible reentrance (for example,
1904 through type_set_bases):
1905
1906 - when looking up the mcls.mro attribute (it could be
1907 a user-provided descriptor);
1908
1909 - from inside a custom mro() itself;
1910
1911 - through a finalizer of the return value of mro().
1912*/
1913static PyObject *
1914mro_invoke(PyTypeObject *type)
1915{
1916 PyObject *mro_result;
1917 PyObject *new_mro;
1918 int custom = (Py_TYPE(type) != &PyType_Type);
1919
1920 if (custom) {
1921 _Py_IDENTIFIER(mro);
Victor Stinner516b9812017-02-09 22:53:47 +01001922 int unbound;
1923 PyObject *mro_meth = lookup_method((PyObject *)type, &PyId_mro,
1924 &unbound);
Benjamin Peterson104b9e02015-02-05 22:29:14 -05001925 if (mro_meth == NULL)
1926 return NULL;
Victor Stinner516b9812017-02-09 22:53:47 +01001927 mro_result = call_unbound_noarg(unbound, mro_meth, (PyObject *)type);
Benjamin Peterson104b9e02015-02-05 22:29:14 -05001928 Py_DECREF(mro_meth);
1929 }
1930 else {
1931 mro_result = mro_implementation(type);
1932 }
1933 if (mro_result == NULL)
1934 return NULL;
1935
1936 new_mro = PySequence_Tuple(mro_result);
1937 Py_DECREF(mro_result);
1938 if (new_mro == NULL)
1939 return NULL;
1940
1941 if (custom && mro_check(type, new_mro) < 0) {
1942 Py_DECREF(new_mro);
1943 return NULL;
1944 }
1945
1946 return new_mro;
1947}
1948
1949/* Calculates and assigns a new MRO to type->tp_mro.
1950 Return values and invariants:
1951
1952 - Returns 1 if a new MRO value has been set to type->tp_mro due to
1953 this call of mro_internal (no tricky reentrancy and no errors).
1954
1955 In case if p_old_mro argument is not NULL, a previous value
1956 of type->tp_mro is put there, and the ownership of this
1957 reference is transferred to a caller.
1958 Otherwise, the previous value (if any) is decref'ed.
1959
1960 - Returns 0 in case when type->tp_mro gets changed because of
1961 reentering here through a custom mro() (see a comment to mro_invoke).
1962
1963 In this case, a refcount of an old type->tp_mro is adjusted
1964 somewhere deeper in the call stack (by the innermost mro_internal
1965 or its caller) and may become zero upon returning from here.
1966 This also implies that the whole hierarchy of subclasses of the type
1967 has seen the new value and updated their MRO accordingly.
1968
1969 - Returns -1 in case of an error.
1970*/
1971static int
1972mro_internal(PyTypeObject *type, PyObject **p_old_mro)
1973{
1974 PyObject *new_mro, *old_mro;
1975 int reent;
1976
1977 /* Keep a reference to be able to do a reentrancy check below.
1978 Don't let old_mro be GC'ed and its address be reused for
1979 another object, like (suddenly!) a new tp_mro. */
1980 old_mro = type->tp_mro;
1981 Py_XINCREF(old_mro);
1982 new_mro = mro_invoke(type); /* might cause reentrance */
1983 reent = (type->tp_mro != old_mro);
1984 Py_XDECREF(old_mro);
1985 if (new_mro == NULL)
1986 return -1;
1987
1988 if (reent) {
1989 Py_DECREF(new_mro);
1990 return 0;
1991 }
1992
1993 type->tp_mro = new_mro;
Christian Heimesa62da1d2008-01-12 19:39:10 +00001994
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001995 type_mro_modified(type, type->tp_mro);
Florent Xiclunaaa6c1d22011-12-12 18:54:29 +01001996 /* corner case: the super class might have been hidden
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001997 from the custom MRO */
1998 type_mro_modified(type, type->tp_bases);
Christian Heimesa62da1d2008-01-12 19:39:10 +00001999
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002000 PyType_Modified(type);
Christian Heimesa62da1d2008-01-12 19:39:10 +00002001
Benjamin Peterson104b9e02015-02-05 22:29:14 -05002002 if (p_old_mro != NULL)
2003 *p_old_mro = old_mro; /* transfer the ownership */
2004 else
2005 Py_XDECREF(old_mro);
2006
2007 return 1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002008}
2009
2010
2011/* Calculate the best base amongst multiple base classes.
2012 This is the first one that's on the path to the "solid base". */
2013
2014static PyTypeObject *
2015best_base(PyObject *bases)
2016{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002017 Py_ssize_t i, n;
2018 PyTypeObject *base, *winner, *candidate, *base_i;
2019 PyObject *base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002020
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002021 assert(PyTuple_Check(bases));
2022 n = PyTuple_GET_SIZE(bases);
2023 assert(n > 0);
2024 base = NULL;
2025 winner = NULL;
2026 for (i = 0; i < n; i++) {
2027 base_proto = PyTuple_GET_ITEM(bases, i);
2028 if (!PyType_Check(base_proto)) {
2029 PyErr_SetString(
2030 PyExc_TypeError,
2031 "bases must be types");
2032 return NULL;
2033 }
2034 base_i = (PyTypeObject *)base_proto;
2035 if (base_i->tp_dict == NULL) {
2036 if (PyType_Ready(base_i) < 0)
2037 return NULL;
2038 }
Benjamin Petersonbd6c41a2015-10-06 19:36:54 -07002039 if (!PyType_HasFeature(base_i, Py_TPFLAGS_BASETYPE)) {
2040 PyErr_Format(PyExc_TypeError,
2041 "type '%.100s' is not an acceptable base type",
2042 base_i->tp_name);
2043 return NULL;
2044 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002045 candidate = solid_base(base_i);
2046 if (winner == NULL) {
2047 winner = candidate;
2048 base = base_i;
2049 }
2050 else if (PyType_IsSubtype(winner, candidate))
2051 ;
2052 else if (PyType_IsSubtype(candidate, winner)) {
2053 winner = candidate;
2054 base = base_i;
2055 }
2056 else {
2057 PyErr_SetString(
2058 PyExc_TypeError,
2059 "multiple bases have "
2060 "instance lay-out conflict");
2061 return NULL;
2062 }
2063 }
Florent Xiclunaaa6c1d22011-12-12 18:54:29 +01002064 assert (base != NULL);
2065
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002066 return base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002067}
2068
2069static int
2070extra_ivars(PyTypeObject *type, PyTypeObject *base)
2071{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002072 size_t t_size = type->tp_basicsize;
2073 size_t b_size = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002074
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002075 assert(t_size >= b_size); /* Else type smaller than base! */
2076 if (type->tp_itemsize || base->tp_itemsize) {
2077 /* If itemsize is involved, stricter rules */
2078 return t_size != b_size ||
2079 type->tp_itemsize != base->tp_itemsize;
2080 }
2081 if (type->tp_weaklistoffset && base->tp_weaklistoffset == 0 &&
2082 type->tp_weaklistoffset + sizeof(PyObject *) == t_size &&
2083 type->tp_flags & Py_TPFLAGS_HEAPTYPE)
2084 t_size -= sizeof(PyObject *);
2085 if (type->tp_dictoffset && base->tp_dictoffset == 0 &&
2086 type->tp_dictoffset + sizeof(PyObject *) == t_size &&
2087 type->tp_flags & Py_TPFLAGS_HEAPTYPE)
2088 t_size -= sizeof(PyObject *);
Guido van Rossum9676b222001-08-17 20:32:36 +00002089
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002090 return t_size != b_size;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002091}
2092
2093static PyTypeObject *
2094solid_base(PyTypeObject *type)
2095{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002096 PyTypeObject *base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002097
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002098 if (type->tp_base)
2099 base = solid_base(type->tp_base);
2100 else
2101 base = &PyBaseObject_Type;
2102 if (extra_ivars(type, base))
2103 return type;
2104 else
2105 return base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002106}
2107
Jeremy Hylton938ace62002-07-17 16:30:39 +00002108static void object_dealloc(PyObject *);
2109static int object_init(PyObject *, PyObject *, PyObject *);
2110static int update_slot(PyTypeObject *, PyObject *);
2111static void fixup_slot_dispatchers(PyTypeObject *);
Nick Coghland78448e2016-07-30 16:26:03 +10002112static int set_names(PyTypeObject *);
2113static int init_subclass(PyTypeObject *, PyObject *);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002114
Guido van Rossum360e4b82007-05-14 22:51:27 +00002115/*
2116 * Helpers for __dict__ descriptor. We don't want to expose the dicts
2117 * inherited from various builtin types. The builtin base usually provides
2118 * its own __dict__ descriptor, so we use that when we can.
2119 */
2120static PyTypeObject *
2121get_builtin_base_with_dict(PyTypeObject *type)
2122{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002123 while (type->tp_base != NULL) {
2124 if (type->tp_dictoffset != 0 &&
2125 !(type->tp_flags & Py_TPFLAGS_HEAPTYPE))
2126 return type;
2127 type = type->tp_base;
2128 }
2129 return NULL;
Guido van Rossum360e4b82007-05-14 22:51:27 +00002130}
2131
2132static PyObject *
2133get_dict_descriptor(PyTypeObject *type)
2134{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002135 PyObject *descr;
Guido van Rossum360e4b82007-05-14 22:51:27 +00002136
Victor Stinner3c1e4812012-03-26 22:10:51 +02002137 descr = _PyType_LookupId(type, &PyId___dict__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002138 if (descr == NULL || !PyDescr_IsData(descr))
2139 return NULL;
Guido van Rossum360e4b82007-05-14 22:51:27 +00002140
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002141 return descr;
Guido van Rossum360e4b82007-05-14 22:51:27 +00002142}
2143
2144static void
2145raise_dict_descr_error(PyObject *obj)
2146{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002147 PyErr_Format(PyExc_TypeError,
2148 "this __dict__ descriptor does not support "
2149 "'%.200s' objects", Py_TYPE(obj)->tp_name);
Guido van Rossum360e4b82007-05-14 22:51:27 +00002150}
2151
Tim Peters6d6c1a32001-08-02 04:15:00 +00002152static PyObject *
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00002153subtype_dict(PyObject *obj, void *context)
2154{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002155 PyTypeObject *base;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00002156
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002157 base = get_builtin_base_with_dict(Py_TYPE(obj));
2158 if (base != NULL) {
2159 descrgetfunc func;
2160 PyObject *descr = get_dict_descriptor(base);
2161 if (descr == NULL) {
2162 raise_dict_descr_error(obj);
2163 return NULL;
2164 }
2165 func = Py_TYPE(descr)->tp_descr_get;
2166 if (func == NULL) {
2167 raise_dict_descr_error(obj);
2168 return NULL;
2169 }
2170 return func(descr, obj, (PyObject *)(Py_TYPE(obj)));
2171 }
Benjamin Peterson8eb12692012-02-19 19:59:10 -05002172 return PyObject_GenericGetDict(obj, context);
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00002173}
2174
Guido van Rossum6661be32001-10-26 04:26:12 +00002175static int
2176subtype_setdict(PyObject *obj, PyObject *value, void *context)
2177{
Serhiy Storchaka576f1322016-01-05 21:27:54 +02002178 PyObject **dictptr;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002179 PyTypeObject *base;
Guido van Rossum6661be32001-10-26 04:26:12 +00002180
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002181 base = get_builtin_base_with_dict(Py_TYPE(obj));
2182 if (base != NULL) {
2183 descrsetfunc func;
2184 PyObject *descr = get_dict_descriptor(base);
2185 if (descr == NULL) {
2186 raise_dict_descr_error(obj);
2187 return -1;
2188 }
2189 func = Py_TYPE(descr)->tp_descr_set;
2190 if (func == NULL) {
2191 raise_dict_descr_error(obj);
2192 return -1;
2193 }
2194 return func(descr, obj, value);
2195 }
Benjamin Peterson8eb12692012-02-19 19:59:10 -05002196 /* Almost like PyObject_GenericSetDict, but allow __dict__ to be deleted. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002197 dictptr = _PyObject_GetDictPtr(obj);
2198 if (dictptr == NULL) {
2199 PyErr_SetString(PyExc_AttributeError,
2200 "This object has no __dict__");
2201 return -1;
2202 }
Benjamin Peterson006c5a22012-02-19 20:36:12 -05002203 if (value != NULL && !PyDict_Check(value)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002204 PyErr_Format(PyExc_TypeError,
2205 "__dict__ must be set to a dictionary, "
2206 "not a '%.200s'", Py_TYPE(value)->tp_name);
2207 return -1;
2208 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002209 Py_XINCREF(value);
Serhiy Storchakaec397562016-04-06 09:50:03 +03002210 Py_XSETREF(*dictptr, value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002211 return 0;
Guido van Rossum6661be32001-10-26 04:26:12 +00002212}
2213
Guido van Rossumad47da02002-08-12 19:05:44 +00002214static PyObject *
2215subtype_getweakref(PyObject *obj, void *context)
2216{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002217 PyObject **weaklistptr;
2218 PyObject *result;
Victor Stinner08625052018-10-26 18:39:11 +02002219 PyTypeObject *type = Py_TYPE(obj);
Guido van Rossumad47da02002-08-12 19:05:44 +00002220
Victor Stinner08625052018-10-26 18:39:11 +02002221 if (type->tp_weaklistoffset == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002222 PyErr_SetString(PyExc_AttributeError,
2223 "This object has no __weakref__");
2224 return NULL;
2225 }
Victor Stinner08625052018-10-26 18:39:11 +02002226 _PyObject_ASSERT((PyObject *)type,
2227 type->tp_weaklistoffset > 0);
2228 _PyObject_ASSERT((PyObject *)type,
2229 ((type->tp_weaklistoffset + sizeof(PyObject *))
2230 <= (size_t)(type->tp_basicsize)));
2231 weaklistptr = (PyObject **)((char *)obj + type->tp_weaklistoffset);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002232 if (*weaklistptr == NULL)
2233 result = Py_None;
2234 else
2235 result = *weaklistptr;
2236 Py_INCREF(result);
2237 return result;
Guido van Rossumad47da02002-08-12 19:05:44 +00002238}
2239
Guido van Rossum373c7412003-01-07 13:41:37 +00002240/* Three variants on the subtype_getsets list. */
2241
2242static PyGetSetDef subtype_getsets_full[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002243 {"__dict__", subtype_dict, subtype_setdict,
2244 PyDoc_STR("dictionary for instance variables (if defined)")},
2245 {"__weakref__", subtype_getweakref, NULL,
2246 PyDoc_STR("list of weak references to the object (if defined)")},
2247 {0}
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00002248};
2249
Guido van Rossum373c7412003-01-07 13:41:37 +00002250static PyGetSetDef subtype_getsets_dict_only[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002251 {"__dict__", subtype_dict, subtype_setdict,
2252 PyDoc_STR("dictionary for instance variables (if defined)")},
2253 {0}
Guido van Rossum373c7412003-01-07 13:41:37 +00002254};
2255
2256static PyGetSetDef subtype_getsets_weakref_only[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002257 {"__weakref__", subtype_getweakref, NULL,
2258 PyDoc_STR("list of weak references to the object (if defined)")},
2259 {0}
Guido van Rossum373c7412003-01-07 13:41:37 +00002260};
2261
Guido van Rossum9923ffe2002-06-04 19:52:53 +00002262static int
2263valid_identifier(PyObject *s)
2264{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002265 if (!PyUnicode_Check(s)) {
2266 PyErr_Format(PyExc_TypeError,
2267 "__slots__ items must be strings, not '%.200s'",
2268 Py_TYPE(s)->tp_name);
2269 return 0;
2270 }
2271 if (!PyUnicode_IsIdentifier(s)) {
2272 PyErr_SetString(PyExc_TypeError,
2273 "__slots__ must be identifiers");
2274 return 0;
2275 }
2276 return 1;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00002277}
2278
Guido van Rossumd8faa362007-04-27 19:54:29 +00002279/* Forward */
2280static int
2281object_init(PyObject *self, PyObject *args, PyObject *kwds);
2282
2283static int
2284type_init(PyObject *cls, PyObject *args, PyObject *kwds)
2285{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002286 int res;
Guido van Rossumd8faa362007-04-27 19:54:29 +00002287
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002288 assert(args != NULL && PyTuple_Check(args));
2289 assert(kwds == NULL || PyDict_Check(kwds));
Guido van Rossumd8faa362007-04-27 19:54:29 +00002290
Nick Coghland78448e2016-07-30 16:26:03 +10002291 if (kwds != NULL && PyTuple_Check(args) && PyTuple_GET_SIZE(args) == 1 &&
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02002292 PyDict_Check(kwds) && PyDict_GET_SIZE(kwds) != 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002293 PyErr_SetString(PyExc_TypeError,
2294 "type.__init__() takes no keyword arguments");
2295 return -1;
2296 }
Guido van Rossumd8faa362007-04-27 19:54:29 +00002297
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002298 if (args != NULL && PyTuple_Check(args) &&
2299 (PyTuple_GET_SIZE(args) != 1 && PyTuple_GET_SIZE(args) != 3)) {
2300 PyErr_SetString(PyExc_TypeError,
2301 "type.__init__() takes 1 or 3 arguments");
2302 return -1;
2303 }
Guido van Rossumd8faa362007-04-27 19:54:29 +00002304
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002305 /* Call object.__init__(self) now. */
2306 /* XXX Could call super(type, cls).__init__() but what's the point? */
2307 args = PyTuple_GetSlice(args, 0, 0);
Alexey Izbyshevf6247aa2018-08-24 07:22:16 +03002308 if (args == NULL) {
2309 return -1;
2310 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002311 res = object_init(cls, args, NULL);
2312 Py_DECREF(args);
2313 return res;
Guido van Rossumd8faa362007-04-27 19:54:29 +00002314}
2315
Victor Stinner4ca1cf32012-10-30 23:40:45 +01002316unsigned long
Martin v. Löwis738236d2011-02-05 20:35:29 +00002317PyType_GetFlags(PyTypeObject *type)
2318{
2319 return type->tp_flags;
2320}
2321
Nick Coghlande31b192011-10-23 22:04:16 +10002322/* Determine the most derived metatype. */
2323PyTypeObject *
2324_PyType_CalculateMetaclass(PyTypeObject *metatype, PyObject *bases)
2325{
2326 Py_ssize_t i, nbases;
2327 PyTypeObject *winner;
2328 PyObject *tmp;
2329 PyTypeObject *tmptype;
2330
2331 /* Determine the proper metatype to deal with this,
2332 and check for metatype conflicts while we're at it.
2333 Note that if some other metatype wins to contract,
2334 it's possible that its instances are not types. */
2335
2336 nbases = PyTuple_GET_SIZE(bases);
2337 winner = metatype;
2338 for (i = 0; i < nbases; i++) {
2339 tmp = PyTuple_GET_ITEM(bases, i);
2340 tmptype = Py_TYPE(tmp);
2341 if (PyType_IsSubtype(winner, tmptype))
2342 continue;
2343 if (PyType_IsSubtype(tmptype, winner)) {
2344 winner = tmptype;
2345 continue;
2346 }
2347 /* else: */
2348 PyErr_SetString(PyExc_TypeError,
2349 "metaclass conflict: "
2350 "the metaclass of a derived class "
2351 "must be a (non-strict) subclass "
2352 "of the metaclasses of all its bases");
2353 return NULL;
2354 }
2355 return winner;
2356}
2357
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00002358static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00002359type_new(PyTypeObject *metatype, PyObject *args, PyObject *kwds)
2360{
Victor Stinner6f738742012-02-25 01:22:36 +01002361 PyObject *name, *bases = NULL, *orig_dict, *dict = NULL;
Nick Coghlan944368e2016-09-11 14:45:49 +10002362 PyObject *qualname, *slots = NULL, *tmp, *newslots, *cell;
Victor Stinner6f738742012-02-25 01:22:36 +01002363 PyTypeObject *type = NULL, *base, *tmptype, *winner;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002364 PyHeapTypeObject *et;
2365 PyMemberDef *mp;
Serhiy Storchaka42bf8fc2015-12-30 21:40:49 +02002366 Py_ssize_t i, nbases, nslots, slotoffset, name_size;
2367 int j, may_add_dict, may_add_weak, add_dict, add_weak;
Victor Stinner3c1e4812012-03-26 22:10:51 +02002368 _Py_IDENTIFIER(__qualname__);
2369 _Py_IDENTIFIER(__slots__);
Nick Coghlan944368e2016-09-11 14:45:49 +10002370 _Py_IDENTIFIER(__classcell__);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002371
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002372 assert(args != NULL && PyTuple_Check(args));
2373 assert(kwds == NULL || PyDict_Check(kwds));
Tim Peters3abca122001-10-27 19:37:48 +00002374
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002375 /* Special case: type(x) should return x->ob_type */
Berker Peksag3f015a62016-08-19 11:04:07 +03002376 /* We only want type itself to accept the one-argument form (#27157)
2377 Note: We don't call PyType_CheckExact as that also allows subclasses */
2378 if (metatype == &PyType_Type) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002379 const Py_ssize_t nargs = PyTuple_GET_SIZE(args);
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02002380 const Py_ssize_t nkwds = kwds == NULL ? 0 : PyDict_GET_SIZE(kwds);
Tim Peters3abca122001-10-27 19:37:48 +00002381
Berker Peksag3f015a62016-08-19 11:04:07 +03002382 if (nargs == 1 && nkwds == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002383 PyObject *x = PyTuple_GET_ITEM(args, 0);
2384 Py_INCREF(Py_TYPE(x));
2385 return (PyObject *) Py_TYPE(x);
2386 }
Tim Peters3abca122001-10-27 19:37:48 +00002387
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002388 /* SF bug 475327 -- if that didn't trigger, we need 3
Berker Peksag78e24d42018-01-04 13:24:45 +03002389 arguments. but PyArg_ParseTuple below may give
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002390 a msg saying type() needs exactly 3. */
Nick Coghland78448e2016-07-30 16:26:03 +10002391 if (nargs != 3) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002392 PyErr_SetString(PyExc_TypeError,
2393 "type() takes 1 or 3 arguments");
2394 return NULL;
2395 }
2396 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002397
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002398 /* Check arguments: (name, bases, dict) */
Berker Peksag3f015a62016-08-19 11:04:07 +03002399 if (!PyArg_ParseTuple(args, "UO!O!:type.__new__", &name, &PyTuple_Type,
2400 &bases, &PyDict_Type, &orig_dict))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002401 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002402
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002403 /* Adjust for empty tuple bases */
Nick Coghlande31b192011-10-23 22:04:16 +10002404 nbases = PyTuple_GET_SIZE(bases);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002405 if (nbases == 0) {
scoder2102c782017-10-01 10:37:47 +02002406 base = &PyBaseObject_Type;
2407 bases = PyTuple_Pack(1, base);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002408 if (bases == NULL)
scoder2102c782017-10-01 10:37:47 +02002409 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002410 nbases = 1;
2411 }
scoder2102c782017-10-01 10:37:47 +02002412 else {
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +01002413 _Py_IDENTIFIER(__mro_entries__);
2414 for (i = 0; i < nbases; i++) {
2415 tmp = PyTuple_GET_ITEM(bases, i);
2416 if (PyType_Check(tmp)) {
2417 continue;
2418 }
Serhiy Storchakaf320be72018-01-25 10:49:40 +02002419 if (_PyObject_LookupAttrId(tmp, &PyId___mro_entries__, &tmp) < 0) {
2420 return NULL;
2421 }
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +01002422 if (tmp != NULL) {
2423 PyErr_SetString(PyExc_TypeError,
2424 "type() doesn't support MRO entry resolution; "
2425 "use types.new_class()");
2426 Py_DECREF(tmp);
2427 return NULL;
2428 }
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +01002429 }
scoder2102c782017-10-01 10:37:47 +02002430 /* Search the bases for the proper metatype to deal with this: */
2431 winner = _PyType_CalculateMetaclass(metatype, bases);
2432 if (winner == NULL) {
2433 return NULL;
2434 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002435
scoder2102c782017-10-01 10:37:47 +02002436 if (winner != metatype) {
2437 if (winner->tp_new != type_new) /* Pass it to the winner */
2438 return winner->tp_new(winner, args, kwds);
2439 metatype = winner;
2440 }
2441
2442 /* Calculate best base, and check that all bases are type objects */
2443 base = best_base(bases);
2444 if (base == NULL) {
2445 return NULL;
2446 }
2447
2448 Py_INCREF(bases);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002449 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002450
scoder2102c782017-10-01 10:37:47 +02002451 /* Use "goto error" from this point on as we now own the reference to "bases". */
2452
Victor Stinner6f738742012-02-25 01:22:36 +01002453 dict = PyDict_Copy(orig_dict);
2454 if (dict == NULL)
2455 goto error;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002456
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002457 /* Check for a __slots__ sequence variable in dict, and count it */
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02002458 slots = _PyDict_GetItemIdWithError(dict, &PyId___slots__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002459 nslots = 0;
2460 add_dict = 0;
2461 add_weak = 0;
2462 may_add_dict = base->tp_dictoffset == 0;
2463 may_add_weak = base->tp_weaklistoffset == 0 && base->tp_itemsize == 0;
2464 if (slots == NULL) {
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02002465 if (PyErr_Occurred()) {
2466 goto error;
2467 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002468 if (may_add_dict) {
2469 add_dict++;
2470 }
2471 if (may_add_weak) {
2472 add_weak++;
2473 }
2474 }
2475 else {
2476 /* Have slots */
Guido van Rossumad47da02002-08-12 19:05:44 +00002477
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002478 /* Make it into a tuple */
2479 if (PyUnicode_Check(slots))
2480 slots = PyTuple_Pack(1, slots);
2481 else
2482 slots = PySequence_Tuple(slots);
Victor Stinner6f738742012-02-25 01:22:36 +01002483 if (slots == NULL)
2484 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002485 assert(PyTuple_Check(slots));
Guido van Rossumad47da02002-08-12 19:05:44 +00002486
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002487 /* Are slots allowed? */
2488 nslots = PyTuple_GET_SIZE(slots);
2489 if (nslots > 0 && base->tp_itemsize != 0) {
2490 PyErr_Format(PyExc_TypeError,
2491 "nonempty __slots__ "
2492 "not supported for subtype of '%s'",
2493 base->tp_name);
Victor Stinner6f738742012-02-25 01:22:36 +01002494 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002495 }
Guido van Rossumad47da02002-08-12 19:05:44 +00002496
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002497 /* Check for valid slot names and two special cases */
2498 for (i = 0; i < nslots; i++) {
2499 PyObject *tmp = PyTuple_GET_ITEM(slots, i);
2500 if (!valid_identifier(tmp))
Victor Stinner6f738742012-02-25 01:22:36 +01002501 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002502 assert(PyUnicode_Check(tmp));
Serhiy Storchakaf5894dd2016-11-16 15:40:39 +02002503 if (_PyUnicode_EqualToASCIIId(tmp, &PyId___dict__)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002504 if (!may_add_dict || add_dict) {
2505 PyErr_SetString(PyExc_TypeError,
2506 "__dict__ slot disallowed: "
2507 "we already got one");
Victor Stinner6f738742012-02-25 01:22:36 +01002508 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002509 }
2510 add_dict++;
2511 }
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02002512 if (_PyUnicode_EqualToASCIIString(tmp, "__weakref__")) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002513 if (!may_add_weak || add_weak) {
2514 PyErr_SetString(PyExc_TypeError,
2515 "__weakref__ slot disallowed: "
2516 "either we already got one, "
2517 "or __itemsize__ != 0");
Victor Stinner6f738742012-02-25 01:22:36 +01002518 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002519 }
2520 add_weak++;
2521 }
2522 }
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00002523
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002524 /* Copy slots into a list, mangle names and sort them.
2525 Sorted names are needed for __class__ assignment.
2526 Convert them back to tuple at the end.
2527 */
2528 newslots = PyList_New(nslots - add_dict - add_weak);
2529 if (newslots == NULL)
Victor Stinner6f738742012-02-25 01:22:36 +01002530 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002531 for (i = j = 0; i < nslots; i++) {
2532 tmp = PyTuple_GET_ITEM(slots, i);
2533 if ((add_dict &&
Serhiy Storchakaf5894dd2016-11-16 15:40:39 +02002534 _PyUnicode_EqualToASCIIId(tmp, &PyId___dict__)) ||
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002535 (add_weak &&
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02002536 _PyUnicode_EqualToASCIIString(tmp, "__weakref__")))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002537 continue;
2538 tmp =_Py_Mangle(name, tmp);
Benjamin Petersonae13c882011-08-16 22:26:48 -05002539 if (!tmp) {
2540 Py_DECREF(newslots);
Victor Stinner6f738742012-02-25 01:22:36 +01002541 goto error;
Benjamin Petersonae13c882011-08-16 22:26:48 -05002542 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002543 PyList_SET_ITEM(newslots, j, tmp);
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02002544 if (PyDict_GetItemWithError(dict, tmp)) {
Xiang Zhangc393ee82017-03-08 11:18:49 +08002545 /* CPython inserts __qualname__ and __classcell__ (when needed)
2546 into the namespace when creating a class. They will be deleted
2547 below so won't act as class variables. */
2548 if (!_PyUnicode_EqualToASCIIId(tmp, &PyId___qualname__) &&
2549 !_PyUnicode_EqualToASCIIId(tmp, &PyId___classcell__)) {
2550 PyErr_Format(PyExc_ValueError,
2551 "%R in __slots__ conflicts with class variable",
2552 tmp);
2553 Py_DECREF(newslots);
2554 goto error;
2555 }
Benjamin Petersonc4085c82011-08-16 18:53:26 -05002556 }
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02002557 else if (PyErr_Occurred()) {
2558 Py_DECREF(newslots);
2559 goto error;
2560 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002561 j++;
2562 }
2563 assert(j == nslots - add_dict - add_weak);
2564 nslots = j;
Victor Stinner6f738742012-02-25 01:22:36 +01002565 Py_CLEAR(slots);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002566 if (PyList_Sort(newslots) == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002567 Py_DECREF(newslots);
Victor Stinner6f738742012-02-25 01:22:36 +01002568 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002569 }
2570 slots = PyList_AsTuple(newslots);
2571 Py_DECREF(newslots);
Victor Stinner6f738742012-02-25 01:22:36 +01002572 if (slots == NULL)
2573 goto error;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00002574
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002575 /* Secondary bases may provide weakrefs or dict */
2576 if (nbases > 1 &&
2577 ((may_add_dict && !add_dict) ||
2578 (may_add_weak && !add_weak))) {
2579 for (i = 0; i < nbases; i++) {
2580 tmp = PyTuple_GET_ITEM(bases, i);
2581 if (tmp == (PyObject *)base)
2582 continue; /* Skip primary base */
2583 assert(PyType_Check(tmp));
2584 tmptype = (PyTypeObject *)tmp;
2585 if (may_add_dict && !add_dict &&
2586 tmptype->tp_dictoffset != 0)
2587 add_dict++;
2588 if (may_add_weak && !add_weak &&
2589 tmptype->tp_weaklistoffset != 0)
2590 add_weak++;
2591 if (may_add_dict && !add_dict)
2592 continue;
2593 if (may_add_weak && !add_weak)
2594 continue;
2595 /* Nothing more to check */
2596 break;
2597 }
2598 }
2599 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002600
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002601 /* Allocate the type object */
2602 type = (PyTypeObject *)metatype->tp_alloc(metatype, nslots);
Victor Stinner6f738742012-02-25 01:22:36 +01002603 if (type == NULL)
2604 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002605
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002606 /* Keep name and slots alive in the extended type object */
2607 et = (PyHeapTypeObject *)type;
2608 Py_INCREF(name);
2609 et->ht_name = name;
2610 et->ht_slots = slots;
Victor Stinner6f738742012-02-25 01:22:36 +01002611 slots = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002612
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002613 /* Initialize tp_flags */
2614 type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE |
Antoine Pitrou796564c2013-07-30 19:59:21 +02002615 Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_FINALIZE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002616 if (base->tp_flags & Py_TPFLAGS_HAVE_GC)
2617 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossumdc91b992001-08-08 22:26:22 +00002618
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002619 /* Initialize essential fields */
Yury Selivanov75445082015-05-11 22:57:16 -04002620 type->tp_as_async = &et->as_async;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002621 type->tp_as_number = &et->as_number;
2622 type->tp_as_sequence = &et->as_sequence;
2623 type->tp_as_mapping = &et->as_mapping;
2624 type->tp_as_buffer = &et->as_buffer;
Serhiy Storchaka42bf8fc2015-12-30 21:40:49 +02002625 type->tp_name = PyUnicode_AsUTF8AndSize(name, &name_size);
Victor Stinner6f738742012-02-25 01:22:36 +01002626 if (!type->tp_name)
2627 goto error;
Serhiy Storchaka42bf8fc2015-12-30 21:40:49 +02002628 if (strlen(type->tp_name) != (size_t)name_size) {
2629 PyErr_SetString(PyExc_ValueError,
2630 "type name must not contain null characters");
2631 goto error;
2632 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002633
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002634 /* Set tp_base and tp_bases */
2635 type->tp_bases = bases;
Victor Stinner6f738742012-02-25 01:22:36 +01002636 bases = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002637 Py_INCREF(base);
2638 type->tp_base = base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002639
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002640 /* Initialize tp_dict from passed-in dict */
Victor Stinner6f738742012-02-25 01:22:36 +01002641 Py_INCREF(dict);
2642 type->tp_dict = dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002643
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002644 /* Set __module__ in the dict */
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02002645 if (_PyDict_GetItemIdWithError(dict, &PyId___module__) == NULL) {
2646 if (PyErr_Occurred()) {
2647 goto error;
2648 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002649 tmp = PyEval_GetGlobals();
2650 if (tmp != NULL) {
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02002651 tmp = _PyDict_GetItemIdWithError(tmp, &PyId___name__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002652 if (tmp != NULL) {
Victor Stinner3c1e4812012-03-26 22:10:51 +02002653 if (_PyDict_SetItemId(dict, &PyId___module__,
2654 tmp) < 0)
Victor Stinner6f738742012-02-25 01:22:36 +01002655 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002656 }
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02002657 else if (PyErr_Occurred()) {
2658 goto error;
2659 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002660 }
2661 }
Guido van Rossumc3542212001-08-16 09:18:56 +00002662
Victor Stinner6f738742012-02-25 01:22:36 +01002663 /* Set ht_qualname to dict['__qualname__'] if available, else to
2664 __name__. The __qualname__ accessor will look for ht_qualname.
2665 */
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02002666 qualname = _PyDict_GetItemIdWithError(dict, &PyId___qualname__);
Victor Stinner6f738742012-02-25 01:22:36 +01002667 if (qualname != NULL) {
2668 if (!PyUnicode_Check(qualname)) {
2669 PyErr_Format(PyExc_TypeError,
2670 "type __qualname__ must be a str, not %s",
2671 Py_TYPE(qualname)->tp_name);
2672 goto error;
2673 }
2674 }
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02002675 else if (PyErr_Occurred()) {
2676 goto error;
2677 }
Benjamin Peterson8afa7fa2012-10-30 23:51:03 -04002678 et->ht_qualname = qualname ? qualname : et->ht_name;
2679 Py_INCREF(et->ht_qualname);
Nick Coghlan944368e2016-09-11 14:45:49 +10002680 if (qualname != NULL && _PyDict_DelItemId(dict, &PyId___qualname__) < 0)
Benjamin Peterson8afa7fa2012-10-30 23:51:03 -04002681 goto error;
Victor Stinner6f738742012-02-25 01:22:36 +01002682
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002683 /* Set tp_doc to a copy of dict['__doc__'], if the latter is there
2684 and is a string. The __doc__ accessor will first look for tp_doc;
2685 if that fails, it will still look into __dict__.
2686 */
2687 {
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02002688 PyObject *doc = _PyDict_GetItemIdWithError(dict, &PyId___doc__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002689 if (doc != NULL && PyUnicode_Check(doc)) {
2690 Py_ssize_t len;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02002691 const char *doc_str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002692 char *tp_doc;
Alexandre Vassalottia85998a2008-05-03 18:24:43 +00002693
Serhiy Storchaka06515832016-11-20 09:13:07 +02002694 doc_str = PyUnicode_AsUTF8(doc);
Victor Stinner6f738742012-02-25 01:22:36 +01002695 if (doc_str == NULL)
2696 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002697 /* Silently truncate the docstring if it contains null bytes. */
2698 len = strlen(doc_str);
2699 tp_doc = (char *)PyObject_MALLOC(len + 1);
Victor Stinner53510cd2013-07-15 19:34:20 +02002700 if (tp_doc == NULL) {
2701 PyErr_NoMemory();
Victor Stinner6f738742012-02-25 01:22:36 +01002702 goto error;
Victor Stinner53510cd2013-07-15 19:34:20 +02002703 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002704 memcpy(tp_doc, doc_str, len + 1);
2705 type->tp_doc = tp_doc;
2706 }
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02002707 else if (doc == NULL && PyErr_Occurred()) {
2708 goto error;
2709 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002710 }
Tim Peters2f93e282001-10-04 05:27:00 +00002711
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002712 /* Special-case __new__: if it's a plain function,
2713 make it a static function */
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02002714 tmp = _PyDict_GetItemIdWithError(dict, &PyId___new__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002715 if (tmp != NULL && PyFunction_Check(tmp)) {
2716 tmp = PyStaticMethod_New(tmp);
Victor Stinner6f738742012-02-25 01:22:36 +01002717 if (tmp == NULL)
2718 goto error;
Serhiy Storchaka484c9132016-06-05 10:48:36 +03002719 if (_PyDict_SetItemId(dict, &PyId___new__, tmp) < 0) {
2720 Py_DECREF(tmp);
Victor Stinner3c1e4812012-03-26 22:10:51 +02002721 goto error;
Serhiy Storchaka484c9132016-06-05 10:48:36 +03002722 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002723 Py_DECREF(tmp);
2724 }
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02002725 else if (tmp == NULL && PyErr_Occurred()) {
2726 goto error;
2727 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002728
Serhiy Storchakace5b0e92018-01-05 00:21:41 +02002729 /* Special-case __init_subclass__ and __class_getitem__:
2730 if they are plain functions, make them classmethods */
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02002731 tmp = _PyDict_GetItemIdWithError(dict, &PyId___init_subclass__);
Nick Coghland78448e2016-07-30 16:26:03 +10002732 if (tmp != NULL && PyFunction_Check(tmp)) {
2733 tmp = PyClassMethod_New(tmp);
2734 if (tmp == NULL)
2735 goto error;
2736 if (_PyDict_SetItemId(dict, &PyId___init_subclass__, tmp) < 0) {
2737 Py_DECREF(tmp);
2738 goto error;
2739 }
2740 Py_DECREF(tmp);
2741 }
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02002742 else if (tmp == NULL && PyErr_Occurred()) {
2743 goto error;
2744 }
Nick Coghland78448e2016-07-30 16:26:03 +10002745
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02002746 tmp = _PyDict_GetItemIdWithError(dict, &PyId___class_getitem__);
Serhiy Storchakace5b0e92018-01-05 00:21:41 +02002747 if (tmp != NULL && PyFunction_Check(tmp)) {
2748 tmp = PyClassMethod_New(tmp);
2749 if (tmp == NULL)
2750 goto error;
2751 if (_PyDict_SetItemId(dict, &PyId___class_getitem__, tmp) < 0) {
2752 Py_DECREF(tmp);
2753 goto error;
2754 }
2755 Py_DECREF(tmp);
2756 }
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02002757 else if (tmp == NULL && PyErr_Occurred()) {
2758 goto error;
2759 }
Serhiy Storchakace5b0e92018-01-05 00:21:41 +02002760
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002761 /* Add descriptors for custom slots from __slots__, or for __dict__ */
2762 mp = PyHeapType_GET_MEMBERS(et);
2763 slotoffset = base->tp_basicsize;
Victor Stinner6f738742012-02-25 01:22:36 +01002764 if (et->ht_slots != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002765 for (i = 0; i < nslots; i++, mp++) {
Serhiy Storchaka06515832016-11-20 09:13:07 +02002766 mp->name = PyUnicode_AsUTF8(
Victor Stinner6f738742012-02-25 01:22:36 +01002767 PyTuple_GET_ITEM(et->ht_slots, i));
2768 if (mp->name == NULL)
2769 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002770 mp->type = T_OBJECT_EX;
2771 mp->offset = slotoffset;
Guido van Rossumd8faa362007-04-27 19:54:29 +00002772
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002773 /* __dict__ and __weakref__ are already filtered out */
2774 assert(strcmp(mp->name, "__dict__") != 0);
2775 assert(strcmp(mp->name, "__weakref__") != 0);
Guido van Rossumd8faa362007-04-27 19:54:29 +00002776
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002777 slotoffset += sizeof(PyObject *);
2778 }
2779 }
2780 if (add_dict) {
2781 if (base->tp_itemsize)
2782 type->tp_dictoffset = -(long)sizeof(PyObject *);
2783 else
2784 type->tp_dictoffset = slotoffset;
2785 slotoffset += sizeof(PyObject *);
2786 }
2787 if (add_weak) {
2788 assert(!base->tp_itemsize);
2789 type->tp_weaklistoffset = slotoffset;
2790 slotoffset += sizeof(PyObject *);
2791 }
2792 type->tp_basicsize = slotoffset;
2793 type->tp_itemsize = base->tp_itemsize;
2794 type->tp_members = PyHeapType_GET_MEMBERS(et);
Guido van Rossum373c7412003-01-07 13:41:37 +00002795
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002796 if (type->tp_weaklistoffset && type->tp_dictoffset)
2797 type->tp_getset = subtype_getsets_full;
2798 else if (type->tp_weaklistoffset && !type->tp_dictoffset)
2799 type->tp_getset = subtype_getsets_weakref_only;
2800 else if (!type->tp_weaklistoffset && type->tp_dictoffset)
2801 type->tp_getset = subtype_getsets_dict_only;
2802 else
2803 type->tp_getset = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002804
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002805 /* Special case some slots */
2806 if (type->tp_dictoffset != 0 || nslots > 0) {
2807 if (base->tp_getattr == NULL && base->tp_getattro == NULL)
2808 type->tp_getattro = PyObject_GenericGetAttr;
2809 if (base->tp_setattr == NULL && base->tp_setattro == NULL)
2810 type->tp_setattro = PyObject_GenericSetAttr;
2811 }
2812 type->tp_dealloc = subtype_dealloc;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002813
Antoine Pitroua63cc212015-04-13 20:10:06 +02002814 /* Enable GC unless this class is not adding new instance variables and
2815 the base class did not use GC. */
2816 if ((base->tp_flags & Py_TPFLAGS_HAVE_GC) ||
2817 type->tp_basicsize > base->tp_basicsize)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002818 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossum9475a232001-10-05 20:51:39 +00002819
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002820 /* Always override allocation strategy to use regular heap */
2821 type->tp_alloc = PyType_GenericAlloc;
2822 if (type->tp_flags & Py_TPFLAGS_HAVE_GC) {
2823 type->tp_free = PyObject_GC_Del;
2824 type->tp_traverse = subtype_traverse;
2825 type->tp_clear = subtype_clear;
2826 }
2827 else
2828 type->tp_free = PyObject_Del;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002829
Nick Coghlan19d24672016-12-05 16:47:55 +10002830 /* store type in class' cell if one is supplied */
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02002831 cell = _PyDict_GetItemIdWithError(dict, &PyId___classcell__);
Nick Coghlan19d24672016-12-05 16:47:55 +10002832 if (cell != NULL) {
2833 /* At least one method requires a reference to its defining class */
2834 if (!PyCell_Check(cell)) {
2835 PyErr_Format(PyExc_TypeError,
2836 "__classcell__ must be a nonlocal cell, not %.200R",
2837 Py_TYPE(cell));
2838 goto error;
2839 }
Nick Coghlan944368e2016-09-11 14:45:49 +10002840 PyCell_Set(cell, (PyObject *) type);
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02002841 if (_PyDict_DelItemId(dict, &PyId___classcell__) < 0) {
2842 goto error;
2843 }
2844 }
2845 else if (PyErr_Occurred()) {
2846 goto error;
Nick Coghlan944368e2016-09-11 14:45:49 +10002847 }
2848
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002849 /* Initialize the rest */
Victor Stinner6f738742012-02-25 01:22:36 +01002850 if (PyType_Ready(type) < 0)
2851 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002852
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002853 /* Put the proper slots in place */
2854 fixup_slot_dispatchers(type);
Guido van Rossumf040ede2001-08-07 16:40:56 +00002855
Benjamin Petersondf813792014-03-17 15:57:17 -05002856 if (type->tp_dictoffset) {
2857 et->ht_cached_keys = _PyDict_NewKeysForClass();
2858 }
2859
Nick Coghland78448e2016-07-30 16:26:03 +10002860 if (set_names(type) < 0)
2861 goto error;
2862
2863 if (init_subclass(type, kwds) < 0)
2864 goto error;
2865
Victor Stinner6f738742012-02-25 01:22:36 +01002866 Py_DECREF(dict);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002867 return (PyObject *)type;
Victor Stinner6f738742012-02-25 01:22:36 +01002868
2869error:
2870 Py_XDECREF(dict);
2871 Py_XDECREF(bases);
2872 Py_XDECREF(slots);
2873 Py_XDECREF(type);
2874 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002875}
2876
Serhiy Storchaka2d06e842015-12-25 19:53:18 +02002877static const short slotoffsets[] = {
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002878 -1, /* invalid slot */
2879#include "typeslots.inc"
2880};
2881
Benjamin Petersone28108c2012-01-29 20:13:18 -05002882PyObject *
Martin v. Löwis9c564092012-06-23 23:20:45 +02002883PyType_FromSpecWithBases(PyType_Spec *spec, PyObject *bases)
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002884{
Eddie Elizondo474eedf2018-11-13 04:09:31 -08002885 PyHeapTypeObject *res;
2886 PyMemberDef *memb;
Nick Coghlana48db2b2015-05-24 01:03:46 +10002887 PyObject *modname;
Eddie Elizondo474eedf2018-11-13 04:09:31 -08002888 PyTypeObject *type, *base;
Victor Stinner54e4ca72013-07-11 22:42:25 +02002889
Eddie Elizondo474eedf2018-11-13 04:09:31 -08002890 PyType_Slot *slot;
2891 Py_ssize_t nmembers;
2892 char *s, *res_start;
2893
2894 nmembers = 0;
2895 for (slot = spec->slots; slot->slot; slot++) {
2896 if (slot->slot == Py_tp_members) {
2897 for (memb = slot->pfunc; memb->name != NULL; memb++) {
2898 nmembers++;
2899 }
2900 }
2901 }
2902
2903 res = (PyHeapTypeObject*)PyType_GenericAlloc(&PyType_Type, nmembers);
Alexey Izbyshev5f79b502018-08-25 21:53:47 +03002904 if (res == NULL)
2905 return NULL;
Eddie Elizondo474eedf2018-11-13 04:09:31 -08002906 res_start = (char*)res;
Alexey Izbyshev5f79b502018-08-25 21:53:47 +03002907
2908 if (spec->name == NULL) {
2909 PyErr_SetString(PyExc_SystemError,
2910 "Type spec does not define the name field.");
2911 goto fail;
2912 }
2913
Martin v. Löwis9c564092012-06-23 23:20:45 +02002914 /* Set the type name and qualname */
2915 s = strrchr(spec->name, '.');
2916 if (s == NULL)
2917 s = (char*)spec->name;
2918 else
2919 s++;
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002920
Antoine Pitroubb78f572012-06-24 00:18:27 +02002921 type = &res->ht_type;
Antoine Pitrou66a3a7e2012-06-24 00:42:59 +02002922 /* The flags must be initialized early, before the GC traverses us */
2923 type->tp_flags = spec->flags | Py_TPFLAGS_HEAPTYPE;
Martin v. Löwis9c564092012-06-23 23:20:45 +02002924 res->ht_name = PyUnicode_FromString(s);
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002925 if (!res->ht_name)
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002926 goto fail;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002927 res->ht_qualname = res->ht_name;
2928 Py_INCREF(res->ht_qualname);
Antoine Pitroubb78f572012-06-24 00:18:27 +02002929 type->tp_name = spec->name;
Victor Stinner54e4ca72013-07-11 22:42:25 +02002930
Martin v. Löwis9c564092012-06-23 23:20:45 +02002931 /* Adjust for empty tuple bases */
2932 if (!bases) {
2933 base = &PyBaseObject_Type;
2934 /* See whether Py_tp_base(s) was specified */
2935 for (slot = spec->slots; slot->slot; slot++) {
2936 if (slot->slot == Py_tp_base)
2937 base = slot->pfunc;
2938 else if (slot->slot == Py_tp_bases) {
2939 bases = slot->pfunc;
2940 Py_INCREF(bases);
2941 }
2942 }
2943 if (!bases)
2944 bases = PyTuple_Pack(1, base);
2945 if (!bases)
2946 goto fail;
2947 }
2948 else
2949 Py_INCREF(bases);
2950
2951 /* Calculate best base, and check that all bases are type objects */
2952 base = best_base(bases);
2953 if (base == NULL) {
2954 goto fail;
2955 }
2956 if (!PyType_HasFeature(base, Py_TPFLAGS_BASETYPE)) {
2957 PyErr_Format(PyExc_TypeError,
2958 "type '%.100s' is not an acceptable base type",
2959 base->tp_name);
2960 goto fail;
2961 }
2962
Martin v. Löwis9c564092012-06-23 23:20:45 +02002963 /* Initialize essential fields */
Yury Selivanov75445082015-05-11 22:57:16 -04002964 type->tp_as_async = &res->as_async;
Martin v. Löwis9c564092012-06-23 23:20:45 +02002965 type->tp_as_number = &res->as_number;
2966 type->tp_as_sequence = &res->as_sequence;
2967 type->tp_as_mapping = &res->as_mapping;
2968 type->tp_as_buffer = &res->as_buffer;
2969 /* Set tp_base and tp_bases */
2970 type->tp_bases = bases;
2971 bases = NULL;
2972 Py_INCREF(base);
2973 type->tp_base = base;
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002974
Antoine Pitroubb78f572012-06-24 00:18:27 +02002975 type->tp_basicsize = spec->basicsize;
2976 type->tp_itemsize = spec->itemsize;
Victor Stinner0fcab4a2011-01-04 12:59:15 +00002977
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002978 for (slot = spec->slots; slot->slot; slot++) {
Victor Stinner12174a52014-08-15 23:17:38 +02002979 if (slot->slot < 0
2980 || (size_t)slot->slot >= Py_ARRAY_LENGTH(slotoffsets)) {
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002981 PyErr_SetString(PyExc_RuntimeError, "invalid slot offset");
2982 goto fail;
2983 }
Martin v. Löwis9c564092012-06-23 23:20:45 +02002984 if (slot->slot == Py_tp_base || slot->slot == Py_tp_bases)
2985 /* Processed above */
2986 continue;
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002987 *(void**)(res_start + slotoffsets[slot->slot]) = slot->pfunc;
Georg Brandl032400b2011-02-19 21:47:02 +00002988
2989 /* need to make a copy of the docstring slot, which usually
2990 points to a static string literal */
2991 if (slot->slot == Py_tp_doc) {
Larry Hastings2623c8c2014-02-08 22:15:29 -08002992 const char *old_doc = _PyType_DocWithoutSignature(type->tp_name, slot->pfunc);
Larry Hastings5c661892014-01-24 06:17:25 -08002993 size_t len = strlen(old_doc)+1;
Georg Brandl032400b2011-02-19 21:47:02 +00002994 char *tp_doc = PyObject_MALLOC(len);
Victor Stinner53510cd2013-07-15 19:34:20 +02002995 if (tp_doc == NULL) {
2996 PyErr_NoMemory();
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002997 goto fail;
Victor Stinner53510cd2013-07-15 19:34:20 +02002998 }
Larry Hastings5c661892014-01-24 06:17:25 -08002999 memcpy(tp_doc, old_doc, len);
Antoine Pitroubb78f572012-06-24 00:18:27 +02003000 type->tp_doc = tp_doc;
Georg Brandl032400b2011-02-19 21:47:02 +00003001 }
Eddie Elizondo474eedf2018-11-13 04:09:31 -08003002
3003 /* Move the slots to the heap type itself */
3004 if (slot->slot == Py_tp_members) {
3005 size_t len = Py_TYPE(type)->tp_itemsize * nmembers;
3006 memcpy(PyHeapType_GET_MEMBERS(res), slot->pfunc, len);
3007 type->tp_members = PyHeapType_GET_MEMBERS(res);
3008 }
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00003009 }
Antoine Pitroubb78f572012-06-24 00:18:27 +02003010 if (type->tp_dealloc == NULL) {
Antoine Pitrou99cc6292012-06-23 14:42:38 +02003011 /* It's a heap type, so needs the heap types' dealloc.
3012 subtype_dealloc will call the base type's tp_dealloc, if
3013 necessary. */
Antoine Pitroubb78f572012-06-24 00:18:27 +02003014 type->tp_dealloc = subtype_dealloc;
Antoine Pitrou99cc6292012-06-23 14:42:38 +02003015 }
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00003016
Antoine Pitroubb78f572012-06-24 00:18:27 +02003017 if (PyType_Ready(type) < 0)
Benjamin Peterson2652d252012-01-29 20:16:37 -05003018 goto fail;
3019
Benjamin Petersondf813792014-03-17 15:57:17 -05003020 if (type->tp_dictoffset) {
3021 res->ht_cached_keys = _PyDict_NewKeysForClass();
3022 }
3023
Martin v. Löwis9c564092012-06-23 23:20:45 +02003024 /* Set type.__module__ */
3025 s = strrchr(spec->name, '.');
Nick Coghlana48db2b2015-05-24 01:03:46 +10003026 if (s != NULL) {
Christian Heimes5cade882016-10-13 21:10:31 +02003027 int err;
Nick Coghlana48db2b2015-05-24 01:03:46 +10003028 modname = PyUnicode_FromStringAndSize(
3029 spec->name, (Py_ssize_t)(s - spec->name));
3030 if (modname == NULL) {
3031 goto fail;
3032 }
Christian Heimes5cade882016-10-13 21:10:31 +02003033 err = _PyDict_SetItemId(type->tp_dict, &PyId___module__, modname);
Nick Coghlana48db2b2015-05-24 01:03:46 +10003034 Py_DECREF(modname);
Christian Heimes5cade882016-10-13 21:10:31 +02003035 if (err != 0)
3036 goto fail;
Nick Coghlana48db2b2015-05-24 01:03:46 +10003037 } else {
Serhiy Storchaka490055a2015-03-01 10:03:02 +02003038 if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
Serhiy Storchaka71c6f442015-03-01 14:39:20 +02003039 "builtin type %.200s has no __module__ attribute",
Serhiy Storchaka490055a2015-03-01 10:03:02 +02003040 spec->name))
3041 goto fail;
3042 }
Martin v. Löwis9c564092012-06-23 23:20:45 +02003043
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00003044 return (PyObject*)res;
Victor Stinner0fcab4a2011-01-04 12:59:15 +00003045
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00003046 fail:
3047 Py_DECREF(res);
3048 return NULL;
3049}
3050
Martin v. Löwis9c564092012-06-23 23:20:45 +02003051PyObject *
3052PyType_FromSpec(PyType_Spec *spec)
3053{
3054 return PyType_FromSpecWithBases(spec, NULL);
3055}
3056
Martin v. Löwisca7b0462014-02-04 09:33:05 +01003057void *
3058PyType_GetSlot(PyTypeObject *type, int slot)
3059{
Victor Stinner12174a52014-08-15 23:17:38 +02003060 if (!PyType_HasFeature(type, Py_TPFLAGS_HEAPTYPE) || slot < 0) {
Martin v. Löwisca7b0462014-02-04 09:33:05 +01003061 PyErr_BadInternalCall();
3062 return NULL;
3063 }
Victor Stinner12174a52014-08-15 23:17:38 +02003064 if ((size_t)slot >= Py_ARRAY_LENGTH(slotoffsets)) {
Martin v. Löwisca7b0462014-02-04 09:33:05 +01003065 /* Extension module requesting slot from a future version */
3066 return NULL;
3067 }
3068 return *(void**)(((char*)type) + slotoffsets[slot]);
3069}
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00003070
scoder2102c782017-10-01 10:37:47 +02003071/* Internal API to look for a name through the MRO, bypassing the method cache.
3072 This returns a borrowed reference, and might set an exception.
3073 'error' is set to: -1: error with exception; 1: error without exception; 0: ok */
3074static PyObject *
3075find_name_in_mro(PyTypeObject *type, PyObject *name, int *error)
3076{
3077 Py_ssize_t i, n;
3078 PyObject *mro, *res, *base, *dict;
3079 Py_hash_t hash;
3080
3081 if (!PyUnicode_CheckExact(name) ||
3082 (hash = ((PyASCIIObject *) name)->hash) == -1)
3083 {
3084 hash = PyObject_Hash(name);
3085 if (hash == -1) {
3086 *error = -1;
3087 return NULL;
3088 }
3089 }
3090
3091 /* Look in tp_dict of types in MRO */
3092 mro = type->tp_mro;
3093
3094 if (mro == NULL) {
3095 if ((type->tp_flags & Py_TPFLAGS_READYING) == 0) {
3096 if (PyType_Ready(type) < 0) {
3097 *error = -1;
3098 return NULL;
3099 }
3100 mro = type->tp_mro;
3101 }
3102 if (mro == NULL) {
3103 *error = 1;
3104 return NULL;
3105 }
3106 }
3107
3108 res = NULL;
3109 /* Keep a strong reference to mro because type->tp_mro can be replaced
3110 during dict lookup, e.g. when comparing to non-string keys. */
3111 Py_INCREF(mro);
3112 assert(PyTuple_Check(mro));
3113 n = PyTuple_GET_SIZE(mro);
3114 for (i = 0; i < n; i++) {
3115 base = PyTuple_GET_ITEM(mro, i);
3116 assert(PyType_Check(base));
3117 dict = ((PyTypeObject *)base)->tp_dict;
3118 assert(dict && PyDict_Check(dict));
3119 res = _PyDict_GetItem_KnownHash(dict, name, hash);
3120 if (res != NULL)
3121 break;
3122 if (PyErr_Occurred()) {
3123 *error = -1;
3124 goto done;
3125 }
3126 }
3127 *error = 0;
3128done:
3129 Py_DECREF(mro);
3130 return res;
3131}
3132
Tim Peters6d6c1a32001-08-02 04:15:00 +00003133/* Internal API to look for a name through the MRO.
3134 This returns a borrowed reference, and doesn't set an exception! */
3135PyObject *
3136_PyType_Lookup(PyTypeObject *type, PyObject *name)
3137{
scoder2102c782017-10-01 10:37:47 +02003138 PyObject *res;
3139 int error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003140 unsigned int h;
Christian Heimesa62da1d2008-01-12 19:39:10 +00003141
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003142 if (MCACHE_CACHEABLE_NAME(name) &&
3143 PyType_HasFeature(type, Py_TPFLAGS_VALID_VERSION_TAG)) {
3144 /* fast path */
3145 h = MCACHE_HASH_METHOD(type, name);
3146 if (method_cache[h].version == type->tp_version_tag &&
Antoine Pitrou2a40e362014-11-15 00:56:27 +01003147 method_cache[h].name == name) {
3148#if MCACHE_STATS
3149 method_cache_hits++;
3150#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003151 return method_cache[h].value;
Antoine Pitrou2a40e362014-11-15 00:56:27 +01003152 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003153 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003154
scoder2102c782017-10-01 10:37:47 +02003155 /* We may end up clearing live exceptions below, so make sure it's ours. */
3156 assert(!PyErr_Occurred());
Guido van Rossum23094982002-06-10 14:30:43 +00003157
scoder2102c782017-10-01 10:37:47 +02003158 res = find_name_in_mro(type, name, &error);
3159 /* Only put NULL results into cache if there was no error. */
3160 if (error) {
3161 /* It's not ideal to clear the error condition,
3162 but this function is documented as not setting
3163 an exception, and I don't want to change that.
3164 E.g., when PyType_Ready() can't proceed, it won't
3165 set the "ready" flag, so future attempts to ready
3166 the same type will call it again -- hopefully
3167 in a context that propagates the exception out.
3168 */
3169 if (error == -1) {
Serhiy Storchaka8ef34602016-10-08 12:24:09 +03003170 PyErr_Clear();
Serhiy Storchaka8ef34602016-10-08 12:24:09 +03003171 }
scoder2102c782017-10-01 10:37:47 +02003172 return NULL;
Serhiy Storchaka8ef34602016-10-08 12:24:09 +03003173 }
Guido van Rossum23094982002-06-10 14:30:43 +00003174
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003175 if (MCACHE_CACHEABLE_NAME(name) && assign_version_tag(type)) {
3176 h = MCACHE_HASH_METHOD(type, name);
3177 method_cache[h].version = type->tp_version_tag;
3178 method_cache[h].value = res; /* borrowed */
3179 Py_INCREF(name);
Antoine Pitrou2a40e362014-11-15 00:56:27 +01003180 assert(((PyASCIIObject *)(name))->hash != -1);
3181#if MCACHE_STATS
3182 if (method_cache[h].name != Py_None && method_cache[h].name != name)
3183 method_cache_collisions++;
3184 else
3185 method_cache_misses++;
3186#endif
Serhiy Storchaka57a01d32016-04-10 18:05:40 +03003187 Py_SETREF(method_cache[h].name, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003188 }
3189 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003190}
3191
Raymond Hettinger2ff21902013-10-01 00:55:43 -07003192PyObject *
Victor Stinner3c1e4812012-03-26 22:10:51 +02003193_PyType_LookupId(PyTypeObject *type, struct _Py_Identifier *name)
3194{
3195 PyObject *oname;
3196 oname = _PyUnicode_FromId(name); /* borrowed */
3197 if (oname == NULL)
3198 return NULL;
3199 return _PyType_Lookup(type, oname);
3200}
3201
Stefan Behneld8b9e1f2019-02-20 18:29:24 +01003202/* Check if the "readied" PyUnicode name
3203 is a double-underscore special name. */
3204static int
3205is_dunder_name(PyObject *name)
3206{
3207 Py_ssize_t length = PyUnicode_GET_LENGTH(name);
3208 int kind = PyUnicode_KIND(name);
3209 /* Special names contain at least "__x__" and are always ASCII. */
3210 if (length > 4 && kind == PyUnicode_1BYTE_KIND) {
3211 Py_UCS1 *characters = PyUnicode_1BYTE_DATA(name);
3212 return (
3213 ((characters[length-2] == '_') && (characters[length-1] == '_')) &&
3214 ((characters[0] == '_') && (characters[1] == '_'))
3215 );
3216 }
3217 return 0;
3218}
3219
Tim Peters6d6c1a32001-08-02 04:15:00 +00003220/* This is similar to PyObject_GenericGetAttr(),
3221 but uses _PyType_Lookup() instead of just looking in type->tp_dict. */
3222static PyObject *
3223type_getattro(PyTypeObject *type, PyObject *name)
3224{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003225 PyTypeObject *metatype = Py_TYPE(type);
3226 PyObject *meta_attribute, *attribute;
3227 descrgetfunc meta_get;
jdemeyer8f735482018-09-07 09:37:00 +02003228 PyObject* res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003229
Benjamin Peterson16d84ac2012-03-16 09:32:59 -05003230 if (!PyUnicode_Check(name)) {
3231 PyErr_Format(PyExc_TypeError,
3232 "attribute name must be string, not '%.200s'",
3233 name->ob_type->tp_name);
3234 return NULL;
3235 }
3236
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003237 /* Initialize this type (we'll assume the metatype is initialized) */
3238 if (type->tp_dict == NULL) {
3239 if (PyType_Ready(type) < 0)
3240 return NULL;
3241 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003242
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003243 /* No readable descriptor found yet */
3244 meta_get = NULL;
Tim Peters34592512002-07-11 06:23:50 +00003245
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003246 /* Look for the attribute in the metatype */
3247 meta_attribute = _PyType_Lookup(metatype, name);
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00003248
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003249 if (meta_attribute != NULL) {
jdemeyer8f735482018-09-07 09:37:00 +02003250 Py_INCREF(meta_attribute);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003251 meta_get = Py_TYPE(meta_attribute)->tp_descr_get;
Tim Peters34592512002-07-11 06:23:50 +00003252
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003253 if (meta_get != NULL && PyDescr_IsData(meta_attribute)) {
3254 /* Data descriptors implement tp_descr_set to intercept
3255 * writes. Assume the attribute is not overridden in
3256 * type's tp_dict (and bases): call the descriptor now.
3257 */
jdemeyer8f735482018-09-07 09:37:00 +02003258 res = meta_get(meta_attribute, (PyObject *)type,
3259 (PyObject *)metatype);
3260 Py_DECREF(meta_attribute);
3261 return res;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003262 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003263 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003264
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003265 /* No data descriptor found on metatype. Look in tp_dict of this
3266 * type and its bases */
3267 attribute = _PyType_Lookup(type, name);
3268 if (attribute != NULL) {
3269 /* Implement descriptor functionality, if any */
jdemeyer8f735482018-09-07 09:37:00 +02003270 Py_INCREF(attribute);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003271 descrgetfunc local_get = Py_TYPE(attribute)->tp_descr_get;
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00003272
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003273 Py_XDECREF(meta_attribute);
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00003274
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003275 if (local_get != NULL) {
3276 /* NULL 2nd argument indicates the descriptor was
3277 * found on the target object itself (or a base) */
jdemeyer8f735482018-09-07 09:37:00 +02003278 res = local_get(attribute, (PyObject *)NULL,
3279 (PyObject *)type);
3280 Py_DECREF(attribute);
3281 return res;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003282 }
Tim Peters34592512002-07-11 06:23:50 +00003283
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003284 return attribute;
3285 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003286
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003287 /* No attribute found in local __dict__ (or bases): use the
3288 * descriptor from the metatype, if any */
3289 if (meta_get != NULL) {
3290 PyObject *res;
3291 res = meta_get(meta_attribute, (PyObject *)type,
3292 (PyObject *)metatype);
3293 Py_DECREF(meta_attribute);
3294 return res;
3295 }
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00003296
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003297 /* If an ordinary attribute was found on the metatype, return it now */
3298 if (meta_attribute != NULL) {
3299 return meta_attribute;
3300 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003301
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003302 /* Give up */
3303 PyErr_Format(PyExc_AttributeError,
3304 "type object '%.50s' has no attribute '%U'",
3305 type->tp_name, name);
3306 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003307}
3308
3309static int
3310type_setattro(PyTypeObject *type, PyObject *name, PyObject *value)
3311{
Victor Stinnerbda5a2b2017-01-25 23:33:27 +01003312 int res;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003313 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
3314 PyErr_Format(
3315 PyExc_TypeError,
3316 "can't set attributes of built-in/extension type '%s'",
3317 type->tp_name);
3318 return -1;
3319 }
Serhiy Storchakad8969852017-05-20 08:48:06 +03003320 if (PyUnicode_Check(name)) {
3321 if (PyUnicode_CheckExact(name)) {
3322 if (PyUnicode_READY(name) == -1)
3323 return -1;
3324 Py_INCREF(name);
3325 }
3326 else {
3327 name = _PyUnicode_Copy(name);
3328 if (name == NULL)
3329 return -1;
3330 }
Serhiy Storchakad8969852017-05-20 08:48:06 +03003331 if (!PyUnicode_CHECK_INTERNED(name)) {
Stefan Behneld8b9e1f2019-02-20 18:29:24 +01003332 PyUnicode_InternInPlace(&name);
3333 if (!PyUnicode_CHECK_INTERNED(name)) {
3334 PyErr_SetString(PyExc_MemoryError,
3335 "Out of memory interning an attribute name");
3336 Py_DECREF(name);
3337 return -1;
3338 }
Serhiy Storchakad8969852017-05-20 08:48:06 +03003339 }
3340 }
3341 else {
3342 /* Will fail in _PyObject_GenericSetAttrWithDict. */
3343 Py_INCREF(name);
3344 }
3345 res = _PyObject_GenericSetAttrWithDict((PyObject *)type, name, value, NULL);
3346 if (res == 0) {
Stefan Behneld8b9e1f2019-02-20 18:29:24 +01003347 /* Clear the VALID_VERSION flag of 'type' and all its
3348 subclasses. This could possibly be unified with the
3349 update_subclasses() recursion in update_slot(), but carefully:
3350 they each have their own conditions on which to stop
3351 recursing into subclasses. */
3352 PyType_Modified(type);
3353
3354 if (is_dunder_name(name)) {
3355 res = update_slot(type, name);
3356 }
Serhiy Storchakad8969852017-05-20 08:48:06 +03003357 assert(_PyType_CheckConsistency(type));
3358 }
3359 Py_DECREF(name);
Victor Stinnerbda5a2b2017-01-25 23:33:27 +01003360 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003361}
3362
Benjamin Peterson64acccf2012-04-27 15:07:36 -04003363extern void
3364_PyDictKeys_DecRef(PyDictKeysObject *keys);
3365
Tim Peters6d6c1a32001-08-02 04:15:00 +00003366static void
3367type_dealloc(PyTypeObject *type)
3368{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003369 PyHeapTypeObject *et;
Antoine Pitrou84745ab2013-10-29 21:31:25 +01003370 PyObject *tp, *val, *tb;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003371
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003372 /* Assert this is a heap-allocated type object */
Victor Stinner08625052018-10-26 18:39:11 +02003373 _PyObject_ASSERT((PyObject *)type, type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003374 _PyObject_GC_UNTRACK(type);
Antoine Pitrou84745ab2013-10-29 21:31:25 +01003375 PyErr_Fetch(&tp, &val, &tb);
3376 remove_all_subclasses(type, type->tp_bases);
3377 PyErr_Restore(tp, val, tb);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003378 PyObject_ClearWeakRefs((PyObject *)type);
3379 et = (PyHeapTypeObject *)type;
3380 Py_XDECREF(type->tp_base);
3381 Py_XDECREF(type->tp_dict);
3382 Py_XDECREF(type->tp_bases);
3383 Py_XDECREF(type->tp_mro);
3384 Py_XDECREF(type->tp_cache);
3385 Py_XDECREF(type->tp_subclasses);
3386 /* A type's tp_doc is heap allocated, unlike the tp_doc slots
3387 * of most other objects. It's okay to cast it to char *.
3388 */
3389 PyObject_Free((char *)type->tp_doc);
3390 Py_XDECREF(et->ht_name);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003391 Py_XDECREF(et->ht_qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003392 Py_XDECREF(et->ht_slots);
Benjamin Peterson64acccf2012-04-27 15:07:36 -04003393 if (et->ht_cached_keys)
3394 _PyDictKeys_DecRef(et->ht_cached_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003395 Py_TYPE(type)->tp_free((PyObject *)type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003396}
3397
Serhiy Storchaka5c643a02017-03-19 08:46:44 +02003398/*[clinic input]
3399type.__subclasses__
3400
3401Return a list of immediate subclasses.
3402[clinic start generated code]*/
3403
Guido van Rossum1c450732001-10-08 15:18:27 +00003404static PyObject *
Serhiy Storchaka5c643a02017-03-19 08:46:44 +02003405type___subclasses___impl(PyTypeObject *self)
3406/*[clinic end generated code: output=eb5eb54485942819 input=5af66132436f9a7b]*/
Guido van Rossum1c450732001-10-08 15:18:27 +00003407{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003408 PyObject *list, *raw, *ref;
Antoine Pitrou84745ab2013-10-29 21:31:25 +01003409 Py_ssize_t i;
Guido van Rossum1c450732001-10-08 15:18:27 +00003410
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003411 list = PyList_New(0);
3412 if (list == NULL)
3413 return NULL;
Serhiy Storchaka5c643a02017-03-19 08:46:44 +02003414 raw = self->tp_subclasses;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003415 if (raw == NULL)
3416 return list;
Antoine Pitrou84745ab2013-10-29 21:31:25 +01003417 assert(PyDict_CheckExact(raw));
3418 i = 0;
3419 while (PyDict_Next(raw, &i, NULL, &ref)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003420 assert(PyWeakref_CheckRef(ref));
3421 ref = PyWeakref_GET_OBJECT(ref);
3422 if (ref != Py_None) {
3423 if (PyList_Append(list, ref) < 0) {
3424 Py_DECREF(list);
3425 return NULL;
3426 }
3427 }
3428 }
3429 return list;
Guido van Rossum1c450732001-10-08 15:18:27 +00003430}
3431
Guido van Rossum47374822007-08-02 16:48:17 +00003432static PyObject *
Serhiy Storchakaa5552f02017-12-15 13:11:11 +02003433type_prepare(PyObject *self, PyObject *const *args, Py_ssize_t nargs,
Victor Stinnerd526cfe2017-01-16 23:52:00 +01003434 PyObject *kwnames)
Guido van Rossum47374822007-08-02 16:48:17 +00003435{
Eric Snow4f29e752016-09-08 15:11:11 -07003436 return PyDict_New();
Guido van Rossum47374822007-08-02 16:48:17 +00003437}
3438
Victor Stinner63941882011-09-29 00:42:28 +02003439/*
Benjamin Peterson82b00c12011-05-24 11:09:06 -05003440 Merge the __dict__ of aclass into dict, and recursively also all
3441 the __dict__s of aclass's base classes. The order of merging isn't
3442 defined, as it's expected that only the final set of dict keys is
3443 interesting.
3444 Return 0 on success, -1 on error.
3445*/
3446
3447static int
3448merge_class_dict(PyObject *dict, PyObject *aclass)
3449{
3450 PyObject *classdict;
3451 PyObject *bases;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02003452 _Py_IDENTIFIER(__bases__);
Benjamin Peterson82b00c12011-05-24 11:09:06 -05003453
3454 assert(PyDict_Check(dict));
3455 assert(aclass);
3456
3457 /* Merge in the type's dict (if any). */
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02003458 classdict = _PyObject_GetAttrId(aclass, &PyId___dict__);
Benjamin Peterson82b00c12011-05-24 11:09:06 -05003459 if (classdict == NULL)
3460 PyErr_Clear();
3461 else {
3462 int status = PyDict_Update(dict, classdict);
3463 Py_DECREF(classdict);
3464 if (status < 0)
3465 return -1;
3466 }
3467
3468 /* Recursively merge in the base types' (if any) dicts. */
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02003469 bases = _PyObject_GetAttrId(aclass, &PyId___bases__);
Benjamin Peterson82b00c12011-05-24 11:09:06 -05003470 if (bases == NULL)
3471 PyErr_Clear();
3472 else {
3473 /* We have no guarantee that bases is a real tuple */
3474 Py_ssize_t i, n;
3475 n = PySequence_Size(bases); /* This better be right */
3476 if (n < 0)
3477 PyErr_Clear();
3478 else {
3479 for (i = 0; i < n; i++) {
3480 int status;
3481 PyObject *base = PySequence_GetItem(bases, i);
3482 if (base == NULL) {
3483 Py_DECREF(bases);
3484 return -1;
3485 }
3486 status = merge_class_dict(dict, base);
3487 Py_DECREF(base);
3488 if (status < 0) {
3489 Py_DECREF(bases);
3490 return -1;
3491 }
3492 }
3493 }
3494 Py_DECREF(bases);
3495 }
3496 return 0;
3497}
3498
3499/* __dir__ for type objects: returns __dict__ and __bases__.
3500 We deliberately don't suck up its __class__, as methods belonging to the
3501 metaclass would probably be more confusing than helpful.
3502*/
Serhiy Storchaka5c643a02017-03-19 08:46:44 +02003503/*[clinic input]
3504type.__dir__
3505
3506Specialized __dir__ implementation for types.
3507[clinic start generated code]*/
3508
Benjamin Peterson82b00c12011-05-24 11:09:06 -05003509static PyObject *
Serhiy Storchaka5c643a02017-03-19 08:46:44 +02003510type___dir___impl(PyTypeObject *self)
3511/*[clinic end generated code: output=69d02fe92c0f15fa input=7733befbec645968]*/
Benjamin Peterson82b00c12011-05-24 11:09:06 -05003512{
3513 PyObject *result = NULL;
3514 PyObject *dict = PyDict_New();
3515
Serhiy Storchaka5c643a02017-03-19 08:46:44 +02003516 if (dict != NULL && merge_class_dict(dict, (PyObject *)self) == 0)
Benjamin Peterson82b00c12011-05-24 11:09:06 -05003517 result = PyDict_Keys(dict);
3518
3519 Py_XDECREF(dict);
3520 return result;
3521}
3522
Serhiy Storchaka5c643a02017-03-19 08:46:44 +02003523/*[clinic input]
3524type.__sizeof__
3525
3526Return memory consumption of the type object.
3527[clinic start generated code]*/
3528
3529static PyObject *
3530type___sizeof___impl(PyTypeObject *self)
3531/*[clinic end generated code: output=766f4f16cd3b1854 input=99398f24b9cf45d6]*/
Martin v. Loewis4f2f3b62012-04-24 19:13:57 +02003532{
3533 Py_ssize_t size;
Serhiy Storchaka5c643a02017-03-19 08:46:44 +02003534 if (self->tp_flags & Py_TPFLAGS_HEAPTYPE) {
3535 PyHeapTypeObject* et = (PyHeapTypeObject*)self;
Martin v. Loewis4f2f3b62012-04-24 19:13:57 +02003536 size = sizeof(PyHeapTypeObject);
3537 if (et->ht_cached_keys)
3538 size += _PyDict_KeysSize(et->ht_cached_keys);
3539 }
3540 else
3541 size = sizeof(PyTypeObject);
3542 return PyLong_FromSsize_t(size);
3543}
3544
Tim Peters6d6c1a32001-08-02 04:15:00 +00003545static PyMethodDef type_methods[] = {
Serhiy Storchaka5c643a02017-03-19 08:46:44 +02003546 TYPE_MRO_METHODDEF
3547 TYPE___SUBCLASSES___METHODDEF
Serhiy Storchaka62be7422018-11-27 13:27:31 +02003548 {"__prepare__", (PyCFunction)(void(*)(void))type_prepare,
Serhiy Storchaka6969eaf2017-07-03 21:20:15 +03003549 METH_FASTCALL | METH_KEYWORDS | METH_CLASS,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003550 PyDoc_STR("__prepare__() -> dict\n"
3551 "used to create the namespace for the class statement")},
Serhiy Storchaka5c643a02017-03-19 08:46:44 +02003552 TYPE___INSTANCECHECK___METHODDEF
3553 TYPE___SUBCLASSCHECK___METHODDEF
3554 TYPE___DIR___METHODDEF
3555 TYPE___SIZEOF___METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003556 {0}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003557};
3558
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003559PyDoc_STRVAR(type_doc,
Larry Hastings5c661892014-01-24 06:17:25 -08003560/* this text signature cannot be accurate yet. will fix. --larry */
Larry Hastings2623c8c2014-02-08 22:15:29 -08003561"type(object_or_name, bases, dict)\n"
Tim Peters6d6c1a32001-08-02 04:15:00 +00003562"type(object) -> the object's type\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003563"type(name, bases, dict) -> a new type");
Tim Peters6d6c1a32001-08-02 04:15:00 +00003564
Guido van Rossum048eb752001-10-02 21:24:57 +00003565static int
3566type_traverse(PyTypeObject *type, visitproc visit, void *arg)
3567{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003568 /* Because of type_is_gc(), the collector only calls this
3569 for heaptypes. */
Antoine Pitrou1351ca62012-06-24 00:30:12 +02003570 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
3571 char msg[200];
3572 sprintf(msg, "type_traverse() called for non-heap type '%.100s'",
3573 type->tp_name);
3574 Py_FatalError(msg);
3575 }
Guido van Rossum048eb752001-10-02 21:24:57 +00003576
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003577 Py_VISIT(type->tp_dict);
3578 Py_VISIT(type->tp_cache);
3579 Py_VISIT(type->tp_mro);
3580 Py_VISIT(type->tp_bases);
3581 Py_VISIT(type->tp_base);
Guido van Rossuma3862092002-06-10 15:24:42 +00003582
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003583 /* There's no need to visit type->tp_subclasses or
3584 ((PyHeapTypeObject *)type)->ht_slots, because they can't be involved
3585 in cycles; tp_subclasses is a list of weak references,
3586 and slots is a tuple of strings. */
Guido van Rossum048eb752001-10-02 21:24:57 +00003587
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003588 return 0;
Guido van Rossum048eb752001-10-02 21:24:57 +00003589}
3590
3591static int
3592type_clear(PyTypeObject *type)
3593{
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003594 PyDictKeysObject *cached_keys;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003595 /* Because of type_is_gc(), the collector only calls this
3596 for heaptypes. */
Victor Stinner08625052018-10-26 18:39:11 +02003597 _PyObject_ASSERT((PyObject *)type, type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00003598
Antoine Pitrou2e872082011-12-15 14:15:31 +01003599 /* We need to invalidate the method cache carefully before clearing
3600 the dict, so that other objects caught in a reference cycle
3601 don't start calling destroyed methods.
3602
3603 Otherwise, the only field we need to clear is tp_mro, which is
3604 part of a hard cycle (its first element is the class itself) that
3605 won't be broken otherwise (it's a tuple and tuples don't have a
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003606 tp_clear handler). None of the other fields need to be
3607 cleared, and here's why:
Guido van Rossum048eb752001-10-02 21:24:57 +00003608
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003609 tp_cache:
3610 Not used; if it were, it would be a dict.
Guido van Rossuma3862092002-06-10 15:24:42 +00003611
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003612 tp_bases, tp_base:
3613 If these are involved in a cycle, there must be at least
3614 one other, mutable object in the cycle, e.g. a base
3615 class's dict; the cycle will be broken that way.
Guido van Rossuma3862092002-06-10 15:24:42 +00003616
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003617 tp_subclasses:
Antoine Pitrou84745ab2013-10-29 21:31:25 +01003618 A dict of weak references can't be part of a cycle; and
3619 dicts have their own tp_clear.
Guido van Rossuma3862092002-06-10 15:24:42 +00003620
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003621 slots (in PyHeapTypeObject):
3622 A tuple of strings can't be part of a cycle.
3623 */
Guido van Rossuma3862092002-06-10 15:24:42 +00003624
Antoine Pitrou2e872082011-12-15 14:15:31 +01003625 PyType_Modified(type);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003626 cached_keys = ((PyHeapTypeObject *)type)->ht_cached_keys;
3627 if (cached_keys != NULL) {
3628 ((PyHeapTypeObject *)type)->ht_cached_keys = NULL;
3629 _PyDictKeys_DecRef(cached_keys);
3630 }
Antoine Pitrou2e872082011-12-15 14:15:31 +01003631 if (type->tp_dict)
3632 PyDict_Clear(type->tp_dict);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003633 Py_CLEAR(type->tp_mro);
Guido van Rossum048eb752001-10-02 21:24:57 +00003634
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003635 return 0;
Guido van Rossum048eb752001-10-02 21:24:57 +00003636}
3637
3638static int
3639type_is_gc(PyTypeObject *type)
3640{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003641 return type->tp_flags & Py_TPFLAGS_HEAPTYPE;
Guido van Rossum048eb752001-10-02 21:24:57 +00003642}
3643
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003644PyTypeObject PyType_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003645 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3646 "type", /* tp_name */
3647 sizeof(PyHeapTypeObject), /* tp_basicsize */
3648 sizeof(PyMemberDef), /* tp_itemsize */
3649 (destructor)type_dealloc, /* tp_dealloc */
3650 0, /* tp_print */
3651 0, /* tp_getattr */
3652 0, /* tp_setattr */
3653 0, /* tp_reserved */
3654 (reprfunc)type_repr, /* tp_repr */
3655 0, /* tp_as_number */
3656 0, /* tp_as_sequence */
3657 0, /* tp_as_mapping */
3658 0, /* tp_hash */
3659 (ternaryfunc)type_call, /* tp_call */
3660 0, /* tp_str */
3661 (getattrofunc)type_getattro, /* tp_getattro */
3662 (setattrofunc)type_setattro, /* tp_setattro */
3663 0, /* tp_as_buffer */
3664 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
3665 Py_TPFLAGS_BASETYPE | Py_TPFLAGS_TYPE_SUBCLASS, /* tp_flags */
3666 type_doc, /* tp_doc */
3667 (traverseproc)type_traverse, /* tp_traverse */
3668 (inquiry)type_clear, /* tp_clear */
3669 0, /* tp_richcompare */
3670 offsetof(PyTypeObject, tp_weaklist), /* tp_weaklistoffset */
3671 0, /* tp_iter */
3672 0, /* tp_iternext */
3673 type_methods, /* tp_methods */
3674 type_members, /* tp_members */
3675 type_getsets, /* tp_getset */
3676 0, /* tp_base */
3677 0, /* tp_dict */
3678 0, /* tp_descr_get */
3679 0, /* tp_descr_set */
3680 offsetof(PyTypeObject, tp_dict), /* tp_dictoffset */
3681 type_init, /* tp_init */
3682 0, /* tp_alloc */
3683 type_new, /* tp_new */
3684 PyObject_GC_Del, /* tp_free */
3685 (inquiry)type_is_gc, /* tp_is_gc */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003686};
Tim Peters6d6c1a32001-08-02 04:15:00 +00003687
3688
3689/* The base type of all types (eventually)... except itself. */
3690
Guido van Rossumd8faa362007-04-27 19:54:29 +00003691/* You may wonder why object.__new__() only complains about arguments
3692 when object.__init__() is not overridden, and vice versa.
3693
3694 Consider the use cases:
3695
3696 1. When neither is overridden, we want to hear complaints about
3697 excess (i.e., any) arguments, since their presence could
3698 indicate there's a bug.
3699
3700 2. When defining an Immutable type, we are likely to override only
3701 __new__(), since __init__() is called too late to initialize an
3702 Immutable object. Since __new__() defines the signature for the
3703 type, it would be a pain to have to override __init__() just to
3704 stop it from complaining about excess arguments.
3705
3706 3. When defining a Mutable type, we are likely to override only
3707 __init__(). So here the converse reasoning applies: we don't
3708 want to have to override __new__() just to stop it from
3709 complaining.
3710
3711 4. When __init__() is overridden, and the subclass __init__() calls
3712 object.__init__(), the latter should complain about excess
3713 arguments; ditto for __new__().
3714
3715 Use cases 2 and 3 make it unattractive to unconditionally check for
3716 excess arguments. The best solution that addresses all four use
3717 cases is as follows: __init__() complains about excess arguments
3718 unless __new__() is overridden and __init__() is not overridden
3719 (IOW, if __init__() is overridden or __new__() is not overridden);
3720 symmetrically, __new__() complains about excess arguments unless
3721 __init__() is overridden and __new__() is not overridden
3722 (IOW, if __new__() is overridden or __init__() is not overridden).
3723
3724 However, for backwards compatibility, this breaks too much code.
3725 Therefore, in 2.6, we'll *warn* about excess arguments when both
3726 methods are overridden; for all other cases we'll use the above
3727 rules.
3728
3729*/
3730
3731/* Forward */
3732static PyObject *
3733object_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
3734
3735static int
3736excess_args(PyObject *args, PyObject *kwds)
3737{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003738 return PyTuple_GET_SIZE(args) ||
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02003739 (kwds && PyDict_Check(kwds) && PyDict_GET_SIZE(kwds));
Guido van Rossumd8faa362007-04-27 19:54:29 +00003740}
3741
Tim Peters6d6c1a32001-08-02 04:15:00 +00003742static int
3743object_init(PyObject *self, PyObject *args, PyObject *kwds)
3744{
Benjamin Peterson96384b92012-03-17 00:05:44 -05003745 PyTypeObject *type = Py_TYPE(self);
Serhiy Storchakaa6c0c062017-09-20 06:44:32 +03003746 if (excess_args(args, kwds)) {
3747 if (type->tp_init != object_init) {
Sanyam Khurana51054832019-02-19 18:53:48 +05303748 PyErr_SetString(PyExc_TypeError,
3749 "object.__init__() takes exactly one argument (the instance to initialize)");
Serhiy Storchakaa6c0c062017-09-20 06:44:32 +03003750 return -1;
3751 }
3752 if (type->tp_new == object_new) {
Sanyam Khurana51054832019-02-19 18:53:48 +05303753 PyErr_Format(PyExc_TypeError,
3754 "%.200s.__init__() takes exactly one argument (the instance to initialize)",
Serhiy Storchakaa6c0c062017-09-20 06:44:32 +03003755 type->tp_name);
3756 return -1;
3757 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003758 }
Serhiy Storchakaa6c0c062017-09-20 06:44:32 +03003759 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003760}
3761
Guido van Rossum298e4212003-02-13 16:30:16 +00003762static PyObject *
3763object_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3764{
Serhiy Storchakaa6c0c062017-09-20 06:44:32 +03003765 if (excess_args(args, kwds)) {
3766 if (type->tp_new != object_new) {
Sanyam Khurana51054832019-02-19 18:53:48 +05303767 PyErr_SetString(PyExc_TypeError,
3768 "object.__new__() takes exactly one argument (the type to instantiate)");
Serhiy Storchakaa6c0c062017-09-20 06:44:32 +03003769 return NULL;
3770 }
3771 if (type->tp_init == object_init) {
3772 PyErr_Format(PyExc_TypeError, "%.200s() takes no arguments",
3773 type->tp_name);
3774 return NULL;
3775 }
Benjamin Peterson96384b92012-03-17 00:05:44 -05003776 }
Victor Stinner3c1e4812012-03-26 22:10:51 +02003777
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003778 if (type->tp_flags & Py_TPFLAGS_IS_ABSTRACT) {
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02003779 PyObject *abstract_methods;
3780 PyObject *sorted_methods;
3781 PyObject *joined;
Benjamin Peterson9a03ecf2012-03-16 20:15:54 -05003782 PyObject *comma;
3783 _Py_static_string(comma_id, ", ");
Christian Heimes9e7f1d22008-02-28 12:27:11 +00003784
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003785 /* Compute ", ".join(sorted(type.__abstractmethods__))
3786 into joined. */
3787 abstract_methods = type_abstractmethods(type, NULL);
3788 if (abstract_methods == NULL)
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02003789 return NULL;
3790 sorted_methods = PySequence_List(abstract_methods);
3791 Py_DECREF(abstract_methods);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003792 if (sorted_methods == NULL)
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02003793 return NULL;
3794 if (PyList_Sort(sorted_methods)) {
3795 Py_DECREF(sorted_methods);
3796 return NULL;
3797 }
Benjamin Peterson9a03ecf2012-03-16 20:15:54 -05003798 comma = _PyUnicode_FromId(&comma_id);
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02003799 if (comma == NULL) {
3800 Py_DECREF(sorted_methods);
3801 return NULL;
3802 }
Benjamin Peterson9a03ecf2012-03-16 20:15:54 -05003803 joined = PyUnicode_Join(comma, sorted_methods);
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02003804 Py_DECREF(sorted_methods);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003805 if (joined == NULL)
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02003806 return NULL;
Christian Heimes9e7f1d22008-02-28 12:27:11 +00003807
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003808 PyErr_Format(PyExc_TypeError,
3809 "Can't instantiate abstract class %s "
3810 "with abstract methods %U",
3811 type->tp_name,
3812 joined);
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02003813 Py_DECREF(joined);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003814 return NULL;
3815 }
3816 return type->tp_alloc(type, 0);
Guido van Rossum298e4212003-02-13 16:30:16 +00003817}
3818
Tim Peters6d6c1a32001-08-02 04:15:00 +00003819static void
3820object_dealloc(PyObject *self)
3821{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003822 Py_TYPE(self)->tp_free(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003823}
3824
Guido van Rossum8e248182001-08-12 05:17:56 +00003825static PyObject *
3826object_repr(PyObject *self)
3827{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003828 PyTypeObject *type;
3829 PyObject *mod, *name, *rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00003830
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003831 type = Py_TYPE(self);
3832 mod = type_module(type, NULL);
3833 if (mod == NULL)
3834 PyErr_Clear();
3835 else if (!PyUnicode_Check(mod)) {
3836 Py_DECREF(mod);
3837 mod = NULL;
3838 }
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003839 name = type_qualname(type, NULL);
Christian Heimese81dc292012-09-10 16:57:36 +02003840 if (name == NULL) {
3841 Py_XDECREF(mod);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003842 return NULL;
Christian Heimese81dc292012-09-10 16:57:36 +02003843 }
Serhiy Storchakaf5894dd2016-11-16 15:40:39 +02003844 if (mod != NULL && !_PyUnicode_EqualToASCIIId(mod, &PyId_builtins))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003845 rtn = PyUnicode_FromFormat("<%U.%U object at %p>", mod, name, self);
3846 else
3847 rtn = PyUnicode_FromFormat("<%s object at %p>",
3848 type->tp_name, self);
3849 Py_XDECREF(mod);
3850 Py_DECREF(name);
3851 return rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00003852}
3853
Guido van Rossumb8f63662001-08-15 23:57:02 +00003854static PyObject *
3855object_str(PyObject *self)
3856{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003857 unaryfunc f;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003858
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003859 f = Py_TYPE(self)->tp_repr;
Benjamin Peterson7b166872012-04-24 11:06:25 -04003860 if (f == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003861 f = object_repr;
3862 return f(self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003863}
3864
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003865static PyObject *
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003866object_richcompare(PyObject *self, PyObject *other, int op)
3867{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003868 PyObject *res;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003869
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003870 switch (op) {
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003871
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003872 case Py_EQ:
3873 /* Return NotImplemented instead of False, so if two
3874 objects are compared, both get a chance at the
3875 comparison. See issue #1393. */
3876 res = (self == other) ? Py_True : Py_NotImplemented;
3877 Py_INCREF(res);
3878 break;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003879
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003880 case Py_NE:
Serhiy Storchakaf4b7a022015-01-26 09:57:07 +02003881 /* By default, __ne__() delegates to __eq__() and inverts the result,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003882 unless the latter returns NotImplemented. */
Serhiy Storchakaf4b7a022015-01-26 09:57:07 +02003883 if (self->ob_type->tp_richcompare == NULL) {
3884 res = Py_NotImplemented;
3885 Py_INCREF(res);
3886 break;
3887 }
3888 res = (*self->ob_type->tp_richcompare)(self, other, Py_EQ);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003889 if (res != NULL && res != Py_NotImplemented) {
3890 int ok = PyObject_IsTrue(res);
3891 Py_DECREF(res);
3892 if (ok < 0)
3893 res = NULL;
3894 else {
3895 if (ok)
3896 res = Py_False;
3897 else
3898 res = Py_True;
3899 Py_INCREF(res);
3900 }
3901 }
3902 break;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003903
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003904 default:
3905 res = Py_NotImplemented;
3906 Py_INCREF(res);
3907 break;
3908 }
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003909
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003910 return res;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003911}
3912
3913static PyObject *
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003914object_get_class(PyObject *self, void *closure)
3915{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003916 Py_INCREF(Py_TYPE(self));
3917 return (PyObject *)(Py_TYPE(self));
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003918}
3919
3920static int
Benjamin Peterson9d4cbcc2015-01-30 13:33:42 -05003921compatible_with_tp_base(PyTypeObject *child)
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003922{
Benjamin Peterson9d4cbcc2015-01-30 13:33:42 -05003923 PyTypeObject *parent = child->tp_base;
3924 return (parent != NULL &&
3925 child->tp_basicsize == parent->tp_basicsize &&
3926 child->tp_itemsize == parent->tp_itemsize &&
3927 child->tp_dictoffset == parent->tp_dictoffset &&
3928 child->tp_weaklistoffset == parent->tp_weaklistoffset &&
3929 ((child->tp_flags & Py_TPFLAGS_HAVE_GC) ==
3930 (parent->tp_flags & Py_TPFLAGS_HAVE_GC)) &&
3931 (child->tp_dealloc == subtype_dealloc ||
3932 child->tp_dealloc == parent->tp_dealloc));
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003933}
3934
3935static int
3936same_slots_added(PyTypeObject *a, PyTypeObject *b)
3937{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003938 PyTypeObject *base = a->tp_base;
3939 Py_ssize_t size;
3940 PyObject *slots_a, *slots_b;
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003941
Benjamin Peterson67641d22011-01-17 19:24:34 +00003942 assert(base == b->tp_base);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003943 size = base->tp_basicsize;
3944 if (a->tp_dictoffset == size && b->tp_dictoffset == size)
3945 size += sizeof(PyObject *);
3946 if (a->tp_weaklistoffset == size && b->tp_weaklistoffset == size)
3947 size += sizeof(PyObject *);
Guido van Rossumd8faa362007-04-27 19:54:29 +00003948
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003949 /* Check slots compliance */
Benjamin Peterson9d4cbcc2015-01-30 13:33:42 -05003950 if (!(a->tp_flags & Py_TPFLAGS_HEAPTYPE) ||
3951 !(b->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
3952 return 0;
3953 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003954 slots_a = ((PyHeapTypeObject *)a)->ht_slots;
3955 slots_b = ((PyHeapTypeObject *)b)->ht_slots;
3956 if (slots_a && slots_b) {
3957 if (PyObject_RichCompareBool(slots_a, slots_b, Py_EQ) != 1)
3958 return 0;
3959 size += sizeof(PyObject *) * PyTuple_GET_SIZE(slots_a);
3960 }
3961 return size == a->tp_basicsize && size == b->tp_basicsize;
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003962}
3963
3964static int
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02003965compatible_for_assignment(PyTypeObject* oldto, PyTypeObject* newto, const char* attr)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003966{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003967 PyTypeObject *newbase, *oldbase;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003968
Benjamin Peterson9d4cbcc2015-01-30 13:33:42 -05003969 if (newto->tp_free != oldto->tp_free) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003970 PyErr_Format(PyExc_TypeError,
3971 "%s assignment: "
3972 "'%s' deallocator differs from '%s'",
3973 attr,
3974 newto->tp_name,
3975 oldto->tp_name);
3976 return 0;
3977 }
Benjamin Peterson9d4cbcc2015-01-30 13:33:42 -05003978 /*
3979 It's tricky to tell if two arbitrary types are sufficiently compatible as
3980 to be interchangeable; e.g., even if they have the same tp_basicsize, they
3981 might have totally different struct fields. It's much easier to tell if a
3982 type and its supertype are compatible; e.g., if they have the same
3983 tp_basicsize, then that means they have identical fields. So to check
3984 whether two arbitrary types are compatible, we first find the highest
3985 supertype that each is compatible with, and then if those supertypes are
3986 compatible then the original types must also be compatible.
3987 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003988 newbase = newto;
3989 oldbase = oldto;
Benjamin Peterson9d4cbcc2015-01-30 13:33:42 -05003990 while (compatible_with_tp_base(newbase))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003991 newbase = newbase->tp_base;
Benjamin Peterson9d4cbcc2015-01-30 13:33:42 -05003992 while (compatible_with_tp_base(oldbase))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003993 oldbase = oldbase->tp_base;
3994 if (newbase != oldbase &&
3995 (newbase->tp_base != oldbase->tp_base ||
3996 !same_slots_added(newbase, oldbase))) {
3997 PyErr_Format(PyExc_TypeError,
3998 "%s assignment: "
3999 "'%s' object layout differs from '%s'",
4000 attr,
4001 newto->tp_name,
4002 oldto->tp_name);
4003 return 0;
4004 }
Tim Petersea7f75d2002-12-07 21:39:16 +00004005
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004006 return 1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00004007}
4008
4009static int
Guido van Rossum5c294fb2001-09-25 03:43:42 +00004010object_set_class(PyObject *self, PyObject *value, void *closure)
4011{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004012 PyTypeObject *oldto = Py_TYPE(self);
4013 PyTypeObject *newto;
Guido van Rossum5c294fb2001-09-25 03:43:42 +00004014
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004015 if (value == NULL) {
4016 PyErr_SetString(PyExc_TypeError,
4017 "can't delete __class__ attribute");
4018 return -1;
4019 }
4020 if (!PyType_Check(value)) {
4021 PyErr_Format(PyExc_TypeError,
Florent Xiclunaaa6c1d22011-12-12 18:54:29 +01004022 "__class__ must be set to a class, not '%s' object",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004023 Py_TYPE(value)->tp_name);
4024 return -1;
4025 }
4026 newto = (PyTypeObject *)value;
Guido van Rossum7d293ee2015-09-04 20:54:07 -07004027 /* In versions of CPython prior to 3.5, the code in
4028 compatible_for_assignment was not set up to correctly check for memory
4029 layout / slot / etc. compatibility for non-HEAPTYPE classes, so we just
4030 disallowed __class__ assignment in any case that wasn't HEAPTYPE ->
4031 HEAPTYPE.
4032
4033 During the 3.5 development cycle, we fixed the code in
4034 compatible_for_assignment to correctly check compatibility between
4035 arbitrary types, and started allowing __class__ assignment in all cases
4036 where the old and new types did in fact have compatible slots and
4037 memory layout (regardless of whether they were implemented as HEAPTYPEs
4038 or not).
4039
4040 Just before 3.5 was released, though, we discovered that this led to
4041 problems with immutable types like int, where the interpreter assumes
4042 they are immutable and interns some values. Formerly this wasn't a
4043 problem, because they really were immutable -- in particular, all the
4044 types where the interpreter applied this interning trick happened to
4045 also be statically allocated, so the old HEAPTYPE rules were
4046 "accidentally" stopping them from allowing __class__ assignment. But
4047 with the changes to __class__ assignment, we started allowing code like
4048
4049 class MyInt(int):
4050 ...
4051 # Modifies the type of *all* instances of 1 in the whole program,
4052 # including future instances (!), because the 1 object is interned.
4053 (1).__class__ = MyInt
4054
4055 (see https://bugs.python.org/issue24912).
4056
4057 In theory the proper fix would be to identify which classes rely on
4058 this invariant and somehow disallow __class__ assignment only for them,
4059 perhaps via some mechanism like a new Py_TPFLAGS_IMMUTABLE flag (a
4060 "blacklisting" approach). But in practice, since this problem wasn't
4061 noticed late in the 3.5 RC cycle, we're taking the conservative
4062 approach and reinstating the same HEAPTYPE->HEAPTYPE check that we used
4063 to have, plus a "whitelist". For now, the whitelist consists only of
4064 ModuleType subtypes, since those are the cases that motivated the patch
4065 in the first place -- see https://bugs.python.org/issue22986 -- and
4066 since module objects are mutable we can be sure that they are
4067 definitely not being interned. So now we allow HEAPTYPE->HEAPTYPE *or*
4068 ModuleType subtype -> ModuleType subtype.
4069
4070 So far as we know, all the code beyond the following 'if' statement
4071 will correctly handle non-HEAPTYPE classes, and the HEAPTYPE check is
4072 needed only to protect that subset of non-HEAPTYPE classes for which
4073 the interpreter has baked in the assumption that all instances are
4074 truly immutable.
4075 */
4076 if (!(PyType_IsSubtype(newto, &PyModule_Type) &&
4077 PyType_IsSubtype(oldto, &PyModule_Type)) &&
4078 (!(newto->tp_flags & Py_TPFLAGS_HEAPTYPE) ||
4079 !(oldto->tp_flags & Py_TPFLAGS_HEAPTYPE))) {
4080 PyErr_Format(PyExc_TypeError,
4081 "__class__ assignment only supported for heap types "
4082 "or ModuleType subclasses");
4083 return -1;
4084 }
4085
Christian Heimesde4d1832013-07-20 14:19:46 +02004086 if (compatible_for_assignment(oldto, newto, "__class__")) {
Benjamin Peterson9d4cbcc2015-01-30 13:33:42 -05004087 if (newto->tp_flags & Py_TPFLAGS_HEAPTYPE)
4088 Py_INCREF(newto);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004089 Py_TYPE(self) = newto;
Benjamin Peterson9d4cbcc2015-01-30 13:33:42 -05004090 if (oldto->tp_flags & Py_TPFLAGS_HEAPTYPE)
4091 Py_DECREF(oldto);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004092 return 0;
4093 }
4094 else {
4095 return -1;
4096 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00004097}
4098
4099static PyGetSetDef object_getsets[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004100 {"__class__", object_get_class, object_set_class,
4101 PyDoc_STR("the object's class")},
4102 {0}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004103};
4104
Guido van Rossumc53f0092003-02-18 22:05:12 +00004105
Guido van Rossum036f9992003-02-21 22:02:54 +00004106/* Stuff to implement __reduce_ex__ for pickle protocols >= 2.
Alexandre Vassalottif7fa63d2008-05-11 08:55:36 +00004107 We fall back to helpers in copyreg for:
Guido van Rossum036f9992003-02-21 22:02:54 +00004108 - pickle protocols < 2
4109 - calculating the list of slot names (done only once per class)
4110 - the __newobj__ function (which is used as a token but never called)
4111*/
4112
4113static PyObject *
Alexandre Vassalottif7fa63d2008-05-11 08:55:36 +00004114import_copyreg(void)
Guido van Rossum036f9992003-02-21 22:02:54 +00004115{
Alexandre Vassalotti1a830702013-11-30 00:53:09 -08004116 PyObject *copyreg_str;
4117 PyObject *copyreg_module;
Alexandre Vassalotti1a830702013-11-30 00:53:09 -08004118 _Py_IDENTIFIER(copyreg);
Guido van Rossum3926a632001-09-25 16:25:58 +00004119
Alexandre Vassalotti1a830702013-11-30 00:53:09 -08004120 copyreg_str = _PyUnicode_FromId(&PyId_copyreg);
4121 if (copyreg_str == NULL) {
4122 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004123 }
Alexandre Vassalotti1a830702013-11-30 00:53:09 -08004124 /* Try to fetch cached copy of copyreg from sys.modules first in an
4125 attempt to avoid the import overhead. Previously this was implemented
4126 by storing a reference to the cached module in a static variable, but
Raymond Hettinger15f44ab2016-08-30 10:47:49 -07004127 this broke when multiple embedded interpreters were in use (see issue
Alexandre Vassalotti1a830702013-11-30 00:53:09 -08004128 #17408 and #19088). */
Eric Snow3f9eee62017-09-15 16:35:20 -06004129 copyreg_module = PyImport_GetModule(copyreg_str);
Alexandre Vassalotti1a830702013-11-30 00:53:09 -08004130 if (copyreg_module != NULL) {
Alexandre Vassalotti1a830702013-11-30 00:53:09 -08004131 return copyreg_module;
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01004132 }
Alexandre Vassalotti1a830702013-11-30 00:53:09 -08004133 if (PyErr_Occurred()) {
4134 return NULL;
4135 }
4136 return PyImport_Import(copyreg_str);
Guido van Rossum036f9992003-02-21 22:02:54 +00004137}
4138
Benjamin Peterson6cb526e2016-09-09 12:42:51 -07004139static PyObject *
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004140_PyType_GetSlotNames(PyTypeObject *cls)
Guido van Rossum036f9992003-02-21 22:02:54 +00004141{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004142 PyObject *copyreg;
4143 PyObject *slotnames;
Victor Stinner3c1e4812012-03-26 22:10:51 +02004144 _Py_IDENTIFIER(__slotnames__);
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02004145 _Py_IDENTIFIER(_slotnames);
Guido van Rossum036f9992003-02-21 22:02:54 +00004146
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004147 assert(PyType_Check(cls));
4148
4149 /* Get the slot names from the cache in the class if possible. */
4150 slotnames = _PyDict_GetItemIdWithError(cls->tp_dict, &PyId___slotnames__);
4151 if (slotnames != NULL) {
4152 if (slotnames != Py_None && !PyList_Check(slotnames)) {
4153 PyErr_Format(PyExc_TypeError,
4154 "%.200s.__slotnames__ should be a list or None, "
4155 "not %.200s",
4156 cls->tp_name, Py_TYPE(slotnames)->tp_name);
4157 return NULL;
4158 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004159 Py_INCREF(slotnames);
4160 return slotnames;
4161 }
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004162 else {
4163 if (PyErr_Occurred()) {
4164 return NULL;
4165 }
4166 /* The class does not have the slot names cached yet. */
4167 }
Guido van Rossum036f9992003-02-21 22:02:54 +00004168
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004169 copyreg = import_copyreg();
4170 if (copyreg == NULL)
4171 return NULL;
Guido van Rossum036f9992003-02-21 22:02:54 +00004172
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004173 /* Use _slotnames function from the copyreg module to find the slots
4174 by this class and its bases. This function will cache the result
4175 in __slotnames__. */
4176 slotnames = _PyObject_CallMethodIdObjArgs(copyreg, &PyId__slotnames,
4177 cls, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004178 Py_DECREF(copyreg);
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004179 if (slotnames == NULL)
4180 return NULL;
4181
4182 if (slotnames != Py_None && !PyList_Check(slotnames)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004183 PyErr_SetString(PyExc_TypeError,
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004184 "copyreg._slotnames didn't return a list or None");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004185 Py_DECREF(slotnames);
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004186 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004187 }
Guido van Rossum036f9992003-02-21 22:02:54 +00004188
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004189 return slotnames;
Guido van Rossum036f9992003-02-21 22:02:54 +00004190}
4191
Benjamin Peterson6cb526e2016-09-09 12:42:51 -07004192static PyObject *
Serhiy Storchakaf81be8a2015-12-25 21:04:29 +02004193_PyObject_GetState(PyObject *obj, int required)
Guido van Rossum036f9992003-02-21 22:02:54 +00004194{
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004195 PyObject *state;
4196 PyObject *getstate;
Victor Stinner3c1e4812012-03-26 22:10:51 +02004197 _Py_IDENTIFIER(__getstate__);
Guido van Rossum036f9992003-02-21 22:02:54 +00004198
Serhiy Storchakaf320be72018-01-25 10:49:40 +02004199 if (_PyObject_LookupAttrId(obj, &PyId___getstate__, &getstate) < 0) {
4200 return NULL;
4201 }
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004202 if (getstate == NULL) {
4203 PyObject *slotnames;
4204
Serhiy Storchakaf81be8a2015-12-25 21:04:29 +02004205 if (required && obj->ob_type->tp_itemsize) {
4206 PyErr_Format(PyExc_TypeError,
Serhiy Storchaka0353b4e2018-10-31 02:28:07 +02004207 "cannot pickle '%.200s' object",
Serhiy Storchakaf81be8a2015-12-25 21:04:29 +02004208 Py_TYPE(obj)->tp_name);
4209 return NULL;
4210 }
4211
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004212 {
4213 PyObject **dict;
4214 dict = _PyObject_GetDictPtr(obj);
Larry Hastings5c661892014-01-24 06:17:25 -08004215 /* It is possible that the object's dict is not initialized
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004216 yet. In this case, we will return None for the state.
4217 We also return None if the dict is empty to make the behavior
4218 consistent regardless whether the dict was initialized or not.
4219 This make unit testing easier. */
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02004220 if (dict != NULL && *dict != NULL && PyDict_GET_SIZE(*dict)) {
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004221 state = *dict;
4222 }
4223 else {
4224 state = Py_None;
4225 }
4226 Py_INCREF(state);
4227 }
4228
4229 slotnames = _PyType_GetSlotNames(Py_TYPE(obj));
4230 if (slotnames == NULL) {
4231 Py_DECREF(state);
4232 return NULL;
4233 }
4234
4235 assert(slotnames == Py_None || PyList_Check(slotnames));
Serhiy Storchakaf81be8a2015-12-25 21:04:29 +02004236 if (required) {
4237 Py_ssize_t basicsize = PyBaseObject_Type.tp_basicsize;
4238 if (obj->ob_type->tp_dictoffset)
4239 basicsize += sizeof(PyObject *);
4240 if (obj->ob_type->tp_weaklistoffset)
4241 basicsize += sizeof(PyObject *);
4242 if (slotnames != Py_None)
Serhiy Storchakafff9a312017-03-21 08:53:25 +02004243 basicsize += sizeof(PyObject *) * PyList_GET_SIZE(slotnames);
Serhiy Storchakaf81be8a2015-12-25 21:04:29 +02004244 if (obj->ob_type->tp_basicsize > basicsize) {
4245 Py_DECREF(slotnames);
4246 Py_DECREF(state);
4247 PyErr_Format(PyExc_TypeError,
Serhiy Storchaka0353b4e2018-10-31 02:28:07 +02004248 "cannot pickle '%.200s' object",
Serhiy Storchakaf81be8a2015-12-25 21:04:29 +02004249 Py_TYPE(obj)->tp_name);
4250 return NULL;
4251 }
4252 }
4253
Serhiy Storchakafff9a312017-03-21 08:53:25 +02004254 if (slotnames != Py_None && PyList_GET_SIZE(slotnames) > 0) {
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004255 PyObject *slots;
4256 Py_ssize_t slotnames_size, i;
4257
4258 slots = PyDict_New();
4259 if (slots == NULL) {
4260 Py_DECREF(slotnames);
4261 Py_DECREF(state);
4262 return NULL;
4263 }
4264
Serhiy Storchakafff9a312017-03-21 08:53:25 +02004265 slotnames_size = PyList_GET_SIZE(slotnames);
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004266 for (i = 0; i < slotnames_size; i++) {
4267 PyObject *name, *value;
4268
4269 name = PyList_GET_ITEM(slotnames, i);
Serhiy Storchakad28bb622015-11-25 18:33:29 +02004270 Py_INCREF(name);
Serhiy Storchakaf320be72018-01-25 10:49:40 +02004271 if (_PyObject_LookupAttr(obj, name, &value) < 0) {
4272 goto error;
4273 }
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004274 if (value == NULL) {
Serhiy Storchakad28bb622015-11-25 18:33:29 +02004275 Py_DECREF(name);
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004276 /* It is not an error if the attribute is not present. */
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004277 }
4278 else {
4279 int err = PyDict_SetItem(slots, name, value);
Serhiy Storchakad28bb622015-11-25 18:33:29 +02004280 Py_DECREF(name);
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004281 Py_DECREF(value);
4282 if (err) {
4283 goto error;
4284 }
4285 }
4286
Martin Panter8f265652016-04-19 04:03:41 +00004287 /* The list is stored on the class so it may mutate while we
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004288 iterate over it */
Serhiy Storchakafff9a312017-03-21 08:53:25 +02004289 if (slotnames_size != PyList_GET_SIZE(slotnames)) {
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004290 PyErr_Format(PyExc_RuntimeError,
4291 "__slotsname__ changed size during iteration");
4292 goto error;
4293 }
4294
4295 /* We handle errors within the loop here. */
4296 if (0) {
4297 error:
4298 Py_DECREF(slotnames);
4299 Py_DECREF(slots);
4300 Py_DECREF(state);
4301 return NULL;
4302 }
4303 }
4304
4305 /* If we found some slot attributes, pack them in a tuple along
Berker Peksag0ac70c02016-04-29 16:54:10 +03004306 the original attribute dictionary. */
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02004307 if (PyDict_GET_SIZE(slots) > 0) {
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004308 PyObject *state2;
4309
4310 state2 = PyTuple_Pack(2, state, slots);
4311 Py_DECREF(state);
4312 if (state2 == NULL) {
4313 Py_DECREF(slotnames);
4314 Py_DECREF(slots);
4315 return NULL;
4316 }
4317 state = state2;
4318 }
4319 Py_DECREF(slots);
4320 }
4321 Py_DECREF(slotnames);
4322 }
4323 else { /* getstate != NULL */
Victor Stinnera5ed5f02016-12-06 18:45:50 +01004324 state = _PyObject_CallNoArg(getstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004325 Py_DECREF(getstate);
4326 if (state == NULL)
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004327 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004328 }
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004329
4330 return state;
4331}
4332
Benjamin Peterson6cb526e2016-09-09 12:42:51 -07004333static int
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004334_PyObject_GetNewArguments(PyObject *obj, PyObject **args, PyObject **kwargs)
4335{
4336 PyObject *getnewargs, *getnewargs_ex;
4337 _Py_IDENTIFIER(__getnewargs_ex__);
4338 _Py_IDENTIFIER(__getnewargs__);
4339
4340 if (args == NULL || kwargs == NULL) {
4341 PyErr_BadInternalCall();
4342 return -1;
4343 }
4344
4345 /* We first attempt to fetch the arguments for __new__ by calling
4346 __getnewargs_ex__ on the object. */
Benjamin Petersone686c5c2014-02-16 13:49:16 -05004347 getnewargs_ex = _PyObject_LookupSpecial(obj, &PyId___getnewargs_ex__);
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004348 if (getnewargs_ex != NULL) {
Victor Stinnera5ed5f02016-12-06 18:45:50 +01004349 PyObject *newargs = _PyObject_CallNoArg(getnewargs_ex);
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004350 Py_DECREF(getnewargs_ex);
4351 if (newargs == NULL) {
4352 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004353 }
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004354 if (!PyTuple_Check(newargs)) {
4355 PyErr_Format(PyExc_TypeError,
4356 "__getnewargs_ex__ should return a tuple, "
4357 "not '%.200s'", Py_TYPE(newargs)->tp_name);
4358 Py_DECREF(newargs);
4359 return -1;
4360 }
Serhiy Storchakafff9a312017-03-21 08:53:25 +02004361 if (PyTuple_GET_SIZE(newargs) != 2) {
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004362 PyErr_Format(PyExc_ValueError,
4363 "__getnewargs_ex__ should return a tuple of "
Serhiy Storchakafff9a312017-03-21 08:53:25 +02004364 "length 2, not %zd", PyTuple_GET_SIZE(newargs));
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004365 Py_DECREF(newargs);
4366 return -1;
4367 }
4368 *args = PyTuple_GET_ITEM(newargs, 0);
4369 Py_INCREF(*args);
4370 *kwargs = PyTuple_GET_ITEM(newargs, 1);
4371 Py_INCREF(*kwargs);
4372 Py_DECREF(newargs);
4373
4374 /* XXX We should perhaps allow None to be passed here. */
4375 if (!PyTuple_Check(*args)) {
4376 PyErr_Format(PyExc_TypeError,
4377 "first item of the tuple returned by "
4378 "__getnewargs_ex__ must be a tuple, not '%.200s'",
4379 Py_TYPE(*args)->tp_name);
4380 Py_CLEAR(*args);
4381 Py_CLEAR(*kwargs);
4382 return -1;
4383 }
4384 if (!PyDict_Check(*kwargs)) {
4385 PyErr_Format(PyExc_TypeError,
4386 "second item of the tuple returned by "
4387 "__getnewargs_ex__ must be a dict, not '%.200s'",
4388 Py_TYPE(*kwargs)->tp_name);
4389 Py_CLEAR(*args);
4390 Py_CLEAR(*kwargs);
4391 return -1;
4392 }
4393 return 0;
Benjamin Petersone686c5c2014-02-16 13:49:16 -05004394 } else if (PyErr_Occurred()) {
4395 return -1;
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004396 }
4397
4398 /* The object does not have __getnewargs_ex__ so we fallback on using
4399 __getnewargs__ instead. */
Benjamin Petersone686c5c2014-02-16 13:49:16 -05004400 getnewargs = _PyObject_LookupSpecial(obj, &PyId___getnewargs__);
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004401 if (getnewargs != NULL) {
Victor Stinnera5ed5f02016-12-06 18:45:50 +01004402 *args = _PyObject_CallNoArg(getnewargs);
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004403 Py_DECREF(getnewargs);
4404 if (*args == NULL) {
4405 return -1;
4406 }
4407 if (!PyTuple_Check(*args)) {
4408 PyErr_Format(PyExc_TypeError,
4409 "__getnewargs__ should return a tuple, "
4410 "not '%.200s'", Py_TYPE(*args)->tp_name);
4411 Py_CLEAR(*args);
4412 return -1;
4413 }
4414 *kwargs = NULL;
4415 return 0;
Benjamin Petersone686c5c2014-02-16 13:49:16 -05004416 } else if (PyErr_Occurred()) {
4417 return -1;
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004418 }
4419
4420 /* The object does not have __getnewargs_ex__ and __getnewargs__. This may
Martin Panter8f265652016-04-19 04:03:41 +00004421 mean __new__ does not takes any arguments on this object, or that the
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004422 object does not implement the reduce protocol for pickling or
4423 copying. */
4424 *args = NULL;
4425 *kwargs = NULL;
4426 return 0;
4427}
4428
Benjamin Peterson6cb526e2016-09-09 12:42:51 -07004429static int
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004430_PyObject_GetItemsIter(PyObject *obj, PyObject **listitems,
4431 PyObject **dictitems)
4432{
4433 if (listitems == NULL || dictitems == NULL) {
4434 PyErr_BadInternalCall();
4435 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004436 }
Guido van Rossum036f9992003-02-21 22:02:54 +00004437
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004438 if (!PyList_Check(obj)) {
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004439 *listitems = Py_None;
4440 Py_INCREF(*listitems);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004441 }
4442 else {
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004443 *listitems = PyObject_GetIter(obj);
Christian Heimes2489bd82013-11-23 21:19:43 +01004444 if (*listitems == NULL)
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004445 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004446 }
Guido van Rossum036f9992003-02-21 22:02:54 +00004447
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004448 if (!PyDict_Check(obj)) {
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004449 *dictitems = Py_None;
4450 Py_INCREF(*dictitems);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004451 }
4452 else {
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004453 PyObject *items;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02004454 _Py_IDENTIFIER(items);
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004455
4456 items = _PyObject_CallMethodIdObjArgs(obj, &PyId_items, NULL);
4457 if (items == NULL) {
4458 Py_CLEAR(*listitems);
4459 return -1;
4460 }
4461 *dictitems = PyObject_GetIter(items);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004462 Py_DECREF(items);
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004463 if (*dictitems == NULL) {
4464 Py_CLEAR(*listitems);
4465 return -1;
4466 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004467 }
Guido van Rossum036f9992003-02-21 22:02:54 +00004468
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004469 assert(*listitems != NULL && *dictitems != NULL);
4470
4471 return 0;
4472}
4473
4474static PyObject *
Serhiy Storchaka0d554d72015-10-10 22:42:18 +03004475reduce_newobj(PyObject *obj)
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004476{
4477 PyObject *args = NULL, *kwargs = NULL;
4478 PyObject *copyreg;
4479 PyObject *newobj, *newargs, *state, *listitems, *dictitems;
4480 PyObject *result;
Serhiy Storchakaf81be8a2015-12-25 21:04:29 +02004481 int hasargs;
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004482
Serhiy Storchakad7a44152015-11-12 11:23:04 +02004483 if (Py_TYPE(obj)->tp_new == NULL) {
4484 PyErr_Format(PyExc_TypeError,
Serhiy Storchaka0353b4e2018-10-31 02:28:07 +02004485 "cannot pickle '%.200s' object",
Serhiy Storchakad7a44152015-11-12 11:23:04 +02004486 Py_TYPE(obj)->tp_name);
4487 return NULL;
4488 }
Serhiy Storchaka707b5cc2014-12-16 19:43:46 +02004489 if (_PyObject_GetNewArguments(obj, &args, &kwargs) < 0)
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004490 return NULL;
Serhiy Storchaka707b5cc2014-12-16 19:43:46 +02004491
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004492 copyreg = import_copyreg();
4493 if (copyreg == NULL) {
Serhiy Storchakaf81be8a2015-12-25 21:04:29 +02004494 Py_XDECREF(args);
Serhiy Storchaka707b5cc2014-12-16 19:43:46 +02004495 Py_XDECREF(kwargs);
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004496 return NULL;
4497 }
Serhiy Storchakaf81be8a2015-12-25 21:04:29 +02004498 hasargs = (args != NULL);
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02004499 if (kwargs == NULL || PyDict_GET_SIZE(kwargs) == 0) {
Serhiy Storchaka707b5cc2014-12-16 19:43:46 +02004500 _Py_IDENTIFIER(__newobj__);
4501 PyObject *cls;
4502 Py_ssize_t i, n;
4503
4504 Py_XDECREF(kwargs);
4505 newobj = _PyObject_GetAttrId(copyreg, &PyId___newobj__);
4506 Py_DECREF(copyreg);
4507 if (newobj == NULL) {
Serhiy Storchakaf81be8a2015-12-25 21:04:29 +02004508 Py_XDECREF(args);
Serhiy Storchaka707b5cc2014-12-16 19:43:46 +02004509 return NULL;
4510 }
Serhiy Storchakaf81be8a2015-12-25 21:04:29 +02004511 n = args ? PyTuple_GET_SIZE(args) : 0;
Serhiy Storchaka707b5cc2014-12-16 19:43:46 +02004512 newargs = PyTuple_New(n+1);
4513 if (newargs == NULL) {
Serhiy Storchakaf81be8a2015-12-25 21:04:29 +02004514 Py_XDECREF(args);
Serhiy Storchaka707b5cc2014-12-16 19:43:46 +02004515 Py_DECREF(newobj);
4516 return NULL;
4517 }
4518 cls = (PyObject *) Py_TYPE(obj);
4519 Py_INCREF(cls);
4520 PyTuple_SET_ITEM(newargs, 0, cls);
4521 for (i = 0; i < n; i++) {
4522 PyObject *v = PyTuple_GET_ITEM(args, i);
4523 Py_INCREF(v);
4524 PyTuple_SET_ITEM(newargs, i+1, v);
4525 }
Serhiy Storchakaf81be8a2015-12-25 21:04:29 +02004526 Py_XDECREF(args);
Serhiy Storchaka707b5cc2014-12-16 19:43:46 +02004527 }
Christian Heimes07a2a1b2016-09-09 00:21:22 +02004528 else if (args != NULL) {
Serhiy Storchaka707b5cc2014-12-16 19:43:46 +02004529 _Py_IDENTIFIER(__newobj_ex__);
4530
4531 newobj = _PyObject_GetAttrId(copyreg, &PyId___newobj_ex__);
4532 Py_DECREF(copyreg);
4533 if (newobj == NULL) {
4534 Py_DECREF(args);
4535 Py_DECREF(kwargs);
4536 return NULL;
4537 }
4538 newargs = PyTuple_Pack(3, Py_TYPE(obj), args, kwargs);
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004539 Py_DECREF(args);
4540 Py_DECREF(kwargs);
Serhiy Storchaka707b5cc2014-12-16 19:43:46 +02004541 if (newargs == NULL) {
4542 Py_DECREF(newobj);
4543 return NULL;
4544 }
4545 }
Christian Heimes07a2a1b2016-09-09 00:21:22 +02004546 else {
4547 /* args == NULL */
4548 Py_DECREF(kwargs);
4549 PyErr_BadInternalCall();
4550 return NULL;
4551 }
Serhiy Storchaka707b5cc2014-12-16 19:43:46 +02004552
Serhiy Storchakaf81be8a2015-12-25 21:04:29 +02004553 state = _PyObject_GetState(obj,
4554 !hasargs && !PyList_Check(obj) && !PyDict_Check(obj));
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004555 if (state == NULL) {
4556 Py_DECREF(newobj);
4557 Py_DECREF(newargs);
4558 return NULL;
4559 }
4560 if (_PyObject_GetItemsIter(obj, &listitems, &dictitems) < 0) {
4561 Py_DECREF(newobj);
4562 Py_DECREF(newargs);
4563 Py_DECREF(state);
4564 return NULL;
4565 }
4566
4567 result = PyTuple_Pack(5, newobj, newargs, state, listitems, dictitems);
4568 Py_DECREF(newobj);
4569 Py_DECREF(newargs);
4570 Py_DECREF(state);
4571 Py_DECREF(listitems);
4572 Py_DECREF(dictitems);
Larry Hastings5c661892014-01-24 06:17:25 -08004573 return result;
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004574}
4575
Guido van Rossumd8faa362007-04-27 19:54:29 +00004576/*
4577 * There were two problems when object.__reduce__ and object.__reduce_ex__
4578 * were implemented in the same function:
4579 * - trying to pickle an object with a custom __reduce__ method that
4580 * fell back to object.__reduce__ in certain circumstances led to
Yury Selivanovf488fb42015-07-03 01:04:23 -04004581 * infinite recursion at Python level and eventual RecursionError.
Guido van Rossumd8faa362007-04-27 19:54:29 +00004582 * - Pickling objects that lied about their type by overwriting the
4583 * __class__ descriptor could lead to infinite recursion at C level
4584 * and eventual segfault.
4585 *
4586 * Because of backwards compatibility, the two methods still have to
4587 * behave in the same way, even if this is not required by the pickle
4588 * protocol. This common functionality was moved to the _common_reduce
4589 * function.
4590 */
4591static PyObject *
4592_common_reduce(PyObject *self, int proto)
4593{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004594 PyObject *copyreg, *res;
Guido van Rossumd8faa362007-04-27 19:54:29 +00004595
Serhiy Storchaka707b5cc2014-12-16 19:43:46 +02004596 if (proto >= 2)
Serhiy Storchaka0d554d72015-10-10 22:42:18 +03004597 return reduce_newobj(self);
Guido van Rossumd8faa362007-04-27 19:54:29 +00004598
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004599 copyreg = import_copyreg();
4600 if (!copyreg)
4601 return NULL;
Guido van Rossumd8faa362007-04-27 19:54:29 +00004602
INADA Naoki72dccde2017-02-16 09:26:01 +09004603 res = PyObject_CallMethod(copyreg, "_reduce_ex", "Oi", self, proto);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004604 Py_DECREF(copyreg);
Guido van Rossumd8faa362007-04-27 19:54:29 +00004605
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004606 return res;
Guido van Rossumd8faa362007-04-27 19:54:29 +00004607}
4608
Serhiy Storchaka5c643a02017-03-19 08:46:44 +02004609/*[clinic input]
4610object.__reduce__
4611
Serhiy Storchaka5c643a02017-03-19 08:46:44 +02004612Helper for pickle.
4613[clinic start generated code]*/
4614
Guido van Rossumd8faa362007-04-27 19:54:29 +00004615static PyObject *
Serhiy Storchaka205e00c2017-04-08 09:52:59 +03004616object___reduce___impl(PyObject *self)
4617/*[clinic end generated code: output=d4ca691f891c6e2f input=11562e663947e18b]*/
Guido van Rossumd8faa362007-04-27 19:54:29 +00004618{
Serhiy Storchaka205e00c2017-04-08 09:52:59 +03004619 return _common_reduce(self, 0);
Guido van Rossumd8faa362007-04-27 19:54:29 +00004620}
4621
Serhiy Storchaka5c643a02017-03-19 08:46:44 +02004622/*[clinic input]
4623object.__reduce_ex__
4624
Serhiy Storchaka205e00c2017-04-08 09:52:59 +03004625 protocol: int
Serhiy Storchaka5c643a02017-03-19 08:46:44 +02004626 /
4627
4628Helper for pickle.
4629[clinic start generated code]*/
4630
Guido van Rossum036f9992003-02-21 22:02:54 +00004631static PyObject *
Serhiy Storchaka5c643a02017-03-19 08:46:44 +02004632object___reduce_ex___impl(PyObject *self, int protocol)
Serhiy Storchaka205e00c2017-04-08 09:52:59 +03004633/*[clinic end generated code: output=2e157766f6b50094 input=f326b43fb8a4c5ff]*/
Guido van Rossum036f9992003-02-21 22:02:54 +00004634{
Victor Stinner3c1e4812012-03-26 22:10:51 +02004635 static PyObject *objreduce;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004636 PyObject *reduce, *res;
Victor Stinner3c1e4812012-03-26 22:10:51 +02004637 _Py_IDENTIFIER(__reduce__);
Guido van Rossum036f9992003-02-21 22:02:54 +00004638
Victor Stinner3c1e4812012-03-26 22:10:51 +02004639 if (objreduce == NULL) {
4640 objreduce = _PyDict_GetItemId(PyBaseObject_Type.tp_dict,
4641 &PyId___reduce__);
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01004642 }
4643
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02004644 if (_PyObject_LookupAttrId(self, &PyId___reduce__, &reduce) < 0) {
4645 return NULL;
4646 }
4647 if (reduce != NULL) {
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01004648 PyObject *cls, *clsreduce;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004649 int override;
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01004650
4651 cls = (PyObject *) Py_TYPE(self);
Victor Stinner3c1e4812012-03-26 22:10:51 +02004652 clsreduce = _PyObject_GetAttrId(cls, &PyId___reduce__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004653 if (clsreduce == NULL) {
4654 Py_DECREF(reduce);
4655 return NULL;
4656 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004657 override = (clsreduce != objreduce);
4658 Py_DECREF(clsreduce);
4659 if (override) {
Victor Stinnera5ed5f02016-12-06 18:45:50 +01004660 res = _PyObject_CallNoArg(reduce);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004661 Py_DECREF(reduce);
4662 return res;
4663 }
4664 else
4665 Py_DECREF(reduce);
4666 }
Guido van Rossum036f9992003-02-21 22:02:54 +00004667
Serhiy Storchaka5c643a02017-03-19 08:46:44 +02004668 return _common_reduce(self, protocol);
Guido van Rossum3926a632001-09-25 16:25:58 +00004669}
4670
Christian Heimes9e7f1d22008-02-28 12:27:11 +00004671static PyObject *
4672object_subclasshook(PyObject *cls, PyObject *args)
4673{
Brian Curtindfc80e32011-08-10 20:28:54 -05004674 Py_RETURN_NOTIMPLEMENTED;
Christian Heimes9e7f1d22008-02-28 12:27:11 +00004675}
4676
4677PyDoc_STRVAR(object_subclasshook_doc,
4678"Abstract classes can override this to customize issubclass().\n"
4679"\n"
4680"This is invoked early on by abc.ABCMeta.__subclasscheck__().\n"
4681"It should return True, False or NotImplemented. If it returns\n"
4682"NotImplemented, the normal algorithm is used. Otherwise, it\n"
4683"overrides the normal algorithm (and the outcome is cached).\n");
Eric Smith8c663262007-08-25 02:26:07 +00004684
Nick Coghland78448e2016-07-30 16:26:03 +10004685static PyObject *
4686object_init_subclass(PyObject *cls, PyObject *arg)
4687{
4688 Py_RETURN_NONE;
4689}
4690
4691PyDoc_STRVAR(object_init_subclass_doc,
Berker Peksag01d17192016-07-30 14:06:15 +03004692"This method is called when a class is subclassed.\n"
Nick Coghland78448e2016-07-30 16:26:03 +10004693"\n"
Berker Peksag01d17192016-07-30 14:06:15 +03004694"The default implementation does nothing. It may be\n"
4695"overridden to extend subclasses.\n");
Nick Coghland78448e2016-07-30 16:26:03 +10004696
Serhiy Storchaka5c643a02017-03-19 08:46:44 +02004697/*[clinic input]
4698object.__format__
4699
4700 format_spec: unicode
4701 /
4702
4703Default object formatter.
4704[clinic start generated code]*/
4705
Eric Smith8c663262007-08-25 02:26:07 +00004706static PyObject *
Serhiy Storchaka5c643a02017-03-19 08:46:44 +02004707object___format___impl(PyObject *self, PyObject *format_spec)
4708/*[clinic end generated code: output=34897efb543a974b input=7c3b3bc53a6fb7fa]*/
Eric Smith8c663262007-08-25 02:26:07 +00004709{
Serhiy Storchakad1af5ef2016-10-30 19:33:54 +02004710 /* Issue 7994: If we're converting to a string, we
4711 should reject format specifications */
4712 if (PyUnicode_GET_LENGTH(format_spec) > 0) {
4713 PyErr_Format(PyExc_TypeError,
4714 "unsupported format string passed to %.200s.__format__",
4715 self->ob_type->tp_name);
4716 return NULL;
4717 }
Serhiy Storchaka7e19dbc2017-05-13 12:40:52 +03004718 return PyObject_Str(self);
Eric Smith8c663262007-08-25 02:26:07 +00004719}
4720
Serhiy Storchaka5c643a02017-03-19 08:46:44 +02004721/*[clinic input]
4722object.__sizeof__
4723
4724Size of object in memory, in bytes.
4725[clinic start generated code]*/
4726
Martin v. Löwis00709aa2008-06-04 14:18:43 +00004727static PyObject *
Serhiy Storchaka5c643a02017-03-19 08:46:44 +02004728object___sizeof___impl(PyObject *self)
4729/*[clinic end generated code: output=73edab332f97d550 input=1200ff3dfe485306]*/
Martin v. Löwis00709aa2008-06-04 14:18:43 +00004730{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004731 Py_ssize_t res, isize;
Martin v. Löwis00709aa2008-06-04 14:18:43 +00004732
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004733 res = 0;
4734 isize = self->ob_type->tp_itemsize;
4735 if (isize > 0)
Antoine Pitroua6545102015-03-10 22:32:00 +01004736 res = Py_SIZE(self) * isize;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004737 res += self->ob_type->tp_basicsize;
Martin v. Löwis00709aa2008-06-04 14:18:43 +00004738
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004739 return PyLong_FromSsize_t(res);
Martin v. Löwis00709aa2008-06-04 14:18:43 +00004740}
4741
Benjamin Peterson82b00c12011-05-24 11:09:06 -05004742/* __dir__ for generic objects: returns __dict__, __class__,
4743 and recursively up the __class__.__bases__ chain.
4744*/
Serhiy Storchaka5c643a02017-03-19 08:46:44 +02004745/*[clinic input]
4746object.__dir__
4747
4748Default dir() implementation.
4749[clinic start generated code]*/
4750
Benjamin Peterson82b00c12011-05-24 11:09:06 -05004751static PyObject *
Serhiy Storchaka5c643a02017-03-19 08:46:44 +02004752object___dir___impl(PyObject *self)
4753/*[clinic end generated code: output=66dd48ea62f26c90 input=0a89305bec669b10]*/
Benjamin Peterson82b00c12011-05-24 11:09:06 -05004754{
4755 PyObject *result = NULL;
4756 PyObject *dict = NULL;
4757 PyObject *itsclass = NULL;
4758
4759 /* Get __dict__ (which may or may not be a real dict...) */
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02004760 dict = _PyObject_GetAttrId(self, &PyId___dict__);
Benjamin Peterson82b00c12011-05-24 11:09:06 -05004761 if (dict == NULL) {
4762 PyErr_Clear();
4763 dict = PyDict_New();
4764 }
4765 else if (!PyDict_Check(dict)) {
4766 Py_DECREF(dict);
4767 dict = PyDict_New();
4768 }
4769 else {
4770 /* Copy __dict__ to avoid mutating it. */
4771 PyObject *temp = PyDict_Copy(dict);
4772 Py_DECREF(dict);
4773 dict = temp;
4774 }
4775
4776 if (dict == NULL)
4777 goto error;
4778
4779 /* Merge in attrs reachable from its class. */
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02004780 itsclass = _PyObject_GetAttrId(self, &PyId___class__);
Benjamin Peterson82b00c12011-05-24 11:09:06 -05004781 if (itsclass == NULL)
4782 /* XXX(tomer): Perhaps fall back to obj->ob_type if no
4783 __class__ exists? */
4784 PyErr_Clear();
4785 else if (merge_class_dict(dict, itsclass) != 0)
4786 goto error;
4787
4788 result = PyDict_Keys(dict);
4789 /* fall through */
4790error:
4791 Py_XDECREF(itsclass);
4792 Py_XDECREF(dict);
4793 return result;
4794}
4795
Guido van Rossum3926a632001-09-25 16:25:58 +00004796static PyMethodDef object_methods[] = {
Serhiy Storchaka5c643a02017-03-19 08:46:44 +02004797 OBJECT___REDUCE_EX___METHODDEF
4798 OBJECT___REDUCE___METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004799 {"__subclasshook__", object_subclasshook, METH_CLASS | METH_VARARGS,
4800 object_subclasshook_doc},
Nick Coghland78448e2016-07-30 16:26:03 +10004801 {"__init_subclass__", object_init_subclass, METH_CLASS | METH_NOARGS,
4802 object_init_subclass_doc},
Serhiy Storchaka5c643a02017-03-19 08:46:44 +02004803 OBJECT___FORMAT___METHODDEF
4804 OBJECT___SIZEOF___METHODDEF
4805 OBJECT___DIR___METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004806 {0}
Guido van Rossum3926a632001-09-25 16:25:58 +00004807};
4808
Guido van Rossum036f9992003-02-21 22:02:54 +00004809
Tim Peters6d6c1a32001-08-02 04:15:00 +00004810PyTypeObject PyBaseObject_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004811 PyVarObject_HEAD_INIT(&PyType_Type, 0)
4812 "object", /* tp_name */
4813 sizeof(PyObject), /* tp_basicsize */
4814 0, /* tp_itemsize */
4815 object_dealloc, /* tp_dealloc */
4816 0, /* tp_print */
4817 0, /* tp_getattr */
4818 0, /* tp_setattr */
4819 0, /* tp_reserved */
4820 object_repr, /* tp_repr */
4821 0, /* tp_as_number */
4822 0, /* tp_as_sequence */
4823 0, /* tp_as_mapping */
4824 (hashfunc)_Py_HashPointer, /* tp_hash */
4825 0, /* tp_call */
4826 object_str, /* tp_str */
4827 PyObject_GenericGetAttr, /* tp_getattro */
4828 PyObject_GenericSetAttr, /* tp_setattro */
4829 0, /* tp_as_buffer */
Larry Hastings5c661892014-01-24 06:17:25 -08004830 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Larry Hastings2623c8c2014-02-08 22:15:29 -08004831 PyDoc_STR("object()\n--\n\nThe most base type"), /* tp_doc */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004832 0, /* tp_traverse */
4833 0, /* tp_clear */
4834 object_richcompare, /* tp_richcompare */
4835 0, /* tp_weaklistoffset */
4836 0, /* tp_iter */
4837 0, /* tp_iternext */
4838 object_methods, /* tp_methods */
4839 0, /* tp_members */
4840 object_getsets, /* tp_getset */
4841 0, /* tp_base */
4842 0, /* tp_dict */
4843 0, /* tp_descr_get */
4844 0, /* tp_descr_set */
4845 0, /* tp_dictoffset */
4846 object_init, /* tp_init */
4847 PyType_GenericAlloc, /* tp_alloc */
4848 object_new, /* tp_new */
4849 PyObject_Del, /* tp_free */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004850};
4851
4852
Guido van Rossum50e9fb92006-08-17 05:42:55 +00004853/* Add the methods from tp_methods to the __dict__ in a type object */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004854
4855static int
4856add_methods(PyTypeObject *type, PyMethodDef *meth)
4857{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004858 PyObject *dict = type->tp_dict;
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02004859 PyObject *name;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004860
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004861 for (; meth->ml_name != NULL; meth++) {
4862 PyObject *descr;
Benjamin Peterson89a6e9a2012-05-08 09:22:24 -04004863 int err;
INADA Naoki35a96a22017-01-28 16:35:44 +09004864 int isdescr = 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004865 if (meth->ml_flags & METH_CLASS) {
4866 if (meth->ml_flags & METH_STATIC) {
4867 PyErr_SetString(PyExc_ValueError,
4868 "method cannot be both class and static");
4869 return -1;
4870 }
4871 descr = PyDescr_NewClassMethod(type, meth);
4872 }
4873 else if (meth->ml_flags & METH_STATIC) {
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02004874 PyObject *cfunc = PyCFunction_NewEx(meth, (PyObject*)type, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004875 if (cfunc == NULL)
4876 return -1;
4877 descr = PyStaticMethod_New(cfunc);
INADA Naoki35a96a22017-01-28 16:35:44 +09004878 isdescr = 0; // PyStaticMethod is not PyDescrObject
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004879 Py_DECREF(cfunc);
4880 }
4881 else {
4882 descr = PyDescr_NewMethod(type, meth);
4883 }
4884 if (descr == NULL)
4885 return -1;
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02004886
INADA Naoki35a96a22017-01-28 16:35:44 +09004887 if (isdescr) {
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02004888 name = PyDescr_NAME(descr);
INADA Naoki35a96a22017-01-28 16:35:44 +09004889 }
4890 else {
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02004891 name = PyUnicode_FromString(meth->ml_name);
4892 if (name == NULL) {
4893 Py_DECREF(descr);
4894 return -1;
4895 }
4896 }
4897
4898 if (!(meth->ml_flags & METH_COEXIST)) {
4899 if (PyDict_GetItemWithError(dict, name)) {
4900 if (!isdescr) {
4901 Py_DECREF(name);
4902 }
4903 Py_DECREF(descr);
4904 continue;
4905 }
4906 else if (PyErr_Occurred()) {
4907 if (!isdescr) {
4908 Py_DECREF(name);
4909 }
4910 return -1;
4911 }
4912 }
4913 err = PyDict_SetItem(dict, name, descr);
4914 if (!isdescr) {
4915 Py_DECREF(name);
INADA Naoki35a96a22017-01-28 16:35:44 +09004916 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004917 Py_DECREF(descr);
Benjamin Peterson89a6e9a2012-05-08 09:22:24 -04004918 if (err < 0)
4919 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004920 }
4921 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004922}
4923
4924static int
Guido van Rossum6f799372001-09-20 20:46:19 +00004925add_members(PyTypeObject *type, PyMemberDef *memb)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004926{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004927 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004928
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004929 for (; memb->name != NULL; memb++) {
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02004930 PyObject *descr = PyDescr_NewMember(type, memb);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004931 if (descr == NULL)
4932 return -1;
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02004933
4934 if (PyDict_GetItemWithError(dict, PyDescr_NAME(descr))) {
4935 Py_DECREF(descr);
4936 continue;
4937 }
4938 else if (PyErr_Occurred()) {
4939 Py_DECREF(descr);
4940 return -1;
4941 }
INADA Naoki35a96a22017-01-28 16:35:44 +09004942 if (PyDict_SetItem(dict, PyDescr_NAME(descr), descr) < 0) {
Benjamin Peterson27007dc2016-07-06 23:26:32 -07004943 Py_DECREF(descr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004944 return -1;
Benjamin Peterson27007dc2016-07-06 23:26:32 -07004945 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004946 Py_DECREF(descr);
4947 }
4948 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004949}
4950
4951static int
Guido van Rossum32d34c82001-09-20 21:45:26 +00004952add_getset(PyTypeObject *type, PyGetSetDef *gsp)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004953{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004954 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004955
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004956 for (; gsp->name != NULL; gsp++) {
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02004957 PyObject *descr = PyDescr_NewGetSet(type, gsp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004958 if (descr == NULL)
4959 return -1;
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02004960
4961 if (PyDict_GetItemWithError(dict, PyDescr_NAME(descr))) {
Benjamin Petersond5a551c2019-02-25 23:12:10 -08004962 Py_DECREF(descr);
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02004963 continue;
4964 }
4965 else if (PyErr_Occurred()) {
4966 Py_DECREF(descr);
4967 return -1;
4968 }
INADA Naoki35a96a22017-01-28 16:35:44 +09004969 if (PyDict_SetItem(dict, PyDescr_NAME(descr), descr) < 0) {
Benjamin Peterson27007dc2016-07-06 23:26:32 -07004970 Py_DECREF(descr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004971 return -1;
Benjamin Peterson27007dc2016-07-06 23:26:32 -07004972 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004973 Py_DECREF(descr);
4974 }
4975 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004976}
4977
Guido van Rossum13d52f02001-08-10 21:24:08 +00004978static void
4979inherit_special(PyTypeObject *type, PyTypeObject *base)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004980{
Tim Peters6d6c1a32001-08-02 04:15:00 +00004981
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004982 /* Copying basicsize is connected to the GC flags */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004983 if (!(type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
4984 (base->tp_flags & Py_TPFLAGS_HAVE_GC) &&
4985 (!type->tp_traverse && !type->tp_clear)) {
4986 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
4987 if (type->tp_traverse == NULL)
4988 type->tp_traverse = base->tp_traverse;
4989 if (type->tp_clear == NULL)
4990 type->tp_clear = base->tp_clear;
4991 }
4992 {
4993 /* The condition below could use some explanation.
4994 It appears that tp_new is not inherited for static types
4995 whose base class is 'object'; this seems to be a precaution
4996 so that old extension types don't suddenly become
4997 callable (object.__new__ wouldn't insure the invariants
4998 that the extension type's own factory function ensures).
4999 Heap types, of course, are under our control, so they do
5000 inherit tp_new; static extension types that specify some
Florent Xiclunaaa6c1d22011-12-12 18:54:29 +01005001 other built-in type as the default also
5002 inherit object.__new__. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005003 if (base != &PyBaseObject_Type ||
5004 (type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
5005 if (type->tp_new == NULL)
5006 type->tp_new = base->tp_new;
5007 }
5008 }
Benjamin Petersona7465e22010-07-05 15:01:22 +00005009 if (type->tp_basicsize == 0)
5010 type->tp_basicsize = base->tp_basicsize;
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00005011
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005012 /* Copy other non-function slots */
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00005013
5014#undef COPYVAL
5015#define COPYVAL(SLOT) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005016 if (type->SLOT == 0) type->SLOT = base->SLOT
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00005017
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005018 COPYVAL(tp_itemsize);
5019 COPYVAL(tp_weaklistoffset);
5020 COPYVAL(tp_dictoffset);
Thomas Wouters27d517b2007-02-25 20:39:11 +00005021
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005022 /* Setup fast subclass flags */
5023 if (PyType_IsSubtype(base, (PyTypeObject*)PyExc_BaseException))
5024 type->tp_flags |= Py_TPFLAGS_BASE_EXC_SUBCLASS;
5025 else if (PyType_IsSubtype(base, &PyType_Type))
5026 type->tp_flags |= Py_TPFLAGS_TYPE_SUBCLASS;
5027 else if (PyType_IsSubtype(base, &PyLong_Type))
5028 type->tp_flags |= Py_TPFLAGS_LONG_SUBCLASS;
5029 else if (PyType_IsSubtype(base, &PyBytes_Type))
5030 type->tp_flags |= Py_TPFLAGS_BYTES_SUBCLASS;
5031 else if (PyType_IsSubtype(base, &PyUnicode_Type))
5032 type->tp_flags |= Py_TPFLAGS_UNICODE_SUBCLASS;
5033 else if (PyType_IsSubtype(base, &PyTuple_Type))
5034 type->tp_flags |= Py_TPFLAGS_TUPLE_SUBCLASS;
5035 else if (PyType_IsSubtype(base, &PyList_Type))
5036 type->tp_flags |= Py_TPFLAGS_LIST_SUBCLASS;
5037 else if (PyType_IsSubtype(base, &PyDict_Type))
5038 type->tp_flags |= Py_TPFLAGS_DICT_SUBCLASS;
Guido van Rossum13d52f02001-08-10 21:24:08 +00005039}
5040
Guido van Rossum38938152006-08-21 23:36:26 +00005041static int
Guido van Rossumf5243f02008-01-01 04:06:48 +00005042overrides_hash(PyTypeObject *type)
Guido van Rossum38938152006-08-21 23:36:26 +00005043{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005044 PyObject *dict = type->tp_dict;
Victor Stinner3c1e4812012-03-26 22:10:51 +02005045 _Py_IDENTIFIER(__eq__);
Guido van Rossum38938152006-08-21 23:36:26 +00005046
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005047 assert(dict != NULL);
Victor Stinner3c1e4812012-03-26 22:10:51 +02005048 if (_PyDict_GetItemId(dict, &PyId___eq__) != NULL)
5049 return 1;
5050 if (_PyDict_GetItemId(dict, &PyId___hash__) != NULL)
5051 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005052 return 0;
Guido van Rossum38938152006-08-21 23:36:26 +00005053}
5054
Guido van Rossum13d52f02001-08-10 21:24:08 +00005055static void
5056inherit_slots(PyTypeObject *type, PyTypeObject *base)
5057{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005058 PyTypeObject *basebase;
Guido van Rossum13d52f02001-08-10 21:24:08 +00005059
5060#undef SLOTDEFINED
Tim Peters6d6c1a32001-08-02 04:15:00 +00005061#undef COPYSLOT
5062#undef COPYNUM
5063#undef COPYSEQ
5064#undef COPYMAP
Guido van Rossum5af588b2001-10-12 14:13:21 +00005065#undef COPYBUF
Guido van Rossum13d52f02001-08-10 21:24:08 +00005066
5067#define SLOTDEFINED(SLOT) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005068 (base->SLOT != 0 && \
5069 (basebase == NULL || base->SLOT != basebase->SLOT))
Guido van Rossum13d52f02001-08-10 21:24:08 +00005070
Tim Peters6d6c1a32001-08-02 04:15:00 +00005071#define COPYSLOT(SLOT) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005072 if (!type->SLOT && SLOTDEFINED(SLOT)) type->SLOT = base->SLOT
Tim Peters6d6c1a32001-08-02 04:15:00 +00005073
Yury Selivanov75445082015-05-11 22:57:16 -04005074#define COPYASYNC(SLOT) COPYSLOT(tp_as_async->SLOT)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005075#define COPYNUM(SLOT) COPYSLOT(tp_as_number->SLOT)
5076#define COPYSEQ(SLOT) COPYSLOT(tp_as_sequence->SLOT)
5077#define COPYMAP(SLOT) COPYSLOT(tp_as_mapping->SLOT)
Tim Petersfc57ccb2001-10-12 02:38:24 +00005078#define COPYBUF(SLOT) COPYSLOT(tp_as_buffer->SLOT)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005079
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005080 /* This won't inherit indirect slots (from tp_as_number etc.)
5081 if type doesn't provide the space. */
Guido van Rossum13d52f02001-08-10 21:24:08 +00005082
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005083 if (type->tp_as_number != NULL && base->tp_as_number != NULL) {
5084 basebase = base->tp_base;
5085 if (basebase->tp_as_number == NULL)
5086 basebase = NULL;
5087 COPYNUM(nb_add);
5088 COPYNUM(nb_subtract);
5089 COPYNUM(nb_multiply);
5090 COPYNUM(nb_remainder);
5091 COPYNUM(nb_divmod);
5092 COPYNUM(nb_power);
5093 COPYNUM(nb_negative);
5094 COPYNUM(nb_positive);
5095 COPYNUM(nb_absolute);
5096 COPYNUM(nb_bool);
5097 COPYNUM(nb_invert);
5098 COPYNUM(nb_lshift);
5099 COPYNUM(nb_rshift);
5100 COPYNUM(nb_and);
5101 COPYNUM(nb_xor);
5102 COPYNUM(nb_or);
5103 COPYNUM(nb_int);
5104 COPYNUM(nb_float);
5105 COPYNUM(nb_inplace_add);
5106 COPYNUM(nb_inplace_subtract);
5107 COPYNUM(nb_inplace_multiply);
5108 COPYNUM(nb_inplace_remainder);
5109 COPYNUM(nb_inplace_power);
5110 COPYNUM(nb_inplace_lshift);
5111 COPYNUM(nb_inplace_rshift);
5112 COPYNUM(nb_inplace_and);
5113 COPYNUM(nb_inplace_xor);
5114 COPYNUM(nb_inplace_or);
5115 COPYNUM(nb_true_divide);
5116 COPYNUM(nb_floor_divide);
5117 COPYNUM(nb_inplace_true_divide);
5118 COPYNUM(nb_inplace_floor_divide);
5119 COPYNUM(nb_index);
Benjamin Petersond51374e2014-04-09 23:55:56 -04005120 COPYNUM(nb_matrix_multiply);
5121 COPYNUM(nb_inplace_matrix_multiply);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005122 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00005123
Yury Selivanov75445082015-05-11 22:57:16 -04005124 if (type->tp_as_async != NULL && base->tp_as_async != NULL) {
5125 basebase = base->tp_base;
5126 if (basebase->tp_as_async == NULL)
5127 basebase = NULL;
5128 COPYASYNC(am_await);
5129 COPYASYNC(am_aiter);
5130 COPYASYNC(am_anext);
5131 }
5132
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005133 if (type->tp_as_sequence != NULL && base->tp_as_sequence != NULL) {
5134 basebase = base->tp_base;
5135 if (basebase->tp_as_sequence == NULL)
5136 basebase = NULL;
5137 COPYSEQ(sq_length);
5138 COPYSEQ(sq_concat);
5139 COPYSEQ(sq_repeat);
5140 COPYSEQ(sq_item);
5141 COPYSEQ(sq_ass_item);
5142 COPYSEQ(sq_contains);
5143 COPYSEQ(sq_inplace_concat);
5144 COPYSEQ(sq_inplace_repeat);
5145 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00005146
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005147 if (type->tp_as_mapping != NULL && base->tp_as_mapping != NULL) {
5148 basebase = base->tp_base;
5149 if (basebase->tp_as_mapping == NULL)
5150 basebase = NULL;
5151 COPYMAP(mp_length);
5152 COPYMAP(mp_subscript);
5153 COPYMAP(mp_ass_subscript);
5154 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00005155
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005156 if (type->tp_as_buffer != NULL && base->tp_as_buffer != NULL) {
5157 basebase = base->tp_base;
5158 if (basebase->tp_as_buffer == NULL)
5159 basebase = NULL;
5160 COPYBUF(bf_getbuffer);
5161 COPYBUF(bf_releasebuffer);
5162 }
Tim Petersfc57ccb2001-10-12 02:38:24 +00005163
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005164 basebase = base->tp_base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005165
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005166 COPYSLOT(tp_dealloc);
5167 if (type->tp_getattr == NULL && type->tp_getattro == NULL) {
5168 type->tp_getattr = base->tp_getattr;
5169 type->tp_getattro = base->tp_getattro;
5170 }
5171 if (type->tp_setattr == NULL && type->tp_setattro == NULL) {
5172 type->tp_setattr = base->tp_setattr;
5173 type->tp_setattro = base->tp_setattro;
5174 }
5175 /* tp_reserved is ignored */
5176 COPYSLOT(tp_repr);
5177 /* tp_hash see tp_richcompare */
5178 COPYSLOT(tp_call);
5179 COPYSLOT(tp_str);
5180 {
5181 /* Copy comparison-related slots only when
5182 not overriding them anywhere */
5183 if (type->tp_richcompare == NULL &&
5184 type->tp_hash == NULL &&
5185 !overrides_hash(type))
5186 {
5187 type->tp_richcompare = base->tp_richcompare;
5188 type->tp_hash = base->tp_hash;
5189 }
5190 }
5191 {
5192 COPYSLOT(tp_iter);
5193 COPYSLOT(tp_iternext);
5194 }
5195 {
5196 COPYSLOT(tp_descr_get);
5197 COPYSLOT(tp_descr_set);
5198 COPYSLOT(tp_dictoffset);
5199 COPYSLOT(tp_init);
5200 COPYSLOT(tp_alloc);
5201 COPYSLOT(tp_is_gc);
Antoine Pitrou796564c2013-07-30 19:59:21 +02005202 if ((type->tp_flags & Py_TPFLAGS_HAVE_FINALIZE) &&
5203 (base->tp_flags & Py_TPFLAGS_HAVE_FINALIZE)) {
5204 COPYSLOT(tp_finalize);
5205 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005206 if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) ==
5207 (base->tp_flags & Py_TPFLAGS_HAVE_GC)) {
5208 /* They agree about gc. */
5209 COPYSLOT(tp_free);
5210 }
5211 else if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
5212 type->tp_free == NULL &&
5213 base->tp_free == PyObject_Free) {
5214 /* A bit of magic to plug in the correct default
5215 * tp_free function when a derived class adds gc,
5216 * didn't define tp_free, and the base uses the
5217 * default non-gc tp_free.
5218 */
5219 type->tp_free = PyObject_GC_Del;
5220 }
5221 /* else they didn't agree about gc, and there isn't something
5222 * obvious to be done -- the type is on its own.
5223 */
5224 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00005225}
5226
Jeremy Hylton938ace62002-07-17 16:30:39 +00005227static int add_operators(PyTypeObject *);
Guido van Rossum13d52f02001-08-10 21:24:08 +00005228
Tim Peters6d6c1a32001-08-02 04:15:00 +00005229int
Guido van Rossum528b7eb2001-08-07 17:24:28 +00005230PyType_Ready(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005231{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005232 PyObject *dict, *bases;
5233 PyTypeObject *base;
5234 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005235
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005236 if (type->tp_flags & Py_TPFLAGS_READY) {
Victor Stinnerbda5a2b2017-01-25 23:33:27 +01005237 assert(_PyType_CheckConsistency(type));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005238 return 0;
5239 }
Victor Stinner08625052018-10-26 18:39:11 +02005240 _PyObject_ASSERT((PyObject *)type,
5241 (type->tp_flags & Py_TPFLAGS_READYING) == 0);
Guido van Rossumd614f972001-08-10 17:39:49 +00005242
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005243 type->tp_flags |= Py_TPFLAGS_READYING;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005244
Tim Peters36eb4df2003-03-23 03:33:13 +00005245#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005246 /* PyType_Ready is the closest thing we have to a choke point
5247 * for type objects, so is the best place I can think of to try
5248 * to get type objects into the doubly-linked list of all objects.
Leo Ariasc3d95082018-02-03 18:36:10 -06005249 * Still, not all type objects go through PyType_Ready.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005250 */
5251 _Py_AddToAllObjects((PyObject *)type, 0);
Tim Peters36eb4df2003-03-23 03:33:13 +00005252#endif
5253
Serhiy Storchakade0574b2016-10-07 23:24:35 +03005254 if (type->tp_name == NULL) {
5255 PyErr_Format(PyExc_SystemError,
5256 "Type does not define the tp_name field.");
5257 goto error;
5258 }
5259
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005260 /* Initialize tp_base (defaults to BaseObject unless that's us) */
5261 base = type->tp_base;
5262 if (base == NULL && type != &PyBaseObject_Type) {
5263 base = type->tp_base = &PyBaseObject_Type;
5264 Py_INCREF(base);
5265 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00005266
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005267 /* Now the only way base can still be NULL is if type is
5268 * &PyBaseObject_Type.
5269 */
Guido van Rossum692cdbc2006-03-10 02:04:28 +00005270
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005271 /* Initialize the base class */
5272 if (base != NULL && base->tp_dict == NULL) {
5273 if (PyType_Ready(base) < 0)
5274 goto error;
5275 }
Guido van Rossum323a9cf2002-08-14 17:26:30 +00005276
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005277 /* Initialize ob_type if NULL. This means extensions that want to be
5278 compilable separately on Windows can call PyType_Ready() instead of
5279 initializing the ob_type field of their type objects. */
5280 /* The test for base != NULL is really unnecessary, since base is only
5281 NULL when type is &PyBaseObject_Type, and we know its ob_type is
5282 not NULL (it's initialized to &PyType_Type). But coverity doesn't
5283 know that. */
5284 if (Py_TYPE(type) == NULL && base != NULL)
5285 Py_TYPE(type) = Py_TYPE(base);
Guido van Rossum0986d822002-04-08 01:38:42 +00005286
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005287 /* Initialize tp_bases */
5288 bases = type->tp_bases;
5289 if (bases == NULL) {
5290 if (base == NULL)
5291 bases = PyTuple_New(0);
5292 else
5293 bases = PyTuple_Pack(1, base);
5294 if (bases == NULL)
5295 goto error;
5296 type->tp_bases = bases;
5297 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00005298
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005299 /* Initialize tp_dict */
5300 dict = type->tp_dict;
5301 if (dict == NULL) {
5302 dict = PyDict_New();
5303 if (dict == NULL)
5304 goto error;
5305 type->tp_dict = dict;
5306 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00005307
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005308 /* Add type-specific descriptors to tp_dict */
5309 if (add_operators(type) < 0)
5310 goto error;
5311 if (type->tp_methods != NULL) {
5312 if (add_methods(type, type->tp_methods) < 0)
5313 goto error;
5314 }
5315 if (type->tp_members != NULL) {
5316 if (add_members(type, type->tp_members) < 0)
5317 goto error;
5318 }
5319 if (type->tp_getset != NULL) {
5320 if (add_getset(type, type->tp_getset) < 0)
5321 goto error;
5322 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00005323
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005324 /* Calculate method resolution order */
Benjamin Peterson104b9e02015-02-05 22:29:14 -05005325 if (mro_internal(type, NULL) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005326 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005327
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005328 /* Inherit special flags from dominant base */
5329 if (type->tp_base != NULL)
5330 inherit_special(type, type->tp_base);
Guido van Rossum13d52f02001-08-10 21:24:08 +00005331
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005332 /* Initialize tp_dict properly */
5333 bases = type->tp_mro;
5334 assert(bases != NULL);
5335 assert(PyTuple_Check(bases));
5336 n = PyTuple_GET_SIZE(bases);
5337 for (i = 1; i < n; i++) {
5338 PyObject *b = PyTuple_GET_ITEM(bases, i);
5339 if (PyType_Check(b))
5340 inherit_slots(type, (PyTypeObject *)b);
5341 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00005342
Serhiy Storchakae09bcc82015-01-28 11:03:33 +02005343 /* All bases of statically allocated type should be statically allocated */
5344 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE))
5345 for (i = 0; i < n; i++) {
5346 PyObject *b = PyTuple_GET_ITEM(bases, i);
5347 if (PyType_Check(b) &&
5348 (((PyTypeObject *)b)->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
5349 PyErr_Format(PyExc_TypeError,
5350 "type '%.100s' is not dynamically allocated but "
5351 "its base type '%.100s' is dynamically allocated",
5352 type->tp_name, ((PyTypeObject *)b)->tp_name);
5353 goto error;
5354 }
5355 }
5356
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005357 /* Sanity check for tp_free. */
5358 if (PyType_IS_GC(type) && (type->tp_flags & Py_TPFLAGS_BASETYPE) &&
5359 (type->tp_free == NULL || type->tp_free == PyObject_Del)) {
5360 /* This base class needs to call tp_free, but doesn't have
5361 * one, or its tp_free is for non-gc'ed objects.
5362 */
5363 PyErr_Format(PyExc_TypeError, "type '%.100s' participates in "
5364 "gc and is a base type but has inappropriate "
5365 "tp_free slot",
5366 type->tp_name);
5367 goto error;
5368 }
Tim Peters3cfe7542003-05-21 21:29:48 +00005369
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005370 /* if the type dictionary doesn't contain a __doc__, set it from
5371 the tp_doc slot.
5372 */
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02005373 if (_PyDict_GetItemIdWithError(type->tp_dict, &PyId___doc__) == NULL) {
5374 if (PyErr_Occurred()) {
5375 goto error;
5376 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005377 if (type->tp_doc != NULL) {
Larry Hastings2623c8c2014-02-08 22:15:29 -08005378 const char *old_doc = _PyType_DocWithoutSignature(type->tp_name,
5379 type->tp_doc);
Larry Hastings5c661892014-01-24 06:17:25 -08005380 PyObject *doc = PyUnicode_FromString(old_doc);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005381 if (doc == NULL)
5382 goto error;
Victor Stinner5967bf42013-07-17 22:01:37 +02005383 if (_PyDict_SetItemId(type->tp_dict, &PyId___doc__, doc) < 0) {
5384 Py_DECREF(doc);
5385 goto error;
5386 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005387 Py_DECREF(doc);
5388 } else {
Victor Stinner5967bf42013-07-17 22:01:37 +02005389 if (_PyDict_SetItemId(type->tp_dict,
5390 &PyId___doc__, Py_None) < 0)
5391 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005392 }
5393 }
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00005394
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005395 /* Hack for tp_hash and __hash__.
5396 If after all that, tp_hash is still NULL, and __hash__ is not in
5397 tp_dict, set tp_hash to PyObject_HashNotImplemented and
5398 tp_dict['__hash__'] equal to None.
5399 This signals that __hash__ is not inherited.
5400 */
5401 if (type->tp_hash == NULL) {
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02005402 if (_PyDict_GetItemIdWithError(type->tp_dict, &PyId___hash__) == NULL) {
5403 if (PyErr_Occurred() ||
5404 _PyDict_SetItemId(type->tp_dict, &PyId___hash__, Py_None) < 0)
5405 {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005406 goto error;
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02005407 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005408 type->tp_hash = PyObject_HashNotImplemented;
5409 }
5410 }
Guido van Rossum38938152006-08-21 23:36:26 +00005411
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005412 /* Some more special stuff */
5413 base = type->tp_base;
5414 if (base != NULL) {
Yury Selivanov75445082015-05-11 22:57:16 -04005415 if (type->tp_as_async == NULL)
5416 type->tp_as_async = base->tp_as_async;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005417 if (type->tp_as_number == NULL)
5418 type->tp_as_number = base->tp_as_number;
5419 if (type->tp_as_sequence == NULL)
5420 type->tp_as_sequence = base->tp_as_sequence;
5421 if (type->tp_as_mapping == NULL)
5422 type->tp_as_mapping = base->tp_as_mapping;
5423 if (type->tp_as_buffer == NULL)
5424 type->tp_as_buffer = base->tp_as_buffer;
5425 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00005426
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005427 /* Link into each base class's list of subclasses */
5428 bases = type->tp_bases;
5429 n = PyTuple_GET_SIZE(bases);
5430 for (i = 0; i < n; i++) {
5431 PyObject *b = PyTuple_GET_ITEM(bases, i);
5432 if (PyType_Check(b) &&
5433 add_subclass((PyTypeObject *)b, type) < 0)
5434 goto error;
5435 }
Guido van Rossum1c450732001-10-08 15:18:27 +00005436
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005437 /* All done -- set the ready flag */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005438 type->tp_flags =
5439 (type->tp_flags & ~Py_TPFLAGS_READYING) | Py_TPFLAGS_READY;
Victor Stinnerbda5a2b2017-01-25 23:33:27 +01005440 assert(_PyType_CheckConsistency(type));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005441 return 0;
Guido van Rossumd614f972001-08-10 17:39:49 +00005442
5443 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005444 type->tp_flags &= ~Py_TPFLAGS_READYING;
5445 return -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005446}
5447
Guido van Rossum1c450732001-10-08 15:18:27 +00005448static int
5449add_subclass(PyTypeObject *base, PyTypeObject *type)
5450{
Antoine Pitrou84745ab2013-10-29 21:31:25 +01005451 int result = -1;
5452 PyObject *dict, *key, *newobj;
Guido van Rossum1c450732001-10-08 15:18:27 +00005453
Antoine Pitrou84745ab2013-10-29 21:31:25 +01005454 dict = base->tp_subclasses;
5455 if (dict == NULL) {
5456 base->tp_subclasses = dict = PyDict_New();
5457 if (dict == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005458 return -1;
5459 }
Antoine Pitrou84745ab2013-10-29 21:31:25 +01005460 assert(PyDict_CheckExact(dict));
5461 key = PyLong_FromVoidPtr((void *) type);
5462 if (key == NULL)
Victor Stinner9812af82013-07-08 22:25:48 +02005463 return -1;
Antoine Pitrou84745ab2013-10-29 21:31:25 +01005464 newobj = PyWeakref_NewRef((PyObject *)type, NULL);
5465 if (newobj != NULL) {
5466 result = PyDict_SetItem(dict, key, newobj);
5467 Py_DECREF(newobj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005468 }
Antoine Pitrou84745ab2013-10-29 21:31:25 +01005469 Py_DECREF(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005470 return result;
Guido van Rossum1c450732001-10-08 15:18:27 +00005471}
5472
Benjamin Peterson104b9e02015-02-05 22:29:14 -05005473static int
5474add_all_subclasses(PyTypeObject *type, PyObject *bases)
5475{
5476 int res = 0;
5477
5478 if (bases) {
5479 Py_ssize_t i;
5480 for (i = 0; i < PyTuple_GET_SIZE(bases); i++) {
5481 PyObject *base = PyTuple_GET_ITEM(bases, i);
5482 if (PyType_Check(base) &&
5483 add_subclass((PyTypeObject*)base, type) < 0)
5484 res = -1;
5485 }
5486 }
5487
5488 return res;
5489}
5490
Michael W. Hudson98bbc492002-11-26 14:47:27 +00005491static void
5492remove_subclass(PyTypeObject *base, PyTypeObject *type)
5493{
Antoine Pitrou84745ab2013-10-29 21:31:25 +01005494 PyObject *dict, *key;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00005495
Antoine Pitrou84745ab2013-10-29 21:31:25 +01005496 dict = base->tp_subclasses;
5497 if (dict == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005498 return;
5499 }
Antoine Pitrou84745ab2013-10-29 21:31:25 +01005500 assert(PyDict_CheckExact(dict));
5501 key = PyLong_FromVoidPtr((void *) type);
5502 if (key == NULL || PyDict_DelItem(dict, key)) {
5503 /* This can happen if the type initialization errored out before
5504 the base subclasses were updated (e.g. a non-str __qualname__
5505 was passed in the type dict). */
5506 PyErr_Clear();
5507 }
5508 Py_XDECREF(key);
5509}
5510
5511static void
5512remove_all_subclasses(PyTypeObject *type, PyObject *bases)
5513{
5514 if (bases) {
5515 Py_ssize_t i;
5516 for (i = 0; i < PyTuple_GET_SIZE(bases); i++) {
5517 PyObject *base = PyTuple_GET_ITEM(bases, i);
5518 if (PyType_Check(base))
5519 remove_subclass((PyTypeObject*) base, type);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005520 }
5521 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +00005522}
Tim Peters6d6c1a32001-08-02 04:15:00 +00005523
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00005524static int
5525check_num_args(PyObject *ob, int n)
5526{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005527 if (!PyTuple_CheckExact(ob)) {
5528 PyErr_SetString(PyExc_SystemError,
5529 "PyArg_UnpackTuple() argument list is not a tuple");
5530 return 0;
5531 }
5532 if (n == PyTuple_GET_SIZE(ob))
5533 return 1;
5534 PyErr_Format(
5535 PyExc_TypeError,
Xtreak63262782018-12-21 20:15:13 +05305536 "expected %d argument%s, got %zd", n, n == 1 ? "" : "s", PyTuple_GET_SIZE(ob));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005537 return 0;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00005538}
5539
Tim Peters6d6c1a32001-08-02 04:15:00 +00005540/* Generic wrappers for overloadable 'operators' such as __getitem__ */
5541
5542/* There's a wrapper *function* for each distinct function typedef used
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005543 for type object slots (e.g. binaryfunc, ternaryfunc, etc.). There's a
Tim Peters6d6c1a32001-08-02 04:15:00 +00005544 wrapper *table* for each distinct operation (e.g. __len__, __add__).
5545 Most tables have only one entry; the tables for binary operators have two
5546 entries, one regular and one with reversed arguments. */
5547
5548static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00005549wrap_lenfunc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005550{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005551 lenfunc func = (lenfunc)wrapped;
5552 Py_ssize_t res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005553
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005554 if (!check_num_args(args, 0))
5555 return NULL;
5556 res = (*func)(self);
5557 if (res == -1 && PyErr_Occurred())
5558 return NULL;
5559 return PyLong_FromLong((long)res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005560}
5561
Tim Peters6d6c1a32001-08-02 04:15:00 +00005562static PyObject *
Raymond Hettingerf34f2642003-10-11 17:29:04 +00005563wrap_inquirypred(PyObject *self, PyObject *args, void *wrapped)
5564{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005565 inquiry func = (inquiry)wrapped;
5566 int res;
Raymond Hettingerf34f2642003-10-11 17:29:04 +00005567
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005568 if (!check_num_args(args, 0))
5569 return NULL;
5570 res = (*func)(self);
5571 if (res == -1 && PyErr_Occurred())
5572 return NULL;
5573 return PyBool_FromLong((long)res);
Raymond Hettingerf34f2642003-10-11 17:29:04 +00005574}
5575
5576static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00005577wrap_binaryfunc(PyObject *self, PyObject *args, void *wrapped)
5578{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005579 binaryfunc func = (binaryfunc)wrapped;
5580 PyObject *other;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005581
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005582 if (!check_num_args(args, 1))
5583 return NULL;
5584 other = PyTuple_GET_ITEM(args, 0);
5585 return (*func)(self, other);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005586}
5587
5588static PyObject *
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00005589wrap_binaryfunc_l(PyObject *self, PyObject *args, void *wrapped)
5590{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005591 binaryfunc func = (binaryfunc)wrapped;
5592 PyObject *other;
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00005593
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005594 if (!check_num_args(args, 1))
5595 return NULL;
5596 other = PyTuple_GET_ITEM(args, 0);
5597 return (*func)(self, other);
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00005598}
5599
5600static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00005601wrap_binaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
5602{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005603 binaryfunc func = (binaryfunc)wrapped;
5604 PyObject *other;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005605
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005606 if (!check_num_args(args, 1))
5607 return NULL;
5608 other = PyTuple_GET_ITEM(args, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005609 return (*func)(other, self);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005610}
5611
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00005612static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00005613wrap_ternaryfunc(PyObject *self, PyObject *args, void *wrapped)
5614{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005615 ternaryfunc func = (ternaryfunc)wrapped;
5616 PyObject *other;
5617 PyObject *third = Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005618
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005619 /* Note: This wrapper only works for __pow__() */
Tim Peters6d6c1a32001-08-02 04:15:00 +00005620
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005621 if (!PyArg_UnpackTuple(args, "", 1, 2, &other, &third))
5622 return NULL;
5623 return (*func)(self, other, third);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005624}
5625
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00005626static PyObject *
5627wrap_ternaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
5628{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005629 ternaryfunc func = (ternaryfunc)wrapped;
5630 PyObject *other;
5631 PyObject *third = Py_None;
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00005632
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005633 /* Note: This wrapper only works for __pow__() */
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00005634
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005635 if (!PyArg_UnpackTuple(args, "", 1, 2, &other, &third))
5636 return NULL;
5637 return (*func)(other, self, third);
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00005638}
5639
Tim Peters6d6c1a32001-08-02 04:15:00 +00005640static PyObject *
5641wrap_unaryfunc(PyObject *self, PyObject *args, void *wrapped)
5642{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005643 unaryfunc func = (unaryfunc)wrapped;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005644
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005645 if (!check_num_args(args, 0))
5646 return NULL;
5647 return (*func)(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005648}
5649
Tim Peters6d6c1a32001-08-02 04:15:00 +00005650static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00005651wrap_indexargfunc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005652{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005653 ssizeargfunc func = (ssizeargfunc)wrapped;
5654 PyObject* o;
5655 Py_ssize_t i;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005656
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005657 if (!PyArg_UnpackTuple(args, "", 1, 1, &o))
5658 return NULL;
5659 i = PyNumber_AsSsize_t(o, PyExc_OverflowError);
5660 if (i == -1 && PyErr_Occurred())
5661 return NULL;
5662 return (*func)(self, i);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005663}
5664
Martin v. Löwis18e16552006-02-15 17:27:45 +00005665static Py_ssize_t
Guido van Rossum5d815f32001-08-17 21:57:47 +00005666getindex(PyObject *self, PyObject *arg)
5667{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005668 Py_ssize_t i;
Guido van Rossum5d815f32001-08-17 21:57:47 +00005669
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005670 i = PyNumber_AsSsize_t(arg, PyExc_OverflowError);
5671 if (i == -1 && PyErr_Occurred())
5672 return -1;
5673 if (i < 0) {
5674 PySequenceMethods *sq = Py_TYPE(self)->tp_as_sequence;
5675 if (sq && sq->sq_length) {
5676 Py_ssize_t n = (*sq->sq_length)(self);
Serhiy Storchaka813f9432017-04-16 09:21:44 +03005677 if (n < 0) {
5678 assert(PyErr_Occurred());
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005679 return -1;
Serhiy Storchaka813f9432017-04-16 09:21:44 +03005680 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005681 i += n;
5682 }
5683 }
5684 return i;
Guido van Rossum5d815f32001-08-17 21:57:47 +00005685}
5686
5687static PyObject *
5688wrap_sq_item(PyObject *self, PyObject *args, void *wrapped)
5689{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005690 ssizeargfunc func = (ssizeargfunc)wrapped;
5691 PyObject *arg;
5692 Py_ssize_t i;
Guido van Rossum5d815f32001-08-17 21:57:47 +00005693
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005694 if (PyTuple_GET_SIZE(args) == 1) {
5695 arg = PyTuple_GET_ITEM(args, 0);
5696 i = getindex(self, arg);
5697 if (i == -1 && PyErr_Occurred())
5698 return NULL;
5699 return (*func)(self, i);
5700 }
5701 check_num_args(args, 1);
5702 assert(PyErr_Occurred());
5703 return NULL;
Guido van Rossum5d815f32001-08-17 21:57:47 +00005704}
5705
Tim Peters6d6c1a32001-08-02 04:15:00 +00005706static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00005707wrap_sq_setitem(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005708{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005709 ssizeobjargproc func = (ssizeobjargproc)wrapped;
5710 Py_ssize_t i;
5711 int res;
5712 PyObject *arg, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005713
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005714 if (!PyArg_UnpackTuple(args, "", 2, 2, &arg, &value))
5715 return NULL;
5716 i = getindex(self, arg);
5717 if (i == -1 && PyErr_Occurred())
5718 return NULL;
5719 res = (*func)(self, i, value);
5720 if (res == -1 && PyErr_Occurred())
5721 return NULL;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02005722 Py_RETURN_NONE;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005723}
5724
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00005725static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00005726wrap_sq_delitem(PyObject *self, PyObject *args, void *wrapped)
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00005727{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005728 ssizeobjargproc func = (ssizeobjargproc)wrapped;
5729 Py_ssize_t i;
5730 int res;
5731 PyObject *arg;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00005732
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005733 if (!check_num_args(args, 1))
5734 return NULL;
5735 arg = PyTuple_GET_ITEM(args, 0);
5736 i = getindex(self, arg);
5737 if (i == -1 && PyErr_Occurred())
5738 return NULL;
5739 res = (*func)(self, i, NULL);
5740 if (res == -1 && PyErr_Occurred())
5741 return NULL;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02005742 Py_RETURN_NONE;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00005743}
5744
Tim Peters6d6c1a32001-08-02 04:15:00 +00005745/* XXX objobjproc is a misnomer; should be objargpred */
5746static PyObject *
5747wrap_objobjproc(PyObject *self, PyObject *args, void *wrapped)
5748{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005749 objobjproc func = (objobjproc)wrapped;
5750 int res;
5751 PyObject *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005752
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005753 if (!check_num_args(args, 1))
5754 return NULL;
5755 value = PyTuple_GET_ITEM(args, 0);
5756 res = (*func)(self, value);
5757 if (res == -1 && PyErr_Occurred())
5758 return NULL;
5759 else
5760 return PyBool_FromLong(res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005761}
5762
Tim Peters6d6c1a32001-08-02 04:15:00 +00005763static PyObject *
5764wrap_objobjargproc(PyObject *self, PyObject *args, void *wrapped)
5765{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005766 objobjargproc func = (objobjargproc)wrapped;
5767 int res;
5768 PyObject *key, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005769
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005770 if (!PyArg_UnpackTuple(args, "", 2, 2, &key, &value))
5771 return NULL;
5772 res = (*func)(self, key, value);
5773 if (res == -1 && PyErr_Occurred())
5774 return NULL;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02005775 Py_RETURN_NONE;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005776}
5777
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00005778static PyObject *
5779wrap_delitem(PyObject *self, PyObject *args, void *wrapped)
5780{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005781 objobjargproc func = (objobjargproc)wrapped;
5782 int res;
5783 PyObject *key;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00005784
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005785 if (!check_num_args(args, 1))
5786 return NULL;
5787 key = PyTuple_GET_ITEM(args, 0);
5788 res = (*func)(self, key, NULL);
5789 if (res == -1 && PyErr_Occurred())
5790 return NULL;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02005791 Py_RETURN_NONE;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00005792}
5793
Guido van Rossum4dcdb782003-04-14 21:46:03 +00005794/* Helper to check for object.__setattr__ or __delattr__ applied to a type.
Guido van Rossum52b27052003-04-15 20:05:10 +00005795 This is called the Carlo Verre hack after its discoverer. */
Guido van Rossum4dcdb782003-04-14 21:46:03 +00005796static int
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02005797hackcheck(PyObject *self, setattrofunc func, const char *what)
Guido van Rossum4dcdb782003-04-14 21:46:03 +00005798{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005799 PyTypeObject *type = Py_TYPE(self);
5800 while (type && type->tp_flags & Py_TPFLAGS_HEAPTYPE)
5801 type = type->tp_base;
5802 /* If type is NULL now, this is a really weird type.
5803 In the spirit of backwards compatibility (?), just shut up. */
5804 if (type && type->tp_setattro != func) {
5805 PyErr_Format(PyExc_TypeError,
5806 "can't apply this %s to %s object",
5807 what,
5808 type->tp_name);
5809 return 0;
5810 }
5811 return 1;
Guido van Rossum4dcdb782003-04-14 21:46:03 +00005812}
5813
Tim Peters6d6c1a32001-08-02 04:15:00 +00005814static PyObject *
5815wrap_setattr(PyObject *self, PyObject *args, void *wrapped)
5816{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005817 setattrofunc func = (setattrofunc)wrapped;
5818 int res;
5819 PyObject *name, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005820
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005821 if (!PyArg_UnpackTuple(args, "", 2, 2, &name, &value))
5822 return NULL;
5823 if (!hackcheck(self, func, "__setattr__"))
5824 return NULL;
5825 res = (*func)(self, name, value);
5826 if (res < 0)
5827 return NULL;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02005828 Py_RETURN_NONE;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005829}
5830
5831static PyObject *
5832wrap_delattr(PyObject *self, PyObject *args, void *wrapped)
5833{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005834 setattrofunc func = (setattrofunc)wrapped;
5835 int res;
5836 PyObject *name;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005837
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005838 if (!check_num_args(args, 1))
5839 return NULL;
5840 name = PyTuple_GET_ITEM(args, 0);
5841 if (!hackcheck(self, func, "__delattr__"))
5842 return NULL;
5843 res = (*func)(self, name, NULL);
5844 if (res < 0)
5845 return NULL;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02005846 Py_RETURN_NONE;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005847}
5848
Tim Peters6d6c1a32001-08-02 04:15:00 +00005849static PyObject *
5850wrap_hashfunc(PyObject *self, PyObject *args, void *wrapped)
5851{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005852 hashfunc func = (hashfunc)wrapped;
Benjamin Peterson8035bc52010-10-23 16:20:50 +00005853 Py_hash_t res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005854
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005855 if (!check_num_args(args, 0))
5856 return NULL;
5857 res = (*func)(self);
5858 if (res == -1 && PyErr_Occurred())
5859 return NULL;
Benjamin Peterson8035bc52010-10-23 16:20:50 +00005860 return PyLong_FromSsize_t(res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005861}
5862
Tim Peters6d6c1a32001-08-02 04:15:00 +00005863static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00005864wrap_call(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005865{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005866 ternaryfunc func = (ternaryfunc)wrapped;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005867
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005868 return (*func)(self, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005869}
5870
Tim Peters6d6c1a32001-08-02 04:15:00 +00005871static PyObject *
Antoine Pitrou796564c2013-07-30 19:59:21 +02005872wrap_del(PyObject *self, PyObject *args, void *wrapped)
5873{
5874 destructor func = (destructor)wrapped;
5875
5876 if (!check_num_args(args, 0))
5877 return NULL;
5878
5879 (*func)(self);
5880 Py_RETURN_NONE;
5881}
5882
5883static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00005884wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op)
5885{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005886 richcmpfunc func = (richcmpfunc)wrapped;
5887 PyObject *other;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005888
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005889 if (!check_num_args(args, 1))
5890 return NULL;
5891 other = PyTuple_GET_ITEM(args, 0);
5892 return (*func)(self, other, op);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005893}
5894
5895#undef RICHCMP_WRAPPER
5896#define RICHCMP_WRAPPER(NAME, OP) \
5897static PyObject * \
5898richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \
5899{ \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005900 return wrap_richcmpfunc(self, args, wrapped, OP); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00005901}
5902
Jack Jansen8e938b42001-08-08 15:29:49 +00005903RICHCMP_WRAPPER(lt, Py_LT)
5904RICHCMP_WRAPPER(le, Py_LE)
5905RICHCMP_WRAPPER(eq, Py_EQ)
5906RICHCMP_WRAPPER(ne, Py_NE)
5907RICHCMP_WRAPPER(gt, Py_GT)
5908RICHCMP_WRAPPER(ge, Py_GE)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005909
Tim Peters6d6c1a32001-08-02 04:15:00 +00005910static PyObject *
5911wrap_next(PyObject *self, PyObject *args, void *wrapped)
5912{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005913 unaryfunc func = (unaryfunc)wrapped;
5914 PyObject *res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005915
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005916 if (!check_num_args(args, 0))
5917 return NULL;
5918 res = (*func)(self);
5919 if (res == NULL && !PyErr_Occurred())
5920 PyErr_SetNone(PyExc_StopIteration);
5921 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005922}
5923
Tim Peters6d6c1a32001-08-02 04:15:00 +00005924static PyObject *
5925wrap_descr_get(PyObject *self, PyObject *args, void *wrapped)
5926{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005927 descrgetfunc func = (descrgetfunc)wrapped;
5928 PyObject *obj;
5929 PyObject *type = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005930
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005931 if (!PyArg_UnpackTuple(args, "", 1, 2, &obj, &type))
5932 return NULL;
5933 if (obj == Py_None)
5934 obj = NULL;
5935 if (type == Py_None)
5936 type = NULL;
5937 if (type == NULL &&obj == NULL) {
5938 PyErr_SetString(PyExc_TypeError,
5939 "__get__(None, None) is invalid");
5940 return NULL;
5941 }
5942 return (*func)(self, obj, type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005943}
5944
Tim Peters6d6c1a32001-08-02 04:15:00 +00005945static PyObject *
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005946wrap_descr_set(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005947{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005948 descrsetfunc func = (descrsetfunc)wrapped;
5949 PyObject *obj, *value;
5950 int ret;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005951
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005952 if (!PyArg_UnpackTuple(args, "", 2, 2, &obj, &value))
5953 return NULL;
5954 ret = (*func)(self, obj, value);
5955 if (ret < 0)
5956 return NULL;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02005957 Py_RETURN_NONE;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005958}
Guido van Rossum22b13872002-08-06 21:41:44 +00005959
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00005960static PyObject *
5961wrap_descr_delete(PyObject *self, PyObject *args, void *wrapped)
5962{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005963 descrsetfunc func = (descrsetfunc)wrapped;
5964 PyObject *obj;
5965 int ret;
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00005966
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005967 if (!check_num_args(args, 1))
5968 return NULL;
5969 obj = PyTuple_GET_ITEM(args, 0);
5970 ret = (*func)(self, obj, NULL);
5971 if (ret < 0)
5972 return NULL;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02005973 Py_RETURN_NONE;
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00005974}
Tim Peters6d6c1a32001-08-02 04:15:00 +00005975
Tim Peters6d6c1a32001-08-02 04:15:00 +00005976static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00005977wrap_init(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005978{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005979 initproc func = (initproc)wrapped;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005980
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005981 if (func(self, args, kwds) < 0)
5982 return NULL;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02005983 Py_RETURN_NONE;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005984}
5985
Tim Peters6d6c1a32001-08-02 04:15:00 +00005986static PyObject *
Guido van Rossum0d231ed2001-08-06 16:50:37 +00005987tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005988{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005989 PyTypeObject *type, *subtype, *staticbase;
5990 PyObject *arg0, *res;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00005991
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005992 if (self == NULL || !PyType_Check(self))
5993 Py_FatalError("__new__() called with non-type 'self'");
5994 type = (PyTypeObject *)self;
5995 if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) {
5996 PyErr_Format(PyExc_TypeError,
5997 "%s.__new__(): not enough arguments",
5998 type->tp_name);
5999 return NULL;
6000 }
6001 arg0 = PyTuple_GET_ITEM(args, 0);
6002 if (!PyType_Check(arg0)) {
6003 PyErr_Format(PyExc_TypeError,
6004 "%s.__new__(X): X is not a type object (%s)",
6005 type->tp_name,
6006 Py_TYPE(arg0)->tp_name);
6007 return NULL;
6008 }
6009 subtype = (PyTypeObject *)arg0;
6010 if (!PyType_IsSubtype(subtype, type)) {
6011 PyErr_Format(PyExc_TypeError,
6012 "%s.__new__(%s): %s is not a subtype of %s",
6013 type->tp_name,
6014 subtype->tp_name,
6015 subtype->tp_name,
6016 type->tp_name);
6017 return NULL;
6018 }
Barry Warsaw60f01882001-08-22 19:24:42 +00006019
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006020 /* Check that the use doesn't do something silly and unsafe like
6021 object.__new__(dict). To do this, we check that the
6022 most derived base that's not a heap type is this type. */
6023 staticbase = subtype;
Martin v. Löwis9c564092012-06-23 23:20:45 +02006024 while (staticbase && (staticbase->tp_new == slot_tp_new))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006025 staticbase = staticbase->tp_base;
6026 /* If staticbase is NULL now, it is a really weird type.
6027 In the spirit of backwards compatibility (?), just shut up. */
6028 if (staticbase && staticbase->tp_new != type->tp_new) {
6029 PyErr_Format(PyExc_TypeError,
6030 "%s.__new__(%s) is not safe, use %s.__new__()",
6031 type->tp_name,
6032 subtype->tp_name,
Benjamin Petersone8239332014-11-26 23:03:11 -06006033 staticbase->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006034 return NULL;
6035 }
Barry Warsaw60f01882001-08-22 19:24:42 +00006036
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006037 args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
6038 if (args == NULL)
6039 return NULL;
6040 res = type->tp_new(subtype, args, kwds);
6041 Py_DECREF(args);
6042 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00006043}
6044
Guido van Rossum0d231ed2001-08-06 16:50:37 +00006045static struct PyMethodDef tp_new_methoddef[] = {
Serhiy Storchaka62be7422018-11-27 13:27:31 +02006046 {"__new__", (PyCFunction)(void(*)(void))tp_new_wrapper, METH_VARARGS|METH_KEYWORDS,
Larry Hastings2623c8c2014-02-08 22:15:29 -08006047 PyDoc_STR("__new__($type, *args, **kwargs)\n--\n\n"
Larry Hastings581ee362014-01-28 05:00:08 -08006048 "Create and return a new object. "
6049 "See help(type) for accurate signature.")},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006050 {0}
Tim Peters6d6c1a32001-08-02 04:15:00 +00006051};
6052
6053static int
Guido van Rossum0d231ed2001-08-06 16:50:37 +00006054add_tp_new_wrapper(PyTypeObject *type)
6055{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006056 PyObject *func;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00006057
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02006058 if (_PyDict_GetItemIdWithError(type->tp_dict, &PyId___new__) != NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006059 return 0;
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02006060 if (PyErr_Occurred())
6061 return -1;
Andrew Svetlov3ba3a3e2012-12-25 13:32:35 +02006062 func = PyCFunction_NewEx(tp_new_methoddef, (PyObject *)type, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006063 if (func == NULL)
6064 return -1;
Victor Stinner3c1e4812012-03-26 22:10:51 +02006065 if (_PyDict_SetItemId(type->tp_dict, &PyId___new__, func)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006066 Py_DECREF(func);
6067 return -1;
6068 }
6069 Py_DECREF(func);
6070 return 0;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00006071}
6072
Guido van Rossumf040ede2001-08-07 16:40:56 +00006073/* Slot wrappers that call the corresponding __foo__ slot. See comments
6074 below at override_slots() for more explanation. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00006075
Guido van Rossumdc91b992001-08-08 22:26:22 +00006076#define SLOT0(FUNCNAME, OPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00006077static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00006078FUNCNAME(PyObject *self) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00006079{ \
Benjamin Petersonce798522012-01-22 11:24:29 -05006080 _Py_static_string(id, OPSTR); \
Victor Stinner434723f2017-01-11 00:07:40 +01006081 return call_method(self, &id, NULL, 0); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00006082}
6083
Victor Stinner887b4302016-12-09 00:41:46 +01006084#define SLOT1(FUNCNAME, OPSTR, ARG1TYPE) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00006085static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00006086FUNCNAME(PyObject *self, ARG1TYPE arg1) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00006087{ \
Victor Stinner434723f2017-01-11 00:07:40 +01006088 PyObject* stack[1] = {arg1}; \
Benjamin Petersonce798522012-01-22 11:24:29 -05006089 _Py_static_string(id, OPSTR); \
Victor Stinner434723f2017-01-11 00:07:40 +01006090 return call_method(self, &id, stack, 1); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00006091}
6092
Guido van Rossumcd118802003-01-06 22:57:47 +00006093/* Boolean helper for SLOT1BINFULL().
6094 right.__class__ is a nontrivial subclass of left.__class__. */
6095static int
Victor Stinner3c1e4812012-03-26 22:10:51 +02006096method_is_overloaded(PyObject *left, PyObject *right, struct _Py_Identifier *name)
Guido van Rossumcd118802003-01-06 22:57:47 +00006097{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006098 PyObject *a, *b;
6099 int ok;
Guido van Rossumcd118802003-01-06 22:57:47 +00006100
Victor Stinner3c1e4812012-03-26 22:10:51 +02006101 b = _PyObject_GetAttrId((PyObject *)(Py_TYPE(right)), name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006102 if (b == NULL) {
6103 PyErr_Clear();
6104 /* If right doesn't have it, it's not overloaded */
6105 return 0;
6106 }
Guido van Rossumcd118802003-01-06 22:57:47 +00006107
Victor Stinner3c1e4812012-03-26 22:10:51 +02006108 a = _PyObject_GetAttrId((PyObject *)(Py_TYPE(left)), name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006109 if (a == NULL) {
6110 PyErr_Clear();
6111 Py_DECREF(b);
6112 /* If right has it but left doesn't, it's overloaded */
6113 return 1;
6114 }
Guido van Rossumcd118802003-01-06 22:57:47 +00006115
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006116 ok = PyObject_RichCompareBool(a, b, Py_NE);
6117 Py_DECREF(a);
6118 Py_DECREF(b);
6119 if (ok < 0) {
6120 PyErr_Clear();
6121 return 0;
6122 }
Guido van Rossumcd118802003-01-06 22:57:47 +00006123
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006124 return ok;
Guido van Rossumcd118802003-01-06 22:57:47 +00006125}
6126
Guido van Rossumdc91b992001-08-08 22:26:22 +00006127
6128#define SLOT1BINFULL(FUNCNAME, TESTFUNC, SLOTNAME, OPSTR, ROPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00006129static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00006130FUNCNAME(PyObject *self, PyObject *other) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00006131{ \
Victor Stinner434723f2017-01-11 00:07:40 +01006132 PyObject* stack[1]; \
Benjamin Petersonce798522012-01-22 11:24:29 -05006133 _Py_static_string(op_id, OPSTR); \
6134 _Py_static_string(rop_id, ROPSTR); \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006135 int do_other = Py_TYPE(self) != Py_TYPE(other) && \
6136 Py_TYPE(other)->tp_as_number != NULL && \
6137 Py_TYPE(other)->tp_as_number->SLOTNAME == TESTFUNC; \
6138 if (Py_TYPE(self)->tp_as_number != NULL && \
6139 Py_TYPE(self)->tp_as_number->SLOTNAME == TESTFUNC) { \
6140 PyObject *r; \
6141 if (do_other && \
6142 PyType_IsSubtype(Py_TYPE(other), Py_TYPE(self)) && \
Victor Stinner3c1e4812012-03-26 22:10:51 +02006143 method_is_overloaded(self, other, &rop_id)) { \
Victor Stinner434723f2017-01-11 00:07:40 +01006144 stack[0] = self; \
6145 r = call_maybe(other, &rop_id, stack, 1); \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006146 if (r != Py_NotImplemented) \
6147 return r; \
6148 Py_DECREF(r); \
6149 do_other = 0; \
6150 } \
Victor Stinner434723f2017-01-11 00:07:40 +01006151 stack[0] = other; \
6152 r = call_maybe(self, &op_id, stack, 1); \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006153 if (r != Py_NotImplemented || \
6154 Py_TYPE(other) == Py_TYPE(self)) \
6155 return r; \
6156 Py_DECREF(r); \
6157 } \
6158 if (do_other) { \
Victor Stinner434723f2017-01-11 00:07:40 +01006159 stack[0] = self; \
6160 return call_maybe(other, &rop_id, stack, 1); \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006161 } \
Brian Curtindfc80e32011-08-10 20:28:54 -05006162 Py_RETURN_NOTIMPLEMENTED; \
Guido van Rossumdc91b992001-08-08 22:26:22 +00006163}
6164
6165#define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006166 SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR)
Guido van Rossumdc91b992001-08-08 22:26:22 +00006167
Martin v. Löwis18e16552006-02-15 17:27:45 +00006168static Py_ssize_t
Tim Peters6d6c1a32001-08-02 04:15:00 +00006169slot_sq_length(PyObject *self)
6170{
Victor Stinner434723f2017-01-11 00:07:40 +01006171 PyObject *res = call_method(self, &PyId___len__, NULL, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006172 Py_ssize_t len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00006173
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006174 if (res == NULL)
6175 return -1;
Serhiy Storchakabaf9f292017-04-16 09:37:18 +03006176
6177 Py_SETREF(res, PyNumber_Index(res));
6178 if (res == NULL)
6179 return -1;
6180
6181 assert(PyLong_Check(res));
6182 if (Py_SIZE(res) < 0) {
Xiang Zhang8e1ddbd2017-04-17 00:54:21 +08006183 Py_DECREF(res);
Serhiy Storchakabaf9f292017-04-16 09:37:18 +03006184 PyErr_SetString(PyExc_ValueError,
6185 "__len__() should return >= 0");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006186 return -1;
6187 }
Serhiy Storchakabaf9f292017-04-16 09:37:18 +03006188
6189 len = PyNumber_AsSsize_t(res, PyExc_OverflowError);
6190 assert(len >= 0 || PyErr_ExceptionMatches(PyExc_OverflowError));
6191 Py_DECREF(res);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006192 return len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00006193}
6194
Guido van Rossumf4593e02001-10-03 12:09:30 +00006195static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00006196slot_sq_item(PyObject *self, Py_ssize_t i)
Guido van Rossumf4593e02001-10-03 12:09:30 +00006197{
Serhiy Storchaka4e624ca2017-06-01 08:18:25 +03006198 PyObject *retval;
6199 PyObject *args[1];
6200 PyObject *ival = PyLong_FromSsize_t(i);
6201 if (ival == NULL) {
Victor Stinner018016d2016-08-19 18:17:37 +02006202 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006203 }
Serhiy Storchaka4e624ca2017-06-01 08:18:25 +03006204 args[0] = ival;
6205 retval = call_method(self, &PyId___getitem__, args, 1);
Victor Stinner5e877492016-08-19 18:19:42 +02006206 Py_DECREF(ival);
Victor Stinner018016d2016-08-19 18:17:37 +02006207 return retval;
Guido van Rossumf4593e02001-10-03 12:09:30 +00006208}
6209
Tim Peters6d6c1a32001-08-02 04:15:00 +00006210static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00006211slot_sq_ass_item(PyObject *self, Py_ssize_t index, PyObject *value)
Tim Peters6d6c1a32001-08-02 04:15:00 +00006212{
Victor Stinner434723f2017-01-11 00:07:40 +01006213 PyObject *stack[2];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006214 PyObject *res;
Victor Stinner887b4302016-12-09 00:41:46 +01006215 PyObject *index_obj;
6216
6217 index_obj = PyLong_FromSsize_t(index);
6218 if (index_obj == NULL) {
6219 return -1;
6220 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00006221
Victor Stinner434723f2017-01-11 00:07:40 +01006222 stack[0] = index_obj;
6223 if (value == NULL) {
6224 res = call_method(self, &PyId___delitem__, stack, 1);
6225 }
6226 else {
6227 stack[1] = value;
6228 res = call_method(self, &PyId___setitem__, stack, 2);
6229 }
Victor Stinner887b4302016-12-09 00:41:46 +01006230 Py_DECREF(index_obj);
6231
6232 if (res == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006233 return -1;
Victor Stinner887b4302016-12-09 00:41:46 +01006234 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006235 Py_DECREF(res);
6236 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00006237}
6238
6239static int
Tim Peters6d6c1a32001-08-02 04:15:00 +00006240slot_sq_contains(PyObject *self, PyObject *value)
6241{
Victor Stinnera7720f62016-08-19 17:48:51 +02006242 PyObject *func, *res;
Victor Stinner516b9812017-02-09 22:53:47 +01006243 int result = -1, unbound;
Benjamin Petersonce798522012-01-22 11:24:29 -05006244 _Py_IDENTIFIER(__contains__);
Tim Petersbf9b2442003-03-23 05:35:36 +00006245
Victor Stinner516b9812017-02-09 22:53:47 +01006246 func = lookup_maybe_method(self, &PyId___contains__, &unbound);
Guido van Rossum97c1adf2016-08-18 09:22:23 -07006247 if (func == Py_None) {
6248 Py_DECREF(func);
6249 PyErr_Format(PyExc_TypeError,
6250 "'%.200s' object is not a container",
6251 Py_TYPE(self)->tp_name);
6252 return -1;
6253 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006254 if (func != NULL) {
Victor Stinner516b9812017-02-09 22:53:47 +01006255 PyObject *args[1] = {value};
6256 res = call_unbound(unbound, func, self, args, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006257 Py_DECREF(func);
6258 if (res != NULL) {
6259 result = PyObject_IsTrue(res);
6260 Py_DECREF(res);
6261 }
6262 }
6263 else if (! PyErr_Occurred()) {
6264 /* Possible results: -1 and 1 */
6265 result = (int)_PySequence_IterSearch(self, value,
6266 PY_ITERSEARCH_CONTAINS);
6267 }
6268 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00006269}
6270
Tim Peters6d6c1a32001-08-02 04:15:00 +00006271#define slot_mp_length slot_sq_length
6272
Victor Stinner887b4302016-12-09 00:41:46 +01006273SLOT1(slot_mp_subscript, "__getitem__", PyObject *)
Tim Peters6d6c1a32001-08-02 04:15:00 +00006274
6275static int
6276slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value)
6277{
Victor Stinner434723f2017-01-11 00:07:40 +01006278 PyObject *stack[2];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006279 PyObject *res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00006280
Victor Stinner434723f2017-01-11 00:07:40 +01006281 stack[0] = key;
6282 if (value == NULL) {
6283 res = call_method(self, &PyId___delitem__, stack, 1);
6284 }
6285 else {
6286 stack[1] = value;
6287 res = call_method(self, &PyId___setitem__, stack, 2);
6288 }
Benjamin Petersonce798522012-01-22 11:24:29 -05006289
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006290 if (res == NULL)
6291 return -1;
6292 Py_DECREF(res);
6293 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00006294}
6295
Guido van Rossumdc91b992001-08-08 22:26:22 +00006296SLOT1BIN(slot_nb_add, nb_add, "__add__", "__radd__")
6297SLOT1BIN(slot_nb_subtract, nb_subtract, "__sub__", "__rsub__")
6298SLOT1BIN(slot_nb_multiply, nb_multiply, "__mul__", "__rmul__")
Benjamin Petersond51374e2014-04-09 23:55:56 -04006299SLOT1BIN(slot_nb_matrix_multiply, nb_matrix_multiply, "__matmul__", "__rmatmul__")
Guido van Rossumdc91b992001-08-08 22:26:22 +00006300SLOT1BIN(slot_nb_remainder, nb_remainder, "__mod__", "__rmod__")
6301SLOT1BIN(slot_nb_divmod, nb_divmod, "__divmod__", "__rdivmod__")
6302
Jeremy Hylton938ace62002-07-17 16:30:39 +00006303static PyObject *slot_nb_power(PyObject *, PyObject *, PyObject *);
Guido van Rossumdc91b992001-08-08 22:26:22 +00006304
6305SLOT1BINFULL(slot_nb_power_binary, slot_nb_power,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006306 nb_power, "__pow__", "__rpow__")
Guido van Rossumdc91b992001-08-08 22:26:22 +00006307
6308static PyObject *
6309slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus)
6310{
Benjamin Petersonce798522012-01-22 11:24:29 -05006311 _Py_IDENTIFIER(__pow__);
Guido van Rossum2730b132001-08-28 18:22:14 +00006312
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006313 if (modulus == Py_None)
6314 return slot_nb_power_binary(self, other);
6315 /* Three-arg power doesn't use __rpow__. But ternary_op
6316 can call this when the second argument's type uses
6317 slot_nb_power, so check before calling self.__pow__. */
6318 if (Py_TYPE(self)->tp_as_number != NULL &&
6319 Py_TYPE(self)->tp_as_number->nb_power == slot_nb_power) {
Victor Stinner434723f2017-01-11 00:07:40 +01006320 PyObject* stack[2] = {other, modulus};
6321 return call_method(self, &PyId___pow__, stack, 2);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006322 }
Brian Curtindfc80e32011-08-10 20:28:54 -05006323 Py_RETURN_NOTIMPLEMENTED;
Guido van Rossumdc91b992001-08-08 22:26:22 +00006324}
6325
6326SLOT0(slot_nb_negative, "__neg__")
6327SLOT0(slot_nb_positive, "__pos__")
6328SLOT0(slot_nb_absolute, "__abs__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00006329
6330static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00006331slot_nb_bool(PyObject *self)
Tim Peters6d6c1a32001-08-02 04:15:00 +00006332{
Victor Stinner20a30072016-08-19 18:28:25 +02006333 PyObject *func, *value;
Victor Stinner516b9812017-02-09 22:53:47 +01006334 int result, unbound;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006335 int using_len = 0;
Benjamin Petersonce798522012-01-22 11:24:29 -05006336 _Py_IDENTIFIER(__bool__);
Tim Peters6d6c1a32001-08-02 04:15:00 +00006337
Victor Stinner516b9812017-02-09 22:53:47 +01006338 func = lookup_maybe_method(self, &PyId___bool__, &unbound);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006339 if (func == NULL) {
Victor Stinnera12eec42016-08-19 18:26:05 +02006340 if (PyErr_Occurred()) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006341 return -1;
Victor Stinnera12eec42016-08-19 18:26:05 +02006342 }
6343
Victor Stinner516b9812017-02-09 22:53:47 +01006344 func = lookup_maybe_method(self, &PyId___len__, &unbound);
Victor Stinnera12eec42016-08-19 18:26:05 +02006345 if (func == NULL) {
6346 if (PyErr_Occurred()) {
6347 return -1;
6348 }
6349 return 1;
6350 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006351 using_len = 1;
6352 }
Victor Stinnera12eec42016-08-19 18:26:05 +02006353
Victor Stinner516b9812017-02-09 22:53:47 +01006354 value = call_unbound_noarg(unbound, func, self);
Victor Stinnera12eec42016-08-19 18:26:05 +02006355 if (value == NULL) {
6356 goto error;
6357 }
6358
6359 if (using_len) {
6360 /* bool type enforced by slot_nb_len */
6361 result = PyObject_IsTrue(value);
6362 }
6363 else if (PyBool_Check(value)) {
6364 result = PyObject_IsTrue(value);
6365 }
6366 else {
6367 PyErr_Format(PyExc_TypeError,
6368 "__bool__ should return "
6369 "bool, returned %s",
6370 Py_TYPE(value)->tp_name);
6371 result = -1;
6372 }
6373
6374 Py_DECREF(value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006375 Py_DECREF(func);
6376 return result;
Victor Stinnera12eec42016-08-19 18:26:05 +02006377
6378error:
6379 Py_DECREF(func);
6380 return -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00006381}
6382
Guido van Rossum38fff8c2006-03-07 18:50:55 +00006383
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00006384static PyObject *
Guido van Rossum38fff8c2006-03-07 18:50:55 +00006385slot_nb_index(PyObject *self)
6386{
Benjamin Petersonce798522012-01-22 11:24:29 -05006387 _Py_IDENTIFIER(__index__);
Victor Stinner434723f2017-01-11 00:07:40 +01006388 return call_method(self, &PyId___index__, NULL, 0);
Guido van Rossum38fff8c2006-03-07 18:50:55 +00006389}
6390
6391
Guido van Rossumdc91b992001-08-08 22:26:22 +00006392SLOT0(slot_nb_invert, "__invert__")
6393SLOT1BIN(slot_nb_lshift, nb_lshift, "__lshift__", "__rlshift__")
6394SLOT1BIN(slot_nb_rshift, nb_rshift, "__rshift__", "__rrshift__")
6395SLOT1BIN(slot_nb_and, nb_and, "__and__", "__rand__")
6396SLOT1BIN(slot_nb_xor, nb_xor, "__xor__", "__rxor__")
6397SLOT1BIN(slot_nb_or, nb_or, "__or__", "__ror__")
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00006398
Guido van Rossumdc91b992001-08-08 22:26:22 +00006399SLOT0(slot_nb_int, "__int__")
Guido van Rossumdc91b992001-08-08 22:26:22 +00006400SLOT0(slot_nb_float, "__float__")
Victor Stinner887b4302016-12-09 00:41:46 +01006401SLOT1(slot_nb_inplace_add, "__iadd__", PyObject *)
6402SLOT1(slot_nb_inplace_subtract, "__isub__", PyObject *)
6403SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *)
6404SLOT1(slot_nb_inplace_matrix_multiply, "__imatmul__", PyObject *)
6405SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *)
Thomas Wouterscf297e42007-02-23 15:07:44 +00006406/* Can't use SLOT1 here, because nb_inplace_power is ternary */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006407static PyObject *
6408slot_nb_inplace_power(PyObject *self, PyObject * arg1, PyObject *arg2)
6409{
Victor Stinner434723f2017-01-11 00:07:40 +01006410 PyObject *stack[1] = {arg1};
Benjamin Petersonce798522012-01-22 11:24:29 -05006411 _Py_IDENTIFIER(__ipow__);
Victor Stinner434723f2017-01-11 00:07:40 +01006412 return call_method(self, &PyId___ipow__, stack, 1);
Thomas Wouterscf297e42007-02-23 15:07:44 +00006413}
Victor Stinner887b4302016-12-09 00:41:46 +01006414SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *)
6415SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *)
6416SLOT1(slot_nb_inplace_and, "__iand__", PyObject *)
6417SLOT1(slot_nb_inplace_xor, "__ixor__", PyObject *)
6418SLOT1(slot_nb_inplace_or, "__ior__", PyObject *)
Guido van Rossumdc91b992001-08-08 22:26:22 +00006419SLOT1BIN(slot_nb_floor_divide, nb_floor_divide,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006420 "__floordiv__", "__rfloordiv__")
Guido van Rossumdc91b992001-08-08 22:26:22 +00006421SLOT1BIN(slot_nb_true_divide, nb_true_divide, "__truediv__", "__rtruediv__")
Victor Stinner887b4302016-12-09 00:41:46 +01006422SLOT1(slot_nb_inplace_floor_divide, "__ifloordiv__", PyObject *)
6423SLOT1(slot_nb_inplace_true_divide, "__itruediv__", PyObject *)
Tim Peters6d6c1a32001-08-02 04:15:00 +00006424
Guido van Rossumb8f63662001-08-15 23:57:02 +00006425static PyObject *
6426slot_tp_repr(PyObject *self)
6427{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006428 PyObject *func, *res;
Benjamin Petersonce798522012-01-22 11:24:29 -05006429 _Py_IDENTIFIER(__repr__);
Victor Stinner516b9812017-02-09 22:53:47 +01006430 int unbound;
Guido van Rossumb8f63662001-08-15 23:57:02 +00006431
Serhiy Storchaka4e624ca2017-06-01 08:18:25 +03006432 func = lookup_maybe_method(self, &PyId___repr__, &unbound);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006433 if (func != NULL) {
Victor Stinner516b9812017-02-09 22:53:47 +01006434 res = call_unbound_noarg(unbound, func, self);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006435 Py_DECREF(func);
6436 return res;
6437 }
6438 PyErr_Clear();
6439 return PyUnicode_FromFormat("<%s object at %p>",
6440 Py_TYPE(self)->tp_name, self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00006441}
6442
Victor Stinner516b9812017-02-09 22:53:47 +01006443SLOT0(slot_tp_str, "__str__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00006444
Benjamin Peterson8f67d082010-10-17 20:54:53 +00006445static Py_hash_t
Tim Peters6d6c1a32001-08-02 04:15:00 +00006446slot_tp_hash(PyObject *self)
6447{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006448 PyObject *func, *res;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00006449 Py_ssize_t h;
Victor Stinner516b9812017-02-09 22:53:47 +01006450 int unbound;
Tim Peters6d6c1a32001-08-02 04:15:00 +00006451
Serhiy Storchaka4e624ca2017-06-01 08:18:25 +03006452 func = lookup_maybe_method(self, &PyId___hash__, &unbound);
Guido van Rossumb8f63662001-08-15 23:57:02 +00006453
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006454 if (func == Py_None) {
6455 Py_DECREF(func);
6456 func = NULL;
6457 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +00006458
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006459 if (func == NULL) {
6460 return PyObject_HashNotImplemented(self);
6461 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +00006462
Victor Stinner516b9812017-02-09 22:53:47 +01006463 res = call_unbound_noarg(unbound, func, self);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006464 Py_DECREF(func);
6465 if (res == NULL)
6466 return -1;
Mark Dickinsondc787d22010-05-23 13:33:13 +00006467
6468 if (!PyLong_Check(res)) {
6469 PyErr_SetString(PyExc_TypeError,
6470 "__hash__ method should return an integer");
6471 return -1;
6472 }
Benjamin Peterson8f67d082010-10-17 20:54:53 +00006473 /* Transform the PyLong `res` to a Py_hash_t `h`. For an existing
6474 hashable Python object x, hash(x) will always lie within the range of
6475 Py_hash_t. Therefore our transformation must preserve values that
6476 already lie within this range, to ensure that if x.__hash__() returns
6477 hash(y) then hash(x) == hash(y). */
6478 h = PyLong_AsSsize_t(res);
6479 if (h == -1 && PyErr_Occurred()) {
6480 /* res was not within the range of a Py_hash_t, so we're free to
Mark Dickinsondc787d22010-05-23 13:33:13 +00006481 use any sufficiently bit-mixing transformation;
6482 long.__hash__ will do nicely. */
Benjamin Peterson8f67d082010-10-17 20:54:53 +00006483 PyErr_Clear();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006484 h = PyLong_Type.tp_hash(res);
Benjamin Peterson8f67d082010-10-17 20:54:53 +00006485 }
Benjamin Petersone7dfeeb2010-10-17 21:27:01 +00006486 /* -1 is reserved for errors. */
6487 if (h == -1)
6488 h = -2;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006489 Py_DECREF(res);
Mark Dickinsondc787d22010-05-23 13:33:13 +00006490 return h;
Tim Peters6d6c1a32001-08-02 04:15:00 +00006491}
6492
6493static PyObject *
6494slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds)
6495{
Benjamin Petersonce798522012-01-22 11:24:29 -05006496 _Py_IDENTIFIER(__call__);
Victor Stinner516b9812017-02-09 22:53:47 +01006497 int unbound;
6498 PyObject *meth = lookup_method(self, &PyId___call__, &unbound);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006499 PyObject *res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00006500
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006501 if (meth == NULL)
6502 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006503
Victor Stinner516b9812017-02-09 22:53:47 +01006504 if (unbound) {
6505 res = _PyObject_Call_Prepend(meth, self, args, kwds);
6506 }
6507 else {
6508 res = PyObject_Call(meth, args, kwds);
6509 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006510
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006511 Py_DECREF(meth);
6512 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00006513}
6514
Guido van Rossum14a6f832001-10-17 13:59:09 +00006515/* There are two slot dispatch functions for tp_getattro.
6516
6517 - slot_tp_getattro() is used when __getattribute__ is overridden
6518 but no __getattr__ hook is present;
6519
6520 - slot_tp_getattr_hook() is used when a __getattr__ hook is present.
6521
Guido van Rossumc334df52002-04-04 23:44:47 +00006522 The code in update_one_slot() always installs slot_tp_getattr_hook(); this
6523 detects the absence of __getattr__ and then installs the simpler slot if
6524 necessary. */
Guido van Rossum14a6f832001-10-17 13:59:09 +00006525
Tim Peters6d6c1a32001-08-02 04:15:00 +00006526static PyObject *
6527slot_tp_getattro(PyObject *self, PyObject *name)
6528{
Victor Stinner434723f2017-01-11 00:07:40 +01006529 PyObject *stack[1] = {name};
6530 return call_method(self, &PyId___getattribute__, stack, 1);
Tim Peters6d6c1a32001-08-02 04:15:00 +00006531}
6532
Guido van Rossum19c1cd52001-09-21 21:24:49 +00006533static PyObject *
Benjamin Peterson9262b842008-11-17 22:45:50 +00006534call_attribute(PyObject *self, PyObject *attr, PyObject *name)
6535{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006536 PyObject *res, *descr = NULL;
6537 descrgetfunc f = Py_TYPE(attr)->tp_descr_get;
Benjamin Peterson9262b842008-11-17 22:45:50 +00006538
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006539 if (f != NULL) {
6540 descr = f(attr, self, (PyObject *)(Py_TYPE(self)));
6541 if (descr == NULL)
6542 return NULL;
6543 else
6544 attr = descr;
6545 }
Victor Stinnerde4ae3d2016-12-04 22:59:09 +01006546 res = PyObject_CallFunctionObjArgs(attr, name, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006547 Py_XDECREF(descr);
6548 return res;
Benjamin Peterson9262b842008-11-17 22:45:50 +00006549}
6550
6551static PyObject *
Guido van Rossum19c1cd52001-09-21 21:24:49 +00006552slot_tp_getattr_hook(PyObject *self, PyObject *name)
6553{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006554 PyTypeObject *tp = Py_TYPE(self);
6555 PyObject *getattr, *getattribute, *res;
Victor Stinner3c1e4812012-03-26 22:10:51 +02006556 _Py_IDENTIFIER(__getattr__);
Guido van Rossum19c1cd52001-09-21 21:24:49 +00006557
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006558 /* speed hack: we could use lookup_maybe, but that would resolve the
6559 method fully for each attribute lookup for classes with
6560 __getattr__, even when the attribute is present. So we use
6561 _PyType_Lookup and create the method only when needed, with
6562 call_attribute. */
Victor Stinner3c1e4812012-03-26 22:10:51 +02006563 getattr = _PyType_LookupId(tp, &PyId___getattr__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006564 if (getattr == NULL) {
6565 /* No __getattr__ hook: use a simpler dispatcher */
6566 tp->tp_getattro = slot_tp_getattro;
6567 return slot_tp_getattro(self, name);
6568 }
6569 Py_INCREF(getattr);
6570 /* speed hack: we could use lookup_maybe, but that would resolve the
6571 method fully for each attribute lookup for classes with
6572 __getattr__, even when self has the default __getattribute__
6573 method. So we use _PyType_Lookup and create the method only when
6574 needed, with call_attribute. */
Victor Stinner3c1e4812012-03-26 22:10:51 +02006575 getattribute = _PyType_LookupId(tp, &PyId___getattribute__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006576 if (getattribute == NULL ||
6577 (Py_TYPE(getattribute) == &PyWrapperDescr_Type &&
6578 ((PyWrapperDescrObject *)getattribute)->d_wrapped ==
6579 (void *)PyObject_GenericGetAttr))
6580 res = PyObject_GenericGetAttr(self, name);
6581 else {
6582 Py_INCREF(getattribute);
6583 res = call_attribute(self, getattribute, name);
6584 Py_DECREF(getattribute);
6585 }
6586 if (res == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) {
6587 PyErr_Clear();
6588 res = call_attribute(self, getattr, name);
6589 }
6590 Py_DECREF(getattr);
6591 return res;
Guido van Rossum19c1cd52001-09-21 21:24:49 +00006592}
6593
Tim Peters6d6c1a32001-08-02 04:15:00 +00006594static int
6595slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value)
6596{
Victor Stinner434723f2017-01-11 00:07:40 +01006597 PyObject *stack[2];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006598 PyObject *res;
Benjamin Petersonce798522012-01-22 11:24:29 -05006599 _Py_IDENTIFIER(__delattr__);
6600 _Py_IDENTIFIER(__setattr__);
Tim Peters6d6c1a32001-08-02 04:15:00 +00006601
Victor Stinner434723f2017-01-11 00:07:40 +01006602 stack[0] = name;
6603 if (value == NULL) {
6604 res = call_method(self, &PyId___delattr__, stack, 1);
6605 }
6606 else {
6607 stack[1] = value;
6608 res = call_method(self, &PyId___setattr__, stack, 2);
6609 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006610 if (res == NULL)
6611 return -1;
6612 Py_DECREF(res);
6613 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00006614}
6615
Benjamin Petersonce798522012-01-22 11:24:29 -05006616static _Py_Identifier name_op[] = {
6617 {0, "__lt__", 0},
6618 {0, "__le__", 0},
6619 {0, "__eq__", 0},
6620 {0, "__ne__", 0},
6621 {0, "__gt__", 0},
6622 {0, "__ge__", 0}
Guido van Rossumf5243f02008-01-01 04:06:48 +00006623};
6624
Tim Peters6d6c1a32001-08-02 04:15:00 +00006625static PyObject *
Mark Dickinson6f1d0492009-11-15 13:58:49 +00006626slot_tp_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters6d6c1a32001-08-02 04:15:00 +00006627{
Victor Stinner516b9812017-02-09 22:53:47 +01006628 int unbound;
Victor Stinnera7720f62016-08-19 17:48:51 +02006629 PyObject *func, *res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00006630
Serhiy Storchaka4e624ca2017-06-01 08:18:25 +03006631 func = lookup_maybe_method(self, &name_op[op], &unbound);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006632 if (func == NULL) {
6633 PyErr_Clear();
Brian Curtindfc80e32011-08-10 20:28:54 -05006634 Py_RETURN_NOTIMPLEMENTED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006635 }
Victor Stinner516b9812017-02-09 22:53:47 +01006636
6637 PyObject *args[1] = {other};
6638 res = call_unbound(unbound, func, self, args, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006639 Py_DECREF(func);
6640 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00006641}
6642
Guido van Rossumb8f63662001-08-15 23:57:02 +00006643static PyObject *
Guido van Rossumb8f63662001-08-15 23:57:02 +00006644slot_tp_iter(PyObject *self)
6645{
Victor Stinner516b9812017-02-09 22:53:47 +01006646 int unbound;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006647 PyObject *func, *res;
Benjamin Petersonce798522012-01-22 11:24:29 -05006648 _Py_IDENTIFIER(__iter__);
Guido van Rossumb8f63662001-08-15 23:57:02 +00006649
Serhiy Storchaka4e624ca2017-06-01 08:18:25 +03006650 func = lookup_maybe_method(self, &PyId___iter__, &unbound);
Guido van Rossum97c1adf2016-08-18 09:22:23 -07006651 if (func == Py_None) {
6652 Py_DECREF(func);
6653 PyErr_Format(PyExc_TypeError,
6654 "'%.200s' object is not iterable",
6655 Py_TYPE(self)->tp_name);
6656 return NULL;
6657 }
Victor Stinner69112672016-08-19 18:41:02 +02006658
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006659 if (func != NULL) {
Victor Stinner516b9812017-02-09 22:53:47 +01006660 res = call_unbound_noarg(unbound, func, self);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006661 Py_DECREF(func);
6662 return res;
6663 }
Victor Stinner69112672016-08-19 18:41:02 +02006664
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006665 PyErr_Clear();
Serhiy Storchaka4e624ca2017-06-01 08:18:25 +03006666 func = lookup_maybe_method(self, &PyId___getitem__, &unbound);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006667 if (func == NULL) {
6668 PyErr_Format(PyExc_TypeError,
6669 "'%.200s' object is not iterable",
6670 Py_TYPE(self)->tp_name);
6671 return NULL;
6672 }
6673 Py_DECREF(func);
6674 return PySeqIter_New(self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00006675}
Tim Peters6d6c1a32001-08-02 04:15:00 +00006676
6677static PyObject *
6678slot_tp_iternext(PyObject *self)
6679{
Benjamin Petersonce798522012-01-22 11:24:29 -05006680 _Py_IDENTIFIER(__next__);
Victor Stinner434723f2017-01-11 00:07:40 +01006681 return call_method(self, &PyId___next__, NULL, 0);
Tim Peters6d6c1a32001-08-02 04:15:00 +00006682}
6683
Guido van Rossum1a493502001-08-17 16:47:50 +00006684static PyObject *
6685slot_tp_descr_get(PyObject *self, PyObject *obj, PyObject *type)
6686{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006687 PyTypeObject *tp = Py_TYPE(self);
6688 PyObject *get;
Victor Stinner3c1e4812012-03-26 22:10:51 +02006689 _Py_IDENTIFIER(__get__);
Guido van Rossum1a493502001-08-17 16:47:50 +00006690
Victor Stinner3c1e4812012-03-26 22:10:51 +02006691 get = _PyType_LookupId(tp, &PyId___get__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006692 if (get == NULL) {
6693 /* Avoid further slowdowns */
6694 if (tp->tp_descr_get == slot_tp_descr_get)
6695 tp->tp_descr_get = NULL;
6696 Py_INCREF(self);
6697 return self;
6698 }
6699 if (obj == NULL)
6700 obj = Py_None;
6701 if (type == NULL)
6702 type = Py_None;
6703 return PyObject_CallFunctionObjArgs(get, self, obj, type, NULL);
Guido van Rossum1a493502001-08-17 16:47:50 +00006704}
Tim Peters6d6c1a32001-08-02 04:15:00 +00006705
6706static int
6707slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value)
6708{
Victor Stinner434723f2017-01-11 00:07:40 +01006709 PyObject* stack[2];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006710 PyObject *res;
Benjamin Petersonce798522012-01-22 11:24:29 -05006711 _Py_IDENTIFIER(__delete__);
6712 _Py_IDENTIFIER(__set__);
Guido van Rossum2c252392001-08-24 10:13:31 +00006713
Victor Stinner434723f2017-01-11 00:07:40 +01006714 stack[0] = target;
6715 if (value == NULL) {
6716 res = call_method(self, &PyId___delete__, stack, 1);
6717 }
6718 else {
6719 stack[1] = value;
6720 res = call_method(self, &PyId___set__, stack, 2);
6721 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006722 if (res == NULL)
6723 return -1;
6724 Py_DECREF(res);
6725 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00006726}
6727
6728static int
6729slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds)
6730{
Benjamin Petersonce798522012-01-22 11:24:29 -05006731 _Py_IDENTIFIER(__init__);
Victor Stinner516b9812017-02-09 22:53:47 +01006732 int unbound;
6733 PyObject *meth = lookup_method(self, &PyId___init__, &unbound);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006734 PyObject *res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00006735
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006736 if (meth == NULL)
6737 return -1;
Victor Stinner516b9812017-02-09 22:53:47 +01006738 if (unbound) {
6739 res = _PyObject_Call_Prepend(meth, self, args, kwds);
6740 }
6741 else {
6742 res = PyObject_Call(meth, args, kwds);
6743 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006744 Py_DECREF(meth);
6745 if (res == NULL)
6746 return -1;
6747 if (res != Py_None) {
6748 PyErr_Format(PyExc_TypeError,
6749 "__init__() should return None, not '%.200s'",
6750 Py_TYPE(res)->tp_name);
6751 Py_DECREF(res);
6752 return -1;
6753 }
6754 Py_DECREF(res);
6755 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00006756}
6757
6758static PyObject *
6759slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
6760{
Victor Stinner3f1057a2016-08-25 01:04:14 +02006761 PyObject *func, *result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00006762
Victor Stinner3c1e4812012-03-26 22:10:51 +02006763 func = _PyObject_GetAttrId((PyObject *)type, &PyId___new__);
Victor Stinner3f1057a2016-08-25 01:04:14 +02006764 if (func == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006765 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006766 }
Victor Stinner3f1057a2016-08-25 01:04:14 +02006767
6768 result = _PyObject_Call_Prepend(func, (PyObject *)type, args, kwds);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006769 Py_DECREF(func);
Victor Stinner3f1057a2016-08-25 01:04:14 +02006770 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00006771}
6772
Guido van Rossumfebd61d2002-08-08 20:55:20 +00006773static void
Antoine Pitrou796564c2013-07-30 19:59:21 +02006774slot_tp_finalize(PyObject *self)
Guido van Rossumfebd61d2002-08-08 20:55:20 +00006775{
Benjamin Petersonce798522012-01-22 11:24:29 -05006776 _Py_IDENTIFIER(__del__);
Victor Stinner516b9812017-02-09 22:53:47 +01006777 int unbound;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006778 PyObject *del, *res;
6779 PyObject *error_type, *error_value, *error_traceback;
Guido van Rossumfebd61d2002-08-08 20:55:20 +00006780
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006781 /* Save the current exception, if any. */
6782 PyErr_Fetch(&error_type, &error_value, &error_traceback);
Guido van Rossumfebd61d2002-08-08 20:55:20 +00006783
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006784 /* Execute __del__ method, if any. */
Victor Stinner516b9812017-02-09 22:53:47 +01006785 del = lookup_maybe_method(self, &PyId___del__, &unbound);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006786 if (del != NULL) {
Victor Stinner516b9812017-02-09 22:53:47 +01006787 res = call_unbound_noarg(unbound, del, self);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006788 if (res == NULL)
6789 PyErr_WriteUnraisable(del);
6790 else
6791 Py_DECREF(res);
6792 Py_DECREF(del);
6793 }
Guido van Rossumfebd61d2002-08-08 20:55:20 +00006794
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006795 /* Restore the saved exception. */
6796 PyErr_Restore(error_type, error_value, error_traceback);
Guido van Rossumfebd61d2002-08-08 20:55:20 +00006797}
6798
Yury Selivanov75445082015-05-11 22:57:16 -04006799static PyObject *
6800slot_am_await(PyObject *self)
6801{
Victor Stinner516b9812017-02-09 22:53:47 +01006802 int unbound;
Yury Selivanov75445082015-05-11 22:57:16 -04006803 PyObject *func, *res;
6804 _Py_IDENTIFIER(__await__);
6805
Serhiy Storchaka4e624ca2017-06-01 08:18:25 +03006806 func = lookup_maybe_method(self, &PyId___await__, &unbound);
Yury Selivanov75445082015-05-11 22:57:16 -04006807 if (func != NULL) {
Victor Stinner516b9812017-02-09 22:53:47 +01006808 res = call_unbound_noarg(unbound, func, self);
Yury Selivanov75445082015-05-11 22:57:16 -04006809 Py_DECREF(func);
6810 return res;
6811 }
6812 PyErr_Format(PyExc_AttributeError,
6813 "object %.50s does not have __await__ method",
6814 Py_TYPE(self)->tp_name);
6815 return NULL;
6816}
6817
6818static PyObject *
6819slot_am_aiter(PyObject *self)
6820{
Victor Stinner516b9812017-02-09 22:53:47 +01006821 int unbound;
Yury Selivanov75445082015-05-11 22:57:16 -04006822 PyObject *func, *res;
6823 _Py_IDENTIFIER(__aiter__);
6824
Serhiy Storchaka4e624ca2017-06-01 08:18:25 +03006825 func = lookup_maybe_method(self, &PyId___aiter__, &unbound);
Yury Selivanov75445082015-05-11 22:57:16 -04006826 if (func != NULL) {
Victor Stinner516b9812017-02-09 22:53:47 +01006827 res = call_unbound_noarg(unbound, func, self);
Yury Selivanov75445082015-05-11 22:57:16 -04006828 Py_DECREF(func);
6829 return res;
6830 }
6831 PyErr_Format(PyExc_AttributeError,
6832 "object %.50s does not have __aiter__ method",
6833 Py_TYPE(self)->tp_name);
6834 return NULL;
6835}
6836
6837static PyObject *
6838slot_am_anext(PyObject *self)
6839{
Victor Stinner516b9812017-02-09 22:53:47 +01006840 int unbound;
Yury Selivanov75445082015-05-11 22:57:16 -04006841 PyObject *func, *res;
6842 _Py_IDENTIFIER(__anext__);
6843
Serhiy Storchaka4e624ca2017-06-01 08:18:25 +03006844 func = lookup_maybe_method(self, &PyId___anext__, &unbound);
Yury Selivanov75445082015-05-11 22:57:16 -04006845 if (func != NULL) {
Victor Stinner516b9812017-02-09 22:53:47 +01006846 res = call_unbound_noarg(unbound, func, self);
Yury Selivanov75445082015-05-11 22:57:16 -04006847 Py_DECREF(func);
6848 return res;
6849 }
6850 PyErr_Format(PyExc_AttributeError,
6851 "object %.50s does not have __anext__ method",
6852 Py_TYPE(self)->tp_name);
6853 return NULL;
6854}
Guido van Rossum7b9144b2001-10-09 19:39:46 +00006855
Benjamin Peterson63952412013-04-01 17:41:41 -04006856/*
6857Table mapping __foo__ names to tp_foo offsets and slot_tp_foo wrapper functions.
6858
6859The table is ordered by offsets relative to the 'PyHeapTypeObject' structure,
6860which incorporates the additional structures used for numbers, sequences and
6861mappings. Note that multiple names may map to the same slot (e.g. __eq__,
6862__ne__ etc. all map to tp_richcompare) and one name may map to multiple slots
6863(e.g. __str__ affects tp_str as well as tp_repr). The table is terminated with
6864an all-zero entry. (This table is further initialized in init_slotdefs().)
6865*/
Guido van Rossum7b9144b2001-10-09 19:39:46 +00006866
Guido van Rossum6d204072001-10-21 00:44:31 +00006867typedef struct wrapperbase slotdef;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00006868
6869#undef TPSLOT
Guido van Rossumc8e56452001-10-22 00:43:43 +00006870#undef FLSLOT
Yury Selivanov75445082015-05-11 22:57:16 -04006871#undef AMSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00006872#undef ETSLOT
6873#undef SQSLOT
6874#undef MPSLOT
6875#undef NBSLOT
Guido van Rossum6d204072001-10-21 00:44:31 +00006876#undef UNSLOT
6877#undef IBSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00006878#undef BINSLOT
6879#undef RBINSLOT
6880
Guido van Rossum6d204072001-10-21 00:44:31 +00006881#define TPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006882 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
6883 PyDoc_STR(DOC)}
Guido van Rossumc8e56452001-10-22 00:43:43 +00006884#define FLSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC, FLAGS) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006885 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
6886 PyDoc_STR(DOC), FLAGS}
Guido van Rossum6d204072001-10-21 00:44:31 +00006887#define ETSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006888 {NAME, offsetof(PyHeapTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
6889 PyDoc_STR(DOC)}
Yury Selivanov75445082015-05-11 22:57:16 -04006890#define AMSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
6891 ETSLOT(NAME, as_async.SLOT, FUNCTION, WRAPPER, DOC)
Guido van Rossum6d204072001-10-21 00:44:31 +00006892#define SQSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006893 ETSLOT(NAME, as_sequence.SLOT, FUNCTION, WRAPPER, DOC)
Guido van Rossum6d204072001-10-21 00:44:31 +00006894#define MPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006895 ETSLOT(NAME, as_mapping.SLOT, FUNCTION, WRAPPER, DOC)
Guido van Rossum6d204072001-10-21 00:44:31 +00006896#define NBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006897 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, DOC)
Guido van Rossum6d204072001-10-21 00:44:31 +00006898#define UNSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006899 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
Larry Hastings69a25472014-02-09 22:22:38 -08006900 NAME "($self, /)\n--\n\n" DOC)
Guido van Rossum6d204072001-10-21 00:44:31 +00006901#define IBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006902 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
Larry Hastings69a25472014-02-09 22:22:38 -08006903 NAME "($self, value, /)\n--\n\nReturn self" DOC "value.")
Guido van Rossum6d204072001-10-21 00:44:31 +00006904#define BINSLOT(NAME, SLOT, FUNCTION, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006905 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
Larry Hastings69a25472014-02-09 22:22:38 -08006906 NAME "($self, value, /)\n--\n\nReturn self" DOC "value.")
Guido van Rossum6d204072001-10-21 00:44:31 +00006907#define RBINSLOT(NAME, SLOT, FUNCTION, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006908 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
Larry Hastings69a25472014-02-09 22:22:38 -08006909 NAME "($self, value, /)\n--\n\nReturn value" DOC "self.")
Anthony Baxter56616992005-06-03 14:12:21 +00006910#define BINSLOTNOTINFIX(NAME, SLOT, FUNCTION, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006911 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
Larry Hastings69a25472014-02-09 22:22:38 -08006912 NAME "($self, value, /)\n--\n\n" DOC)
Anthony Baxter56616992005-06-03 14:12:21 +00006913#define RBINSLOTNOTINFIX(NAME, SLOT, FUNCTION, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006914 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
Larry Hastings69a25472014-02-09 22:22:38 -08006915 NAME "($self, value, /)\n--\n\n" DOC)
Guido van Rossum7b9144b2001-10-09 19:39:46 +00006916
6917static slotdef slotdefs[] = {
Benjamin Peterson63952412013-04-01 17:41:41 -04006918 TPSLOT("__getattribute__", tp_getattr, NULL, NULL, ""),
6919 TPSLOT("__getattr__", tp_getattr, NULL, NULL, ""),
6920 TPSLOT("__setattr__", tp_setattr, NULL, NULL, ""),
6921 TPSLOT("__delattr__", tp_setattr, NULL, NULL, ""),
6922 TPSLOT("__repr__", tp_repr, slot_tp_repr, wrap_unaryfunc,
Larry Hastings69a25472014-02-09 22:22:38 -08006923 "__repr__($self, /)\n--\n\nReturn repr(self)."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006924 TPSLOT("__hash__", tp_hash, slot_tp_hash, wrap_hashfunc,
Larry Hastings69a25472014-02-09 22:22:38 -08006925 "__hash__($self, /)\n--\n\nReturn hash(self)."),
Serhiy Storchaka1c607152018-11-27 21:34:27 +02006926 FLSLOT("__call__", tp_call, slot_tp_call, (wrapperfunc)(void(*)(void))wrap_call,
Larry Hastings69a25472014-02-09 22:22:38 -08006927 "__call__($self, /, *args, **kwargs)\n--\n\nCall self as a function.",
Larry Hastings5c661892014-01-24 06:17:25 -08006928 PyWrapperFlag_KEYWORDS),
Benjamin Peterson63952412013-04-01 17:41:41 -04006929 TPSLOT("__str__", tp_str, slot_tp_str, wrap_unaryfunc,
Larry Hastings69a25472014-02-09 22:22:38 -08006930 "__str__($self, /)\n--\n\nReturn str(self)."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006931 TPSLOT("__getattribute__", tp_getattro, slot_tp_getattr_hook,
Larry Hastings5c661892014-01-24 06:17:25 -08006932 wrap_binaryfunc,
Larry Hastings69a25472014-02-09 22:22:38 -08006933 "__getattribute__($self, name, /)\n--\n\nReturn getattr(self, name)."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006934 TPSLOT("__getattr__", tp_getattro, slot_tp_getattr_hook, NULL, ""),
6935 TPSLOT("__setattr__", tp_setattro, slot_tp_setattro, wrap_setattr,
Larry Hastings69a25472014-02-09 22:22:38 -08006936 "__setattr__($self, name, value, /)\n--\n\nImplement setattr(self, name, value)."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006937 TPSLOT("__delattr__", tp_setattro, slot_tp_setattro, wrap_delattr,
Larry Hastings69a25472014-02-09 22:22:38 -08006938 "__delattr__($self, name, /)\n--\n\nImplement delattr(self, name)."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006939 TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare, richcmp_lt,
Larry Hastings69a25472014-02-09 22:22:38 -08006940 "__lt__($self, value, /)\n--\n\nReturn self<value."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006941 TPSLOT("__le__", tp_richcompare, slot_tp_richcompare, richcmp_le,
Larry Hastings69a25472014-02-09 22:22:38 -08006942 "__le__($self, value, /)\n--\n\nReturn self<=value."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006943 TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare, richcmp_eq,
Larry Hastings69a25472014-02-09 22:22:38 -08006944 "__eq__($self, value, /)\n--\n\nReturn self==value."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006945 TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare, richcmp_ne,
Larry Hastings69a25472014-02-09 22:22:38 -08006946 "__ne__($self, value, /)\n--\n\nReturn self!=value."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006947 TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare, richcmp_gt,
Larry Hastings69a25472014-02-09 22:22:38 -08006948 "__gt__($self, value, /)\n--\n\nReturn self>value."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006949 TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare, richcmp_ge,
Zachary Wareea42b4c2014-04-18 09:14:31 -05006950 "__ge__($self, value, /)\n--\n\nReturn self>=value."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006951 TPSLOT("__iter__", tp_iter, slot_tp_iter, wrap_unaryfunc,
Larry Hastings69a25472014-02-09 22:22:38 -08006952 "__iter__($self, /)\n--\n\nImplement iter(self)."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006953 TPSLOT("__next__", tp_iternext, slot_tp_iternext, wrap_next,
Larry Hastings69a25472014-02-09 22:22:38 -08006954 "__next__($self, /)\n--\n\nImplement next(self)."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006955 TPSLOT("__get__", tp_descr_get, slot_tp_descr_get, wrap_descr_get,
Larry Hastings69a25472014-02-09 22:22:38 -08006956 "__get__($self, instance, owner, /)\n--\n\nReturn an attribute of instance, which is of type owner."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006957 TPSLOT("__set__", tp_descr_set, slot_tp_descr_set, wrap_descr_set,
Larry Hastings69a25472014-02-09 22:22:38 -08006958 "__set__($self, instance, value, /)\n--\n\nSet an attribute of instance to value."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006959 TPSLOT("__delete__", tp_descr_set, slot_tp_descr_set,
Larry Hastings5c661892014-01-24 06:17:25 -08006960 wrap_descr_delete,
Yury Selivanov056e2652014-03-02 12:25:27 -05006961 "__delete__($self, instance, /)\n--\n\nDelete an attribute of instance."),
Serhiy Storchaka1c607152018-11-27 21:34:27 +02006962 FLSLOT("__init__", tp_init, slot_tp_init, (wrapperfunc)(void(*)(void))wrap_init,
Larry Hastings69a25472014-02-09 22:22:38 -08006963 "__init__($self, /, *args, **kwargs)\n--\n\n"
Larry Hastings581ee362014-01-28 05:00:08 -08006964 "Initialize self. See help(type(self)) for accurate signature.",
Benjamin Peterson63952412013-04-01 17:41:41 -04006965 PyWrapperFlag_KEYWORDS),
Larry Hastings5c661892014-01-24 06:17:25 -08006966 TPSLOT("__new__", tp_new, slot_tp_new, NULL,
Larry Hastings69a25472014-02-09 22:22:38 -08006967 "__new__(type, /, *args, **kwargs)\n--\n\n"
Larry Hastings581ee362014-01-28 05:00:08 -08006968 "Create and return new object. See help(type) for accurate signature."),
Antoine Pitrou796564c2013-07-30 19:59:21 +02006969 TPSLOT("__del__", tp_finalize, slot_tp_finalize, (wrapperfunc)wrap_del, ""),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00006970
Yury Selivanov75445082015-05-11 22:57:16 -04006971 AMSLOT("__await__", am_await, slot_am_await, wrap_unaryfunc,
6972 "__await__($self, /)\n--\n\nReturn an iterator to be used in await expression."),
6973 AMSLOT("__aiter__", am_aiter, slot_am_aiter, wrap_unaryfunc,
6974 "__aiter__($self, /)\n--\n\nReturn an awaitable, that resolves in asynchronous iterator."),
6975 AMSLOT("__anext__", am_anext, slot_am_anext, wrap_unaryfunc,
6976 "__anext__($self, /)\n--\n\nReturn a value or raise StopAsyncIteration."),
6977
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006978 BINSLOT("__add__", nb_add, slot_nb_add,
Larry Hastings5c661892014-01-24 06:17:25 -08006979 "+"),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006980 RBINSLOT("__radd__", nb_add, slot_nb_add,
Larry Hastings5c661892014-01-24 06:17:25 -08006981 "+"),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006982 BINSLOT("__sub__", nb_subtract, slot_nb_subtract,
Larry Hastings5c661892014-01-24 06:17:25 -08006983 "-"),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006984 RBINSLOT("__rsub__", nb_subtract, slot_nb_subtract,
Larry Hastings5c661892014-01-24 06:17:25 -08006985 "-"),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006986 BINSLOT("__mul__", nb_multiply, slot_nb_multiply,
Larry Hastings5c661892014-01-24 06:17:25 -08006987 "*"),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006988 RBINSLOT("__rmul__", nb_multiply, slot_nb_multiply,
Larry Hastings5c661892014-01-24 06:17:25 -08006989 "*"),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006990 BINSLOT("__mod__", nb_remainder, slot_nb_remainder,
Larry Hastings5c661892014-01-24 06:17:25 -08006991 "%"),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006992 RBINSLOT("__rmod__", nb_remainder, slot_nb_remainder,
Larry Hastings5c661892014-01-24 06:17:25 -08006993 "%"),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006994 BINSLOTNOTINFIX("__divmod__", nb_divmod, slot_nb_divmod,
Larry Hastings581ee362014-01-28 05:00:08 -08006995 "Return divmod(self, value)."),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006996 RBINSLOTNOTINFIX("__rdivmod__", nb_divmod, slot_nb_divmod,
Larry Hastings581ee362014-01-28 05:00:08 -08006997 "Return divmod(value, self)."),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006998 NBSLOT("__pow__", nb_power, slot_nb_power, wrap_ternaryfunc,
Larry Hastings69a25472014-02-09 22:22:38 -08006999 "__pow__($self, value, mod=None, /)\n--\n\nReturn pow(self, value, mod)."),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007000 NBSLOT("__rpow__", nb_power, slot_nb_power, wrap_ternaryfunc_r,
Larry Hastings69a25472014-02-09 22:22:38 -08007001 "__rpow__($self, value, mod=None, /)\n--\n\nReturn pow(value, self, mod)."),
Larry Hastings5c661892014-01-24 06:17:25 -08007002 UNSLOT("__neg__", nb_negative, slot_nb_negative, wrap_unaryfunc, "-self"),
7003 UNSLOT("__pos__", nb_positive, slot_nb_positive, wrap_unaryfunc, "+self"),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007004 UNSLOT("__abs__", nb_absolute, slot_nb_absolute, wrap_unaryfunc,
Larry Hastings5c661892014-01-24 06:17:25 -08007005 "abs(self)"),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007006 UNSLOT("__bool__", nb_bool, slot_nb_bool, wrap_inquirypred,
Larry Hastings5c661892014-01-24 06:17:25 -08007007 "self != 0"),
7008 UNSLOT("__invert__", nb_invert, slot_nb_invert, wrap_unaryfunc, "~self"),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007009 BINSLOT("__lshift__", nb_lshift, slot_nb_lshift, "<<"),
7010 RBINSLOT("__rlshift__", nb_lshift, slot_nb_lshift, "<<"),
7011 BINSLOT("__rshift__", nb_rshift, slot_nb_rshift, ">>"),
7012 RBINSLOT("__rrshift__", nb_rshift, slot_nb_rshift, ">>"),
7013 BINSLOT("__and__", nb_and, slot_nb_and, "&"),
7014 RBINSLOT("__rand__", nb_and, slot_nb_and, "&"),
7015 BINSLOT("__xor__", nb_xor, slot_nb_xor, "^"),
7016 RBINSLOT("__rxor__", nb_xor, slot_nb_xor, "^"),
7017 BINSLOT("__or__", nb_or, slot_nb_or, "|"),
7018 RBINSLOT("__ror__", nb_or, slot_nb_or, "|"),
7019 UNSLOT("__int__", nb_int, slot_nb_int, wrap_unaryfunc,
Larry Hastings5c661892014-01-24 06:17:25 -08007020 "int(self)"),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007021 UNSLOT("__float__", nb_float, slot_nb_float, wrap_unaryfunc,
Larry Hastings5c661892014-01-24 06:17:25 -08007022 "float(self)"),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007023 IBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add,
Eli Benderskyd3baae72011-11-11 16:57:05 +02007024 wrap_binaryfunc, "+="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007025 IBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract,
Eli Benderskyd3baae72011-11-11 16:57:05 +02007026 wrap_binaryfunc, "-="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007027 IBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply,
Eli Benderskyd3baae72011-11-11 16:57:05 +02007028 wrap_binaryfunc, "*="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007029 IBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder,
Eli Benderskyd3baae72011-11-11 16:57:05 +02007030 wrap_binaryfunc, "%="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007031 IBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power,
Eli Benderskyd3baae72011-11-11 16:57:05 +02007032 wrap_binaryfunc, "**="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007033 IBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift,
Eli Benderskyd3baae72011-11-11 16:57:05 +02007034 wrap_binaryfunc, "<<="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007035 IBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift,
Eli Benderskyd3baae72011-11-11 16:57:05 +02007036 wrap_binaryfunc, ">>="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007037 IBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and,
Eli Benderskyd3baae72011-11-11 16:57:05 +02007038 wrap_binaryfunc, "&="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007039 IBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor,
Eli Benderskyd3baae72011-11-11 16:57:05 +02007040 wrap_binaryfunc, "^="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007041 IBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or,
Eli Benderskyd3baae72011-11-11 16:57:05 +02007042 wrap_binaryfunc, "|="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007043 BINSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
7044 RBINSLOT("__rfloordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
7045 BINSLOT("__truediv__", nb_true_divide, slot_nb_true_divide, "/"),
7046 RBINSLOT("__rtruediv__", nb_true_divide, slot_nb_true_divide, "/"),
7047 IBSLOT("__ifloordiv__", nb_inplace_floor_divide,
Georg Brandle1d26f32014-10-31 13:12:57 +01007048 slot_nb_inplace_floor_divide, wrap_binaryfunc, "//="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007049 IBSLOT("__itruediv__", nb_inplace_true_divide,
Georg Brandle1d26f32014-10-31 13:12:57 +01007050 slot_nb_inplace_true_divide, wrap_binaryfunc, "/="),
Benjamin Peterson63952412013-04-01 17:41:41 -04007051 NBSLOT("__index__", nb_index, slot_nb_index, wrap_unaryfunc,
Larry Hastings69a25472014-02-09 22:22:38 -08007052 "__index__($self, /)\n--\n\n"
Zachary Ware715ef022014-04-18 09:23:14 -05007053 "Return self converted to an integer, if self is suitable "
Larry Hastings5c661892014-01-24 06:17:25 -08007054 "for use as an index into a list."),
Benjamin Petersond51374e2014-04-09 23:55:56 -04007055 BINSLOT("__matmul__", nb_matrix_multiply, slot_nb_matrix_multiply,
7056 "@"),
7057 RBINSLOT("__rmatmul__", nb_matrix_multiply, slot_nb_matrix_multiply,
7058 "@"),
7059 IBSLOT("__imatmul__", nb_inplace_matrix_multiply, slot_nb_inplace_matrix_multiply,
7060 wrap_binaryfunc, "@="),
Benjamin Peterson63952412013-04-01 17:41:41 -04007061 MPSLOT("__len__", mp_length, slot_mp_length, wrap_lenfunc,
Larry Hastings69a25472014-02-09 22:22:38 -08007062 "__len__($self, /)\n--\n\nReturn len(self)."),
Benjamin Peterson63952412013-04-01 17:41:41 -04007063 MPSLOT("__getitem__", mp_subscript, slot_mp_subscript,
7064 wrap_binaryfunc,
Larry Hastings69a25472014-02-09 22:22:38 -08007065 "__getitem__($self, key, /)\n--\n\nReturn self[key]."),
Benjamin Peterson63952412013-04-01 17:41:41 -04007066 MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript,
7067 wrap_objobjargproc,
Larry Hastings69a25472014-02-09 22:22:38 -08007068 "__setitem__($self, key, value, /)\n--\n\nSet self[key] to value."),
Benjamin Peterson63952412013-04-01 17:41:41 -04007069 MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript,
7070 wrap_delitem,
Yury Selivanov056e2652014-03-02 12:25:27 -05007071 "__delitem__($self, key, /)\n--\n\nDelete self[key]."),
Benjamin Peterson63952412013-04-01 17:41:41 -04007072
7073 SQSLOT("__len__", sq_length, slot_sq_length, wrap_lenfunc,
Larry Hastings69a25472014-02-09 22:22:38 -08007074 "__len__($self, /)\n--\n\nReturn len(self)."),
Benjamin Peterson63952412013-04-01 17:41:41 -04007075 /* Heap types defining __add__/__mul__ have sq_concat/sq_repeat == NULL.
7076 The logic in abstract.c always falls back to nb_add/nb_multiply in
7077 this case. Defining both the nb_* and the sq_* slots to call the
7078 user-defined methods has unexpected side-effects, as shown by
7079 test_descr.notimplemented() */
7080 SQSLOT("__add__", sq_concat, NULL, wrap_binaryfunc,
Larry Hastings69a25472014-02-09 22:22:38 -08007081 "__add__($self, value, /)\n--\n\nReturn self+value."),
Benjamin Peterson63952412013-04-01 17:41:41 -04007082 SQSLOT("__mul__", sq_repeat, NULL, wrap_indexargfunc,
Grant Jenks0904f762018-05-08 15:00:19 -07007083 "__mul__($self, value, /)\n--\n\nReturn self*value."),
Benjamin Peterson63952412013-04-01 17:41:41 -04007084 SQSLOT("__rmul__", sq_repeat, NULL, wrap_indexargfunc,
Grant Jenks0904f762018-05-08 15:00:19 -07007085 "__rmul__($self, value, /)\n--\n\nReturn value*self."),
Benjamin Peterson63952412013-04-01 17:41:41 -04007086 SQSLOT("__getitem__", sq_item, slot_sq_item, wrap_sq_item,
Larry Hastings69a25472014-02-09 22:22:38 -08007087 "__getitem__($self, key, /)\n--\n\nReturn self[key]."),
Benjamin Peterson63952412013-04-01 17:41:41 -04007088 SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_setitem,
Larry Hastings69a25472014-02-09 22:22:38 -08007089 "__setitem__($self, key, value, /)\n--\n\nSet self[key] to value."),
Benjamin Peterson63952412013-04-01 17:41:41 -04007090 SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_delitem,
Larry Hastings69a25472014-02-09 22:22:38 -08007091 "__delitem__($self, key, /)\n--\n\nDelete self[key]."),
Benjamin Peterson63952412013-04-01 17:41:41 -04007092 SQSLOT("__contains__", sq_contains, slot_sq_contains, wrap_objobjproc,
Larry Hastings69a25472014-02-09 22:22:38 -08007093 "__contains__($self, key, /)\n--\n\nReturn key in self."),
Benjamin Peterson63952412013-04-01 17:41:41 -04007094 SQSLOT("__iadd__", sq_inplace_concat, NULL,
Larry Hastings5c661892014-01-24 06:17:25 -08007095 wrap_binaryfunc,
Larry Hastings69a25472014-02-09 22:22:38 -08007096 "__iadd__($self, value, /)\n--\n\nImplement self+=value."),
Benjamin Peterson63952412013-04-01 17:41:41 -04007097 SQSLOT("__imul__", sq_inplace_repeat, NULL,
Larry Hastings5c661892014-01-24 06:17:25 -08007098 wrap_indexargfunc,
Larry Hastings69a25472014-02-09 22:22:38 -08007099 "__imul__($self, value, /)\n--\n\nImplement self*=value."),
Benjamin Peterson63952412013-04-01 17:41:41 -04007100
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007101 {NULL}
Guido van Rossum7b9144b2001-10-09 19:39:46 +00007102};
7103
Guido van Rossumc334df52002-04-04 23:44:47 +00007104/* Given a type pointer and an offset gotten from a slotdef entry, return a
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007105 pointer to the actual slot. This is not quite the same as simply adding
Guido van Rossumc334df52002-04-04 23:44:47 +00007106 the offset to the type pointer, since it takes care to indirect through the
7107 proper indirection pointer (as_buffer, etc.); it returns NULL if the
7108 indirection pointer is NULL. */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00007109static void **
Martin v. Löwis18e16552006-02-15 17:27:45 +00007110slotptr(PyTypeObject *type, int ioffset)
Guido van Rossum7b9144b2001-10-09 19:39:46 +00007111{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007112 char *ptr;
7113 long offset = ioffset;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00007114
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007115 /* Note: this depends on the order of the members of PyHeapTypeObject! */
7116 assert(offset >= 0);
7117 assert((size_t)offset < offsetof(PyHeapTypeObject, as_buffer));
7118 if ((size_t)offset >= offsetof(PyHeapTypeObject, as_sequence)) {
7119 ptr = (char *)type->tp_as_sequence;
7120 offset -= offsetof(PyHeapTypeObject, as_sequence);
7121 }
7122 else if ((size_t)offset >= offsetof(PyHeapTypeObject, as_mapping)) {
7123 ptr = (char *)type->tp_as_mapping;
7124 offset -= offsetof(PyHeapTypeObject, as_mapping);
7125 }
7126 else if ((size_t)offset >= offsetof(PyHeapTypeObject, as_number)) {
7127 ptr = (char *)type->tp_as_number;
7128 offset -= offsetof(PyHeapTypeObject, as_number);
7129 }
Yury Selivanov75445082015-05-11 22:57:16 -04007130 else if ((size_t)offset >= offsetof(PyHeapTypeObject, as_async)) {
7131 ptr = (char *)type->tp_as_async;
7132 offset -= offsetof(PyHeapTypeObject, as_async);
7133 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007134 else {
7135 ptr = (char *)type;
7136 }
7137 if (ptr != NULL)
7138 ptr += offset;
7139 return (void **)ptr;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00007140}
Guido van Rossumf040ede2001-08-07 16:40:56 +00007141
Guido van Rossumc334df52002-04-04 23:44:47 +00007142/* Length of array of slotdef pointers used to store slots with the
7143 same __name__. There should be at most MAX_EQUIV-1 slotdef entries with
7144 the same __name__, for any __name__. Since that's a static property, it is
7145 appropriate to declare fixed-size arrays for this. */
7146#define MAX_EQUIV 10
7147
7148/* Return a slot pointer for a given name, but ONLY if the attribute has
7149 exactly one slot function. The name must be an interned string. */
7150static void **
7151resolve_slotdups(PyTypeObject *type, PyObject *name)
7152{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007153 /* XXX Maybe this could be optimized more -- but is it worth it? */
Guido van Rossumc334df52002-04-04 23:44:47 +00007154
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007155 /* pname and ptrs act as a little cache */
7156 static PyObject *pname;
7157 static slotdef *ptrs[MAX_EQUIV];
7158 slotdef *p, **pp;
7159 void **res, **ptr;
Guido van Rossumc334df52002-04-04 23:44:47 +00007160
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007161 if (pname != name) {
7162 /* Collect all slotdefs that match name into ptrs. */
7163 pname = name;
7164 pp = ptrs;
7165 for (p = slotdefs; p->name_strobj; p++) {
7166 if (p->name_strobj == name)
7167 *pp++ = p;
7168 }
7169 *pp = NULL;
7170 }
Guido van Rossumc334df52002-04-04 23:44:47 +00007171
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007172 /* Look in all matching slots of the type; if exactly one of these has
7173 a filled-in slot, return its value. Otherwise return NULL. */
7174 res = NULL;
7175 for (pp = ptrs; *pp; pp++) {
7176 ptr = slotptr(type, (*pp)->offset);
7177 if (ptr == NULL || *ptr == NULL)
7178 continue;
7179 if (res != NULL)
7180 return NULL;
7181 res = ptr;
7182 }
7183 return res;
Guido van Rossumc334df52002-04-04 23:44:47 +00007184}
7185
Guido van Rossum8d24ee92003-03-24 23:49:49 +00007186/* Common code for update_slots_callback() and fixup_slot_dispatchers(). This
Guido van Rossumc334df52002-04-04 23:44:47 +00007187 does some incredibly complex thinking and then sticks something into the
7188 slot. (It sees if the adjacent slotdefs for the same slot have conflicting
7189 interests, and then stores a generic wrapper or a specific function into
7190 the slot.) Return a pointer to the next slotdef with a different offset,
7191 because that's convenient for fixup_slot_dispatchers(). */
7192static slotdef *
7193update_one_slot(PyTypeObject *type, slotdef *p)
7194{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007195 PyObject *descr;
7196 PyWrapperDescrObject *d;
7197 void *generic = NULL, *specific = NULL;
7198 int use_generic = 0;
7199 int offset = p->offset;
scoder2102c782017-10-01 10:37:47 +02007200 int error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007201 void **ptr = slotptr(type, offset);
Guido van Rossumc334df52002-04-04 23:44:47 +00007202
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007203 if (ptr == NULL) {
7204 do {
7205 ++p;
7206 } while (p->offset == offset);
7207 return p;
7208 }
scoder2102c782017-10-01 10:37:47 +02007209 /* We may end up clearing live exceptions below, so make sure it's ours. */
7210 assert(!PyErr_Occurred());
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007211 do {
scoder2102c782017-10-01 10:37:47 +02007212 /* Use faster uncached lookup as we won't get any cache hits during type setup. */
7213 descr = find_name_in_mro(type, p->name_strobj, &error);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007214 if (descr == NULL) {
scoder2102c782017-10-01 10:37:47 +02007215 if (error == -1) {
7216 /* It is unlikely by not impossible that there has been an exception
7217 during lookup. Since this function originally expected no errors,
7218 we ignore them here in order to keep up the interface. */
7219 PyErr_Clear();
7220 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007221 if (ptr == (void**)&type->tp_iternext) {
Trent Nelsonab02db22012-09-18 21:58:03 -04007222 specific = (void *)_PyObject_NextNotImplemented;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007223 }
7224 continue;
7225 }
Benjamin Peterson7b166872012-04-24 11:06:25 -04007226 if (Py_TYPE(descr) == &PyWrapperDescr_Type &&
7227 ((PyWrapperDescrObject *)descr)->d_base->name_strobj == p->name_strobj) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007228 void **tptr = resolve_slotdups(type, p->name_strobj);
7229 if (tptr == NULL || tptr == ptr)
7230 generic = p->function;
7231 d = (PyWrapperDescrObject *)descr;
7232 if (d->d_base->wrapper == p->wrapper &&
7233 PyType_IsSubtype(type, PyDescr_TYPE(d)))
7234 {
7235 if (specific == NULL ||
7236 specific == d->d_wrapped)
7237 specific = d->d_wrapped;
7238 else
7239 use_generic = 1;
7240 }
7241 }
7242 else if (Py_TYPE(descr) == &PyCFunction_Type &&
7243 PyCFunction_GET_FUNCTION(descr) ==
Serhiy Storchaka62be7422018-11-27 13:27:31 +02007244 (PyCFunction)(void(*)(void))tp_new_wrapper &&
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007245 ptr == (void**)&type->tp_new)
7246 {
7247 /* The __new__ wrapper is not a wrapper descriptor,
7248 so must be special-cased differently.
7249 If we don't do this, creating an instance will
7250 always use slot_tp_new which will look up
7251 __new__ in the MRO which will call tp_new_wrapper
7252 which will look through the base classes looking
7253 for a static base and call its tp_new (usually
7254 PyType_GenericNew), after performing various
7255 sanity checks and constructing a new argument
7256 list. Cut all that nonsense short -- this speeds
7257 up instance creation tremendously. */
Serhiy Storchaka49010ee2016-12-14 19:52:17 +02007258 specific = (void *)type->tp_new;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007259 /* XXX I'm not 100% sure that there isn't a hole
7260 in this reasoning that requires additional
7261 sanity checks. I'll buy the first person to
7262 point out a bug in this reasoning a beer. */
7263 }
7264 else if (descr == Py_None &&
7265 ptr == (void**)&type->tp_hash) {
7266 /* We specifically allow __hash__ to be set to None
7267 to prevent inheritance of the default
7268 implementation from object.__hash__ */
Trent Nelsonab02db22012-09-18 21:58:03 -04007269 specific = (void *)PyObject_HashNotImplemented;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007270 }
7271 else {
7272 use_generic = 1;
7273 generic = p->function;
7274 }
7275 } while ((++p)->offset == offset);
7276 if (specific && !use_generic)
7277 *ptr = specific;
7278 else
7279 *ptr = generic;
7280 return p;
Guido van Rossumc334df52002-04-04 23:44:47 +00007281}
7282
Guido van Rossum8d24ee92003-03-24 23:49:49 +00007283/* In the type, update the slots whose slotdefs are gathered in the pp array.
7284 This is a callback for update_subclasses(). */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00007285static int
Guido van Rossum8d24ee92003-03-24 23:49:49 +00007286update_slots_callback(PyTypeObject *type, void *data)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00007287{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007288 slotdef **pp = (slotdef **)data;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00007289
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007290 for (; *pp; pp++)
7291 update_one_slot(type, *pp);
7292 return 0;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00007293}
7294
Martin v. Löwis996b6712014-07-26 16:44:07 +02007295static int slotdefs_initialized = 0;
Guido van Rossumc334df52002-04-04 23:44:47 +00007296/* Initialize the slotdefs table by adding interned string objects for the
Martin v. Löwis5b561502014-07-26 15:25:04 +02007297 names. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00007298static void
Guido van Rossumd396b9c2001-10-13 20:02:41 +00007299init_slotdefs(void)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00007300{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007301 slotdef *p;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00007302
Martin v. Löwis996b6712014-07-26 16:44:07 +02007303 if (slotdefs_initialized)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007304 return;
7305 for (p = slotdefs; p->name; p++) {
Benjamin Peterson63952412013-04-01 17:41:41 -04007306 /* Slots must be ordered by their offset in the PyHeapTypeObject. */
7307 assert(!p[1].name || p->offset <= p[1].offset);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007308 p->name_strobj = PyUnicode_InternFromString(p->name);
Serhiy Storchakad8969852017-05-20 08:48:06 +03007309 if (!p->name_strobj || !PyUnicode_CHECK_INTERNED(p->name_strobj))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007310 Py_FatalError("Out of memory interning slotdef names");
7311 }
Martin v. Löwis996b6712014-07-26 16:44:07 +02007312 slotdefs_initialized = 1;
7313}
7314
7315/* Undo init_slotdefs, releasing the interned strings. */
Victor Stinner331a7262014-07-27 16:11:30 +02007316static void clear_slotdefs(void)
Martin v. Löwis996b6712014-07-26 16:44:07 +02007317{
7318 slotdef *p;
7319 for (p = slotdefs; p->name; p++) {
7320 Py_CLEAR(p->name_strobj);
7321 }
7322 slotdefs_initialized = 0;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00007323}
7324
Guido van Rossumc334df52002-04-04 23:44:47 +00007325/* Update the slots after assignment to a class (type) attribute. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00007326static int
7327update_slot(PyTypeObject *type, PyObject *name)
7328{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007329 slotdef *ptrs[MAX_EQUIV];
7330 slotdef *p;
7331 slotdef **pp;
7332 int offset;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00007333
Serhiy Storchakad8969852017-05-20 08:48:06 +03007334 assert(PyUnicode_CheckExact(name));
7335 assert(PyUnicode_CHECK_INTERNED(name));
7336
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007337 init_slotdefs();
7338 pp = ptrs;
7339 for (p = slotdefs; p->name; p++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007340 if (p->name_strobj == name)
7341 *pp++ = p;
7342 }
7343 *pp = NULL;
7344 for (pp = ptrs; *pp; pp++) {
7345 p = *pp;
7346 offset = p->offset;
7347 while (p > slotdefs && (p-1)->offset == offset)
7348 --p;
7349 *pp = p;
7350 }
7351 if (ptrs[0] == NULL)
7352 return 0; /* Not an attribute that affects any slots */
7353 return update_subclasses(type, name,
7354 update_slots_callback, (void *)ptrs);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00007355}
7356
Guido van Rossumc334df52002-04-04 23:44:47 +00007357/* Store the proper functions in the slot dispatches at class (type)
7358 definition time, based upon which operations the class overrides in its
7359 dict. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00007360static void
Guido van Rossum7b9144b2001-10-09 19:39:46 +00007361fixup_slot_dispatchers(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00007362{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007363 slotdef *p;
Tim Peters6d6c1a32001-08-02 04:15:00 +00007364
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007365 init_slotdefs();
7366 for (p = slotdefs; p->name; )
7367 p = update_one_slot(type, p);
Tim Peters6d6c1a32001-08-02 04:15:00 +00007368}
Guido van Rossum705f0f52001-08-24 16:47:00 +00007369
Michael W. Hudson98bbc492002-11-26 14:47:27 +00007370static void
7371update_all_slots(PyTypeObject* type)
7372{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007373 slotdef *p;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00007374
Stefan Behneld8b9e1f2019-02-20 18:29:24 +01007375 /* Clear the VALID_VERSION flag of 'type' and all its subclasses. */
7376 PyType_Modified(type);
7377
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007378 init_slotdefs();
7379 for (p = slotdefs; p->name; p++) {
7380 /* update_slot returns int but can't actually fail */
7381 update_slot(type, p->name_strobj);
7382 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +00007383}
7384
Nick Coghland78448e2016-07-30 16:26:03 +10007385/* Call __set_name__ on all descriptors in a newly generated type */
7386static int
7387set_names(PyTypeObject *type)
7388{
Serhiy Storchaka9ec07722016-11-29 09:54:17 +02007389 PyObject *names_to_set, *key, *value, *set_name, *tmp;
Nick Coghland78448e2016-07-30 16:26:03 +10007390 Py_ssize_t i = 0;
7391
Serhiy Storchaka9ec07722016-11-29 09:54:17 +02007392 names_to_set = PyDict_Copy(type->tp_dict);
7393 if (names_to_set == NULL)
7394 return -1;
7395
7396 while (PyDict_Next(names_to_set, &i, &key, &value)) {
Serhiy Storchaka4e624ca2017-06-01 08:18:25 +03007397 set_name = _PyObject_LookupSpecial(value, &PyId___set_name__);
Serhiy Storchakaafd02a42016-09-21 15:54:59 +03007398 if (set_name != NULL) {
7399 tmp = PyObject_CallFunctionObjArgs(set_name, type, key, NULL);
7400 Py_DECREF(set_name);
Serhiy Storchakad5d32d22016-10-21 17:13:31 +03007401 if (tmp == NULL) {
7402 _PyErr_FormatFromCause(PyExc_RuntimeError,
7403 "Error calling __set_name__ on '%.100s' instance %R "
7404 "in '%.100s'",
7405 value->ob_type->tp_name, key, type->tp_name);
Serhiy Storchaka9ec07722016-11-29 09:54:17 +02007406 Py_DECREF(names_to_set);
Nick Coghland78448e2016-07-30 16:26:03 +10007407 return -1;
Serhiy Storchakad5d32d22016-10-21 17:13:31 +03007408 }
Nick Coghland78448e2016-07-30 16:26:03 +10007409 else
7410 Py_DECREF(tmp);
7411 }
Serhiy Storchaka9ec07722016-11-29 09:54:17 +02007412 else if (PyErr_Occurred()) {
7413 Py_DECREF(names_to_set);
Serhiy Storchakaafd02a42016-09-21 15:54:59 +03007414 return -1;
Serhiy Storchaka9ec07722016-11-29 09:54:17 +02007415 }
Nick Coghland78448e2016-07-30 16:26:03 +10007416 }
7417
Serhiy Storchaka9ec07722016-11-29 09:54:17 +02007418 Py_DECREF(names_to_set);
Nick Coghland78448e2016-07-30 16:26:03 +10007419 return 0;
7420}
7421
7422/* Call __init_subclass__ on the parent of a newly generated type */
7423static int
7424init_subclass(PyTypeObject *type, PyObject *kwds)
7425{
Victor Stinner463b86a2016-08-22 23:33:13 +02007426 PyObject *super, *func, *result;
7427 PyObject *args[2] = {(PyObject *)type, (PyObject *)type};
Nick Coghland78448e2016-07-30 16:26:03 +10007428
Victor Stinner463b86a2016-08-22 23:33:13 +02007429 super = _PyObject_FastCall((PyObject *)&PySuper_Type, args, 2);
7430 if (super == NULL) {
Nick Coghland78448e2016-07-30 16:26:03 +10007431 return -1;
Victor Stinner253021d2016-08-20 02:37:41 +02007432 }
7433
Victor Stinner463b86a2016-08-22 23:33:13 +02007434 func = _PyObject_GetAttrId(super, &PyId___init_subclass__);
7435 Py_DECREF(super);
7436 if (func == NULL) {
Nick Coghland78448e2016-07-30 16:26:03 +10007437 return -1;
Victor Stinner463b86a2016-08-22 23:33:13 +02007438 }
Nick Coghland78448e2016-07-30 16:26:03 +10007439
Victor Stinner463b86a2016-08-22 23:33:13 +02007440
7441 result = _PyObject_FastCallDict(func, NULL, 0, kwds);
7442 Py_DECREF(func);
7443 if (result == NULL) {
7444 return -1;
7445 }
7446
7447 Py_DECREF(result);
Nick Coghland78448e2016-07-30 16:26:03 +10007448 return 0;
7449}
7450
Guido van Rossum8d24ee92003-03-24 23:49:49 +00007451/* recurse_down_subclasses() and update_subclasses() are mutually
7452 recursive functions to call a callback for all subclasses,
7453 but refraining from recursing into subclasses that define 'name'. */
7454
7455static int
7456update_subclasses(PyTypeObject *type, PyObject *name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007457 update_callback callback, void *data)
Guido van Rossum8d24ee92003-03-24 23:49:49 +00007458{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007459 if (callback(type, data) < 0)
7460 return -1;
7461 return recurse_down_subclasses(type, name, callback, data);
Guido van Rossum8d24ee92003-03-24 23:49:49 +00007462}
7463
7464static int
7465recurse_down_subclasses(PyTypeObject *type, PyObject *name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007466 update_callback callback, void *data)
Guido van Rossum8d24ee92003-03-24 23:49:49 +00007467{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007468 PyTypeObject *subclass;
7469 PyObject *ref, *subclasses, *dict;
Antoine Pitrou84745ab2013-10-29 21:31:25 +01007470 Py_ssize_t i;
Guido van Rossum8d24ee92003-03-24 23:49:49 +00007471
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007472 subclasses = type->tp_subclasses;
7473 if (subclasses == NULL)
7474 return 0;
Antoine Pitrou84745ab2013-10-29 21:31:25 +01007475 assert(PyDict_CheckExact(subclasses));
7476 i = 0;
7477 while (PyDict_Next(subclasses, &i, NULL, &ref)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007478 assert(PyWeakref_CheckRef(ref));
7479 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
7480 assert(subclass != NULL);
7481 if ((PyObject *)subclass == Py_None)
7482 continue;
7483 assert(PyType_Check(subclass));
7484 /* Avoid recursing down into unaffected classes */
7485 dict = subclass->tp_dict;
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02007486 if (dict != NULL && PyDict_Check(dict)) {
7487 if (PyDict_GetItemWithError(dict, name) != NULL) {
7488 continue;
7489 }
7490 if (PyErr_Occurred()) {
7491 return -1;
7492 }
7493 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007494 if (update_subclasses(subclass, name, callback, data) < 0)
7495 return -1;
7496 }
7497 return 0;
Guido van Rossum8d24ee92003-03-24 23:49:49 +00007498}
7499
Guido van Rossum6d204072001-10-21 00:44:31 +00007500/* This function is called by PyType_Ready() to populate the type's
7501 dictionary with method descriptors for function slots. For each
Guido van Rossum09638c12002-06-13 19:17:46 +00007502 function slot (like tp_repr) that's defined in the type, one or more
7503 corresponding descriptors are added in the type's tp_dict dictionary
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007504 under the appropriate name (like __repr__). Some function slots
Guido van Rossum09638c12002-06-13 19:17:46 +00007505 cause more than one descriptor to be added (for example, the nb_add
7506 slot adds both __add__ and __radd__ descriptors) and some function
7507 slots compete for the same descriptor (for example both sq_item and
7508 mp_subscript generate a __getitem__ descriptor).
7509
Ezio Melotti13925002011-03-16 11:05:33 +02007510 In the latter case, the first slotdef entry encountered wins. Since
Tim Petersbf9b2442003-03-23 05:35:36 +00007511 slotdef entries are sorted by the offset of the slot in the
Guido van Rossume5c691a2003-03-07 15:13:17 +00007512 PyHeapTypeObject, this gives us some control over disambiguating
Guido van Rossum8d24ee92003-03-24 23:49:49 +00007513 between competing slots: the members of PyHeapTypeObject are listed
7514 from most general to least general, so the most general slot is
7515 preferred. In particular, because as_mapping comes before as_sequence,
7516 for a type that defines both mp_subscript and sq_item, mp_subscript
7517 wins.
Guido van Rossum09638c12002-06-13 19:17:46 +00007518
7519 This only adds new descriptors and doesn't overwrite entries in
7520 tp_dict that were previously defined. The descriptors contain a
7521 reference to the C function they must call, so that it's safe if they
7522 are copied into a subtype's __dict__ and the subtype has a different
7523 C function in its slot -- calling the method defined by the
7524 descriptor will call the C function that was used to create it,
7525 rather than the C function present in the slot when it is called.
7526 (This is important because a subtype may have a C function in the
7527 slot that calls the method from the dictionary, and we want to avoid
7528 infinite recursion here.) */
Guido van Rossum6d204072001-10-21 00:44:31 +00007529
7530static int
7531add_operators(PyTypeObject *type)
7532{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007533 PyObject *dict = type->tp_dict;
7534 slotdef *p;
7535 PyObject *descr;
7536 void **ptr;
Guido van Rossum6d204072001-10-21 00:44:31 +00007537
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007538 init_slotdefs();
7539 for (p = slotdefs; p->name; p++) {
7540 if (p->wrapper == NULL)
7541 continue;
7542 ptr = slotptr(type, p->offset);
7543 if (!ptr || !*ptr)
7544 continue;
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02007545 if (PyDict_GetItemWithError(dict, p->name_strobj))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007546 continue;
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02007547 if (PyErr_Occurred()) {
7548 return -1;
7549 }
Trent Nelsonab02db22012-09-18 21:58:03 -04007550 if (*ptr == (void *)PyObject_HashNotImplemented) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007551 /* Classes may prevent the inheritance of the tp_hash
7552 slot by storing PyObject_HashNotImplemented in it. Make it
7553 visible as a None value for the __hash__ attribute. */
7554 if (PyDict_SetItem(dict, p->name_strobj, Py_None) < 0)
7555 return -1;
7556 }
7557 else {
7558 descr = PyDescr_NewWrapper(type, p, *ptr);
7559 if (descr == NULL)
7560 return -1;
Benjamin Peterson27007dc2016-07-06 23:26:32 -07007561 if (PyDict_SetItem(dict, p->name_strobj, descr) < 0) {
7562 Py_DECREF(descr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007563 return -1;
Benjamin Peterson27007dc2016-07-06 23:26:32 -07007564 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007565 Py_DECREF(descr);
7566 }
7567 }
7568 if (type->tp_new != NULL) {
7569 if (add_tp_new_wrapper(type) < 0)
7570 return -1;
7571 }
7572 return 0;
Guido van Rossum6d204072001-10-21 00:44:31 +00007573}
7574
Guido van Rossum705f0f52001-08-24 16:47:00 +00007575
7576/* Cooperative 'super' */
7577
7578typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007579 PyObject_HEAD
7580 PyTypeObject *type;
7581 PyObject *obj;
7582 PyTypeObject *obj_type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00007583} superobject;
7584
Guido van Rossum6f799372001-09-20 20:46:19 +00007585static PyMemberDef super_members[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007586 {"__thisclass__", T_OBJECT, offsetof(superobject, type), READONLY,
7587 "the class invoking super()"},
7588 {"__self__", T_OBJECT, offsetof(superobject, obj), READONLY,
7589 "the instance invoking super(); may be None"},
7590 {"__self_class__", T_OBJECT, offsetof(superobject, obj_type), READONLY,
7591 "the type of the instance invoking super(); may be None"},
7592 {0}
Guido van Rossum41eb14d2001-08-30 23:13:11 +00007593};
7594
Guido van Rossum705f0f52001-08-24 16:47:00 +00007595static void
7596super_dealloc(PyObject *self)
7597{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007598 superobject *su = (superobject *)self;
Guido van Rossum705f0f52001-08-24 16:47:00 +00007599
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007600 _PyObject_GC_UNTRACK(self);
7601 Py_XDECREF(su->obj);
7602 Py_XDECREF(su->type);
7603 Py_XDECREF(su->obj_type);
7604 Py_TYPE(self)->tp_free(self);
Guido van Rossum705f0f52001-08-24 16:47:00 +00007605}
7606
7607static PyObject *
Guido van Rossum41eb14d2001-08-30 23:13:11 +00007608super_repr(PyObject *self)
7609{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007610 superobject *su = (superobject *)self;
Guido van Rossum41eb14d2001-08-30 23:13:11 +00007611
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007612 if (su->obj_type)
7613 return PyUnicode_FromFormat(
7614 "<super: <class '%s'>, <%s object>>",
7615 su->type ? su->type->tp_name : "NULL",
7616 su->obj_type->tp_name);
7617 else
7618 return PyUnicode_FromFormat(
7619 "<super: <class '%s'>, NULL>",
7620 su->type ? su->type->tp_name : "NULL");
Guido van Rossum41eb14d2001-08-30 23:13:11 +00007621}
7622
7623static PyObject *
Guido van Rossum705f0f52001-08-24 16:47:00 +00007624super_getattro(PyObject *self, PyObject *name)
7625{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007626 superobject *su = (superobject *)self;
Benjamin Peterson104b9e02015-02-05 22:29:14 -05007627 PyTypeObject *starttype;
7628 PyObject *mro;
7629 Py_ssize_t i, n;
Guido van Rossum705f0f52001-08-24 16:47:00 +00007630
Benjamin Peterson104b9e02015-02-05 22:29:14 -05007631 starttype = su->obj_type;
7632 if (starttype == NULL)
7633 goto skip;
7634
7635 /* We want __class__ to return the class of the super object
7636 (i.e. super, or a subclass), not the class of su->obj. */
7637 if (PyUnicode_Check(name) &&
7638 PyUnicode_GET_LENGTH(name) == 9 &&
Serhiy Storchakaf5894dd2016-11-16 15:40:39 +02007639 _PyUnicode_EqualToASCIIId(name, &PyId___class__))
Benjamin Peterson104b9e02015-02-05 22:29:14 -05007640 goto skip;
7641
7642 mro = starttype->tp_mro;
7643 if (mro == NULL)
7644 goto skip;
7645
7646 assert(PyTuple_Check(mro));
7647 n = PyTuple_GET_SIZE(mro);
7648
7649 /* No need to check the last one: it's gonna be skipped anyway. */
7650 for (i = 0; i+1 < n; i++) {
7651 if ((PyObject *)(su->type) == PyTuple_GET_ITEM(mro, i))
7652 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007653 }
Benjamin Peterson104b9e02015-02-05 22:29:14 -05007654 i++; /* skip su->type (if any) */
7655 if (i >= n)
7656 goto skip;
Guido van Rossum76ba09f2003-04-16 19:40:58 +00007657
Benjamin Peterson104b9e02015-02-05 22:29:14 -05007658 /* keep a strong reference to mro because starttype->tp_mro can be
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02007659 replaced during PyDict_GetItemWithError(dict, name) */
Benjamin Peterson104b9e02015-02-05 22:29:14 -05007660 Py_INCREF(mro);
7661 do {
7662 PyObject *res, *tmp, *dict;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007663 descrgetfunc f;
Guido van Rossum705f0f52001-08-24 16:47:00 +00007664
Benjamin Peterson104b9e02015-02-05 22:29:14 -05007665 tmp = PyTuple_GET_ITEM(mro, i);
7666 assert(PyType_Check(tmp));
Guido van Rossum155db9a2002-04-02 17:53:47 +00007667
Benjamin Peterson104b9e02015-02-05 22:29:14 -05007668 dict = ((PyTypeObject *)tmp)->tp_dict;
7669 assert(dict != NULL && PyDict_Check(dict));
7670
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02007671 res = PyDict_GetItemWithError(dict, name);
Benjamin Peterson104b9e02015-02-05 22:29:14 -05007672 if (res != NULL) {
7673 Py_INCREF(res);
7674
7675 f = Py_TYPE(res)->tp_descr_get;
7676 if (f != NULL) {
7677 tmp = f(res,
7678 /* Only pass 'obj' param if this is instance-mode super
7679 (See SF ID #743627) */
7680 (su->obj == (PyObject *)starttype) ? NULL : su->obj,
7681 (PyObject *)starttype);
7682 Py_DECREF(res);
7683 res = tmp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007684 }
Benjamin Peterson104b9e02015-02-05 22:29:14 -05007685
7686 Py_DECREF(mro);
7687 return res;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007688 }
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02007689 else if (PyErr_Occurred()) {
Benjamin Petersond5a551c2019-02-25 23:12:10 -08007690 Py_DECREF(mro);
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02007691 return NULL;
7692 }
Benjamin Peterson104b9e02015-02-05 22:29:14 -05007693
7694 i++;
7695 } while (i < n);
7696 Py_DECREF(mro);
7697
7698 skip:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007699 return PyObject_GenericGetAttr(self, name);
Guido van Rossum705f0f52001-08-24 16:47:00 +00007700}
7701
Guido van Rossuma89d10e2003-02-12 03:58:38 +00007702static PyTypeObject *
Guido van Rossum5b443c62001-12-03 15:38:28 +00007703supercheck(PyTypeObject *type, PyObject *obj)
7704{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007705 /* Check that a super() call makes sense. Return a type object.
Guido van Rossuma89d10e2003-02-12 03:58:38 +00007706
Florent Xiclunaaa6c1d22011-12-12 18:54:29 +01007707 obj can be a class, or an instance of one:
Guido van Rossuma89d10e2003-02-12 03:58:38 +00007708
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007709 - If it is a class, it must be a subclass of 'type'. This case is
7710 used for class methods; the return value is obj.
Guido van Rossuma89d10e2003-02-12 03:58:38 +00007711
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007712 - If it is an instance, it must be an instance of 'type'. This is
7713 the normal case; the return value is obj.__class__.
Guido van Rossuma89d10e2003-02-12 03:58:38 +00007714
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007715 But... when obj is an instance, we want to allow for the case where
7716 Py_TYPE(obj) is not a subclass of type, but obj.__class__ is!
7717 This will allow using super() with a proxy for obj.
7718 */
Guido van Rossuma89d10e2003-02-12 03:58:38 +00007719
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007720 /* Check for first bullet above (special case) */
7721 if (PyType_Check(obj) && PyType_IsSubtype((PyTypeObject *)obj, type)) {
7722 Py_INCREF(obj);
7723 return (PyTypeObject *)obj;
7724 }
Guido van Rossum8e80a722003-02-18 19:22:22 +00007725
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007726 /* Normal case */
7727 if (PyType_IsSubtype(Py_TYPE(obj), type)) {
7728 Py_INCREF(Py_TYPE(obj));
7729 return Py_TYPE(obj);
7730 }
7731 else {
7732 /* Try the slow way */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007733 PyObject *class_attr;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00007734
Martin v. Löwisbfc6d742011-10-13 20:03:57 +02007735 class_attr = _PyObject_GetAttrId(obj, &PyId___class__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007736 if (class_attr != NULL &&
7737 PyType_Check(class_attr) &&
7738 (PyTypeObject *)class_attr != Py_TYPE(obj))
7739 {
7740 int ok = PyType_IsSubtype(
7741 (PyTypeObject *)class_attr, type);
7742 if (ok)
7743 return (PyTypeObject *)class_attr;
7744 }
Guido van Rossuma89d10e2003-02-12 03:58:38 +00007745
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007746 if (class_attr == NULL)
7747 PyErr_Clear();
7748 else
7749 Py_DECREF(class_attr);
7750 }
Guido van Rossuma89d10e2003-02-12 03:58:38 +00007751
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007752 PyErr_SetString(PyExc_TypeError,
7753 "super(type, obj): "
7754 "obj must be an instance or subtype of type");
7755 return NULL;
Guido van Rossum5b443c62001-12-03 15:38:28 +00007756}
7757
Guido van Rossum705f0f52001-08-24 16:47:00 +00007758static PyObject *
7759super_descr_get(PyObject *self, PyObject *obj, PyObject *type)
7760{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007761 superobject *su = (superobject *)self;
7762 superobject *newobj;
Guido van Rossum705f0f52001-08-24 16:47:00 +00007763
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007764 if (obj == NULL || obj == Py_None || su->obj != NULL) {
7765 /* Not binding to an object, or already bound */
7766 Py_INCREF(self);
7767 return self;
7768 }
7769 if (Py_TYPE(su) != &PySuper_Type)
7770 /* If su is an instance of a (strict) subclass of super,
7771 call its type */
7772 return PyObject_CallFunctionObjArgs((PyObject *)Py_TYPE(su),
7773 su->type, obj, NULL);
7774 else {
7775 /* Inline the common case */
7776 PyTypeObject *obj_type = supercheck(su->type, obj);
7777 if (obj_type == NULL)
7778 return NULL;
7779 newobj = (superobject *)PySuper_Type.tp_new(&PySuper_Type,
7780 NULL, NULL);
7781 if (newobj == NULL)
7782 return NULL;
7783 Py_INCREF(su->type);
7784 Py_INCREF(obj);
7785 newobj->type = su->type;
7786 newobj->obj = obj;
7787 newobj->obj_type = obj_type;
7788 return (PyObject *)newobj;
7789 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00007790}
7791
7792static int
7793super_init(PyObject *self, PyObject *args, PyObject *kwds)
7794{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007795 superobject *su = (superobject *)self;
7796 PyTypeObject *type = NULL;
7797 PyObject *obj = NULL;
7798 PyTypeObject *obj_type = NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00007799
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007800 if (!_PyArg_NoKeywords("super", kwds))
7801 return -1;
7802 if (!PyArg_ParseTuple(args, "|O!O:super", &PyType_Type, &type, &obj))
7803 return -1;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00007804
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007805 if (type == NULL) {
7806 /* Call super(), without args -- fill in from __class__
7807 and first local variable on the stack. */
Victor Stinner1c6970f2014-05-13 01:32:36 +02007808 PyFrameObject *f;
7809 PyCodeObject *co;
Victor Stinner0fcab4a2011-01-04 12:59:15 +00007810 Py_ssize_t i, n;
Victor Stinner50b48572018-11-01 01:51:40 +01007811 f = _PyThreadState_GET()->frame;
Victor Stinner1c6970f2014-05-13 01:32:36 +02007812 if (f == NULL) {
7813 PyErr_SetString(PyExc_RuntimeError,
7814 "super(): no current frame");
7815 return -1;
7816 }
7817 co = f->f_code;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007818 if (co == NULL) {
Benjamin Peterson6a42bd62012-09-01 23:04:38 -04007819 PyErr_SetString(PyExc_RuntimeError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007820 "super(): no code object");
7821 return -1;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00007822 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007823 if (co->co_argcount == 0) {
Benjamin Peterson6a42bd62012-09-01 23:04:38 -04007824 PyErr_SetString(PyExc_RuntimeError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007825 "super(): no arguments");
7826 return -1;
7827 }
7828 obj = f->f_localsplus[0];
Benjamin Peterson159ae412013-05-12 18:16:06 -05007829 if (obj == NULL && co->co_cell2arg) {
7830 /* The first argument might be a cell. */
7831 n = PyTuple_GET_SIZE(co->co_cellvars);
7832 for (i = 0; i < n; i++) {
7833 if (co->co_cell2arg[i] == 0) {
7834 PyObject *cell = f->f_localsplus[co->co_nlocals + i];
7835 assert(PyCell_Check(cell));
7836 obj = PyCell_GET(cell);
7837 break;
7838 }
7839 }
Guido van Rossum6832c812013-05-10 08:47:42 -07007840 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007841 if (obj == NULL) {
Benjamin Peterson6a42bd62012-09-01 23:04:38 -04007842 PyErr_SetString(PyExc_RuntimeError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007843 "super(): arg[0] deleted");
7844 return -1;
7845 }
7846 if (co->co_freevars == NULL)
7847 n = 0;
7848 else {
7849 assert(PyTuple_Check(co->co_freevars));
7850 n = PyTuple_GET_SIZE(co->co_freevars);
7851 }
7852 for (i = 0; i < n; i++) {
7853 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
7854 assert(PyUnicode_Check(name));
Serhiy Storchakaf5894dd2016-11-16 15:40:39 +02007855 if (_PyUnicode_EqualToASCIIId(name, &PyId___class__)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007856 Py_ssize_t index = co->co_nlocals +
7857 PyTuple_GET_SIZE(co->co_cellvars) + i;
7858 PyObject *cell = f->f_localsplus[index];
7859 if (cell == NULL || !PyCell_Check(cell)) {
Benjamin Peterson6a42bd62012-09-01 23:04:38 -04007860 PyErr_SetString(PyExc_RuntimeError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007861 "super(): bad __class__ cell");
7862 return -1;
7863 }
7864 type = (PyTypeObject *) PyCell_GET(cell);
7865 if (type == NULL) {
Benjamin Peterson6a42bd62012-09-01 23:04:38 -04007866 PyErr_SetString(PyExc_RuntimeError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007867 "super(): empty __class__ cell");
7868 return -1;
7869 }
7870 if (!PyType_Check(type)) {
Benjamin Peterson6a42bd62012-09-01 23:04:38 -04007871 PyErr_Format(PyExc_RuntimeError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007872 "super(): __class__ is not a type (%s)",
7873 Py_TYPE(type)->tp_name);
7874 return -1;
7875 }
7876 break;
7877 }
7878 }
7879 if (type == NULL) {
Benjamin Peterson6a42bd62012-09-01 23:04:38 -04007880 PyErr_SetString(PyExc_RuntimeError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007881 "super(): __class__ cell not found");
7882 return -1;
7883 }
7884 }
Guido van Rossumcd16bf62007-06-13 18:07:49 +00007885
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007886 if (obj == Py_None)
7887 obj = NULL;
7888 if (obj != NULL) {
7889 obj_type = supercheck(type, obj);
7890 if (obj_type == NULL)
7891 return -1;
7892 Py_INCREF(obj);
7893 }
7894 Py_INCREF(type);
Serhiy Storchaka3d749762016-04-13 15:27:33 +03007895 Py_XSETREF(su->type, type);
7896 Py_XSETREF(su->obj, obj);
7897 Py_XSETREF(su->obj_type, obj_type);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007898 return 0;
Guido van Rossum705f0f52001-08-24 16:47:00 +00007899}
7900
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007901PyDoc_STRVAR(super_doc,
Guido van Rossumcd16bf62007-06-13 18:07:49 +00007902"super() -> same as super(__class__, <first argument>)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00007903"super(type) -> unbound super object\n"
7904"super(type, obj) -> bound super object; requires isinstance(obj, type)\n"
Guido van Rossume705ef12001-08-29 15:47:06 +00007905"super(type, type2) -> bound super object; requires issubclass(type2, type)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00007906"Typical use to call a cooperative superclass method:\n"
7907"class C(B):\n"
7908" def meth(self, arg):\n"
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007909" super().meth(arg)\n"
Guido van Rossumcd16bf62007-06-13 18:07:49 +00007910"This works for class methods too:\n"
7911"class C(B):\n"
7912" @classmethod\n"
7913" def cmeth(cls, arg):\n"
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007914" super().cmeth(arg)\n");
Guido van Rossum705f0f52001-08-24 16:47:00 +00007915
Guido van Rossum048eb752001-10-02 21:24:57 +00007916static int
7917super_traverse(PyObject *self, visitproc visit, void *arg)
7918{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007919 superobject *su = (superobject *)self;
Guido van Rossum048eb752001-10-02 21:24:57 +00007920
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007921 Py_VISIT(su->obj);
7922 Py_VISIT(su->type);
7923 Py_VISIT(su->obj_type);
Guido van Rossum048eb752001-10-02 21:24:57 +00007924
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007925 return 0;
Guido van Rossum048eb752001-10-02 21:24:57 +00007926}
7927
Guido van Rossum705f0f52001-08-24 16:47:00 +00007928PyTypeObject PySuper_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007929 PyVarObject_HEAD_INIT(&PyType_Type, 0)
7930 "super", /* tp_name */
7931 sizeof(superobject), /* tp_basicsize */
7932 0, /* tp_itemsize */
7933 /* methods */
7934 super_dealloc, /* tp_dealloc */
7935 0, /* tp_print */
7936 0, /* tp_getattr */
7937 0, /* tp_setattr */
7938 0, /* tp_reserved */
7939 super_repr, /* tp_repr */
7940 0, /* tp_as_number */
7941 0, /* tp_as_sequence */
7942 0, /* tp_as_mapping */
7943 0, /* tp_hash */
7944 0, /* tp_call */
7945 0, /* tp_str */
7946 super_getattro, /* tp_getattro */
7947 0, /* tp_setattro */
7948 0, /* tp_as_buffer */
7949 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
7950 Py_TPFLAGS_BASETYPE, /* tp_flags */
7951 super_doc, /* tp_doc */
7952 super_traverse, /* tp_traverse */
7953 0, /* tp_clear */
7954 0, /* tp_richcompare */
7955 0, /* tp_weaklistoffset */
7956 0, /* tp_iter */
7957 0, /* tp_iternext */
7958 0, /* tp_methods */
7959 super_members, /* tp_members */
7960 0, /* tp_getset */
7961 0, /* tp_base */
7962 0, /* tp_dict */
7963 super_descr_get, /* tp_descr_get */
7964 0, /* tp_descr_set */
7965 0, /* tp_dictoffset */
7966 super_init, /* tp_init */
7967 PyType_GenericAlloc, /* tp_alloc */
7968 PyType_GenericNew, /* tp_new */
7969 PyObject_GC_Del, /* tp_free */
Guido van Rossum705f0f52001-08-24 16:47:00 +00007970};