blob: 1181d77efd09cd159a8abd15b3805b39a3360e86 [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__);
Martin v. Löwise75fc142013-11-07 18:46:53 +010056_Py_IDENTIFIER(__len__);
Victor Stinner3c1e4812012-03-26 22:10:51 +020057_Py_IDENTIFIER(__module__);
58_Py_IDENTIFIER(__name__);
59_Py_IDENTIFIER(__new__);
Martin v. Löwise75fc142013-11-07 18:46:53 +010060_Py_IDENTIFIER(__setitem__);
Victor Stinnerbd303c12013-11-07 23:07:29 +010061_Py_IDENTIFIER(builtins);
Victor Stinner3c1e4812012-03-26 22:10:51 +020062
63static PyObject *
Martin v. Löwis9c564092012-06-23 23:20:45 +020064slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
65
Martin v. Löwis996b6712014-07-26 16:44:07 +020066static void
Victor Stinner331a7262014-07-27 16:11:30 +020067clear_slotdefs(void);
Martin v. Löwis996b6712014-07-26 16:44:07 +020068
Larry Hastings5c661892014-01-24 06:17:25 -080069/*
Larry Hastings2623c8c2014-02-08 22:15:29 -080070 * finds the beginning of the docstring's introspection signature.
Larry Hastings5c661892014-01-24 06:17:25 -080071 * if present, returns a pointer pointing to the first '('.
72 * otherwise returns NULL.
Larry Hastings2623c8c2014-02-08 22:15:29 -080073 *
74 * doesn't guarantee that the signature is valid, only that it
75 * has a valid prefix. (the signature must also pass skip_signature.)
Larry Hastings5c661892014-01-24 06:17:25 -080076 */
77static const char *
Larry Hastings2623c8c2014-02-08 22:15:29 -080078find_signature(const char *name, const char *doc)
Larry Hastings5c661892014-01-24 06:17:25 -080079{
Larry Hastings2623c8c2014-02-08 22:15:29 -080080 const char *dot;
81 size_t length;
82
83 if (!doc)
84 return NULL;
85
86 assert(name != NULL);
87
88 /* for dotted names like classes, only use the last component */
89 dot = strrchr(name, '.');
90 if (dot)
91 name = dot + 1;
92
93 length = strlen(name);
94 if (strncmp(doc, name, length))
95 return NULL;
96 doc += length;
97 if (*doc != '(')
98 return NULL;
99 return doc;
Larry Hastings5c661892014-01-24 06:17:25 -0800100}
101
Larry Hastings2623c8c2014-02-08 22:15:29 -0800102#define SIGNATURE_END_MARKER ")\n--\n\n"
103#define SIGNATURE_END_MARKER_LENGTH 6
Larry Hastings5c661892014-01-24 06:17:25 -0800104/*
Larry Hastings2623c8c2014-02-08 22:15:29 -0800105 * skips past the end of the docstring's instrospection signature.
106 * (assumes doc starts with a valid signature prefix.)
Larry Hastings5c661892014-01-24 06:17:25 -0800107 */
108static const char *
109skip_signature(const char *doc)
110{
Larry Hastings2623c8c2014-02-08 22:15:29 -0800111 while (*doc) {
112 if ((*doc == *SIGNATURE_END_MARKER) &&
113 !strncmp(doc, SIGNATURE_END_MARKER, SIGNATURE_END_MARKER_LENGTH))
114 return doc + SIGNATURE_END_MARKER_LENGTH;
115 if ((*doc == '\n') && (doc[1] == '\n'))
116 return NULL;
Larry Hastings5c661892014-01-24 06:17:25 -0800117 doc++;
Larry Hastings2623c8c2014-02-08 22:15:29 -0800118 }
119 return NULL;
Larry Hastings5c661892014-01-24 06:17:25 -0800120}
121
122static const char *
Larry Hastings2623c8c2014-02-08 22:15:29 -0800123_PyType_DocWithoutSignature(const char *name, const char *internal_doc)
Larry Hastings5c661892014-01-24 06:17:25 -0800124{
Larry Hastings2623c8c2014-02-08 22:15:29 -0800125 const char *doc = find_signature(name, internal_doc);
Larry Hastings5c661892014-01-24 06:17:25 -0800126
Larry Hastings2623c8c2014-02-08 22:15:29 -0800127 if (doc) {
128 doc = skip_signature(doc);
129 if (doc)
130 return doc;
131 }
Larry Hastings5c661892014-01-24 06:17:25 -0800132 return internal_doc;
133}
134
135PyObject *
Larry Hastings2623c8c2014-02-08 22:15:29 -0800136_PyType_GetDocFromInternalDoc(const char *name, const char *internal_doc)
Larry Hastings5c661892014-01-24 06:17:25 -0800137{
Larry Hastings2623c8c2014-02-08 22:15:29 -0800138 const char *doc = _PyType_DocWithoutSignature(name, internal_doc);
Larry Hastings5c661892014-01-24 06:17:25 -0800139
Zachary Ware8ef887c2015-04-13 18:22:35 -0500140 if (!doc || *doc == '\0') {
Larry Hastings5c661892014-01-24 06:17:25 -0800141 Py_INCREF(Py_None);
142 return Py_None;
143 }
144
145 return PyUnicode_FromString(doc);
146}
147
148PyObject *
Larry Hastings2623c8c2014-02-08 22:15:29 -0800149_PyType_GetTextSignatureFromInternalDoc(const char *name, const char *internal_doc)
Larry Hastings5c661892014-01-24 06:17:25 -0800150{
Larry Hastings2623c8c2014-02-08 22:15:29 -0800151 const char *start = find_signature(name, internal_doc);
152 const char *end;
Larry Hastings5c661892014-01-24 06:17:25 -0800153
Larry Hastings2623c8c2014-02-08 22:15:29 -0800154 if (start)
155 end = skip_signature(start);
156 else
157 end = NULL;
158 if (!end) {
Larry Hastings5c661892014-01-24 06:17:25 -0800159 Py_INCREF(Py_None);
160 return Py_None;
161 }
162
Larry Hastings2623c8c2014-02-08 22:15:29 -0800163 /* back "end" up until it points just past the final ')' */
164 end -= SIGNATURE_END_MARKER_LENGTH - 1;
165 assert((end - start) >= 2); /* should be "()" at least */
166 assert(end[-1] == ')');
167 assert(end[0] == '\n');
168 return PyUnicode_FromStringAndSize(start, end - start);
Larry Hastings5c661892014-01-24 06:17:25 -0800169}
170
Christian Heimes26855632008-01-27 23:50:43 +0000171unsigned int
172PyType_ClearCache(void)
173{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000174 Py_ssize_t i;
175 unsigned int cur_version_tag = next_version_tag - 1;
176
Antoine Pitrou2a40e362014-11-15 00:56:27 +0100177#if MCACHE_STATS
178 size_t total = method_cache_hits + method_cache_collisions + method_cache_misses;
179 fprintf(stderr, "-- Method cache hits = %zd (%d%%)\n",
180 method_cache_hits, (int) (100.0 * method_cache_hits / total));
181 fprintf(stderr, "-- Method cache true misses = %zd (%d%%)\n",
182 method_cache_misses, (int) (100.0 * method_cache_misses / total));
183 fprintf(stderr, "-- Method cache collisions = %zd (%d%%)\n",
184 method_cache_collisions, (int) (100.0 * method_cache_collisions / total));
185 fprintf(stderr, "-- Method cache size = %zd KB\n",
186 sizeof(method_cache) / 1024);
187#endif
188
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000189 for (i = 0; i < (1 << MCACHE_SIZE_EXP); i++) {
190 method_cache[i].version = 0;
191 Py_CLEAR(method_cache[i].name);
192 method_cache[i].value = NULL;
193 }
194 next_version_tag = 0;
195 /* mark all version tags as invalid */
196 PyType_Modified(&PyBaseObject_Type);
197 return cur_version_tag;
Christian Heimes26855632008-01-27 23:50:43 +0000198}
Christian Heimesa62da1d2008-01-12 19:39:10 +0000199
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000200void
Antoine Pitrou957a23b2013-05-04 20:45:02 +0200201_PyType_Fini(void)
202{
203 PyType_ClearCache();
Martin v. Löwis996b6712014-07-26 16:44:07 +0200204 clear_slotdefs();
Antoine Pitrou957a23b2013-05-04 20:45:02 +0200205}
206
207void
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000208PyType_Modified(PyTypeObject *type)
Christian Heimesa62da1d2008-01-12 19:39:10 +0000209{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000210 /* Invalidate any cached data for the specified type and all
211 subclasses. This function is called after the base
212 classes, mro, or attributes of the type are altered.
Christian Heimesa62da1d2008-01-12 19:39:10 +0000213
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000214 Invariants:
Christian Heimesa62da1d2008-01-12 19:39:10 +0000215
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000216 - Py_TPFLAGS_VALID_VERSION_TAG is never set if
217 Py_TPFLAGS_HAVE_VERSION_TAG is not set (e.g. on type
218 objects coming from non-recompiled extension modules)
Christian Heimesa62da1d2008-01-12 19:39:10 +0000219
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000220 - before Py_TPFLAGS_VALID_VERSION_TAG can be set on a type,
221 it must first be set on all super types.
Christian Heimesa62da1d2008-01-12 19:39:10 +0000222
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000223 This function clears the Py_TPFLAGS_VALID_VERSION_TAG of a
224 type (so it must first clear it on all subclasses). The
225 tp_version_tag value is meaningless unless this flag is set.
226 We don't assign new version tags eagerly, but only as
227 needed.
228 */
229 PyObject *raw, *ref;
Antoine Pitrou84745ab2013-10-29 21:31:25 +0100230 Py_ssize_t i;
Christian Heimesa62da1d2008-01-12 19:39:10 +0000231
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000232 if (!PyType_HasFeature(type, Py_TPFLAGS_VALID_VERSION_TAG))
233 return;
Christian Heimesa62da1d2008-01-12 19:39:10 +0000234
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000235 raw = type->tp_subclasses;
236 if (raw != NULL) {
Antoine Pitrou84745ab2013-10-29 21:31:25 +0100237 assert(PyDict_CheckExact(raw));
238 i = 0;
239 while (PyDict_Next(raw, &i, NULL, &ref)) {
240 assert(PyWeakref_CheckRef(ref));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000241 ref = PyWeakref_GET_OBJECT(ref);
242 if (ref != Py_None) {
243 PyType_Modified((PyTypeObject *)ref);
244 }
245 }
246 }
247 type->tp_flags &= ~Py_TPFLAGS_VALID_VERSION_TAG;
Christian Heimesa62da1d2008-01-12 19:39:10 +0000248}
249
250static void
251type_mro_modified(PyTypeObject *type, PyObject *bases) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000252 /*
Florent Xiclunaaa6c1d22011-12-12 18:54:29 +0100253 Check that all base classes or elements of the MRO of type are
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000254 able to be cached. This function is called after the base
255 classes or mro of the type are altered.
Christian Heimesa62da1d2008-01-12 19:39:10 +0000256
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000257 Unset HAVE_VERSION_TAG and VALID_VERSION_TAG if the type
Florent Xiclunaaa6c1d22011-12-12 18:54:29 +0100258 has a custom MRO that includes a type which is not officially
259 super type.
Christian Heimesa62da1d2008-01-12 19:39:10 +0000260
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000261 Called from mro_internal, which will subsequently be called on
262 each subclass when their mro is recursively updated.
263 */
264 Py_ssize_t i, n;
265 int clear = 0;
Christian Heimesa62da1d2008-01-12 19:39:10 +0000266
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000267 if (!PyType_HasFeature(type, Py_TPFLAGS_HAVE_VERSION_TAG))
268 return;
Christian Heimesa62da1d2008-01-12 19:39:10 +0000269
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000270 n = PyTuple_GET_SIZE(bases);
271 for (i = 0; i < n; i++) {
272 PyObject *b = PyTuple_GET_ITEM(bases, i);
273 PyTypeObject *cls;
Christian Heimesa62da1d2008-01-12 19:39:10 +0000274
Florent Xiclunaaa6c1d22011-12-12 18:54:29 +0100275 assert(PyType_Check(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000276 cls = (PyTypeObject *)b;
Christian Heimesa62da1d2008-01-12 19:39:10 +0000277
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000278 if (!PyType_HasFeature(cls, Py_TPFLAGS_HAVE_VERSION_TAG) ||
279 !PyType_IsSubtype(type, cls)) {
280 clear = 1;
281 break;
282 }
283 }
Christian Heimesa62da1d2008-01-12 19:39:10 +0000284
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000285 if (clear)
286 type->tp_flags &= ~(Py_TPFLAGS_HAVE_VERSION_TAG|
287 Py_TPFLAGS_VALID_VERSION_TAG);
Christian Heimesa62da1d2008-01-12 19:39:10 +0000288}
289
290static int
291assign_version_tag(PyTypeObject *type)
292{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000293 /* Ensure that the tp_version_tag is valid and set
294 Py_TPFLAGS_VALID_VERSION_TAG. To respect the invariant, this
295 must first be done on all super classes. Return 0 if this
296 cannot be done, 1 if Py_TPFLAGS_VALID_VERSION_TAG.
297 */
298 Py_ssize_t i, n;
299 PyObject *bases;
Christian Heimesa62da1d2008-01-12 19:39:10 +0000300
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000301 if (PyType_HasFeature(type, Py_TPFLAGS_VALID_VERSION_TAG))
302 return 1;
303 if (!PyType_HasFeature(type, Py_TPFLAGS_HAVE_VERSION_TAG))
304 return 0;
305 if (!PyType_HasFeature(type, Py_TPFLAGS_READY))
306 return 0;
Christian Heimesa62da1d2008-01-12 19:39:10 +0000307
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000308 type->tp_version_tag = next_version_tag++;
309 /* for stress-testing: next_version_tag &= 0xFF; */
Christian Heimesa62da1d2008-01-12 19:39:10 +0000310
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000311 if (type->tp_version_tag == 0) {
312 /* wrap-around or just starting Python - clear the whole
313 cache by filling names with references to Py_None.
314 Values are also set to NULL for added protection, as they
315 are borrowed reference */
316 for (i = 0; i < (1 << MCACHE_SIZE_EXP); i++) {
317 method_cache[i].value = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000318 Py_INCREF(Py_None);
Serhiy Storchaka48842712016-04-06 09:45:48 +0300319 Py_XSETREF(method_cache[i].name, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000320 }
321 /* mark all version tags as invalid */
322 PyType_Modified(&PyBaseObject_Type);
323 return 1;
324 }
325 bases = type->tp_bases;
326 n = PyTuple_GET_SIZE(bases);
327 for (i = 0; i < n; i++) {
328 PyObject *b = PyTuple_GET_ITEM(bases, i);
329 assert(PyType_Check(b));
330 if (!assign_version_tag((PyTypeObject *)b))
331 return 0;
332 }
333 type->tp_flags |= Py_TPFLAGS_VALID_VERSION_TAG;
334 return 1;
Christian Heimesa62da1d2008-01-12 19:39:10 +0000335}
336
337
Guido van Rossum6f799372001-09-20 20:46:19 +0000338static PyMemberDef type_members[] = {
Benjamin Peterson0e102062010-08-25 23:13:17 +0000339 {"__basicsize__", T_PYSSIZET, offsetof(PyTypeObject,tp_basicsize),READONLY},
340 {"__itemsize__", T_PYSSIZET, offsetof(PyTypeObject, tp_itemsize), READONLY},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000341 {"__flags__", T_LONG, offsetof(PyTypeObject, tp_flags), READONLY},
342 {"__weakrefoffset__", T_LONG,
343 offsetof(PyTypeObject, tp_weaklistoffset), READONLY},
344 {"__base__", T_OBJECT, offsetof(PyTypeObject, tp_base), READONLY},
345 {"__dictoffset__", T_LONG,
346 offsetof(PyTypeObject, tp_dictoffset), READONLY},
347 {"__mro__", T_OBJECT, offsetof(PyTypeObject, tp_mro), READONLY},
348 {0}
Tim Peters6d6c1a32001-08-02 04:15:00 +0000349};
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000350
Benjamin Petersond9f23d22011-08-17 11:54:03 -0500351static int
352check_set_special_type_attr(PyTypeObject *type, PyObject *value, const char *name)
353{
354 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
355 PyErr_Format(PyExc_TypeError,
356 "can't set %s.%s", type->tp_name, name);
357 return 0;
358 }
359 if (!value) {
360 PyErr_Format(PyExc_TypeError,
361 "can't delete %s.%s", type->tp_name, name);
362 return 0;
363 }
364 return 1;
365}
366
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000367static PyObject *
Guido van Rossumc3542212001-08-16 09:18:56 +0000368type_name(PyTypeObject *type, void *context)
369{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000370 const char *s;
Guido van Rossumc3542212001-08-16 09:18:56 +0000371
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000372 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
373 PyHeapTypeObject* et = (PyHeapTypeObject*)type;
Tim Petersea7f75d2002-12-07 21:39:16 +0000374
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000375 Py_INCREF(et->ht_name);
376 return et->ht_name;
377 }
378 else {
379 s = strrchr(type->tp_name, '.');
380 if (s == NULL)
381 s = type->tp_name;
382 else
383 s++;
384 return PyUnicode_FromString(s);
385 }
Guido van Rossumc3542212001-08-16 09:18:56 +0000386}
387
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100388static PyObject *
389type_qualname(PyTypeObject *type, void *context)
390{
391 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
392 PyHeapTypeObject* et = (PyHeapTypeObject*)type;
393 Py_INCREF(et->ht_qualname);
394 return et->ht_qualname;
395 }
396 else {
397 return type_name(type, context);
398 }
399}
400
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000401static int
402type_set_name(PyTypeObject *type, PyObject *value, void *context)
403{
Serhiy Storchaka42bf8fc2015-12-30 21:40:49 +0200404 const char *tp_name;
405 Py_ssize_t name_size;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000406
Benjamin Petersond9f23d22011-08-17 11:54:03 -0500407 if (!check_set_special_type_attr(type, value, "__name__"))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000408 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000409 if (!PyUnicode_Check(value)) {
410 PyErr_Format(PyExc_TypeError,
411 "can only assign string to %s.__name__, not '%s'",
412 type->tp_name, Py_TYPE(value)->tp_name);
413 return -1;
414 }
Guido van Rossume845c0f2007-11-02 23:07:07 +0000415
Serhiy Storchaka42bf8fc2015-12-30 21:40:49 +0200416 tp_name = PyUnicode_AsUTF8AndSize(value, &name_size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000417 if (tp_name == NULL)
418 return -1;
Serhiy Storchaka42bf8fc2015-12-30 21:40:49 +0200419 if (strlen(tp_name) != (size_t)name_size) {
420 PyErr_SetString(PyExc_ValueError,
421 "type name must not contain null characters");
422 return -1;
423 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000424
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000425 type->tp_name = tp_name;
Serhiy Storchaka42bf8fc2015-12-30 21:40:49 +0200426 Py_INCREF(value);
Serhiy Storchaka57a01d32016-04-10 18:05:40 +0300427 Py_SETREF(((PyHeapTypeObject*)type)->ht_name, value);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000428
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000429 return 0;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000430}
431
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100432static int
433type_set_qualname(PyTypeObject *type, PyObject *value, void *context)
434{
435 PyHeapTypeObject* et;
436
Benjamin Peterson2c05a2e2012-10-31 00:01:15 -0400437 if (!check_set_special_type_attr(type, value, "__qualname__"))
438 return -1;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100439 if (!PyUnicode_Check(value)) {
440 PyErr_Format(PyExc_TypeError,
441 "can only assign string to %s.__qualname__, not '%s'",
442 type->tp_name, Py_TYPE(value)->tp_name);
443 return -1;
444 }
445
446 et = (PyHeapTypeObject*)type;
447 Py_INCREF(value);
Serhiy Storchaka57a01d32016-04-10 18:05:40 +0300448 Py_SETREF(et->ht_qualname, value);
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100449 return 0;
450}
451
Guido van Rossumc3542212001-08-16 09:18:56 +0000452static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000453type_module(PyTypeObject *type, void *context)
Guido van Rossum29ca26e1995-01-07 11:58:15 +0000454{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000455 char *s;
Guido van Rossumc3542212001-08-16 09:18:56 +0000456
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000457 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
Victor Stinnerad14ccd2013-11-07 00:46:04 +0100458 PyObject *mod = _PyDict_GetItemId(type->tp_dict, &PyId___module__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000459 if (!mod) {
460 PyErr_Format(PyExc_AttributeError, "__module__");
461 return 0;
462 }
463 Py_XINCREF(mod);
464 return mod;
465 }
466 else {
Victor Stinnerad14ccd2013-11-07 00:46:04 +0100467 PyObject *name;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000468 s = strrchr(type->tp_name, '.');
469 if (s != NULL)
470 return PyUnicode_FromStringAndSize(
471 type->tp_name, (Py_ssize_t)(s - type->tp_name));
Victor Stinnerbd303c12013-11-07 23:07:29 +0100472 name = _PyUnicode_FromId(&PyId_builtins);
Victor Stinnerad14ccd2013-11-07 00:46:04 +0100473 Py_XINCREF(name);
474 return name;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000475 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000476}
477
Guido van Rossum3926a632001-09-25 16:25:58 +0000478static int
479type_set_module(PyTypeObject *type, PyObject *value, void *context)
480{
Benjamin Petersond9f23d22011-08-17 11:54:03 -0500481 if (!check_set_special_type_attr(type, value, "__module__"))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000482 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000483
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000484 PyType_Modified(type);
Christian Heimesa62da1d2008-01-12 19:39:10 +0000485
Victor Stinner3c1e4812012-03-26 22:10:51 +0200486 return _PyDict_SetItemId(type->tp_dict, &PyId___module__, value);
Guido van Rossum3926a632001-09-25 16:25:58 +0000487}
488
Tim Peters6d6c1a32001-08-02 04:15:00 +0000489static PyObject *
Christian Heimes9e7f1d22008-02-28 12:27:11 +0000490type_abstractmethods(PyTypeObject *type, void *context)
491{
Benjamin Petersonaec5fd12010-10-02 00:03:31 +0000492 PyObject *mod = NULL;
Benjamin Peterson84060b82010-10-03 02:13:39 +0000493 /* type itself has an __abstractmethods__ descriptor (this). Don't return
494 that. */
Benjamin Petersonaec5fd12010-10-02 00:03:31 +0000495 if (type != &PyType_Type)
Victor Stinner3688aa92013-11-06 18:59:18 +0100496 mod = _PyDict_GetItemId(type->tp_dict, &PyId___abstractmethods__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000497 if (!mod) {
Victor Stinner3688aa92013-11-06 18:59:18 +0100498 PyObject *message = _PyUnicode_FromId(&PyId___abstractmethods__);
499 if (message)
500 PyErr_SetObject(PyExc_AttributeError, message);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000501 return NULL;
502 }
503 Py_XINCREF(mod);
504 return mod;
Christian Heimes9e7f1d22008-02-28 12:27:11 +0000505}
506
507static int
508type_set_abstractmethods(PyTypeObject *type, PyObject *value, void *context)
509{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000510 /* __abstractmethods__ should only be set once on a type, in
511 abc.ABCMeta.__new__, so this function doesn't do anything
512 special to update subclasses.
513 */
Antoine Pitrou6f430e42012-08-15 23:18:25 +0200514 int abstract, res;
Benjamin Peterson477ba912011-01-12 15:34:01 +0000515 if (value != NULL) {
Antoine Pitrou6f430e42012-08-15 23:18:25 +0200516 abstract = PyObject_IsTrue(value);
517 if (abstract < 0)
518 return -1;
Victor Stinner3688aa92013-11-06 18:59:18 +0100519 res = _PyDict_SetItemId(type->tp_dict, &PyId___abstractmethods__, value);
Benjamin Peterson477ba912011-01-12 15:34:01 +0000520 }
521 else {
Antoine Pitrou6f430e42012-08-15 23:18:25 +0200522 abstract = 0;
Victor Stinner3688aa92013-11-06 18:59:18 +0100523 res = _PyDict_DelItemId(type->tp_dict, &PyId___abstractmethods__);
Benjamin Peterson477ba912011-01-12 15:34:01 +0000524 if (res && PyErr_ExceptionMatches(PyExc_KeyError)) {
Victor Stinner3688aa92013-11-06 18:59:18 +0100525 PyObject *message = _PyUnicode_FromId(&PyId___abstractmethods__);
526 if (message)
527 PyErr_SetObject(PyExc_AttributeError, message);
Benjamin Peterson477ba912011-01-12 15:34:01 +0000528 return -1;
529 }
530 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000531 if (res == 0) {
532 PyType_Modified(type);
Antoine Pitrou6f430e42012-08-15 23:18:25 +0200533 if (abstract)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000534 type->tp_flags |= Py_TPFLAGS_IS_ABSTRACT;
Antoine Pitrou6f430e42012-08-15 23:18:25 +0200535 else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000536 type->tp_flags &= ~Py_TPFLAGS_IS_ABSTRACT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000537 }
538 return res;
Christian Heimes9e7f1d22008-02-28 12:27:11 +0000539}
540
541static PyObject *
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000542type_get_bases(PyTypeObject *type, void *context)
543{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000544 Py_INCREF(type->tp_bases);
545 return type->tp_bases;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000546}
547
548static PyTypeObject *best_base(PyObject *);
Benjamin Peterson104b9e02015-02-05 22:29:14 -0500549static int mro_internal(PyTypeObject *, PyObject **);
Steve Dowerb4e20bb2015-02-06 08:50:23 -0800550Py_LOCAL_INLINE(int) type_is_subtype_base_chain(PyTypeObject *, PyTypeObject *);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000551static int compatible_for_assignment(PyTypeObject *, PyTypeObject *, char *);
552static int add_subclass(PyTypeObject*, PyTypeObject*);
Benjamin Peterson104b9e02015-02-05 22:29:14 -0500553static int add_all_subclasses(PyTypeObject *type, PyObject *bases);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000554static void remove_subclass(PyTypeObject *, PyTypeObject *);
Antoine Pitrou84745ab2013-10-29 21:31:25 +0100555static void remove_all_subclasses(PyTypeObject *type, PyObject *bases);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000556static void update_all_slots(PyTypeObject *);
557
Guido van Rossum8d24ee92003-03-24 23:49:49 +0000558typedef int (*update_callback)(PyTypeObject *, void *);
559static int update_subclasses(PyTypeObject *type, PyObject *name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000560 update_callback callback, void *data);
Guido van Rossum8d24ee92003-03-24 23:49:49 +0000561static int recurse_down_subclasses(PyTypeObject *type, PyObject *name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000562 update_callback callback, void *data);
Benjamin Peterson104b9e02015-02-05 22:29:14 -0500563static PyObject *type_subclasses(PyTypeObject *type, PyObject *ignored);
Guido van Rossum8d24ee92003-03-24 23:49:49 +0000564
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000565static int
Benjamin Peterson104b9e02015-02-05 22:29:14 -0500566mro_hierarchy(PyTypeObject *type, PyObject *temp)
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000567{
Benjamin Peterson104b9e02015-02-05 22:29:14 -0500568 int res;
569 PyObject *new_mro, *old_mro;
570 PyObject *tuple;
571 PyObject *subclasses;
572 Py_ssize_t i, n;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000573
Benjamin Peterson104b9e02015-02-05 22:29:14 -0500574 res = mro_internal(type, &old_mro);
575 if (res <= 0)
576 /* error / reentrance */
577 return res;
578 new_mro = type->tp_mro;
Antoine Pitrou84745ab2013-10-29 21:31:25 +0100579
Benjamin Peterson104b9e02015-02-05 22:29:14 -0500580 if (old_mro != NULL)
581 tuple = PyTuple_Pack(3, type, new_mro, old_mro);
582 else
583 tuple = PyTuple_Pack(2, type, new_mro);
584
585 if (tuple != NULL)
586 res = PyList_Append(temp, tuple);
587 else
588 res = -1;
589 Py_XDECREF(tuple);
590
591 if (res < 0) {
592 type->tp_mro = old_mro;
593 Py_DECREF(new_mro);
594 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000595 }
Benjamin Peterson104b9e02015-02-05 22:29:14 -0500596 Py_XDECREF(old_mro);
597
598 /* Obtain a copy of subclasses list to iterate over.
599
600 Otherwise type->tp_subclasses might be altered
601 in the middle of the loop, for example, through a custom mro(),
602 by invoking type_set_bases on some subclass of the type
603 which in turn calls remove_subclass/add_subclass on this type.
604
605 Finally, this makes things simple avoiding the need to deal
606 with dictionary iterators and weak references.
607 */
608 subclasses = type_subclasses(type, NULL);
609 if (subclasses == NULL)
610 return -1;
611 n = PyList_GET_SIZE(subclasses);
612 for (i = 0; i < n; i++) {
613 PyTypeObject *subclass;
614 subclass = (PyTypeObject *)PyList_GET_ITEM(subclasses, i);
615 res = mro_hierarchy(subclass, temp);
616 if (res < 0)
617 break;
618 }
619 Py_DECREF(subclasses);
620
621 return res;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000622}
623
624static int
Benjamin Peterson104b9e02015-02-05 22:29:14 -0500625type_set_bases(PyTypeObject *type, PyObject *new_bases, void *context)
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000626{
Benjamin Peterson104b9e02015-02-05 22:29:14 -0500627 int res = 0;
628 PyObject *temp;
629 PyObject *old_bases;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000630 PyTypeObject *new_base, *old_base;
Benjamin Peterson104b9e02015-02-05 22:29:14 -0500631 Py_ssize_t i;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000632
Benjamin Peterson104b9e02015-02-05 22:29:14 -0500633 if (!check_set_special_type_attr(type, new_bases, "__bases__"))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000634 return -1;
Benjamin Peterson104b9e02015-02-05 22:29:14 -0500635 if (!PyTuple_Check(new_bases)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000636 PyErr_Format(PyExc_TypeError,
637 "can only assign tuple to %s.__bases__, not %s",
Benjamin Peterson104b9e02015-02-05 22:29:14 -0500638 type->tp_name, Py_TYPE(new_bases)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000639 return -1;
640 }
Benjamin Peterson104b9e02015-02-05 22:29:14 -0500641 if (PyTuple_GET_SIZE(new_bases) == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000642 PyErr_Format(PyExc_TypeError,
643 "can only assign non-empty tuple to %s.__bases__, not ()",
644 type->tp_name);
645 return -1;
646 }
Benjamin Peterson104b9e02015-02-05 22:29:14 -0500647 for (i = 0; i < PyTuple_GET_SIZE(new_bases); i++) {
648 PyObject *ob;
649 PyTypeObject *base;
650
651 ob = PyTuple_GET_ITEM(new_bases, i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000652 if (!PyType_Check(ob)) {
Benjamin Petersonb6af60c2012-04-01 18:49:54 -0400653 PyErr_Format(PyExc_TypeError,
Benjamin Peterson9ee601e2012-04-01 18:51:37 -0400654 "%s.__bases__ must be tuple of classes, not '%s'",
Benjamin Petersonb6af60c2012-04-01 18:49:54 -0400655 type->tp_name, Py_TYPE(ob)->tp_name);
656 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000657 }
Benjamin Peterson104b9e02015-02-05 22:29:14 -0500658
659 base = (PyTypeObject*)ob;
660 if (PyType_IsSubtype(base, type) ||
661 /* In case of reentering here again through a custom mro()
662 the above check is not enough since it relies on
663 base->tp_mro which would gonna be updated inside
664 mro_internal only upon returning from the mro().
665
666 However, base->tp_base has already been assigned (see
667 below), which in turn may cause an inheritance cycle
668 through tp_base chain. And this is definitely
669 not what you want to ever happen. */
670 (base->tp_mro != NULL && type_is_subtype_base_chain(base, type))) {
671
Benjamin Peterson3471bb62012-04-01 18:48:40 -0400672 PyErr_SetString(PyExc_TypeError,
673 "a __bases__ item causes an inheritance cycle");
674 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000675 }
676 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000677
Benjamin Peterson104b9e02015-02-05 22:29:14 -0500678 new_base = best_base(new_bases);
679 if (new_base == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000680 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000681
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000682 if (!compatible_for_assignment(type->tp_base, new_base, "__bases__"))
683 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000684
Benjamin Peterson104b9e02015-02-05 22:29:14 -0500685 Py_INCREF(new_bases);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000686 Py_INCREF(new_base);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000687
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000688 old_bases = type->tp_bases;
689 old_base = type->tp_base;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000690
Benjamin Peterson104b9e02015-02-05 22:29:14 -0500691 type->tp_bases = new_bases;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000692 type->tp_base = new_base;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000693
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000694 temp = PyList_New(0);
Benjamin Peterson104b9e02015-02-05 22:29:14 -0500695 if (temp == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000696 goto bail;
Benjamin Peterson104b9e02015-02-05 22:29:14 -0500697 if (mro_hierarchy(type, temp) < 0)
698 goto undo;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000699 Py_DECREF(temp);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000700
Benjamin Peterson104b9e02015-02-05 22:29:14 -0500701 /* Take no action in case if type->tp_bases has been replaced
702 through reentrance. */
703 if (type->tp_bases == new_bases) {
704 /* any base that was in __bases__ but now isn't, we
705 need to remove |type| from its tp_subclasses.
706 conversely, any class now in __bases__ that wasn't
707 needs to have |type| added to its subclasses. */
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000708
Benjamin Peterson104b9e02015-02-05 22:29:14 -0500709 /* for now, sod that: just remove from all old_bases,
710 add to all new_bases */
711 remove_all_subclasses(type, old_bases);
712 res = add_all_subclasses(type, new_bases);
713 update_all_slots(type);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000714 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000715
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000716 Py_DECREF(old_bases);
717 Py_DECREF(old_base);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000718
Benjamin Peterson104b9e02015-02-05 22:29:14 -0500719 return res;
720
721 undo:
722 for (i = PyList_GET_SIZE(temp) - 1; i >= 0; i--) {
723 PyTypeObject *cls;
724 PyObject *new_mro, *old_mro = NULL;
725
726 PyArg_UnpackTuple(PyList_GET_ITEM(temp, i),
727 "", 2, 3, &cls, &new_mro, &old_mro);
728 /* Do not rollback if cls has a newer version of MRO. */
729 if (cls->tp_mro == new_mro) {
730 Py_XINCREF(old_mro);
731 cls->tp_mro = old_mro;
732 Py_DECREF(new_mro);
733 }
734 }
735 Py_DECREF(temp);
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000736
737 bail:
Benjamin Peterson104b9e02015-02-05 22:29:14 -0500738 if (type->tp_bases == new_bases) {
739 assert(type->tp_base == new_base);
Michael W. Hudsone723e452003-08-07 14:58:10 +0000740
Benjamin Peterson104b9e02015-02-05 22:29:14 -0500741 type->tp_bases = old_bases;
742 type->tp_base = old_base;
743
744 Py_DECREF(new_bases);
745 Py_DECREF(new_base);
746 }
747 else {
748 Py_DECREF(old_bases);
749 Py_DECREF(old_base);
750 }
Tim Petersea7f75d2002-12-07 21:39:16 +0000751
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000752 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000753}
754
755static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000756type_dict(PyTypeObject *type, void *context)
757{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000758 if (type->tp_dict == NULL) {
759 Py_INCREF(Py_None);
760 return Py_None;
761 }
762 return PyDictProxy_New(type->tp_dict);
Guido van Rossum29ca26e1995-01-07 11:58:15 +0000763}
764
Tim Peters24008312002-03-17 18:56:20 +0000765static PyObject *
766type_get_doc(PyTypeObject *type, void *context)
767{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000768 PyObject *result;
Larry Hastings5c661892014-01-24 06:17:25 -0800769 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE) && type->tp_doc != NULL) {
Larry Hastings2623c8c2014-02-08 22:15:29 -0800770 return _PyType_GetDocFromInternalDoc(type->tp_name, type->tp_doc);
Larry Hastings5c661892014-01-24 06:17:25 -0800771 }
Victor Stinner3c1e4812012-03-26 22:10:51 +0200772 result = _PyDict_GetItemId(type->tp_dict, &PyId___doc__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000773 if (result == NULL) {
774 result = Py_None;
775 Py_INCREF(result);
776 }
777 else if (Py_TYPE(result)->tp_descr_get) {
778 result = Py_TYPE(result)->tp_descr_get(result, NULL,
779 (PyObject *)type);
780 }
781 else {
782 Py_INCREF(result);
783 }
784 return result;
Tim Peters24008312002-03-17 18:56:20 +0000785}
786
Larry Hastings5c661892014-01-24 06:17:25 -0800787static PyObject *
788type_get_text_signature(PyTypeObject *type, void *context)
789{
Larry Hastings2623c8c2014-02-08 22:15:29 -0800790 return _PyType_GetTextSignatureFromInternalDoc(type->tp_name, type->tp_doc);
Larry Hastings5c661892014-01-24 06:17:25 -0800791}
792
Benjamin Peterson01fc6cd2011-08-17 12:03:47 -0500793static int
794type_set_doc(PyTypeObject *type, PyObject *value, void *context)
795{
796 if (!check_set_special_type_attr(type, value, "__doc__"))
797 return -1;
798 PyType_Modified(type);
Victor Stinner3c1e4812012-03-26 22:10:51 +0200799 return _PyDict_SetItemId(type->tp_dict, &PyId___doc__, value);
Benjamin Peterson01fc6cd2011-08-17 12:03:47 -0500800}
801
Antoine Pitrouec569b72008-08-26 22:40:48 +0000802static PyObject *
803type___instancecheck__(PyObject *type, PyObject *inst)
804{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000805 switch (_PyObject_RealIsInstance(inst, type)) {
806 case -1:
807 return NULL;
808 case 0:
809 Py_RETURN_FALSE;
810 default:
811 Py_RETURN_TRUE;
812 }
Antoine Pitrouec569b72008-08-26 22:40:48 +0000813}
814
815
816static PyObject *
Antoine Pitrouec569b72008-08-26 22:40:48 +0000817type___subclasscheck__(PyObject *type, PyObject *inst)
818{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000819 switch (_PyObject_RealIsSubclass(inst, type)) {
820 case -1:
821 return NULL;
822 case 0:
823 Py_RETURN_FALSE;
824 default:
825 Py_RETURN_TRUE;
826 }
Antoine Pitrouec569b72008-08-26 22:40:48 +0000827}
828
Antoine Pitrouec569b72008-08-26 22:40:48 +0000829
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000830static PyGetSetDef type_getsets[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000831 {"__name__", (getter)type_name, (setter)type_set_name, NULL},
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100832 {"__qualname__", (getter)type_qualname, (setter)type_set_qualname, NULL},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000833 {"__bases__", (getter)type_get_bases, (setter)type_set_bases, NULL},
834 {"__module__", (getter)type_module, (setter)type_set_module, NULL},
835 {"__abstractmethods__", (getter)type_abstractmethods,
836 (setter)type_set_abstractmethods, NULL},
837 {"__dict__", (getter)type_dict, NULL, NULL},
Benjamin Peterson01fc6cd2011-08-17 12:03:47 -0500838 {"__doc__", (getter)type_get_doc, (setter)type_set_doc, NULL},
Larry Hastings5c661892014-01-24 06:17:25 -0800839 {"__text_signature__", (getter)type_get_text_signature, NULL, NULL},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000840 {0}
Tim Peters6d6c1a32001-08-02 04:15:00 +0000841};
842
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000843static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000844type_repr(PyTypeObject *type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000845{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000846 PyObject *mod, *name, *rtn;
Guido van Rossumc3542212001-08-16 09:18:56 +0000847
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000848 mod = type_module(type, NULL);
849 if (mod == NULL)
850 PyErr_Clear();
851 else if (!PyUnicode_Check(mod)) {
852 Py_DECREF(mod);
853 mod = NULL;
854 }
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100855 name = type_qualname(type, NULL);
Christian Heimesa0e7e412012-09-10 03:00:14 +0200856 if (name == NULL) {
857 Py_XDECREF(mod);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000858 return NULL;
Christian Heimesa0e7e412012-09-10 03:00:14 +0200859 }
Barry Warsaw7ce36942001-08-24 18:34:26 +0000860
Victor Stinnerbd303c12013-11-07 23:07:29 +0100861 if (mod != NULL && _PyUnicode_CompareWithId(mod, &PyId_builtins))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000862 rtn = PyUnicode_FromFormat("<class '%U.%U'>", mod, name);
863 else
864 rtn = PyUnicode_FromFormat("<class '%s'>", type->tp_name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000865
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000866 Py_XDECREF(mod);
867 Py_DECREF(name);
868 return rtn;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000869}
870
Tim Peters6d6c1a32001-08-02 04:15:00 +0000871static PyObject *
872type_call(PyTypeObject *type, PyObject *args, PyObject *kwds)
873{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000874 PyObject *obj;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000875
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000876 if (type->tp_new == NULL) {
877 PyErr_Format(PyExc_TypeError,
878 "cannot create '%.100s' instances",
879 type->tp_name);
880 return NULL;
881 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000882
Victor Stinner33824f62013-08-26 14:05:19 +0200883#ifdef Py_DEBUG
884 /* type_call() must not be called with an exception set,
885 because it may clear it (directly or indirectly) and so the
Martin Panter9955a372015-10-07 10:26:23 +0000886 caller loses its exception */
Victor Stinner33824f62013-08-26 14:05:19 +0200887 assert(!PyErr_Occurred());
888#endif
889
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000890 obj = type->tp_new(type, args, kwds);
891 if (obj != NULL) {
892 /* Ugly exception: when the call was type(something),
893 don't call tp_init on the result. */
894 if (type == &PyType_Type &&
895 PyTuple_Check(args) && PyTuple_GET_SIZE(args) == 1 &&
896 (kwds == NULL ||
897 (PyDict_Check(kwds) && PyDict_Size(kwds) == 0)))
898 return obj;
899 /* If the returned object is not an instance of type,
900 it won't be initialized. */
901 if (!PyType_IsSubtype(Py_TYPE(obj), type))
902 return obj;
903 type = Py_TYPE(obj);
Victor Stinner3997cfd2013-07-16 22:51:21 +0200904 if (type->tp_init != NULL) {
905 int res = type->tp_init(obj, args, kwds);
906 if (res < 0) {
907 Py_DECREF(obj);
908 obj = NULL;
909 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000910 }
911 }
912 return obj;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000913}
914
915PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000916PyType_GenericAlloc(PyTypeObject *type, Py_ssize_t nitems)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000917{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000918 PyObject *obj;
919 const size_t size = _PyObject_VAR_SIZE(type, nitems+1);
920 /* note that we need to add one, for the sentinel */
Tim Peters406fe3b2001-10-06 19:04:01 +0000921
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000922 if (PyType_IS_GC(type))
923 obj = _PyObject_GC_Malloc(size);
924 else
925 obj = (PyObject *)PyObject_MALLOC(size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000926
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000927 if (obj == NULL)
928 return PyErr_NoMemory();
Tim Peters406fe3b2001-10-06 19:04:01 +0000929
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000930 memset(obj, '\0', size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000931
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000932 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
933 Py_INCREF(type);
Tim Peters406fe3b2001-10-06 19:04:01 +0000934
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000935 if (type->tp_itemsize == 0)
Christian Heimesd3afe782013-12-04 09:27:47 +0100936 (void)PyObject_INIT(obj, type);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000937 else
938 (void) PyObject_INIT_VAR((PyVarObject *)obj, type, nitems);
Tim Peters406fe3b2001-10-06 19:04:01 +0000939
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000940 if (PyType_IS_GC(type))
941 _PyObject_GC_TRACK(obj);
942 return obj;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000943}
944
945PyObject *
946PyType_GenericNew(PyTypeObject *type, PyObject *args, PyObject *kwds)
947{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000948 return type->tp_alloc(type, 0);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000949}
950
Guido van Rossum9475a232001-10-05 20:51:39 +0000951/* Helpers for subtyping */
952
953static int
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000954traverse_slots(PyTypeObject *type, PyObject *self, visitproc visit, void *arg)
955{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000956 Py_ssize_t i, n;
957 PyMemberDef *mp;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000958
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000959 n = Py_SIZE(type);
960 mp = PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type);
961 for (i = 0; i < n; i++, mp++) {
962 if (mp->type == T_OBJECT_EX) {
963 char *addr = (char *)self + mp->offset;
964 PyObject *obj = *(PyObject **)addr;
965 if (obj != NULL) {
966 int err = visit(obj, arg);
967 if (err)
968 return err;
969 }
970 }
971 }
972 return 0;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000973}
974
975static int
Guido van Rossum9475a232001-10-05 20:51:39 +0000976subtype_traverse(PyObject *self, visitproc visit, void *arg)
977{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000978 PyTypeObject *type, *base;
979 traverseproc basetraverse;
Guido van Rossum9475a232001-10-05 20:51:39 +0000980
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000981 /* Find the nearest base with a different tp_traverse,
982 and traverse slots while we're at it */
983 type = Py_TYPE(self);
984 base = type;
985 while ((basetraverse = base->tp_traverse) == subtype_traverse) {
986 if (Py_SIZE(base)) {
987 int err = traverse_slots(base, self, visit, arg);
988 if (err)
989 return err;
990 }
991 base = base->tp_base;
992 assert(base);
993 }
Guido van Rossum9475a232001-10-05 20:51:39 +0000994
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000995 if (type->tp_dictoffset != base->tp_dictoffset) {
996 PyObject **dictptr = _PyObject_GetDictPtr(self);
997 if (dictptr && *dictptr)
998 Py_VISIT(*dictptr);
999 }
Guido van Rossum9475a232001-10-05 20:51:39 +00001000
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001001 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
1002 /* For a heaptype, the instances count as references
1003 to the type. Traverse the type so the collector
1004 can find cycles involving this link. */
1005 Py_VISIT(type);
Guido van Rossuma3862092002-06-10 15:24:42 +00001006
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001007 if (basetraverse)
1008 return basetraverse(self, visit, arg);
1009 return 0;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001010}
1011
1012static void
1013clear_slots(PyTypeObject *type, PyObject *self)
1014{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001015 Py_ssize_t i, n;
1016 PyMemberDef *mp;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001017
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001018 n = Py_SIZE(type);
1019 mp = PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type);
1020 for (i = 0; i < n; i++, mp++) {
1021 if (mp->type == T_OBJECT_EX && !(mp->flags & READONLY)) {
1022 char *addr = (char *)self + mp->offset;
1023 PyObject *obj = *(PyObject **)addr;
1024 if (obj != NULL) {
1025 *(PyObject **)addr = NULL;
1026 Py_DECREF(obj);
1027 }
1028 }
1029 }
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001030}
1031
1032static int
1033subtype_clear(PyObject *self)
1034{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001035 PyTypeObject *type, *base;
1036 inquiry baseclear;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001037
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001038 /* Find the nearest base with a different tp_clear
1039 and clear slots while we're at it */
1040 type = Py_TYPE(self);
1041 base = type;
1042 while ((baseclear = base->tp_clear) == subtype_clear) {
1043 if (Py_SIZE(base))
1044 clear_slots(base, self);
1045 base = base->tp_base;
1046 assert(base);
1047 }
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001048
Benjamin Peterson52c42432012-03-07 18:41:11 -06001049 /* Clear the instance dict (if any), to break cycles involving only
1050 __dict__ slots (as in the case 'self.__dict__ is self'). */
1051 if (type->tp_dictoffset != base->tp_dictoffset) {
1052 PyObject **dictptr = _PyObject_GetDictPtr(self);
1053 if (dictptr && *dictptr)
1054 Py_CLEAR(*dictptr);
1055 }
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001056
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001057 if (baseclear)
1058 return baseclear(self);
1059 return 0;
Guido van Rossum9475a232001-10-05 20:51:39 +00001060}
Tim Peters6d6c1a32001-08-02 04:15:00 +00001061
1062static void
1063subtype_dealloc(PyObject *self)
1064{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001065 PyTypeObject *type, *base;
1066 destructor basedealloc;
Antoine Pitrou56cd62c2012-09-06 00:59:49 +02001067 PyThreadState *tstate = PyThreadState_GET();
Antoine Pitrou796564c2013-07-30 19:59:21 +02001068 int has_finalizer;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001069
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001070 /* Extract the type; we expect it to be a heap type */
1071 type = Py_TYPE(self);
1072 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001073
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001074 /* Test whether the type has GC exactly once */
Guido van Rossum22b13872002-08-06 21:41:44 +00001075
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001076 if (!PyType_IS_GC(type)) {
1077 /* It's really rare to find a dynamic type that doesn't have
1078 GC; it can only happen when deriving from 'object' and not
1079 adding any slots or instance variables. This allows
1080 certain simplifications: there's no need to call
1081 clear_slots(), or DECREF the dict, or clear weakrefs. */
Guido van Rossum22b13872002-08-06 21:41:44 +00001082
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001083 /* Maybe call finalizer; exit early if resurrected */
Antoine Pitrou796564c2013-07-30 19:59:21 +02001084 if (type->tp_finalize) {
1085 if (PyObject_CallFinalizerFromDealloc(self) < 0)
1086 return;
1087 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001088 if (type->tp_del) {
1089 type->tp_del(self);
1090 if (self->ob_refcnt > 0)
1091 return;
1092 }
Guido van Rossum22b13872002-08-06 21:41:44 +00001093
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001094 /* Find the nearest base with a different tp_dealloc */
1095 base = type;
1096 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
1097 assert(Py_SIZE(base) == 0);
1098 base = base->tp_base;
1099 assert(base);
1100 }
Guido van Rossum22b13872002-08-06 21:41:44 +00001101
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001102 /* Extract the type again; tp_del may have changed it */
1103 type = Py_TYPE(self);
Benjamin Peterson193152c2009-04-25 01:08:45 +00001104
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001105 /* Call the base tp_dealloc() */
1106 assert(basedealloc);
1107 basedealloc(self);
Guido van Rossum22b13872002-08-06 21:41:44 +00001108
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001109 /* Can't reference self beyond this point */
1110 Py_DECREF(type);
Guido van Rossum22b13872002-08-06 21:41:44 +00001111
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001112 /* Done */
1113 return;
1114 }
Guido van Rossum22b13872002-08-06 21:41:44 +00001115
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001116 /* We get here only if the type has GC */
Guido van Rossum22b13872002-08-06 21:41:44 +00001117
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001118 /* UnTrack and re-Track around the trashcan macro, alas */
1119 /* See explanation at end of function for full disclosure */
1120 PyObject_GC_UnTrack(self);
1121 ++_PyTrash_delete_nesting;
Antoine Pitrou56cd62c2012-09-06 00:59:49 +02001122 ++ tstate->trash_delete_nesting;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001123 Py_TRASHCAN_SAFE_BEGIN(self);
1124 --_PyTrash_delete_nesting;
Antoine Pitrou56cd62c2012-09-06 00:59:49 +02001125 -- tstate->trash_delete_nesting;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001126 /* DO NOT restore GC tracking at this point. weakref callbacks
1127 * (if any, and whether directly here or indirectly in something we
1128 * call) may trigger GC, and if self is tracked at that point, it
1129 * will look like trash to GC and GC will try to delete self again.
1130 */
Guido van Rossum22b13872002-08-06 21:41:44 +00001131
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001132 /* Find the nearest base with a different tp_dealloc */
1133 base = type;
Brett Cannonb94767f2011-02-22 20:15:44 +00001134 while ((/*basedealloc =*/ base->tp_dealloc) == subtype_dealloc) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001135 base = base->tp_base;
1136 assert(base);
1137 }
Guido van Rossum14227b42001-12-06 02:35:58 +00001138
Antoine Pitrou796564c2013-07-30 19:59:21 +02001139 has_finalizer = type->tp_finalize || type->tp_del;
Guido van Rossum59195fd2003-06-13 20:54:40 +00001140
Antoine Pitrou796564c2013-07-30 19:59:21 +02001141 /* Maybe call finalizer; exit early if resurrected */
1142 if (has_finalizer)
1143 _PyObject_GC_TRACK(self);
1144
1145 if (type->tp_finalize) {
1146 if (PyObject_CallFinalizerFromDealloc(self) < 0) {
1147 /* Resurrected */
1148 goto endlabel;
1149 }
1150 }
1151 /* If we added a weaklist, we clear it. Do this *before* calling
1152 tp_del, clearing slots, or clearing the instance dict. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001153 if (type->tp_weaklistoffset && !base->tp_weaklistoffset)
1154 PyObject_ClearWeakRefs(self);
Guido van Rossum1987c662003-05-29 14:29:23 +00001155
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001156 if (type->tp_del) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001157 type->tp_del(self);
Antoine Pitrou796564c2013-07-30 19:59:21 +02001158 if (self->ob_refcnt > 0) {
1159 /* Resurrected */
1160 goto endlabel;
1161 }
1162 }
1163 if (has_finalizer) {
1164 _PyObject_GC_UNTRACK(self);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001165 /* New weakrefs could be created during the finalizer call.
Antoine Pitrou796564c2013-07-30 19:59:21 +02001166 If this occurs, clear them out without calling their
1167 finalizers since they might rely on part of the object
1168 being finalized that has already been destroyed. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001169 if (type->tp_weaklistoffset && !base->tp_weaklistoffset) {
1170 /* Modeled after GET_WEAKREFS_LISTPTR() */
1171 PyWeakReference **list = (PyWeakReference **) \
1172 PyObject_GET_WEAKREFS_LISTPTR(self);
1173 while (*list)
1174 _PyWeakref_ClearRef(*list);
1175 }
1176 }
Guido van Rossum1987c662003-05-29 14:29:23 +00001177
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001178 /* Clear slots up to the nearest base with a different tp_dealloc */
1179 base = type;
1180 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
1181 if (Py_SIZE(base))
1182 clear_slots(base, self);
1183 base = base->tp_base;
1184 assert(base);
1185 }
Guido van Rossum59195fd2003-06-13 20:54:40 +00001186
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001187 /* If we added a dict, DECREF it */
1188 if (type->tp_dictoffset && !base->tp_dictoffset) {
1189 PyObject **dictptr = _PyObject_GetDictPtr(self);
1190 if (dictptr != NULL) {
1191 PyObject *dict = *dictptr;
1192 if (dict != NULL) {
1193 Py_DECREF(dict);
1194 *dictptr = NULL;
1195 }
1196 }
1197 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001198
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001199 /* Extract the type again; tp_del may have changed it */
1200 type = Py_TYPE(self);
Benjamin Peterson193152c2009-04-25 01:08:45 +00001201
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001202 /* Call the base tp_dealloc(); first retrack self if
1203 * basedealloc knows about gc.
1204 */
1205 if (PyType_IS_GC(base))
1206 _PyObject_GC_TRACK(self);
1207 assert(basedealloc);
1208 basedealloc(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001209
Benjamin Peterson9d4cbcc2015-01-30 13:33:42 -05001210 /* Can't reference self beyond this point. It's possible tp_del switched
1211 our type from a HEAPTYPE to a non-HEAPTYPE, so be careful about
1212 reference counting. */
1213 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
1214 Py_DECREF(type);
Guido van Rossum22b13872002-08-06 21:41:44 +00001215
Guido van Rossum0906e072002-08-07 20:42:09 +00001216 endlabel:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001217 ++_PyTrash_delete_nesting;
Antoine Pitrou56cd62c2012-09-06 00:59:49 +02001218 ++ tstate->trash_delete_nesting;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001219 Py_TRASHCAN_SAFE_END(self);
1220 --_PyTrash_delete_nesting;
Antoine Pitrou56cd62c2012-09-06 00:59:49 +02001221 -- tstate->trash_delete_nesting;
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001222
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001223 /* Explanation of the weirdness around the trashcan macros:
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001224
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001225 Q. What do the trashcan macros do?
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001226
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001227 A. Read the comment titled "Trashcan mechanism" in object.h.
1228 For one, this explains why there must be a call to GC-untrack
1229 before the trashcan begin macro. Without understanding the
1230 trashcan code, the answers to the following questions don't make
1231 sense.
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001232
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001233 Q. Why do we GC-untrack before the trashcan and then immediately
1234 GC-track again afterward?
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001235
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001236 A. In the case that the base class is GC-aware, the base class
1237 probably GC-untracks the object. If it does that using the
1238 UNTRACK macro, this will crash when the object is already
1239 untracked. Because we don't know what the base class does, the
1240 only safe thing is to make sure the object is tracked when we
1241 call the base class dealloc. But... The trashcan begin macro
1242 requires that the object is *untracked* before it is called. So
1243 the dance becomes:
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001244
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001245 GC untrack
1246 trashcan begin
1247 GC track
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001248
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001249 Q. Why did the last question say "immediately GC-track again"?
1250 It's nowhere near immediately.
Tim Petersf7f9e992003-11-13 21:59:32 +00001251
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001252 A. Because the code *used* to re-track immediately. Bad Idea.
1253 self has a refcount of 0, and if gc ever gets its hands on it
1254 (which can happen if any weakref callback gets invoked), it
1255 looks like trash to gc too, and gc also tries to delete self
Ezio Melotti13925002011-03-16 11:05:33 +02001256 then. But we're already deleting self. Double deallocation is
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001257 a subtle disaster.
Tim Petersf7f9e992003-11-13 21:59:32 +00001258
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001259 Q. Why the bizarre (net-zero) manipulation of
1260 _PyTrash_delete_nesting around the trashcan macros?
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001261
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001262 A. Some base classes (e.g. list) also use the trashcan mechanism.
1263 The following scenario used to be possible:
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001264
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001265 - suppose the trashcan level is one below the trashcan limit
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001266
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001267 - subtype_dealloc() is called
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001268
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001269 - the trashcan limit is not yet reached, so the trashcan level
1270 is incremented and the code between trashcan begin and end is
1271 executed
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001272
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001273 - this destroys much of the object's contents, including its
1274 slots and __dict__
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001275
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001276 - basedealloc() is called; this is really list_dealloc(), or
1277 some other type which also uses the trashcan macros
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001278
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001279 - the trashcan limit is now reached, so the object is put on the
1280 trashcan's to-be-deleted-later list
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001281
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001282 - basedealloc() returns
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001283
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001284 - subtype_dealloc() decrefs the object's type
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001285
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001286 - subtype_dealloc() returns
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001287
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001288 - later, the trashcan code starts deleting the objects from its
1289 to-be-deleted-later list
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001290
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001291 - subtype_dealloc() is called *AGAIN* for the same object
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001292
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001293 - at the very least (if the destroyed slots and __dict__ don't
1294 cause problems) the object's type gets decref'ed a second
1295 time, which is *BAD*!!!
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001296
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001297 The remedy is to make sure that if the code between trashcan
1298 begin and end in subtype_dealloc() is called, the code between
1299 trashcan begin and end in basedealloc() will also be called.
1300 This is done by decrementing the level after passing into the
1301 trashcan block, and incrementing it just before leaving the
1302 block.
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001303
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001304 But now it's possible that a chain of objects consisting solely
1305 of objects whose deallocator is subtype_dealloc() will defeat
1306 the trashcan mechanism completely: the decremented level means
1307 that the effective level never reaches the limit. Therefore, we
1308 *increment* the level *before* entering the trashcan block, and
1309 matchingly decrement it after leaving. This means the trashcan
1310 code will trigger a little early, but that's no big deal.
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001311
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001312 Q. Are there any live examples of code in need of all this
1313 complexity?
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001314
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001315 A. Yes. See SF bug 668433 for code that crashed (when Python was
1316 compiled in debug mode) before the trashcan level manipulations
1317 were added. For more discussion, see SF patches 581742, 575073
1318 and bug 574207.
1319 */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001320}
1321
Jeremy Hylton938ace62002-07-17 16:30:39 +00001322static PyTypeObject *solid_base(PyTypeObject *type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001323
Tim Peters6d6c1a32001-08-02 04:15:00 +00001324/* type test with subclassing support */
1325
Benjamin Peterson104b9e02015-02-05 22:29:14 -05001326Py_LOCAL_INLINE(int)
1327type_is_subtype_base_chain(PyTypeObject *a, PyTypeObject *b)
1328{
1329 do {
1330 if (a == b)
1331 return 1;
1332 a = a->tp_base;
1333 } while (a != NULL);
1334
1335 return (b == &PyBaseObject_Type);
1336}
1337
Tim Peters6d6c1a32001-08-02 04:15:00 +00001338int
1339PyType_IsSubtype(PyTypeObject *a, PyTypeObject *b)
1340{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001341 PyObject *mro;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001342
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001343 mro = a->tp_mro;
1344 if (mro != NULL) {
1345 /* Deal with multiple inheritance without recursion
1346 by walking the MRO tuple */
1347 Py_ssize_t i, n;
1348 assert(PyTuple_Check(mro));
1349 n = PyTuple_GET_SIZE(mro);
1350 for (i = 0; i < n; i++) {
1351 if (PyTuple_GET_ITEM(mro, i) == (PyObject *)b)
1352 return 1;
1353 }
1354 return 0;
1355 }
Benjamin Peterson104b9e02015-02-05 22:29:14 -05001356 else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001357 /* a is not completely initilized yet; follow tp_base */
Benjamin Peterson104b9e02015-02-05 22:29:14 -05001358 return type_is_subtype_base_chain(a, b);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001359}
1360
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001361/* Internal routines to do a method lookup in the type
Guido van Rossum60718732001-08-28 17:47:51 +00001362 without looking in the instance dictionary
1363 (so we can't use PyObject_GetAttr) but still binding
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001364 it to the instance. The arguments are the object,
Guido van Rossum60718732001-08-28 17:47:51 +00001365 the method name as a C string, and the address of a
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001366 static variable used to cache the interned Python string.
1367
1368 Two variants:
1369
1370 - lookup_maybe() returns NULL without raising an exception
1371 when the _PyType_Lookup() call fails;
1372
1373 - lookup_method() always raises an exception upon errors.
Benjamin Peterson224205f2009-05-08 03:25:19 +00001374
1375 - _PyObject_LookupSpecial() exported for the benefit of other places.
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001376*/
Guido van Rossum60718732001-08-28 17:47:51 +00001377
1378static PyObject *
Benjamin Petersonce798522012-01-22 11:24:29 -05001379lookup_maybe(PyObject *self, _Py_Identifier *attrid)
Guido van Rossum60718732001-08-28 17:47:51 +00001380{
Victor Stinner3c1e4812012-03-26 22:10:51 +02001381 PyObject *res;
Guido van Rossum60718732001-08-28 17:47:51 +00001382
Victor Stinner3c1e4812012-03-26 22:10:51 +02001383 res = _PyType_LookupId(Py_TYPE(self), attrid);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001384 if (res != NULL) {
1385 descrgetfunc f;
1386 if ((f = Py_TYPE(res)->tp_descr_get) == NULL)
1387 Py_INCREF(res);
1388 else
1389 res = f(res, self, (PyObject *)(Py_TYPE(self)));
1390 }
1391 return res;
Guido van Rossum60718732001-08-28 17:47:51 +00001392}
1393
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001394static PyObject *
Benjamin Petersonce798522012-01-22 11:24:29 -05001395lookup_method(PyObject *self, _Py_Identifier *attrid)
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001396{
Benjamin Petersonce798522012-01-22 11:24:29 -05001397 PyObject *res = lookup_maybe(self, attrid);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001398 if (res == NULL && !PyErr_Occurred())
Benjamin Petersonce798522012-01-22 11:24:29 -05001399 PyErr_SetObject(PyExc_AttributeError, attrid->object);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001400 return res;
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001401}
1402
Benjamin Peterson224205f2009-05-08 03:25:19 +00001403PyObject *
Benjamin Petersonce798522012-01-22 11:24:29 -05001404_PyObject_LookupSpecial(PyObject *self, _Py_Identifier *attrid)
Benjamin Peterson224205f2009-05-08 03:25:19 +00001405{
Benjamin Petersonce798522012-01-22 11:24:29 -05001406 return lookup_maybe(self, attrid);
Benjamin Peterson224205f2009-05-08 03:25:19 +00001407}
1408
Guido van Rossum2730b132001-08-28 18:22:14 +00001409/* A variation of PyObject_CallMethod that uses lookup_method()
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001410 instead of PyObject_GetAttrString(). This uses the same convention
Guido van Rossum2730b132001-08-28 18:22:14 +00001411 as lookup_method to cache the interned name string object. */
1412
Neil Schemenauerf23473f2001-10-21 22:28:58 +00001413static PyObject *
Benjamin Petersonce798522012-01-22 11:24:29 -05001414call_method(PyObject *o, _Py_Identifier *nameid, char *format, ...)
Guido van Rossum2730b132001-08-28 18:22:14 +00001415{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001416 va_list va;
1417 PyObject *args, *func = 0, *retval;
1418 va_start(va, format);
Guido van Rossum2730b132001-08-28 18:22:14 +00001419
Benjamin Petersonce798522012-01-22 11:24:29 -05001420 func = lookup_maybe(o, nameid);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001421 if (func == NULL) {
1422 va_end(va);
1423 if (!PyErr_Occurred())
Benjamin Petersonce798522012-01-22 11:24:29 -05001424 PyErr_SetObject(PyExc_AttributeError, nameid->object);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001425 return NULL;
1426 }
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001427
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001428 if (format && *format)
1429 args = Py_VaBuildValue(format, va);
1430 else
1431 args = PyTuple_New(0);
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001432
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001433 va_end(va);
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001434
Victor Stinnerd925bd52016-08-19 17:51:49 +02001435 if (args == NULL) {
1436 Py_DECREF(func);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001437 return NULL;
Victor Stinnerd925bd52016-08-19 17:51:49 +02001438 }
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001439
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001440 assert(PyTuple_Check(args));
1441 retval = PyObject_Call(func, args, NULL);
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001442
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001443 Py_DECREF(args);
1444 Py_DECREF(func);
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001445
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001446 return retval;
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001447}
1448
1449/* Clone of call_method() that returns NotImplemented when the lookup fails. */
1450
Neil Schemenauerf23473f2001-10-21 22:28:58 +00001451static PyObject *
Benjamin Petersonce798522012-01-22 11:24:29 -05001452call_maybe(PyObject *o, _Py_Identifier *nameid, char *format, ...)
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001453{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001454 va_list va;
1455 PyObject *args, *func = 0, *retval;
1456 va_start(va, format);
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001457
Benjamin Petersonce798522012-01-22 11:24:29 -05001458 func = lookup_maybe(o, nameid);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001459 if (func == NULL) {
1460 va_end(va);
Brian Curtindfc80e32011-08-10 20:28:54 -05001461 if (!PyErr_Occurred())
1462 Py_RETURN_NOTIMPLEMENTED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001463 return NULL;
1464 }
Guido van Rossum2730b132001-08-28 18:22:14 +00001465
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001466 if (format && *format)
1467 args = Py_VaBuildValue(format, va);
1468 else
1469 args = PyTuple_New(0);
Guido van Rossum2730b132001-08-28 18:22:14 +00001470
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001471 va_end(va);
Guido van Rossum2730b132001-08-28 18:22:14 +00001472
Victor Stinner6902ddf2016-08-19 17:58:12 +02001473 if (args == NULL) {
1474 Py_DECREF(func);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001475 return NULL;
Victor Stinner6902ddf2016-08-19 17:58:12 +02001476 }
Guido van Rossum2730b132001-08-28 18:22:14 +00001477
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001478 assert(PyTuple_Check(args));
1479 retval = PyObject_Call(func, args, NULL);
Guido van Rossum2730b132001-08-28 18:22:14 +00001480
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001481 Py_DECREF(args);
1482 Py_DECREF(func);
Guido van Rossum2730b132001-08-28 18:22:14 +00001483
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001484 return retval;
Guido van Rossum2730b132001-08-28 18:22:14 +00001485}
1486
Tim Petersea7f75d2002-12-07 21:39:16 +00001487/*
Guido van Rossum1f121312002-11-14 19:49:16 +00001488 Method resolution order algorithm C3 described in
1489 "A Monotonic Superclass Linearization for Dylan",
1490 by Kim Barrett, Bob Cassel, Paul Haahr,
Tim Petersea7f75d2002-12-07 21:39:16 +00001491 David A. Moon, Keith Playford, and P. Tucker Withington.
Guido van Rossum1f121312002-11-14 19:49:16 +00001492 (OOPSLA 1996)
1493
Guido van Rossum98f33732002-11-25 21:36:54 +00001494 Some notes about the rules implied by C3:
1495
Tim Petersea7f75d2002-12-07 21:39:16 +00001496 No duplicate bases.
Guido van Rossum98f33732002-11-25 21:36:54 +00001497 It isn't legal to repeat a class in a list of base classes.
1498
1499 The next three properties are the 3 constraints in "C3".
1500
Martin Panter69332c12016-08-04 13:07:31 +00001501 Local precedence order.
Guido van Rossum98f33732002-11-25 21:36:54 +00001502 If A precedes B in C's MRO, then A will precede B in the MRO of all
1503 subclasses of C.
1504
1505 Monotonicity.
1506 The MRO of a class must be an extension without reordering of the
1507 MRO of each of its superclasses.
1508
1509 Extended Precedence Graph (EPG).
1510 Linearization is consistent if there is a path in the EPG from
1511 each class to all its successors in the linearization. See
1512 the paper for definition of EPG.
Guido van Rossum1f121312002-11-14 19:49:16 +00001513 */
1514
Tim Petersea7f75d2002-12-07 21:39:16 +00001515static int
Guido van Rossum1f121312002-11-14 19:49:16 +00001516tail_contains(PyObject *list, int whence, PyObject *o) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001517 Py_ssize_t j, size;
1518 size = PyList_GET_SIZE(list);
Guido van Rossum1f121312002-11-14 19:49:16 +00001519
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001520 for (j = whence+1; j < size; j++) {
1521 if (PyList_GET_ITEM(list, j) == o)
1522 return 1;
1523 }
1524 return 0;
Guido van Rossum1f121312002-11-14 19:49:16 +00001525}
1526
Guido van Rossum98f33732002-11-25 21:36:54 +00001527static PyObject *
1528class_name(PyObject *cls)
1529{
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001530 PyObject *name = _PyObject_GetAttrId(cls, &PyId___name__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001531 if (name == NULL) {
1532 PyErr_Clear();
1533 Py_XDECREF(name);
1534 name = PyObject_Repr(cls);
1535 }
1536 if (name == NULL)
1537 return NULL;
1538 if (!PyUnicode_Check(name)) {
1539 Py_DECREF(name);
1540 return NULL;
1541 }
1542 return name;
Guido van Rossum98f33732002-11-25 21:36:54 +00001543}
1544
1545static int
1546check_duplicates(PyObject *list)
1547{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001548 Py_ssize_t i, j, n;
1549 /* Let's use a quadratic time algorithm,
1550 assuming that the bases lists is short.
1551 */
1552 n = PyList_GET_SIZE(list);
1553 for (i = 0; i < n; i++) {
1554 PyObject *o = PyList_GET_ITEM(list, i);
1555 for (j = i + 1; j < n; j++) {
1556 if (PyList_GET_ITEM(list, j) == o) {
1557 o = class_name(o);
1558 if (o != NULL) {
1559 PyErr_Format(PyExc_TypeError,
1560 "duplicate base class %U",
1561 o);
1562 Py_DECREF(o);
1563 } else {
1564 PyErr_SetString(PyExc_TypeError,
1565 "duplicate base class");
1566 }
1567 return -1;
1568 }
1569 }
1570 }
1571 return 0;
Guido van Rossum98f33732002-11-25 21:36:54 +00001572}
1573
1574/* Raise a TypeError for an MRO order disagreement.
1575
1576 It's hard to produce a good error message. In the absence of better
1577 insight into error reporting, report the classes that were candidates
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001578 to be put next into the MRO. There is some conflict between the
Guido van Rossum98f33732002-11-25 21:36:54 +00001579 order in which they should be put in the MRO, but it's hard to
1580 diagnose what constraint can't be satisfied.
1581*/
1582
1583static void
1584set_mro_error(PyObject *to_merge, int *remain)
1585{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001586 Py_ssize_t i, n, off, to_merge_size;
1587 char buf[1000];
1588 PyObject *k, *v;
1589 PyObject *set = PyDict_New();
1590 if (!set) return;
Guido van Rossum98f33732002-11-25 21:36:54 +00001591
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001592 to_merge_size = PyList_GET_SIZE(to_merge);
1593 for (i = 0; i < to_merge_size; i++) {
1594 PyObject *L = PyList_GET_ITEM(to_merge, i);
1595 if (remain[i] < PyList_GET_SIZE(L)) {
1596 PyObject *c = PyList_GET_ITEM(L, remain[i]);
1597 if (PyDict_SetItem(set, c, Py_None) < 0) {
1598 Py_DECREF(set);
1599 return;
1600 }
1601 }
1602 }
1603 n = PyDict_Size(set);
Guido van Rossum98f33732002-11-25 21:36:54 +00001604
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001605 off = PyOS_snprintf(buf, sizeof(buf), "Cannot create a \
Raymond Hettingerf394df42003-04-06 19:13:41 +00001606consistent method resolution\norder (MRO) for bases");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001607 i = 0;
1608 while (PyDict_Next(set, &i, &k, &v) && (size_t)off < sizeof(buf)) {
1609 PyObject *name = class_name(k);
Victor Stinnere5f99f32010-05-19 01:42:46 +00001610 char *name_str;
1611 if (name != NULL) {
1612 name_str = _PyUnicode_AsString(name);
1613 if (name_str == NULL)
Victor Stinnerba644a62010-05-19 01:50:45 +00001614 name_str = "?";
Victor Stinnere5f99f32010-05-19 01:42:46 +00001615 } else
Victor Stinnerba644a62010-05-19 01:50:45 +00001616 name_str = "?";
Victor Stinnere5f99f32010-05-19 01:42:46 +00001617 off += PyOS_snprintf(buf + off, sizeof(buf) - off, " %s", name_str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001618 Py_XDECREF(name);
1619 if (--n && (size_t)(off+1) < sizeof(buf)) {
1620 buf[off++] = ',';
1621 buf[off] = '\0';
1622 }
1623 }
1624 PyErr_SetString(PyExc_TypeError, buf);
1625 Py_DECREF(set);
Guido van Rossum98f33732002-11-25 21:36:54 +00001626}
1627
Tim Petersea7f75d2002-12-07 21:39:16 +00001628static int
Benjamin Peterson104b9e02015-02-05 22:29:14 -05001629pmerge(PyObject *acc, PyObject* to_merge)
1630{
1631 int res = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001632 Py_ssize_t i, j, to_merge_size, empty_cnt;
1633 int *remain;
Tim Petersea7f75d2002-12-07 21:39:16 +00001634
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001635 to_merge_size = PyList_GET_SIZE(to_merge);
Guido van Rossum1f121312002-11-14 19:49:16 +00001636
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001637 /* remain stores an index into each sublist of to_merge.
1638 remain[i] is the index of the next base in to_merge[i]
1639 that is not included in acc.
1640 */
1641 remain = (int *)PyMem_MALLOC(SIZEOF_INT*to_merge_size);
Victor Stinnera41f0852013-07-12 00:42:14 +02001642 if (remain == NULL) {
1643 PyErr_NoMemory();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001644 return -1;
Victor Stinnera41f0852013-07-12 00:42:14 +02001645 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001646 for (i = 0; i < to_merge_size; i++)
1647 remain[i] = 0;
Guido van Rossum1f121312002-11-14 19:49:16 +00001648
1649 again:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001650 empty_cnt = 0;
1651 for (i = 0; i < to_merge_size; i++) {
1652 PyObject *candidate;
Tim Petersea7f75d2002-12-07 21:39:16 +00001653
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001654 PyObject *cur_list = PyList_GET_ITEM(to_merge, i);
Guido van Rossum1f121312002-11-14 19:49:16 +00001655
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001656 if (remain[i] >= PyList_GET_SIZE(cur_list)) {
1657 empty_cnt++;
1658 continue;
1659 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001660
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001661 /* Choose next candidate for MRO.
Guido van Rossum98f33732002-11-25 21:36:54 +00001662
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001663 The input sequences alone can determine the choice.
1664 If not, choose the class which appears in the MRO
1665 of the earliest direct superclass of the new class.
1666 */
Guido van Rossum98f33732002-11-25 21:36:54 +00001667
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001668 candidate = PyList_GET_ITEM(cur_list, remain[i]);
1669 for (j = 0; j < to_merge_size; j++) {
1670 PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
Benjamin Peterson104b9e02015-02-05 22:29:14 -05001671 if (tail_contains(j_lst, remain[j], candidate))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001672 goto skip; /* continue outer loop */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001673 }
Benjamin Peterson104b9e02015-02-05 22:29:14 -05001674 res = PyList_Append(acc, candidate);
1675 if (res < 0)
1676 goto out;
1677
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001678 for (j = 0; j < to_merge_size; j++) {
1679 PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
1680 if (remain[j] < PyList_GET_SIZE(j_lst) &&
1681 PyList_GET_ITEM(j_lst, remain[j]) == candidate) {
1682 remain[j]++;
1683 }
1684 }
1685 goto again;
1686 skip: ;
1687 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001688
Benjamin Peterson104b9e02015-02-05 22:29:14 -05001689 if (empty_cnt != to_merge_size) {
1690 set_mro_error(to_merge, remain);
1691 res = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001692 }
Benjamin Peterson104b9e02015-02-05 22:29:14 -05001693
1694 out:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001695 PyMem_FREE(remain);
Benjamin Peterson104b9e02015-02-05 22:29:14 -05001696
1697 return res;
Guido van Rossum1f121312002-11-14 19:49:16 +00001698}
1699
Tim Peters6d6c1a32001-08-02 04:15:00 +00001700static PyObject *
1701mro_implementation(PyTypeObject *type)
1702{
Benjamin Peterson104b9e02015-02-05 22:29:14 -05001703 PyObject *result = NULL;
1704 PyObject *bases;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001705 PyObject *to_merge, *bases_aslist;
Benjamin Peterson104b9e02015-02-05 22:29:14 -05001706 int res;
1707 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001708
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001709 if (type->tp_dict == NULL) {
1710 if (PyType_Ready(type) < 0)
1711 return NULL;
1712 }
Guido van Rossum63517572002-06-18 16:44:57 +00001713
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001714 /* Find a superclass linearization that honors the constraints
1715 of the explicit lists of bases and the constraints implied by
1716 each base class.
Guido van Rossum98f33732002-11-25 21:36:54 +00001717
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001718 to_merge is a list of lists, where each list is a superclass
1719 linearization implied by a base class. The last element of
1720 to_merge is the declared list of bases.
1721 */
Guido van Rossum98f33732002-11-25 21:36:54 +00001722
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001723 bases = type->tp_bases;
1724 n = PyTuple_GET_SIZE(bases);
Guido van Rossum1f121312002-11-14 19:49:16 +00001725
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001726 to_merge = PyList_New(n+1);
1727 if (to_merge == NULL)
1728 return NULL;
Guido van Rossum1f121312002-11-14 19:49:16 +00001729
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001730 for (i = 0; i < n; i++) {
Benjamin Peterson104b9e02015-02-05 22:29:14 -05001731 PyTypeObject *base;
1732 PyObject *base_mro_aslist;
1733
1734 base = (PyTypeObject *)PyTuple_GET_ITEM(bases, i);
1735 if (base->tp_mro == NULL) {
1736 PyErr_Format(PyExc_TypeError,
1737 "Cannot extend an incomplete type '%.100s'",
1738 base->tp_name);
1739 goto out;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001740 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001741
Benjamin Peterson104b9e02015-02-05 22:29:14 -05001742 base_mro_aslist = PySequence_List(base->tp_mro);
1743 if (base_mro_aslist == NULL)
1744 goto out;
1745
1746 PyList_SET_ITEM(to_merge, i, base_mro_aslist);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001747 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001748
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001749 bases_aslist = PySequence_List(bases);
Benjamin Peterson104b9e02015-02-05 22:29:14 -05001750 if (bases_aslist == NULL)
1751 goto out;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001752 /* This is just a basic sanity check. */
1753 if (check_duplicates(bases_aslist) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001754 Py_DECREF(bases_aslist);
Benjamin Peterson104b9e02015-02-05 22:29:14 -05001755 goto out;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001756 }
1757 PyList_SET_ITEM(to_merge, n, bases_aslist);
Guido van Rossum1f121312002-11-14 19:49:16 +00001758
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001759 result = Py_BuildValue("[O]", (PyObject *)type);
Benjamin Peterson104b9e02015-02-05 22:29:14 -05001760 if (result == NULL)
1761 goto out;
Guido van Rossum1f121312002-11-14 19:49:16 +00001762
Benjamin Peterson104b9e02015-02-05 22:29:14 -05001763 res = pmerge(result, to_merge);
1764 if (res < 0)
1765 Py_CLEAR(result);
1766
1767 out:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001768 Py_DECREF(to_merge);
Guido van Rossum1f121312002-11-14 19:49:16 +00001769
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001770 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001771}
1772
1773static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001774mro_external(PyObject *self)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001775{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001776 PyTypeObject *type = (PyTypeObject *)self;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001777
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001778 return mro_implementation(type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001779}
1780
1781static int
Benjamin Peterson104b9e02015-02-05 22:29:14 -05001782mro_check(PyTypeObject *type, PyObject *mro)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001783{
Benjamin Peterson104b9e02015-02-05 22:29:14 -05001784 PyTypeObject *solid;
1785 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001786
Benjamin Peterson104b9e02015-02-05 22:29:14 -05001787 solid = solid_base(type);
1788
1789 n = PyTuple_GET_SIZE(mro);
1790 for (i = 0; i < n; i++) {
1791 PyTypeObject *base;
1792 PyObject *tmp;
1793
1794 tmp = PyTuple_GET_ITEM(mro, i);
1795 if (!PyType_Check(tmp)) {
1796 PyErr_Format(
1797 PyExc_TypeError,
1798 "mro() returned a non-class ('%.500s')",
1799 Py_TYPE(tmp)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001800 return -1;
Benjamin Peterson104b9e02015-02-05 22:29:14 -05001801 }
Armin Rigo037d1e02005-12-29 17:07:39 +00001802
Benjamin Peterson104b9e02015-02-05 22:29:14 -05001803 base = (PyTypeObject*)tmp;
1804 if (!PyType_IsSubtype(solid, solid_base(base))) {
1805 PyErr_Format(
1806 PyExc_TypeError,
1807 "mro() returned base with unsuitable layout ('%.500s')",
1808 base->tp_name);
1809 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001810 }
1811 }
Benjamin Peterson104b9e02015-02-05 22:29:14 -05001812
1813 return 0;
1814}
1815
1816/* Lookups an mcls.mro method, invokes it and checks the result (if needed,
1817 in case of a custom mro() implementation).
1818
1819 Keep in mind that during execution of this function type->tp_mro
1820 can be replaced due to possible reentrance (for example,
1821 through type_set_bases):
1822
1823 - when looking up the mcls.mro attribute (it could be
1824 a user-provided descriptor);
1825
1826 - from inside a custom mro() itself;
1827
1828 - through a finalizer of the return value of mro().
1829*/
1830static PyObject *
1831mro_invoke(PyTypeObject *type)
1832{
1833 PyObject *mro_result;
1834 PyObject *new_mro;
1835 int custom = (Py_TYPE(type) != &PyType_Type);
1836
1837 if (custom) {
1838 _Py_IDENTIFIER(mro);
1839 PyObject *mro_meth = lookup_method((PyObject *)type, &PyId_mro);
1840 if (mro_meth == NULL)
1841 return NULL;
1842 mro_result = PyObject_CallObject(mro_meth, NULL);
1843 Py_DECREF(mro_meth);
1844 }
1845 else {
1846 mro_result = mro_implementation(type);
1847 }
1848 if (mro_result == NULL)
1849 return NULL;
1850
1851 new_mro = PySequence_Tuple(mro_result);
1852 Py_DECREF(mro_result);
1853 if (new_mro == NULL)
1854 return NULL;
1855
1856 if (custom && mro_check(type, new_mro) < 0) {
1857 Py_DECREF(new_mro);
1858 return NULL;
1859 }
1860
1861 return new_mro;
1862}
1863
1864/* Calculates and assigns a new MRO to type->tp_mro.
1865 Return values and invariants:
1866
1867 - Returns 1 if a new MRO value has been set to type->tp_mro due to
1868 this call of mro_internal (no tricky reentrancy and no errors).
1869
1870 In case if p_old_mro argument is not NULL, a previous value
1871 of type->tp_mro is put there, and the ownership of this
1872 reference is transferred to a caller.
1873 Otherwise, the previous value (if any) is decref'ed.
1874
1875 - Returns 0 in case when type->tp_mro gets changed because of
1876 reentering here through a custom mro() (see a comment to mro_invoke).
1877
1878 In this case, a refcount of an old type->tp_mro is adjusted
1879 somewhere deeper in the call stack (by the innermost mro_internal
1880 or its caller) and may become zero upon returning from here.
1881 This also implies that the whole hierarchy of subclasses of the type
1882 has seen the new value and updated their MRO accordingly.
1883
1884 - Returns -1 in case of an error.
1885*/
1886static int
1887mro_internal(PyTypeObject *type, PyObject **p_old_mro)
1888{
1889 PyObject *new_mro, *old_mro;
1890 int reent;
1891
1892 /* Keep a reference to be able to do a reentrancy check below.
1893 Don't let old_mro be GC'ed and its address be reused for
1894 another object, like (suddenly!) a new tp_mro. */
1895 old_mro = type->tp_mro;
1896 Py_XINCREF(old_mro);
1897 new_mro = mro_invoke(type); /* might cause reentrance */
1898 reent = (type->tp_mro != old_mro);
1899 Py_XDECREF(old_mro);
1900 if (new_mro == NULL)
1901 return -1;
1902
1903 if (reent) {
1904 Py_DECREF(new_mro);
1905 return 0;
1906 }
1907
1908 type->tp_mro = new_mro;
Christian Heimesa62da1d2008-01-12 19:39:10 +00001909
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001910 type_mro_modified(type, type->tp_mro);
Florent Xiclunaaa6c1d22011-12-12 18:54:29 +01001911 /* corner case: the super class might have been hidden
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001912 from the custom MRO */
1913 type_mro_modified(type, type->tp_bases);
Christian Heimesa62da1d2008-01-12 19:39:10 +00001914
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001915 PyType_Modified(type);
Christian Heimesa62da1d2008-01-12 19:39:10 +00001916
Benjamin Peterson104b9e02015-02-05 22:29:14 -05001917 if (p_old_mro != NULL)
1918 *p_old_mro = old_mro; /* transfer the ownership */
1919 else
1920 Py_XDECREF(old_mro);
1921
1922 return 1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001923}
1924
1925
1926/* Calculate the best base amongst multiple base classes.
1927 This is the first one that's on the path to the "solid base". */
1928
1929static PyTypeObject *
1930best_base(PyObject *bases)
1931{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001932 Py_ssize_t i, n;
1933 PyTypeObject *base, *winner, *candidate, *base_i;
1934 PyObject *base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001935
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001936 assert(PyTuple_Check(bases));
1937 n = PyTuple_GET_SIZE(bases);
1938 assert(n > 0);
1939 base = NULL;
1940 winner = NULL;
1941 for (i = 0; i < n; i++) {
1942 base_proto = PyTuple_GET_ITEM(bases, i);
1943 if (!PyType_Check(base_proto)) {
1944 PyErr_SetString(
1945 PyExc_TypeError,
1946 "bases must be types");
1947 return NULL;
1948 }
1949 base_i = (PyTypeObject *)base_proto;
1950 if (base_i->tp_dict == NULL) {
1951 if (PyType_Ready(base_i) < 0)
1952 return NULL;
1953 }
Benjamin Petersonbd6c41a2015-10-06 19:36:54 -07001954 if (!PyType_HasFeature(base_i, Py_TPFLAGS_BASETYPE)) {
1955 PyErr_Format(PyExc_TypeError,
1956 "type '%.100s' is not an acceptable base type",
1957 base_i->tp_name);
1958 return NULL;
1959 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001960 candidate = solid_base(base_i);
1961 if (winner == NULL) {
1962 winner = candidate;
1963 base = base_i;
1964 }
1965 else if (PyType_IsSubtype(winner, candidate))
1966 ;
1967 else if (PyType_IsSubtype(candidate, winner)) {
1968 winner = candidate;
1969 base = base_i;
1970 }
1971 else {
1972 PyErr_SetString(
1973 PyExc_TypeError,
1974 "multiple bases have "
1975 "instance lay-out conflict");
1976 return NULL;
1977 }
1978 }
Florent Xiclunaaa6c1d22011-12-12 18:54:29 +01001979 assert (base != NULL);
1980
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001981 return base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001982}
1983
1984static int
1985extra_ivars(PyTypeObject *type, PyTypeObject *base)
1986{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001987 size_t t_size = type->tp_basicsize;
1988 size_t b_size = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001989
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001990 assert(t_size >= b_size); /* Else type smaller than base! */
1991 if (type->tp_itemsize || base->tp_itemsize) {
1992 /* If itemsize is involved, stricter rules */
1993 return t_size != b_size ||
1994 type->tp_itemsize != base->tp_itemsize;
1995 }
1996 if (type->tp_weaklistoffset && base->tp_weaklistoffset == 0 &&
1997 type->tp_weaklistoffset + sizeof(PyObject *) == t_size &&
1998 type->tp_flags & Py_TPFLAGS_HEAPTYPE)
1999 t_size -= sizeof(PyObject *);
2000 if (type->tp_dictoffset && base->tp_dictoffset == 0 &&
2001 type->tp_dictoffset + sizeof(PyObject *) == t_size &&
2002 type->tp_flags & Py_TPFLAGS_HEAPTYPE)
2003 t_size -= sizeof(PyObject *);
Guido van Rossum9676b222001-08-17 20:32:36 +00002004
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002005 return t_size != b_size;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002006}
2007
2008static PyTypeObject *
2009solid_base(PyTypeObject *type)
2010{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002011 PyTypeObject *base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002012
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002013 if (type->tp_base)
2014 base = solid_base(type->tp_base);
2015 else
2016 base = &PyBaseObject_Type;
2017 if (extra_ivars(type, base))
2018 return type;
2019 else
2020 return base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002021}
2022
Jeremy Hylton938ace62002-07-17 16:30:39 +00002023static void object_dealloc(PyObject *);
2024static int object_init(PyObject *, PyObject *, PyObject *);
2025static int update_slot(PyTypeObject *, PyObject *);
2026static void fixup_slot_dispatchers(PyTypeObject *);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002027
Guido van Rossum360e4b82007-05-14 22:51:27 +00002028/*
2029 * Helpers for __dict__ descriptor. We don't want to expose the dicts
2030 * inherited from various builtin types. The builtin base usually provides
2031 * its own __dict__ descriptor, so we use that when we can.
2032 */
2033static PyTypeObject *
2034get_builtin_base_with_dict(PyTypeObject *type)
2035{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002036 while (type->tp_base != NULL) {
2037 if (type->tp_dictoffset != 0 &&
2038 !(type->tp_flags & Py_TPFLAGS_HEAPTYPE))
2039 return type;
2040 type = type->tp_base;
2041 }
2042 return NULL;
Guido van Rossum360e4b82007-05-14 22:51:27 +00002043}
2044
2045static PyObject *
2046get_dict_descriptor(PyTypeObject *type)
2047{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002048 PyObject *descr;
Guido van Rossum360e4b82007-05-14 22:51:27 +00002049
Victor Stinner3c1e4812012-03-26 22:10:51 +02002050 descr = _PyType_LookupId(type, &PyId___dict__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002051 if (descr == NULL || !PyDescr_IsData(descr))
2052 return NULL;
Guido van Rossum360e4b82007-05-14 22:51:27 +00002053
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002054 return descr;
Guido van Rossum360e4b82007-05-14 22:51:27 +00002055}
2056
2057static void
2058raise_dict_descr_error(PyObject *obj)
2059{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002060 PyErr_Format(PyExc_TypeError,
2061 "this __dict__ descriptor does not support "
2062 "'%.200s' objects", Py_TYPE(obj)->tp_name);
Guido van Rossum360e4b82007-05-14 22:51:27 +00002063}
2064
Tim Peters6d6c1a32001-08-02 04:15:00 +00002065static PyObject *
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00002066subtype_dict(PyObject *obj, void *context)
2067{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002068 PyTypeObject *base;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00002069
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002070 base = get_builtin_base_with_dict(Py_TYPE(obj));
2071 if (base != NULL) {
2072 descrgetfunc func;
2073 PyObject *descr = get_dict_descriptor(base);
2074 if (descr == NULL) {
2075 raise_dict_descr_error(obj);
2076 return NULL;
2077 }
2078 func = Py_TYPE(descr)->tp_descr_get;
2079 if (func == NULL) {
2080 raise_dict_descr_error(obj);
2081 return NULL;
2082 }
2083 return func(descr, obj, (PyObject *)(Py_TYPE(obj)));
2084 }
Benjamin Peterson8eb12692012-02-19 19:59:10 -05002085 return PyObject_GenericGetDict(obj, context);
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00002086}
2087
Guido van Rossum6661be32001-10-26 04:26:12 +00002088static int
2089subtype_setdict(PyObject *obj, PyObject *value, void *context)
2090{
Benjamin Peterson8eb12692012-02-19 19:59:10 -05002091 PyObject *dict, **dictptr;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002092 PyTypeObject *base;
Guido van Rossum6661be32001-10-26 04:26:12 +00002093
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002094 base = get_builtin_base_with_dict(Py_TYPE(obj));
2095 if (base != NULL) {
2096 descrsetfunc func;
2097 PyObject *descr = get_dict_descriptor(base);
2098 if (descr == NULL) {
2099 raise_dict_descr_error(obj);
2100 return -1;
2101 }
2102 func = Py_TYPE(descr)->tp_descr_set;
2103 if (func == NULL) {
2104 raise_dict_descr_error(obj);
2105 return -1;
2106 }
2107 return func(descr, obj, value);
2108 }
Benjamin Peterson8eb12692012-02-19 19:59:10 -05002109 /* Almost like PyObject_GenericSetDict, but allow __dict__ to be deleted. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002110 dictptr = _PyObject_GetDictPtr(obj);
2111 if (dictptr == NULL) {
2112 PyErr_SetString(PyExc_AttributeError,
2113 "This object has no __dict__");
2114 return -1;
2115 }
Benjamin Peterson006c5a22012-02-19 20:36:12 -05002116 if (value != NULL && !PyDict_Check(value)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002117 PyErr_Format(PyExc_TypeError,
2118 "__dict__ must be set to a dictionary, "
2119 "not a '%.200s'", Py_TYPE(value)->tp_name);
2120 return -1;
2121 }
2122 dict = *dictptr;
2123 Py_XINCREF(value);
2124 *dictptr = value;
2125 Py_XDECREF(dict);
2126 return 0;
Guido van Rossum6661be32001-10-26 04:26:12 +00002127}
2128
Guido van Rossumad47da02002-08-12 19:05:44 +00002129static PyObject *
2130subtype_getweakref(PyObject *obj, void *context)
2131{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002132 PyObject **weaklistptr;
2133 PyObject *result;
Guido van Rossumad47da02002-08-12 19:05:44 +00002134
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002135 if (Py_TYPE(obj)->tp_weaklistoffset == 0) {
2136 PyErr_SetString(PyExc_AttributeError,
2137 "This object has no __weakref__");
2138 return NULL;
2139 }
2140 assert(Py_TYPE(obj)->tp_weaklistoffset > 0);
2141 assert(Py_TYPE(obj)->tp_weaklistoffset + sizeof(PyObject *) <=
2142 (size_t)(Py_TYPE(obj)->tp_basicsize));
2143 weaklistptr = (PyObject **)
2144 ((char *)obj + Py_TYPE(obj)->tp_weaklistoffset);
2145 if (*weaklistptr == NULL)
2146 result = Py_None;
2147 else
2148 result = *weaklistptr;
2149 Py_INCREF(result);
2150 return result;
Guido van Rossumad47da02002-08-12 19:05:44 +00002151}
2152
Guido van Rossum373c7412003-01-07 13:41:37 +00002153/* Three variants on the subtype_getsets list. */
2154
2155static PyGetSetDef subtype_getsets_full[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002156 {"__dict__", subtype_dict, subtype_setdict,
2157 PyDoc_STR("dictionary for instance variables (if defined)")},
2158 {"__weakref__", subtype_getweakref, NULL,
2159 PyDoc_STR("list of weak references to the object (if defined)")},
2160 {0}
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00002161};
2162
Guido van Rossum373c7412003-01-07 13:41:37 +00002163static PyGetSetDef subtype_getsets_dict_only[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002164 {"__dict__", subtype_dict, subtype_setdict,
2165 PyDoc_STR("dictionary for instance variables (if defined)")},
2166 {0}
Guido van Rossum373c7412003-01-07 13:41:37 +00002167};
2168
2169static PyGetSetDef subtype_getsets_weakref_only[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002170 {"__weakref__", subtype_getweakref, NULL,
2171 PyDoc_STR("list of weak references to the object (if defined)")},
2172 {0}
Guido van Rossum373c7412003-01-07 13:41:37 +00002173};
2174
Guido van Rossum9923ffe2002-06-04 19:52:53 +00002175static int
2176valid_identifier(PyObject *s)
2177{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002178 if (!PyUnicode_Check(s)) {
2179 PyErr_Format(PyExc_TypeError,
2180 "__slots__ items must be strings, not '%.200s'",
2181 Py_TYPE(s)->tp_name);
2182 return 0;
2183 }
2184 if (!PyUnicode_IsIdentifier(s)) {
2185 PyErr_SetString(PyExc_TypeError,
2186 "__slots__ must be identifiers");
2187 return 0;
2188 }
2189 return 1;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00002190}
2191
Guido van Rossumd8faa362007-04-27 19:54:29 +00002192/* Forward */
2193static int
2194object_init(PyObject *self, PyObject *args, PyObject *kwds);
2195
2196static int
2197type_init(PyObject *cls, PyObject *args, PyObject *kwds)
2198{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002199 int res;
Guido van Rossumd8faa362007-04-27 19:54:29 +00002200
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002201 assert(args != NULL && PyTuple_Check(args));
2202 assert(kwds == NULL || PyDict_Check(kwds));
Guido van Rossumd8faa362007-04-27 19:54:29 +00002203
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002204 if (kwds != NULL && PyDict_Check(kwds) && PyDict_Size(kwds) != 0) {
2205 PyErr_SetString(PyExc_TypeError,
2206 "type.__init__() takes no keyword arguments");
2207 return -1;
2208 }
Guido van Rossumd8faa362007-04-27 19:54:29 +00002209
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002210 if (args != NULL && PyTuple_Check(args) &&
2211 (PyTuple_GET_SIZE(args) != 1 && PyTuple_GET_SIZE(args) != 3)) {
2212 PyErr_SetString(PyExc_TypeError,
2213 "type.__init__() takes 1 or 3 arguments");
2214 return -1;
2215 }
Guido van Rossumd8faa362007-04-27 19:54:29 +00002216
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002217 /* Call object.__init__(self) now. */
2218 /* XXX Could call super(type, cls).__init__() but what's the point? */
2219 args = PyTuple_GetSlice(args, 0, 0);
2220 res = object_init(cls, args, NULL);
2221 Py_DECREF(args);
2222 return res;
Guido van Rossumd8faa362007-04-27 19:54:29 +00002223}
2224
Victor Stinner4ca1cf32012-10-30 23:40:45 +01002225unsigned long
Martin v. Löwis738236d2011-02-05 20:35:29 +00002226PyType_GetFlags(PyTypeObject *type)
2227{
2228 return type->tp_flags;
2229}
2230
Nick Coghlande31b192011-10-23 22:04:16 +10002231/* Determine the most derived metatype. */
2232PyTypeObject *
2233_PyType_CalculateMetaclass(PyTypeObject *metatype, PyObject *bases)
2234{
2235 Py_ssize_t i, nbases;
2236 PyTypeObject *winner;
2237 PyObject *tmp;
2238 PyTypeObject *tmptype;
2239
2240 /* Determine the proper metatype to deal with this,
2241 and check for metatype conflicts while we're at it.
2242 Note that if some other metatype wins to contract,
2243 it's possible that its instances are not types. */
2244
2245 nbases = PyTuple_GET_SIZE(bases);
2246 winner = metatype;
2247 for (i = 0; i < nbases; i++) {
2248 tmp = PyTuple_GET_ITEM(bases, i);
2249 tmptype = Py_TYPE(tmp);
2250 if (PyType_IsSubtype(winner, tmptype))
2251 continue;
2252 if (PyType_IsSubtype(tmptype, winner)) {
2253 winner = tmptype;
2254 continue;
2255 }
2256 /* else: */
2257 PyErr_SetString(PyExc_TypeError,
2258 "metaclass conflict: "
2259 "the metaclass of a derived class "
2260 "must be a (non-strict) subclass "
2261 "of the metaclasses of all its bases");
2262 return NULL;
2263 }
2264 return winner;
2265}
2266
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00002267static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00002268type_new(PyTypeObject *metatype, PyObject *args, PyObject *kwds)
2269{
Victor Stinner6f738742012-02-25 01:22:36 +01002270 PyObject *name, *bases = NULL, *orig_dict, *dict = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002271 static char *kwlist[] = {"name", "bases", "dict", 0};
Victor Stinner6f738742012-02-25 01:22:36 +01002272 PyObject *qualname, *slots = NULL, *tmp, *newslots;
2273 PyTypeObject *type = NULL, *base, *tmptype, *winner;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002274 PyHeapTypeObject *et;
2275 PyMemberDef *mp;
Serhiy Storchaka42bf8fc2015-12-30 21:40:49 +02002276 Py_ssize_t i, nbases, nslots, slotoffset, name_size;
2277 int j, may_add_dict, may_add_weak, add_dict, add_weak;
Victor Stinner3c1e4812012-03-26 22:10:51 +02002278 _Py_IDENTIFIER(__qualname__);
2279 _Py_IDENTIFIER(__slots__);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002280
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002281 assert(args != NULL && PyTuple_Check(args));
2282 assert(kwds == NULL || PyDict_Check(kwds));
Tim Peters3abca122001-10-27 19:37:48 +00002283
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002284 /* Special case: type(x) should return x->ob_type */
2285 {
2286 const Py_ssize_t nargs = PyTuple_GET_SIZE(args);
2287 const Py_ssize_t nkwds = kwds == NULL ? 0 : PyDict_Size(kwds);
Tim Peters3abca122001-10-27 19:37:48 +00002288
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002289 if (PyType_CheckExact(metatype) && nargs == 1 && nkwds == 0) {
2290 PyObject *x = PyTuple_GET_ITEM(args, 0);
2291 Py_INCREF(Py_TYPE(x));
2292 return (PyObject *) Py_TYPE(x);
2293 }
Tim Peters3abca122001-10-27 19:37:48 +00002294
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002295 /* SF bug 475327 -- if that didn't trigger, we need 3
2296 arguments. but PyArg_ParseTupleAndKeywords below may give
2297 a msg saying type() needs exactly 3. */
2298 if (nargs + nkwds != 3) {
2299 PyErr_SetString(PyExc_TypeError,
2300 "type() takes 1 or 3 arguments");
2301 return NULL;
2302 }
2303 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002304
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002305 /* Check arguments: (name, bases, dict) */
2306 if (!PyArg_ParseTupleAndKeywords(args, kwds, "UO!O!:type", kwlist,
2307 &name,
2308 &PyTuple_Type, &bases,
Victor Stinner6f738742012-02-25 01:22:36 +01002309 &PyDict_Type, &orig_dict))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002310 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002311
Nick Coghlande31b192011-10-23 22:04:16 +10002312 /* Determine the proper metatype to deal with this: */
2313 winner = _PyType_CalculateMetaclass(metatype, bases);
2314 if (winner == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002315 return NULL;
2316 }
Nick Coghlande31b192011-10-23 22:04:16 +10002317
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002318 if (winner != metatype) {
2319 if (winner->tp_new != type_new) /* Pass it to the winner */
2320 return winner->tp_new(winner, args, kwds);
2321 metatype = winner;
2322 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002323
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002324 /* Adjust for empty tuple bases */
Nick Coghlande31b192011-10-23 22:04:16 +10002325 nbases = PyTuple_GET_SIZE(bases);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002326 if (nbases == 0) {
2327 bases = PyTuple_Pack(1, &PyBaseObject_Type);
2328 if (bases == NULL)
Victor Stinner6f738742012-02-25 01:22:36 +01002329 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002330 nbases = 1;
2331 }
2332 else
2333 Py_INCREF(bases);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002334
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002335 /* Calculate best base, and check that all bases are type objects */
2336 base = best_base(bases);
2337 if (base == NULL) {
Victor Stinner6f738742012-02-25 01:22:36 +01002338 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002339 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002340
Victor Stinner6f738742012-02-25 01:22:36 +01002341 dict = PyDict_Copy(orig_dict);
2342 if (dict == NULL)
2343 goto error;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002344
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002345 /* Check for a __slots__ sequence variable in dict, and count it */
Victor Stinner3c1e4812012-03-26 22:10:51 +02002346 slots = _PyDict_GetItemId(dict, &PyId___slots__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002347 nslots = 0;
2348 add_dict = 0;
2349 add_weak = 0;
2350 may_add_dict = base->tp_dictoffset == 0;
2351 may_add_weak = base->tp_weaklistoffset == 0 && base->tp_itemsize == 0;
2352 if (slots == NULL) {
2353 if (may_add_dict) {
2354 add_dict++;
2355 }
2356 if (may_add_weak) {
2357 add_weak++;
2358 }
2359 }
2360 else {
2361 /* Have slots */
Guido van Rossumad47da02002-08-12 19:05:44 +00002362
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002363 /* Make it into a tuple */
2364 if (PyUnicode_Check(slots))
2365 slots = PyTuple_Pack(1, slots);
2366 else
2367 slots = PySequence_Tuple(slots);
Victor Stinner6f738742012-02-25 01:22:36 +01002368 if (slots == NULL)
2369 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002370 assert(PyTuple_Check(slots));
Guido van Rossumad47da02002-08-12 19:05:44 +00002371
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002372 /* Are slots allowed? */
2373 nslots = PyTuple_GET_SIZE(slots);
2374 if (nslots > 0 && base->tp_itemsize != 0) {
2375 PyErr_Format(PyExc_TypeError,
2376 "nonempty __slots__ "
2377 "not supported for subtype of '%s'",
2378 base->tp_name);
Victor Stinner6f738742012-02-25 01:22:36 +01002379 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002380 }
Guido van Rossumad47da02002-08-12 19:05:44 +00002381
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002382 /* Check for valid slot names and two special cases */
2383 for (i = 0; i < nslots; i++) {
2384 PyObject *tmp = PyTuple_GET_ITEM(slots, i);
2385 if (!valid_identifier(tmp))
Victor Stinner6f738742012-02-25 01:22:36 +01002386 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002387 assert(PyUnicode_Check(tmp));
Victor Stinnerad14ccd2013-11-07 00:46:04 +01002388 if (_PyUnicode_CompareWithId(tmp, &PyId___dict__) == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002389 if (!may_add_dict || add_dict) {
2390 PyErr_SetString(PyExc_TypeError,
2391 "__dict__ slot disallowed: "
2392 "we already got one");
Victor Stinner6f738742012-02-25 01:22:36 +01002393 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002394 }
2395 add_dict++;
2396 }
2397 if (PyUnicode_CompareWithASCIIString(tmp, "__weakref__") == 0) {
2398 if (!may_add_weak || add_weak) {
2399 PyErr_SetString(PyExc_TypeError,
2400 "__weakref__ slot disallowed: "
2401 "either we already got one, "
2402 "or __itemsize__ != 0");
Victor Stinner6f738742012-02-25 01:22:36 +01002403 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002404 }
2405 add_weak++;
2406 }
2407 }
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00002408
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002409 /* Copy slots into a list, mangle names and sort them.
2410 Sorted names are needed for __class__ assignment.
2411 Convert them back to tuple at the end.
2412 */
2413 newslots = PyList_New(nslots - add_dict - add_weak);
2414 if (newslots == NULL)
Victor Stinner6f738742012-02-25 01:22:36 +01002415 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002416 for (i = j = 0; i < nslots; i++) {
2417 tmp = PyTuple_GET_ITEM(slots, i);
2418 if ((add_dict &&
Victor Stinnerad14ccd2013-11-07 00:46:04 +01002419 _PyUnicode_CompareWithId(tmp, &PyId___dict__) == 0) ||
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002420 (add_weak &&
2421 PyUnicode_CompareWithASCIIString(tmp, "__weakref__") == 0))
2422 continue;
2423 tmp =_Py_Mangle(name, tmp);
Benjamin Petersonae13c882011-08-16 22:26:48 -05002424 if (!tmp) {
2425 Py_DECREF(newslots);
Victor Stinner6f738742012-02-25 01:22:36 +01002426 goto error;
Benjamin Petersonae13c882011-08-16 22:26:48 -05002427 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002428 PyList_SET_ITEM(newslots, j, tmp);
Benjamin Petersonc4085c82011-08-16 18:53:26 -05002429 if (PyDict_GetItem(dict, tmp)) {
2430 PyErr_Format(PyExc_ValueError,
2431 "%R in __slots__ conflicts with class variable",
2432 tmp);
Benjamin Petersond17cefc2011-08-16 22:28:23 -05002433 Py_DECREF(newslots);
Victor Stinner6f738742012-02-25 01:22:36 +01002434 goto error;
Benjamin Petersonc4085c82011-08-16 18:53:26 -05002435 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002436 j++;
2437 }
2438 assert(j == nslots - add_dict - add_weak);
2439 nslots = j;
Victor Stinner6f738742012-02-25 01:22:36 +01002440 Py_CLEAR(slots);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002441 if (PyList_Sort(newslots) == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002442 Py_DECREF(newslots);
Victor Stinner6f738742012-02-25 01:22:36 +01002443 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002444 }
2445 slots = PyList_AsTuple(newslots);
2446 Py_DECREF(newslots);
Victor Stinner6f738742012-02-25 01:22:36 +01002447 if (slots == NULL)
2448 goto error;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00002449
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002450 /* Secondary bases may provide weakrefs or dict */
2451 if (nbases > 1 &&
2452 ((may_add_dict && !add_dict) ||
2453 (may_add_weak && !add_weak))) {
2454 for (i = 0; i < nbases; i++) {
2455 tmp = PyTuple_GET_ITEM(bases, i);
2456 if (tmp == (PyObject *)base)
2457 continue; /* Skip primary base */
2458 assert(PyType_Check(tmp));
2459 tmptype = (PyTypeObject *)tmp;
2460 if (may_add_dict && !add_dict &&
2461 tmptype->tp_dictoffset != 0)
2462 add_dict++;
2463 if (may_add_weak && !add_weak &&
2464 tmptype->tp_weaklistoffset != 0)
2465 add_weak++;
2466 if (may_add_dict && !add_dict)
2467 continue;
2468 if (may_add_weak && !add_weak)
2469 continue;
2470 /* Nothing more to check */
2471 break;
2472 }
2473 }
2474 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002475
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002476 /* Allocate the type object */
2477 type = (PyTypeObject *)metatype->tp_alloc(metatype, nslots);
Victor Stinner6f738742012-02-25 01:22:36 +01002478 if (type == NULL)
2479 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002480
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002481 /* Keep name and slots alive in the extended type object */
2482 et = (PyHeapTypeObject *)type;
2483 Py_INCREF(name);
2484 et->ht_name = name;
2485 et->ht_slots = slots;
Victor Stinner6f738742012-02-25 01:22:36 +01002486 slots = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002487
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002488 /* Initialize tp_flags */
2489 type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE |
Antoine Pitrou796564c2013-07-30 19:59:21 +02002490 Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_FINALIZE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002491 if (base->tp_flags & Py_TPFLAGS_HAVE_GC)
2492 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossumdc91b992001-08-08 22:26:22 +00002493
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002494 /* Initialize essential fields */
Yury Selivanov75445082015-05-11 22:57:16 -04002495 type->tp_as_async = &et->as_async;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002496 type->tp_as_number = &et->as_number;
2497 type->tp_as_sequence = &et->as_sequence;
2498 type->tp_as_mapping = &et->as_mapping;
2499 type->tp_as_buffer = &et->as_buffer;
Serhiy Storchaka42bf8fc2015-12-30 21:40:49 +02002500 type->tp_name = PyUnicode_AsUTF8AndSize(name, &name_size);
Victor Stinner6f738742012-02-25 01:22:36 +01002501 if (!type->tp_name)
2502 goto error;
Serhiy Storchaka42bf8fc2015-12-30 21:40:49 +02002503 if (strlen(type->tp_name) != (size_t)name_size) {
2504 PyErr_SetString(PyExc_ValueError,
2505 "type name must not contain null characters");
2506 goto error;
2507 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002508
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002509 /* Set tp_base and tp_bases */
2510 type->tp_bases = bases;
Victor Stinner6f738742012-02-25 01:22:36 +01002511 bases = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002512 Py_INCREF(base);
2513 type->tp_base = base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002514
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002515 /* Initialize tp_dict from passed-in dict */
Victor Stinner6f738742012-02-25 01:22:36 +01002516 Py_INCREF(dict);
2517 type->tp_dict = dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002518
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002519 /* Set __module__ in the dict */
Victor Stinner3c1e4812012-03-26 22:10:51 +02002520 if (_PyDict_GetItemId(dict, &PyId___module__) == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002521 tmp = PyEval_GetGlobals();
2522 if (tmp != NULL) {
Victor Stinner3c1e4812012-03-26 22:10:51 +02002523 tmp = _PyDict_GetItemId(tmp, &PyId___name__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002524 if (tmp != NULL) {
Victor Stinner3c1e4812012-03-26 22:10:51 +02002525 if (_PyDict_SetItemId(dict, &PyId___module__,
2526 tmp) < 0)
Victor Stinner6f738742012-02-25 01:22:36 +01002527 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002528 }
2529 }
2530 }
Guido van Rossumc3542212001-08-16 09:18:56 +00002531
Victor Stinner6f738742012-02-25 01:22:36 +01002532 /* Set ht_qualname to dict['__qualname__'] if available, else to
2533 __name__. The __qualname__ accessor will look for ht_qualname.
2534 */
Victor Stinner3c1e4812012-03-26 22:10:51 +02002535 qualname = _PyDict_GetItemId(dict, &PyId___qualname__);
Victor Stinner6f738742012-02-25 01:22:36 +01002536 if (qualname != NULL) {
2537 if (!PyUnicode_Check(qualname)) {
2538 PyErr_Format(PyExc_TypeError,
2539 "type __qualname__ must be a str, not %s",
2540 Py_TYPE(qualname)->tp_name);
2541 goto error;
2542 }
2543 }
Benjamin Peterson8afa7fa2012-10-30 23:51:03 -04002544 et->ht_qualname = qualname ? qualname : et->ht_name;
2545 Py_INCREF(et->ht_qualname);
2546 if (qualname != NULL && PyDict_DelItem(dict, PyId___qualname__.object) < 0)
2547 goto error;
Victor Stinner6f738742012-02-25 01:22:36 +01002548
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002549 /* Set tp_doc to a copy of dict['__doc__'], if the latter is there
2550 and is a string. The __doc__ accessor will first look for tp_doc;
2551 if that fails, it will still look into __dict__.
2552 */
2553 {
Victor Stinner3c1e4812012-03-26 22:10:51 +02002554 PyObject *doc = _PyDict_GetItemId(dict, &PyId___doc__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002555 if (doc != NULL && PyUnicode_Check(doc)) {
2556 Py_ssize_t len;
2557 char *doc_str;
2558 char *tp_doc;
Alexandre Vassalottia85998a2008-05-03 18:24:43 +00002559
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002560 doc_str = _PyUnicode_AsString(doc);
Victor Stinner6f738742012-02-25 01:22:36 +01002561 if (doc_str == NULL)
2562 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002563 /* Silently truncate the docstring if it contains null bytes. */
2564 len = strlen(doc_str);
2565 tp_doc = (char *)PyObject_MALLOC(len + 1);
Victor Stinner53510cd2013-07-15 19:34:20 +02002566 if (tp_doc == NULL) {
2567 PyErr_NoMemory();
Victor Stinner6f738742012-02-25 01:22:36 +01002568 goto error;
Victor Stinner53510cd2013-07-15 19:34:20 +02002569 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002570 memcpy(tp_doc, doc_str, len + 1);
2571 type->tp_doc = tp_doc;
2572 }
2573 }
Tim Peters2f93e282001-10-04 05:27:00 +00002574
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002575 /* Special-case __new__: if it's a plain function,
2576 make it a static function */
Victor Stinner3c1e4812012-03-26 22:10:51 +02002577 tmp = _PyDict_GetItemId(dict, &PyId___new__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002578 if (tmp != NULL && PyFunction_Check(tmp)) {
2579 tmp = PyStaticMethod_New(tmp);
Victor Stinner6f738742012-02-25 01:22:36 +01002580 if (tmp == NULL)
2581 goto error;
Serhiy Storchaka484c9132016-06-05 10:48:36 +03002582 if (_PyDict_SetItemId(dict, &PyId___new__, tmp) < 0) {
2583 Py_DECREF(tmp);
Victor Stinner3c1e4812012-03-26 22:10:51 +02002584 goto error;
Serhiy Storchaka484c9132016-06-05 10:48:36 +03002585 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002586 Py_DECREF(tmp);
2587 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002588
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002589 /* Add descriptors for custom slots from __slots__, or for __dict__ */
2590 mp = PyHeapType_GET_MEMBERS(et);
2591 slotoffset = base->tp_basicsize;
Victor Stinner6f738742012-02-25 01:22:36 +01002592 if (et->ht_slots != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002593 for (i = 0; i < nslots; i++, mp++) {
2594 mp->name = _PyUnicode_AsString(
Victor Stinner6f738742012-02-25 01:22:36 +01002595 PyTuple_GET_ITEM(et->ht_slots, i));
2596 if (mp->name == NULL)
2597 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002598 mp->type = T_OBJECT_EX;
2599 mp->offset = slotoffset;
Guido van Rossumd8faa362007-04-27 19:54:29 +00002600
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002601 /* __dict__ and __weakref__ are already filtered out */
2602 assert(strcmp(mp->name, "__dict__") != 0);
2603 assert(strcmp(mp->name, "__weakref__") != 0);
Guido van Rossumd8faa362007-04-27 19:54:29 +00002604
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002605 slotoffset += sizeof(PyObject *);
2606 }
2607 }
2608 if (add_dict) {
2609 if (base->tp_itemsize)
2610 type->tp_dictoffset = -(long)sizeof(PyObject *);
2611 else
2612 type->tp_dictoffset = slotoffset;
2613 slotoffset += sizeof(PyObject *);
2614 }
2615 if (add_weak) {
2616 assert(!base->tp_itemsize);
2617 type->tp_weaklistoffset = slotoffset;
2618 slotoffset += sizeof(PyObject *);
2619 }
2620 type->tp_basicsize = slotoffset;
2621 type->tp_itemsize = base->tp_itemsize;
2622 type->tp_members = PyHeapType_GET_MEMBERS(et);
Guido van Rossum373c7412003-01-07 13:41:37 +00002623
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002624 if (type->tp_weaklistoffset && type->tp_dictoffset)
2625 type->tp_getset = subtype_getsets_full;
2626 else if (type->tp_weaklistoffset && !type->tp_dictoffset)
2627 type->tp_getset = subtype_getsets_weakref_only;
2628 else if (!type->tp_weaklistoffset && type->tp_dictoffset)
2629 type->tp_getset = subtype_getsets_dict_only;
2630 else
2631 type->tp_getset = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002632
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002633 /* Special case some slots */
2634 if (type->tp_dictoffset != 0 || nslots > 0) {
2635 if (base->tp_getattr == NULL && base->tp_getattro == NULL)
2636 type->tp_getattro = PyObject_GenericGetAttr;
2637 if (base->tp_setattr == NULL && base->tp_setattro == NULL)
2638 type->tp_setattro = PyObject_GenericSetAttr;
2639 }
2640 type->tp_dealloc = subtype_dealloc;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002641
Antoine Pitroua63cc212015-04-13 20:10:06 +02002642 /* Enable GC unless this class is not adding new instance variables and
2643 the base class did not use GC. */
2644 if ((base->tp_flags & Py_TPFLAGS_HAVE_GC) ||
2645 type->tp_basicsize > base->tp_basicsize)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002646 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossum9475a232001-10-05 20:51:39 +00002647
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002648 /* Always override allocation strategy to use regular heap */
2649 type->tp_alloc = PyType_GenericAlloc;
2650 if (type->tp_flags & Py_TPFLAGS_HAVE_GC) {
2651 type->tp_free = PyObject_GC_Del;
2652 type->tp_traverse = subtype_traverse;
2653 type->tp_clear = subtype_clear;
2654 }
2655 else
2656 type->tp_free = PyObject_Del;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002657
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002658 /* Initialize the rest */
Victor Stinner6f738742012-02-25 01:22:36 +01002659 if (PyType_Ready(type) < 0)
2660 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002661
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002662 /* Put the proper slots in place */
2663 fixup_slot_dispatchers(type);
Guido van Rossumf040ede2001-08-07 16:40:56 +00002664
Benjamin Petersondf813792014-03-17 15:57:17 -05002665 if (type->tp_dictoffset) {
2666 et->ht_cached_keys = _PyDict_NewKeysForClass();
2667 }
2668
Victor Stinner6f738742012-02-25 01:22:36 +01002669 Py_DECREF(dict);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002670 return (PyObject *)type;
Victor Stinner6f738742012-02-25 01:22:36 +01002671
2672error:
2673 Py_XDECREF(dict);
2674 Py_XDECREF(bases);
2675 Py_XDECREF(slots);
2676 Py_XDECREF(type);
2677 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002678}
2679
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002680static short slotoffsets[] = {
2681 -1, /* invalid slot */
2682#include "typeslots.inc"
2683};
2684
Benjamin Petersone28108c2012-01-29 20:13:18 -05002685PyObject *
Martin v. Löwis9c564092012-06-23 23:20:45 +02002686PyType_FromSpecWithBases(PyType_Spec *spec, PyObject *bases)
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002687{
2688 PyHeapTypeObject *res = (PyHeapTypeObject*)PyType_GenericAlloc(&PyType_Type, 0);
Martin v. Löwis9c564092012-06-23 23:20:45 +02002689 PyTypeObject *type, *base;
Nick Coghlana48db2b2015-05-24 01:03:46 +10002690 PyObject *modname;
Martin v. Löwis9c564092012-06-23 23:20:45 +02002691 char *s;
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002692 char *res_start = (char*)res;
2693 PyType_Slot *slot;
Victor Stinner54e4ca72013-07-11 22:42:25 +02002694
Martin v. Löwis9c564092012-06-23 23:20:45 +02002695 /* Set the type name and qualname */
2696 s = strrchr(spec->name, '.');
2697 if (s == NULL)
2698 s = (char*)spec->name;
2699 else
2700 s++;
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002701
Martin v. Löwis5e06a5d2011-02-21 16:24:00 +00002702 if (res == NULL)
Antoine Pitroubb78f572012-06-24 00:18:27 +02002703 return NULL;
2704 type = &res->ht_type;
Antoine Pitrou66a3a7e2012-06-24 00:42:59 +02002705 /* The flags must be initialized early, before the GC traverses us */
2706 type->tp_flags = spec->flags | Py_TPFLAGS_HEAPTYPE;
Martin v. Löwis9c564092012-06-23 23:20:45 +02002707 res->ht_name = PyUnicode_FromString(s);
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002708 if (!res->ht_name)
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002709 goto fail;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002710 res->ht_qualname = res->ht_name;
2711 Py_INCREF(res->ht_qualname);
Antoine Pitroubb78f572012-06-24 00:18:27 +02002712 type->tp_name = spec->name;
2713 if (!type->tp_name)
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002714 goto fail;
Victor Stinner54e4ca72013-07-11 22:42:25 +02002715
Martin v. Löwis9c564092012-06-23 23:20:45 +02002716 /* Adjust for empty tuple bases */
2717 if (!bases) {
2718 base = &PyBaseObject_Type;
2719 /* See whether Py_tp_base(s) was specified */
2720 for (slot = spec->slots; slot->slot; slot++) {
2721 if (slot->slot == Py_tp_base)
2722 base = slot->pfunc;
2723 else if (slot->slot == Py_tp_bases) {
2724 bases = slot->pfunc;
2725 Py_INCREF(bases);
2726 }
2727 }
2728 if (!bases)
2729 bases = PyTuple_Pack(1, base);
2730 if (!bases)
2731 goto fail;
2732 }
2733 else
2734 Py_INCREF(bases);
2735
2736 /* Calculate best base, and check that all bases are type objects */
2737 base = best_base(bases);
2738 if (base == NULL) {
2739 goto fail;
2740 }
2741 if (!PyType_HasFeature(base, Py_TPFLAGS_BASETYPE)) {
2742 PyErr_Format(PyExc_TypeError,
2743 "type '%.100s' is not an acceptable base type",
2744 base->tp_name);
2745 goto fail;
2746 }
2747
Martin v. Löwis9c564092012-06-23 23:20:45 +02002748 /* Initialize essential fields */
Yury Selivanov75445082015-05-11 22:57:16 -04002749 type->tp_as_async = &res->as_async;
Martin v. Löwis9c564092012-06-23 23:20:45 +02002750 type->tp_as_number = &res->as_number;
2751 type->tp_as_sequence = &res->as_sequence;
2752 type->tp_as_mapping = &res->as_mapping;
2753 type->tp_as_buffer = &res->as_buffer;
2754 /* Set tp_base and tp_bases */
2755 type->tp_bases = bases;
2756 bases = NULL;
2757 Py_INCREF(base);
2758 type->tp_base = base;
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002759
Antoine Pitroubb78f572012-06-24 00:18:27 +02002760 type->tp_basicsize = spec->basicsize;
2761 type->tp_itemsize = spec->itemsize;
Victor Stinner0fcab4a2011-01-04 12:59:15 +00002762
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002763 for (slot = spec->slots; slot->slot; slot++) {
Victor Stinner12174a52014-08-15 23:17:38 +02002764 if (slot->slot < 0
2765 || (size_t)slot->slot >= Py_ARRAY_LENGTH(slotoffsets)) {
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002766 PyErr_SetString(PyExc_RuntimeError, "invalid slot offset");
2767 goto fail;
2768 }
Martin v. Löwis9c564092012-06-23 23:20:45 +02002769 if (slot->slot == Py_tp_base || slot->slot == Py_tp_bases)
2770 /* Processed above */
2771 continue;
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002772 *(void**)(res_start + slotoffsets[slot->slot]) = slot->pfunc;
Georg Brandl032400b2011-02-19 21:47:02 +00002773
2774 /* need to make a copy of the docstring slot, which usually
2775 points to a static string literal */
2776 if (slot->slot == Py_tp_doc) {
Larry Hastings2623c8c2014-02-08 22:15:29 -08002777 const char *old_doc = _PyType_DocWithoutSignature(type->tp_name, slot->pfunc);
Larry Hastings5c661892014-01-24 06:17:25 -08002778 size_t len = strlen(old_doc)+1;
Georg Brandl032400b2011-02-19 21:47:02 +00002779 char *tp_doc = PyObject_MALLOC(len);
Victor Stinner53510cd2013-07-15 19:34:20 +02002780 if (tp_doc == NULL) {
2781 PyErr_NoMemory();
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002782 goto fail;
Victor Stinner53510cd2013-07-15 19:34:20 +02002783 }
Larry Hastings5c661892014-01-24 06:17:25 -08002784 memcpy(tp_doc, old_doc, len);
Antoine Pitroubb78f572012-06-24 00:18:27 +02002785 type->tp_doc = tp_doc;
Georg Brandl032400b2011-02-19 21:47:02 +00002786 }
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002787 }
Antoine Pitroubb78f572012-06-24 00:18:27 +02002788 if (type->tp_dealloc == NULL) {
Antoine Pitrou99cc6292012-06-23 14:42:38 +02002789 /* It's a heap type, so needs the heap types' dealloc.
2790 subtype_dealloc will call the base type's tp_dealloc, if
2791 necessary. */
Antoine Pitroubb78f572012-06-24 00:18:27 +02002792 type->tp_dealloc = subtype_dealloc;
Antoine Pitrou99cc6292012-06-23 14:42:38 +02002793 }
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002794
Antoine Pitroubb78f572012-06-24 00:18:27 +02002795 if (PyType_Ready(type) < 0)
Benjamin Peterson2652d252012-01-29 20:16:37 -05002796 goto fail;
2797
Benjamin Petersondf813792014-03-17 15:57:17 -05002798 if (type->tp_dictoffset) {
2799 res->ht_cached_keys = _PyDict_NewKeysForClass();
2800 }
2801
Martin v. Löwis9c564092012-06-23 23:20:45 +02002802 /* Set type.__module__ */
2803 s = strrchr(spec->name, '.');
Nick Coghlana48db2b2015-05-24 01:03:46 +10002804 if (s != NULL) {
2805 modname = PyUnicode_FromStringAndSize(
2806 spec->name, (Py_ssize_t)(s - spec->name));
2807 if (modname == NULL) {
2808 goto fail;
2809 }
2810 _PyDict_SetItemId(type->tp_dict, &PyId___module__, modname);
2811 Py_DECREF(modname);
2812 } else {
Serhiy Storchaka490055a2015-03-01 10:03:02 +02002813 if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
Serhiy Storchaka71c6f442015-03-01 14:39:20 +02002814 "builtin type %.200s has no __module__ attribute",
Serhiy Storchaka490055a2015-03-01 10:03:02 +02002815 spec->name))
2816 goto fail;
2817 }
Martin v. Löwis9c564092012-06-23 23:20:45 +02002818
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002819 return (PyObject*)res;
Victor Stinner0fcab4a2011-01-04 12:59:15 +00002820
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002821 fail:
2822 Py_DECREF(res);
2823 return NULL;
2824}
2825
Martin v. Löwis9c564092012-06-23 23:20:45 +02002826PyObject *
2827PyType_FromSpec(PyType_Spec *spec)
2828{
2829 return PyType_FromSpecWithBases(spec, NULL);
2830}
2831
Martin v. Löwisca7b0462014-02-04 09:33:05 +01002832void *
2833PyType_GetSlot(PyTypeObject *type, int slot)
2834{
Victor Stinner12174a52014-08-15 23:17:38 +02002835 if (!PyType_HasFeature(type, Py_TPFLAGS_HEAPTYPE) || slot < 0) {
Martin v. Löwisca7b0462014-02-04 09:33:05 +01002836 PyErr_BadInternalCall();
2837 return NULL;
2838 }
Victor Stinner12174a52014-08-15 23:17:38 +02002839 if ((size_t)slot >= Py_ARRAY_LENGTH(slotoffsets)) {
Martin v. Löwisca7b0462014-02-04 09:33:05 +01002840 /* Extension module requesting slot from a future version */
2841 return NULL;
2842 }
2843 return *(void**)(((char*)type) + slotoffsets[slot]);
2844}
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002845
Tim Peters6d6c1a32001-08-02 04:15:00 +00002846/* Internal API to look for a name through the MRO.
2847 This returns a borrowed reference, and doesn't set an exception! */
2848PyObject *
2849_PyType_Lookup(PyTypeObject *type, PyObject *name)
2850{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002851 Py_ssize_t i, n;
2852 PyObject *mro, *res, *base, *dict;
2853 unsigned int h;
Christian Heimesa62da1d2008-01-12 19:39:10 +00002854
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002855 if (MCACHE_CACHEABLE_NAME(name) &&
2856 PyType_HasFeature(type, Py_TPFLAGS_VALID_VERSION_TAG)) {
2857 /* fast path */
2858 h = MCACHE_HASH_METHOD(type, name);
2859 if (method_cache[h].version == type->tp_version_tag &&
Antoine Pitrou2a40e362014-11-15 00:56:27 +01002860 method_cache[h].name == name) {
2861#if MCACHE_STATS
2862 method_cache_hits++;
2863#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002864 return method_cache[h].value;
Antoine Pitrou2a40e362014-11-15 00:56:27 +01002865 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002866 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002867
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002868 /* Look in tp_dict of types in MRO */
2869 mro = type->tp_mro;
Guido van Rossum23094982002-06-10 14:30:43 +00002870
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002871 /* If mro is NULL, the type is either not yet initialized
2872 by PyType_Ready(), or already cleared by type_clear().
2873 Either way the safest thing to do is to return NULL. */
2874 if (mro == NULL)
2875 return NULL;
Guido van Rossum23094982002-06-10 14:30:43 +00002876
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002877 res = NULL;
Victor Stinnerd74782b2012-03-09 00:39:08 +01002878 /* keep a strong reference to mro because type->tp_mro can be replaced
2879 during PyDict_GetItem(dict, name) */
2880 Py_INCREF(mro);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002881 assert(PyTuple_Check(mro));
2882 n = PyTuple_GET_SIZE(mro);
2883 for (i = 0; i < n; i++) {
2884 base = PyTuple_GET_ITEM(mro, i);
2885 assert(PyType_Check(base));
2886 dict = ((PyTypeObject *)base)->tp_dict;
2887 assert(dict && PyDict_Check(dict));
2888 res = PyDict_GetItem(dict, name);
2889 if (res != NULL)
2890 break;
2891 }
Victor Stinnerd74782b2012-03-09 00:39:08 +01002892 Py_DECREF(mro);
Christian Heimesa62da1d2008-01-12 19:39:10 +00002893
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002894 if (MCACHE_CACHEABLE_NAME(name) && assign_version_tag(type)) {
2895 h = MCACHE_HASH_METHOD(type, name);
2896 method_cache[h].version = type->tp_version_tag;
2897 method_cache[h].value = res; /* borrowed */
2898 Py_INCREF(name);
Antoine Pitrou2a40e362014-11-15 00:56:27 +01002899 assert(((PyASCIIObject *)(name))->hash != -1);
2900#if MCACHE_STATS
2901 if (method_cache[h].name != Py_None && method_cache[h].name != name)
2902 method_cache_collisions++;
2903 else
2904 method_cache_misses++;
2905#endif
Serhiy Storchaka57a01d32016-04-10 18:05:40 +03002906 Py_SETREF(method_cache[h].name, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002907 }
2908 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002909}
2910
Raymond Hettinger2ff21902013-10-01 00:55:43 -07002911PyObject *
Victor Stinner3c1e4812012-03-26 22:10:51 +02002912_PyType_LookupId(PyTypeObject *type, struct _Py_Identifier *name)
2913{
2914 PyObject *oname;
2915 oname = _PyUnicode_FromId(name); /* borrowed */
2916 if (oname == NULL)
2917 return NULL;
2918 return _PyType_Lookup(type, oname);
2919}
2920
Tim Peters6d6c1a32001-08-02 04:15:00 +00002921/* This is similar to PyObject_GenericGetAttr(),
2922 but uses _PyType_Lookup() instead of just looking in type->tp_dict. */
2923static PyObject *
2924type_getattro(PyTypeObject *type, PyObject *name)
2925{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002926 PyTypeObject *metatype = Py_TYPE(type);
2927 PyObject *meta_attribute, *attribute;
2928 descrgetfunc meta_get;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002929
Benjamin Peterson16d84ac2012-03-16 09:32:59 -05002930 if (!PyUnicode_Check(name)) {
2931 PyErr_Format(PyExc_TypeError,
2932 "attribute name must be string, not '%.200s'",
2933 name->ob_type->tp_name);
2934 return NULL;
2935 }
2936
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002937 /* Initialize this type (we'll assume the metatype is initialized) */
2938 if (type->tp_dict == NULL) {
2939 if (PyType_Ready(type) < 0)
2940 return NULL;
2941 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002942
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002943 /* No readable descriptor found yet */
2944 meta_get = NULL;
Tim Peters34592512002-07-11 06:23:50 +00002945
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002946 /* Look for the attribute in the metatype */
2947 meta_attribute = _PyType_Lookup(metatype, name);
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002948
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002949 if (meta_attribute != NULL) {
2950 meta_get = Py_TYPE(meta_attribute)->tp_descr_get;
Tim Peters34592512002-07-11 06:23:50 +00002951
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002952 if (meta_get != NULL && PyDescr_IsData(meta_attribute)) {
2953 /* Data descriptors implement tp_descr_set to intercept
2954 * writes. Assume the attribute is not overridden in
2955 * type's tp_dict (and bases): call the descriptor now.
2956 */
2957 return meta_get(meta_attribute, (PyObject *)type,
2958 (PyObject *)metatype);
2959 }
2960 Py_INCREF(meta_attribute);
2961 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002962
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002963 /* No data descriptor found on metatype. Look in tp_dict of this
2964 * type and its bases */
2965 attribute = _PyType_Lookup(type, name);
2966 if (attribute != NULL) {
2967 /* Implement descriptor functionality, if any */
2968 descrgetfunc local_get = Py_TYPE(attribute)->tp_descr_get;
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00002969
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002970 Py_XDECREF(meta_attribute);
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00002971
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002972 if (local_get != NULL) {
2973 /* NULL 2nd argument indicates the descriptor was
2974 * found on the target object itself (or a base) */
2975 return local_get(attribute, (PyObject *)NULL,
2976 (PyObject *)type);
2977 }
Tim Peters34592512002-07-11 06:23:50 +00002978
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002979 Py_INCREF(attribute);
2980 return attribute;
2981 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002982
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002983 /* No attribute found in local __dict__ (or bases): use the
2984 * descriptor from the metatype, if any */
2985 if (meta_get != NULL) {
2986 PyObject *res;
2987 res = meta_get(meta_attribute, (PyObject *)type,
2988 (PyObject *)metatype);
2989 Py_DECREF(meta_attribute);
2990 return res;
2991 }
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002992
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002993 /* If an ordinary attribute was found on the metatype, return it now */
2994 if (meta_attribute != NULL) {
2995 return meta_attribute;
2996 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002997
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002998 /* Give up */
2999 PyErr_Format(PyExc_AttributeError,
3000 "type object '%.50s' has no attribute '%U'",
3001 type->tp_name, name);
3002 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003003}
3004
3005static int
3006type_setattro(PyTypeObject *type, PyObject *name, PyObject *value)
3007{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003008 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
3009 PyErr_Format(
3010 PyExc_TypeError,
3011 "can't set attributes of built-in/extension type '%s'",
3012 type->tp_name);
3013 return -1;
3014 }
3015 if (PyObject_GenericSetAttr((PyObject *)type, name, value) < 0)
3016 return -1;
3017 return update_slot(type, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003018}
3019
Benjamin Peterson64acccf2012-04-27 15:07:36 -04003020extern void
3021_PyDictKeys_DecRef(PyDictKeysObject *keys);
3022
Tim Peters6d6c1a32001-08-02 04:15:00 +00003023static void
3024type_dealloc(PyTypeObject *type)
3025{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003026 PyHeapTypeObject *et;
Antoine Pitrou84745ab2013-10-29 21:31:25 +01003027 PyObject *tp, *val, *tb;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003028
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003029 /* Assert this is a heap-allocated type object */
3030 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
3031 _PyObject_GC_UNTRACK(type);
Antoine Pitrou84745ab2013-10-29 21:31:25 +01003032 PyErr_Fetch(&tp, &val, &tb);
3033 remove_all_subclasses(type, type->tp_bases);
3034 PyErr_Restore(tp, val, tb);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003035 PyObject_ClearWeakRefs((PyObject *)type);
3036 et = (PyHeapTypeObject *)type;
3037 Py_XDECREF(type->tp_base);
3038 Py_XDECREF(type->tp_dict);
3039 Py_XDECREF(type->tp_bases);
3040 Py_XDECREF(type->tp_mro);
3041 Py_XDECREF(type->tp_cache);
3042 Py_XDECREF(type->tp_subclasses);
3043 /* A type's tp_doc is heap allocated, unlike the tp_doc slots
3044 * of most other objects. It's okay to cast it to char *.
3045 */
3046 PyObject_Free((char *)type->tp_doc);
3047 Py_XDECREF(et->ht_name);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003048 Py_XDECREF(et->ht_qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003049 Py_XDECREF(et->ht_slots);
Benjamin Peterson64acccf2012-04-27 15:07:36 -04003050 if (et->ht_cached_keys)
3051 _PyDictKeys_DecRef(et->ht_cached_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003052 Py_TYPE(type)->tp_free((PyObject *)type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003053}
3054
Guido van Rossum1c450732001-10-08 15:18:27 +00003055static PyObject *
3056type_subclasses(PyTypeObject *type, PyObject *args_ignored)
3057{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003058 PyObject *list, *raw, *ref;
Antoine Pitrou84745ab2013-10-29 21:31:25 +01003059 Py_ssize_t i;
Guido van Rossum1c450732001-10-08 15:18:27 +00003060
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003061 list = PyList_New(0);
3062 if (list == NULL)
3063 return NULL;
3064 raw = type->tp_subclasses;
3065 if (raw == NULL)
3066 return list;
Antoine Pitrou84745ab2013-10-29 21:31:25 +01003067 assert(PyDict_CheckExact(raw));
3068 i = 0;
3069 while (PyDict_Next(raw, &i, NULL, &ref)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003070 assert(PyWeakref_CheckRef(ref));
3071 ref = PyWeakref_GET_OBJECT(ref);
3072 if (ref != Py_None) {
3073 if (PyList_Append(list, ref) < 0) {
3074 Py_DECREF(list);
3075 return NULL;
3076 }
3077 }
3078 }
3079 return list;
Guido van Rossum1c450732001-10-08 15:18:27 +00003080}
3081
Guido van Rossum47374822007-08-02 16:48:17 +00003082static PyObject *
3083type_prepare(PyObject *self, PyObject *args, PyObject *kwds)
3084{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003085 return PyDict_New();
Guido van Rossum47374822007-08-02 16:48:17 +00003086}
3087
Victor Stinner63941882011-09-29 00:42:28 +02003088/*
Benjamin Peterson82b00c12011-05-24 11:09:06 -05003089 Merge the __dict__ of aclass into dict, and recursively also all
3090 the __dict__s of aclass's base classes. The order of merging isn't
3091 defined, as it's expected that only the final set of dict keys is
3092 interesting.
3093 Return 0 on success, -1 on error.
3094*/
3095
3096static int
3097merge_class_dict(PyObject *dict, PyObject *aclass)
3098{
3099 PyObject *classdict;
3100 PyObject *bases;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02003101 _Py_IDENTIFIER(__bases__);
Benjamin Peterson82b00c12011-05-24 11:09:06 -05003102
3103 assert(PyDict_Check(dict));
3104 assert(aclass);
3105
3106 /* Merge in the type's dict (if any). */
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02003107 classdict = _PyObject_GetAttrId(aclass, &PyId___dict__);
Benjamin Peterson82b00c12011-05-24 11:09:06 -05003108 if (classdict == NULL)
3109 PyErr_Clear();
3110 else {
3111 int status = PyDict_Update(dict, classdict);
3112 Py_DECREF(classdict);
3113 if (status < 0)
3114 return -1;
3115 }
3116
3117 /* Recursively merge in the base types' (if any) dicts. */
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02003118 bases = _PyObject_GetAttrId(aclass, &PyId___bases__);
Benjamin Peterson82b00c12011-05-24 11:09:06 -05003119 if (bases == NULL)
3120 PyErr_Clear();
3121 else {
3122 /* We have no guarantee that bases is a real tuple */
3123 Py_ssize_t i, n;
3124 n = PySequence_Size(bases); /* This better be right */
3125 if (n < 0)
3126 PyErr_Clear();
3127 else {
3128 for (i = 0; i < n; i++) {
3129 int status;
3130 PyObject *base = PySequence_GetItem(bases, i);
3131 if (base == NULL) {
3132 Py_DECREF(bases);
3133 return -1;
3134 }
3135 status = merge_class_dict(dict, base);
3136 Py_DECREF(base);
3137 if (status < 0) {
3138 Py_DECREF(bases);
3139 return -1;
3140 }
3141 }
3142 }
3143 Py_DECREF(bases);
3144 }
3145 return 0;
3146}
3147
3148/* __dir__ for type objects: returns __dict__ and __bases__.
3149 We deliberately don't suck up its __class__, as methods belonging to the
3150 metaclass would probably be more confusing than helpful.
3151*/
3152static PyObject *
3153type_dir(PyObject *self, PyObject *args)
3154{
3155 PyObject *result = NULL;
3156 PyObject *dict = PyDict_New();
3157
3158 if (dict != NULL && merge_class_dict(dict, self) == 0)
3159 result = PyDict_Keys(dict);
3160
3161 Py_XDECREF(dict);
3162 return result;
3163}
3164
Martin v. Loewis4f2f3b62012-04-24 19:13:57 +02003165static PyObject*
3166type_sizeof(PyObject *self, PyObject *args_unused)
3167{
3168 Py_ssize_t size;
3169 PyTypeObject *type = (PyTypeObject*)self;
3170 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
3171 PyHeapTypeObject* et = (PyHeapTypeObject*)type;
3172 size = sizeof(PyHeapTypeObject);
3173 if (et->ht_cached_keys)
3174 size += _PyDict_KeysSize(et->ht_cached_keys);
3175 }
3176 else
3177 size = sizeof(PyTypeObject);
3178 return PyLong_FromSsize_t(size);
3179}
3180
Tim Peters6d6c1a32001-08-02 04:15:00 +00003181static PyMethodDef type_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003182 {"mro", (PyCFunction)mro_external, METH_NOARGS,
3183 PyDoc_STR("mro() -> list\nreturn a type's method resolution order")},
3184 {"__subclasses__", (PyCFunction)type_subclasses, METH_NOARGS,
3185 PyDoc_STR("__subclasses__() -> list of immediate subclasses")},
3186 {"__prepare__", (PyCFunction)type_prepare,
3187 METH_VARARGS | METH_KEYWORDS | METH_CLASS,
3188 PyDoc_STR("__prepare__() -> dict\n"
3189 "used to create the namespace for the class statement")},
3190 {"__instancecheck__", type___instancecheck__, METH_O,
Benjamin Petersonfbe56bb2011-05-24 12:42:51 -05003191 PyDoc_STR("__instancecheck__() -> bool\ncheck if an object is an instance")},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003192 {"__subclasscheck__", type___subclasscheck__, METH_O,
Benjamin Petersonfbe56bb2011-05-24 12:42:51 -05003193 PyDoc_STR("__subclasscheck__() -> bool\ncheck if a class is a subclass")},
Benjamin Peterson82b00c12011-05-24 11:09:06 -05003194 {"__dir__", type_dir, METH_NOARGS,
Benjamin Petersonc7284122011-05-24 12:46:15 -05003195 PyDoc_STR("__dir__() -> list\nspecialized __dir__ implementation for types")},
Martin v. Loewis4f2f3b62012-04-24 19:13:57 +02003196 {"__sizeof__", type_sizeof, METH_NOARGS,
3197 "__sizeof__() -> int\nreturn memory consumption of the type object"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003198 {0}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003199};
3200
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003201PyDoc_STRVAR(type_doc,
Larry Hastings5c661892014-01-24 06:17:25 -08003202/* this text signature cannot be accurate yet. will fix. --larry */
Larry Hastings2623c8c2014-02-08 22:15:29 -08003203"type(object_or_name, bases, dict)\n"
Tim Peters6d6c1a32001-08-02 04:15:00 +00003204"type(object) -> the object's type\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003205"type(name, bases, dict) -> a new type");
Tim Peters6d6c1a32001-08-02 04:15:00 +00003206
Guido van Rossum048eb752001-10-02 21:24:57 +00003207static int
3208type_traverse(PyTypeObject *type, visitproc visit, void *arg)
3209{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003210 /* Because of type_is_gc(), the collector only calls this
3211 for heaptypes. */
Antoine Pitrou1351ca62012-06-24 00:30:12 +02003212 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
3213 char msg[200];
3214 sprintf(msg, "type_traverse() called for non-heap type '%.100s'",
3215 type->tp_name);
3216 Py_FatalError(msg);
3217 }
Guido van Rossum048eb752001-10-02 21:24:57 +00003218
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003219 Py_VISIT(type->tp_dict);
3220 Py_VISIT(type->tp_cache);
3221 Py_VISIT(type->tp_mro);
3222 Py_VISIT(type->tp_bases);
3223 Py_VISIT(type->tp_base);
Guido van Rossuma3862092002-06-10 15:24:42 +00003224
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003225 /* There's no need to visit type->tp_subclasses or
3226 ((PyHeapTypeObject *)type)->ht_slots, because they can't be involved
3227 in cycles; tp_subclasses is a list of weak references,
3228 and slots is a tuple of strings. */
Guido van Rossum048eb752001-10-02 21:24:57 +00003229
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003230 return 0;
Guido van Rossum048eb752001-10-02 21:24:57 +00003231}
3232
3233static int
3234type_clear(PyTypeObject *type)
3235{
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003236 PyDictKeysObject *cached_keys;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003237 /* Because of type_is_gc(), the collector only calls this
3238 for heaptypes. */
3239 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00003240
Antoine Pitrou2e872082011-12-15 14:15:31 +01003241 /* We need to invalidate the method cache carefully before clearing
3242 the dict, so that other objects caught in a reference cycle
3243 don't start calling destroyed methods.
3244
3245 Otherwise, the only field we need to clear is tp_mro, which is
3246 part of a hard cycle (its first element is the class itself) that
3247 won't be broken otherwise (it's a tuple and tuples don't have a
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003248 tp_clear handler). None of the other fields need to be
3249 cleared, and here's why:
Guido van Rossum048eb752001-10-02 21:24:57 +00003250
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003251 tp_cache:
3252 Not used; if it were, it would be a dict.
Guido van Rossuma3862092002-06-10 15:24:42 +00003253
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003254 tp_bases, tp_base:
3255 If these are involved in a cycle, there must be at least
3256 one other, mutable object in the cycle, e.g. a base
3257 class's dict; the cycle will be broken that way.
Guido van Rossuma3862092002-06-10 15:24:42 +00003258
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003259 tp_subclasses:
Antoine Pitrou84745ab2013-10-29 21:31:25 +01003260 A dict of weak references can't be part of a cycle; and
3261 dicts have their own tp_clear.
Guido van Rossuma3862092002-06-10 15:24:42 +00003262
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003263 slots (in PyHeapTypeObject):
3264 A tuple of strings can't be part of a cycle.
3265 */
Guido van Rossuma3862092002-06-10 15:24:42 +00003266
Antoine Pitrou2e872082011-12-15 14:15:31 +01003267 PyType_Modified(type);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003268 cached_keys = ((PyHeapTypeObject *)type)->ht_cached_keys;
3269 if (cached_keys != NULL) {
3270 ((PyHeapTypeObject *)type)->ht_cached_keys = NULL;
3271 _PyDictKeys_DecRef(cached_keys);
3272 }
Antoine Pitrou2e872082011-12-15 14:15:31 +01003273 if (type->tp_dict)
3274 PyDict_Clear(type->tp_dict);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003275 Py_CLEAR(type->tp_mro);
Guido van Rossum048eb752001-10-02 21:24:57 +00003276
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003277 return 0;
Guido van Rossum048eb752001-10-02 21:24:57 +00003278}
3279
3280static int
3281type_is_gc(PyTypeObject *type)
3282{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003283 return type->tp_flags & Py_TPFLAGS_HEAPTYPE;
Guido van Rossum048eb752001-10-02 21:24:57 +00003284}
3285
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003286PyTypeObject PyType_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003287 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3288 "type", /* tp_name */
3289 sizeof(PyHeapTypeObject), /* tp_basicsize */
3290 sizeof(PyMemberDef), /* tp_itemsize */
3291 (destructor)type_dealloc, /* tp_dealloc */
3292 0, /* tp_print */
3293 0, /* tp_getattr */
3294 0, /* tp_setattr */
3295 0, /* tp_reserved */
3296 (reprfunc)type_repr, /* tp_repr */
3297 0, /* tp_as_number */
3298 0, /* tp_as_sequence */
3299 0, /* tp_as_mapping */
3300 0, /* tp_hash */
3301 (ternaryfunc)type_call, /* tp_call */
3302 0, /* tp_str */
3303 (getattrofunc)type_getattro, /* tp_getattro */
3304 (setattrofunc)type_setattro, /* tp_setattro */
3305 0, /* tp_as_buffer */
3306 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
3307 Py_TPFLAGS_BASETYPE | Py_TPFLAGS_TYPE_SUBCLASS, /* tp_flags */
3308 type_doc, /* tp_doc */
3309 (traverseproc)type_traverse, /* tp_traverse */
3310 (inquiry)type_clear, /* tp_clear */
3311 0, /* tp_richcompare */
3312 offsetof(PyTypeObject, tp_weaklist), /* tp_weaklistoffset */
3313 0, /* tp_iter */
3314 0, /* tp_iternext */
3315 type_methods, /* tp_methods */
3316 type_members, /* tp_members */
3317 type_getsets, /* tp_getset */
3318 0, /* tp_base */
3319 0, /* tp_dict */
3320 0, /* tp_descr_get */
3321 0, /* tp_descr_set */
3322 offsetof(PyTypeObject, tp_dict), /* tp_dictoffset */
3323 type_init, /* tp_init */
3324 0, /* tp_alloc */
3325 type_new, /* tp_new */
3326 PyObject_GC_Del, /* tp_free */
3327 (inquiry)type_is_gc, /* tp_is_gc */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003328};
Tim Peters6d6c1a32001-08-02 04:15:00 +00003329
3330
3331/* The base type of all types (eventually)... except itself. */
3332
Guido van Rossumd8faa362007-04-27 19:54:29 +00003333/* You may wonder why object.__new__() only complains about arguments
3334 when object.__init__() is not overridden, and vice versa.
3335
3336 Consider the use cases:
3337
3338 1. When neither is overridden, we want to hear complaints about
3339 excess (i.e., any) arguments, since their presence could
3340 indicate there's a bug.
3341
3342 2. When defining an Immutable type, we are likely to override only
3343 __new__(), since __init__() is called too late to initialize an
3344 Immutable object. Since __new__() defines the signature for the
3345 type, it would be a pain to have to override __init__() just to
3346 stop it from complaining about excess arguments.
3347
3348 3. When defining a Mutable type, we are likely to override only
3349 __init__(). So here the converse reasoning applies: we don't
3350 want to have to override __new__() just to stop it from
3351 complaining.
3352
3353 4. When __init__() is overridden, and the subclass __init__() calls
3354 object.__init__(), the latter should complain about excess
3355 arguments; ditto for __new__().
3356
3357 Use cases 2 and 3 make it unattractive to unconditionally check for
3358 excess arguments. The best solution that addresses all four use
3359 cases is as follows: __init__() complains about excess arguments
3360 unless __new__() is overridden and __init__() is not overridden
3361 (IOW, if __init__() is overridden or __new__() is not overridden);
3362 symmetrically, __new__() complains about excess arguments unless
3363 __init__() is overridden and __new__() is not overridden
3364 (IOW, if __new__() is overridden or __init__() is not overridden).
3365
3366 However, for backwards compatibility, this breaks too much code.
3367 Therefore, in 2.6, we'll *warn* about excess arguments when both
3368 methods are overridden; for all other cases we'll use the above
3369 rules.
3370
3371*/
3372
3373/* Forward */
3374static PyObject *
3375object_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
3376
3377static int
3378excess_args(PyObject *args, PyObject *kwds)
3379{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003380 return PyTuple_GET_SIZE(args) ||
3381 (kwds && PyDict_Check(kwds) && PyDict_Size(kwds));
Guido van Rossumd8faa362007-04-27 19:54:29 +00003382}
3383
Tim Peters6d6c1a32001-08-02 04:15:00 +00003384static int
3385object_init(PyObject *self, PyObject *args, PyObject *kwds)
3386{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003387 int err = 0;
Benjamin Peterson96384b92012-03-17 00:05:44 -05003388 PyTypeObject *type = Py_TYPE(self);
3389 if (excess_args(args, kwds) &&
3390 (type->tp_new == object_new || type->tp_init != object_init)) {
3391 PyErr_SetString(PyExc_TypeError, "object.__init__() takes no parameters");
3392 err = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003393 }
3394 return err;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003395}
3396
Guido van Rossum298e4212003-02-13 16:30:16 +00003397static PyObject *
3398object_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3399{
Benjamin Peterson96384b92012-03-17 00:05:44 -05003400 if (excess_args(args, kwds) &&
3401 (type->tp_init == object_init || type->tp_new != object_new)) {
R David Murray702a5dc2013-02-18 21:39:18 -05003402 PyErr_SetString(PyExc_TypeError, "object() takes no parameters");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003403 return NULL;
Benjamin Peterson96384b92012-03-17 00:05:44 -05003404 }
Victor Stinner3c1e4812012-03-26 22:10:51 +02003405
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003406 if (type->tp_flags & Py_TPFLAGS_IS_ABSTRACT) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003407 PyObject *abstract_methods = NULL;
3408 PyObject *builtins;
3409 PyObject *sorted;
3410 PyObject *sorted_methods = NULL;
3411 PyObject *joined = NULL;
Benjamin Peterson9a03ecf2012-03-16 20:15:54 -05003412 PyObject *comma;
3413 _Py_static_string(comma_id, ", ");
Victor Stinner3c1e4812012-03-26 22:10:51 +02003414 _Py_IDENTIFIER(sorted);
Christian Heimes9e7f1d22008-02-28 12:27:11 +00003415
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003416 /* Compute ", ".join(sorted(type.__abstractmethods__))
3417 into joined. */
3418 abstract_methods = type_abstractmethods(type, NULL);
3419 if (abstract_methods == NULL)
3420 goto error;
3421 builtins = PyEval_GetBuiltins();
3422 if (builtins == NULL)
3423 goto error;
Victor Stinner3c1e4812012-03-26 22:10:51 +02003424 sorted = _PyDict_GetItemId(builtins, &PyId_sorted);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003425 if (sorted == NULL)
3426 goto error;
3427 sorted_methods = PyObject_CallFunctionObjArgs(sorted,
3428 abstract_methods,
3429 NULL);
3430 if (sorted_methods == NULL)
3431 goto error;
Benjamin Peterson9a03ecf2012-03-16 20:15:54 -05003432 comma = _PyUnicode_FromId(&comma_id);
3433 if (comma == NULL)
3434 goto error;
3435 joined = PyUnicode_Join(comma, sorted_methods);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003436 if (joined == NULL)
3437 goto error;
Christian Heimes9e7f1d22008-02-28 12:27:11 +00003438
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003439 PyErr_Format(PyExc_TypeError,
3440 "Can't instantiate abstract class %s "
3441 "with abstract methods %U",
3442 type->tp_name,
3443 joined);
3444 error:
3445 Py_XDECREF(joined);
3446 Py_XDECREF(sorted_methods);
3447 Py_XDECREF(abstract_methods);
3448 return NULL;
3449 }
3450 return type->tp_alloc(type, 0);
Guido van Rossum298e4212003-02-13 16:30:16 +00003451}
3452
Tim Peters6d6c1a32001-08-02 04:15:00 +00003453static void
3454object_dealloc(PyObject *self)
3455{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003456 Py_TYPE(self)->tp_free(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003457}
3458
Guido van Rossum8e248182001-08-12 05:17:56 +00003459static PyObject *
3460object_repr(PyObject *self)
3461{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003462 PyTypeObject *type;
3463 PyObject *mod, *name, *rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00003464
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003465 type = Py_TYPE(self);
3466 mod = type_module(type, NULL);
3467 if (mod == NULL)
3468 PyErr_Clear();
3469 else if (!PyUnicode_Check(mod)) {
3470 Py_DECREF(mod);
3471 mod = NULL;
3472 }
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003473 name = type_qualname(type, NULL);
Christian Heimese81dc292012-09-10 16:57:36 +02003474 if (name == NULL) {
3475 Py_XDECREF(mod);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003476 return NULL;
Christian Heimese81dc292012-09-10 16:57:36 +02003477 }
Victor Stinnerbd303c12013-11-07 23:07:29 +01003478 if (mod != NULL && _PyUnicode_CompareWithId(mod, &PyId_builtins))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003479 rtn = PyUnicode_FromFormat("<%U.%U object at %p>", mod, name, self);
3480 else
3481 rtn = PyUnicode_FromFormat("<%s object at %p>",
3482 type->tp_name, self);
3483 Py_XDECREF(mod);
3484 Py_DECREF(name);
3485 return rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00003486}
3487
Guido van Rossumb8f63662001-08-15 23:57:02 +00003488static PyObject *
3489object_str(PyObject *self)
3490{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003491 unaryfunc f;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003492
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003493 f = Py_TYPE(self)->tp_repr;
Benjamin Peterson7b166872012-04-24 11:06:25 -04003494 if (f == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003495 f = object_repr;
3496 return f(self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003497}
3498
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003499static PyObject *
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003500object_richcompare(PyObject *self, PyObject *other, int op)
3501{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003502 PyObject *res;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003503
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003504 switch (op) {
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003505
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003506 case Py_EQ:
3507 /* Return NotImplemented instead of False, so if two
3508 objects are compared, both get a chance at the
3509 comparison. See issue #1393. */
3510 res = (self == other) ? Py_True : Py_NotImplemented;
3511 Py_INCREF(res);
3512 break;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003513
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003514 case Py_NE:
Serhiy Storchakaf4b7a022015-01-26 09:57:07 +02003515 /* By default, __ne__() delegates to __eq__() and inverts the result,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003516 unless the latter returns NotImplemented. */
Serhiy Storchakaf4b7a022015-01-26 09:57:07 +02003517 if (self->ob_type->tp_richcompare == NULL) {
3518 res = Py_NotImplemented;
3519 Py_INCREF(res);
3520 break;
3521 }
3522 res = (*self->ob_type->tp_richcompare)(self, other, Py_EQ);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003523 if (res != NULL && res != Py_NotImplemented) {
3524 int ok = PyObject_IsTrue(res);
3525 Py_DECREF(res);
3526 if (ok < 0)
3527 res = NULL;
3528 else {
3529 if (ok)
3530 res = Py_False;
3531 else
3532 res = Py_True;
3533 Py_INCREF(res);
3534 }
3535 }
3536 break;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003537
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003538 default:
3539 res = Py_NotImplemented;
3540 Py_INCREF(res);
3541 break;
3542 }
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003543
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003544 return res;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003545}
3546
3547static PyObject *
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003548object_get_class(PyObject *self, void *closure)
3549{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003550 Py_INCREF(Py_TYPE(self));
3551 return (PyObject *)(Py_TYPE(self));
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003552}
3553
3554static int
Benjamin Peterson9d4cbcc2015-01-30 13:33:42 -05003555compatible_with_tp_base(PyTypeObject *child)
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003556{
Benjamin Peterson9d4cbcc2015-01-30 13:33:42 -05003557 PyTypeObject *parent = child->tp_base;
3558 return (parent != NULL &&
3559 child->tp_basicsize == parent->tp_basicsize &&
3560 child->tp_itemsize == parent->tp_itemsize &&
3561 child->tp_dictoffset == parent->tp_dictoffset &&
3562 child->tp_weaklistoffset == parent->tp_weaklistoffset &&
3563 ((child->tp_flags & Py_TPFLAGS_HAVE_GC) ==
3564 (parent->tp_flags & Py_TPFLAGS_HAVE_GC)) &&
3565 (child->tp_dealloc == subtype_dealloc ||
3566 child->tp_dealloc == parent->tp_dealloc));
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003567}
3568
3569static int
3570same_slots_added(PyTypeObject *a, PyTypeObject *b)
3571{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003572 PyTypeObject *base = a->tp_base;
3573 Py_ssize_t size;
3574 PyObject *slots_a, *slots_b;
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003575
Benjamin Peterson67641d22011-01-17 19:24:34 +00003576 assert(base == b->tp_base);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003577 size = base->tp_basicsize;
3578 if (a->tp_dictoffset == size && b->tp_dictoffset == size)
3579 size += sizeof(PyObject *);
3580 if (a->tp_weaklistoffset == size && b->tp_weaklistoffset == size)
3581 size += sizeof(PyObject *);
Guido van Rossumd8faa362007-04-27 19:54:29 +00003582
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003583 /* Check slots compliance */
Benjamin Peterson9d4cbcc2015-01-30 13:33:42 -05003584 if (!(a->tp_flags & Py_TPFLAGS_HEAPTYPE) ||
3585 !(b->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
3586 return 0;
3587 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003588 slots_a = ((PyHeapTypeObject *)a)->ht_slots;
3589 slots_b = ((PyHeapTypeObject *)b)->ht_slots;
3590 if (slots_a && slots_b) {
3591 if (PyObject_RichCompareBool(slots_a, slots_b, Py_EQ) != 1)
3592 return 0;
3593 size += sizeof(PyObject *) * PyTuple_GET_SIZE(slots_a);
3594 }
3595 return size == a->tp_basicsize && size == b->tp_basicsize;
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003596}
3597
3598static int
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003599compatible_for_assignment(PyTypeObject* oldto, PyTypeObject* newto, char* attr)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003600{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003601 PyTypeObject *newbase, *oldbase;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003602
Benjamin Peterson9d4cbcc2015-01-30 13:33:42 -05003603 if (newto->tp_free != oldto->tp_free) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003604 PyErr_Format(PyExc_TypeError,
3605 "%s assignment: "
3606 "'%s' deallocator differs from '%s'",
3607 attr,
3608 newto->tp_name,
3609 oldto->tp_name);
3610 return 0;
3611 }
Benjamin Peterson9d4cbcc2015-01-30 13:33:42 -05003612 /*
3613 It's tricky to tell if two arbitrary types are sufficiently compatible as
3614 to be interchangeable; e.g., even if they have the same tp_basicsize, they
3615 might have totally different struct fields. It's much easier to tell if a
3616 type and its supertype are compatible; e.g., if they have the same
3617 tp_basicsize, then that means they have identical fields. So to check
3618 whether two arbitrary types are compatible, we first find the highest
3619 supertype that each is compatible with, and then if those supertypes are
3620 compatible then the original types must also be compatible.
3621 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003622 newbase = newto;
3623 oldbase = oldto;
Benjamin Peterson9d4cbcc2015-01-30 13:33:42 -05003624 while (compatible_with_tp_base(newbase))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003625 newbase = newbase->tp_base;
Benjamin Peterson9d4cbcc2015-01-30 13:33:42 -05003626 while (compatible_with_tp_base(oldbase))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003627 oldbase = oldbase->tp_base;
3628 if (newbase != oldbase &&
3629 (newbase->tp_base != oldbase->tp_base ||
3630 !same_slots_added(newbase, oldbase))) {
3631 PyErr_Format(PyExc_TypeError,
3632 "%s assignment: "
3633 "'%s' object layout differs from '%s'",
3634 attr,
3635 newto->tp_name,
3636 oldto->tp_name);
3637 return 0;
3638 }
Tim Petersea7f75d2002-12-07 21:39:16 +00003639
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003640 return 1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003641}
3642
3643static int
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003644object_set_class(PyObject *self, PyObject *value, void *closure)
3645{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003646 PyTypeObject *oldto = Py_TYPE(self);
3647 PyTypeObject *newto;
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003648
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003649 if (value == NULL) {
3650 PyErr_SetString(PyExc_TypeError,
3651 "can't delete __class__ attribute");
3652 return -1;
3653 }
3654 if (!PyType_Check(value)) {
3655 PyErr_Format(PyExc_TypeError,
Florent Xiclunaaa6c1d22011-12-12 18:54:29 +01003656 "__class__ must be set to a class, not '%s' object",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003657 Py_TYPE(value)->tp_name);
3658 return -1;
3659 }
3660 newto = (PyTypeObject *)value;
Guido van Rossum7d293ee2015-09-04 20:54:07 -07003661 /* In versions of CPython prior to 3.5, the code in
3662 compatible_for_assignment was not set up to correctly check for memory
3663 layout / slot / etc. compatibility for non-HEAPTYPE classes, so we just
3664 disallowed __class__ assignment in any case that wasn't HEAPTYPE ->
3665 HEAPTYPE.
3666
3667 During the 3.5 development cycle, we fixed the code in
3668 compatible_for_assignment to correctly check compatibility between
3669 arbitrary types, and started allowing __class__ assignment in all cases
3670 where the old and new types did in fact have compatible slots and
3671 memory layout (regardless of whether they were implemented as HEAPTYPEs
3672 or not).
3673
3674 Just before 3.5 was released, though, we discovered that this led to
3675 problems with immutable types like int, where the interpreter assumes
3676 they are immutable and interns some values. Formerly this wasn't a
3677 problem, because they really were immutable -- in particular, all the
3678 types where the interpreter applied this interning trick happened to
3679 also be statically allocated, so the old HEAPTYPE rules were
3680 "accidentally" stopping them from allowing __class__ assignment. But
3681 with the changes to __class__ assignment, we started allowing code like
3682
3683 class MyInt(int):
3684 ...
3685 # Modifies the type of *all* instances of 1 in the whole program,
3686 # including future instances (!), because the 1 object is interned.
3687 (1).__class__ = MyInt
3688
3689 (see https://bugs.python.org/issue24912).
3690
3691 In theory the proper fix would be to identify which classes rely on
3692 this invariant and somehow disallow __class__ assignment only for them,
3693 perhaps via some mechanism like a new Py_TPFLAGS_IMMUTABLE flag (a
3694 "blacklisting" approach). But in practice, since this problem wasn't
3695 noticed late in the 3.5 RC cycle, we're taking the conservative
3696 approach and reinstating the same HEAPTYPE->HEAPTYPE check that we used
3697 to have, plus a "whitelist". For now, the whitelist consists only of
3698 ModuleType subtypes, since those are the cases that motivated the patch
3699 in the first place -- see https://bugs.python.org/issue22986 -- and
3700 since module objects are mutable we can be sure that they are
3701 definitely not being interned. So now we allow HEAPTYPE->HEAPTYPE *or*
3702 ModuleType subtype -> ModuleType subtype.
3703
3704 So far as we know, all the code beyond the following 'if' statement
3705 will correctly handle non-HEAPTYPE classes, and the HEAPTYPE check is
3706 needed only to protect that subset of non-HEAPTYPE classes for which
3707 the interpreter has baked in the assumption that all instances are
3708 truly immutable.
3709 */
3710 if (!(PyType_IsSubtype(newto, &PyModule_Type) &&
3711 PyType_IsSubtype(oldto, &PyModule_Type)) &&
3712 (!(newto->tp_flags & Py_TPFLAGS_HEAPTYPE) ||
3713 !(oldto->tp_flags & Py_TPFLAGS_HEAPTYPE))) {
3714 PyErr_Format(PyExc_TypeError,
3715 "__class__ assignment only supported for heap types "
3716 "or ModuleType subclasses");
3717 return -1;
3718 }
3719
Christian Heimesde4d1832013-07-20 14:19:46 +02003720 if (compatible_for_assignment(oldto, newto, "__class__")) {
Benjamin Peterson9d4cbcc2015-01-30 13:33:42 -05003721 if (newto->tp_flags & Py_TPFLAGS_HEAPTYPE)
3722 Py_INCREF(newto);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003723 Py_TYPE(self) = newto;
Benjamin Peterson9d4cbcc2015-01-30 13:33:42 -05003724 if (oldto->tp_flags & Py_TPFLAGS_HEAPTYPE)
3725 Py_DECREF(oldto);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003726 return 0;
3727 }
3728 else {
3729 return -1;
3730 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003731}
3732
3733static PyGetSetDef object_getsets[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003734 {"__class__", object_get_class, object_set_class,
3735 PyDoc_STR("the object's class")},
3736 {0}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003737};
3738
Guido van Rossumc53f0092003-02-18 22:05:12 +00003739
Guido van Rossum036f9992003-02-21 22:02:54 +00003740/* Stuff to implement __reduce_ex__ for pickle protocols >= 2.
Alexandre Vassalottif7fa63d2008-05-11 08:55:36 +00003741 We fall back to helpers in copyreg for:
Guido van Rossum036f9992003-02-21 22:02:54 +00003742 - pickle protocols < 2
3743 - calculating the list of slot names (done only once per class)
3744 - the __newobj__ function (which is used as a token but never called)
3745*/
3746
3747static PyObject *
Alexandre Vassalottif7fa63d2008-05-11 08:55:36 +00003748import_copyreg(void)
Guido van Rossum036f9992003-02-21 22:02:54 +00003749{
Alexandre Vassalotti1a830702013-11-30 00:53:09 -08003750 PyObject *copyreg_str;
3751 PyObject *copyreg_module;
3752 PyInterpreterState *interp = PyThreadState_GET()->interp;
3753 _Py_IDENTIFIER(copyreg);
Guido van Rossum3926a632001-09-25 16:25:58 +00003754
Alexandre Vassalotti1a830702013-11-30 00:53:09 -08003755 copyreg_str = _PyUnicode_FromId(&PyId_copyreg);
3756 if (copyreg_str == NULL) {
3757 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003758 }
Alexandre Vassalotti1a830702013-11-30 00:53:09 -08003759 /* Try to fetch cached copy of copyreg from sys.modules first in an
3760 attempt to avoid the import overhead. Previously this was implemented
3761 by storing a reference to the cached module in a static variable, but
3762 this broke when multiple embeded interpreters were in use (see issue
3763 #17408 and #19088). */
3764 copyreg_module = PyDict_GetItemWithError(interp->modules, copyreg_str);
3765 if (copyreg_module != NULL) {
3766 Py_INCREF(copyreg_module);
3767 return copyreg_module;
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003768 }
Alexandre Vassalotti1a830702013-11-30 00:53:09 -08003769 if (PyErr_Occurred()) {
3770 return NULL;
3771 }
3772 return PyImport_Import(copyreg_str);
Guido van Rossum036f9992003-02-21 22:02:54 +00003773}
3774
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01003775Py_LOCAL(PyObject *)
3776_PyType_GetSlotNames(PyTypeObject *cls)
Guido van Rossum036f9992003-02-21 22:02:54 +00003777{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003778 PyObject *copyreg;
3779 PyObject *slotnames;
Victor Stinner3c1e4812012-03-26 22:10:51 +02003780 _Py_IDENTIFIER(__slotnames__);
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02003781 _Py_IDENTIFIER(_slotnames);
Guido van Rossum036f9992003-02-21 22:02:54 +00003782
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01003783 assert(PyType_Check(cls));
3784
3785 /* Get the slot names from the cache in the class if possible. */
3786 slotnames = _PyDict_GetItemIdWithError(cls->tp_dict, &PyId___slotnames__);
3787 if (slotnames != NULL) {
3788 if (slotnames != Py_None && !PyList_Check(slotnames)) {
3789 PyErr_Format(PyExc_TypeError,
3790 "%.200s.__slotnames__ should be a list or None, "
3791 "not %.200s",
3792 cls->tp_name, Py_TYPE(slotnames)->tp_name);
3793 return NULL;
3794 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003795 Py_INCREF(slotnames);
3796 return slotnames;
3797 }
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01003798 else {
3799 if (PyErr_Occurred()) {
3800 return NULL;
3801 }
3802 /* The class does not have the slot names cached yet. */
3803 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003804
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003805 copyreg = import_copyreg();
3806 if (copyreg == NULL)
3807 return NULL;
Guido van Rossum036f9992003-02-21 22:02:54 +00003808
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01003809 /* Use _slotnames function from the copyreg module to find the slots
3810 by this class and its bases. This function will cache the result
3811 in __slotnames__. */
3812 slotnames = _PyObject_CallMethodIdObjArgs(copyreg, &PyId__slotnames,
3813 cls, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003814 Py_DECREF(copyreg);
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01003815 if (slotnames == NULL)
3816 return NULL;
3817
3818 if (slotnames != Py_None && !PyList_Check(slotnames)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003819 PyErr_SetString(PyExc_TypeError,
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01003820 "copyreg._slotnames didn't return a list or None");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003821 Py_DECREF(slotnames);
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01003822 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003823 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003824
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003825 return slotnames;
Guido van Rossum036f9992003-02-21 22:02:54 +00003826}
3827
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01003828Py_LOCAL(PyObject *)
Serhiy Storchakaf81be8a2015-12-25 21:04:29 +02003829_PyObject_GetState(PyObject *obj, int required)
Guido van Rossum036f9992003-02-21 22:02:54 +00003830{
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01003831 PyObject *state;
3832 PyObject *getstate;
Victor Stinner3c1e4812012-03-26 22:10:51 +02003833 _Py_IDENTIFIER(__getstate__);
Guido van Rossum036f9992003-02-21 22:02:54 +00003834
Victor Stinner3c1e4812012-03-26 22:10:51 +02003835 getstate = _PyObject_GetAttrId(obj, &PyId___getstate__);
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01003836 if (getstate == NULL) {
3837 PyObject *slotnames;
3838
3839 if (!PyErr_ExceptionMatches(PyExc_AttributeError)) {
3840 return NULL;
3841 }
3842 PyErr_Clear();
3843
Serhiy Storchakaf81be8a2015-12-25 21:04:29 +02003844 if (required && obj->ob_type->tp_itemsize) {
3845 PyErr_Format(PyExc_TypeError,
3846 "can't pickle %.200s objects",
3847 Py_TYPE(obj)->tp_name);
3848 return NULL;
3849 }
3850
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01003851 {
3852 PyObject **dict;
3853 dict = _PyObject_GetDictPtr(obj);
Larry Hastings5c661892014-01-24 06:17:25 -08003854 /* It is possible that the object's dict is not initialized
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01003855 yet. In this case, we will return None for the state.
3856 We also return None if the dict is empty to make the behavior
3857 consistent regardless whether the dict was initialized or not.
3858 This make unit testing easier. */
3859 if (dict != NULL && *dict != NULL && PyDict_Size(*dict) > 0) {
3860 state = *dict;
3861 }
3862 else {
3863 state = Py_None;
3864 }
3865 Py_INCREF(state);
3866 }
3867
3868 slotnames = _PyType_GetSlotNames(Py_TYPE(obj));
3869 if (slotnames == NULL) {
3870 Py_DECREF(state);
3871 return NULL;
3872 }
3873
3874 assert(slotnames == Py_None || PyList_Check(slotnames));
3875 if (slotnames != Py_None && Py_SIZE(slotnames) > 0) {
3876 PyObject *slots;
3877 Py_ssize_t slotnames_size, i;
3878
3879 slots = PyDict_New();
3880 if (slots == NULL) {
3881 Py_DECREF(slotnames);
3882 Py_DECREF(state);
3883 return NULL;
3884 }
3885
3886 slotnames_size = Py_SIZE(slotnames);
3887 for (i = 0; i < slotnames_size; i++) {
3888 PyObject *name, *value;
3889
3890 name = PyList_GET_ITEM(slotnames, i);
Serhiy Storchakad28bb622015-11-25 18:33:29 +02003891 Py_INCREF(name);
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01003892 value = PyObject_GetAttr(obj, name);
3893 if (value == NULL) {
Serhiy Storchakad28bb622015-11-25 18:33:29 +02003894 Py_DECREF(name);
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01003895 if (!PyErr_ExceptionMatches(PyExc_AttributeError)) {
3896 goto error;
3897 }
3898 /* It is not an error if the attribute is not present. */
3899 PyErr_Clear();
3900 }
3901 else {
3902 int err = PyDict_SetItem(slots, name, value);
Serhiy Storchakad28bb622015-11-25 18:33:29 +02003903 Py_DECREF(name);
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01003904 Py_DECREF(value);
3905 if (err) {
3906 goto error;
3907 }
3908 }
3909
Martin Panter8f265652016-04-19 04:03:41 +00003910 /* The list is stored on the class so it may mutate while we
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01003911 iterate over it */
3912 if (slotnames_size != Py_SIZE(slotnames)) {
3913 PyErr_Format(PyExc_RuntimeError,
3914 "__slotsname__ changed size during iteration");
3915 goto error;
3916 }
3917
3918 /* We handle errors within the loop here. */
3919 if (0) {
3920 error:
3921 Py_DECREF(slotnames);
3922 Py_DECREF(slots);
3923 Py_DECREF(state);
3924 return NULL;
3925 }
3926 }
3927
3928 /* If we found some slot attributes, pack them in a tuple along
3929 the orginal attribute dictionary. */
3930 if (PyDict_Size(slots) > 0) {
3931 PyObject *state2;
3932
3933 state2 = PyTuple_Pack(2, state, slots);
3934 Py_DECREF(state);
3935 if (state2 == NULL) {
3936 Py_DECREF(slotnames);
3937 Py_DECREF(slots);
3938 return NULL;
3939 }
3940 state = state2;
3941 }
3942 Py_DECREF(slots);
3943 }
3944 Py_DECREF(slotnames);
3945 }
3946 else { /* getstate != NULL */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003947 state = PyObject_CallObject(getstate, NULL);
3948 Py_DECREF(getstate);
3949 if (state == NULL)
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01003950 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003951 }
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01003952
3953 return state;
3954}
3955
3956Py_LOCAL(int)
3957_PyObject_GetNewArguments(PyObject *obj, PyObject **args, PyObject **kwargs)
3958{
3959 PyObject *getnewargs, *getnewargs_ex;
3960 _Py_IDENTIFIER(__getnewargs_ex__);
3961 _Py_IDENTIFIER(__getnewargs__);
3962
3963 if (args == NULL || kwargs == NULL) {
3964 PyErr_BadInternalCall();
3965 return -1;
3966 }
3967
3968 /* We first attempt to fetch the arguments for __new__ by calling
3969 __getnewargs_ex__ on the object. */
Benjamin Petersone686c5c2014-02-16 13:49:16 -05003970 getnewargs_ex = _PyObject_LookupSpecial(obj, &PyId___getnewargs_ex__);
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01003971 if (getnewargs_ex != NULL) {
3972 PyObject *newargs = PyObject_CallObject(getnewargs_ex, NULL);
3973 Py_DECREF(getnewargs_ex);
3974 if (newargs == NULL) {
3975 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003976 }
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01003977 if (!PyTuple_Check(newargs)) {
3978 PyErr_Format(PyExc_TypeError,
3979 "__getnewargs_ex__ should return a tuple, "
3980 "not '%.200s'", Py_TYPE(newargs)->tp_name);
3981 Py_DECREF(newargs);
3982 return -1;
3983 }
3984 if (Py_SIZE(newargs) != 2) {
3985 PyErr_Format(PyExc_ValueError,
3986 "__getnewargs_ex__ should return a tuple of "
3987 "length 2, not %zd", Py_SIZE(newargs));
3988 Py_DECREF(newargs);
3989 return -1;
3990 }
3991 *args = PyTuple_GET_ITEM(newargs, 0);
3992 Py_INCREF(*args);
3993 *kwargs = PyTuple_GET_ITEM(newargs, 1);
3994 Py_INCREF(*kwargs);
3995 Py_DECREF(newargs);
3996
3997 /* XXX We should perhaps allow None to be passed here. */
3998 if (!PyTuple_Check(*args)) {
3999 PyErr_Format(PyExc_TypeError,
4000 "first item of the tuple returned by "
4001 "__getnewargs_ex__ must be a tuple, not '%.200s'",
4002 Py_TYPE(*args)->tp_name);
4003 Py_CLEAR(*args);
4004 Py_CLEAR(*kwargs);
4005 return -1;
4006 }
4007 if (!PyDict_Check(*kwargs)) {
4008 PyErr_Format(PyExc_TypeError,
4009 "second item of the tuple returned by "
4010 "__getnewargs_ex__ must be a dict, not '%.200s'",
4011 Py_TYPE(*kwargs)->tp_name);
4012 Py_CLEAR(*args);
4013 Py_CLEAR(*kwargs);
4014 return -1;
4015 }
4016 return 0;
Benjamin Petersone686c5c2014-02-16 13:49:16 -05004017 } else if (PyErr_Occurred()) {
4018 return -1;
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004019 }
4020
4021 /* The object does not have __getnewargs_ex__ so we fallback on using
4022 __getnewargs__ instead. */
Benjamin Petersone686c5c2014-02-16 13:49:16 -05004023 getnewargs = _PyObject_LookupSpecial(obj, &PyId___getnewargs__);
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004024 if (getnewargs != NULL) {
4025 *args = PyObject_CallObject(getnewargs, NULL);
4026 Py_DECREF(getnewargs);
4027 if (*args == NULL) {
4028 return -1;
4029 }
4030 if (!PyTuple_Check(*args)) {
4031 PyErr_Format(PyExc_TypeError,
4032 "__getnewargs__ should return a tuple, "
4033 "not '%.200s'", Py_TYPE(*args)->tp_name);
4034 Py_CLEAR(*args);
4035 return -1;
4036 }
4037 *kwargs = NULL;
4038 return 0;
Benjamin Petersone686c5c2014-02-16 13:49:16 -05004039 } else if (PyErr_Occurred()) {
4040 return -1;
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004041 }
4042
4043 /* The object does not have __getnewargs_ex__ and __getnewargs__. This may
Martin Panter8f265652016-04-19 04:03:41 +00004044 mean __new__ does not takes any arguments on this object, or that the
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004045 object does not implement the reduce protocol for pickling or
4046 copying. */
4047 *args = NULL;
4048 *kwargs = NULL;
4049 return 0;
4050}
4051
4052Py_LOCAL(int)
4053_PyObject_GetItemsIter(PyObject *obj, PyObject **listitems,
4054 PyObject **dictitems)
4055{
4056 if (listitems == NULL || dictitems == NULL) {
4057 PyErr_BadInternalCall();
4058 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004059 }
Guido van Rossum036f9992003-02-21 22:02:54 +00004060
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004061 if (!PyList_Check(obj)) {
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004062 *listitems = Py_None;
4063 Py_INCREF(*listitems);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004064 }
4065 else {
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004066 *listitems = PyObject_GetIter(obj);
Christian Heimes2489bd82013-11-23 21:19:43 +01004067 if (*listitems == NULL)
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004068 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004069 }
Guido van Rossum036f9992003-02-21 22:02:54 +00004070
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004071 if (!PyDict_Check(obj)) {
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004072 *dictitems = Py_None;
4073 Py_INCREF(*dictitems);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004074 }
4075 else {
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004076 PyObject *items;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02004077 _Py_IDENTIFIER(items);
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004078
4079 items = _PyObject_CallMethodIdObjArgs(obj, &PyId_items, NULL);
4080 if (items == NULL) {
4081 Py_CLEAR(*listitems);
4082 return -1;
4083 }
4084 *dictitems = PyObject_GetIter(items);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004085 Py_DECREF(items);
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004086 if (*dictitems == NULL) {
4087 Py_CLEAR(*listitems);
4088 return -1;
4089 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004090 }
Guido van Rossum036f9992003-02-21 22:02:54 +00004091
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004092 assert(*listitems != NULL && *dictitems != NULL);
4093
4094 return 0;
4095}
4096
4097static PyObject *
Serhiy Storchaka707b5cc2014-12-16 19:43:46 +02004098reduce_newobj(PyObject *obj, int proto)
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004099{
4100 PyObject *args = NULL, *kwargs = NULL;
4101 PyObject *copyreg;
4102 PyObject *newobj, *newargs, *state, *listitems, *dictitems;
4103 PyObject *result;
Serhiy Storchakaf81be8a2015-12-25 21:04:29 +02004104 int hasargs;
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004105
Serhiy Storchakad7a44152015-11-12 11:23:04 +02004106 if (Py_TYPE(obj)->tp_new == NULL) {
4107 PyErr_Format(PyExc_TypeError,
Serhiy Storchakaf81be8a2015-12-25 21:04:29 +02004108 "can't pickle %.200s objects",
Serhiy Storchakad7a44152015-11-12 11:23:04 +02004109 Py_TYPE(obj)->tp_name);
4110 return NULL;
4111 }
Serhiy Storchaka707b5cc2014-12-16 19:43:46 +02004112 if (_PyObject_GetNewArguments(obj, &args, &kwargs) < 0)
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004113 return NULL;
Serhiy Storchaka707b5cc2014-12-16 19:43:46 +02004114
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004115 copyreg = import_copyreg();
4116 if (copyreg == NULL) {
Serhiy Storchakaf81be8a2015-12-25 21:04:29 +02004117 Py_XDECREF(args);
Serhiy Storchaka707b5cc2014-12-16 19:43:46 +02004118 Py_XDECREF(kwargs);
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004119 return NULL;
4120 }
Serhiy Storchakaf81be8a2015-12-25 21:04:29 +02004121 hasargs = (args != NULL);
Serhiy Storchaka707b5cc2014-12-16 19:43:46 +02004122 if (kwargs == NULL || PyDict_Size(kwargs) == 0) {
4123 _Py_IDENTIFIER(__newobj__);
4124 PyObject *cls;
4125 Py_ssize_t i, n;
4126
4127 Py_XDECREF(kwargs);
4128 newobj = _PyObject_GetAttrId(copyreg, &PyId___newobj__);
4129 Py_DECREF(copyreg);
4130 if (newobj == NULL) {
Serhiy Storchakaf81be8a2015-12-25 21:04:29 +02004131 Py_XDECREF(args);
Serhiy Storchaka707b5cc2014-12-16 19:43:46 +02004132 return NULL;
4133 }
Serhiy Storchakaf81be8a2015-12-25 21:04:29 +02004134 n = args ? PyTuple_GET_SIZE(args) : 0;
Serhiy Storchaka707b5cc2014-12-16 19:43:46 +02004135 newargs = PyTuple_New(n+1);
4136 if (newargs == NULL) {
Serhiy Storchakaf81be8a2015-12-25 21:04:29 +02004137 Py_XDECREF(args);
Serhiy Storchaka707b5cc2014-12-16 19:43:46 +02004138 Py_DECREF(newobj);
4139 return NULL;
4140 }
4141 cls = (PyObject *) Py_TYPE(obj);
4142 Py_INCREF(cls);
4143 PyTuple_SET_ITEM(newargs, 0, cls);
4144 for (i = 0; i < n; i++) {
4145 PyObject *v = PyTuple_GET_ITEM(args, i);
4146 Py_INCREF(v);
4147 PyTuple_SET_ITEM(newargs, i+1, v);
4148 }
Serhiy Storchakaf81be8a2015-12-25 21:04:29 +02004149 Py_XDECREF(args);
Serhiy Storchaka707b5cc2014-12-16 19:43:46 +02004150 }
4151 else if (proto >= 4) {
4152 _Py_IDENTIFIER(__newobj_ex__);
4153
4154 newobj = _PyObject_GetAttrId(copyreg, &PyId___newobj_ex__);
4155 Py_DECREF(copyreg);
4156 if (newobj == NULL) {
4157 Py_DECREF(args);
4158 Py_DECREF(kwargs);
4159 return NULL;
4160 }
4161 newargs = PyTuple_Pack(3, Py_TYPE(obj), args, kwargs);
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004162 Py_DECREF(args);
4163 Py_DECREF(kwargs);
Serhiy Storchaka707b5cc2014-12-16 19:43:46 +02004164 if (newargs == NULL) {
4165 Py_DECREF(newobj);
4166 return NULL;
4167 }
4168 }
4169 else {
4170 PyErr_SetString(PyExc_ValueError,
4171 "must use protocol 4 or greater to copy this "
4172 "object; since __getnewargs_ex__ returned "
4173 "keyword arguments.");
4174 Py_DECREF(args);
4175 Py_DECREF(kwargs);
4176 Py_DECREF(copyreg);
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004177 return NULL;
4178 }
Serhiy Storchaka707b5cc2014-12-16 19:43:46 +02004179
Serhiy Storchakaf81be8a2015-12-25 21:04:29 +02004180 state = _PyObject_GetState(obj,
4181 !hasargs && !PyList_Check(obj) && !PyDict_Check(obj));
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004182 if (state == NULL) {
4183 Py_DECREF(newobj);
4184 Py_DECREF(newargs);
4185 return NULL;
4186 }
4187 if (_PyObject_GetItemsIter(obj, &listitems, &dictitems) < 0) {
4188 Py_DECREF(newobj);
4189 Py_DECREF(newargs);
4190 Py_DECREF(state);
4191 return NULL;
4192 }
4193
4194 result = PyTuple_Pack(5, newobj, newargs, state, listitems, dictitems);
4195 Py_DECREF(newobj);
4196 Py_DECREF(newargs);
4197 Py_DECREF(state);
4198 Py_DECREF(listitems);
4199 Py_DECREF(dictitems);
Larry Hastings5c661892014-01-24 06:17:25 -08004200 return result;
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004201}
4202
Guido van Rossumd8faa362007-04-27 19:54:29 +00004203/*
4204 * There were two problems when object.__reduce__ and object.__reduce_ex__
4205 * were implemented in the same function:
4206 * - trying to pickle an object with a custom __reduce__ method that
4207 * fell back to object.__reduce__ in certain circumstances led to
Yury Selivanovf488fb42015-07-03 01:04:23 -04004208 * infinite recursion at Python level and eventual RecursionError.
Guido van Rossumd8faa362007-04-27 19:54:29 +00004209 * - Pickling objects that lied about their type by overwriting the
4210 * __class__ descriptor could lead to infinite recursion at C level
4211 * and eventual segfault.
4212 *
4213 * Because of backwards compatibility, the two methods still have to
4214 * behave in the same way, even if this is not required by the pickle
4215 * protocol. This common functionality was moved to the _common_reduce
4216 * function.
4217 */
4218static PyObject *
4219_common_reduce(PyObject *self, int proto)
4220{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004221 PyObject *copyreg, *res;
Guido van Rossumd8faa362007-04-27 19:54:29 +00004222
Serhiy Storchaka707b5cc2014-12-16 19:43:46 +02004223 if (proto >= 2)
4224 return reduce_newobj(self, proto);
Guido van Rossumd8faa362007-04-27 19:54:29 +00004225
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004226 copyreg = import_copyreg();
4227 if (!copyreg)
4228 return NULL;
Guido van Rossumd8faa362007-04-27 19:54:29 +00004229
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004230 res = PyEval_CallMethod(copyreg, "_reduce_ex", "(Oi)", self, proto);
4231 Py_DECREF(copyreg);
Guido van Rossumd8faa362007-04-27 19:54:29 +00004232
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004233 return res;
Guido van Rossumd8faa362007-04-27 19:54:29 +00004234}
4235
4236static PyObject *
4237object_reduce(PyObject *self, PyObject *args)
4238{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004239 int proto = 0;
Guido van Rossumd8faa362007-04-27 19:54:29 +00004240
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004241 if (!PyArg_ParseTuple(args, "|i:__reduce__", &proto))
4242 return NULL;
Guido van Rossumd8faa362007-04-27 19:54:29 +00004243
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004244 return _common_reduce(self, proto);
Guido van Rossumd8faa362007-04-27 19:54:29 +00004245}
4246
Guido van Rossum036f9992003-02-21 22:02:54 +00004247static PyObject *
4248object_reduce_ex(PyObject *self, PyObject *args)
4249{
Victor Stinner3c1e4812012-03-26 22:10:51 +02004250 static PyObject *objreduce;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004251 PyObject *reduce, *res;
4252 int proto = 0;
Victor Stinner3c1e4812012-03-26 22:10:51 +02004253 _Py_IDENTIFIER(__reduce__);
Guido van Rossum036f9992003-02-21 22:02:54 +00004254
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004255 if (!PyArg_ParseTuple(args, "|i:__reduce_ex__", &proto))
4256 return NULL;
Guido van Rossum036f9992003-02-21 22:02:54 +00004257
Victor Stinner3c1e4812012-03-26 22:10:51 +02004258 if (objreduce == NULL) {
4259 objreduce = _PyDict_GetItemId(PyBaseObject_Type.tp_dict,
4260 &PyId___reduce__);
4261 if (objreduce == NULL)
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01004262 return NULL;
4263 }
4264
Victor Stinner3c1e4812012-03-26 22:10:51 +02004265 reduce = _PyObject_GetAttrId(self, &PyId___reduce__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004266 if (reduce == NULL)
4267 PyErr_Clear();
4268 else {
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01004269 PyObject *cls, *clsreduce;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004270 int override;
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01004271
4272 cls = (PyObject *) Py_TYPE(self);
Victor Stinner3c1e4812012-03-26 22:10:51 +02004273 clsreduce = _PyObject_GetAttrId(cls, &PyId___reduce__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004274 if (clsreduce == NULL) {
4275 Py_DECREF(reduce);
4276 return NULL;
4277 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004278 override = (clsreduce != objreduce);
4279 Py_DECREF(clsreduce);
4280 if (override) {
4281 res = PyObject_CallObject(reduce, NULL);
4282 Py_DECREF(reduce);
4283 return res;
4284 }
4285 else
4286 Py_DECREF(reduce);
4287 }
Guido van Rossum036f9992003-02-21 22:02:54 +00004288
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004289 return _common_reduce(self, proto);
Guido van Rossum3926a632001-09-25 16:25:58 +00004290}
4291
Christian Heimes9e7f1d22008-02-28 12:27:11 +00004292static PyObject *
4293object_subclasshook(PyObject *cls, PyObject *args)
4294{
Brian Curtindfc80e32011-08-10 20:28:54 -05004295 Py_RETURN_NOTIMPLEMENTED;
Christian Heimes9e7f1d22008-02-28 12:27:11 +00004296}
4297
4298PyDoc_STRVAR(object_subclasshook_doc,
4299"Abstract classes can override this to customize issubclass().\n"
4300"\n"
4301"This is invoked early on by abc.ABCMeta.__subclasscheck__().\n"
4302"It should return True, False or NotImplemented. If it returns\n"
4303"NotImplemented, the normal algorithm is used. Otherwise, it\n"
4304"overrides the normal algorithm (and the outcome is cached).\n");
Eric Smith8c663262007-08-25 02:26:07 +00004305
4306/*
4307 from PEP 3101, this code implements:
4308
4309 class object:
4310 def __format__(self, format_spec):
Serhiy Storchakad741a882015-06-11 00:06:39 +03004311 return format(str(self), format_spec)
Eric Smith8c663262007-08-25 02:26:07 +00004312*/
4313static PyObject *
4314object_format(PyObject *self, PyObject *args)
4315{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004316 PyObject *format_spec;
4317 PyObject *self_as_str = NULL;
4318 PyObject *result = NULL;
Eric Smith8c663262007-08-25 02:26:07 +00004319
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004320 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
4321 return NULL;
Eric Smith8c663262007-08-25 02:26:07 +00004322
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004323 self_as_str = PyObject_Str(self);
Eric Smithe4d63172010-09-13 20:48:43 +00004324 if (self_as_str != NULL) {
4325 /* Issue 7994: If we're converting to a string, we
Eric V. Smithb9cd3532011-03-12 10:08:48 -05004326 should reject format specifications */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004327 if (PyUnicode_GET_LENGTH(format_spec) > 0) {
Andrew Svetlov2cd8ce42012-12-23 14:27:17 +02004328 PyErr_SetString(PyExc_TypeError,
Eric V. Smithb9cd3532011-03-12 10:08:48 -05004329 "non-empty format string passed to object.__format__");
Andrew Svetlov2cd8ce42012-12-23 14:27:17 +02004330 goto done;
Eric V. Smithb9cd3532011-03-12 10:08:48 -05004331 }
Eric Smith8c663262007-08-25 02:26:07 +00004332
Eric V. Smithb9cd3532011-03-12 10:08:48 -05004333 result = PyObject_Format(self_as_str, format_spec);
Eric Smithe4d63172010-09-13 20:48:43 +00004334 }
4335
4336done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004337 Py_XDECREF(self_as_str);
Eric Smith8c663262007-08-25 02:26:07 +00004338
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004339 return result;
Eric Smith8c663262007-08-25 02:26:07 +00004340}
4341
Martin v. Löwis00709aa2008-06-04 14:18:43 +00004342static PyObject *
4343object_sizeof(PyObject *self, PyObject *args)
4344{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004345 Py_ssize_t res, isize;
Martin v. Löwis00709aa2008-06-04 14:18:43 +00004346
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004347 res = 0;
4348 isize = self->ob_type->tp_itemsize;
4349 if (isize > 0)
Antoine Pitroua6545102015-03-10 22:32:00 +01004350 res = Py_SIZE(self) * isize;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004351 res += self->ob_type->tp_basicsize;
Martin v. Löwis00709aa2008-06-04 14:18:43 +00004352
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004353 return PyLong_FromSsize_t(res);
Martin v. Löwis00709aa2008-06-04 14:18:43 +00004354}
4355
Benjamin Peterson82b00c12011-05-24 11:09:06 -05004356/* __dir__ for generic objects: returns __dict__, __class__,
4357 and recursively up the __class__.__bases__ chain.
4358*/
4359static PyObject *
4360object_dir(PyObject *self, PyObject *args)
4361{
4362 PyObject *result = NULL;
4363 PyObject *dict = NULL;
4364 PyObject *itsclass = NULL;
4365
4366 /* Get __dict__ (which may or may not be a real dict...) */
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02004367 dict = _PyObject_GetAttrId(self, &PyId___dict__);
Benjamin Peterson82b00c12011-05-24 11:09:06 -05004368 if (dict == NULL) {
4369 PyErr_Clear();
4370 dict = PyDict_New();
4371 }
4372 else if (!PyDict_Check(dict)) {
4373 Py_DECREF(dict);
4374 dict = PyDict_New();
4375 }
4376 else {
4377 /* Copy __dict__ to avoid mutating it. */
4378 PyObject *temp = PyDict_Copy(dict);
4379 Py_DECREF(dict);
4380 dict = temp;
4381 }
4382
4383 if (dict == NULL)
4384 goto error;
4385
4386 /* Merge in attrs reachable from its class. */
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02004387 itsclass = _PyObject_GetAttrId(self, &PyId___class__);
Benjamin Peterson82b00c12011-05-24 11:09:06 -05004388 if (itsclass == NULL)
4389 /* XXX(tomer): Perhaps fall back to obj->ob_type if no
4390 __class__ exists? */
4391 PyErr_Clear();
4392 else if (merge_class_dict(dict, itsclass) != 0)
4393 goto error;
4394
4395 result = PyDict_Keys(dict);
4396 /* fall through */
4397error:
4398 Py_XDECREF(itsclass);
4399 Py_XDECREF(dict);
4400 return result;
4401}
4402
Guido van Rossum3926a632001-09-25 16:25:58 +00004403static PyMethodDef object_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004404 {"__reduce_ex__", object_reduce_ex, METH_VARARGS,
4405 PyDoc_STR("helper for pickle")},
4406 {"__reduce__", object_reduce, METH_VARARGS,
4407 PyDoc_STR("helper for pickle")},
4408 {"__subclasshook__", object_subclasshook, METH_CLASS | METH_VARARGS,
4409 object_subclasshook_doc},
4410 {"__format__", object_format, METH_VARARGS,
4411 PyDoc_STR("default object formatter")},
4412 {"__sizeof__", object_sizeof, METH_NOARGS,
Benjamin Petersonfbe56bb2011-05-24 12:42:51 -05004413 PyDoc_STR("__sizeof__() -> int\nsize of object in memory, in bytes")},
Benjamin Peterson82b00c12011-05-24 11:09:06 -05004414 {"__dir__", object_dir, METH_NOARGS,
Benjamin Petersonc7284122011-05-24 12:46:15 -05004415 PyDoc_STR("__dir__() -> list\ndefault dir() implementation")},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004416 {0}
Guido van Rossum3926a632001-09-25 16:25:58 +00004417};
4418
Guido van Rossum036f9992003-02-21 22:02:54 +00004419
Tim Peters6d6c1a32001-08-02 04:15:00 +00004420PyTypeObject PyBaseObject_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004421 PyVarObject_HEAD_INIT(&PyType_Type, 0)
4422 "object", /* tp_name */
4423 sizeof(PyObject), /* tp_basicsize */
4424 0, /* tp_itemsize */
4425 object_dealloc, /* tp_dealloc */
4426 0, /* tp_print */
4427 0, /* tp_getattr */
4428 0, /* tp_setattr */
4429 0, /* tp_reserved */
4430 object_repr, /* tp_repr */
4431 0, /* tp_as_number */
4432 0, /* tp_as_sequence */
4433 0, /* tp_as_mapping */
4434 (hashfunc)_Py_HashPointer, /* tp_hash */
4435 0, /* tp_call */
4436 object_str, /* tp_str */
4437 PyObject_GenericGetAttr, /* tp_getattro */
4438 PyObject_GenericSetAttr, /* tp_setattro */
4439 0, /* tp_as_buffer */
Larry Hastings5c661892014-01-24 06:17:25 -08004440 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Larry Hastings2623c8c2014-02-08 22:15:29 -08004441 PyDoc_STR("object()\n--\n\nThe most base type"), /* tp_doc */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004442 0, /* tp_traverse */
4443 0, /* tp_clear */
4444 object_richcompare, /* tp_richcompare */
4445 0, /* tp_weaklistoffset */
4446 0, /* tp_iter */
4447 0, /* tp_iternext */
4448 object_methods, /* tp_methods */
4449 0, /* tp_members */
4450 object_getsets, /* tp_getset */
4451 0, /* tp_base */
4452 0, /* tp_dict */
4453 0, /* tp_descr_get */
4454 0, /* tp_descr_set */
4455 0, /* tp_dictoffset */
4456 object_init, /* tp_init */
4457 PyType_GenericAlloc, /* tp_alloc */
4458 object_new, /* tp_new */
4459 PyObject_Del, /* tp_free */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004460};
4461
4462
Guido van Rossum50e9fb92006-08-17 05:42:55 +00004463/* Add the methods from tp_methods to the __dict__ in a type object */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004464
4465static int
4466add_methods(PyTypeObject *type, PyMethodDef *meth)
4467{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004468 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004469
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004470 for (; meth->ml_name != NULL; meth++) {
4471 PyObject *descr;
Benjamin Peterson89a6e9a2012-05-08 09:22:24 -04004472 int err;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004473 if (PyDict_GetItemString(dict, meth->ml_name) &&
4474 !(meth->ml_flags & METH_COEXIST))
4475 continue;
4476 if (meth->ml_flags & METH_CLASS) {
4477 if (meth->ml_flags & METH_STATIC) {
4478 PyErr_SetString(PyExc_ValueError,
4479 "method cannot be both class and static");
4480 return -1;
4481 }
4482 descr = PyDescr_NewClassMethod(type, meth);
4483 }
4484 else if (meth->ml_flags & METH_STATIC) {
Andrew Svetlov3ba3a3e2012-12-25 13:32:35 +02004485 PyObject *cfunc = PyCFunction_NewEx(meth, (PyObject*)type, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004486 if (cfunc == NULL)
4487 return -1;
4488 descr = PyStaticMethod_New(cfunc);
4489 Py_DECREF(cfunc);
4490 }
4491 else {
4492 descr = PyDescr_NewMethod(type, meth);
4493 }
4494 if (descr == NULL)
4495 return -1;
Benjamin Peterson89a6e9a2012-05-08 09:22:24 -04004496 err = PyDict_SetItemString(dict, meth->ml_name, descr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004497 Py_DECREF(descr);
Benjamin Peterson89a6e9a2012-05-08 09:22:24 -04004498 if (err < 0)
4499 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004500 }
4501 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004502}
4503
4504static int
Guido van Rossum6f799372001-09-20 20:46:19 +00004505add_members(PyTypeObject *type, PyMemberDef *memb)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004506{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004507 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004508
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004509 for (; memb->name != NULL; memb++) {
4510 PyObject *descr;
4511 if (PyDict_GetItemString(dict, memb->name))
4512 continue;
4513 descr = PyDescr_NewMember(type, memb);
4514 if (descr == NULL)
4515 return -1;
Benjamin Peterson27007dc2016-07-06 23:26:32 -07004516 if (PyDict_SetItemString(dict, memb->name, descr) < 0) {
4517 Py_DECREF(descr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004518 return -1;
Benjamin Peterson27007dc2016-07-06 23:26:32 -07004519 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004520 Py_DECREF(descr);
4521 }
4522 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004523}
4524
4525static int
Guido van Rossum32d34c82001-09-20 21:45:26 +00004526add_getset(PyTypeObject *type, PyGetSetDef *gsp)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004527{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004528 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004529
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004530 for (; gsp->name != NULL; gsp++) {
4531 PyObject *descr;
4532 if (PyDict_GetItemString(dict, gsp->name))
4533 continue;
4534 descr = PyDescr_NewGetSet(type, gsp);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004535
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004536 if (descr == NULL)
4537 return -1;
Benjamin Peterson27007dc2016-07-06 23:26:32 -07004538 if (PyDict_SetItemString(dict, gsp->name, descr) < 0) {
4539 Py_DECREF(descr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004540 return -1;
Benjamin Peterson27007dc2016-07-06 23:26:32 -07004541 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004542 Py_DECREF(descr);
4543 }
4544 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004545}
4546
Guido van Rossum13d52f02001-08-10 21:24:08 +00004547static void
4548inherit_special(PyTypeObject *type, PyTypeObject *base)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004549{
Tim Peters6d6c1a32001-08-02 04:15:00 +00004550
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004551 /* Copying basicsize is connected to the GC flags */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004552 if (!(type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
4553 (base->tp_flags & Py_TPFLAGS_HAVE_GC) &&
4554 (!type->tp_traverse && !type->tp_clear)) {
4555 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
4556 if (type->tp_traverse == NULL)
4557 type->tp_traverse = base->tp_traverse;
4558 if (type->tp_clear == NULL)
4559 type->tp_clear = base->tp_clear;
4560 }
4561 {
4562 /* The condition below could use some explanation.
4563 It appears that tp_new is not inherited for static types
4564 whose base class is 'object'; this seems to be a precaution
4565 so that old extension types don't suddenly become
4566 callable (object.__new__ wouldn't insure the invariants
4567 that the extension type's own factory function ensures).
4568 Heap types, of course, are under our control, so they do
4569 inherit tp_new; static extension types that specify some
Florent Xiclunaaa6c1d22011-12-12 18:54:29 +01004570 other built-in type as the default also
4571 inherit object.__new__. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004572 if (base != &PyBaseObject_Type ||
4573 (type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
4574 if (type->tp_new == NULL)
4575 type->tp_new = base->tp_new;
4576 }
4577 }
Benjamin Petersona7465e22010-07-05 15:01:22 +00004578 if (type->tp_basicsize == 0)
4579 type->tp_basicsize = base->tp_basicsize;
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00004580
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004581 /* Copy other non-function slots */
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00004582
4583#undef COPYVAL
4584#define COPYVAL(SLOT) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004585 if (type->SLOT == 0) type->SLOT = base->SLOT
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00004586
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004587 COPYVAL(tp_itemsize);
4588 COPYVAL(tp_weaklistoffset);
4589 COPYVAL(tp_dictoffset);
Thomas Wouters27d517b2007-02-25 20:39:11 +00004590
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004591 /* Setup fast subclass flags */
4592 if (PyType_IsSubtype(base, (PyTypeObject*)PyExc_BaseException))
4593 type->tp_flags |= Py_TPFLAGS_BASE_EXC_SUBCLASS;
4594 else if (PyType_IsSubtype(base, &PyType_Type))
4595 type->tp_flags |= Py_TPFLAGS_TYPE_SUBCLASS;
4596 else if (PyType_IsSubtype(base, &PyLong_Type))
4597 type->tp_flags |= Py_TPFLAGS_LONG_SUBCLASS;
4598 else if (PyType_IsSubtype(base, &PyBytes_Type))
4599 type->tp_flags |= Py_TPFLAGS_BYTES_SUBCLASS;
4600 else if (PyType_IsSubtype(base, &PyUnicode_Type))
4601 type->tp_flags |= Py_TPFLAGS_UNICODE_SUBCLASS;
4602 else if (PyType_IsSubtype(base, &PyTuple_Type))
4603 type->tp_flags |= Py_TPFLAGS_TUPLE_SUBCLASS;
4604 else if (PyType_IsSubtype(base, &PyList_Type))
4605 type->tp_flags |= Py_TPFLAGS_LIST_SUBCLASS;
4606 else if (PyType_IsSubtype(base, &PyDict_Type))
4607 type->tp_flags |= Py_TPFLAGS_DICT_SUBCLASS;
Guido van Rossum13d52f02001-08-10 21:24:08 +00004608}
4609
Guido van Rossum38938152006-08-21 23:36:26 +00004610static int
Guido van Rossumf5243f02008-01-01 04:06:48 +00004611overrides_hash(PyTypeObject *type)
Guido van Rossum38938152006-08-21 23:36:26 +00004612{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004613 PyObject *dict = type->tp_dict;
Victor Stinner3c1e4812012-03-26 22:10:51 +02004614 _Py_IDENTIFIER(__eq__);
Guido van Rossum38938152006-08-21 23:36:26 +00004615
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004616 assert(dict != NULL);
Victor Stinner3c1e4812012-03-26 22:10:51 +02004617 if (_PyDict_GetItemId(dict, &PyId___eq__) != NULL)
4618 return 1;
4619 if (_PyDict_GetItemId(dict, &PyId___hash__) != NULL)
4620 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004621 return 0;
Guido van Rossum38938152006-08-21 23:36:26 +00004622}
4623
Guido van Rossum13d52f02001-08-10 21:24:08 +00004624static void
4625inherit_slots(PyTypeObject *type, PyTypeObject *base)
4626{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004627 PyTypeObject *basebase;
Guido van Rossum13d52f02001-08-10 21:24:08 +00004628
4629#undef SLOTDEFINED
Tim Peters6d6c1a32001-08-02 04:15:00 +00004630#undef COPYSLOT
4631#undef COPYNUM
4632#undef COPYSEQ
4633#undef COPYMAP
Guido van Rossum5af588b2001-10-12 14:13:21 +00004634#undef COPYBUF
Guido van Rossum13d52f02001-08-10 21:24:08 +00004635
4636#define SLOTDEFINED(SLOT) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004637 (base->SLOT != 0 && \
4638 (basebase == NULL || base->SLOT != basebase->SLOT))
Guido van Rossum13d52f02001-08-10 21:24:08 +00004639
Tim Peters6d6c1a32001-08-02 04:15:00 +00004640#define COPYSLOT(SLOT) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004641 if (!type->SLOT && SLOTDEFINED(SLOT)) type->SLOT = base->SLOT
Tim Peters6d6c1a32001-08-02 04:15:00 +00004642
Yury Selivanov75445082015-05-11 22:57:16 -04004643#define COPYASYNC(SLOT) COPYSLOT(tp_as_async->SLOT)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004644#define COPYNUM(SLOT) COPYSLOT(tp_as_number->SLOT)
4645#define COPYSEQ(SLOT) COPYSLOT(tp_as_sequence->SLOT)
4646#define COPYMAP(SLOT) COPYSLOT(tp_as_mapping->SLOT)
Tim Petersfc57ccb2001-10-12 02:38:24 +00004647#define COPYBUF(SLOT) COPYSLOT(tp_as_buffer->SLOT)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004648
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004649 /* This won't inherit indirect slots (from tp_as_number etc.)
4650 if type doesn't provide the space. */
Guido van Rossum13d52f02001-08-10 21:24:08 +00004651
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004652 if (type->tp_as_number != NULL && base->tp_as_number != NULL) {
4653 basebase = base->tp_base;
4654 if (basebase->tp_as_number == NULL)
4655 basebase = NULL;
4656 COPYNUM(nb_add);
4657 COPYNUM(nb_subtract);
4658 COPYNUM(nb_multiply);
4659 COPYNUM(nb_remainder);
4660 COPYNUM(nb_divmod);
4661 COPYNUM(nb_power);
4662 COPYNUM(nb_negative);
4663 COPYNUM(nb_positive);
4664 COPYNUM(nb_absolute);
4665 COPYNUM(nb_bool);
4666 COPYNUM(nb_invert);
4667 COPYNUM(nb_lshift);
4668 COPYNUM(nb_rshift);
4669 COPYNUM(nb_and);
4670 COPYNUM(nb_xor);
4671 COPYNUM(nb_or);
4672 COPYNUM(nb_int);
4673 COPYNUM(nb_float);
4674 COPYNUM(nb_inplace_add);
4675 COPYNUM(nb_inplace_subtract);
4676 COPYNUM(nb_inplace_multiply);
4677 COPYNUM(nb_inplace_remainder);
4678 COPYNUM(nb_inplace_power);
4679 COPYNUM(nb_inplace_lshift);
4680 COPYNUM(nb_inplace_rshift);
4681 COPYNUM(nb_inplace_and);
4682 COPYNUM(nb_inplace_xor);
4683 COPYNUM(nb_inplace_or);
4684 COPYNUM(nb_true_divide);
4685 COPYNUM(nb_floor_divide);
4686 COPYNUM(nb_inplace_true_divide);
4687 COPYNUM(nb_inplace_floor_divide);
4688 COPYNUM(nb_index);
Benjamin Petersond51374e2014-04-09 23:55:56 -04004689 COPYNUM(nb_matrix_multiply);
4690 COPYNUM(nb_inplace_matrix_multiply);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004691 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004692
Yury Selivanov75445082015-05-11 22:57:16 -04004693 if (type->tp_as_async != NULL && base->tp_as_async != NULL) {
4694 basebase = base->tp_base;
4695 if (basebase->tp_as_async == NULL)
4696 basebase = NULL;
4697 COPYASYNC(am_await);
4698 COPYASYNC(am_aiter);
4699 COPYASYNC(am_anext);
4700 }
4701
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004702 if (type->tp_as_sequence != NULL && base->tp_as_sequence != NULL) {
4703 basebase = base->tp_base;
4704 if (basebase->tp_as_sequence == NULL)
4705 basebase = NULL;
4706 COPYSEQ(sq_length);
4707 COPYSEQ(sq_concat);
4708 COPYSEQ(sq_repeat);
4709 COPYSEQ(sq_item);
4710 COPYSEQ(sq_ass_item);
4711 COPYSEQ(sq_contains);
4712 COPYSEQ(sq_inplace_concat);
4713 COPYSEQ(sq_inplace_repeat);
4714 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004715
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004716 if (type->tp_as_mapping != NULL && base->tp_as_mapping != NULL) {
4717 basebase = base->tp_base;
4718 if (basebase->tp_as_mapping == NULL)
4719 basebase = NULL;
4720 COPYMAP(mp_length);
4721 COPYMAP(mp_subscript);
4722 COPYMAP(mp_ass_subscript);
4723 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004724
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004725 if (type->tp_as_buffer != NULL && base->tp_as_buffer != NULL) {
4726 basebase = base->tp_base;
4727 if (basebase->tp_as_buffer == NULL)
4728 basebase = NULL;
4729 COPYBUF(bf_getbuffer);
4730 COPYBUF(bf_releasebuffer);
4731 }
Tim Petersfc57ccb2001-10-12 02:38:24 +00004732
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004733 basebase = base->tp_base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004734
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004735 COPYSLOT(tp_dealloc);
4736 if (type->tp_getattr == NULL && type->tp_getattro == NULL) {
4737 type->tp_getattr = base->tp_getattr;
4738 type->tp_getattro = base->tp_getattro;
4739 }
4740 if (type->tp_setattr == NULL && type->tp_setattro == NULL) {
4741 type->tp_setattr = base->tp_setattr;
4742 type->tp_setattro = base->tp_setattro;
4743 }
4744 /* tp_reserved is ignored */
4745 COPYSLOT(tp_repr);
4746 /* tp_hash see tp_richcompare */
4747 COPYSLOT(tp_call);
4748 COPYSLOT(tp_str);
4749 {
4750 /* Copy comparison-related slots only when
4751 not overriding them anywhere */
4752 if (type->tp_richcompare == NULL &&
4753 type->tp_hash == NULL &&
4754 !overrides_hash(type))
4755 {
4756 type->tp_richcompare = base->tp_richcompare;
4757 type->tp_hash = base->tp_hash;
4758 }
4759 }
4760 {
4761 COPYSLOT(tp_iter);
4762 COPYSLOT(tp_iternext);
4763 }
4764 {
4765 COPYSLOT(tp_descr_get);
4766 COPYSLOT(tp_descr_set);
4767 COPYSLOT(tp_dictoffset);
4768 COPYSLOT(tp_init);
4769 COPYSLOT(tp_alloc);
4770 COPYSLOT(tp_is_gc);
Antoine Pitrou796564c2013-07-30 19:59:21 +02004771 if ((type->tp_flags & Py_TPFLAGS_HAVE_FINALIZE) &&
4772 (base->tp_flags & Py_TPFLAGS_HAVE_FINALIZE)) {
4773 COPYSLOT(tp_finalize);
4774 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004775 if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) ==
4776 (base->tp_flags & Py_TPFLAGS_HAVE_GC)) {
4777 /* They agree about gc. */
4778 COPYSLOT(tp_free);
4779 }
4780 else if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
4781 type->tp_free == NULL &&
4782 base->tp_free == PyObject_Free) {
4783 /* A bit of magic to plug in the correct default
4784 * tp_free function when a derived class adds gc,
4785 * didn't define tp_free, and the base uses the
4786 * default non-gc tp_free.
4787 */
4788 type->tp_free = PyObject_GC_Del;
4789 }
4790 /* else they didn't agree about gc, and there isn't something
4791 * obvious to be done -- the type is on its own.
4792 */
4793 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004794}
4795
Jeremy Hylton938ace62002-07-17 16:30:39 +00004796static int add_operators(PyTypeObject *);
Guido van Rossum13d52f02001-08-10 21:24:08 +00004797
Tim Peters6d6c1a32001-08-02 04:15:00 +00004798int
Guido van Rossum528b7eb2001-08-07 17:24:28 +00004799PyType_Ready(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004800{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004801 PyObject *dict, *bases;
4802 PyTypeObject *base;
4803 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004804
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004805 if (type->tp_flags & Py_TPFLAGS_READY) {
4806 assert(type->tp_dict != NULL);
4807 return 0;
4808 }
4809 assert((type->tp_flags & Py_TPFLAGS_READYING) == 0);
Guido van Rossumd614f972001-08-10 17:39:49 +00004810
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004811 type->tp_flags |= Py_TPFLAGS_READYING;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004812
Tim Peters36eb4df2003-03-23 03:33:13 +00004813#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004814 /* PyType_Ready is the closest thing we have to a choke point
4815 * for type objects, so is the best place I can think of to try
4816 * to get type objects into the doubly-linked list of all objects.
4817 * Still, not all type objects go thru PyType_Ready.
4818 */
4819 _Py_AddToAllObjects((PyObject *)type, 0);
Tim Peters36eb4df2003-03-23 03:33:13 +00004820#endif
4821
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004822 /* Initialize tp_base (defaults to BaseObject unless that's us) */
4823 base = type->tp_base;
4824 if (base == NULL && type != &PyBaseObject_Type) {
4825 base = type->tp_base = &PyBaseObject_Type;
4826 Py_INCREF(base);
4827 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004828
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004829 /* Now the only way base can still be NULL is if type is
4830 * &PyBaseObject_Type.
4831 */
Guido van Rossum692cdbc2006-03-10 02:04:28 +00004832
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004833 /* Initialize the base class */
4834 if (base != NULL && base->tp_dict == NULL) {
4835 if (PyType_Ready(base) < 0)
4836 goto error;
4837 }
Guido van Rossum323a9cf2002-08-14 17:26:30 +00004838
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004839 /* Initialize ob_type if NULL. This means extensions that want to be
4840 compilable separately on Windows can call PyType_Ready() instead of
4841 initializing the ob_type field of their type objects. */
4842 /* The test for base != NULL is really unnecessary, since base is only
4843 NULL when type is &PyBaseObject_Type, and we know its ob_type is
4844 not NULL (it's initialized to &PyType_Type). But coverity doesn't
4845 know that. */
4846 if (Py_TYPE(type) == NULL && base != NULL)
4847 Py_TYPE(type) = Py_TYPE(base);
Guido van Rossum0986d822002-04-08 01:38:42 +00004848
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004849 /* Initialize tp_bases */
4850 bases = type->tp_bases;
4851 if (bases == NULL) {
4852 if (base == NULL)
4853 bases = PyTuple_New(0);
4854 else
4855 bases = PyTuple_Pack(1, base);
4856 if (bases == NULL)
4857 goto error;
4858 type->tp_bases = bases;
4859 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004860
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004861 /* Initialize tp_dict */
4862 dict = type->tp_dict;
4863 if (dict == NULL) {
4864 dict = PyDict_New();
4865 if (dict == NULL)
4866 goto error;
4867 type->tp_dict = dict;
4868 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004869
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004870 /* Add type-specific descriptors to tp_dict */
4871 if (add_operators(type) < 0)
4872 goto error;
4873 if (type->tp_methods != NULL) {
4874 if (add_methods(type, type->tp_methods) < 0)
4875 goto error;
4876 }
4877 if (type->tp_members != NULL) {
4878 if (add_members(type, type->tp_members) < 0)
4879 goto error;
4880 }
4881 if (type->tp_getset != NULL) {
4882 if (add_getset(type, type->tp_getset) < 0)
4883 goto error;
4884 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004885
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004886 /* Calculate method resolution order */
Benjamin Peterson104b9e02015-02-05 22:29:14 -05004887 if (mro_internal(type, NULL) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004888 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004889
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004890 /* Inherit special flags from dominant base */
4891 if (type->tp_base != NULL)
4892 inherit_special(type, type->tp_base);
Guido van Rossum13d52f02001-08-10 21:24:08 +00004893
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004894 /* Initialize tp_dict properly */
4895 bases = type->tp_mro;
4896 assert(bases != NULL);
4897 assert(PyTuple_Check(bases));
4898 n = PyTuple_GET_SIZE(bases);
4899 for (i = 1; i < n; i++) {
4900 PyObject *b = PyTuple_GET_ITEM(bases, i);
4901 if (PyType_Check(b))
4902 inherit_slots(type, (PyTypeObject *)b);
4903 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004904
Serhiy Storchakae09bcc82015-01-28 11:03:33 +02004905 /* All bases of statically allocated type should be statically allocated */
4906 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE))
4907 for (i = 0; i < n; i++) {
4908 PyObject *b = PyTuple_GET_ITEM(bases, i);
4909 if (PyType_Check(b) &&
4910 (((PyTypeObject *)b)->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
4911 PyErr_Format(PyExc_TypeError,
4912 "type '%.100s' is not dynamically allocated but "
4913 "its base type '%.100s' is dynamically allocated",
4914 type->tp_name, ((PyTypeObject *)b)->tp_name);
4915 goto error;
4916 }
4917 }
4918
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004919 /* Sanity check for tp_free. */
4920 if (PyType_IS_GC(type) && (type->tp_flags & Py_TPFLAGS_BASETYPE) &&
4921 (type->tp_free == NULL || type->tp_free == PyObject_Del)) {
4922 /* This base class needs to call tp_free, but doesn't have
4923 * one, or its tp_free is for non-gc'ed objects.
4924 */
4925 PyErr_Format(PyExc_TypeError, "type '%.100s' participates in "
4926 "gc and is a base type but has inappropriate "
4927 "tp_free slot",
4928 type->tp_name);
4929 goto error;
4930 }
Tim Peters3cfe7542003-05-21 21:29:48 +00004931
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004932 /* if the type dictionary doesn't contain a __doc__, set it from
4933 the tp_doc slot.
4934 */
Victor Stinner3c1e4812012-03-26 22:10:51 +02004935 if (_PyDict_GetItemId(type->tp_dict, &PyId___doc__) == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004936 if (type->tp_doc != NULL) {
Larry Hastings2623c8c2014-02-08 22:15:29 -08004937 const char *old_doc = _PyType_DocWithoutSignature(type->tp_name,
4938 type->tp_doc);
Larry Hastings5c661892014-01-24 06:17:25 -08004939 PyObject *doc = PyUnicode_FromString(old_doc);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004940 if (doc == NULL)
4941 goto error;
Victor Stinner5967bf42013-07-17 22:01:37 +02004942 if (_PyDict_SetItemId(type->tp_dict, &PyId___doc__, doc) < 0) {
4943 Py_DECREF(doc);
4944 goto error;
4945 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004946 Py_DECREF(doc);
4947 } else {
Victor Stinner5967bf42013-07-17 22:01:37 +02004948 if (_PyDict_SetItemId(type->tp_dict,
4949 &PyId___doc__, Py_None) < 0)
4950 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004951 }
4952 }
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00004953
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004954 /* Hack for tp_hash and __hash__.
4955 If after all that, tp_hash is still NULL, and __hash__ is not in
4956 tp_dict, set tp_hash to PyObject_HashNotImplemented and
4957 tp_dict['__hash__'] equal to None.
4958 This signals that __hash__ is not inherited.
4959 */
4960 if (type->tp_hash == NULL) {
Victor Stinner3c1e4812012-03-26 22:10:51 +02004961 if (_PyDict_GetItemId(type->tp_dict, &PyId___hash__) == NULL) {
4962 if (_PyDict_SetItemId(type->tp_dict, &PyId___hash__, Py_None) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004963 goto error;
4964 type->tp_hash = PyObject_HashNotImplemented;
4965 }
4966 }
Guido van Rossum38938152006-08-21 23:36:26 +00004967
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004968 /* Some more special stuff */
4969 base = type->tp_base;
4970 if (base != NULL) {
Yury Selivanov75445082015-05-11 22:57:16 -04004971 if (type->tp_as_async == NULL)
4972 type->tp_as_async = base->tp_as_async;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004973 if (type->tp_as_number == NULL)
4974 type->tp_as_number = base->tp_as_number;
4975 if (type->tp_as_sequence == NULL)
4976 type->tp_as_sequence = base->tp_as_sequence;
4977 if (type->tp_as_mapping == NULL)
4978 type->tp_as_mapping = base->tp_as_mapping;
4979 if (type->tp_as_buffer == NULL)
4980 type->tp_as_buffer = base->tp_as_buffer;
4981 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004982
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004983 /* Link into each base class's list of subclasses */
4984 bases = type->tp_bases;
4985 n = PyTuple_GET_SIZE(bases);
4986 for (i = 0; i < n; i++) {
4987 PyObject *b = PyTuple_GET_ITEM(bases, i);
4988 if (PyType_Check(b) &&
4989 add_subclass((PyTypeObject *)b, type) < 0)
4990 goto error;
4991 }
Guido van Rossum1c450732001-10-08 15:18:27 +00004992
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004993 /* All done -- set the ready flag */
4994 assert(type->tp_dict != NULL);
4995 type->tp_flags =
4996 (type->tp_flags & ~Py_TPFLAGS_READYING) | Py_TPFLAGS_READY;
4997 return 0;
Guido van Rossumd614f972001-08-10 17:39:49 +00004998
4999 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005000 type->tp_flags &= ~Py_TPFLAGS_READYING;
5001 return -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005002}
5003
Guido van Rossum1c450732001-10-08 15:18:27 +00005004static int
5005add_subclass(PyTypeObject *base, PyTypeObject *type)
5006{
Antoine Pitrou84745ab2013-10-29 21:31:25 +01005007 int result = -1;
5008 PyObject *dict, *key, *newobj;
Guido van Rossum1c450732001-10-08 15:18:27 +00005009
Antoine Pitrou84745ab2013-10-29 21:31:25 +01005010 dict = base->tp_subclasses;
5011 if (dict == NULL) {
5012 base->tp_subclasses = dict = PyDict_New();
5013 if (dict == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005014 return -1;
5015 }
Antoine Pitrou84745ab2013-10-29 21:31:25 +01005016 assert(PyDict_CheckExact(dict));
5017 key = PyLong_FromVoidPtr((void *) type);
5018 if (key == NULL)
Victor Stinner9812af82013-07-08 22:25:48 +02005019 return -1;
Antoine Pitrou84745ab2013-10-29 21:31:25 +01005020 newobj = PyWeakref_NewRef((PyObject *)type, NULL);
5021 if (newobj != NULL) {
5022 result = PyDict_SetItem(dict, key, newobj);
5023 Py_DECREF(newobj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005024 }
Antoine Pitrou84745ab2013-10-29 21:31:25 +01005025 Py_DECREF(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005026 return result;
Guido van Rossum1c450732001-10-08 15:18:27 +00005027}
5028
Benjamin Peterson104b9e02015-02-05 22:29:14 -05005029static int
5030add_all_subclasses(PyTypeObject *type, PyObject *bases)
5031{
5032 int res = 0;
5033
5034 if (bases) {
5035 Py_ssize_t i;
5036 for (i = 0; i < PyTuple_GET_SIZE(bases); i++) {
5037 PyObject *base = PyTuple_GET_ITEM(bases, i);
5038 if (PyType_Check(base) &&
5039 add_subclass((PyTypeObject*)base, type) < 0)
5040 res = -1;
5041 }
5042 }
5043
5044 return res;
5045}
5046
Michael W. Hudson98bbc492002-11-26 14:47:27 +00005047static void
5048remove_subclass(PyTypeObject *base, PyTypeObject *type)
5049{
Antoine Pitrou84745ab2013-10-29 21:31:25 +01005050 PyObject *dict, *key;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00005051
Antoine Pitrou84745ab2013-10-29 21:31:25 +01005052 dict = base->tp_subclasses;
5053 if (dict == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005054 return;
5055 }
Antoine Pitrou84745ab2013-10-29 21:31:25 +01005056 assert(PyDict_CheckExact(dict));
5057 key = PyLong_FromVoidPtr((void *) type);
5058 if (key == NULL || PyDict_DelItem(dict, key)) {
5059 /* This can happen if the type initialization errored out before
5060 the base subclasses were updated (e.g. a non-str __qualname__
5061 was passed in the type dict). */
5062 PyErr_Clear();
5063 }
5064 Py_XDECREF(key);
5065}
5066
5067static void
5068remove_all_subclasses(PyTypeObject *type, PyObject *bases)
5069{
5070 if (bases) {
5071 Py_ssize_t i;
5072 for (i = 0; i < PyTuple_GET_SIZE(bases); i++) {
5073 PyObject *base = PyTuple_GET_ITEM(bases, i);
5074 if (PyType_Check(base))
5075 remove_subclass((PyTypeObject*) base, type);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005076 }
5077 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +00005078}
Tim Peters6d6c1a32001-08-02 04:15:00 +00005079
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00005080static int
5081check_num_args(PyObject *ob, int n)
5082{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005083 if (!PyTuple_CheckExact(ob)) {
5084 PyErr_SetString(PyExc_SystemError,
5085 "PyArg_UnpackTuple() argument list is not a tuple");
5086 return 0;
5087 }
5088 if (n == PyTuple_GET_SIZE(ob))
5089 return 1;
5090 PyErr_Format(
5091 PyExc_TypeError,
5092 "expected %d arguments, got %zd", n, PyTuple_GET_SIZE(ob));
5093 return 0;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00005094}
5095
Tim Peters6d6c1a32001-08-02 04:15:00 +00005096/* Generic wrappers for overloadable 'operators' such as __getitem__ */
5097
5098/* There's a wrapper *function* for each distinct function typedef used
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005099 for type object slots (e.g. binaryfunc, ternaryfunc, etc.). There's a
Tim Peters6d6c1a32001-08-02 04:15:00 +00005100 wrapper *table* for each distinct operation (e.g. __len__, __add__).
5101 Most tables have only one entry; the tables for binary operators have two
5102 entries, one regular and one with reversed arguments. */
5103
5104static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00005105wrap_lenfunc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005106{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005107 lenfunc func = (lenfunc)wrapped;
5108 Py_ssize_t res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005109
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005110 if (!check_num_args(args, 0))
5111 return NULL;
5112 res = (*func)(self);
5113 if (res == -1 && PyErr_Occurred())
5114 return NULL;
5115 return PyLong_FromLong((long)res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005116}
5117
Tim Peters6d6c1a32001-08-02 04:15:00 +00005118static PyObject *
Raymond Hettingerf34f2642003-10-11 17:29:04 +00005119wrap_inquirypred(PyObject *self, PyObject *args, void *wrapped)
5120{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005121 inquiry func = (inquiry)wrapped;
5122 int res;
Raymond Hettingerf34f2642003-10-11 17:29:04 +00005123
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005124 if (!check_num_args(args, 0))
5125 return NULL;
5126 res = (*func)(self);
5127 if (res == -1 && PyErr_Occurred())
5128 return NULL;
5129 return PyBool_FromLong((long)res);
Raymond Hettingerf34f2642003-10-11 17:29:04 +00005130}
5131
5132static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00005133wrap_binaryfunc(PyObject *self, PyObject *args, void *wrapped)
5134{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005135 binaryfunc func = (binaryfunc)wrapped;
5136 PyObject *other;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005137
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005138 if (!check_num_args(args, 1))
5139 return NULL;
5140 other = PyTuple_GET_ITEM(args, 0);
5141 return (*func)(self, other);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005142}
5143
5144static PyObject *
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00005145wrap_binaryfunc_l(PyObject *self, PyObject *args, void *wrapped)
5146{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005147 binaryfunc func = (binaryfunc)wrapped;
5148 PyObject *other;
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00005149
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005150 if (!check_num_args(args, 1))
5151 return NULL;
5152 other = PyTuple_GET_ITEM(args, 0);
5153 return (*func)(self, other);
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00005154}
5155
5156static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00005157wrap_binaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
5158{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005159 binaryfunc func = (binaryfunc)wrapped;
5160 PyObject *other;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005161
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005162 if (!check_num_args(args, 1))
5163 return NULL;
5164 other = PyTuple_GET_ITEM(args, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005165 return (*func)(other, self);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005166}
5167
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00005168static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00005169wrap_ternaryfunc(PyObject *self, PyObject *args, void *wrapped)
5170{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005171 ternaryfunc func = (ternaryfunc)wrapped;
5172 PyObject *other;
5173 PyObject *third = Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005174
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005175 /* Note: This wrapper only works for __pow__() */
Tim Peters6d6c1a32001-08-02 04:15:00 +00005176
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005177 if (!PyArg_UnpackTuple(args, "", 1, 2, &other, &third))
5178 return NULL;
5179 return (*func)(self, other, third);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005180}
5181
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00005182static PyObject *
5183wrap_ternaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
5184{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005185 ternaryfunc func = (ternaryfunc)wrapped;
5186 PyObject *other;
5187 PyObject *third = Py_None;
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00005188
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005189 /* Note: This wrapper only works for __pow__() */
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00005190
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005191 if (!PyArg_UnpackTuple(args, "", 1, 2, &other, &third))
5192 return NULL;
5193 return (*func)(other, self, third);
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00005194}
5195
Tim Peters6d6c1a32001-08-02 04:15:00 +00005196static PyObject *
5197wrap_unaryfunc(PyObject *self, PyObject *args, void *wrapped)
5198{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005199 unaryfunc func = (unaryfunc)wrapped;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005200
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005201 if (!check_num_args(args, 0))
5202 return NULL;
5203 return (*func)(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005204}
5205
Tim Peters6d6c1a32001-08-02 04:15:00 +00005206static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00005207wrap_indexargfunc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005208{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005209 ssizeargfunc func = (ssizeargfunc)wrapped;
5210 PyObject* o;
5211 Py_ssize_t i;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005212
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005213 if (!PyArg_UnpackTuple(args, "", 1, 1, &o))
5214 return NULL;
5215 i = PyNumber_AsSsize_t(o, PyExc_OverflowError);
5216 if (i == -1 && PyErr_Occurred())
5217 return NULL;
5218 return (*func)(self, i);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005219}
5220
Martin v. Löwis18e16552006-02-15 17:27:45 +00005221static Py_ssize_t
Guido van Rossum5d815f32001-08-17 21:57:47 +00005222getindex(PyObject *self, PyObject *arg)
5223{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005224 Py_ssize_t i;
Guido van Rossum5d815f32001-08-17 21:57:47 +00005225
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005226 i = PyNumber_AsSsize_t(arg, PyExc_OverflowError);
5227 if (i == -1 && PyErr_Occurred())
5228 return -1;
5229 if (i < 0) {
5230 PySequenceMethods *sq = Py_TYPE(self)->tp_as_sequence;
5231 if (sq && sq->sq_length) {
5232 Py_ssize_t n = (*sq->sq_length)(self);
5233 if (n < 0)
5234 return -1;
5235 i += n;
5236 }
5237 }
5238 return i;
Guido van Rossum5d815f32001-08-17 21:57:47 +00005239}
5240
5241static PyObject *
5242wrap_sq_item(PyObject *self, PyObject *args, void *wrapped)
5243{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005244 ssizeargfunc func = (ssizeargfunc)wrapped;
5245 PyObject *arg;
5246 Py_ssize_t i;
Guido van Rossum5d815f32001-08-17 21:57:47 +00005247
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005248 if (PyTuple_GET_SIZE(args) == 1) {
5249 arg = PyTuple_GET_ITEM(args, 0);
5250 i = getindex(self, arg);
5251 if (i == -1 && PyErr_Occurred())
5252 return NULL;
5253 return (*func)(self, i);
5254 }
5255 check_num_args(args, 1);
5256 assert(PyErr_Occurred());
5257 return NULL;
Guido van Rossum5d815f32001-08-17 21:57:47 +00005258}
5259
Tim Peters6d6c1a32001-08-02 04:15:00 +00005260static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00005261wrap_sq_setitem(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005262{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005263 ssizeobjargproc func = (ssizeobjargproc)wrapped;
5264 Py_ssize_t i;
5265 int res;
5266 PyObject *arg, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005267
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005268 if (!PyArg_UnpackTuple(args, "", 2, 2, &arg, &value))
5269 return NULL;
5270 i = getindex(self, arg);
5271 if (i == -1 && PyErr_Occurred())
5272 return NULL;
5273 res = (*func)(self, i, value);
5274 if (res == -1 && PyErr_Occurred())
5275 return NULL;
5276 Py_INCREF(Py_None);
5277 return Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005278}
5279
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00005280static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00005281wrap_sq_delitem(PyObject *self, PyObject *args, void *wrapped)
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00005282{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005283 ssizeobjargproc func = (ssizeobjargproc)wrapped;
5284 Py_ssize_t i;
5285 int res;
5286 PyObject *arg;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00005287
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005288 if (!check_num_args(args, 1))
5289 return NULL;
5290 arg = PyTuple_GET_ITEM(args, 0);
5291 i = getindex(self, arg);
5292 if (i == -1 && PyErr_Occurred())
5293 return NULL;
5294 res = (*func)(self, i, NULL);
5295 if (res == -1 && PyErr_Occurred())
5296 return NULL;
5297 Py_INCREF(Py_None);
5298 return Py_None;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00005299}
5300
Tim Peters6d6c1a32001-08-02 04:15:00 +00005301/* XXX objobjproc is a misnomer; should be objargpred */
5302static PyObject *
5303wrap_objobjproc(PyObject *self, PyObject *args, void *wrapped)
5304{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005305 objobjproc func = (objobjproc)wrapped;
5306 int res;
5307 PyObject *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005308
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005309 if (!check_num_args(args, 1))
5310 return NULL;
5311 value = PyTuple_GET_ITEM(args, 0);
5312 res = (*func)(self, value);
5313 if (res == -1 && PyErr_Occurred())
5314 return NULL;
5315 else
5316 return PyBool_FromLong(res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005317}
5318
Tim Peters6d6c1a32001-08-02 04:15:00 +00005319static PyObject *
5320wrap_objobjargproc(PyObject *self, PyObject *args, void *wrapped)
5321{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005322 objobjargproc func = (objobjargproc)wrapped;
5323 int res;
5324 PyObject *key, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005325
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005326 if (!PyArg_UnpackTuple(args, "", 2, 2, &key, &value))
5327 return NULL;
5328 res = (*func)(self, key, 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 *
5336wrap_delitem(PyObject *self, PyObject *args, void *wrapped)
5337{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005338 objobjargproc func = (objobjargproc)wrapped;
5339 int res;
5340 PyObject *key;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00005341
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005342 if (!check_num_args(args, 1))
5343 return NULL;
5344 key = PyTuple_GET_ITEM(args, 0);
5345 res = (*func)(self, key, NULL);
5346 if (res == -1 && PyErr_Occurred())
5347 return NULL;
5348 Py_INCREF(Py_None);
5349 return Py_None;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00005350}
5351
Guido van Rossum4dcdb782003-04-14 21:46:03 +00005352/* Helper to check for object.__setattr__ or __delattr__ applied to a type.
Guido van Rossum52b27052003-04-15 20:05:10 +00005353 This is called the Carlo Verre hack after its discoverer. */
Guido van Rossum4dcdb782003-04-14 21:46:03 +00005354static int
5355hackcheck(PyObject *self, setattrofunc func, char *what)
5356{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005357 PyTypeObject *type = Py_TYPE(self);
5358 while (type && type->tp_flags & Py_TPFLAGS_HEAPTYPE)
5359 type = type->tp_base;
5360 /* If type is NULL now, this is a really weird type.
5361 In the spirit of backwards compatibility (?), just shut up. */
5362 if (type && type->tp_setattro != func) {
5363 PyErr_Format(PyExc_TypeError,
5364 "can't apply this %s to %s object",
5365 what,
5366 type->tp_name);
5367 return 0;
5368 }
5369 return 1;
Guido van Rossum4dcdb782003-04-14 21:46:03 +00005370}
5371
Tim Peters6d6c1a32001-08-02 04:15:00 +00005372static PyObject *
5373wrap_setattr(PyObject *self, PyObject *args, void *wrapped)
5374{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005375 setattrofunc func = (setattrofunc)wrapped;
5376 int res;
5377 PyObject *name, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005378
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005379 if (!PyArg_UnpackTuple(args, "", 2, 2, &name, &value))
5380 return NULL;
5381 if (!hackcheck(self, func, "__setattr__"))
5382 return NULL;
5383 res = (*func)(self, name, value);
5384 if (res < 0)
5385 return NULL;
5386 Py_INCREF(Py_None);
5387 return Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005388}
5389
5390static PyObject *
5391wrap_delattr(PyObject *self, PyObject *args, void *wrapped)
5392{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005393 setattrofunc func = (setattrofunc)wrapped;
5394 int res;
5395 PyObject *name;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005396
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005397 if (!check_num_args(args, 1))
5398 return NULL;
5399 name = PyTuple_GET_ITEM(args, 0);
5400 if (!hackcheck(self, func, "__delattr__"))
5401 return NULL;
5402 res = (*func)(self, name, NULL);
5403 if (res < 0)
5404 return NULL;
5405 Py_INCREF(Py_None);
5406 return Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005407}
5408
Tim Peters6d6c1a32001-08-02 04:15:00 +00005409static PyObject *
5410wrap_hashfunc(PyObject *self, PyObject *args, void *wrapped)
5411{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005412 hashfunc func = (hashfunc)wrapped;
Benjamin Peterson8035bc52010-10-23 16:20:50 +00005413 Py_hash_t res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005414
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005415 if (!check_num_args(args, 0))
5416 return NULL;
5417 res = (*func)(self);
5418 if (res == -1 && PyErr_Occurred())
5419 return NULL;
Benjamin Peterson8035bc52010-10-23 16:20:50 +00005420 return PyLong_FromSsize_t(res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005421}
5422
Tim Peters6d6c1a32001-08-02 04:15:00 +00005423static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00005424wrap_call(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005425{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005426 ternaryfunc func = (ternaryfunc)wrapped;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005427
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005428 return (*func)(self, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005429}
5430
Tim Peters6d6c1a32001-08-02 04:15:00 +00005431static PyObject *
Antoine Pitrou796564c2013-07-30 19:59:21 +02005432wrap_del(PyObject *self, PyObject *args, void *wrapped)
5433{
5434 destructor func = (destructor)wrapped;
5435
5436 if (!check_num_args(args, 0))
5437 return NULL;
5438
5439 (*func)(self);
5440 Py_RETURN_NONE;
5441}
5442
5443static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00005444wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op)
5445{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005446 richcmpfunc func = (richcmpfunc)wrapped;
5447 PyObject *other;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005448
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005449 if (!check_num_args(args, 1))
5450 return NULL;
5451 other = PyTuple_GET_ITEM(args, 0);
5452 return (*func)(self, other, op);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005453}
5454
5455#undef RICHCMP_WRAPPER
5456#define RICHCMP_WRAPPER(NAME, OP) \
5457static PyObject * \
5458richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \
5459{ \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005460 return wrap_richcmpfunc(self, args, wrapped, OP); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00005461}
5462
Jack Jansen8e938b42001-08-08 15:29:49 +00005463RICHCMP_WRAPPER(lt, Py_LT)
5464RICHCMP_WRAPPER(le, Py_LE)
5465RICHCMP_WRAPPER(eq, Py_EQ)
5466RICHCMP_WRAPPER(ne, Py_NE)
5467RICHCMP_WRAPPER(gt, Py_GT)
5468RICHCMP_WRAPPER(ge, Py_GE)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005469
Tim Peters6d6c1a32001-08-02 04:15:00 +00005470static PyObject *
5471wrap_next(PyObject *self, PyObject *args, void *wrapped)
5472{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005473 unaryfunc func = (unaryfunc)wrapped;
5474 PyObject *res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005475
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005476 if (!check_num_args(args, 0))
5477 return NULL;
5478 res = (*func)(self);
5479 if (res == NULL && !PyErr_Occurred())
5480 PyErr_SetNone(PyExc_StopIteration);
5481 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005482}
5483
Tim Peters6d6c1a32001-08-02 04:15:00 +00005484static PyObject *
5485wrap_descr_get(PyObject *self, PyObject *args, void *wrapped)
5486{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005487 descrgetfunc func = (descrgetfunc)wrapped;
5488 PyObject *obj;
5489 PyObject *type = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005490
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005491 if (!PyArg_UnpackTuple(args, "", 1, 2, &obj, &type))
5492 return NULL;
5493 if (obj == Py_None)
5494 obj = NULL;
5495 if (type == Py_None)
5496 type = NULL;
5497 if (type == NULL &&obj == NULL) {
5498 PyErr_SetString(PyExc_TypeError,
5499 "__get__(None, None) is invalid");
5500 return NULL;
5501 }
5502 return (*func)(self, obj, type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005503}
5504
Tim Peters6d6c1a32001-08-02 04:15:00 +00005505static PyObject *
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005506wrap_descr_set(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005507{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005508 descrsetfunc func = (descrsetfunc)wrapped;
5509 PyObject *obj, *value;
5510 int ret;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005511
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005512 if (!PyArg_UnpackTuple(args, "", 2, 2, &obj, &value))
5513 return NULL;
5514 ret = (*func)(self, obj, value);
5515 if (ret < 0)
5516 return NULL;
5517 Py_INCREF(Py_None);
5518 return Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005519}
Guido van Rossum22b13872002-08-06 21:41:44 +00005520
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00005521static PyObject *
5522wrap_descr_delete(PyObject *self, PyObject *args, void *wrapped)
5523{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005524 descrsetfunc func = (descrsetfunc)wrapped;
5525 PyObject *obj;
5526 int ret;
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00005527
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005528 if (!check_num_args(args, 1))
5529 return NULL;
5530 obj = PyTuple_GET_ITEM(args, 0);
5531 ret = (*func)(self, obj, NULL);
5532 if (ret < 0)
5533 return NULL;
5534 Py_INCREF(Py_None);
5535 return Py_None;
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00005536}
Tim Peters6d6c1a32001-08-02 04:15:00 +00005537
Tim Peters6d6c1a32001-08-02 04:15:00 +00005538static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00005539wrap_init(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005540{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005541 initproc func = (initproc)wrapped;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005542
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005543 if (func(self, args, kwds) < 0)
5544 return NULL;
5545 Py_INCREF(Py_None);
5546 return Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005547}
5548
Tim Peters6d6c1a32001-08-02 04:15:00 +00005549static PyObject *
Guido van Rossum0d231ed2001-08-06 16:50:37 +00005550tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005551{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005552 PyTypeObject *type, *subtype, *staticbase;
5553 PyObject *arg0, *res;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00005554
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005555 if (self == NULL || !PyType_Check(self))
5556 Py_FatalError("__new__() called with non-type 'self'");
5557 type = (PyTypeObject *)self;
5558 if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) {
5559 PyErr_Format(PyExc_TypeError,
5560 "%s.__new__(): not enough arguments",
5561 type->tp_name);
5562 return NULL;
5563 }
5564 arg0 = PyTuple_GET_ITEM(args, 0);
5565 if (!PyType_Check(arg0)) {
5566 PyErr_Format(PyExc_TypeError,
5567 "%s.__new__(X): X is not a type object (%s)",
5568 type->tp_name,
5569 Py_TYPE(arg0)->tp_name);
5570 return NULL;
5571 }
5572 subtype = (PyTypeObject *)arg0;
5573 if (!PyType_IsSubtype(subtype, type)) {
5574 PyErr_Format(PyExc_TypeError,
5575 "%s.__new__(%s): %s is not a subtype of %s",
5576 type->tp_name,
5577 subtype->tp_name,
5578 subtype->tp_name,
5579 type->tp_name);
5580 return NULL;
5581 }
Barry Warsaw60f01882001-08-22 19:24:42 +00005582
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005583 /* Check that the use doesn't do something silly and unsafe like
5584 object.__new__(dict). To do this, we check that the
5585 most derived base that's not a heap type is this type. */
5586 staticbase = subtype;
Martin v. Löwis9c564092012-06-23 23:20:45 +02005587 while (staticbase && (staticbase->tp_new == slot_tp_new))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005588 staticbase = staticbase->tp_base;
5589 /* If staticbase is NULL now, it is a really weird type.
5590 In the spirit of backwards compatibility (?), just shut up. */
5591 if (staticbase && staticbase->tp_new != type->tp_new) {
5592 PyErr_Format(PyExc_TypeError,
5593 "%s.__new__(%s) is not safe, use %s.__new__()",
5594 type->tp_name,
5595 subtype->tp_name,
Benjamin Petersone8239332014-11-26 23:03:11 -06005596 staticbase->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005597 return NULL;
5598 }
Barry Warsaw60f01882001-08-22 19:24:42 +00005599
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005600 args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
5601 if (args == NULL)
5602 return NULL;
5603 res = type->tp_new(subtype, args, kwds);
5604 Py_DECREF(args);
5605 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005606}
5607
Guido van Rossum0d231ed2001-08-06 16:50:37 +00005608static struct PyMethodDef tp_new_methoddef[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005609 {"__new__", (PyCFunction)tp_new_wrapper, METH_VARARGS|METH_KEYWORDS,
Larry Hastings2623c8c2014-02-08 22:15:29 -08005610 PyDoc_STR("__new__($type, *args, **kwargs)\n--\n\n"
Larry Hastings581ee362014-01-28 05:00:08 -08005611 "Create and return a new object. "
5612 "See help(type) for accurate signature.")},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005613 {0}
Tim Peters6d6c1a32001-08-02 04:15:00 +00005614};
5615
5616static int
Guido van Rossum0d231ed2001-08-06 16:50:37 +00005617add_tp_new_wrapper(PyTypeObject *type)
5618{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005619 PyObject *func;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00005620
Victor Stinner3c1e4812012-03-26 22:10:51 +02005621 if (_PyDict_GetItemId(type->tp_dict, &PyId___new__) != NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005622 return 0;
Andrew Svetlov3ba3a3e2012-12-25 13:32:35 +02005623 func = PyCFunction_NewEx(tp_new_methoddef, (PyObject *)type, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005624 if (func == NULL)
5625 return -1;
Victor Stinner3c1e4812012-03-26 22:10:51 +02005626 if (_PyDict_SetItemId(type->tp_dict, &PyId___new__, func)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005627 Py_DECREF(func);
5628 return -1;
5629 }
5630 Py_DECREF(func);
5631 return 0;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00005632}
5633
Guido van Rossumf040ede2001-08-07 16:40:56 +00005634/* Slot wrappers that call the corresponding __foo__ slot. See comments
5635 below at override_slots() for more explanation. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00005636
Guido van Rossumdc91b992001-08-08 22:26:22 +00005637#define SLOT0(FUNCNAME, OPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00005638static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00005639FUNCNAME(PyObject *self) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00005640{ \
Benjamin Petersonce798522012-01-22 11:24:29 -05005641 _Py_static_string(id, OPSTR); \
5642 return call_method(self, &id, "()"); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00005643}
5644
Guido van Rossumdc91b992001-08-08 22:26:22 +00005645#define SLOT1(FUNCNAME, OPSTR, ARG1TYPE, ARGCODES) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00005646static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00005647FUNCNAME(PyObject *self, ARG1TYPE arg1) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00005648{ \
Benjamin Petersonce798522012-01-22 11:24:29 -05005649 _Py_static_string(id, OPSTR); \
5650 return call_method(self, &id, "(" ARGCODES ")", arg1); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00005651}
5652
Guido van Rossumcd118802003-01-06 22:57:47 +00005653/* Boolean helper for SLOT1BINFULL().
5654 right.__class__ is a nontrivial subclass of left.__class__. */
5655static int
Victor Stinner3c1e4812012-03-26 22:10:51 +02005656method_is_overloaded(PyObject *left, PyObject *right, struct _Py_Identifier *name)
Guido van Rossumcd118802003-01-06 22:57:47 +00005657{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005658 PyObject *a, *b;
5659 int ok;
Guido van Rossumcd118802003-01-06 22:57:47 +00005660
Victor Stinner3c1e4812012-03-26 22:10:51 +02005661 b = _PyObject_GetAttrId((PyObject *)(Py_TYPE(right)), name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005662 if (b == NULL) {
5663 PyErr_Clear();
5664 /* If right doesn't have it, it's not overloaded */
5665 return 0;
5666 }
Guido van Rossumcd118802003-01-06 22:57:47 +00005667
Victor Stinner3c1e4812012-03-26 22:10:51 +02005668 a = _PyObject_GetAttrId((PyObject *)(Py_TYPE(left)), name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005669 if (a == NULL) {
5670 PyErr_Clear();
5671 Py_DECREF(b);
5672 /* If right has it but left doesn't, it's overloaded */
5673 return 1;
5674 }
Guido van Rossumcd118802003-01-06 22:57:47 +00005675
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005676 ok = PyObject_RichCompareBool(a, b, Py_NE);
5677 Py_DECREF(a);
5678 Py_DECREF(b);
5679 if (ok < 0) {
5680 PyErr_Clear();
5681 return 0;
5682 }
Guido van Rossumcd118802003-01-06 22:57:47 +00005683
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005684 return ok;
Guido van Rossumcd118802003-01-06 22:57:47 +00005685}
5686
Guido van Rossumdc91b992001-08-08 22:26:22 +00005687
5688#define SLOT1BINFULL(FUNCNAME, TESTFUNC, SLOTNAME, OPSTR, ROPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00005689static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00005690FUNCNAME(PyObject *self, PyObject *other) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00005691{ \
Benjamin Petersonce798522012-01-22 11:24:29 -05005692 _Py_static_string(op_id, OPSTR); \
5693 _Py_static_string(rop_id, ROPSTR); \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005694 int do_other = Py_TYPE(self) != Py_TYPE(other) && \
5695 Py_TYPE(other)->tp_as_number != NULL && \
5696 Py_TYPE(other)->tp_as_number->SLOTNAME == TESTFUNC; \
5697 if (Py_TYPE(self)->tp_as_number != NULL && \
5698 Py_TYPE(self)->tp_as_number->SLOTNAME == TESTFUNC) { \
5699 PyObject *r; \
5700 if (do_other && \
5701 PyType_IsSubtype(Py_TYPE(other), Py_TYPE(self)) && \
Victor Stinner3c1e4812012-03-26 22:10:51 +02005702 method_is_overloaded(self, other, &rop_id)) { \
Benjamin Petersonce798522012-01-22 11:24:29 -05005703 r = call_maybe(other, &rop_id, "(O)", self); \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005704 if (r != Py_NotImplemented) \
5705 return r; \
5706 Py_DECREF(r); \
5707 do_other = 0; \
5708 } \
Benjamin Petersonce798522012-01-22 11:24:29 -05005709 r = call_maybe(self, &op_id, "(O)", other); \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005710 if (r != Py_NotImplemented || \
5711 Py_TYPE(other) == Py_TYPE(self)) \
5712 return r; \
5713 Py_DECREF(r); \
5714 } \
5715 if (do_other) { \
Benjamin Petersonce798522012-01-22 11:24:29 -05005716 return call_maybe(other, &rop_id, "(O)", self); \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005717 } \
Brian Curtindfc80e32011-08-10 20:28:54 -05005718 Py_RETURN_NOTIMPLEMENTED; \
Guido van Rossumdc91b992001-08-08 22:26:22 +00005719}
5720
5721#define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005722 SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR)
Guido van Rossumdc91b992001-08-08 22:26:22 +00005723
5724#define SLOT2(FUNCNAME, OPSTR, ARG1TYPE, ARG2TYPE, ARGCODES) \
5725static PyObject * \
5726FUNCNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \
5727{ \
Benjamin Petersonce798522012-01-22 11:24:29 -05005728 _Py_static_string(id, #OPSTR); \
5729 return call_method(self, &id, "(" ARGCODES ")", arg1, arg2); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00005730}
5731
Martin v. Löwis18e16552006-02-15 17:27:45 +00005732static Py_ssize_t
Tim Peters6d6c1a32001-08-02 04:15:00 +00005733slot_sq_length(PyObject *self)
5734{
Benjamin Petersonce798522012-01-22 11:24:29 -05005735 PyObject *res = call_method(self, &PyId___len__, "()");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005736 Py_ssize_t len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005737
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005738 if (res == NULL)
5739 return -1;
5740 len = PyNumber_AsSsize_t(res, PyExc_OverflowError);
5741 Py_DECREF(res);
5742 if (len < 0) {
5743 if (!PyErr_Occurred())
5744 PyErr_SetString(PyExc_ValueError,
5745 "__len__() should return >= 0");
5746 return -1;
5747 }
5748 return len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005749}
5750
Guido van Rossumf4593e02001-10-03 12:09:30 +00005751/* Super-optimized version of slot_sq_item.
5752 Other slots could do the same... */
5753static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00005754slot_sq_item(PyObject *self, Py_ssize_t i)
Guido van Rossumf4593e02001-10-03 12:09:30 +00005755{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005756 PyObject *func, *args = NULL, *ival = NULL, *retval = NULL;
5757 descrgetfunc f;
Guido van Rossumf4593e02001-10-03 12:09:30 +00005758
Victor Stinner3c1e4812012-03-26 22:10:51 +02005759 func = _PyType_LookupId(Py_TYPE(self), &PyId___getitem__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005760 if (func != NULL) {
5761 if ((f = Py_TYPE(func)->tp_descr_get) == NULL)
5762 Py_INCREF(func);
5763 else {
5764 func = f(func, self, (PyObject *)(Py_TYPE(self)));
5765 if (func == NULL) {
5766 return NULL;
5767 }
5768 }
5769 ival = PyLong_FromSsize_t(i);
5770 if (ival != NULL) {
5771 args = PyTuple_New(1);
5772 if (args != NULL) {
5773 PyTuple_SET_ITEM(args, 0, ival);
5774 retval = PyObject_Call(func, args, NULL);
5775 Py_XDECREF(args);
5776 Py_XDECREF(func);
5777 return retval;
5778 }
5779 }
5780 }
5781 else {
Victor Stinner3c1e4812012-03-26 22:10:51 +02005782 PyObject *getitem_str = _PyUnicode_FromId(&PyId___getitem__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005783 PyErr_SetObject(PyExc_AttributeError, getitem_str);
5784 }
5785 Py_XDECREF(args);
5786 Py_XDECREF(ival);
5787 Py_XDECREF(func);
5788 return NULL;
Guido van Rossumf4593e02001-10-03 12:09:30 +00005789}
5790
Tim Peters6d6c1a32001-08-02 04:15:00 +00005791static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00005792slot_sq_ass_item(PyObject *self, Py_ssize_t index, PyObject *value)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005793{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005794 PyObject *res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005795
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005796 if (value == NULL)
Benjamin Petersonce798522012-01-22 11:24:29 -05005797 res = call_method(self, &PyId___delitem__, "(n)", index);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005798 else
Benjamin Petersonce798522012-01-22 11:24:29 -05005799 res = call_method(self, &PyId___setitem__, "(nO)", index, value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005800 if (res == NULL)
5801 return -1;
5802 Py_DECREF(res);
5803 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005804}
5805
5806static int
Tim Peters6d6c1a32001-08-02 04:15:00 +00005807slot_sq_contains(PyObject *self, PyObject *value)
5808{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005809 PyObject *func, *res, *args;
5810 int result = -1;
Benjamin Petersonce798522012-01-22 11:24:29 -05005811 _Py_IDENTIFIER(__contains__);
Tim Petersbf9b2442003-03-23 05:35:36 +00005812
Benjamin Petersonce798522012-01-22 11:24:29 -05005813 func = lookup_maybe(self, &PyId___contains__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005814 if (func != NULL) {
5815 args = PyTuple_Pack(1, value);
5816 if (args == NULL)
5817 res = NULL;
5818 else {
5819 res = PyObject_Call(func, args, NULL);
5820 Py_DECREF(args);
5821 }
5822 Py_DECREF(func);
5823 if (res != NULL) {
5824 result = PyObject_IsTrue(res);
5825 Py_DECREF(res);
5826 }
5827 }
5828 else if (! PyErr_Occurred()) {
5829 /* Possible results: -1 and 1 */
5830 result = (int)_PySequence_IterSearch(self, value,
5831 PY_ITERSEARCH_CONTAINS);
5832 }
5833 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005834}
5835
Tim Peters6d6c1a32001-08-02 04:15:00 +00005836#define slot_mp_length slot_sq_length
5837
Guido van Rossumdc91b992001-08-08 22:26:22 +00005838SLOT1(slot_mp_subscript, "__getitem__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00005839
5840static int
5841slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value)
5842{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005843 PyObject *res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005844
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005845 if (value == NULL)
Benjamin Petersonce798522012-01-22 11:24:29 -05005846 res = call_method(self, &PyId___delitem__, "(O)", key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005847 else
Benjamin Petersonce798522012-01-22 11:24:29 -05005848 res = call_method(self, &PyId___setitem__, "(OO)", key, value);
5849
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005850 if (res == NULL)
5851 return -1;
5852 Py_DECREF(res);
5853 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005854}
5855
Guido van Rossumdc91b992001-08-08 22:26:22 +00005856SLOT1BIN(slot_nb_add, nb_add, "__add__", "__radd__")
5857SLOT1BIN(slot_nb_subtract, nb_subtract, "__sub__", "__rsub__")
5858SLOT1BIN(slot_nb_multiply, nb_multiply, "__mul__", "__rmul__")
Benjamin Petersond51374e2014-04-09 23:55:56 -04005859SLOT1BIN(slot_nb_matrix_multiply, nb_matrix_multiply, "__matmul__", "__rmatmul__")
Guido van Rossumdc91b992001-08-08 22:26:22 +00005860SLOT1BIN(slot_nb_remainder, nb_remainder, "__mod__", "__rmod__")
5861SLOT1BIN(slot_nb_divmod, nb_divmod, "__divmod__", "__rdivmod__")
5862
Jeremy Hylton938ace62002-07-17 16:30:39 +00005863static PyObject *slot_nb_power(PyObject *, PyObject *, PyObject *);
Guido van Rossumdc91b992001-08-08 22:26:22 +00005864
5865SLOT1BINFULL(slot_nb_power_binary, slot_nb_power,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005866 nb_power, "__pow__", "__rpow__")
Guido van Rossumdc91b992001-08-08 22:26:22 +00005867
5868static PyObject *
5869slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus)
5870{
Benjamin Petersonce798522012-01-22 11:24:29 -05005871 _Py_IDENTIFIER(__pow__);
Guido van Rossum2730b132001-08-28 18:22:14 +00005872
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005873 if (modulus == Py_None)
5874 return slot_nb_power_binary(self, other);
5875 /* Three-arg power doesn't use __rpow__. But ternary_op
5876 can call this when the second argument's type uses
5877 slot_nb_power, so check before calling self.__pow__. */
5878 if (Py_TYPE(self)->tp_as_number != NULL &&
5879 Py_TYPE(self)->tp_as_number->nb_power == slot_nb_power) {
Benjamin Petersonce798522012-01-22 11:24:29 -05005880 return call_method(self, &PyId___pow__, "(OO)", other, modulus);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005881 }
Brian Curtindfc80e32011-08-10 20:28:54 -05005882 Py_RETURN_NOTIMPLEMENTED;
Guido van Rossumdc91b992001-08-08 22:26:22 +00005883}
5884
5885SLOT0(slot_nb_negative, "__neg__")
5886SLOT0(slot_nb_positive, "__pos__")
5887SLOT0(slot_nb_absolute, "__abs__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00005888
5889static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00005890slot_nb_bool(PyObject *self)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005891{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005892 PyObject *func, *args;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005893 int result = -1;
5894 int using_len = 0;
Benjamin Petersonce798522012-01-22 11:24:29 -05005895 _Py_IDENTIFIER(__bool__);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005896
Benjamin Petersonce798522012-01-22 11:24:29 -05005897 func = lookup_maybe(self, &PyId___bool__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005898 if (func == NULL) {
5899 if (PyErr_Occurred())
5900 return -1;
Benjamin Petersonce798522012-01-22 11:24:29 -05005901 func = lookup_maybe(self, &PyId___len__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005902 if (func == NULL)
5903 return PyErr_Occurred() ? -1 : 1;
5904 using_len = 1;
5905 }
5906 args = PyTuple_New(0);
5907 if (args != NULL) {
5908 PyObject *temp = PyObject_Call(func, args, NULL);
5909 Py_DECREF(args);
5910 if (temp != NULL) {
5911 if (using_len) {
5912 /* enforced by slot_nb_len */
5913 result = PyObject_IsTrue(temp);
5914 }
5915 else if (PyBool_Check(temp)) {
5916 result = PyObject_IsTrue(temp);
5917 }
5918 else {
5919 PyErr_Format(PyExc_TypeError,
5920 "__bool__ should return "
5921 "bool, returned %s",
5922 Py_TYPE(temp)->tp_name);
5923 result = -1;
5924 }
5925 Py_DECREF(temp);
5926 }
5927 }
5928 Py_DECREF(func);
5929 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005930}
5931
Guido van Rossum38fff8c2006-03-07 18:50:55 +00005932
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00005933static PyObject *
Guido van Rossum38fff8c2006-03-07 18:50:55 +00005934slot_nb_index(PyObject *self)
5935{
Benjamin Petersonce798522012-01-22 11:24:29 -05005936 _Py_IDENTIFIER(__index__);
5937 return call_method(self, &PyId___index__, "()");
Guido van Rossum38fff8c2006-03-07 18:50:55 +00005938}
5939
5940
Guido van Rossumdc91b992001-08-08 22:26:22 +00005941SLOT0(slot_nb_invert, "__invert__")
5942SLOT1BIN(slot_nb_lshift, nb_lshift, "__lshift__", "__rlshift__")
5943SLOT1BIN(slot_nb_rshift, nb_rshift, "__rshift__", "__rrshift__")
5944SLOT1BIN(slot_nb_and, nb_and, "__and__", "__rand__")
5945SLOT1BIN(slot_nb_xor, nb_xor, "__xor__", "__rxor__")
5946SLOT1BIN(slot_nb_or, nb_or, "__or__", "__ror__")
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00005947
Guido van Rossumdc91b992001-08-08 22:26:22 +00005948SLOT0(slot_nb_int, "__int__")
Guido van Rossumdc91b992001-08-08 22:26:22 +00005949SLOT0(slot_nb_float, "__float__")
Guido van Rossumdc91b992001-08-08 22:26:22 +00005950SLOT1(slot_nb_inplace_add, "__iadd__", PyObject *, "O")
5951SLOT1(slot_nb_inplace_subtract, "__isub__", PyObject *, "O")
5952SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *, "O")
Benjamin Petersond51374e2014-04-09 23:55:56 -04005953SLOT1(slot_nb_inplace_matrix_multiply, "__imatmul__", PyObject *, "O")
Guido van Rossumdc91b992001-08-08 22:26:22 +00005954SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *, "O")
Thomas Wouterscf297e42007-02-23 15:07:44 +00005955/* Can't use SLOT1 here, because nb_inplace_power is ternary */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005956static PyObject *
5957slot_nb_inplace_power(PyObject *self, PyObject * arg1, PyObject *arg2)
5958{
Benjamin Petersonce798522012-01-22 11:24:29 -05005959 _Py_IDENTIFIER(__ipow__);
5960 return call_method(self, &PyId___ipow__, "(" "O" ")", arg1);
Thomas Wouterscf297e42007-02-23 15:07:44 +00005961}
Guido van Rossumdc91b992001-08-08 22:26:22 +00005962SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *, "O")
5963SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *, "O")
5964SLOT1(slot_nb_inplace_and, "__iand__", PyObject *, "O")
5965SLOT1(slot_nb_inplace_xor, "__ixor__", PyObject *, "O")
5966SLOT1(slot_nb_inplace_or, "__ior__", PyObject *, "O")
5967SLOT1BIN(slot_nb_floor_divide, nb_floor_divide,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005968 "__floordiv__", "__rfloordiv__")
Guido van Rossumdc91b992001-08-08 22:26:22 +00005969SLOT1BIN(slot_nb_true_divide, nb_true_divide, "__truediv__", "__rtruediv__")
5970SLOT1(slot_nb_inplace_floor_divide, "__ifloordiv__", PyObject *, "O")
5971SLOT1(slot_nb_inplace_true_divide, "__itruediv__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00005972
Guido van Rossumb8f63662001-08-15 23:57:02 +00005973static PyObject *
5974slot_tp_repr(PyObject *self)
5975{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005976 PyObject *func, *res;
Benjamin Petersonce798522012-01-22 11:24:29 -05005977 _Py_IDENTIFIER(__repr__);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005978
Benjamin Petersonce798522012-01-22 11:24:29 -05005979 func = lookup_method(self, &PyId___repr__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005980 if (func != NULL) {
5981 res = PyEval_CallObject(func, NULL);
5982 Py_DECREF(func);
5983 return res;
5984 }
5985 PyErr_Clear();
5986 return PyUnicode_FromFormat("<%s object at %p>",
5987 Py_TYPE(self)->tp_name, self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005988}
5989
5990static PyObject *
5991slot_tp_str(PyObject *self)
5992{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005993 PyObject *func, *res;
Benjamin Petersonce798522012-01-22 11:24:29 -05005994 _Py_IDENTIFIER(__str__);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005995
Benjamin Petersonce798522012-01-22 11:24:29 -05005996 func = lookup_method(self, &PyId___str__);
Victor Stinner2e8474d2013-07-11 22:46:11 +02005997 if (func == NULL)
5998 return NULL;
Victor Stinnerbebba502013-10-29 10:56:34 +01005999 res = PyEval_CallObject(func, NULL);
6000 Py_DECREF(func);
6001 return res;
6002}
Tim Peters6d6c1a32001-08-02 04:15:00 +00006003
Benjamin Peterson8f67d082010-10-17 20:54:53 +00006004static Py_hash_t
Tim Peters6d6c1a32001-08-02 04:15:00 +00006005slot_tp_hash(PyObject *self)
6006{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006007 PyObject *func, *res;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00006008 Py_ssize_t h;
Tim Peters6d6c1a32001-08-02 04:15:00 +00006009
Benjamin Petersonce798522012-01-22 11:24:29 -05006010 func = lookup_method(self, &PyId___hash__);
Guido van Rossumb8f63662001-08-15 23:57:02 +00006011
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006012 if (func == Py_None) {
6013 Py_DECREF(func);
6014 func = NULL;
6015 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +00006016
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006017 if (func == NULL) {
6018 return PyObject_HashNotImplemented(self);
6019 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +00006020
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006021 res = PyEval_CallObject(func, NULL);
6022 Py_DECREF(func);
6023 if (res == NULL)
6024 return -1;
Mark Dickinsondc787d22010-05-23 13:33:13 +00006025
6026 if (!PyLong_Check(res)) {
6027 PyErr_SetString(PyExc_TypeError,
6028 "__hash__ method should return an integer");
6029 return -1;
6030 }
Benjamin Peterson8f67d082010-10-17 20:54:53 +00006031 /* Transform the PyLong `res` to a Py_hash_t `h`. For an existing
6032 hashable Python object x, hash(x) will always lie within the range of
6033 Py_hash_t. Therefore our transformation must preserve values that
6034 already lie within this range, to ensure that if x.__hash__() returns
6035 hash(y) then hash(x) == hash(y). */
6036 h = PyLong_AsSsize_t(res);
6037 if (h == -1 && PyErr_Occurred()) {
6038 /* res was not within the range of a Py_hash_t, so we're free to
Mark Dickinsondc787d22010-05-23 13:33:13 +00006039 use any sufficiently bit-mixing transformation;
6040 long.__hash__ will do nicely. */
Benjamin Peterson8f67d082010-10-17 20:54:53 +00006041 PyErr_Clear();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006042 h = PyLong_Type.tp_hash(res);
Benjamin Peterson8f67d082010-10-17 20:54:53 +00006043 }
Benjamin Petersone7dfeeb2010-10-17 21:27:01 +00006044 /* -1 is reserved for errors. */
6045 if (h == -1)
6046 h = -2;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006047 Py_DECREF(res);
Mark Dickinsondc787d22010-05-23 13:33:13 +00006048 return h;
Tim Peters6d6c1a32001-08-02 04:15:00 +00006049}
6050
6051static PyObject *
6052slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds)
6053{
Benjamin Petersonce798522012-01-22 11:24:29 -05006054 _Py_IDENTIFIER(__call__);
6055 PyObject *meth = lookup_method(self, &PyId___call__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006056 PyObject *res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00006057
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006058 if (meth == NULL)
6059 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006060
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006061 res = PyObject_Call(meth, args, kwds);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006062
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006063 Py_DECREF(meth);
6064 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00006065}
6066
Guido van Rossum14a6f832001-10-17 13:59:09 +00006067/* There are two slot dispatch functions for tp_getattro.
6068
6069 - slot_tp_getattro() is used when __getattribute__ is overridden
6070 but no __getattr__ hook is present;
6071
6072 - slot_tp_getattr_hook() is used when a __getattr__ hook is present.
6073
Guido van Rossumc334df52002-04-04 23:44:47 +00006074 The code in update_one_slot() always installs slot_tp_getattr_hook(); this
6075 detects the absence of __getattr__ and then installs the simpler slot if
6076 necessary. */
Guido van Rossum14a6f832001-10-17 13:59:09 +00006077
Tim Peters6d6c1a32001-08-02 04:15:00 +00006078static PyObject *
6079slot_tp_getattro(PyObject *self, PyObject *name)
6080{
Benjamin Petersonce798522012-01-22 11:24:29 -05006081 return call_method(self, &PyId___getattribute__, "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00006082}
6083
Guido van Rossum19c1cd52001-09-21 21:24:49 +00006084static PyObject *
Benjamin Peterson9262b842008-11-17 22:45:50 +00006085call_attribute(PyObject *self, PyObject *attr, PyObject *name)
6086{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006087 PyObject *res, *descr = NULL;
6088 descrgetfunc f = Py_TYPE(attr)->tp_descr_get;
Benjamin Peterson9262b842008-11-17 22:45:50 +00006089
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006090 if (f != NULL) {
6091 descr = f(attr, self, (PyObject *)(Py_TYPE(self)));
6092 if (descr == NULL)
6093 return NULL;
6094 else
6095 attr = descr;
6096 }
6097 res = PyObject_CallFunctionObjArgs(attr, name, NULL);
6098 Py_XDECREF(descr);
6099 return res;
Benjamin Peterson9262b842008-11-17 22:45:50 +00006100}
6101
6102static PyObject *
Guido van Rossum19c1cd52001-09-21 21:24:49 +00006103slot_tp_getattr_hook(PyObject *self, PyObject *name)
6104{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006105 PyTypeObject *tp = Py_TYPE(self);
6106 PyObject *getattr, *getattribute, *res;
Victor Stinner3c1e4812012-03-26 22:10:51 +02006107 _Py_IDENTIFIER(__getattr__);
Guido van Rossum19c1cd52001-09-21 21:24:49 +00006108
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006109 /* speed hack: we could use lookup_maybe, but that would resolve the
6110 method fully for each attribute lookup for classes with
6111 __getattr__, even when the attribute is present. So we use
6112 _PyType_Lookup and create the method only when needed, with
6113 call_attribute. */
Victor Stinner3c1e4812012-03-26 22:10:51 +02006114 getattr = _PyType_LookupId(tp, &PyId___getattr__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006115 if (getattr == NULL) {
6116 /* No __getattr__ hook: use a simpler dispatcher */
6117 tp->tp_getattro = slot_tp_getattro;
6118 return slot_tp_getattro(self, name);
6119 }
6120 Py_INCREF(getattr);
6121 /* speed hack: we could use lookup_maybe, but that would resolve the
6122 method fully for each attribute lookup for classes with
6123 __getattr__, even when self has the default __getattribute__
6124 method. So we use _PyType_Lookup and create the method only when
6125 needed, with call_attribute. */
Victor Stinner3c1e4812012-03-26 22:10:51 +02006126 getattribute = _PyType_LookupId(tp, &PyId___getattribute__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006127 if (getattribute == NULL ||
6128 (Py_TYPE(getattribute) == &PyWrapperDescr_Type &&
6129 ((PyWrapperDescrObject *)getattribute)->d_wrapped ==
6130 (void *)PyObject_GenericGetAttr))
6131 res = PyObject_GenericGetAttr(self, name);
6132 else {
6133 Py_INCREF(getattribute);
6134 res = call_attribute(self, getattribute, name);
6135 Py_DECREF(getattribute);
6136 }
6137 if (res == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) {
6138 PyErr_Clear();
6139 res = call_attribute(self, getattr, name);
6140 }
6141 Py_DECREF(getattr);
6142 return res;
Guido van Rossum19c1cd52001-09-21 21:24:49 +00006143}
6144
Tim Peters6d6c1a32001-08-02 04:15:00 +00006145static int
6146slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value)
6147{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006148 PyObject *res;
Benjamin Petersonce798522012-01-22 11:24:29 -05006149 _Py_IDENTIFIER(__delattr__);
6150 _Py_IDENTIFIER(__setattr__);
Tim Peters6d6c1a32001-08-02 04:15:00 +00006151
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006152 if (value == NULL)
Benjamin Petersonce798522012-01-22 11:24:29 -05006153 res = call_method(self, &PyId___delattr__, "(O)", name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006154 else
Benjamin Petersonce798522012-01-22 11:24:29 -05006155 res = call_method(self, &PyId___setattr__, "(OO)", name, value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006156 if (res == NULL)
6157 return -1;
6158 Py_DECREF(res);
6159 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00006160}
6161
Benjamin Petersonce798522012-01-22 11:24:29 -05006162static _Py_Identifier name_op[] = {
6163 {0, "__lt__", 0},
6164 {0, "__le__", 0},
6165 {0, "__eq__", 0},
6166 {0, "__ne__", 0},
6167 {0, "__gt__", 0},
6168 {0, "__ge__", 0}
Guido van Rossumf5243f02008-01-01 04:06:48 +00006169};
6170
Tim Peters6d6c1a32001-08-02 04:15:00 +00006171static PyObject *
Mark Dickinson6f1d0492009-11-15 13:58:49 +00006172slot_tp_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters6d6c1a32001-08-02 04:15:00 +00006173{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006174 PyObject *func, *args, *res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00006175
Benjamin Petersonce798522012-01-22 11:24:29 -05006176 func = lookup_method(self, &name_op[op]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006177 if (func == NULL) {
6178 PyErr_Clear();
Brian Curtindfc80e32011-08-10 20:28:54 -05006179 Py_RETURN_NOTIMPLEMENTED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006180 }
6181 args = PyTuple_Pack(1, other);
6182 if (args == NULL)
6183 res = NULL;
6184 else {
6185 res = PyObject_Call(func, args, NULL);
6186 Py_DECREF(args);
6187 }
6188 Py_DECREF(func);
6189 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00006190}
6191
Guido van Rossumb8f63662001-08-15 23:57:02 +00006192static PyObject *
Guido van Rossumb8f63662001-08-15 23:57:02 +00006193slot_tp_iter(PyObject *self)
6194{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006195 PyObject *func, *res;
Benjamin Petersonce798522012-01-22 11:24:29 -05006196 _Py_IDENTIFIER(__iter__);
Guido van Rossumb8f63662001-08-15 23:57:02 +00006197
Benjamin Petersonce798522012-01-22 11:24:29 -05006198 func = lookup_method(self, &PyId___iter__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006199 if (func != NULL) {
6200 PyObject *args;
6201 args = res = PyTuple_New(0);
6202 if (args != NULL) {
6203 res = PyObject_Call(func, args, NULL);
6204 Py_DECREF(args);
6205 }
6206 Py_DECREF(func);
6207 return res;
6208 }
6209 PyErr_Clear();
Benjamin Petersonce798522012-01-22 11:24:29 -05006210 func = lookup_method(self, &PyId___getitem__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006211 if (func == NULL) {
6212 PyErr_Format(PyExc_TypeError,
6213 "'%.200s' object is not iterable",
6214 Py_TYPE(self)->tp_name);
6215 return NULL;
6216 }
6217 Py_DECREF(func);
6218 return PySeqIter_New(self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00006219}
Tim Peters6d6c1a32001-08-02 04:15:00 +00006220
6221static PyObject *
6222slot_tp_iternext(PyObject *self)
6223{
Benjamin Petersonce798522012-01-22 11:24:29 -05006224 _Py_IDENTIFIER(__next__);
6225 return call_method(self, &PyId___next__, "()");
Tim Peters6d6c1a32001-08-02 04:15:00 +00006226}
6227
Guido van Rossum1a493502001-08-17 16:47:50 +00006228static PyObject *
6229slot_tp_descr_get(PyObject *self, PyObject *obj, PyObject *type)
6230{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006231 PyTypeObject *tp = Py_TYPE(self);
6232 PyObject *get;
Victor Stinner3c1e4812012-03-26 22:10:51 +02006233 _Py_IDENTIFIER(__get__);
Guido van Rossum1a493502001-08-17 16:47:50 +00006234
Victor Stinner3c1e4812012-03-26 22:10:51 +02006235 get = _PyType_LookupId(tp, &PyId___get__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006236 if (get == NULL) {
6237 /* Avoid further slowdowns */
6238 if (tp->tp_descr_get == slot_tp_descr_get)
6239 tp->tp_descr_get = NULL;
6240 Py_INCREF(self);
6241 return self;
6242 }
6243 if (obj == NULL)
6244 obj = Py_None;
6245 if (type == NULL)
6246 type = Py_None;
6247 return PyObject_CallFunctionObjArgs(get, self, obj, type, NULL);
Guido van Rossum1a493502001-08-17 16:47:50 +00006248}
Tim Peters6d6c1a32001-08-02 04:15:00 +00006249
6250static int
6251slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value)
6252{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006253 PyObject *res;
Benjamin Petersonce798522012-01-22 11:24:29 -05006254 _Py_IDENTIFIER(__delete__);
6255 _Py_IDENTIFIER(__set__);
Guido van Rossum2c252392001-08-24 10:13:31 +00006256
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006257 if (value == NULL)
Benjamin Petersonce798522012-01-22 11:24:29 -05006258 res = call_method(self, &PyId___delete__, "(O)", target);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006259 else
Benjamin Petersonce798522012-01-22 11:24:29 -05006260 res = call_method(self, &PyId___set__, "(OO)", target, value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006261 if (res == NULL)
6262 return -1;
6263 Py_DECREF(res);
6264 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00006265}
6266
6267static int
6268slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds)
6269{
Benjamin Petersonce798522012-01-22 11:24:29 -05006270 _Py_IDENTIFIER(__init__);
6271 PyObject *meth = lookup_method(self, &PyId___init__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006272 PyObject *res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00006273
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006274 if (meth == NULL)
6275 return -1;
6276 res = PyObject_Call(meth, args, kwds);
6277 Py_DECREF(meth);
6278 if (res == NULL)
6279 return -1;
6280 if (res != Py_None) {
6281 PyErr_Format(PyExc_TypeError,
6282 "__init__() should return None, not '%.200s'",
6283 Py_TYPE(res)->tp_name);
6284 Py_DECREF(res);
6285 return -1;
6286 }
6287 Py_DECREF(res);
6288 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00006289}
6290
6291static PyObject *
6292slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
6293{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006294 PyObject *func;
6295 PyObject *newargs, *x;
6296 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +00006297
Victor Stinner3c1e4812012-03-26 22:10:51 +02006298 func = _PyObject_GetAttrId((PyObject *)type, &PyId___new__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006299 if (func == NULL)
6300 return NULL;
6301 assert(PyTuple_Check(args));
6302 n = PyTuple_GET_SIZE(args);
6303 newargs = PyTuple_New(n+1);
6304 if (newargs == NULL)
6305 return NULL;
6306 Py_INCREF(type);
6307 PyTuple_SET_ITEM(newargs, 0, (PyObject *)type);
6308 for (i = 0; i < n; i++) {
6309 x = PyTuple_GET_ITEM(args, i);
6310 Py_INCREF(x);
6311 PyTuple_SET_ITEM(newargs, i+1, x);
6312 }
6313 x = PyObject_Call(func, newargs, kwds);
6314 Py_DECREF(newargs);
6315 Py_DECREF(func);
6316 return x;
Tim Peters6d6c1a32001-08-02 04:15:00 +00006317}
6318
Guido van Rossumfebd61d2002-08-08 20:55:20 +00006319static void
Antoine Pitrou796564c2013-07-30 19:59:21 +02006320slot_tp_finalize(PyObject *self)
Guido van Rossumfebd61d2002-08-08 20:55:20 +00006321{
Benjamin Petersonce798522012-01-22 11:24:29 -05006322 _Py_IDENTIFIER(__del__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006323 PyObject *del, *res;
6324 PyObject *error_type, *error_value, *error_traceback;
Guido van Rossumfebd61d2002-08-08 20:55:20 +00006325
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006326 /* Save the current exception, if any. */
6327 PyErr_Fetch(&error_type, &error_value, &error_traceback);
Guido van Rossumfebd61d2002-08-08 20:55:20 +00006328
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006329 /* Execute __del__ method, if any. */
Benjamin Petersonce798522012-01-22 11:24:29 -05006330 del = lookup_maybe(self, &PyId___del__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006331 if (del != NULL) {
6332 res = PyEval_CallObject(del, NULL);
6333 if (res == NULL)
6334 PyErr_WriteUnraisable(del);
6335 else
6336 Py_DECREF(res);
6337 Py_DECREF(del);
6338 }
Guido van Rossumfebd61d2002-08-08 20:55:20 +00006339
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006340 /* Restore the saved exception. */
6341 PyErr_Restore(error_type, error_value, error_traceback);
Guido van Rossumfebd61d2002-08-08 20:55:20 +00006342}
6343
Yury Selivanov75445082015-05-11 22:57:16 -04006344static PyObject *
6345slot_am_await(PyObject *self)
6346{
6347 PyObject *func, *res;
6348 _Py_IDENTIFIER(__await__);
6349
6350 func = lookup_method(self, &PyId___await__);
6351 if (func != NULL) {
6352 res = PyEval_CallObject(func, NULL);
6353 Py_DECREF(func);
6354 return res;
6355 }
6356 PyErr_Format(PyExc_AttributeError,
6357 "object %.50s does not have __await__ method",
6358 Py_TYPE(self)->tp_name);
6359 return NULL;
6360}
6361
6362static PyObject *
6363slot_am_aiter(PyObject *self)
6364{
6365 PyObject *func, *res;
6366 _Py_IDENTIFIER(__aiter__);
6367
6368 func = lookup_method(self, &PyId___aiter__);
6369 if (func != NULL) {
6370 res = PyEval_CallObject(func, NULL);
6371 Py_DECREF(func);
6372 return res;
6373 }
6374 PyErr_Format(PyExc_AttributeError,
6375 "object %.50s does not have __aiter__ method",
6376 Py_TYPE(self)->tp_name);
6377 return NULL;
6378}
6379
6380static PyObject *
6381slot_am_anext(PyObject *self)
6382{
6383 PyObject *func, *res;
6384 _Py_IDENTIFIER(__anext__);
6385
6386 func = lookup_method(self, &PyId___anext__);
6387 if (func != NULL) {
6388 res = PyEval_CallObject(func, NULL);
6389 Py_DECREF(func);
6390 return res;
6391 }
6392 PyErr_Format(PyExc_AttributeError,
6393 "object %.50s does not have __anext__ method",
6394 Py_TYPE(self)->tp_name);
6395 return NULL;
6396}
Guido van Rossum7b9144b2001-10-09 19:39:46 +00006397
Benjamin Peterson63952412013-04-01 17:41:41 -04006398/*
6399Table mapping __foo__ names to tp_foo offsets and slot_tp_foo wrapper functions.
6400
6401The table is ordered by offsets relative to the 'PyHeapTypeObject' structure,
6402which incorporates the additional structures used for numbers, sequences and
6403mappings. Note that multiple names may map to the same slot (e.g. __eq__,
6404__ne__ etc. all map to tp_richcompare) and one name may map to multiple slots
6405(e.g. __str__ affects tp_str as well as tp_repr). The table is terminated with
6406an all-zero entry. (This table is further initialized in init_slotdefs().)
6407*/
Guido van Rossum7b9144b2001-10-09 19:39:46 +00006408
Guido van Rossum6d204072001-10-21 00:44:31 +00006409typedef struct wrapperbase slotdef;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00006410
6411#undef TPSLOT
Guido van Rossumc8e56452001-10-22 00:43:43 +00006412#undef FLSLOT
Yury Selivanov75445082015-05-11 22:57:16 -04006413#undef AMSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00006414#undef ETSLOT
6415#undef SQSLOT
6416#undef MPSLOT
6417#undef NBSLOT
Guido van Rossum6d204072001-10-21 00:44:31 +00006418#undef UNSLOT
6419#undef IBSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00006420#undef BINSLOT
6421#undef RBINSLOT
6422
Guido van Rossum6d204072001-10-21 00:44:31 +00006423#define TPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006424 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
6425 PyDoc_STR(DOC)}
Guido van Rossumc8e56452001-10-22 00:43:43 +00006426#define FLSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC, FLAGS) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006427 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
6428 PyDoc_STR(DOC), FLAGS}
Guido van Rossum6d204072001-10-21 00:44:31 +00006429#define ETSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006430 {NAME, offsetof(PyHeapTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
6431 PyDoc_STR(DOC)}
Yury Selivanov75445082015-05-11 22:57:16 -04006432#define AMSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
6433 ETSLOT(NAME, as_async.SLOT, FUNCTION, WRAPPER, DOC)
Guido van Rossum6d204072001-10-21 00:44:31 +00006434#define SQSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006435 ETSLOT(NAME, as_sequence.SLOT, FUNCTION, WRAPPER, DOC)
Guido van Rossum6d204072001-10-21 00:44:31 +00006436#define MPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006437 ETSLOT(NAME, as_mapping.SLOT, FUNCTION, WRAPPER, DOC)
Guido van Rossum6d204072001-10-21 00:44:31 +00006438#define NBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006439 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, DOC)
Guido van Rossum6d204072001-10-21 00:44:31 +00006440#define UNSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006441 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
Larry Hastings69a25472014-02-09 22:22:38 -08006442 NAME "($self, /)\n--\n\n" DOC)
Guido van Rossum6d204072001-10-21 00:44:31 +00006443#define IBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006444 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
Larry Hastings69a25472014-02-09 22:22:38 -08006445 NAME "($self, value, /)\n--\n\nReturn self" DOC "value.")
Guido van Rossum6d204072001-10-21 00:44:31 +00006446#define BINSLOT(NAME, SLOT, FUNCTION, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006447 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
Larry Hastings69a25472014-02-09 22:22:38 -08006448 NAME "($self, value, /)\n--\n\nReturn self" DOC "value.")
Guido van Rossum6d204072001-10-21 00:44:31 +00006449#define RBINSLOT(NAME, SLOT, FUNCTION, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006450 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
Larry Hastings69a25472014-02-09 22:22:38 -08006451 NAME "($self, value, /)\n--\n\nReturn value" DOC "self.")
Anthony Baxter56616992005-06-03 14:12:21 +00006452#define BINSLOTNOTINFIX(NAME, SLOT, FUNCTION, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006453 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
Larry Hastings69a25472014-02-09 22:22:38 -08006454 NAME "($self, value, /)\n--\n\n" DOC)
Anthony Baxter56616992005-06-03 14:12:21 +00006455#define RBINSLOTNOTINFIX(NAME, SLOT, FUNCTION, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006456 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
Larry Hastings69a25472014-02-09 22:22:38 -08006457 NAME "($self, value, /)\n--\n\n" DOC)
Guido van Rossum7b9144b2001-10-09 19:39:46 +00006458
6459static slotdef slotdefs[] = {
Benjamin Peterson63952412013-04-01 17:41:41 -04006460 TPSLOT("__getattribute__", tp_getattr, NULL, NULL, ""),
6461 TPSLOT("__getattr__", tp_getattr, NULL, NULL, ""),
6462 TPSLOT("__setattr__", tp_setattr, NULL, NULL, ""),
6463 TPSLOT("__delattr__", tp_setattr, NULL, NULL, ""),
6464 TPSLOT("__repr__", tp_repr, slot_tp_repr, wrap_unaryfunc,
Larry Hastings69a25472014-02-09 22:22:38 -08006465 "__repr__($self, /)\n--\n\nReturn repr(self)."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006466 TPSLOT("__hash__", tp_hash, slot_tp_hash, wrap_hashfunc,
Larry Hastings69a25472014-02-09 22:22:38 -08006467 "__hash__($self, /)\n--\n\nReturn hash(self)."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006468 FLSLOT("__call__", tp_call, slot_tp_call, (wrapperfunc)wrap_call,
Larry Hastings69a25472014-02-09 22:22:38 -08006469 "__call__($self, /, *args, **kwargs)\n--\n\nCall self as a function.",
Larry Hastings5c661892014-01-24 06:17:25 -08006470 PyWrapperFlag_KEYWORDS),
Benjamin Peterson63952412013-04-01 17:41:41 -04006471 TPSLOT("__str__", tp_str, slot_tp_str, wrap_unaryfunc,
Larry Hastings69a25472014-02-09 22:22:38 -08006472 "__str__($self, /)\n--\n\nReturn str(self)."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006473 TPSLOT("__getattribute__", tp_getattro, slot_tp_getattr_hook,
Larry Hastings5c661892014-01-24 06:17:25 -08006474 wrap_binaryfunc,
Larry Hastings69a25472014-02-09 22:22:38 -08006475 "__getattribute__($self, name, /)\n--\n\nReturn getattr(self, name)."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006476 TPSLOT("__getattr__", tp_getattro, slot_tp_getattr_hook, NULL, ""),
6477 TPSLOT("__setattr__", tp_setattro, slot_tp_setattro, wrap_setattr,
Larry Hastings69a25472014-02-09 22:22:38 -08006478 "__setattr__($self, name, value, /)\n--\n\nImplement setattr(self, name, value)."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006479 TPSLOT("__delattr__", tp_setattro, slot_tp_setattro, wrap_delattr,
Larry Hastings69a25472014-02-09 22:22:38 -08006480 "__delattr__($self, name, /)\n--\n\nImplement delattr(self, name)."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006481 TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare, richcmp_lt,
Larry Hastings69a25472014-02-09 22:22:38 -08006482 "__lt__($self, value, /)\n--\n\nReturn self<value."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006483 TPSLOT("__le__", tp_richcompare, slot_tp_richcompare, richcmp_le,
Larry Hastings69a25472014-02-09 22:22:38 -08006484 "__le__($self, value, /)\n--\n\nReturn self<=value."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006485 TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare, richcmp_eq,
Larry Hastings69a25472014-02-09 22:22:38 -08006486 "__eq__($self, value, /)\n--\n\nReturn self==value."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006487 TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare, richcmp_ne,
Larry Hastings69a25472014-02-09 22:22:38 -08006488 "__ne__($self, value, /)\n--\n\nReturn self!=value."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006489 TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare, richcmp_gt,
Larry Hastings69a25472014-02-09 22:22:38 -08006490 "__gt__($self, value, /)\n--\n\nReturn self>value."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006491 TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare, richcmp_ge,
Zachary Wareea42b4c2014-04-18 09:14:31 -05006492 "__ge__($self, value, /)\n--\n\nReturn self>=value."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006493 TPSLOT("__iter__", tp_iter, slot_tp_iter, wrap_unaryfunc,
Larry Hastings69a25472014-02-09 22:22:38 -08006494 "__iter__($self, /)\n--\n\nImplement iter(self)."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006495 TPSLOT("__next__", tp_iternext, slot_tp_iternext, wrap_next,
Larry Hastings69a25472014-02-09 22:22:38 -08006496 "__next__($self, /)\n--\n\nImplement next(self)."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006497 TPSLOT("__get__", tp_descr_get, slot_tp_descr_get, wrap_descr_get,
Larry Hastings69a25472014-02-09 22:22:38 -08006498 "__get__($self, instance, owner, /)\n--\n\nReturn an attribute of instance, which is of type owner."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006499 TPSLOT("__set__", tp_descr_set, slot_tp_descr_set, wrap_descr_set,
Larry Hastings69a25472014-02-09 22:22:38 -08006500 "__set__($self, instance, value, /)\n--\n\nSet an attribute of instance to value."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006501 TPSLOT("__delete__", tp_descr_set, slot_tp_descr_set,
Larry Hastings5c661892014-01-24 06:17:25 -08006502 wrap_descr_delete,
Yury Selivanov056e2652014-03-02 12:25:27 -05006503 "__delete__($self, instance, /)\n--\n\nDelete an attribute of instance."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006504 FLSLOT("__init__", tp_init, slot_tp_init, (wrapperfunc)wrap_init,
Larry Hastings69a25472014-02-09 22:22:38 -08006505 "__init__($self, /, *args, **kwargs)\n--\n\n"
Larry Hastings581ee362014-01-28 05:00:08 -08006506 "Initialize self. See help(type(self)) for accurate signature.",
Benjamin Peterson63952412013-04-01 17:41:41 -04006507 PyWrapperFlag_KEYWORDS),
Larry Hastings5c661892014-01-24 06:17:25 -08006508 TPSLOT("__new__", tp_new, slot_tp_new, NULL,
Larry Hastings69a25472014-02-09 22:22:38 -08006509 "__new__(type, /, *args, **kwargs)\n--\n\n"
Larry Hastings581ee362014-01-28 05:00:08 -08006510 "Create and return new object. See help(type) for accurate signature."),
Antoine Pitrou796564c2013-07-30 19:59:21 +02006511 TPSLOT("__del__", tp_finalize, slot_tp_finalize, (wrapperfunc)wrap_del, ""),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00006512
Yury Selivanov75445082015-05-11 22:57:16 -04006513 AMSLOT("__await__", am_await, slot_am_await, wrap_unaryfunc,
6514 "__await__($self, /)\n--\n\nReturn an iterator to be used in await expression."),
6515 AMSLOT("__aiter__", am_aiter, slot_am_aiter, wrap_unaryfunc,
6516 "__aiter__($self, /)\n--\n\nReturn an awaitable, that resolves in asynchronous iterator."),
6517 AMSLOT("__anext__", am_anext, slot_am_anext, wrap_unaryfunc,
6518 "__anext__($self, /)\n--\n\nReturn a value or raise StopAsyncIteration."),
6519
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006520 BINSLOT("__add__", nb_add, slot_nb_add,
Larry Hastings5c661892014-01-24 06:17:25 -08006521 "+"),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006522 RBINSLOT("__radd__", nb_add, slot_nb_add,
Larry Hastings5c661892014-01-24 06:17:25 -08006523 "+"),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006524 BINSLOT("__sub__", nb_subtract, slot_nb_subtract,
Larry Hastings5c661892014-01-24 06:17:25 -08006525 "-"),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006526 RBINSLOT("__rsub__", nb_subtract, slot_nb_subtract,
Larry Hastings5c661892014-01-24 06:17:25 -08006527 "-"),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006528 BINSLOT("__mul__", nb_multiply, slot_nb_multiply,
Larry Hastings5c661892014-01-24 06:17:25 -08006529 "*"),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006530 RBINSLOT("__rmul__", nb_multiply, slot_nb_multiply,
Larry Hastings5c661892014-01-24 06:17:25 -08006531 "*"),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006532 BINSLOT("__mod__", nb_remainder, slot_nb_remainder,
Larry Hastings5c661892014-01-24 06:17:25 -08006533 "%"),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006534 RBINSLOT("__rmod__", nb_remainder, slot_nb_remainder,
Larry Hastings5c661892014-01-24 06:17:25 -08006535 "%"),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006536 BINSLOTNOTINFIX("__divmod__", nb_divmod, slot_nb_divmod,
Larry Hastings581ee362014-01-28 05:00:08 -08006537 "Return divmod(self, value)."),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006538 RBINSLOTNOTINFIX("__rdivmod__", nb_divmod, slot_nb_divmod,
Larry Hastings581ee362014-01-28 05:00:08 -08006539 "Return divmod(value, self)."),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006540 NBSLOT("__pow__", nb_power, slot_nb_power, wrap_ternaryfunc,
Larry Hastings69a25472014-02-09 22:22:38 -08006541 "__pow__($self, value, mod=None, /)\n--\n\nReturn pow(self, value, mod)."),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006542 NBSLOT("__rpow__", nb_power, slot_nb_power, wrap_ternaryfunc_r,
Larry Hastings69a25472014-02-09 22:22:38 -08006543 "__rpow__($self, value, mod=None, /)\n--\n\nReturn pow(value, self, mod)."),
Larry Hastings5c661892014-01-24 06:17:25 -08006544 UNSLOT("__neg__", nb_negative, slot_nb_negative, wrap_unaryfunc, "-self"),
6545 UNSLOT("__pos__", nb_positive, slot_nb_positive, wrap_unaryfunc, "+self"),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006546 UNSLOT("__abs__", nb_absolute, slot_nb_absolute, wrap_unaryfunc,
Larry Hastings5c661892014-01-24 06:17:25 -08006547 "abs(self)"),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006548 UNSLOT("__bool__", nb_bool, slot_nb_bool, wrap_inquirypred,
Larry Hastings5c661892014-01-24 06:17:25 -08006549 "self != 0"),
6550 UNSLOT("__invert__", nb_invert, slot_nb_invert, wrap_unaryfunc, "~self"),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006551 BINSLOT("__lshift__", nb_lshift, slot_nb_lshift, "<<"),
6552 RBINSLOT("__rlshift__", nb_lshift, slot_nb_lshift, "<<"),
6553 BINSLOT("__rshift__", nb_rshift, slot_nb_rshift, ">>"),
6554 RBINSLOT("__rrshift__", nb_rshift, slot_nb_rshift, ">>"),
6555 BINSLOT("__and__", nb_and, slot_nb_and, "&"),
6556 RBINSLOT("__rand__", nb_and, slot_nb_and, "&"),
6557 BINSLOT("__xor__", nb_xor, slot_nb_xor, "^"),
6558 RBINSLOT("__rxor__", nb_xor, slot_nb_xor, "^"),
6559 BINSLOT("__or__", nb_or, slot_nb_or, "|"),
6560 RBINSLOT("__ror__", nb_or, slot_nb_or, "|"),
6561 UNSLOT("__int__", nb_int, slot_nb_int, wrap_unaryfunc,
Larry Hastings5c661892014-01-24 06:17:25 -08006562 "int(self)"),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006563 UNSLOT("__float__", nb_float, slot_nb_float, wrap_unaryfunc,
Larry Hastings5c661892014-01-24 06:17:25 -08006564 "float(self)"),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006565 IBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add,
Eli Benderskyd3baae72011-11-11 16:57:05 +02006566 wrap_binaryfunc, "+="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006567 IBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract,
Eli Benderskyd3baae72011-11-11 16:57:05 +02006568 wrap_binaryfunc, "-="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006569 IBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply,
Eli Benderskyd3baae72011-11-11 16:57:05 +02006570 wrap_binaryfunc, "*="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006571 IBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder,
Eli Benderskyd3baae72011-11-11 16:57:05 +02006572 wrap_binaryfunc, "%="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006573 IBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power,
Eli Benderskyd3baae72011-11-11 16:57:05 +02006574 wrap_binaryfunc, "**="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006575 IBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift,
Eli Benderskyd3baae72011-11-11 16:57:05 +02006576 wrap_binaryfunc, "<<="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006577 IBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift,
Eli Benderskyd3baae72011-11-11 16:57:05 +02006578 wrap_binaryfunc, ">>="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006579 IBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and,
Eli Benderskyd3baae72011-11-11 16:57:05 +02006580 wrap_binaryfunc, "&="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006581 IBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor,
Eli Benderskyd3baae72011-11-11 16:57:05 +02006582 wrap_binaryfunc, "^="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006583 IBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or,
Eli Benderskyd3baae72011-11-11 16:57:05 +02006584 wrap_binaryfunc, "|="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006585 BINSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
6586 RBINSLOT("__rfloordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
6587 BINSLOT("__truediv__", nb_true_divide, slot_nb_true_divide, "/"),
6588 RBINSLOT("__rtruediv__", nb_true_divide, slot_nb_true_divide, "/"),
6589 IBSLOT("__ifloordiv__", nb_inplace_floor_divide,
Georg Brandle1d26f32014-10-31 13:12:57 +01006590 slot_nb_inplace_floor_divide, wrap_binaryfunc, "//="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006591 IBSLOT("__itruediv__", nb_inplace_true_divide,
Georg Brandle1d26f32014-10-31 13:12:57 +01006592 slot_nb_inplace_true_divide, wrap_binaryfunc, "/="),
Benjamin Peterson63952412013-04-01 17:41:41 -04006593 NBSLOT("__index__", nb_index, slot_nb_index, wrap_unaryfunc,
Larry Hastings69a25472014-02-09 22:22:38 -08006594 "__index__($self, /)\n--\n\n"
Zachary Ware715ef022014-04-18 09:23:14 -05006595 "Return self converted to an integer, if self is suitable "
Larry Hastings5c661892014-01-24 06:17:25 -08006596 "for use as an index into a list."),
Benjamin Petersond51374e2014-04-09 23:55:56 -04006597 BINSLOT("__matmul__", nb_matrix_multiply, slot_nb_matrix_multiply,
6598 "@"),
6599 RBINSLOT("__rmatmul__", nb_matrix_multiply, slot_nb_matrix_multiply,
6600 "@"),
6601 IBSLOT("__imatmul__", nb_inplace_matrix_multiply, slot_nb_inplace_matrix_multiply,
6602 wrap_binaryfunc, "@="),
Benjamin Peterson63952412013-04-01 17:41:41 -04006603 MPSLOT("__len__", mp_length, slot_mp_length, wrap_lenfunc,
Larry Hastings69a25472014-02-09 22:22:38 -08006604 "__len__($self, /)\n--\n\nReturn len(self)."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006605 MPSLOT("__getitem__", mp_subscript, slot_mp_subscript,
6606 wrap_binaryfunc,
Larry Hastings69a25472014-02-09 22:22:38 -08006607 "__getitem__($self, key, /)\n--\n\nReturn self[key]."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006608 MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript,
6609 wrap_objobjargproc,
Larry Hastings69a25472014-02-09 22:22:38 -08006610 "__setitem__($self, key, value, /)\n--\n\nSet self[key] to value."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006611 MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript,
6612 wrap_delitem,
Yury Selivanov056e2652014-03-02 12:25:27 -05006613 "__delitem__($self, key, /)\n--\n\nDelete self[key]."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006614
6615 SQSLOT("__len__", sq_length, slot_sq_length, wrap_lenfunc,
Larry Hastings69a25472014-02-09 22:22:38 -08006616 "__len__($self, /)\n--\n\nReturn len(self)."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006617 /* Heap types defining __add__/__mul__ have sq_concat/sq_repeat == NULL.
6618 The logic in abstract.c always falls back to nb_add/nb_multiply in
6619 this case. Defining both the nb_* and the sq_* slots to call the
6620 user-defined methods has unexpected side-effects, as shown by
6621 test_descr.notimplemented() */
6622 SQSLOT("__add__", sq_concat, NULL, wrap_binaryfunc,
Larry Hastings69a25472014-02-09 22:22:38 -08006623 "__add__($self, value, /)\n--\n\nReturn self+value."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006624 SQSLOT("__mul__", sq_repeat, NULL, wrap_indexargfunc,
Larry Hastings69a25472014-02-09 22:22:38 -08006625 "__mul__($self, value, /)\n--\n\nReturn self*value.n"),
Benjamin Peterson63952412013-04-01 17:41:41 -04006626 SQSLOT("__rmul__", sq_repeat, NULL, wrap_indexargfunc,
Larry Hastings69a25472014-02-09 22:22:38 -08006627 "__rmul__($self, value, /)\n--\n\nReturn self*value."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006628 SQSLOT("__getitem__", sq_item, slot_sq_item, wrap_sq_item,
Larry Hastings69a25472014-02-09 22:22:38 -08006629 "__getitem__($self, key, /)\n--\n\nReturn self[key]."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006630 SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_setitem,
Larry Hastings69a25472014-02-09 22:22:38 -08006631 "__setitem__($self, key, value, /)\n--\n\nSet self[key] to value."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006632 SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_delitem,
Larry Hastings69a25472014-02-09 22:22:38 -08006633 "__delitem__($self, key, /)\n--\n\nDelete self[key]."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006634 SQSLOT("__contains__", sq_contains, slot_sq_contains, wrap_objobjproc,
Larry Hastings69a25472014-02-09 22:22:38 -08006635 "__contains__($self, key, /)\n--\n\nReturn key in self."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006636 SQSLOT("__iadd__", sq_inplace_concat, NULL,
Larry Hastings5c661892014-01-24 06:17:25 -08006637 wrap_binaryfunc,
Larry Hastings69a25472014-02-09 22:22:38 -08006638 "__iadd__($self, value, /)\n--\n\nImplement self+=value."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006639 SQSLOT("__imul__", sq_inplace_repeat, NULL,
Larry Hastings5c661892014-01-24 06:17:25 -08006640 wrap_indexargfunc,
Larry Hastings69a25472014-02-09 22:22:38 -08006641 "__imul__($self, value, /)\n--\n\nImplement self*=value."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006642
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006643 {NULL}
Guido van Rossum7b9144b2001-10-09 19:39:46 +00006644};
6645
Guido van Rossumc334df52002-04-04 23:44:47 +00006646/* Given a type pointer and an offset gotten from a slotdef entry, return a
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006647 pointer to the actual slot. This is not quite the same as simply adding
Guido van Rossumc334df52002-04-04 23:44:47 +00006648 the offset to the type pointer, since it takes care to indirect through the
6649 proper indirection pointer (as_buffer, etc.); it returns NULL if the
6650 indirection pointer is NULL. */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00006651static void **
Martin v. Löwis18e16552006-02-15 17:27:45 +00006652slotptr(PyTypeObject *type, int ioffset)
Guido van Rossum7b9144b2001-10-09 19:39:46 +00006653{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006654 char *ptr;
6655 long offset = ioffset;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00006656
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006657 /* Note: this depends on the order of the members of PyHeapTypeObject! */
6658 assert(offset >= 0);
6659 assert((size_t)offset < offsetof(PyHeapTypeObject, as_buffer));
6660 if ((size_t)offset >= offsetof(PyHeapTypeObject, as_sequence)) {
6661 ptr = (char *)type->tp_as_sequence;
6662 offset -= offsetof(PyHeapTypeObject, as_sequence);
6663 }
6664 else if ((size_t)offset >= offsetof(PyHeapTypeObject, as_mapping)) {
6665 ptr = (char *)type->tp_as_mapping;
6666 offset -= offsetof(PyHeapTypeObject, as_mapping);
6667 }
6668 else if ((size_t)offset >= offsetof(PyHeapTypeObject, as_number)) {
6669 ptr = (char *)type->tp_as_number;
6670 offset -= offsetof(PyHeapTypeObject, as_number);
6671 }
Yury Selivanov75445082015-05-11 22:57:16 -04006672 else if ((size_t)offset >= offsetof(PyHeapTypeObject, as_async)) {
6673 ptr = (char *)type->tp_as_async;
6674 offset -= offsetof(PyHeapTypeObject, as_async);
6675 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006676 else {
6677 ptr = (char *)type;
6678 }
6679 if (ptr != NULL)
6680 ptr += offset;
6681 return (void **)ptr;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00006682}
Guido van Rossumf040ede2001-08-07 16:40:56 +00006683
Guido van Rossumc334df52002-04-04 23:44:47 +00006684/* Length of array of slotdef pointers used to store slots with the
6685 same __name__. There should be at most MAX_EQUIV-1 slotdef entries with
6686 the same __name__, for any __name__. Since that's a static property, it is
6687 appropriate to declare fixed-size arrays for this. */
6688#define MAX_EQUIV 10
6689
6690/* Return a slot pointer for a given name, but ONLY if the attribute has
6691 exactly one slot function. The name must be an interned string. */
6692static void **
6693resolve_slotdups(PyTypeObject *type, PyObject *name)
6694{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006695 /* XXX Maybe this could be optimized more -- but is it worth it? */
Guido van Rossumc334df52002-04-04 23:44:47 +00006696
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006697 /* pname and ptrs act as a little cache */
6698 static PyObject *pname;
6699 static slotdef *ptrs[MAX_EQUIV];
6700 slotdef *p, **pp;
6701 void **res, **ptr;
Guido van Rossumc334df52002-04-04 23:44:47 +00006702
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006703 if (pname != name) {
6704 /* Collect all slotdefs that match name into ptrs. */
6705 pname = name;
6706 pp = ptrs;
6707 for (p = slotdefs; p->name_strobj; p++) {
6708 if (p->name_strobj == name)
6709 *pp++ = p;
6710 }
6711 *pp = NULL;
6712 }
Guido van Rossumc334df52002-04-04 23:44:47 +00006713
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006714 /* Look in all matching slots of the type; if exactly one of these has
6715 a filled-in slot, return its value. Otherwise return NULL. */
6716 res = NULL;
6717 for (pp = ptrs; *pp; pp++) {
6718 ptr = slotptr(type, (*pp)->offset);
6719 if (ptr == NULL || *ptr == NULL)
6720 continue;
6721 if (res != NULL)
6722 return NULL;
6723 res = ptr;
6724 }
6725 return res;
Guido van Rossumc334df52002-04-04 23:44:47 +00006726}
6727
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006728/* Common code for update_slots_callback() and fixup_slot_dispatchers(). This
Guido van Rossumc334df52002-04-04 23:44:47 +00006729 does some incredibly complex thinking and then sticks something into the
6730 slot. (It sees if the adjacent slotdefs for the same slot have conflicting
6731 interests, and then stores a generic wrapper or a specific function into
6732 the slot.) Return a pointer to the next slotdef with a different offset,
6733 because that's convenient for fixup_slot_dispatchers(). */
6734static slotdef *
6735update_one_slot(PyTypeObject *type, slotdef *p)
6736{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006737 PyObject *descr;
6738 PyWrapperDescrObject *d;
6739 void *generic = NULL, *specific = NULL;
6740 int use_generic = 0;
6741 int offset = p->offset;
6742 void **ptr = slotptr(type, offset);
Guido van Rossumc334df52002-04-04 23:44:47 +00006743
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006744 if (ptr == NULL) {
6745 do {
6746 ++p;
6747 } while (p->offset == offset);
6748 return p;
6749 }
6750 do {
6751 descr = _PyType_Lookup(type, p->name_strobj);
6752 if (descr == NULL) {
6753 if (ptr == (void**)&type->tp_iternext) {
Trent Nelsonab02db22012-09-18 21:58:03 -04006754 specific = (void *)_PyObject_NextNotImplemented;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006755 }
6756 continue;
6757 }
Benjamin Peterson7b166872012-04-24 11:06:25 -04006758 if (Py_TYPE(descr) == &PyWrapperDescr_Type &&
6759 ((PyWrapperDescrObject *)descr)->d_base->name_strobj == p->name_strobj) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006760 void **tptr = resolve_slotdups(type, p->name_strobj);
6761 if (tptr == NULL || tptr == ptr)
6762 generic = p->function;
6763 d = (PyWrapperDescrObject *)descr;
6764 if (d->d_base->wrapper == p->wrapper &&
6765 PyType_IsSubtype(type, PyDescr_TYPE(d)))
6766 {
6767 if (specific == NULL ||
6768 specific == d->d_wrapped)
6769 specific = d->d_wrapped;
6770 else
6771 use_generic = 1;
6772 }
6773 }
6774 else if (Py_TYPE(descr) == &PyCFunction_Type &&
6775 PyCFunction_GET_FUNCTION(descr) ==
6776 (PyCFunction)tp_new_wrapper &&
6777 ptr == (void**)&type->tp_new)
6778 {
6779 /* The __new__ wrapper is not a wrapper descriptor,
6780 so must be special-cased differently.
6781 If we don't do this, creating an instance will
6782 always use slot_tp_new which will look up
6783 __new__ in the MRO which will call tp_new_wrapper
6784 which will look through the base classes looking
6785 for a static base and call its tp_new (usually
6786 PyType_GenericNew), after performing various
6787 sanity checks and constructing a new argument
6788 list. Cut all that nonsense short -- this speeds
6789 up instance creation tremendously. */
Benjamin Petersonc3526202016-05-28 14:04:40 -07006790 specific = (void *)type->tp_new;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006791 /* XXX I'm not 100% sure that there isn't a hole
6792 in this reasoning that requires additional
6793 sanity checks. I'll buy the first person to
6794 point out a bug in this reasoning a beer. */
6795 }
6796 else if (descr == Py_None &&
6797 ptr == (void**)&type->tp_hash) {
6798 /* We specifically allow __hash__ to be set to None
6799 to prevent inheritance of the default
6800 implementation from object.__hash__ */
Trent Nelsonab02db22012-09-18 21:58:03 -04006801 specific = (void *)PyObject_HashNotImplemented;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006802 }
6803 else {
6804 use_generic = 1;
6805 generic = p->function;
6806 }
6807 } while ((++p)->offset == offset);
6808 if (specific && !use_generic)
6809 *ptr = specific;
6810 else
6811 *ptr = generic;
6812 return p;
Guido van Rossumc334df52002-04-04 23:44:47 +00006813}
6814
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006815/* In the type, update the slots whose slotdefs are gathered in the pp array.
6816 This is a callback for update_subclasses(). */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006817static int
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006818update_slots_callback(PyTypeObject *type, void *data)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006819{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006820 slotdef **pp = (slotdef **)data;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006821
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006822 for (; *pp; pp++)
6823 update_one_slot(type, *pp);
6824 return 0;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006825}
6826
Martin v. Löwis996b6712014-07-26 16:44:07 +02006827static int slotdefs_initialized = 0;
Guido van Rossumc334df52002-04-04 23:44:47 +00006828/* Initialize the slotdefs table by adding interned string objects for the
Martin v. Löwis5b561502014-07-26 15:25:04 +02006829 names. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006830static void
Guido van Rossumd396b9c2001-10-13 20:02:41 +00006831init_slotdefs(void)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006832{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006833 slotdef *p;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006834
Martin v. Löwis996b6712014-07-26 16:44:07 +02006835 if (slotdefs_initialized)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006836 return;
6837 for (p = slotdefs; p->name; p++) {
Benjamin Peterson63952412013-04-01 17:41:41 -04006838 /* Slots must be ordered by their offset in the PyHeapTypeObject. */
6839 assert(!p[1].name || p->offset <= p[1].offset);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006840 p->name_strobj = PyUnicode_InternFromString(p->name);
6841 if (!p->name_strobj)
6842 Py_FatalError("Out of memory interning slotdef names");
6843 }
Martin v. Löwis996b6712014-07-26 16:44:07 +02006844 slotdefs_initialized = 1;
6845}
6846
6847/* Undo init_slotdefs, releasing the interned strings. */
Victor Stinner331a7262014-07-27 16:11:30 +02006848static void clear_slotdefs(void)
Martin v. Löwis996b6712014-07-26 16:44:07 +02006849{
6850 slotdef *p;
6851 for (p = slotdefs; p->name; p++) {
6852 Py_CLEAR(p->name_strobj);
6853 }
6854 slotdefs_initialized = 0;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006855}
6856
Guido van Rossumc334df52002-04-04 23:44:47 +00006857/* Update the slots after assignment to a class (type) attribute. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006858static int
6859update_slot(PyTypeObject *type, PyObject *name)
6860{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006861 slotdef *ptrs[MAX_EQUIV];
6862 slotdef *p;
6863 slotdef **pp;
6864 int offset;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006865
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006866 /* Clear the VALID_VERSION flag of 'type' and all its
6867 subclasses. This could possibly be unified with the
6868 update_subclasses() recursion below, but carefully:
6869 they each have their own conditions on which to stop
6870 recursing into subclasses. */
6871 PyType_Modified(type);
Christian Heimesa62da1d2008-01-12 19:39:10 +00006872
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006873 init_slotdefs();
6874 pp = ptrs;
6875 for (p = slotdefs; p->name; p++) {
6876 /* XXX assume name is interned! */
6877 if (p->name_strobj == name)
6878 *pp++ = p;
6879 }
6880 *pp = NULL;
6881 for (pp = ptrs; *pp; pp++) {
6882 p = *pp;
6883 offset = p->offset;
6884 while (p > slotdefs && (p-1)->offset == offset)
6885 --p;
6886 *pp = p;
6887 }
6888 if (ptrs[0] == NULL)
6889 return 0; /* Not an attribute that affects any slots */
6890 return update_subclasses(type, name,
6891 update_slots_callback, (void *)ptrs);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006892}
6893
Guido van Rossumc334df52002-04-04 23:44:47 +00006894/* Store the proper functions in the slot dispatches at class (type)
6895 definition time, based upon which operations the class overrides in its
6896 dict. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00006897static void
Guido van Rossum7b9144b2001-10-09 19:39:46 +00006898fixup_slot_dispatchers(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00006899{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006900 slotdef *p;
Tim Peters6d6c1a32001-08-02 04:15:00 +00006901
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006902 init_slotdefs();
6903 for (p = slotdefs; p->name; )
6904 p = update_one_slot(type, p);
Tim Peters6d6c1a32001-08-02 04:15:00 +00006905}
Guido van Rossum705f0f52001-08-24 16:47:00 +00006906
Michael W. Hudson98bbc492002-11-26 14:47:27 +00006907static void
6908update_all_slots(PyTypeObject* type)
6909{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006910 slotdef *p;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00006911
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006912 init_slotdefs();
6913 for (p = slotdefs; p->name; p++) {
6914 /* update_slot returns int but can't actually fail */
6915 update_slot(type, p->name_strobj);
6916 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +00006917}
6918
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006919/* recurse_down_subclasses() and update_subclasses() are mutually
6920 recursive functions to call a callback for all subclasses,
6921 but refraining from recursing into subclasses that define 'name'. */
6922
6923static int
6924update_subclasses(PyTypeObject *type, PyObject *name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006925 update_callback callback, void *data)
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006926{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006927 if (callback(type, data) < 0)
6928 return -1;
6929 return recurse_down_subclasses(type, name, callback, data);
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006930}
6931
6932static int
6933recurse_down_subclasses(PyTypeObject *type, PyObject *name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006934 update_callback callback, void *data)
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006935{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006936 PyTypeObject *subclass;
6937 PyObject *ref, *subclasses, *dict;
Antoine Pitrou84745ab2013-10-29 21:31:25 +01006938 Py_ssize_t i;
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006939
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006940 subclasses = type->tp_subclasses;
6941 if (subclasses == NULL)
6942 return 0;
Antoine Pitrou84745ab2013-10-29 21:31:25 +01006943 assert(PyDict_CheckExact(subclasses));
6944 i = 0;
6945 while (PyDict_Next(subclasses, &i, NULL, &ref)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006946 assert(PyWeakref_CheckRef(ref));
6947 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
6948 assert(subclass != NULL);
6949 if ((PyObject *)subclass == Py_None)
6950 continue;
6951 assert(PyType_Check(subclass));
6952 /* Avoid recursing down into unaffected classes */
6953 dict = subclass->tp_dict;
6954 if (dict != NULL && PyDict_Check(dict) &&
6955 PyDict_GetItem(dict, name) != NULL)
6956 continue;
6957 if (update_subclasses(subclass, name, callback, data) < 0)
6958 return -1;
6959 }
6960 return 0;
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006961}
6962
Guido van Rossum6d204072001-10-21 00:44:31 +00006963/* This function is called by PyType_Ready() to populate the type's
6964 dictionary with method descriptors for function slots. For each
Guido van Rossum09638c12002-06-13 19:17:46 +00006965 function slot (like tp_repr) that's defined in the type, one or more
6966 corresponding descriptors are added in the type's tp_dict dictionary
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006967 under the appropriate name (like __repr__). Some function slots
Guido van Rossum09638c12002-06-13 19:17:46 +00006968 cause more than one descriptor to be added (for example, the nb_add
6969 slot adds both __add__ and __radd__ descriptors) and some function
6970 slots compete for the same descriptor (for example both sq_item and
6971 mp_subscript generate a __getitem__ descriptor).
6972
Ezio Melotti13925002011-03-16 11:05:33 +02006973 In the latter case, the first slotdef entry encountered wins. Since
Tim Petersbf9b2442003-03-23 05:35:36 +00006974 slotdef entries are sorted by the offset of the slot in the
Guido van Rossume5c691a2003-03-07 15:13:17 +00006975 PyHeapTypeObject, this gives us some control over disambiguating
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006976 between competing slots: the members of PyHeapTypeObject are listed
6977 from most general to least general, so the most general slot is
6978 preferred. In particular, because as_mapping comes before as_sequence,
6979 for a type that defines both mp_subscript and sq_item, mp_subscript
6980 wins.
Guido van Rossum09638c12002-06-13 19:17:46 +00006981
6982 This only adds new descriptors and doesn't overwrite entries in
6983 tp_dict that were previously defined. The descriptors contain a
6984 reference to the C function they must call, so that it's safe if they
6985 are copied into a subtype's __dict__ and the subtype has a different
6986 C function in its slot -- calling the method defined by the
6987 descriptor will call the C function that was used to create it,
6988 rather than the C function present in the slot when it is called.
6989 (This is important because a subtype may have a C function in the
6990 slot that calls the method from the dictionary, and we want to avoid
6991 infinite recursion here.) */
Guido van Rossum6d204072001-10-21 00:44:31 +00006992
6993static int
6994add_operators(PyTypeObject *type)
6995{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006996 PyObject *dict = type->tp_dict;
6997 slotdef *p;
6998 PyObject *descr;
6999 void **ptr;
Guido van Rossum6d204072001-10-21 00:44:31 +00007000
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007001 init_slotdefs();
7002 for (p = slotdefs; p->name; p++) {
7003 if (p->wrapper == NULL)
7004 continue;
7005 ptr = slotptr(type, p->offset);
7006 if (!ptr || !*ptr)
7007 continue;
7008 if (PyDict_GetItem(dict, p->name_strobj))
7009 continue;
Trent Nelsonab02db22012-09-18 21:58:03 -04007010 if (*ptr == (void *)PyObject_HashNotImplemented) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007011 /* Classes may prevent the inheritance of the tp_hash
7012 slot by storing PyObject_HashNotImplemented in it. Make it
7013 visible as a None value for the __hash__ attribute. */
7014 if (PyDict_SetItem(dict, p->name_strobj, Py_None) < 0)
7015 return -1;
7016 }
7017 else {
7018 descr = PyDescr_NewWrapper(type, p, *ptr);
7019 if (descr == NULL)
7020 return -1;
Benjamin Peterson27007dc2016-07-06 23:26:32 -07007021 if (PyDict_SetItem(dict, p->name_strobj, descr) < 0) {
7022 Py_DECREF(descr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007023 return -1;
Benjamin Peterson27007dc2016-07-06 23:26:32 -07007024 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007025 Py_DECREF(descr);
7026 }
7027 }
7028 if (type->tp_new != NULL) {
7029 if (add_tp_new_wrapper(type) < 0)
7030 return -1;
7031 }
7032 return 0;
Guido van Rossum6d204072001-10-21 00:44:31 +00007033}
7034
Guido van Rossum705f0f52001-08-24 16:47:00 +00007035
7036/* Cooperative 'super' */
7037
7038typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007039 PyObject_HEAD
7040 PyTypeObject *type;
7041 PyObject *obj;
7042 PyTypeObject *obj_type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00007043} superobject;
7044
Guido van Rossum6f799372001-09-20 20:46:19 +00007045static PyMemberDef super_members[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007046 {"__thisclass__", T_OBJECT, offsetof(superobject, type), READONLY,
7047 "the class invoking super()"},
7048 {"__self__", T_OBJECT, offsetof(superobject, obj), READONLY,
7049 "the instance invoking super(); may be None"},
7050 {"__self_class__", T_OBJECT, offsetof(superobject, obj_type), READONLY,
7051 "the type of the instance invoking super(); may be None"},
7052 {0}
Guido van Rossum41eb14d2001-08-30 23:13:11 +00007053};
7054
Guido van Rossum705f0f52001-08-24 16:47:00 +00007055static void
7056super_dealloc(PyObject *self)
7057{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007058 superobject *su = (superobject *)self;
Guido van Rossum705f0f52001-08-24 16:47:00 +00007059
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007060 _PyObject_GC_UNTRACK(self);
7061 Py_XDECREF(su->obj);
7062 Py_XDECREF(su->type);
7063 Py_XDECREF(su->obj_type);
7064 Py_TYPE(self)->tp_free(self);
Guido van Rossum705f0f52001-08-24 16:47:00 +00007065}
7066
7067static PyObject *
Guido van Rossum41eb14d2001-08-30 23:13:11 +00007068super_repr(PyObject *self)
7069{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007070 superobject *su = (superobject *)self;
Guido van Rossum41eb14d2001-08-30 23:13:11 +00007071
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007072 if (su->obj_type)
7073 return PyUnicode_FromFormat(
7074 "<super: <class '%s'>, <%s object>>",
7075 su->type ? su->type->tp_name : "NULL",
7076 su->obj_type->tp_name);
7077 else
7078 return PyUnicode_FromFormat(
7079 "<super: <class '%s'>, NULL>",
7080 su->type ? su->type->tp_name : "NULL");
Guido van Rossum41eb14d2001-08-30 23:13:11 +00007081}
7082
7083static PyObject *
Guido van Rossum705f0f52001-08-24 16:47:00 +00007084super_getattro(PyObject *self, PyObject *name)
7085{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007086 superobject *su = (superobject *)self;
Benjamin Peterson104b9e02015-02-05 22:29:14 -05007087 PyTypeObject *starttype;
7088 PyObject *mro;
7089 Py_ssize_t i, n;
Guido van Rossum705f0f52001-08-24 16:47:00 +00007090
Benjamin Peterson104b9e02015-02-05 22:29:14 -05007091 starttype = su->obj_type;
7092 if (starttype == NULL)
7093 goto skip;
7094
7095 /* We want __class__ to return the class of the super object
7096 (i.e. super, or a subclass), not the class of su->obj. */
7097 if (PyUnicode_Check(name) &&
7098 PyUnicode_GET_LENGTH(name) == 9 &&
7099 _PyUnicode_CompareWithId(name, &PyId___class__) == 0)
7100 goto skip;
7101
7102 mro = starttype->tp_mro;
7103 if (mro == NULL)
7104 goto skip;
7105
7106 assert(PyTuple_Check(mro));
7107 n = PyTuple_GET_SIZE(mro);
7108
7109 /* No need to check the last one: it's gonna be skipped anyway. */
7110 for (i = 0; i+1 < n; i++) {
7111 if ((PyObject *)(su->type) == PyTuple_GET_ITEM(mro, i))
7112 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007113 }
Benjamin Peterson104b9e02015-02-05 22:29:14 -05007114 i++; /* skip su->type (if any) */
7115 if (i >= n)
7116 goto skip;
Guido van Rossum76ba09f2003-04-16 19:40:58 +00007117
Benjamin Peterson104b9e02015-02-05 22:29:14 -05007118 /* keep a strong reference to mro because starttype->tp_mro can be
7119 replaced during PyDict_GetItem(dict, name) */
7120 Py_INCREF(mro);
7121 do {
7122 PyObject *res, *tmp, *dict;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007123 descrgetfunc f;
Guido van Rossum705f0f52001-08-24 16:47:00 +00007124
Benjamin Peterson104b9e02015-02-05 22:29:14 -05007125 tmp = PyTuple_GET_ITEM(mro, i);
7126 assert(PyType_Check(tmp));
Guido van Rossum155db9a2002-04-02 17:53:47 +00007127
Benjamin Peterson104b9e02015-02-05 22:29:14 -05007128 dict = ((PyTypeObject *)tmp)->tp_dict;
7129 assert(dict != NULL && PyDict_Check(dict));
7130
7131 res = PyDict_GetItem(dict, name);
7132 if (res != NULL) {
7133 Py_INCREF(res);
7134
7135 f = Py_TYPE(res)->tp_descr_get;
7136 if (f != NULL) {
7137 tmp = f(res,
7138 /* Only pass 'obj' param if this is instance-mode super
7139 (See SF ID #743627) */
7140 (su->obj == (PyObject *)starttype) ? NULL : su->obj,
7141 (PyObject *)starttype);
7142 Py_DECREF(res);
7143 res = tmp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007144 }
Benjamin Peterson104b9e02015-02-05 22:29:14 -05007145
7146 Py_DECREF(mro);
7147 return res;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007148 }
Benjamin Peterson104b9e02015-02-05 22:29:14 -05007149
7150 i++;
7151 } while (i < n);
7152 Py_DECREF(mro);
7153
7154 skip:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007155 return PyObject_GenericGetAttr(self, name);
Guido van Rossum705f0f52001-08-24 16:47:00 +00007156}
7157
Guido van Rossuma89d10e2003-02-12 03:58:38 +00007158static PyTypeObject *
Guido van Rossum5b443c62001-12-03 15:38:28 +00007159supercheck(PyTypeObject *type, PyObject *obj)
7160{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007161 /* Check that a super() call makes sense. Return a type object.
Guido van Rossuma89d10e2003-02-12 03:58:38 +00007162
Florent Xiclunaaa6c1d22011-12-12 18:54:29 +01007163 obj can be a class, or an instance of one:
Guido van Rossuma89d10e2003-02-12 03:58:38 +00007164
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007165 - If it is a class, it must be a subclass of 'type'. This case is
7166 used for class methods; the return value is obj.
Guido van Rossuma89d10e2003-02-12 03:58:38 +00007167
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007168 - If it is an instance, it must be an instance of 'type'. This is
7169 the normal case; the return value is obj.__class__.
Guido van Rossuma89d10e2003-02-12 03:58:38 +00007170
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007171 But... when obj is an instance, we want to allow for the case where
7172 Py_TYPE(obj) is not a subclass of type, but obj.__class__ is!
7173 This will allow using super() with a proxy for obj.
7174 */
Guido van Rossuma89d10e2003-02-12 03:58:38 +00007175
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007176 /* Check for first bullet above (special case) */
7177 if (PyType_Check(obj) && PyType_IsSubtype((PyTypeObject *)obj, type)) {
7178 Py_INCREF(obj);
7179 return (PyTypeObject *)obj;
7180 }
Guido van Rossum8e80a722003-02-18 19:22:22 +00007181
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007182 /* Normal case */
7183 if (PyType_IsSubtype(Py_TYPE(obj), type)) {
7184 Py_INCREF(Py_TYPE(obj));
7185 return Py_TYPE(obj);
7186 }
7187 else {
7188 /* Try the slow way */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007189 PyObject *class_attr;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00007190
Martin v. Löwisbfc6d742011-10-13 20:03:57 +02007191 class_attr = _PyObject_GetAttrId(obj, &PyId___class__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007192 if (class_attr != NULL &&
7193 PyType_Check(class_attr) &&
7194 (PyTypeObject *)class_attr != Py_TYPE(obj))
7195 {
7196 int ok = PyType_IsSubtype(
7197 (PyTypeObject *)class_attr, type);
7198 if (ok)
7199 return (PyTypeObject *)class_attr;
7200 }
Guido van Rossuma89d10e2003-02-12 03:58:38 +00007201
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007202 if (class_attr == NULL)
7203 PyErr_Clear();
7204 else
7205 Py_DECREF(class_attr);
7206 }
Guido van Rossuma89d10e2003-02-12 03:58:38 +00007207
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007208 PyErr_SetString(PyExc_TypeError,
7209 "super(type, obj): "
7210 "obj must be an instance or subtype of type");
7211 return NULL;
Guido van Rossum5b443c62001-12-03 15:38:28 +00007212}
7213
Guido van Rossum705f0f52001-08-24 16:47:00 +00007214static PyObject *
7215super_descr_get(PyObject *self, PyObject *obj, PyObject *type)
7216{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007217 superobject *su = (superobject *)self;
7218 superobject *newobj;
Guido van Rossum705f0f52001-08-24 16:47:00 +00007219
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007220 if (obj == NULL || obj == Py_None || su->obj != NULL) {
7221 /* Not binding to an object, or already bound */
7222 Py_INCREF(self);
7223 return self;
7224 }
7225 if (Py_TYPE(su) != &PySuper_Type)
7226 /* If su is an instance of a (strict) subclass of super,
7227 call its type */
7228 return PyObject_CallFunctionObjArgs((PyObject *)Py_TYPE(su),
7229 su->type, obj, NULL);
7230 else {
7231 /* Inline the common case */
7232 PyTypeObject *obj_type = supercheck(su->type, obj);
7233 if (obj_type == NULL)
7234 return NULL;
7235 newobj = (superobject *)PySuper_Type.tp_new(&PySuper_Type,
7236 NULL, NULL);
7237 if (newobj == NULL)
7238 return NULL;
7239 Py_INCREF(su->type);
7240 Py_INCREF(obj);
7241 newobj->type = su->type;
7242 newobj->obj = obj;
7243 newobj->obj_type = obj_type;
7244 return (PyObject *)newobj;
7245 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00007246}
7247
7248static int
7249super_init(PyObject *self, PyObject *args, PyObject *kwds)
7250{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007251 superobject *su = (superobject *)self;
7252 PyTypeObject *type = NULL;
7253 PyObject *obj = NULL;
7254 PyTypeObject *obj_type = NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00007255
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007256 if (!_PyArg_NoKeywords("super", kwds))
7257 return -1;
7258 if (!PyArg_ParseTuple(args, "|O!O:super", &PyType_Type, &type, &obj))
7259 return -1;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00007260
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007261 if (type == NULL) {
7262 /* Call super(), without args -- fill in from __class__
7263 and first local variable on the stack. */
Victor Stinner1c6970f2014-05-13 01:32:36 +02007264 PyFrameObject *f;
7265 PyCodeObject *co;
Victor Stinner0fcab4a2011-01-04 12:59:15 +00007266 Py_ssize_t i, n;
Victor Stinner1c6970f2014-05-13 01:32:36 +02007267 f = PyThreadState_GET()->frame;
7268 if (f == NULL) {
7269 PyErr_SetString(PyExc_RuntimeError,
7270 "super(): no current frame");
7271 return -1;
7272 }
7273 co = f->f_code;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007274 if (co == NULL) {
Benjamin Peterson6a42bd62012-09-01 23:04:38 -04007275 PyErr_SetString(PyExc_RuntimeError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007276 "super(): no code object");
7277 return -1;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00007278 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007279 if (co->co_argcount == 0) {
Benjamin Peterson6a42bd62012-09-01 23:04:38 -04007280 PyErr_SetString(PyExc_RuntimeError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007281 "super(): no arguments");
7282 return -1;
7283 }
7284 obj = f->f_localsplus[0];
Benjamin Peterson159ae412013-05-12 18:16:06 -05007285 if (obj == NULL && co->co_cell2arg) {
7286 /* The first argument might be a cell. */
7287 n = PyTuple_GET_SIZE(co->co_cellvars);
7288 for (i = 0; i < n; i++) {
7289 if (co->co_cell2arg[i] == 0) {
7290 PyObject *cell = f->f_localsplus[co->co_nlocals + i];
7291 assert(PyCell_Check(cell));
7292 obj = PyCell_GET(cell);
7293 break;
7294 }
7295 }
Guido van Rossum6832c812013-05-10 08:47:42 -07007296 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007297 if (obj == NULL) {
Benjamin Peterson6a42bd62012-09-01 23:04:38 -04007298 PyErr_SetString(PyExc_RuntimeError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007299 "super(): arg[0] deleted");
7300 return -1;
7301 }
7302 if (co->co_freevars == NULL)
7303 n = 0;
7304 else {
7305 assert(PyTuple_Check(co->co_freevars));
7306 n = PyTuple_GET_SIZE(co->co_freevars);
7307 }
7308 for (i = 0; i < n; i++) {
7309 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
7310 assert(PyUnicode_Check(name));
Victor Stinnerad14ccd2013-11-07 00:46:04 +01007311 if (!_PyUnicode_CompareWithId(name, &PyId___class__)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007312 Py_ssize_t index = co->co_nlocals +
7313 PyTuple_GET_SIZE(co->co_cellvars) + i;
7314 PyObject *cell = f->f_localsplus[index];
7315 if (cell == NULL || !PyCell_Check(cell)) {
Benjamin Peterson6a42bd62012-09-01 23:04:38 -04007316 PyErr_SetString(PyExc_RuntimeError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007317 "super(): bad __class__ cell");
7318 return -1;
7319 }
7320 type = (PyTypeObject *) PyCell_GET(cell);
7321 if (type == NULL) {
Benjamin Peterson6a42bd62012-09-01 23:04:38 -04007322 PyErr_SetString(PyExc_RuntimeError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007323 "super(): empty __class__ cell");
7324 return -1;
7325 }
7326 if (!PyType_Check(type)) {
Benjamin Peterson6a42bd62012-09-01 23:04:38 -04007327 PyErr_Format(PyExc_RuntimeError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007328 "super(): __class__ is not a type (%s)",
7329 Py_TYPE(type)->tp_name);
7330 return -1;
7331 }
7332 break;
7333 }
7334 }
7335 if (type == NULL) {
Benjamin Peterson6a42bd62012-09-01 23:04:38 -04007336 PyErr_SetString(PyExc_RuntimeError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007337 "super(): __class__ cell not found");
7338 return -1;
7339 }
7340 }
Guido van Rossumcd16bf62007-06-13 18:07:49 +00007341
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007342 if (obj == Py_None)
7343 obj = NULL;
7344 if (obj != NULL) {
7345 obj_type = supercheck(type, obj);
7346 if (obj_type == NULL)
7347 return -1;
7348 Py_INCREF(obj);
7349 }
7350 Py_INCREF(type);
Serhiy Storchaka3d749762016-04-13 15:27:33 +03007351 Py_XSETREF(su->type, type);
7352 Py_XSETREF(su->obj, obj);
7353 Py_XSETREF(su->obj_type, obj_type);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007354 return 0;
Guido van Rossum705f0f52001-08-24 16:47:00 +00007355}
7356
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007357PyDoc_STRVAR(super_doc,
Guido van Rossumcd16bf62007-06-13 18:07:49 +00007358"super() -> same as super(__class__, <first argument>)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00007359"super(type) -> unbound super object\n"
7360"super(type, obj) -> bound super object; requires isinstance(obj, type)\n"
Guido van Rossume705ef12001-08-29 15:47:06 +00007361"super(type, type2) -> bound super object; requires issubclass(type2, type)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00007362"Typical use to call a cooperative superclass method:\n"
7363"class C(B):\n"
7364" def meth(self, arg):\n"
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007365" super().meth(arg)\n"
Guido van Rossumcd16bf62007-06-13 18:07:49 +00007366"This works for class methods too:\n"
7367"class C(B):\n"
7368" @classmethod\n"
7369" def cmeth(cls, arg):\n"
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007370" super().cmeth(arg)\n");
Guido van Rossum705f0f52001-08-24 16:47:00 +00007371
Guido van Rossum048eb752001-10-02 21:24:57 +00007372static int
7373super_traverse(PyObject *self, visitproc visit, void *arg)
7374{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007375 superobject *su = (superobject *)self;
Guido van Rossum048eb752001-10-02 21:24:57 +00007376
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007377 Py_VISIT(su->obj);
7378 Py_VISIT(su->type);
7379 Py_VISIT(su->obj_type);
Guido van Rossum048eb752001-10-02 21:24:57 +00007380
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007381 return 0;
Guido van Rossum048eb752001-10-02 21:24:57 +00007382}
7383
Guido van Rossum705f0f52001-08-24 16:47:00 +00007384PyTypeObject PySuper_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007385 PyVarObject_HEAD_INIT(&PyType_Type, 0)
7386 "super", /* tp_name */
7387 sizeof(superobject), /* tp_basicsize */
7388 0, /* tp_itemsize */
7389 /* methods */
7390 super_dealloc, /* tp_dealloc */
7391 0, /* tp_print */
7392 0, /* tp_getattr */
7393 0, /* tp_setattr */
7394 0, /* tp_reserved */
7395 super_repr, /* tp_repr */
7396 0, /* tp_as_number */
7397 0, /* tp_as_sequence */
7398 0, /* tp_as_mapping */
7399 0, /* tp_hash */
7400 0, /* tp_call */
7401 0, /* tp_str */
7402 super_getattro, /* tp_getattro */
7403 0, /* tp_setattro */
7404 0, /* tp_as_buffer */
7405 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
7406 Py_TPFLAGS_BASETYPE, /* tp_flags */
7407 super_doc, /* tp_doc */
7408 super_traverse, /* tp_traverse */
7409 0, /* tp_clear */
7410 0, /* tp_richcompare */
7411 0, /* tp_weaklistoffset */
7412 0, /* tp_iter */
7413 0, /* tp_iternext */
7414 0, /* tp_methods */
7415 super_members, /* tp_members */
7416 0, /* tp_getset */
7417 0, /* tp_base */
7418 0, /* tp_dict */
7419 super_descr_get, /* tp_descr_get */
7420 0, /* tp_descr_set */
7421 0, /* tp_dictoffset */
7422 super_init, /* tp_init */
7423 PyType_GenericAlloc, /* tp_alloc */
7424 PyType_GenericNew, /* tp_new */
7425 PyObject_GC_Del, /* tp_free */
Guido van Rossum705f0f52001-08-24 16:47:00 +00007426};