blob: 329261b037320ac62deac8f1f42a0d046f382183 [file] [log] [blame]
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001/* Type object implementation */
2
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003#include "Python.h"
Guido van Rossumcd16bf62007-06-13 18:07:49 +00004#include "frameobject.h"
Tim Peters6d6c1a32001-08-02 04:15:00 +00005#include "structmember.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00006
Guido van Rossum9923ffe2002-06-04 19:52:53 +00007#include <ctype.h>
8
Christian Heimesa62da1d2008-01-12 19:39:10 +00009
10/* Support type attribute cache */
11
12/* The cache can keep references to the names alive for longer than
13 they normally would. This is why the maximum size is limited to
14 MCACHE_MAX_ATTR_SIZE, since it might be a problem if very large
15 strings are used as attribute names. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000016#define MCACHE_MAX_ATTR_SIZE 100
Antoine Pitrou2a40e362014-11-15 00:56:27 +010017#define MCACHE_SIZE_EXP 12
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000018#define MCACHE_HASH(version, name_hash) \
Antoine Pitrou2a40e362014-11-15 00:56:27 +010019 (((unsigned int)(version) ^ (unsigned int)(name_hash)) \
20 & ((1 << MCACHE_SIZE_EXP) - 1))
21
Christian Heimesa62da1d2008-01-12 19:39:10 +000022#define MCACHE_HASH_METHOD(type, name) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000023 MCACHE_HASH((type)->tp_version_tag, \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020024 ((PyASCIIObject *)(name))->hash)
Christian Heimesa62da1d2008-01-12 19:39:10 +000025#define MCACHE_CACHEABLE_NAME(name) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000026 PyUnicode_CheckExact(name) && \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020027 PyUnicode_READY(name) != -1 && \
28 PyUnicode_GET_LENGTH(name) <= MCACHE_MAX_ATTR_SIZE
Christian Heimesa62da1d2008-01-12 19:39:10 +000029
30struct method_cache_entry {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000031 unsigned int version;
32 PyObject *name; /* reference to exactly a str or None */
33 PyObject *value; /* borrowed */
Christian Heimesa62da1d2008-01-12 19:39:10 +000034};
35
36static struct method_cache_entry method_cache[1 << MCACHE_SIZE_EXP];
37static unsigned int next_version_tag = 0;
Christian Heimes26855632008-01-27 23:50:43 +000038
Antoine Pitrou2a40e362014-11-15 00:56:27 +010039#define MCACHE_STATS 0
40
41#if MCACHE_STATS
42static size_t method_cache_hits = 0;
43static size_t method_cache_misses = 0;
44static size_t method_cache_collisions = 0;
45#endif
46
Martin v. Löwise75fc142013-11-07 18:46:53 +010047/* alphabetical order */
48_Py_IDENTIFIER(__abstractmethods__);
Martin v. Löwisbd928fe2011-10-14 10:20:37 +020049_Py_IDENTIFIER(__class__);
Martin v. Löwise75fc142013-11-07 18:46:53 +010050_Py_IDENTIFIER(__delitem__);
Victor Stinner3c1e4812012-03-26 22:10:51 +020051_Py_IDENTIFIER(__dict__);
52_Py_IDENTIFIER(__doc__);
Victor Stinner3c1e4812012-03-26 22:10:51 +020053_Py_IDENTIFIER(__getattribute__);
Martin v. Löwise75fc142013-11-07 18:46:53 +010054_Py_IDENTIFIER(__getitem__);
Victor Stinner3c1e4812012-03-26 22:10:51 +020055_Py_IDENTIFIER(__hash__);
Nick Coghland78448e2016-07-30 16:26:03 +100056_Py_IDENTIFIER(__init_subclass__);
Martin v. Löwise75fc142013-11-07 18:46:53 +010057_Py_IDENTIFIER(__len__);
Victor Stinner3c1e4812012-03-26 22:10:51 +020058_Py_IDENTIFIER(__module__);
59_Py_IDENTIFIER(__name__);
60_Py_IDENTIFIER(__new__);
Nick Coghland78448e2016-07-30 16:26:03 +100061_Py_IDENTIFIER(__set_name__);
Martin v. Löwise75fc142013-11-07 18:46:53 +010062_Py_IDENTIFIER(__setitem__);
Victor Stinnerbd303c12013-11-07 23:07:29 +010063_Py_IDENTIFIER(builtins);
Victor Stinner3c1e4812012-03-26 22:10:51 +020064
65static PyObject *
Martin v. Löwis9c564092012-06-23 23:20:45 +020066slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
67
Martin v. Löwis996b6712014-07-26 16:44:07 +020068static void
Victor Stinner331a7262014-07-27 16:11:30 +020069clear_slotdefs(void);
Martin v. Löwis996b6712014-07-26 16:44:07 +020070
Larry Hastings5c661892014-01-24 06:17:25 -080071/*
Larry Hastings2623c8c2014-02-08 22:15:29 -080072 * finds the beginning of the docstring's introspection signature.
Larry Hastings5c661892014-01-24 06:17:25 -080073 * if present, returns a pointer pointing to the first '('.
74 * otherwise returns NULL.
Larry Hastings2623c8c2014-02-08 22:15:29 -080075 *
76 * doesn't guarantee that the signature is valid, only that it
77 * has a valid prefix. (the signature must also pass skip_signature.)
Larry Hastings5c661892014-01-24 06:17:25 -080078 */
79static const char *
Larry Hastings2623c8c2014-02-08 22:15:29 -080080find_signature(const char *name, const char *doc)
Larry Hastings5c661892014-01-24 06:17:25 -080081{
Larry Hastings2623c8c2014-02-08 22:15:29 -080082 const char *dot;
83 size_t length;
84
85 if (!doc)
86 return NULL;
87
88 assert(name != NULL);
89
90 /* for dotted names like classes, only use the last component */
91 dot = strrchr(name, '.');
92 if (dot)
93 name = dot + 1;
94
95 length = strlen(name);
96 if (strncmp(doc, name, length))
97 return NULL;
98 doc += length;
99 if (*doc != '(')
100 return NULL;
101 return doc;
Larry Hastings5c661892014-01-24 06:17:25 -0800102}
103
Larry Hastings2623c8c2014-02-08 22:15:29 -0800104#define SIGNATURE_END_MARKER ")\n--\n\n"
105#define SIGNATURE_END_MARKER_LENGTH 6
Larry Hastings5c661892014-01-24 06:17:25 -0800106/*
Larry Hastings2623c8c2014-02-08 22:15:29 -0800107 * skips past the end of the docstring's instrospection signature.
108 * (assumes doc starts with a valid signature prefix.)
Larry Hastings5c661892014-01-24 06:17:25 -0800109 */
110static const char *
111skip_signature(const char *doc)
112{
Larry Hastings2623c8c2014-02-08 22:15:29 -0800113 while (*doc) {
114 if ((*doc == *SIGNATURE_END_MARKER) &&
115 !strncmp(doc, SIGNATURE_END_MARKER, SIGNATURE_END_MARKER_LENGTH))
116 return doc + SIGNATURE_END_MARKER_LENGTH;
117 if ((*doc == '\n') && (doc[1] == '\n'))
118 return NULL;
Larry Hastings5c661892014-01-24 06:17:25 -0800119 doc++;
Larry Hastings2623c8c2014-02-08 22:15:29 -0800120 }
121 return NULL;
Larry Hastings5c661892014-01-24 06:17:25 -0800122}
123
124static const char *
Larry Hastings2623c8c2014-02-08 22:15:29 -0800125_PyType_DocWithoutSignature(const char *name, const char *internal_doc)
Larry Hastings5c661892014-01-24 06:17:25 -0800126{
Larry Hastings2623c8c2014-02-08 22:15:29 -0800127 const char *doc = find_signature(name, internal_doc);
Larry Hastings5c661892014-01-24 06:17:25 -0800128
Larry Hastings2623c8c2014-02-08 22:15:29 -0800129 if (doc) {
130 doc = skip_signature(doc);
131 if (doc)
132 return doc;
133 }
Larry Hastings5c661892014-01-24 06:17:25 -0800134 return internal_doc;
135}
136
137PyObject *
Larry Hastings2623c8c2014-02-08 22:15:29 -0800138_PyType_GetDocFromInternalDoc(const char *name, const char *internal_doc)
Larry Hastings5c661892014-01-24 06:17:25 -0800139{
Larry Hastings2623c8c2014-02-08 22:15:29 -0800140 const char *doc = _PyType_DocWithoutSignature(name, internal_doc);
Larry Hastings5c661892014-01-24 06:17:25 -0800141
Zachary Ware8ef887c2015-04-13 18:22:35 -0500142 if (!doc || *doc == '\0') {
Larry Hastings5c661892014-01-24 06:17:25 -0800143 Py_INCREF(Py_None);
144 return Py_None;
145 }
146
147 return PyUnicode_FromString(doc);
148}
149
150PyObject *
Larry Hastings2623c8c2014-02-08 22:15:29 -0800151_PyType_GetTextSignatureFromInternalDoc(const char *name, const char *internal_doc)
Larry Hastings5c661892014-01-24 06:17:25 -0800152{
Larry Hastings2623c8c2014-02-08 22:15:29 -0800153 const char *start = find_signature(name, internal_doc);
154 const char *end;
Larry Hastings5c661892014-01-24 06:17:25 -0800155
Larry Hastings2623c8c2014-02-08 22:15:29 -0800156 if (start)
157 end = skip_signature(start);
158 else
159 end = NULL;
160 if (!end) {
Larry Hastings5c661892014-01-24 06:17:25 -0800161 Py_INCREF(Py_None);
162 return Py_None;
163 }
164
Larry Hastings2623c8c2014-02-08 22:15:29 -0800165 /* back "end" up until it points just past the final ')' */
166 end -= SIGNATURE_END_MARKER_LENGTH - 1;
167 assert((end - start) >= 2); /* should be "()" at least */
168 assert(end[-1] == ')');
169 assert(end[0] == '\n');
170 return PyUnicode_FromStringAndSize(start, end - start);
Larry Hastings5c661892014-01-24 06:17:25 -0800171}
172
Christian Heimes26855632008-01-27 23:50:43 +0000173unsigned int
174PyType_ClearCache(void)
175{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000176 Py_ssize_t i;
177 unsigned int cur_version_tag = next_version_tag - 1;
178
Antoine Pitrou2a40e362014-11-15 00:56:27 +0100179#if MCACHE_STATS
180 size_t total = method_cache_hits + method_cache_collisions + method_cache_misses;
181 fprintf(stderr, "-- Method cache hits = %zd (%d%%)\n",
182 method_cache_hits, (int) (100.0 * method_cache_hits / total));
183 fprintf(stderr, "-- Method cache true misses = %zd (%d%%)\n",
184 method_cache_misses, (int) (100.0 * method_cache_misses / total));
185 fprintf(stderr, "-- Method cache collisions = %zd (%d%%)\n",
186 method_cache_collisions, (int) (100.0 * method_cache_collisions / total));
187 fprintf(stderr, "-- Method cache size = %zd KB\n",
188 sizeof(method_cache) / 1024);
189#endif
190
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000191 for (i = 0; i < (1 << MCACHE_SIZE_EXP); i++) {
192 method_cache[i].version = 0;
193 Py_CLEAR(method_cache[i].name);
194 method_cache[i].value = NULL;
195 }
196 next_version_tag = 0;
197 /* mark all version tags as invalid */
198 PyType_Modified(&PyBaseObject_Type);
199 return cur_version_tag;
Christian Heimes26855632008-01-27 23:50:43 +0000200}
Christian Heimesa62da1d2008-01-12 19:39:10 +0000201
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000202void
Antoine Pitrou957a23b2013-05-04 20:45:02 +0200203_PyType_Fini(void)
204{
205 PyType_ClearCache();
Martin v. Löwis996b6712014-07-26 16:44:07 +0200206 clear_slotdefs();
Antoine Pitrou957a23b2013-05-04 20:45:02 +0200207}
208
209void
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000210PyType_Modified(PyTypeObject *type)
Christian Heimesa62da1d2008-01-12 19:39:10 +0000211{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000212 /* Invalidate any cached data for the specified type and all
213 subclasses. This function is called after the base
214 classes, mro, or attributes of the type are altered.
Christian Heimesa62da1d2008-01-12 19:39:10 +0000215
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000216 Invariants:
Christian Heimesa62da1d2008-01-12 19:39:10 +0000217
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000218 - Py_TPFLAGS_VALID_VERSION_TAG is never set if
219 Py_TPFLAGS_HAVE_VERSION_TAG is not set (e.g. on type
220 objects coming from non-recompiled extension modules)
Christian Heimesa62da1d2008-01-12 19:39:10 +0000221
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000222 - before Py_TPFLAGS_VALID_VERSION_TAG can be set on a type,
223 it must first be set on all super types.
Christian Heimesa62da1d2008-01-12 19:39:10 +0000224
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000225 This function clears the Py_TPFLAGS_VALID_VERSION_TAG of a
226 type (so it must first clear it on all subclasses). The
227 tp_version_tag value is meaningless unless this flag is set.
228 We don't assign new version tags eagerly, but only as
229 needed.
230 */
231 PyObject *raw, *ref;
Antoine Pitrou84745ab2013-10-29 21:31:25 +0100232 Py_ssize_t i;
Christian Heimesa62da1d2008-01-12 19:39:10 +0000233
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000234 if (!PyType_HasFeature(type, Py_TPFLAGS_VALID_VERSION_TAG))
235 return;
Christian Heimesa62da1d2008-01-12 19:39:10 +0000236
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000237 raw = type->tp_subclasses;
238 if (raw != NULL) {
Antoine Pitrou84745ab2013-10-29 21:31:25 +0100239 assert(PyDict_CheckExact(raw));
240 i = 0;
241 while (PyDict_Next(raw, &i, NULL, &ref)) {
242 assert(PyWeakref_CheckRef(ref));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000243 ref = PyWeakref_GET_OBJECT(ref);
244 if (ref != Py_None) {
245 PyType_Modified((PyTypeObject *)ref);
246 }
247 }
248 }
249 type->tp_flags &= ~Py_TPFLAGS_VALID_VERSION_TAG;
Christian Heimesa62da1d2008-01-12 19:39:10 +0000250}
251
252static void
253type_mro_modified(PyTypeObject *type, PyObject *bases) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000254 /*
Florent Xiclunaaa6c1d22011-12-12 18:54:29 +0100255 Check that all base classes or elements of the MRO of type are
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000256 able to be cached. This function is called after the base
257 classes or mro of the type are altered.
Christian Heimesa62da1d2008-01-12 19:39:10 +0000258
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000259 Unset HAVE_VERSION_TAG and VALID_VERSION_TAG if the type
Florent Xiclunaaa6c1d22011-12-12 18:54:29 +0100260 has a custom MRO that includes a type which is not officially
261 super type.
Christian Heimesa62da1d2008-01-12 19:39:10 +0000262
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000263 Called from mro_internal, which will subsequently be called on
264 each subclass when their mro is recursively updated.
265 */
266 Py_ssize_t i, n;
267 int clear = 0;
Christian Heimesa62da1d2008-01-12 19:39:10 +0000268
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000269 if (!PyType_HasFeature(type, Py_TPFLAGS_HAVE_VERSION_TAG))
270 return;
Christian Heimesa62da1d2008-01-12 19:39:10 +0000271
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000272 n = PyTuple_GET_SIZE(bases);
273 for (i = 0; i < n; i++) {
274 PyObject *b = PyTuple_GET_ITEM(bases, i);
275 PyTypeObject *cls;
Christian Heimesa62da1d2008-01-12 19:39:10 +0000276
Florent Xiclunaaa6c1d22011-12-12 18:54:29 +0100277 assert(PyType_Check(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000278 cls = (PyTypeObject *)b;
Christian Heimesa62da1d2008-01-12 19:39:10 +0000279
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000280 if (!PyType_HasFeature(cls, Py_TPFLAGS_HAVE_VERSION_TAG) ||
281 !PyType_IsSubtype(type, cls)) {
282 clear = 1;
283 break;
284 }
285 }
Christian Heimesa62da1d2008-01-12 19:39:10 +0000286
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000287 if (clear)
288 type->tp_flags &= ~(Py_TPFLAGS_HAVE_VERSION_TAG|
289 Py_TPFLAGS_VALID_VERSION_TAG);
Christian Heimesa62da1d2008-01-12 19:39:10 +0000290}
291
292static int
293assign_version_tag(PyTypeObject *type)
294{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000295 /* Ensure that the tp_version_tag is valid and set
296 Py_TPFLAGS_VALID_VERSION_TAG. To respect the invariant, this
297 must first be done on all super classes. Return 0 if this
298 cannot be done, 1 if Py_TPFLAGS_VALID_VERSION_TAG.
299 */
300 Py_ssize_t i, n;
301 PyObject *bases;
Christian Heimesa62da1d2008-01-12 19:39:10 +0000302
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000303 if (PyType_HasFeature(type, Py_TPFLAGS_VALID_VERSION_TAG))
304 return 1;
305 if (!PyType_HasFeature(type, Py_TPFLAGS_HAVE_VERSION_TAG))
306 return 0;
307 if (!PyType_HasFeature(type, Py_TPFLAGS_READY))
308 return 0;
Christian Heimesa62da1d2008-01-12 19:39:10 +0000309
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000310 type->tp_version_tag = next_version_tag++;
311 /* for stress-testing: next_version_tag &= 0xFF; */
Christian Heimesa62da1d2008-01-12 19:39:10 +0000312
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000313 if (type->tp_version_tag == 0) {
314 /* wrap-around or just starting Python - clear the whole
315 cache by filling names with references to Py_None.
316 Values are also set to NULL for added protection, as they
317 are borrowed reference */
318 for (i = 0; i < (1 << MCACHE_SIZE_EXP); i++) {
319 method_cache[i].value = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000320 Py_INCREF(Py_None);
Serhiy Storchaka48842712016-04-06 09:45:48 +0300321 Py_XSETREF(method_cache[i].name, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000322 }
323 /* mark all version tags as invalid */
324 PyType_Modified(&PyBaseObject_Type);
325 return 1;
326 }
327 bases = type->tp_bases;
328 n = PyTuple_GET_SIZE(bases);
329 for (i = 0; i < n; i++) {
330 PyObject *b = PyTuple_GET_ITEM(bases, i);
331 assert(PyType_Check(b));
332 if (!assign_version_tag((PyTypeObject *)b))
333 return 0;
334 }
335 type->tp_flags |= Py_TPFLAGS_VALID_VERSION_TAG;
336 return 1;
Christian Heimesa62da1d2008-01-12 19:39:10 +0000337}
338
339
Guido van Rossum6f799372001-09-20 20:46:19 +0000340static PyMemberDef type_members[] = {
Benjamin Peterson0e102062010-08-25 23:13:17 +0000341 {"__basicsize__", T_PYSSIZET, offsetof(PyTypeObject,tp_basicsize),READONLY},
342 {"__itemsize__", T_PYSSIZET, offsetof(PyTypeObject, tp_itemsize), READONLY},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000343 {"__flags__", T_LONG, offsetof(PyTypeObject, tp_flags), READONLY},
344 {"__weakrefoffset__", T_LONG,
345 offsetof(PyTypeObject, tp_weaklistoffset), READONLY},
346 {"__base__", T_OBJECT, offsetof(PyTypeObject, tp_base), READONLY},
347 {"__dictoffset__", T_LONG,
348 offsetof(PyTypeObject, tp_dictoffset), READONLY},
349 {"__mro__", T_OBJECT, offsetof(PyTypeObject, tp_mro), READONLY},
350 {0}
Tim Peters6d6c1a32001-08-02 04:15:00 +0000351};
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000352
Benjamin Petersond9f23d22011-08-17 11:54:03 -0500353static int
354check_set_special_type_attr(PyTypeObject *type, PyObject *value, const char *name)
355{
356 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
357 PyErr_Format(PyExc_TypeError,
358 "can't set %s.%s", type->tp_name, name);
359 return 0;
360 }
361 if (!value) {
362 PyErr_Format(PyExc_TypeError,
363 "can't delete %s.%s", type->tp_name, name);
364 return 0;
365 }
366 return 1;
367}
368
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000369static PyObject *
Guido van Rossumc3542212001-08-16 09:18:56 +0000370type_name(PyTypeObject *type, void *context)
371{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000372 const char *s;
Guido van Rossumc3542212001-08-16 09:18:56 +0000373
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000374 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
375 PyHeapTypeObject* et = (PyHeapTypeObject*)type;
Tim Petersea7f75d2002-12-07 21:39:16 +0000376
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000377 Py_INCREF(et->ht_name);
378 return et->ht_name;
379 }
380 else {
381 s = strrchr(type->tp_name, '.');
382 if (s == NULL)
383 s = type->tp_name;
384 else
385 s++;
386 return PyUnicode_FromString(s);
387 }
Guido van Rossumc3542212001-08-16 09:18:56 +0000388}
389
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100390static PyObject *
391type_qualname(PyTypeObject *type, void *context)
392{
393 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
394 PyHeapTypeObject* et = (PyHeapTypeObject*)type;
395 Py_INCREF(et->ht_qualname);
396 return et->ht_qualname;
397 }
398 else {
399 return type_name(type, context);
400 }
401}
402
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000403static int
404type_set_name(PyTypeObject *type, PyObject *value, void *context)
405{
Serhiy Storchaka42bf8fc2015-12-30 21:40:49 +0200406 const char *tp_name;
407 Py_ssize_t name_size;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000408
Benjamin Petersond9f23d22011-08-17 11:54:03 -0500409 if (!check_set_special_type_attr(type, value, "__name__"))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000410 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000411 if (!PyUnicode_Check(value)) {
412 PyErr_Format(PyExc_TypeError,
413 "can only assign string to %s.__name__, not '%s'",
414 type->tp_name, Py_TYPE(value)->tp_name);
415 return -1;
416 }
Guido van Rossume845c0f2007-11-02 23:07:07 +0000417
Serhiy Storchaka42bf8fc2015-12-30 21:40:49 +0200418 tp_name = PyUnicode_AsUTF8AndSize(value, &name_size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000419 if (tp_name == NULL)
420 return -1;
Serhiy Storchaka42bf8fc2015-12-30 21:40:49 +0200421 if (strlen(tp_name) != (size_t)name_size) {
422 PyErr_SetString(PyExc_ValueError,
423 "type name must not contain null characters");
424 return -1;
425 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000426
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000427 type->tp_name = tp_name;
Serhiy Storchaka1ed017a2015-12-27 15:51:32 +0200428 Py_INCREF(value);
Serhiy Storchaka57a01d32016-04-10 18:05:40 +0300429 Py_SETREF(((PyHeapTypeObject*)type)->ht_name, value);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000430
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000431 return 0;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000432}
433
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100434static int
435type_set_qualname(PyTypeObject *type, PyObject *value, void *context)
436{
437 PyHeapTypeObject* et;
438
Benjamin Peterson2c05a2e2012-10-31 00:01:15 -0400439 if (!check_set_special_type_attr(type, value, "__qualname__"))
440 return -1;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100441 if (!PyUnicode_Check(value)) {
442 PyErr_Format(PyExc_TypeError,
443 "can only assign string to %s.__qualname__, not '%s'",
444 type->tp_name, Py_TYPE(value)->tp_name);
445 return -1;
446 }
447
448 et = (PyHeapTypeObject*)type;
449 Py_INCREF(value);
Serhiy Storchaka57a01d32016-04-10 18:05:40 +0300450 Py_SETREF(et->ht_qualname, value);
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100451 return 0;
452}
453
Guido van Rossumc3542212001-08-16 09:18:56 +0000454static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000455type_module(PyTypeObject *type, void *context)
Guido van Rossum29ca26e1995-01-07 11:58:15 +0000456{
Serhiy Storchaka7c19aff2016-09-10 00:53:02 +0300457 PyObject *mod;
Guido van Rossumc3542212001-08-16 09:18:56 +0000458
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000459 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
Serhiy Storchaka7c19aff2016-09-10 00:53:02 +0300460 mod = _PyDict_GetItemId(type->tp_dict, &PyId___module__);
461 if (mod == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000462 PyErr_Format(PyExc_AttributeError, "__module__");
Serhiy Storchaka7c19aff2016-09-10 00:53:02 +0300463 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000464 }
Serhiy Storchaka27ba8862016-05-25 16:14:55 +0300465 Py_INCREF(mod);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000466 }
467 else {
Serhiy Storchaka7c19aff2016-09-10 00:53:02 +0300468 const char *s = strrchr(type->tp_name, '.');
469 if (s != NULL) {
470 mod = PyUnicode_FromStringAndSize(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000471 type->tp_name, (Py_ssize_t)(s - type->tp_name));
Serhiy Storchaka7c19aff2016-09-10 00:53:02 +0300472 if (mod != NULL)
473 PyUnicode_InternInPlace(&mod);
474 }
475 else {
476 mod = _PyUnicode_FromId(&PyId_builtins);
477 Py_XINCREF(mod);
478 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000479 }
Serhiy Storchaka7c19aff2016-09-10 00:53:02 +0300480 return mod;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000481}
482
Guido van Rossum3926a632001-09-25 16:25:58 +0000483static int
484type_set_module(PyTypeObject *type, PyObject *value, void *context)
485{
Benjamin Petersond9f23d22011-08-17 11:54:03 -0500486 if (!check_set_special_type_attr(type, value, "__module__"))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000487 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000488
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000489 PyType_Modified(type);
Christian Heimesa62da1d2008-01-12 19:39:10 +0000490
Victor Stinner3c1e4812012-03-26 22:10:51 +0200491 return _PyDict_SetItemId(type->tp_dict, &PyId___module__, value);
Guido van Rossum3926a632001-09-25 16:25:58 +0000492}
493
Tim Peters6d6c1a32001-08-02 04:15:00 +0000494static PyObject *
Christian Heimes9e7f1d22008-02-28 12:27:11 +0000495type_abstractmethods(PyTypeObject *type, void *context)
496{
Benjamin Petersonaec5fd12010-10-02 00:03:31 +0000497 PyObject *mod = NULL;
Benjamin Peterson84060b82010-10-03 02:13:39 +0000498 /* type itself has an __abstractmethods__ descriptor (this). Don't return
499 that. */
Benjamin Petersonaec5fd12010-10-02 00:03:31 +0000500 if (type != &PyType_Type)
Victor Stinner3688aa92013-11-06 18:59:18 +0100501 mod = _PyDict_GetItemId(type->tp_dict, &PyId___abstractmethods__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000502 if (!mod) {
Victor Stinner3688aa92013-11-06 18:59:18 +0100503 PyObject *message = _PyUnicode_FromId(&PyId___abstractmethods__);
504 if (message)
505 PyErr_SetObject(PyExc_AttributeError, message);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000506 return NULL;
507 }
Serhiy Storchaka27ba8862016-05-25 16:14:55 +0300508 Py_INCREF(mod);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000509 return mod;
Christian Heimes9e7f1d22008-02-28 12:27:11 +0000510}
511
512static int
513type_set_abstractmethods(PyTypeObject *type, PyObject *value, void *context)
514{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000515 /* __abstractmethods__ should only be set once on a type, in
516 abc.ABCMeta.__new__, so this function doesn't do anything
517 special to update subclasses.
518 */
Antoine Pitrou6f430e42012-08-15 23:18:25 +0200519 int abstract, res;
Benjamin Peterson477ba912011-01-12 15:34:01 +0000520 if (value != NULL) {
Antoine Pitrou6f430e42012-08-15 23:18:25 +0200521 abstract = PyObject_IsTrue(value);
522 if (abstract < 0)
523 return -1;
Victor Stinner3688aa92013-11-06 18:59:18 +0100524 res = _PyDict_SetItemId(type->tp_dict, &PyId___abstractmethods__, value);
Benjamin Peterson477ba912011-01-12 15:34:01 +0000525 }
526 else {
Antoine Pitrou6f430e42012-08-15 23:18:25 +0200527 abstract = 0;
Victor Stinner3688aa92013-11-06 18:59:18 +0100528 res = _PyDict_DelItemId(type->tp_dict, &PyId___abstractmethods__);
Benjamin Peterson477ba912011-01-12 15:34:01 +0000529 if (res && PyErr_ExceptionMatches(PyExc_KeyError)) {
Victor Stinner3688aa92013-11-06 18:59:18 +0100530 PyObject *message = _PyUnicode_FromId(&PyId___abstractmethods__);
531 if (message)
532 PyErr_SetObject(PyExc_AttributeError, message);
Benjamin Peterson477ba912011-01-12 15:34:01 +0000533 return -1;
534 }
535 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000536 if (res == 0) {
537 PyType_Modified(type);
Antoine Pitrou6f430e42012-08-15 23:18:25 +0200538 if (abstract)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000539 type->tp_flags |= Py_TPFLAGS_IS_ABSTRACT;
Antoine Pitrou6f430e42012-08-15 23:18:25 +0200540 else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000541 type->tp_flags &= ~Py_TPFLAGS_IS_ABSTRACT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000542 }
543 return res;
Christian Heimes9e7f1d22008-02-28 12:27:11 +0000544}
545
546static PyObject *
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000547type_get_bases(PyTypeObject *type, void *context)
548{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000549 Py_INCREF(type->tp_bases);
550 return type->tp_bases;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000551}
552
553static PyTypeObject *best_base(PyObject *);
Benjamin Peterson104b9e02015-02-05 22:29:14 -0500554static int mro_internal(PyTypeObject *, PyObject **);
Benjamin Peterson6cb526e2016-09-09 12:42:51 -0700555static int type_is_subtype_base_chain(PyTypeObject *, PyTypeObject *);
Serhiy Storchakaef1585e2015-12-25 20:01:53 +0200556static int compatible_for_assignment(PyTypeObject *, PyTypeObject *, const char *);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000557static int add_subclass(PyTypeObject*, PyTypeObject*);
Benjamin Peterson104b9e02015-02-05 22:29:14 -0500558static int add_all_subclasses(PyTypeObject *type, PyObject *bases);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000559static void remove_subclass(PyTypeObject *, PyTypeObject *);
Antoine Pitrou84745ab2013-10-29 21:31:25 +0100560static void remove_all_subclasses(PyTypeObject *type, PyObject *bases);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000561static void update_all_slots(PyTypeObject *);
562
Guido van Rossum8d24ee92003-03-24 23:49:49 +0000563typedef int (*update_callback)(PyTypeObject *, void *);
564static int update_subclasses(PyTypeObject *type, PyObject *name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000565 update_callback callback, void *data);
Guido van Rossum8d24ee92003-03-24 23:49:49 +0000566static int recurse_down_subclasses(PyTypeObject *type, PyObject *name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000567 update_callback callback, void *data);
Benjamin Peterson104b9e02015-02-05 22:29:14 -0500568static PyObject *type_subclasses(PyTypeObject *type, PyObject *ignored);
Guido van Rossum8d24ee92003-03-24 23:49:49 +0000569
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000570static int
Benjamin Peterson104b9e02015-02-05 22:29:14 -0500571mro_hierarchy(PyTypeObject *type, PyObject *temp)
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000572{
Benjamin Peterson104b9e02015-02-05 22:29:14 -0500573 int res;
574 PyObject *new_mro, *old_mro;
575 PyObject *tuple;
576 PyObject *subclasses;
577 Py_ssize_t i, n;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000578
Benjamin Peterson104b9e02015-02-05 22:29:14 -0500579 res = mro_internal(type, &old_mro);
580 if (res <= 0)
581 /* error / reentrance */
582 return res;
583 new_mro = type->tp_mro;
Antoine Pitrou84745ab2013-10-29 21:31:25 +0100584
Benjamin Peterson104b9e02015-02-05 22:29:14 -0500585 if (old_mro != NULL)
586 tuple = PyTuple_Pack(3, type, new_mro, old_mro);
587 else
588 tuple = PyTuple_Pack(2, type, new_mro);
589
590 if (tuple != NULL)
591 res = PyList_Append(temp, tuple);
592 else
593 res = -1;
594 Py_XDECREF(tuple);
595
596 if (res < 0) {
597 type->tp_mro = old_mro;
598 Py_DECREF(new_mro);
599 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000600 }
Benjamin Peterson104b9e02015-02-05 22:29:14 -0500601 Py_XDECREF(old_mro);
602
603 /* Obtain a copy of subclasses list to iterate over.
604
605 Otherwise type->tp_subclasses might be altered
606 in the middle of the loop, for example, through a custom mro(),
607 by invoking type_set_bases on some subclass of the type
608 which in turn calls remove_subclass/add_subclass on this type.
609
610 Finally, this makes things simple avoiding the need to deal
611 with dictionary iterators and weak references.
612 */
613 subclasses = type_subclasses(type, NULL);
614 if (subclasses == NULL)
615 return -1;
616 n = PyList_GET_SIZE(subclasses);
617 for (i = 0; i < n; i++) {
618 PyTypeObject *subclass;
619 subclass = (PyTypeObject *)PyList_GET_ITEM(subclasses, i);
620 res = mro_hierarchy(subclass, temp);
621 if (res < 0)
622 break;
623 }
624 Py_DECREF(subclasses);
625
626 return res;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000627}
628
629static int
Benjamin Peterson104b9e02015-02-05 22:29:14 -0500630type_set_bases(PyTypeObject *type, PyObject *new_bases, void *context)
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000631{
Benjamin Peterson104b9e02015-02-05 22:29:14 -0500632 int res = 0;
633 PyObject *temp;
634 PyObject *old_bases;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000635 PyTypeObject *new_base, *old_base;
Benjamin Peterson104b9e02015-02-05 22:29:14 -0500636 Py_ssize_t i;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000637
Benjamin Peterson104b9e02015-02-05 22:29:14 -0500638 if (!check_set_special_type_attr(type, new_bases, "__bases__"))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000639 return -1;
Benjamin Peterson104b9e02015-02-05 22:29:14 -0500640 if (!PyTuple_Check(new_bases)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000641 PyErr_Format(PyExc_TypeError,
642 "can only assign tuple to %s.__bases__, not %s",
Benjamin Peterson104b9e02015-02-05 22:29:14 -0500643 type->tp_name, Py_TYPE(new_bases)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000644 return -1;
645 }
Benjamin Peterson104b9e02015-02-05 22:29:14 -0500646 if (PyTuple_GET_SIZE(new_bases) == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000647 PyErr_Format(PyExc_TypeError,
648 "can only assign non-empty tuple to %s.__bases__, not ()",
649 type->tp_name);
650 return -1;
651 }
Benjamin Peterson104b9e02015-02-05 22:29:14 -0500652 for (i = 0; i < PyTuple_GET_SIZE(new_bases); i++) {
653 PyObject *ob;
654 PyTypeObject *base;
655
656 ob = PyTuple_GET_ITEM(new_bases, i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000657 if (!PyType_Check(ob)) {
Benjamin Petersonb6af60c2012-04-01 18:49:54 -0400658 PyErr_Format(PyExc_TypeError,
Benjamin Peterson9ee601e2012-04-01 18:51:37 -0400659 "%s.__bases__ must be tuple of classes, not '%s'",
Benjamin Petersonb6af60c2012-04-01 18:49:54 -0400660 type->tp_name, Py_TYPE(ob)->tp_name);
661 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000662 }
Benjamin Peterson104b9e02015-02-05 22:29:14 -0500663
664 base = (PyTypeObject*)ob;
665 if (PyType_IsSubtype(base, type) ||
666 /* In case of reentering here again through a custom mro()
667 the above check is not enough since it relies on
668 base->tp_mro which would gonna be updated inside
669 mro_internal only upon returning from the mro().
670
671 However, base->tp_base has already been assigned (see
672 below), which in turn may cause an inheritance cycle
673 through tp_base chain. And this is definitely
674 not what you want to ever happen. */
675 (base->tp_mro != NULL && type_is_subtype_base_chain(base, type))) {
676
Benjamin Peterson3471bb62012-04-01 18:48:40 -0400677 PyErr_SetString(PyExc_TypeError,
678 "a __bases__ item causes an inheritance cycle");
679 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000680 }
681 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000682
Benjamin Peterson104b9e02015-02-05 22:29:14 -0500683 new_base = best_base(new_bases);
684 if (new_base == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000685 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000686
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000687 if (!compatible_for_assignment(type->tp_base, new_base, "__bases__"))
688 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000689
Benjamin Peterson104b9e02015-02-05 22:29:14 -0500690 Py_INCREF(new_bases);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000691 Py_INCREF(new_base);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000692
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000693 old_bases = type->tp_bases;
694 old_base = type->tp_base;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000695
Benjamin Peterson104b9e02015-02-05 22:29:14 -0500696 type->tp_bases = new_bases;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000697 type->tp_base = new_base;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000698
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000699 temp = PyList_New(0);
Benjamin Peterson104b9e02015-02-05 22:29:14 -0500700 if (temp == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000701 goto bail;
Benjamin Peterson104b9e02015-02-05 22:29:14 -0500702 if (mro_hierarchy(type, temp) < 0)
703 goto undo;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000704 Py_DECREF(temp);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000705
Benjamin Peterson104b9e02015-02-05 22:29:14 -0500706 /* Take no action in case if type->tp_bases has been replaced
707 through reentrance. */
708 if (type->tp_bases == new_bases) {
709 /* any base that was in __bases__ but now isn't, we
710 need to remove |type| from its tp_subclasses.
711 conversely, any class now in __bases__ that wasn't
712 needs to have |type| added to its subclasses. */
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000713
Benjamin Peterson104b9e02015-02-05 22:29:14 -0500714 /* for now, sod that: just remove from all old_bases,
715 add to all new_bases */
716 remove_all_subclasses(type, old_bases);
717 res = add_all_subclasses(type, new_bases);
718 update_all_slots(type);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000719 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000720
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000721 Py_DECREF(old_bases);
722 Py_DECREF(old_base);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000723
Benjamin Peterson104b9e02015-02-05 22:29:14 -0500724 return res;
725
726 undo:
727 for (i = PyList_GET_SIZE(temp) - 1; i >= 0; i--) {
728 PyTypeObject *cls;
729 PyObject *new_mro, *old_mro = NULL;
730
731 PyArg_UnpackTuple(PyList_GET_ITEM(temp, i),
732 "", 2, 3, &cls, &new_mro, &old_mro);
733 /* Do not rollback if cls has a newer version of MRO. */
734 if (cls->tp_mro == new_mro) {
735 Py_XINCREF(old_mro);
736 cls->tp_mro = old_mro;
737 Py_DECREF(new_mro);
738 }
739 }
740 Py_DECREF(temp);
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000741
742 bail:
Benjamin Peterson104b9e02015-02-05 22:29:14 -0500743 if (type->tp_bases == new_bases) {
744 assert(type->tp_base == new_base);
Michael W. Hudsone723e452003-08-07 14:58:10 +0000745
Benjamin Peterson104b9e02015-02-05 22:29:14 -0500746 type->tp_bases = old_bases;
747 type->tp_base = old_base;
748
749 Py_DECREF(new_bases);
750 Py_DECREF(new_base);
751 }
752 else {
753 Py_DECREF(old_bases);
754 Py_DECREF(old_base);
755 }
Tim Petersea7f75d2002-12-07 21:39:16 +0000756
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000757 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000758}
759
760static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000761type_dict(PyTypeObject *type, void *context)
762{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000763 if (type->tp_dict == NULL) {
764 Py_INCREF(Py_None);
765 return Py_None;
766 }
767 return PyDictProxy_New(type->tp_dict);
Guido van Rossum29ca26e1995-01-07 11:58:15 +0000768}
769
Tim Peters24008312002-03-17 18:56:20 +0000770static PyObject *
771type_get_doc(PyTypeObject *type, void *context)
772{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000773 PyObject *result;
Larry Hastings5c661892014-01-24 06:17:25 -0800774 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE) && type->tp_doc != NULL) {
Larry Hastings2623c8c2014-02-08 22:15:29 -0800775 return _PyType_GetDocFromInternalDoc(type->tp_name, type->tp_doc);
Larry Hastings5c661892014-01-24 06:17:25 -0800776 }
Victor Stinner3c1e4812012-03-26 22:10:51 +0200777 result = _PyDict_GetItemId(type->tp_dict, &PyId___doc__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000778 if (result == NULL) {
779 result = Py_None;
780 Py_INCREF(result);
781 }
782 else if (Py_TYPE(result)->tp_descr_get) {
783 result = Py_TYPE(result)->tp_descr_get(result, NULL,
784 (PyObject *)type);
785 }
786 else {
787 Py_INCREF(result);
788 }
789 return result;
Tim Peters24008312002-03-17 18:56:20 +0000790}
791
Larry Hastings5c661892014-01-24 06:17:25 -0800792static PyObject *
793type_get_text_signature(PyTypeObject *type, void *context)
794{
Larry Hastings2623c8c2014-02-08 22:15:29 -0800795 return _PyType_GetTextSignatureFromInternalDoc(type->tp_name, type->tp_doc);
Larry Hastings5c661892014-01-24 06:17:25 -0800796}
797
Benjamin Peterson01fc6cd2011-08-17 12:03:47 -0500798static int
799type_set_doc(PyTypeObject *type, PyObject *value, void *context)
800{
801 if (!check_set_special_type_attr(type, value, "__doc__"))
802 return -1;
803 PyType_Modified(type);
Victor Stinner3c1e4812012-03-26 22:10:51 +0200804 return _PyDict_SetItemId(type->tp_dict, &PyId___doc__, value);
Benjamin Peterson01fc6cd2011-08-17 12:03:47 -0500805}
806
Antoine Pitrouec569b72008-08-26 22:40:48 +0000807static PyObject *
808type___instancecheck__(PyObject *type, PyObject *inst)
809{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000810 switch (_PyObject_RealIsInstance(inst, type)) {
811 case -1:
812 return NULL;
813 case 0:
814 Py_RETURN_FALSE;
815 default:
816 Py_RETURN_TRUE;
817 }
Antoine Pitrouec569b72008-08-26 22:40:48 +0000818}
819
820
821static PyObject *
Antoine Pitrouec569b72008-08-26 22:40:48 +0000822type___subclasscheck__(PyObject *type, PyObject *inst)
823{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000824 switch (_PyObject_RealIsSubclass(inst, type)) {
825 case -1:
826 return NULL;
827 case 0:
828 Py_RETURN_FALSE;
829 default:
830 Py_RETURN_TRUE;
831 }
Antoine Pitrouec569b72008-08-26 22:40:48 +0000832}
833
Antoine Pitrouec569b72008-08-26 22:40:48 +0000834
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000835static PyGetSetDef type_getsets[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000836 {"__name__", (getter)type_name, (setter)type_set_name, NULL},
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100837 {"__qualname__", (getter)type_qualname, (setter)type_set_qualname, NULL},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000838 {"__bases__", (getter)type_get_bases, (setter)type_set_bases, NULL},
839 {"__module__", (getter)type_module, (setter)type_set_module, NULL},
840 {"__abstractmethods__", (getter)type_abstractmethods,
841 (setter)type_set_abstractmethods, NULL},
842 {"__dict__", (getter)type_dict, NULL, NULL},
Benjamin Peterson01fc6cd2011-08-17 12:03:47 -0500843 {"__doc__", (getter)type_get_doc, (setter)type_set_doc, NULL},
Larry Hastings5c661892014-01-24 06:17:25 -0800844 {"__text_signature__", (getter)type_get_text_signature, NULL, NULL},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000845 {0}
Tim Peters6d6c1a32001-08-02 04:15:00 +0000846};
847
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000848static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000849type_repr(PyTypeObject *type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000850{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000851 PyObject *mod, *name, *rtn;
Guido van Rossumc3542212001-08-16 09:18:56 +0000852
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000853 mod = type_module(type, NULL);
854 if (mod == NULL)
855 PyErr_Clear();
856 else if (!PyUnicode_Check(mod)) {
857 Py_DECREF(mod);
858 mod = NULL;
859 }
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100860 name = type_qualname(type, NULL);
Christian Heimesa0e7e412012-09-10 03:00:14 +0200861 if (name == NULL) {
862 Py_XDECREF(mod);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000863 return NULL;
Christian Heimesa0e7e412012-09-10 03:00:14 +0200864 }
Barry Warsaw7ce36942001-08-24 18:34:26 +0000865
Serhiy Storchakaf5894dd2016-11-16 15:40:39 +0200866 if (mod != NULL && !_PyUnicode_EqualToASCIIId(mod, &PyId_builtins))
Benjamin Petersonab078e92016-07-13 21:13:29 -0700867 rtn = PyUnicode_FromFormat("<class '%U.%U'>", mod, name);
868 else
869 rtn = PyUnicode_FromFormat("<class '%s'>", type->tp_name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000870
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000871 Py_XDECREF(mod);
872 Py_DECREF(name);
873 return rtn;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000874}
875
Tim Peters6d6c1a32001-08-02 04:15:00 +0000876static PyObject *
877type_call(PyTypeObject *type, PyObject *args, PyObject *kwds)
878{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000879 PyObject *obj;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000880
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000881 if (type->tp_new == NULL) {
882 PyErr_Format(PyExc_TypeError,
883 "cannot create '%.100s' instances",
884 type->tp_name);
885 return NULL;
886 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000887
Victor Stinner33824f62013-08-26 14:05:19 +0200888#ifdef Py_DEBUG
889 /* type_call() must not be called with an exception set,
890 because it may clear it (directly or indirectly) and so the
Martin Panter9955a372015-10-07 10:26:23 +0000891 caller loses its exception */
Victor Stinner33824f62013-08-26 14:05:19 +0200892 assert(!PyErr_Occurred());
893#endif
894
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000895 obj = type->tp_new(type, args, kwds);
Victor Stinner99bb14b2015-09-03 12:16:49 +0200896 obj = _Py_CheckFunctionResult((PyObject*)type, obj, NULL);
897 if (obj == NULL)
898 return NULL;
899
900 /* Ugly exception: when the call was type(something),
901 don't call tp_init on the result. */
902 if (type == &PyType_Type &&
903 PyTuple_Check(args) && PyTuple_GET_SIZE(args) == 1 &&
904 (kwds == NULL ||
905 (PyDict_Check(kwds) && PyDict_Size(kwds) == 0)))
906 return obj;
907
908 /* If the returned object is not an instance of type,
909 it won't be initialized. */
910 if (!PyType_IsSubtype(Py_TYPE(obj), type))
911 return obj;
912
913 type = Py_TYPE(obj);
914 if (type->tp_init != NULL) {
915 int res = type->tp_init(obj, args, kwds);
916 if (res < 0) {
917 assert(PyErr_Occurred());
918 Py_DECREF(obj);
919 obj = NULL;
920 }
921 else {
922 assert(!PyErr_Occurred());
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000923 }
924 }
925 return obj;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000926}
927
928PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000929PyType_GenericAlloc(PyTypeObject *type, Py_ssize_t nitems)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000930{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000931 PyObject *obj;
932 const size_t size = _PyObject_VAR_SIZE(type, nitems+1);
933 /* note that we need to add one, for the sentinel */
Tim Peters406fe3b2001-10-06 19:04:01 +0000934
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000935 if (PyType_IS_GC(type))
936 obj = _PyObject_GC_Malloc(size);
937 else
938 obj = (PyObject *)PyObject_MALLOC(size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000939
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000940 if (obj == NULL)
941 return PyErr_NoMemory();
Tim Peters406fe3b2001-10-06 19:04:01 +0000942
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000943 memset(obj, '\0', size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000944
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000945 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
946 Py_INCREF(type);
Tim Peters406fe3b2001-10-06 19:04:01 +0000947
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000948 if (type->tp_itemsize == 0)
Christian Heimesd3afe782013-12-04 09:27:47 +0100949 (void)PyObject_INIT(obj, type);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000950 else
951 (void) PyObject_INIT_VAR((PyVarObject *)obj, type, nitems);
Tim Peters406fe3b2001-10-06 19:04:01 +0000952
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000953 if (PyType_IS_GC(type))
954 _PyObject_GC_TRACK(obj);
955 return obj;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000956}
957
958PyObject *
959PyType_GenericNew(PyTypeObject *type, PyObject *args, PyObject *kwds)
960{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000961 return type->tp_alloc(type, 0);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000962}
963
Guido van Rossum9475a232001-10-05 20:51:39 +0000964/* Helpers for subtyping */
965
966static int
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000967traverse_slots(PyTypeObject *type, PyObject *self, visitproc visit, void *arg)
968{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000969 Py_ssize_t i, n;
970 PyMemberDef *mp;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000971
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000972 n = Py_SIZE(type);
973 mp = PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type);
974 for (i = 0; i < n; i++, mp++) {
975 if (mp->type == T_OBJECT_EX) {
976 char *addr = (char *)self + mp->offset;
977 PyObject *obj = *(PyObject **)addr;
978 if (obj != NULL) {
979 int err = visit(obj, arg);
980 if (err)
981 return err;
982 }
983 }
984 }
985 return 0;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000986}
987
988static int
Guido van Rossum9475a232001-10-05 20:51:39 +0000989subtype_traverse(PyObject *self, visitproc visit, void *arg)
990{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000991 PyTypeObject *type, *base;
992 traverseproc basetraverse;
Guido van Rossum9475a232001-10-05 20:51:39 +0000993
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000994 /* Find the nearest base with a different tp_traverse,
995 and traverse slots while we're at it */
996 type = Py_TYPE(self);
997 base = type;
998 while ((basetraverse = base->tp_traverse) == subtype_traverse) {
999 if (Py_SIZE(base)) {
1000 int err = traverse_slots(base, self, visit, arg);
1001 if (err)
1002 return err;
1003 }
1004 base = base->tp_base;
1005 assert(base);
1006 }
Guido van Rossum9475a232001-10-05 20:51:39 +00001007
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001008 if (type->tp_dictoffset != base->tp_dictoffset) {
1009 PyObject **dictptr = _PyObject_GetDictPtr(self);
1010 if (dictptr && *dictptr)
1011 Py_VISIT(*dictptr);
1012 }
Guido van Rossum9475a232001-10-05 20:51:39 +00001013
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001014 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
1015 /* For a heaptype, the instances count as references
1016 to the type. Traverse the type so the collector
1017 can find cycles involving this link. */
1018 Py_VISIT(type);
Guido van Rossuma3862092002-06-10 15:24:42 +00001019
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001020 if (basetraverse)
1021 return basetraverse(self, visit, arg);
1022 return 0;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001023}
1024
1025static void
1026clear_slots(PyTypeObject *type, PyObject *self)
1027{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001028 Py_ssize_t i, n;
1029 PyMemberDef *mp;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001030
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001031 n = Py_SIZE(type);
1032 mp = PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type);
1033 for (i = 0; i < n; i++, mp++) {
1034 if (mp->type == T_OBJECT_EX && !(mp->flags & READONLY)) {
1035 char *addr = (char *)self + mp->offset;
1036 PyObject *obj = *(PyObject **)addr;
1037 if (obj != NULL) {
1038 *(PyObject **)addr = NULL;
1039 Py_DECREF(obj);
1040 }
1041 }
1042 }
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001043}
1044
1045static int
1046subtype_clear(PyObject *self)
1047{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001048 PyTypeObject *type, *base;
1049 inquiry baseclear;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001050
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001051 /* Find the nearest base with a different tp_clear
1052 and clear slots while we're at it */
1053 type = Py_TYPE(self);
1054 base = type;
1055 while ((baseclear = base->tp_clear) == subtype_clear) {
1056 if (Py_SIZE(base))
1057 clear_slots(base, self);
1058 base = base->tp_base;
1059 assert(base);
1060 }
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001061
Benjamin Peterson52c42432012-03-07 18:41:11 -06001062 /* Clear the instance dict (if any), to break cycles involving only
1063 __dict__ slots (as in the case 'self.__dict__ is self'). */
1064 if (type->tp_dictoffset != base->tp_dictoffset) {
1065 PyObject **dictptr = _PyObject_GetDictPtr(self);
1066 if (dictptr && *dictptr)
1067 Py_CLEAR(*dictptr);
1068 }
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001069
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001070 if (baseclear)
1071 return baseclear(self);
1072 return 0;
Guido van Rossum9475a232001-10-05 20:51:39 +00001073}
Tim Peters6d6c1a32001-08-02 04:15:00 +00001074
1075static void
1076subtype_dealloc(PyObject *self)
1077{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001078 PyTypeObject *type, *base;
1079 destructor basedealloc;
Antoine Pitrou56cd62c2012-09-06 00:59:49 +02001080 PyThreadState *tstate = PyThreadState_GET();
Antoine Pitrou796564c2013-07-30 19:59:21 +02001081 int has_finalizer;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001082
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001083 /* Extract the type; we expect it to be a heap type */
1084 type = Py_TYPE(self);
1085 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001086
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001087 /* Test whether the type has GC exactly once */
Guido van Rossum22b13872002-08-06 21:41:44 +00001088
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001089 if (!PyType_IS_GC(type)) {
1090 /* It's really rare to find a dynamic type that doesn't have
1091 GC; it can only happen when deriving from 'object' and not
1092 adding any slots or instance variables. This allows
1093 certain simplifications: there's no need to call
1094 clear_slots(), or DECREF the dict, or clear weakrefs. */
Guido van Rossum22b13872002-08-06 21:41:44 +00001095
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001096 /* Maybe call finalizer; exit early if resurrected */
Antoine Pitrou796564c2013-07-30 19:59:21 +02001097 if (type->tp_finalize) {
1098 if (PyObject_CallFinalizerFromDealloc(self) < 0)
1099 return;
1100 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001101 if (type->tp_del) {
1102 type->tp_del(self);
1103 if (self->ob_refcnt > 0)
1104 return;
1105 }
Guido van Rossum22b13872002-08-06 21:41:44 +00001106
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001107 /* Find the nearest base with a different tp_dealloc */
1108 base = type;
1109 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
1110 assert(Py_SIZE(base) == 0);
1111 base = base->tp_base;
1112 assert(base);
1113 }
Guido van Rossum22b13872002-08-06 21:41:44 +00001114
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001115 /* Extract the type again; tp_del may have changed it */
1116 type = Py_TYPE(self);
Benjamin Peterson193152c2009-04-25 01:08:45 +00001117
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001118 /* Call the base tp_dealloc() */
1119 assert(basedealloc);
1120 basedealloc(self);
Guido van Rossum22b13872002-08-06 21:41:44 +00001121
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001122 /* Can't reference self beyond this point */
1123 Py_DECREF(type);
Guido van Rossum22b13872002-08-06 21:41:44 +00001124
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001125 /* Done */
1126 return;
1127 }
Guido van Rossum22b13872002-08-06 21:41:44 +00001128
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001129 /* We get here only if the type has GC */
Guido van Rossum22b13872002-08-06 21:41:44 +00001130
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001131 /* UnTrack and re-Track around the trashcan macro, alas */
1132 /* See explanation at end of function for full disclosure */
1133 PyObject_GC_UnTrack(self);
1134 ++_PyTrash_delete_nesting;
Antoine Pitrou56cd62c2012-09-06 00:59:49 +02001135 ++ tstate->trash_delete_nesting;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001136 Py_TRASHCAN_SAFE_BEGIN(self);
1137 --_PyTrash_delete_nesting;
Antoine Pitrou56cd62c2012-09-06 00:59:49 +02001138 -- tstate->trash_delete_nesting;
Guido van Rossum22b13872002-08-06 21:41:44 +00001139
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001140 /* Find the nearest base with a different tp_dealloc */
1141 base = type;
Brett Cannonb94767f2011-02-22 20:15:44 +00001142 while ((/*basedealloc =*/ base->tp_dealloc) == subtype_dealloc) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001143 base = base->tp_base;
1144 assert(base);
1145 }
Guido van Rossum14227b42001-12-06 02:35:58 +00001146
Antoine Pitrou796564c2013-07-30 19:59:21 +02001147 has_finalizer = type->tp_finalize || type->tp_del;
Guido van Rossum59195fd2003-06-13 20:54:40 +00001148
Antoine Pitrou796564c2013-07-30 19:59:21 +02001149 if (type->tp_finalize) {
Benjamin Peterson8f657c32016-10-04 00:00:02 -07001150 _PyObject_GC_TRACK(self);
Antoine Pitrou796564c2013-07-30 19:59:21 +02001151 if (PyObject_CallFinalizerFromDealloc(self) < 0) {
1152 /* Resurrected */
1153 goto endlabel;
1154 }
Benjamin Peterson8f657c32016-10-04 00:00:02 -07001155 _PyObject_GC_UNTRACK(self);
Antoine Pitrou796564c2013-07-30 19:59:21 +02001156 }
Benjamin Peterson8f657c32016-10-04 00:00:02 -07001157 /*
1158 If we added a weaklist, we clear it. Do this *before* calling tp_del,
1159 clearing slots, or clearing the instance dict.
1160
1161 GC tracking must be off at this point. weakref callbacks (if any, and
1162 whether directly here or indirectly in something we call) may trigger GC,
1163 and if self is tracked at that point, it will look like trash to GC and GC
1164 will try to delete self again.
1165 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001166 if (type->tp_weaklistoffset && !base->tp_weaklistoffset)
1167 PyObject_ClearWeakRefs(self);
Guido van Rossum1987c662003-05-29 14:29:23 +00001168
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001169 if (type->tp_del) {
Benjamin Peterson8f657c32016-10-04 00:00:02 -07001170 _PyObject_GC_TRACK(self);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001171 type->tp_del(self);
Antoine Pitrou796564c2013-07-30 19:59:21 +02001172 if (self->ob_refcnt > 0) {
1173 /* Resurrected */
1174 goto endlabel;
1175 }
Benjamin Peterson8f657c32016-10-04 00:00:02 -07001176 _PyObject_GC_UNTRACK(self);
Antoine Pitrou796564c2013-07-30 19:59:21 +02001177 }
1178 if (has_finalizer) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001179 /* New weakrefs could be created during the finalizer call.
Antoine Pitrou796564c2013-07-30 19:59:21 +02001180 If this occurs, clear them out without calling their
1181 finalizers since they might rely on part of the object
1182 being finalized that has already been destroyed. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001183 if (type->tp_weaklistoffset && !base->tp_weaklistoffset) {
1184 /* Modeled after GET_WEAKREFS_LISTPTR() */
1185 PyWeakReference **list = (PyWeakReference **) \
1186 PyObject_GET_WEAKREFS_LISTPTR(self);
1187 while (*list)
1188 _PyWeakref_ClearRef(*list);
1189 }
1190 }
Guido van Rossum1987c662003-05-29 14:29:23 +00001191
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001192 /* Clear slots up to the nearest base with a different tp_dealloc */
1193 base = type;
1194 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
1195 if (Py_SIZE(base))
1196 clear_slots(base, self);
1197 base = base->tp_base;
1198 assert(base);
1199 }
Guido van Rossum59195fd2003-06-13 20:54:40 +00001200
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001201 /* If we added a dict, DECREF it */
1202 if (type->tp_dictoffset && !base->tp_dictoffset) {
1203 PyObject **dictptr = _PyObject_GetDictPtr(self);
1204 if (dictptr != NULL) {
1205 PyObject *dict = *dictptr;
1206 if (dict != NULL) {
1207 Py_DECREF(dict);
1208 *dictptr = NULL;
1209 }
1210 }
1211 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001212
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001213 /* Extract the type again; tp_del may have changed it */
1214 type = Py_TYPE(self);
Benjamin Peterson193152c2009-04-25 01:08:45 +00001215
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001216 /* Call the base tp_dealloc(); first retrack self if
1217 * basedealloc knows about gc.
1218 */
1219 if (PyType_IS_GC(base))
1220 _PyObject_GC_TRACK(self);
1221 assert(basedealloc);
1222 basedealloc(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001223
Benjamin Peterson9d4cbcc2015-01-30 13:33:42 -05001224 /* Can't reference self beyond this point. It's possible tp_del switched
1225 our type from a HEAPTYPE to a non-HEAPTYPE, so be careful about
1226 reference counting. */
1227 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
1228 Py_DECREF(type);
Guido van Rossum22b13872002-08-06 21:41:44 +00001229
Guido van Rossum0906e072002-08-07 20:42:09 +00001230 endlabel:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001231 ++_PyTrash_delete_nesting;
Antoine Pitrou56cd62c2012-09-06 00:59:49 +02001232 ++ tstate->trash_delete_nesting;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001233 Py_TRASHCAN_SAFE_END(self);
1234 --_PyTrash_delete_nesting;
Antoine Pitrou56cd62c2012-09-06 00:59:49 +02001235 -- tstate->trash_delete_nesting;
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001236
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001237 /* Explanation of the weirdness around the trashcan macros:
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001238
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001239 Q. What do the trashcan macros do?
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001240
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001241 A. Read the comment titled "Trashcan mechanism" in object.h.
1242 For one, this explains why there must be a call to GC-untrack
1243 before the trashcan begin macro. Without understanding the
1244 trashcan code, the answers to the following questions don't make
1245 sense.
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001246
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001247 Q. Why do we GC-untrack before the trashcan and then immediately
1248 GC-track again afterward?
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001249
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001250 A. In the case that the base class is GC-aware, the base class
1251 probably GC-untracks the object. If it does that using the
1252 UNTRACK macro, this will crash when the object is already
1253 untracked. Because we don't know what the base class does, the
1254 only safe thing is to make sure the object is tracked when we
1255 call the base class dealloc. But... The trashcan begin macro
1256 requires that the object is *untracked* before it is called. So
1257 the dance becomes:
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001258
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001259 GC untrack
1260 trashcan begin
1261 GC track
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001262
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001263 Q. Why did the last question say "immediately GC-track again"?
1264 It's nowhere near immediately.
Tim Petersf7f9e992003-11-13 21:59:32 +00001265
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001266 A. Because the code *used* to re-track immediately. Bad Idea.
1267 self has a refcount of 0, and if gc ever gets its hands on it
1268 (which can happen if any weakref callback gets invoked), it
1269 looks like trash to gc too, and gc also tries to delete self
Ezio Melotti13925002011-03-16 11:05:33 +02001270 then. But we're already deleting self. Double deallocation is
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001271 a subtle disaster.
Tim Petersf7f9e992003-11-13 21:59:32 +00001272
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001273 Q. Why the bizarre (net-zero) manipulation of
1274 _PyTrash_delete_nesting around the trashcan macros?
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001275
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001276 A. Some base classes (e.g. list) also use the trashcan mechanism.
1277 The following scenario used to be possible:
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001278
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001279 - suppose the trashcan level is one below the trashcan limit
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001280
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001281 - subtype_dealloc() is called
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001282
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001283 - the trashcan limit is not yet reached, so the trashcan level
1284 is incremented and the code between trashcan begin and end is
1285 executed
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001286
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001287 - this destroys much of the object's contents, including its
1288 slots and __dict__
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001289
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001290 - basedealloc() is called; this is really list_dealloc(), or
1291 some other type which also uses the trashcan macros
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001292
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001293 - the trashcan limit is now reached, so the object is put on the
1294 trashcan's to-be-deleted-later list
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001295
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001296 - basedealloc() returns
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001297
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001298 - subtype_dealloc() decrefs the object's type
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001299
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001300 - subtype_dealloc() returns
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001301
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001302 - later, the trashcan code starts deleting the objects from its
1303 to-be-deleted-later list
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001304
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001305 - subtype_dealloc() is called *AGAIN* for the same object
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001306
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001307 - at the very least (if the destroyed slots and __dict__ don't
1308 cause problems) the object's type gets decref'ed a second
1309 time, which is *BAD*!!!
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001310
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001311 The remedy is to make sure that if the code between trashcan
1312 begin and end in subtype_dealloc() is called, the code between
1313 trashcan begin and end in basedealloc() will also be called.
1314 This is done by decrementing the level after passing into the
1315 trashcan block, and incrementing it just before leaving the
1316 block.
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001317
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001318 But now it's possible that a chain of objects consisting solely
1319 of objects whose deallocator is subtype_dealloc() will defeat
1320 the trashcan mechanism completely: the decremented level means
1321 that the effective level never reaches the limit. Therefore, we
1322 *increment* the level *before* entering the trashcan block, and
1323 matchingly decrement it after leaving. This means the trashcan
1324 code will trigger a little early, but that's no big deal.
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001325
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001326 Q. Are there any live examples of code in need of all this
1327 complexity?
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001328
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001329 A. Yes. See SF bug 668433 for code that crashed (when Python was
1330 compiled in debug mode) before the trashcan level manipulations
1331 were added. For more discussion, see SF patches 581742, 575073
1332 and bug 574207.
1333 */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001334}
1335
Jeremy Hylton938ace62002-07-17 16:30:39 +00001336static PyTypeObject *solid_base(PyTypeObject *type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001337
Tim Peters6d6c1a32001-08-02 04:15:00 +00001338/* type test with subclassing support */
1339
Benjamin Peterson6cb526e2016-09-09 12:42:51 -07001340static int
Benjamin Peterson104b9e02015-02-05 22:29:14 -05001341type_is_subtype_base_chain(PyTypeObject *a, PyTypeObject *b)
1342{
1343 do {
1344 if (a == b)
1345 return 1;
1346 a = a->tp_base;
1347 } while (a != NULL);
1348
1349 return (b == &PyBaseObject_Type);
1350}
1351
Tim Peters6d6c1a32001-08-02 04:15:00 +00001352int
1353PyType_IsSubtype(PyTypeObject *a, PyTypeObject *b)
1354{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001355 PyObject *mro;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001356
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001357 mro = a->tp_mro;
1358 if (mro != NULL) {
1359 /* Deal with multiple inheritance without recursion
1360 by walking the MRO tuple */
1361 Py_ssize_t i, n;
1362 assert(PyTuple_Check(mro));
1363 n = PyTuple_GET_SIZE(mro);
1364 for (i = 0; i < n; i++) {
1365 if (PyTuple_GET_ITEM(mro, i) == (PyObject *)b)
1366 return 1;
1367 }
1368 return 0;
1369 }
Benjamin Peterson104b9e02015-02-05 22:29:14 -05001370 else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001371 /* a is not completely initilized yet; follow tp_base */
Benjamin Peterson104b9e02015-02-05 22:29:14 -05001372 return type_is_subtype_base_chain(a, b);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001373}
1374
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001375/* Internal routines to do a method lookup in the type
Guido van Rossum60718732001-08-28 17:47:51 +00001376 without looking in the instance dictionary
1377 (so we can't use PyObject_GetAttr) but still binding
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001378 it to the instance. The arguments are the object,
Guido van Rossum60718732001-08-28 17:47:51 +00001379 the method name as a C string, and the address of a
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001380 static variable used to cache the interned Python string.
1381
1382 Two variants:
1383
1384 - lookup_maybe() returns NULL without raising an exception
1385 when the _PyType_Lookup() call fails;
1386
1387 - lookup_method() always raises an exception upon errors.
Benjamin Peterson224205f2009-05-08 03:25:19 +00001388
1389 - _PyObject_LookupSpecial() exported for the benefit of other places.
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001390*/
Guido van Rossum60718732001-08-28 17:47:51 +00001391
1392static PyObject *
Benjamin Petersonce798522012-01-22 11:24:29 -05001393lookup_maybe(PyObject *self, _Py_Identifier *attrid)
Guido van Rossum60718732001-08-28 17:47:51 +00001394{
Victor Stinner3c1e4812012-03-26 22:10:51 +02001395 PyObject *res;
Guido van Rossum60718732001-08-28 17:47:51 +00001396
Victor Stinner3c1e4812012-03-26 22:10:51 +02001397 res = _PyType_LookupId(Py_TYPE(self), attrid);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001398 if (res != NULL) {
1399 descrgetfunc f;
1400 if ((f = Py_TYPE(res)->tp_descr_get) == NULL)
1401 Py_INCREF(res);
1402 else
1403 res = f(res, self, (PyObject *)(Py_TYPE(self)));
1404 }
1405 return res;
Guido van Rossum60718732001-08-28 17:47:51 +00001406}
1407
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001408static PyObject *
Benjamin Petersonce798522012-01-22 11:24:29 -05001409lookup_method(PyObject *self, _Py_Identifier *attrid)
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001410{
Benjamin Petersonce798522012-01-22 11:24:29 -05001411 PyObject *res = lookup_maybe(self, attrid);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001412 if (res == NULL && !PyErr_Occurred())
Benjamin Petersonce798522012-01-22 11:24:29 -05001413 PyErr_SetObject(PyExc_AttributeError, attrid->object);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001414 return res;
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001415}
1416
Benjamin Peterson224205f2009-05-08 03:25:19 +00001417PyObject *
Benjamin Petersonce798522012-01-22 11:24:29 -05001418_PyObject_LookupSpecial(PyObject *self, _Py_Identifier *attrid)
Benjamin Peterson224205f2009-05-08 03:25:19 +00001419{
Benjamin Petersonce798522012-01-22 11:24:29 -05001420 return lookup_maybe(self, attrid);
Benjamin Peterson224205f2009-05-08 03:25:19 +00001421}
1422
Guido van Rossum2730b132001-08-28 18:22:14 +00001423/* A variation of PyObject_CallMethod that uses lookup_method()
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001424 instead of PyObject_GetAttrString(). This uses the same convention
Guido van Rossum2730b132001-08-28 18:22:14 +00001425 as lookup_method to cache the interned name string object. */
1426
Neil Schemenauerf23473f2001-10-21 22:28:58 +00001427static PyObject *
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001428call_method(PyObject *o, _Py_Identifier *nameid, const char *format, ...)
Guido van Rossum2730b132001-08-28 18:22:14 +00001429{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001430 va_list va;
Victor Stinnerf736c262016-08-19 18:05:37 +02001431 PyObject *func = NULL, *retval;
Guido van Rossum2730b132001-08-28 18:22:14 +00001432
Benjamin Petersonce798522012-01-22 11:24:29 -05001433 func = lookup_maybe(o, nameid);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001434 if (func == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001435 if (!PyErr_Occurred())
Benjamin Petersonce798522012-01-22 11:24:29 -05001436 PyErr_SetObject(PyExc_AttributeError, nameid->object);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001437 return NULL;
1438 }
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001439
Victor Stinner94463c92016-08-19 18:01:41 +02001440 if (format && *format) {
Victor Stinnerf736c262016-08-19 18:05:37 +02001441 PyObject *args;
1442
Victor Stinner94463c92016-08-19 18:01:41 +02001443 va_start(va, format);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001444 args = Py_VaBuildValue(format, va);
Victor Stinner94463c92016-08-19 18:01:41 +02001445 va_end(va);
Victor Stinnerf736c262016-08-19 18:05:37 +02001446
1447 if (args == NULL) {
1448 Py_DECREF(func);
1449 return NULL;
1450 }
1451 assert(PyTuple_Check(args));
1452
1453 retval = PyObject_Call(func, args, NULL);
1454 Py_DECREF(args);
Victor Stinner94463c92016-08-19 18:01:41 +02001455 }
1456 else {
Victor Stinner559bb6a2016-08-22 22:48:54 +02001457 retval = _PyObject_CallNoArg(func);
Victor Stinnerd925bd52016-08-19 17:51:49 +02001458 }
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001459
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001460 Py_DECREF(func);
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001461
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001462 return retval;
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001463}
1464
1465/* Clone of call_method() that returns NotImplemented when the lookup fails. */
1466
Neil Schemenauerf23473f2001-10-21 22:28:58 +00001467static PyObject *
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001468call_maybe(PyObject *o, _Py_Identifier *nameid, const char *format, ...)
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001469{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001470 va_list va;
Victor Stinnerf736c262016-08-19 18:05:37 +02001471 PyObject *func = NULL, *retval;
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001472
Benjamin Petersonce798522012-01-22 11:24:29 -05001473 func = lookup_maybe(o, nameid);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001474 if (func == NULL) {
Brian Curtindfc80e32011-08-10 20:28:54 -05001475 if (!PyErr_Occurred())
1476 Py_RETURN_NOTIMPLEMENTED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001477 return NULL;
1478 }
Guido van Rossum2730b132001-08-28 18:22:14 +00001479
Victor Stinner94463c92016-08-19 18:01:41 +02001480 if (format && *format) {
Victor Stinnerf736c262016-08-19 18:05:37 +02001481 PyObject *args;
1482
Victor Stinner94463c92016-08-19 18:01:41 +02001483 va_start(va, format);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001484 args = Py_VaBuildValue(format, va);
Victor Stinner94463c92016-08-19 18:01:41 +02001485 va_end(va);
Victor Stinnerf736c262016-08-19 18:05:37 +02001486
1487 if (args == NULL) {
1488 Py_DECREF(func);
1489 return NULL;
1490 }
1491 assert(PyTuple_Check(args));
1492
1493 retval = PyObject_Call(func, args, NULL);
1494 Py_DECREF(args);
Victor Stinner94463c92016-08-19 18:01:41 +02001495 }
1496 else {
Victor Stinner559bb6a2016-08-22 22:48:54 +02001497 retval = _PyObject_CallNoArg(func);
Victor Stinner6902ddf2016-08-19 17:58:12 +02001498 }
Guido van Rossum2730b132001-08-28 18:22:14 +00001499
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001500 Py_DECREF(func);
Guido van Rossum2730b132001-08-28 18:22:14 +00001501
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001502 return retval;
Guido van Rossum2730b132001-08-28 18:22:14 +00001503}
1504
Tim Petersea7f75d2002-12-07 21:39:16 +00001505/*
Guido van Rossum1f121312002-11-14 19:49:16 +00001506 Method resolution order algorithm C3 described in
1507 "A Monotonic Superclass Linearization for Dylan",
1508 by Kim Barrett, Bob Cassel, Paul Haahr,
Tim Petersea7f75d2002-12-07 21:39:16 +00001509 David A. Moon, Keith Playford, and P. Tucker Withington.
Guido van Rossum1f121312002-11-14 19:49:16 +00001510 (OOPSLA 1996)
1511
Guido van Rossum98f33732002-11-25 21:36:54 +00001512 Some notes about the rules implied by C3:
1513
Tim Petersea7f75d2002-12-07 21:39:16 +00001514 No duplicate bases.
Guido van Rossum98f33732002-11-25 21:36:54 +00001515 It isn't legal to repeat a class in a list of base classes.
1516
1517 The next three properties are the 3 constraints in "C3".
1518
Martin Panter69332c12016-08-04 13:07:31 +00001519 Local precedence order.
Guido van Rossum98f33732002-11-25 21:36:54 +00001520 If A precedes B in C's MRO, then A will precede B in the MRO of all
1521 subclasses of C.
1522
1523 Monotonicity.
1524 The MRO of a class must be an extension without reordering of the
1525 MRO of each of its superclasses.
1526
1527 Extended Precedence Graph (EPG).
1528 Linearization is consistent if there is a path in the EPG from
1529 each class to all its successors in the linearization. See
1530 the paper for definition of EPG.
Guido van Rossum1f121312002-11-14 19:49:16 +00001531 */
1532
Tim Petersea7f75d2002-12-07 21:39:16 +00001533static int
Guido van Rossum1f121312002-11-14 19:49:16 +00001534tail_contains(PyObject *list, int whence, PyObject *o) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001535 Py_ssize_t j, size;
1536 size = PyList_GET_SIZE(list);
Guido van Rossum1f121312002-11-14 19:49:16 +00001537
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001538 for (j = whence+1; j < size; j++) {
1539 if (PyList_GET_ITEM(list, j) == o)
1540 return 1;
1541 }
1542 return 0;
Guido van Rossum1f121312002-11-14 19:49:16 +00001543}
1544
Guido van Rossum98f33732002-11-25 21:36:54 +00001545static PyObject *
1546class_name(PyObject *cls)
1547{
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001548 PyObject *name = _PyObject_GetAttrId(cls, &PyId___name__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001549 if (name == NULL) {
1550 PyErr_Clear();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001551 name = PyObject_Repr(cls);
1552 }
1553 if (name == NULL)
1554 return NULL;
1555 if (!PyUnicode_Check(name)) {
1556 Py_DECREF(name);
1557 return NULL;
1558 }
1559 return name;
Guido van Rossum98f33732002-11-25 21:36:54 +00001560}
1561
1562static int
1563check_duplicates(PyObject *list)
1564{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001565 Py_ssize_t i, j, n;
1566 /* Let's use a quadratic time algorithm,
1567 assuming that the bases lists is short.
1568 */
1569 n = PyList_GET_SIZE(list);
1570 for (i = 0; i < n; i++) {
1571 PyObject *o = PyList_GET_ITEM(list, i);
1572 for (j = i + 1; j < n; j++) {
1573 if (PyList_GET_ITEM(list, j) == o) {
1574 o = class_name(o);
1575 if (o != NULL) {
1576 PyErr_Format(PyExc_TypeError,
1577 "duplicate base class %U",
1578 o);
1579 Py_DECREF(o);
1580 } else {
1581 PyErr_SetString(PyExc_TypeError,
1582 "duplicate base class");
1583 }
1584 return -1;
1585 }
1586 }
1587 }
1588 return 0;
Guido van Rossum98f33732002-11-25 21:36:54 +00001589}
1590
1591/* Raise a TypeError for an MRO order disagreement.
1592
1593 It's hard to produce a good error message. In the absence of better
1594 insight into error reporting, report the classes that were candidates
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001595 to be put next into the MRO. There is some conflict between the
Guido van Rossum98f33732002-11-25 21:36:54 +00001596 order in which they should be put in the MRO, but it's hard to
1597 diagnose what constraint can't be satisfied.
1598*/
1599
1600static void
1601set_mro_error(PyObject *to_merge, int *remain)
1602{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001603 Py_ssize_t i, n, off, to_merge_size;
1604 char buf[1000];
1605 PyObject *k, *v;
1606 PyObject *set = PyDict_New();
1607 if (!set) return;
Guido van Rossum98f33732002-11-25 21:36:54 +00001608
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001609 to_merge_size = PyList_GET_SIZE(to_merge);
1610 for (i = 0; i < to_merge_size; i++) {
1611 PyObject *L = PyList_GET_ITEM(to_merge, i);
1612 if (remain[i] < PyList_GET_SIZE(L)) {
1613 PyObject *c = PyList_GET_ITEM(L, remain[i]);
1614 if (PyDict_SetItem(set, c, Py_None) < 0) {
1615 Py_DECREF(set);
1616 return;
1617 }
1618 }
1619 }
1620 n = PyDict_Size(set);
Guido van Rossum98f33732002-11-25 21:36:54 +00001621
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001622 off = PyOS_snprintf(buf, sizeof(buf), "Cannot create a \
Raymond Hettingerf394df42003-04-06 19:13:41 +00001623consistent method resolution\norder (MRO) for bases");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001624 i = 0;
1625 while (PyDict_Next(set, &i, &k, &v) && (size_t)off < sizeof(buf)) {
1626 PyObject *name = class_name(k);
Victor Stinnere5f99f32010-05-19 01:42:46 +00001627 char *name_str;
1628 if (name != NULL) {
Serhiy Storchaka06515832016-11-20 09:13:07 +02001629 name_str = PyUnicode_AsUTF8(name);
Victor Stinnere5f99f32010-05-19 01:42:46 +00001630 if (name_str == NULL)
Victor Stinnerba644a62010-05-19 01:50:45 +00001631 name_str = "?";
Victor Stinnere5f99f32010-05-19 01:42:46 +00001632 } else
Victor Stinnerba644a62010-05-19 01:50:45 +00001633 name_str = "?";
Victor Stinnere5f99f32010-05-19 01:42:46 +00001634 off += PyOS_snprintf(buf + off, sizeof(buf) - off, " %s", name_str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001635 Py_XDECREF(name);
1636 if (--n && (size_t)(off+1) < sizeof(buf)) {
1637 buf[off++] = ',';
1638 buf[off] = '\0';
1639 }
1640 }
1641 PyErr_SetString(PyExc_TypeError, buf);
1642 Py_DECREF(set);
Guido van Rossum98f33732002-11-25 21:36:54 +00001643}
1644
Tim Petersea7f75d2002-12-07 21:39:16 +00001645static int
Benjamin Peterson104b9e02015-02-05 22:29:14 -05001646pmerge(PyObject *acc, PyObject* to_merge)
1647{
1648 int res = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001649 Py_ssize_t i, j, to_merge_size, empty_cnt;
1650 int *remain;
Tim Petersea7f75d2002-12-07 21:39:16 +00001651
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001652 to_merge_size = PyList_GET_SIZE(to_merge);
Guido van Rossum1f121312002-11-14 19:49:16 +00001653
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001654 /* remain stores an index into each sublist of to_merge.
1655 remain[i] is the index of the next base in to_merge[i]
1656 that is not included in acc.
1657 */
1658 remain = (int *)PyMem_MALLOC(SIZEOF_INT*to_merge_size);
Victor Stinnera41f0852013-07-12 00:42:14 +02001659 if (remain == NULL) {
1660 PyErr_NoMemory();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001661 return -1;
Victor Stinnera41f0852013-07-12 00:42:14 +02001662 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001663 for (i = 0; i < to_merge_size; i++)
1664 remain[i] = 0;
Guido van Rossum1f121312002-11-14 19:49:16 +00001665
1666 again:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001667 empty_cnt = 0;
1668 for (i = 0; i < to_merge_size; i++) {
1669 PyObject *candidate;
Tim Petersea7f75d2002-12-07 21:39:16 +00001670
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001671 PyObject *cur_list = PyList_GET_ITEM(to_merge, i);
Guido van Rossum1f121312002-11-14 19:49:16 +00001672
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001673 if (remain[i] >= PyList_GET_SIZE(cur_list)) {
1674 empty_cnt++;
1675 continue;
1676 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001677
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001678 /* Choose next candidate for MRO.
Guido van Rossum98f33732002-11-25 21:36:54 +00001679
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001680 The input sequences alone can determine the choice.
1681 If not, choose the class which appears in the MRO
1682 of the earliest direct superclass of the new class.
1683 */
Guido van Rossum98f33732002-11-25 21:36:54 +00001684
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001685 candidate = PyList_GET_ITEM(cur_list, remain[i]);
1686 for (j = 0; j < to_merge_size; j++) {
1687 PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
Benjamin Peterson104b9e02015-02-05 22:29:14 -05001688 if (tail_contains(j_lst, remain[j], candidate))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001689 goto skip; /* continue outer loop */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001690 }
Benjamin Peterson104b9e02015-02-05 22:29:14 -05001691 res = PyList_Append(acc, candidate);
1692 if (res < 0)
1693 goto out;
1694
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001695 for (j = 0; j < to_merge_size; j++) {
1696 PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
1697 if (remain[j] < PyList_GET_SIZE(j_lst) &&
1698 PyList_GET_ITEM(j_lst, remain[j]) == candidate) {
1699 remain[j]++;
1700 }
1701 }
1702 goto again;
1703 skip: ;
1704 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001705
Benjamin Peterson104b9e02015-02-05 22:29:14 -05001706 if (empty_cnt != to_merge_size) {
1707 set_mro_error(to_merge, remain);
1708 res = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001709 }
Benjamin Peterson104b9e02015-02-05 22:29:14 -05001710
1711 out:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001712 PyMem_FREE(remain);
Benjamin Peterson104b9e02015-02-05 22:29:14 -05001713
1714 return res;
Guido van Rossum1f121312002-11-14 19:49:16 +00001715}
1716
Tim Peters6d6c1a32001-08-02 04:15:00 +00001717static PyObject *
1718mro_implementation(PyTypeObject *type)
1719{
Benjamin Peterson104b9e02015-02-05 22:29:14 -05001720 PyObject *result = NULL;
1721 PyObject *bases;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001722 PyObject *to_merge, *bases_aslist;
Benjamin Peterson104b9e02015-02-05 22:29:14 -05001723 int res;
1724 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001725
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001726 if (type->tp_dict == NULL) {
1727 if (PyType_Ready(type) < 0)
1728 return NULL;
1729 }
Guido van Rossum63517572002-06-18 16:44:57 +00001730
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001731 /* Find a superclass linearization that honors the constraints
1732 of the explicit lists of bases and the constraints implied by
1733 each base class.
Guido van Rossum98f33732002-11-25 21:36:54 +00001734
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001735 to_merge is a list of lists, where each list is a superclass
1736 linearization implied by a base class. The last element of
1737 to_merge is the declared list of bases.
1738 */
Guido van Rossum98f33732002-11-25 21:36:54 +00001739
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001740 bases = type->tp_bases;
1741 n = PyTuple_GET_SIZE(bases);
Guido van Rossum1f121312002-11-14 19:49:16 +00001742
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001743 to_merge = PyList_New(n+1);
1744 if (to_merge == NULL)
1745 return NULL;
Guido van Rossum1f121312002-11-14 19:49:16 +00001746
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001747 for (i = 0; i < n; i++) {
Benjamin Peterson104b9e02015-02-05 22:29:14 -05001748 PyTypeObject *base;
1749 PyObject *base_mro_aslist;
1750
1751 base = (PyTypeObject *)PyTuple_GET_ITEM(bases, i);
1752 if (base->tp_mro == NULL) {
1753 PyErr_Format(PyExc_TypeError,
1754 "Cannot extend an incomplete type '%.100s'",
1755 base->tp_name);
1756 goto out;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001757 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001758
Benjamin Peterson104b9e02015-02-05 22:29:14 -05001759 base_mro_aslist = PySequence_List(base->tp_mro);
1760 if (base_mro_aslist == NULL)
1761 goto out;
1762
1763 PyList_SET_ITEM(to_merge, i, base_mro_aslist);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001764 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001765
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001766 bases_aslist = PySequence_List(bases);
Benjamin Peterson104b9e02015-02-05 22:29:14 -05001767 if (bases_aslist == NULL)
1768 goto out;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001769 /* This is just a basic sanity check. */
1770 if (check_duplicates(bases_aslist) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001771 Py_DECREF(bases_aslist);
Benjamin Peterson104b9e02015-02-05 22:29:14 -05001772 goto out;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001773 }
1774 PyList_SET_ITEM(to_merge, n, bases_aslist);
Guido van Rossum1f121312002-11-14 19:49:16 +00001775
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001776 result = Py_BuildValue("[O]", (PyObject *)type);
Benjamin Peterson104b9e02015-02-05 22:29:14 -05001777 if (result == NULL)
1778 goto out;
Guido van Rossum1f121312002-11-14 19:49:16 +00001779
Benjamin Peterson104b9e02015-02-05 22:29:14 -05001780 res = pmerge(result, to_merge);
1781 if (res < 0)
1782 Py_CLEAR(result);
1783
1784 out:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001785 Py_DECREF(to_merge);
Guido van Rossum1f121312002-11-14 19:49:16 +00001786
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001787 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001788}
1789
1790static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001791mro_external(PyObject *self)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001792{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001793 PyTypeObject *type = (PyTypeObject *)self;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001794
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001795 return mro_implementation(type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001796}
1797
1798static int
Benjamin Peterson104b9e02015-02-05 22:29:14 -05001799mro_check(PyTypeObject *type, PyObject *mro)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001800{
Benjamin Peterson104b9e02015-02-05 22:29:14 -05001801 PyTypeObject *solid;
1802 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001803
Benjamin Peterson104b9e02015-02-05 22:29:14 -05001804 solid = solid_base(type);
1805
1806 n = PyTuple_GET_SIZE(mro);
1807 for (i = 0; i < n; i++) {
1808 PyTypeObject *base;
1809 PyObject *tmp;
1810
1811 tmp = PyTuple_GET_ITEM(mro, i);
1812 if (!PyType_Check(tmp)) {
1813 PyErr_Format(
1814 PyExc_TypeError,
1815 "mro() returned a non-class ('%.500s')",
1816 Py_TYPE(tmp)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001817 return -1;
Benjamin Peterson104b9e02015-02-05 22:29:14 -05001818 }
Armin Rigo037d1e02005-12-29 17:07:39 +00001819
Benjamin Peterson104b9e02015-02-05 22:29:14 -05001820 base = (PyTypeObject*)tmp;
1821 if (!PyType_IsSubtype(solid, solid_base(base))) {
1822 PyErr_Format(
1823 PyExc_TypeError,
1824 "mro() returned base with unsuitable layout ('%.500s')",
1825 base->tp_name);
1826 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001827 }
1828 }
Benjamin Peterson104b9e02015-02-05 22:29:14 -05001829
1830 return 0;
1831}
1832
1833/* Lookups an mcls.mro method, invokes it and checks the result (if needed,
1834 in case of a custom mro() implementation).
1835
1836 Keep in mind that during execution of this function type->tp_mro
1837 can be replaced due to possible reentrance (for example,
1838 through type_set_bases):
1839
1840 - when looking up the mcls.mro attribute (it could be
1841 a user-provided descriptor);
1842
1843 - from inside a custom mro() itself;
1844
1845 - through a finalizer of the return value of mro().
1846*/
1847static PyObject *
1848mro_invoke(PyTypeObject *type)
1849{
1850 PyObject *mro_result;
1851 PyObject *new_mro;
1852 int custom = (Py_TYPE(type) != &PyType_Type);
1853
1854 if (custom) {
1855 _Py_IDENTIFIER(mro);
1856 PyObject *mro_meth = lookup_method((PyObject *)type, &PyId_mro);
1857 if (mro_meth == NULL)
1858 return NULL;
1859 mro_result = PyObject_CallObject(mro_meth, NULL);
1860 Py_DECREF(mro_meth);
1861 }
1862 else {
1863 mro_result = mro_implementation(type);
1864 }
1865 if (mro_result == NULL)
1866 return NULL;
1867
1868 new_mro = PySequence_Tuple(mro_result);
1869 Py_DECREF(mro_result);
1870 if (new_mro == NULL)
1871 return NULL;
1872
1873 if (custom && mro_check(type, new_mro) < 0) {
1874 Py_DECREF(new_mro);
1875 return NULL;
1876 }
1877
1878 return new_mro;
1879}
1880
1881/* Calculates and assigns a new MRO to type->tp_mro.
1882 Return values and invariants:
1883
1884 - Returns 1 if a new MRO value has been set to type->tp_mro due to
1885 this call of mro_internal (no tricky reentrancy and no errors).
1886
1887 In case if p_old_mro argument is not NULL, a previous value
1888 of type->tp_mro is put there, and the ownership of this
1889 reference is transferred to a caller.
1890 Otherwise, the previous value (if any) is decref'ed.
1891
1892 - Returns 0 in case when type->tp_mro gets changed because of
1893 reentering here through a custom mro() (see a comment to mro_invoke).
1894
1895 In this case, a refcount of an old type->tp_mro is adjusted
1896 somewhere deeper in the call stack (by the innermost mro_internal
1897 or its caller) and may become zero upon returning from here.
1898 This also implies that the whole hierarchy of subclasses of the type
1899 has seen the new value and updated their MRO accordingly.
1900
1901 - Returns -1 in case of an error.
1902*/
1903static int
1904mro_internal(PyTypeObject *type, PyObject **p_old_mro)
1905{
1906 PyObject *new_mro, *old_mro;
1907 int reent;
1908
1909 /* Keep a reference to be able to do a reentrancy check below.
1910 Don't let old_mro be GC'ed and its address be reused for
1911 another object, like (suddenly!) a new tp_mro. */
1912 old_mro = type->tp_mro;
1913 Py_XINCREF(old_mro);
1914 new_mro = mro_invoke(type); /* might cause reentrance */
1915 reent = (type->tp_mro != old_mro);
1916 Py_XDECREF(old_mro);
1917 if (new_mro == NULL)
1918 return -1;
1919
1920 if (reent) {
1921 Py_DECREF(new_mro);
1922 return 0;
1923 }
1924
1925 type->tp_mro = new_mro;
Christian Heimesa62da1d2008-01-12 19:39:10 +00001926
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001927 type_mro_modified(type, type->tp_mro);
Florent Xiclunaaa6c1d22011-12-12 18:54:29 +01001928 /* corner case: the super class might have been hidden
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001929 from the custom MRO */
1930 type_mro_modified(type, type->tp_bases);
Christian Heimesa62da1d2008-01-12 19:39:10 +00001931
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001932 PyType_Modified(type);
Christian Heimesa62da1d2008-01-12 19:39:10 +00001933
Benjamin Peterson104b9e02015-02-05 22:29:14 -05001934 if (p_old_mro != NULL)
1935 *p_old_mro = old_mro; /* transfer the ownership */
1936 else
1937 Py_XDECREF(old_mro);
1938
1939 return 1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001940}
1941
1942
1943/* Calculate the best base amongst multiple base classes.
1944 This is the first one that's on the path to the "solid base". */
1945
1946static PyTypeObject *
1947best_base(PyObject *bases)
1948{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001949 Py_ssize_t i, n;
1950 PyTypeObject *base, *winner, *candidate, *base_i;
1951 PyObject *base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001952
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001953 assert(PyTuple_Check(bases));
1954 n = PyTuple_GET_SIZE(bases);
1955 assert(n > 0);
1956 base = NULL;
1957 winner = NULL;
1958 for (i = 0; i < n; i++) {
1959 base_proto = PyTuple_GET_ITEM(bases, i);
1960 if (!PyType_Check(base_proto)) {
1961 PyErr_SetString(
1962 PyExc_TypeError,
1963 "bases must be types");
1964 return NULL;
1965 }
1966 base_i = (PyTypeObject *)base_proto;
1967 if (base_i->tp_dict == NULL) {
1968 if (PyType_Ready(base_i) < 0)
1969 return NULL;
1970 }
Benjamin Petersonbd6c41a2015-10-06 19:36:54 -07001971 if (!PyType_HasFeature(base_i, Py_TPFLAGS_BASETYPE)) {
1972 PyErr_Format(PyExc_TypeError,
1973 "type '%.100s' is not an acceptable base type",
1974 base_i->tp_name);
1975 return NULL;
1976 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001977 candidate = solid_base(base_i);
1978 if (winner == NULL) {
1979 winner = candidate;
1980 base = base_i;
1981 }
1982 else if (PyType_IsSubtype(winner, candidate))
1983 ;
1984 else if (PyType_IsSubtype(candidate, winner)) {
1985 winner = candidate;
1986 base = base_i;
1987 }
1988 else {
1989 PyErr_SetString(
1990 PyExc_TypeError,
1991 "multiple bases have "
1992 "instance lay-out conflict");
1993 return NULL;
1994 }
1995 }
Florent Xiclunaaa6c1d22011-12-12 18:54:29 +01001996 assert (base != NULL);
1997
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001998 return base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001999}
2000
2001static int
2002extra_ivars(PyTypeObject *type, PyTypeObject *base)
2003{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002004 size_t t_size = type->tp_basicsize;
2005 size_t b_size = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002006
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002007 assert(t_size >= b_size); /* Else type smaller than base! */
2008 if (type->tp_itemsize || base->tp_itemsize) {
2009 /* If itemsize is involved, stricter rules */
2010 return t_size != b_size ||
2011 type->tp_itemsize != base->tp_itemsize;
2012 }
2013 if (type->tp_weaklistoffset && base->tp_weaklistoffset == 0 &&
2014 type->tp_weaklistoffset + sizeof(PyObject *) == t_size &&
2015 type->tp_flags & Py_TPFLAGS_HEAPTYPE)
2016 t_size -= sizeof(PyObject *);
2017 if (type->tp_dictoffset && base->tp_dictoffset == 0 &&
2018 type->tp_dictoffset + sizeof(PyObject *) == t_size &&
2019 type->tp_flags & Py_TPFLAGS_HEAPTYPE)
2020 t_size -= sizeof(PyObject *);
Guido van Rossum9676b222001-08-17 20:32:36 +00002021
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002022 return t_size != b_size;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002023}
2024
2025static PyTypeObject *
2026solid_base(PyTypeObject *type)
2027{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002028 PyTypeObject *base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002029
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002030 if (type->tp_base)
2031 base = solid_base(type->tp_base);
2032 else
2033 base = &PyBaseObject_Type;
2034 if (extra_ivars(type, base))
2035 return type;
2036 else
2037 return base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002038}
2039
Jeremy Hylton938ace62002-07-17 16:30:39 +00002040static void object_dealloc(PyObject *);
2041static int object_init(PyObject *, PyObject *, PyObject *);
2042static int update_slot(PyTypeObject *, PyObject *);
2043static void fixup_slot_dispatchers(PyTypeObject *);
Nick Coghland78448e2016-07-30 16:26:03 +10002044static int set_names(PyTypeObject *);
2045static int init_subclass(PyTypeObject *, PyObject *);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002046
Guido van Rossum360e4b82007-05-14 22:51:27 +00002047/*
2048 * Helpers for __dict__ descriptor. We don't want to expose the dicts
2049 * inherited from various builtin types. The builtin base usually provides
2050 * its own __dict__ descriptor, so we use that when we can.
2051 */
2052static PyTypeObject *
2053get_builtin_base_with_dict(PyTypeObject *type)
2054{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002055 while (type->tp_base != NULL) {
2056 if (type->tp_dictoffset != 0 &&
2057 !(type->tp_flags & Py_TPFLAGS_HEAPTYPE))
2058 return type;
2059 type = type->tp_base;
2060 }
2061 return NULL;
Guido van Rossum360e4b82007-05-14 22:51:27 +00002062}
2063
2064static PyObject *
2065get_dict_descriptor(PyTypeObject *type)
2066{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002067 PyObject *descr;
Guido van Rossum360e4b82007-05-14 22:51:27 +00002068
Victor Stinner3c1e4812012-03-26 22:10:51 +02002069 descr = _PyType_LookupId(type, &PyId___dict__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002070 if (descr == NULL || !PyDescr_IsData(descr))
2071 return NULL;
Guido van Rossum360e4b82007-05-14 22:51:27 +00002072
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002073 return descr;
Guido van Rossum360e4b82007-05-14 22:51:27 +00002074}
2075
2076static void
2077raise_dict_descr_error(PyObject *obj)
2078{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002079 PyErr_Format(PyExc_TypeError,
2080 "this __dict__ descriptor does not support "
2081 "'%.200s' objects", Py_TYPE(obj)->tp_name);
Guido van Rossum360e4b82007-05-14 22:51:27 +00002082}
2083
Tim Peters6d6c1a32001-08-02 04:15:00 +00002084static PyObject *
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00002085subtype_dict(PyObject *obj, void *context)
2086{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002087 PyTypeObject *base;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00002088
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002089 base = get_builtin_base_with_dict(Py_TYPE(obj));
2090 if (base != NULL) {
2091 descrgetfunc func;
2092 PyObject *descr = get_dict_descriptor(base);
2093 if (descr == NULL) {
2094 raise_dict_descr_error(obj);
2095 return NULL;
2096 }
2097 func = Py_TYPE(descr)->tp_descr_get;
2098 if (func == NULL) {
2099 raise_dict_descr_error(obj);
2100 return NULL;
2101 }
2102 return func(descr, obj, (PyObject *)(Py_TYPE(obj)));
2103 }
Benjamin Peterson8eb12692012-02-19 19:59:10 -05002104 return PyObject_GenericGetDict(obj, context);
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00002105}
2106
Guido van Rossum6661be32001-10-26 04:26:12 +00002107static int
2108subtype_setdict(PyObject *obj, PyObject *value, void *context)
2109{
Serhiy Storchaka576f1322016-01-05 21:27:54 +02002110 PyObject **dictptr;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002111 PyTypeObject *base;
Guido van Rossum6661be32001-10-26 04:26:12 +00002112
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002113 base = get_builtin_base_with_dict(Py_TYPE(obj));
2114 if (base != NULL) {
2115 descrsetfunc func;
2116 PyObject *descr = get_dict_descriptor(base);
2117 if (descr == NULL) {
2118 raise_dict_descr_error(obj);
2119 return -1;
2120 }
2121 func = Py_TYPE(descr)->tp_descr_set;
2122 if (func == NULL) {
2123 raise_dict_descr_error(obj);
2124 return -1;
2125 }
2126 return func(descr, obj, value);
2127 }
Benjamin Peterson8eb12692012-02-19 19:59:10 -05002128 /* Almost like PyObject_GenericSetDict, but allow __dict__ to be deleted. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002129 dictptr = _PyObject_GetDictPtr(obj);
2130 if (dictptr == NULL) {
2131 PyErr_SetString(PyExc_AttributeError,
2132 "This object has no __dict__");
2133 return -1;
2134 }
Benjamin Peterson006c5a22012-02-19 20:36:12 -05002135 if (value != NULL && !PyDict_Check(value)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002136 PyErr_Format(PyExc_TypeError,
2137 "__dict__ must be set to a dictionary, "
2138 "not a '%.200s'", Py_TYPE(value)->tp_name);
2139 return -1;
2140 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002141 Py_XINCREF(value);
Serhiy Storchakaec397562016-04-06 09:50:03 +03002142 Py_XSETREF(*dictptr, value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002143 return 0;
Guido van Rossum6661be32001-10-26 04:26:12 +00002144}
2145
Guido van Rossumad47da02002-08-12 19:05:44 +00002146static PyObject *
2147subtype_getweakref(PyObject *obj, void *context)
2148{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002149 PyObject **weaklistptr;
2150 PyObject *result;
Guido van Rossumad47da02002-08-12 19:05:44 +00002151
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002152 if (Py_TYPE(obj)->tp_weaklistoffset == 0) {
2153 PyErr_SetString(PyExc_AttributeError,
2154 "This object has no __weakref__");
2155 return NULL;
2156 }
2157 assert(Py_TYPE(obj)->tp_weaklistoffset > 0);
2158 assert(Py_TYPE(obj)->tp_weaklistoffset + sizeof(PyObject *) <=
2159 (size_t)(Py_TYPE(obj)->tp_basicsize));
2160 weaklistptr = (PyObject **)
2161 ((char *)obj + Py_TYPE(obj)->tp_weaklistoffset);
2162 if (*weaklistptr == NULL)
2163 result = Py_None;
2164 else
2165 result = *weaklistptr;
2166 Py_INCREF(result);
2167 return result;
Guido van Rossumad47da02002-08-12 19:05:44 +00002168}
2169
Guido van Rossum373c7412003-01-07 13:41:37 +00002170/* Three variants on the subtype_getsets list. */
2171
2172static PyGetSetDef subtype_getsets_full[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002173 {"__dict__", subtype_dict, subtype_setdict,
2174 PyDoc_STR("dictionary for instance variables (if defined)")},
2175 {"__weakref__", subtype_getweakref, NULL,
2176 PyDoc_STR("list of weak references to the object (if defined)")},
2177 {0}
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00002178};
2179
Guido van Rossum373c7412003-01-07 13:41:37 +00002180static PyGetSetDef subtype_getsets_dict_only[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002181 {"__dict__", subtype_dict, subtype_setdict,
2182 PyDoc_STR("dictionary for instance variables (if defined)")},
2183 {0}
Guido van Rossum373c7412003-01-07 13:41:37 +00002184};
2185
2186static PyGetSetDef subtype_getsets_weakref_only[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002187 {"__weakref__", subtype_getweakref, NULL,
2188 PyDoc_STR("list of weak references to the object (if defined)")},
2189 {0}
Guido van Rossum373c7412003-01-07 13:41:37 +00002190};
2191
Guido van Rossum9923ffe2002-06-04 19:52:53 +00002192static int
2193valid_identifier(PyObject *s)
2194{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002195 if (!PyUnicode_Check(s)) {
2196 PyErr_Format(PyExc_TypeError,
2197 "__slots__ items must be strings, not '%.200s'",
2198 Py_TYPE(s)->tp_name);
2199 return 0;
2200 }
2201 if (!PyUnicode_IsIdentifier(s)) {
2202 PyErr_SetString(PyExc_TypeError,
2203 "__slots__ must be identifiers");
2204 return 0;
2205 }
2206 return 1;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00002207}
2208
Guido van Rossumd8faa362007-04-27 19:54:29 +00002209/* Forward */
2210static int
2211object_init(PyObject *self, PyObject *args, PyObject *kwds);
2212
2213static int
2214type_init(PyObject *cls, PyObject *args, PyObject *kwds)
2215{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002216 int res;
Guido van Rossumd8faa362007-04-27 19:54:29 +00002217
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002218 assert(args != NULL && PyTuple_Check(args));
2219 assert(kwds == NULL || PyDict_Check(kwds));
Guido van Rossumd8faa362007-04-27 19:54:29 +00002220
Nick Coghland78448e2016-07-30 16:26:03 +10002221 if (kwds != NULL && PyTuple_Check(args) && PyTuple_GET_SIZE(args) == 1 &&
2222 PyDict_Check(kwds) && PyDict_Size(kwds) != 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002223 PyErr_SetString(PyExc_TypeError,
2224 "type.__init__() takes no keyword arguments");
2225 return -1;
2226 }
Guido van Rossumd8faa362007-04-27 19:54:29 +00002227
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002228 if (args != NULL && PyTuple_Check(args) &&
2229 (PyTuple_GET_SIZE(args) != 1 && PyTuple_GET_SIZE(args) != 3)) {
2230 PyErr_SetString(PyExc_TypeError,
2231 "type.__init__() takes 1 or 3 arguments");
2232 return -1;
2233 }
Guido van Rossumd8faa362007-04-27 19:54:29 +00002234
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002235 /* Call object.__init__(self) now. */
2236 /* XXX Could call super(type, cls).__init__() but what's the point? */
2237 args = PyTuple_GetSlice(args, 0, 0);
2238 res = object_init(cls, args, NULL);
2239 Py_DECREF(args);
2240 return res;
Guido van Rossumd8faa362007-04-27 19:54:29 +00002241}
2242
Victor Stinner4ca1cf32012-10-30 23:40:45 +01002243unsigned long
Martin v. Löwis738236d2011-02-05 20:35:29 +00002244PyType_GetFlags(PyTypeObject *type)
2245{
2246 return type->tp_flags;
2247}
2248
Nick Coghlande31b192011-10-23 22:04:16 +10002249/* Determine the most derived metatype. */
2250PyTypeObject *
2251_PyType_CalculateMetaclass(PyTypeObject *metatype, PyObject *bases)
2252{
2253 Py_ssize_t i, nbases;
2254 PyTypeObject *winner;
2255 PyObject *tmp;
2256 PyTypeObject *tmptype;
2257
2258 /* Determine the proper metatype to deal with this,
2259 and check for metatype conflicts while we're at it.
2260 Note that if some other metatype wins to contract,
2261 it's possible that its instances are not types. */
2262
2263 nbases = PyTuple_GET_SIZE(bases);
2264 winner = metatype;
2265 for (i = 0; i < nbases; i++) {
2266 tmp = PyTuple_GET_ITEM(bases, i);
2267 tmptype = Py_TYPE(tmp);
2268 if (PyType_IsSubtype(winner, tmptype))
2269 continue;
2270 if (PyType_IsSubtype(tmptype, winner)) {
2271 winner = tmptype;
2272 continue;
2273 }
2274 /* else: */
2275 PyErr_SetString(PyExc_TypeError,
2276 "metaclass conflict: "
2277 "the metaclass of a derived class "
2278 "must be a (non-strict) subclass "
2279 "of the metaclasses of all its bases");
2280 return NULL;
2281 }
2282 return winner;
2283}
2284
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00002285static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00002286type_new(PyTypeObject *metatype, PyObject *args, PyObject *kwds)
2287{
Victor Stinner6f738742012-02-25 01:22:36 +01002288 PyObject *name, *bases = NULL, *orig_dict, *dict = NULL;
Nick Coghlan944368e2016-09-11 14:45:49 +10002289 PyObject *qualname, *slots = NULL, *tmp, *newslots, *cell;
Victor Stinner6f738742012-02-25 01:22:36 +01002290 PyTypeObject *type = NULL, *base, *tmptype, *winner;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002291 PyHeapTypeObject *et;
2292 PyMemberDef *mp;
Serhiy Storchaka42bf8fc2015-12-30 21:40:49 +02002293 Py_ssize_t i, nbases, nslots, slotoffset, name_size;
2294 int j, may_add_dict, may_add_weak, add_dict, add_weak;
Victor Stinner3c1e4812012-03-26 22:10:51 +02002295 _Py_IDENTIFIER(__qualname__);
2296 _Py_IDENTIFIER(__slots__);
Nick Coghlan944368e2016-09-11 14:45:49 +10002297 _Py_IDENTIFIER(__classcell__);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002298
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002299 assert(args != NULL && PyTuple_Check(args));
2300 assert(kwds == NULL || PyDict_Check(kwds));
Tim Peters3abca122001-10-27 19:37:48 +00002301
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002302 /* Special case: type(x) should return x->ob_type */
Berker Peksag3f015a62016-08-19 11:04:07 +03002303 /* We only want type itself to accept the one-argument form (#27157)
2304 Note: We don't call PyType_CheckExact as that also allows subclasses */
2305 if (metatype == &PyType_Type) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002306 const Py_ssize_t nargs = PyTuple_GET_SIZE(args);
2307 const Py_ssize_t nkwds = kwds == NULL ? 0 : PyDict_Size(kwds);
Tim Peters3abca122001-10-27 19:37:48 +00002308
Berker Peksag3f015a62016-08-19 11:04:07 +03002309 if (nargs == 1 && nkwds == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002310 PyObject *x = PyTuple_GET_ITEM(args, 0);
2311 Py_INCREF(Py_TYPE(x));
2312 return (PyObject *) Py_TYPE(x);
2313 }
Tim Peters3abca122001-10-27 19:37:48 +00002314
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002315 /* SF bug 475327 -- if that didn't trigger, we need 3
2316 arguments. but PyArg_ParseTupleAndKeywords below may give
2317 a msg saying type() needs exactly 3. */
Nick Coghland78448e2016-07-30 16:26:03 +10002318 if (nargs != 3) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002319 PyErr_SetString(PyExc_TypeError,
2320 "type() takes 1 or 3 arguments");
2321 return NULL;
2322 }
2323 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002324
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002325 /* Check arguments: (name, bases, dict) */
Berker Peksag3f015a62016-08-19 11:04:07 +03002326 if (!PyArg_ParseTuple(args, "UO!O!:type.__new__", &name, &PyTuple_Type,
2327 &bases, &PyDict_Type, &orig_dict))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002328 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002329
Nick Coghlande31b192011-10-23 22:04:16 +10002330 /* Determine the proper metatype to deal with this: */
2331 winner = _PyType_CalculateMetaclass(metatype, bases);
2332 if (winner == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002333 return NULL;
2334 }
Nick Coghlande31b192011-10-23 22:04:16 +10002335
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002336 if (winner != metatype) {
2337 if (winner->tp_new != type_new) /* Pass it to the winner */
2338 return winner->tp_new(winner, args, kwds);
2339 metatype = winner;
2340 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002341
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002342 /* Adjust for empty tuple bases */
Nick Coghlande31b192011-10-23 22:04:16 +10002343 nbases = PyTuple_GET_SIZE(bases);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002344 if (nbases == 0) {
2345 bases = PyTuple_Pack(1, &PyBaseObject_Type);
2346 if (bases == NULL)
Victor Stinner6f738742012-02-25 01:22:36 +01002347 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002348 nbases = 1;
2349 }
2350 else
2351 Py_INCREF(bases);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002352
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002353 /* Calculate best base, and check that all bases are type objects */
2354 base = best_base(bases);
2355 if (base == NULL) {
Victor Stinner6f738742012-02-25 01:22:36 +01002356 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002357 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002358
Victor Stinner6f738742012-02-25 01:22:36 +01002359 dict = PyDict_Copy(orig_dict);
2360 if (dict == NULL)
2361 goto error;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002362
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002363 /* Check for a __slots__ sequence variable in dict, and count it */
Victor Stinner3c1e4812012-03-26 22:10:51 +02002364 slots = _PyDict_GetItemId(dict, &PyId___slots__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002365 nslots = 0;
2366 add_dict = 0;
2367 add_weak = 0;
2368 may_add_dict = base->tp_dictoffset == 0;
2369 may_add_weak = base->tp_weaklistoffset == 0 && base->tp_itemsize == 0;
2370 if (slots == NULL) {
2371 if (may_add_dict) {
2372 add_dict++;
2373 }
2374 if (may_add_weak) {
2375 add_weak++;
2376 }
2377 }
2378 else {
2379 /* Have slots */
Guido van Rossumad47da02002-08-12 19:05:44 +00002380
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002381 /* Make it into a tuple */
2382 if (PyUnicode_Check(slots))
2383 slots = PyTuple_Pack(1, slots);
2384 else
2385 slots = PySequence_Tuple(slots);
Victor Stinner6f738742012-02-25 01:22:36 +01002386 if (slots == NULL)
2387 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002388 assert(PyTuple_Check(slots));
Guido van Rossumad47da02002-08-12 19:05:44 +00002389
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002390 /* Are slots allowed? */
2391 nslots = PyTuple_GET_SIZE(slots);
2392 if (nslots > 0 && base->tp_itemsize != 0) {
2393 PyErr_Format(PyExc_TypeError,
2394 "nonempty __slots__ "
2395 "not supported for subtype of '%s'",
2396 base->tp_name);
Victor Stinner6f738742012-02-25 01:22:36 +01002397 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002398 }
Guido van Rossumad47da02002-08-12 19:05:44 +00002399
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002400 /* Check for valid slot names and two special cases */
2401 for (i = 0; i < nslots; i++) {
2402 PyObject *tmp = PyTuple_GET_ITEM(slots, i);
2403 if (!valid_identifier(tmp))
Victor Stinner6f738742012-02-25 01:22:36 +01002404 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002405 assert(PyUnicode_Check(tmp));
Serhiy Storchakaf5894dd2016-11-16 15:40:39 +02002406 if (_PyUnicode_EqualToASCIIId(tmp, &PyId___dict__)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002407 if (!may_add_dict || add_dict) {
2408 PyErr_SetString(PyExc_TypeError,
2409 "__dict__ slot disallowed: "
2410 "we already got one");
Victor Stinner6f738742012-02-25 01:22:36 +01002411 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002412 }
2413 add_dict++;
2414 }
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02002415 if (_PyUnicode_EqualToASCIIString(tmp, "__weakref__")) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002416 if (!may_add_weak || add_weak) {
2417 PyErr_SetString(PyExc_TypeError,
2418 "__weakref__ slot disallowed: "
2419 "either we already got one, "
2420 "or __itemsize__ != 0");
Victor Stinner6f738742012-02-25 01:22:36 +01002421 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002422 }
2423 add_weak++;
2424 }
2425 }
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00002426
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002427 /* Copy slots into a list, mangle names and sort them.
2428 Sorted names are needed for __class__ assignment.
2429 Convert them back to tuple at the end.
2430 */
2431 newslots = PyList_New(nslots - add_dict - add_weak);
2432 if (newslots == NULL)
Victor Stinner6f738742012-02-25 01:22:36 +01002433 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002434 for (i = j = 0; i < nslots; i++) {
2435 tmp = PyTuple_GET_ITEM(slots, i);
2436 if ((add_dict &&
Serhiy Storchakaf5894dd2016-11-16 15:40:39 +02002437 _PyUnicode_EqualToASCIIId(tmp, &PyId___dict__)) ||
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002438 (add_weak &&
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02002439 _PyUnicode_EqualToASCIIString(tmp, "__weakref__")))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002440 continue;
2441 tmp =_Py_Mangle(name, tmp);
Benjamin Petersonae13c882011-08-16 22:26:48 -05002442 if (!tmp) {
2443 Py_DECREF(newslots);
Victor Stinner6f738742012-02-25 01:22:36 +01002444 goto error;
Benjamin Petersonae13c882011-08-16 22:26:48 -05002445 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002446 PyList_SET_ITEM(newslots, j, tmp);
Benjamin Petersonc4085c82011-08-16 18:53:26 -05002447 if (PyDict_GetItem(dict, tmp)) {
2448 PyErr_Format(PyExc_ValueError,
2449 "%R in __slots__ conflicts with class variable",
2450 tmp);
Benjamin Petersond17cefc2011-08-16 22:28:23 -05002451 Py_DECREF(newslots);
Victor Stinner6f738742012-02-25 01:22:36 +01002452 goto error;
Benjamin Petersonc4085c82011-08-16 18:53:26 -05002453 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002454 j++;
2455 }
2456 assert(j == nslots - add_dict - add_weak);
2457 nslots = j;
Victor Stinner6f738742012-02-25 01:22:36 +01002458 Py_CLEAR(slots);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002459 if (PyList_Sort(newslots) == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002460 Py_DECREF(newslots);
Victor Stinner6f738742012-02-25 01:22:36 +01002461 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002462 }
2463 slots = PyList_AsTuple(newslots);
2464 Py_DECREF(newslots);
Victor Stinner6f738742012-02-25 01:22:36 +01002465 if (slots == NULL)
2466 goto error;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00002467
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002468 /* Secondary bases may provide weakrefs or dict */
2469 if (nbases > 1 &&
2470 ((may_add_dict && !add_dict) ||
2471 (may_add_weak && !add_weak))) {
2472 for (i = 0; i < nbases; i++) {
2473 tmp = PyTuple_GET_ITEM(bases, i);
2474 if (tmp == (PyObject *)base)
2475 continue; /* Skip primary base */
2476 assert(PyType_Check(tmp));
2477 tmptype = (PyTypeObject *)tmp;
2478 if (may_add_dict && !add_dict &&
2479 tmptype->tp_dictoffset != 0)
2480 add_dict++;
2481 if (may_add_weak && !add_weak &&
2482 tmptype->tp_weaklistoffset != 0)
2483 add_weak++;
2484 if (may_add_dict && !add_dict)
2485 continue;
2486 if (may_add_weak && !add_weak)
2487 continue;
2488 /* Nothing more to check */
2489 break;
2490 }
2491 }
2492 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002493
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002494 /* Allocate the type object */
2495 type = (PyTypeObject *)metatype->tp_alloc(metatype, nslots);
Victor Stinner6f738742012-02-25 01:22:36 +01002496 if (type == NULL)
2497 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002498
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002499 /* Keep name and slots alive in the extended type object */
2500 et = (PyHeapTypeObject *)type;
2501 Py_INCREF(name);
2502 et->ht_name = name;
2503 et->ht_slots = slots;
Victor Stinner6f738742012-02-25 01:22:36 +01002504 slots = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002505
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002506 /* Initialize tp_flags */
2507 type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE |
Antoine Pitrou796564c2013-07-30 19:59:21 +02002508 Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_FINALIZE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002509 if (base->tp_flags & Py_TPFLAGS_HAVE_GC)
2510 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossumdc91b992001-08-08 22:26:22 +00002511
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002512 /* Initialize essential fields */
Yury Selivanov75445082015-05-11 22:57:16 -04002513 type->tp_as_async = &et->as_async;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002514 type->tp_as_number = &et->as_number;
2515 type->tp_as_sequence = &et->as_sequence;
2516 type->tp_as_mapping = &et->as_mapping;
2517 type->tp_as_buffer = &et->as_buffer;
Serhiy Storchaka42bf8fc2015-12-30 21:40:49 +02002518 type->tp_name = PyUnicode_AsUTF8AndSize(name, &name_size);
Victor Stinner6f738742012-02-25 01:22:36 +01002519 if (!type->tp_name)
2520 goto error;
Serhiy Storchaka42bf8fc2015-12-30 21:40:49 +02002521 if (strlen(type->tp_name) != (size_t)name_size) {
2522 PyErr_SetString(PyExc_ValueError,
2523 "type name must not contain null characters");
2524 goto error;
2525 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002526
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002527 /* Set tp_base and tp_bases */
2528 type->tp_bases = bases;
Victor Stinner6f738742012-02-25 01:22:36 +01002529 bases = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002530 Py_INCREF(base);
2531 type->tp_base = base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002532
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002533 /* Initialize tp_dict from passed-in dict */
Victor Stinner6f738742012-02-25 01:22:36 +01002534 Py_INCREF(dict);
2535 type->tp_dict = dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002536
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002537 /* Set __module__ in the dict */
Victor Stinner3c1e4812012-03-26 22:10:51 +02002538 if (_PyDict_GetItemId(dict, &PyId___module__) == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002539 tmp = PyEval_GetGlobals();
2540 if (tmp != NULL) {
Victor Stinner3c1e4812012-03-26 22:10:51 +02002541 tmp = _PyDict_GetItemId(tmp, &PyId___name__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002542 if (tmp != NULL) {
Victor Stinner3c1e4812012-03-26 22:10:51 +02002543 if (_PyDict_SetItemId(dict, &PyId___module__,
2544 tmp) < 0)
Victor Stinner6f738742012-02-25 01:22:36 +01002545 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002546 }
2547 }
2548 }
Guido van Rossumc3542212001-08-16 09:18:56 +00002549
Victor Stinner6f738742012-02-25 01:22:36 +01002550 /* Set ht_qualname to dict['__qualname__'] if available, else to
2551 __name__. The __qualname__ accessor will look for ht_qualname.
2552 */
Victor Stinner3c1e4812012-03-26 22:10:51 +02002553 qualname = _PyDict_GetItemId(dict, &PyId___qualname__);
Victor Stinner6f738742012-02-25 01:22:36 +01002554 if (qualname != NULL) {
2555 if (!PyUnicode_Check(qualname)) {
2556 PyErr_Format(PyExc_TypeError,
2557 "type __qualname__ must be a str, not %s",
2558 Py_TYPE(qualname)->tp_name);
2559 goto error;
2560 }
2561 }
Benjamin Peterson8afa7fa2012-10-30 23:51:03 -04002562 et->ht_qualname = qualname ? qualname : et->ht_name;
2563 Py_INCREF(et->ht_qualname);
Nick Coghlan944368e2016-09-11 14:45:49 +10002564 if (qualname != NULL && _PyDict_DelItemId(dict, &PyId___qualname__) < 0)
Benjamin Peterson8afa7fa2012-10-30 23:51:03 -04002565 goto error;
Victor Stinner6f738742012-02-25 01:22:36 +01002566
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002567 /* Set tp_doc to a copy of dict['__doc__'], if the latter is there
2568 and is a string. The __doc__ accessor will first look for tp_doc;
2569 if that fails, it will still look into __dict__.
2570 */
2571 {
Victor Stinner3c1e4812012-03-26 22:10:51 +02002572 PyObject *doc = _PyDict_GetItemId(dict, &PyId___doc__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002573 if (doc != NULL && PyUnicode_Check(doc)) {
2574 Py_ssize_t len;
2575 char *doc_str;
2576 char *tp_doc;
Alexandre Vassalottia85998a2008-05-03 18:24:43 +00002577
Serhiy Storchaka06515832016-11-20 09:13:07 +02002578 doc_str = PyUnicode_AsUTF8(doc);
Victor Stinner6f738742012-02-25 01:22:36 +01002579 if (doc_str == NULL)
2580 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002581 /* Silently truncate the docstring if it contains null bytes. */
2582 len = strlen(doc_str);
2583 tp_doc = (char *)PyObject_MALLOC(len + 1);
Victor Stinner53510cd2013-07-15 19:34:20 +02002584 if (tp_doc == NULL) {
2585 PyErr_NoMemory();
Victor Stinner6f738742012-02-25 01:22:36 +01002586 goto error;
Victor Stinner53510cd2013-07-15 19:34:20 +02002587 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002588 memcpy(tp_doc, doc_str, len + 1);
2589 type->tp_doc = tp_doc;
2590 }
2591 }
Tim Peters2f93e282001-10-04 05:27:00 +00002592
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002593 /* Special-case __new__: if it's a plain function,
2594 make it a static function */
Victor Stinner3c1e4812012-03-26 22:10:51 +02002595 tmp = _PyDict_GetItemId(dict, &PyId___new__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002596 if (tmp != NULL && PyFunction_Check(tmp)) {
2597 tmp = PyStaticMethod_New(tmp);
Victor Stinner6f738742012-02-25 01:22:36 +01002598 if (tmp == NULL)
2599 goto error;
Serhiy Storchaka484c9132016-06-05 10:48:36 +03002600 if (_PyDict_SetItemId(dict, &PyId___new__, tmp) < 0) {
2601 Py_DECREF(tmp);
Victor Stinner3c1e4812012-03-26 22:10:51 +02002602 goto error;
Serhiy Storchaka484c9132016-06-05 10:48:36 +03002603 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002604 Py_DECREF(tmp);
2605 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002606
Nick Coghland78448e2016-07-30 16:26:03 +10002607 /* Special-case __init_subclass__: if it's a plain function,
2608 make it a classmethod */
2609 tmp = _PyDict_GetItemId(dict, &PyId___init_subclass__);
2610 if (tmp != NULL && PyFunction_Check(tmp)) {
2611 tmp = PyClassMethod_New(tmp);
2612 if (tmp == NULL)
2613 goto error;
2614 if (_PyDict_SetItemId(dict, &PyId___init_subclass__, tmp) < 0) {
2615 Py_DECREF(tmp);
2616 goto error;
2617 }
2618 Py_DECREF(tmp);
2619 }
2620
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002621 /* Add descriptors for custom slots from __slots__, or for __dict__ */
2622 mp = PyHeapType_GET_MEMBERS(et);
2623 slotoffset = base->tp_basicsize;
Victor Stinner6f738742012-02-25 01:22:36 +01002624 if (et->ht_slots != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002625 for (i = 0; i < nslots; i++, mp++) {
Serhiy Storchaka06515832016-11-20 09:13:07 +02002626 mp->name = PyUnicode_AsUTF8(
Victor Stinner6f738742012-02-25 01:22:36 +01002627 PyTuple_GET_ITEM(et->ht_slots, i));
2628 if (mp->name == NULL)
2629 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002630 mp->type = T_OBJECT_EX;
2631 mp->offset = slotoffset;
Guido van Rossumd8faa362007-04-27 19:54:29 +00002632
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002633 /* __dict__ and __weakref__ are already filtered out */
2634 assert(strcmp(mp->name, "__dict__") != 0);
2635 assert(strcmp(mp->name, "__weakref__") != 0);
Guido van Rossumd8faa362007-04-27 19:54:29 +00002636
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002637 slotoffset += sizeof(PyObject *);
2638 }
2639 }
2640 if (add_dict) {
2641 if (base->tp_itemsize)
2642 type->tp_dictoffset = -(long)sizeof(PyObject *);
2643 else
2644 type->tp_dictoffset = slotoffset;
2645 slotoffset += sizeof(PyObject *);
2646 }
2647 if (add_weak) {
2648 assert(!base->tp_itemsize);
2649 type->tp_weaklistoffset = slotoffset;
2650 slotoffset += sizeof(PyObject *);
2651 }
2652 type->tp_basicsize = slotoffset;
2653 type->tp_itemsize = base->tp_itemsize;
2654 type->tp_members = PyHeapType_GET_MEMBERS(et);
Guido van Rossum373c7412003-01-07 13:41:37 +00002655
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002656 if (type->tp_weaklistoffset && type->tp_dictoffset)
2657 type->tp_getset = subtype_getsets_full;
2658 else if (type->tp_weaklistoffset && !type->tp_dictoffset)
2659 type->tp_getset = subtype_getsets_weakref_only;
2660 else if (!type->tp_weaklistoffset && type->tp_dictoffset)
2661 type->tp_getset = subtype_getsets_dict_only;
2662 else
2663 type->tp_getset = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002664
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002665 /* Special case some slots */
2666 if (type->tp_dictoffset != 0 || nslots > 0) {
2667 if (base->tp_getattr == NULL && base->tp_getattro == NULL)
2668 type->tp_getattro = PyObject_GenericGetAttr;
2669 if (base->tp_setattr == NULL && base->tp_setattro == NULL)
2670 type->tp_setattro = PyObject_GenericSetAttr;
2671 }
2672 type->tp_dealloc = subtype_dealloc;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002673
Antoine Pitroua63cc212015-04-13 20:10:06 +02002674 /* Enable GC unless this class is not adding new instance variables and
2675 the base class did not use GC. */
2676 if ((base->tp_flags & Py_TPFLAGS_HAVE_GC) ||
2677 type->tp_basicsize > base->tp_basicsize)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002678 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossum9475a232001-10-05 20:51:39 +00002679
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002680 /* Always override allocation strategy to use regular heap */
2681 type->tp_alloc = PyType_GenericAlloc;
2682 if (type->tp_flags & Py_TPFLAGS_HAVE_GC) {
2683 type->tp_free = PyObject_GC_Del;
2684 type->tp_traverse = subtype_traverse;
2685 type->tp_clear = subtype_clear;
2686 }
2687 else
2688 type->tp_free = PyObject_Del;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002689
Nick Coghlan19d24672016-12-05 16:47:55 +10002690 /* store type in class' cell if one is supplied */
Nick Coghlan944368e2016-09-11 14:45:49 +10002691 cell = _PyDict_GetItemId(dict, &PyId___classcell__);
Nick Coghlan19d24672016-12-05 16:47:55 +10002692 if (cell != NULL) {
2693 /* At least one method requires a reference to its defining class */
2694 if (!PyCell_Check(cell)) {
2695 PyErr_Format(PyExc_TypeError,
2696 "__classcell__ must be a nonlocal cell, not %.200R",
2697 Py_TYPE(cell));
2698 goto error;
2699 }
Nick Coghlan944368e2016-09-11 14:45:49 +10002700 PyCell_Set(cell, (PyObject *) type);
2701 _PyDict_DelItemId(dict, &PyId___classcell__);
2702 PyErr_Clear();
2703 }
2704
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002705 /* Initialize the rest */
Victor Stinner6f738742012-02-25 01:22:36 +01002706 if (PyType_Ready(type) < 0)
2707 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002708
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002709 /* Put the proper slots in place */
2710 fixup_slot_dispatchers(type);
Guido van Rossumf040ede2001-08-07 16:40:56 +00002711
Benjamin Petersondf813792014-03-17 15:57:17 -05002712 if (type->tp_dictoffset) {
2713 et->ht_cached_keys = _PyDict_NewKeysForClass();
2714 }
2715
Nick Coghland78448e2016-07-30 16:26:03 +10002716 if (set_names(type) < 0)
2717 goto error;
2718
2719 if (init_subclass(type, kwds) < 0)
2720 goto error;
2721
Victor Stinner6f738742012-02-25 01:22:36 +01002722 Py_DECREF(dict);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002723 return (PyObject *)type;
Victor Stinner6f738742012-02-25 01:22:36 +01002724
2725error:
2726 Py_XDECREF(dict);
2727 Py_XDECREF(bases);
2728 Py_XDECREF(slots);
2729 Py_XDECREF(type);
2730 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002731}
2732
Serhiy Storchaka2d06e842015-12-25 19:53:18 +02002733static const short slotoffsets[] = {
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002734 -1, /* invalid slot */
2735#include "typeslots.inc"
2736};
2737
Benjamin Petersone28108c2012-01-29 20:13:18 -05002738PyObject *
Martin v. Löwis9c564092012-06-23 23:20:45 +02002739PyType_FromSpecWithBases(PyType_Spec *spec, PyObject *bases)
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002740{
2741 PyHeapTypeObject *res = (PyHeapTypeObject*)PyType_GenericAlloc(&PyType_Type, 0);
Martin v. Löwis9c564092012-06-23 23:20:45 +02002742 PyTypeObject *type, *base;
Nick Coghlana48db2b2015-05-24 01:03:46 +10002743 PyObject *modname;
Martin v. Löwis9c564092012-06-23 23:20:45 +02002744 char *s;
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002745 char *res_start = (char*)res;
2746 PyType_Slot *slot;
Victor Stinner54e4ca72013-07-11 22:42:25 +02002747
Martin v. Löwis9c564092012-06-23 23:20:45 +02002748 /* Set the type name and qualname */
2749 s = strrchr(spec->name, '.');
2750 if (s == NULL)
2751 s = (char*)spec->name;
2752 else
2753 s++;
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002754
Martin v. Löwis5e06a5d2011-02-21 16:24:00 +00002755 if (res == NULL)
Antoine Pitroubb78f572012-06-24 00:18:27 +02002756 return NULL;
2757 type = &res->ht_type;
Antoine Pitrou66a3a7e2012-06-24 00:42:59 +02002758 /* The flags must be initialized early, before the GC traverses us */
2759 type->tp_flags = spec->flags | Py_TPFLAGS_HEAPTYPE;
Martin v. Löwis9c564092012-06-23 23:20:45 +02002760 res->ht_name = PyUnicode_FromString(s);
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002761 if (!res->ht_name)
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002762 goto fail;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002763 res->ht_qualname = res->ht_name;
2764 Py_INCREF(res->ht_qualname);
Antoine Pitroubb78f572012-06-24 00:18:27 +02002765 type->tp_name = spec->name;
2766 if (!type->tp_name)
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002767 goto fail;
Victor Stinner54e4ca72013-07-11 22:42:25 +02002768
Martin v. Löwis9c564092012-06-23 23:20:45 +02002769 /* Adjust for empty tuple bases */
2770 if (!bases) {
2771 base = &PyBaseObject_Type;
2772 /* See whether Py_tp_base(s) was specified */
2773 for (slot = spec->slots; slot->slot; slot++) {
2774 if (slot->slot == Py_tp_base)
2775 base = slot->pfunc;
2776 else if (slot->slot == Py_tp_bases) {
2777 bases = slot->pfunc;
2778 Py_INCREF(bases);
2779 }
2780 }
2781 if (!bases)
2782 bases = PyTuple_Pack(1, base);
2783 if (!bases)
2784 goto fail;
2785 }
2786 else
2787 Py_INCREF(bases);
2788
2789 /* Calculate best base, and check that all bases are type objects */
2790 base = best_base(bases);
2791 if (base == NULL) {
2792 goto fail;
2793 }
2794 if (!PyType_HasFeature(base, Py_TPFLAGS_BASETYPE)) {
2795 PyErr_Format(PyExc_TypeError,
2796 "type '%.100s' is not an acceptable base type",
2797 base->tp_name);
2798 goto fail;
2799 }
2800
Martin v. Löwis9c564092012-06-23 23:20:45 +02002801 /* Initialize essential fields */
Yury Selivanov75445082015-05-11 22:57:16 -04002802 type->tp_as_async = &res->as_async;
Martin v. Löwis9c564092012-06-23 23:20:45 +02002803 type->tp_as_number = &res->as_number;
2804 type->tp_as_sequence = &res->as_sequence;
2805 type->tp_as_mapping = &res->as_mapping;
2806 type->tp_as_buffer = &res->as_buffer;
2807 /* Set tp_base and tp_bases */
2808 type->tp_bases = bases;
2809 bases = NULL;
2810 Py_INCREF(base);
2811 type->tp_base = base;
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002812
Antoine Pitroubb78f572012-06-24 00:18:27 +02002813 type->tp_basicsize = spec->basicsize;
2814 type->tp_itemsize = spec->itemsize;
Victor Stinner0fcab4a2011-01-04 12:59:15 +00002815
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002816 for (slot = spec->slots; slot->slot; slot++) {
Victor Stinner12174a52014-08-15 23:17:38 +02002817 if (slot->slot < 0
2818 || (size_t)slot->slot >= Py_ARRAY_LENGTH(slotoffsets)) {
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002819 PyErr_SetString(PyExc_RuntimeError, "invalid slot offset");
2820 goto fail;
2821 }
Martin v. Löwis9c564092012-06-23 23:20:45 +02002822 if (slot->slot == Py_tp_base || slot->slot == Py_tp_bases)
2823 /* Processed above */
2824 continue;
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002825 *(void**)(res_start + slotoffsets[slot->slot]) = slot->pfunc;
Georg Brandl032400b2011-02-19 21:47:02 +00002826
2827 /* need to make a copy of the docstring slot, which usually
2828 points to a static string literal */
2829 if (slot->slot == Py_tp_doc) {
Larry Hastings2623c8c2014-02-08 22:15:29 -08002830 const char *old_doc = _PyType_DocWithoutSignature(type->tp_name, slot->pfunc);
Larry Hastings5c661892014-01-24 06:17:25 -08002831 size_t len = strlen(old_doc)+1;
Georg Brandl032400b2011-02-19 21:47:02 +00002832 char *tp_doc = PyObject_MALLOC(len);
Victor Stinner53510cd2013-07-15 19:34:20 +02002833 if (tp_doc == NULL) {
2834 PyErr_NoMemory();
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002835 goto fail;
Victor Stinner53510cd2013-07-15 19:34:20 +02002836 }
Larry Hastings5c661892014-01-24 06:17:25 -08002837 memcpy(tp_doc, old_doc, len);
Antoine Pitroubb78f572012-06-24 00:18:27 +02002838 type->tp_doc = tp_doc;
Georg Brandl032400b2011-02-19 21:47:02 +00002839 }
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002840 }
Antoine Pitroubb78f572012-06-24 00:18:27 +02002841 if (type->tp_dealloc == NULL) {
Antoine Pitrou99cc6292012-06-23 14:42:38 +02002842 /* It's a heap type, so needs the heap types' dealloc.
2843 subtype_dealloc will call the base type's tp_dealloc, if
2844 necessary. */
Antoine Pitroubb78f572012-06-24 00:18:27 +02002845 type->tp_dealloc = subtype_dealloc;
Antoine Pitrou99cc6292012-06-23 14:42:38 +02002846 }
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002847
Antoine Pitroubb78f572012-06-24 00:18:27 +02002848 if (PyType_Ready(type) < 0)
Benjamin Peterson2652d252012-01-29 20:16:37 -05002849 goto fail;
2850
Benjamin Petersondf813792014-03-17 15:57:17 -05002851 if (type->tp_dictoffset) {
2852 res->ht_cached_keys = _PyDict_NewKeysForClass();
2853 }
2854
Martin v. Löwis9c564092012-06-23 23:20:45 +02002855 /* Set type.__module__ */
2856 s = strrchr(spec->name, '.');
Nick Coghlana48db2b2015-05-24 01:03:46 +10002857 if (s != NULL) {
Christian Heimes5cade882016-10-13 21:10:31 +02002858 int err;
Nick Coghlana48db2b2015-05-24 01:03:46 +10002859 modname = PyUnicode_FromStringAndSize(
2860 spec->name, (Py_ssize_t)(s - spec->name));
2861 if (modname == NULL) {
2862 goto fail;
2863 }
Christian Heimes5cade882016-10-13 21:10:31 +02002864 err = _PyDict_SetItemId(type->tp_dict, &PyId___module__, modname);
Nick Coghlana48db2b2015-05-24 01:03:46 +10002865 Py_DECREF(modname);
Christian Heimes5cade882016-10-13 21:10:31 +02002866 if (err != 0)
2867 goto fail;
Nick Coghlana48db2b2015-05-24 01:03:46 +10002868 } else {
Serhiy Storchaka490055a2015-03-01 10:03:02 +02002869 if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
Serhiy Storchaka71c6f442015-03-01 14:39:20 +02002870 "builtin type %.200s has no __module__ attribute",
Serhiy Storchaka490055a2015-03-01 10:03:02 +02002871 spec->name))
2872 goto fail;
2873 }
Martin v. Löwis9c564092012-06-23 23:20:45 +02002874
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002875 return (PyObject*)res;
Victor Stinner0fcab4a2011-01-04 12:59:15 +00002876
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002877 fail:
2878 Py_DECREF(res);
2879 return NULL;
2880}
2881
Martin v. Löwis9c564092012-06-23 23:20:45 +02002882PyObject *
2883PyType_FromSpec(PyType_Spec *spec)
2884{
2885 return PyType_FromSpecWithBases(spec, NULL);
2886}
2887
Martin v. Löwisca7b0462014-02-04 09:33:05 +01002888void *
2889PyType_GetSlot(PyTypeObject *type, int slot)
2890{
Victor Stinner12174a52014-08-15 23:17:38 +02002891 if (!PyType_HasFeature(type, Py_TPFLAGS_HEAPTYPE) || slot < 0) {
Martin v. Löwisca7b0462014-02-04 09:33:05 +01002892 PyErr_BadInternalCall();
2893 return NULL;
2894 }
Victor Stinner12174a52014-08-15 23:17:38 +02002895 if ((size_t)slot >= Py_ARRAY_LENGTH(slotoffsets)) {
Martin v. Löwisca7b0462014-02-04 09:33:05 +01002896 /* Extension module requesting slot from a future version */
2897 return NULL;
2898 }
2899 return *(void**)(((char*)type) + slotoffsets[slot]);
2900}
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002901
Tim Peters6d6c1a32001-08-02 04:15:00 +00002902/* Internal API to look for a name through the MRO.
2903 This returns a borrowed reference, and doesn't set an exception! */
2904PyObject *
2905_PyType_Lookup(PyTypeObject *type, PyObject *name)
2906{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002907 Py_ssize_t i, n;
2908 PyObject *mro, *res, *base, *dict;
2909 unsigned int h;
Christian Heimesa62da1d2008-01-12 19:39:10 +00002910
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002911 if (MCACHE_CACHEABLE_NAME(name) &&
2912 PyType_HasFeature(type, Py_TPFLAGS_VALID_VERSION_TAG)) {
2913 /* fast path */
2914 h = MCACHE_HASH_METHOD(type, name);
2915 if (method_cache[h].version == type->tp_version_tag &&
Antoine Pitrou2a40e362014-11-15 00:56:27 +01002916 method_cache[h].name == name) {
2917#if MCACHE_STATS
2918 method_cache_hits++;
2919#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002920 return method_cache[h].value;
Antoine Pitrou2a40e362014-11-15 00:56:27 +01002921 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002922 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002923
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002924 /* Look in tp_dict of types in MRO */
2925 mro = type->tp_mro;
Guido van Rossum23094982002-06-10 14:30:43 +00002926
Serhiy Storchaka8ef34602016-10-08 12:24:09 +03002927 if (mro == NULL) {
2928 if ((type->tp_flags & Py_TPFLAGS_READYING) == 0 &&
2929 PyType_Ready(type) < 0) {
2930 /* It's not ideal to clear the error condition,
2931 but this function is documented as not setting
2932 an exception, and I don't want to change that.
2933 When PyType_Ready() can't proceed, it won't
2934 set the "ready" flag, so future attempts to ready
2935 the same type will call it again -- hopefully
2936 in a context that propagates the exception out.
2937 */
2938 PyErr_Clear();
2939 return NULL;
2940 }
2941 mro = type->tp_mro;
2942 if (mro == NULL) {
2943 return NULL;
2944 }
2945 }
Guido van Rossum23094982002-06-10 14:30:43 +00002946
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002947 res = NULL;
Victor Stinnerd74782b2012-03-09 00:39:08 +01002948 /* keep a strong reference to mro because type->tp_mro can be replaced
2949 during PyDict_GetItem(dict, name) */
2950 Py_INCREF(mro);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002951 assert(PyTuple_Check(mro));
2952 n = PyTuple_GET_SIZE(mro);
2953 for (i = 0; i < n; i++) {
2954 base = PyTuple_GET_ITEM(mro, i);
2955 assert(PyType_Check(base));
2956 dict = ((PyTypeObject *)base)->tp_dict;
2957 assert(dict && PyDict_Check(dict));
2958 res = PyDict_GetItem(dict, name);
2959 if (res != NULL)
2960 break;
2961 }
Victor Stinnerd74782b2012-03-09 00:39:08 +01002962 Py_DECREF(mro);
Christian Heimesa62da1d2008-01-12 19:39:10 +00002963
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002964 if (MCACHE_CACHEABLE_NAME(name) && assign_version_tag(type)) {
2965 h = MCACHE_HASH_METHOD(type, name);
2966 method_cache[h].version = type->tp_version_tag;
2967 method_cache[h].value = res; /* borrowed */
2968 Py_INCREF(name);
Antoine Pitrou2a40e362014-11-15 00:56:27 +01002969 assert(((PyASCIIObject *)(name))->hash != -1);
2970#if MCACHE_STATS
2971 if (method_cache[h].name != Py_None && method_cache[h].name != name)
2972 method_cache_collisions++;
2973 else
2974 method_cache_misses++;
2975#endif
Serhiy Storchaka57a01d32016-04-10 18:05:40 +03002976 Py_SETREF(method_cache[h].name, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002977 }
2978 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002979}
2980
Raymond Hettinger2ff21902013-10-01 00:55:43 -07002981PyObject *
Victor Stinner3c1e4812012-03-26 22:10:51 +02002982_PyType_LookupId(PyTypeObject *type, struct _Py_Identifier *name)
2983{
2984 PyObject *oname;
2985 oname = _PyUnicode_FromId(name); /* borrowed */
2986 if (oname == NULL)
2987 return NULL;
2988 return _PyType_Lookup(type, oname);
2989}
2990
Tim Peters6d6c1a32001-08-02 04:15:00 +00002991/* This is similar to PyObject_GenericGetAttr(),
2992 but uses _PyType_Lookup() instead of just looking in type->tp_dict. */
2993static PyObject *
2994type_getattro(PyTypeObject *type, PyObject *name)
2995{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002996 PyTypeObject *metatype = Py_TYPE(type);
2997 PyObject *meta_attribute, *attribute;
2998 descrgetfunc meta_get;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002999
Benjamin Peterson16d84ac2012-03-16 09:32:59 -05003000 if (!PyUnicode_Check(name)) {
3001 PyErr_Format(PyExc_TypeError,
3002 "attribute name must be string, not '%.200s'",
3003 name->ob_type->tp_name);
3004 return NULL;
3005 }
3006
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003007 /* Initialize this type (we'll assume the metatype is initialized) */
3008 if (type->tp_dict == NULL) {
3009 if (PyType_Ready(type) < 0)
3010 return NULL;
3011 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003012
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003013 /* No readable descriptor found yet */
3014 meta_get = NULL;
Tim Peters34592512002-07-11 06:23:50 +00003015
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003016 /* Look for the attribute in the metatype */
3017 meta_attribute = _PyType_Lookup(metatype, name);
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00003018
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003019 if (meta_attribute != NULL) {
3020 meta_get = Py_TYPE(meta_attribute)->tp_descr_get;
Tim Peters34592512002-07-11 06:23:50 +00003021
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003022 if (meta_get != NULL && PyDescr_IsData(meta_attribute)) {
3023 /* Data descriptors implement tp_descr_set to intercept
3024 * writes. Assume the attribute is not overridden in
3025 * type's tp_dict (and bases): call the descriptor now.
3026 */
3027 return meta_get(meta_attribute, (PyObject *)type,
3028 (PyObject *)metatype);
3029 }
3030 Py_INCREF(meta_attribute);
3031 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003032
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003033 /* No data descriptor found on metatype. Look in tp_dict of this
3034 * type and its bases */
3035 attribute = _PyType_Lookup(type, name);
3036 if (attribute != NULL) {
3037 /* Implement descriptor functionality, if any */
3038 descrgetfunc local_get = Py_TYPE(attribute)->tp_descr_get;
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00003039
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003040 Py_XDECREF(meta_attribute);
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00003041
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003042 if (local_get != NULL) {
3043 /* NULL 2nd argument indicates the descriptor was
3044 * found on the target object itself (or a base) */
3045 return local_get(attribute, (PyObject *)NULL,
3046 (PyObject *)type);
3047 }
Tim Peters34592512002-07-11 06:23:50 +00003048
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003049 Py_INCREF(attribute);
3050 return attribute;
3051 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003052
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003053 /* No attribute found in local __dict__ (or bases): use the
3054 * descriptor from the metatype, if any */
3055 if (meta_get != NULL) {
3056 PyObject *res;
3057 res = meta_get(meta_attribute, (PyObject *)type,
3058 (PyObject *)metatype);
3059 Py_DECREF(meta_attribute);
3060 return res;
3061 }
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00003062
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003063 /* If an ordinary attribute was found on the metatype, return it now */
3064 if (meta_attribute != NULL) {
3065 return meta_attribute;
3066 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003067
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003068 /* Give up */
3069 PyErr_Format(PyExc_AttributeError,
3070 "type object '%.50s' has no attribute '%U'",
3071 type->tp_name, name);
3072 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003073}
3074
3075static int
3076type_setattro(PyTypeObject *type, PyObject *name, PyObject *value)
3077{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003078 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
3079 PyErr_Format(
3080 PyExc_TypeError,
3081 "can't set attributes of built-in/extension type '%s'",
3082 type->tp_name);
3083 return -1;
3084 }
3085 if (PyObject_GenericSetAttr((PyObject *)type, name, value) < 0)
3086 return -1;
3087 return update_slot(type, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003088}
3089
Benjamin Peterson64acccf2012-04-27 15:07:36 -04003090extern void
3091_PyDictKeys_DecRef(PyDictKeysObject *keys);
3092
Tim Peters6d6c1a32001-08-02 04:15:00 +00003093static void
3094type_dealloc(PyTypeObject *type)
3095{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003096 PyHeapTypeObject *et;
Antoine Pitrou84745ab2013-10-29 21:31:25 +01003097 PyObject *tp, *val, *tb;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003098
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003099 /* Assert this is a heap-allocated type object */
3100 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
3101 _PyObject_GC_UNTRACK(type);
Antoine Pitrou84745ab2013-10-29 21:31:25 +01003102 PyErr_Fetch(&tp, &val, &tb);
3103 remove_all_subclasses(type, type->tp_bases);
3104 PyErr_Restore(tp, val, tb);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003105 PyObject_ClearWeakRefs((PyObject *)type);
3106 et = (PyHeapTypeObject *)type;
3107 Py_XDECREF(type->tp_base);
3108 Py_XDECREF(type->tp_dict);
3109 Py_XDECREF(type->tp_bases);
3110 Py_XDECREF(type->tp_mro);
3111 Py_XDECREF(type->tp_cache);
3112 Py_XDECREF(type->tp_subclasses);
3113 /* A type's tp_doc is heap allocated, unlike the tp_doc slots
3114 * of most other objects. It's okay to cast it to char *.
3115 */
3116 PyObject_Free((char *)type->tp_doc);
3117 Py_XDECREF(et->ht_name);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003118 Py_XDECREF(et->ht_qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003119 Py_XDECREF(et->ht_slots);
Benjamin Peterson64acccf2012-04-27 15:07:36 -04003120 if (et->ht_cached_keys)
3121 _PyDictKeys_DecRef(et->ht_cached_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003122 Py_TYPE(type)->tp_free((PyObject *)type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003123}
3124
Guido van Rossum1c450732001-10-08 15:18:27 +00003125static PyObject *
3126type_subclasses(PyTypeObject *type, PyObject *args_ignored)
3127{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003128 PyObject *list, *raw, *ref;
Antoine Pitrou84745ab2013-10-29 21:31:25 +01003129 Py_ssize_t i;
Guido van Rossum1c450732001-10-08 15:18:27 +00003130
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003131 list = PyList_New(0);
3132 if (list == NULL)
3133 return NULL;
3134 raw = type->tp_subclasses;
3135 if (raw == NULL)
3136 return list;
Antoine Pitrou84745ab2013-10-29 21:31:25 +01003137 assert(PyDict_CheckExact(raw));
3138 i = 0;
3139 while (PyDict_Next(raw, &i, NULL, &ref)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003140 assert(PyWeakref_CheckRef(ref));
3141 ref = PyWeakref_GET_OBJECT(ref);
3142 if (ref != Py_None) {
3143 if (PyList_Append(list, ref) < 0) {
3144 Py_DECREF(list);
3145 return NULL;
3146 }
3147 }
3148 }
3149 return list;
Guido van Rossum1c450732001-10-08 15:18:27 +00003150}
3151
Guido van Rossum47374822007-08-02 16:48:17 +00003152static PyObject *
3153type_prepare(PyObject *self, PyObject *args, PyObject *kwds)
3154{
Eric Snow4f29e752016-09-08 15:11:11 -07003155 return PyDict_New();
Guido van Rossum47374822007-08-02 16:48:17 +00003156}
3157
Victor Stinner63941882011-09-29 00:42:28 +02003158/*
Benjamin Peterson82b00c12011-05-24 11:09:06 -05003159 Merge the __dict__ of aclass into dict, and recursively also all
3160 the __dict__s of aclass's base classes. The order of merging isn't
3161 defined, as it's expected that only the final set of dict keys is
3162 interesting.
3163 Return 0 on success, -1 on error.
3164*/
3165
3166static int
3167merge_class_dict(PyObject *dict, PyObject *aclass)
3168{
3169 PyObject *classdict;
3170 PyObject *bases;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02003171 _Py_IDENTIFIER(__bases__);
Benjamin Peterson82b00c12011-05-24 11:09:06 -05003172
3173 assert(PyDict_Check(dict));
3174 assert(aclass);
3175
3176 /* Merge in the type's dict (if any). */
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02003177 classdict = _PyObject_GetAttrId(aclass, &PyId___dict__);
Benjamin Peterson82b00c12011-05-24 11:09:06 -05003178 if (classdict == NULL)
3179 PyErr_Clear();
3180 else {
3181 int status = PyDict_Update(dict, classdict);
3182 Py_DECREF(classdict);
3183 if (status < 0)
3184 return -1;
3185 }
3186
3187 /* Recursively merge in the base types' (if any) dicts. */
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02003188 bases = _PyObject_GetAttrId(aclass, &PyId___bases__);
Benjamin Peterson82b00c12011-05-24 11:09:06 -05003189 if (bases == NULL)
3190 PyErr_Clear();
3191 else {
3192 /* We have no guarantee that bases is a real tuple */
3193 Py_ssize_t i, n;
3194 n = PySequence_Size(bases); /* This better be right */
3195 if (n < 0)
3196 PyErr_Clear();
3197 else {
3198 for (i = 0; i < n; i++) {
3199 int status;
3200 PyObject *base = PySequence_GetItem(bases, i);
3201 if (base == NULL) {
3202 Py_DECREF(bases);
3203 return -1;
3204 }
3205 status = merge_class_dict(dict, base);
3206 Py_DECREF(base);
3207 if (status < 0) {
3208 Py_DECREF(bases);
3209 return -1;
3210 }
3211 }
3212 }
3213 Py_DECREF(bases);
3214 }
3215 return 0;
3216}
3217
3218/* __dir__ for type objects: returns __dict__ and __bases__.
3219 We deliberately don't suck up its __class__, as methods belonging to the
3220 metaclass would probably be more confusing than helpful.
3221*/
3222static PyObject *
3223type_dir(PyObject *self, PyObject *args)
3224{
3225 PyObject *result = NULL;
3226 PyObject *dict = PyDict_New();
3227
3228 if (dict != NULL && merge_class_dict(dict, self) == 0)
3229 result = PyDict_Keys(dict);
3230
3231 Py_XDECREF(dict);
3232 return result;
3233}
3234
Martin v. Loewis4f2f3b62012-04-24 19:13:57 +02003235static PyObject*
3236type_sizeof(PyObject *self, PyObject *args_unused)
3237{
3238 Py_ssize_t size;
3239 PyTypeObject *type = (PyTypeObject*)self;
3240 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
3241 PyHeapTypeObject* et = (PyHeapTypeObject*)type;
3242 size = sizeof(PyHeapTypeObject);
3243 if (et->ht_cached_keys)
3244 size += _PyDict_KeysSize(et->ht_cached_keys);
3245 }
3246 else
3247 size = sizeof(PyTypeObject);
3248 return PyLong_FromSsize_t(size);
3249}
3250
Tim Peters6d6c1a32001-08-02 04:15:00 +00003251static PyMethodDef type_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003252 {"mro", (PyCFunction)mro_external, METH_NOARGS,
3253 PyDoc_STR("mro() -> list\nreturn a type's method resolution order")},
3254 {"__subclasses__", (PyCFunction)type_subclasses, METH_NOARGS,
3255 PyDoc_STR("__subclasses__() -> list of immediate subclasses")},
3256 {"__prepare__", (PyCFunction)type_prepare,
3257 METH_VARARGS | METH_KEYWORDS | METH_CLASS,
3258 PyDoc_STR("__prepare__() -> dict\n"
3259 "used to create the namespace for the class statement")},
3260 {"__instancecheck__", type___instancecheck__, METH_O,
Benjamin Petersonfbe56bb2011-05-24 12:42:51 -05003261 PyDoc_STR("__instancecheck__() -> bool\ncheck if an object is an instance")},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003262 {"__subclasscheck__", type___subclasscheck__, METH_O,
Benjamin Petersonfbe56bb2011-05-24 12:42:51 -05003263 PyDoc_STR("__subclasscheck__() -> bool\ncheck if a class is a subclass")},
Benjamin Peterson82b00c12011-05-24 11:09:06 -05003264 {"__dir__", type_dir, METH_NOARGS,
Benjamin Petersonc7284122011-05-24 12:46:15 -05003265 PyDoc_STR("__dir__() -> list\nspecialized __dir__ implementation for types")},
Martin v. Loewis4f2f3b62012-04-24 19:13:57 +02003266 {"__sizeof__", type_sizeof, METH_NOARGS,
3267 "__sizeof__() -> int\nreturn memory consumption of the type object"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003268 {0}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003269};
3270
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003271PyDoc_STRVAR(type_doc,
Larry Hastings5c661892014-01-24 06:17:25 -08003272/* this text signature cannot be accurate yet. will fix. --larry */
Larry Hastings2623c8c2014-02-08 22:15:29 -08003273"type(object_or_name, bases, dict)\n"
Tim Peters6d6c1a32001-08-02 04:15:00 +00003274"type(object) -> the object's type\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003275"type(name, bases, dict) -> a new type");
Tim Peters6d6c1a32001-08-02 04:15:00 +00003276
Guido van Rossum048eb752001-10-02 21:24:57 +00003277static int
3278type_traverse(PyTypeObject *type, visitproc visit, void *arg)
3279{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003280 /* Because of type_is_gc(), the collector only calls this
3281 for heaptypes. */
Antoine Pitrou1351ca62012-06-24 00:30:12 +02003282 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
3283 char msg[200];
3284 sprintf(msg, "type_traverse() called for non-heap type '%.100s'",
3285 type->tp_name);
3286 Py_FatalError(msg);
3287 }
Guido van Rossum048eb752001-10-02 21:24:57 +00003288
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003289 Py_VISIT(type->tp_dict);
3290 Py_VISIT(type->tp_cache);
3291 Py_VISIT(type->tp_mro);
3292 Py_VISIT(type->tp_bases);
3293 Py_VISIT(type->tp_base);
Guido van Rossuma3862092002-06-10 15:24:42 +00003294
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003295 /* There's no need to visit type->tp_subclasses or
3296 ((PyHeapTypeObject *)type)->ht_slots, because they can't be involved
3297 in cycles; tp_subclasses is a list of weak references,
3298 and slots is a tuple of strings. */
Guido van Rossum048eb752001-10-02 21:24:57 +00003299
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003300 return 0;
Guido van Rossum048eb752001-10-02 21:24:57 +00003301}
3302
3303static int
3304type_clear(PyTypeObject *type)
3305{
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003306 PyDictKeysObject *cached_keys;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003307 /* Because of type_is_gc(), the collector only calls this
3308 for heaptypes. */
3309 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00003310
Antoine Pitrou2e872082011-12-15 14:15:31 +01003311 /* We need to invalidate the method cache carefully before clearing
3312 the dict, so that other objects caught in a reference cycle
3313 don't start calling destroyed methods.
3314
3315 Otherwise, the only field we need to clear is tp_mro, which is
3316 part of a hard cycle (its first element is the class itself) that
3317 won't be broken otherwise (it's a tuple and tuples don't have a
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003318 tp_clear handler). None of the other fields need to be
3319 cleared, and here's why:
Guido van Rossum048eb752001-10-02 21:24:57 +00003320
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003321 tp_cache:
3322 Not used; if it were, it would be a dict.
Guido van Rossuma3862092002-06-10 15:24:42 +00003323
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003324 tp_bases, tp_base:
3325 If these are involved in a cycle, there must be at least
3326 one other, mutable object in the cycle, e.g. a base
3327 class's dict; the cycle will be broken that way.
Guido van Rossuma3862092002-06-10 15:24:42 +00003328
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003329 tp_subclasses:
Antoine Pitrou84745ab2013-10-29 21:31:25 +01003330 A dict of weak references can't be part of a cycle; and
3331 dicts have their own tp_clear.
Guido van Rossuma3862092002-06-10 15:24:42 +00003332
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003333 slots (in PyHeapTypeObject):
3334 A tuple of strings can't be part of a cycle.
3335 */
Guido van Rossuma3862092002-06-10 15:24:42 +00003336
Antoine Pitrou2e872082011-12-15 14:15:31 +01003337 PyType_Modified(type);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003338 cached_keys = ((PyHeapTypeObject *)type)->ht_cached_keys;
3339 if (cached_keys != NULL) {
3340 ((PyHeapTypeObject *)type)->ht_cached_keys = NULL;
3341 _PyDictKeys_DecRef(cached_keys);
3342 }
Antoine Pitrou2e872082011-12-15 14:15:31 +01003343 if (type->tp_dict)
3344 PyDict_Clear(type->tp_dict);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003345 Py_CLEAR(type->tp_mro);
Guido van Rossum048eb752001-10-02 21:24:57 +00003346
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003347 return 0;
Guido van Rossum048eb752001-10-02 21:24:57 +00003348}
3349
3350static int
3351type_is_gc(PyTypeObject *type)
3352{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003353 return type->tp_flags & Py_TPFLAGS_HEAPTYPE;
Guido van Rossum048eb752001-10-02 21:24:57 +00003354}
3355
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003356PyTypeObject PyType_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003357 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3358 "type", /* tp_name */
3359 sizeof(PyHeapTypeObject), /* tp_basicsize */
3360 sizeof(PyMemberDef), /* tp_itemsize */
3361 (destructor)type_dealloc, /* tp_dealloc */
3362 0, /* tp_print */
3363 0, /* tp_getattr */
3364 0, /* tp_setattr */
3365 0, /* tp_reserved */
3366 (reprfunc)type_repr, /* tp_repr */
3367 0, /* tp_as_number */
3368 0, /* tp_as_sequence */
3369 0, /* tp_as_mapping */
3370 0, /* tp_hash */
3371 (ternaryfunc)type_call, /* tp_call */
3372 0, /* tp_str */
3373 (getattrofunc)type_getattro, /* tp_getattro */
3374 (setattrofunc)type_setattro, /* tp_setattro */
3375 0, /* tp_as_buffer */
3376 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
3377 Py_TPFLAGS_BASETYPE | Py_TPFLAGS_TYPE_SUBCLASS, /* tp_flags */
3378 type_doc, /* tp_doc */
3379 (traverseproc)type_traverse, /* tp_traverse */
3380 (inquiry)type_clear, /* tp_clear */
3381 0, /* tp_richcompare */
3382 offsetof(PyTypeObject, tp_weaklist), /* tp_weaklistoffset */
3383 0, /* tp_iter */
3384 0, /* tp_iternext */
3385 type_methods, /* tp_methods */
3386 type_members, /* tp_members */
3387 type_getsets, /* tp_getset */
3388 0, /* tp_base */
3389 0, /* tp_dict */
3390 0, /* tp_descr_get */
3391 0, /* tp_descr_set */
3392 offsetof(PyTypeObject, tp_dict), /* tp_dictoffset */
3393 type_init, /* tp_init */
3394 0, /* tp_alloc */
3395 type_new, /* tp_new */
3396 PyObject_GC_Del, /* tp_free */
3397 (inquiry)type_is_gc, /* tp_is_gc */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003398};
Tim Peters6d6c1a32001-08-02 04:15:00 +00003399
3400
3401/* The base type of all types (eventually)... except itself. */
3402
Guido van Rossumd8faa362007-04-27 19:54:29 +00003403/* You may wonder why object.__new__() only complains about arguments
3404 when object.__init__() is not overridden, and vice versa.
3405
3406 Consider the use cases:
3407
3408 1. When neither is overridden, we want to hear complaints about
3409 excess (i.e., any) arguments, since their presence could
3410 indicate there's a bug.
3411
3412 2. When defining an Immutable type, we are likely to override only
3413 __new__(), since __init__() is called too late to initialize an
3414 Immutable object. Since __new__() defines the signature for the
3415 type, it would be a pain to have to override __init__() just to
3416 stop it from complaining about excess arguments.
3417
3418 3. When defining a Mutable type, we are likely to override only
3419 __init__(). So here the converse reasoning applies: we don't
3420 want to have to override __new__() just to stop it from
3421 complaining.
3422
3423 4. When __init__() is overridden, and the subclass __init__() calls
3424 object.__init__(), the latter should complain about excess
3425 arguments; ditto for __new__().
3426
3427 Use cases 2 and 3 make it unattractive to unconditionally check for
3428 excess arguments. The best solution that addresses all four use
3429 cases is as follows: __init__() complains about excess arguments
3430 unless __new__() is overridden and __init__() is not overridden
3431 (IOW, if __init__() is overridden or __new__() is not overridden);
3432 symmetrically, __new__() complains about excess arguments unless
3433 __init__() is overridden and __new__() is not overridden
3434 (IOW, if __new__() is overridden or __init__() is not overridden).
3435
3436 However, for backwards compatibility, this breaks too much code.
3437 Therefore, in 2.6, we'll *warn* about excess arguments when both
3438 methods are overridden; for all other cases we'll use the above
3439 rules.
3440
3441*/
3442
3443/* Forward */
3444static PyObject *
3445object_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
3446
3447static int
3448excess_args(PyObject *args, PyObject *kwds)
3449{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003450 return PyTuple_GET_SIZE(args) ||
3451 (kwds && PyDict_Check(kwds) && PyDict_Size(kwds));
Guido van Rossumd8faa362007-04-27 19:54:29 +00003452}
3453
Tim Peters6d6c1a32001-08-02 04:15:00 +00003454static int
3455object_init(PyObject *self, PyObject *args, PyObject *kwds)
3456{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003457 int err = 0;
Benjamin Peterson96384b92012-03-17 00:05:44 -05003458 PyTypeObject *type = Py_TYPE(self);
3459 if (excess_args(args, kwds) &&
3460 (type->tp_new == object_new || type->tp_init != object_init)) {
3461 PyErr_SetString(PyExc_TypeError, "object.__init__() takes no parameters");
3462 err = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003463 }
3464 return err;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003465}
3466
Guido van Rossum298e4212003-02-13 16:30:16 +00003467static PyObject *
3468object_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3469{
Benjamin Peterson96384b92012-03-17 00:05:44 -05003470 if (excess_args(args, kwds) &&
3471 (type->tp_init == object_init || type->tp_new != object_new)) {
R David Murray702a5dc2013-02-18 21:39:18 -05003472 PyErr_SetString(PyExc_TypeError, "object() takes no parameters");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003473 return NULL;
Benjamin Peterson96384b92012-03-17 00:05:44 -05003474 }
Victor Stinner3c1e4812012-03-26 22:10:51 +02003475
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003476 if (type->tp_flags & Py_TPFLAGS_IS_ABSTRACT) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003477 PyObject *abstract_methods = NULL;
3478 PyObject *builtins;
3479 PyObject *sorted;
3480 PyObject *sorted_methods = NULL;
3481 PyObject *joined = NULL;
Benjamin Peterson9a03ecf2012-03-16 20:15:54 -05003482 PyObject *comma;
3483 _Py_static_string(comma_id, ", ");
Victor Stinner3c1e4812012-03-26 22:10:51 +02003484 _Py_IDENTIFIER(sorted);
Christian Heimes9e7f1d22008-02-28 12:27:11 +00003485
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003486 /* Compute ", ".join(sorted(type.__abstractmethods__))
3487 into joined. */
3488 abstract_methods = type_abstractmethods(type, NULL);
3489 if (abstract_methods == NULL)
3490 goto error;
3491 builtins = PyEval_GetBuiltins();
3492 if (builtins == NULL)
3493 goto error;
Victor Stinner3c1e4812012-03-26 22:10:51 +02003494 sorted = _PyDict_GetItemId(builtins, &PyId_sorted);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003495 if (sorted == NULL)
3496 goto error;
3497 sorted_methods = PyObject_CallFunctionObjArgs(sorted,
3498 abstract_methods,
3499 NULL);
3500 if (sorted_methods == NULL)
3501 goto error;
Benjamin Peterson9a03ecf2012-03-16 20:15:54 -05003502 comma = _PyUnicode_FromId(&comma_id);
3503 if (comma == NULL)
3504 goto error;
3505 joined = PyUnicode_Join(comma, sorted_methods);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003506 if (joined == NULL)
3507 goto error;
Christian Heimes9e7f1d22008-02-28 12:27:11 +00003508
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003509 PyErr_Format(PyExc_TypeError,
3510 "Can't instantiate abstract class %s "
3511 "with abstract methods %U",
3512 type->tp_name,
3513 joined);
3514 error:
3515 Py_XDECREF(joined);
3516 Py_XDECREF(sorted_methods);
3517 Py_XDECREF(abstract_methods);
3518 return NULL;
3519 }
3520 return type->tp_alloc(type, 0);
Guido van Rossum298e4212003-02-13 16:30:16 +00003521}
3522
Tim Peters6d6c1a32001-08-02 04:15:00 +00003523static void
3524object_dealloc(PyObject *self)
3525{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003526 Py_TYPE(self)->tp_free(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003527}
3528
Guido van Rossum8e248182001-08-12 05:17:56 +00003529static PyObject *
3530object_repr(PyObject *self)
3531{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003532 PyTypeObject *type;
3533 PyObject *mod, *name, *rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00003534
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003535 type = Py_TYPE(self);
3536 mod = type_module(type, NULL);
3537 if (mod == NULL)
3538 PyErr_Clear();
3539 else if (!PyUnicode_Check(mod)) {
3540 Py_DECREF(mod);
3541 mod = NULL;
3542 }
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003543 name = type_qualname(type, NULL);
Christian Heimese81dc292012-09-10 16:57:36 +02003544 if (name == NULL) {
3545 Py_XDECREF(mod);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003546 return NULL;
Christian Heimese81dc292012-09-10 16:57:36 +02003547 }
Serhiy Storchakaf5894dd2016-11-16 15:40:39 +02003548 if (mod != NULL && !_PyUnicode_EqualToASCIIId(mod, &PyId_builtins))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003549 rtn = PyUnicode_FromFormat("<%U.%U object at %p>", mod, name, self);
3550 else
3551 rtn = PyUnicode_FromFormat("<%s object at %p>",
3552 type->tp_name, self);
3553 Py_XDECREF(mod);
3554 Py_DECREF(name);
3555 return rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00003556}
3557
Guido van Rossumb8f63662001-08-15 23:57:02 +00003558static PyObject *
3559object_str(PyObject *self)
3560{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003561 unaryfunc f;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003562
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003563 f = Py_TYPE(self)->tp_repr;
Benjamin Peterson7b166872012-04-24 11:06:25 -04003564 if (f == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003565 f = object_repr;
3566 return f(self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003567}
3568
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003569static PyObject *
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003570object_richcompare(PyObject *self, PyObject *other, int op)
3571{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003572 PyObject *res;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003573
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003574 switch (op) {
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003575
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003576 case Py_EQ:
3577 /* Return NotImplemented instead of False, so if two
3578 objects are compared, both get a chance at the
3579 comparison. See issue #1393. */
3580 res = (self == other) ? Py_True : Py_NotImplemented;
3581 Py_INCREF(res);
3582 break;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003583
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003584 case Py_NE:
Serhiy Storchakaf4b7a022015-01-26 09:57:07 +02003585 /* By default, __ne__() delegates to __eq__() and inverts the result,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003586 unless the latter returns NotImplemented. */
Serhiy Storchakaf4b7a022015-01-26 09:57:07 +02003587 if (self->ob_type->tp_richcompare == NULL) {
3588 res = Py_NotImplemented;
3589 Py_INCREF(res);
3590 break;
3591 }
3592 res = (*self->ob_type->tp_richcompare)(self, other, Py_EQ);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003593 if (res != NULL && res != Py_NotImplemented) {
3594 int ok = PyObject_IsTrue(res);
3595 Py_DECREF(res);
3596 if (ok < 0)
3597 res = NULL;
3598 else {
3599 if (ok)
3600 res = Py_False;
3601 else
3602 res = Py_True;
3603 Py_INCREF(res);
3604 }
3605 }
3606 break;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003607
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003608 default:
3609 res = Py_NotImplemented;
3610 Py_INCREF(res);
3611 break;
3612 }
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003613
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003614 return res;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003615}
3616
3617static PyObject *
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003618object_get_class(PyObject *self, void *closure)
3619{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003620 Py_INCREF(Py_TYPE(self));
3621 return (PyObject *)(Py_TYPE(self));
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003622}
3623
3624static int
Benjamin Peterson9d4cbcc2015-01-30 13:33:42 -05003625compatible_with_tp_base(PyTypeObject *child)
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003626{
Benjamin Peterson9d4cbcc2015-01-30 13:33:42 -05003627 PyTypeObject *parent = child->tp_base;
3628 return (parent != NULL &&
3629 child->tp_basicsize == parent->tp_basicsize &&
3630 child->tp_itemsize == parent->tp_itemsize &&
3631 child->tp_dictoffset == parent->tp_dictoffset &&
3632 child->tp_weaklistoffset == parent->tp_weaklistoffset &&
3633 ((child->tp_flags & Py_TPFLAGS_HAVE_GC) ==
3634 (parent->tp_flags & Py_TPFLAGS_HAVE_GC)) &&
3635 (child->tp_dealloc == subtype_dealloc ||
3636 child->tp_dealloc == parent->tp_dealloc));
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003637}
3638
3639static int
3640same_slots_added(PyTypeObject *a, PyTypeObject *b)
3641{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003642 PyTypeObject *base = a->tp_base;
3643 Py_ssize_t size;
3644 PyObject *slots_a, *slots_b;
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003645
Benjamin Peterson67641d22011-01-17 19:24:34 +00003646 assert(base == b->tp_base);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003647 size = base->tp_basicsize;
3648 if (a->tp_dictoffset == size && b->tp_dictoffset == size)
3649 size += sizeof(PyObject *);
3650 if (a->tp_weaklistoffset == size && b->tp_weaklistoffset == size)
3651 size += sizeof(PyObject *);
Guido van Rossumd8faa362007-04-27 19:54:29 +00003652
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003653 /* Check slots compliance */
Benjamin Peterson9d4cbcc2015-01-30 13:33:42 -05003654 if (!(a->tp_flags & Py_TPFLAGS_HEAPTYPE) ||
3655 !(b->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
3656 return 0;
3657 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003658 slots_a = ((PyHeapTypeObject *)a)->ht_slots;
3659 slots_b = ((PyHeapTypeObject *)b)->ht_slots;
3660 if (slots_a && slots_b) {
3661 if (PyObject_RichCompareBool(slots_a, slots_b, Py_EQ) != 1)
3662 return 0;
3663 size += sizeof(PyObject *) * PyTuple_GET_SIZE(slots_a);
3664 }
3665 return size == a->tp_basicsize && size == b->tp_basicsize;
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003666}
3667
3668static int
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02003669compatible_for_assignment(PyTypeObject* oldto, PyTypeObject* newto, const char* attr)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003670{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003671 PyTypeObject *newbase, *oldbase;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003672
Benjamin Peterson9d4cbcc2015-01-30 13:33:42 -05003673 if (newto->tp_free != oldto->tp_free) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003674 PyErr_Format(PyExc_TypeError,
3675 "%s assignment: "
3676 "'%s' deallocator differs from '%s'",
3677 attr,
3678 newto->tp_name,
3679 oldto->tp_name);
3680 return 0;
3681 }
Benjamin Peterson9d4cbcc2015-01-30 13:33:42 -05003682 /*
3683 It's tricky to tell if two arbitrary types are sufficiently compatible as
3684 to be interchangeable; e.g., even if they have the same tp_basicsize, they
3685 might have totally different struct fields. It's much easier to tell if a
3686 type and its supertype are compatible; e.g., if they have the same
3687 tp_basicsize, then that means they have identical fields. So to check
3688 whether two arbitrary types are compatible, we first find the highest
3689 supertype that each is compatible with, and then if those supertypes are
3690 compatible then the original types must also be compatible.
3691 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003692 newbase = newto;
3693 oldbase = oldto;
Benjamin Peterson9d4cbcc2015-01-30 13:33:42 -05003694 while (compatible_with_tp_base(newbase))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003695 newbase = newbase->tp_base;
Benjamin Peterson9d4cbcc2015-01-30 13:33:42 -05003696 while (compatible_with_tp_base(oldbase))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003697 oldbase = oldbase->tp_base;
3698 if (newbase != oldbase &&
3699 (newbase->tp_base != oldbase->tp_base ||
3700 !same_slots_added(newbase, oldbase))) {
3701 PyErr_Format(PyExc_TypeError,
3702 "%s assignment: "
3703 "'%s' object layout differs from '%s'",
3704 attr,
3705 newto->tp_name,
3706 oldto->tp_name);
3707 return 0;
3708 }
Tim Petersea7f75d2002-12-07 21:39:16 +00003709
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003710 return 1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003711}
3712
3713static int
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003714object_set_class(PyObject *self, PyObject *value, void *closure)
3715{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003716 PyTypeObject *oldto = Py_TYPE(self);
3717 PyTypeObject *newto;
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003718
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003719 if (value == NULL) {
3720 PyErr_SetString(PyExc_TypeError,
3721 "can't delete __class__ attribute");
3722 return -1;
3723 }
3724 if (!PyType_Check(value)) {
3725 PyErr_Format(PyExc_TypeError,
Florent Xiclunaaa6c1d22011-12-12 18:54:29 +01003726 "__class__ must be set to a class, not '%s' object",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003727 Py_TYPE(value)->tp_name);
3728 return -1;
3729 }
3730 newto = (PyTypeObject *)value;
Guido van Rossum7d293ee2015-09-04 20:54:07 -07003731 /* In versions of CPython prior to 3.5, the code in
3732 compatible_for_assignment was not set up to correctly check for memory
3733 layout / slot / etc. compatibility for non-HEAPTYPE classes, so we just
3734 disallowed __class__ assignment in any case that wasn't HEAPTYPE ->
3735 HEAPTYPE.
3736
3737 During the 3.5 development cycle, we fixed the code in
3738 compatible_for_assignment to correctly check compatibility between
3739 arbitrary types, and started allowing __class__ assignment in all cases
3740 where the old and new types did in fact have compatible slots and
3741 memory layout (regardless of whether they were implemented as HEAPTYPEs
3742 or not).
3743
3744 Just before 3.5 was released, though, we discovered that this led to
3745 problems with immutable types like int, where the interpreter assumes
3746 they are immutable and interns some values. Formerly this wasn't a
3747 problem, because they really were immutable -- in particular, all the
3748 types where the interpreter applied this interning trick happened to
3749 also be statically allocated, so the old HEAPTYPE rules were
3750 "accidentally" stopping them from allowing __class__ assignment. But
3751 with the changes to __class__ assignment, we started allowing code like
3752
3753 class MyInt(int):
3754 ...
3755 # Modifies the type of *all* instances of 1 in the whole program,
3756 # including future instances (!), because the 1 object is interned.
3757 (1).__class__ = MyInt
3758
3759 (see https://bugs.python.org/issue24912).
3760
3761 In theory the proper fix would be to identify which classes rely on
3762 this invariant and somehow disallow __class__ assignment only for them,
3763 perhaps via some mechanism like a new Py_TPFLAGS_IMMUTABLE flag (a
3764 "blacklisting" approach). But in practice, since this problem wasn't
3765 noticed late in the 3.5 RC cycle, we're taking the conservative
3766 approach and reinstating the same HEAPTYPE->HEAPTYPE check that we used
3767 to have, plus a "whitelist". For now, the whitelist consists only of
3768 ModuleType subtypes, since those are the cases that motivated the patch
3769 in the first place -- see https://bugs.python.org/issue22986 -- and
3770 since module objects are mutable we can be sure that they are
3771 definitely not being interned. So now we allow HEAPTYPE->HEAPTYPE *or*
3772 ModuleType subtype -> ModuleType subtype.
3773
3774 So far as we know, all the code beyond the following 'if' statement
3775 will correctly handle non-HEAPTYPE classes, and the HEAPTYPE check is
3776 needed only to protect that subset of non-HEAPTYPE classes for which
3777 the interpreter has baked in the assumption that all instances are
3778 truly immutable.
3779 */
3780 if (!(PyType_IsSubtype(newto, &PyModule_Type) &&
3781 PyType_IsSubtype(oldto, &PyModule_Type)) &&
3782 (!(newto->tp_flags & Py_TPFLAGS_HEAPTYPE) ||
3783 !(oldto->tp_flags & Py_TPFLAGS_HEAPTYPE))) {
3784 PyErr_Format(PyExc_TypeError,
3785 "__class__ assignment only supported for heap types "
3786 "or ModuleType subclasses");
3787 return -1;
3788 }
3789
Christian Heimesde4d1832013-07-20 14:19:46 +02003790 if (compatible_for_assignment(oldto, newto, "__class__")) {
Benjamin Peterson9d4cbcc2015-01-30 13:33:42 -05003791 if (newto->tp_flags & Py_TPFLAGS_HEAPTYPE)
3792 Py_INCREF(newto);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003793 Py_TYPE(self) = newto;
Benjamin Peterson9d4cbcc2015-01-30 13:33:42 -05003794 if (oldto->tp_flags & Py_TPFLAGS_HEAPTYPE)
3795 Py_DECREF(oldto);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003796 return 0;
3797 }
3798 else {
3799 return -1;
3800 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003801}
3802
3803static PyGetSetDef object_getsets[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003804 {"__class__", object_get_class, object_set_class,
3805 PyDoc_STR("the object's class")},
3806 {0}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003807};
3808
Guido van Rossumc53f0092003-02-18 22:05:12 +00003809
Guido van Rossum036f9992003-02-21 22:02:54 +00003810/* Stuff to implement __reduce_ex__ for pickle protocols >= 2.
Alexandre Vassalottif7fa63d2008-05-11 08:55:36 +00003811 We fall back to helpers in copyreg for:
Guido van Rossum036f9992003-02-21 22:02:54 +00003812 - pickle protocols < 2
3813 - calculating the list of slot names (done only once per class)
3814 - the __newobj__ function (which is used as a token but never called)
3815*/
3816
3817static PyObject *
Alexandre Vassalottif7fa63d2008-05-11 08:55:36 +00003818import_copyreg(void)
Guido van Rossum036f9992003-02-21 22:02:54 +00003819{
Alexandre Vassalotti1a830702013-11-30 00:53:09 -08003820 PyObject *copyreg_str;
3821 PyObject *copyreg_module;
3822 PyInterpreterState *interp = PyThreadState_GET()->interp;
3823 _Py_IDENTIFIER(copyreg);
Guido van Rossum3926a632001-09-25 16:25:58 +00003824
Alexandre Vassalotti1a830702013-11-30 00:53:09 -08003825 copyreg_str = _PyUnicode_FromId(&PyId_copyreg);
3826 if (copyreg_str == NULL) {
3827 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003828 }
Alexandre Vassalotti1a830702013-11-30 00:53:09 -08003829 /* Try to fetch cached copy of copyreg from sys.modules first in an
3830 attempt to avoid the import overhead. Previously this was implemented
3831 by storing a reference to the cached module in a static variable, but
Raymond Hettinger15f44ab2016-08-30 10:47:49 -07003832 this broke when multiple embedded interpreters were in use (see issue
Alexandre Vassalotti1a830702013-11-30 00:53:09 -08003833 #17408 and #19088). */
3834 copyreg_module = PyDict_GetItemWithError(interp->modules, copyreg_str);
3835 if (copyreg_module != NULL) {
3836 Py_INCREF(copyreg_module);
3837 return copyreg_module;
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003838 }
Alexandre Vassalotti1a830702013-11-30 00:53:09 -08003839 if (PyErr_Occurred()) {
3840 return NULL;
3841 }
3842 return PyImport_Import(copyreg_str);
Guido van Rossum036f9992003-02-21 22:02:54 +00003843}
3844
Benjamin Peterson6cb526e2016-09-09 12:42:51 -07003845static PyObject *
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01003846_PyType_GetSlotNames(PyTypeObject *cls)
Guido van Rossum036f9992003-02-21 22:02:54 +00003847{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003848 PyObject *copyreg;
3849 PyObject *slotnames;
Victor Stinner3c1e4812012-03-26 22:10:51 +02003850 _Py_IDENTIFIER(__slotnames__);
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02003851 _Py_IDENTIFIER(_slotnames);
Guido van Rossum036f9992003-02-21 22:02:54 +00003852
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01003853 assert(PyType_Check(cls));
3854
3855 /* Get the slot names from the cache in the class if possible. */
3856 slotnames = _PyDict_GetItemIdWithError(cls->tp_dict, &PyId___slotnames__);
3857 if (slotnames != NULL) {
3858 if (slotnames != Py_None && !PyList_Check(slotnames)) {
3859 PyErr_Format(PyExc_TypeError,
3860 "%.200s.__slotnames__ should be a list or None, "
3861 "not %.200s",
3862 cls->tp_name, Py_TYPE(slotnames)->tp_name);
3863 return NULL;
3864 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003865 Py_INCREF(slotnames);
3866 return slotnames;
3867 }
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01003868 else {
3869 if (PyErr_Occurred()) {
3870 return NULL;
3871 }
3872 /* The class does not have the slot names cached yet. */
3873 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003874
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003875 copyreg = import_copyreg();
3876 if (copyreg == NULL)
3877 return NULL;
Guido van Rossum036f9992003-02-21 22:02:54 +00003878
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01003879 /* Use _slotnames function from the copyreg module to find the slots
3880 by this class and its bases. This function will cache the result
3881 in __slotnames__. */
3882 slotnames = _PyObject_CallMethodIdObjArgs(copyreg, &PyId__slotnames,
3883 cls, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003884 Py_DECREF(copyreg);
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01003885 if (slotnames == NULL)
3886 return NULL;
3887
3888 if (slotnames != Py_None && !PyList_Check(slotnames)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003889 PyErr_SetString(PyExc_TypeError,
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01003890 "copyreg._slotnames didn't return a list or None");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003891 Py_DECREF(slotnames);
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01003892 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003893 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003894
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003895 return slotnames;
Guido van Rossum036f9992003-02-21 22:02:54 +00003896}
3897
Benjamin Peterson6cb526e2016-09-09 12:42:51 -07003898static PyObject *
Serhiy Storchakaf81be8a2015-12-25 21:04:29 +02003899_PyObject_GetState(PyObject *obj, int required)
Guido van Rossum036f9992003-02-21 22:02:54 +00003900{
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01003901 PyObject *state;
3902 PyObject *getstate;
Victor Stinner3c1e4812012-03-26 22:10:51 +02003903 _Py_IDENTIFIER(__getstate__);
Guido van Rossum036f9992003-02-21 22:02:54 +00003904
Victor Stinner3c1e4812012-03-26 22:10:51 +02003905 getstate = _PyObject_GetAttrId(obj, &PyId___getstate__);
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01003906 if (getstate == NULL) {
3907 PyObject *slotnames;
3908
3909 if (!PyErr_ExceptionMatches(PyExc_AttributeError)) {
3910 return NULL;
3911 }
3912 PyErr_Clear();
3913
Serhiy Storchakaf81be8a2015-12-25 21:04:29 +02003914 if (required && obj->ob_type->tp_itemsize) {
3915 PyErr_Format(PyExc_TypeError,
3916 "can't pickle %.200s objects",
3917 Py_TYPE(obj)->tp_name);
3918 return NULL;
3919 }
3920
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01003921 {
3922 PyObject **dict;
3923 dict = _PyObject_GetDictPtr(obj);
Larry Hastings5c661892014-01-24 06:17:25 -08003924 /* It is possible that the object's dict is not initialized
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01003925 yet. In this case, we will return None for the state.
3926 We also return None if the dict is empty to make the behavior
3927 consistent regardless whether the dict was initialized or not.
3928 This make unit testing easier. */
3929 if (dict != NULL && *dict != NULL && PyDict_Size(*dict) > 0) {
3930 state = *dict;
3931 }
3932 else {
3933 state = Py_None;
3934 }
3935 Py_INCREF(state);
3936 }
3937
3938 slotnames = _PyType_GetSlotNames(Py_TYPE(obj));
3939 if (slotnames == NULL) {
3940 Py_DECREF(state);
3941 return NULL;
3942 }
3943
3944 assert(slotnames == Py_None || PyList_Check(slotnames));
Serhiy Storchakaf81be8a2015-12-25 21:04:29 +02003945 if (required) {
3946 Py_ssize_t basicsize = PyBaseObject_Type.tp_basicsize;
3947 if (obj->ob_type->tp_dictoffset)
3948 basicsize += sizeof(PyObject *);
3949 if (obj->ob_type->tp_weaklistoffset)
3950 basicsize += sizeof(PyObject *);
3951 if (slotnames != Py_None)
3952 basicsize += sizeof(PyObject *) * Py_SIZE(slotnames);
3953 if (obj->ob_type->tp_basicsize > basicsize) {
3954 Py_DECREF(slotnames);
3955 Py_DECREF(state);
3956 PyErr_Format(PyExc_TypeError,
3957 "can't pickle %.200s objects",
3958 Py_TYPE(obj)->tp_name);
3959 return NULL;
3960 }
3961 }
3962
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01003963 if (slotnames != Py_None && Py_SIZE(slotnames) > 0) {
3964 PyObject *slots;
3965 Py_ssize_t slotnames_size, i;
3966
3967 slots = PyDict_New();
3968 if (slots == NULL) {
3969 Py_DECREF(slotnames);
3970 Py_DECREF(state);
3971 return NULL;
3972 }
3973
3974 slotnames_size = Py_SIZE(slotnames);
3975 for (i = 0; i < slotnames_size; i++) {
3976 PyObject *name, *value;
3977
3978 name = PyList_GET_ITEM(slotnames, i);
Serhiy Storchakad28bb622015-11-25 18:33:29 +02003979 Py_INCREF(name);
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01003980 value = PyObject_GetAttr(obj, name);
3981 if (value == NULL) {
Serhiy Storchakad28bb622015-11-25 18:33:29 +02003982 Py_DECREF(name);
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01003983 if (!PyErr_ExceptionMatches(PyExc_AttributeError)) {
3984 goto error;
3985 }
3986 /* It is not an error if the attribute is not present. */
3987 PyErr_Clear();
3988 }
3989 else {
3990 int err = PyDict_SetItem(slots, name, value);
Serhiy Storchakad28bb622015-11-25 18:33:29 +02003991 Py_DECREF(name);
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01003992 Py_DECREF(value);
3993 if (err) {
3994 goto error;
3995 }
3996 }
3997
Martin Panter8f265652016-04-19 04:03:41 +00003998 /* The list is stored on the class so it may mutate while we
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01003999 iterate over it */
4000 if (slotnames_size != Py_SIZE(slotnames)) {
4001 PyErr_Format(PyExc_RuntimeError,
4002 "__slotsname__ changed size during iteration");
4003 goto error;
4004 }
4005
4006 /* We handle errors within the loop here. */
4007 if (0) {
4008 error:
4009 Py_DECREF(slotnames);
4010 Py_DECREF(slots);
4011 Py_DECREF(state);
4012 return NULL;
4013 }
4014 }
4015
4016 /* If we found some slot attributes, pack them in a tuple along
Berker Peksag0ac70c02016-04-29 16:54:10 +03004017 the original attribute dictionary. */
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004018 if (PyDict_Size(slots) > 0) {
4019 PyObject *state2;
4020
4021 state2 = PyTuple_Pack(2, state, slots);
4022 Py_DECREF(state);
4023 if (state2 == NULL) {
4024 Py_DECREF(slotnames);
4025 Py_DECREF(slots);
4026 return NULL;
4027 }
4028 state = state2;
4029 }
4030 Py_DECREF(slots);
4031 }
4032 Py_DECREF(slotnames);
4033 }
4034 else { /* getstate != NULL */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004035 state = PyObject_CallObject(getstate, NULL);
4036 Py_DECREF(getstate);
4037 if (state == NULL)
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004038 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004039 }
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004040
4041 return state;
4042}
4043
Benjamin Peterson6cb526e2016-09-09 12:42:51 -07004044static int
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004045_PyObject_GetNewArguments(PyObject *obj, PyObject **args, PyObject **kwargs)
4046{
4047 PyObject *getnewargs, *getnewargs_ex;
4048 _Py_IDENTIFIER(__getnewargs_ex__);
4049 _Py_IDENTIFIER(__getnewargs__);
4050
4051 if (args == NULL || kwargs == NULL) {
4052 PyErr_BadInternalCall();
4053 return -1;
4054 }
4055
4056 /* We first attempt to fetch the arguments for __new__ by calling
4057 __getnewargs_ex__ on the object. */
Benjamin Petersone686c5c2014-02-16 13:49:16 -05004058 getnewargs_ex = _PyObject_LookupSpecial(obj, &PyId___getnewargs_ex__);
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004059 if (getnewargs_ex != NULL) {
4060 PyObject *newargs = PyObject_CallObject(getnewargs_ex, NULL);
4061 Py_DECREF(getnewargs_ex);
4062 if (newargs == NULL) {
4063 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004064 }
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004065 if (!PyTuple_Check(newargs)) {
4066 PyErr_Format(PyExc_TypeError,
4067 "__getnewargs_ex__ should return a tuple, "
4068 "not '%.200s'", Py_TYPE(newargs)->tp_name);
4069 Py_DECREF(newargs);
4070 return -1;
4071 }
4072 if (Py_SIZE(newargs) != 2) {
4073 PyErr_Format(PyExc_ValueError,
4074 "__getnewargs_ex__ should return a tuple of "
4075 "length 2, not %zd", Py_SIZE(newargs));
4076 Py_DECREF(newargs);
4077 return -1;
4078 }
4079 *args = PyTuple_GET_ITEM(newargs, 0);
4080 Py_INCREF(*args);
4081 *kwargs = PyTuple_GET_ITEM(newargs, 1);
4082 Py_INCREF(*kwargs);
4083 Py_DECREF(newargs);
4084
4085 /* XXX We should perhaps allow None to be passed here. */
4086 if (!PyTuple_Check(*args)) {
4087 PyErr_Format(PyExc_TypeError,
4088 "first item of the tuple returned by "
4089 "__getnewargs_ex__ must be a tuple, not '%.200s'",
4090 Py_TYPE(*args)->tp_name);
4091 Py_CLEAR(*args);
4092 Py_CLEAR(*kwargs);
4093 return -1;
4094 }
4095 if (!PyDict_Check(*kwargs)) {
4096 PyErr_Format(PyExc_TypeError,
4097 "second item of the tuple returned by "
4098 "__getnewargs_ex__ must be a dict, not '%.200s'",
4099 Py_TYPE(*kwargs)->tp_name);
4100 Py_CLEAR(*args);
4101 Py_CLEAR(*kwargs);
4102 return -1;
4103 }
4104 return 0;
Benjamin Petersone686c5c2014-02-16 13:49:16 -05004105 } else if (PyErr_Occurred()) {
4106 return -1;
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004107 }
4108
4109 /* The object does not have __getnewargs_ex__ so we fallback on using
4110 __getnewargs__ instead. */
Benjamin Petersone686c5c2014-02-16 13:49:16 -05004111 getnewargs = _PyObject_LookupSpecial(obj, &PyId___getnewargs__);
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004112 if (getnewargs != NULL) {
4113 *args = PyObject_CallObject(getnewargs, NULL);
4114 Py_DECREF(getnewargs);
4115 if (*args == NULL) {
4116 return -1;
4117 }
4118 if (!PyTuple_Check(*args)) {
4119 PyErr_Format(PyExc_TypeError,
4120 "__getnewargs__ should return a tuple, "
4121 "not '%.200s'", Py_TYPE(*args)->tp_name);
4122 Py_CLEAR(*args);
4123 return -1;
4124 }
4125 *kwargs = NULL;
4126 return 0;
Benjamin Petersone686c5c2014-02-16 13:49:16 -05004127 } else if (PyErr_Occurred()) {
4128 return -1;
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004129 }
4130
4131 /* The object does not have __getnewargs_ex__ and __getnewargs__. This may
Martin Panter8f265652016-04-19 04:03:41 +00004132 mean __new__ does not takes any arguments on this object, or that the
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004133 object does not implement the reduce protocol for pickling or
4134 copying. */
4135 *args = NULL;
4136 *kwargs = NULL;
4137 return 0;
4138}
4139
Benjamin Peterson6cb526e2016-09-09 12:42:51 -07004140static int
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004141_PyObject_GetItemsIter(PyObject *obj, PyObject **listitems,
4142 PyObject **dictitems)
4143{
4144 if (listitems == NULL || dictitems == NULL) {
4145 PyErr_BadInternalCall();
4146 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004147 }
Guido van Rossum036f9992003-02-21 22:02:54 +00004148
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004149 if (!PyList_Check(obj)) {
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004150 *listitems = Py_None;
4151 Py_INCREF(*listitems);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004152 }
4153 else {
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004154 *listitems = PyObject_GetIter(obj);
Christian Heimes2489bd82013-11-23 21:19:43 +01004155 if (*listitems == NULL)
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004156 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004157 }
Guido van Rossum036f9992003-02-21 22:02:54 +00004158
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004159 if (!PyDict_Check(obj)) {
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004160 *dictitems = Py_None;
4161 Py_INCREF(*dictitems);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004162 }
4163 else {
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004164 PyObject *items;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02004165 _Py_IDENTIFIER(items);
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004166
4167 items = _PyObject_CallMethodIdObjArgs(obj, &PyId_items, NULL);
4168 if (items == NULL) {
4169 Py_CLEAR(*listitems);
4170 return -1;
4171 }
4172 *dictitems = PyObject_GetIter(items);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004173 Py_DECREF(items);
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004174 if (*dictitems == NULL) {
4175 Py_CLEAR(*listitems);
4176 return -1;
4177 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004178 }
Guido van Rossum036f9992003-02-21 22:02:54 +00004179
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004180 assert(*listitems != NULL && *dictitems != NULL);
4181
4182 return 0;
4183}
4184
4185static PyObject *
Serhiy Storchaka0d554d72015-10-10 22:42:18 +03004186reduce_newobj(PyObject *obj)
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004187{
4188 PyObject *args = NULL, *kwargs = NULL;
4189 PyObject *copyreg;
4190 PyObject *newobj, *newargs, *state, *listitems, *dictitems;
4191 PyObject *result;
Serhiy Storchakaf81be8a2015-12-25 21:04:29 +02004192 int hasargs;
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004193
Serhiy Storchakad7a44152015-11-12 11:23:04 +02004194 if (Py_TYPE(obj)->tp_new == NULL) {
4195 PyErr_Format(PyExc_TypeError,
Serhiy Storchakaf81be8a2015-12-25 21:04:29 +02004196 "can't pickle %.200s objects",
Serhiy Storchakad7a44152015-11-12 11:23:04 +02004197 Py_TYPE(obj)->tp_name);
4198 return NULL;
4199 }
Serhiy Storchaka707b5cc2014-12-16 19:43:46 +02004200 if (_PyObject_GetNewArguments(obj, &args, &kwargs) < 0)
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004201 return NULL;
Serhiy Storchaka707b5cc2014-12-16 19:43:46 +02004202
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004203 copyreg = import_copyreg();
4204 if (copyreg == NULL) {
Serhiy Storchakaf81be8a2015-12-25 21:04:29 +02004205 Py_XDECREF(args);
Serhiy Storchaka707b5cc2014-12-16 19:43:46 +02004206 Py_XDECREF(kwargs);
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004207 return NULL;
4208 }
Serhiy Storchakaf81be8a2015-12-25 21:04:29 +02004209 hasargs = (args != NULL);
Serhiy Storchaka707b5cc2014-12-16 19:43:46 +02004210 if (kwargs == NULL || PyDict_Size(kwargs) == 0) {
4211 _Py_IDENTIFIER(__newobj__);
4212 PyObject *cls;
4213 Py_ssize_t i, n;
4214
4215 Py_XDECREF(kwargs);
4216 newobj = _PyObject_GetAttrId(copyreg, &PyId___newobj__);
4217 Py_DECREF(copyreg);
4218 if (newobj == NULL) {
Serhiy Storchakaf81be8a2015-12-25 21:04:29 +02004219 Py_XDECREF(args);
Serhiy Storchaka707b5cc2014-12-16 19:43:46 +02004220 return NULL;
4221 }
Serhiy Storchakaf81be8a2015-12-25 21:04:29 +02004222 n = args ? PyTuple_GET_SIZE(args) : 0;
Serhiy Storchaka707b5cc2014-12-16 19:43:46 +02004223 newargs = PyTuple_New(n+1);
4224 if (newargs == NULL) {
Serhiy Storchakaf81be8a2015-12-25 21:04:29 +02004225 Py_XDECREF(args);
Serhiy Storchaka707b5cc2014-12-16 19:43:46 +02004226 Py_DECREF(newobj);
4227 return NULL;
4228 }
4229 cls = (PyObject *) Py_TYPE(obj);
4230 Py_INCREF(cls);
4231 PyTuple_SET_ITEM(newargs, 0, cls);
4232 for (i = 0; i < n; i++) {
4233 PyObject *v = PyTuple_GET_ITEM(args, i);
4234 Py_INCREF(v);
4235 PyTuple_SET_ITEM(newargs, i+1, v);
4236 }
Serhiy Storchakaf81be8a2015-12-25 21:04:29 +02004237 Py_XDECREF(args);
Serhiy Storchaka707b5cc2014-12-16 19:43:46 +02004238 }
Christian Heimes07a2a1b2016-09-09 00:21:22 +02004239 else if (args != NULL) {
Serhiy Storchaka707b5cc2014-12-16 19:43:46 +02004240 _Py_IDENTIFIER(__newobj_ex__);
4241
4242 newobj = _PyObject_GetAttrId(copyreg, &PyId___newobj_ex__);
4243 Py_DECREF(copyreg);
4244 if (newobj == NULL) {
4245 Py_DECREF(args);
4246 Py_DECREF(kwargs);
4247 return NULL;
4248 }
4249 newargs = PyTuple_Pack(3, Py_TYPE(obj), args, kwargs);
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004250 Py_DECREF(args);
4251 Py_DECREF(kwargs);
Serhiy Storchaka707b5cc2014-12-16 19:43:46 +02004252 if (newargs == NULL) {
4253 Py_DECREF(newobj);
4254 return NULL;
4255 }
4256 }
Christian Heimes07a2a1b2016-09-09 00:21:22 +02004257 else {
4258 /* args == NULL */
4259 Py_DECREF(kwargs);
4260 PyErr_BadInternalCall();
4261 return NULL;
4262 }
Serhiy Storchaka707b5cc2014-12-16 19:43:46 +02004263
Serhiy Storchakaf81be8a2015-12-25 21:04:29 +02004264 state = _PyObject_GetState(obj,
4265 !hasargs && !PyList_Check(obj) && !PyDict_Check(obj));
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004266 if (state == NULL) {
4267 Py_DECREF(newobj);
4268 Py_DECREF(newargs);
4269 return NULL;
4270 }
4271 if (_PyObject_GetItemsIter(obj, &listitems, &dictitems) < 0) {
4272 Py_DECREF(newobj);
4273 Py_DECREF(newargs);
4274 Py_DECREF(state);
4275 return NULL;
4276 }
4277
4278 result = PyTuple_Pack(5, newobj, newargs, state, listitems, dictitems);
4279 Py_DECREF(newobj);
4280 Py_DECREF(newargs);
4281 Py_DECREF(state);
4282 Py_DECREF(listitems);
4283 Py_DECREF(dictitems);
Larry Hastings5c661892014-01-24 06:17:25 -08004284 return result;
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004285}
4286
Guido van Rossumd8faa362007-04-27 19:54:29 +00004287/*
4288 * There were two problems when object.__reduce__ and object.__reduce_ex__
4289 * were implemented in the same function:
4290 * - trying to pickle an object with a custom __reduce__ method that
4291 * fell back to object.__reduce__ in certain circumstances led to
Yury Selivanovf488fb42015-07-03 01:04:23 -04004292 * infinite recursion at Python level and eventual RecursionError.
Guido van Rossumd8faa362007-04-27 19:54:29 +00004293 * - Pickling objects that lied about their type by overwriting the
4294 * __class__ descriptor could lead to infinite recursion at C level
4295 * and eventual segfault.
4296 *
4297 * Because of backwards compatibility, the two methods still have to
4298 * behave in the same way, even if this is not required by the pickle
4299 * protocol. This common functionality was moved to the _common_reduce
4300 * function.
4301 */
4302static PyObject *
4303_common_reduce(PyObject *self, int proto)
4304{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004305 PyObject *copyreg, *res;
Guido van Rossumd8faa362007-04-27 19:54:29 +00004306
Serhiy Storchaka707b5cc2014-12-16 19:43:46 +02004307 if (proto >= 2)
Serhiy Storchaka0d554d72015-10-10 22:42:18 +03004308 return reduce_newobj(self);
Guido van Rossumd8faa362007-04-27 19:54:29 +00004309
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004310 copyreg = import_copyreg();
4311 if (!copyreg)
4312 return NULL;
Guido van Rossumd8faa362007-04-27 19:54:29 +00004313
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004314 res = PyEval_CallMethod(copyreg, "_reduce_ex", "(Oi)", self, proto);
4315 Py_DECREF(copyreg);
Guido van Rossumd8faa362007-04-27 19:54:29 +00004316
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004317 return res;
Guido van Rossumd8faa362007-04-27 19:54:29 +00004318}
4319
4320static PyObject *
4321object_reduce(PyObject *self, PyObject *args)
4322{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004323 int proto = 0;
Guido van Rossumd8faa362007-04-27 19:54:29 +00004324
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004325 if (!PyArg_ParseTuple(args, "|i:__reduce__", &proto))
4326 return NULL;
Guido van Rossumd8faa362007-04-27 19:54:29 +00004327
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004328 return _common_reduce(self, proto);
Guido van Rossumd8faa362007-04-27 19:54:29 +00004329}
4330
Guido van Rossum036f9992003-02-21 22:02:54 +00004331static PyObject *
4332object_reduce_ex(PyObject *self, PyObject *args)
4333{
Victor Stinner3c1e4812012-03-26 22:10:51 +02004334 static PyObject *objreduce;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004335 PyObject *reduce, *res;
4336 int proto = 0;
Victor Stinner3c1e4812012-03-26 22:10:51 +02004337 _Py_IDENTIFIER(__reduce__);
Guido van Rossum036f9992003-02-21 22:02:54 +00004338
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004339 if (!PyArg_ParseTuple(args, "|i:__reduce_ex__", &proto))
4340 return NULL;
Guido van Rossum036f9992003-02-21 22:02:54 +00004341
Victor Stinner3c1e4812012-03-26 22:10:51 +02004342 if (objreduce == NULL) {
4343 objreduce = _PyDict_GetItemId(PyBaseObject_Type.tp_dict,
4344 &PyId___reduce__);
4345 if (objreduce == NULL)
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01004346 return NULL;
4347 }
4348
Victor Stinner3c1e4812012-03-26 22:10:51 +02004349 reduce = _PyObject_GetAttrId(self, &PyId___reduce__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004350 if (reduce == NULL)
4351 PyErr_Clear();
4352 else {
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01004353 PyObject *cls, *clsreduce;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004354 int override;
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01004355
4356 cls = (PyObject *) Py_TYPE(self);
Victor Stinner3c1e4812012-03-26 22:10:51 +02004357 clsreduce = _PyObject_GetAttrId(cls, &PyId___reduce__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004358 if (clsreduce == NULL) {
4359 Py_DECREF(reduce);
4360 return NULL;
4361 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004362 override = (clsreduce != objreduce);
4363 Py_DECREF(clsreduce);
4364 if (override) {
4365 res = PyObject_CallObject(reduce, NULL);
4366 Py_DECREF(reduce);
4367 return res;
4368 }
4369 else
4370 Py_DECREF(reduce);
4371 }
Guido van Rossum036f9992003-02-21 22:02:54 +00004372
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004373 return _common_reduce(self, proto);
Guido van Rossum3926a632001-09-25 16:25:58 +00004374}
4375
Christian Heimes9e7f1d22008-02-28 12:27:11 +00004376static PyObject *
4377object_subclasshook(PyObject *cls, PyObject *args)
4378{
Brian Curtindfc80e32011-08-10 20:28:54 -05004379 Py_RETURN_NOTIMPLEMENTED;
Christian Heimes9e7f1d22008-02-28 12:27:11 +00004380}
4381
4382PyDoc_STRVAR(object_subclasshook_doc,
4383"Abstract classes can override this to customize issubclass().\n"
4384"\n"
4385"This is invoked early on by abc.ABCMeta.__subclasscheck__().\n"
4386"It should return True, False or NotImplemented. If it returns\n"
4387"NotImplemented, the normal algorithm is used. Otherwise, it\n"
4388"overrides the normal algorithm (and the outcome is cached).\n");
Eric Smith8c663262007-08-25 02:26:07 +00004389
Nick Coghland78448e2016-07-30 16:26:03 +10004390static PyObject *
4391object_init_subclass(PyObject *cls, PyObject *arg)
4392{
4393 Py_RETURN_NONE;
4394}
4395
4396PyDoc_STRVAR(object_init_subclass_doc,
Berker Peksag01d17192016-07-30 14:06:15 +03004397"This method is called when a class is subclassed.\n"
Nick Coghland78448e2016-07-30 16:26:03 +10004398"\n"
Berker Peksag01d17192016-07-30 14:06:15 +03004399"The default implementation does nothing. It may be\n"
4400"overridden to extend subclasses.\n");
Nick Coghland78448e2016-07-30 16:26:03 +10004401
Eric Smith8c663262007-08-25 02:26:07 +00004402static PyObject *
4403object_format(PyObject *self, PyObject *args)
4404{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004405 PyObject *format_spec;
4406 PyObject *self_as_str = NULL;
4407 PyObject *result = NULL;
Eric Smith8c663262007-08-25 02:26:07 +00004408
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004409 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
4410 return NULL;
Eric Smith8c663262007-08-25 02:26:07 +00004411
Serhiy Storchakad1af5ef2016-10-30 19:33:54 +02004412 /* Issue 7994: If we're converting to a string, we
4413 should reject format specifications */
4414 if (PyUnicode_GET_LENGTH(format_spec) > 0) {
4415 PyErr_Format(PyExc_TypeError,
4416 "unsupported format string passed to %.200s.__format__",
4417 self->ob_type->tp_name);
4418 return NULL;
4419 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004420 self_as_str = PyObject_Str(self);
Eric Smithe4d63172010-09-13 20:48:43 +00004421 if (self_as_str != NULL) {
Eric V. Smithb9cd3532011-03-12 10:08:48 -05004422 result = PyObject_Format(self_as_str, format_spec);
Serhiy Storchakad1af5ef2016-10-30 19:33:54 +02004423 Py_DECREF(self_as_str);
Eric Smithe4d63172010-09-13 20:48:43 +00004424 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004425 return result;
Eric Smith8c663262007-08-25 02:26:07 +00004426}
4427
Martin v. Löwis00709aa2008-06-04 14:18:43 +00004428static PyObject *
4429object_sizeof(PyObject *self, PyObject *args)
4430{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004431 Py_ssize_t res, isize;
Martin v. Löwis00709aa2008-06-04 14:18:43 +00004432
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004433 res = 0;
4434 isize = self->ob_type->tp_itemsize;
4435 if (isize > 0)
Antoine Pitroua6545102015-03-10 22:32:00 +01004436 res = Py_SIZE(self) * isize;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004437 res += self->ob_type->tp_basicsize;
Martin v. Löwis00709aa2008-06-04 14:18:43 +00004438
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004439 return PyLong_FromSsize_t(res);
Martin v. Löwis00709aa2008-06-04 14:18:43 +00004440}
4441
Benjamin Peterson82b00c12011-05-24 11:09:06 -05004442/* __dir__ for generic objects: returns __dict__, __class__,
4443 and recursively up the __class__.__bases__ chain.
4444*/
4445static PyObject *
4446object_dir(PyObject *self, PyObject *args)
4447{
4448 PyObject *result = NULL;
4449 PyObject *dict = NULL;
4450 PyObject *itsclass = NULL;
4451
4452 /* Get __dict__ (which may or may not be a real dict...) */
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02004453 dict = _PyObject_GetAttrId(self, &PyId___dict__);
Benjamin Peterson82b00c12011-05-24 11:09:06 -05004454 if (dict == NULL) {
4455 PyErr_Clear();
4456 dict = PyDict_New();
4457 }
4458 else if (!PyDict_Check(dict)) {
4459 Py_DECREF(dict);
4460 dict = PyDict_New();
4461 }
4462 else {
4463 /* Copy __dict__ to avoid mutating it. */
4464 PyObject *temp = PyDict_Copy(dict);
4465 Py_DECREF(dict);
4466 dict = temp;
4467 }
4468
4469 if (dict == NULL)
4470 goto error;
4471
4472 /* Merge in attrs reachable from its class. */
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02004473 itsclass = _PyObject_GetAttrId(self, &PyId___class__);
Benjamin Peterson82b00c12011-05-24 11:09:06 -05004474 if (itsclass == NULL)
4475 /* XXX(tomer): Perhaps fall back to obj->ob_type if no
4476 __class__ exists? */
4477 PyErr_Clear();
4478 else if (merge_class_dict(dict, itsclass) != 0)
4479 goto error;
4480
4481 result = PyDict_Keys(dict);
4482 /* fall through */
4483error:
4484 Py_XDECREF(itsclass);
4485 Py_XDECREF(dict);
4486 return result;
4487}
4488
Guido van Rossum3926a632001-09-25 16:25:58 +00004489static PyMethodDef object_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004490 {"__reduce_ex__", object_reduce_ex, METH_VARARGS,
4491 PyDoc_STR("helper for pickle")},
4492 {"__reduce__", object_reduce, METH_VARARGS,
4493 PyDoc_STR("helper for pickle")},
4494 {"__subclasshook__", object_subclasshook, METH_CLASS | METH_VARARGS,
4495 object_subclasshook_doc},
Nick Coghland78448e2016-07-30 16:26:03 +10004496 {"__init_subclass__", object_init_subclass, METH_CLASS | METH_NOARGS,
4497 object_init_subclass_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004498 {"__format__", object_format, METH_VARARGS,
4499 PyDoc_STR("default object formatter")},
4500 {"__sizeof__", object_sizeof, METH_NOARGS,
Benjamin Petersonfbe56bb2011-05-24 12:42:51 -05004501 PyDoc_STR("__sizeof__() -> int\nsize of object in memory, in bytes")},
Benjamin Peterson82b00c12011-05-24 11:09:06 -05004502 {"__dir__", object_dir, METH_NOARGS,
Benjamin Petersonc7284122011-05-24 12:46:15 -05004503 PyDoc_STR("__dir__() -> list\ndefault dir() implementation")},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004504 {0}
Guido van Rossum3926a632001-09-25 16:25:58 +00004505};
4506
Guido van Rossum036f9992003-02-21 22:02:54 +00004507
Tim Peters6d6c1a32001-08-02 04:15:00 +00004508PyTypeObject PyBaseObject_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004509 PyVarObject_HEAD_INIT(&PyType_Type, 0)
4510 "object", /* tp_name */
4511 sizeof(PyObject), /* tp_basicsize */
4512 0, /* tp_itemsize */
4513 object_dealloc, /* tp_dealloc */
4514 0, /* tp_print */
4515 0, /* tp_getattr */
4516 0, /* tp_setattr */
4517 0, /* tp_reserved */
4518 object_repr, /* tp_repr */
4519 0, /* tp_as_number */
4520 0, /* tp_as_sequence */
4521 0, /* tp_as_mapping */
4522 (hashfunc)_Py_HashPointer, /* tp_hash */
4523 0, /* tp_call */
4524 object_str, /* tp_str */
4525 PyObject_GenericGetAttr, /* tp_getattro */
4526 PyObject_GenericSetAttr, /* tp_setattro */
4527 0, /* tp_as_buffer */
Larry Hastings5c661892014-01-24 06:17:25 -08004528 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Larry Hastings2623c8c2014-02-08 22:15:29 -08004529 PyDoc_STR("object()\n--\n\nThe most base type"), /* tp_doc */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004530 0, /* tp_traverse */
4531 0, /* tp_clear */
4532 object_richcompare, /* tp_richcompare */
4533 0, /* tp_weaklistoffset */
4534 0, /* tp_iter */
4535 0, /* tp_iternext */
4536 object_methods, /* tp_methods */
4537 0, /* tp_members */
4538 object_getsets, /* tp_getset */
4539 0, /* tp_base */
4540 0, /* tp_dict */
4541 0, /* tp_descr_get */
4542 0, /* tp_descr_set */
4543 0, /* tp_dictoffset */
4544 object_init, /* tp_init */
4545 PyType_GenericAlloc, /* tp_alloc */
4546 object_new, /* tp_new */
4547 PyObject_Del, /* tp_free */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004548};
4549
4550
Guido van Rossum50e9fb92006-08-17 05:42:55 +00004551/* Add the methods from tp_methods to the __dict__ in a type object */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004552
4553static int
4554add_methods(PyTypeObject *type, PyMethodDef *meth)
4555{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004556 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004557
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004558 for (; meth->ml_name != NULL; meth++) {
4559 PyObject *descr;
Benjamin Peterson89a6e9a2012-05-08 09:22:24 -04004560 int err;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004561 if (PyDict_GetItemString(dict, meth->ml_name) &&
4562 !(meth->ml_flags & METH_COEXIST))
4563 continue;
4564 if (meth->ml_flags & METH_CLASS) {
4565 if (meth->ml_flags & METH_STATIC) {
4566 PyErr_SetString(PyExc_ValueError,
4567 "method cannot be both class and static");
4568 return -1;
4569 }
4570 descr = PyDescr_NewClassMethod(type, meth);
4571 }
4572 else if (meth->ml_flags & METH_STATIC) {
Andrew Svetlov3ba3a3e2012-12-25 13:32:35 +02004573 PyObject *cfunc = PyCFunction_NewEx(meth, (PyObject*)type, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004574 if (cfunc == NULL)
4575 return -1;
4576 descr = PyStaticMethod_New(cfunc);
4577 Py_DECREF(cfunc);
4578 }
4579 else {
4580 descr = PyDescr_NewMethod(type, meth);
4581 }
4582 if (descr == NULL)
4583 return -1;
Benjamin Peterson89a6e9a2012-05-08 09:22:24 -04004584 err = PyDict_SetItemString(dict, meth->ml_name, descr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004585 Py_DECREF(descr);
Benjamin Peterson89a6e9a2012-05-08 09:22:24 -04004586 if (err < 0)
4587 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004588 }
4589 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004590}
4591
4592static int
Guido van Rossum6f799372001-09-20 20:46:19 +00004593add_members(PyTypeObject *type, PyMemberDef *memb)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004594{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004595 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004596
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004597 for (; memb->name != NULL; memb++) {
4598 PyObject *descr;
4599 if (PyDict_GetItemString(dict, memb->name))
4600 continue;
4601 descr = PyDescr_NewMember(type, memb);
4602 if (descr == NULL)
4603 return -1;
Benjamin Peterson27007dc2016-07-06 23:26:32 -07004604 if (PyDict_SetItemString(dict, memb->name, descr) < 0) {
4605 Py_DECREF(descr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004606 return -1;
Benjamin Peterson27007dc2016-07-06 23:26:32 -07004607 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004608 Py_DECREF(descr);
4609 }
4610 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004611}
4612
4613static int
Guido van Rossum32d34c82001-09-20 21:45:26 +00004614add_getset(PyTypeObject *type, PyGetSetDef *gsp)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004615{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004616 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004617
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004618 for (; gsp->name != NULL; gsp++) {
4619 PyObject *descr;
4620 if (PyDict_GetItemString(dict, gsp->name))
4621 continue;
4622 descr = PyDescr_NewGetSet(type, gsp);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004623
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004624 if (descr == NULL)
4625 return -1;
Benjamin Peterson27007dc2016-07-06 23:26:32 -07004626 if (PyDict_SetItemString(dict, gsp->name, descr) < 0) {
4627 Py_DECREF(descr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004628 return -1;
Benjamin Peterson27007dc2016-07-06 23:26:32 -07004629 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004630 Py_DECREF(descr);
4631 }
4632 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004633}
4634
Guido van Rossum13d52f02001-08-10 21:24:08 +00004635static void
4636inherit_special(PyTypeObject *type, PyTypeObject *base)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004637{
Tim Peters6d6c1a32001-08-02 04:15:00 +00004638
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004639 /* Copying basicsize is connected to the GC flags */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004640 if (!(type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
4641 (base->tp_flags & Py_TPFLAGS_HAVE_GC) &&
4642 (!type->tp_traverse && !type->tp_clear)) {
4643 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
4644 if (type->tp_traverse == NULL)
4645 type->tp_traverse = base->tp_traverse;
4646 if (type->tp_clear == NULL)
4647 type->tp_clear = base->tp_clear;
4648 }
4649 {
4650 /* The condition below could use some explanation.
4651 It appears that tp_new is not inherited for static types
4652 whose base class is 'object'; this seems to be a precaution
4653 so that old extension types don't suddenly become
4654 callable (object.__new__ wouldn't insure the invariants
4655 that the extension type's own factory function ensures).
4656 Heap types, of course, are under our control, so they do
4657 inherit tp_new; static extension types that specify some
Florent Xiclunaaa6c1d22011-12-12 18:54:29 +01004658 other built-in type as the default also
4659 inherit object.__new__. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004660 if (base != &PyBaseObject_Type ||
4661 (type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
4662 if (type->tp_new == NULL)
4663 type->tp_new = base->tp_new;
4664 }
4665 }
Benjamin Petersona7465e22010-07-05 15:01:22 +00004666 if (type->tp_basicsize == 0)
4667 type->tp_basicsize = base->tp_basicsize;
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00004668
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004669 /* Copy other non-function slots */
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00004670
4671#undef COPYVAL
4672#define COPYVAL(SLOT) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004673 if (type->SLOT == 0) type->SLOT = base->SLOT
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00004674
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004675 COPYVAL(tp_itemsize);
4676 COPYVAL(tp_weaklistoffset);
4677 COPYVAL(tp_dictoffset);
Thomas Wouters27d517b2007-02-25 20:39:11 +00004678
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004679 /* Setup fast subclass flags */
4680 if (PyType_IsSubtype(base, (PyTypeObject*)PyExc_BaseException))
4681 type->tp_flags |= Py_TPFLAGS_BASE_EXC_SUBCLASS;
4682 else if (PyType_IsSubtype(base, &PyType_Type))
4683 type->tp_flags |= Py_TPFLAGS_TYPE_SUBCLASS;
4684 else if (PyType_IsSubtype(base, &PyLong_Type))
4685 type->tp_flags |= Py_TPFLAGS_LONG_SUBCLASS;
4686 else if (PyType_IsSubtype(base, &PyBytes_Type))
4687 type->tp_flags |= Py_TPFLAGS_BYTES_SUBCLASS;
4688 else if (PyType_IsSubtype(base, &PyUnicode_Type))
4689 type->tp_flags |= Py_TPFLAGS_UNICODE_SUBCLASS;
4690 else if (PyType_IsSubtype(base, &PyTuple_Type))
4691 type->tp_flags |= Py_TPFLAGS_TUPLE_SUBCLASS;
4692 else if (PyType_IsSubtype(base, &PyList_Type))
4693 type->tp_flags |= Py_TPFLAGS_LIST_SUBCLASS;
4694 else if (PyType_IsSubtype(base, &PyDict_Type))
4695 type->tp_flags |= Py_TPFLAGS_DICT_SUBCLASS;
Guido van Rossum13d52f02001-08-10 21:24:08 +00004696}
4697
Guido van Rossum38938152006-08-21 23:36:26 +00004698static int
Guido van Rossumf5243f02008-01-01 04:06:48 +00004699overrides_hash(PyTypeObject *type)
Guido van Rossum38938152006-08-21 23:36:26 +00004700{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004701 PyObject *dict = type->tp_dict;
Victor Stinner3c1e4812012-03-26 22:10:51 +02004702 _Py_IDENTIFIER(__eq__);
Guido van Rossum38938152006-08-21 23:36:26 +00004703
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004704 assert(dict != NULL);
Victor Stinner3c1e4812012-03-26 22:10:51 +02004705 if (_PyDict_GetItemId(dict, &PyId___eq__) != NULL)
4706 return 1;
4707 if (_PyDict_GetItemId(dict, &PyId___hash__) != NULL)
4708 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004709 return 0;
Guido van Rossum38938152006-08-21 23:36:26 +00004710}
4711
Guido van Rossum13d52f02001-08-10 21:24:08 +00004712static void
4713inherit_slots(PyTypeObject *type, PyTypeObject *base)
4714{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004715 PyTypeObject *basebase;
Guido van Rossum13d52f02001-08-10 21:24:08 +00004716
4717#undef SLOTDEFINED
Tim Peters6d6c1a32001-08-02 04:15:00 +00004718#undef COPYSLOT
4719#undef COPYNUM
4720#undef COPYSEQ
4721#undef COPYMAP
Guido van Rossum5af588b2001-10-12 14:13:21 +00004722#undef COPYBUF
Guido van Rossum13d52f02001-08-10 21:24:08 +00004723
4724#define SLOTDEFINED(SLOT) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004725 (base->SLOT != 0 && \
4726 (basebase == NULL || base->SLOT != basebase->SLOT))
Guido van Rossum13d52f02001-08-10 21:24:08 +00004727
Tim Peters6d6c1a32001-08-02 04:15:00 +00004728#define COPYSLOT(SLOT) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004729 if (!type->SLOT && SLOTDEFINED(SLOT)) type->SLOT = base->SLOT
Tim Peters6d6c1a32001-08-02 04:15:00 +00004730
Yury Selivanov75445082015-05-11 22:57:16 -04004731#define COPYASYNC(SLOT) COPYSLOT(tp_as_async->SLOT)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004732#define COPYNUM(SLOT) COPYSLOT(tp_as_number->SLOT)
4733#define COPYSEQ(SLOT) COPYSLOT(tp_as_sequence->SLOT)
4734#define COPYMAP(SLOT) COPYSLOT(tp_as_mapping->SLOT)
Tim Petersfc57ccb2001-10-12 02:38:24 +00004735#define COPYBUF(SLOT) COPYSLOT(tp_as_buffer->SLOT)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004736
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004737 /* This won't inherit indirect slots (from tp_as_number etc.)
4738 if type doesn't provide the space. */
Guido van Rossum13d52f02001-08-10 21:24:08 +00004739
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004740 if (type->tp_as_number != NULL && base->tp_as_number != NULL) {
4741 basebase = base->tp_base;
4742 if (basebase->tp_as_number == NULL)
4743 basebase = NULL;
4744 COPYNUM(nb_add);
4745 COPYNUM(nb_subtract);
4746 COPYNUM(nb_multiply);
4747 COPYNUM(nb_remainder);
4748 COPYNUM(nb_divmod);
4749 COPYNUM(nb_power);
4750 COPYNUM(nb_negative);
4751 COPYNUM(nb_positive);
4752 COPYNUM(nb_absolute);
4753 COPYNUM(nb_bool);
4754 COPYNUM(nb_invert);
4755 COPYNUM(nb_lshift);
4756 COPYNUM(nb_rshift);
4757 COPYNUM(nb_and);
4758 COPYNUM(nb_xor);
4759 COPYNUM(nb_or);
4760 COPYNUM(nb_int);
4761 COPYNUM(nb_float);
4762 COPYNUM(nb_inplace_add);
4763 COPYNUM(nb_inplace_subtract);
4764 COPYNUM(nb_inplace_multiply);
4765 COPYNUM(nb_inplace_remainder);
4766 COPYNUM(nb_inplace_power);
4767 COPYNUM(nb_inplace_lshift);
4768 COPYNUM(nb_inplace_rshift);
4769 COPYNUM(nb_inplace_and);
4770 COPYNUM(nb_inplace_xor);
4771 COPYNUM(nb_inplace_or);
4772 COPYNUM(nb_true_divide);
4773 COPYNUM(nb_floor_divide);
4774 COPYNUM(nb_inplace_true_divide);
4775 COPYNUM(nb_inplace_floor_divide);
4776 COPYNUM(nb_index);
Benjamin Petersond51374e2014-04-09 23:55:56 -04004777 COPYNUM(nb_matrix_multiply);
4778 COPYNUM(nb_inplace_matrix_multiply);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004779 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004780
Yury Selivanov75445082015-05-11 22:57:16 -04004781 if (type->tp_as_async != NULL && base->tp_as_async != NULL) {
4782 basebase = base->tp_base;
4783 if (basebase->tp_as_async == NULL)
4784 basebase = NULL;
4785 COPYASYNC(am_await);
4786 COPYASYNC(am_aiter);
4787 COPYASYNC(am_anext);
4788 }
4789
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004790 if (type->tp_as_sequence != NULL && base->tp_as_sequence != NULL) {
4791 basebase = base->tp_base;
4792 if (basebase->tp_as_sequence == NULL)
4793 basebase = NULL;
4794 COPYSEQ(sq_length);
4795 COPYSEQ(sq_concat);
4796 COPYSEQ(sq_repeat);
4797 COPYSEQ(sq_item);
4798 COPYSEQ(sq_ass_item);
4799 COPYSEQ(sq_contains);
4800 COPYSEQ(sq_inplace_concat);
4801 COPYSEQ(sq_inplace_repeat);
4802 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004803
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004804 if (type->tp_as_mapping != NULL && base->tp_as_mapping != NULL) {
4805 basebase = base->tp_base;
4806 if (basebase->tp_as_mapping == NULL)
4807 basebase = NULL;
4808 COPYMAP(mp_length);
4809 COPYMAP(mp_subscript);
4810 COPYMAP(mp_ass_subscript);
4811 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004812
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004813 if (type->tp_as_buffer != NULL && base->tp_as_buffer != NULL) {
4814 basebase = base->tp_base;
4815 if (basebase->tp_as_buffer == NULL)
4816 basebase = NULL;
4817 COPYBUF(bf_getbuffer);
4818 COPYBUF(bf_releasebuffer);
4819 }
Tim Petersfc57ccb2001-10-12 02:38:24 +00004820
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004821 basebase = base->tp_base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004822
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004823 COPYSLOT(tp_dealloc);
4824 if (type->tp_getattr == NULL && type->tp_getattro == NULL) {
4825 type->tp_getattr = base->tp_getattr;
4826 type->tp_getattro = base->tp_getattro;
4827 }
4828 if (type->tp_setattr == NULL && type->tp_setattro == NULL) {
4829 type->tp_setattr = base->tp_setattr;
4830 type->tp_setattro = base->tp_setattro;
4831 }
4832 /* tp_reserved is ignored */
4833 COPYSLOT(tp_repr);
4834 /* tp_hash see tp_richcompare */
4835 COPYSLOT(tp_call);
4836 COPYSLOT(tp_str);
4837 {
4838 /* Copy comparison-related slots only when
4839 not overriding them anywhere */
4840 if (type->tp_richcompare == NULL &&
4841 type->tp_hash == NULL &&
4842 !overrides_hash(type))
4843 {
4844 type->tp_richcompare = base->tp_richcompare;
4845 type->tp_hash = base->tp_hash;
4846 }
4847 }
4848 {
4849 COPYSLOT(tp_iter);
4850 COPYSLOT(tp_iternext);
4851 }
4852 {
4853 COPYSLOT(tp_descr_get);
4854 COPYSLOT(tp_descr_set);
4855 COPYSLOT(tp_dictoffset);
4856 COPYSLOT(tp_init);
4857 COPYSLOT(tp_alloc);
4858 COPYSLOT(tp_is_gc);
Antoine Pitrou796564c2013-07-30 19:59:21 +02004859 if ((type->tp_flags & Py_TPFLAGS_HAVE_FINALIZE) &&
4860 (base->tp_flags & Py_TPFLAGS_HAVE_FINALIZE)) {
4861 COPYSLOT(tp_finalize);
4862 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004863 if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) ==
4864 (base->tp_flags & Py_TPFLAGS_HAVE_GC)) {
4865 /* They agree about gc. */
4866 COPYSLOT(tp_free);
4867 }
4868 else if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
4869 type->tp_free == NULL &&
4870 base->tp_free == PyObject_Free) {
4871 /* A bit of magic to plug in the correct default
4872 * tp_free function when a derived class adds gc,
4873 * didn't define tp_free, and the base uses the
4874 * default non-gc tp_free.
4875 */
4876 type->tp_free = PyObject_GC_Del;
4877 }
4878 /* else they didn't agree about gc, and there isn't something
4879 * obvious to be done -- the type is on its own.
4880 */
4881 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004882}
4883
Jeremy Hylton938ace62002-07-17 16:30:39 +00004884static int add_operators(PyTypeObject *);
Guido van Rossum13d52f02001-08-10 21:24:08 +00004885
Tim Peters6d6c1a32001-08-02 04:15:00 +00004886int
Guido van Rossum528b7eb2001-08-07 17:24:28 +00004887PyType_Ready(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004888{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004889 PyObject *dict, *bases;
4890 PyTypeObject *base;
4891 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004892
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004893 if (type->tp_flags & Py_TPFLAGS_READY) {
4894 assert(type->tp_dict != NULL);
4895 return 0;
4896 }
4897 assert((type->tp_flags & Py_TPFLAGS_READYING) == 0);
Guido van Rossumd614f972001-08-10 17:39:49 +00004898
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004899 type->tp_flags |= Py_TPFLAGS_READYING;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004900
Tim Peters36eb4df2003-03-23 03:33:13 +00004901#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004902 /* PyType_Ready is the closest thing we have to a choke point
4903 * for type objects, so is the best place I can think of to try
4904 * to get type objects into the doubly-linked list of all objects.
4905 * Still, not all type objects go thru PyType_Ready.
4906 */
4907 _Py_AddToAllObjects((PyObject *)type, 0);
Tim Peters36eb4df2003-03-23 03:33:13 +00004908#endif
4909
Serhiy Storchakade0574b2016-10-07 23:24:35 +03004910 if (type->tp_name == NULL) {
4911 PyErr_Format(PyExc_SystemError,
4912 "Type does not define the tp_name field.");
4913 goto error;
4914 }
4915
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004916 /* Initialize tp_base (defaults to BaseObject unless that's us) */
4917 base = type->tp_base;
4918 if (base == NULL && type != &PyBaseObject_Type) {
4919 base = type->tp_base = &PyBaseObject_Type;
4920 Py_INCREF(base);
4921 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004922
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004923 /* Now the only way base can still be NULL is if type is
4924 * &PyBaseObject_Type.
4925 */
Guido van Rossum692cdbc2006-03-10 02:04:28 +00004926
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004927 /* Initialize the base class */
4928 if (base != NULL && base->tp_dict == NULL) {
4929 if (PyType_Ready(base) < 0)
4930 goto error;
4931 }
Guido van Rossum323a9cf2002-08-14 17:26:30 +00004932
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004933 /* Initialize ob_type if NULL. This means extensions that want to be
4934 compilable separately on Windows can call PyType_Ready() instead of
4935 initializing the ob_type field of their type objects. */
4936 /* The test for base != NULL is really unnecessary, since base is only
4937 NULL when type is &PyBaseObject_Type, and we know its ob_type is
4938 not NULL (it's initialized to &PyType_Type). But coverity doesn't
4939 know that. */
4940 if (Py_TYPE(type) == NULL && base != NULL)
4941 Py_TYPE(type) = Py_TYPE(base);
Guido van Rossum0986d822002-04-08 01:38:42 +00004942
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004943 /* Initialize tp_bases */
4944 bases = type->tp_bases;
4945 if (bases == NULL) {
4946 if (base == NULL)
4947 bases = PyTuple_New(0);
4948 else
4949 bases = PyTuple_Pack(1, base);
4950 if (bases == NULL)
4951 goto error;
4952 type->tp_bases = bases;
4953 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004954
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004955 /* Initialize tp_dict */
4956 dict = type->tp_dict;
4957 if (dict == NULL) {
4958 dict = PyDict_New();
4959 if (dict == NULL)
4960 goto error;
4961 type->tp_dict = dict;
4962 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004963
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004964 /* Add type-specific descriptors to tp_dict */
4965 if (add_operators(type) < 0)
4966 goto error;
4967 if (type->tp_methods != NULL) {
4968 if (add_methods(type, type->tp_methods) < 0)
4969 goto error;
4970 }
4971 if (type->tp_members != NULL) {
4972 if (add_members(type, type->tp_members) < 0)
4973 goto error;
4974 }
4975 if (type->tp_getset != NULL) {
4976 if (add_getset(type, type->tp_getset) < 0)
4977 goto error;
4978 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004979
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004980 /* Calculate method resolution order */
Benjamin Peterson104b9e02015-02-05 22:29:14 -05004981 if (mro_internal(type, NULL) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004982 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004983
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004984 /* Inherit special flags from dominant base */
4985 if (type->tp_base != NULL)
4986 inherit_special(type, type->tp_base);
Guido van Rossum13d52f02001-08-10 21:24:08 +00004987
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004988 /* Initialize tp_dict properly */
4989 bases = type->tp_mro;
4990 assert(bases != NULL);
4991 assert(PyTuple_Check(bases));
4992 n = PyTuple_GET_SIZE(bases);
4993 for (i = 1; i < n; i++) {
4994 PyObject *b = PyTuple_GET_ITEM(bases, i);
4995 if (PyType_Check(b))
4996 inherit_slots(type, (PyTypeObject *)b);
4997 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004998
Serhiy Storchakae09bcc82015-01-28 11:03:33 +02004999 /* All bases of statically allocated type should be statically allocated */
5000 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE))
5001 for (i = 0; i < n; i++) {
5002 PyObject *b = PyTuple_GET_ITEM(bases, i);
5003 if (PyType_Check(b) &&
5004 (((PyTypeObject *)b)->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
5005 PyErr_Format(PyExc_TypeError,
5006 "type '%.100s' is not dynamically allocated but "
5007 "its base type '%.100s' is dynamically allocated",
5008 type->tp_name, ((PyTypeObject *)b)->tp_name);
5009 goto error;
5010 }
5011 }
5012
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005013 /* Sanity check for tp_free. */
5014 if (PyType_IS_GC(type) && (type->tp_flags & Py_TPFLAGS_BASETYPE) &&
5015 (type->tp_free == NULL || type->tp_free == PyObject_Del)) {
5016 /* This base class needs to call tp_free, but doesn't have
5017 * one, or its tp_free is for non-gc'ed objects.
5018 */
5019 PyErr_Format(PyExc_TypeError, "type '%.100s' participates in "
5020 "gc and is a base type but has inappropriate "
5021 "tp_free slot",
5022 type->tp_name);
5023 goto error;
5024 }
Tim Peters3cfe7542003-05-21 21:29:48 +00005025
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005026 /* if the type dictionary doesn't contain a __doc__, set it from
5027 the tp_doc slot.
5028 */
Victor Stinner3c1e4812012-03-26 22:10:51 +02005029 if (_PyDict_GetItemId(type->tp_dict, &PyId___doc__) == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005030 if (type->tp_doc != NULL) {
Larry Hastings2623c8c2014-02-08 22:15:29 -08005031 const char *old_doc = _PyType_DocWithoutSignature(type->tp_name,
5032 type->tp_doc);
Larry Hastings5c661892014-01-24 06:17:25 -08005033 PyObject *doc = PyUnicode_FromString(old_doc);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005034 if (doc == NULL)
5035 goto error;
Victor Stinner5967bf42013-07-17 22:01:37 +02005036 if (_PyDict_SetItemId(type->tp_dict, &PyId___doc__, doc) < 0) {
5037 Py_DECREF(doc);
5038 goto error;
5039 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005040 Py_DECREF(doc);
5041 } else {
Victor Stinner5967bf42013-07-17 22:01:37 +02005042 if (_PyDict_SetItemId(type->tp_dict,
5043 &PyId___doc__, Py_None) < 0)
5044 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005045 }
5046 }
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00005047
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005048 /* Hack for tp_hash and __hash__.
5049 If after all that, tp_hash is still NULL, and __hash__ is not in
5050 tp_dict, set tp_hash to PyObject_HashNotImplemented and
5051 tp_dict['__hash__'] equal to None.
5052 This signals that __hash__ is not inherited.
5053 */
5054 if (type->tp_hash == NULL) {
Victor Stinner3c1e4812012-03-26 22:10:51 +02005055 if (_PyDict_GetItemId(type->tp_dict, &PyId___hash__) == NULL) {
5056 if (_PyDict_SetItemId(type->tp_dict, &PyId___hash__, Py_None) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005057 goto error;
5058 type->tp_hash = PyObject_HashNotImplemented;
5059 }
5060 }
Guido van Rossum38938152006-08-21 23:36:26 +00005061
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005062 /* Some more special stuff */
5063 base = type->tp_base;
5064 if (base != NULL) {
Yury Selivanov75445082015-05-11 22:57:16 -04005065 if (type->tp_as_async == NULL)
5066 type->tp_as_async = base->tp_as_async;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005067 if (type->tp_as_number == NULL)
5068 type->tp_as_number = base->tp_as_number;
5069 if (type->tp_as_sequence == NULL)
5070 type->tp_as_sequence = base->tp_as_sequence;
5071 if (type->tp_as_mapping == NULL)
5072 type->tp_as_mapping = base->tp_as_mapping;
5073 if (type->tp_as_buffer == NULL)
5074 type->tp_as_buffer = base->tp_as_buffer;
5075 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00005076
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005077 /* Link into each base class's list of subclasses */
5078 bases = type->tp_bases;
5079 n = PyTuple_GET_SIZE(bases);
5080 for (i = 0; i < n; i++) {
5081 PyObject *b = PyTuple_GET_ITEM(bases, i);
5082 if (PyType_Check(b) &&
5083 add_subclass((PyTypeObject *)b, type) < 0)
5084 goto error;
5085 }
Guido van Rossum1c450732001-10-08 15:18:27 +00005086
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005087 /* All done -- set the ready flag */
5088 assert(type->tp_dict != NULL);
5089 type->tp_flags =
5090 (type->tp_flags & ~Py_TPFLAGS_READYING) | Py_TPFLAGS_READY;
5091 return 0;
Guido van Rossumd614f972001-08-10 17:39:49 +00005092
5093 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005094 type->tp_flags &= ~Py_TPFLAGS_READYING;
5095 return -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005096}
5097
Guido van Rossum1c450732001-10-08 15:18:27 +00005098static int
5099add_subclass(PyTypeObject *base, PyTypeObject *type)
5100{
Antoine Pitrou84745ab2013-10-29 21:31:25 +01005101 int result = -1;
5102 PyObject *dict, *key, *newobj;
Guido van Rossum1c450732001-10-08 15:18:27 +00005103
Antoine Pitrou84745ab2013-10-29 21:31:25 +01005104 dict = base->tp_subclasses;
5105 if (dict == NULL) {
5106 base->tp_subclasses = dict = PyDict_New();
5107 if (dict == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005108 return -1;
5109 }
Antoine Pitrou84745ab2013-10-29 21:31:25 +01005110 assert(PyDict_CheckExact(dict));
5111 key = PyLong_FromVoidPtr((void *) type);
5112 if (key == NULL)
Victor Stinner9812af82013-07-08 22:25:48 +02005113 return -1;
Antoine Pitrou84745ab2013-10-29 21:31:25 +01005114 newobj = PyWeakref_NewRef((PyObject *)type, NULL);
5115 if (newobj != NULL) {
5116 result = PyDict_SetItem(dict, key, newobj);
5117 Py_DECREF(newobj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005118 }
Antoine Pitrou84745ab2013-10-29 21:31:25 +01005119 Py_DECREF(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005120 return result;
Guido van Rossum1c450732001-10-08 15:18:27 +00005121}
5122
Benjamin Peterson104b9e02015-02-05 22:29:14 -05005123static int
5124add_all_subclasses(PyTypeObject *type, PyObject *bases)
5125{
5126 int res = 0;
5127
5128 if (bases) {
5129 Py_ssize_t i;
5130 for (i = 0; i < PyTuple_GET_SIZE(bases); i++) {
5131 PyObject *base = PyTuple_GET_ITEM(bases, i);
5132 if (PyType_Check(base) &&
5133 add_subclass((PyTypeObject*)base, type) < 0)
5134 res = -1;
5135 }
5136 }
5137
5138 return res;
5139}
5140
Michael W. Hudson98bbc492002-11-26 14:47:27 +00005141static void
5142remove_subclass(PyTypeObject *base, PyTypeObject *type)
5143{
Antoine Pitrou84745ab2013-10-29 21:31:25 +01005144 PyObject *dict, *key;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00005145
Antoine Pitrou84745ab2013-10-29 21:31:25 +01005146 dict = base->tp_subclasses;
5147 if (dict == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005148 return;
5149 }
Antoine Pitrou84745ab2013-10-29 21:31:25 +01005150 assert(PyDict_CheckExact(dict));
5151 key = PyLong_FromVoidPtr((void *) type);
5152 if (key == NULL || PyDict_DelItem(dict, key)) {
5153 /* This can happen if the type initialization errored out before
5154 the base subclasses were updated (e.g. a non-str __qualname__
5155 was passed in the type dict). */
5156 PyErr_Clear();
5157 }
5158 Py_XDECREF(key);
5159}
5160
5161static void
5162remove_all_subclasses(PyTypeObject *type, PyObject *bases)
5163{
5164 if (bases) {
5165 Py_ssize_t i;
5166 for (i = 0; i < PyTuple_GET_SIZE(bases); i++) {
5167 PyObject *base = PyTuple_GET_ITEM(bases, i);
5168 if (PyType_Check(base))
5169 remove_subclass((PyTypeObject*) base, type);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005170 }
5171 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +00005172}
Tim Peters6d6c1a32001-08-02 04:15:00 +00005173
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00005174static int
5175check_num_args(PyObject *ob, int n)
5176{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005177 if (!PyTuple_CheckExact(ob)) {
5178 PyErr_SetString(PyExc_SystemError,
5179 "PyArg_UnpackTuple() argument list is not a tuple");
5180 return 0;
5181 }
5182 if (n == PyTuple_GET_SIZE(ob))
5183 return 1;
5184 PyErr_Format(
5185 PyExc_TypeError,
5186 "expected %d arguments, got %zd", n, PyTuple_GET_SIZE(ob));
5187 return 0;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00005188}
5189
Tim Peters6d6c1a32001-08-02 04:15:00 +00005190/* Generic wrappers for overloadable 'operators' such as __getitem__ */
5191
5192/* There's a wrapper *function* for each distinct function typedef used
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005193 for type object slots (e.g. binaryfunc, ternaryfunc, etc.). There's a
Tim Peters6d6c1a32001-08-02 04:15:00 +00005194 wrapper *table* for each distinct operation (e.g. __len__, __add__).
5195 Most tables have only one entry; the tables for binary operators have two
5196 entries, one regular and one with reversed arguments. */
5197
5198static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00005199wrap_lenfunc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005200{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005201 lenfunc func = (lenfunc)wrapped;
5202 Py_ssize_t res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005203
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005204 if (!check_num_args(args, 0))
5205 return NULL;
5206 res = (*func)(self);
5207 if (res == -1 && PyErr_Occurred())
5208 return NULL;
5209 return PyLong_FromLong((long)res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005210}
5211
Tim Peters6d6c1a32001-08-02 04:15:00 +00005212static PyObject *
Raymond Hettingerf34f2642003-10-11 17:29:04 +00005213wrap_inquirypred(PyObject *self, PyObject *args, void *wrapped)
5214{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005215 inquiry func = (inquiry)wrapped;
5216 int res;
Raymond Hettingerf34f2642003-10-11 17:29:04 +00005217
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005218 if (!check_num_args(args, 0))
5219 return NULL;
5220 res = (*func)(self);
5221 if (res == -1 && PyErr_Occurred())
5222 return NULL;
5223 return PyBool_FromLong((long)res);
Raymond Hettingerf34f2642003-10-11 17:29:04 +00005224}
5225
5226static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00005227wrap_binaryfunc(PyObject *self, PyObject *args, void *wrapped)
5228{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005229 binaryfunc func = (binaryfunc)wrapped;
5230 PyObject *other;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005231
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005232 if (!check_num_args(args, 1))
5233 return NULL;
5234 other = PyTuple_GET_ITEM(args, 0);
5235 return (*func)(self, other);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005236}
5237
5238static PyObject *
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00005239wrap_binaryfunc_l(PyObject *self, PyObject *args, void *wrapped)
5240{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005241 binaryfunc func = (binaryfunc)wrapped;
5242 PyObject *other;
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00005243
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005244 if (!check_num_args(args, 1))
5245 return NULL;
5246 other = PyTuple_GET_ITEM(args, 0);
5247 return (*func)(self, other);
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00005248}
5249
5250static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00005251wrap_binaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
5252{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005253 binaryfunc func = (binaryfunc)wrapped;
5254 PyObject *other;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005255
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005256 if (!check_num_args(args, 1))
5257 return NULL;
5258 other = PyTuple_GET_ITEM(args, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005259 return (*func)(other, self);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005260}
5261
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00005262static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00005263wrap_ternaryfunc(PyObject *self, PyObject *args, void *wrapped)
5264{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005265 ternaryfunc func = (ternaryfunc)wrapped;
5266 PyObject *other;
5267 PyObject *third = Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005268
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005269 /* Note: This wrapper only works for __pow__() */
Tim Peters6d6c1a32001-08-02 04:15:00 +00005270
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005271 if (!PyArg_UnpackTuple(args, "", 1, 2, &other, &third))
5272 return NULL;
5273 return (*func)(self, other, third);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005274}
5275
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00005276static PyObject *
5277wrap_ternaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
5278{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005279 ternaryfunc func = (ternaryfunc)wrapped;
5280 PyObject *other;
5281 PyObject *third = Py_None;
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00005282
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005283 /* Note: This wrapper only works for __pow__() */
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00005284
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005285 if (!PyArg_UnpackTuple(args, "", 1, 2, &other, &third))
5286 return NULL;
5287 return (*func)(other, self, third);
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00005288}
5289
Tim Peters6d6c1a32001-08-02 04:15:00 +00005290static PyObject *
5291wrap_unaryfunc(PyObject *self, PyObject *args, void *wrapped)
5292{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005293 unaryfunc func = (unaryfunc)wrapped;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005294
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005295 if (!check_num_args(args, 0))
5296 return NULL;
5297 return (*func)(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005298}
5299
Tim Peters6d6c1a32001-08-02 04:15:00 +00005300static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00005301wrap_indexargfunc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005302{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005303 ssizeargfunc func = (ssizeargfunc)wrapped;
5304 PyObject* o;
5305 Py_ssize_t i;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005306
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005307 if (!PyArg_UnpackTuple(args, "", 1, 1, &o))
5308 return NULL;
5309 i = PyNumber_AsSsize_t(o, PyExc_OverflowError);
5310 if (i == -1 && PyErr_Occurred())
5311 return NULL;
5312 return (*func)(self, i);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005313}
5314
Martin v. Löwis18e16552006-02-15 17:27:45 +00005315static Py_ssize_t
Guido van Rossum5d815f32001-08-17 21:57:47 +00005316getindex(PyObject *self, PyObject *arg)
5317{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005318 Py_ssize_t i;
Guido van Rossum5d815f32001-08-17 21:57:47 +00005319
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005320 i = PyNumber_AsSsize_t(arg, PyExc_OverflowError);
5321 if (i == -1 && PyErr_Occurred())
5322 return -1;
5323 if (i < 0) {
5324 PySequenceMethods *sq = Py_TYPE(self)->tp_as_sequence;
5325 if (sq && sq->sq_length) {
5326 Py_ssize_t n = (*sq->sq_length)(self);
5327 if (n < 0)
5328 return -1;
5329 i += n;
5330 }
5331 }
5332 return i;
Guido van Rossum5d815f32001-08-17 21:57:47 +00005333}
5334
5335static PyObject *
5336wrap_sq_item(PyObject *self, PyObject *args, void *wrapped)
5337{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005338 ssizeargfunc func = (ssizeargfunc)wrapped;
5339 PyObject *arg;
5340 Py_ssize_t i;
Guido van Rossum5d815f32001-08-17 21:57:47 +00005341
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005342 if (PyTuple_GET_SIZE(args) == 1) {
5343 arg = PyTuple_GET_ITEM(args, 0);
5344 i = getindex(self, arg);
5345 if (i == -1 && PyErr_Occurred())
5346 return NULL;
5347 return (*func)(self, i);
5348 }
5349 check_num_args(args, 1);
5350 assert(PyErr_Occurred());
5351 return NULL;
Guido van Rossum5d815f32001-08-17 21:57:47 +00005352}
5353
Tim Peters6d6c1a32001-08-02 04:15:00 +00005354static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00005355wrap_sq_setitem(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005356{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005357 ssizeobjargproc func = (ssizeobjargproc)wrapped;
5358 Py_ssize_t i;
5359 int res;
5360 PyObject *arg, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005361
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005362 if (!PyArg_UnpackTuple(args, "", 2, 2, &arg, &value))
5363 return NULL;
5364 i = getindex(self, arg);
5365 if (i == -1 && PyErr_Occurred())
5366 return NULL;
5367 res = (*func)(self, i, value);
5368 if (res == -1 && PyErr_Occurred())
5369 return NULL;
5370 Py_INCREF(Py_None);
5371 return Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005372}
5373
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00005374static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00005375wrap_sq_delitem(PyObject *self, PyObject *args, void *wrapped)
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00005376{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005377 ssizeobjargproc func = (ssizeobjargproc)wrapped;
5378 Py_ssize_t i;
5379 int res;
5380 PyObject *arg;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00005381
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005382 if (!check_num_args(args, 1))
5383 return NULL;
5384 arg = PyTuple_GET_ITEM(args, 0);
5385 i = getindex(self, arg);
5386 if (i == -1 && PyErr_Occurred())
5387 return NULL;
5388 res = (*func)(self, i, NULL);
5389 if (res == -1 && PyErr_Occurred())
5390 return NULL;
5391 Py_INCREF(Py_None);
5392 return Py_None;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00005393}
5394
Tim Peters6d6c1a32001-08-02 04:15:00 +00005395/* XXX objobjproc is a misnomer; should be objargpred */
5396static PyObject *
5397wrap_objobjproc(PyObject *self, PyObject *args, void *wrapped)
5398{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005399 objobjproc func = (objobjproc)wrapped;
5400 int res;
5401 PyObject *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005402
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005403 if (!check_num_args(args, 1))
5404 return NULL;
5405 value = PyTuple_GET_ITEM(args, 0);
5406 res = (*func)(self, value);
5407 if (res == -1 && PyErr_Occurred())
5408 return NULL;
5409 else
5410 return PyBool_FromLong(res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005411}
5412
Tim Peters6d6c1a32001-08-02 04:15:00 +00005413static PyObject *
5414wrap_objobjargproc(PyObject *self, PyObject *args, void *wrapped)
5415{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005416 objobjargproc func = (objobjargproc)wrapped;
5417 int res;
5418 PyObject *key, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005419
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005420 if (!PyArg_UnpackTuple(args, "", 2, 2, &key, &value))
5421 return NULL;
5422 res = (*func)(self, key, value);
5423 if (res == -1 && PyErr_Occurred())
5424 return NULL;
5425 Py_INCREF(Py_None);
5426 return Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005427}
5428
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00005429static PyObject *
5430wrap_delitem(PyObject *self, PyObject *args, void *wrapped)
5431{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005432 objobjargproc func = (objobjargproc)wrapped;
5433 int res;
5434 PyObject *key;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00005435
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005436 if (!check_num_args(args, 1))
5437 return NULL;
5438 key = PyTuple_GET_ITEM(args, 0);
5439 res = (*func)(self, key, NULL);
5440 if (res == -1 && PyErr_Occurred())
5441 return NULL;
5442 Py_INCREF(Py_None);
5443 return Py_None;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00005444}
5445
Guido van Rossum4dcdb782003-04-14 21:46:03 +00005446/* Helper to check for object.__setattr__ or __delattr__ applied to a type.
Guido van Rossum52b27052003-04-15 20:05:10 +00005447 This is called the Carlo Verre hack after its discoverer. */
Guido van Rossum4dcdb782003-04-14 21:46:03 +00005448static int
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02005449hackcheck(PyObject *self, setattrofunc func, const char *what)
Guido van Rossum4dcdb782003-04-14 21:46:03 +00005450{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005451 PyTypeObject *type = Py_TYPE(self);
5452 while (type && type->tp_flags & Py_TPFLAGS_HEAPTYPE)
5453 type = type->tp_base;
5454 /* If type is NULL now, this is a really weird type.
5455 In the spirit of backwards compatibility (?), just shut up. */
5456 if (type && type->tp_setattro != func) {
5457 PyErr_Format(PyExc_TypeError,
5458 "can't apply this %s to %s object",
5459 what,
5460 type->tp_name);
5461 return 0;
5462 }
5463 return 1;
Guido van Rossum4dcdb782003-04-14 21:46:03 +00005464}
5465
Tim Peters6d6c1a32001-08-02 04:15:00 +00005466static PyObject *
5467wrap_setattr(PyObject *self, PyObject *args, void *wrapped)
5468{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005469 setattrofunc func = (setattrofunc)wrapped;
5470 int res;
5471 PyObject *name, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005472
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005473 if (!PyArg_UnpackTuple(args, "", 2, 2, &name, &value))
5474 return NULL;
5475 if (!hackcheck(self, func, "__setattr__"))
5476 return NULL;
5477 res = (*func)(self, name, value);
5478 if (res < 0)
5479 return NULL;
5480 Py_INCREF(Py_None);
5481 return Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005482}
5483
5484static PyObject *
5485wrap_delattr(PyObject *self, PyObject *args, void *wrapped)
5486{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005487 setattrofunc func = (setattrofunc)wrapped;
5488 int res;
5489 PyObject *name;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005490
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005491 if (!check_num_args(args, 1))
5492 return NULL;
5493 name = PyTuple_GET_ITEM(args, 0);
5494 if (!hackcheck(self, func, "__delattr__"))
5495 return NULL;
5496 res = (*func)(self, name, NULL);
5497 if (res < 0)
5498 return NULL;
5499 Py_INCREF(Py_None);
5500 return Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005501}
5502
Tim Peters6d6c1a32001-08-02 04:15:00 +00005503static PyObject *
5504wrap_hashfunc(PyObject *self, PyObject *args, void *wrapped)
5505{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005506 hashfunc func = (hashfunc)wrapped;
Benjamin Peterson8035bc52010-10-23 16:20:50 +00005507 Py_hash_t res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005508
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005509 if (!check_num_args(args, 0))
5510 return NULL;
5511 res = (*func)(self);
5512 if (res == -1 && PyErr_Occurred())
5513 return NULL;
Benjamin Peterson8035bc52010-10-23 16:20:50 +00005514 return PyLong_FromSsize_t(res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005515}
5516
Tim Peters6d6c1a32001-08-02 04:15:00 +00005517static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00005518wrap_call(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005519{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005520 ternaryfunc func = (ternaryfunc)wrapped;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005521
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005522 return (*func)(self, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005523}
5524
Tim Peters6d6c1a32001-08-02 04:15:00 +00005525static PyObject *
Antoine Pitrou796564c2013-07-30 19:59:21 +02005526wrap_del(PyObject *self, PyObject *args, void *wrapped)
5527{
5528 destructor func = (destructor)wrapped;
5529
5530 if (!check_num_args(args, 0))
5531 return NULL;
5532
5533 (*func)(self);
5534 Py_RETURN_NONE;
5535}
5536
5537static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00005538wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op)
5539{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005540 richcmpfunc func = (richcmpfunc)wrapped;
5541 PyObject *other;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005542
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005543 if (!check_num_args(args, 1))
5544 return NULL;
5545 other = PyTuple_GET_ITEM(args, 0);
5546 return (*func)(self, other, op);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005547}
5548
5549#undef RICHCMP_WRAPPER
5550#define RICHCMP_WRAPPER(NAME, OP) \
5551static PyObject * \
5552richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \
5553{ \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005554 return wrap_richcmpfunc(self, args, wrapped, OP); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00005555}
5556
Jack Jansen8e938b42001-08-08 15:29:49 +00005557RICHCMP_WRAPPER(lt, Py_LT)
5558RICHCMP_WRAPPER(le, Py_LE)
5559RICHCMP_WRAPPER(eq, Py_EQ)
5560RICHCMP_WRAPPER(ne, Py_NE)
5561RICHCMP_WRAPPER(gt, Py_GT)
5562RICHCMP_WRAPPER(ge, Py_GE)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005563
Tim Peters6d6c1a32001-08-02 04:15:00 +00005564static PyObject *
5565wrap_next(PyObject *self, PyObject *args, void *wrapped)
5566{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005567 unaryfunc func = (unaryfunc)wrapped;
5568 PyObject *res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005569
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005570 if (!check_num_args(args, 0))
5571 return NULL;
5572 res = (*func)(self);
5573 if (res == NULL && !PyErr_Occurred())
5574 PyErr_SetNone(PyExc_StopIteration);
5575 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005576}
5577
Tim Peters6d6c1a32001-08-02 04:15:00 +00005578static PyObject *
5579wrap_descr_get(PyObject *self, PyObject *args, void *wrapped)
5580{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005581 descrgetfunc func = (descrgetfunc)wrapped;
5582 PyObject *obj;
5583 PyObject *type = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005584
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005585 if (!PyArg_UnpackTuple(args, "", 1, 2, &obj, &type))
5586 return NULL;
5587 if (obj == Py_None)
5588 obj = NULL;
5589 if (type == Py_None)
5590 type = NULL;
5591 if (type == NULL &&obj == NULL) {
5592 PyErr_SetString(PyExc_TypeError,
5593 "__get__(None, None) is invalid");
5594 return NULL;
5595 }
5596 return (*func)(self, obj, type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005597}
5598
Tim Peters6d6c1a32001-08-02 04:15:00 +00005599static PyObject *
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005600wrap_descr_set(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005601{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005602 descrsetfunc func = (descrsetfunc)wrapped;
5603 PyObject *obj, *value;
5604 int ret;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005605
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005606 if (!PyArg_UnpackTuple(args, "", 2, 2, &obj, &value))
5607 return NULL;
5608 ret = (*func)(self, obj, value);
5609 if (ret < 0)
5610 return NULL;
5611 Py_INCREF(Py_None);
5612 return Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005613}
Guido van Rossum22b13872002-08-06 21:41:44 +00005614
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00005615static PyObject *
5616wrap_descr_delete(PyObject *self, PyObject *args, void *wrapped)
5617{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005618 descrsetfunc func = (descrsetfunc)wrapped;
5619 PyObject *obj;
5620 int ret;
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00005621
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005622 if (!check_num_args(args, 1))
5623 return NULL;
5624 obj = PyTuple_GET_ITEM(args, 0);
5625 ret = (*func)(self, obj, NULL);
5626 if (ret < 0)
5627 return NULL;
5628 Py_INCREF(Py_None);
5629 return Py_None;
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00005630}
Tim Peters6d6c1a32001-08-02 04:15:00 +00005631
Tim Peters6d6c1a32001-08-02 04:15:00 +00005632static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00005633wrap_init(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005634{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005635 initproc func = (initproc)wrapped;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005636
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005637 if (func(self, args, kwds) < 0)
5638 return NULL;
5639 Py_INCREF(Py_None);
5640 return Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005641}
5642
Tim Peters6d6c1a32001-08-02 04:15:00 +00005643static PyObject *
Guido van Rossum0d231ed2001-08-06 16:50:37 +00005644tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005645{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005646 PyTypeObject *type, *subtype, *staticbase;
5647 PyObject *arg0, *res;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00005648
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005649 if (self == NULL || !PyType_Check(self))
5650 Py_FatalError("__new__() called with non-type 'self'");
5651 type = (PyTypeObject *)self;
5652 if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) {
5653 PyErr_Format(PyExc_TypeError,
5654 "%s.__new__(): not enough arguments",
5655 type->tp_name);
5656 return NULL;
5657 }
5658 arg0 = PyTuple_GET_ITEM(args, 0);
5659 if (!PyType_Check(arg0)) {
5660 PyErr_Format(PyExc_TypeError,
5661 "%s.__new__(X): X is not a type object (%s)",
5662 type->tp_name,
5663 Py_TYPE(arg0)->tp_name);
5664 return NULL;
5665 }
5666 subtype = (PyTypeObject *)arg0;
5667 if (!PyType_IsSubtype(subtype, type)) {
5668 PyErr_Format(PyExc_TypeError,
5669 "%s.__new__(%s): %s is not a subtype of %s",
5670 type->tp_name,
5671 subtype->tp_name,
5672 subtype->tp_name,
5673 type->tp_name);
5674 return NULL;
5675 }
Barry Warsaw60f01882001-08-22 19:24:42 +00005676
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005677 /* Check that the use doesn't do something silly and unsafe like
5678 object.__new__(dict). To do this, we check that the
5679 most derived base that's not a heap type is this type. */
5680 staticbase = subtype;
Martin v. Löwis9c564092012-06-23 23:20:45 +02005681 while (staticbase && (staticbase->tp_new == slot_tp_new))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005682 staticbase = staticbase->tp_base;
5683 /* If staticbase is NULL now, it is a really weird type.
5684 In the spirit of backwards compatibility (?), just shut up. */
5685 if (staticbase && staticbase->tp_new != type->tp_new) {
5686 PyErr_Format(PyExc_TypeError,
5687 "%s.__new__(%s) is not safe, use %s.__new__()",
5688 type->tp_name,
5689 subtype->tp_name,
Benjamin Petersone8239332014-11-26 23:03:11 -06005690 staticbase->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005691 return NULL;
5692 }
Barry Warsaw60f01882001-08-22 19:24:42 +00005693
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005694 args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
5695 if (args == NULL)
5696 return NULL;
5697 res = type->tp_new(subtype, args, kwds);
5698 Py_DECREF(args);
5699 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005700}
5701
Guido van Rossum0d231ed2001-08-06 16:50:37 +00005702static struct PyMethodDef tp_new_methoddef[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005703 {"__new__", (PyCFunction)tp_new_wrapper, METH_VARARGS|METH_KEYWORDS,
Larry Hastings2623c8c2014-02-08 22:15:29 -08005704 PyDoc_STR("__new__($type, *args, **kwargs)\n--\n\n"
Larry Hastings581ee362014-01-28 05:00:08 -08005705 "Create and return a new object. "
5706 "See help(type) for accurate signature.")},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005707 {0}
Tim Peters6d6c1a32001-08-02 04:15:00 +00005708};
5709
5710static int
Guido van Rossum0d231ed2001-08-06 16:50:37 +00005711add_tp_new_wrapper(PyTypeObject *type)
5712{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005713 PyObject *func;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00005714
Victor Stinner3c1e4812012-03-26 22:10:51 +02005715 if (_PyDict_GetItemId(type->tp_dict, &PyId___new__) != NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005716 return 0;
Andrew Svetlov3ba3a3e2012-12-25 13:32:35 +02005717 func = PyCFunction_NewEx(tp_new_methoddef, (PyObject *)type, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005718 if (func == NULL)
5719 return -1;
Victor Stinner3c1e4812012-03-26 22:10:51 +02005720 if (_PyDict_SetItemId(type->tp_dict, &PyId___new__, func)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005721 Py_DECREF(func);
5722 return -1;
5723 }
5724 Py_DECREF(func);
5725 return 0;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00005726}
5727
Guido van Rossumf040ede2001-08-07 16:40:56 +00005728/* Slot wrappers that call the corresponding __foo__ slot. See comments
5729 below at override_slots() for more explanation. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00005730
Guido van Rossumdc91b992001-08-08 22:26:22 +00005731#define SLOT0(FUNCNAME, OPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00005732static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00005733FUNCNAME(PyObject *self) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00005734{ \
Benjamin Petersonce798522012-01-22 11:24:29 -05005735 _Py_static_string(id, OPSTR); \
Victor Stinnerad8c83a2016-09-05 17:53:15 -07005736 return call_method(self, &id, NULL); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00005737}
5738
Guido van Rossumdc91b992001-08-08 22:26:22 +00005739#define SLOT1(FUNCNAME, OPSTR, ARG1TYPE, ARGCODES) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00005740static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00005741FUNCNAME(PyObject *self, ARG1TYPE arg1) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00005742{ \
Benjamin Petersonce798522012-01-22 11:24:29 -05005743 _Py_static_string(id, OPSTR); \
5744 return call_method(self, &id, "(" ARGCODES ")", arg1); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00005745}
5746
Guido van Rossumcd118802003-01-06 22:57:47 +00005747/* Boolean helper for SLOT1BINFULL().
5748 right.__class__ is a nontrivial subclass of left.__class__. */
5749static int
Victor Stinner3c1e4812012-03-26 22:10:51 +02005750method_is_overloaded(PyObject *left, PyObject *right, struct _Py_Identifier *name)
Guido van Rossumcd118802003-01-06 22:57:47 +00005751{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005752 PyObject *a, *b;
5753 int ok;
Guido van Rossumcd118802003-01-06 22:57:47 +00005754
Victor Stinner3c1e4812012-03-26 22:10:51 +02005755 b = _PyObject_GetAttrId((PyObject *)(Py_TYPE(right)), name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005756 if (b == NULL) {
5757 PyErr_Clear();
5758 /* If right doesn't have it, it's not overloaded */
5759 return 0;
5760 }
Guido van Rossumcd118802003-01-06 22:57:47 +00005761
Victor Stinner3c1e4812012-03-26 22:10:51 +02005762 a = _PyObject_GetAttrId((PyObject *)(Py_TYPE(left)), name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005763 if (a == NULL) {
5764 PyErr_Clear();
5765 Py_DECREF(b);
5766 /* If right has it but left doesn't, it's overloaded */
5767 return 1;
5768 }
Guido van Rossumcd118802003-01-06 22:57:47 +00005769
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005770 ok = PyObject_RichCompareBool(a, b, Py_NE);
5771 Py_DECREF(a);
5772 Py_DECREF(b);
5773 if (ok < 0) {
5774 PyErr_Clear();
5775 return 0;
5776 }
Guido van Rossumcd118802003-01-06 22:57:47 +00005777
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005778 return ok;
Guido van Rossumcd118802003-01-06 22:57:47 +00005779}
5780
Guido van Rossumdc91b992001-08-08 22:26:22 +00005781
5782#define SLOT1BINFULL(FUNCNAME, TESTFUNC, SLOTNAME, OPSTR, ROPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00005783static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00005784FUNCNAME(PyObject *self, PyObject *other) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00005785{ \
Benjamin Petersonce798522012-01-22 11:24:29 -05005786 _Py_static_string(op_id, OPSTR); \
5787 _Py_static_string(rop_id, ROPSTR); \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005788 int do_other = Py_TYPE(self) != Py_TYPE(other) && \
5789 Py_TYPE(other)->tp_as_number != NULL && \
5790 Py_TYPE(other)->tp_as_number->SLOTNAME == TESTFUNC; \
5791 if (Py_TYPE(self)->tp_as_number != NULL && \
5792 Py_TYPE(self)->tp_as_number->SLOTNAME == TESTFUNC) { \
5793 PyObject *r; \
5794 if (do_other && \
5795 PyType_IsSubtype(Py_TYPE(other), Py_TYPE(self)) && \
Victor Stinner3c1e4812012-03-26 22:10:51 +02005796 method_is_overloaded(self, other, &rop_id)) { \
Benjamin Petersonce798522012-01-22 11:24:29 -05005797 r = call_maybe(other, &rop_id, "(O)", self); \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005798 if (r != Py_NotImplemented) \
5799 return r; \
5800 Py_DECREF(r); \
5801 do_other = 0; \
5802 } \
Benjamin Petersonce798522012-01-22 11:24:29 -05005803 r = call_maybe(self, &op_id, "(O)", other); \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005804 if (r != Py_NotImplemented || \
5805 Py_TYPE(other) == Py_TYPE(self)) \
5806 return r; \
5807 Py_DECREF(r); \
5808 } \
5809 if (do_other) { \
Benjamin Petersonce798522012-01-22 11:24:29 -05005810 return call_maybe(other, &rop_id, "(O)", self); \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005811 } \
Brian Curtindfc80e32011-08-10 20:28:54 -05005812 Py_RETURN_NOTIMPLEMENTED; \
Guido van Rossumdc91b992001-08-08 22:26:22 +00005813}
5814
5815#define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005816 SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR)
Guido van Rossumdc91b992001-08-08 22:26:22 +00005817
5818#define SLOT2(FUNCNAME, OPSTR, ARG1TYPE, ARG2TYPE, ARGCODES) \
5819static PyObject * \
5820FUNCNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \
5821{ \
Benjamin Petersonce798522012-01-22 11:24:29 -05005822 _Py_static_string(id, #OPSTR); \
5823 return call_method(self, &id, "(" ARGCODES ")", arg1, arg2); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00005824}
5825
Martin v. Löwis18e16552006-02-15 17:27:45 +00005826static Py_ssize_t
Tim Peters6d6c1a32001-08-02 04:15:00 +00005827slot_sq_length(PyObject *self)
5828{
Victor Stinnerad8c83a2016-09-05 17:53:15 -07005829 PyObject *res = call_method(self, &PyId___len__, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005830 Py_ssize_t len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005831
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005832 if (res == NULL)
5833 return -1;
5834 len = PyNumber_AsSsize_t(res, PyExc_OverflowError);
5835 Py_DECREF(res);
5836 if (len < 0) {
5837 if (!PyErr_Occurred())
5838 PyErr_SetString(PyExc_ValueError,
5839 "__len__() should return >= 0");
5840 return -1;
5841 }
5842 return len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005843}
5844
Guido van Rossumf4593e02001-10-03 12:09:30 +00005845/* Super-optimized version of slot_sq_item.
5846 Other slots could do the same... */
5847static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00005848slot_sq_item(PyObject *self, Py_ssize_t i)
Guido van Rossumf4593e02001-10-03 12:09:30 +00005849{
Victor Stinner5e877492016-08-19 18:19:42 +02005850 PyObject *func, *ival = NULL, *retval = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005851 descrgetfunc f;
Guido van Rossumf4593e02001-10-03 12:09:30 +00005852
Victor Stinner3c1e4812012-03-26 22:10:51 +02005853 func = _PyType_LookupId(Py_TYPE(self), &PyId___getitem__);
Victor Stinner018016d2016-08-19 18:17:37 +02005854 if (func == NULL) {
Victor Stinner3c1e4812012-03-26 22:10:51 +02005855 PyObject *getitem_str = _PyUnicode_FromId(&PyId___getitem__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005856 PyErr_SetObject(PyExc_AttributeError, getitem_str);
Victor Stinner018016d2016-08-19 18:17:37 +02005857 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005858 }
Victor Stinner018016d2016-08-19 18:17:37 +02005859
5860 f = Py_TYPE(func)->tp_descr_get;
5861 if (f == NULL) {
5862 Py_INCREF(func);
5863 }
5864 else {
5865 func = f(func, self, (PyObject *)(Py_TYPE(self)));
5866 if (func == NULL) {
5867 return NULL;
5868 }
5869 }
5870
5871 ival = PyLong_FromSsize_t(i);
5872 if (ival == NULL) {
5873 goto error;
5874 }
5875
Victor Stinner559bb6a2016-08-22 22:48:54 +02005876 retval = _PyObject_CallArg1(func, ival);
Victor Stinner018016d2016-08-19 18:17:37 +02005877 Py_DECREF(func);
Victor Stinner5e877492016-08-19 18:19:42 +02005878 Py_DECREF(ival);
Victor Stinner018016d2016-08-19 18:17:37 +02005879 return retval;
5880
5881error:
5882 Py_DECREF(func);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005883 return NULL;
Guido van Rossumf4593e02001-10-03 12:09:30 +00005884}
5885
Tim Peters6d6c1a32001-08-02 04:15:00 +00005886static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00005887slot_sq_ass_item(PyObject *self, Py_ssize_t index, PyObject *value)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005888{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005889 PyObject *res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005890
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005891 if (value == NULL)
Benjamin Petersonce798522012-01-22 11:24:29 -05005892 res = call_method(self, &PyId___delitem__, "(n)", index);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005893 else
Benjamin Petersonce798522012-01-22 11:24:29 -05005894 res = call_method(self, &PyId___setitem__, "(nO)", index, value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005895 if (res == NULL)
5896 return -1;
5897 Py_DECREF(res);
5898 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005899}
5900
5901static int
Tim Peters6d6c1a32001-08-02 04:15:00 +00005902slot_sq_contains(PyObject *self, PyObject *value)
5903{
Victor Stinnera7720f62016-08-19 17:48:51 +02005904 PyObject *func, *res;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005905 int result = -1;
Benjamin Petersonce798522012-01-22 11:24:29 -05005906 _Py_IDENTIFIER(__contains__);
Tim Petersbf9b2442003-03-23 05:35:36 +00005907
Benjamin Petersonce798522012-01-22 11:24:29 -05005908 func = lookup_maybe(self, &PyId___contains__);
Guido van Rossum97c1adf2016-08-18 09:22:23 -07005909 if (func == Py_None) {
5910 Py_DECREF(func);
5911 PyErr_Format(PyExc_TypeError,
5912 "'%.200s' object is not a container",
5913 Py_TYPE(self)->tp_name);
5914 return -1;
5915 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005916 if (func != NULL) {
Victor Stinner559bb6a2016-08-22 22:48:54 +02005917 res = _PyObject_CallArg1(func, value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005918 Py_DECREF(func);
5919 if (res != NULL) {
5920 result = PyObject_IsTrue(res);
5921 Py_DECREF(res);
5922 }
5923 }
5924 else if (! PyErr_Occurred()) {
5925 /* Possible results: -1 and 1 */
5926 result = (int)_PySequence_IterSearch(self, value,
5927 PY_ITERSEARCH_CONTAINS);
5928 }
5929 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005930}
5931
Tim Peters6d6c1a32001-08-02 04:15:00 +00005932#define slot_mp_length slot_sq_length
5933
Guido van Rossumdc91b992001-08-08 22:26:22 +00005934SLOT1(slot_mp_subscript, "__getitem__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00005935
5936static int
5937slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value)
5938{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005939 PyObject *res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005940
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005941 if (value == NULL)
Benjamin Petersonce798522012-01-22 11:24:29 -05005942 res = call_method(self, &PyId___delitem__, "(O)", key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005943 else
Benjamin Petersonce798522012-01-22 11:24:29 -05005944 res = call_method(self, &PyId___setitem__, "(OO)", key, value);
5945
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005946 if (res == NULL)
5947 return -1;
5948 Py_DECREF(res);
5949 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005950}
5951
Guido van Rossumdc91b992001-08-08 22:26:22 +00005952SLOT1BIN(slot_nb_add, nb_add, "__add__", "__radd__")
5953SLOT1BIN(slot_nb_subtract, nb_subtract, "__sub__", "__rsub__")
5954SLOT1BIN(slot_nb_multiply, nb_multiply, "__mul__", "__rmul__")
Benjamin Petersond51374e2014-04-09 23:55:56 -04005955SLOT1BIN(slot_nb_matrix_multiply, nb_matrix_multiply, "__matmul__", "__rmatmul__")
Guido van Rossumdc91b992001-08-08 22:26:22 +00005956SLOT1BIN(slot_nb_remainder, nb_remainder, "__mod__", "__rmod__")
5957SLOT1BIN(slot_nb_divmod, nb_divmod, "__divmod__", "__rdivmod__")
5958
Jeremy Hylton938ace62002-07-17 16:30:39 +00005959static PyObject *slot_nb_power(PyObject *, PyObject *, PyObject *);
Guido van Rossumdc91b992001-08-08 22:26:22 +00005960
5961SLOT1BINFULL(slot_nb_power_binary, slot_nb_power,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005962 nb_power, "__pow__", "__rpow__")
Guido van Rossumdc91b992001-08-08 22:26:22 +00005963
5964static PyObject *
5965slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus)
5966{
Benjamin Petersonce798522012-01-22 11:24:29 -05005967 _Py_IDENTIFIER(__pow__);
Guido van Rossum2730b132001-08-28 18:22:14 +00005968
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005969 if (modulus == Py_None)
5970 return slot_nb_power_binary(self, other);
5971 /* Three-arg power doesn't use __rpow__. But ternary_op
5972 can call this when the second argument's type uses
5973 slot_nb_power, so check before calling self.__pow__. */
5974 if (Py_TYPE(self)->tp_as_number != NULL &&
5975 Py_TYPE(self)->tp_as_number->nb_power == slot_nb_power) {
Benjamin Petersonce798522012-01-22 11:24:29 -05005976 return call_method(self, &PyId___pow__, "(OO)", other, modulus);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005977 }
Brian Curtindfc80e32011-08-10 20:28:54 -05005978 Py_RETURN_NOTIMPLEMENTED;
Guido van Rossumdc91b992001-08-08 22:26:22 +00005979}
5980
5981SLOT0(slot_nb_negative, "__neg__")
5982SLOT0(slot_nb_positive, "__pos__")
5983SLOT0(slot_nb_absolute, "__abs__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00005984
5985static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00005986slot_nb_bool(PyObject *self)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005987{
Victor Stinner20a30072016-08-19 18:28:25 +02005988 PyObject *func, *value;
Victor Stinnera12eec42016-08-19 18:26:05 +02005989 int result;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005990 int using_len = 0;
Benjamin Petersonce798522012-01-22 11:24:29 -05005991 _Py_IDENTIFIER(__bool__);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005992
Benjamin Petersonce798522012-01-22 11:24:29 -05005993 func = lookup_maybe(self, &PyId___bool__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005994 if (func == NULL) {
Victor Stinnera12eec42016-08-19 18:26:05 +02005995 if (PyErr_Occurred()) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005996 return -1;
Victor Stinnera12eec42016-08-19 18:26:05 +02005997 }
5998
Benjamin Petersonce798522012-01-22 11:24:29 -05005999 func = lookup_maybe(self, &PyId___len__);
Victor Stinnera12eec42016-08-19 18:26:05 +02006000 if (func == NULL) {
6001 if (PyErr_Occurred()) {
6002 return -1;
6003 }
6004 return 1;
6005 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006006 using_len = 1;
6007 }
Victor Stinnera12eec42016-08-19 18:26:05 +02006008
Victor Stinner559bb6a2016-08-22 22:48:54 +02006009 value = _PyObject_CallNoArg(func);
Victor Stinnera12eec42016-08-19 18:26:05 +02006010 if (value == NULL) {
6011 goto error;
6012 }
6013
6014 if (using_len) {
6015 /* bool type enforced by slot_nb_len */
6016 result = PyObject_IsTrue(value);
6017 }
6018 else if (PyBool_Check(value)) {
6019 result = PyObject_IsTrue(value);
6020 }
6021 else {
6022 PyErr_Format(PyExc_TypeError,
6023 "__bool__ should return "
6024 "bool, returned %s",
6025 Py_TYPE(value)->tp_name);
6026 result = -1;
6027 }
6028
6029 Py_DECREF(value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006030 Py_DECREF(func);
6031 return result;
Victor Stinnera12eec42016-08-19 18:26:05 +02006032
6033error:
6034 Py_DECREF(func);
6035 return -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00006036}
6037
Guido van Rossum38fff8c2006-03-07 18:50:55 +00006038
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00006039static PyObject *
Guido van Rossum38fff8c2006-03-07 18:50:55 +00006040slot_nb_index(PyObject *self)
6041{
Benjamin Petersonce798522012-01-22 11:24:29 -05006042 _Py_IDENTIFIER(__index__);
Victor Stinnerad8c83a2016-09-05 17:53:15 -07006043 return call_method(self, &PyId___index__, NULL);
Guido van Rossum38fff8c2006-03-07 18:50:55 +00006044}
6045
6046
Guido van Rossumdc91b992001-08-08 22:26:22 +00006047SLOT0(slot_nb_invert, "__invert__")
6048SLOT1BIN(slot_nb_lshift, nb_lshift, "__lshift__", "__rlshift__")
6049SLOT1BIN(slot_nb_rshift, nb_rshift, "__rshift__", "__rrshift__")
6050SLOT1BIN(slot_nb_and, nb_and, "__and__", "__rand__")
6051SLOT1BIN(slot_nb_xor, nb_xor, "__xor__", "__rxor__")
6052SLOT1BIN(slot_nb_or, nb_or, "__or__", "__ror__")
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00006053
Guido van Rossumdc91b992001-08-08 22:26:22 +00006054SLOT0(slot_nb_int, "__int__")
Guido van Rossumdc91b992001-08-08 22:26:22 +00006055SLOT0(slot_nb_float, "__float__")
Guido van Rossumdc91b992001-08-08 22:26:22 +00006056SLOT1(slot_nb_inplace_add, "__iadd__", PyObject *, "O")
6057SLOT1(slot_nb_inplace_subtract, "__isub__", PyObject *, "O")
6058SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *, "O")
Benjamin Petersond51374e2014-04-09 23:55:56 -04006059SLOT1(slot_nb_inplace_matrix_multiply, "__imatmul__", PyObject *, "O")
Guido van Rossumdc91b992001-08-08 22:26:22 +00006060SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *, "O")
Thomas Wouterscf297e42007-02-23 15:07:44 +00006061/* Can't use SLOT1 here, because nb_inplace_power is ternary */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006062static PyObject *
6063slot_nb_inplace_power(PyObject *self, PyObject * arg1, PyObject *arg2)
6064{
Benjamin Petersonce798522012-01-22 11:24:29 -05006065 _Py_IDENTIFIER(__ipow__);
6066 return call_method(self, &PyId___ipow__, "(" "O" ")", arg1);
Thomas Wouterscf297e42007-02-23 15:07:44 +00006067}
Guido van Rossumdc91b992001-08-08 22:26:22 +00006068SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *, "O")
6069SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *, "O")
6070SLOT1(slot_nb_inplace_and, "__iand__", PyObject *, "O")
6071SLOT1(slot_nb_inplace_xor, "__ixor__", PyObject *, "O")
6072SLOT1(slot_nb_inplace_or, "__ior__", PyObject *, "O")
6073SLOT1BIN(slot_nb_floor_divide, nb_floor_divide,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006074 "__floordiv__", "__rfloordiv__")
Guido van Rossumdc91b992001-08-08 22:26:22 +00006075SLOT1BIN(slot_nb_true_divide, nb_true_divide, "__truediv__", "__rtruediv__")
6076SLOT1(slot_nb_inplace_floor_divide, "__ifloordiv__", PyObject *, "O")
6077SLOT1(slot_nb_inplace_true_divide, "__itruediv__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00006078
Guido van Rossumb8f63662001-08-15 23:57:02 +00006079static PyObject *
6080slot_tp_repr(PyObject *self)
6081{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006082 PyObject *func, *res;
Benjamin Petersonce798522012-01-22 11:24:29 -05006083 _Py_IDENTIFIER(__repr__);
Guido van Rossumb8f63662001-08-15 23:57:02 +00006084
Benjamin Petersonce798522012-01-22 11:24:29 -05006085 func = lookup_method(self, &PyId___repr__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006086 if (func != NULL) {
6087 res = PyEval_CallObject(func, NULL);
6088 Py_DECREF(func);
6089 return res;
6090 }
6091 PyErr_Clear();
6092 return PyUnicode_FromFormat("<%s object at %p>",
6093 Py_TYPE(self)->tp_name, self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00006094}
6095
6096static PyObject *
6097slot_tp_str(PyObject *self)
6098{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006099 PyObject *func, *res;
Benjamin Petersonce798522012-01-22 11:24:29 -05006100 _Py_IDENTIFIER(__str__);
Guido van Rossumb8f63662001-08-15 23:57:02 +00006101
Benjamin Petersonce798522012-01-22 11:24:29 -05006102 func = lookup_method(self, &PyId___str__);
Victor Stinner2e8474d2013-07-11 22:46:11 +02006103 if (func == NULL)
6104 return NULL;
Victor Stinnerbebba502013-10-29 10:56:34 +01006105 res = PyEval_CallObject(func, NULL);
6106 Py_DECREF(func);
6107 return res;
6108}
Tim Peters6d6c1a32001-08-02 04:15:00 +00006109
Benjamin Peterson8f67d082010-10-17 20:54:53 +00006110static Py_hash_t
Tim Peters6d6c1a32001-08-02 04:15:00 +00006111slot_tp_hash(PyObject *self)
6112{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006113 PyObject *func, *res;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00006114 Py_ssize_t h;
Tim Peters6d6c1a32001-08-02 04:15:00 +00006115
Benjamin Petersonce798522012-01-22 11:24:29 -05006116 func = lookup_method(self, &PyId___hash__);
Guido van Rossumb8f63662001-08-15 23:57:02 +00006117
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006118 if (func == Py_None) {
6119 Py_DECREF(func);
6120 func = NULL;
6121 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +00006122
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006123 if (func == NULL) {
6124 return PyObject_HashNotImplemented(self);
6125 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +00006126
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006127 res = PyEval_CallObject(func, NULL);
6128 Py_DECREF(func);
6129 if (res == NULL)
6130 return -1;
Mark Dickinsondc787d22010-05-23 13:33:13 +00006131
6132 if (!PyLong_Check(res)) {
6133 PyErr_SetString(PyExc_TypeError,
6134 "__hash__ method should return an integer");
6135 return -1;
6136 }
Benjamin Peterson8f67d082010-10-17 20:54:53 +00006137 /* Transform the PyLong `res` to a Py_hash_t `h`. For an existing
6138 hashable Python object x, hash(x) will always lie within the range of
6139 Py_hash_t. Therefore our transformation must preserve values that
6140 already lie within this range, to ensure that if x.__hash__() returns
6141 hash(y) then hash(x) == hash(y). */
6142 h = PyLong_AsSsize_t(res);
6143 if (h == -1 && PyErr_Occurred()) {
6144 /* res was not within the range of a Py_hash_t, so we're free to
Mark Dickinsondc787d22010-05-23 13:33:13 +00006145 use any sufficiently bit-mixing transformation;
6146 long.__hash__ will do nicely. */
Benjamin Peterson8f67d082010-10-17 20:54:53 +00006147 PyErr_Clear();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006148 h = PyLong_Type.tp_hash(res);
Benjamin Peterson8f67d082010-10-17 20:54:53 +00006149 }
Benjamin Petersone7dfeeb2010-10-17 21:27:01 +00006150 /* -1 is reserved for errors. */
6151 if (h == -1)
6152 h = -2;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006153 Py_DECREF(res);
Mark Dickinsondc787d22010-05-23 13:33:13 +00006154 return h;
Tim Peters6d6c1a32001-08-02 04:15:00 +00006155}
6156
6157static PyObject *
6158slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds)
6159{
Benjamin Petersonce798522012-01-22 11:24:29 -05006160 _Py_IDENTIFIER(__call__);
6161 PyObject *meth = lookup_method(self, &PyId___call__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006162 PyObject *res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00006163
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006164 if (meth == NULL)
6165 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006166
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006167 res = PyObject_Call(meth, args, kwds);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006168
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006169 Py_DECREF(meth);
6170 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00006171}
6172
Guido van Rossum14a6f832001-10-17 13:59:09 +00006173/* There are two slot dispatch functions for tp_getattro.
6174
6175 - slot_tp_getattro() is used when __getattribute__ is overridden
6176 but no __getattr__ hook is present;
6177
6178 - slot_tp_getattr_hook() is used when a __getattr__ hook is present.
6179
Guido van Rossumc334df52002-04-04 23:44:47 +00006180 The code in update_one_slot() always installs slot_tp_getattr_hook(); this
6181 detects the absence of __getattr__ and then installs the simpler slot if
6182 necessary. */
Guido van Rossum14a6f832001-10-17 13:59:09 +00006183
Tim Peters6d6c1a32001-08-02 04:15:00 +00006184static PyObject *
6185slot_tp_getattro(PyObject *self, PyObject *name)
6186{
Benjamin Petersonce798522012-01-22 11:24:29 -05006187 return call_method(self, &PyId___getattribute__, "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00006188}
6189
Guido van Rossum19c1cd52001-09-21 21:24:49 +00006190static PyObject *
Benjamin Peterson9262b842008-11-17 22:45:50 +00006191call_attribute(PyObject *self, PyObject *attr, PyObject *name)
6192{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006193 PyObject *res, *descr = NULL;
6194 descrgetfunc f = Py_TYPE(attr)->tp_descr_get;
Benjamin Peterson9262b842008-11-17 22:45:50 +00006195
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006196 if (f != NULL) {
6197 descr = f(attr, self, (PyObject *)(Py_TYPE(self)));
6198 if (descr == NULL)
6199 return NULL;
6200 else
6201 attr = descr;
6202 }
6203 res = PyObject_CallFunctionObjArgs(attr, name, NULL);
6204 Py_XDECREF(descr);
6205 return res;
Benjamin Peterson9262b842008-11-17 22:45:50 +00006206}
6207
6208static PyObject *
Guido van Rossum19c1cd52001-09-21 21:24:49 +00006209slot_tp_getattr_hook(PyObject *self, PyObject *name)
6210{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006211 PyTypeObject *tp = Py_TYPE(self);
6212 PyObject *getattr, *getattribute, *res;
Victor Stinner3c1e4812012-03-26 22:10:51 +02006213 _Py_IDENTIFIER(__getattr__);
Guido van Rossum19c1cd52001-09-21 21:24:49 +00006214
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006215 /* speed hack: we could use lookup_maybe, but that would resolve the
6216 method fully for each attribute lookup for classes with
6217 __getattr__, even when the attribute is present. So we use
6218 _PyType_Lookup and create the method only when needed, with
6219 call_attribute. */
Victor Stinner3c1e4812012-03-26 22:10:51 +02006220 getattr = _PyType_LookupId(tp, &PyId___getattr__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006221 if (getattr == NULL) {
6222 /* No __getattr__ hook: use a simpler dispatcher */
6223 tp->tp_getattro = slot_tp_getattro;
6224 return slot_tp_getattro(self, name);
6225 }
6226 Py_INCREF(getattr);
6227 /* speed hack: we could use lookup_maybe, but that would resolve the
6228 method fully for each attribute lookup for classes with
6229 __getattr__, even when self has the default __getattribute__
6230 method. So we use _PyType_Lookup and create the method only when
6231 needed, with call_attribute. */
Victor Stinner3c1e4812012-03-26 22:10:51 +02006232 getattribute = _PyType_LookupId(tp, &PyId___getattribute__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006233 if (getattribute == NULL ||
6234 (Py_TYPE(getattribute) == &PyWrapperDescr_Type &&
6235 ((PyWrapperDescrObject *)getattribute)->d_wrapped ==
6236 (void *)PyObject_GenericGetAttr))
6237 res = PyObject_GenericGetAttr(self, name);
6238 else {
6239 Py_INCREF(getattribute);
6240 res = call_attribute(self, getattribute, name);
6241 Py_DECREF(getattribute);
6242 }
6243 if (res == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) {
6244 PyErr_Clear();
6245 res = call_attribute(self, getattr, name);
6246 }
6247 Py_DECREF(getattr);
6248 return res;
Guido van Rossum19c1cd52001-09-21 21:24:49 +00006249}
6250
Tim Peters6d6c1a32001-08-02 04:15:00 +00006251static int
6252slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value)
6253{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006254 PyObject *res;
Benjamin Petersonce798522012-01-22 11:24:29 -05006255 _Py_IDENTIFIER(__delattr__);
6256 _Py_IDENTIFIER(__setattr__);
Tim Peters6d6c1a32001-08-02 04:15:00 +00006257
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006258 if (value == NULL)
Benjamin Petersonce798522012-01-22 11:24:29 -05006259 res = call_method(self, &PyId___delattr__, "(O)", name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006260 else
Benjamin Petersonce798522012-01-22 11:24:29 -05006261 res = call_method(self, &PyId___setattr__, "(OO)", name, value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006262 if (res == NULL)
6263 return -1;
6264 Py_DECREF(res);
6265 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00006266}
6267
Benjamin Petersonce798522012-01-22 11:24:29 -05006268static _Py_Identifier name_op[] = {
6269 {0, "__lt__", 0},
6270 {0, "__le__", 0},
6271 {0, "__eq__", 0},
6272 {0, "__ne__", 0},
6273 {0, "__gt__", 0},
6274 {0, "__ge__", 0}
Guido van Rossumf5243f02008-01-01 04:06:48 +00006275};
6276
Tim Peters6d6c1a32001-08-02 04:15:00 +00006277static PyObject *
Mark Dickinson6f1d0492009-11-15 13:58:49 +00006278slot_tp_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters6d6c1a32001-08-02 04:15:00 +00006279{
Victor Stinnera7720f62016-08-19 17:48:51 +02006280 PyObject *func, *res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00006281
Benjamin Petersonce798522012-01-22 11:24:29 -05006282 func = lookup_method(self, &name_op[op]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006283 if (func == NULL) {
6284 PyErr_Clear();
Brian Curtindfc80e32011-08-10 20:28:54 -05006285 Py_RETURN_NOTIMPLEMENTED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006286 }
Victor Stinner559bb6a2016-08-22 22:48:54 +02006287 res = _PyObject_CallArg1(func, other);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006288 Py_DECREF(func);
6289 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00006290}
6291
Guido van Rossumb8f63662001-08-15 23:57:02 +00006292static PyObject *
Guido van Rossumb8f63662001-08-15 23:57:02 +00006293slot_tp_iter(PyObject *self)
6294{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006295 PyObject *func, *res;
Benjamin Petersonce798522012-01-22 11:24:29 -05006296 _Py_IDENTIFIER(__iter__);
Guido van Rossumb8f63662001-08-15 23:57:02 +00006297
Benjamin Petersonce798522012-01-22 11:24:29 -05006298 func = lookup_method(self, &PyId___iter__);
Guido van Rossum97c1adf2016-08-18 09:22:23 -07006299 if (func == Py_None) {
6300 Py_DECREF(func);
6301 PyErr_Format(PyExc_TypeError,
6302 "'%.200s' object is not iterable",
6303 Py_TYPE(self)->tp_name);
6304 return NULL;
6305 }
Victor Stinner69112672016-08-19 18:41:02 +02006306
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006307 if (func != NULL) {
Victor Stinner559bb6a2016-08-22 22:48:54 +02006308 res = _PyObject_CallNoArg(func);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006309 Py_DECREF(func);
6310 return res;
6311 }
Victor Stinner69112672016-08-19 18:41:02 +02006312
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006313 PyErr_Clear();
Benjamin Petersonce798522012-01-22 11:24:29 -05006314 func = lookup_method(self, &PyId___getitem__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006315 if (func == NULL) {
6316 PyErr_Format(PyExc_TypeError,
6317 "'%.200s' object is not iterable",
6318 Py_TYPE(self)->tp_name);
6319 return NULL;
6320 }
6321 Py_DECREF(func);
6322 return PySeqIter_New(self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00006323}
Tim Peters6d6c1a32001-08-02 04:15:00 +00006324
6325static PyObject *
6326slot_tp_iternext(PyObject *self)
6327{
Benjamin Petersonce798522012-01-22 11:24:29 -05006328 _Py_IDENTIFIER(__next__);
Victor Stinnerad8c83a2016-09-05 17:53:15 -07006329 return call_method(self, &PyId___next__, NULL);
Tim Peters6d6c1a32001-08-02 04:15:00 +00006330}
6331
Guido van Rossum1a493502001-08-17 16:47:50 +00006332static PyObject *
6333slot_tp_descr_get(PyObject *self, PyObject *obj, PyObject *type)
6334{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006335 PyTypeObject *tp = Py_TYPE(self);
6336 PyObject *get;
Victor Stinner3c1e4812012-03-26 22:10:51 +02006337 _Py_IDENTIFIER(__get__);
Guido van Rossum1a493502001-08-17 16:47:50 +00006338
Victor Stinner3c1e4812012-03-26 22:10:51 +02006339 get = _PyType_LookupId(tp, &PyId___get__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006340 if (get == NULL) {
6341 /* Avoid further slowdowns */
6342 if (tp->tp_descr_get == slot_tp_descr_get)
6343 tp->tp_descr_get = NULL;
6344 Py_INCREF(self);
6345 return self;
6346 }
6347 if (obj == NULL)
6348 obj = Py_None;
6349 if (type == NULL)
6350 type = Py_None;
6351 return PyObject_CallFunctionObjArgs(get, self, obj, type, NULL);
Guido van Rossum1a493502001-08-17 16:47:50 +00006352}
Tim Peters6d6c1a32001-08-02 04:15:00 +00006353
6354static int
6355slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value)
6356{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006357 PyObject *res;
Benjamin Petersonce798522012-01-22 11:24:29 -05006358 _Py_IDENTIFIER(__delete__);
6359 _Py_IDENTIFIER(__set__);
Guido van Rossum2c252392001-08-24 10:13:31 +00006360
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006361 if (value == NULL)
Benjamin Petersonce798522012-01-22 11:24:29 -05006362 res = call_method(self, &PyId___delete__, "(O)", target);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006363 else
Benjamin Petersonce798522012-01-22 11:24:29 -05006364 res = call_method(self, &PyId___set__, "(OO)", target, value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006365 if (res == NULL)
6366 return -1;
6367 Py_DECREF(res);
6368 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00006369}
6370
6371static int
6372slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds)
6373{
Benjamin Petersonce798522012-01-22 11:24:29 -05006374 _Py_IDENTIFIER(__init__);
6375 PyObject *meth = lookup_method(self, &PyId___init__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006376 PyObject *res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00006377
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006378 if (meth == NULL)
6379 return -1;
6380 res = PyObject_Call(meth, args, kwds);
6381 Py_DECREF(meth);
6382 if (res == NULL)
6383 return -1;
6384 if (res != Py_None) {
6385 PyErr_Format(PyExc_TypeError,
6386 "__init__() should return None, not '%.200s'",
6387 Py_TYPE(res)->tp_name);
6388 Py_DECREF(res);
6389 return -1;
6390 }
6391 Py_DECREF(res);
6392 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00006393}
6394
6395static PyObject *
6396slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
6397{
Victor Stinner3f1057a2016-08-25 01:04:14 +02006398 PyObject *func, *result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00006399
Victor Stinner3c1e4812012-03-26 22:10:51 +02006400 func = _PyObject_GetAttrId((PyObject *)type, &PyId___new__);
Victor Stinner3f1057a2016-08-25 01:04:14 +02006401 if (func == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006402 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006403 }
Victor Stinner3f1057a2016-08-25 01:04:14 +02006404
6405 result = _PyObject_Call_Prepend(func, (PyObject *)type, args, kwds);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006406 Py_DECREF(func);
Victor Stinner3f1057a2016-08-25 01:04:14 +02006407 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00006408}
6409
Guido van Rossumfebd61d2002-08-08 20:55:20 +00006410static void
Antoine Pitrou796564c2013-07-30 19:59:21 +02006411slot_tp_finalize(PyObject *self)
Guido van Rossumfebd61d2002-08-08 20:55:20 +00006412{
Benjamin Petersonce798522012-01-22 11:24:29 -05006413 _Py_IDENTIFIER(__del__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006414 PyObject *del, *res;
6415 PyObject *error_type, *error_value, *error_traceback;
Guido van Rossumfebd61d2002-08-08 20:55:20 +00006416
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006417 /* Save the current exception, if any. */
6418 PyErr_Fetch(&error_type, &error_value, &error_traceback);
Guido van Rossumfebd61d2002-08-08 20:55:20 +00006419
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006420 /* Execute __del__ method, if any. */
Benjamin Petersonce798522012-01-22 11:24:29 -05006421 del = lookup_maybe(self, &PyId___del__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006422 if (del != NULL) {
6423 res = PyEval_CallObject(del, NULL);
6424 if (res == NULL)
6425 PyErr_WriteUnraisable(del);
6426 else
6427 Py_DECREF(res);
6428 Py_DECREF(del);
6429 }
Guido van Rossumfebd61d2002-08-08 20:55:20 +00006430
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006431 /* Restore the saved exception. */
6432 PyErr_Restore(error_type, error_value, error_traceback);
Guido van Rossumfebd61d2002-08-08 20:55:20 +00006433}
6434
Yury Selivanov75445082015-05-11 22:57:16 -04006435static PyObject *
6436slot_am_await(PyObject *self)
6437{
6438 PyObject *func, *res;
6439 _Py_IDENTIFIER(__await__);
6440
6441 func = lookup_method(self, &PyId___await__);
6442 if (func != NULL) {
6443 res = PyEval_CallObject(func, NULL);
6444 Py_DECREF(func);
6445 return res;
6446 }
6447 PyErr_Format(PyExc_AttributeError,
6448 "object %.50s does not have __await__ method",
6449 Py_TYPE(self)->tp_name);
6450 return NULL;
6451}
6452
6453static PyObject *
6454slot_am_aiter(PyObject *self)
6455{
6456 PyObject *func, *res;
6457 _Py_IDENTIFIER(__aiter__);
6458
6459 func = lookup_method(self, &PyId___aiter__);
6460 if (func != NULL) {
6461 res = PyEval_CallObject(func, NULL);
6462 Py_DECREF(func);
6463 return res;
6464 }
6465 PyErr_Format(PyExc_AttributeError,
6466 "object %.50s does not have __aiter__ method",
6467 Py_TYPE(self)->tp_name);
6468 return NULL;
6469}
6470
6471static PyObject *
6472slot_am_anext(PyObject *self)
6473{
6474 PyObject *func, *res;
6475 _Py_IDENTIFIER(__anext__);
6476
6477 func = lookup_method(self, &PyId___anext__);
6478 if (func != NULL) {
6479 res = PyEval_CallObject(func, NULL);
6480 Py_DECREF(func);
6481 return res;
6482 }
6483 PyErr_Format(PyExc_AttributeError,
6484 "object %.50s does not have __anext__ method",
6485 Py_TYPE(self)->tp_name);
6486 return NULL;
6487}
Guido van Rossum7b9144b2001-10-09 19:39:46 +00006488
Benjamin Peterson63952412013-04-01 17:41:41 -04006489/*
6490Table mapping __foo__ names to tp_foo offsets and slot_tp_foo wrapper functions.
6491
6492The table is ordered by offsets relative to the 'PyHeapTypeObject' structure,
6493which incorporates the additional structures used for numbers, sequences and
6494mappings. Note that multiple names may map to the same slot (e.g. __eq__,
6495__ne__ etc. all map to tp_richcompare) and one name may map to multiple slots
6496(e.g. __str__ affects tp_str as well as tp_repr). The table is terminated with
6497an all-zero entry. (This table is further initialized in init_slotdefs().)
6498*/
Guido van Rossum7b9144b2001-10-09 19:39:46 +00006499
Guido van Rossum6d204072001-10-21 00:44:31 +00006500typedef struct wrapperbase slotdef;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00006501
6502#undef TPSLOT
Guido van Rossumc8e56452001-10-22 00:43:43 +00006503#undef FLSLOT
Yury Selivanov75445082015-05-11 22:57:16 -04006504#undef AMSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00006505#undef ETSLOT
6506#undef SQSLOT
6507#undef MPSLOT
6508#undef NBSLOT
Guido van Rossum6d204072001-10-21 00:44:31 +00006509#undef UNSLOT
6510#undef IBSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00006511#undef BINSLOT
6512#undef RBINSLOT
6513
Guido van Rossum6d204072001-10-21 00:44:31 +00006514#define TPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006515 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
6516 PyDoc_STR(DOC)}
Guido van Rossumc8e56452001-10-22 00:43:43 +00006517#define FLSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC, FLAGS) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006518 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
6519 PyDoc_STR(DOC), FLAGS}
Guido van Rossum6d204072001-10-21 00:44:31 +00006520#define ETSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006521 {NAME, offsetof(PyHeapTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
6522 PyDoc_STR(DOC)}
Yury Selivanov75445082015-05-11 22:57:16 -04006523#define AMSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
6524 ETSLOT(NAME, as_async.SLOT, FUNCTION, WRAPPER, DOC)
Guido van Rossum6d204072001-10-21 00:44:31 +00006525#define SQSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006526 ETSLOT(NAME, as_sequence.SLOT, FUNCTION, WRAPPER, DOC)
Guido van Rossum6d204072001-10-21 00:44:31 +00006527#define MPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006528 ETSLOT(NAME, as_mapping.SLOT, FUNCTION, WRAPPER, DOC)
Guido van Rossum6d204072001-10-21 00:44:31 +00006529#define NBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006530 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, DOC)
Guido van Rossum6d204072001-10-21 00:44:31 +00006531#define UNSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006532 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
Larry Hastings69a25472014-02-09 22:22:38 -08006533 NAME "($self, /)\n--\n\n" DOC)
Guido van Rossum6d204072001-10-21 00:44:31 +00006534#define IBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006535 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
Larry Hastings69a25472014-02-09 22:22:38 -08006536 NAME "($self, value, /)\n--\n\nReturn self" DOC "value.")
Guido van Rossum6d204072001-10-21 00:44:31 +00006537#define BINSLOT(NAME, SLOT, FUNCTION, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006538 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
Larry Hastings69a25472014-02-09 22:22:38 -08006539 NAME "($self, value, /)\n--\n\nReturn self" DOC "value.")
Guido van Rossum6d204072001-10-21 00:44:31 +00006540#define RBINSLOT(NAME, SLOT, FUNCTION, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006541 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
Larry Hastings69a25472014-02-09 22:22:38 -08006542 NAME "($self, value, /)\n--\n\nReturn value" DOC "self.")
Anthony Baxter56616992005-06-03 14:12:21 +00006543#define BINSLOTNOTINFIX(NAME, SLOT, FUNCTION, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006544 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
Larry Hastings69a25472014-02-09 22:22:38 -08006545 NAME "($self, value, /)\n--\n\n" DOC)
Anthony Baxter56616992005-06-03 14:12:21 +00006546#define RBINSLOTNOTINFIX(NAME, SLOT, FUNCTION, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006547 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
Larry Hastings69a25472014-02-09 22:22:38 -08006548 NAME "($self, value, /)\n--\n\n" DOC)
Guido van Rossum7b9144b2001-10-09 19:39:46 +00006549
6550static slotdef slotdefs[] = {
Benjamin Peterson63952412013-04-01 17:41:41 -04006551 TPSLOT("__getattribute__", tp_getattr, NULL, NULL, ""),
6552 TPSLOT("__getattr__", tp_getattr, NULL, NULL, ""),
6553 TPSLOT("__setattr__", tp_setattr, NULL, NULL, ""),
6554 TPSLOT("__delattr__", tp_setattr, NULL, NULL, ""),
6555 TPSLOT("__repr__", tp_repr, slot_tp_repr, wrap_unaryfunc,
Larry Hastings69a25472014-02-09 22:22:38 -08006556 "__repr__($self, /)\n--\n\nReturn repr(self)."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006557 TPSLOT("__hash__", tp_hash, slot_tp_hash, wrap_hashfunc,
Larry Hastings69a25472014-02-09 22:22:38 -08006558 "__hash__($self, /)\n--\n\nReturn hash(self)."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006559 FLSLOT("__call__", tp_call, slot_tp_call, (wrapperfunc)wrap_call,
Larry Hastings69a25472014-02-09 22:22:38 -08006560 "__call__($self, /, *args, **kwargs)\n--\n\nCall self as a function.",
Larry Hastings5c661892014-01-24 06:17:25 -08006561 PyWrapperFlag_KEYWORDS),
Benjamin Peterson63952412013-04-01 17:41:41 -04006562 TPSLOT("__str__", tp_str, slot_tp_str, wrap_unaryfunc,
Larry Hastings69a25472014-02-09 22:22:38 -08006563 "__str__($self, /)\n--\n\nReturn str(self)."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006564 TPSLOT("__getattribute__", tp_getattro, slot_tp_getattr_hook,
Larry Hastings5c661892014-01-24 06:17:25 -08006565 wrap_binaryfunc,
Larry Hastings69a25472014-02-09 22:22:38 -08006566 "__getattribute__($self, name, /)\n--\n\nReturn getattr(self, name)."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006567 TPSLOT("__getattr__", tp_getattro, slot_tp_getattr_hook, NULL, ""),
6568 TPSLOT("__setattr__", tp_setattro, slot_tp_setattro, wrap_setattr,
Larry Hastings69a25472014-02-09 22:22:38 -08006569 "__setattr__($self, name, value, /)\n--\n\nImplement setattr(self, name, value)."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006570 TPSLOT("__delattr__", tp_setattro, slot_tp_setattro, wrap_delattr,
Larry Hastings69a25472014-02-09 22:22:38 -08006571 "__delattr__($self, name, /)\n--\n\nImplement delattr(self, name)."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006572 TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare, richcmp_lt,
Larry Hastings69a25472014-02-09 22:22:38 -08006573 "__lt__($self, value, /)\n--\n\nReturn self<value."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006574 TPSLOT("__le__", tp_richcompare, slot_tp_richcompare, richcmp_le,
Larry Hastings69a25472014-02-09 22:22:38 -08006575 "__le__($self, value, /)\n--\n\nReturn self<=value."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006576 TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare, richcmp_eq,
Larry Hastings69a25472014-02-09 22:22:38 -08006577 "__eq__($self, value, /)\n--\n\nReturn self==value."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006578 TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare, richcmp_ne,
Larry Hastings69a25472014-02-09 22:22:38 -08006579 "__ne__($self, value, /)\n--\n\nReturn self!=value."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006580 TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare, richcmp_gt,
Larry Hastings69a25472014-02-09 22:22:38 -08006581 "__gt__($self, value, /)\n--\n\nReturn self>value."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006582 TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare, richcmp_ge,
Zachary Wareea42b4c2014-04-18 09:14:31 -05006583 "__ge__($self, value, /)\n--\n\nReturn self>=value."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006584 TPSLOT("__iter__", tp_iter, slot_tp_iter, wrap_unaryfunc,
Larry Hastings69a25472014-02-09 22:22:38 -08006585 "__iter__($self, /)\n--\n\nImplement iter(self)."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006586 TPSLOT("__next__", tp_iternext, slot_tp_iternext, wrap_next,
Larry Hastings69a25472014-02-09 22:22:38 -08006587 "__next__($self, /)\n--\n\nImplement next(self)."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006588 TPSLOT("__get__", tp_descr_get, slot_tp_descr_get, wrap_descr_get,
Larry Hastings69a25472014-02-09 22:22:38 -08006589 "__get__($self, instance, owner, /)\n--\n\nReturn an attribute of instance, which is of type owner."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006590 TPSLOT("__set__", tp_descr_set, slot_tp_descr_set, wrap_descr_set,
Larry Hastings69a25472014-02-09 22:22:38 -08006591 "__set__($self, instance, value, /)\n--\n\nSet an attribute of instance to value."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006592 TPSLOT("__delete__", tp_descr_set, slot_tp_descr_set,
Larry Hastings5c661892014-01-24 06:17:25 -08006593 wrap_descr_delete,
Yury Selivanov056e2652014-03-02 12:25:27 -05006594 "__delete__($self, instance, /)\n--\n\nDelete an attribute of instance."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006595 FLSLOT("__init__", tp_init, slot_tp_init, (wrapperfunc)wrap_init,
Larry Hastings69a25472014-02-09 22:22:38 -08006596 "__init__($self, /, *args, **kwargs)\n--\n\n"
Larry Hastings581ee362014-01-28 05:00:08 -08006597 "Initialize self. See help(type(self)) for accurate signature.",
Benjamin Peterson63952412013-04-01 17:41:41 -04006598 PyWrapperFlag_KEYWORDS),
Larry Hastings5c661892014-01-24 06:17:25 -08006599 TPSLOT("__new__", tp_new, slot_tp_new, NULL,
Larry Hastings69a25472014-02-09 22:22:38 -08006600 "__new__(type, /, *args, **kwargs)\n--\n\n"
Larry Hastings581ee362014-01-28 05:00:08 -08006601 "Create and return new object. See help(type) for accurate signature."),
Antoine Pitrou796564c2013-07-30 19:59:21 +02006602 TPSLOT("__del__", tp_finalize, slot_tp_finalize, (wrapperfunc)wrap_del, ""),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00006603
Yury Selivanov75445082015-05-11 22:57:16 -04006604 AMSLOT("__await__", am_await, slot_am_await, wrap_unaryfunc,
6605 "__await__($self, /)\n--\n\nReturn an iterator to be used in await expression."),
6606 AMSLOT("__aiter__", am_aiter, slot_am_aiter, wrap_unaryfunc,
6607 "__aiter__($self, /)\n--\n\nReturn an awaitable, that resolves in asynchronous iterator."),
6608 AMSLOT("__anext__", am_anext, slot_am_anext, wrap_unaryfunc,
6609 "__anext__($self, /)\n--\n\nReturn a value or raise StopAsyncIteration."),
6610
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006611 BINSLOT("__add__", nb_add, slot_nb_add,
Larry Hastings5c661892014-01-24 06:17:25 -08006612 "+"),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006613 RBINSLOT("__radd__", nb_add, slot_nb_add,
Larry Hastings5c661892014-01-24 06:17:25 -08006614 "+"),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006615 BINSLOT("__sub__", nb_subtract, slot_nb_subtract,
Larry Hastings5c661892014-01-24 06:17:25 -08006616 "-"),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006617 RBINSLOT("__rsub__", nb_subtract, slot_nb_subtract,
Larry Hastings5c661892014-01-24 06:17:25 -08006618 "-"),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006619 BINSLOT("__mul__", nb_multiply, slot_nb_multiply,
Larry Hastings5c661892014-01-24 06:17:25 -08006620 "*"),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006621 RBINSLOT("__rmul__", nb_multiply, slot_nb_multiply,
Larry Hastings5c661892014-01-24 06:17:25 -08006622 "*"),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006623 BINSLOT("__mod__", nb_remainder, slot_nb_remainder,
Larry Hastings5c661892014-01-24 06:17:25 -08006624 "%"),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006625 RBINSLOT("__rmod__", nb_remainder, slot_nb_remainder,
Larry Hastings5c661892014-01-24 06:17:25 -08006626 "%"),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006627 BINSLOTNOTINFIX("__divmod__", nb_divmod, slot_nb_divmod,
Larry Hastings581ee362014-01-28 05:00:08 -08006628 "Return divmod(self, value)."),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006629 RBINSLOTNOTINFIX("__rdivmod__", nb_divmod, slot_nb_divmod,
Larry Hastings581ee362014-01-28 05:00:08 -08006630 "Return divmod(value, self)."),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006631 NBSLOT("__pow__", nb_power, slot_nb_power, wrap_ternaryfunc,
Larry Hastings69a25472014-02-09 22:22:38 -08006632 "__pow__($self, value, mod=None, /)\n--\n\nReturn pow(self, value, mod)."),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006633 NBSLOT("__rpow__", nb_power, slot_nb_power, wrap_ternaryfunc_r,
Larry Hastings69a25472014-02-09 22:22:38 -08006634 "__rpow__($self, value, mod=None, /)\n--\n\nReturn pow(value, self, mod)."),
Larry Hastings5c661892014-01-24 06:17:25 -08006635 UNSLOT("__neg__", nb_negative, slot_nb_negative, wrap_unaryfunc, "-self"),
6636 UNSLOT("__pos__", nb_positive, slot_nb_positive, wrap_unaryfunc, "+self"),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006637 UNSLOT("__abs__", nb_absolute, slot_nb_absolute, wrap_unaryfunc,
Larry Hastings5c661892014-01-24 06:17:25 -08006638 "abs(self)"),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006639 UNSLOT("__bool__", nb_bool, slot_nb_bool, wrap_inquirypred,
Larry Hastings5c661892014-01-24 06:17:25 -08006640 "self != 0"),
6641 UNSLOT("__invert__", nb_invert, slot_nb_invert, wrap_unaryfunc, "~self"),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006642 BINSLOT("__lshift__", nb_lshift, slot_nb_lshift, "<<"),
6643 RBINSLOT("__rlshift__", nb_lshift, slot_nb_lshift, "<<"),
6644 BINSLOT("__rshift__", nb_rshift, slot_nb_rshift, ">>"),
6645 RBINSLOT("__rrshift__", nb_rshift, slot_nb_rshift, ">>"),
6646 BINSLOT("__and__", nb_and, slot_nb_and, "&"),
6647 RBINSLOT("__rand__", nb_and, slot_nb_and, "&"),
6648 BINSLOT("__xor__", nb_xor, slot_nb_xor, "^"),
6649 RBINSLOT("__rxor__", nb_xor, slot_nb_xor, "^"),
6650 BINSLOT("__or__", nb_or, slot_nb_or, "|"),
6651 RBINSLOT("__ror__", nb_or, slot_nb_or, "|"),
6652 UNSLOT("__int__", nb_int, slot_nb_int, wrap_unaryfunc,
Larry Hastings5c661892014-01-24 06:17:25 -08006653 "int(self)"),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006654 UNSLOT("__float__", nb_float, slot_nb_float, wrap_unaryfunc,
Larry Hastings5c661892014-01-24 06:17:25 -08006655 "float(self)"),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006656 IBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add,
Eli Benderskyd3baae72011-11-11 16:57:05 +02006657 wrap_binaryfunc, "+="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006658 IBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract,
Eli Benderskyd3baae72011-11-11 16:57:05 +02006659 wrap_binaryfunc, "-="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006660 IBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply,
Eli Benderskyd3baae72011-11-11 16:57:05 +02006661 wrap_binaryfunc, "*="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006662 IBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder,
Eli Benderskyd3baae72011-11-11 16:57:05 +02006663 wrap_binaryfunc, "%="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006664 IBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power,
Eli Benderskyd3baae72011-11-11 16:57:05 +02006665 wrap_binaryfunc, "**="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006666 IBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift,
Eli Benderskyd3baae72011-11-11 16:57:05 +02006667 wrap_binaryfunc, "<<="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006668 IBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift,
Eli Benderskyd3baae72011-11-11 16:57:05 +02006669 wrap_binaryfunc, ">>="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006670 IBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and,
Eli Benderskyd3baae72011-11-11 16:57:05 +02006671 wrap_binaryfunc, "&="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006672 IBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor,
Eli Benderskyd3baae72011-11-11 16:57:05 +02006673 wrap_binaryfunc, "^="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006674 IBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or,
Eli Benderskyd3baae72011-11-11 16:57:05 +02006675 wrap_binaryfunc, "|="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006676 BINSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
6677 RBINSLOT("__rfloordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
6678 BINSLOT("__truediv__", nb_true_divide, slot_nb_true_divide, "/"),
6679 RBINSLOT("__rtruediv__", nb_true_divide, slot_nb_true_divide, "/"),
6680 IBSLOT("__ifloordiv__", nb_inplace_floor_divide,
Georg Brandle1d26f32014-10-31 13:12:57 +01006681 slot_nb_inplace_floor_divide, wrap_binaryfunc, "//="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006682 IBSLOT("__itruediv__", nb_inplace_true_divide,
Georg Brandle1d26f32014-10-31 13:12:57 +01006683 slot_nb_inplace_true_divide, wrap_binaryfunc, "/="),
Benjamin Peterson63952412013-04-01 17:41:41 -04006684 NBSLOT("__index__", nb_index, slot_nb_index, wrap_unaryfunc,
Larry Hastings69a25472014-02-09 22:22:38 -08006685 "__index__($self, /)\n--\n\n"
Zachary Ware715ef022014-04-18 09:23:14 -05006686 "Return self converted to an integer, if self is suitable "
Larry Hastings5c661892014-01-24 06:17:25 -08006687 "for use as an index into a list."),
Benjamin Petersond51374e2014-04-09 23:55:56 -04006688 BINSLOT("__matmul__", nb_matrix_multiply, slot_nb_matrix_multiply,
6689 "@"),
6690 RBINSLOT("__rmatmul__", nb_matrix_multiply, slot_nb_matrix_multiply,
6691 "@"),
6692 IBSLOT("__imatmul__", nb_inplace_matrix_multiply, slot_nb_inplace_matrix_multiply,
6693 wrap_binaryfunc, "@="),
Benjamin Peterson63952412013-04-01 17:41:41 -04006694 MPSLOT("__len__", mp_length, slot_mp_length, wrap_lenfunc,
Larry Hastings69a25472014-02-09 22:22:38 -08006695 "__len__($self, /)\n--\n\nReturn len(self)."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006696 MPSLOT("__getitem__", mp_subscript, slot_mp_subscript,
6697 wrap_binaryfunc,
Larry Hastings69a25472014-02-09 22:22:38 -08006698 "__getitem__($self, key, /)\n--\n\nReturn self[key]."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006699 MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript,
6700 wrap_objobjargproc,
Larry Hastings69a25472014-02-09 22:22:38 -08006701 "__setitem__($self, key, value, /)\n--\n\nSet self[key] to value."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006702 MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript,
6703 wrap_delitem,
Yury Selivanov056e2652014-03-02 12:25:27 -05006704 "__delitem__($self, key, /)\n--\n\nDelete self[key]."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006705
6706 SQSLOT("__len__", sq_length, slot_sq_length, wrap_lenfunc,
Larry Hastings69a25472014-02-09 22:22:38 -08006707 "__len__($self, /)\n--\n\nReturn len(self)."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006708 /* Heap types defining __add__/__mul__ have sq_concat/sq_repeat == NULL.
6709 The logic in abstract.c always falls back to nb_add/nb_multiply in
6710 this case. Defining both the nb_* and the sq_* slots to call the
6711 user-defined methods has unexpected side-effects, as shown by
6712 test_descr.notimplemented() */
6713 SQSLOT("__add__", sq_concat, NULL, wrap_binaryfunc,
Larry Hastings69a25472014-02-09 22:22:38 -08006714 "__add__($self, value, /)\n--\n\nReturn self+value."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006715 SQSLOT("__mul__", sq_repeat, NULL, wrap_indexargfunc,
Larry Hastings69a25472014-02-09 22:22:38 -08006716 "__mul__($self, value, /)\n--\n\nReturn self*value.n"),
Benjamin Peterson63952412013-04-01 17:41:41 -04006717 SQSLOT("__rmul__", sq_repeat, NULL, wrap_indexargfunc,
Larry Hastings69a25472014-02-09 22:22:38 -08006718 "__rmul__($self, value, /)\n--\n\nReturn self*value."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006719 SQSLOT("__getitem__", sq_item, slot_sq_item, wrap_sq_item,
Larry Hastings69a25472014-02-09 22:22:38 -08006720 "__getitem__($self, key, /)\n--\n\nReturn self[key]."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006721 SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_setitem,
Larry Hastings69a25472014-02-09 22:22:38 -08006722 "__setitem__($self, key, value, /)\n--\n\nSet self[key] to value."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006723 SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_delitem,
Larry Hastings69a25472014-02-09 22:22:38 -08006724 "__delitem__($self, key, /)\n--\n\nDelete self[key]."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006725 SQSLOT("__contains__", sq_contains, slot_sq_contains, wrap_objobjproc,
Larry Hastings69a25472014-02-09 22:22:38 -08006726 "__contains__($self, key, /)\n--\n\nReturn key in self."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006727 SQSLOT("__iadd__", sq_inplace_concat, NULL,
Larry Hastings5c661892014-01-24 06:17:25 -08006728 wrap_binaryfunc,
Larry Hastings69a25472014-02-09 22:22:38 -08006729 "__iadd__($self, value, /)\n--\n\nImplement self+=value."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006730 SQSLOT("__imul__", sq_inplace_repeat, NULL,
Larry Hastings5c661892014-01-24 06:17:25 -08006731 wrap_indexargfunc,
Larry Hastings69a25472014-02-09 22:22:38 -08006732 "__imul__($self, value, /)\n--\n\nImplement self*=value."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006733
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006734 {NULL}
Guido van Rossum7b9144b2001-10-09 19:39:46 +00006735};
6736
Guido van Rossumc334df52002-04-04 23:44:47 +00006737/* Given a type pointer and an offset gotten from a slotdef entry, return a
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006738 pointer to the actual slot. This is not quite the same as simply adding
Guido van Rossumc334df52002-04-04 23:44:47 +00006739 the offset to the type pointer, since it takes care to indirect through the
6740 proper indirection pointer (as_buffer, etc.); it returns NULL if the
6741 indirection pointer is NULL. */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00006742static void **
Martin v. Löwis18e16552006-02-15 17:27:45 +00006743slotptr(PyTypeObject *type, int ioffset)
Guido van Rossum7b9144b2001-10-09 19:39:46 +00006744{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006745 char *ptr;
6746 long offset = ioffset;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00006747
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006748 /* Note: this depends on the order of the members of PyHeapTypeObject! */
6749 assert(offset >= 0);
6750 assert((size_t)offset < offsetof(PyHeapTypeObject, as_buffer));
6751 if ((size_t)offset >= offsetof(PyHeapTypeObject, as_sequence)) {
6752 ptr = (char *)type->tp_as_sequence;
6753 offset -= offsetof(PyHeapTypeObject, as_sequence);
6754 }
6755 else if ((size_t)offset >= offsetof(PyHeapTypeObject, as_mapping)) {
6756 ptr = (char *)type->tp_as_mapping;
6757 offset -= offsetof(PyHeapTypeObject, as_mapping);
6758 }
6759 else if ((size_t)offset >= offsetof(PyHeapTypeObject, as_number)) {
6760 ptr = (char *)type->tp_as_number;
6761 offset -= offsetof(PyHeapTypeObject, as_number);
6762 }
Yury Selivanov75445082015-05-11 22:57:16 -04006763 else if ((size_t)offset >= offsetof(PyHeapTypeObject, as_async)) {
6764 ptr = (char *)type->tp_as_async;
6765 offset -= offsetof(PyHeapTypeObject, as_async);
6766 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006767 else {
6768 ptr = (char *)type;
6769 }
6770 if (ptr != NULL)
6771 ptr += offset;
6772 return (void **)ptr;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00006773}
Guido van Rossumf040ede2001-08-07 16:40:56 +00006774
Guido van Rossumc334df52002-04-04 23:44:47 +00006775/* Length of array of slotdef pointers used to store slots with the
6776 same __name__. There should be at most MAX_EQUIV-1 slotdef entries with
6777 the same __name__, for any __name__. Since that's a static property, it is
6778 appropriate to declare fixed-size arrays for this. */
6779#define MAX_EQUIV 10
6780
6781/* Return a slot pointer for a given name, but ONLY if the attribute has
6782 exactly one slot function. The name must be an interned string. */
6783static void **
6784resolve_slotdups(PyTypeObject *type, PyObject *name)
6785{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006786 /* XXX Maybe this could be optimized more -- but is it worth it? */
Guido van Rossumc334df52002-04-04 23:44:47 +00006787
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006788 /* pname and ptrs act as a little cache */
6789 static PyObject *pname;
6790 static slotdef *ptrs[MAX_EQUIV];
6791 slotdef *p, **pp;
6792 void **res, **ptr;
Guido van Rossumc334df52002-04-04 23:44:47 +00006793
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006794 if (pname != name) {
6795 /* Collect all slotdefs that match name into ptrs. */
6796 pname = name;
6797 pp = ptrs;
6798 for (p = slotdefs; p->name_strobj; p++) {
6799 if (p->name_strobj == name)
6800 *pp++ = p;
6801 }
6802 *pp = NULL;
6803 }
Guido van Rossumc334df52002-04-04 23:44:47 +00006804
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006805 /* Look in all matching slots of the type; if exactly one of these has
6806 a filled-in slot, return its value. Otherwise return NULL. */
6807 res = NULL;
6808 for (pp = ptrs; *pp; pp++) {
6809 ptr = slotptr(type, (*pp)->offset);
6810 if (ptr == NULL || *ptr == NULL)
6811 continue;
6812 if (res != NULL)
6813 return NULL;
6814 res = ptr;
6815 }
6816 return res;
Guido van Rossumc334df52002-04-04 23:44:47 +00006817}
6818
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006819/* Common code for update_slots_callback() and fixup_slot_dispatchers(). This
Guido van Rossumc334df52002-04-04 23:44:47 +00006820 does some incredibly complex thinking and then sticks something into the
6821 slot. (It sees if the adjacent slotdefs for the same slot have conflicting
6822 interests, and then stores a generic wrapper or a specific function into
6823 the slot.) Return a pointer to the next slotdef with a different offset,
6824 because that's convenient for fixup_slot_dispatchers(). */
6825static slotdef *
6826update_one_slot(PyTypeObject *type, slotdef *p)
6827{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006828 PyObject *descr;
6829 PyWrapperDescrObject *d;
6830 void *generic = NULL, *specific = NULL;
6831 int use_generic = 0;
6832 int offset = p->offset;
6833 void **ptr = slotptr(type, offset);
Guido van Rossumc334df52002-04-04 23:44:47 +00006834
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006835 if (ptr == NULL) {
6836 do {
6837 ++p;
6838 } while (p->offset == offset);
6839 return p;
6840 }
6841 do {
6842 descr = _PyType_Lookup(type, p->name_strobj);
6843 if (descr == NULL) {
6844 if (ptr == (void**)&type->tp_iternext) {
Trent Nelsonab02db22012-09-18 21:58:03 -04006845 specific = (void *)_PyObject_NextNotImplemented;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006846 }
6847 continue;
6848 }
Benjamin Peterson7b166872012-04-24 11:06:25 -04006849 if (Py_TYPE(descr) == &PyWrapperDescr_Type &&
6850 ((PyWrapperDescrObject *)descr)->d_base->name_strobj == p->name_strobj) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006851 void **tptr = resolve_slotdups(type, p->name_strobj);
6852 if (tptr == NULL || tptr == ptr)
6853 generic = p->function;
6854 d = (PyWrapperDescrObject *)descr;
6855 if (d->d_base->wrapper == p->wrapper &&
6856 PyType_IsSubtype(type, PyDescr_TYPE(d)))
6857 {
6858 if (specific == NULL ||
6859 specific == d->d_wrapped)
6860 specific = d->d_wrapped;
6861 else
6862 use_generic = 1;
6863 }
6864 }
6865 else if (Py_TYPE(descr) == &PyCFunction_Type &&
6866 PyCFunction_GET_FUNCTION(descr) ==
6867 (PyCFunction)tp_new_wrapper &&
6868 ptr == (void**)&type->tp_new)
6869 {
6870 /* The __new__ wrapper is not a wrapper descriptor,
6871 so must be special-cased differently.
6872 If we don't do this, creating an instance will
6873 always use slot_tp_new which will look up
6874 __new__ in the MRO which will call tp_new_wrapper
6875 which will look through the base classes looking
6876 for a static base and call its tp_new (usually
6877 PyType_GenericNew), after performing various
6878 sanity checks and constructing a new argument
6879 list. Cut all that nonsense short -- this speeds
6880 up instance creation tremendously. */
Serhiy Storchaka49010ee2016-12-14 19:52:17 +02006881 specific = (void *)type->tp_new;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006882 /* XXX I'm not 100% sure that there isn't a hole
6883 in this reasoning that requires additional
6884 sanity checks. I'll buy the first person to
6885 point out a bug in this reasoning a beer. */
6886 }
6887 else if (descr == Py_None &&
6888 ptr == (void**)&type->tp_hash) {
6889 /* We specifically allow __hash__ to be set to None
6890 to prevent inheritance of the default
6891 implementation from object.__hash__ */
Trent Nelsonab02db22012-09-18 21:58:03 -04006892 specific = (void *)PyObject_HashNotImplemented;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006893 }
6894 else {
6895 use_generic = 1;
6896 generic = p->function;
6897 }
6898 } while ((++p)->offset == offset);
6899 if (specific && !use_generic)
6900 *ptr = specific;
6901 else
6902 *ptr = generic;
6903 return p;
Guido van Rossumc334df52002-04-04 23:44:47 +00006904}
6905
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006906/* In the type, update the slots whose slotdefs are gathered in the pp array.
6907 This is a callback for update_subclasses(). */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006908static int
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006909update_slots_callback(PyTypeObject *type, void *data)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006910{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006911 slotdef **pp = (slotdef **)data;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006912
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006913 for (; *pp; pp++)
6914 update_one_slot(type, *pp);
6915 return 0;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006916}
6917
Martin v. Löwis996b6712014-07-26 16:44:07 +02006918static int slotdefs_initialized = 0;
Guido van Rossumc334df52002-04-04 23:44:47 +00006919/* Initialize the slotdefs table by adding interned string objects for the
Martin v. Löwis5b561502014-07-26 15:25:04 +02006920 names. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006921static void
Guido van Rossumd396b9c2001-10-13 20:02:41 +00006922init_slotdefs(void)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006923{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006924 slotdef *p;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006925
Martin v. Löwis996b6712014-07-26 16:44:07 +02006926 if (slotdefs_initialized)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006927 return;
6928 for (p = slotdefs; p->name; p++) {
Benjamin Peterson63952412013-04-01 17:41:41 -04006929 /* Slots must be ordered by their offset in the PyHeapTypeObject. */
6930 assert(!p[1].name || p->offset <= p[1].offset);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006931 p->name_strobj = PyUnicode_InternFromString(p->name);
6932 if (!p->name_strobj)
6933 Py_FatalError("Out of memory interning slotdef names");
6934 }
Martin v. Löwis996b6712014-07-26 16:44:07 +02006935 slotdefs_initialized = 1;
6936}
6937
6938/* Undo init_slotdefs, releasing the interned strings. */
Victor Stinner331a7262014-07-27 16:11:30 +02006939static void clear_slotdefs(void)
Martin v. Löwis996b6712014-07-26 16:44:07 +02006940{
6941 slotdef *p;
6942 for (p = slotdefs; p->name; p++) {
6943 Py_CLEAR(p->name_strobj);
6944 }
6945 slotdefs_initialized = 0;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006946}
6947
Guido van Rossumc334df52002-04-04 23:44:47 +00006948/* Update the slots after assignment to a class (type) attribute. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006949static int
6950update_slot(PyTypeObject *type, PyObject *name)
6951{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006952 slotdef *ptrs[MAX_EQUIV];
6953 slotdef *p;
6954 slotdef **pp;
6955 int offset;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006956
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006957 /* Clear the VALID_VERSION flag of 'type' and all its
6958 subclasses. This could possibly be unified with the
6959 update_subclasses() recursion below, but carefully:
6960 they each have their own conditions on which to stop
6961 recursing into subclasses. */
6962 PyType_Modified(type);
Christian Heimesa62da1d2008-01-12 19:39:10 +00006963
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006964 init_slotdefs();
6965 pp = ptrs;
6966 for (p = slotdefs; p->name; p++) {
6967 /* XXX assume name is interned! */
6968 if (p->name_strobj == name)
6969 *pp++ = p;
6970 }
6971 *pp = NULL;
6972 for (pp = ptrs; *pp; pp++) {
6973 p = *pp;
6974 offset = p->offset;
6975 while (p > slotdefs && (p-1)->offset == offset)
6976 --p;
6977 *pp = p;
6978 }
6979 if (ptrs[0] == NULL)
6980 return 0; /* Not an attribute that affects any slots */
6981 return update_subclasses(type, name,
6982 update_slots_callback, (void *)ptrs);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006983}
6984
Guido van Rossumc334df52002-04-04 23:44:47 +00006985/* Store the proper functions in the slot dispatches at class (type)
6986 definition time, based upon which operations the class overrides in its
6987 dict. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00006988static void
Guido van Rossum7b9144b2001-10-09 19:39:46 +00006989fixup_slot_dispatchers(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00006990{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006991 slotdef *p;
Tim Peters6d6c1a32001-08-02 04:15:00 +00006992
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006993 init_slotdefs();
6994 for (p = slotdefs; p->name; )
6995 p = update_one_slot(type, p);
Tim Peters6d6c1a32001-08-02 04:15:00 +00006996}
Guido van Rossum705f0f52001-08-24 16:47:00 +00006997
Michael W. Hudson98bbc492002-11-26 14:47:27 +00006998static void
6999update_all_slots(PyTypeObject* type)
7000{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007001 slotdef *p;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00007002
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007003 init_slotdefs();
7004 for (p = slotdefs; p->name; p++) {
7005 /* update_slot returns int but can't actually fail */
7006 update_slot(type, p->name_strobj);
7007 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +00007008}
7009
Nick Coghland78448e2016-07-30 16:26:03 +10007010/* Call __set_name__ on all descriptors in a newly generated type */
7011static int
7012set_names(PyTypeObject *type)
7013{
Serhiy Storchaka9ec07722016-11-29 09:54:17 +02007014 PyObject *names_to_set, *key, *value, *set_name, *tmp;
Nick Coghland78448e2016-07-30 16:26:03 +10007015 Py_ssize_t i = 0;
7016
Serhiy Storchaka9ec07722016-11-29 09:54:17 +02007017 names_to_set = PyDict_Copy(type->tp_dict);
7018 if (names_to_set == NULL)
7019 return -1;
7020
7021 while (PyDict_Next(names_to_set, &i, &key, &value)) {
Serhiy Storchakaafd02a42016-09-21 15:54:59 +03007022 set_name = lookup_maybe(value, &PyId___set_name__);
7023 if (set_name != NULL) {
7024 tmp = PyObject_CallFunctionObjArgs(set_name, type, key, NULL);
7025 Py_DECREF(set_name);
Serhiy Storchakad5d32d22016-10-21 17:13:31 +03007026 if (tmp == NULL) {
7027 _PyErr_FormatFromCause(PyExc_RuntimeError,
7028 "Error calling __set_name__ on '%.100s' instance %R "
7029 "in '%.100s'",
7030 value->ob_type->tp_name, key, type->tp_name);
Serhiy Storchaka9ec07722016-11-29 09:54:17 +02007031 Py_DECREF(names_to_set);
Nick Coghland78448e2016-07-30 16:26:03 +10007032 return -1;
Serhiy Storchakad5d32d22016-10-21 17:13:31 +03007033 }
Nick Coghland78448e2016-07-30 16:26:03 +10007034 else
7035 Py_DECREF(tmp);
7036 }
Serhiy Storchaka9ec07722016-11-29 09:54:17 +02007037 else if (PyErr_Occurred()) {
7038 Py_DECREF(names_to_set);
Serhiy Storchakaafd02a42016-09-21 15:54:59 +03007039 return -1;
Serhiy Storchaka9ec07722016-11-29 09:54:17 +02007040 }
Nick Coghland78448e2016-07-30 16:26:03 +10007041 }
7042
Serhiy Storchaka9ec07722016-11-29 09:54:17 +02007043 Py_DECREF(names_to_set);
Nick Coghland78448e2016-07-30 16:26:03 +10007044 return 0;
7045}
7046
7047/* Call __init_subclass__ on the parent of a newly generated type */
7048static int
7049init_subclass(PyTypeObject *type, PyObject *kwds)
7050{
Victor Stinner463b86a2016-08-22 23:33:13 +02007051 PyObject *super, *func, *result;
7052 PyObject *args[2] = {(PyObject *)type, (PyObject *)type};
Nick Coghland78448e2016-07-30 16:26:03 +10007053
Victor Stinner463b86a2016-08-22 23:33:13 +02007054 super = _PyObject_FastCall((PyObject *)&PySuper_Type, args, 2);
7055 if (super == NULL) {
Nick Coghland78448e2016-07-30 16:26:03 +10007056 return -1;
Victor Stinner253021d2016-08-20 02:37:41 +02007057 }
7058
Victor Stinner463b86a2016-08-22 23:33:13 +02007059 func = _PyObject_GetAttrId(super, &PyId___init_subclass__);
7060 Py_DECREF(super);
7061 if (func == NULL) {
Nick Coghland78448e2016-07-30 16:26:03 +10007062 return -1;
Victor Stinner463b86a2016-08-22 23:33:13 +02007063 }
Nick Coghland78448e2016-07-30 16:26:03 +10007064
Victor Stinner463b86a2016-08-22 23:33:13 +02007065
7066 result = _PyObject_FastCallDict(func, NULL, 0, kwds);
7067 Py_DECREF(func);
7068 if (result == NULL) {
7069 return -1;
7070 }
7071
7072 Py_DECREF(result);
Nick Coghland78448e2016-07-30 16:26:03 +10007073 return 0;
7074}
7075
Guido van Rossum8d24ee92003-03-24 23:49:49 +00007076/* recurse_down_subclasses() and update_subclasses() are mutually
7077 recursive functions to call a callback for all subclasses,
7078 but refraining from recursing into subclasses that define 'name'. */
7079
7080static int
7081update_subclasses(PyTypeObject *type, PyObject *name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007082 update_callback callback, void *data)
Guido van Rossum8d24ee92003-03-24 23:49:49 +00007083{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007084 if (callback(type, data) < 0)
7085 return -1;
7086 return recurse_down_subclasses(type, name, callback, data);
Guido van Rossum8d24ee92003-03-24 23:49:49 +00007087}
7088
7089static int
7090recurse_down_subclasses(PyTypeObject *type, PyObject *name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007091 update_callback callback, void *data)
Guido van Rossum8d24ee92003-03-24 23:49:49 +00007092{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007093 PyTypeObject *subclass;
7094 PyObject *ref, *subclasses, *dict;
Antoine Pitrou84745ab2013-10-29 21:31:25 +01007095 Py_ssize_t i;
Guido van Rossum8d24ee92003-03-24 23:49:49 +00007096
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007097 subclasses = type->tp_subclasses;
7098 if (subclasses == NULL)
7099 return 0;
Antoine Pitrou84745ab2013-10-29 21:31:25 +01007100 assert(PyDict_CheckExact(subclasses));
7101 i = 0;
7102 while (PyDict_Next(subclasses, &i, NULL, &ref)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007103 assert(PyWeakref_CheckRef(ref));
7104 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
7105 assert(subclass != NULL);
7106 if ((PyObject *)subclass == Py_None)
7107 continue;
7108 assert(PyType_Check(subclass));
7109 /* Avoid recursing down into unaffected classes */
7110 dict = subclass->tp_dict;
7111 if (dict != NULL && PyDict_Check(dict) &&
7112 PyDict_GetItem(dict, name) != NULL)
7113 continue;
7114 if (update_subclasses(subclass, name, callback, data) < 0)
7115 return -1;
7116 }
7117 return 0;
Guido van Rossum8d24ee92003-03-24 23:49:49 +00007118}
7119
Guido van Rossum6d204072001-10-21 00:44:31 +00007120/* This function is called by PyType_Ready() to populate the type's
7121 dictionary with method descriptors for function slots. For each
Guido van Rossum09638c12002-06-13 19:17:46 +00007122 function slot (like tp_repr) that's defined in the type, one or more
7123 corresponding descriptors are added in the type's tp_dict dictionary
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007124 under the appropriate name (like __repr__). Some function slots
Guido van Rossum09638c12002-06-13 19:17:46 +00007125 cause more than one descriptor to be added (for example, the nb_add
7126 slot adds both __add__ and __radd__ descriptors) and some function
7127 slots compete for the same descriptor (for example both sq_item and
7128 mp_subscript generate a __getitem__ descriptor).
7129
Ezio Melotti13925002011-03-16 11:05:33 +02007130 In the latter case, the first slotdef entry encountered wins. Since
Tim Petersbf9b2442003-03-23 05:35:36 +00007131 slotdef entries are sorted by the offset of the slot in the
Guido van Rossume5c691a2003-03-07 15:13:17 +00007132 PyHeapTypeObject, this gives us some control over disambiguating
Guido van Rossum8d24ee92003-03-24 23:49:49 +00007133 between competing slots: the members of PyHeapTypeObject are listed
7134 from most general to least general, so the most general slot is
7135 preferred. In particular, because as_mapping comes before as_sequence,
7136 for a type that defines both mp_subscript and sq_item, mp_subscript
7137 wins.
Guido van Rossum09638c12002-06-13 19:17:46 +00007138
7139 This only adds new descriptors and doesn't overwrite entries in
7140 tp_dict that were previously defined. The descriptors contain a
7141 reference to the C function they must call, so that it's safe if they
7142 are copied into a subtype's __dict__ and the subtype has a different
7143 C function in its slot -- calling the method defined by the
7144 descriptor will call the C function that was used to create it,
7145 rather than the C function present in the slot when it is called.
7146 (This is important because a subtype may have a C function in the
7147 slot that calls the method from the dictionary, and we want to avoid
7148 infinite recursion here.) */
Guido van Rossum6d204072001-10-21 00:44:31 +00007149
7150static int
7151add_operators(PyTypeObject *type)
7152{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007153 PyObject *dict = type->tp_dict;
7154 slotdef *p;
7155 PyObject *descr;
7156 void **ptr;
Guido van Rossum6d204072001-10-21 00:44:31 +00007157
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007158 init_slotdefs();
7159 for (p = slotdefs; p->name; p++) {
7160 if (p->wrapper == NULL)
7161 continue;
7162 ptr = slotptr(type, p->offset);
7163 if (!ptr || !*ptr)
7164 continue;
7165 if (PyDict_GetItem(dict, p->name_strobj))
7166 continue;
Trent Nelsonab02db22012-09-18 21:58:03 -04007167 if (*ptr == (void *)PyObject_HashNotImplemented) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007168 /* Classes may prevent the inheritance of the tp_hash
7169 slot by storing PyObject_HashNotImplemented in it. Make it
7170 visible as a None value for the __hash__ attribute. */
7171 if (PyDict_SetItem(dict, p->name_strobj, Py_None) < 0)
7172 return -1;
7173 }
7174 else {
7175 descr = PyDescr_NewWrapper(type, p, *ptr);
7176 if (descr == NULL)
7177 return -1;
Benjamin Peterson27007dc2016-07-06 23:26:32 -07007178 if (PyDict_SetItem(dict, p->name_strobj, descr) < 0) {
7179 Py_DECREF(descr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007180 return -1;
Benjamin Peterson27007dc2016-07-06 23:26:32 -07007181 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007182 Py_DECREF(descr);
7183 }
7184 }
7185 if (type->tp_new != NULL) {
7186 if (add_tp_new_wrapper(type) < 0)
7187 return -1;
7188 }
7189 return 0;
Guido van Rossum6d204072001-10-21 00:44:31 +00007190}
7191
Guido van Rossum705f0f52001-08-24 16:47:00 +00007192
7193/* Cooperative 'super' */
7194
7195typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007196 PyObject_HEAD
7197 PyTypeObject *type;
7198 PyObject *obj;
7199 PyTypeObject *obj_type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00007200} superobject;
7201
Guido van Rossum6f799372001-09-20 20:46:19 +00007202static PyMemberDef super_members[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007203 {"__thisclass__", T_OBJECT, offsetof(superobject, type), READONLY,
7204 "the class invoking super()"},
7205 {"__self__", T_OBJECT, offsetof(superobject, obj), READONLY,
7206 "the instance invoking super(); may be None"},
7207 {"__self_class__", T_OBJECT, offsetof(superobject, obj_type), READONLY,
7208 "the type of the instance invoking super(); may be None"},
7209 {0}
Guido van Rossum41eb14d2001-08-30 23:13:11 +00007210};
7211
Guido van Rossum705f0f52001-08-24 16:47:00 +00007212static void
7213super_dealloc(PyObject *self)
7214{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007215 superobject *su = (superobject *)self;
Guido van Rossum705f0f52001-08-24 16:47:00 +00007216
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007217 _PyObject_GC_UNTRACK(self);
7218 Py_XDECREF(su->obj);
7219 Py_XDECREF(su->type);
7220 Py_XDECREF(su->obj_type);
7221 Py_TYPE(self)->tp_free(self);
Guido van Rossum705f0f52001-08-24 16:47:00 +00007222}
7223
7224static PyObject *
Guido van Rossum41eb14d2001-08-30 23:13:11 +00007225super_repr(PyObject *self)
7226{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007227 superobject *su = (superobject *)self;
Guido van Rossum41eb14d2001-08-30 23:13:11 +00007228
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007229 if (su->obj_type)
7230 return PyUnicode_FromFormat(
7231 "<super: <class '%s'>, <%s object>>",
7232 su->type ? su->type->tp_name : "NULL",
7233 su->obj_type->tp_name);
7234 else
7235 return PyUnicode_FromFormat(
7236 "<super: <class '%s'>, NULL>",
7237 su->type ? su->type->tp_name : "NULL");
Guido van Rossum41eb14d2001-08-30 23:13:11 +00007238}
7239
7240static PyObject *
Guido van Rossum705f0f52001-08-24 16:47:00 +00007241super_getattro(PyObject *self, PyObject *name)
7242{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007243 superobject *su = (superobject *)self;
Benjamin Peterson104b9e02015-02-05 22:29:14 -05007244 PyTypeObject *starttype;
7245 PyObject *mro;
7246 Py_ssize_t i, n;
Guido van Rossum705f0f52001-08-24 16:47:00 +00007247
Benjamin Peterson104b9e02015-02-05 22:29:14 -05007248 starttype = su->obj_type;
7249 if (starttype == NULL)
7250 goto skip;
7251
7252 /* We want __class__ to return the class of the super object
7253 (i.e. super, or a subclass), not the class of su->obj. */
7254 if (PyUnicode_Check(name) &&
7255 PyUnicode_GET_LENGTH(name) == 9 &&
Serhiy Storchakaf5894dd2016-11-16 15:40:39 +02007256 _PyUnicode_EqualToASCIIId(name, &PyId___class__))
Benjamin Peterson104b9e02015-02-05 22:29:14 -05007257 goto skip;
7258
7259 mro = starttype->tp_mro;
7260 if (mro == NULL)
7261 goto skip;
7262
7263 assert(PyTuple_Check(mro));
7264 n = PyTuple_GET_SIZE(mro);
7265
7266 /* No need to check the last one: it's gonna be skipped anyway. */
7267 for (i = 0; i+1 < n; i++) {
7268 if ((PyObject *)(su->type) == PyTuple_GET_ITEM(mro, i))
7269 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007270 }
Benjamin Peterson104b9e02015-02-05 22:29:14 -05007271 i++; /* skip su->type (if any) */
7272 if (i >= n)
7273 goto skip;
Guido van Rossum76ba09f2003-04-16 19:40:58 +00007274
Benjamin Peterson104b9e02015-02-05 22:29:14 -05007275 /* keep a strong reference to mro because starttype->tp_mro can be
7276 replaced during PyDict_GetItem(dict, name) */
7277 Py_INCREF(mro);
7278 do {
7279 PyObject *res, *tmp, *dict;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007280 descrgetfunc f;
Guido van Rossum705f0f52001-08-24 16:47:00 +00007281
Benjamin Peterson104b9e02015-02-05 22:29:14 -05007282 tmp = PyTuple_GET_ITEM(mro, i);
7283 assert(PyType_Check(tmp));
Guido van Rossum155db9a2002-04-02 17:53:47 +00007284
Benjamin Peterson104b9e02015-02-05 22:29:14 -05007285 dict = ((PyTypeObject *)tmp)->tp_dict;
7286 assert(dict != NULL && PyDict_Check(dict));
7287
7288 res = PyDict_GetItem(dict, name);
7289 if (res != NULL) {
7290 Py_INCREF(res);
7291
7292 f = Py_TYPE(res)->tp_descr_get;
7293 if (f != NULL) {
7294 tmp = f(res,
7295 /* Only pass 'obj' param if this is instance-mode super
7296 (See SF ID #743627) */
7297 (su->obj == (PyObject *)starttype) ? NULL : su->obj,
7298 (PyObject *)starttype);
7299 Py_DECREF(res);
7300 res = tmp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007301 }
Benjamin Peterson104b9e02015-02-05 22:29:14 -05007302
7303 Py_DECREF(mro);
7304 return res;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007305 }
Benjamin Peterson104b9e02015-02-05 22:29:14 -05007306
7307 i++;
7308 } while (i < n);
7309 Py_DECREF(mro);
7310
7311 skip:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007312 return PyObject_GenericGetAttr(self, name);
Guido van Rossum705f0f52001-08-24 16:47:00 +00007313}
7314
Guido van Rossuma89d10e2003-02-12 03:58:38 +00007315static PyTypeObject *
Guido van Rossum5b443c62001-12-03 15:38:28 +00007316supercheck(PyTypeObject *type, PyObject *obj)
7317{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007318 /* Check that a super() call makes sense. Return a type object.
Guido van Rossuma89d10e2003-02-12 03:58:38 +00007319
Florent Xiclunaaa6c1d22011-12-12 18:54:29 +01007320 obj can be a class, or an instance of one:
Guido van Rossuma89d10e2003-02-12 03:58:38 +00007321
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007322 - If it is a class, it must be a subclass of 'type'. This case is
7323 used for class methods; the return value is obj.
Guido van Rossuma89d10e2003-02-12 03:58:38 +00007324
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007325 - If it is an instance, it must be an instance of 'type'. This is
7326 the normal case; the return value is obj.__class__.
Guido van Rossuma89d10e2003-02-12 03:58:38 +00007327
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007328 But... when obj is an instance, we want to allow for the case where
7329 Py_TYPE(obj) is not a subclass of type, but obj.__class__ is!
7330 This will allow using super() with a proxy for obj.
7331 */
Guido van Rossuma89d10e2003-02-12 03:58:38 +00007332
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007333 /* Check for first bullet above (special case) */
7334 if (PyType_Check(obj) && PyType_IsSubtype((PyTypeObject *)obj, type)) {
7335 Py_INCREF(obj);
7336 return (PyTypeObject *)obj;
7337 }
Guido van Rossum8e80a722003-02-18 19:22:22 +00007338
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007339 /* Normal case */
7340 if (PyType_IsSubtype(Py_TYPE(obj), type)) {
7341 Py_INCREF(Py_TYPE(obj));
7342 return Py_TYPE(obj);
7343 }
7344 else {
7345 /* Try the slow way */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007346 PyObject *class_attr;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00007347
Martin v. Löwisbfc6d742011-10-13 20:03:57 +02007348 class_attr = _PyObject_GetAttrId(obj, &PyId___class__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007349 if (class_attr != NULL &&
7350 PyType_Check(class_attr) &&
7351 (PyTypeObject *)class_attr != Py_TYPE(obj))
7352 {
7353 int ok = PyType_IsSubtype(
7354 (PyTypeObject *)class_attr, type);
7355 if (ok)
7356 return (PyTypeObject *)class_attr;
7357 }
Guido van Rossuma89d10e2003-02-12 03:58:38 +00007358
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007359 if (class_attr == NULL)
7360 PyErr_Clear();
7361 else
7362 Py_DECREF(class_attr);
7363 }
Guido van Rossuma89d10e2003-02-12 03:58:38 +00007364
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007365 PyErr_SetString(PyExc_TypeError,
7366 "super(type, obj): "
7367 "obj must be an instance or subtype of type");
7368 return NULL;
Guido van Rossum5b443c62001-12-03 15:38:28 +00007369}
7370
Guido van Rossum705f0f52001-08-24 16:47:00 +00007371static PyObject *
7372super_descr_get(PyObject *self, PyObject *obj, PyObject *type)
7373{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007374 superobject *su = (superobject *)self;
7375 superobject *newobj;
Guido van Rossum705f0f52001-08-24 16:47:00 +00007376
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007377 if (obj == NULL || obj == Py_None || su->obj != NULL) {
7378 /* Not binding to an object, or already bound */
7379 Py_INCREF(self);
7380 return self;
7381 }
7382 if (Py_TYPE(su) != &PySuper_Type)
7383 /* If su is an instance of a (strict) subclass of super,
7384 call its type */
7385 return PyObject_CallFunctionObjArgs((PyObject *)Py_TYPE(su),
7386 su->type, obj, NULL);
7387 else {
7388 /* Inline the common case */
7389 PyTypeObject *obj_type = supercheck(su->type, obj);
7390 if (obj_type == NULL)
7391 return NULL;
7392 newobj = (superobject *)PySuper_Type.tp_new(&PySuper_Type,
7393 NULL, NULL);
7394 if (newobj == NULL)
7395 return NULL;
7396 Py_INCREF(su->type);
7397 Py_INCREF(obj);
7398 newobj->type = su->type;
7399 newobj->obj = obj;
7400 newobj->obj_type = obj_type;
7401 return (PyObject *)newobj;
7402 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00007403}
7404
7405static int
7406super_init(PyObject *self, PyObject *args, PyObject *kwds)
7407{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007408 superobject *su = (superobject *)self;
7409 PyTypeObject *type = NULL;
7410 PyObject *obj = NULL;
7411 PyTypeObject *obj_type = NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00007412
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007413 if (!_PyArg_NoKeywords("super", kwds))
7414 return -1;
7415 if (!PyArg_ParseTuple(args, "|O!O:super", &PyType_Type, &type, &obj))
7416 return -1;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00007417
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007418 if (type == NULL) {
7419 /* Call super(), without args -- fill in from __class__
7420 and first local variable on the stack. */
Victor Stinner1c6970f2014-05-13 01:32:36 +02007421 PyFrameObject *f;
7422 PyCodeObject *co;
Victor Stinner0fcab4a2011-01-04 12:59:15 +00007423 Py_ssize_t i, n;
Victor Stinner1c6970f2014-05-13 01:32:36 +02007424 f = PyThreadState_GET()->frame;
7425 if (f == NULL) {
7426 PyErr_SetString(PyExc_RuntimeError,
7427 "super(): no current frame");
7428 return -1;
7429 }
7430 co = f->f_code;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007431 if (co == NULL) {
Benjamin Peterson6a42bd62012-09-01 23:04:38 -04007432 PyErr_SetString(PyExc_RuntimeError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007433 "super(): no code object");
7434 return -1;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00007435 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007436 if (co->co_argcount == 0) {
Benjamin Peterson6a42bd62012-09-01 23:04:38 -04007437 PyErr_SetString(PyExc_RuntimeError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007438 "super(): no arguments");
7439 return -1;
7440 }
7441 obj = f->f_localsplus[0];
Benjamin Peterson159ae412013-05-12 18:16:06 -05007442 if (obj == NULL && co->co_cell2arg) {
7443 /* The first argument might be a cell. */
7444 n = PyTuple_GET_SIZE(co->co_cellvars);
7445 for (i = 0; i < n; i++) {
7446 if (co->co_cell2arg[i] == 0) {
7447 PyObject *cell = f->f_localsplus[co->co_nlocals + i];
7448 assert(PyCell_Check(cell));
7449 obj = PyCell_GET(cell);
7450 break;
7451 }
7452 }
Guido van Rossum6832c812013-05-10 08:47:42 -07007453 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007454 if (obj == NULL) {
Benjamin Peterson6a42bd62012-09-01 23:04:38 -04007455 PyErr_SetString(PyExc_RuntimeError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007456 "super(): arg[0] deleted");
7457 return -1;
7458 }
7459 if (co->co_freevars == NULL)
7460 n = 0;
7461 else {
7462 assert(PyTuple_Check(co->co_freevars));
7463 n = PyTuple_GET_SIZE(co->co_freevars);
7464 }
7465 for (i = 0; i < n; i++) {
7466 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
7467 assert(PyUnicode_Check(name));
Serhiy Storchakaf5894dd2016-11-16 15:40:39 +02007468 if (_PyUnicode_EqualToASCIIId(name, &PyId___class__)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007469 Py_ssize_t index = co->co_nlocals +
7470 PyTuple_GET_SIZE(co->co_cellvars) + i;
7471 PyObject *cell = f->f_localsplus[index];
7472 if (cell == NULL || !PyCell_Check(cell)) {
Benjamin Peterson6a42bd62012-09-01 23:04:38 -04007473 PyErr_SetString(PyExc_RuntimeError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007474 "super(): bad __class__ cell");
7475 return -1;
7476 }
7477 type = (PyTypeObject *) PyCell_GET(cell);
7478 if (type == NULL) {
Benjamin Peterson6a42bd62012-09-01 23:04:38 -04007479 PyErr_SetString(PyExc_RuntimeError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007480 "super(): empty __class__ cell");
7481 return -1;
7482 }
7483 if (!PyType_Check(type)) {
Benjamin Peterson6a42bd62012-09-01 23:04:38 -04007484 PyErr_Format(PyExc_RuntimeError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007485 "super(): __class__ is not a type (%s)",
7486 Py_TYPE(type)->tp_name);
7487 return -1;
7488 }
7489 break;
7490 }
7491 }
7492 if (type == NULL) {
Benjamin Peterson6a42bd62012-09-01 23:04:38 -04007493 PyErr_SetString(PyExc_RuntimeError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007494 "super(): __class__ cell not found");
7495 return -1;
7496 }
7497 }
Guido van Rossumcd16bf62007-06-13 18:07:49 +00007498
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007499 if (obj == Py_None)
7500 obj = NULL;
7501 if (obj != NULL) {
7502 obj_type = supercheck(type, obj);
7503 if (obj_type == NULL)
7504 return -1;
7505 Py_INCREF(obj);
7506 }
7507 Py_INCREF(type);
Serhiy Storchaka3d749762016-04-13 15:27:33 +03007508 Py_XSETREF(su->type, type);
7509 Py_XSETREF(su->obj, obj);
7510 Py_XSETREF(su->obj_type, obj_type);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007511 return 0;
Guido van Rossum705f0f52001-08-24 16:47:00 +00007512}
7513
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007514PyDoc_STRVAR(super_doc,
Guido van Rossumcd16bf62007-06-13 18:07:49 +00007515"super() -> same as super(__class__, <first argument>)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00007516"super(type) -> unbound super object\n"
7517"super(type, obj) -> bound super object; requires isinstance(obj, type)\n"
Guido van Rossume705ef12001-08-29 15:47:06 +00007518"super(type, type2) -> bound super object; requires issubclass(type2, type)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00007519"Typical use to call a cooperative superclass method:\n"
7520"class C(B):\n"
7521" def meth(self, arg):\n"
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007522" super().meth(arg)\n"
Guido van Rossumcd16bf62007-06-13 18:07:49 +00007523"This works for class methods too:\n"
7524"class C(B):\n"
7525" @classmethod\n"
7526" def cmeth(cls, arg):\n"
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007527" super().cmeth(arg)\n");
Guido van Rossum705f0f52001-08-24 16:47:00 +00007528
Guido van Rossum048eb752001-10-02 21:24:57 +00007529static int
7530super_traverse(PyObject *self, visitproc visit, void *arg)
7531{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007532 superobject *su = (superobject *)self;
Guido van Rossum048eb752001-10-02 21:24:57 +00007533
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007534 Py_VISIT(su->obj);
7535 Py_VISIT(su->type);
7536 Py_VISIT(su->obj_type);
Guido van Rossum048eb752001-10-02 21:24:57 +00007537
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007538 return 0;
Guido van Rossum048eb752001-10-02 21:24:57 +00007539}
7540
Guido van Rossum705f0f52001-08-24 16:47:00 +00007541PyTypeObject PySuper_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007542 PyVarObject_HEAD_INIT(&PyType_Type, 0)
7543 "super", /* tp_name */
7544 sizeof(superobject), /* tp_basicsize */
7545 0, /* tp_itemsize */
7546 /* methods */
7547 super_dealloc, /* tp_dealloc */
7548 0, /* tp_print */
7549 0, /* tp_getattr */
7550 0, /* tp_setattr */
7551 0, /* tp_reserved */
7552 super_repr, /* tp_repr */
7553 0, /* tp_as_number */
7554 0, /* tp_as_sequence */
7555 0, /* tp_as_mapping */
7556 0, /* tp_hash */
7557 0, /* tp_call */
7558 0, /* tp_str */
7559 super_getattro, /* tp_getattro */
7560 0, /* tp_setattro */
7561 0, /* tp_as_buffer */
7562 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
7563 Py_TPFLAGS_BASETYPE, /* tp_flags */
7564 super_doc, /* tp_doc */
7565 super_traverse, /* tp_traverse */
7566 0, /* tp_clear */
7567 0, /* tp_richcompare */
7568 0, /* tp_weaklistoffset */
7569 0, /* tp_iter */
7570 0, /* tp_iternext */
7571 0, /* tp_methods */
7572 super_members, /* tp_members */
7573 0, /* tp_getset */
7574 0, /* tp_base */
7575 0, /* tp_dict */
7576 super_descr_get, /* tp_descr_get */
7577 0, /* tp_descr_set */
7578 0, /* tp_dictoffset */
7579 super_init, /* tp_init */
7580 PyType_GenericAlloc, /* tp_alloc */
7581 PyType_GenericNew, /* tp_new */
7582 PyObject_GC_Del, /* tp_free */
Guido van Rossum705f0f52001-08-24 16:47:00 +00007583};