blob: 9b3d1533e9379c3d395fa5e0fa39ad2ba3540671 [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{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000457 char *s;
Guido van Rossumc3542212001-08-16 09:18:56 +0000458
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000459 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
Victor Stinnerad14ccd2013-11-07 00:46:04 +0100460 PyObject *mod = _PyDict_GetItemId(type->tp_dict, &PyId___module__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000461 if (!mod) {
462 PyErr_Format(PyExc_AttributeError, "__module__");
463 return 0;
464 }
Serhiy Storchaka27ba8862016-05-25 16:14:55 +0300465 Py_INCREF(mod);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000466 return mod;
467 }
468 else {
Victor Stinnerad14ccd2013-11-07 00:46:04 +0100469 PyObject *name;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000470 s = strrchr(type->tp_name, '.');
471 if (s != NULL)
472 return PyUnicode_FromStringAndSize(
473 type->tp_name, (Py_ssize_t)(s - type->tp_name));
Victor Stinnerbd303c12013-11-07 23:07:29 +0100474 name = _PyUnicode_FromId(&PyId_builtins);
Victor Stinnerad14ccd2013-11-07 00:46:04 +0100475 Py_XINCREF(name);
476 return name;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000477 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000478}
479
Guido van Rossum3926a632001-09-25 16:25:58 +0000480static int
481type_set_module(PyTypeObject *type, PyObject *value, void *context)
482{
Benjamin Petersond9f23d22011-08-17 11:54:03 -0500483 if (!check_set_special_type_attr(type, value, "__module__"))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000484 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000485
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000486 PyType_Modified(type);
Christian Heimesa62da1d2008-01-12 19:39:10 +0000487
Victor Stinner3c1e4812012-03-26 22:10:51 +0200488 return _PyDict_SetItemId(type->tp_dict, &PyId___module__, value);
Guido van Rossum3926a632001-09-25 16:25:58 +0000489}
490
Tim Peters6d6c1a32001-08-02 04:15:00 +0000491static PyObject *
Christian Heimes9e7f1d22008-02-28 12:27:11 +0000492type_abstractmethods(PyTypeObject *type, void *context)
493{
Benjamin Petersonaec5fd12010-10-02 00:03:31 +0000494 PyObject *mod = NULL;
Benjamin Peterson84060b82010-10-03 02:13:39 +0000495 /* type itself has an __abstractmethods__ descriptor (this). Don't return
496 that. */
Benjamin Petersonaec5fd12010-10-02 00:03:31 +0000497 if (type != &PyType_Type)
Victor Stinner3688aa92013-11-06 18:59:18 +0100498 mod = _PyDict_GetItemId(type->tp_dict, &PyId___abstractmethods__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000499 if (!mod) {
Victor Stinner3688aa92013-11-06 18:59:18 +0100500 PyObject *message = _PyUnicode_FromId(&PyId___abstractmethods__);
501 if (message)
502 PyErr_SetObject(PyExc_AttributeError, message);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000503 return NULL;
504 }
Serhiy Storchaka27ba8862016-05-25 16:14:55 +0300505 Py_INCREF(mod);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000506 return mod;
Christian Heimes9e7f1d22008-02-28 12:27:11 +0000507}
508
509static int
510type_set_abstractmethods(PyTypeObject *type, PyObject *value, void *context)
511{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000512 /* __abstractmethods__ should only be set once on a type, in
513 abc.ABCMeta.__new__, so this function doesn't do anything
514 special to update subclasses.
515 */
Antoine Pitrou6f430e42012-08-15 23:18:25 +0200516 int abstract, res;
Benjamin Peterson477ba912011-01-12 15:34:01 +0000517 if (value != NULL) {
Antoine Pitrou6f430e42012-08-15 23:18:25 +0200518 abstract = PyObject_IsTrue(value);
519 if (abstract < 0)
520 return -1;
Victor Stinner3688aa92013-11-06 18:59:18 +0100521 res = _PyDict_SetItemId(type->tp_dict, &PyId___abstractmethods__, value);
Benjamin Peterson477ba912011-01-12 15:34:01 +0000522 }
523 else {
Antoine Pitrou6f430e42012-08-15 23:18:25 +0200524 abstract = 0;
Victor Stinner3688aa92013-11-06 18:59:18 +0100525 res = _PyDict_DelItemId(type->tp_dict, &PyId___abstractmethods__);
Benjamin Peterson477ba912011-01-12 15:34:01 +0000526 if (res && PyErr_ExceptionMatches(PyExc_KeyError)) {
Victor Stinner3688aa92013-11-06 18:59:18 +0100527 PyObject *message = _PyUnicode_FromId(&PyId___abstractmethods__);
528 if (message)
529 PyErr_SetObject(PyExc_AttributeError, message);
Benjamin Peterson477ba912011-01-12 15:34:01 +0000530 return -1;
531 }
532 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000533 if (res == 0) {
534 PyType_Modified(type);
Antoine Pitrou6f430e42012-08-15 23:18:25 +0200535 if (abstract)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000536 type->tp_flags |= Py_TPFLAGS_IS_ABSTRACT;
Antoine Pitrou6f430e42012-08-15 23:18:25 +0200537 else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000538 type->tp_flags &= ~Py_TPFLAGS_IS_ABSTRACT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000539 }
540 return res;
Christian Heimes9e7f1d22008-02-28 12:27:11 +0000541}
542
543static PyObject *
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000544type_get_bases(PyTypeObject *type, void *context)
545{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000546 Py_INCREF(type->tp_bases);
547 return type->tp_bases;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000548}
549
550static PyTypeObject *best_base(PyObject *);
Benjamin Peterson104b9e02015-02-05 22:29:14 -0500551static int mro_internal(PyTypeObject *, PyObject **);
Steve Dowerb4e20bb2015-02-06 08:50:23 -0800552Py_LOCAL_INLINE(int) type_is_subtype_base_chain(PyTypeObject *, PyTypeObject *);
Serhiy Storchakaef1585e2015-12-25 20:01:53 +0200553static int compatible_for_assignment(PyTypeObject *, PyTypeObject *, const char *);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000554static int add_subclass(PyTypeObject*, PyTypeObject*);
Benjamin Peterson104b9e02015-02-05 22:29:14 -0500555static int add_all_subclasses(PyTypeObject *type, PyObject *bases);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000556static void remove_subclass(PyTypeObject *, PyTypeObject *);
Antoine Pitrou84745ab2013-10-29 21:31:25 +0100557static void remove_all_subclasses(PyTypeObject *type, PyObject *bases);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000558static void update_all_slots(PyTypeObject *);
559
Guido van Rossum8d24ee92003-03-24 23:49:49 +0000560typedef int (*update_callback)(PyTypeObject *, void *);
561static int update_subclasses(PyTypeObject *type, PyObject *name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000562 update_callback callback, void *data);
Guido van Rossum8d24ee92003-03-24 23:49:49 +0000563static int recurse_down_subclasses(PyTypeObject *type, PyObject *name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000564 update_callback callback, void *data);
Benjamin Peterson104b9e02015-02-05 22:29:14 -0500565static PyObject *type_subclasses(PyTypeObject *type, PyObject *ignored);
Guido van Rossum8d24ee92003-03-24 23:49:49 +0000566
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000567static int
Benjamin Peterson104b9e02015-02-05 22:29:14 -0500568mro_hierarchy(PyTypeObject *type, PyObject *temp)
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000569{
Benjamin Peterson104b9e02015-02-05 22:29:14 -0500570 int res;
571 PyObject *new_mro, *old_mro;
572 PyObject *tuple;
573 PyObject *subclasses;
574 Py_ssize_t i, n;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000575
Benjamin Peterson104b9e02015-02-05 22:29:14 -0500576 res = mro_internal(type, &old_mro);
577 if (res <= 0)
578 /* error / reentrance */
579 return res;
580 new_mro = type->tp_mro;
Antoine Pitrou84745ab2013-10-29 21:31:25 +0100581
Benjamin Peterson104b9e02015-02-05 22:29:14 -0500582 if (old_mro != NULL)
583 tuple = PyTuple_Pack(3, type, new_mro, old_mro);
584 else
585 tuple = PyTuple_Pack(2, type, new_mro);
586
587 if (tuple != NULL)
588 res = PyList_Append(temp, tuple);
589 else
590 res = -1;
591 Py_XDECREF(tuple);
592
593 if (res < 0) {
594 type->tp_mro = old_mro;
595 Py_DECREF(new_mro);
596 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000597 }
Benjamin Peterson104b9e02015-02-05 22:29:14 -0500598 Py_XDECREF(old_mro);
599
600 /* Obtain a copy of subclasses list to iterate over.
601
602 Otherwise type->tp_subclasses might be altered
603 in the middle of the loop, for example, through a custom mro(),
604 by invoking type_set_bases on some subclass of the type
605 which in turn calls remove_subclass/add_subclass on this type.
606
607 Finally, this makes things simple avoiding the need to deal
608 with dictionary iterators and weak references.
609 */
610 subclasses = type_subclasses(type, NULL);
611 if (subclasses == NULL)
612 return -1;
613 n = PyList_GET_SIZE(subclasses);
614 for (i = 0; i < n; i++) {
615 PyTypeObject *subclass;
616 subclass = (PyTypeObject *)PyList_GET_ITEM(subclasses, i);
617 res = mro_hierarchy(subclass, temp);
618 if (res < 0)
619 break;
620 }
621 Py_DECREF(subclasses);
622
623 return res;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000624}
625
626static int
Benjamin Peterson104b9e02015-02-05 22:29:14 -0500627type_set_bases(PyTypeObject *type, PyObject *new_bases, void *context)
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000628{
Benjamin Peterson104b9e02015-02-05 22:29:14 -0500629 int res = 0;
630 PyObject *temp;
631 PyObject *old_bases;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000632 PyTypeObject *new_base, *old_base;
Benjamin Peterson104b9e02015-02-05 22:29:14 -0500633 Py_ssize_t i;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000634
Benjamin Peterson104b9e02015-02-05 22:29:14 -0500635 if (!check_set_special_type_attr(type, new_bases, "__bases__"))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000636 return -1;
Benjamin Peterson104b9e02015-02-05 22:29:14 -0500637 if (!PyTuple_Check(new_bases)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000638 PyErr_Format(PyExc_TypeError,
639 "can only assign tuple to %s.__bases__, not %s",
Benjamin Peterson104b9e02015-02-05 22:29:14 -0500640 type->tp_name, Py_TYPE(new_bases)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000641 return -1;
642 }
Benjamin Peterson104b9e02015-02-05 22:29:14 -0500643 if (PyTuple_GET_SIZE(new_bases) == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000644 PyErr_Format(PyExc_TypeError,
645 "can only assign non-empty tuple to %s.__bases__, not ()",
646 type->tp_name);
647 return -1;
648 }
Benjamin Peterson104b9e02015-02-05 22:29:14 -0500649 for (i = 0; i < PyTuple_GET_SIZE(new_bases); i++) {
650 PyObject *ob;
651 PyTypeObject *base;
652
653 ob = PyTuple_GET_ITEM(new_bases, i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000654 if (!PyType_Check(ob)) {
Benjamin Petersonb6af60c2012-04-01 18:49:54 -0400655 PyErr_Format(PyExc_TypeError,
Benjamin Peterson9ee601e2012-04-01 18:51:37 -0400656 "%s.__bases__ must be tuple of classes, not '%s'",
Benjamin Petersonb6af60c2012-04-01 18:49:54 -0400657 type->tp_name, Py_TYPE(ob)->tp_name);
658 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000659 }
Benjamin Peterson104b9e02015-02-05 22:29:14 -0500660
661 base = (PyTypeObject*)ob;
662 if (PyType_IsSubtype(base, type) ||
663 /* In case of reentering here again through a custom mro()
664 the above check is not enough since it relies on
665 base->tp_mro which would gonna be updated inside
666 mro_internal only upon returning from the mro().
667
668 However, base->tp_base has already been assigned (see
669 below), which in turn may cause an inheritance cycle
670 through tp_base chain. And this is definitely
671 not what you want to ever happen. */
672 (base->tp_mro != NULL && type_is_subtype_base_chain(base, type))) {
673
Benjamin Peterson3471bb62012-04-01 18:48:40 -0400674 PyErr_SetString(PyExc_TypeError,
675 "a __bases__ item causes an inheritance cycle");
676 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000677 }
678 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000679
Benjamin Peterson104b9e02015-02-05 22:29:14 -0500680 new_base = best_base(new_bases);
681 if (new_base == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000682 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000683
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000684 if (!compatible_for_assignment(type->tp_base, new_base, "__bases__"))
685 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000686
Benjamin Peterson104b9e02015-02-05 22:29:14 -0500687 Py_INCREF(new_bases);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000688 Py_INCREF(new_base);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000689
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000690 old_bases = type->tp_bases;
691 old_base = type->tp_base;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000692
Benjamin Peterson104b9e02015-02-05 22:29:14 -0500693 type->tp_bases = new_bases;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000694 type->tp_base = new_base;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000695
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000696 temp = PyList_New(0);
Benjamin Peterson104b9e02015-02-05 22:29:14 -0500697 if (temp == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000698 goto bail;
Benjamin Peterson104b9e02015-02-05 22:29:14 -0500699 if (mro_hierarchy(type, temp) < 0)
700 goto undo;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000701 Py_DECREF(temp);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000702
Benjamin Peterson104b9e02015-02-05 22:29:14 -0500703 /* Take no action in case if type->tp_bases has been replaced
704 through reentrance. */
705 if (type->tp_bases == new_bases) {
706 /* any base that was in __bases__ but now isn't, we
707 need to remove |type| from its tp_subclasses.
708 conversely, any class now in __bases__ that wasn't
709 needs to have |type| added to its subclasses. */
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000710
Benjamin Peterson104b9e02015-02-05 22:29:14 -0500711 /* for now, sod that: just remove from all old_bases,
712 add to all new_bases */
713 remove_all_subclasses(type, old_bases);
714 res = add_all_subclasses(type, new_bases);
715 update_all_slots(type);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000716 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000717
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000718 Py_DECREF(old_bases);
719 Py_DECREF(old_base);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000720
Benjamin Peterson104b9e02015-02-05 22:29:14 -0500721 return res;
722
723 undo:
724 for (i = PyList_GET_SIZE(temp) - 1; i >= 0; i--) {
725 PyTypeObject *cls;
726 PyObject *new_mro, *old_mro = NULL;
727
728 PyArg_UnpackTuple(PyList_GET_ITEM(temp, i),
729 "", 2, 3, &cls, &new_mro, &old_mro);
730 /* Do not rollback if cls has a newer version of MRO. */
731 if (cls->tp_mro == new_mro) {
732 Py_XINCREF(old_mro);
733 cls->tp_mro = old_mro;
734 Py_DECREF(new_mro);
735 }
736 }
737 Py_DECREF(temp);
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000738
739 bail:
Benjamin Peterson104b9e02015-02-05 22:29:14 -0500740 if (type->tp_bases == new_bases) {
741 assert(type->tp_base == new_base);
Michael W. Hudsone723e452003-08-07 14:58:10 +0000742
Benjamin Peterson104b9e02015-02-05 22:29:14 -0500743 type->tp_bases = old_bases;
744 type->tp_base = old_base;
745
746 Py_DECREF(new_bases);
747 Py_DECREF(new_base);
748 }
749 else {
750 Py_DECREF(old_bases);
751 Py_DECREF(old_base);
752 }
Tim Petersea7f75d2002-12-07 21:39:16 +0000753
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000754 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000755}
756
757static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000758type_dict(PyTypeObject *type, void *context)
759{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000760 if (type->tp_dict == NULL) {
761 Py_INCREF(Py_None);
762 return Py_None;
763 }
764 return PyDictProxy_New(type->tp_dict);
Guido van Rossum29ca26e1995-01-07 11:58:15 +0000765}
766
Tim Peters24008312002-03-17 18:56:20 +0000767static PyObject *
768type_get_doc(PyTypeObject *type, void *context)
769{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000770 PyObject *result;
Larry Hastings5c661892014-01-24 06:17:25 -0800771 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE) && type->tp_doc != NULL) {
Larry Hastings2623c8c2014-02-08 22:15:29 -0800772 return _PyType_GetDocFromInternalDoc(type->tp_name, type->tp_doc);
Larry Hastings5c661892014-01-24 06:17:25 -0800773 }
Victor Stinner3c1e4812012-03-26 22:10:51 +0200774 result = _PyDict_GetItemId(type->tp_dict, &PyId___doc__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000775 if (result == NULL) {
776 result = Py_None;
777 Py_INCREF(result);
778 }
779 else if (Py_TYPE(result)->tp_descr_get) {
780 result = Py_TYPE(result)->tp_descr_get(result, NULL,
781 (PyObject *)type);
782 }
783 else {
784 Py_INCREF(result);
785 }
786 return result;
Tim Peters24008312002-03-17 18:56:20 +0000787}
788
Larry Hastings5c661892014-01-24 06:17:25 -0800789static PyObject *
790type_get_text_signature(PyTypeObject *type, void *context)
791{
Larry Hastings2623c8c2014-02-08 22:15:29 -0800792 return _PyType_GetTextSignatureFromInternalDoc(type->tp_name, type->tp_doc);
Larry Hastings5c661892014-01-24 06:17:25 -0800793}
794
Benjamin Peterson01fc6cd2011-08-17 12:03:47 -0500795static int
796type_set_doc(PyTypeObject *type, PyObject *value, void *context)
797{
798 if (!check_set_special_type_attr(type, value, "__doc__"))
799 return -1;
800 PyType_Modified(type);
Victor Stinner3c1e4812012-03-26 22:10:51 +0200801 return _PyDict_SetItemId(type->tp_dict, &PyId___doc__, value);
Benjamin Peterson01fc6cd2011-08-17 12:03:47 -0500802}
803
Antoine Pitrouec569b72008-08-26 22:40:48 +0000804static PyObject *
805type___instancecheck__(PyObject *type, PyObject *inst)
806{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000807 switch (_PyObject_RealIsInstance(inst, type)) {
808 case -1:
809 return NULL;
810 case 0:
811 Py_RETURN_FALSE;
812 default:
813 Py_RETURN_TRUE;
814 }
Antoine Pitrouec569b72008-08-26 22:40:48 +0000815}
816
817
818static PyObject *
Antoine Pitrouec569b72008-08-26 22:40:48 +0000819type___subclasscheck__(PyObject *type, PyObject *inst)
820{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000821 switch (_PyObject_RealIsSubclass(inst, type)) {
822 case -1:
823 return NULL;
824 case 0:
825 Py_RETURN_FALSE;
826 default:
827 Py_RETURN_TRUE;
828 }
Antoine Pitrouec569b72008-08-26 22:40:48 +0000829}
830
Antoine Pitrouec569b72008-08-26 22:40:48 +0000831
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000832static PyGetSetDef type_getsets[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000833 {"__name__", (getter)type_name, (setter)type_set_name, NULL},
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100834 {"__qualname__", (getter)type_qualname, (setter)type_set_qualname, NULL},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000835 {"__bases__", (getter)type_get_bases, (setter)type_set_bases, NULL},
836 {"__module__", (getter)type_module, (setter)type_set_module, NULL},
837 {"__abstractmethods__", (getter)type_abstractmethods,
838 (setter)type_set_abstractmethods, NULL},
839 {"__dict__", (getter)type_dict, NULL, NULL},
Benjamin Peterson01fc6cd2011-08-17 12:03:47 -0500840 {"__doc__", (getter)type_get_doc, (setter)type_set_doc, NULL},
Larry Hastings5c661892014-01-24 06:17:25 -0800841 {"__text_signature__", (getter)type_get_text_signature, NULL, NULL},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000842 {0}
Tim Peters6d6c1a32001-08-02 04:15:00 +0000843};
844
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000845static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000846type_repr(PyTypeObject *type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000847{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000848 PyObject *mod, *name, *rtn;
Guido van Rossumc3542212001-08-16 09:18:56 +0000849
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000850 mod = type_module(type, NULL);
851 if (mod == NULL)
852 PyErr_Clear();
853 else if (!PyUnicode_Check(mod)) {
854 Py_DECREF(mod);
855 mod = NULL;
856 }
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100857 name = type_qualname(type, NULL);
Christian Heimesa0e7e412012-09-10 03:00:14 +0200858 if (name == NULL) {
859 Py_XDECREF(mod);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000860 return NULL;
Christian Heimesa0e7e412012-09-10 03:00:14 +0200861 }
Barry Warsaw7ce36942001-08-24 18:34:26 +0000862
Victor Stinnerbd303c12013-11-07 23:07:29 +0100863 if (mod != NULL && _PyUnicode_CompareWithId(mod, &PyId_builtins))
Benjamin Petersonab078e92016-07-13 21:13:29 -0700864 rtn = PyUnicode_FromFormat("<class '%U.%U'>", mod, name);
865 else
866 rtn = PyUnicode_FromFormat("<class '%s'>", type->tp_name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000867
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000868 Py_XDECREF(mod);
869 Py_DECREF(name);
870 return rtn;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000871}
872
Tim Peters6d6c1a32001-08-02 04:15:00 +0000873static PyObject *
874type_call(PyTypeObject *type, PyObject *args, PyObject *kwds)
875{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000876 PyObject *obj;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000877
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000878 if (type->tp_new == NULL) {
879 PyErr_Format(PyExc_TypeError,
880 "cannot create '%.100s' instances",
881 type->tp_name);
882 return NULL;
883 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000884
Victor Stinner33824f62013-08-26 14:05:19 +0200885#ifdef Py_DEBUG
886 /* type_call() must not be called with an exception set,
887 because it may clear it (directly or indirectly) and so the
Martin Panter9955a372015-10-07 10:26:23 +0000888 caller loses its exception */
Victor Stinner33824f62013-08-26 14:05:19 +0200889 assert(!PyErr_Occurred());
890#endif
891
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000892 obj = type->tp_new(type, args, kwds);
Victor Stinner99bb14b2015-09-03 12:16:49 +0200893 obj = _Py_CheckFunctionResult((PyObject*)type, obj, NULL);
894 if (obj == NULL)
895 return NULL;
896
897 /* Ugly exception: when the call was type(something),
898 don't call tp_init on the result. */
899 if (type == &PyType_Type &&
900 PyTuple_Check(args) && PyTuple_GET_SIZE(args) == 1 &&
901 (kwds == NULL ||
902 (PyDict_Check(kwds) && PyDict_Size(kwds) == 0)))
903 return obj;
904
905 /* If the returned object is not an instance of type,
906 it won't be initialized. */
907 if (!PyType_IsSubtype(Py_TYPE(obj), type))
908 return obj;
909
910 type = Py_TYPE(obj);
911 if (type->tp_init != NULL) {
912 int res = type->tp_init(obj, args, kwds);
913 if (res < 0) {
914 assert(PyErr_Occurred());
915 Py_DECREF(obj);
916 obj = NULL;
917 }
918 else {
919 assert(!PyErr_Occurred());
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000920 }
921 }
922 return obj;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000923}
924
925PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000926PyType_GenericAlloc(PyTypeObject *type, Py_ssize_t nitems)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000927{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000928 PyObject *obj;
929 const size_t size = _PyObject_VAR_SIZE(type, nitems+1);
930 /* note that we need to add one, for the sentinel */
Tim Peters406fe3b2001-10-06 19:04:01 +0000931
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000932 if (PyType_IS_GC(type))
933 obj = _PyObject_GC_Malloc(size);
934 else
935 obj = (PyObject *)PyObject_MALLOC(size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000936
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000937 if (obj == NULL)
938 return PyErr_NoMemory();
Tim Peters406fe3b2001-10-06 19:04:01 +0000939
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000940 memset(obj, '\0', size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000941
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000942 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
943 Py_INCREF(type);
Tim Peters406fe3b2001-10-06 19:04:01 +0000944
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000945 if (type->tp_itemsize == 0)
Christian Heimesd3afe782013-12-04 09:27:47 +0100946 (void)PyObject_INIT(obj, type);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000947 else
948 (void) PyObject_INIT_VAR((PyVarObject *)obj, type, nitems);
Tim Peters406fe3b2001-10-06 19:04:01 +0000949
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000950 if (PyType_IS_GC(type))
951 _PyObject_GC_TRACK(obj);
952 return obj;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000953}
954
955PyObject *
956PyType_GenericNew(PyTypeObject *type, PyObject *args, PyObject *kwds)
957{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000958 return type->tp_alloc(type, 0);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000959}
960
Guido van Rossum9475a232001-10-05 20:51:39 +0000961/* Helpers for subtyping */
962
963static int
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000964traverse_slots(PyTypeObject *type, PyObject *self, visitproc visit, void *arg)
965{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000966 Py_ssize_t i, n;
967 PyMemberDef *mp;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000968
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000969 n = Py_SIZE(type);
970 mp = PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type);
971 for (i = 0; i < n; i++, mp++) {
972 if (mp->type == T_OBJECT_EX) {
973 char *addr = (char *)self + mp->offset;
974 PyObject *obj = *(PyObject **)addr;
975 if (obj != NULL) {
976 int err = visit(obj, arg);
977 if (err)
978 return err;
979 }
980 }
981 }
982 return 0;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000983}
984
985static int
Guido van Rossum9475a232001-10-05 20:51:39 +0000986subtype_traverse(PyObject *self, visitproc visit, void *arg)
987{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000988 PyTypeObject *type, *base;
989 traverseproc basetraverse;
Guido van Rossum9475a232001-10-05 20:51:39 +0000990
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000991 /* Find the nearest base with a different tp_traverse,
992 and traverse slots while we're at it */
993 type = Py_TYPE(self);
994 base = type;
995 while ((basetraverse = base->tp_traverse) == subtype_traverse) {
996 if (Py_SIZE(base)) {
997 int err = traverse_slots(base, self, visit, arg);
998 if (err)
999 return err;
1000 }
1001 base = base->tp_base;
1002 assert(base);
1003 }
Guido van Rossum9475a232001-10-05 20:51:39 +00001004
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001005 if (type->tp_dictoffset != base->tp_dictoffset) {
1006 PyObject **dictptr = _PyObject_GetDictPtr(self);
1007 if (dictptr && *dictptr)
1008 Py_VISIT(*dictptr);
1009 }
Guido van Rossum9475a232001-10-05 20:51:39 +00001010
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001011 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
1012 /* For a heaptype, the instances count as references
1013 to the type. Traverse the type so the collector
1014 can find cycles involving this link. */
1015 Py_VISIT(type);
Guido van Rossuma3862092002-06-10 15:24:42 +00001016
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001017 if (basetraverse)
1018 return basetraverse(self, visit, arg);
1019 return 0;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001020}
1021
1022static void
1023clear_slots(PyTypeObject *type, PyObject *self)
1024{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001025 Py_ssize_t i, n;
1026 PyMemberDef *mp;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001027
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001028 n = Py_SIZE(type);
1029 mp = PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type);
1030 for (i = 0; i < n; i++, mp++) {
1031 if (mp->type == T_OBJECT_EX && !(mp->flags & READONLY)) {
1032 char *addr = (char *)self + mp->offset;
1033 PyObject *obj = *(PyObject **)addr;
1034 if (obj != NULL) {
1035 *(PyObject **)addr = NULL;
1036 Py_DECREF(obj);
1037 }
1038 }
1039 }
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001040}
1041
1042static int
1043subtype_clear(PyObject *self)
1044{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001045 PyTypeObject *type, *base;
1046 inquiry baseclear;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001047
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001048 /* Find the nearest base with a different tp_clear
1049 and clear slots while we're at it */
1050 type = Py_TYPE(self);
1051 base = type;
1052 while ((baseclear = base->tp_clear) == subtype_clear) {
1053 if (Py_SIZE(base))
1054 clear_slots(base, self);
1055 base = base->tp_base;
1056 assert(base);
1057 }
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001058
Benjamin Peterson52c42432012-03-07 18:41:11 -06001059 /* Clear the instance dict (if any), to break cycles involving only
1060 __dict__ slots (as in the case 'self.__dict__ is self'). */
1061 if (type->tp_dictoffset != base->tp_dictoffset) {
1062 PyObject **dictptr = _PyObject_GetDictPtr(self);
1063 if (dictptr && *dictptr)
1064 Py_CLEAR(*dictptr);
1065 }
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001066
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001067 if (baseclear)
1068 return baseclear(self);
1069 return 0;
Guido van Rossum9475a232001-10-05 20:51:39 +00001070}
Tim Peters6d6c1a32001-08-02 04:15:00 +00001071
1072static void
1073subtype_dealloc(PyObject *self)
1074{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001075 PyTypeObject *type, *base;
1076 destructor basedealloc;
Antoine Pitrou56cd62c2012-09-06 00:59:49 +02001077 PyThreadState *tstate = PyThreadState_GET();
Antoine Pitrou796564c2013-07-30 19:59:21 +02001078 int has_finalizer;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001079
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001080 /* Extract the type; we expect it to be a heap type */
1081 type = Py_TYPE(self);
1082 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001083
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001084 /* Test whether the type has GC exactly once */
Guido van Rossum22b13872002-08-06 21:41:44 +00001085
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001086 if (!PyType_IS_GC(type)) {
1087 /* It's really rare to find a dynamic type that doesn't have
1088 GC; it can only happen when deriving from 'object' and not
1089 adding any slots or instance variables. This allows
1090 certain simplifications: there's no need to call
1091 clear_slots(), or DECREF the dict, or clear weakrefs. */
Guido van Rossum22b13872002-08-06 21:41:44 +00001092
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001093 /* Maybe call finalizer; exit early if resurrected */
Antoine Pitrou796564c2013-07-30 19:59:21 +02001094 if (type->tp_finalize) {
1095 if (PyObject_CallFinalizerFromDealloc(self) < 0)
1096 return;
1097 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001098 if (type->tp_del) {
1099 type->tp_del(self);
1100 if (self->ob_refcnt > 0)
1101 return;
1102 }
Guido van Rossum22b13872002-08-06 21:41:44 +00001103
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001104 /* Find the nearest base with a different tp_dealloc */
1105 base = type;
1106 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
1107 assert(Py_SIZE(base) == 0);
1108 base = base->tp_base;
1109 assert(base);
1110 }
Guido van Rossum22b13872002-08-06 21:41:44 +00001111
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001112 /* Extract the type again; tp_del may have changed it */
1113 type = Py_TYPE(self);
Benjamin Peterson193152c2009-04-25 01:08:45 +00001114
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001115 /* Call the base tp_dealloc() */
1116 assert(basedealloc);
1117 basedealloc(self);
Guido van Rossum22b13872002-08-06 21:41:44 +00001118
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001119 /* Can't reference self beyond this point */
1120 Py_DECREF(type);
Guido van Rossum22b13872002-08-06 21:41:44 +00001121
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001122 /* Done */
1123 return;
1124 }
Guido van Rossum22b13872002-08-06 21:41:44 +00001125
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001126 /* We get here only if the type has GC */
Guido van Rossum22b13872002-08-06 21:41:44 +00001127
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001128 /* UnTrack and re-Track around the trashcan macro, alas */
1129 /* See explanation at end of function for full disclosure */
1130 PyObject_GC_UnTrack(self);
1131 ++_PyTrash_delete_nesting;
Antoine Pitrou56cd62c2012-09-06 00:59:49 +02001132 ++ tstate->trash_delete_nesting;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001133 Py_TRASHCAN_SAFE_BEGIN(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 /* DO NOT restore GC tracking at this point. weakref callbacks
1137 * (if any, and whether directly here or indirectly in something we
1138 * call) may trigger GC, and if self is tracked at that point, it
1139 * will look like trash to GC and GC will try to delete self again.
1140 */
Guido van Rossum22b13872002-08-06 21:41:44 +00001141
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001142 /* Find the nearest base with a different tp_dealloc */
1143 base = type;
Brett Cannonb94767f2011-02-22 20:15:44 +00001144 while ((/*basedealloc =*/ base->tp_dealloc) == subtype_dealloc) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001145 base = base->tp_base;
1146 assert(base);
1147 }
Guido van Rossum14227b42001-12-06 02:35:58 +00001148
Antoine Pitrou796564c2013-07-30 19:59:21 +02001149 has_finalizer = type->tp_finalize || type->tp_del;
Guido van Rossum59195fd2003-06-13 20:54:40 +00001150
Antoine Pitrou796564c2013-07-30 19:59:21 +02001151 /* Maybe call finalizer; exit early if resurrected */
1152 if (has_finalizer)
1153 _PyObject_GC_TRACK(self);
1154
1155 if (type->tp_finalize) {
1156 if (PyObject_CallFinalizerFromDealloc(self) < 0) {
1157 /* Resurrected */
1158 goto endlabel;
1159 }
1160 }
1161 /* If we added a weaklist, we clear it. Do this *before* calling
1162 tp_del, clearing slots, or clearing the instance dict. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001163 if (type->tp_weaklistoffset && !base->tp_weaklistoffset)
1164 PyObject_ClearWeakRefs(self);
Guido van Rossum1987c662003-05-29 14:29:23 +00001165
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001166 if (type->tp_del) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001167 type->tp_del(self);
Antoine Pitrou796564c2013-07-30 19:59:21 +02001168 if (self->ob_refcnt > 0) {
1169 /* Resurrected */
1170 goto endlabel;
1171 }
1172 }
1173 if (has_finalizer) {
1174 _PyObject_GC_UNTRACK(self);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001175 /* New weakrefs could be created during the finalizer call.
Antoine Pitrou796564c2013-07-30 19:59:21 +02001176 If this occurs, clear them out without calling their
1177 finalizers since they might rely on part of the object
1178 being finalized that has already been destroyed. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001179 if (type->tp_weaklistoffset && !base->tp_weaklistoffset) {
1180 /* Modeled after GET_WEAKREFS_LISTPTR() */
1181 PyWeakReference **list = (PyWeakReference **) \
1182 PyObject_GET_WEAKREFS_LISTPTR(self);
1183 while (*list)
1184 _PyWeakref_ClearRef(*list);
1185 }
1186 }
Guido van Rossum1987c662003-05-29 14:29:23 +00001187
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001188 /* Clear slots up to the nearest base with a different tp_dealloc */
1189 base = type;
1190 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
1191 if (Py_SIZE(base))
1192 clear_slots(base, self);
1193 base = base->tp_base;
1194 assert(base);
1195 }
Guido van Rossum59195fd2003-06-13 20:54:40 +00001196
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001197 /* If we added a dict, DECREF it */
1198 if (type->tp_dictoffset && !base->tp_dictoffset) {
1199 PyObject **dictptr = _PyObject_GetDictPtr(self);
1200 if (dictptr != NULL) {
1201 PyObject *dict = *dictptr;
1202 if (dict != NULL) {
1203 Py_DECREF(dict);
1204 *dictptr = NULL;
1205 }
1206 }
1207 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001208
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001209 /* Extract the type again; tp_del may have changed it */
1210 type = Py_TYPE(self);
Benjamin Peterson193152c2009-04-25 01:08:45 +00001211
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001212 /* Call the base tp_dealloc(); first retrack self if
1213 * basedealloc knows about gc.
1214 */
1215 if (PyType_IS_GC(base))
1216 _PyObject_GC_TRACK(self);
1217 assert(basedealloc);
1218 basedealloc(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001219
Benjamin Peterson9d4cbcc2015-01-30 13:33:42 -05001220 /* Can't reference self beyond this point. It's possible tp_del switched
1221 our type from a HEAPTYPE to a non-HEAPTYPE, so be careful about
1222 reference counting. */
1223 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
1224 Py_DECREF(type);
Guido van Rossum22b13872002-08-06 21:41:44 +00001225
Guido van Rossum0906e072002-08-07 20:42:09 +00001226 endlabel:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001227 ++_PyTrash_delete_nesting;
Antoine Pitrou56cd62c2012-09-06 00:59:49 +02001228 ++ tstate->trash_delete_nesting;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001229 Py_TRASHCAN_SAFE_END(self);
1230 --_PyTrash_delete_nesting;
Antoine Pitrou56cd62c2012-09-06 00:59:49 +02001231 -- tstate->trash_delete_nesting;
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001232
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001233 /* Explanation of the weirdness around the trashcan macros:
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001234
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001235 Q. What do the trashcan macros do?
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001236
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001237 A. Read the comment titled "Trashcan mechanism" in object.h.
1238 For one, this explains why there must be a call to GC-untrack
1239 before the trashcan begin macro. Without understanding the
1240 trashcan code, the answers to the following questions don't make
1241 sense.
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001242
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001243 Q. Why do we GC-untrack before the trashcan and then immediately
1244 GC-track again afterward?
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001245
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001246 A. In the case that the base class is GC-aware, the base class
1247 probably GC-untracks the object. If it does that using the
1248 UNTRACK macro, this will crash when the object is already
1249 untracked. Because we don't know what the base class does, the
1250 only safe thing is to make sure the object is tracked when we
1251 call the base class dealloc. But... The trashcan begin macro
1252 requires that the object is *untracked* before it is called. So
1253 the dance becomes:
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001254
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001255 GC untrack
1256 trashcan begin
1257 GC track
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001258
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001259 Q. Why did the last question say "immediately GC-track again"?
1260 It's nowhere near immediately.
Tim Petersf7f9e992003-11-13 21:59:32 +00001261
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001262 A. Because the code *used* to re-track immediately. Bad Idea.
1263 self has a refcount of 0, and if gc ever gets its hands on it
1264 (which can happen if any weakref callback gets invoked), it
1265 looks like trash to gc too, and gc also tries to delete self
Ezio Melotti13925002011-03-16 11:05:33 +02001266 then. But we're already deleting self. Double deallocation is
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001267 a subtle disaster.
Tim Petersf7f9e992003-11-13 21:59:32 +00001268
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001269 Q. Why the bizarre (net-zero) manipulation of
1270 _PyTrash_delete_nesting around the trashcan macros?
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001271
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001272 A. Some base classes (e.g. list) also use the trashcan mechanism.
1273 The following scenario used to be possible:
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001274
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001275 - suppose the trashcan level is one below the trashcan limit
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001276
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001277 - subtype_dealloc() is called
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001278
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001279 - the trashcan limit is not yet reached, so the trashcan level
1280 is incremented and the code between trashcan begin and end is
1281 executed
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001282
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001283 - this destroys much of the object's contents, including its
1284 slots and __dict__
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001285
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001286 - basedealloc() is called; this is really list_dealloc(), or
1287 some other type which also uses the trashcan macros
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001288
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001289 - the trashcan limit is now reached, so the object is put on the
1290 trashcan's to-be-deleted-later list
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001291
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001292 - basedealloc() returns
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001293
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001294 - subtype_dealloc() decrefs the object's type
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001295
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001296 - subtype_dealloc() returns
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001297
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001298 - later, the trashcan code starts deleting the objects from its
1299 to-be-deleted-later list
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001300
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001301 - subtype_dealloc() is called *AGAIN* for the same object
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001302
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001303 - at the very least (if the destroyed slots and __dict__ don't
1304 cause problems) the object's type gets decref'ed a second
1305 time, which is *BAD*!!!
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001306
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001307 The remedy is to make sure that if the code between trashcan
1308 begin and end in subtype_dealloc() is called, the code between
1309 trashcan begin and end in basedealloc() will also be called.
1310 This is done by decrementing the level after passing into the
1311 trashcan block, and incrementing it just before leaving the
1312 block.
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001313
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001314 But now it's possible that a chain of objects consisting solely
1315 of objects whose deallocator is subtype_dealloc() will defeat
1316 the trashcan mechanism completely: the decremented level means
1317 that the effective level never reaches the limit. Therefore, we
1318 *increment* the level *before* entering the trashcan block, and
1319 matchingly decrement it after leaving. This means the trashcan
1320 code will trigger a little early, but that's no big deal.
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001321
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001322 Q. Are there any live examples of code in need of all this
1323 complexity?
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001324
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001325 A. Yes. See SF bug 668433 for code that crashed (when Python was
1326 compiled in debug mode) before the trashcan level manipulations
1327 were added. For more discussion, see SF patches 581742, 575073
1328 and bug 574207.
1329 */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001330}
1331
Jeremy Hylton938ace62002-07-17 16:30:39 +00001332static PyTypeObject *solid_base(PyTypeObject *type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001333
Tim Peters6d6c1a32001-08-02 04:15:00 +00001334/* type test with subclassing support */
1335
Benjamin Peterson104b9e02015-02-05 22:29:14 -05001336Py_LOCAL_INLINE(int)
1337type_is_subtype_base_chain(PyTypeObject *a, PyTypeObject *b)
1338{
1339 do {
1340 if (a == b)
1341 return 1;
1342 a = a->tp_base;
1343 } while (a != NULL);
1344
1345 return (b == &PyBaseObject_Type);
1346}
1347
Tim Peters6d6c1a32001-08-02 04:15:00 +00001348int
1349PyType_IsSubtype(PyTypeObject *a, PyTypeObject *b)
1350{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001351 PyObject *mro;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001352
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001353 mro = a->tp_mro;
1354 if (mro != NULL) {
1355 /* Deal with multiple inheritance without recursion
1356 by walking the MRO tuple */
1357 Py_ssize_t i, n;
1358 assert(PyTuple_Check(mro));
1359 n = PyTuple_GET_SIZE(mro);
1360 for (i = 0; i < n; i++) {
1361 if (PyTuple_GET_ITEM(mro, i) == (PyObject *)b)
1362 return 1;
1363 }
1364 return 0;
1365 }
Benjamin Peterson104b9e02015-02-05 22:29:14 -05001366 else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001367 /* a is not completely initilized yet; follow tp_base */
Benjamin Peterson104b9e02015-02-05 22:29:14 -05001368 return type_is_subtype_base_chain(a, b);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001369}
1370
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001371/* Internal routines to do a method lookup in the type
Guido van Rossum60718732001-08-28 17:47:51 +00001372 without looking in the instance dictionary
1373 (so we can't use PyObject_GetAttr) but still binding
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001374 it to the instance. The arguments are the object,
Guido van Rossum60718732001-08-28 17:47:51 +00001375 the method name as a C string, and the address of a
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001376 static variable used to cache the interned Python string.
1377
1378 Two variants:
1379
1380 - lookup_maybe() returns NULL without raising an exception
1381 when the _PyType_Lookup() call fails;
1382
1383 - lookup_method() always raises an exception upon errors.
Benjamin Peterson224205f2009-05-08 03:25:19 +00001384
1385 - _PyObject_LookupSpecial() exported for the benefit of other places.
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001386*/
Guido van Rossum60718732001-08-28 17:47:51 +00001387
1388static PyObject *
Benjamin Petersonce798522012-01-22 11:24:29 -05001389lookup_maybe(PyObject *self, _Py_Identifier *attrid)
Guido van Rossum60718732001-08-28 17:47:51 +00001390{
Victor Stinner3c1e4812012-03-26 22:10:51 +02001391 PyObject *res;
Guido van Rossum60718732001-08-28 17:47:51 +00001392
Victor Stinner3c1e4812012-03-26 22:10:51 +02001393 res = _PyType_LookupId(Py_TYPE(self), attrid);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001394 if (res != NULL) {
1395 descrgetfunc f;
1396 if ((f = Py_TYPE(res)->tp_descr_get) == NULL)
1397 Py_INCREF(res);
1398 else
1399 res = f(res, self, (PyObject *)(Py_TYPE(self)));
1400 }
1401 return res;
Guido van Rossum60718732001-08-28 17:47:51 +00001402}
1403
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001404static PyObject *
Benjamin Petersonce798522012-01-22 11:24:29 -05001405lookup_method(PyObject *self, _Py_Identifier *attrid)
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001406{
Benjamin Petersonce798522012-01-22 11:24:29 -05001407 PyObject *res = lookup_maybe(self, attrid);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001408 if (res == NULL && !PyErr_Occurred())
Benjamin Petersonce798522012-01-22 11:24:29 -05001409 PyErr_SetObject(PyExc_AttributeError, attrid->object);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001410 return res;
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001411}
1412
Benjamin Peterson224205f2009-05-08 03:25:19 +00001413PyObject *
Benjamin Petersonce798522012-01-22 11:24:29 -05001414_PyObject_LookupSpecial(PyObject *self, _Py_Identifier *attrid)
Benjamin Peterson224205f2009-05-08 03:25:19 +00001415{
Benjamin Petersonce798522012-01-22 11:24:29 -05001416 return lookup_maybe(self, attrid);
Benjamin Peterson224205f2009-05-08 03:25:19 +00001417}
1418
Guido van Rossum2730b132001-08-28 18:22:14 +00001419/* A variation of PyObject_CallMethod that uses lookup_method()
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001420 instead of PyObject_GetAttrString(). This uses the same convention
Guido van Rossum2730b132001-08-28 18:22:14 +00001421 as lookup_method to cache the interned name string object. */
1422
Neil Schemenauerf23473f2001-10-21 22:28:58 +00001423static PyObject *
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001424call_method(PyObject *o, _Py_Identifier *nameid, const char *format, ...)
Guido van Rossum2730b132001-08-28 18:22:14 +00001425{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001426 va_list va;
Victor Stinnerf736c262016-08-19 18:05:37 +02001427 PyObject *func = NULL, *retval;
Guido van Rossum2730b132001-08-28 18:22:14 +00001428
Benjamin Petersonce798522012-01-22 11:24:29 -05001429 func = lookup_maybe(o, nameid);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001430 if (func == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001431 if (!PyErr_Occurred())
Benjamin Petersonce798522012-01-22 11:24:29 -05001432 PyErr_SetObject(PyExc_AttributeError, nameid->object);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001433 return NULL;
1434 }
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001435
Victor Stinner94463c92016-08-19 18:01:41 +02001436 if (format && *format) {
Victor Stinnerf736c262016-08-19 18:05:37 +02001437 PyObject *args;
1438
Victor Stinner94463c92016-08-19 18:01:41 +02001439 va_start(va, format);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001440 args = Py_VaBuildValue(format, va);
Victor Stinner94463c92016-08-19 18:01:41 +02001441 va_end(va);
Victor Stinnerf736c262016-08-19 18:05:37 +02001442
1443 if (args == NULL) {
1444 Py_DECREF(func);
1445 return NULL;
1446 }
1447 assert(PyTuple_Check(args));
1448
1449 retval = PyObject_Call(func, args, NULL);
1450 Py_DECREF(args);
Victor Stinner94463c92016-08-19 18:01:41 +02001451 }
1452 else {
Victor Stinner559bb6a2016-08-22 22:48:54 +02001453 retval = _PyObject_CallNoArg(func);
Victor Stinnerd925bd52016-08-19 17:51:49 +02001454 }
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001455
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001456 Py_DECREF(func);
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001457
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001458 return retval;
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001459}
1460
1461/* Clone of call_method() that returns NotImplemented when the lookup fails. */
1462
Neil Schemenauerf23473f2001-10-21 22:28:58 +00001463static PyObject *
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001464call_maybe(PyObject *o, _Py_Identifier *nameid, const char *format, ...)
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001465{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001466 va_list va;
Victor Stinnerf736c262016-08-19 18:05:37 +02001467 PyObject *func = NULL, *retval;
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001468
Benjamin Petersonce798522012-01-22 11:24:29 -05001469 func = lookup_maybe(o, nameid);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001470 if (func == NULL) {
Brian Curtindfc80e32011-08-10 20:28:54 -05001471 if (!PyErr_Occurred())
1472 Py_RETURN_NOTIMPLEMENTED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001473 return NULL;
1474 }
Guido van Rossum2730b132001-08-28 18:22:14 +00001475
Victor Stinner94463c92016-08-19 18:01:41 +02001476 if (format && *format) {
Victor Stinnerf736c262016-08-19 18:05:37 +02001477 PyObject *args;
1478
Victor Stinner94463c92016-08-19 18:01:41 +02001479 va_start(va, format);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001480 args = Py_VaBuildValue(format, va);
Victor Stinner94463c92016-08-19 18:01:41 +02001481 va_end(va);
Victor Stinnerf736c262016-08-19 18:05:37 +02001482
1483 if (args == NULL) {
1484 Py_DECREF(func);
1485 return NULL;
1486 }
1487 assert(PyTuple_Check(args));
1488
1489 retval = PyObject_Call(func, args, NULL);
1490 Py_DECREF(args);
Victor Stinner94463c92016-08-19 18:01:41 +02001491 }
1492 else {
Victor Stinner559bb6a2016-08-22 22:48:54 +02001493 retval = _PyObject_CallNoArg(func);
Victor Stinner6902ddf2016-08-19 17:58:12 +02001494 }
Guido van Rossum2730b132001-08-28 18:22:14 +00001495
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001496 Py_DECREF(func);
Guido van Rossum2730b132001-08-28 18:22:14 +00001497
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001498 return retval;
Guido van Rossum2730b132001-08-28 18:22:14 +00001499}
1500
Tim Petersea7f75d2002-12-07 21:39:16 +00001501/*
Guido van Rossum1f121312002-11-14 19:49:16 +00001502 Method resolution order algorithm C3 described in
1503 "A Monotonic Superclass Linearization for Dylan",
1504 by Kim Barrett, Bob Cassel, Paul Haahr,
Tim Petersea7f75d2002-12-07 21:39:16 +00001505 David A. Moon, Keith Playford, and P. Tucker Withington.
Guido van Rossum1f121312002-11-14 19:49:16 +00001506 (OOPSLA 1996)
1507
Guido van Rossum98f33732002-11-25 21:36:54 +00001508 Some notes about the rules implied by C3:
1509
Tim Petersea7f75d2002-12-07 21:39:16 +00001510 No duplicate bases.
Guido van Rossum98f33732002-11-25 21:36:54 +00001511 It isn't legal to repeat a class in a list of base classes.
1512
1513 The next three properties are the 3 constraints in "C3".
1514
Martin Panter69332c12016-08-04 13:07:31 +00001515 Local precedence order.
Guido van Rossum98f33732002-11-25 21:36:54 +00001516 If A precedes B in C's MRO, then A will precede B in the MRO of all
1517 subclasses of C.
1518
1519 Monotonicity.
1520 The MRO of a class must be an extension without reordering of the
1521 MRO of each of its superclasses.
1522
1523 Extended Precedence Graph (EPG).
1524 Linearization is consistent if there is a path in the EPG from
1525 each class to all its successors in the linearization. See
1526 the paper for definition of EPG.
Guido van Rossum1f121312002-11-14 19:49:16 +00001527 */
1528
Tim Petersea7f75d2002-12-07 21:39:16 +00001529static int
Guido van Rossum1f121312002-11-14 19:49:16 +00001530tail_contains(PyObject *list, int whence, PyObject *o) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001531 Py_ssize_t j, size;
1532 size = PyList_GET_SIZE(list);
Guido van Rossum1f121312002-11-14 19:49:16 +00001533
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001534 for (j = whence+1; j < size; j++) {
1535 if (PyList_GET_ITEM(list, j) == o)
1536 return 1;
1537 }
1538 return 0;
Guido van Rossum1f121312002-11-14 19:49:16 +00001539}
1540
Guido van Rossum98f33732002-11-25 21:36:54 +00001541static PyObject *
1542class_name(PyObject *cls)
1543{
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001544 PyObject *name = _PyObject_GetAttrId(cls, &PyId___name__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001545 if (name == NULL) {
1546 PyErr_Clear();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001547 name = PyObject_Repr(cls);
1548 }
1549 if (name == NULL)
1550 return NULL;
1551 if (!PyUnicode_Check(name)) {
1552 Py_DECREF(name);
1553 return NULL;
1554 }
1555 return name;
Guido van Rossum98f33732002-11-25 21:36:54 +00001556}
1557
1558static int
1559check_duplicates(PyObject *list)
1560{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001561 Py_ssize_t i, j, n;
1562 /* Let's use a quadratic time algorithm,
1563 assuming that the bases lists is short.
1564 */
1565 n = PyList_GET_SIZE(list);
1566 for (i = 0; i < n; i++) {
1567 PyObject *o = PyList_GET_ITEM(list, i);
1568 for (j = i + 1; j < n; j++) {
1569 if (PyList_GET_ITEM(list, j) == o) {
1570 o = class_name(o);
1571 if (o != NULL) {
1572 PyErr_Format(PyExc_TypeError,
1573 "duplicate base class %U",
1574 o);
1575 Py_DECREF(o);
1576 } else {
1577 PyErr_SetString(PyExc_TypeError,
1578 "duplicate base class");
1579 }
1580 return -1;
1581 }
1582 }
1583 }
1584 return 0;
Guido van Rossum98f33732002-11-25 21:36:54 +00001585}
1586
1587/* Raise a TypeError for an MRO order disagreement.
1588
1589 It's hard to produce a good error message. In the absence of better
1590 insight into error reporting, report the classes that were candidates
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001591 to be put next into the MRO. There is some conflict between the
Guido van Rossum98f33732002-11-25 21:36:54 +00001592 order in which they should be put in the MRO, but it's hard to
1593 diagnose what constraint can't be satisfied.
1594*/
1595
1596static void
1597set_mro_error(PyObject *to_merge, int *remain)
1598{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001599 Py_ssize_t i, n, off, to_merge_size;
1600 char buf[1000];
1601 PyObject *k, *v;
1602 PyObject *set = PyDict_New();
1603 if (!set) return;
Guido van Rossum98f33732002-11-25 21:36:54 +00001604
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001605 to_merge_size = PyList_GET_SIZE(to_merge);
1606 for (i = 0; i < to_merge_size; i++) {
1607 PyObject *L = PyList_GET_ITEM(to_merge, i);
1608 if (remain[i] < PyList_GET_SIZE(L)) {
1609 PyObject *c = PyList_GET_ITEM(L, remain[i]);
1610 if (PyDict_SetItem(set, c, Py_None) < 0) {
1611 Py_DECREF(set);
1612 return;
1613 }
1614 }
1615 }
1616 n = PyDict_Size(set);
Guido van Rossum98f33732002-11-25 21:36:54 +00001617
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001618 off = PyOS_snprintf(buf, sizeof(buf), "Cannot create a \
Raymond Hettingerf394df42003-04-06 19:13:41 +00001619consistent method resolution\norder (MRO) for bases");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001620 i = 0;
1621 while (PyDict_Next(set, &i, &k, &v) && (size_t)off < sizeof(buf)) {
1622 PyObject *name = class_name(k);
Victor Stinnere5f99f32010-05-19 01:42:46 +00001623 char *name_str;
1624 if (name != NULL) {
1625 name_str = _PyUnicode_AsString(name);
1626 if (name_str == NULL)
Victor Stinnerba644a62010-05-19 01:50:45 +00001627 name_str = "?";
Victor Stinnere5f99f32010-05-19 01:42:46 +00001628 } else
Victor Stinnerba644a62010-05-19 01:50:45 +00001629 name_str = "?";
Victor Stinnere5f99f32010-05-19 01:42:46 +00001630 off += PyOS_snprintf(buf + off, sizeof(buf) - off, " %s", name_str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001631 Py_XDECREF(name);
1632 if (--n && (size_t)(off+1) < sizeof(buf)) {
1633 buf[off++] = ',';
1634 buf[off] = '\0';
1635 }
1636 }
1637 PyErr_SetString(PyExc_TypeError, buf);
1638 Py_DECREF(set);
Guido van Rossum98f33732002-11-25 21:36:54 +00001639}
1640
Tim Petersea7f75d2002-12-07 21:39:16 +00001641static int
Benjamin Peterson104b9e02015-02-05 22:29:14 -05001642pmerge(PyObject *acc, PyObject* to_merge)
1643{
1644 int res = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001645 Py_ssize_t i, j, to_merge_size, empty_cnt;
1646 int *remain;
Tim Petersea7f75d2002-12-07 21:39:16 +00001647
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001648 to_merge_size = PyList_GET_SIZE(to_merge);
Guido van Rossum1f121312002-11-14 19:49:16 +00001649
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001650 /* remain stores an index into each sublist of to_merge.
1651 remain[i] is the index of the next base in to_merge[i]
1652 that is not included in acc.
1653 */
1654 remain = (int *)PyMem_MALLOC(SIZEOF_INT*to_merge_size);
Victor Stinnera41f0852013-07-12 00:42:14 +02001655 if (remain == NULL) {
1656 PyErr_NoMemory();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001657 return -1;
Victor Stinnera41f0852013-07-12 00:42:14 +02001658 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001659 for (i = 0; i < to_merge_size; i++)
1660 remain[i] = 0;
Guido van Rossum1f121312002-11-14 19:49:16 +00001661
1662 again:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001663 empty_cnt = 0;
1664 for (i = 0; i < to_merge_size; i++) {
1665 PyObject *candidate;
Tim Petersea7f75d2002-12-07 21:39:16 +00001666
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001667 PyObject *cur_list = PyList_GET_ITEM(to_merge, i);
Guido van Rossum1f121312002-11-14 19:49:16 +00001668
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001669 if (remain[i] >= PyList_GET_SIZE(cur_list)) {
1670 empty_cnt++;
1671 continue;
1672 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001673
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001674 /* Choose next candidate for MRO.
Guido van Rossum98f33732002-11-25 21:36:54 +00001675
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001676 The input sequences alone can determine the choice.
1677 If not, choose the class which appears in the MRO
1678 of the earliest direct superclass of the new class.
1679 */
Guido van Rossum98f33732002-11-25 21:36:54 +00001680
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001681 candidate = PyList_GET_ITEM(cur_list, remain[i]);
1682 for (j = 0; j < to_merge_size; j++) {
1683 PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
Benjamin Peterson104b9e02015-02-05 22:29:14 -05001684 if (tail_contains(j_lst, remain[j], candidate))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001685 goto skip; /* continue outer loop */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001686 }
Benjamin Peterson104b9e02015-02-05 22:29:14 -05001687 res = PyList_Append(acc, candidate);
1688 if (res < 0)
1689 goto out;
1690
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001691 for (j = 0; j < to_merge_size; j++) {
1692 PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
1693 if (remain[j] < PyList_GET_SIZE(j_lst) &&
1694 PyList_GET_ITEM(j_lst, remain[j]) == candidate) {
1695 remain[j]++;
1696 }
1697 }
1698 goto again;
1699 skip: ;
1700 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001701
Benjamin Peterson104b9e02015-02-05 22:29:14 -05001702 if (empty_cnt != to_merge_size) {
1703 set_mro_error(to_merge, remain);
1704 res = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001705 }
Benjamin Peterson104b9e02015-02-05 22:29:14 -05001706
1707 out:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001708 PyMem_FREE(remain);
Benjamin Peterson104b9e02015-02-05 22:29:14 -05001709
1710 return res;
Guido van Rossum1f121312002-11-14 19:49:16 +00001711}
1712
Tim Peters6d6c1a32001-08-02 04:15:00 +00001713static PyObject *
1714mro_implementation(PyTypeObject *type)
1715{
Benjamin Peterson104b9e02015-02-05 22:29:14 -05001716 PyObject *result = NULL;
1717 PyObject *bases;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001718 PyObject *to_merge, *bases_aslist;
Benjamin Peterson104b9e02015-02-05 22:29:14 -05001719 int res;
1720 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001721
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001722 if (type->tp_dict == NULL) {
1723 if (PyType_Ready(type) < 0)
1724 return NULL;
1725 }
Guido van Rossum63517572002-06-18 16:44:57 +00001726
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001727 /* Find a superclass linearization that honors the constraints
1728 of the explicit lists of bases and the constraints implied by
1729 each base class.
Guido van Rossum98f33732002-11-25 21:36:54 +00001730
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001731 to_merge is a list of lists, where each list is a superclass
1732 linearization implied by a base class. The last element of
1733 to_merge is the declared list of bases.
1734 */
Guido van Rossum98f33732002-11-25 21:36:54 +00001735
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001736 bases = type->tp_bases;
1737 n = PyTuple_GET_SIZE(bases);
Guido van Rossum1f121312002-11-14 19:49:16 +00001738
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001739 to_merge = PyList_New(n+1);
1740 if (to_merge == NULL)
1741 return NULL;
Guido van Rossum1f121312002-11-14 19:49:16 +00001742
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001743 for (i = 0; i < n; i++) {
Benjamin Peterson104b9e02015-02-05 22:29:14 -05001744 PyTypeObject *base;
1745 PyObject *base_mro_aslist;
1746
1747 base = (PyTypeObject *)PyTuple_GET_ITEM(bases, i);
1748 if (base->tp_mro == NULL) {
1749 PyErr_Format(PyExc_TypeError,
1750 "Cannot extend an incomplete type '%.100s'",
1751 base->tp_name);
1752 goto out;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001753 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001754
Benjamin Peterson104b9e02015-02-05 22:29:14 -05001755 base_mro_aslist = PySequence_List(base->tp_mro);
1756 if (base_mro_aslist == NULL)
1757 goto out;
1758
1759 PyList_SET_ITEM(to_merge, i, base_mro_aslist);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001760 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001761
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001762 bases_aslist = PySequence_List(bases);
Benjamin Peterson104b9e02015-02-05 22:29:14 -05001763 if (bases_aslist == NULL)
1764 goto out;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001765 /* This is just a basic sanity check. */
1766 if (check_duplicates(bases_aslist) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001767 Py_DECREF(bases_aslist);
Benjamin Peterson104b9e02015-02-05 22:29:14 -05001768 goto out;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001769 }
1770 PyList_SET_ITEM(to_merge, n, bases_aslist);
Guido van Rossum1f121312002-11-14 19:49:16 +00001771
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001772 result = Py_BuildValue("[O]", (PyObject *)type);
Benjamin Peterson104b9e02015-02-05 22:29:14 -05001773 if (result == NULL)
1774 goto out;
Guido van Rossum1f121312002-11-14 19:49:16 +00001775
Benjamin Peterson104b9e02015-02-05 22:29:14 -05001776 res = pmerge(result, to_merge);
1777 if (res < 0)
1778 Py_CLEAR(result);
1779
1780 out:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001781 Py_DECREF(to_merge);
Guido van Rossum1f121312002-11-14 19:49:16 +00001782
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001783 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001784}
1785
1786static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001787mro_external(PyObject *self)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001788{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001789 PyTypeObject *type = (PyTypeObject *)self;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001790
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001791 return mro_implementation(type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001792}
1793
1794static int
Benjamin Peterson104b9e02015-02-05 22:29:14 -05001795mro_check(PyTypeObject *type, PyObject *mro)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001796{
Benjamin Peterson104b9e02015-02-05 22:29:14 -05001797 PyTypeObject *solid;
1798 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001799
Benjamin Peterson104b9e02015-02-05 22:29:14 -05001800 solid = solid_base(type);
1801
1802 n = PyTuple_GET_SIZE(mro);
1803 for (i = 0; i < n; i++) {
1804 PyTypeObject *base;
1805 PyObject *tmp;
1806
1807 tmp = PyTuple_GET_ITEM(mro, i);
1808 if (!PyType_Check(tmp)) {
1809 PyErr_Format(
1810 PyExc_TypeError,
1811 "mro() returned a non-class ('%.500s')",
1812 Py_TYPE(tmp)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001813 return -1;
Benjamin Peterson104b9e02015-02-05 22:29:14 -05001814 }
Armin Rigo037d1e02005-12-29 17:07:39 +00001815
Benjamin Peterson104b9e02015-02-05 22:29:14 -05001816 base = (PyTypeObject*)tmp;
1817 if (!PyType_IsSubtype(solid, solid_base(base))) {
1818 PyErr_Format(
1819 PyExc_TypeError,
1820 "mro() returned base with unsuitable layout ('%.500s')",
1821 base->tp_name);
1822 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001823 }
1824 }
Benjamin Peterson104b9e02015-02-05 22:29:14 -05001825
1826 return 0;
1827}
1828
1829/* Lookups an mcls.mro method, invokes it and checks the result (if needed,
1830 in case of a custom mro() implementation).
1831
1832 Keep in mind that during execution of this function type->tp_mro
1833 can be replaced due to possible reentrance (for example,
1834 through type_set_bases):
1835
1836 - when looking up the mcls.mro attribute (it could be
1837 a user-provided descriptor);
1838
1839 - from inside a custom mro() itself;
1840
1841 - through a finalizer of the return value of mro().
1842*/
1843static PyObject *
1844mro_invoke(PyTypeObject *type)
1845{
1846 PyObject *mro_result;
1847 PyObject *new_mro;
1848 int custom = (Py_TYPE(type) != &PyType_Type);
1849
1850 if (custom) {
1851 _Py_IDENTIFIER(mro);
1852 PyObject *mro_meth = lookup_method((PyObject *)type, &PyId_mro);
1853 if (mro_meth == NULL)
1854 return NULL;
1855 mro_result = PyObject_CallObject(mro_meth, NULL);
1856 Py_DECREF(mro_meth);
1857 }
1858 else {
1859 mro_result = mro_implementation(type);
1860 }
1861 if (mro_result == NULL)
1862 return NULL;
1863
1864 new_mro = PySequence_Tuple(mro_result);
1865 Py_DECREF(mro_result);
1866 if (new_mro == NULL)
1867 return NULL;
1868
1869 if (custom && mro_check(type, new_mro) < 0) {
1870 Py_DECREF(new_mro);
1871 return NULL;
1872 }
1873
1874 return new_mro;
1875}
1876
1877/* Calculates and assigns a new MRO to type->tp_mro.
1878 Return values and invariants:
1879
1880 - Returns 1 if a new MRO value has been set to type->tp_mro due to
1881 this call of mro_internal (no tricky reentrancy and no errors).
1882
1883 In case if p_old_mro argument is not NULL, a previous value
1884 of type->tp_mro is put there, and the ownership of this
1885 reference is transferred to a caller.
1886 Otherwise, the previous value (if any) is decref'ed.
1887
1888 - Returns 0 in case when type->tp_mro gets changed because of
1889 reentering here through a custom mro() (see a comment to mro_invoke).
1890
1891 In this case, a refcount of an old type->tp_mro is adjusted
1892 somewhere deeper in the call stack (by the innermost mro_internal
1893 or its caller) and may become zero upon returning from here.
1894 This also implies that the whole hierarchy of subclasses of the type
1895 has seen the new value and updated their MRO accordingly.
1896
1897 - Returns -1 in case of an error.
1898*/
1899static int
1900mro_internal(PyTypeObject *type, PyObject **p_old_mro)
1901{
1902 PyObject *new_mro, *old_mro;
1903 int reent;
1904
1905 /* Keep a reference to be able to do a reentrancy check below.
1906 Don't let old_mro be GC'ed and its address be reused for
1907 another object, like (suddenly!) a new tp_mro. */
1908 old_mro = type->tp_mro;
1909 Py_XINCREF(old_mro);
1910 new_mro = mro_invoke(type); /* might cause reentrance */
1911 reent = (type->tp_mro != old_mro);
1912 Py_XDECREF(old_mro);
1913 if (new_mro == NULL)
1914 return -1;
1915
1916 if (reent) {
1917 Py_DECREF(new_mro);
1918 return 0;
1919 }
1920
1921 type->tp_mro = new_mro;
Christian Heimesa62da1d2008-01-12 19:39:10 +00001922
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001923 type_mro_modified(type, type->tp_mro);
Florent Xiclunaaa6c1d22011-12-12 18:54:29 +01001924 /* corner case: the super class might have been hidden
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001925 from the custom MRO */
1926 type_mro_modified(type, type->tp_bases);
Christian Heimesa62da1d2008-01-12 19:39:10 +00001927
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001928 PyType_Modified(type);
Christian Heimesa62da1d2008-01-12 19:39:10 +00001929
Benjamin Peterson104b9e02015-02-05 22:29:14 -05001930 if (p_old_mro != NULL)
1931 *p_old_mro = old_mro; /* transfer the ownership */
1932 else
1933 Py_XDECREF(old_mro);
1934
1935 return 1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001936}
1937
1938
1939/* Calculate the best base amongst multiple base classes.
1940 This is the first one that's on the path to the "solid base". */
1941
1942static PyTypeObject *
1943best_base(PyObject *bases)
1944{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001945 Py_ssize_t i, n;
1946 PyTypeObject *base, *winner, *candidate, *base_i;
1947 PyObject *base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001948
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001949 assert(PyTuple_Check(bases));
1950 n = PyTuple_GET_SIZE(bases);
1951 assert(n > 0);
1952 base = NULL;
1953 winner = NULL;
1954 for (i = 0; i < n; i++) {
1955 base_proto = PyTuple_GET_ITEM(bases, i);
1956 if (!PyType_Check(base_proto)) {
1957 PyErr_SetString(
1958 PyExc_TypeError,
1959 "bases must be types");
1960 return NULL;
1961 }
1962 base_i = (PyTypeObject *)base_proto;
1963 if (base_i->tp_dict == NULL) {
1964 if (PyType_Ready(base_i) < 0)
1965 return NULL;
1966 }
Benjamin Petersonbd6c41a2015-10-06 19:36:54 -07001967 if (!PyType_HasFeature(base_i, Py_TPFLAGS_BASETYPE)) {
1968 PyErr_Format(PyExc_TypeError,
1969 "type '%.100s' is not an acceptable base type",
1970 base_i->tp_name);
1971 return NULL;
1972 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001973 candidate = solid_base(base_i);
1974 if (winner == NULL) {
1975 winner = candidate;
1976 base = base_i;
1977 }
1978 else if (PyType_IsSubtype(winner, candidate))
1979 ;
1980 else if (PyType_IsSubtype(candidate, winner)) {
1981 winner = candidate;
1982 base = base_i;
1983 }
1984 else {
1985 PyErr_SetString(
1986 PyExc_TypeError,
1987 "multiple bases have "
1988 "instance lay-out conflict");
1989 return NULL;
1990 }
1991 }
Florent Xiclunaaa6c1d22011-12-12 18:54:29 +01001992 assert (base != NULL);
1993
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001994 return base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001995}
1996
1997static int
1998extra_ivars(PyTypeObject *type, PyTypeObject *base)
1999{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002000 size_t t_size = type->tp_basicsize;
2001 size_t b_size = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002002
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002003 assert(t_size >= b_size); /* Else type smaller than base! */
2004 if (type->tp_itemsize || base->tp_itemsize) {
2005 /* If itemsize is involved, stricter rules */
2006 return t_size != b_size ||
2007 type->tp_itemsize != base->tp_itemsize;
2008 }
2009 if (type->tp_weaklistoffset && base->tp_weaklistoffset == 0 &&
2010 type->tp_weaklistoffset + sizeof(PyObject *) == t_size &&
2011 type->tp_flags & Py_TPFLAGS_HEAPTYPE)
2012 t_size -= sizeof(PyObject *);
2013 if (type->tp_dictoffset && base->tp_dictoffset == 0 &&
2014 type->tp_dictoffset + sizeof(PyObject *) == t_size &&
2015 type->tp_flags & Py_TPFLAGS_HEAPTYPE)
2016 t_size -= sizeof(PyObject *);
Guido van Rossum9676b222001-08-17 20:32:36 +00002017
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002018 return t_size != b_size;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002019}
2020
2021static PyTypeObject *
2022solid_base(PyTypeObject *type)
2023{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002024 PyTypeObject *base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002025
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002026 if (type->tp_base)
2027 base = solid_base(type->tp_base);
2028 else
2029 base = &PyBaseObject_Type;
2030 if (extra_ivars(type, base))
2031 return type;
2032 else
2033 return base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002034}
2035
Jeremy Hylton938ace62002-07-17 16:30:39 +00002036static void object_dealloc(PyObject *);
2037static int object_init(PyObject *, PyObject *, PyObject *);
2038static int update_slot(PyTypeObject *, PyObject *);
2039static void fixup_slot_dispatchers(PyTypeObject *);
Nick Coghland78448e2016-07-30 16:26:03 +10002040static int set_names(PyTypeObject *);
2041static int init_subclass(PyTypeObject *, PyObject *);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002042
Guido van Rossum360e4b82007-05-14 22:51:27 +00002043/*
2044 * Helpers for __dict__ descriptor. We don't want to expose the dicts
2045 * inherited from various builtin types. The builtin base usually provides
2046 * its own __dict__ descriptor, so we use that when we can.
2047 */
2048static PyTypeObject *
2049get_builtin_base_with_dict(PyTypeObject *type)
2050{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002051 while (type->tp_base != NULL) {
2052 if (type->tp_dictoffset != 0 &&
2053 !(type->tp_flags & Py_TPFLAGS_HEAPTYPE))
2054 return type;
2055 type = type->tp_base;
2056 }
2057 return NULL;
Guido van Rossum360e4b82007-05-14 22:51:27 +00002058}
2059
2060static PyObject *
2061get_dict_descriptor(PyTypeObject *type)
2062{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002063 PyObject *descr;
Guido van Rossum360e4b82007-05-14 22:51:27 +00002064
Victor Stinner3c1e4812012-03-26 22:10:51 +02002065 descr = _PyType_LookupId(type, &PyId___dict__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002066 if (descr == NULL || !PyDescr_IsData(descr))
2067 return NULL;
Guido van Rossum360e4b82007-05-14 22:51:27 +00002068
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002069 return descr;
Guido van Rossum360e4b82007-05-14 22:51:27 +00002070}
2071
2072static void
2073raise_dict_descr_error(PyObject *obj)
2074{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002075 PyErr_Format(PyExc_TypeError,
2076 "this __dict__ descriptor does not support "
2077 "'%.200s' objects", Py_TYPE(obj)->tp_name);
Guido van Rossum360e4b82007-05-14 22:51:27 +00002078}
2079
Tim Peters6d6c1a32001-08-02 04:15:00 +00002080static PyObject *
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00002081subtype_dict(PyObject *obj, void *context)
2082{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002083 PyTypeObject *base;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00002084
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002085 base = get_builtin_base_with_dict(Py_TYPE(obj));
2086 if (base != NULL) {
2087 descrgetfunc func;
2088 PyObject *descr = get_dict_descriptor(base);
2089 if (descr == NULL) {
2090 raise_dict_descr_error(obj);
2091 return NULL;
2092 }
2093 func = Py_TYPE(descr)->tp_descr_get;
2094 if (func == NULL) {
2095 raise_dict_descr_error(obj);
2096 return NULL;
2097 }
2098 return func(descr, obj, (PyObject *)(Py_TYPE(obj)));
2099 }
Benjamin Peterson8eb12692012-02-19 19:59:10 -05002100 return PyObject_GenericGetDict(obj, context);
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00002101}
2102
Guido van Rossum6661be32001-10-26 04:26:12 +00002103static int
2104subtype_setdict(PyObject *obj, PyObject *value, void *context)
2105{
Serhiy Storchaka576f1322016-01-05 21:27:54 +02002106 PyObject **dictptr;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002107 PyTypeObject *base;
Guido van Rossum6661be32001-10-26 04:26:12 +00002108
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002109 base = get_builtin_base_with_dict(Py_TYPE(obj));
2110 if (base != NULL) {
2111 descrsetfunc func;
2112 PyObject *descr = get_dict_descriptor(base);
2113 if (descr == NULL) {
2114 raise_dict_descr_error(obj);
2115 return -1;
2116 }
2117 func = Py_TYPE(descr)->tp_descr_set;
2118 if (func == NULL) {
2119 raise_dict_descr_error(obj);
2120 return -1;
2121 }
2122 return func(descr, obj, value);
2123 }
Benjamin Peterson8eb12692012-02-19 19:59:10 -05002124 /* Almost like PyObject_GenericSetDict, but allow __dict__ to be deleted. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002125 dictptr = _PyObject_GetDictPtr(obj);
2126 if (dictptr == NULL) {
2127 PyErr_SetString(PyExc_AttributeError,
2128 "This object has no __dict__");
2129 return -1;
2130 }
Benjamin Peterson006c5a22012-02-19 20:36:12 -05002131 if (value != NULL && !PyDict_Check(value)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002132 PyErr_Format(PyExc_TypeError,
2133 "__dict__ must be set to a dictionary, "
2134 "not a '%.200s'", Py_TYPE(value)->tp_name);
2135 return -1;
2136 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002137 Py_XINCREF(value);
Serhiy Storchakaec397562016-04-06 09:50:03 +03002138 Py_XSETREF(*dictptr, value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002139 return 0;
Guido van Rossum6661be32001-10-26 04:26:12 +00002140}
2141
Guido van Rossumad47da02002-08-12 19:05:44 +00002142static PyObject *
2143subtype_getweakref(PyObject *obj, void *context)
2144{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002145 PyObject **weaklistptr;
2146 PyObject *result;
Guido van Rossumad47da02002-08-12 19:05:44 +00002147
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002148 if (Py_TYPE(obj)->tp_weaklistoffset == 0) {
2149 PyErr_SetString(PyExc_AttributeError,
2150 "This object has no __weakref__");
2151 return NULL;
2152 }
2153 assert(Py_TYPE(obj)->tp_weaklistoffset > 0);
2154 assert(Py_TYPE(obj)->tp_weaklistoffset + sizeof(PyObject *) <=
2155 (size_t)(Py_TYPE(obj)->tp_basicsize));
2156 weaklistptr = (PyObject **)
2157 ((char *)obj + Py_TYPE(obj)->tp_weaklistoffset);
2158 if (*weaklistptr == NULL)
2159 result = Py_None;
2160 else
2161 result = *weaklistptr;
2162 Py_INCREF(result);
2163 return result;
Guido van Rossumad47da02002-08-12 19:05:44 +00002164}
2165
Guido van Rossum373c7412003-01-07 13:41:37 +00002166/* Three variants on the subtype_getsets list. */
2167
2168static PyGetSetDef subtype_getsets_full[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002169 {"__dict__", subtype_dict, subtype_setdict,
2170 PyDoc_STR("dictionary for instance variables (if defined)")},
2171 {"__weakref__", subtype_getweakref, NULL,
2172 PyDoc_STR("list of weak references to the object (if defined)")},
2173 {0}
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00002174};
2175
Guido van Rossum373c7412003-01-07 13:41:37 +00002176static PyGetSetDef subtype_getsets_dict_only[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002177 {"__dict__", subtype_dict, subtype_setdict,
2178 PyDoc_STR("dictionary for instance variables (if defined)")},
2179 {0}
Guido van Rossum373c7412003-01-07 13:41:37 +00002180};
2181
2182static PyGetSetDef subtype_getsets_weakref_only[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002183 {"__weakref__", subtype_getweakref, NULL,
2184 PyDoc_STR("list of weak references to the object (if defined)")},
2185 {0}
Guido van Rossum373c7412003-01-07 13:41:37 +00002186};
2187
Guido van Rossum9923ffe2002-06-04 19:52:53 +00002188static int
2189valid_identifier(PyObject *s)
2190{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002191 if (!PyUnicode_Check(s)) {
2192 PyErr_Format(PyExc_TypeError,
2193 "__slots__ items must be strings, not '%.200s'",
2194 Py_TYPE(s)->tp_name);
2195 return 0;
2196 }
2197 if (!PyUnicode_IsIdentifier(s)) {
2198 PyErr_SetString(PyExc_TypeError,
2199 "__slots__ must be identifiers");
2200 return 0;
2201 }
2202 return 1;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00002203}
2204
Guido van Rossumd8faa362007-04-27 19:54:29 +00002205/* Forward */
2206static int
2207object_init(PyObject *self, PyObject *args, PyObject *kwds);
2208
2209static int
2210type_init(PyObject *cls, PyObject *args, PyObject *kwds)
2211{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002212 int res;
Guido van Rossumd8faa362007-04-27 19:54:29 +00002213
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002214 assert(args != NULL && PyTuple_Check(args));
2215 assert(kwds == NULL || PyDict_Check(kwds));
Guido van Rossumd8faa362007-04-27 19:54:29 +00002216
Nick Coghland78448e2016-07-30 16:26:03 +10002217 if (kwds != NULL && PyTuple_Check(args) && PyTuple_GET_SIZE(args) == 1 &&
2218 PyDict_Check(kwds) && PyDict_Size(kwds) != 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002219 PyErr_SetString(PyExc_TypeError,
2220 "type.__init__() takes no keyword arguments");
2221 return -1;
2222 }
Guido van Rossumd8faa362007-04-27 19:54:29 +00002223
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002224 if (args != NULL && PyTuple_Check(args) &&
2225 (PyTuple_GET_SIZE(args) != 1 && PyTuple_GET_SIZE(args) != 3)) {
2226 PyErr_SetString(PyExc_TypeError,
2227 "type.__init__() takes 1 or 3 arguments");
2228 return -1;
2229 }
Guido van Rossumd8faa362007-04-27 19:54:29 +00002230
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002231 /* Call object.__init__(self) now. */
2232 /* XXX Could call super(type, cls).__init__() but what's the point? */
2233 args = PyTuple_GetSlice(args, 0, 0);
2234 res = object_init(cls, args, NULL);
2235 Py_DECREF(args);
2236 return res;
Guido van Rossumd8faa362007-04-27 19:54:29 +00002237}
2238
Victor Stinner4ca1cf32012-10-30 23:40:45 +01002239unsigned long
Martin v. Löwis738236d2011-02-05 20:35:29 +00002240PyType_GetFlags(PyTypeObject *type)
2241{
2242 return type->tp_flags;
2243}
2244
Nick Coghlande31b192011-10-23 22:04:16 +10002245/* Determine the most derived metatype. */
2246PyTypeObject *
2247_PyType_CalculateMetaclass(PyTypeObject *metatype, PyObject *bases)
2248{
2249 Py_ssize_t i, nbases;
2250 PyTypeObject *winner;
2251 PyObject *tmp;
2252 PyTypeObject *tmptype;
2253
2254 /* Determine the proper metatype to deal with this,
2255 and check for metatype conflicts while we're at it.
2256 Note that if some other metatype wins to contract,
2257 it's possible that its instances are not types. */
2258
2259 nbases = PyTuple_GET_SIZE(bases);
2260 winner = metatype;
2261 for (i = 0; i < nbases; i++) {
2262 tmp = PyTuple_GET_ITEM(bases, i);
2263 tmptype = Py_TYPE(tmp);
2264 if (PyType_IsSubtype(winner, tmptype))
2265 continue;
2266 if (PyType_IsSubtype(tmptype, winner)) {
2267 winner = tmptype;
2268 continue;
2269 }
2270 /* else: */
2271 PyErr_SetString(PyExc_TypeError,
2272 "metaclass conflict: "
2273 "the metaclass of a derived class "
2274 "must be a (non-strict) subclass "
2275 "of the metaclasses of all its bases");
2276 return NULL;
2277 }
2278 return winner;
2279}
2280
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00002281static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00002282type_new(PyTypeObject *metatype, PyObject *args, PyObject *kwds)
2283{
Victor Stinner6f738742012-02-25 01:22:36 +01002284 PyObject *name, *bases = NULL, *orig_dict, *dict = NULL;
Victor Stinner6f738742012-02-25 01:22:36 +01002285 PyObject *qualname, *slots = NULL, *tmp, *newslots;
2286 PyTypeObject *type = NULL, *base, *tmptype, *winner;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002287 PyHeapTypeObject *et;
2288 PyMemberDef *mp;
Serhiy Storchaka42bf8fc2015-12-30 21:40:49 +02002289 Py_ssize_t i, nbases, nslots, slotoffset, name_size;
2290 int j, may_add_dict, may_add_weak, add_dict, add_weak;
Victor Stinner3c1e4812012-03-26 22:10:51 +02002291 _Py_IDENTIFIER(__qualname__);
2292 _Py_IDENTIFIER(__slots__);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002293
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002294 assert(args != NULL && PyTuple_Check(args));
2295 assert(kwds == NULL || PyDict_Check(kwds));
Tim Peters3abca122001-10-27 19:37:48 +00002296
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002297 /* Special case: type(x) should return x->ob_type */
Berker Peksag3f015a62016-08-19 11:04:07 +03002298 /* We only want type itself to accept the one-argument form (#27157)
2299 Note: We don't call PyType_CheckExact as that also allows subclasses */
2300 if (metatype == &PyType_Type) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002301 const Py_ssize_t nargs = PyTuple_GET_SIZE(args);
2302 const Py_ssize_t nkwds = kwds == NULL ? 0 : PyDict_Size(kwds);
Tim Peters3abca122001-10-27 19:37:48 +00002303
Berker Peksag3f015a62016-08-19 11:04:07 +03002304 if (nargs == 1 && nkwds == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002305 PyObject *x = PyTuple_GET_ITEM(args, 0);
2306 Py_INCREF(Py_TYPE(x));
2307 return (PyObject *) Py_TYPE(x);
2308 }
Tim Peters3abca122001-10-27 19:37:48 +00002309
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002310 /* SF bug 475327 -- if that didn't trigger, we need 3
2311 arguments. but PyArg_ParseTupleAndKeywords below may give
2312 a msg saying type() needs exactly 3. */
Nick Coghland78448e2016-07-30 16:26:03 +10002313 if (nargs != 3) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002314 PyErr_SetString(PyExc_TypeError,
2315 "type() takes 1 or 3 arguments");
2316 return NULL;
2317 }
2318 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002319
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002320 /* Check arguments: (name, bases, dict) */
Berker Peksag3f015a62016-08-19 11:04:07 +03002321 if (!PyArg_ParseTuple(args, "UO!O!:type.__new__", &name, &PyTuple_Type,
2322 &bases, &PyDict_Type, &orig_dict))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002323 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002324
Nick Coghlande31b192011-10-23 22:04:16 +10002325 /* Determine the proper metatype to deal with this: */
2326 winner = _PyType_CalculateMetaclass(metatype, bases);
2327 if (winner == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002328 return NULL;
2329 }
Nick Coghlande31b192011-10-23 22:04:16 +10002330
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002331 if (winner != metatype) {
2332 if (winner->tp_new != type_new) /* Pass it to the winner */
2333 return winner->tp_new(winner, args, kwds);
2334 metatype = winner;
2335 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002336
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002337 /* Adjust for empty tuple bases */
Nick Coghlande31b192011-10-23 22:04:16 +10002338 nbases = PyTuple_GET_SIZE(bases);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002339 if (nbases == 0) {
2340 bases = PyTuple_Pack(1, &PyBaseObject_Type);
2341 if (bases == NULL)
Victor Stinner6f738742012-02-25 01:22:36 +01002342 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002343 nbases = 1;
2344 }
2345 else
2346 Py_INCREF(bases);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002347
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002348 /* Calculate best base, and check that all bases are type objects */
2349 base = best_base(bases);
2350 if (base == NULL) {
Victor Stinner6f738742012-02-25 01:22:36 +01002351 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002352 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002353
Victor Stinner6f738742012-02-25 01:22:36 +01002354 dict = PyDict_Copy(orig_dict);
2355 if (dict == NULL)
2356 goto error;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002357
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002358 /* Check for a __slots__ sequence variable in dict, and count it */
Victor Stinner3c1e4812012-03-26 22:10:51 +02002359 slots = _PyDict_GetItemId(dict, &PyId___slots__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002360 nslots = 0;
2361 add_dict = 0;
2362 add_weak = 0;
2363 may_add_dict = base->tp_dictoffset == 0;
2364 may_add_weak = base->tp_weaklistoffset == 0 && base->tp_itemsize == 0;
2365 if (slots == NULL) {
2366 if (may_add_dict) {
2367 add_dict++;
2368 }
2369 if (may_add_weak) {
2370 add_weak++;
2371 }
2372 }
2373 else {
2374 /* Have slots */
Guido van Rossumad47da02002-08-12 19:05:44 +00002375
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002376 /* Make it into a tuple */
2377 if (PyUnicode_Check(slots))
2378 slots = PyTuple_Pack(1, slots);
2379 else
2380 slots = PySequence_Tuple(slots);
Victor Stinner6f738742012-02-25 01:22:36 +01002381 if (slots == NULL)
2382 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002383 assert(PyTuple_Check(slots));
Guido van Rossumad47da02002-08-12 19:05:44 +00002384
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002385 /* Are slots allowed? */
2386 nslots = PyTuple_GET_SIZE(slots);
2387 if (nslots > 0 && base->tp_itemsize != 0) {
2388 PyErr_Format(PyExc_TypeError,
2389 "nonempty __slots__ "
2390 "not supported for subtype of '%s'",
2391 base->tp_name);
Victor Stinner6f738742012-02-25 01:22:36 +01002392 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002393 }
Guido van Rossumad47da02002-08-12 19:05:44 +00002394
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002395 /* Check for valid slot names and two special cases */
2396 for (i = 0; i < nslots; i++) {
2397 PyObject *tmp = PyTuple_GET_ITEM(slots, i);
2398 if (!valid_identifier(tmp))
Victor Stinner6f738742012-02-25 01:22:36 +01002399 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002400 assert(PyUnicode_Check(tmp));
Victor Stinnerad14ccd2013-11-07 00:46:04 +01002401 if (_PyUnicode_CompareWithId(tmp, &PyId___dict__) == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002402 if (!may_add_dict || add_dict) {
2403 PyErr_SetString(PyExc_TypeError,
2404 "__dict__ slot disallowed: "
2405 "we already got one");
Victor Stinner6f738742012-02-25 01:22:36 +01002406 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002407 }
2408 add_dict++;
2409 }
2410 if (PyUnicode_CompareWithASCIIString(tmp, "__weakref__") == 0) {
2411 if (!may_add_weak || add_weak) {
2412 PyErr_SetString(PyExc_TypeError,
2413 "__weakref__ slot disallowed: "
2414 "either we already got one, "
2415 "or __itemsize__ != 0");
Victor Stinner6f738742012-02-25 01:22:36 +01002416 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002417 }
2418 add_weak++;
2419 }
2420 }
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00002421
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002422 /* Copy slots into a list, mangle names and sort them.
2423 Sorted names are needed for __class__ assignment.
2424 Convert them back to tuple at the end.
2425 */
2426 newslots = PyList_New(nslots - add_dict - add_weak);
2427 if (newslots == NULL)
Victor Stinner6f738742012-02-25 01:22:36 +01002428 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002429 for (i = j = 0; i < nslots; i++) {
2430 tmp = PyTuple_GET_ITEM(slots, i);
2431 if ((add_dict &&
Victor Stinnerad14ccd2013-11-07 00:46:04 +01002432 _PyUnicode_CompareWithId(tmp, &PyId___dict__) == 0) ||
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002433 (add_weak &&
2434 PyUnicode_CompareWithASCIIString(tmp, "__weakref__") == 0))
2435 continue;
2436 tmp =_Py_Mangle(name, tmp);
Benjamin Petersonae13c882011-08-16 22:26:48 -05002437 if (!tmp) {
2438 Py_DECREF(newslots);
Victor Stinner6f738742012-02-25 01:22:36 +01002439 goto error;
Benjamin Petersonae13c882011-08-16 22:26:48 -05002440 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002441 PyList_SET_ITEM(newslots, j, tmp);
Benjamin Petersonc4085c82011-08-16 18:53:26 -05002442 if (PyDict_GetItem(dict, tmp)) {
2443 PyErr_Format(PyExc_ValueError,
2444 "%R in __slots__ conflicts with class variable",
2445 tmp);
Benjamin Petersond17cefc2011-08-16 22:28:23 -05002446 Py_DECREF(newslots);
Victor Stinner6f738742012-02-25 01:22:36 +01002447 goto error;
Benjamin Petersonc4085c82011-08-16 18:53:26 -05002448 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002449 j++;
2450 }
2451 assert(j == nslots - add_dict - add_weak);
2452 nslots = j;
Victor Stinner6f738742012-02-25 01:22:36 +01002453 Py_CLEAR(slots);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002454 if (PyList_Sort(newslots) == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002455 Py_DECREF(newslots);
Victor Stinner6f738742012-02-25 01:22:36 +01002456 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002457 }
2458 slots = PyList_AsTuple(newslots);
2459 Py_DECREF(newslots);
Victor Stinner6f738742012-02-25 01:22:36 +01002460 if (slots == NULL)
2461 goto error;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00002462
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002463 /* Secondary bases may provide weakrefs or dict */
2464 if (nbases > 1 &&
2465 ((may_add_dict && !add_dict) ||
2466 (may_add_weak && !add_weak))) {
2467 for (i = 0; i < nbases; i++) {
2468 tmp = PyTuple_GET_ITEM(bases, i);
2469 if (tmp == (PyObject *)base)
2470 continue; /* Skip primary base */
2471 assert(PyType_Check(tmp));
2472 tmptype = (PyTypeObject *)tmp;
2473 if (may_add_dict && !add_dict &&
2474 tmptype->tp_dictoffset != 0)
2475 add_dict++;
2476 if (may_add_weak && !add_weak &&
2477 tmptype->tp_weaklistoffset != 0)
2478 add_weak++;
2479 if (may_add_dict && !add_dict)
2480 continue;
2481 if (may_add_weak && !add_weak)
2482 continue;
2483 /* Nothing more to check */
2484 break;
2485 }
2486 }
2487 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002488
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002489 /* Allocate the type object */
2490 type = (PyTypeObject *)metatype->tp_alloc(metatype, nslots);
Victor Stinner6f738742012-02-25 01:22:36 +01002491 if (type == NULL)
2492 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002493
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002494 /* Keep name and slots alive in the extended type object */
2495 et = (PyHeapTypeObject *)type;
2496 Py_INCREF(name);
2497 et->ht_name = name;
2498 et->ht_slots = slots;
Victor Stinner6f738742012-02-25 01:22:36 +01002499 slots = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002500
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002501 /* Initialize tp_flags */
2502 type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE |
Antoine Pitrou796564c2013-07-30 19:59:21 +02002503 Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_FINALIZE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002504 if (base->tp_flags & Py_TPFLAGS_HAVE_GC)
2505 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossumdc91b992001-08-08 22:26:22 +00002506
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002507 /* Initialize essential fields */
Yury Selivanov75445082015-05-11 22:57:16 -04002508 type->tp_as_async = &et->as_async;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002509 type->tp_as_number = &et->as_number;
2510 type->tp_as_sequence = &et->as_sequence;
2511 type->tp_as_mapping = &et->as_mapping;
2512 type->tp_as_buffer = &et->as_buffer;
Serhiy Storchaka42bf8fc2015-12-30 21:40:49 +02002513 type->tp_name = PyUnicode_AsUTF8AndSize(name, &name_size);
Victor Stinner6f738742012-02-25 01:22:36 +01002514 if (!type->tp_name)
2515 goto error;
Serhiy Storchaka42bf8fc2015-12-30 21:40:49 +02002516 if (strlen(type->tp_name) != (size_t)name_size) {
2517 PyErr_SetString(PyExc_ValueError,
2518 "type name must not contain null characters");
2519 goto error;
2520 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002521
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002522 /* Set tp_base and tp_bases */
2523 type->tp_bases = bases;
Victor Stinner6f738742012-02-25 01:22:36 +01002524 bases = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002525 Py_INCREF(base);
2526 type->tp_base = base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002527
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002528 /* Initialize tp_dict from passed-in dict */
Victor Stinner6f738742012-02-25 01:22:36 +01002529 Py_INCREF(dict);
2530 type->tp_dict = dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002531
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002532 /* Set __module__ in the dict */
Victor Stinner3c1e4812012-03-26 22:10:51 +02002533 if (_PyDict_GetItemId(dict, &PyId___module__) == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002534 tmp = PyEval_GetGlobals();
2535 if (tmp != NULL) {
Victor Stinner3c1e4812012-03-26 22:10:51 +02002536 tmp = _PyDict_GetItemId(tmp, &PyId___name__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002537 if (tmp != NULL) {
Victor Stinner3c1e4812012-03-26 22:10:51 +02002538 if (_PyDict_SetItemId(dict, &PyId___module__,
2539 tmp) < 0)
Victor Stinner6f738742012-02-25 01:22:36 +01002540 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002541 }
2542 }
2543 }
Guido van Rossumc3542212001-08-16 09:18:56 +00002544
Victor Stinner6f738742012-02-25 01:22:36 +01002545 /* Set ht_qualname to dict['__qualname__'] if available, else to
2546 __name__. The __qualname__ accessor will look for ht_qualname.
2547 */
Victor Stinner3c1e4812012-03-26 22:10:51 +02002548 qualname = _PyDict_GetItemId(dict, &PyId___qualname__);
Victor Stinner6f738742012-02-25 01:22:36 +01002549 if (qualname != NULL) {
2550 if (!PyUnicode_Check(qualname)) {
2551 PyErr_Format(PyExc_TypeError,
2552 "type __qualname__ must be a str, not %s",
2553 Py_TYPE(qualname)->tp_name);
2554 goto error;
2555 }
2556 }
Benjamin Peterson8afa7fa2012-10-30 23:51:03 -04002557 et->ht_qualname = qualname ? qualname : et->ht_name;
2558 Py_INCREF(et->ht_qualname);
2559 if (qualname != NULL && PyDict_DelItem(dict, PyId___qualname__.object) < 0)
2560 goto error;
Victor Stinner6f738742012-02-25 01:22:36 +01002561
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002562 /* Set tp_doc to a copy of dict['__doc__'], if the latter is there
2563 and is a string. The __doc__ accessor will first look for tp_doc;
2564 if that fails, it will still look into __dict__.
2565 */
2566 {
Victor Stinner3c1e4812012-03-26 22:10:51 +02002567 PyObject *doc = _PyDict_GetItemId(dict, &PyId___doc__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002568 if (doc != NULL && PyUnicode_Check(doc)) {
2569 Py_ssize_t len;
2570 char *doc_str;
2571 char *tp_doc;
Alexandre Vassalottia85998a2008-05-03 18:24:43 +00002572
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002573 doc_str = _PyUnicode_AsString(doc);
Victor Stinner6f738742012-02-25 01:22:36 +01002574 if (doc_str == NULL)
2575 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002576 /* Silently truncate the docstring if it contains null bytes. */
2577 len = strlen(doc_str);
2578 tp_doc = (char *)PyObject_MALLOC(len + 1);
Victor Stinner53510cd2013-07-15 19:34:20 +02002579 if (tp_doc == NULL) {
2580 PyErr_NoMemory();
Victor Stinner6f738742012-02-25 01:22:36 +01002581 goto error;
Victor Stinner53510cd2013-07-15 19:34:20 +02002582 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002583 memcpy(tp_doc, doc_str, len + 1);
2584 type->tp_doc = tp_doc;
2585 }
2586 }
Tim Peters2f93e282001-10-04 05:27:00 +00002587
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002588 /* Special-case __new__: if it's a plain function,
2589 make it a static function */
Victor Stinner3c1e4812012-03-26 22:10:51 +02002590 tmp = _PyDict_GetItemId(dict, &PyId___new__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002591 if (tmp != NULL && PyFunction_Check(tmp)) {
2592 tmp = PyStaticMethod_New(tmp);
Victor Stinner6f738742012-02-25 01:22:36 +01002593 if (tmp == NULL)
2594 goto error;
Serhiy Storchaka484c9132016-06-05 10:48:36 +03002595 if (_PyDict_SetItemId(dict, &PyId___new__, tmp) < 0) {
2596 Py_DECREF(tmp);
Victor Stinner3c1e4812012-03-26 22:10:51 +02002597 goto error;
Serhiy Storchaka484c9132016-06-05 10:48:36 +03002598 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002599 Py_DECREF(tmp);
2600 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002601
Nick Coghland78448e2016-07-30 16:26:03 +10002602 /* Special-case __init_subclass__: if it's a plain function,
2603 make it a classmethod */
2604 tmp = _PyDict_GetItemId(dict, &PyId___init_subclass__);
2605 if (tmp != NULL && PyFunction_Check(tmp)) {
2606 tmp = PyClassMethod_New(tmp);
2607 if (tmp == NULL)
2608 goto error;
2609 if (_PyDict_SetItemId(dict, &PyId___init_subclass__, tmp) < 0) {
2610 Py_DECREF(tmp);
2611 goto error;
2612 }
2613 Py_DECREF(tmp);
2614 }
2615
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002616 /* Add descriptors for custom slots from __slots__, or for __dict__ */
2617 mp = PyHeapType_GET_MEMBERS(et);
2618 slotoffset = base->tp_basicsize;
Victor Stinner6f738742012-02-25 01:22:36 +01002619 if (et->ht_slots != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002620 for (i = 0; i < nslots; i++, mp++) {
2621 mp->name = _PyUnicode_AsString(
Victor Stinner6f738742012-02-25 01:22:36 +01002622 PyTuple_GET_ITEM(et->ht_slots, i));
2623 if (mp->name == NULL)
2624 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002625 mp->type = T_OBJECT_EX;
2626 mp->offset = slotoffset;
Guido van Rossumd8faa362007-04-27 19:54:29 +00002627
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002628 /* __dict__ and __weakref__ are already filtered out */
2629 assert(strcmp(mp->name, "__dict__") != 0);
2630 assert(strcmp(mp->name, "__weakref__") != 0);
Guido van Rossumd8faa362007-04-27 19:54:29 +00002631
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002632 slotoffset += sizeof(PyObject *);
2633 }
2634 }
2635 if (add_dict) {
2636 if (base->tp_itemsize)
2637 type->tp_dictoffset = -(long)sizeof(PyObject *);
2638 else
2639 type->tp_dictoffset = slotoffset;
2640 slotoffset += sizeof(PyObject *);
2641 }
2642 if (add_weak) {
2643 assert(!base->tp_itemsize);
2644 type->tp_weaklistoffset = slotoffset;
2645 slotoffset += sizeof(PyObject *);
2646 }
2647 type->tp_basicsize = slotoffset;
2648 type->tp_itemsize = base->tp_itemsize;
2649 type->tp_members = PyHeapType_GET_MEMBERS(et);
Guido van Rossum373c7412003-01-07 13:41:37 +00002650
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002651 if (type->tp_weaklistoffset && type->tp_dictoffset)
2652 type->tp_getset = subtype_getsets_full;
2653 else if (type->tp_weaklistoffset && !type->tp_dictoffset)
2654 type->tp_getset = subtype_getsets_weakref_only;
2655 else if (!type->tp_weaklistoffset && type->tp_dictoffset)
2656 type->tp_getset = subtype_getsets_dict_only;
2657 else
2658 type->tp_getset = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002659
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002660 /* Special case some slots */
2661 if (type->tp_dictoffset != 0 || nslots > 0) {
2662 if (base->tp_getattr == NULL && base->tp_getattro == NULL)
2663 type->tp_getattro = PyObject_GenericGetAttr;
2664 if (base->tp_setattr == NULL && base->tp_setattro == NULL)
2665 type->tp_setattro = PyObject_GenericSetAttr;
2666 }
2667 type->tp_dealloc = subtype_dealloc;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002668
Antoine Pitroua63cc212015-04-13 20:10:06 +02002669 /* Enable GC unless this class is not adding new instance variables and
2670 the base class did not use GC. */
2671 if ((base->tp_flags & Py_TPFLAGS_HAVE_GC) ||
2672 type->tp_basicsize > base->tp_basicsize)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002673 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossum9475a232001-10-05 20:51:39 +00002674
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002675 /* Always override allocation strategy to use regular heap */
2676 type->tp_alloc = PyType_GenericAlloc;
2677 if (type->tp_flags & Py_TPFLAGS_HAVE_GC) {
2678 type->tp_free = PyObject_GC_Del;
2679 type->tp_traverse = subtype_traverse;
2680 type->tp_clear = subtype_clear;
2681 }
2682 else
2683 type->tp_free = PyObject_Del;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002684
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002685 /* Initialize the rest */
Victor Stinner6f738742012-02-25 01:22:36 +01002686 if (PyType_Ready(type) < 0)
2687 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002688
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002689 /* Put the proper slots in place */
2690 fixup_slot_dispatchers(type);
Guido van Rossumf040ede2001-08-07 16:40:56 +00002691
Benjamin Petersondf813792014-03-17 15:57:17 -05002692 if (type->tp_dictoffset) {
2693 et->ht_cached_keys = _PyDict_NewKeysForClass();
2694 }
2695
Nick Coghland78448e2016-07-30 16:26:03 +10002696 if (set_names(type) < 0)
2697 goto error;
2698
2699 if (init_subclass(type, kwds) < 0)
2700 goto error;
2701
Victor Stinner6f738742012-02-25 01:22:36 +01002702 Py_DECREF(dict);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002703 return (PyObject *)type;
Victor Stinner6f738742012-02-25 01:22:36 +01002704
2705error:
2706 Py_XDECREF(dict);
2707 Py_XDECREF(bases);
2708 Py_XDECREF(slots);
2709 Py_XDECREF(type);
2710 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002711}
2712
Serhiy Storchaka2d06e842015-12-25 19:53:18 +02002713static const short slotoffsets[] = {
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002714 -1, /* invalid slot */
2715#include "typeslots.inc"
2716};
2717
Benjamin Petersone28108c2012-01-29 20:13:18 -05002718PyObject *
Martin v. Löwis9c564092012-06-23 23:20:45 +02002719PyType_FromSpecWithBases(PyType_Spec *spec, PyObject *bases)
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002720{
2721 PyHeapTypeObject *res = (PyHeapTypeObject*)PyType_GenericAlloc(&PyType_Type, 0);
Martin v. Löwis9c564092012-06-23 23:20:45 +02002722 PyTypeObject *type, *base;
Nick Coghlana48db2b2015-05-24 01:03:46 +10002723 PyObject *modname;
Martin v. Löwis9c564092012-06-23 23:20:45 +02002724 char *s;
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002725 char *res_start = (char*)res;
2726 PyType_Slot *slot;
Victor Stinner54e4ca72013-07-11 22:42:25 +02002727
Martin v. Löwis9c564092012-06-23 23:20:45 +02002728 /* Set the type name and qualname */
2729 s = strrchr(spec->name, '.');
2730 if (s == NULL)
2731 s = (char*)spec->name;
2732 else
2733 s++;
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002734
Martin v. Löwis5e06a5d2011-02-21 16:24:00 +00002735 if (res == NULL)
Antoine Pitroubb78f572012-06-24 00:18:27 +02002736 return NULL;
2737 type = &res->ht_type;
Antoine Pitrou66a3a7e2012-06-24 00:42:59 +02002738 /* The flags must be initialized early, before the GC traverses us */
2739 type->tp_flags = spec->flags | Py_TPFLAGS_HEAPTYPE;
Martin v. Löwis9c564092012-06-23 23:20:45 +02002740 res->ht_name = PyUnicode_FromString(s);
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002741 if (!res->ht_name)
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002742 goto fail;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002743 res->ht_qualname = res->ht_name;
2744 Py_INCREF(res->ht_qualname);
Antoine Pitroubb78f572012-06-24 00:18:27 +02002745 type->tp_name = spec->name;
2746 if (!type->tp_name)
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002747 goto fail;
Victor Stinner54e4ca72013-07-11 22:42:25 +02002748
Martin v. Löwis9c564092012-06-23 23:20:45 +02002749 /* Adjust for empty tuple bases */
2750 if (!bases) {
2751 base = &PyBaseObject_Type;
2752 /* See whether Py_tp_base(s) was specified */
2753 for (slot = spec->slots; slot->slot; slot++) {
2754 if (slot->slot == Py_tp_base)
2755 base = slot->pfunc;
2756 else if (slot->slot == Py_tp_bases) {
2757 bases = slot->pfunc;
2758 Py_INCREF(bases);
2759 }
2760 }
2761 if (!bases)
2762 bases = PyTuple_Pack(1, base);
2763 if (!bases)
2764 goto fail;
2765 }
2766 else
2767 Py_INCREF(bases);
2768
2769 /* Calculate best base, and check that all bases are type objects */
2770 base = best_base(bases);
2771 if (base == NULL) {
2772 goto fail;
2773 }
2774 if (!PyType_HasFeature(base, Py_TPFLAGS_BASETYPE)) {
2775 PyErr_Format(PyExc_TypeError,
2776 "type '%.100s' is not an acceptable base type",
2777 base->tp_name);
2778 goto fail;
2779 }
2780
Martin v. Löwis9c564092012-06-23 23:20:45 +02002781 /* Initialize essential fields */
Yury Selivanov75445082015-05-11 22:57:16 -04002782 type->tp_as_async = &res->as_async;
Martin v. Löwis9c564092012-06-23 23:20:45 +02002783 type->tp_as_number = &res->as_number;
2784 type->tp_as_sequence = &res->as_sequence;
2785 type->tp_as_mapping = &res->as_mapping;
2786 type->tp_as_buffer = &res->as_buffer;
2787 /* Set tp_base and tp_bases */
2788 type->tp_bases = bases;
2789 bases = NULL;
2790 Py_INCREF(base);
2791 type->tp_base = base;
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002792
Antoine Pitroubb78f572012-06-24 00:18:27 +02002793 type->tp_basicsize = spec->basicsize;
2794 type->tp_itemsize = spec->itemsize;
Victor Stinner0fcab4a2011-01-04 12:59:15 +00002795
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002796 for (slot = spec->slots; slot->slot; slot++) {
Victor Stinner12174a52014-08-15 23:17:38 +02002797 if (slot->slot < 0
2798 || (size_t)slot->slot >= Py_ARRAY_LENGTH(slotoffsets)) {
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002799 PyErr_SetString(PyExc_RuntimeError, "invalid slot offset");
2800 goto fail;
2801 }
Martin v. Löwis9c564092012-06-23 23:20:45 +02002802 if (slot->slot == Py_tp_base || slot->slot == Py_tp_bases)
2803 /* Processed above */
2804 continue;
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002805 *(void**)(res_start + slotoffsets[slot->slot]) = slot->pfunc;
Georg Brandl032400b2011-02-19 21:47:02 +00002806
2807 /* need to make a copy of the docstring slot, which usually
2808 points to a static string literal */
2809 if (slot->slot == Py_tp_doc) {
Larry Hastings2623c8c2014-02-08 22:15:29 -08002810 const char *old_doc = _PyType_DocWithoutSignature(type->tp_name, slot->pfunc);
Larry Hastings5c661892014-01-24 06:17:25 -08002811 size_t len = strlen(old_doc)+1;
Georg Brandl032400b2011-02-19 21:47:02 +00002812 char *tp_doc = PyObject_MALLOC(len);
Victor Stinner53510cd2013-07-15 19:34:20 +02002813 if (tp_doc == NULL) {
2814 PyErr_NoMemory();
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002815 goto fail;
Victor Stinner53510cd2013-07-15 19:34:20 +02002816 }
Larry Hastings5c661892014-01-24 06:17:25 -08002817 memcpy(tp_doc, old_doc, len);
Antoine Pitroubb78f572012-06-24 00:18:27 +02002818 type->tp_doc = tp_doc;
Georg Brandl032400b2011-02-19 21:47:02 +00002819 }
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002820 }
Antoine Pitroubb78f572012-06-24 00:18:27 +02002821 if (type->tp_dealloc == NULL) {
Antoine Pitrou99cc6292012-06-23 14:42:38 +02002822 /* It's a heap type, so needs the heap types' dealloc.
2823 subtype_dealloc will call the base type's tp_dealloc, if
2824 necessary. */
Antoine Pitroubb78f572012-06-24 00:18:27 +02002825 type->tp_dealloc = subtype_dealloc;
Antoine Pitrou99cc6292012-06-23 14:42:38 +02002826 }
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002827
Antoine Pitroubb78f572012-06-24 00:18:27 +02002828 if (PyType_Ready(type) < 0)
Benjamin Peterson2652d252012-01-29 20:16:37 -05002829 goto fail;
2830
Benjamin Petersondf813792014-03-17 15:57:17 -05002831 if (type->tp_dictoffset) {
2832 res->ht_cached_keys = _PyDict_NewKeysForClass();
2833 }
2834
Martin v. Löwis9c564092012-06-23 23:20:45 +02002835 /* Set type.__module__ */
2836 s = strrchr(spec->name, '.');
Nick Coghlana48db2b2015-05-24 01:03:46 +10002837 if (s != NULL) {
2838 modname = PyUnicode_FromStringAndSize(
2839 spec->name, (Py_ssize_t)(s - spec->name));
2840 if (modname == NULL) {
2841 goto fail;
2842 }
2843 _PyDict_SetItemId(type->tp_dict, &PyId___module__, modname);
2844 Py_DECREF(modname);
2845 } else {
Serhiy Storchaka490055a2015-03-01 10:03:02 +02002846 if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
Serhiy Storchaka71c6f442015-03-01 14:39:20 +02002847 "builtin type %.200s has no __module__ attribute",
Serhiy Storchaka490055a2015-03-01 10:03:02 +02002848 spec->name))
2849 goto fail;
2850 }
Martin v. Löwis9c564092012-06-23 23:20:45 +02002851
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002852 return (PyObject*)res;
Victor Stinner0fcab4a2011-01-04 12:59:15 +00002853
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002854 fail:
2855 Py_DECREF(res);
2856 return NULL;
2857}
2858
Martin v. Löwis9c564092012-06-23 23:20:45 +02002859PyObject *
2860PyType_FromSpec(PyType_Spec *spec)
2861{
2862 return PyType_FromSpecWithBases(spec, NULL);
2863}
2864
Martin v. Löwisca7b0462014-02-04 09:33:05 +01002865void *
2866PyType_GetSlot(PyTypeObject *type, int slot)
2867{
Victor Stinner12174a52014-08-15 23:17:38 +02002868 if (!PyType_HasFeature(type, Py_TPFLAGS_HEAPTYPE) || slot < 0) {
Martin v. Löwisca7b0462014-02-04 09:33:05 +01002869 PyErr_BadInternalCall();
2870 return NULL;
2871 }
Victor Stinner12174a52014-08-15 23:17:38 +02002872 if ((size_t)slot >= Py_ARRAY_LENGTH(slotoffsets)) {
Martin v. Löwisca7b0462014-02-04 09:33:05 +01002873 /* Extension module requesting slot from a future version */
2874 return NULL;
2875 }
2876 return *(void**)(((char*)type) + slotoffsets[slot]);
2877}
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002878
Tim Peters6d6c1a32001-08-02 04:15:00 +00002879/* Internal API to look for a name through the MRO.
2880 This returns a borrowed reference, and doesn't set an exception! */
2881PyObject *
2882_PyType_Lookup(PyTypeObject *type, PyObject *name)
2883{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002884 Py_ssize_t i, n;
2885 PyObject *mro, *res, *base, *dict;
2886 unsigned int h;
Christian Heimesa62da1d2008-01-12 19:39:10 +00002887
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002888 if (MCACHE_CACHEABLE_NAME(name) &&
2889 PyType_HasFeature(type, Py_TPFLAGS_VALID_VERSION_TAG)) {
2890 /* fast path */
2891 h = MCACHE_HASH_METHOD(type, name);
2892 if (method_cache[h].version == type->tp_version_tag &&
Antoine Pitrou2a40e362014-11-15 00:56:27 +01002893 method_cache[h].name == name) {
2894#if MCACHE_STATS
2895 method_cache_hits++;
2896#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002897 return method_cache[h].value;
Antoine Pitrou2a40e362014-11-15 00:56:27 +01002898 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002899 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002900
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002901 /* Look in tp_dict of types in MRO */
2902 mro = type->tp_mro;
Guido van Rossum23094982002-06-10 14:30:43 +00002903
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002904 /* If mro is NULL, the type is either not yet initialized
2905 by PyType_Ready(), or already cleared by type_clear().
2906 Either way the safest thing to do is to return NULL. */
2907 if (mro == NULL)
2908 return NULL;
Guido van Rossum23094982002-06-10 14:30:43 +00002909
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002910 res = NULL;
Victor Stinnerd74782b2012-03-09 00:39:08 +01002911 /* keep a strong reference to mro because type->tp_mro can be replaced
2912 during PyDict_GetItem(dict, name) */
2913 Py_INCREF(mro);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002914 assert(PyTuple_Check(mro));
2915 n = PyTuple_GET_SIZE(mro);
2916 for (i = 0; i < n; i++) {
2917 base = PyTuple_GET_ITEM(mro, i);
2918 assert(PyType_Check(base));
2919 dict = ((PyTypeObject *)base)->tp_dict;
2920 assert(dict && PyDict_Check(dict));
2921 res = PyDict_GetItem(dict, name);
2922 if (res != NULL)
2923 break;
2924 }
Victor Stinnerd74782b2012-03-09 00:39:08 +01002925 Py_DECREF(mro);
Christian Heimesa62da1d2008-01-12 19:39:10 +00002926
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002927 if (MCACHE_CACHEABLE_NAME(name) && assign_version_tag(type)) {
2928 h = MCACHE_HASH_METHOD(type, name);
2929 method_cache[h].version = type->tp_version_tag;
2930 method_cache[h].value = res; /* borrowed */
2931 Py_INCREF(name);
Antoine Pitrou2a40e362014-11-15 00:56:27 +01002932 assert(((PyASCIIObject *)(name))->hash != -1);
2933#if MCACHE_STATS
2934 if (method_cache[h].name != Py_None && method_cache[h].name != name)
2935 method_cache_collisions++;
2936 else
2937 method_cache_misses++;
2938#endif
Serhiy Storchaka57a01d32016-04-10 18:05:40 +03002939 Py_SETREF(method_cache[h].name, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002940 }
2941 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002942}
2943
Raymond Hettinger2ff21902013-10-01 00:55:43 -07002944PyObject *
Victor Stinner3c1e4812012-03-26 22:10:51 +02002945_PyType_LookupId(PyTypeObject *type, struct _Py_Identifier *name)
2946{
2947 PyObject *oname;
2948 oname = _PyUnicode_FromId(name); /* borrowed */
2949 if (oname == NULL)
2950 return NULL;
2951 return _PyType_Lookup(type, oname);
2952}
2953
Tim Peters6d6c1a32001-08-02 04:15:00 +00002954/* This is similar to PyObject_GenericGetAttr(),
2955 but uses _PyType_Lookup() instead of just looking in type->tp_dict. */
2956static PyObject *
2957type_getattro(PyTypeObject *type, PyObject *name)
2958{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002959 PyTypeObject *metatype = Py_TYPE(type);
2960 PyObject *meta_attribute, *attribute;
2961 descrgetfunc meta_get;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002962
Benjamin Peterson16d84ac2012-03-16 09:32:59 -05002963 if (!PyUnicode_Check(name)) {
2964 PyErr_Format(PyExc_TypeError,
2965 "attribute name must be string, not '%.200s'",
2966 name->ob_type->tp_name);
2967 return NULL;
2968 }
2969
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002970 /* Initialize this type (we'll assume the metatype is initialized) */
2971 if (type->tp_dict == NULL) {
2972 if (PyType_Ready(type) < 0)
2973 return NULL;
2974 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002975
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002976 /* No readable descriptor found yet */
2977 meta_get = NULL;
Tim Peters34592512002-07-11 06:23:50 +00002978
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002979 /* Look for the attribute in the metatype */
2980 meta_attribute = _PyType_Lookup(metatype, name);
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002981
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002982 if (meta_attribute != NULL) {
2983 meta_get = Py_TYPE(meta_attribute)->tp_descr_get;
Tim Peters34592512002-07-11 06:23:50 +00002984
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002985 if (meta_get != NULL && PyDescr_IsData(meta_attribute)) {
2986 /* Data descriptors implement tp_descr_set to intercept
2987 * writes. Assume the attribute is not overridden in
2988 * type's tp_dict (and bases): call the descriptor now.
2989 */
2990 return meta_get(meta_attribute, (PyObject *)type,
2991 (PyObject *)metatype);
2992 }
2993 Py_INCREF(meta_attribute);
2994 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002995
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002996 /* No data descriptor found on metatype. Look in tp_dict of this
2997 * type and its bases */
2998 attribute = _PyType_Lookup(type, name);
2999 if (attribute != NULL) {
3000 /* Implement descriptor functionality, if any */
3001 descrgetfunc local_get = Py_TYPE(attribute)->tp_descr_get;
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00003002
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003003 Py_XDECREF(meta_attribute);
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00003004
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003005 if (local_get != NULL) {
3006 /* NULL 2nd argument indicates the descriptor was
3007 * found on the target object itself (or a base) */
3008 return local_get(attribute, (PyObject *)NULL,
3009 (PyObject *)type);
3010 }
Tim Peters34592512002-07-11 06:23:50 +00003011
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003012 Py_INCREF(attribute);
3013 return attribute;
3014 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003015
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003016 /* No attribute found in local __dict__ (or bases): use the
3017 * descriptor from the metatype, if any */
3018 if (meta_get != NULL) {
3019 PyObject *res;
3020 res = meta_get(meta_attribute, (PyObject *)type,
3021 (PyObject *)metatype);
3022 Py_DECREF(meta_attribute);
3023 return res;
3024 }
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00003025
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003026 /* If an ordinary attribute was found on the metatype, return it now */
3027 if (meta_attribute != NULL) {
3028 return meta_attribute;
3029 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003030
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003031 /* Give up */
3032 PyErr_Format(PyExc_AttributeError,
3033 "type object '%.50s' has no attribute '%U'",
3034 type->tp_name, name);
3035 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003036}
3037
3038static int
3039type_setattro(PyTypeObject *type, PyObject *name, PyObject *value)
3040{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003041 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
3042 PyErr_Format(
3043 PyExc_TypeError,
3044 "can't set attributes of built-in/extension type '%s'",
3045 type->tp_name);
3046 return -1;
3047 }
3048 if (PyObject_GenericSetAttr((PyObject *)type, name, value) < 0)
3049 return -1;
3050 return update_slot(type, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003051}
3052
Benjamin Peterson64acccf2012-04-27 15:07:36 -04003053extern void
3054_PyDictKeys_DecRef(PyDictKeysObject *keys);
3055
Tim Peters6d6c1a32001-08-02 04:15:00 +00003056static void
3057type_dealloc(PyTypeObject *type)
3058{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003059 PyHeapTypeObject *et;
Antoine Pitrou84745ab2013-10-29 21:31:25 +01003060 PyObject *tp, *val, *tb;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003061
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003062 /* Assert this is a heap-allocated type object */
3063 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
3064 _PyObject_GC_UNTRACK(type);
Antoine Pitrou84745ab2013-10-29 21:31:25 +01003065 PyErr_Fetch(&tp, &val, &tb);
3066 remove_all_subclasses(type, type->tp_bases);
3067 PyErr_Restore(tp, val, tb);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003068 PyObject_ClearWeakRefs((PyObject *)type);
3069 et = (PyHeapTypeObject *)type;
3070 Py_XDECREF(type->tp_base);
3071 Py_XDECREF(type->tp_dict);
3072 Py_XDECREF(type->tp_bases);
3073 Py_XDECREF(type->tp_mro);
3074 Py_XDECREF(type->tp_cache);
3075 Py_XDECREF(type->tp_subclasses);
3076 /* A type's tp_doc is heap allocated, unlike the tp_doc slots
3077 * of most other objects. It's okay to cast it to char *.
3078 */
3079 PyObject_Free((char *)type->tp_doc);
3080 Py_XDECREF(et->ht_name);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003081 Py_XDECREF(et->ht_qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003082 Py_XDECREF(et->ht_slots);
Benjamin Peterson64acccf2012-04-27 15:07:36 -04003083 if (et->ht_cached_keys)
3084 _PyDictKeys_DecRef(et->ht_cached_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003085 Py_TYPE(type)->tp_free((PyObject *)type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003086}
3087
Guido van Rossum1c450732001-10-08 15:18:27 +00003088static PyObject *
3089type_subclasses(PyTypeObject *type, PyObject *args_ignored)
3090{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003091 PyObject *list, *raw, *ref;
Antoine Pitrou84745ab2013-10-29 21:31:25 +01003092 Py_ssize_t i;
Guido van Rossum1c450732001-10-08 15:18:27 +00003093
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003094 list = PyList_New(0);
3095 if (list == NULL)
3096 return NULL;
3097 raw = type->tp_subclasses;
3098 if (raw == NULL)
3099 return list;
Antoine Pitrou84745ab2013-10-29 21:31:25 +01003100 assert(PyDict_CheckExact(raw));
3101 i = 0;
3102 while (PyDict_Next(raw, &i, NULL, &ref)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003103 assert(PyWeakref_CheckRef(ref));
3104 ref = PyWeakref_GET_OBJECT(ref);
3105 if (ref != Py_None) {
3106 if (PyList_Append(list, ref) < 0) {
3107 Py_DECREF(list);
3108 return NULL;
3109 }
3110 }
3111 }
3112 return list;
Guido van Rossum1c450732001-10-08 15:18:27 +00003113}
3114
Guido van Rossum47374822007-08-02 16:48:17 +00003115static PyObject *
3116type_prepare(PyObject *self, PyObject *args, PyObject *kwds)
3117{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003118 return PyDict_New();
Guido van Rossum47374822007-08-02 16:48:17 +00003119}
3120
Victor Stinner63941882011-09-29 00:42:28 +02003121/*
Benjamin Peterson82b00c12011-05-24 11:09:06 -05003122 Merge the __dict__ of aclass into dict, and recursively also all
3123 the __dict__s of aclass's base classes. The order of merging isn't
3124 defined, as it's expected that only the final set of dict keys is
3125 interesting.
3126 Return 0 on success, -1 on error.
3127*/
3128
3129static int
3130merge_class_dict(PyObject *dict, PyObject *aclass)
3131{
3132 PyObject *classdict;
3133 PyObject *bases;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02003134 _Py_IDENTIFIER(__bases__);
Benjamin Peterson82b00c12011-05-24 11:09:06 -05003135
3136 assert(PyDict_Check(dict));
3137 assert(aclass);
3138
3139 /* Merge in the type's dict (if any). */
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02003140 classdict = _PyObject_GetAttrId(aclass, &PyId___dict__);
Benjamin Peterson82b00c12011-05-24 11:09:06 -05003141 if (classdict == NULL)
3142 PyErr_Clear();
3143 else {
3144 int status = PyDict_Update(dict, classdict);
3145 Py_DECREF(classdict);
3146 if (status < 0)
3147 return -1;
3148 }
3149
3150 /* Recursively merge in the base types' (if any) dicts. */
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02003151 bases = _PyObject_GetAttrId(aclass, &PyId___bases__);
Benjamin Peterson82b00c12011-05-24 11:09:06 -05003152 if (bases == NULL)
3153 PyErr_Clear();
3154 else {
3155 /* We have no guarantee that bases is a real tuple */
3156 Py_ssize_t i, n;
3157 n = PySequence_Size(bases); /* This better be right */
3158 if (n < 0)
3159 PyErr_Clear();
3160 else {
3161 for (i = 0; i < n; i++) {
3162 int status;
3163 PyObject *base = PySequence_GetItem(bases, i);
3164 if (base == NULL) {
3165 Py_DECREF(bases);
3166 return -1;
3167 }
3168 status = merge_class_dict(dict, base);
3169 Py_DECREF(base);
3170 if (status < 0) {
3171 Py_DECREF(bases);
3172 return -1;
3173 }
3174 }
3175 }
3176 Py_DECREF(bases);
3177 }
3178 return 0;
3179}
3180
3181/* __dir__ for type objects: returns __dict__ and __bases__.
3182 We deliberately don't suck up its __class__, as methods belonging to the
3183 metaclass would probably be more confusing than helpful.
3184*/
3185static PyObject *
3186type_dir(PyObject *self, PyObject *args)
3187{
3188 PyObject *result = NULL;
3189 PyObject *dict = PyDict_New();
3190
3191 if (dict != NULL && merge_class_dict(dict, self) == 0)
3192 result = PyDict_Keys(dict);
3193
3194 Py_XDECREF(dict);
3195 return result;
3196}
3197
Martin v. Loewis4f2f3b62012-04-24 19:13:57 +02003198static PyObject*
3199type_sizeof(PyObject *self, PyObject *args_unused)
3200{
3201 Py_ssize_t size;
3202 PyTypeObject *type = (PyTypeObject*)self;
3203 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
3204 PyHeapTypeObject* et = (PyHeapTypeObject*)type;
3205 size = sizeof(PyHeapTypeObject);
3206 if (et->ht_cached_keys)
3207 size += _PyDict_KeysSize(et->ht_cached_keys);
3208 }
3209 else
3210 size = sizeof(PyTypeObject);
3211 return PyLong_FromSsize_t(size);
3212}
3213
Tim Peters6d6c1a32001-08-02 04:15:00 +00003214static PyMethodDef type_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003215 {"mro", (PyCFunction)mro_external, METH_NOARGS,
3216 PyDoc_STR("mro() -> list\nreturn a type's method resolution order")},
3217 {"__subclasses__", (PyCFunction)type_subclasses, METH_NOARGS,
3218 PyDoc_STR("__subclasses__() -> list of immediate subclasses")},
3219 {"__prepare__", (PyCFunction)type_prepare,
3220 METH_VARARGS | METH_KEYWORDS | METH_CLASS,
3221 PyDoc_STR("__prepare__() -> dict\n"
3222 "used to create the namespace for the class statement")},
3223 {"__instancecheck__", type___instancecheck__, METH_O,
Benjamin Petersonfbe56bb2011-05-24 12:42:51 -05003224 PyDoc_STR("__instancecheck__() -> bool\ncheck if an object is an instance")},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003225 {"__subclasscheck__", type___subclasscheck__, METH_O,
Benjamin Petersonfbe56bb2011-05-24 12:42:51 -05003226 PyDoc_STR("__subclasscheck__() -> bool\ncheck if a class is a subclass")},
Benjamin Peterson82b00c12011-05-24 11:09:06 -05003227 {"__dir__", type_dir, METH_NOARGS,
Benjamin Petersonc7284122011-05-24 12:46:15 -05003228 PyDoc_STR("__dir__() -> list\nspecialized __dir__ implementation for types")},
Martin v. Loewis4f2f3b62012-04-24 19:13:57 +02003229 {"__sizeof__", type_sizeof, METH_NOARGS,
3230 "__sizeof__() -> int\nreturn memory consumption of the type object"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003231 {0}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003232};
3233
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003234PyDoc_STRVAR(type_doc,
Larry Hastings5c661892014-01-24 06:17:25 -08003235/* this text signature cannot be accurate yet. will fix. --larry */
Larry Hastings2623c8c2014-02-08 22:15:29 -08003236"type(object_or_name, bases, dict)\n"
Tim Peters6d6c1a32001-08-02 04:15:00 +00003237"type(object) -> the object's type\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003238"type(name, bases, dict) -> a new type");
Tim Peters6d6c1a32001-08-02 04:15:00 +00003239
Guido van Rossum048eb752001-10-02 21:24:57 +00003240static int
3241type_traverse(PyTypeObject *type, visitproc visit, void *arg)
3242{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003243 /* Because of type_is_gc(), the collector only calls this
3244 for heaptypes. */
Antoine Pitrou1351ca62012-06-24 00:30:12 +02003245 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
3246 char msg[200];
3247 sprintf(msg, "type_traverse() called for non-heap type '%.100s'",
3248 type->tp_name);
3249 Py_FatalError(msg);
3250 }
Guido van Rossum048eb752001-10-02 21:24:57 +00003251
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003252 Py_VISIT(type->tp_dict);
3253 Py_VISIT(type->tp_cache);
3254 Py_VISIT(type->tp_mro);
3255 Py_VISIT(type->tp_bases);
3256 Py_VISIT(type->tp_base);
Guido van Rossuma3862092002-06-10 15:24:42 +00003257
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003258 /* There's no need to visit type->tp_subclasses or
3259 ((PyHeapTypeObject *)type)->ht_slots, because they can't be involved
3260 in cycles; tp_subclasses is a list of weak references,
3261 and slots is a tuple of strings. */
Guido van Rossum048eb752001-10-02 21:24:57 +00003262
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003263 return 0;
Guido van Rossum048eb752001-10-02 21:24:57 +00003264}
3265
3266static int
3267type_clear(PyTypeObject *type)
3268{
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003269 PyDictKeysObject *cached_keys;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003270 /* Because of type_is_gc(), the collector only calls this
3271 for heaptypes. */
3272 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00003273
Antoine Pitrou2e872082011-12-15 14:15:31 +01003274 /* We need to invalidate the method cache carefully before clearing
3275 the dict, so that other objects caught in a reference cycle
3276 don't start calling destroyed methods.
3277
3278 Otherwise, the only field we need to clear is tp_mro, which is
3279 part of a hard cycle (its first element is the class itself) that
3280 won't be broken otherwise (it's a tuple and tuples don't have a
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003281 tp_clear handler). None of the other fields need to be
3282 cleared, and here's why:
Guido van Rossum048eb752001-10-02 21:24:57 +00003283
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003284 tp_cache:
3285 Not used; if it were, it would be a dict.
Guido van Rossuma3862092002-06-10 15:24:42 +00003286
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003287 tp_bases, tp_base:
3288 If these are involved in a cycle, there must be at least
3289 one other, mutable object in the cycle, e.g. a base
3290 class's dict; the cycle will be broken that way.
Guido van Rossuma3862092002-06-10 15:24:42 +00003291
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003292 tp_subclasses:
Antoine Pitrou84745ab2013-10-29 21:31:25 +01003293 A dict of weak references can't be part of a cycle; and
3294 dicts have their own tp_clear.
Guido van Rossuma3862092002-06-10 15:24:42 +00003295
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003296 slots (in PyHeapTypeObject):
3297 A tuple of strings can't be part of a cycle.
3298 */
Guido van Rossuma3862092002-06-10 15:24:42 +00003299
Antoine Pitrou2e872082011-12-15 14:15:31 +01003300 PyType_Modified(type);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003301 cached_keys = ((PyHeapTypeObject *)type)->ht_cached_keys;
3302 if (cached_keys != NULL) {
3303 ((PyHeapTypeObject *)type)->ht_cached_keys = NULL;
3304 _PyDictKeys_DecRef(cached_keys);
3305 }
Antoine Pitrou2e872082011-12-15 14:15:31 +01003306 if (type->tp_dict)
3307 PyDict_Clear(type->tp_dict);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003308 Py_CLEAR(type->tp_mro);
Guido van Rossum048eb752001-10-02 21:24:57 +00003309
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003310 return 0;
Guido van Rossum048eb752001-10-02 21:24:57 +00003311}
3312
3313static int
3314type_is_gc(PyTypeObject *type)
3315{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003316 return type->tp_flags & Py_TPFLAGS_HEAPTYPE;
Guido van Rossum048eb752001-10-02 21:24:57 +00003317}
3318
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003319PyTypeObject PyType_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003320 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3321 "type", /* tp_name */
3322 sizeof(PyHeapTypeObject), /* tp_basicsize */
3323 sizeof(PyMemberDef), /* tp_itemsize */
3324 (destructor)type_dealloc, /* tp_dealloc */
3325 0, /* tp_print */
3326 0, /* tp_getattr */
3327 0, /* tp_setattr */
3328 0, /* tp_reserved */
3329 (reprfunc)type_repr, /* tp_repr */
3330 0, /* tp_as_number */
3331 0, /* tp_as_sequence */
3332 0, /* tp_as_mapping */
3333 0, /* tp_hash */
3334 (ternaryfunc)type_call, /* tp_call */
3335 0, /* tp_str */
3336 (getattrofunc)type_getattro, /* tp_getattro */
3337 (setattrofunc)type_setattro, /* tp_setattro */
3338 0, /* tp_as_buffer */
3339 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
3340 Py_TPFLAGS_BASETYPE | Py_TPFLAGS_TYPE_SUBCLASS, /* tp_flags */
3341 type_doc, /* tp_doc */
3342 (traverseproc)type_traverse, /* tp_traverse */
3343 (inquiry)type_clear, /* tp_clear */
3344 0, /* tp_richcompare */
3345 offsetof(PyTypeObject, tp_weaklist), /* tp_weaklistoffset */
3346 0, /* tp_iter */
3347 0, /* tp_iternext */
3348 type_methods, /* tp_methods */
3349 type_members, /* tp_members */
3350 type_getsets, /* tp_getset */
3351 0, /* tp_base */
3352 0, /* tp_dict */
3353 0, /* tp_descr_get */
3354 0, /* tp_descr_set */
3355 offsetof(PyTypeObject, tp_dict), /* tp_dictoffset */
3356 type_init, /* tp_init */
3357 0, /* tp_alloc */
3358 type_new, /* tp_new */
3359 PyObject_GC_Del, /* tp_free */
3360 (inquiry)type_is_gc, /* tp_is_gc */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003361};
Tim Peters6d6c1a32001-08-02 04:15:00 +00003362
3363
3364/* The base type of all types (eventually)... except itself. */
3365
Guido van Rossumd8faa362007-04-27 19:54:29 +00003366/* You may wonder why object.__new__() only complains about arguments
3367 when object.__init__() is not overridden, and vice versa.
3368
3369 Consider the use cases:
3370
3371 1. When neither is overridden, we want to hear complaints about
3372 excess (i.e., any) arguments, since their presence could
3373 indicate there's a bug.
3374
3375 2. When defining an Immutable type, we are likely to override only
3376 __new__(), since __init__() is called too late to initialize an
3377 Immutable object. Since __new__() defines the signature for the
3378 type, it would be a pain to have to override __init__() just to
3379 stop it from complaining about excess arguments.
3380
3381 3. When defining a Mutable type, we are likely to override only
3382 __init__(). So here the converse reasoning applies: we don't
3383 want to have to override __new__() just to stop it from
3384 complaining.
3385
3386 4. When __init__() is overridden, and the subclass __init__() calls
3387 object.__init__(), the latter should complain about excess
3388 arguments; ditto for __new__().
3389
3390 Use cases 2 and 3 make it unattractive to unconditionally check for
3391 excess arguments. The best solution that addresses all four use
3392 cases is as follows: __init__() complains about excess arguments
3393 unless __new__() is overridden and __init__() is not overridden
3394 (IOW, if __init__() is overridden or __new__() is not overridden);
3395 symmetrically, __new__() complains about excess arguments unless
3396 __init__() is overridden and __new__() is not overridden
3397 (IOW, if __new__() is overridden or __init__() is not overridden).
3398
3399 However, for backwards compatibility, this breaks too much code.
3400 Therefore, in 2.6, we'll *warn* about excess arguments when both
3401 methods are overridden; for all other cases we'll use the above
3402 rules.
3403
3404*/
3405
3406/* Forward */
3407static PyObject *
3408object_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
3409
3410static int
3411excess_args(PyObject *args, PyObject *kwds)
3412{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003413 return PyTuple_GET_SIZE(args) ||
3414 (kwds && PyDict_Check(kwds) && PyDict_Size(kwds));
Guido van Rossumd8faa362007-04-27 19:54:29 +00003415}
3416
Tim Peters6d6c1a32001-08-02 04:15:00 +00003417static int
3418object_init(PyObject *self, PyObject *args, PyObject *kwds)
3419{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003420 int err = 0;
Benjamin Peterson96384b92012-03-17 00:05:44 -05003421 PyTypeObject *type = Py_TYPE(self);
3422 if (excess_args(args, kwds) &&
3423 (type->tp_new == object_new || type->tp_init != object_init)) {
3424 PyErr_SetString(PyExc_TypeError, "object.__init__() takes no parameters");
3425 err = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003426 }
3427 return err;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003428}
3429
Guido van Rossum298e4212003-02-13 16:30:16 +00003430static PyObject *
3431object_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3432{
Benjamin Peterson96384b92012-03-17 00:05:44 -05003433 if (excess_args(args, kwds) &&
3434 (type->tp_init == object_init || type->tp_new != object_new)) {
R David Murray702a5dc2013-02-18 21:39:18 -05003435 PyErr_SetString(PyExc_TypeError, "object() takes no parameters");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003436 return NULL;
Benjamin Peterson96384b92012-03-17 00:05:44 -05003437 }
Victor Stinner3c1e4812012-03-26 22:10:51 +02003438
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003439 if (type->tp_flags & Py_TPFLAGS_IS_ABSTRACT) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003440 PyObject *abstract_methods = NULL;
3441 PyObject *builtins;
3442 PyObject *sorted;
3443 PyObject *sorted_methods = NULL;
3444 PyObject *joined = NULL;
Benjamin Peterson9a03ecf2012-03-16 20:15:54 -05003445 PyObject *comma;
3446 _Py_static_string(comma_id, ", ");
Victor Stinner3c1e4812012-03-26 22:10:51 +02003447 _Py_IDENTIFIER(sorted);
Christian Heimes9e7f1d22008-02-28 12:27:11 +00003448
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003449 /* Compute ", ".join(sorted(type.__abstractmethods__))
3450 into joined. */
3451 abstract_methods = type_abstractmethods(type, NULL);
3452 if (abstract_methods == NULL)
3453 goto error;
3454 builtins = PyEval_GetBuiltins();
3455 if (builtins == NULL)
3456 goto error;
Victor Stinner3c1e4812012-03-26 22:10:51 +02003457 sorted = _PyDict_GetItemId(builtins, &PyId_sorted);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003458 if (sorted == NULL)
3459 goto error;
3460 sorted_methods = PyObject_CallFunctionObjArgs(sorted,
3461 abstract_methods,
3462 NULL);
3463 if (sorted_methods == NULL)
3464 goto error;
Benjamin Peterson9a03ecf2012-03-16 20:15:54 -05003465 comma = _PyUnicode_FromId(&comma_id);
3466 if (comma == NULL)
3467 goto error;
3468 joined = PyUnicode_Join(comma, sorted_methods);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003469 if (joined == NULL)
3470 goto error;
Christian Heimes9e7f1d22008-02-28 12:27:11 +00003471
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003472 PyErr_Format(PyExc_TypeError,
3473 "Can't instantiate abstract class %s "
3474 "with abstract methods %U",
3475 type->tp_name,
3476 joined);
3477 error:
3478 Py_XDECREF(joined);
3479 Py_XDECREF(sorted_methods);
3480 Py_XDECREF(abstract_methods);
3481 return NULL;
3482 }
3483 return type->tp_alloc(type, 0);
Guido van Rossum298e4212003-02-13 16:30:16 +00003484}
3485
Tim Peters6d6c1a32001-08-02 04:15:00 +00003486static void
3487object_dealloc(PyObject *self)
3488{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003489 Py_TYPE(self)->tp_free(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003490}
3491
Guido van Rossum8e248182001-08-12 05:17:56 +00003492static PyObject *
3493object_repr(PyObject *self)
3494{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003495 PyTypeObject *type;
3496 PyObject *mod, *name, *rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00003497
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003498 type = Py_TYPE(self);
3499 mod = type_module(type, NULL);
3500 if (mod == NULL)
3501 PyErr_Clear();
3502 else if (!PyUnicode_Check(mod)) {
3503 Py_DECREF(mod);
3504 mod = NULL;
3505 }
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003506 name = type_qualname(type, NULL);
Christian Heimese81dc292012-09-10 16:57:36 +02003507 if (name == NULL) {
3508 Py_XDECREF(mod);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003509 return NULL;
Christian Heimese81dc292012-09-10 16:57:36 +02003510 }
Victor Stinnerbd303c12013-11-07 23:07:29 +01003511 if (mod != NULL && _PyUnicode_CompareWithId(mod, &PyId_builtins))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003512 rtn = PyUnicode_FromFormat("<%U.%U object at %p>", mod, name, self);
3513 else
3514 rtn = PyUnicode_FromFormat("<%s object at %p>",
3515 type->tp_name, self);
3516 Py_XDECREF(mod);
3517 Py_DECREF(name);
3518 return rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00003519}
3520
Guido van Rossumb8f63662001-08-15 23:57:02 +00003521static PyObject *
3522object_str(PyObject *self)
3523{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003524 unaryfunc f;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003525
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003526 f = Py_TYPE(self)->tp_repr;
Benjamin Peterson7b166872012-04-24 11:06:25 -04003527 if (f == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003528 f = object_repr;
3529 return f(self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003530}
3531
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003532static PyObject *
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003533object_richcompare(PyObject *self, PyObject *other, int op)
3534{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003535 PyObject *res;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003536
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003537 switch (op) {
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003538
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003539 case Py_EQ:
3540 /* Return NotImplemented instead of False, so if two
3541 objects are compared, both get a chance at the
3542 comparison. See issue #1393. */
3543 res = (self == other) ? Py_True : Py_NotImplemented;
3544 Py_INCREF(res);
3545 break;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003546
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003547 case Py_NE:
Serhiy Storchakaf4b7a022015-01-26 09:57:07 +02003548 /* By default, __ne__() delegates to __eq__() and inverts the result,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003549 unless the latter returns NotImplemented. */
Serhiy Storchakaf4b7a022015-01-26 09:57:07 +02003550 if (self->ob_type->tp_richcompare == NULL) {
3551 res = Py_NotImplemented;
3552 Py_INCREF(res);
3553 break;
3554 }
3555 res = (*self->ob_type->tp_richcompare)(self, other, Py_EQ);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003556 if (res != NULL && res != Py_NotImplemented) {
3557 int ok = PyObject_IsTrue(res);
3558 Py_DECREF(res);
3559 if (ok < 0)
3560 res = NULL;
3561 else {
3562 if (ok)
3563 res = Py_False;
3564 else
3565 res = Py_True;
3566 Py_INCREF(res);
3567 }
3568 }
3569 break;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003570
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003571 default:
3572 res = Py_NotImplemented;
3573 Py_INCREF(res);
3574 break;
3575 }
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003576
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003577 return res;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003578}
3579
3580static PyObject *
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003581object_get_class(PyObject *self, void *closure)
3582{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003583 Py_INCREF(Py_TYPE(self));
3584 return (PyObject *)(Py_TYPE(self));
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003585}
3586
3587static int
Benjamin Peterson9d4cbcc2015-01-30 13:33:42 -05003588compatible_with_tp_base(PyTypeObject *child)
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003589{
Benjamin Peterson9d4cbcc2015-01-30 13:33:42 -05003590 PyTypeObject *parent = child->tp_base;
3591 return (parent != NULL &&
3592 child->tp_basicsize == parent->tp_basicsize &&
3593 child->tp_itemsize == parent->tp_itemsize &&
3594 child->tp_dictoffset == parent->tp_dictoffset &&
3595 child->tp_weaklistoffset == parent->tp_weaklistoffset &&
3596 ((child->tp_flags & Py_TPFLAGS_HAVE_GC) ==
3597 (parent->tp_flags & Py_TPFLAGS_HAVE_GC)) &&
3598 (child->tp_dealloc == subtype_dealloc ||
3599 child->tp_dealloc == parent->tp_dealloc));
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003600}
3601
3602static int
3603same_slots_added(PyTypeObject *a, PyTypeObject *b)
3604{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003605 PyTypeObject *base = a->tp_base;
3606 Py_ssize_t size;
3607 PyObject *slots_a, *slots_b;
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003608
Benjamin Peterson67641d22011-01-17 19:24:34 +00003609 assert(base == b->tp_base);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003610 size = base->tp_basicsize;
3611 if (a->tp_dictoffset == size && b->tp_dictoffset == size)
3612 size += sizeof(PyObject *);
3613 if (a->tp_weaklistoffset == size && b->tp_weaklistoffset == size)
3614 size += sizeof(PyObject *);
Guido van Rossumd8faa362007-04-27 19:54:29 +00003615
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003616 /* Check slots compliance */
Benjamin Peterson9d4cbcc2015-01-30 13:33:42 -05003617 if (!(a->tp_flags & Py_TPFLAGS_HEAPTYPE) ||
3618 !(b->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
3619 return 0;
3620 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003621 slots_a = ((PyHeapTypeObject *)a)->ht_slots;
3622 slots_b = ((PyHeapTypeObject *)b)->ht_slots;
3623 if (slots_a && slots_b) {
3624 if (PyObject_RichCompareBool(slots_a, slots_b, Py_EQ) != 1)
3625 return 0;
3626 size += sizeof(PyObject *) * PyTuple_GET_SIZE(slots_a);
3627 }
3628 return size == a->tp_basicsize && size == b->tp_basicsize;
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003629}
3630
3631static int
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02003632compatible_for_assignment(PyTypeObject* oldto, PyTypeObject* newto, const char* attr)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003633{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003634 PyTypeObject *newbase, *oldbase;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003635
Benjamin Peterson9d4cbcc2015-01-30 13:33:42 -05003636 if (newto->tp_free != oldto->tp_free) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003637 PyErr_Format(PyExc_TypeError,
3638 "%s assignment: "
3639 "'%s' deallocator differs from '%s'",
3640 attr,
3641 newto->tp_name,
3642 oldto->tp_name);
3643 return 0;
3644 }
Benjamin Peterson9d4cbcc2015-01-30 13:33:42 -05003645 /*
3646 It's tricky to tell if two arbitrary types are sufficiently compatible as
3647 to be interchangeable; e.g., even if they have the same tp_basicsize, they
3648 might have totally different struct fields. It's much easier to tell if a
3649 type and its supertype are compatible; e.g., if they have the same
3650 tp_basicsize, then that means they have identical fields. So to check
3651 whether two arbitrary types are compatible, we first find the highest
3652 supertype that each is compatible with, and then if those supertypes are
3653 compatible then the original types must also be compatible.
3654 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003655 newbase = newto;
3656 oldbase = oldto;
Benjamin Peterson9d4cbcc2015-01-30 13:33:42 -05003657 while (compatible_with_tp_base(newbase))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003658 newbase = newbase->tp_base;
Benjamin Peterson9d4cbcc2015-01-30 13:33:42 -05003659 while (compatible_with_tp_base(oldbase))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003660 oldbase = oldbase->tp_base;
3661 if (newbase != oldbase &&
3662 (newbase->tp_base != oldbase->tp_base ||
3663 !same_slots_added(newbase, oldbase))) {
3664 PyErr_Format(PyExc_TypeError,
3665 "%s assignment: "
3666 "'%s' object layout differs from '%s'",
3667 attr,
3668 newto->tp_name,
3669 oldto->tp_name);
3670 return 0;
3671 }
Tim Petersea7f75d2002-12-07 21:39:16 +00003672
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003673 return 1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003674}
3675
3676static int
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003677object_set_class(PyObject *self, PyObject *value, void *closure)
3678{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003679 PyTypeObject *oldto = Py_TYPE(self);
3680 PyTypeObject *newto;
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003681
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003682 if (value == NULL) {
3683 PyErr_SetString(PyExc_TypeError,
3684 "can't delete __class__ attribute");
3685 return -1;
3686 }
3687 if (!PyType_Check(value)) {
3688 PyErr_Format(PyExc_TypeError,
Florent Xiclunaaa6c1d22011-12-12 18:54:29 +01003689 "__class__ must be set to a class, not '%s' object",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003690 Py_TYPE(value)->tp_name);
3691 return -1;
3692 }
3693 newto = (PyTypeObject *)value;
Guido van Rossum7d293ee2015-09-04 20:54:07 -07003694 /* In versions of CPython prior to 3.5, the code in
3695 compatible_for_assignment was not set up to correctly check for memory
3696 layout / slot / etc. compatibility for non-HEAPTYPE classes, so we just
3697 disallowed __class__ assignment in any case that wasn't HEAPTYPE ->
3698 HEAPTYPE.
3699
3700 During the 3.5 development cycle, we fixed the code in
3701 compatible_for_assignment to correctly check compatibility between
3702 arbitrary types, and started allowing __class__ assignment in all cases
3703 where the old and new types did in fact have compatible slots and
3704 memory layout (regardless of whether they were implemented as HEAPTYPEs
3705 or not).
3706
3707 Just before 3.5 was released, though, we discovered that this led to
3708 problems with immutable types like int, where the interpreter assumes
3709 they are immutable and interns some values. Formerly this wasn't a
3710 problem, because they really were immutable -- in particular, all the
3711 types where the interpreter applied this interning trick happened to
3712 also be statically allocated, so the old HEAPTYPE rules were
3713 "accidentally" stopping them from allowing __class__ assignment. But
3714 with the changes to __class__ assignment, we started allowing code like
3715
3716 class MyInt(int):
3717 ...
3718 # Modifies the type of *all* instances of 1 in the whole program,
3719 # including future instances (!), because the 1 object is interned.
3720 (1).__class__ = MyInt
3721
3722 (see https://bugs.python.org/issue24912).
3723
3724 In theory the proper fix would be to identify which classes rely on
3725 this invariant and somehow disallow __class__ assignment only for them,
3726 perhaps via some mechanism like a new Py_TPFLAGS_IMMUTABLE flag (a
3727 "blacklisting" approach). But in practice, since this problem wasn't
3728 noticed late in the 3.5 RC cycle, we're taking the conservative
3729 approach and reinstating the same HEAPTYPE->HEAPTYPE check that we used
3730 to have, plus a "whitelist". For now, the whitelist consists only of
3731 ModuleType subtypes, since those are the cases that motivated the patch
3732 in the first place -- see https://bugs.python.org/issue22986 -- and
3733 since module objects are mutable we can be sure that they are
3734 definitely not being interned. So now we allow HEAPTYPE->HEAPTYPE *or*
3735 ModuleType subtype -> ModuleType subtype.
3736
3737 So far as we know, all the code beyond the following 'if' statement
3738 will correctly handle non-HEAPTYPE classes, and the HEAPTYPE check is
3739 needed only to protect that subset of non-HEAPTYPE classes for which
3740 the interpreter has baked in the assumption that all instances are
3741 truly immutable.
3742 */
3743 if (!(PyType_IsSubtype(newto, &PyModule_Type) &&
3744 PyType_IsSubtype(oldto, &PyModule_Type)) &&
3745 (!(newto->tp_flags & Py_TPFLAGS_HEAPTYPE) ||
3746 !(oldto->tp_flags & Py_TPFLAGS_HEAPTYPE))) {
3747 PyErr_Format(PyExc_TypeError,
3748 "__class__ assignment only supported for heap types "
3749 "or ModuleType subclasses");
3750 return -1;
3751 }
3752
Christian Heimesde4d1832013-07-20 14:19:46 +02003753 if (compatible_for_assignment(oldto, newto, "__class__")) {
Benjamin Peterson9d4cbcc2015-01-30 13:33:42 -05003754 if (newto->tp_flags & Py_TPFLAGS_HEAPTYPE)
3755 Py_INCREF(newto);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003756 Py_TYPE(self) = newto;
Benjamin Peterson9d4cbcc2015-01-30 13:33:42 -05003757 if (oldto->tp_flags & Py_TPFLAGS_HEAPTYPE)
3758 Py_DECREF(oldto);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003759 return 0;
3760 }
3761 else {
3762 return -1;
3763 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003764}
3765
3766static PyGetSetDef object_getsets[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003767 {"__class__", object_get_class, object_set_class,
3768 PyDoc_STR("the object's class")},
3769 {0}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003770};
3771
Guido van Rossumc53f0092003-02-18 22:05:12 +00003772
Guido van Rossum036f9992003-02-21 22:02:54 +00003773/* Stuff to implement __reduce_ex__ for pickle protocols >= 2.
Alexandre Vassalottif7fa63d2008-05-11 08:55:36 +00003774 We fall back to helpers in copyreg for:
Guido van Rossum036f9992003-02-21 22:02:54 +00003775 - pickle protocols < 2
3776 - calculating the list of slot names (done only once per class)
3777 - the __newobj__ function (which is used as a token but never called)
3778*/
3779
3780static PyObject *
Alexandre Vassalottif7fa63d2008-05-11 08:55:36 +00003781import_copyreg(void)
Guido van Rossum036f9992003-02-21 22:02:54 +00003782{
Alexandre Vassalotti1a830702013-11-30 00:53:09 -08003783 PyObject *copyreg_str;
3784 PyObject *copyreg_module;
3785 PyInterpreterState *interp = PyThreadState_GET()->interp;
3786 _Py_IDENTIFIER(copyreg);
Guido van Rossum3926a632001-09-25 16:25:58 +00003787
Alexandre Vassalotti1a830702013-11-30 00:53:09 -08003788 copyreg_str = _PyUnicode_FromId(&PyId_copyreg);
3789 if (copyreg_str == NULL) {
3790 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003791 }
Alexandre Vassalotti1a830702013-11-30 00:53:09 -08003792 /* Try to fetch cached copy of copyreg from sys.modules first in an
3793 attempt to avoid the import overhead. Previously this was implemented
3794 by storing a reference to the cached module in a static variable, but
3795 this broke when multiple embeded interpreters were in use (see issue
3796 #17408 and #19088). */
3797 copyreg_module = PyDict_GetItemWithError(interp->modules, copyreg_str);
3798 if (copyreg_module != NULL) {
3799 Py_INCREF(copyreg_module);
3800 return copyreg_module;
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003801 }
Alexandre Vassalotti1a830702013-11-30 00:53:09 -08003802 if (PyErr_Occurred()) {
3803 return NULL;
3804 }
3805 return PyImport_Import(copyreg_str);
Guido van Rossum036f9992003-02-21 22:02:54 +00003806}
3807
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01003808Py_LOCAL(PyObject *)
3809_PyType_GetSlotNames(PyTypeObject *cls)
Guido van Rossum036f9992003-02-21 22:02:54 +00003810{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003811 PyObject *copyreg;
3812 PyObject *slotnames;
Victor Stinner3c1e4812012-03-26 22:10:51 +02003813 _Py_IDENTIFIER(__slotnames__);
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02003814 _Py_IDENTIFIER(_slotnames);
Guido van Rossum036f9992003-02-21 22:02:54 +00003815
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01003816 assert(PyType_Check(cls));
3817
3818 /* Get the slot names from the cache in the class if possible. */
3819 slotnames = _PyDict_GetItemIdWithError(cls->tp_dict, &PyId___slotnames__);
3820 if (slotnames != NULL) {
3821 if (slotnames != Py_None && !PyList_Check(slotnames)) {
3822 PyErr_Format(PyExc_TypeError,
3823 "%.200s.__slotnames__ should be a list or None, "
3824 "not %.200s",
3825 cls->tp_name, Py_TYPE(slotnames)->tp_name);
3826 return NULL;
3827 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003828 Py_INCREF(slotnames);
3829 return slotnames;
3830 }
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01003831 else {
3832 if (PyErr_Occurred()) {
3833 return NULL;
3834 }
3835 /* The class does not have the slot names cached yet. */
3836 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003837
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003838 copyreg = import_copyreg();
3839 if (copyreg == NULL)
3840 return NULL;
Guido van Rossum036f9992003-02-21 22:02:54 +00003841
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01003842 /* Use _slotnames function from the copyreg module to find the slots
3843 by this class and its bases. This function will cache the result
3844 in __slotnames__. */
3845 slotnames = _PyObject_CallMethodIdObjArgs(copyreg, &PyId__slotnames,
3846 cls, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003847 Py_DECREF(copyreg);
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01003848 if (slotnames == NULL)
3849 return NULL;
3850
3851 if (slotnames != Py_None && !PyList_Check(slotnames)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003852 PyErr_SetString(PyExc_TypeError,
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01003853 "copyreg._slotnames didn't return a list or None");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003854 Py_DECREF(slotnames);
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01003855 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003856 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003857
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003858 return slotnames;
Guido van Rossum036f9992003-02-21 22:02:54 +00003859}
3860
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01003861Py_LOCAL(PyObject *)
Serhiy Storchakaf81be8a2015-12-25 21:04:29 +02003862_PyObject_GetState(PyObject *obj, int required)
Guido van Rossum036f9992003-02-21 22:02:54 +00003863{
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01003864 PyObject *state;
3865 PyObject *getstate;
Victor Stinner3c1e4812012-03-26 22:10:51 +02003866 _Py_IDENTIFIER(__getstate__);
Guido van Rossum036f9992003-02-21 22:02:54 +00003867
Victor Stinner3c1e4812012-03-26 22:10:51 +02003868 getstate = _PyObject_GetAttrId(obj, &PyId___getstate__);
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01003869 if (getstate == NULL) {
3870 PyObject *slotnames;
3871
3872 if (!PyErr_ExceptionMatches(PyExc_AttributeError)) {
3873 return NULL;
3874 }
3875 PyErr_Clear();
3876
Serhiy Storchakaf81be8a2015-12-25 21:04:29 +02003877 if (required && obj->ob_type->tp_itemsize) {
3878 PyErr_Format(PyExc_TypeError,
3879 "can't pickle %.200s objects",
3880 Py_TYPE(obj)->tp_name);
3881 return NULL;
3882 }
3883
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01003884 {
3885 PyObject **dict;
3886 dict = _PyObject_GetDictPtr(obj);
Larry Hastings5c661892014-01-24 06:17:25 -08003887 /* It is possible that the object's dict is not initialized
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01003888 yet. In this case, we will return None for the state.
3889 We also return None if the dict is empty to make the behavior
3890 consistent regardless whether the dict was initialized or not.
3891 This make unit testing easier. */
3892 if (dict != NULL && *dict != NULL && PyDict_Size(*dict) > 0) {
3893 state = *dict;
3894 }
3895 else {
3896 state = Py_None;
3897 }
3898 Py_INCREF(state);
3899 }
3900
3901 slotnames = _PyType_GetSlotNames(Py_TYPE(obj));
3902 if (slotnames == NULL) {
3903 Py_DECREF(state);
3904 return NULL;
3905 }
3906
3907 assert(slotnames == Py_None || PyList_Check(slotnames));
Serhiy Storchakaf81be8a2015-12-25 21:04:29 +02003908 if (required) {
3909 Py_ssize_t basicsize = PyBaseObject_Type.tp_basicsize;
3910 if (obj->ob_type->tp_dictoffset)
3911 basicsize += sizeof(PyObject *);
3912 if (obj->ob_type->tp_weaklistoffset)
3913 basicsize += sizeof(PyObject *);
3914 if (slotnames != Py_None)
3915 basicsize += sizeof(PyObject *) * Py_SIZE(slotnames);
3916 if (obj->ob_type->tp_basicsize > basicsize) {
3917 Py_DECREF(slotnames);
3918 Py_DECREF(state);
3919 PyErr_Format(PyExc_TypeError,
3920 "can't pickle %.200s objects",
3921 Py_TYPE(obj)->tp_name);
3922 return NULL;
3923 }
3924 }
3925
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01003926 if (slotnames != Py_None && Py_SIZE(slotnames) > 0) {
3927 PyObject *slots;
3928 Py_ssize_t slotnames_size, i;
3929
3930 slots = PyDict_New();
3931 if (slots == NULL) {
3932 Py_DECREF(slotnames);
3933 Py_DECREF(state);
3934 return NULL;
3935 }
3936
3937 slotnames_size = Py_SIZE(slotnames);
3938 for (i = 0; i < slotnames_size; i++) {
3939 PyObject *name, *value;
3940
3941 name = PyList_GET_ITEM(slotnames, i);
Serhiy Storchakad28bb622015-11-25 18:33:29 +02003942 Py_INCREF(name);
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01003943 value = PyObject_GetAttr(obj, name);
3944 if (value == NULL) {
Serhiy Storchakad28bb622015-11-25 18:33:29 +02003945 Py_DECREF(name);
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01003946 if (!PyErr_ExceptionMatches(PyExc_AttributeError)) {
3947 goto error;
3948 }
3949 /* It is not an error if the attribute is not present. */
3950 PyErr_Clear();
3951 }
3952 else {
3953 int err = PyDict_SetItem(slots, name, value);
Serhiy Storchakad28bb622015-11-25 18:33:29 +02003954 Py_DECREF(name);
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01003955 Py_DECREF(value);
3956 if (err) {
3957 goto error;
3958 }
3959 }
3960
Martin Panter8f265652016-04-19 04:03:41 +00003961 /* The list is stored on the class so it may mutate while we
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01003962 iterate over it */
3963 if (slotnames_size != Py_SIZE(slotnames)) {
3964 PyErr_Format(PyExc_RuntimeError,
3965 "__slotsname__ changed size during iteration");
3966 goto error;
3967 }
3968
3969 /* We handle errors within the loop here. */
3970 if (0) {
3971 error:
3972 Py_DECREF(slotnames);
3973 Py_DECREF(slots);
3974 Py_DECREF(state);
3975 return NULL;
3976 }
3977 }
3978
3979 /* If we found some slot attributes, pack them in a tuple along
Berker Peksag0ac70c02016-04-29 16:54:10 +03003980 the original attribute dictionary. */
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01003981 if (PyDict_Size(slots) > 0) {
3982 PyObject *state2;
3983
3984 state2 = PyTuple_Pack(2, state, slots);
3985 Py_DECREF(state);
3986 if (state2 == NULL) {
3987 Py_DECREF(slotnames);
3988 Py_DECREF(slots);
3989 return NULL;
3990 }
3991 state = state2;
3992 }
3993 Py_DECREF(slots);
3994 }
3995 Py_DECREF(slotnames);
3996 }
3997 else { /* getstate != NULL */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003998 state = PyObject_CallObject(getstate, NULL);
3999 Py_DECREF(getstate);
4000 if (state == NULL)
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004001 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004002 }
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004003
4004 return state;
4005}
4006
4007Py_LOCAL(int)
4008_PyObject_GetNewArguments(PyObject *obj, PyObject **args, PyObject **kwargs)
4009{
4010 PyObject *getnewargs, *getnewargs_ex;
4011 _Py_IDENTIFIER(__getnewargs_ex__);
4012 _Py_IDENTIFIER(__getnewargs__);
4013
4014 if (args == NULL || kwargs == NULL) {
4015 PyErr_BadInternalCall();
4016 return -1;
4017 }
4018
4019 /* We first attempt to fetch the arguments for __new__ by calling
4020 __getnewargs_ex__ on the object. */
Benjamin Petersone686c5c2014-02-16 13:49:16 -05004021 getnewargs_ex = _PyObject_LookupSpecial(obj, &PyId___getnewargs_ex__);
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004022 if (getnewargs_ex != NULL) {
4023 PyObject *newargs = PyObject_CallObject(getnewargs_ex, NULL);
4024 Py_DECREF(getnewargs_ex);
4025 if (newargs == NULL) {
4026 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004027 }
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004028 if (!PyTuple_Check(newargs)) {
4029 PyErr_Format(PyExc_TypeError,
4030 "__getnewargs_ex__ should return a tuple, "
4031 "not '%.200s'", Py_TYPE(newargs)->tp_name);
4032 Py_DECREF(newargs);
4033 return -1;
4034 }
4035 if (Py_SIZE(newargs) != 2) {
4036 PyErr_Format(PyExc_ValueError,
4037 "__getnewargs_ex__ should return a tuple of "
4038 "length 2, not %zd", Py_SIZE(newargs));
4039 Py_DECREF(newargs);
4040 return -1;
4041 }
4042 *args = PyTuple_GET_ITEM(newargs, 0);
4043 Py_INCREF(*args);
4044 *kwargs = PyTuple_GET_ITEM(newargs, 1);
4045 Py_INCREF(*kwargs);
4046 Py_DECREF(newargs);
4047
4048 /* XXX We should perhaps allow None to be passed here. */
4049 if (!PyTuple_Check(*args)) {
4050 PyErr_Format(PyExc_TypeError,
4051 "first item of the tuple returned by "
4052 "__getnewargs_ex__ must be a tuple, not '%.200s'",
4053 Py_TYPE(*args)->tp_name);
4054 Py_CLEAR(*args);
4055 Py_CLEAR(*kwargs);
4056 return -1;
4057 }
4058 if (!PyDict_Check(*kwargs)) {
4059 PyErr_Format(PyExc_TypeError,
4060 "second item of the tuple returned by "
4061 "__getnewargs_ex__ must be a dict, not '%.200s'",
4062 Py_TYPE(*kwargs)->tp_name);
4063 Py_CLEAR(*args);
4064 Py_CLEAR(*kwargs);
4065 return -1;
4066 }
4067 return 0;
Benjamin Petersone686c5c2014-02-16 13:49:16 -05004068 } else if (PyErr_Occurred()) {
4069 return -1;
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004070 }
4071
4072 /* The object does not have __getnewargs_ex__ so we fallback on using
4073 __getnewargs__ instead. */
Benjamin Petersone686c5c2014-02-16 13:49:16 -05004074 getnewargs = _PyObject_LookupSpecial(obj, &PyId___getnewargs__);
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004075 if (getnewargs != NULL) {
4076 *args = PyObject_CallObject(getnewargs, NULL);
4077 Py_DECREF(getnewargs);
4078 if (*args == NULL) {
4079 return -1;
4080 }
4081 if (!PyTuple_Check(*args)) {
4082 PyErr_Format(PyExc_TypeError,
4083 "__getnewargs__ should return a tuple, "
4084 "not '%.200s'", Py_TYPE(*args)->tp_name);
4085 Py_CLEAR(*args);
4086 return -1;
4087 }
4088 *kwargs = NULL;
4089 return 0;
Benjamin Petersone686c5c2014-02-16 13:49:16 -05004090 } else if (PyErr_Occurred()) {
4091 return -1;
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004092 }
4093
4094 /* The object does not have __getnewargs_ex__ and __getnewargs__. This may
Martin Panter8f265652016-04-19 04:03:41 +00004095 mean __new__ does not takes any arguments on this object, or that the
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004096 object does not implement the reduce protocol for pickling or
4097 copying. */
4098 *args = NULL;
4099 *kwargs = NULL;
4100 return 0;
4101}
4102
4103Py_LOCAL(int)
4104_PyObject_GetItemsIter(PyObject *obj, PyObject **listitems,
4105 PyObject **dictitems)
4106{
4107 if (listitems == NULL || dictitems == NULL) {
4108 PyErr_BadInternalCall();
4109 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004110 }
Guido van Rossum036f9992003-02-21 22:02:54 +00004111
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004112 if (!PyList_Check(obj)) {
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004113 *listitems = Py_None;
4114 Py_INCREF(*listitems);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004115 }
4116 else {
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004117 *listitems = PyObject_GetIter(obj);
Christian Heimes2489bd82013-11-23 21:19:43 +01004118 if (*listitems == NULL)
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004119 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004120 }
Guido van Rossum036f9992003-02-21 22:02:54 +00004121
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004122 if (!PyDict_Check(obj)) {
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004123 *dictitems = Py_None;
4124 Py_INCREF(*dictitems);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004125 }
4126 else {
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004127 PyObject *items;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02004128 _Py_IDENTIFIER(items);
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004129
4130 items = _PyObject_CallMethodIdObjArgs(obj, &PyId_items, NULL);
4131 if (items == NULL) {
4132 Py_CLEAR(*listitems);
4133 return -1;
4134 }
4135 *dictitems = PyObject_GetIter(items);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004136 Py_DECREF(items);
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004137 if (*dictitems == NULL) {
4138 Py_CLEAR(*listitems);
4139 return -1;
4140 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004141 }
Guido van Rossum036f9992003-02-21 22:02:54 +00004142
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004143 assert(*listitems != NULL && *dictitems != NULL);
4144
4145 return 0;
4146}
4147
4148static PyObject *
Serhiy Storchaka0d554d72015-10-10 22:42:18 +03004149reduce_newobj(PyObject *obj)
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004150{
4151 PyObject *args = NULL, *kwargs = NULL;
4152 PyObject *copyreg;
4153 PyObject *newobj, *newargs, *state, *listitems, *dictitems;
4154 PyObject *result;
Serhiy Storchakaf81be8a2015-12-25 21:04:29 +02004155 int hasargs;
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004156
Serhiy Storchakad7a44152015-11-12 11:23:04 +02004157 if (Py_TYPE(obj)->tp_new == NULL) {
4158 PyErr_Format(PyExc_TypeError,
Serhiy Storchakaf81be8a2015-12-25 21:04:29 +02004159 "can't pickle %.200s objects",
Serhiy Storchakad7a44152015-11-12 11:23:04 +02004160 Py_TYPE(obj)->tp_name);
4161 return NULL;
4162 }
Serhiy Storchaka707b5cc2014-12-16 19:43:46 +02004163 if (_PyObject_GetNewArguments(obj, &args, &kwargs) < 0)
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004164 return NULL;
Serhiy Storchaka707b5cc2014-12-16 19:43:46 +02004165
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004166 copyreg = import_copyreg();
4167 if (copyreg == NULL) {
Serhiy Storchakaf81be8a2015-12-25 21:04:29 +02004168 Py_XDECREF(args);
Serhiy Storchaka707b5cc2014-12-16 19:43:46 +02004169 Py_XDECREF(kwargs);
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004170 return NULL;
4171 }
Serhiy Storchakaf81be8a2015-12-25 21:04:29 +02004172 hasargs = (args != NULL);
Serhiy Storchaka707b5cc2014-12-16 19:43:46 +02004173 if (kwargs == NULL || PyDict_Size(kwargs) == 0) {
4174 _Py_IDENTIFIER(__newobj__);
4175 PyObject *cls;
4176 Py_ssize_t i, n;
4177
4178 Py_XDECREF(kwargs);
4179 newobj = _PyObject_GetAttrId(copyreg, &PyId___newobj__);
4180 Py_DECREF(copyreg);
4181 if (newobj == NULL) {
Serhiy Storchakaf81be8a2015-12-25 21:04:29 +02004182 Py_XDECREF(args);
Serhiy Storchaka707b5cc2014-12-16 19:43:46 +02004183 return NULL;
4184 }
Serhiy Storchakaf81be8a2015-12-25 21:04:29 +02004185 n = args ? PyTuple_GET_SIZE(args) : 0;
Serhiy Storchaka707b5cc2014-12-16 19:43:46 +02004186 newargs = PyTuple_New(n+1);
4187 if (newargs == NULL) {
Serhiy Storchakaf81be8a2015-12-25 21:04:29 +02004188 Py_XDECREF(args);
Serhiy Storchaka707b5cc2014-12-16 19:43:46 +02004189 Py_DECREF(newobj);
4190 return NULL;
4191 }
4192 cls = (PyObject *) Py_TYPE(obj);
4193 Py_INCREF(cls);
4194 PyTuple_SET_ITEM(newargs, 0, cls);
4195 for (i = 0; i < n; i++) {
4196 PyObject *v = PyTuple_GET_ITEM(args, i);
4197 Py_INCREF(v);
4198 PyTuple_SET_ITEM(newargs, i+1, v);
4199 }
Serhiy Storchakaf81be8a2015-12-25 21:04:29 +02004200 Py_XDECREF(args);
Serhiy Storchaka707b5cc2014-12-16 19:43:46 +02004201 }
Serhiy Storchaka0d554d72015-10-10 22:42:18 +03004202 else {
Serhiy Storchaka707b5cc2014-12-16 19:43:46 +02004203 _Py_IDENTIFIER(__newobj_ex__);
4204
4205 newobj = _PyObject_GetAttrId(copyreg, &PyId___newobj_ex__);
4206 Py_DECREF(copyreg);
4207 if (newobj == NULL) {
4208 Py_DECREF(args);
4209 Py_DECREF(kwargs);
4210 return NULL;
4211 }
4212 newargs = PyTuple_Pack(3, Py_TYPE(obj), args, kwargs);
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004213 Py_DECREF(args);
4214 Py_DECREF(kwargs);
Serhiy Storchaka707b5cc2014-12-16 19:43:46 +02004215 if (newargs == NULL) {
4216 Py_DECREF(newobj);
4217 return NULL;
4218 }
4219 }
Serhiy Storchaka707b5cc2014-12-16 19:43:46 +02004220
Serhiy Storchakaf81be8a2015-12-25 21:04:29 +02004221 state = _PyObject_GetState(obj,
4222 !hasargs && !PyList_Check(obj) && !PyDict_Check(obj));
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004223 if (state == NULL) {
4224 Py_DECREF(newobj);
4225 Py_DECREF(newargs);
4226 return NULL;
4227 }
4228 if (_PyObject_GetItemsIter(obj, &listitems, &dictitems) < 0) {
4229 Py_DECREF(newobj);
4230 Py_DECREF(newargs);
4231 Py_DECREF(state);
4232 return NULL;
4233 }
4234
4235 result = PyTuple_Pack(5, newobj, newargs, state, listitems, dictitems);
4236 Py_DECREF(newobj);
4237 Py_DECREF(newargs);
4238 Py_DECREF(state);
4239 Py_DECREF(listitems);
4240 Py_DECREF(dictitems);
Larry Hastings5c661892014-01-24 06:17:25 -08004241 return result;
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004242}
4243
Guido van Rossumd8faa362007-04-27 19:54:29 +00004244/*
4245 * There were two problems when object.__reduce__ and object.__reduce_ex__
4246 * were implemented in the same function:
4247 * - trying to pickle an object with a custom __reduce__ method that
4248 * fell back to object.__reduce__ in certain circumstances led to
Yury Selivanovf488fb42015-07-03 01:04:23 -04004249 * infinite recursion at Python level and eventual RecursionError.
Guido van Rossumd8faa362007-04-27 19:54:29 +00004250 * - Pickling objects that lied about their type by overwriting the
4251 * __class__ descriptor could lead to infinite recursion at C level
4252 * and eventual segfault.
4253 *
4254 * Because of backwards compatibility, the two methods still have to
4255 * behave in the same way, even if this is not required by the pickle
4256 * protocol. This common functionality was moved to the _common_reduce
4257 * function.
4258 */
4259static PyObject *
4260_common_reduce(PyObject *self, int proto)
4261{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004262 PyObject *copyreg, *res;
Guido van Rossumd8faa362007-04-27 19:54:29 +00004263
Serhiy Storchaka707b5cc2014-12-16 19:43:46 +02004264 if (proto >= 2)
Serhiy Storchaka0d554d72015-10-10 22:42:18 +03004265 return reduce_newobj(self);
Guido van Rossumd8faa362007-04-27 19:54:29 +00004266
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004267 copyreg = import_copyreg();
4268 if (!copyreg)
4269 return NULL;
Guido van Rossumd8faa362007-04-27 19:54:29 +00004270
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004271 res = PyEval_CallMethod(copyreg, "_reduce_ex", "(Oi)", self, proto);
4272 Py_DECREF(copyreg);
Guido van Rossumd8faa362007-04-27 19:54:29 +00004273
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004274 return res;
Guido van Rossumd8faa362007-04-27 19:54:29 +00004275}
4276
4277static PyObject *
4278object_reduce(PyObject *self, PyObject *args)
4279{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004280 int proto = 0;
Guido van Rossumd8faa362007-04-27 19:54:29 +00004281
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004282 if (!PyArg_ParseTuple(args, "|i:__reduce__", &proto))
4283 return NULL;
Guido van Rossumd8faa362007-04-27 19:54:29 +00004284
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004285 return _common_reduce(self, proto);
Guido van Rossumd8faa362007-04-27 19:54:29 +00004286}
4287
Guido van Rossum036f9992003-02-21 22:02:54 +00004288static PyObject *
4289object_reduce_ex(PyObject *self, PyObject *args)
4290{
Victor Stinner3c1e4812012-03-26 22:10:51 +02004291 static PyObject *objreduce;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004292 PyObject *reduce, *res;
4293 int proto = 0;
Victor Stinner3c1e4812012-03-26 22:10:51 +02004294 _Py_IDENTIFIER(__reduce__);
Guido van Rossum036f9992003-02-21 22:02:54 +00004295
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004296 if (!PyArg_ParseTuple(args, "|i:__reduce_ex__", &proto))
4297 return NULL;
Guido van Rossum036f9992003-02-21 22:02:54 +00004298
Victor Stinner3c1e4812012-03-26 22:10:51 +02004299 if (objreduce == NULL) {
4300 objreduce = _PyDict_GetItemId(PyBaseObject_Type.tp_dict,
4301 &PyId___reduce__);
4302 if (objreduce == NULL)
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01004303 return NULL;
4304 }
4305
Victor Stinner3c1e4812012-03-26 22:10:51 +02004306 reduce = _PyObject_GetAttrId(self, &PyId___reduce__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004307 if (reduce == NULL)
4308 PyErr_Clear();
4309 else {
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01004310 PyObject *cls, *clsreduce;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004311 int override;
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01004312
4313 cls = (PyObject *) Py_TYPE(self);
Victor Stinner3c1e4812012-03-26 22:10:51 +02004314 clsreduce = _PyObject_GetAttrId(cls, &PyId___reduce__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004315 if (clsreduce == NULL) {
4316 Py_DECREF(reduce);
4317 return NULL;
4318 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004319 override = (clsreduce != objreduce);
4320 Py_DECREF(clsreduce);
4321 if (override) {
4322 res = PyObject_CallObject(reduce, NULL);
4323 Py_DECREF(reduce);
4324 return res;
4325 }
4326 else
4327 Py_DECREF(reduce);
4328 }
Guido van Rossum036f9992003-02-21 22:02:54 +00004329
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004330 return _common_reduce(self, proto);
Guido van Rossum3926a632001-09-25 16:25:58 +00004331}
4332
Christian Heimes9e7f1d22008-02-28 12:27:11 +00004333static PyObject *
4334object_subclasshook(PyObject *cls, PyObject *args)
4335{
Brian Curtindfc80e32011-08-10 20:28:54 -05004336 Py_RETURN_NOTIMPLEMENTED;
Christian Heimes9e7f1d22008-02-28 12:27:11 +00004337}
4338
4339PyDoc_STRVAR(object_subclasshook_doc,
4340"Abstract classes can override this to customize issubclass().\n"
4341"\n"
4342"This is invoked early on by abc.ABCMeta.__subclasscheck__().\n"
4343"It should return True, False or NotImplemented. If it returns\n"
4344"NotImplemented, the normal algorithm is used. Otherwise, it\n"
4345"overrides the normal algorithm (and the outcome is cached).\n");
Eric Smith8c663262007-08-25 02:26:07 +00004346
Nick Coghland78448e2016-07-30 16:26:03 +10004347static PyObject *
4348object_init_subclass(PyObject *cls, PyObject *arg)
4349{
4350 Py_RETURN_NONE;
4351}
4352
4353PyDoc_STRVAR(object_init_subclass_doc,
Berker Peksag01d17192016-07-30 14:06:15 +03004354"This method is called when a class is subclassed.\n"
Nick Coghland78448e2016-07-30 16:26:03 +10004355"\n"
Berker Peksag01d17192016-07-30 14:06:15 +03004356"The default implementation does nothing. It may be\n"
4357"overridden to extend subclasses.\n");
Nick Coghland78448e2016-07-30 16:26:03 +10004358
Eric Smith8c663262007-08-25 02:26:07 +00004359/*
4360 from PEP 3101, this code implements:
4361
4362 class object:
4363 def __format__(self, format_spec):
Serhiy Storchakad741a882015-06-11 00:06:39 +03004364 return format(str(self), format_spec)
Eric Smith8c663262007-08-25 02:26:07 +00004365*/
4366static PyObject *
4367object_format(PyObject *self, PyObject *args)
4368{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004369 PyObject *format_spec;
4370 PyObject *self_as_str = NULL;
4371 PyObject *result = NULL;
Eric Smith8c663262007-08-25 02:26:07 +00004372
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004373 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
4374 return NULL;
Eric Smith8c663262007-08-25 02:26:07 +00004375
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004376 self_as_str = PyObject_Str(self);
Eric Smithe4d63172010-09-13 20:48:43 +00004377 if (self_as_str != NULL) {
4378 /* Issue 7994: If we're converting to a string, we
Eric V. Smithb9cd3532011-03-12 10:08:48 -05004379 should reject format specifications */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004380 if (PyUnicode_GET_LENGTH(format_spec) > 0) {
Andrew Svetlov2cd8ce42012-12-23 14:27:17 +02004381 PyErr_SetString(PyExc_TypeError,
Eric V. Smithb9cd3532011-03-12 10:08:48 -05004382 "non-empty format string passed to object.__format__");
Andrew Svetlov2cd8ce42012-12-23 14:27:17 +02004383 goto done;
Eric V. Smithb9cd3532011-03-12 10:08:48 -05004384 }
Eric Smith8c663262007-08-25 02:26:07 +00004385
Eric V. Smithb9cd3532011-03-12 10:08:48 -05004386 result = PyObject_Format(self_as_str, format_spec);
Eric Smithe4d63172010-09-13 20:48:43 +00004387 }
4388
4389done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004390 Py_XDECREF(self_as_str);
Eric Smith8c663262007-08-25 02:26:07 +00004391
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004392 return result;
Eric Smith8c663262007-08-25 02:26:07 +00004393}
4394
Martin v. Löwis00709aa2008-06-04 14:18:43 +00004395static PyObject *
4396object_sizeof(PyObject *self, PyObject *args)
4397{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004398 Py_ssize_t res, isize;
Martin v. Löwis00709aa2008-06-04 14:18:43 +00004399
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004400 res = 0;
4401 isize = self->ob_type->tp_itemsize;
4402 if (isize > 0)
Antoine Pitroua6545102015-03-10 22:32:00 +01004403 res = Py_SIZE(self) * isize;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004404 res += self->ob_type->tp_basicsize;
Martin v. Löwis00709aa2008-06-04 14:18:43 +00004405
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004406 return PyLong_FromSsize_t(res);
Martin v. Löwis00709aa2008-06-04 14:18:43 +00004407}
4408
Benjamin Peterson82b00c12011-05-24 11:09:06 -05004409/* __dir__ for generic objects: returns __dict__, __class__,
4410 and recursively up the __class__.__bases__ chain.
4411*/
4412static PyObject *
4413object_dir(PyObject *self, PyObject *args)
4414{
4415 PyObject *result = NULL;
4416 PyObject *dict = NULL;
4417 PyObject *itsclass = NULL;
4418
4419 /* Get __dict__ (which may or may not be a real dict...) */
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02004420 dict = _PyObject_GetAttrId(self, &PyId___dict__);
Benjamin Peterson82b00c12011-05-24 11:09:06 -05004421 if (dict == NULL) {
4422 PyErr_Clear();
4423 dict = PyDict_New();
4424 }
4425 else if (!PyDict_Check(dict)) {
4426 Py_DECREF(dict);
4427 dict = PyDict_New();
4428 }
4429 else {
4430 /* Copy __dict__ to avoid mutating it. */
4431 PyObject *temp = PyDict_Copy(dict);
4432 Py_DECREF(dict);
4433 dict = temp;
4434 }
4435
4436 if (dict == NULL)
4437 goto error;
4438
4439 /* Merge in attrs reachable from its class. */
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02004440 itsclass = _PyObject_GetAttrId(self, &PyId___class__);
Benjamin Peterson82b00c12011-05-24 11:09:06 -05004441 if (itsclass == NULL)
4442 /* XXX(tomer): Perhaps fall back to obj->ob_type if no
4443 __class__ exists? */
4444 PyErr_Clear();
4445 else if (merge_class_dict(dict, itsclass) != 0)
4446 goto error;
4447
4448 result = PyDict_Keys(dict);
4449 /* fall through */
4450error:
4451 Py_XDECREF(itsclass);
4452 Py_XDECREF(dict);
4453 return result;
4454}
4455
Guido van Rossum3926a632001-09-25 16:25:58 +00004456static PyMethodDef object_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004457 {"__reduce_ex__", object_reduce_ex, METH_VARARGS,
4458 PyDoc_STR("helper for pickle")},
4459 {"__reduce__", object_reduce, METH_VARARGS,
4460 PyDoc_STR("helper for pickle")},
4461 {"__subclasshook__", object_subclasshook, METH_CLASS | METH_VARARGS,
4462 object_subclasshook_doc},
Nick Coghland78448e2016-07-30 16:26:03 +10004463 {"__init_subclass__", object_init_subclass, METH_CLASS | METH_NOARGS,
4464 object_init_subclass_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004465 {"__format__", object_format, METH_VARARGS,
4466 PyDoc_STR("default object formatter")},
4467 {"__sizeof__", object_sizeof, METH_NOARGS,
Benjamin Petersonfbe56bb2011-05-24 12:42:51 -05004468 PyDoc_STR("__sizeof__() -> int\nsize of object in memory, in bytes")},
Benjamin Peterson82b00c12011-05-24 11:09:06 -05004469 {"__dir__", object_dir, METH_NOARGS,
Benjamin Petersonc7284122011-05-24 12:46:15 -05004470 PyDoc_STR("__dir__() -> list\ndefault dir() implementation")},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004471 {0}
Guido van Rossum3926a632001-09-25 16:25:58 +00004472};
4473
Guido van Rossum036f9992003-02-21 22:02:54 +00004474
Tim Peters6d6c1a32001-08-02 04:15:00 +00004475PyTypeObject PyBaseObject_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004476 PyVarObject_HEAD_INIT(&PyType_Type, 0)
4477 "object", /* tp_name */
4478 sizeof(PyObject), /* tp_basicsize */
4479 0, /* tp_itemsize */
4480 object_dealloc, /* tp_dealloc */
4481 0, /* tp_print */
4482 0, /* tp_getattr */
4483 0, /* tp_setattr */
4484 0, /* tp_reserved */
4485 object_repr, /* tp_repr */
4486 0, /* tp_as_number */
4487 0, /* tp_as_sequence */
4488 0, /* tp_as_mapping */
4489 (hashfunc)_Py_HashPointer, /* tp_hash */
4490 0, /* tp_call */
4491 object_str, /* tp_str */
4492 PyObject_GenericGetAttr, /* tp_getattro */
4493 PyObject_GenericSetAttr, /* tp_setattro */
4494 0, /* tp_as_buffer */
Larry Hastings5c661892014-01-24 06:17:25 -08004495 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Larry Hastings2623c8c2014-02-08 22:15:29 -08004496 PyDoc_STR("object()\n--\n\nThe most base type"), /* tp_doc */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004497 0, /* tp_traverse */
4498 0, /* tp_clear */
4499 object_richcompare, /* tp_richcompare */
4500 0, /* tp_weaklistoffset */
4501 0, /* tp_iter */
4502 0, /* tp_iternext */
4503 object_methods, /* tp_methods */
4504 0, /* tp_members */
4505 object_getsets, /* tp_getset */
4506 0, /* tp_base */
4507 0, /* tp_dict */
4508 0, /* tp_descr_get */
4509 0, /* tp_descr_set */
4510 0, /* tp_dictoffset */
4511 object_init, /* tp_init */
4512 PyType_GenericAlloc, /* tp_alloc */
4513 object_new, /* tp_new */
4514 PyObject_Del, /* tp_free */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004515};
4516
4517
Guido van Rossum50e9fb92006-08-17 05:42:55 +00004518/* Add the methods from tp_methods to the __dict__ in a type object */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004519
4520static int
4521add_methods(PyTypeObject *type, PyMethodDef *meth)
4522{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004523 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004524
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004525 for (; meth->ml_name != NULL; meth++) {
4526 PyObject *descr;
Benjamin Peterson89a6e9a2012-05-08 09:22:24 -04004527 int err;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004528 if (PyDict_GetItemString(dict, meth->ml_name) &&
4529 !(meth->ml_flags & METH_COEXIST))
4530 continue;
4531 if (meth->ml_flags & METH_CLASS) {
4532 if (meth->ml_flags & METH_STATIC) {
4533 PyErr_SetString(PyExc_ValueError,
4534 "method cannot be both class and static");
4535 return -1;
4536 }
4537 descr = PyDescr_NewClassMethod(type, meth);
4538 }
4539 else if (meth->ml_flags & METH_STATIC) {
Andrew Svetlov3ba3a3e2012-12-25 13:32:35 +02004540 PyObject *cfunc = PyCFunction_NewEx(meth, (PyObject*)type, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004541 if (cfunc == NULL)
4542 return -1;
4543 descr = PyStaticMethod_New(cfunc);
4544 Py_DECREF(cfunc);
4545 }
4546 else {
4547 descr = PyDescr_NewMethod(type, meth);
4548 }
4549 if (descr == NULL)
4550 return -1;
Benjamin Peterson89a6e9a2012-05-08 09:22:24 -04004551 err = PyDict_SetItemString(dict, meth->ml_name, descr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004552 Py_DECREF(descr);
Benjamin Peterson89a6e9a2012-05-08 09:22:24 -04004553 if (err < 0)
4554 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004555 }
4556 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004557}
4558
4559static int
Guido van Rossum6f799372001-09-20 20:46:19 +00004560add_members(PyTypeObject *type, PyMemberDef *memb)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004561{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004562 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004563
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004564 for (; memb->name != NULL; memb++) {
4565 PyObject *descr;
4566 if (PyDict_GetItemString(dict, memb->name))
4567 continue;
4568 descr = PyDescr_NewMember(type, memb);
4569 if (descr == NULL)
4570 return -1;
Benjamin Peterson27007dc2016-07-06 23:26:32 -07004571 if (PyDict_SetItemString(dict, memb->name, descr) < 0) {
4572 Py_DECREF(descr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004573 return -1;
Benjamin Peterson27007dc2016-07-06 23:26:32 -07004574 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004575 Py_DECREF(descr);
4576 }
4577 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004578}
4579
4580static int
Guido van Rossum32d34c82001-09-20 21:45:26 +00004581add_getset(PyTypeObject *type, PyGetSetDef *gsp)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004582{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004583 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004584
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004585 for (; gsp->name != NULL; gsp++) {
4586 PyObject *descr;
4587 if (PyDict_GetItemString(dict, gsp->name))
4588 continue;
4589 descr = PyDescr_NewGetSet(type, gsp);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004590
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004591 if (descr == NULL)
4592 return -1;
Benjamin Peterson27007dc2016-07-06 23:26:32 -07004593 if (PyDict_SetItemString(dict, gsp->name, descr) < 0) {
4594 Py_DECREF(descr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004595 return -1;
Benjamin Peterson27007dc2016-07-06 23:26:32 -07004596 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004597 Py_DECREF(descr);
4598 }
4599 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004600}
4601
Guido van Rossum13d52f02001-08-10 21:24:08 +00004602static void
4603inherit_special(PyTypeObject *type, PyTypeObject *base)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004604{
Tim Peters6d6c1a32001-08-02 04:15:00 +00004605
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004606 /* Copying basicsize is connected to the GC flags */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004607 if (!(type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
4608 (base->tp_flags & Py_TPFLAGS_HAVE_GC) &&
4609 (!type->tp_traverse && !type->tp_clear)) {
4610 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
4611 if (type->tp_traverse == NULL)
4612 type->tp_traverse = base->tp_traverse;
4613 if (type->tp_clear == NULL)
4614 type->tp_clear = base->tp_clear;
4615 }
4616 {
4617 /* The condition below could use some explanation.
4618 It appears that tp_new is not inherited for static types
4619 whose base class is 'object'; this seems to be a precaution
4620 so that old extension types don't suddenly become
4621 callable (object.__new__ wouldn't insure the invariants
4622 that the extension type's own factory function ensures).
4623 Heap types, of course, are under our control, so they do
4624 inherit tp_new; static extension types that specify some
Florent Xiclunaaa6c1d22011-12-12 18:54:29 +01004625 other built-in type as the default also
4626 inherit object.__new__. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004627 if (base != &PyBaseObject_Type ||
4628 (type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
4629 if (type->tp_new == NULL)
4630 type->tp_new = base->tp_new;
4631 }
4632 }
Benjamin Petersona7465e22010-07-05 15:01:22 +00004633 if (type->tp_basicsize == 0)
4634 type->tp_basicsize = base->tp_basicsize;
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00004635
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004636 /* Copy other non-function slots */
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00004637
4638#undef COPYVAL
4639#define COPYVAL(SLOT) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004640 if (type->SLOT == 0) type->SLOT = base->SLOT
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00004641
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004642 COPYVAL(tp_itemsize);
4643 COPYVAL(tp_weaklistoffset);
4644 COPYVAL(tp_dictoffset);
Thomas Wouters27d517b2007-02-25 20:39:11 +00004645
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004646 /* Setup fast subclass flags */
4647 if (PyType_IsSubtype(base, (PyTypeObject*)PyExc_BaseException))
4648 type->tp_flags |= Py_TPFLAGS_BASE_EXC_SUBCLASS;
4649 else if (PyType_IsSubtype(base, &PyType_Type))
4650 type->tp_flags |= Py_TPFLAGS_TYPE_SUBCLASS;
4651 else if (PyType_IsSubtype(base, &PyLong_Type))
4652 type->tp_flags |= Py_TPFLAGS_LONG_SUBCLASS;
4653 else if (PyType_IsSubtype(base, &PyBytes_Type))
4654 type->tp_flags |= Py_TPFLAGS_BYTES_SUBCLASS;
4655 else if (PyType_IsSubtype(base, &PyUnicode_Type))
4656 type->tp_flags |= Py_TPFLAGS_UNICODE_SUBCLASS;
4657 else if (PyType_IsSubtype(base, &PyTuple_Type))
4658 type->tp_flags |= Py_TPFLAGS_TUPLE_SUBCLASS;
4659 else if (PyType_IsSubtype(base, &PyList_Type))
4660 type->tp_flags |= Py_TPFLAGS_LIST_SUBCLASS;
4661 else if (PyType_IsSubtype(base, &PyDict_Type))
4662 type->tp_flags |= Py_TPFLAGS_DICT_SUBCLASS;
Guido van Rossum13d52f02001-08-10 21:24:08 +00004663}
4664
Guido van Rossum38938152006-08-21 23:36:26 +00004665static int
Guido van Rossumf5243f02008-01-01 04:06:48 +00004666overrides_hash(PyTypeObject *type)
Guido van Rossum38938152006-08-21 23:36:26 +00004667{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004668 PyObject *dict = type->tp_dict;
Victor Stinner3c1e4812012-03-26 22:10:51 +02004669 _Py_IDENTIFIER(__eq__);
Guido van Rossum38938152006-08-21 23:36:26 +00004670
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004671 assert(dict != NULL);
Victor Stinner3c1e4812012-03-26 22:10:51 +02004672 if (_PyDict_GetItemId(dict, &PyId___eq__) != NULL)
4673 return 1;
4674 if (_PyDict_GetItemId(dict, &PyId___hash__) != NULL)
4675 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004676 return 0;
Guido van Rossum38938152006-08-21 23:36:26 +00004677}
4678
Guido van Rossum13d52f02001-08-10 21:24:08 +00004679static void
4680inherit_slots(PyTypeObject *type, PyTypeObject *base)
4681{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004682 PyTypeObject *basebase;
Guido van Rossum13d52f02001-08-10 21:24:08 +00004683
4684#undef SLOTDEFINED
Tim Peters6d6c1a32001-08-02 04:15:00 +00004685#undef COPYSLOT
4686#undef COPYNUM
4687#undef COPYSEQ
4688#undef COPYMAP
Guido van Rossum5af588b2001-10-12 14:13:21 +00004689#undef COPYBUF
Guido van Rossum13d52f02001-08-10 21:24:08 +00004690
4691#define SLOTDEFINED(SLOT) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004692 (base->SLOT != 0 && \
4693 (basebase == NULL || base->SLOT != basebase->SLOT))
Guido van Rossum13d52f02001-08-10 21:24:08 +00004694
Tim Peters6d6c1a32001-08-02 04:15:00 +00004695#define COPYSLOT(SLOT) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004696 if (!type->SLOT && SLOTDEFINED(SLOT)) type->SLOT = base->SLOT
Tim Peters6d6c1a32001-08-02 04:15:00 +00004697
Yury Selivanov75445082015-05-11 22:57:16 -04004698#define COPYASYNC(SLOT) COPYSLOT(tp_as_async->SLOT)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004699#define COPYNUM(SLOT) COPYSLOT(tp_as_number->SLOT)
4700#define COPYSEQ(SLOT) COPYSLOT(tp_as_sequence->SLOT)
4701#define COPYMAP(SLOT) COPYSLOT(tp_as_mapping->SLOT)
Tim Petersfc57ccb2001-10-12 02:38:24 +00004702#define COPYBUF(SLOT) COPYSLOT(tp_as_buffer->SLOT)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004703
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004704 /* This won't inherit indirect slots (from tp_as_number etc.)
4705 if type doesn't provide the space. */
Guido van Rossum13d52f02001-08-10 21:24:08 +00004706
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004707 if (type->tp_as_number != NULL && base->tp_as_number != NULL) {
4708 basebase = base->tp_base;
4709 if (basebase->tp_as_number == NULL)
4710 basebase = NULL;
4711 COPYNUM(nb_add);
4712 COPYNUM(nb_subtract);
4713 COPYNUM(nb_multiply);
4714 COPYNUM(nb_remainder);
4715 COPYNUM(nb_divmod);
4716 COPYNUM(nb_power);
4717 COPYNUM(nb_negative);
4718 COPYNUM(nb_positive);
4719 COPYNUM(nb_absolute);
4720 COPYNUM(nb_bool);
4721 COPYNUM(nb_invert);
4722 COPYNUM(nb_lshift);
4723 COPYNUM(nb_rshift);
4724 COPYNUM(nb_and);
4725 COPYNUM(nb_xor);
4726 COPYNUM(nb_or);
4727 COPYNUM(nb_int);
4728 COPYNUM(nb_float);
4729 COPYNUM(nb_inplace_add);
4730 COPYNUM(nb_inplace_subtract);
4731 COPYNUM(nb_inplace_multiply);
4732 COPYNUM(nb_inplace_remainder);
4733 COPYNUM(nb_inplace_power);
4734 COPYNUM(nb_inplace_lshift);
4735 COPYNUM(nb_inplace_rshift);
4736 COPYNUM(nb_inplace_and);
4737 COPYNUM(nb_inplace_xor);
4738 COPYNUM(nb_inplace_or);
4739 COPYNUM(nb_true_divide);
4740 COPYNUM(nb_floor_divide);
4741 COPYNUM(nb_inplace_true_divide);
4742 COPYNUM(nb_inplace_floor_divide);
4743 COPYNUM(nb_index);
Benjamin Petersond51374e2014-04-09 23:55:56 -04004744 COPYNUM(nb_matrix_multiply);
4745 COPYNUM(nb_inplace_matrix_multiply);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004746 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004747
Yury Selivanov75445082015-05-11 22:57:16 -04004748 if (type->tp_as_async != NULL && base->tp_as_async != NULL) {
4749 basebase = base->tp_base;
4750 if (basebase->tp_as_async == NULL)
4751 basebase = NULL;
4752 COPYASYNC(am_await);
4753 COPYASYNC(am_aiter);
4754 COPYASYNC(am_anext);
4755 }
4756
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004757 if (type->tp_as_sequence != NULL && base->tp_as_sequence != NULL) {
4758 basebase = base->tp_base;
4759 if (basebase->tp_as_sequence == NULL)
4760 basebase = NULL;
4761 COPYSEQ(sq_length);
4762 COPYSEQ(sq_concat);
4763 COPYSEQ(sq_repeat);
4764 COPYSEQ(sq_item);
4765 COPYSEQ(sq_ass_item);
4766 COPYSEQ(sq_contains);
4767 COPYSEQ(sq_inplace_concat);
4768 COPYSEQ(sq_inplace_repeat);
4769 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004770
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004771 if (type->tp_as_mapping != NULL && base->tp_as_mapping != NULL) {
4772 basebase = base->tp_base;
4773 if (basebase->tp_as_mapping == NULL)
4774 basebase = NULL;
4775 COPYMAP(mp_length);
4776 COPYMAP(mp_subscript);
4777 COPYMAP(mp_ass_subscript);
4778 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004779
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004780 if (type->tp_as_buffer != NULL && base->tp_as_buffer != NULL) {
4781 basebase = base->tp_base;
4782 if (basebase->tp_as_buffer == NULL)
4783 basebase = NULL;
4784 COPYBUF(bf_getbuffer);
4785 COPYBUF(bf_releasebuffer);
4786 }
Tim Petersfc57ccb2001-10-12 02:38:24 +00004787
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004788 basebase = base->tp_base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004789
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004790 COPYSLOT(tp_dealloc);
4791 if (type->tp_getattr == NULL && type->tp_getattro == NULL) {
4792 type->tp_getattr = base->tp_getattr;
4793 type->tp_getattro = base->tp_getattro;
4794 }
4795 if (type->tp_setattr == NULL && type->tp_setattro == NULL) {
4796 type->tp_setattr = base->tp_setattr;
4797 type->tp_setattro = base->tp_setattro;
4798 }
4799 /* tp_reserved is ignored */
4800 COPYSLOT(tp_repr);
4801 /* tp_hash see tp_richcompare */
4802 COPYSLOT(tp_call);
4803 COPYSLOT(tp_str);
4804 {
4805 /* Copy comparison-related slots only when
4806 not overriding them anywhere */
4807 if (type->tp_richcompare == NULL &&
4808 type->tp_hash == NULL &&
4809 !overrides_hash(type))
4810 {
4811 type->tp_richcompare = base->tp_richcompare;
4812 type->tp_hash = base->tp_hash;
4813 }
4814 }
4815 {
4816 COPYSLOT(tp_iter);
4817 COPYSLOT(tp_iternext);
4818 }
4819 {
4820 COPYSLOT(tp_descr_get);
4821 COPYSLOT(tp_descr_set);
4822 COPYSLOT(tp_dictoffset);
4823 COPYSLOT(tp_init);
4824 COPYSLOT(tp_alloc);
4825 COPYSLOT(tp_is_gc);
Antoine Pitrou796564c2013-07-30 19:59:21 +02004826 if ((type->tp_flags & Py_TPFLAGS_HAVE_FINALIZE) &&
4827 (base->tp_flags & Py_TPFLAGS_HAVE_FINALIZE)) {
4828 COPYSLOT(tp_finalize);
4829 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004830 if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) ==
4831 (base->tp_flags & Py_TPFLAGS_HAVE_GC)) {
4832 /* They agree about gc. */
4833 COPYSLOT(tp_free);
4834 }
4835 else if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
4836 type->tp_free == NULL &&
4837 base->tp_free == PyObject_Free) {
4838 /* A bit of magic to plug in the correct default
4839 * tp_free function when a derived class adds gc,
4840 * didn't define tp_free, and the base uses the
4841 * default non-gc tp_free.
4842 */
4843 type->tp_free = PyObject_GC_Del;
4844 }
4845 /* else they didn't agree about gc, and there isn't something
4846 * obvious to be done -- the type is on its own.
4847 */
4848 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004849}
4850
Jeremy Hylton938ace62002-07-17 16:30:39 +00004851static int add_operators(PyTypeObject *);
Guido van Rossum13d52f02001-08-10 21:24:08 +00004852
Tim Peters6d6c1a32001-08-02 04:15:00 +00004853int
Guido van Rossum528b7eb2001-08-07 17:24:28 +00004854PyType_Ready(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004855{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004856 PyObject *dict, *bases;
4857 PyTypeObject *base;
4858 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004859
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004860 if (type->tp_flags & Py_TPFLAGS_READY) {
4861 assert(type->tp_dict != NULL);
4862 return 0;
4863 }
4864 assert((type->tp_flags & Py_TPFLAGS_READYING) == 0);
Guido van Rossumd614f972001-08-10 17:39:49 +00004865
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004866 type->tp_flags |= Py_TPFLAGS_READYING;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004867
Tim Peters36eb4df2003-03-23 03:33:13 +00004868#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004869 /* PyType_Ready is the closest thing we have to a choke point
4870 * for type objects, so is the best place I can think of to try
4871 * to get type objects into the doubly-linked list of all objects.
4872 * Still, not all type objects go thru PyType_Ready.
4873 */
4874 _Py_AddToAllObjects((PyObject *)type, 0);
Tim Peters36eb4df2003-03-23 03:33:13 +00004875#endif
4876
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004877 /* Initialize tp_base (defaults to BaseObject unless that's us) */
4878 base = type->tp_base;
4879 if (base == NULL && type != &PyBaseObject_Type) {
4880 base = type->tp_base = &PyBaseObject_Type;
4881 Py_INCREF(base);
4882 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004883
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004884 /* Now the only way base can still be NULL is if type is
4885 * &PyBaseObject_Type.
4886 */
Guido van Rossum692cdbc2006-03-10 02:04:28 +00004887
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004888 /* Initialize the base class */
4889 if (base != NULL && base->tp_dict == NULL) {
4890 if (PyType_Ready(base) < 0)
4891 goto error;
4892 }
Guido van Rossum323a9cf2002-08-14 17:26:30 +00004893
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004894 /* Initialize ob_type if NULL. This means extensions that want to be
4895 compilable separately on Windows can call PyType_Ready() instead of
4896 initializing the ob_type field of their type objects. */
4897 /* The test for base != NULL is really unnecessary, since base is only
4898 NULL when type is &PyBaseObject_Type, and we know its ob_type is
4899 not NULL (it's initialized to &PyType_Type). But coverity doesn't
4900 know that. */
4901 if (Py_TYPE(type) == NULL && base != NULL)
4902 Py_TYPE(type) = Py_TYPE(base);
Guido van Rossum0986d822002-04-08 01:38:42 +00004903
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004904 /* Initialize tp_bases */
4905 bases = type->tp_bases;
4906 if (bases == NULL) {
4907 if (base == NULL)
4908 bases = PyTuple_New(0);
4909 else
4910 bases = PyTuple_Pack(1, base);
4911 if (bases == NULL)
4912 goto error;
4913 type->tp_bases = bases;
4914 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004915
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004916 /* Initialize tp_dict */
4917 dict = type->tp_dict;
4918 if (dict == NULL) {
4919 dict = PyDict_New();
4920 if (dict == NULL)
4921 goto error;
4922 type->tp_dict = dict;
4923 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004924
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004925 /* Add type-specific descriptors to tp_dict */
4926 if (add_operators(type) < 0)
4927 goto error;
4928 if (type->tp_methods != NULL) {
4929 if (add_methods(type, type->tp_methods) < 0)
4930 goto error;
4931 }
4932 if (type->tp_members != NULL) {
4933 if (add_members(type, type->tp_members) < 0)
4934 goto error;
4935 }
4936 if (type->tp_getset != NULL) {
4937 if (add_getset(type, type->tp_getset) < 0)
4938 goto error;
4939 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004940
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004941 /* Calculate method resolution order */
Benjamin Peterson104b9e02015-02-05 22:29:14 -05004942 if (mro_internal(type, NULL) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004943 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004944
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004945 /* Inherit special flags from dominant base */
4946 if (type->tp_base != NULL)
4947 inherit_special(type, type->tp_base);
Guido van Rossum13d52f02001-08-10 21:24:08 +00004948
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004949 /* Initialize tp_dict properly */
4950 bases = type->tp_mro;
4951 assert(bases != NULL);
4952 assert(PyTuple_Check(bases));
4953 n = PyTuple_GET_SIZE(bases);
4954 for (i = 1; i < n; i++) {
4955 PyObject *b = PyTuple_GET_ITEM(bases, i);
4956 if (PyType_Check(b))
4957 inherit_slots(type, (PyTypeObject *)b);
4958 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004959
Serhiy Storchakae09bcc82015-01-28 11:03:33 +02004960 /* All bases of statically allocated type should be statically allocated */
4961 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE))
4962 for (i = 0; i < n; i++) {
4963 PyObject *b = PyTuple_GET_ITEM(bases, i);
4964 if (PyType_Check(b) &&
4965 (((PyTypeObject *)b)->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
4966 PyErr_Format(PyExc_TypeError,
4967 "type '%.100s' is not dynamically allocated but "
4968 "its base type '%.100s' is dynamically allocated",
4969 type->tp_name, ((PyTypeObject *)b)->tp_name);
4970 goto error;
4971 }
4972 }
4973
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004974 /* Sanity check for tp_free. */
4975 if (PyType_IS_GC(type) && (type->tp_flags & Py_TPFLAGS_BASETYPE) &&
4976 (type->tp_free == NULL || type->tp_free == PyObject_Del)) {
4977 /* This base class needs to call tp_free, but doesn't have
4978 * one, or its tp_free is for non-gc'ed objects.
4979 */
4980 PyErr_Format(PyExc_TypeError, "type '%.100s' participates in "
4981 "gc and is a base type but has inappropriate "
4982 "tp_free slot",
4983 type->tp_name);
4984 goto error;
4985 }
Tim Peters3cfe7542003-05-21 21:29:48 +00004986
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004987 /* if the type dictionary doesn't contain a __doc__, set it from
4988 the tp_doc slot.
4989 */
Victor Stinner3c1e4812012-03-26 22:10:51 +02004990 if (_PyDict_GetItemId(type->tp_dict, &PyId___doc__) == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004991 if (type->tp_doc != NULL) {
Larry Hastings2623c8c2014-02-08 22:15:29 -08004992 const char *old_doc = _PyType_DocWithoutSignature(type->tp_name,
4993 type->tp_doc);
Larry Hastings5c661892014-01-24 06:17:25 -08004994 PyObject *doc = PyUnicode_FromString(old_doc);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004995 if (doc == NULL)
4996 goto error;
Victor Stinner5967bf42013-07-17 22:01:37 +02004997 if (_PyDict_SetItemId(type->tp_dict, &PyId___doc__, doc) < 0) {
4998 Py_DECREF(doc);
4999 goto error;
5000 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005001 Py_DECREF(doc);
5002 } else {
Victor Stinner5967bf42013-07-17 22:01:37 +02005003 if (_PyDict_SetItemId(type->tp_dict,
5004 &PyId___doc__, Py_None) < 0)
5005 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005006 }
5007 }
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00005008
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005009 /* Hack for tp_hash and __hash__.
5010 If after all that, tp_hash is still NULL, and __hash__ is not in
5011 tp_dict, set tp_hash to PyObject_HashNotImplemented and
5012 tp_dict['__hash__'] equal to None.
5013 This signals that __hash__ is not inherited.
5014 */
5015 if (type->tp_hash == NULL) {
Victor Stinner3c1e4812012-03-26 22:10:51 +02005016 if (_PyDict_GetItemId(type->tp_dict, &PyId___hash__) == NULL) {
5017 if (_PyDict_SetItemId(type->tp_dict, &PyId___hash__, Py_None) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005018 goto error;
5019 type->tp_hash = PyObject_HashNotImplemented;
5020 }
5021 }
Guido van Rossum38938152006-08-21 23:36:26 +00005022
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005023 /* Some more special stuff */
5024 base = type->tp_base;
5025 if (base != NULL) {
Yury Selivanov75445082015-05-11 22:57:16 -04005026 if (type->tp_as_async == NULL)
5027 type->tp_as_async = base->tp_as_async;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005028 if (type->tp_as_number == NULL)
5029 type->tp_as_number = base->tp_as_number;
5030 if (type->tp_as_sequence == NULL)
5031 type->tp_as_sequence = base->tp_as_sequence;
5032 if (type->tp_as_mapping == NULL)
5033 type->tp_as_mapping = base->tp_as_mapping;
5034 if (type->tp_as_buffer == NULL)
5035 type->tp_as_buffer = base->tp_as_buffer;
5036 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00005037
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005038 /* Link into each base class's list of subclasses */
5039 bases = type->tp_bases;
5040 n = PyTuple_GET_SIZE(bases);
5041 for (i = 0; i < n; i++) {
5042 PyObject *b = PyTuple_GET_ITEM(bases, i);
5043 if (PyType_Check(b) &&
5044 add_subclass((PyTypeObject *)b, type) < 0)
5045 goto error;
5046 }
Guido van Rossum1c450732001-10-08 15:18:27 +00005047
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005048 /* All done -- set the ready flag */
5049 assert(type->tp_dict != NULL);
5050 type->tp_flags =
5051 (type->tp_flags & ~Py_TPFLAGS_READYING) | Py_TPFLAGS_READY;
5052 return 0;
Guido van Rossumd614f972001-08-10 17:39:49 +00005053
5054 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005055 type->tp_flags &= ~Py_TPFLAGS_READYING;
5056 return -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005057}
5058
Guido van Rossum1c450732001-10-08 15:18:27 +00005059static int
5060add_subclass(PyTypeObject *base, PyTypeObject *type)
5061{
Antoine Pitrou84745ab2013-10-29 21:31:25 +01005062 int result = -1;
5063 PyObject *dict, *key, *newobj;
Guido van Rossum1c450732001-10-08 15:18:27 +00005064
Antoine Pitrou84745ab2013-10-29 21:31:25 +01005065 dict = base->tp_subclasses;
5066 if (dict == NULL) {
5067 base->tp_subclasses = dict = PyDict_New();
5068 if (dict == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005069 return -1;
5070 }
Antoine Pitrou84745ab2013-10-29 21:31:25 +01005071 assert(PyDict_CheckExact(dict));
5072 key = PyLong_FromVoidPtr((void *) type);
5073 if (key == NULL)
Victor Stinner9812af82013-07-08 22:25:48 +02005074 return -1;
Antoine Pitrou84745ab2013-10-29 21:31:25 +01005075 newobj = PyWeakref_NewRef((PyObject *)type, NULL);
5076 if (newobj != NULL) {
5077 result = PyDict_SetItem(dict, key, newobj);
5078 Py_DECREF(newobj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005079 }
Antoine Pitrou84745ab2013-10-29 21:31:25 +01005080 Py_DECREF(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005081 return result;
Guido van Rossum1c450732001-10-08 15:18:27 +00005082}
5083
Benjamin Peterson104b9e02015-02-05 22:29:14 -05005084static int
5085add_all_subclasses(PyTypeObject *type, PyObject *bases)
5086{
5087 int res = 0;
5088
5089 if (bases) {
5090 Py_ssize_t i;
5091 for (i = 0; i < PyTuple_GET_SIZE(bases); i++) {
5092 PyObject *base = PyTuple_GET_ITEM(bases, i);
5093 if (PyType_Check(base) &&
5094 add_subclass((PyTypeObject*)base, type) < 0)
5095 res = -1;
5096 }
5097 }
5098
5099 return res;
5100}
5101
Michael W. Hudson98bbc492002-11-26 14:47:27 +00005102static void
5103remove_subclass(PyTypeObject *base, PyTypeObject *type)
5104{
Antoine Pitrou84745ab2013-10-29 21:31:25 +01005105 PyObject *dict, *key;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00005106
Antoine Pitrou84745ab2013-10-29 21:31:25 +01005107 dict = base->tp_subclasses;
5108 if (dict == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005109 return;
5110 }
Antoine Pitrou84745ab2013-10-29 21:31:25 +01005111 assert(PyDict_CheckExact(dict));
5112 key = PyLong_FromVoidPtr((void *) type);
5113 if (key == NULL || PyDict_DelItem(dict, key)) {
5114 /* This can happen if the type initialization errored out before
5115 the base subclasses were updated (e.g. a non-str __qualname__
5116 was passed in the type dict). */
5117 PyErr_Clear();
5118 }
5119 Py_XDECREF(key);
5120}
5121
5122static void
5123remove_all_subclasses(PyTypeObject *type, PyObject *bases)
5124{
5125 if (bases) {
5126 Py_ssize_t i;
5127 for (i = 0; i < PyTuple_GET_SIZE(bases); i++) {
5128 PyObject *base = PyTuple_GET_ITEM(bases, i);
5129 if (PyType_Check(base))
5130 remove_subclass((PyTypeObject*) base, type);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005131 }
5132 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +00005133}
Tim Peters6d6c1a32001-08-02 04:15:00 +00005134
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00005135static int
5136check_num_args(PyObject *ob, int n)
5137{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005138 if (!PyTuple_CheckExact(ob)) {
5139 PyErr_SetString(PyExc_SystemError,
5140 "PyArg_UnpackTuple() argument list is not a tuple");
5141 return 0;
5142 }
5143 if (n == PyTuple_GET_SIZE(ob))
5144 return 1;
5145 PyErr_Format(
5146 PyExc_TypeError,
5147 "expected %d arguments, got %zd", n, PyTuple_GET_SIZE(ob));
5148 return 0;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00005149}
5150
Tim Peters6d6c1a32001-08-02 04:15:00 +00005151/* Generic wrappers for overloadable 'operators' such as __getitem__ */
5152
5153/* There's a wrapper *function* for each distinct function typedef used
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005154 for type object slots (e.g. binaryfunc, ternaryfunc, etc.). There's a
Tim Peters6d6c1a32001-08-02 04:15:00 +00005155 wrapper *table* for each distinct operation (e.g. __len__, __add__).
5156 Most tables have only one entry; the tables for binary operators have two
5157 entries, one regular and one with reversed arguments. */
5158
5159static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00005160wrap_lenfunc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005161{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005162 lenfunc func = (lenfunc)wrapped;
5163 Py_ssize_t res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005164
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005165 if (!check_num_args(args, 0))
5166 return NULL;
5167 res = (*func)(self);
5168 if (res == -1 && PyErr_Occurred())
5169 return NULL;
5170 return PyLong_FromLong((long)res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005171}
5172
Tim Peters6d6c1a32001-08-02 04:15:00 +00005173static PyObject *
Raymond Hettingerf34f2642003-10-11 17:29:04 +00005174wrap_inquirypred(PyObject *self, PyObject *args, void *wrapped)
5175{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005176 inquiry func = (inquiry)wrapped;
5177 int res;
Raymond Hettingerf34f2642003-10-11 17:29:04 +00005178
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005179 if (!check_num_args(args, 0))
5180 return NULL;
5181 res = (*func)(self);
5182 if (res == -1 && PyErr_Occurred())
5183 return NULL;
5184 return PyBool_FromLong((long)res);
Raymond Hettingerf34f2642003-10-11 17:29:04 +00005185}
5186
5187static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00005188wrap_binaryfunc(PyObject *self, PyObject *args, void *wrapped)
5189{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005190 binaryfunc func = (binaryfunc)wrapped;
5191 PyObject *other;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005192
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005193 if (!check_num_args(args, 1))
5194 return NULL;
5195 other = PyTuple_GET_ITEM(args, 0);
5196 return (*func)(self, other);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005197}
5198
5199static PyObject *
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00005200wrap_binaryfunc_l(PyObject *self, PyObject *args, void *wrapped)
5201{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005202 binaryfunc func = (binaryfunc)wrapped;
5203 PyObject *other;
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00005204
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005205 if (!check_num_args(args, 1))
5206 return NULL;
5207 other = PyTuple_GET_ITEM(args, 0);
5208 return (*func)(self, other);
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00005209}
5210
5211static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00005212wrap_binaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
5213{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005214 binaryfunc func = (binaryfunc)wrapped;
5215 PyObject *other;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005216
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005217 if (!check_num_args(args, 1))
5218 return NULL;
5219 other = PyTuple_GET_ITEM(args, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005220 return (*func)(other, self);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005221}
5222
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00005223static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00005224wrap_ternaryfunc(PyObject *self, PyObject *args, void *wrapped)
5225{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005226 ternaryfunc func = (ternaryfunc)wrapped;
5227 PyObject *other;
5228 PyObject *third = Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005229
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005230 /* Note: This wrapper only works for __pow__() */
Tim Peters6d6c1a32001-08-02 04:15:00 +00005231
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005232 if (!PyArg_UnpackTuple(args, "", 1, 2, &other, &third))
5233 return NULL;
5234 return (*func)(self, other, third);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005235}
5236
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00005237static PyObject *
5238wrap_ternaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
5239{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005240 ternaryfunc func = (ternaryfunc)wrapped;
5241 PyObject *other;
5242 PyObject *third = Py_None;
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00005243
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005244 /* Note: This wrapper only works for __pow__() */
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00005245
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005246 if (!PyArg_UnpackTuple(args, "", 1, 2, &other, &third))
5247 return NULL;
5248 return (*func)(other, self, third);
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00005249}
5250
Tim Peters6d6c1a32001-08-02 04:15:00 +00005251static PyObject *
5252wrap_unaryfunc(PyObject *self, PyObject *args, void *wrapped)
5253{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005254 unaryfunc func = (unaryfunc)wrapped;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005255
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005256 if (!check_num_args(args, 0))
5257 return NULL;
5258 return (*func)(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005259}
5260
Tim Peters6d6c1a32001-08-02 04:15:00 +00005261static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00005262wrap_indexargfunc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005263{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005264 ssizeargfunc func = (ssizeargfunc)wrapped;
5265 PyObject* o;
5266 Py_ssize_t i;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005267
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005268 if (!PyArg_UnpackTuple(args, "", 1, 1, &o))
5269 return NULL;
5270 i = PyNumber_AsSsize_t(o, PyExc_OverflowError);
5271 if (i == -1 && PyErr_Occurred())
5272 return NULL;
5273 return (*func)(self, i);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005274}
5275
Martin v. Löwis18e16552006-02-15 17:27:45 +00005276static Py_ssize_t
Guido van Rossum5d815f32001-08-17 21:57:47 +00005277getindex(PyObject *self, PyObject *arg)
5278{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005279 Py_ssize_t i;
Guido van Rossum5d815f32001-08-17 21:57:47 +00005280
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005281 i = PyNumber_AsSsize_t(arg, PyExc_OverflowError);
5282 if (i == -1 && PyErr_Occurred())
5283 return -1;
5284 if (i < 0) {
5285 PySequenceMethods *sq = Py_TYPE(self)->tp_as_sequence;
5286 if (sq && sq->sq_length) {
5287 Py_ssize_t n = (*sq->sq_length)(self);
5288 if (n < 0)
5289 return -1;
5290 i += n;
5291 }
5292 }
5293 return i;
Guido van Rossum5d815f32001-08-17 21:57:47 +00005294}
5295
5296static PyObject *
5297wrap_sq_item(PyObject *self, PyObject *args, void *wrapped)
5298{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005299 ssizeargfunc func = (ssizeargfunc)wrapped;
5300 PyObject *arg;
5301 Py_ssize_t i;
Guido van Rossum5d815f32001-08-17 21:57:47 +00005302
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005303 if (PyTuple_GET_SIZE(args) == 1) {
5304 arg = PyTuple_GET_ITEM(args, 0);
5305 i = getindex(self, arg);
5306 if (i == -1 && PyErr_Occurred())
5307 return NULL;
5308 return (*func)(self, i);
5309 }
5310 check_num_args(args, 1);
5311 assert(PyErr_Occurred());
5312 return NULL;
Guido van Rossum5d815f32001-08-17 21:57:47 +00005313}
5314
Tim Peters6d6c1a32001-08-02 04:15:00 +00005315static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00005316wrap_sq_setitem(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005317{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005318 ssizeobjargproc func = (ssizeobjargproc)wrapped;
5319 Py_ssize_t i;
5320 int res;
5321 PyObject *arg, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005322
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005323 if (!PyArg_UnpackTuple(args, "", 2, 2, &arg, &value))
5324 return NULL;
5325 i = getindex(self, arg);
5326 if (i == -1 && PyErr_Occurred())
5327 return NULL;
5328 res = (*func)(self, i, value);
5329 if (res == -1 && PyErr_Occurred())
5330 return NULL;
5331 Py_INCREF(Py_None);
5332 return Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005333}
5334
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00005335static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00005336wrap_sq_delitem(PyObject *self, PyObject *args, void *wrapped)
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00005337{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005338 ssizeobjargproc func = (ssizeobjargproc)wrapped;
5339 Py_ssize_t i;
5340 int res;
5341 PyObject *arg;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00005342
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005343 if (!check_num_args(args, 1))
5344 return NULL;
5345 arg = PyTuple_GET_ITEM(args, 0);
5346 i = getindex(self, arg);
5347 if (i == -1 && PyErr_Occurred())
5348 return NULL;
5349 res = (*func)(self, i, NULL);
5350 if (res == -1 && PyErr_Occurred())
5351 return NULL;
5352 Py_INCREF(Py_None);
5353 return Py_None;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00005354}
5355
Tim Peters6d6c1a32001-08-02 04:15:00 +00005356/* XXX objobjproc is a misnomer; should be objargpred */
5357static PyObject *
5358wrap_objobjproc(PyObject *self, PyObject *args, void *wrapped)
5359{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005360 objobjproc func = (objobjproc)wrapped;
5361 int res;
5362 PyObject *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005363
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005364 if (!check_num_args(args, 1))
5365 return NULL;
5366 value = PyTuple_GET_ITEM(args, 0);
5367 res = (*func)(self, value);
5368 if (res == -1 && PyErr_Occurred())
5369 return NULL;
5370 else
5371 return PyBool_FromLong(res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005372}
5373
Tim Peters6d6c1a32001-08-02 04:15:00 +00005374static PyObject *
5375wrap_objobjargproc(PyObject *self, PyObject *args, void *wrapped)
5376{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005377 objobjargproc func = (objobjargproc)wrapped;
5378 int res;
5379 PyObject *key, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005380
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005381 if (!PyArg_UnpackTuple(args, "", 2, 2, &key, &value))
5382 return NULL;
5383 res = (*func)(self, key, value);
5384 if (res == -1 && PyErr_Occurred())
5385 return NULL;
5386 Py_INCREF(Py_None);
5387 return Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005388}
5389
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00005390static PyObject *
5391wrap_delitem(PyObject *self, PyObject *args, void *wrapped)
5392{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005393 objobjargproc func = (objobjargproc)wrapped;
5394 int res;
5395 PyObject *key;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00005396
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005397 if (!check_num_args(args, 1))
5398 return NULL;
5399 key = PyTuple_GET_ITEM(args, 0);
5400 res = (*func)(self, key, NULL);
5401 if (res == -1 && PyErr_Occurred())
5402 return NULL;
5403 Py_INCREF(Py_None);
5404 return Py_None;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00005405}
5406
Guido van Rossum4dcdb782003-04-14 21:46:03 +00005407/* Helper to check for object.__setattr__ or __delattr__ applied to a type.
Guido van Rossum52b27052003-04-15 20:05:10 +00005408 This is called the Carlo Verre hack after its discoverer. */
Guido van Rossum4dcdb782003-04-14 21:46:03 +00005409static int
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02005410hackcheck(PyObject *self, setattrofunc func, const char *what)
Guido van Rossum4dcdb782003-04-14 21:46:03 +00005411{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005412 PyTypeObject *type = Py_TYPE(self);
5413 while (type && type->tp_flags & Py_TPFLAGS_HEAPTYPE)
5414 type = type->tp_base;
5415 /* If type is NULL now, this is a really weird type.
5416 In the spirit of backwards compatibility (?), just shut up. */
5417 if (type && type->tp_setattro != func) {
5418 PyErr_Format(PyExc_TypeError,
5419 "can't apply this %s to %s object",
5420 what,
5421 type->tp_name);
5422 return 0;
5423 }
5424 return 1;
Guido van Rossum4dcdb782003-04-14 21:46:03 +00005425}
5426
Tim Peters6d6c1a32001-08-02 04:15:00 +00005427static PyObject *
5428wrap_setattr(PyObject *self, PyObject *args, void *wrapped)
5429{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005430 setattrofunc func = (setattrofunc)wrapped;
5431 int res;
5432 PyObject *name, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005433
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005434 if (!PyArg_UnpackTuple(args, "", 2, 2, &name, &value))
5435 return NULL;
5436 if (!hackcheck(self, func, "__setattr__"))
5437 return NULL;
5438 res = (*func)(self, name, value);
5439 if (res < 0)
5440 return NULL;
5441 Py_INCREF(Py_None);
5442 return Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005443}
5444
5445static PyObject *
5446wrap_delattr(PyObject *self, PyObject *args, void *wrapped)
5447{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005448 setattrofunc func = (setattrofunc)wrapped;
5449 int res;
5450 PyObject *name;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005451
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005452 if (!check_num_args(args, 1))
5453 return NULL;
5454 name = PyTuple_GET_ITEM(args, 0);
5455 if (!hackcheck(self, func, "__delattr__"))
5456 return NULL;
5457 res = (*func)(self, name, NULL);
5458 if (res < 0)
5459 return NULL;
5460 Py_INCREF(Py_None);
5461 return Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005462}
5463
Tim Peters6d6c1a32001-08-02 04:15:00 +00005464static PyObject *
5465wrap_hashfunc(PyObject *self, PyObject *args, void *wrapped)
5466{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005467 hashfunc func = (hashfunc)wrapped;
Benjamin Peterson8035bc52010-10-23 16:20:50 +00005468 Py_hash_t res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005469
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005470 if (!check_num_args(args, 0))
5471 return NULL;
5472 res = (*func)(self);
5473 if (res == -1 && PyErr_Occurred())
5474 return NULL;
Benjamin Peterson8035bc52010-10-23 16:20:50 +00005475 return PyLong_FromSsize_t(res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005476}
5477
Tim Peters6d6c1a32001-08-02 04:15:00 +00005478static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00005479wrap_call(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005480{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005481 ternaryfunc func = (ternaryfunc)wrapped;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005482
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005483 return (*func)(self, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005484}
5485
Tim Peters6d6c1a32001-08-02 04:15:00 +00005486static PyObject *
Antoine Pitrou796564c2013-07-30 19:59:21 +02005487wrap_del(PyObject *self, PyObject *args, void *wrapped)
5488{
5489 destructor func = (destructor)wrapped;
5490
5491 if (!check_num_args(args, 0))
5492 return NULL;
5493
5494 (*func)(self);
5495 Py_RETURN_NONE;
5496}
5497
5498static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00005499wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op)
5500{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005501 richcmpfunc func = (richcmpfunc)wrapped;
5502 PyObject *other;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005503
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005504 if (!check_num_args(args, 1))
5505 return NULL;
5506 other = PyTuple_GET_ITEM(args, 0);
5507 return (*func)(self, other, op);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005508}
5509
5510#undef RICHCMP_WRAPPER
5511#define RICHCMP_WRAPPER(NAME, OP) \
5512static PyObject * \
5513richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \
5514{ \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005515 return wrap_richcmpfunc(self, args, wrapped, OP); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00005516}
5517
Jack Jansen8e938b42001-08-08 15:29:49 +00005518RICHCMP_WRAPPER(lt, Py_LT)
5519RICHCMP_WRAPPER(le, Py_LE)
5520RICHCMP_WRAPPER(eq, Py_EQ)
5521RICHCMP_WRAPPER(ne, Py_NE)
5522RICHCMP_WRAPPER(gt, Py_GT)
5523RICHCMP_WRAPPER(ge, Py_GE)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005524
Tim Peters6d6c1a32001-08-02 04:15:00 +00005525static PyObject *
5526wrap_next(PyObject *self, PyObject *args, void *wrapped)
5527{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005528 unaryfunc func = (unaryfunc)wrapped;
5529 PyObject *res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005530
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005531 if (!check_num_args(args, 0))
5532 return NULL;
5533 res = (*func)(self);
5534 if (res == NULL && !PyErr_Occurred())
5535 PyErr_SetNone(PyExc_StopIteration);
5536 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005537}
5538
Tim Peters6d6c1a32001-08-02 04:15:00 +00005539static PyObject *
5540wrap_descr_get(PyObject *self, PyObject *args, void *wrapped)
5541{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005542 descrgetfunc func = (descrgetfunc)wrapped;
5543 PyObject *obj;
5544 PyObject *type = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005545
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005546 if (!PyArg_UnpackTuple(args, "", 1, 2, &obj, &type))
5547 return NULL;
5548 if (obj == Py_None)
5549 obj = NULL;
5550 if (type == Py_None)
5551 type = NULL;
5552 if (type == NULL &&obj == NULL) {
5553 PyErr_SetString(PyExc_TypeError,
5554 "__get__(None, None) is invalid");
5555 return NULL;
5556 }
5557 return (*func)(self, obj, type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005558}
5559
Tim Peters6d6c1a32001-08-02 04:15:00 +00005560static PyObject *
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005561wrap_descr_set(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005562{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005563 descrsetfunc func = (descrsetfunc)wrapped;
5564 PyObject *obj, *value;
5565 int ret;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005566
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005567 if (!PyArg_UnpackTuple(args, "", 2, 2, &obj, &value))
5568 return NULL;
5569 ret = (*func)(self, obj, value);
5570 if (ret < 0)
5571 return NULL;
5572 Py_INCREF(Py_None);
5573 return Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005574}
Guido van Rossum22b13872002-08-06 21:41:44 +00005575
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00005576static PyObject *
5577wrap_descr_delete(PyObject *self, PyObject *args, void *wrapped)
5578{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005579 descrsetfunc func = (descrsetfunc)wrapped;
5580 PyObject *obj;
5581 int ret;
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00005582
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005583 if (!check_num_args(args, 1))
5584 return NULL;
5585 obj = PyTuple_GET_ITEM(args, 0);
5586 ret = (*func)(self, obj, NULL);
5587 if (ret < 0)
5588 return NULL;
5589 Py_INCREF(Py_None);
5590 return Py_None;
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00005591}
Tim Peters6d6c1a32001-08-02 04:15:00 +00005592
Tim Peters6d6c1a32001-08-02 04:15:00 +00005593static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00005594wrap_init(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005595{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005596 initproc func = (initproc)wrapped;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005597
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005598 if (func(self, args, kwds) < 0)
5599 return NULL;
5600 Py_INCREF(Py_None);
5601 return Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005602}
5603
Tim Peters6d6c1a32001-08-02 04:15:00 +00005604static PyObject *
Guido van Rossum0d231ed2001-08-06 16:50:37 +00005605tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005606{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005607 PyTypeObject *type, *subtype, *staticbase;
5608 PyObject *arg0, *res;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00005609
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005610 if (self == NULL || !PyType_Check(self))
5611 Py_FatalError("__new__() called with non-type 'self'");
5612 type = (PyTypeObject *)self;
5613 if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) {
5614 PyErr_Format(PyExc_TypeError,
5615 "%s.__new__(): not enough arguments",
5616 type->tp_name);
5617 return NULL;
5618 }
5619 arg0 = PyTuple_GET_ITEM(args, 0);
5620 if (!PyType_Check(arg0)) {
5621 PyErr_Format(PyExc_TypeError,
5622 "%s.__new__(X): X is not a type object (%s)",
5623 type->tp_name,
5624 Py_TYPE(arg0)->tp_name);
5625 return NULL;
5626 }
5627 subtype = (PyTypeObject *)arg0;
5628 if (!PyType_IsSubtype(subtype, type)) {
5629 PyErr_Format(PyExc_TypeError,
5630 "%s.__new__(%s): %s is not a subtype of %s",
5631 type->tp_name,
5632 subtype->tp_name,
5633 subtype->tp_name,
5634 type->tp_name);
5635 return NULL;
5636 }
Barry Warsaw60f01882001-08-22 19:24:42 +00005637
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005638 /* Check that the use doesn't do something silly and unsafe like
5639 object.__new__(dict). To do this, we check that the
5640 most derived base that's not a heap type is this type. */
5641 staticbase = subtype;
Martin v. Löwis9c564092012-06-23 23:20:45 +02005642 while (staticbase && (staticbase->tp_new == slot_tp_new))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005643 staticbase = staticbase->tp_base;
5644 /* If staticbase is NULL now, it is a really weird type.
5645 In the spirit of backwards compatibility (?), just shut up. */
5646 if (staticbase && staticbase->tp_new != type->tp_new) {
5647 PyErr_Format(PyExc_TypeError,
5648 "%s.__new__(%s) is not safe, use %s.__new__()",
5649 type->tp_name,
5650 subtype->tp_name,
Benjamin Petersone8239332014-11-26 23:03:11 -06005651 staticbase->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005652 return NULL;
5653 }
Barry Warsaw60f01882001-08-22 19:24:42 +00005654
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005655 args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
5656 if (args == NULL)
5657 return NULL;
5658 res = type->tp_new(subtype, args, kwds);
5659 Py_DECREF(args);
5660 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005661}
5662
Guido van Rossum0d231ed2001-08-06 16:50:37 +00005663static struct PyMethodDef tp_new_methoddef[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005664 {"__new__", (PyCFunction)tp_new_wrapper, METH_VARARGS|METH_KEYWORDS,
Larry Hastings2623c8c2014-02-08 22:15:29 -08005665 PyDoc_STR("__new__($type, *args, **kwargs)\n--\n\n"
Larry Hastings581ee362014-01-28 05:00:08 -08005666 "Create and return a new object. "
5667 "See help(type) for accurate signature.")},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005668 {0}
Tim Peters6d6c1a32001-08-02 04:15:00 +00005669};
5670
5671static int
Guido van Rossum0d231ed2001-08-06 16:50:37 +00005672add_tp_new_wrapper(PyTypeObject *type)
5673{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005674 PyObject *func;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00005675
Victor Stinner3c1e4812012-03-26 22:10:51 +02005676 if (_PyDict_GetItemId(type->tp_dict, &PyId___new__) != NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005677 return 0;
Andrew Svetlov3ba3a3e2012-12-25 13:32:35 +02005678 func = PyCFunction_NewEx(tp_new_methoddef, (PyObject *)type, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005679 if (func == NULL)
5680 return -1;
Victor Stinner3c1e4812012-03-26 22:10:51 +02005681 if (_PyDict_SetItemId(type->tp_dict, &PyId___new__, func)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005682 Py_DECREF(func);
5683 return -1;
5684 }
5685 Py_DECREF(func);
5686 return 0;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00005687}
5688
Guido van Rossumf040ede2001-08-07 16:40:56 +00005689/* Slot wrappers that call the corresponding __foo__ slot. See comments
5690 below at override_slots() for more explanation. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00005691
Guido van Rossumdc91b992001-08-08 22:26:22 +00005692#define SLOT0(FUNCNAME, OPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00005693static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00005694FUNCNAME(PyObject *self) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00005695{ \
Benjamin Petersonce798522012-01-22 11:24:29 -05005696 _Py_static_string(id, OPSTR); \
5697 return call_method(self, &id, "()"); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00005698}
5699
Guido van Rossumdc91b992001-08-08 22:26:22 +00005700#define SLOT1(FUNCNAME, OPSTR, ARG1TYPE, ARGCODES) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00005701static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00005702FUNCNAME(PyObject *self, ARG1TYPE arg1) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00005703{ \
Benjamin Petersonce798522012-01-22 11:24:29 -05005704 _Py_static_string(id, OPSTR); \
5705 return call_method(self, &id, "(" ARGCODES ")", arg1); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00005706}
5707
Guido van Rossumcd118802003-01-06 22:57:47 +00005708/* Boolean helper for SLOT1BINFULL().
5709 right.__class__ is a nontrivial subclass of left.__class__. */
5710static int
Victor Stinner3c1e4812012-03-26 22:10:51 +02005711method_is_overloaded(PyObject *left, PyObject *right, struct _Py_Identifier *name)
Guido van Rossumcd118802003-01-06 22:57:47 +00005712{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005713 PyObject *a, *b;
5714 int ok;
Guido van Rossumcd118802003-01-06 22:57:47 +00005715
Victor Stinner3c1e4812012-03-26 22:10:51 +02005716 b = _PyObject_GetAttrId((PyObject *)(Py_TYPE(right)), name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005717 if (b == NULL) {
5718 PyErr_Clear();
5719 /* If right doesn't have it, it's not overloaded */
5720 return 0;
5721 }
Guido van Rossumcd118802003-01-06 22:57:47 +00005722
Victor Stinner3c1e4812012-03-26 22:10:51 +02005723 a = _PyObject_GetAttrId((PyObject *)(Py_TYPE(left)), name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005724 if (a == NULL) {
5725 PyErr_Clear();
5726 Py_DECREF(b);
5727 /* If right has it but left doesn't, it's overloaded */
5728 return 1;
5729 }
Guido van Rossumcd118802003-01-06 22:57:47 +00005730
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005731 ok = PyObject_RichCompareBool(a, b, Py_NE);
5732 Py_DECREF(a);
5733 Py_DECREF(b);
5734 if (ok < 0) {
5735 PyErr_Clear();
5736 return 0;
5737 }
Guido van Rossumcd118802003-01-06 22:57:47 +00005738
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005739 return ok;
Guido van Rossumcd118802003-01-06 22:57:47 +00005740}
5741
Guido van Rossumdc91b992001-08-08 22:26:22 +00005742
5743#define SLOT1BINFULL(FUNCNAME, TESTFUNC, SLOTNAME, OPSTR, ROPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00005744static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00005745FUNCNAME(PyObject *self, PyObject *other) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00005746{ \
Benjamin Petersonce798522012-01-22 11:24:29 -05005747 _Py_static_string(op_id, OPSTR); \
5748 _Py_static_string(rop_id, ROPSTR); \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005749 int do_other = Py_TYPE(self) != Py_TYPE(other) && \
5750 Py_TYPE(other)->tp_as_number != NULL && \
5751 Py_TYPE(other)->tp_as_number->SLOTNAME == TESTFUNC; \
5752 if (Py_TYPE(self)->tp_as_number != NULL && \
5753 Py_TYPE(self)->tp_as_number->SLOTNAME == TESTFUNC) { \
5754 PyObject *r; \
5755 if (do_other && \
5756 PyType_IsSubtype(Py_TYPE(other), Py_TYPE(self)) && \
Victor Stinner3c1e4812012-03-26 22:10:51 +02005757 method_is_overloaded(self, other, &rop_id)) { \
Benjamin Petersonce798522012-01-22 11:24:29 -05005758 r = call_maybe(other, &rop_id, "(O)", self); \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005759 if (r != Py_NotImplemented) \
5760 return r; \
5761 Py_DECREF(r); \
5762 do_other = 0; \
5763 } \
Benjamin Petersonce798522012-01-22 11:24:29 -05005764 r = call_maybe(self, &op_id, "(O)", other); \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005765 if (r != Py_NotImplemented || \
5766 Py_TYPE(other) == Py_TYPE(self)) \
5767 return r; \
5768 Py_DECREF(r); \
5769 } \
5770 if (do_other) { \
Benjamin Petersonce798522012-01-22 11:24:29 -05005771 return call_maybe(other, &rop_id, "(O)", self); \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005772 } \
Brian Curtindfc80e32011-08-10 20:28:54 -05005773 Py_RETURN_NOTIMPLEMENTED; \
Guido van Rossumdc91b992001-08-08 22:26:22 +00005774}
5775
5776#define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005777 SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR)
Guido van Rossumdc91b992001-08-08 22:26:22 +00005778
5779#define SLOT2(FUNCNAME, OPSTR, ARG1TYPE, ARG2TYPE, ARGCODES) \
5780static PyObject * \
5781FUNCNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \
5782{ \
Benjamin Petersonce798522012-01-22 11:24:29 -05005783 _Py_static_string(id, #OPSTR); \
5784 return call_method(self, &id, "(" ARGCODES ")", arg1, arg2); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00005785}
5786
Martin v. Löwis18e16552006-02-15 17:27:45 +00005787static Py_ssize_t
Tim Peters6d6c1a32001-08-02 04:15:00 +00005788slot_sq_length(PyObject *self)
5789{
Benjamin Petersonce798522012-01-22 11:24:29 -05005790 PyObject *res = call_method(self, &PyId___len__, "()");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005791 Py_ssize_t len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005792
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005793 if (res == NULL)
5794 return -1;
5795 len = PyNumber_AsSsize_t(res, PyExc_OverflowError);
5796 Py_DECREF(res);
5797 if (len < 0) {
5798 if (!PyErr_Occurred())
5799 PyErr_SetString(PyExc_ValueError,
5800 "__len__() should return >= 0");
5801 return -1;
5802 }
5803 return len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005804}
5805
Guido van Rossumf4593e02001-10-03 12:09:30 +00005806/* Super-optimized version of slot_sq_item.
5807 Other slots could do the same... */
5808static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00005809slot_sq_item(PyObject *self, Py_ssize_t i)
Guido van Rossumf4593e02001-10-03 12:09:30 +00005810{
Victor Stinner5e877492016-08-19 18:19:42 +02005811 PyObject *func, *ival = NULL, *retval = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005812 descrgetfunc f;
Guido van Rossumf4593e02001-10-03 12:09:30 +00005813
Victor Stinner3c1e4812012-03-26 22:10:51 +02005814 func = _PyType_LookupId(Py_TYPE(self), &PyId___getitem__);
Victor Stinner018016d2016-08-19 18:17:37 +02005815 if (func == NULL) {
Victor Stinner3c1e4812012-03-26 22:10:51 +02005816 PyObject *getitem_str = _PyUnicode_FromId(&PyId___getitem__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005817 PyErr_SetObject(PyExc_AttributeError, getitem_str);
Victor Stinner018016d2016-08-19 18:17:37 +02005818 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005819 }
Victor Stinner018016d2016-08-19 18:17:37 +02005820
5821 f = Py_TYPE(func)->tp_descr_get;
5822 if (f == NULL) {
5823 Py_INCREF(func);
5824 }
5825 else {
5826 func = f(func, self, (PyObject *)(Py_TYPE(self)));
5827 if (func == NULL) {
5828 return NULL;
5829 }
5830 }
5831
5832 ival = PyLong_FromSsize_t(i);
5833 if (ival == NULL) {
5834 goto error;
5835 }
5836
Victor Stinner559bb6a2016-08-22 22:48:54 +02005837 retval = _PyObject_CallArg1(func, ival);
Victor Stinner018016d2016-08-19 18:17:37 +02005838 Py_DECREF(func);
Victor Stinner5e877492016-08-19 18:19:42 +02005839 Py_DECREF(ival);
Victor Stinner018016d2016-08-19 18:17:37 +02005840 return retval;
5841
5842error:
5843 Py_DECREF(func);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005844 return NULL;
Guido van Rossumf4593e02001-10-03 12:09:30 +00005845}
5846
Tim Peters6d6c1a32001-08-02 04:15:00 +00005847static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00005848slot_sq_ass_item(PyObject *self, Py_ssize_t index, PyObject *value)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005849{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005850 PyObject *res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005851
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005852 if (value == NULL)
Benjamin Petersonce798522012-01-22 11:24:29 -05005853 res = call_method(self, &PyId___delitem__, "(n)", index);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005854 else
Benjamin Petersonce798522012-01-22 11:24:29 -05005855 res = call_method(self, &PyId___setitem__, "(nO)", index, value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005856 if (res == NULL)
5857 return -1;
5858 Py_DECREF(res);
5859 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005860}
5861
5862static int
Tim Peters6d6c1a32001-08-02 04:15:00 +00005863slot_sq_contains(PyObject *self, PyObject *value)
5864{
Victor Stinnera7720f62016-08-19 17:48:51 +02005865 PyObject *func, *res;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005866 int result = -1;
Benjamin Petersonce798522012-01-22 11:24:29 -05005867 _Py_IDENTIFIER(__contains__);
Tim Petersbf9b2442003-03-23 05:35:36 +00005868
Benjamin Petersonce798522012-01-22 11:24:29 -05005869 func = lookup_maybe(self, &PyId___contains__);
Guido van Rossum97c1adf2016-08-18 09:22:23 -07005870 if (func == Py_None) {
5871 Py_DECREF(func);
5872 PyErr_Format(PyExc_TypeError,
5873 "'%.200s' object is not a container",
5874 Py_TYPE(self)->tp_name);
5875 return -1;
5876 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005877 if (func != NULL) {
Victor Stinner559bb6a2016-08-22 22:48:54 +02005878 res = _PyObject_CallArg1(func, value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005879 Py_DECREF(func);
5880 if (res != NULL) {
5881 result = PyObject_IsTrue(res);
5882 Py_DECREF(res);
5883 }
5884 }
5885 else if (! PyErr_Occurred()) {
5886 /* Possible results: -1 and 1 */
5887 result = (int)_PySequence_IterSearch(self, value,
5888 PY_ITERSEARCH_CONTAINS);
5889 }
5890 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005891}
5892
Tim Peters6d6c1a32001-08-02 04:15:00 +00005893#define slot_mp_length slot_sq_length
5894
Guido van Rossumdc91b992001-08-08 22:26:22 +00005895SLOT1(slot_mp_subscript, "__getitem__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00005896
5897static int
5898slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value)
5899{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005900 PyObject *res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005901
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005902 if (value == NULL)
Benjamin Petersonce798522012-01-22 11:24:29 -05005903 res = call_method(self, &PyId___delitem__, "(O)", key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005904 else
Benjamin Petersonce798522012-01-22 11:24:29 -05005905 res = call_method(self, &PyId___setitem__, "(OO)", key, value);
5906
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005907 if (res == NULL)
5908 return -1;
5909 Py_DECREF(res);
5910 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005911}
5912
Guido van Rossumdc91b992001-08-08 22:26:22 +00005913SLOT1BIN(slot_nb_add, nb_add, "__add__", "__radd__")
5914SLOT1BIN(slot_nb_subtract, nb_subtract, "__sub__", "__rsub__")
5915SLOT1BIN(slot_nb_multiply, nb_multiply, "__mul__", "__rmul__")
Benjamin Petersond51374e2014-04-09 23:55:56 -04005916SLOT1BIN(slot_nb_matrix_multiply, nb_matrix_multiply, "__matmul__", "__rmatmul__")
Guido van Rossumdc91b992001-08-08 22:26:22 +00005917SLOT1BIN(slot_nb_remainder, nb_remainder, "__mod__", "__rmod__")
5918SLOT1BIN(slot_nb_divmod, nb_divmod, "__divmod__", "__rdivmod__")
5919
Jeremy Hylton938ace62002-07-17 16:30:39 +00005920static PyObject *slot_nb_power(PyObject *, PyObject *, PyObject *);
Guido van Rossumdc91b992001-08-08 22:26:22 +00005921
5922SLOT1BINFULL(slot_nb_power_binary, slot_nb_power,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005923 nb_power, "__pow__", "__rpow__")
Guido van Rossumdc91b992001-08-08 22:26:22 +00005924
5925static PyObject *
5926slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus)
5927{
Benjamin Petersonce798522012-01-22 11:24:29 -05005928 _Py_IDENTIFIER(__pow__);
Guido van Rossum2730b132001-08-28 18:22:14 +00005929
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005930 if (modulus == Py_None)
5931 return slot_nb_power_binary(self, other);
5932 /* Three-arg power doesn't use __rpow__. But ternary_op
5933 can call this when the second argument's type uses
5934 slot_nb_power, so check before calling self.__pow__. */
5935 if (Py_TYPE(self)->tp_as_number != NULL &&
5936 Py_TYPE(self)->tp_as_number->nb_power == slot_nb_power) {
Benjamin Petersonce798522012-01-22 11:24:29 -05005937 return call_method(self, &PyId___pow__, "(OO)", other, modulus);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005938 }
Brian Curtindfc80e32011-08-10 20:28:54 -05005939 Py_RETURN_NOTIMPLEMENTED;
Guido van Rossumdc91b992001-08-08 22:26:22 +00005940}
5941
5942SLOT0(slot_nb_negative, "__neg__")
5943SLOT0(slot_nb_positive, "__pos__")
5944SLOT0(slot_nb_absolute, "__abs__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00005945
5946static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00005947slot_nb_bool(PyObject *self)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005948{
Victor Stinner20a30072016-08-19 18:28:25 +02005949 PyObject *func, *value;
Victor Stinnera12eec42016-08-19 18:26:05 +02005950 int result;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005951 int using_len = 0;
Benjamin Petersonce798522012-01-22 11:24:29 -05005952 _Py_IDENTIFIER(__bool__);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005953
Benjamin Petersonce798522012-01-22 11:24:29 -05005954 func = lookup_maybe(self, &PyId___bool__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005955 if (func == NULL) {
Victor Stinnera12eec42016-08-19 18:26:05 +02005956 if (PyErr_Occurred()) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005957 return -1;
Victor Stinnera12eec42016-08-19 18:26:05 +02005958 }
5959
Benjamin Petersonce798522012-01-22 11:24:29 -05005960 func = lookup_maybe(self, &PyId___len__);
Victor Stinnera12eec42016-08-19 18:26:05 +02005961 if (func == NULL) {
5962 if (PyErr_Occurred()) {
5963 return -1;
5964 }
5965 return 1;
5966 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005967 using_len = 1;
5968 }
Victor Stinnera12eec42016-08-19 18:26:05 +02005969
Victor Stinner559bb6a2016-08-22 22:48:54 +02005970 value = _PyObject_CallNoArg(func);
Victor Stinnera12eec42016-08-19 18:26:05 +02005971 if (value == NULL) {
5972 goto error;
5973 }
5974
5975 if (using_len) {
5976 /* bool type enforced by slot_nb_len */
5977 result = PyObject_IsTrue(value);
5978 }
5979 else if (PyBool_Check(value)) {
5980 result = PyObject_IsTrue(value);
5981 }
5982 else {
5983 PyErr_Format(PyExc_TypeError,
5984 "__bool__ should return "
5985 "bool, returned %s",
5986 Py_TYPE(value)->tp_name);
5987 result = -1;
5988 }
5989
5990 Py_DECREF(value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005991 Py_DECREF(func);
5992 return result;
Victor Stinnera12eec42016-08-19 18:26:05 +02005993
5994error:
5995 Py_DECREF(func);
5996 return -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005997}
5998
Guido van Rossum38fff8c2006-03-07 18:50:55 +00005999
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00006000static PyObject *
Guido van Rossum38fff8c2006-03-07 18:50:55 +00006001slot_nb_index(PyObject *self)
6002{
Benjamin Petersonce798522012-01-22 11:24:29 -05006003 _Py_IDENTIFIER(__index__);
6004 return call_method(self, &PyId___index__, "()");
Guido van Rossum38fff8c2006-03-07 18:50:55 +00006005}
6006
6007
Guido van Rossumdc91b992001-08-08 22:26:22 +00006008SLOT0(slot_nb_invert, "__invert__")
6009SLOT1BIN(slot_nb_lshift, nb_lshift, "__lshift__", "__rlshift__")
6010SLOT1BIN(slot_nb_rshift, nb_rshift, "__rshift__", "__rrshift__")
6011SLOT1BIN(slot_nb_and, nb_and, "__and__", "__rand__")
6012SLOT1BIN(slot_nb_xor, nb_xor, "__xor__", "__rxor__")
6013SLOT1BIN(slot_nb_or, nb_or, "__or__", "__ror__")
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00006014
Guido van Rossumdc91b992001-08-08 22:26:22 +00006015SLOT0(slot_nb_int, "__int__")
Guido van Rossumdc91b992001-08-08 22:26:22 +00006016SLOT0(slot_nb_float, "__float__")
Guido van Rossumdc91b992001-08-08 22:26:22 +00006017SLOT1(slot_nb_inplace_add, "__iadd__", PyObject *, "O")
6018SLOT1(slot_nb_inplace_subtract, "__isub__", PyObject *, "O")
6019SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *, "O")
Benjamin Petersond51374e2014-04-09 23:55:56 -04006020SLOT1(slot_nb_inplace_matrix_multiply, "__imatmul__", PyObject *, "O")
Guido van Rossumdc91b992001-08-08 22:26:22 +00006021SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *, "O")
Thomas Wouterscf297e42007-02-23 15:07:44 +00006022/* Can't use SLOT1 here, because nb_inplace_power is ternary */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006023static PyObject *
6024slot_nb_inplace_power(PyObject *self, PyObject * arg1, PyObject *arg2)
6025{
Benjamin Petersonce798522012-01-22 11:24:29 -05006026 _Py_IDENTIFIER(__ipow__);
6027 return call_method(self, &PyId___ipow__, "(" "O" ")", arg1);
Thomas Wouterscf297e42007-02-23 15:07:44 +00006028}
Guido van Rossumdc91b992001-08-08 22:26:22 +00006029SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *, "O")
6030SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *, "O")
6031SLOT1(slot_nb_inplace_and, "__iand__", PyObject *, "O")
6032SLOT1(slot_nb_inplace_xor, "__ixor__", PyObject *, "O")
6033SLOT1(slot_nb_inplace_or, "__ior__", PyObject *, "O")
6034SLOT1BIN(slot_nb_floor_divide, nb_floor_divide,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006035 "__floordiv__", "__rfloordiv__")
Guido van Rossumdc91b992001-08-08 22:26:22 +00006036SLOT1BIN(slot_nb_true_divide, nb_true_divide, "__truediv__", "__rtruediv__")
6037SLOT1(slot_nb_inplace_floor_divide, "__ifloordiv__", PyObject *, "O")
6038SLOT1(slot_nb_inplace_true_divide, "__itruediv__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00006039
Guido van Rossumb8f63662001-08-15 23:57:02 +00006040static PyObject *
6041slot_tp_repr(PyObject *self)
6042{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006043 PyObject *func, *res;
Benjamin Petersonce798522012-01-22 11:24:29 -05006044 _Py_IDENTIFIER(__repr__);
Guido van Rossumb8f63662001-08-15 23:57:02 +00006045
Benjamin Petersonce798522012-01-22 11:24:29 -05006046 func = lookup_method(self, &PyId___repr__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006047 if (func != NULL) {
6048 res = PyEval_CallObject(func, NULL);
6049 Py_DECREF(func);
6050 return res;
6051 }
6052 PyErr_Clear();
6053 return PyUnicode_FromFormat("<%s object at %p>",
6054 Py_TYPE(self)->tp_name, self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00006055}
6056
6057static PyObject *
6058slot_tp_str(PyObject *self)
6059{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006060 PyObject *func, *res;
Benjamin Petersonce798522012-01-22 11:24:29 -05006061 _Py_IDENTIFIER(__str__);
Guido van Rossumb8f63662001-08-15 23:57:02 +00006062
Benjamin Petersonce798522012-01-22 11:24:29 -05006063 func = lookup_method(self, &PyId___str__);
Victor Stinner2e8474d2013-07-11 22:46:11 +02006064 if (func == NULL)
6065 return NULL;
Victor Stinnerbebba502013-10-29 10:56:34 +01006066 res = PyEval_CallObject(func, NULL);
6067 Py_DECREF(func);
6068 return res;
6069}
Tim Peters6d6c1a32001-08-02 04:15:00 +00006070
Benjamin Peterson8f67d082010-10-17 20:54:53 +00006071static Py_hash_t
Tim Peters6d6c1a32001-08-02 04:15:00 +00006072slot_tp_hash(PyObject *self)
6073{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006074 PyObject *func, *res;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00006075 Py_ssize_t h;
Tim Peters6d6c1a32001-08-02 04:15:00 +00006076
Benjamin Petersonce798522012-01-22 11:24:29 -05006077 func = lookup_method(self, &PyId___hash__);
Guido van Rossumb8f63662001-08-15 23:57:02 +00006078
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006079 if (func == Py_None) {
6080 Py_DECREF(func);
6081 func = NULL;
6082 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +00006083
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006084 if (func == NULL) {
6085 return PyObject_HashNotImplemented(self);
6086 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +00006087
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006088 res = PyEval_CallObject(func, NULL);
6089 Py_DECREF(func);
6090 if (res == NULL)
6091 return -1;
Mark Dickinsondc787d22010-05-23 13:33:13 +00006092
6093 if (!PyLong_Check(res)) {
6094 PyErr_SetString(PyExc_TypeError,
6095 "__hash__ method should return an integer");
6096 return -1;
6097 }
Benjamin Peterson8f67d082010-10-17 20:54:53 +00006098 /* Transform the PyLong `res` to a Py_hash_t `h`. For an existing
6099 hashable Python object x, hash(x) will always lie within the range of
6100 Py_hash_t. Therefore our transformation must preserve values that
6101 already lie within this range, to ensure that if x.__hash__() returns
6102 hash(y) then hash(x) == hash(y). */
6103 h = PyLong_AsSsize_t(res);
6104 if (h == -1 && PyErr_Occurred()) {
6105 /* res was not within the range of a Py_hash_t, so we're free to
Mark Dickinsondc787d22010-05-23 13:33:13 +00006106 use any sufficiently bit-mixing transformation;
6107 long.__hash__ will do nicely. */
Benjamin Peterson8f67d082010-10-17 20:54:53 +00006108 PyErr_Clear();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006109 h = PyLong_Type.tp_hash(res);
Benjamin Peterson8f67d082010-10-17 20:54:53 +00006110 }
Benjamin Petersone7dfeeb2010-10-17 21:27:01 +00006111 /* -1 is reserved for errors. */
6112 if (h == -1)
6113 h = -2;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006114 Py_DECREF(res);
Mark Dickinsondc787d22010-05-23 13:33:13 +00006115 return h;
Tim Peters6d6c1a32001-08-02 04:15:00 +00006116}
6117
6118static PyObject *
6119slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds)
6120{
Benjamin Petersonce798522012-01-22 11:24:29 -05006121 _Py_IDENTIFIER(__call__);
6122 PyObject *meth = lookup_method(self, &PyId___call__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006123 PyObject *res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00006124
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006125 if (meth == NULL)
6126 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006127
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006128 res = PyObject_Call(meth, args, kwds);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006129
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006130 Py_DECREF(meth);
6131 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00006132}
6133
Guido van Rossum14a6f832001-10-17 13:59:09 +00006134/* There are two slot dispatch functions for tp_getattro.
6135
6136 - slot_tp_getattro() is used when __getattribute__ is overridden
6137 but no __getattr__ hook is present;
6138
6139 - slot_tp_getattr_hook() is used when a __getattr__ hook is present.
6140
Guido van Rossumc334df52002-04-04 23:44:47 +00006141 The code in update_one_slot() always installs slot_tp_getattr_hook(); this
6142 detects the absence of __getattr__ and then installs the simpler slot if
6143 necessary. */
Guido van Rossum14a6f832001-10-17 13:59:09 +00006144
Tim Peters6d6c1a32001-08-02 04:15:00 +00006145static PyObject *
6146slot_tp_getattro(PyObject *self, PyObject *name)
6147{
Benjamin Petersonce798522012-01-22 11:24:29 -05006148 return call_method(self, &PyId___getattribute__, "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00006149}
6150
Guido van Rossum19c1cd52001-09-21 21:24:49 +00006151static PyObject *
Benjamin Peterson9262b842008-11-17 22:45:50 +00006152call_attribute(PyObject *self, PyObject *attr, PyObject *name)
6153{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006154 PyObject *res, *descr = NULL;
6155 descrgetfunc f = Py_TYPE(attr)->tp_descr_get;
Benjamin Peterson9262b842008-11-17 22:45:50 +00006156
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006157 if (f != NULL) {
6158 descr = f(attr, self, (PyObject *)(Py_TYPE(self)));
6159 if (descr == NULL)
6160 return NULL;
6161 else
6162 attr = descr;
6163 }
6164 res = PyObject_CallFunctionObjArgs(attr, name, NULL);
6165 Py_XDECREF(descr);
6166 return res;
Benjamin Peterson9262b842008-11-17 22:45:50 +00006167}
6168
6169static PyObject *
Guido van Rossum19c1cd52001-09-21 21:24:49 +00006170slot_tp_getattr_hook(PyObject *self, PyObject *name)
6171{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006172 PyTypeObject *tp = Py_TYPE(self);
6173 PyObject *getattr, *getattribute, *res;
Victor Stinner3c1e4812012-03-26 22:10:51 +02006174 _Py_IDENTIFIER(__getattr__);
Guido van Rossum19c1cd52001-09-21 21:24:49 +00006175
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006176 /* speed hack: we could use lookup_maybe, but that would resolve the
6177 method fully for each attribute lookup for classes with
6178 __getattr__, even when the attribute is present. So we use
6179 _PyType_Lookup and create the method only when needed, with
6180 call_attribute. */
Victor Stinner3c1e4812012-03-26 22:10:51 +02006181 getattr = _PyType_LookupId(tp, &PyId___getattr__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006182 if (getattr == NULL) {
6183 /* No __getattr__ hook: use a simpler dispatcher */
6184 tp->tp_getattro = slot_tp_getattro;
6185 return slot_tp_getattro(self, name);
6186 }
6187 Py_INCREF(getattr);
6188 /* speed hack: we could use lookup_maybe, but that would resolve the
6189 method fully for each attribute lookup for classes with
6190 __getattr__, even when self has the default __getattribute__
6191 method. So we use _PyType_Lookup and create the method only when
6192 needed, with call_attribute. */
Victor Stinner3c1e4812012-03-26 22:10:51 +02006193 getattribute = _PyType_LookupId(tp, &PyId___getattribute__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006194 if (getattribute == NULL ||
6195 (Py_TYPE(getattribute) == &PyWrapperDescr_Type &&
6196 ((PyWrapperDescrObject *)getattribute)->d_wrapped ==
6197 (void *)PyObject_GenericGetAttr))
6198 res = PyObject_GenericGetAttr(self, name);
6199 else {
6200 Py_INCREF(getattribute);
6201 res = call_attribute(self, getattribute, name);
6202 Py_DECREF(getattribute);
6203 }
6204 if (res == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) {
6205 PyErr_Clear();
6206 res = call_attribute(self, getattr, name);
6207 }
6208 Py_DECREF(getattr);
6209 return res;
Guido van Rossum19c1cd52001-09-21 21:24:49 +00006210}
6211
Tim Peters6d6c1a32001-08-02 04:15:00 +00006212static int
6213slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value)
6214{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006215 PyObject *res;
Benjamin Petersonce798522012-01-22 11:24:29 -05006216 _Py_IDENTIFIER(__delattr__);
6217 _Py_IDENTIFIER(__setattr__);
Tim Peters6d6c1a32001-08-02 04:15:00 +00006218
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006219 if (value == NULL)
Benjamin Petersonce798522012-01-22 11:24:29 -05006220 res = call_method(self, &PyId___delattr__, "(O)", name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006221 else
Benjamin Petersonce798522012-01-22 11:24:29 -05006222 res = call_method(self, &PyId___setattr__, "(OO)", name, value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006223 if (res == NULL)
6224 return -1;
6225 Py_DECREF(res);
6226 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00006227}
6228
Benjamin Petersonce798522012-01-22 11:24:29 -05006229static _Py_Identifier name_op[] = {
6230 {0, "__lt__", 0},
6231 {0, "__le__", 0},
6232 {0, "__eq__", 0},
6233 {0, "__ne__", 0},
6234 {0, "__gt__", 0},
6235 {0, "__ge__", 0}
Guido van Rossumf5243f02008-01-01 04:06:48 +00006236};
6237
Tim Peters6d6c1a32001-08-02 04:15:00 +00006238static PyObject *
Mark Dickinson6f1d0492009-11-15 13:58:49 +00006239slot_tp_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters6d6c1a32001-08-02 04:15:00 +00006240{
Victor Stinnera7720f62016-08-19 17:48:51 +02006241 PyObject *func, *res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00006242
Benjamin Petersonce798522012-01-22 11:24:29 -05006243 func = lookup_method(self, &name_op[op]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006244 if (func == NULL) {
6245 PyErr_Clear();
Brian Curtindfc80e32011-08-10 20:28:54 -05006246 Py_RETURN_NOTIMPLEMENTED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006247 }
Victor Stinner559bb6a2016-08-22 22:48:54 +02006248 res = _PyObject_CallArg1(func, other);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006249 Py_DECREF(func);
6250 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00006251}
6252
Guido van Rossumb8f63662001-08-15 23:57:02 +00006253static PyObject *
Guido van Rossumb8f63662001-08-15 23:57:02 +00006254slot_tp_iter(PyObject *self)
6255{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006256 PyObject *func, *res;
Benjamin Petersonce798522012-01-22 11:24:29 -05006257 _Py_IDENTIFIER(__iter__);
Guido van Rossumb8f63662001-08-15 23:57:02 +00006258
Benjamin Petersonce798522012-01-22 11:24:29 -05006259 func = lookup_method(self, &PyId___iter__);
Guido van Rossum97c1adf2016-08-18 09:22:23 -07006260 if (func == Py_None) {
6261 Py_DECREF(func);
6262 PyErr_Format(PyExc_TypeError,
6263 "'%.200s' object is not iterable",
6264 Py_TYPE(self)->tp_name);
6265 return NULL;
6266 }
Victor Stinner69112672016-08-19 18:41:02 +02006267
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006268 if (func != NULL) {
Victor Stinner559bb6a2016-08-22 22:48:54 +02006269 res = _PyObject_CallNoArg(func);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006270 Py_DECREF(func);
6271 return res;
6272 }
Victor Stinner69112672016-08-19 18:41:02 +02006273
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006274 PyErr_Clear();
Benjamin Petersonce798522012-01-22 11:24:29 -05006275 func = lookup_method(self, &PyId___getitem__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006276 if (func == NULL) {
6277 PyErr_Format(PyExc_TypeError,
6278 "'%.200s' object is not iterable",
6279 Py_TYPE(self)->tp_name);
6280 return NULL;
6281 }
6282 Py_DECREF(func);
6283 return PySeqIter_New(self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00006284}
Tim Peters6d6c1a32001-08-02 04:15:00 +00006285
6286static PyObject *
6287slot_tp_iternext(PyObject *self)
6288{
Benjamin Petersonce798522012-01-22 11:24:29 -05006289 _Py_IDENTIFIER(__next__);
6290 return call_method(self, &PyId___next__, "()");
Tim Peters6d6c1a32001-08-02 04:15:00 +00006291}
6292
Guido van Rossum1a493502001-08-17 16:47:50 +00006293static PyObject *
6294slot_tp_descr_get(PyObject *self, PyObject *obj, PyObject *type)
6295{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006296 PyTypeObject *tp = Py_TYPE(self);
6297 PyObject *get;
Victor Stinner3c1e4812012-03-26 22:10:51 +02006298 _Py_IDENTIFIER(__get__);
Guido van Rossum1a493502001-08-17 16:47:50 +00006299
Victor Stinner3c1e4812012-03-26 22:10:51 +02006300 get = _PyType_LookupId(tp, &PyId___get__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006301 if (get == NULL) {
6302 /* Avoid further slowdowns */
6303 if (tp->tp_descr_get == slot_tp_descr_get)
6304 tp->tp_descr_get = NULL;
6305 Py_INCREF(self);
6306 return self;
6307 }
6308 if (obj == NULL)
6309 obj = Py_None;
6310 if (type == NULL)
6311 type = Py_None;
6312 return PyObject_CallFunctionObjArgs(get, self, obj, type, NULL);
Guido van Rossum1a493502001-08-17 16:47:50 +00006313}
Tim Peters6d6c1a32001-08-02 04:15:00 +00006314
6315static int
6316slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value)
6317{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006318 PyObject *res;
Benjamin Petersonce798522012-01-22 11:24:29 -05006319 _Py_IDENTIFIER(__delete__);
6320 _Py_IDENTIFIER(__set__);
Guido van Rossum2c252392001-08-24 10:13:31 +00006321
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006322 if (value == NULL)
Benjamin Petersonce798522012-01-22 11:24:29 -05006323 res = call_method(self, &PyId___delete__, "(O)", target);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006324 else
Benjamin Petersonce798522012-01-22 11:24:29 -05006325 res = call_method(self, &PyId___set__, "(OO)", target, value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006326 if (res == NULL)
6327 return -1;
6328 Py_DECREF(res);
6329 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00006330}
6331
6332static int
6333slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds)
6334{
Benjamin Petersonce798522012-01-22 11:24:29 -05006335 _Py_IDENTIFIER(__init__);
6336 PyObject *meth = lookup_method(self, &PyId___init__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006337 PyObject *res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00006338
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006339 if (meth == NULL)
6340 return -1;
6341 res = PyObject_Call(meth, args, kwds);
6342 Py_DECREF(meth);
6343 if (res == NULL)
6344 return -1;
6345 if (res != Py_None) {
6346 PyErr_Format(PyExc_TypeError,
6347 "__init__() should return None, not '%.200s'",
6348 Py_TYPE(res)->tp_name);
6349 Py_DECREF(res);
6350 return -1;
6351 }
6352 Py_DECREF(res);
6353 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00006354}
6355
6356static PyObject *
6357slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
6358{
Victor Stinner3f1057a2016-08-25 01:04:14 +02006359 PyObject *func, *result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00006360
Victor Stinner3c1e4812012-03-26 22:10:51 +02006361 func = _PyObject_GetAttrId((PyObject *)type, &PyId___new__);
Victor Stinner3f1057a2016-08-25 01:04:14 +02006362 if (func == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006363 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006364 }
Victor Stinner3f1057a2016-08-25 01:04:14 +02006365
6366 result = _PyObject_Call_Prepend(func, (PyObject *)type, args, kwds);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006367 Py_DECREF(func);
Victor Stinner3f1057a2016-08-25 01:04:14 +02006368 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00006369}
6370
Guido van Rossumfebd61d2002-08-08 20:55:20 +00006371static void
Antoine Pitrou796564c2013-07-30 19:59:21 +02006372slot_tp_finalize(PyObject *self)
Guido van Rossumfebd61d2002-08-08 20:55:20 +00006373{
Benjamin Petersonce798522012-01-22 11:24:29 -05006374 _Py_IDENTIFIER(__del__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006375 PyObject *del, *res;
6376 PyObject *error_type, *error_value, *error_traceback;
Guido van Rossumfebd61d2002-08-08 20:55:20 +00006377
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006378 /* Save the current exception, if any. */
6379 PyErr_Fetch(&error_type, &error_value, &error_traceback);
Guido van Rossumfebd61d2002-08-08 20:55:20 +00006380
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006381 /* Execute __del__ method, if any. */
Benjamin Petersonce798522012-01-22 11:24:29 -05006382 del = lookup_maybe(self, &PyId___del__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006383 if (del != NULL) {
6384 res = PyEval_CallObject(del, NULL);
6385 if (res == NULL)
6386 PyErr_WriteUnraisable(del);
6387 else
6388 Py_DECREF(res);
6389 Py_DECREF(del);
6390 }
Guido van Rossumfebd61d2002-08-08 20:55:20 +00006391
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006392 /* Restore the saved exception. */
6393 PyErr_Restore(error_type, error_value, error_traceback);
Guido van Rossumfebd61d2002-08-08 20:55:20 +00006394}
6395
Yury Selivanov75445082015-05-11 22:57:16 -04006396static PyObject *
6397slot_am_await(PyObject *self)
6398{
6399 PyObject *func, *res;
6400 _Py_IDENTIFIER(__await__);
6401
6402 func = lookup_method(self, &PyId___await__);
6403 if (func != NULL) {
6404 res = PyEval_CallObject(func, NULL);
6405 Py_DECREF(func);
6406 return res;
6407 }
6408 PyErr_Format(PyExc_AttributeError,
6409 "object %.50s does not have __await__ method",
6410 Py_TYPE(self)->tp_name);
6411 return NULL;
6412}
6413
6414static PyObject *
6415slot_am_aiter(PyObject *self)
6416{
6417 PyObject *func, *res;
6418 _Py_IDENTIFIER(__aiter__);
6419
6420 func = lookup_method(self, &PyId___aiter__);
6421 if (func != NULL) {
6422 res = PyEval_CallObject(func, NULL);
6423 Py_DECREF(func);
6424 return res;
6425 }
6426 PyErr_Format(PyExc_AttributeError,
6427 "object %.50s does not have __aiter__ method",
6428 Py_TYPE(self)->tp_name);
6429 return NULL;
6430}
6431
6432static PyObject *
6433slot_am_anext(PyObject *self)
6434{
6435 PyObject *func, *res;
6436 _Py_IDENTIFIER(__anext__);
6437
6438 func = lookup_method(self, &PyId___anext__);
6439 if (func != NULL) {
6440 res = PyEval_CallObject(func, NULL);
6441 Py_DECREF(func);
6442 return res;
6443 }
6444 PyErr_Format(PyExc_AttributeError,
6445 "object %.50s does not have __anext__ method",
6446 Py_TYPE(self)->tp_name);
6447 return NULL;
6448}
Guido van Rossum7b9144b2001-10-09 19:39:46 +00006449
Benjamin Peterson63952412013-04-01 17:41:41 -04006450/*
6451Table mapping __foo__ names to tp_foo offsets and slot_tp_foo wrapper functions.
6452
6453The table is ordered by offsets relative to the 'PyHeapTypeObject' structure,
6454which incorporates the additional structures used for numbers, sequences and
6455mappings. Note that multiple names may map to the same slot (e.g. __eq__,
6456__ne__ etc. all map to tp_richcompare) and one name may map to multiple slots
6457(e.g. __str__ affects tp_str as well as tp_repr). The table is terminated with
6458an all-zero entry. (This table is further initialized in init_slotdefs().)
6459*/
Guido van Rossum7b9144b2001-10-09 19:39:46 +00006460
Guido van Rossum6d204072001-10-21 00:44:31 +00006461typedef struct wrapperbase slotdef;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00006462
6463#undef TPSLOT
Guido van Rossumc8e56452001-10-22 00:43:43 +00006464#undef FLSLOT
Yury Selivanov75445082015-05-11 22:57:16 -04006465#undef AMSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00006466#undef ETSLOT
6467#undef SQSLOT
6468#undef MPSLOT
6469#undef NBSLOT
Guido van Rossum6d204072001-10-21 00:44:31 +00006470#undef UNSLOT
6471#undef IBSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00006472#undef BINSLOT
6473#undef RBINSLOT
6474
Guido van Rossum6d204072001-10-21 00:44:31 +00006475#define TPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006476 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
6477 PyDoc_STR(DOC)}
Guido van Rossumc8e56452001-10-22 00:43:43 +00006478#define FLSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC, FLAGS) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006479 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
6480 PyDoc_STR(DOC), FLAGS}
Guido van Rossum6d204072001-10-21 00:44:31 +00006481#define ETSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006482 {NAME, offsetof(PyHeapTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
6483 PyDoc_STR(DOC)}
Yury Selivanov75445082015-05-11 22:57:16 -04006484#define AMSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
6485 ETSLOT(NAME, as_async.SLOT, FUNCTION, WRAPPER, DOC)
Guido van Rossum6d204072001-10-21 00:44:31 +00006486#define SQSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006487 ETSLOT(NAME, as_sequence.SLOT, FUNCTION, WRAPPER, DOC)
Guido van Rossum6d204072001-10-21 00:44:31 +00006488#define MPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006489 ETSLOT(NAME, as_mapping.SLOT, FUNCTION, WRAPPER, DOC)
Guido van Rossum6d204072001-10-21 00:44:31 +00006490#define NBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006491 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, DOC)
Guido van Rossum6d204072001-10-21 00:44:31 +00006492#define UNSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006493 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
Larry Hastings69a25472014-02-09 22:22:38 -08006494 NAME "($self, /)\n--\n\n" DOC)
Guido van Rossum6d204072001-10-21 00:44:31 +00006495#define IBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006496 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
Larry Hastings69a25472014-02-09 22:22:38 -08006497 NAME "($self, value, /)\n--\n\nReturn self" DOC "value.")
Guido van Rossum6d204072001-10-21 00:44:31 +00006498#define BINSLOT(NAME, SLOT, FUNCTION, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006499 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
Larry Hastings69a25472014-02-09 22:22:38 -08006500 NAME "($self, value, /)\n--\n\nReturn self" DOC "value.")
Guido van Rossum6d204072001-10-21 00:44:31 +00006501#define RBINSLOT(NAME, SLOT, FUNCTION, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006502 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
Larry Hastings69a25472014-02-09 22:22:38 -08006503 NAME "($self, value, /)\n--\n\nReturn value" DOC "self.")
Anthony Baxter56616992005-06-03 14:12:21 +00006504#define BINSLOTNOTINFIX(NAME, SLOT, FUNCTION, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006505 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
Larry Hastings69a25472014-02-09 22:22:38 -08006506 NAME "($self, value, /)\n--\n\n" DOC)
Anthony Baxter56616992005-06-03 14:12:21 +00006507#define RBINSLOTNOTINFIX(NAME, SLOT, FUNCTION, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006508 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
Larry Hastings69a25472014-02-09 22:22:38 -08006509 NAME "($self, value, /)\n--\n\n" DOC)
Guido van Rossum7b9144b2001-10-09 19:39:46 +00006510
6511static slotdef slotdefs[] = {
Benjamin Peterson63952412013-04-01 17:41:41 -04006512 TPSLOT("__getattribute__", tp_getattr, NULL, NULL, ""),
6513 TPSLOT("__getattr__", tp_getattr, NULL, NULL, ""),
6514 TPSLOT("__setattr__", tp_setattr, NULL, NULL, ""),
6515 TPSLOT("__delattr__", tp_setattr, NULL, NULL, ""),
6516 TPSLOT("__repr__", tp_repr, slot_tp_repr, wrap_unaryfunc,
Larry Hastings69a25472014-02-09 22:22:38 -08006517 "__repr__($self, /)\n--\n\nReturn repr(self)."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006518 TPSLOT("__hash__", tp_hash, slot_tp_hash, wrap_hashfunc,
Larry Hastings69a25472014-02-09 22:22:38 -08006519 "__hash__($self, /)\n--\n\nReturn hash(self)."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006520 FLSLOT("__call__", tp_call, slot_tp_call, (wrapperfunc)wrap_call,
Larry Hastings69a25472014-02-09 22:22:38 -08006521 "__call__($self, /, *args, **kwargs)\n--\n\nCall self as a function.",
Larry Hastings5c661892014-01-24 06:17:25 -08006522 PyWrapperFlag_KEYWORDS),
Benjamin Peterson63952412013-04-01 17:41:41 -04006523 TPSLOT("__str__", tp_str, slot_tp_str, wrap_unaryfunc,
Larry Hastings69a25472014-02-09 22:22:38 -08006524 "__str__($self, /)\n--\n\nReturn str(self)."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006525 TPSLOT("__getattribute__", tp_getattro, slot_tp_getattr_hook,
Larry Hastings5c661892014-01-24 06:17:25 -08006526 wrap_binaryfunc,
Larry Hastings69a25472014-02-09 22:22:38 -08006527 "__getattribute__($self, name, /)\n--\n\nReturn getattr(self, name)."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006528 TPSLOT("__getattr__", tp_getattro, slot_tp_getattr_hook, NULL, ""),
6529 TPSLOT("__setattr__", tp_setattro, slot_tp_setattro, wrap_setattr,
Larry Hastings69a25472014-02-09 22:22:38 -08006530 "__setattr__($self, name, value, /)\n--\n\nImplement setattr(self, name, value)."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006531 TPSLOT("__delattr__", tp_setattro, slot_tp_setattro, wrap_delattr,
Larry Hastings69a25472014-02-09 22:22:38 -08006532 "__delattr__($self, name, /)\n--\n\nImplement delattr(self, name)."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006533 TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare, richcmp_lt,
Larry Hastings69a25472014-02-09 22:22:38 -08006534 "__lt__($self, value, /)\n--\n\nReturn self<value."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006535 TPSLOT("__le__", tp_richcompare, slot_tp_richcompare, richcmp_le,
Larry Hastings69a25472014-02-09 22:22:38 -08006536 "__le__($self, value, /)\n--\n\nReturn self<=value."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006537 TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare, richcmp_eq,
Larry Hastings69a25472014-02-09 22:22:38 -08006538 "__eq__($self, value, /)\n--\n\nReturn self==value."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006539 TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare, richcmp_ne,
Larry Hastings69a25472014-02-09 22:22:38 -08006540 "__ne__($self, value, /)\n--\n\nReturn self!=value."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006541 TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare, richcmp_gt,
Larry Hastings69a25472014-02-09 22:22:38 -08006542 "__gt__($self, value, /)\n--\n\nReturn self>value."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006543 TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare, richcmp_ge,
Zachary Wareea42b4c2014-04-18 09:14:31 -05006544 "__ge__($self, value, /)\n--\n\nReturn self>=value."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006545 TPSLOT("__iter__", tp_iter, slot_tp_iter, wrap_unaryfunc,
Larry Hastings69a25472014-02-09 22:22:38 -08006546 "__iter__($self, /)\n--\n\nImplement iter(self)."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006547 TPSLOT("__next__", tp_iternext, slot_tp_iternext, wrap_next,
Larry Hastings69a25472014-02-09 22:22:38 -08006548 "__next__($self, /)\n--\n\nImplement next(self)."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006549 TPSLOT("__get__", tp_descr_get, slot_tp_descr_get, wrap_descr_get,
Larry Hastings69a25472014-02-09 22:22:38 -08006550 "__get__($self, instance, owner, /)\n--\n\nReturn an attribute of instance, which is of type owner."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006551 TPSLOT("__set__", tp_descr_set, slot_tp_descr_set, wrap_descr_set,
Larry Hastings69a25472014-02-09 22:22:38 -08006552 "__set__($self, instance, value, /)\n--\n\nSet an attribute of instance to value."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006553 TPSLOT("__delete__", tp_descr_set, slot_tp_descr_set,
Larry Hastings5c661892014-01-24 06:17:25 -08006554 wrap_descr_delete,
Yury Selivanov056e2652014-03-02 12:25:27 -05006555 "__delete__($self, instance, /)\n--\n\nDelete an attribute of instance."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006556 FLSLOT("__init__", tp_init, slot_tp_init, (wrapperfunc)wrap_init,
Larry Hastings69a25472014-02-09 22:22:38 -08006557 "__init__($self, /, *args, **kwargs)\n--\n\n"
Larry Hastings581ee362014-01-28 05:00:08 -08006558 "Initialize self. See help(type(self)) for accurate signature.",
Benjamin Peterson63952412013-04-01 17:41:41 -04006559 PyWrapperFlag_KEYWORDS),
Larry Hastings5c661892014-01-24 06:17:25 -08006560 TPSLOT("__new__", tp_new, slot_tp_new, NULL,
Larry Hastings69a25472014-02-09 22:22:38 -08006561 "__new__(type, /, *args, **kwargs)\n--\n\n"
Larry Hastings581ee362014-01-28 05:00:08 -08006562 "Create and return new object. See help(type) for accurate signature."),
Antoine Pitrou796564c2013-07-30 19:59:21 +02006563 TPSLOT("__del__", tp_finalize, slot_tp_finalize, (wrapperfunc)wrap_del, ""),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00006564
Yury Selivanov75445082015-05-11 22:57:16 -04006565 AMSLOT("__await__", am_await, slot_am_await, wrap_unaryfunc,
6566 "__await__($self, /)\n--\n\nReturn an iterator to be used in await expression."),
6567 AMSLOT("__aiter__", am_aiter, slot_am_aiter, wrap_unaryfunc,
6568 "__aiter__($self, /)\n--\n\nReturn an awaitable, that resolves in asynchronous iterator."),
6569 AMSLOT("__anext__", am_anext, slot_am_anext, wrap_unaryfunc,
6570 "__anext__($self, /)\n--\n\nReturn a value or raise StopAsyncIteration."),
6571
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006572 BINSLOT("__add__", nb_add, slot_nb_add,
Larry Hastings5c661892014-01-24 06:17:25 -08006573 "+"),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006574 RBINSLOT("__radd__", nb_add, slot_nb_add,
Larry Hastings5c661892014-01-24 06:17:25 -08006575 "+"),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006576 BINSLOT("__sub__", nb_subtract, slot_nb_subtract,
Larry Hastings5c661892014-01-24 06:17:25 -08006577 "-"),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006578 RBINSLOT("__rsub__", nb_subtract, slot_nb_subtract,
Larry Hastings5c661892014-01-24 06:17:25 -08006579 "-"),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006580 BINSLOT("__mul__", nb_multiply, slot_nb_multiply,
Larry Hastings5c661892014-01-24 06:17:25 -08006581 "*"),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006582 RBINSLOT("__rmul__", nb_multiply, slot_nb_multiply,
Larry Hastings5c661892014-01-24 06:17:25 -08006583 "*"),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006584 BINSLOT("__mod__", nb_remainder, slot_nb_remainder,
Larry Hastings5c661892014-01-24 06:17:25 -08006585 "%"),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006586 RBINSLOT("__rmod__", nb_remainder, slot_nb_remainder,
Larry Hastings5c661892014-01-24 06:17:25 -08006587 "%"),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006588 BINSLOTNOTINFIX("__divmod__", nb_divmod, slot_nb_divmod,
Larry Hastings581ee362014-01-28 05:00:08 -08006589 "Return divmod(self, value)."),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006590 RBINSLOTNOTINFIX("__rdivmod__", nb_divmod, slot_nb_divmod,
Larry Hastings581ee362014-01-28 05:00:08 -08006591 "Return divmod(value, self)."),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006592 NBSLOT("__pow__", nb_power, slot_nb_power, wrap_ternaryfunc,
Larry Hastings69a25472014-02-09 22:22:38 -08006593 "__pow__($self, value, mod=None, /)\n--\n\nReturn pow(self, value, mod)."),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006594 NBSLOT("__rpow__", nb_power, slot_nb_power, wrap_ternaryfunc_r,
Larry Hastings69a25472014-02-09 22:22:38 -08006595 "__rpow__($self, value, mod=None, /)\n--\n\nReturn pow(value, self, mod)."),
Larry Hastings5c661892014-01-24 06:17:25 -08006596 UNSLOT("__neg__", nb_negative, slot_nb_negative, wrap_unaryfunc, "-self"),
6597 UNSLOT("__pos__", nb_positive, slot_nb_positive, wrap_unaryfunc, "+self"),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006598 UNSLOT("__abs__", nb_absolute, slot_nb_absolute, wrap_unaryfunc,
Larry Hastings5c661892014-01-24 06:17:25 -08006599 "abs(self)"),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006600 UNSLOT("__bool__", nb_bool, slot_nb_bool, wrap_inquirypred,
Larry Hastings5c661892014-01-24 06:17:25 -08006601 "self != 0"),
6602 UNSLOT("__invert__", nb_invert, slot_nb_invert, wrap_unaryfunc, "~self"),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006603 BINSLOT("__lshift__", nb_lshift, slot_nb_lshift, "<<"),
6604 RBINSLOT("__rlshift__", nb_lshift, slot_nb_lshift, "<<"),
6605 BINSLOT("__rshift__", nb_rshift, slot_nb_rshift, ">>"),
6606 RBINSLOT("__rrshift__", nb_rshift, slot_nb_rshift, ">>"),
6607 BINSLOT("__and__", nb_and, slot_nb_and, "&"),
6608 RBINSLOT("__rand__", nb_and, slot_nb_and, "&"),
6609 BINSLOT("__xor__", nb_xor, slot_nb_xor, "^"),
6610 RBINSLOT("__rxor__", nb_xor, slot_nb_xor, "^"),
6611 BINSLOT("__or__", nb_or, slot_nb_or, "|"),
6612 RBINSLOT("__ror__", nb_or, slot_nb_or, "|"),
6613 UNSLOT("__int__", nb_int, slot_nb_int, wrap_unaryfunc,
Larry Hastings5c661892014-01-24 06:17:25 -08006614 "int(self)"),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006615 UNSLOT("__float__", nb_float, slot_nb_float, wrap_unaryfunc,
Larry Hastings5c661892014-01-24 06:17:25 -08006616 "float(self)"),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006617 IBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add,
Eli Benderskyd3baae72011-11-11 16:57:05 +02006618 wrap_binaryfunc, "+="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006619 IBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract,
Eli Benderskyd3baae72011-11-11 16:57:05 +02006620 wrap_binaryfunc, "-="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006621 IBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply,
Eli Benderskyd3baae72011-11-11 16:57:05 +02006622 wrap_binaryfunc, "*="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006623 IBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder,
Eli Benderskyd3baae72011-11-11 16:57:05 +02006624 wrap_binaryfunc, "%="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006625 IBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power,
Eli Benderskyd3baae72011-11-11 16:57:05 +02006626 wrap_binaryfunc, "**="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006627 IBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift,
Eli Benderskyd3baae72011-11-11 16:57:05 +02006628 wrap_binaryfunc, "<<="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006629 IBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift,
Eli Benderskyd3baae72011-11-11 16:57:05 +02006630 wrap_binaryfunc, ">>="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006631 IBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and,
Eli Benderskyd3baae72011-11-11 16:57:05 +02006632 wrap_binaryfunc, "&="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006633 IBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor,
Eli Benderskyd3baae72011-11-11 16:57:05 +02006634 wrap_binaryfunc, "^="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006635 IBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or,
Eli Benderskyd3baae72011-11-11 16:57:05 +02006636 wrap_binaryfunc, "|="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006637 BINSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
6638 RBINSLOT("__rfloordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
6639 BINSLOT("__truediv__", nb_true_divide, slot_nb_true_divide, "/"),
6640 RBINSLOT("__rtruediv__", nb_true_divide, slot_nb_true_divide, "/"),
6641 IBSLOT("__ifloordiv__", nb_inplace_floor_divide,
Georg Brandle1d26f32014-10-31 13:12:57 +01006642 slot_nb_inplace_floor_divide, wrap_binaryfunc, "//="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006643 IBSLOT("__itruediv__", nb_inplace_true_divide,
Georg Brandle1d26f32014-10-31 13:12:57 +01006644 slot_nb_inplace_true_divide, wrap_binaryfunc, "/="),
Benjamin Peterson63952412013-04-01 17:41:41 -04006645 NBSLOT("__index__", nb_index, slot_nb_index, wrap_unaryfunc,
Larry Hastings69a25472014-02-09 22:22:38 -08006646 "__index__($self, /)\n--\n\n"
Zachary Ware715ef022014-04-18 09:23:14 -05006647 "Return self converted to an integer, if self is suitable "
Larry Hastings5c661892014-01-24 06:17:25 -08006648 "for use as an index into a list."),
Benjamin Petersond51374e2014-04-09 23:55:56 -04006649 BINSLOT("__matmul__", nb_matrix_multiply, slot_nb_matrix_multiply,
6650 "@"),
6651 RBINSLOT("__rmatmul__", nb_matrix_multiply, slot_nb_matrix_multiply,
6652 "@"),
6653 IBSLOT("__imatmul__", nb_inplace_matrix_multiply, slot_nb_inplace_matrix_multiply,
6654 wrap_binaryfunc, "@="),
Benjamin Peterson63952412013-04-01 17:41:41 -04006655 MPSLOT("__len__", mp_length, slot_mp_length, wrap_lenfunc,
Larry Hastings69a25472014-02-09 22:22:38 -08006656 "__len__($self, /)\n--\n\nReturn len(self)."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006657 MPSLOT("__getitem__", mp_subscript, slot_mp_subscript,
6658 wrap_binaryfunc,
Larry Hastings69a25472014-02-09 22:22:38 -08006659 "__getitem__($self, key, /)\n--\n\nReturn self[key]."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006660 MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript,
6661 wrap_objobjargproc,
Larry Hastings69a25472014-02-09 22:22:38 -08006662 "__setitem__($self, key, value, /)\n--\n\nSet self[key] to value."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006663 MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript,
6664 wrap_delitem,
Yury Selivanov056e2652014-03-02 12:25:27 -05006665 "__delitem__($self, key, /)\n--\n\nDelete self[key]."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006666
6667 SQSLOT("__len__", sq_length, slot_sq_length, wrap_lenfunc,
Larry Hastings69a25472014-02-09 22:22:38 -08006668 "__len__($self, /)\n--\n\nReturn len(self)."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006669 /* Heap types defining __add__/__mul__ have sq_concat/sq_repeat == NULL.
6670 The logic in abstract.c always falls back to nb_add/nb_multiply in
6671 this case. Defining both the nb_* and the sq_* slots to call the
6672 user-defined methods has unexpected side-effects, as shown by
6673 test_descr.notimplemented() */
6674 SQSLOT("__add__", sq_concat, NULL, wrap_binaryfunc,
Larry Hastings69a25472014-02-09 22:22:38 -08006675 "__add__($self, value, /)\n--\n\nReturn self+value."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006676 SQSLOT("__mul__", sq_repeat, NULL, wrap_indexargfunc,
Larry Hastings69a25472014-02-09 22:22:38 -08006677 "__mul__($self, value, /)\n--\n\nReturn self*value.n"),
Benjamin Peterson63952412013-04-01 17:41:41 -04006678 SQSLOT("__rmul__", sq_repeat, NULL, wrap_indexargfunc,
Larry Hastings69a25472014-02-09 22:22:38 -08006679 "__rmul__($self, value, /)\n--\n\nReturn self*value."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006680 SQSLOT("__getitem__", sq_item, slot_sq_item, wrap_sq_item,
Larry Hastings69a25472014-02-09 22:22:38 -08006681 "__getitem__($self, key, /)\n--\n\nReturn self[key]."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006682 SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_setitem,
Larry Hastings69a25472014-02-09 22:22:38 -08006683 "__setitem__($self, key, value, /)\n--\n\nSet self[key] to value."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006684 SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_delitem,
Larry Hastings69a25472014-02-09 22:22:38 -08006685 "__delitem__($self, key, /)\n--\n\nDelete self[key]."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006686 SQSLOT("__contains__", sq_contains, slot_sq_contains, wrap_objobjproc,
Larry Hastings69a25472014-02-09 22:22:38 -08006687 "__contains__($self, key, /)\n--\n\nReturn key in self."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006688 SQSLOT("__iadd__", sq_inplace_concat, NULL,
Larry Hastings5c661892014-01-24 06:17:25 -08006689 wrap_binaryfunc,
Larry Hastings69a25472014-02-09 22:22:38 -08006690 "__iadd__($self, value, /)\n--\n\nImplement self+=value."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006691 SQSLOT("__imul__", sq_inplace_repeat, NULL,
Larry Hastings5c661892014-01-24 06:17:25 -08006692 wrap_indexargfunc,
Larry Hastings69a25472014-02-09 22:22:38 -08006693 "__imul__($self, value, /)\n--\n\nImplement self*=value."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006694
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006695 {NULL}
Guido van Rossum7b9144b2001-10-09 19:39:46 +00006696};
6697
Guido van Rossumc334df52002-04-04 23:44:47 +00006698/* Given a type pointer and an offset gotten from a slotdef entry, return a
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006699 pointer to the actual slot. This is not quite the same as simply adding
Guido van Rossumc334df52002-04-04 23:44:47 +00006700 the offset to the type pointer, since it takes care to indirect through the
6701 proper indirection pointer (as_buffer, etc.); it returns NULL if the
6702 indirection pointer is NULL. */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00006703static void **
Martin v. Löwis18e16552006-02-15 17:27:45 +00006704slotptr(PyTypeObject *type, int ioffset)
Guido van Rossum7b9144b2001-10-09 19:39:46 +00006705{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006706 char *ptr;
6707 long offset = ioffset;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00006708
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006709 /* Note: this depends on the order of the members of PyHeapTypeObject! */
6710 assert(offset >= 0);
6711 assert((size_t)offset < offsetof(PyHeapTypeObject, as_buffer));
6712 if ((size_t)offset >= offsetof(PyHeapTypeObject, as_sequence)) {
6713 ptr = (char *)type->tp_as_sequence;
6714 offset -= offsetof(PyHeapTypeObject, as_sequence);
6715 }
6716 else if ((size_t)offset >= offsetof(PyHeapTypeObject, as_mapping)) {
6717 ptr = (char *)type->tp_as_mapping;
6718 offset -= offsetof(PyHeapTypeObject, as_mapping);
6719 }
6720 else if ((size_t)offset >= offsetof(PyHeapTypeObject, as_number)) {
6721 ptr = (char *)type->tp_as_number;
6722 offset -= offsetof(PyHeapTypeObject, as_number);
6723 }
Yury Selivanov75445082015-05-11 22:57:16 -04006724 else if ((size_t)offset >= offsetof(PyHeapTypeObject, as_async)) {
6725 ptr = (char *)type->tp_as_async;
6726 offset -= offsetof(PyHeapTypeObject, as_async);
6727 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006728 else {
6729 ptr = (char *)type;
6730 }
6731 if (ptr != NULL)
6732 ptr += offset;
6733 return (void **)ptr;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00006734}
Guido van Rossumf040ede2001-08-07 16:40:56 +00006735
Guido van Rossumc334df52002-04-04 23:44:47 +00006736/* Length of array of slotdef pointers used to store slots with the
6737 same __name__. There should be at most MAX_EQUIV-1 slotdef entries with
6738 the same __name__, for any __name__. Since that's a static property, it is
6739 appropriate to declare fixed-size arrays for this. */
6740#define MAX_EQUIV 10
6741
6742/* Return a slot pointer for a given name, but ONLY if the attribute has
6743 exactly one slot function. The name must be an interned string. */
6744static void **
6745resolve_slotdups(PyTypeObject *type, PyObject *name)
6746{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006747 /* XXX Maybe this could be optimized more -- but is it worth it? */
Guido van Rossumc334df52002-04-04 23:44:47 +00006748
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006749 /* pname and ptrs act as a little cache */
6750 static PyObject *pname;
6751 static slotdef *ptrs[MAX_EQUIV];
6752 slotdef *p, **pp;
6753 void **res, **ptr;
Guido van Rossumc334df52002-04-04 23:44:47 +00006754
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006755 if (pname != name) {
6756 /* Collect all slotdefs that match name into ptrs. */
6757 pname = name;
6758 pp = ptrs;
6759 for (p = slotdefs; p->name_strobj; p++) {
6760 if (p->name_strobj == name)
6761 *pp++ = p;
6762 }
6763 *pp = NULL;
6764 }
Guido van Rossumc334df52002-04-04 23:44:47 +00006765
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006766 /* Look in all matching slots of the type; if exactly one of these has
6767 a filled-in slot, return its value. Otherwise return NULL. */
6768 res = NULL;
6769 for (pp = ptrs; *pp; pp++) {
6770 ptr = slotptr(type, (*pp)->offset);
6771 if (ptr == NULL || *ptr == NULL)
6772 continue;
6773 if (res != NULL)
6774 return NULL;
6775 res = ptr;
6776 }
6777 return res;
Guido van Rossumc334df52002-04-04 23:44:47 +00006778}
6779
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006780/* Common code for update_slots_callback() and fixup_slot_dispatchers(). This
Guido van Rossumc334df52002-04-04 23:44:47 +00006781 does some incredibly complex thinking and then sticks something into the
6782 slot. (It sees if the adjacent slotdefs for the same slot have conflicting
6783 interests, and then stores a generic wrapper or a specific function into
6784 the slot.) Return a pointer to the next slotdef with a different offset,
6785 because that's convenient for fixup_slot_dispatchers(). */
6786static slotdef *
6787update_one_slot(PyTypeObject *type, slotdef *p)
6788{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006789 PyObject *descr;
6790 PyWrapperDescrObject *d;
6791 void *generic = NULL, *specific = NULL;
6792 int use_generic = 0;
6793 int offset = p->offset;
6794 void **ptr = slotptr(type, offset);
Guido van Rossumc334df52002-04-04 23:44:47 +00006795
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006796 if (ptr == NULL) {
6797 do {
6798 ++p;
6799 } while (p->offset == offset);
6800 return p;
6801 }
6802 do {
6803 descr = _PyType_Lookup(type, p->name_strobj);
6804 if (descr == NULL) {
6805 if (ptr == (void**)&type->tp_iternext) {
Trent Nelsonab02db22012-09-18 21:58:03 -04006806 specific = (void *)_PyObject_NextNotImplemented;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006807 }
6808 continue;
6809 }
Benjamin Peterson7b166872012-04-24 11:06:25 -04006810 if (Py_TYPE(descr) == &PyWrapperDescr_Type &&
6811 ((PyWrapperDescrObject *)descr)->d_base->name_strobj == p->name_strobj) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006812 void **tptr = resolve_slotdups(type, p->name_strobj);
6813 if (tptr == NULL || tptr == ptr)
6814 generic = p->function;
6815 d = (PyWrapperDescrObject *)descr;
6816 if (d->d_base->wrapper == p->wrapper &&
6817 PyType_IsSubtype(type, PyDescr_TYPE(d)))
6818 {
6819 if (specific == NULL ||
6820 specific == d->d_wrapped)
6821 specific = d->d_wrapped;
6822 else
6823 use_generic = 1;
6824 }
6825 }
6826 else if (Py_TYPE(descr) == &PyCFunction_Type &&
6827 PyCFunction_GET_FUNCTION(descr) ==
6828 (PyCFunction)tp_new_wrapper &&
6829 ptr == (void**)&type->tp_new)
6830 {
6831 /* The __new__ wrapper is not a wrapper descriptor,
6832 so must be special-cased differently.
6833 If we don't do this, creating an instance will
6834 always use slot_tp_new which will look up
6835 __new__ in the MRO which will call tp_new_wrapper
6836 which will look through the base classes looking
6837 for a static base and call its tp_new (usually
6838 PyType_GenericNew), after performing various
6839 sanity checks and constructing a new argument
6840 list. Cut all that nonsense short -- this speeds
6841 up instance creation tremendously. */
Benjamin Petersonc3526202016-05-28 14:04:40 -07006842 specific = (void *)type->tp_new;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006843 /* XXX I'm not 100% sure that there isn't a hole
6844 in this reasoning that requires additional
6845 sanity checks. I'll buy the first person to
6846 point out a bug in this reasoning a beer. */
6847 }
6848 else if (descr == Py_None &&
6849 ptr == (void**)&type->tp_hash) {
6850 /* We specifically allow __hash__ to be set to None
6851 to prevent inheritance of the default
6852 implementation from object.__hash__ */
Trent Nelsonab02db22012-09-18 21:58:03 -04006853 specific = (void *)PyObject_HashNotImplemented;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006854 }
6855 else {
6856 use_generic = 1;
6857 generic = p->function;
6858 }
6859 } while ((++p)->offset == offset);
6860 if (specific && !use_generic)
6861 *ptr = specific;
6862 else
6863 *ptr = generic;
6864 return p;
Guido van Rossumc334df52002-04-04 23:44:47 +00006865}
6866
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006867/* In the type, update the slots whose slotdefs are gathered in the pp array.
6868 This is a callback for update_subclasses(). */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006869static int
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006870update_slots_callback(PyTypeObject *type, void *data)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006871{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006872 slotdef **pp = (slotdef **)data;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006873
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006874 for (; *pp; pp++)
6875 update_one_slot(type, *pp);
6876 return 0;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006877}
6878
Martin v. Löwis996b6712014-07-26 16:44:07 +02006879static int slotdefs_initialized = 0;
Guido van Rossumc334df52002-04-04 23:44:47 +00006880/* Initialize the slotdefs table by adding interned string objects for the
Martin v. Löwis5b561502014-07-26 15:25:04 +02006881 names. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006882static void
Guido van Rossumd396b9c2001-10-13 20:02:41 +00006883init_slotdefs(void)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006884{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006885 slotdef *p;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006886
Martin v. Löwis996b6712014-07-26 16:44:07 +02006887 if (slotdefs_initialized)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006888 return;
6889 for (p = slotdefs; p->name; p++) {
Benjamin Peterson63952412013-04-01 17:41:41 -04006890 /* Slots must be ordered by their offset in the PyHeapTypeObject. */
6891 assert(!p[1].name || p->offset <= p[1].offset);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006892 p->name_strobj = PyUnicode_InternFromString(p->name);
6893 if (!p->name_strobj)
6894 Py_FatalError("Out of memory interning slotdef names");
6895 }
Martin v. Löwis996b6712014-07-26 16:44:07 +02006896 slotdefs_initialized = 1;
6897}
6898
6899/* Undo init_slotdefs, releasing the interned strings. */
Victor Stinner331a7262014-07-27 16:11:30 +02006900static void clear_slotdefs(void)
Martin v. Löwis996b6712014-07-26 16:44:07 +02006901{
6902 slotdef *p;
6903 for (p = slotdefs; p->name; p++) {
6904 Py_CLEAR(p->name_strobj);
6905 }
6906 slotdefs_initialized = 0;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006907}
6908
Guido van Rossumc334df52002-04-04 23:44:47 +00006909/* Update the slots after assignment to a class (type) attribute. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006910static int
6911update_slot(PyTypeObject *type, PyObject *name)
6912{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006913 slotdef *ptrs[MAX_EQUIV];
6914 slotdef *p;
6915 slotdef **pp;
6916 int offset;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006917
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006918 /* Clear the VALID_VERSION flag of 'type' and all its
6919 subclasses. This could possibly be unified with the
6920 update_subclasses() recursion below, but carefully:
6921 they each have their own conditions on which to stop
6922 recursing into subclasses. */
6923 PyType_Modified(type);
Christian Heimesa62da1d2008-01-12 19:39:10 +00006924
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006925 init_slotdefs();
6926 pp = ptrs;
6927 for (p = slotdefs; p->name; p++) {
6928 /* XXX assume name is interned! */
6929 if (p->name_strobj == name)
6930 *pp++ = p;
6931 }
6932 *pp = NULL;
6933 for (pp = ptrs; *pp; pp++) {
6934 p = *pp;
6935 offset = p->offset;
6936 while (p > slotdefs && (p-1)->offset == offset)
6937 --p;
6938 *pp = p;
6939 }
6940 if (ptrs[0] == NULL)
6941 return 0; /* Not an attribute that affects any slots */
6942 return update_subclasses(type, name,
6943 update_slots_callback, (void *)ptrs);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006944}
6945
Guido van Rossumc334df52002-04-04 23:44:47 +00006946/* Store the proper functions in the slot dispatches at class (type)
6947 definition time, based upon which operations the class overrides in its
6948 dict. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00006949static void
Guido van Rossum7b9144b2001-10-09 19:39:46 +00006950fixup_slot_dispatchers(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00006951{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006952 slotdef *p;
Tim Peters6d6c1a32001-08-02 04:15:00 +00006953
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006954 init_slotdefs();
6955 for (p = slotdefs; p->name; )
6956 p = update_one_slot(type, p);
Tim Peters6d6c1a32001-08-02 04:15:00 +00006957}
Guido van Rossum705f0f52001-08-24 16:47:00 +00006958
Michael W. Hudson98bbc492002-11-26 14:47:27 +00006959static void
6960update_all_slots(PyTypeObject* type)
6961{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006962 slotdef *p;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00006963
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006964 init_slotdefs();
6965 for (p = slotdefs; p->name; p++) {
6966 /* update_slot returns int but can't actually fail */
6967 update_slot(type, p->name_strobj);
6968 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +00006969}
6970
Nick Coghland78448e2016-07-30 16:26:03 +10006971/* Call __set_name__ on all descriptors in a newly generated type */
6972static int
6973set_names(PyTypeObject *type)
6974{
6975 PyObject *key, *value, *tmp;
6976 Py_ssize_t i = 0;
6977
6978 while (PyDict_Next(type->tp_dict, &i, &key, &value)) {
6979 if (PyObject_HasAttr(value, _PyUnicode_FromId(&PyId___set_name__))) {
6980 tmp = PyObject_CallMethodObjArgs(
6981 value, _PyUnicode_FromId(&PyId___set_name__),
6982 type, key, NULL);
6983 if (tmp == NULL)
6984 return -1;
6985 else
6986 Py_DECREF(tmp);
6987 }
6988 }
6989
6990 return 0;
6991}
6992
6993/* Call __init_subclass__ on the parent of a newly generated type */
6994static int
6995init_subclass(PyTypeObject *type, PyObject *kwds)
6996{
Victor Stinner463b86a2016-08-22 23:33:13 +02006997 PyObject *super, *func, *result;
6998 PyObject *args[2] = {(PyObject *)type, (PyObject *)type};
Nick Coghland78448e2016-07-30 16:26:03 +10006999
Victor Stinner463b86a2016-08-22 23:33:13 +02007000 super = _PyObject_FastCall((PyObject *)&PySuper_Type, args, 2);
7001 if (super == NULL) {
Nick Coghland78448e2016-07-30 16:26:03 +10007002 return -1;
Victor Stinner253021d2016-08-20 02:37:41 +02007003 }
7004
Victor Stinner463b86a2016-08-22 23:33:13 +02007005 func = _PyObject_GetAttrId(super, &PyId___init_subclass__);
7006 Py_DECREF(super);
7007 if (func == NULL) {
Nick Coghland78448e2016-07-30 16:26:03 +10007008 return -1;
Victor Stinner463b86a2016-08-22 23:33:13 +02007009 }
Nick Coghland78448e2016-07-30 16:26:03 +10007010
Victor Stinner463b86a2016-08-22 23:33:13 +02007011
7012 result = _PyObject_FastCallDict(func, NULL, 0, kwds);
7013 Py_DECREF(func);
7014 if (result == NULL) {
7015 return -1;
7016 }
7017
7018 Py_DECREF(result);
Nick Coghland78448e2016-07-30 16:26:03 +10007019 return 0;
7020}
7021
Guido van Rossum8d24ee92003-03-24 23:49:49 +00007022/* recurse_down_subclasses() and update_subclasses() are mutually
7023 recursive functions to call a callback for all subclasses,
7024 but refraining from recursing into subclasses that define 'name'. */
7025
7026static int
7027update_subclasses(PyTypeObject *type, PyObject *name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007028 update_callback callback, void *data)
Guido van Rossum8d24ee92003-03-24 23:49:49 +00007029{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007030 if (callback(type, data) < 0)
7031 return -1;
7032 return recurse_down_subclasses(type, name, callback, data);
Guido van Rossum8d24ee92003-03-24 23:49:49 +00007033}
7034
7035static int
7036recurse_down_subclasses(PyTypeObject *type, PyObject *name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007037 update_callback callback, void *data)
Guido van Rossum8d24ee92003-03-24 23:49:49 +00007038{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007039 PyTypeObject *subclass;
7040 PyObject *ref, *subclasses, *dict;
Antoine Pitrou84745ab2013-10-29 21:31:25 +01007041 Py_ssize_t i;
Guido van Rossum8d24ee92003-03-24 23:49:49 +00007042
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007043 subclasses = type->tp_subclasses;
7044 if (subclasses == NULL)
7045 return 0;
Antoine Pitrou84745ab2013-10-29 21:31:25 +01007046 assert(PyDict_CheckExact(subclasses));
7047 i = 0;
7048 while (PyDict_Next(subclasses, &i, NULL, &ref)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007049 assert(PyWeakref_CheckRef(ref));
7050 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
7051 assert(subclass != NULL);
7052 if ((PyObject *)subclass == Py_None)
7053 continue;
7054 assert(PyType_Check(subclass));
7055 /* Avoid recursing down into unaffected classes */
7056 dict = subclass->tp_dict;
7057 if (dict != NULL && PyDict_Check(dict) &&
7058 PyDict_GetItem(dict, name) != NULL)
7059 continue;
7060 if (update_subclasses(subclass, name, callback, data) < 0)
7061 return -1;
7062 }
7063 return 0;
Guido van Rossum8d24ee92003-03-24 23:49:49 +00007064}
7065
Guido van Rossum6d204072001-10-21 00:44:31 +00007066/* This function is called by PyType_Ready() to populate the type's
7067 dictionary with method descriptors for function slots. For each
Guido van Rossum09638c12002-06-13 19:17:46 +00007068 function slot (like tp_repr) that's defined in the type, one or more
7069 corresponding descriptors are added in the type's tp_dict dictionary
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007070 under the appropriate name (like __repr__). Some function slots
Guido van Rossum09638c12002-06-13 19:17:46 +00007071 cause more than one descriptor to be added (for example, the nb_add
7072 slot adds both __add__ and __radd__ descriptors) and some function
7073 slots compete for the same descriptor (for example both sq_item and
7074 mp_subscript generate a __getitem__ descriptor).
7075
Ezio Melotti13925002011-03-16 11:05:33 +02007076 In the latter case, the first slotdef entry encountered wins. Since
Tim Petersbf9b2442003-03-23 05:35:36 +00007077 slotdef entries are sorted by the offset of the slot in the
Guido van Rossume5c691a2003-03-07 15:13:17 +00007078 PyHeapTypeObject, this gives us some control over disambiguating
Guido van Rossum8d24ee92003-03-24 23:49:49 +00007079 between competing slots: the members of PyHeapTypeObject are listed
7080 from most general to least general, so the most general slot is
7081 preferred. In particular, because as_mapping comes before as_sequence,
7082 for a type that defines both mp_subscript and sq_item, mp_subscript
7083 wins.
Guido van Rossum09638c12002-06-13 19:17:46 +00007084
7085 This only adds new descriptors and doesn't overwrite entries in
7086 tp_dict that were previously defined. The descriptors contain a
7087 reference to the C function they must call, so that it's safe if they
7088 are copied into a subtype's __dict__ and the subtype has a different
7089 C function in its slot -- calling the method defined by the
7090 descriptor will call the C function that was used to create it,
7091 rather than the C function present in the slot when it is called.
7092 (This is important because a subtype may have a C function in the
7093 slot that calls the method from the dictionary, and we want to avoid
7094 infinite recursion here.) */
Guido van Rossum6d204072001-10-21 00:44:31 +00007095
7096static int
7097add_operators(PyTypeObject *type)
7098{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007099 PyObject *dict = type->tp_dict;
7100 slotdef *p;
7101 PyObject *descr;
7102 void **ptr;
Guido van Rossum6d204072001-10-21 00:44:31 +00007103
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007104 init_slotdefs();
7105 for (p = slotdefs; p->name; p++) {
7106 if (p->wrapper == NULL)
7107 continue;
7108 ptr = slotptr(type, p->offset);
7109 if (!ptr || !*ptr)
7110 continue;
7111 if (PyDict_GetItem(dict, p->name_strobj))
7112 continue;
Trent Nelsonab02db22012-09-18 21:58:03 -04007113 if (*ptr == (void *)PyObject_HashNotImplemented) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007114 /* Classes may prevent the inheritance of the tp_hash
7115 slot by storing PyObject_HashNotImplemented in it. Make it
7116 visible as a None value for the __hash__ attribute. */
7117 if (PyDict_SetItem(dict, p->name_strobj, Py_None) < 0)
7118 return -1;
7119 }
7120 else {
7121 descr = PyDescr_NewWrapper(type, p, *ptr);
7122 if (descr == NULL)
7123 return -1;
Benjamin Peterson27007dc2016-07-06 23:26:32 -07007124 if (PyDict_SetItem(dict, p->name_strobj, descr) < 0) {
7125 Py_DECREF(descr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007126 return -1;
Benjamin Peterson27007dc2016-07-06 23:26:32 -07007127 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007128 Py_DECREF(descr);
7129 }
7130 }
7131 if (type->tp_new != NULL) {
7132 if (add_tp_new_wrapper(type) < 0)
7133 return -1;
7134 }
7135 return 0;
Guido van Rossum6d204072001-10-21 00:44:31 +00007136}
7137
Guido van Rossum705f0f52001-08-24 16:47:00 +00007138
7139/* Cooperative 'super' */
7140
7141typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007142 PyObject_HEAD
7143 PyTypeObject *type;
7144 PyObject *obj;
7145 PyTypeObject *obj_type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00007146} superobject;
7147
Guido van Rossum6f799372001-09-20 20:46:19 +00007148static PyMemberDef super_members[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007149 {"__thisclass__", T_OBJECT, offsetof(superobject, type), READONLY,
7150 "the class invoking super()"},
7151 {"__self__", T_OBJECT, offsetof(superobject, obj), READONLY,
7152 "the instance invoking super(); may be None"},
7153 {"__self_class__", T_OBJECT, offsetof(superobject, obj_type), READONLY,
7154 "the type of the instance invoking super(); may be None"},
7155 {0}
Guido van Rossum41eb14d2001-08-30 23:13:11 +00007156};
7157
Guido van Rossum705f0f52001-08-24 16:47:00 +00007158static void
7159super_dealloc(PyObject *self)
7160{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007161 superobject *su = (superobject *)self;
Guido van Rossum705f0f52001-08-24 16:47:00 +00007162
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007163 _PyObject_GC_UNTRACK(self);
7164 Py_XDECREF(su->obj);
7165 Py_XDECREF(su->type);
7166 Py_XDECREF(su->obj_type);
7167 Py_TYPE(self)->tp_free(self);
Guido van Rossum705f0f52001-08-24 16:47:00 +00007168}
7169
7170static PyObject *
Guido van Rossum41eb14d2001-08-30 23:13:11 +00007171super_repr(PyObject *self)
7172{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007173 superobject *su = (superobject *)self;
Guido van Rossum41eb14d2001-08-30 23:13:11 +00007174
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007175 if (su->obj_type)
7176 return PyUnicode_FromFormat(
7177 "<super: <class '%s'>, <%s object>>",
7178 su->type ? su->type->tp_name : "NULL",
7179 su->obj_type->tp_name);
7180 else
7181 return PyUnicode_FromFormat(
7182 "<super: <class '%s'>, NULL>",
7183 su->type ? su->type->tp_name : "NULL");
Guido van Rossum41eb14d2001-08-30 23:13:11 +00007184}
7185
7186static PyObject *
Guido van Rossum705f0f52001-08-24 16:47:00 +00007187super_getattro(PyObject *self, PyObject *name)
7188{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007189 superobject *su = (superobject *)self;
Benjamin Peterson104b9e02015-02-05 22:29:14 -05007190 PyTypeObject *starttype;
7191 PyObject *mro;
7192 Py_ssize_t i, n;
Guido van Rossum705f0f52001-08-24 16:47:00 +00007193
Benjamin Peterson104b9e02015-02-05 22:29:14 -05007194 starttype = su->obj_type;
7195 if (starttype == NULL)
7196 goto skip;
7197
7198 /* We want __class__ to return the class of the super object
7199 (i.e. super, or a subclass), not the class of su->obj. */
7200 if (PyUnicode_Check(name) &&
7201 PyUnicode_GET_LENGTH(name) == 9 &&
7202 _PyUnicode_CompareWithId(name, &PyId___class__) == 0)
7203 goto skip;
7204
7205 mro = starttype->tp_mro;
7206 if (mro == NULL)
7207 goto skip;
7208
7209 assert(PyTuple_Check(mro));
7210 n = PyTuple_GET_SIZE(mro);
7211
7212 /* No need to check the last one: it's gonna be skipped anyway. */
7213 for (i = 0; i+1 < n; i++) {
7214 if ((PyObject *)(su->type) == PyTuple_GET_ITEM(mro, i))
7215 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007216 }
Benjamin Peterson104b9e02015-02-05 22:29:14 -05007217 i++; /* skip su->type (if any) */
7218 if (i >= n)
7219 goto skip;
Guido van Rossum76ba09f2003-04-16 19:40:58 +00007220
Benjamin Peterson104b9e02015-02-05 22:29:14 -05007221 /* keep a strong reference to mro because starttype->tp_mro can be
7222 replaced during PyDict_GetItem(dict, name) */
7223 Py_INCREF(mro);
7224 do {
7225 PyObject *res, *tmp, *dict;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007226 descrgetfunc f;
Guido van Rossum705f0f52001-08-24 16:47:00 +00007227
Benjamin Peterson104b9e02015-02-05 22:29:14 -05007228 tmp = PyTuple_GET_ITEM(mro, i);
7229 assert(PyType_Check(tmp));
Guido van Rossum155db9a2002-04-02 17:53:47 +00007230
Benjamin Peterson104b9e02015-02-05 22:29:14 -05007231 dict = ((PyTypeObject *)tmp)->tp_dict;
7232 assert(dict != NULL && PyDict_Check(dict));
7233
7234 res = PyDict_GetItem(dict, name);
7235 if (res != NULL) {
7236 Py_INCREF(res);
7237
7238 f = Py_TYPE(res)->tp_descr_get;
7239 if (f != NULL) {
7240 tmp = f(res,
7241 /* Only pass 'obj' param if this is instance-mode super
7242 (See SF ID #743627) */
7243 (su->obj == (PyObject *)starttype) ? NULL : su->obj,
7244 (PyObject *)starttype);
7245 Py_DECREF(res);
7246 res = tmp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007247 }
Benjamin Peterson104b9e02015-02-05 22:29:14 -05007248
7249 Py_DECREF(mro);
7250 return res;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007251 }
Benjamin Peterson104b9e02015-02-05 22:29:14 -05007252
7253 i++;
7254 } while (i < n);
7255 Py_DECREF(mro);
7256
7257 skip:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007258 return PyObject_GenericGetAttr(self, name);
Guido van Rossum705f0f52001-08-24 16:47:00 +00007259}
7260
Guido van Rossuma89d10e2003-02-12 03:58:38 +00007261static PyTypeObject *
Guido van Rossum5b443c62001-12-03 15:38:28 +00007262supercheck(PyTypeObject *type, PyObject *obj)
7263{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007264 /* Check that a super() call makes sense. Return a type object.
Guido van Rossuma89d10e2003-02-12 03:58:38 +00007265
Florent Xiclunaaa6c1d22011-12-12 18:54:29 +01007266 obj can be a class, or an instance of one:
Guido van Rossuma89d10e2003-02-12 03:58:38 +00007267
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007268 - If it is a class, it must be a subclass of 'type'. This case is
7269 used for class methods; the return value is obj.
Guido van Rossuma89d10e2003-02-12 03:58:38 +00007270
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007271 - If it is an instance, it must be an instance of 'type'. This is
7272 the normal case; the return value is obj.__class__.
Guido van Rossuma89d10e2003-02-12 03:58:38 +00007273
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007274 But... when obj is an instance, we want to allow for the case where
7275 Py_TYPE(obj) is not a subclass of type, but obj.__class__ is!
7276 This will allow using super() with a proxy for obj.
7277 */
Guido van Rossuma89d10e2003-02-12 03:58:38 +00007278
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007279 /* Check for first bullet above (special case) */
7280 if (PyType_Check(obj) && PyType_IsSubtype((PyTypeObject *)obj, type)) {
7281 Py_INCREF(obj);
7282 return (PyTypeObject *)obj;
7283 }
Guido van Rossum8e80a722003-02-18 19:22:22 +00007284
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007285 /* Normal case */
7286 if (PyType_IsSubtype(Py_TYPE(obj), type)) {
7287 Py_INCREF(Py_TYPE(obj));
7288 return Py_TYPE(obj);
7289 }
7290 else {
7291 /* Try the slow way */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007292 PyObject *class_attr;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00007293
Martin v. Löwisbfc6d742011-10-13 20:03:57 +02007294 class_attr = _PyObject_GetAttrId(obj, &PyId___class__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007295 if (class_attr != NULL &&
7296 PyType_Check(class_attr) &&
7297 (PyTypeObject *)class_attr != Py_TYPE(obj))
7298 {
7299 int ok = PyType_IsSubtype(
7300 (PyTypeObject *)class_attr, type);
7301 if (ok)
7302 return (PyTypeObject *)class_attr;
7303 }
Guido van Rossuma89d10e2003-02-12 03:58:38 +00007304
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007305 if (class_attr == NULL)
7306 PyErr_Clear();
7307 else
7308 Py_DECREF(class_attr);
7309 }
Guido van Rossuma89d10e2003-02-12 03:58:38 +00007310
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007311 PyErr_SetString(PyExc_TypeError,
7312 "super(type, obj): "
7313 "obj must be an instance or subtype of type");
7314 return NULL;
Guido van Rossum5b443c62001-12-03 15:38:28 +00007315}
7316
Guido van Rossum705f0f52001-08-24 16:47:00 +00007317static PyObject *
7318super_descr_get(PyObject *self, PyObject *obj, PyObject *type)
7319{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007320 superobject *su = (superobject *)self;
7321 superobject *newobj;
Guido van Rossum705f0f52001-08-24 16:47:00 +00007322
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007323 if (obj == NULL || obj == Py_None || su->obj != NULL) {
7324 /* Not binding to an object, or already bound */
7325 Py_INCREF(self);
7326 return self;
7327 }
7328 if (Py_TYPE(su) != &PySuper_Type)
7329 /* If su is an instance of a (strict) subclass of super,
7330 call its type */
7331 return PyObject_CallFunctionObjArgs((PyObject *)Py_TYPE(su),
7332 su->type, obj, NULL);
7333 else {
7334 /* Inline the common case */
7335 PyTypeObject *obj_type = supercheck(su->type, obj);
7336 if (obj_type == NULL)
7337 return NULL;
7338 newobj = (superobject *)PySuper_Type.tp_new(&PySuper_Type,
7339 NULL, NULL);
7340 if (newobj == NULL)
7341 return NULL;
7342 Py_INCREF(su->type);
7343 Py_INCREF(obj);
7344 newobj->type = su->type;
7345 newobj->obj = obj;
7346 newobj->obj_type = obj_type;
7347 return (PyObject *)newobj;
7348 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00007349}
7350
7351static int
7352super_init(PyObject *self, PyObject *args, PyObject *kwds)
7353{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007354 superobject *su = (superobject *)self;
7355 PyTypeObject *type = NULL;
7356 PyObject *obj = NULL;
7357 PyTypeObject *obj_type = NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00007358
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007359 if (!_PyArg_NoKeywords("super", kwds))
7360 return -1;
7361 if (!PyArg_ParseTuple(args, "|O!O:super", &PyType_Type, &type, &obj))
7362 return -1;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00007363
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007364 if (type == NULL) {
7365 /* Call super(), without args -- fill in from __class__
7366 and first local variable on the stack. */
Victor Stinner1c6970f2014-05-13 01:32:36 +02007367 PyFrameObject *f;
7368 PyCodeObject *co;
Victor Stinner0fcab4a2011-01-04 12:59:15 +00007369 Py_ssize_t i, n;
Victor Stinner1c6970f2014-05-13 01:32:36 +02007370 f = PyThreadState_GET()->frame;
7371 if (f == NULL) {
7372 PyErr_SetString(PyExc_RuntimeError,
7373 "super(): no current frame");
7374 return -1;
7375 }
7376 co = f->f_code;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007377 if (co == NULL) {
Benjamin Peterson6a42bd62012-09-01 23:04:38 -04007378 PyErr_SetString(PyExc_RuntimeError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007379 "super(): no code object");
7380 return -1;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00007381 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007382 if (co->co_argcount == 0) {
Benjamin Peterson6a42bd62012-09-01 23:04:38 -04007383 PyErr_SetString(PyExc_RuntimeError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007384 "super(): no arguments");
7385 return -1;
7386 }
7387 obj = f->f_localsplus[0];
Benjamin Peterson159ae412013-05-12 18:16:06 -05007388 if (obj == NULL && co->co_cell2arg) {
7389 /* The first argument might be a cell. */
7390 n = PyTuple_GET_SIZE(co->co_cellvars);
7391 for (i = 0; i < n; i++) {
7392 if (co->co_cell2arg[i] == 0) {
7393 PyObject *cell = f->f_localsplus[co->co_nlocals + i];
7394 assert(PyCell_Check(cell));
7395 obj = PyCell_GET(cell);
7396 break;
7397 }
7398 }
Guido van Rossum6832c812013-05-10 08:47:42 -07007399 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007400 if (obj == NULL) {
Benjamin Peterson6a42bd62012-09-01 23:04:38 -04007401 PyErr_SetString(PyExc_RuntimeError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007402 "super(): arg[0] deleted");
7403 return -1;
7404 }
7405 if (co->co_freevars == NULL)
7406 n = 0;
7407 else {
7408 assert(PyTuple_Check(co->co_freevars));
7409 n = PyTuple_GET_SIZE(co->co_freevars);
7410 }
7411 for (i = 0; i < n; i++) {
7412 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
7413 assert(PyUnicode_Check(name));
Victor Stinnerad14ccd2013-11-07 00:46:04 +01007414 if (!_PyUnicode_CompareWithId(name, &PyId___class__)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007415 Py_ssize_t index = co->co_nlocals +
7416 PyTuple_GET_SIZE(co->co_cellvars) + i;
7417 PyObject *cell = f->f_localsplus[index];
7418 if (cell == NULL || !PyCell_Check(cell)) {
Benjamin Peterson6a42bd62012-09-01 23:04:38 -04007419 PyErr_SetString(PyExc_RuntimeError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007420 "super(): bad __class__ cell");
7421 return -1;
7422 }
7423 type = (PyTypeObject *) PyCell_GET(cell);
7424 if (type == NULL) {
Benjamin Peterson6a42bd62012-09-01 23:04:38 -04007425 PyErr_SetString(PyExc_RuntimeError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007426 "super(): empty __class__ cell");
7427 return -1;
7428 }
7429 if (!PyType_Check(type)) {
Benjamin Peterson6a42bd62012-09-01 23:04:38 -04007430 PyErr_Format(PyExc_RuntimeError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007431 "super(): __class__ is not a type (%s)",
7432 Py_TYPE(type)->tp_name);
7433 return -1;
7434 }
7435 break;
7436 }
7437 }
7438 if (type == NULL) {
Benjamin Peterson6a42bd62012-09-01 23:04:38 -04007439 PyErr_SetString(PyExc_RuntimeError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007440 "super(): __class__ cell not found");
7441 return -1;
7442 }
7443 }
Guido van Rossumcd16bf62007-06-13 18:07:49 +00007444
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007445 if (obj == Py_None)
7446 obj = NULL;
7447 if (obj != NULL) {
7448 obj_type = supercheck(type, obj);
7449 if (obj_type == NULL)
7450 return -1;
7451 Py_INCREF(obj);
7452 }
7453 Py_INCREF(type);
Serhiy Storchaka3d749762016-04-13 15:27:33 +03007454 Py_XSETREF(su->type, type);
7455 Py_XSETREF(su->obj, obj);
7456 Py_XSETREF(su->obj_type, obj_type);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007457 return 0;
Guido van Rossum705f0f52001-08-24 16:47:00 +00007458}
7459
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007460PyDoc_STRVAR(super_doc,
Guido van Rossumcd16bf62007-06-13 18:07:49 +00007461"super() -> same as super(__class__, <first argument>)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00007462"super(type) -> unbound super object\n"
7463"super(type, obj) -> bound super object; requires isinstance(obj, type)\n"
Guido van Rossume705ef12001-08-29 15:47:06 +00007464"super(type, type2) -> bound super object; requires issubclass(type2, type)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00007465"Typical use to call a cooperative superclass method:\n"
7466"class C(B):\n"
7467" def meth(self, arg):\n"
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007468" super().meth(arg)\n"
Guido van Rossumcd16bf62007-06-13 18:07:49 +00007469"This works for class methods too:\n"
7470"class C(B):\n"
7471" @classmethod\n"
7472" def cmeth(cls, arg):\n"
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007473" super().cmeth(arg)\n");
Guido van Rossum705f0f52001-08-24 16:47:00 +00007474
Guido van Rossum048eb752001-10-02 21:24:57 +00007475static int
7476super_traverse(PyObject *self, visitproc visit, void *arg)
7477{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007478 superobject *su = (superobject *)self;
Guido van Rossum048eb752001-10-02 21:24:57 +00007479
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007480 Py_VISIT(su->obj);
7481 Py_VISIT(su->type);
7482 Py_VISIT(su->obj_type);
Guido van Rossum048eb752001-10-02 21:24:57 +00007483
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007484 return 0;
Guido van Rossum048eb752001-10-02 21:24:57 +00007485}
7486
Guido van Rossum705f0f52001-08-24 16:47:00 +00007487PyTypeObject PySuper_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007488 PyVarObject_HEAD_INIT(&PyType_Type, 0)
7489 "super", /* tp_name */
7490 sizeof(superobject), /* tp_basicsize */
7491 0, /* tp_itemsize */
7492 /* methods */
7493 super_dealloc, /* tp_dealloc */
7494 0, /* tp_print */
7495 0, /* tp_getattr */
7496 0, /* tp_setattr */
7497 0, /* tp_reserved */
7498 super_repr, /* tp_repr */
7499 0, /* tp_as_number */
7500 0, /* tp_as_sequence */
7501 0, /* tp_as_mapping */
7502 0, /* tp_hash */
7503 0, /* tp_call */
7504 0, /* tp_str */
7505 super_getattro, /* tp_getattro */
7506 0, /* tp_setattro */
7507 0, /* tp_as_buffer */
7508 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
7509 Py_TPFLAGS_BASETYPE, /* tp_flags */
7510 super_doc, /* tp_doc */
7511 super_traverse, /* tp_traverse */
7512 0, /* tp_clear */
7513 0, /* tp_richcompare */
7514 0, /* tp_weaklistoffset */
7515 0, /* tp_iter */
7516 0, /* tp_iternext */
7517 0, /* tp_methods */
7518 super_members, /* tp_members */
7519 0, /* tp_getset */
7520 0, /* tp_base */
7521 0, /* tp_dict */
7522 super_descr_get, /* tp_descr_get */
7523 0, /* tp_descr_set */
7524 0, /* tp_dictoffset */
7525 super_init, /* tp_init */
7526 PyType_GenericAlloc, /* tp_alloc */
7527 PyType_GenericNew, /* tp_new */
7528 PyObject_GC_Del, /* tp_free */
Guido van Rossum705f0f52001-08-24 16:47:00 +00007529};