blob: bb83530d588780979a24b8de0afe5558a5d6ac22 [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;
318 Py_XDECREF(method_cache[i].name);
319 method_cache[i].name = Py_None;
320 Py_INCREF(Py_None);
321 }
322 /* mark all version tags as invalid */
323 PyType_Modified(&PyBaseObject_Type);
324 return 1;
325 }
326 bases = type->tp_bases;
327 n = PyTuple_GET_SIZE(bases);
328 for (i = 0; i < n; i++) {
329 PyObject *b = PyTuple_GET_ITEM(bases, i);
330 assert(PyType_Check(b));
331 if (!assign_version_tag((PyTypeObject *)b))
332 return 0;
333 }
334 type->tp_flags |= Py_TPFLAGS_VALID_VERSION_TAG;
335 return 1;
Christian Heimesa62da1d2008-01-12 19:39:10 +0000336}
337
338
Guido van Rossum6f799372001-09-20 20:46:19 +0000339static PyMemberDef type_members[] = {
Benjamin Peterson0e102062010-08-25 23:13:17 +0000340 {"__basicsize__", T_PYSSIZET, offsetof(PyTypeObject,tp_basicsize),READONLY},
341 {"__itemsize__", T_PYSSIZET, offsetof(PyTypeObject, tp_itemsize), READONLY},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000342 {"__flags__", T_LONG, offsetof(PyTypeObject, tp_flags), READONLY},
343 {"__weakrefoffset__", T_LONG,
344 offsetof(PyTypeObject, tp_weaklistoffset), READONLY},
345 {"__base__", T_OBJECT, offsetof(PyTypeObject, tp_base), READONLY},
346 {"__dictoffset__", T_LONG,
347 offsetof(PyTypeObject, tp_dictoffset), READONLY},
348 {"__mro__", T_OBJECT, offsetof(PyTypeObject, tp_mro), READONLY},
349 {0}
Tim Peters6d6c1a32001-08-02 04:15:00 +0000350};
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000351
Benjamin Petersond9f23d22011-08-17 11:54:03 -0500352static int
353check_set_special_type_attr(PyTypeObject *type, PyObject *value, const char *name)
354{
355 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
356 PyErr_Format(PyExc_TypeError,
357 "can't set %s.%s", type->tp_name, name);
358 return 0;
359 }
360 if (!value) {
361 PyErr_Format(PyExc_TypeError,
362 "can't delete %s.%s", type->tp_name, name);
363 return 0;
364 }
365 return 1;
366}
367
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000368static PyObject *
Guido van Rossumc3542212001-08-16 09:18:56 +0000369type_name(PyTypeObject *type, void *context)
370{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000371 const char *s;
Guido van Rossumc3542212001-08-16 09:18:56 +0000372
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000373 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
374 PyHeapTypeObject* et = (PyHeapTypeObject*)type;
Tim Petersea7f75d2002-12-07 21:39:16 +0000375
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000376 Py_INCREF(et->ht_name);
377 return et->ht_name;
378 }
379 else {
380 s = strrchr(type->tp_name, '.');
381 if (s == NULL)
382 s = type->tp_name;
383 else
384 s++;
385 return PyUnicode_FromString(s);
386 }
Guido van Rossumc3542212001-08-16 09:18:56 +0000387}
388
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100389static PyObject *
390type_qualname(PyTypeObject *type, void *context)
391{
392 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
393 PyHeapTypeObject* et = (PyHeapTypeObject*)type;
394 Py_INCREF(et->ht_qualname);
395 return et->ht_qualname;
396 }
397 else {
398 return type_name(type, context);
399 }
400}
401
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000402static int
403type_set_name(PyTypeObject *type, PyObject *value, void *context)
404{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000405 PyHeapTypeObject* et;
406 char *tp_name;
407 PyObject *tmp;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000408
Benjamin Petersond9f23d22011-08-17 11:54:03 -0500409 if (!check_set_special_type_attr(type, value, "__name__"))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000410 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000411 if (!PyUnicode_Check(value)) {
412 PyErr_Format(PyExc_TypeError,
413 "can only assign string to %s.__name__, not '%s'",
414 type->tp_name, Py_TYPE(value)->tp_name);
415 return -1;
416 }
Guido van Rossume845c0f2007-11-02 23:07:07 +0000417
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000418 /* Check absence of null characters */
419 tmp = PyUnicode_FromStringAndSize("\0", 1);
420 if (tmp == NULL)
421 return -1;
422 if (PyUnicode_Contains(value, tmp) != 0) {
423 Py_DECREF(tmp);
424 PyErr_Format(PyExc_ValueError,
425 "__name__ must not contain null bytes");
426 return -1;
427 }
428 Py_DECREF(tmp);
Guido van Rossume845c0f2007-11-02 23:07:07 +0000429
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000430 tp_name = _PyUnicode_AsString(value);
431 if (tp_name == NULL)
432 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000433
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000434 et = (PyHeapTypeObject*)type;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000435
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000436 Py_INCREF(value);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000437
Mark Dickinson64aafeb2013-04-13 15:26:58 +0100438 /* Wait until et is a sane state before Py_DECREF'ing the old et->ht_name
439 value. (Bug #16447.) */
440 tmp = et->ht_name;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000441 et->ht_name = value;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000442
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000443 type->tp_name = tp_name;
Mark Dickinson64aafeb2013-04-13 15:26:58 +0100444 Py_DECREF(tmp);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000445
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000446 return 0;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000447}
448
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100449static int
450type_set_qualname(PyTypeObject *type, PyObject *value, void *context)
451{
452 PyHeapTypeObject* et;
453
Benjamin Peterson2c05a2e2012-10-31 00:01:15 -0400454 if (!check_set_special_type_attr(type, value, "__qualname__"))
455 return -1;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100456 if (!PyUnicode_Check(value)) {
457 PyErr_Format(PyExc_TypeError,
458 "can only assign string to %s.__qualname__, not '%s'",
459 type->tp_name, Py_TYPE(value)->tp_name);
460 return -1;
461 }
462
463 et = (PyHeapTypeObject*)type;
464 Py_INCREF(value);
465 Py_DECREF(et->ht_qualname);
466 et->ht_qualname = value;
467 return 0;
468}
469
Guido van Rossumc3542212001-08-16 09:18:56 +0000470static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000471type_module(PyTypeObject *type, void *context)
Guido van Rossum29ca26e1995-01-07 11:58:15 +0000472{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000473 char *s;
Guido van Rossumc3542212001-08-16 09:18:56 +0000474
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000475 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
Victor Stinnerad14ccd2013-11-07 00:46:04 +0100476 PyObject *mod = _PyDict_GetItemId(type->tp_dict, &PyId___module__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000477 if (!mod) {
478 PyErr_Format(PyExc_AttributeError, "__module__");
479 return 0;
480 }
481 Py_XINCREF(mod);
482 return mod;
483 }
484 else {
Victor Stinnerad14ccd2013-11-07 00:46:04 +0100485 PyObject *name;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000486 s = strrchr(type->tp_name, '.');
487 if (s != NULL)
488 return PyUnicode_FromStringAndSize(
489 type->tp_name, (Py_ssize_t)(s - type->tp_name));
Victor Stinnerbd303c12013-11-07 23:07:29 +0100490 name = _PyUnicode_FromId(&PyId_builtins);
Victor Stinnerad14ccd2013-11-07 00:46:04 +0100491 Py_XINCREF(name);
492 return name;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000493 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000494}
495
Guido van Rossum3926a632001-09-25 16:25:58 +0000496static int
497type_set_module(PyTypeObject *type, PyObject *value, void *context)
498{
Benjamin Petersond9f23d22011-08-17 11:54:03 -0500499 if (!check_set_special_type_attr(type, value, "__module__"))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000500 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000501
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000502 PyType_Modified(type);
Christian Heimesa62da1d2008-01-12 19:39:10 +0000503
Victor Stinner3c1e4812012-03-26 22:10:51 +0200504 return _PyDict_SetItemId(type->tp_dict, &PyId___module__, value);
Guido van Rossum3926a632001-09-25 16:25:58 +0000505}
506
Tim Peters6d6c1a32001-08-02 04:15:00 +0000507static PyObject *
Christian Heimes9e7f1d22008-02-28 12:27:11 +0000508type_abstractmethods(PyTypeObject *type, void *context)
509{
Benjamin Petersonaec5fd12010-10-02 00:03:31 +0000510 PyObject *mod = NULL;
Benjamin Peterson84060b82010-10-03 02:13:39 +0000511 /* type itself has an __abstractmethods__ descriptor (this). Don't return
512 that. */
Benjamin Petersonaec5fd12010-10-02 00:03:31 +0000513 if (type != &PyType_Type)
Victor Stinner3688aa92013-11-06 18:59:18 +0100514 mod = _PyDict_GetItemId(type->tp_dict, &PyId___abstractmethods__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000515 if (!mod) {
Victor Stinner3688aa92013-11-06 18:59:18 +0100516 PyObject *message = _PyUnicode_FromId(&PyId___abstractmethods__);
517 if (message)
518 PyErr_SetObject(PyExc_AttributeError, message);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000519 return NULL;
520 }
521 Py_XINCREF(mod);
522 return mod;
Christian Heimes9e7f1d22008-02-28 12:27:11 +0000523}
524
525static int
526type_set_abstractmethods(PyTypeObject *type, PyObject *value, void *context)
527{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000528 /* __abstractmethods__ should only be set once on a type, in
529 abc.ABCMeta.__new__, so this function doesn't do anything
530 special to update subclasses.
531 */
Antoine Pitrou6f430e42012-08-15 23:18:25 +0200532 int abstract, res;
Benjamin Peterson477ba912011-01-12 15:34:01 +0000533 if (value != NULL) {
Antoine Pitrou6f430e42012-08-15 23:18:25 +0200534 abstract = PyObject_IsTrue(value);
535 if (abstract < 0)
536 return -1;
Victor Stinner3688aa92013-11-06 18:59:18 +0100537 res = _PyDict_SetItemId(type->tp_dict, &PyId___abstractmethods__, value);
Benjamin Peterson477ba912011-01-12 15:34:01 +0000538 }
539 else {
Antoine Pitrou6f430e42012-08-15 23:18:25 +0200540 abstract = 0;
Victor Stinner3688aa92013-11-06 18:59:18 +0100541 res = _PyDict_DelItemId(type->tp_dict, &PyId___abstractmethods__);
Benjamin Peterson477ba912011-01-12 15:34:01 +0000542 if (res && PyErr_ExceptionMatches(PyExc_KeyError)) {
Victor Stinner3688aa92013-11-06 18:59:18 +0100543 PyObject *message = _PyUnicode_FromId(&PyId___abstractmethods__);
544 if (message)
545 PyErr_SetObject(PyExc_AttributeError, message);
Benjamin Peterson477ba912011-01-12 15:34:01 +0000546 return -1;
547 }
548 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000549 if (res == 0) {
550 PyType_Modified(type);
Antoine Pitrou6f430e42012-08-15 23:18:25 +0200551 if (abstract)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000552 type->tp_flags |= Py_TPFLAGS_IS_ABSTRACT;
Antoine Pitrou6f430e42012-08-15 23:18:25 +0200553 else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000554 type->tp_flags &= ~Py_TPFLAGS_IS_ABSTRACT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000555 }
556 return res;
Christian Heimes9e7f1d22008-02-28 12:27:11 +0000557}
558
559static PyObject *
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000560type_get_bases(PyTypeObject *type, void *context)
561{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000562 Py_INCREF(type->tp_bases);
563 return type->tp_bases;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000564}
565
566static PyTypeObject *best_base(PyObject *);
Benjamin Peterson104b9e02015-02-05 22:29:14 -0500567static int mro_internal(PyTypeObject *, PyObject **);
Steve Dowerb4e20bb2015-02-06 08:50:23 -0800568Py_LOCAL_INLINE(int) type_is_subtype_base_chain(PyTypeObject *, PyTypeObject *);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000569static int compatible_for_assignment(PyTypeObject *, PyTypeObject *, char *);
570static int add_subclass(PyTypeObject*, PyTypeObject*);
Benjamin Peterson104b9e02015-02-05 22:29:14 -0500571static int add_all_subclasses(PyTypeObject *type, PyObject *bases);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000572static void remove_subclass(PyTypeObject *, PyTypeObject *);
Antoine Pitrou84745ab2013-10-29 21:31:25 +0100573static void remove_all_subclasses(PyTypeObject *type, PyObject *bases);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000574static void update_all_slots(PyTypeObject *);
575
Guido van Rossum8d24ee92003-03-24 23:49:49 +0000576typedef int (*update_callback)(PyTypeObject *, void *);
577static int update_subclasses(PyTypeObject *type, PyObject *name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000578 update_callback callback, void *data);
Guido van Rossum8d24ee92003-03-24 23:49:49 +0000579static int recurse_down_subclasses(PyTypeObject *type, PyObject *name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000580 update_callback callback, void *data);
Benjamin Peterson104b9e02015-02-05 22:29:14 -0500581static PyObject *type_subclasses(PyTypeObject *type, PyObject *ignored);
Guido van Rossum8d24ee92003-03-24 23:49:49 +0000582
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000583static int
Benjamin Peterson104b9e02015-02-05 22:29:14 -0500584mro_hierarchy(PyTypeObject *type, PyObject *temp)
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000585{
Benjamin Peterson104b9e02015-02-05 22:29:14 -0500586 int res;
587 PyObject *new_mro, *old_mro;
588 PyObject *tuple;
589 PyObject *subclasses;
590 Py_ssize_t i, n;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000591
Benjamin Peterson104b9e02015-02-05 22:29:14 -0500592 res = mro_internal(type, &old_mro);
593 if (res <= 0)
594 /* error / reentrance */
595 return res;
596 new_mro = type->tp_mro;
Antoine Pitrou84745ab2013-10-29 21:31:25 +0100597
Benjamin Peterson104b9e02015-02-05 22:29:14 -0500598 if (old_mro != NULL)
599 tuple = PyTuple_Pack(3, type, new_mro, old_mro);
600 else
601 tuple = PyTuple_Pack(2, type, new_mro);
602
603 if (tuple != NULL)
604 res = PyList_Append(temp, tuple);
605 else
606 res = -1;
607 Py_XDECREF(tuple);
608
609 if (res < 0) {
610 type->tp_mro = old_mro;
611 Py_DECREF(new_mro);
612 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000613 }
Benjamin Peterson104b9e02015-02-05 22:29:14 -0500614 Py_XDECREF(old_mro);
615
616 /* Obtain a copy of subclasses list to iterate over.
617
618 Otherwise type->tp_subclasses might be altered
619 in the middle of the loop, for example, through a custom mro(),
620 by invoking type_set_bases on some subclass of the type
621 which in turn calls remove_subclass/add_subclass on this type.
622
623 Finally, this makes things simple avoiding the need to deal
624 with dictionary iterators and weak references.
625 */
626 subclasses = type_subclasses(type, NULL);
627 if (subclasses == NULL)
628 return -1;
629 n = PyList_GET_SIZE(subclasses);
630 for (i = 0; i < n; i++) {
631 PyTypeObject *subclass;
632 subclass = (PyTypeObject *)PyList_GET_ITEM(subclasses, i);
633 res = mro_hierarchy(subclass, temp);
634 if (res < 0)
635 break;
636 }
637 Py_DECREF(subclasses);
638
639 return res;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000640}
641
642static int
Benjamin Peterson104b9e02015-02-05 22:29:14 -0500643type_set_bases(PyTypeObject *type, PyObject *new_bases, void *context)
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000644{
Benjamin Peterson104b9e02015-02-05 22:29:14 -0500645 int res = 0;
646 PyObject *temp;
647 PyObject *old_bases;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000648 PyTypeObject *new_base, *old_base;
Benjamin Peterson104b9e02015-02-05 22:29:14 -0500649 Py_ssize_t i;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000650
Benjamin Peterson104b9e02015-02-05 22:29:14 -0500651 if (!check_set_special_type_attr(type, new_bases, "__bases__"))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000652 return -1;
Benjamin Peterson104b9e02015-02-05 22:29:14 -0500653 if (!PyTuple_Check(new_bases)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000654 PyErr_Format(PyExc_TypeError,
655 "can only assign tuple to %s.__bases__, not %s",
Benjamin Peterson104b9e02015-02-05 22:29:14 -0500656 type->tp_name, Py_TYPE(new_bases)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000657 return -1;
658 }
Benjamin Peterson104b9e02015-02-05 22:29:14 -0500659 if (PyTuple_GET_SIZE(new_bases) == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000660 PyErr_Format(PyExc_TypeError,
661 "can only assign non-empty tuple to %s.__bases__, not ()",
662 type->tp_name);
663 return -1;
664 }
Benjamin Peterson104b9e02015-02-05 22:29:14 -0500665 for (i = 0; i < PyTuple_GET_SIZE(new_bases); i++) {
666 PyObject *ob;
667 PyTypeObject *base;
668
669 ob = PyTuple_GET_ITEM(new_bases, i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000670 if (!PyType_Check(ob)) {
Benjamin Petersonb6af60c2012-04-01 18:49:54 -0400671 PyErr_Format(PyExc_TypeError,
Benjamin Peterson9ee601e2012-04-01 18:51:37 -0400672 "%s.__bases__ must be tuple of classes, not '%s'",
Benjamin Petersonb6af60c2012-04-01 18:49:54 -0400673 type->tp_name, Py_TYPE(ob)->tp_name);
674 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000675 }
Benjamin Peterson104b9e02015-02-05 22:29:14 -0500676
677 base = (PyTypeObject*)ob;
678 if (PyType_IsSubtype(base, type) ||
679 /* In case of reentering here again through a custom mro()
680 the above check is not enough since it relies on
681 base->tp_mro which would gonna be updated inside
682 mro_internal only upon returning from the mro().
683
684 However, base->tp_base has already been assigned (see
685 below), which in turn may cause an inheritance cycle
686 through tp_base chain. And this is definitely
687 not what you want to ever happen. */
688 (base->tp_mro != NULL && type_is_subtype_base_chain(base, type))) {
689
Benjamin Peterson3471bb62012-04-01 18:48:40 -0400690 PyErr_SetString(PyExc_TypeError,
691 "a __bases__ item causes an inheritance cycle");
692 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000693 }
694 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000695
Benjamin Peterson104b9e02015-02-05 22:29:14 -0500696 new_base = best_base(new_bases);
697 if (new_base == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000698 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000699
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000700 if (!compatible_for_assignment(type->tp_base, new_base, "__bases__"))
701 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000702
Benjamin Peterson104b9e02015-02-05 22:29:14 -0500703 Py_INCREF(new_bases);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000704 Py_INCREF(new_base);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000705
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000706 old_bases = type->tp_bases;
707 old_base = type->tp_base;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000708
Benjamin Peterson104b9e02015-02-05 22:29:14 -0500709 type->tp_bases = new_bases;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000710 type->tp_base = new_base;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000711
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000712 temp = PyList_New(0);
Benjamin Peterson104b9e02015-02-05 22:29:14 -0500713 if (temp == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000714 goto bail;
Benjamin Peterson104b9e02015-02-05 22:29:14 -0500715 if (mro_hierarchy(type, temp) < 0)
716 goto undo;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000717 Py_DECREF(temp);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000718
Benjamin Peterson104b9e02015-02-05 22:29:14 -0500719 /* Take no action in case if type->tp_bases has been replaced
720 through reentrance. */
721 if (type->tp_bases == new_bases) {
722 /* any base that was in __bases__ but now isn't, we
723 need to remove |type| from its tp_subclasses.
724 conversely, any class now in __bases__ that wasn't
725 needs to have |type| added to its subclasses. */
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000726
Benjamin Peterson104b9e02015-02-05 22:29:14 -0500727 /* for now, sod that: just remove from all old_bases,
728 add to all new_bases */
729 remove_all_subclasses(type, old_bases);
730 res = add_all_subclasses(type, new_bases);
731 update_all_slots(type);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000732 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000733
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000734 Py_DECREF(old_bases);
735 Py_DECREF(old_base);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000736
Benjamin Peterson104b9e02015-02-05 22:29:14 -0500737 return res;
738
739 undo:
740 for (i = PyList_GET_SIZE(temp) - 1; i >= 0; i--) {
741 PyTypeObject *cls;
742 PyObject *new_mro, *old_mro = NULL;
743
744 PyArg_UnpackTuple(PyList_GET_ITEM(temp, i),
745 "", 2, 3, &cls, &new_mro, &old_mro);
746 /* Do not rollback if cls has a newer version of MRO. */
747 if (cls->tp_mro == new_mro) {
748 Py_XINCREF(old_mro);
749 cls->tp_mro = old_mro;
750 Py_DECREF(new_mro);
751 }
752 }
753 Py_DECREF(temp);
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000754
755 bail:
Benjamin Peterson104b9e02015-02-05 22:29:14 -0500756 if (type->tp_bases == new_bases) {
757 assert(type->tp_base == new_base);
Michael W. Hudsone723e452003-08-07 14:58:10 +0000758
Benjamin Peterson104b9e02015-02-05 22:29:14 -0500759 type->tp_bases = old_bases;
760 type->tp_base = old_base;
761
762 Py_DECREF(new_bases);
763 Py_DECREF(new_base);
764 }
765 else {
766 Py_DECREF(old_bases);
767 Py_DECREF(old_base);
768 }
Tim Petersea7f75d2002-12-07 21:39:16 +0000769
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000770 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000771}
772
773static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000774type_dict(PyTypeObject *type, void *context)
775{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000776 if (type->tp_dict == NULL) {
777 Py_INCREF(Py_None);
778 return Py_None;
779 }
780 return PyDictProxy_New(type->tp_dict);
Guido van Rossum29ca26e1995-01-07 11:58:15 +0000781}
782
Tim Peters24008312002-03-17 18:56:20 +0000783static PyObject *
784type_get_doc(PyTypeObject *type, void *context)
785{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000786 PyObject *result;
Larry Hastings5c661892014-01-24 06:17:25 -0800787 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE) && type->tp_doc != NULL) {
Larry Hastings2623c8c2014-02-08 22:15:29 -0800788 return _PyType_GetDocFromInternalDoc(type->tp_name, type->tp_doc);
Larry Hastings5c661892014-01-24 06:17:25 -0800789 }
Victor Stinner3c1e4812012-03-26 22:10:51 +0200790 result = _PyDict_GetItemId(type->tp_dict, &PyId___doc__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000791 if (result == NULL) {
792 result = Py_None;
793 Py_INCREF(result);
794 }
795 else if (Py_TYPE(result)->tp_descr_get) {
796 result = Py_TYPE(result)->tp_descr_get(result, NULL,
797 (PyObject *)type);
798 }
799 else {
800 Py_INCREF(result);
801 }
802 return result;
Tim Peters24008312002-03-17 18:56:20 +0000803}
804
Larry Hastings5c661892014-01-24 06:17:25 -0800805static PyObject *
806type_get_text_signature(PyTypeObject *type, void *context)
807{
Larry Hastings2623c8c2014-02-08 22:15:29 -0800808 return _PyType_GetTextSignatureFromInternalDoc(type->tp_name, type->tp_doc);
Larry Hastings5c661892014-01-24 06:17:25 -0800809}
810
Benjamin Peterson01fc6cd2011-08-17 12:03:47 -0500811static int
812type_set_doc(PyTypeObject *type, PyObject *value, void *context)
813{
814 if (!check_set_special_type_attr(type, value, "__doc__"))
815 return -1;
816 PyType_Modified(type);
Victor Stinner3c1e4812012-03-26 22:10:51 +0200817 return _PyDict_SetItemId(type->tp_dict, &PyId___doc__, value);
Benjamin Peterson01fc6cd2011-08-17 12:03:47 -0500818}
819
Antoine Pitrouec569b72008-08-26 22:40:48 +0000820static PyObject *
821type___instancecheck__(PyObject *type, PyObject *inst)
822{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000823 switch (_PyObject_RealIsInstance(inst, type)) {
824 case -1:
825 return NULL;
826 case 0:
827 Py_RETURN_FALSE;
828 default:
829 Py_RETURN_TRUE;
830 }
Antoine Pitrouec569b72008-08-26 22:40:48 +0000831}
832
833
834static PyObject *
Antoine Pitrouec569b72008-08-26 22:40:48 +0000835type___subclasscheck__(PyObject *type, PyObject *inst)
836{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000837 switch (_PyObject_RealIsSubclass(inst, type)) {
838 case -1:
839 return NULL;
840 case 0:
841 Py_RETURN_FALSE;
842 default:
843 Py_RETURN_TRUE;
844 }
Antoine Pitrouec569b72008-08-26 22:40:48 +0000845}
846
Antoine Pitrouec569b72008-08-26 22:40:48 +0000847
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000848static PyGetSetDef type_getsets[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000849 {"__name__", (getter)type_name, (setter)type_set_name, NULL},
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100850 {"__qualname__", (getter)type_qualname, (setter)type_set_qualname, NULL},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000851 {"__bases__", (getter)type_get_bases, (setter)type_set_bases, NULL},
852 {"__module__", (getter)type_module, (setter)type_set_module, NULL},
853 {"__abstractmethods__", (getter)type_abstractmethods,
854 (setter)type_set_abstractmethods, NULL},
855 {"__dict__", (getter)type_dict, NULL, NULL},
Benjamin Peterson01fc6cd2011-08-17 12:03:47 -0500856 {"__doc__", (getter)type_get_doc, (setter)type_set_doc, NULL},
Larry Hastings5c661892014-01-24 06:17:25 -0800857 {"__text_signature__", (getter)type_get_text_signature, NULL, NULL},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000858 {0}
Tim Peters6d6c1a32001-08-02 04:15:00 +0000859};
860
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000861static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000862type_repr(PyTypeObject *type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000863{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000864 PyObject *mod, *name, *rtn;
Guido van Rossumc3542212001-08-16 09:18:56 +0000865
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000866 mod = type_module(type, NULL);
867 if (mod == NULL)
868 PyErr_Clear();
869 else if (!PyUnicode_Check(mod)) {
870 Py_DECREF(mod);
871 mod = NULL;
872 }
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100873 name = type_qualname(type, NULL);
Christian Heimesa0e7e412012-09-10 03:00:14 +0200874 if (name == NULL) {
875 Py_XDECREF(mod);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000876 return NULL;
Christian Heimesa0e7e412012-09-10 03:00:14 +0200877 }
Barry Warsaw7ce36942001-08-24 18:34:26 +0000878
Victor Stinnerbd303c12013-11-07 23:07:29 +0100879 if (mod != NULL && _PyUnicode_CompareWithId(mod, &PyId_builtins))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000880 rtn = PyUnicode_FromFormat("<class '%U.%U'>", mod, name);
881 else
882 rtn = PyUnicode_FromFormat("<class '%s'>", type->tp_name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000883
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000884 Py_XDECREF(mod);
885 Py_DECREF(name);
886 return rtn;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000887}
888
Tim Peters6d6c1a32001-08-02 04:15:00 +0000889static PyObject *
890type_call(PyTypeObject *type, PyObject *args, PyObject *kwds)
891{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000892 PyObject *obj;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000893
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000894 if (type->tp_new == NULL) {
895 PyErr_Format(PyExc_TypeError,
896 "cannot create '%.100s' instances",
897 type->tp_name);
898 return NULL;
899 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000900
Victor Stinner33824f62013-08-26 14:05:19 +0200901#ifdef Py_DEBUG
902 /* type_call() must not be called with an exception set,
903 because it may clear it (directly or indirectly) and so the
904 caller looses its exception */
905 assert(!PyErr_Occurred());
906#endif
907
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000908 obj = type->tp_new(type, args, kwds);
909 if (obj != NULL) {
910 /* Ugly exception: when the call was type(something),
911 don't call tp_init on the result. */
912 if (type == &PyType_Type &&
913 PyTuple_Check(args) && PyTuple_GET_SIZE(args) == 1 &&
914 (kwds == NULL ||
915 (PyDict_Check(kwds) && PyDict_Size(kwds) == 0)))
916 return obj;
917 /* If the returned object is not an instance of type,
918 it won't be initialized. */
919 if (!PyType_IsSubtype(Py_TYPE(obj), type))
920 return obj;
921 type = Py_TYPE(obj);
Victor Stinner3997cfd2013-07-16 22:51:21 +0200922 if (type->tp_init != NULL) {
923 int res = type->tp_init(obj, args, kwds);
924 if (res < 0) {
925 Py_DECREF(obj);
926 obj = NULL;
927 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000928 }
929 }
930 return obj;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000931}
932
933PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000934PyType_GenericAlloc(PyTypeObject *type, Py_ssize_t nitems)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000935{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000936 PyObject *obj;
937 const size_t size = _PyObject_VAR_SIZE(type, nitems+1);
938 /* note that we need to add one, for the sentinel */
Tim Peters406fe3b2001-10-06 19:04:01 +0000939
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000940 if (PyType_IS_GC(type))
941 obj = _PyObject_GC_Malloc(size);
942 else
943 obj = (PyObject *)PyObject_MALLOC(size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000944
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000945 if (obj == NULL)
946 return PyErr_NoMemory();
Tim Peters406fe3b2001-10-06 19:04:01 +0000947
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000948 memset(obj, '\0', size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000949
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000950 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
951 Py_INCREF(type);
Tim Peters406fe3b2001-10-06 19:04:01 +0000952
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000953 if (type->tp_itemsize == 0)
Christian Heimesd3afe782013-12-04 09:27:47 +0100954 (void)PyObject_INIT(obj, type);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000955 else
956 (void) PyObject_INIT_VAR((PyVarObject *)obj, type, nitems);
Tim Peters406fe3b2001-10-06 19:04:01 +0000957
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000958 if (PyType_IS_GC(type))
959 _PyObject_GC_TRACK(obj);
960 return obj;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000961}
962
963PyObject *
964PyType_GenericNew(PyTypeObject *type, PyObject *args, PyObject *kwds)
965{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000966 return type->tp_alloc(type, 0);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000967}
968
Guido van Rossum9475a232001-10-05 20:51:39 +0000969/* Helpers for subtyping */
970
971static int
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000972traverse_slots(PyTypeObject *type, PyObject *self, visitproc visit, void *arg)
973{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000974 Py_ssize_t i, n;
975 PyMemberDef *mp;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000976
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000977 n = Py_SIZE(type);
978 mp = PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type);
979 for (i = 0; i < n; i++, mp++) {
980 if (mp->type == T_OBJECT_EX) {
981 char *addr = (char *)self + mp->offset;
982 PyObject *obj = *(PyObject **)addr;
983 if (obj != NULL) {
984 int err = visit(obj, arg);
985 if (err)
986 return err;
987 }
988 }
989 }
990 return 0;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000991}
992
993static int
Guido van Rossum9475a232001-10-05 20:51:39 +0000994subtype_traverse(PyObject *self, visitproc visit, void *arg)
995{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000996 PyTypeObject *type, *base;
997 traverseproc basetraverse;
Guido van Rossum9475a232001-10-05 20:51:39 +0000998
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000999 /* Find the nearest base with a different tp_traverse,
1000 and traverse slots while we're at it */
1001 type = Py_TYPE(self);
1002 base = type;
1003 while ((basetraverse = base->tp_traverse) == subtype_traverse) {
1004 if (Py_SIZE(base)) {
1005 int err = traverse_slots(base, self, visit, arg);
1006 if (err)
1007 return err;
1008 }
1009 base = base->tp_base;
1010 assert(base);
1011 }
Guido van Rossum9475a232001-10-05 20:51:39 +00001012
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001013 if (type->tp_dictoffset != base->tp_dictoffset) {
1014 PyObject **dictptr = _PyObject_GetDictPtr(self);
1015 if (dictptr && *dictptr)
1016 Py_VISIT(*dictptr);
1017 }
Guido van Rossum9475a232001-10-05 20:51:39 +00001018
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001019 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
1020 /* For a heaptype, the instances count as references
1021 to the type. Traverse the type so the collector
1022 can find cycles involving this link. */
1023 Py_VISIT(type);
Guido van Rossuma3862092002-06-10 15:24:42 +00001024
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001025 if (basetraverse)
1026 return basetraverse(self, visit, arg);
1027 return 0;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001028}
1029
1030static void
1031clear_slots(PyTypeObject *type, PyObject *self)
1032{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001033 Py_ssize_t i, n;
1034 PyMemberDef *mp;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001035
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001036 n = Py_SIZE(type);
1037 mp = PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type);
1038 for (i = 0; i < n; i++, mp++) {
1039 if (mp->type == T_OBJECT_EX && !(mp->flags & READONLY)) {
1040 char *addr = (char *)self + mp->offset;
1041 PyObject *obj = *(PyObject **)addr;
1042 if (obj != NULL) {
1043 *(PyObject **)addr = NULL;
1044 Py_DECREF(obj);
1045 }
1046 }
1047 }
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001048}
1049
1050static int
1051subtype_clear(PyObject *self)
1052{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001053 PyTypeObject *type, *base;
1054 inquiry baseclear;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001055
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001056 /* Find the nearest base with a different tp_clear
1057 and clear slots while we're at it */
1058 type = Py_TYPE(self);
1059 base = type;
1060 while ((baseclear = base->tp_clear) == subtype_clear) {
1061 if (Py_SIZE(base))
1062 clear_slots(base, self);
1063 base = base->tp_base;
1064 assert(base);
1065 }
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001066
Benjamin Peterson52c42432012-03-07 18:41:11 -06001067 /* Clear the instance dict (if any), to break cycles involving only
1068 __dict__ slots (as in the case 'self.__dict__ is self'). */
1069 if (type->tp_dictoffset != base->tp_dictoffset) {
1070 PyObject **dictptr = _PyObject_GetDictPtr(self);
1071 if (dictptr && *dictptr)
1072 Py_CLEAR(*dictptr);
1073 }
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001074
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001075 if (baseclear)
1076 return baseclear(self);
1077 return 0;
Guido van Rossum9475a232001-10-05 20:51:39 +00001078}
Tim Peters6d6c1a32001-08-02 04:15:00 +00001079
1080static void
1081subtype_dealloc(PyObject *self)
1082{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001083 PyTypeObject *type, *base;
1084 destructor basedealloc;
Antoine Pitrou56cd62c2012-09-06 00:59:49 +02001085 PyThreadState *tstate = PyThreadState_GET();
Antoine Pitrou796564c2013-07-30 19:59:21 +02001086 int has_finalizer;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001087
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001088 /* Extract the type; we expect it to be a heap type */
1089 type = Py_TYPE(self);
1090 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001091
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001092 /* Test whether the type has GC exactly once */
Guido van Rossum22b13872002-08-06 21:41:44 +00001093
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001094 if (!PyType_IS_GC(type)) {
1095 /* It's really rare to find a dynamic type that doesn't have
1096 GC; it can only happen when deriving from 'object' and not
1097 adding any slots or instance variables. This allows
1098 certain simplifications: there's no need to call
1099 clear_slots(), or DECREF the dict, or clear weakrefs. */
Guido van Rossum22b13872002-08-06 21:41:44 +00001100
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001101 /* Maybe call finalizer; exit early if resurrected */
Antoine Pitrou796564c2013-07-30 19:59:21 +02001102 if (type->tp_finalize) {
1103 if (PyObject_CallFinalizerFromDealloc(self) < 0)
1104 return;
1105 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001106 if (type->tp_del) {
1107 type->tp_del(self);
1108 if (self->ob_refcnt > 0)
1109 return;
1110 }
Guido van Rossum22b13872002-08-06 21:41:44 +00001111
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001112 /* Find the nearest base with a different tp_dealloc */
1113 base = type;
1114 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
1115 assert(Py_SIZE(base) == 0);
1116 base = base->tp_base;
1117 assert(base);
1118 }
Guido van Rossum22b13872002-08-06 21:41:44 +00001119
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001120 /* Extract the type again; tp_del may have changed it */
1121 type = Py_TYPE(self);
Benjamin Peterson193152c2009-04-25 01:08:45 +00001122
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001123 /* Call the base tp_dealloc() */
1124 assert(basedealloc);
1125 basedealloc(self);
Guido van Rossum22b13872002-08-06 21:41:44 +00001126
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001127 /* Can't reference self beyond this point */
1128 Py_DECREF(type);
Guido van Rossum22b13872002-08-06 21:41:44 +00001129
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001130 /* Done */
1131 return;
1132 }
Guido van Rossum22b13872002-08-06 21:41:44 +00001133
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001134 /* We get here only if the type has GC */
Guido van Rossum22b13872002-08-06 21:41:44 +00001135
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001136 /* UnTrack and re-Track around the trashcan macro, alas */
1137 /* See explanation at end of function for full disclosure */
1138 PyObject_GC_UnTrack(self);
1139 ++_PyTrash_delete_nesting;
Antoine Pitrou56cd62c2012-09-06 00:59:49 +02001140 ++ tstate->trash_delete_nesting;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001141 Py_TRASHCAN_SAFE_BEGIN(self);
1142 --_PyTrash_delete_nesting;
Antoine Pitrou56cd62c2012-09-06 00:59:49 +02001143 -- tstate->trash_delete_nesting;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001144 /* DO NOT restore GC tracking at this point. weakref callbacks
1145 * (if any, and whether directly here or indirectly in something we
1146 * call) may trigger GC, and if self is tracked at that point, it
1147 * will look like trash to GC and GC will try to delete self again.
1148 */
Guido van Rossum22b13872002-08-06 21:41:44 +00001149
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001150 /* Find the nearest base with a different tp_dealloc */
1151 base = type;
Brett Cannonb94767f2011-02-22 20:15:44 +00001152 while ((/*basedealloc =*/ base->tp_dealloc) == subtype_dealloc) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001153 base = base->tp_base;
1154 assert(base);
1155 }
Guido van Rossum14227b42001-12-06 02:35:58 +00001156
Antoine Pitrou796564c2013-07-30 19:59:21 +02001157 has_finalizer = type->tp_finalize || type->tp_del;
Guido van Rossum59195fd2003-06-13 20:54:40 +00001158
Antoine Pitrou796564c2013-07-30 19:59:21 +02001159 /* Maybe call finalizer; exit early if resurrected */
1160 if (has_finalizer)
1161 _PyObject_GC_TRACK(self);
1162
1163 if (type->tp_finalize) {
1164 if (PyObject_CallFinalizerFromDealloc(self) < 0) {
1165 /* Resurrected */
1166 goto endlabel;
1167 }
1168 }
1169 /* If we added a weaklist, we clear it. Do this *before* calling
1170 tp_del, clearing slots, or clearing the instance dict. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001171 if (type->tp_weaklistoffset && !base->tp_weaklistoffset)
1172 PyObject_ClearWeakRefs(self);
Guido van Rossum1987c662003-05-29 14:29:23 +00001173
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001174 if (type->tp_del) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001175 type->tp_del(self);
Antoine Pitrou796564c2013-07-30 19:59:21 +02001176 if (self->ob_refcnt > 0) {
1177 /* Resurrected */
1178 goto endlabel;
1179 }
1180 }
1181 if (has_finalizer) {
1182 _PyObject_GC_UNTRACK(self);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001183 /* New weakrefs could be created during the finalizer call.
Antoine Pitrou796564c2013-07-30 19:59:21 +02001184 If this occurs, clear them out without calling their
1185 finalizers since they might rely on part of the object
1186 being finalized that has already been destroyed. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001187 if (type->tp_weaklistoffset && !base->tp_weaklistoffset) {
1188 /* Modeled after GET_WEAKREFS_LISTPTR() */
1189 PyWeakReference **list = (PyWeakReference **) \
1190 PyObject_GET_WEAKREFS_LISTPTR(self);
1191 while (*list)
1192 _PyWeakref_ClearRef(*list);
1193 }
1194 }
Guido van Rossum1987c662003-05-29 14:29:23 +00001195
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001196 /* Clear slots up to the nearest base with a different tp_dealloc */
1197 base = type;
1198 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
1199 if (Py_SIZE(base))
1200 clear_slots(base, self);
1201 base = base->tp_base;
1202 assert(base);
1203 }
Guido van Rossum59195fd2003-06-13 20:54:40 +00001204
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001205 /* If we added a dict, DECREF it */
1206 if (type->tp_dictoffset && !base->tp_dictoffset) {
1207 PyObject **dictptr = _PyObject_GetDictPtr(self);
1208 if (dictptr != NULL) {
1209 PyObject *dict = *dictptr;
1210 if (dict != NULL) {
1211 Py_DECREF(dict);
1212 *dictptr = NULL;
1213 }
1214 }
1215 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001216
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001217 /* Extract the type again; tp_del may have changed it */
1218 type = Py_TYPE(self);
Benjamin Peterson193152c2009-04-25 01:08:45 +00001219
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001220 /* Call the base tp_dealloc(); first retrack self if
1221 * basedealloc knows about gc.
1222 */
1223 if (PyType_IS_GC(base))
1224 _PyObject_GC_TRACK(self);
1225 assert(basedealloc);
1226 basedealloc(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001227
Benjamin Peterson9d4cbcc2015-01-30 13:33:42 -05001228 /* Can't reference self beyond this point. It's possible tp_del switched
1229 our type from a HEAPTYPE to a non-HEAPTYPE, so be careful about
1230 reference counting. */
1231 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
1232 Py_DECREF(type);
Guido van Rossum22b13872002-08-06 21:41:44 +00001233
Guido van Rossum0906e072002-08-07 20:42:09 +00001234 endlabel:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001235 ++_PyTrash_delete_nesting;
Antoine Pitrou56cd62c2012-09-06 00:59:49 +02001236 ++ tstate->trash_delete_nesting;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001237 Py_TRASHCAN_SAFE_END(self);
1238 --_PyTrash_delete_nesting;
Antoine Pitrou56cd62c2012-09-06 00:59:49 +02001239 -- tstate->trash_delete_nesting;
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001240
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001241 /* Explanation of the weirdness around the trashcan macros:
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001242
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001243 Q. What do the trashcan macros do?
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001244
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001245 A. Read the comment titled "Trashcan mechanism" in object.h.
1246 For one, this explains why there must be a call to GC-untrack
1247 before the trashcan begin macro. Without understanding the
1248 trashcan code, the answers to the following questions don't make
1249 sense.
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001250
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001251 Q. Why do we GC-untrack before the trashcan and then immediately
1252 GC-track again afterward?
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001253
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001254 A. In the case that the base class is GC-aware, the base class
1255 probably GC-untracks the object. If it does that using the
1256 UNTRACK macro, this will crash when the object is already
1257 untracked. Because we don't know what the base class does, the
1258 only safe thing is to make sure the object is tracked when we
1259 call the base class dealloc. But... The trashcan begin macro
1260 requires that the object is *untracked* before it is called. So
1261 the dance becomes:
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001262
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001263 GC untrack
1264 trashcan begin
1265 GC track
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001266
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001267 Q. Why did the last question say "immediately GC-track again"?
1268 It's nowhere near immediately.
Tim Petersf7f9e992003-11-13 21:59:32 +00001269
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001270 A. Because the code *used* to re-track immediately. Bad Idea.
1271 self has a refcount of 0, and if gc ever gets its hands on it
1272 (which can happen if any weakref callback gets invoked), it
1273 looks like trash to gc too, and gc also tries to delete self
Ezio Melotti13925002011-03-16 11:05:33 +02001274 then. But we're already deleting self. Double deallocation is
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001275 a subtle disaster.
Tim Petersf7f9e992003-11-13 21:59:32 +00001276
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001277 Q. Why the bizarre (net-zero) manipulation of
1278 _PyTrash_delete_nesting around the trashcan macros?
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001279
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001280 A. Some base classes (e.g. list) also use the trashcan mechanism.
1281 The following scenario used to be possible:
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001282
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001283 - suppose the trashcan level is one below the trashcan limit
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001284
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001285 - subtype_dealloc() is called
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001286
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001287 - the trashcan limit is not yet reached, so the trashcan level
1288 is incremented and the code between trashcan begin and end is
1289 executed
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001290
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001291 - this destroys much of the object's contents, including its
1292 slots and __dict__
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001293
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001294 - basedealloc() is called; this is really list_dealloc(), or
1295 some other type which also uses the trashcan macros
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001296
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001297 - the trashcan limit is now reached, so the object is put on the
1298 trashcan's to-be-deleted-later list
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001299
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001300 - basedealloc() returns
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001301
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001302 - subtype_dealloc() decrefs the object's type
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001303
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001304 - subtype_dealloc() returns
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001305
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001306 - later, the trashcan code starts deleting the objects from its
1307 to-be-deleted-later list
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001308
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001309 - subtype_dealloc() is called *AGAIN* for the same object
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001310
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001311 - at the very least (if the destroyed slots and __dict__ don't
1312 cause problems) the object's type gets decref'ed a second
1313 time, which is *BAD*!!!
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001314
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001315 The remedy is to make sure that if the code between trashcan
1316 begin and end in subtype_dealloc() is called, the code between
1317 trashcan begin and end in basedealloc() will also be called.
1318 This is done by decrementing the level after passing into the
1319 trashcan block, and incrementing it just before leaving the
1320 block.
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001321
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001322 But now it's possible that a chain of objects consisting solely
1323 of objects whose deallocator is subtype_dealloc() will defeat
1324 the trashcan mechanism completely: the decremented level means
1325 that the effective level never reaches the limit. Therefore, we
1326 *increment* the level *before* entering the trashcan block, and
1327 matchingly decrement it after leaving. This means the trashcan
1328 code will trigger a little early, but that's no big deal.
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001329
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001330 Q. Are there any live examples of code in need of all this
1331 complexity?
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001332
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001333 A. Yes. See SF bug 668433 for code that crashed (when Python was
1334 compiled in debug mode) before the trashcan level manipulations
1335 were added. For more discussion, see SF patches 581742, 575073
1336 and bug 574207.
1337 */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001338}
1339
Jeremy Hylton938ace62002-07-17 16:30:39 +00001340static PyTypeObject *solid_base(PyTypeObject *type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001341
Tim Peters6d6c1a32001-08-02 04:15:00 +00001342/* type test with subclassing support */
1343
Benjamin Peterson104b9e02015-02-05 22:29:14 -05001344Py_LOCAL_INLINE(int)
1345type_is_subtype_base_chain(PyTypeObject *a, PyTypeObject *b)
1346{
1347 do {
1348 if (a == b)
1349 return 1;
1350 a = a->tp_base;
1351 } while (a != NULL);
1352
1353 return (b == &PyBaseObject_Type);
1354}
1355
Tim Peters6d6c1a32001-08-02 04:15:00 +00001356int
1357PyType_IsSubtype(PyTypeObject *a, PyTypeObject *b)
1358{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001359 PyObject *mro;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001360
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001361 mro = a->tp_mro;
1362 if (mro != NULL) {
1363 /* Deal with multiple inheritance without recursion
1364 by walking the MRO tuple */
1365 Py_ssize_t i, n;
1366 assert(PyTuple_Check(mro));
1367 n = PyTuple_GET_SIZE(mro);
1368 for (i = 0; i < n; i++) {
1369 if (PyTuple_GET_ITEM(mro, i) == (PyObject *)b)
1370 return 1;
1371 }
1372 return 0;
1373 }
Benjamin Peterson104b9e02015-02-05 22:29:14 -05001374 else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001375 /* a is not completely initilized yet; follow tp_base */
Benjamin Peterson104b9e02015-02-05 22:29:14 -05001376 return type_is_subtype_base_chain(a, b);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001377}
1378
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001379/* Internal routines to do a method lookup in the type
Guido van Rossum60718732001-08-28 17:47:51 +00001380 without looking in the instance dictionary
1381 (so we can't use PyObject_GetAttr) but still binding
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001382 it to the instance. The arguments are the object,
Guido van Rossum60718732001-08-28 17:47:51 +00001383 the method name as a C string, and the address of a
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001384 static variable used to cache the interned Python string.
1385
1386 Two variants:
1387
1388 - lookup_maybe() returns NULL without raising an exception
1389 when the _PyType_Lookup() call fails;
1390
1391 - lookup_method() always raises an exception upon errors.
Benjamin Peterson224205f2009-05-08 03:25:19 +00001392
1393 - _PyObject_LookupSpecial() exported for the benefit of other places.
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001394*/
Guido van Rossum60718732001-08-28 17:47:51 +00001395
1396static PyObject *
Benjamin Petersonce798522012-01-22 11:24:29 -05001397lookup_maybe(PyObject *self, _Py_Identifier *attrid)
Guido van Rossum60718732001-08-28 17:47:51 +00001398{
Victor Stinner3c1e4812012-03-26 22:10:51 +02001399 PyObject *res;
Guido van Rossum60718732001-08-28 17:47:51 +00001400
Victor Stinner3c1e4812012-03-26 22:10:51 +02001401 res = _PyType_LookupId(Py_TYPE(self), attrid);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001402 if (res != NULL) {
1403 descrgetfunc f;
1404 if ((f = Py_TYPE(res)->tp_descr_get) == NULL)
1405 Py_INCREF(res);
1406 else
1407 res = f(res, self, (PyObject *)(Py_TYPE(self)));
1408 }
1409 return res;
Guido van Rossum60718732001-08-28 17:47:51 +00001410}
1411
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001412static PyObject *
Benjamin Petersonce798522012-01-22 11:24:29 -05001413lookup_method(PyObject *self, _Py_Identifier *attrid)
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001414{
Benjamin Petersonce798522012-01-22 11:24:29 -05001415 PyObject *res = lookup_maybe(self, attrid);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001416 if (res == NULL && !PyErr_Occurred())
Benjamin Petersonce798522012-01-22 11:24:29 -05001417 PyErr_SetObject(PyExc_AttributeError, attrid->object);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001418 return res;
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001419}
1420
Benjamin Peterson224205f2009-05-08 03:25:19 +00001421PyObject *
Benjamin Petersonce798522012-01-22 11:24:29 -05001422_PyObject_LookupSpecial(PyObject *self, _Py_Identifier *attrid)
Benjamin Peterson224205f2009-05-08 03:25:19 +00001423{
Benjamin Petersonce798522012-01-22 11:24:29 -05001424 return lookup_maybe(self, attrid);
Benjamin Peterson224205f2009-05-08 03:25:19 +00001425}
1426
Guido van Rossum2730b132001-08-28 18:22:14 +00001427/* A variation of PyObject_CallMethod that uses lookup_method()
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001428 instead of PyObject_GetAttrString(). This uses the same convention
Guido van Rossum2730b132001-08-28 18:22:14 +00001429 as lookup_method to cache the interned name string object. */
1430
Neil Schemenauerf23473f2001-10-21 22:28:58 +00001431static PyObject *
Benjamin Petersonce798522012-01-22 11:24:29 -05001432call_method(PyObject *o, _Py_Identifier *nameid, char *format, ...)
Guido van Rossum2730b132001-08-28 18:22:14 +00001433{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001434 va_list va;
1435 PyObject *args, *func = 0, *retval;
1436 va_start(va, format);
Guido van Rossum2730b132001-08-28 18:22:14 +00001437
Benjamin Petersonce798522012-01-22 11:24:29 -05001438 func = lookup_maybe(o, nameid);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001439 if (func == NULL) {
1440 va_end(va);
1441 if (!PyErr_Occurred())
Benjamin Petersonce798522012-01-22 11:24:29 -05001442 PyErr_SetObject(PyExc_AttributeError, nameid->object);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001443 return NULL;
1444 }
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001445
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001446 if (format && *format)
1447 args = Py_VaBuildValue(format, va);
1448 else
1449 args = PyTuple_New(0);
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001450
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001451 va_end(va);
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001452
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001453 if (args == NULL)
1454 return NULL;
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001455
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001456 assert(PyTuple_Check(args));
1457 retval = PyObject_Call(func, args, NULL);
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001458
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001459 Py_DECREF(args);
1460 Py_DECREF(func);
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001461
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001462 return retval;
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001463}
1464
1465/* Clone of call_method() that returns NotImplemented when the lookup fails. */
1466
Neil Schemenauerf23473f2001-10-21 22:28:58 +00001467static PyObject *
Benjamin Petersonce798522012-01-22 11:24:29 -05001468call_maybe(PyObject *o, _Py_Identifier *nameid, char *format, ...)
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001469{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001470 va_list va;
1471 PyObject *args, *func = 0, *retval;
1472 va_start(va, format);
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001473
Benjamin Petersonce798522012-01-22 11:24:29 -05001474 func = lookup_maybe(o, nameid);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001475 if (func == NULL) {
1476 va_end(va);
Brian Curtindfc80e32011-08-10 20:28:54 -05001477 if (!PyErr_Occurred())
1478 Py_RETURN_NOTIMPLEMENTED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001479 return NULL;
1480 }
Guido van Rossum2730b132001-08-28 18:22:14 +00001481
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001482 if (format && *format)
1483 args = Py_VaBuildValue(format, va);
1484 else
1485 args = PyTuple_New(0);
Guido van Rossum2730b132001-08-28 18:22:14 +00001486
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001487 va_end(va);
Guido van Rossum2730b132001-08-28 18:22:14 +00001488
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001489 if (args == NULL)
1490 return NULL;
Guido van Rossum2730b132001-08-28 18:22:14 +00001491
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001492 assert(PyTuple_Check(args));
1493 retval = PyObject_Call(func, args, NULL);
Guido van Rossum2730b132001-08-28 18:22:14 +00001494
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001495 Py_DECREF(args);
1496 Py_DECREF(func);
Guido van Rossum2730b132001-08-28 18:22:14 +00001497
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001498 return retval;
Guido van Rossum2730b132001-08-28 18:22:14 +00001499}
1500
Tim Petersea7f75d2002-12-07 21:39:16 +00001501/*
Guido van Rossum1f121312002-11-14 19:49:16 +00001502 Method resolution order algorithm C3 described in
1503 "A Monotonic Superclass Linearization for Dylan",
1504 by Kim Barrett, Bob Cassel, Paul Haahr,
Tim Petersea7f75d2002-12-07 21:39:16 +00001505 David A. Moon, Keith Playford, and P. Tucker Withington.
Guido van Rossum1f121312002-11-14 19:49:16 +00001506 (OOPSLA 1996)
1507
Guido van Rossum98f33732002-11-25 21:36:54 +00001508 Some notes about the rules implied by C3:
1509
Tim Petersea7f75d2002-12-07 21:39:16 +00001510 No duplicate bases.
Guido van Rossum98f33732002-11-25 21:36:54 +00001511 It isn't legal to repeat a class in a list of base classes.
1512
1513 The next three properties are the 3 constraints in "C3".
1514
Tim Petersea7f75d2002-12-07 21:39:16 +00001515 Local precendece order.
Guido van Rossum98f33732002-11-25 21:36:54 +00001516 If A precedes B in C's MRO, then A will precede B in the MRO of all
1517 subclasses of C.
1518
1519 Monotonicity.
1520 The MRO of a class must be an extension without reordering of the
1521 MRO of each of its superclasses.
1522
1523 Extended Precedence Graph (EPG).
1524 Linearization is consistent if there is a path in the EPG from
1525 each class to all its successors in the linearization. See
1526 the paper for definition of EPG.
Guido van Rossum1f121312002-11-14 19:49:16 +00001527 */
1528
Tim Petersea7f75d2002-12-07 21:39:16 +00001529static int
Guido van Rossum1f121312002-11-14 19:49:16 +00001530tail_contains(PyObject *list, int whence, PyObject *o) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001531 Py_ssize_t j, size;
1532 size = PyList_GET_SIZE(list);
Guido van Rossum1f121312002-11-14 19:49:16 +00001533
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001534 for (j = whence+1; j < size; j++) {
1535 if (PyList_GET_ITEM(list, j) == o)
1536 return 1;
1537 }
1538 return 0;
Guido van Rossum1f121312002-11-14 19:49:16 +00001539}
1540
Guido van Rossum98f33732002-11-25 21:36:54 +00001541static PyObject *
1542class_name(PyObject *cls)
1543{
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001544 PyObject *name = _PyObject_GetAttrId(cls, &PyId___name__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001545 if (name == NULL) {
1546 PyErr_Clear();
1547 Py_XDECREF(name);
1548 name = PyObject_Repr(cls);
1549 }
1550 if (name == NULL)
1551 return NULL;
1552 if (!PyUnicode_Check(name)) {
1553 Py_DECREF(name);
1554 return NULL;
1555 }
1556 return name;
Guido van Rossum98f33732002-11-25 21:36:54 +00001557}
1558
1559static int
1560check_duplicates(PyObject *list)
1561{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001562 Py_ssize_t i, j, n;
1563 /* Let's use a quadratic time algorithm,
1564 assuming that the bases lists is short.
1565 */
1566 n = PyList_GET_SIZE(list);
1567 for (i = 0; i < n; i++) {
1568 PyObject *o = PyList_GET_ITEM(list, i);
1569 for (j = i + 1; j < n; j++) {
1570 if (PyList_GET_ITEM(list, j) == o) {
1571 o = class_name(o);
1572 if (o != NULL) {
1573 PyErr_Format(PyExc_TypeError,
1574 "duplicate base class %U",
1575 o);
1576 Py_DECREF(o);
1577 } else {
1578 PyErr_SetString(PyExc_TypeError,
1579 "duplicate base class");
1580 }
1581 return -1;
1582 }
1583 }
1584 }
1585 return 0;
Guido van Rossum98f33732002-11-25 21:36:54 +00001586}
1587
1588/* Raise a TypeError for an MRO order disagreement.
1589
1590 It's hard to produce a good error message. In the absence of better
1591 insight into error reporting, report the classes that were candidates
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001592 to be put next into the MRO. There is some conflict between the
Guido van Rossum98f33732002-11-25 21:36:54 +00001593 order in which they should be put in the MRO, but it's hard to
1594 diagnose what constraint can't be satisfied.
1595*/
1596
1597static void
1598set_mro_error(PyObject *to_merge, int *remain)
1599{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001600 Py_ssize_t i, n, off, to_merge_size;
1601 char buf[1000];
1602 PyObject *k, *v;
1603 PyObject *set = PyDict_New();
1604 if (!set) return;
Guido van Rossum98f33732002-11-25 21:36:54 +00001605
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001606 to_merge_size = PyList_GET_SIZE(to_merge);
1607 for (i = 0; i < to_merge_size; i++) {
1608 PyObject *L = PyList_GET_ITEM(to_merge, i);
1609 if (remain[i] < PyList_GET_SIZE(L)) {
1610 PyObject *c = PyList_GET_ITEM(L, remain[i]);
1611 if (PyDict_SetItem(set, c, Py_None) < 0) {
1612 Py_DECREF(set);
1613 return;
1614 }
1615 }
1616 }
1617 n = PyDict_Size(set);
Guido van Rossum98f33732002-11-25 21:36:54 +00001618
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001619 off = PyOS_snprintf(buf, sizeof(buf), "Cannot create a \
Raymond Hettingerf394df42003-04-06 19:13:41 +00001620consistent method resolution\norder (MRO) for bases");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001621 i = 0;
1622 while (PyDict_Next(set, &i, &k, &v) && (size_t)off < sizeof(buf)) {
1623 PyObject *name = class_name(k);
Victor Stinnere5f99f32010-05-19 01:42:46 +00001624 char *name_str;
1625 if (name != NULL) {
1626 name_str = _PyUnicode_AsString(name);
1627 if (name_str == NULL)
Victor Stinnerba644a62010-05-19 01:50:45 +00001628 name_str = "?";
Victor Stinnere5f99f32010-05-19 01:42:46 +00001629 } else
Victor Stinnerba644a62010-05-19 01:50:45 +00001630 name_str = "?";
Victor Stinnere5f99f32010-05-19 01:42:46 +00001631 off += PyOS_snprintf(buf + off, sizeof(buf) - off, " %s", name_str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001632 Py_XDECREF(name);
1633 if (--n && (size_t)(off+1) < sizeof(buf)) {
1634 buf[off++] = ',';
1635 buf[off] = '\0';
1636 }
1637 }
1638 PyErr_SetString(PyExc_TypeError, buf);
1639 Py_DECREF(set);
Guido van Rossum98f33732002-11-25 21:36:54 +00001640}
1641
Tim Petersea7f75d2002-12-07 21:39:16 +00001642static int
Benjamin Peterson104b9e02015-02-05 22:29:14 -05001643pmerge(PyObject *acc, PyObject* to_merge)
1644{
1645 int res = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001646 Py_ssize_t i, j, to_merge_size, empty_cnt;
1647 int *remain;
Tim Petersea7f75d2002-12-07 21:39:16 +00001648
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001649 to_merge_size = PyList_GET_SIZE(to_merge);
Guido van Rossum1f121312002-11-14 19:49:16 +00001650
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001651 /* remain stores an index into each sublist of to_merge.
1652 remain[i] is the index of the next base in to_merge[i]
1653 that is not included in acc.
1654 */
1655 remain = (int *)PyMem_MALLOC(SIZEOF_INT*to_merge_size);
Victor Stinnera41f0852013-07-12 00:42:14 +02001656 if (remain == NULL) {
1657 PyErr_NoMemory();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001658 return -1;
Victor Stinnera41f0852013-07-12 00:42:14 +02001659 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001660 for (i = 0; i < to_merge_size; i++)
1661 remain[i] = 0;
Guido van Rossum1f121312002-11-14 19:49:16 +00001662
1663 again:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001664 empty_cnt = 0;
1665 for (i = 0; i < to_merge_size; i++) {
1666 PyObject *candidate;
Tim Petersea7f75d2002-12-07 21:39:16 +00001667
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001668 PyObject *cur_list = PyList_GET_ITEM(to_merge, i);
Guido van Rossum1f121312002-11-14 19:49:16 +00001669
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001670 if (remain[i] >= PyList_GET_SIZE(cur_list)) {
1671 empty_cnt++;
1672 continue;
1673 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001674
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001675 /* Choose next candidate for MRO.
Guido van Rossum98f33732002-11-25 21:36:54 +00001676
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001677 The input sequences alone can determine the choice.
1678 If not, choose the class which appears in the MRO
1679 of the earliest direct superclass of the new class.
1680 */
Guido van Rossum98f33732002-11-25 21:36:54 +00001681
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001682 candidate = PyList_GET_ITEM(cur_list, remain[i]);
1683 for (j = 0; j < to_merge_size; j++) {
1684 PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
Benjamin Peterson104b9e02015-02-05 22:29:14 -05001685 if (tail_contains(j_lst, remain[j], candidate))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001686 goto skip; /* continue outer loop */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001687 }
Benjamin Peterson104b9e02015-02-05 22:29:14 -05001688 res = PyList_Append(acc, candidate);
1689 if (res < 0)
1690 goto out;
1691
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001692 for (j = 0; j < to_merge_size; j++) {
1693 PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
1694 if (remain[j] < PyList_GET_SIZE(j_lst) &&
1695 PyList_GET_ITEM(j_lst, remain[j]) == candidate) {
1696 remain[j]++;
1697 }
1698 }
1699 goto again;
1700 skip: ;
1701 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001702
Benjamin Peterson104b9e02015-02-05 22:29:14 -05001703 if (empty_cnt != to_merge_size) {
1704 set_mro_error(to_merge, remain);
1705 res = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001706 }
Benjamin Peterson104b9e02015-02-05 22:29:14 -05001707
1708 out:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001709 PyMem_FREE(remain);
Benjamin Peterson104b9e02015-02-05 22:29:14 -05001710
1711 return res;
Guido van Rossum1f121312002-11-14 19:49:16 +00001712}
1713
Tim Peters6d6c1a32001-08-02 04:15:00 +00001714static PyObject *
1715mro_implementation(PyTypeObject *type)
1716{
Benjamin Peterson104b9e02015-02-05 22:29:14 -05001717 PyObject *result = NULL;
1718 PyObject *bases;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001719 PyObject *to_merge, *bases_aslist;
Benjamin Peterson104b9e02015-02-05 22:29:14 -05001720 int res;
1721 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001722
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001723 if (type->tp_dict == NULL) {
1724 if (PyType_Ready(type) < 0)
1725 return NULL;
1726 }
Guido van Rossum63517572002-06-18 16:44:57 +00001727
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001728 /* Find a superclass linearization that honors the constraints
1729 of the explicit lists of bases and the constraints implied by
1730 each base class.
Guido van Rossum98f33732002-11-25 21:36:54 +00001731
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001732 to_merge is a list of lists, where each list is a superclass
1733 linearization implied by a base class. The last element of
1734 to_merge is the declared list of bases.
1735 */
Guido van Rossum98f33732002-11-25 21:36:54 +00001736
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001737 bases = type->tp_bases;
1738 n = PyTuple_GET_SIZE(bases);
Guido van Rossum1f121312002-11-14 19:49:16 +00001739
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001740 to_merge = PyList_New(n+1);
1741 if (to_merge == NULL)
1742 return NULL;
Guido van Rossum1f121312002-11-14 19:49:16 +00001743
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001744 for (i = 0; i < n; i++) {
Benjamin Peterson104b9e02015-02-05 22:29:14 -05001745 PyTypeObject *base;
1746 PyObject *base_mro_aslist;
1747
1748 base = (PyTypeObject *)PyTuple_GET_ITEM(bases, i);
1749 if (base->tp_mro == NULL) {
1750 PyErr_Format(PyExc_TypeError,
1751 "Cannot extend an incomplete type '%.100s'",
1752 base->tp_name);
1753 goto out;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001754 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001755
Benjamin Peterson104b9e02015-02-05 22:29:14 -05001756 base_mro_aslist = PySequence_List(base->tp_mro);
1757 if (base_mro_aslist == NULL)
1758 goto out;
1759
1760 PyList_SET_ITEM(to_merge, i, base_mro_aslist);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001761 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001762
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001763 bases_aslist = PySequence_List(bases);
Benjamin Peterson104b9e02015-02-05 22:29:14 -05001764 if (bases_aslist == NULL)
1765 goto out;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001766 /* This is just a basic sanity check. */
1767 if (check_duplicates(bases_aslist) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001768 Py_DECREF(bases_aslist);
Benjamin Peterson104b9e02015-02-05 22:29:14 -05001769 goto out;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001770 }
1771 PyList_SET_ITEM(to_merge, n, bases_aslist);
Guido van Rossum1f121312002-11-14 19:49:16 +00001772
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001773 result = Py_BuildValue("[O]", (PyObject *)type);
Benjamin Peterson104b9e02015-02-05 22:29:14 -05001774 if (result == NULL)
1775 goto out;
Guido van Rossum1f121312002-11-14 19:49:16 +00001776
Benjamin Peterson104b9e02015-02-05 22:29:14 -05001777 res = pmerge(result, to_merge);
1778 if (res < 0)
1779 Py_CLEAR(result);
1780
1781 out:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001782 Py_DECREF(to_merge);
Guido van Rossum1f121312002-11-14 19:49:16 +00001783
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001784 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001785}
1786
1787static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001788mro_external(PyObject *self)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001789{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001790 PyTypeObject *type = (PyTypeObject *)self;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001791
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001792 return mro_implementation(type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001793}
1794
1795static int
Benjamin Peterson104b9e02015-02-05 22:29:14 -05001796mro_check(PyTypeObject *type, PyObject *mro)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001797{
Benjamin Peterson104b9e02015-02-05 22:29:14 -05001798 PyTypeObject *solid;
1799 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001800
Benjamin Peterson104b9e02015-02-05 22:29:14 -05001801 solid = solid_base(type);
1802
1803 n = PyTuple_GET_SIZE(mro);
1804 for (i = 0; i < n; i++) {
1805 PyTypeObject *base;
1806 PyObject *tmp;
1807
1808 tmp = PyTuple_GET_ITEM(mro, i);
1809 if (!PyType_Check(tmp)) {
1810 PyErr_Format(
1811 PyExc_TypeError,
1812 "mro() returned a non-class ('%.500s')",
1813 Py_TYPE(tmp)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001814 return -1;
Benjamin Peterson104b9e02015-02-05 22:29:14 -05001815 }
Armin Rigo037d1e02005-12-29 17:07:39 +00001816
Benjamin Peterson104b9e02015-02-05 22:29:14 -05001817 base = (PyTypeObject*)tmp;
1818 if (!PyType_IsSubtype(solid, solid_base(base))) {
1819 PyErr_Format(
1820 PyExc_TypeError,
1821 "mro() returned base with unsuitable layout ('%.500s')",
1822 base->tp_name);
1823 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001824 }
1825 }
Benjamin Peterson104b9e02015-02-05 22:29:14 -05001826
1827 return 0;
1828}
1829
1830/* Lookups an mcls.mro method, invokes it and checks the result (if needed,
1831 in case of a custom mro() implementation).
1832
1833 Keep in mind that during execution of this function type->tp_mro
1834 can be replaced due to possible reentrance (for example,
1835 through type_set_bases):
1836
1837 - when looking up the mcls.mro attribute (it could be
1838 a user-provided descriptor);
1839
1840 - from inside a custom mro() itself;
1841
1842 - through a finalizer of the return value of mro().
1843*/
1844static PyObject *
1845mro_invoke(PyTypeObject *type)
1846{
1847 PyObject *mro_result;
1848 PyObject *new_mro;
1849 int custom = (Py_TYPE(type) != &PyType_Type);
1850
1851 if (custom) {
1852 _Py_IDENTIFIER(mro);
1853 PyObject *mro_meth = lookup_method((PyObject *)type, &PyId_mro);
1854 if (mro_meth == NULL)
1855 return NULL;
1856 mro_result = PyObject_CallObject(mro_meth, NULL);
1857 Py_DECREF(mro_meth);
1858 }
1859 else {
1860 mro_result = mro_implementation(type);
1861 }
1862 if (mro_result == NULL)
1863 return NULL;
1864
1865 new_mro = PySequence_Tuple(mro_result);
1866 Py_DECREF(mro_result);
1867 if (new_mro == NULL)
1868 return NULL;
1869
1870 if (custom && mro_check(type, new_mro) < 0) {
1871 Py_DECREF(new_mro);
1872 return NULL;
1873 }
1874
1875 return new_mro;
1876}
1877
1878/* Calculates and assigns a new MRO to type->tp_mro.
1879 Return values and invariants:
1880
1881 - Returns 1 if a new MRO value has been set to type->tp_mro due to
1882 this call of mro_internal (no tricky reentrancy and no errors).
1883
1884 In case if p_old_mro argument is not NULL, a previous value
1885 of type->tp_mro is put there, and the ownership of this
1886 reference is transferred to a caller.
1887 Otherwise, the previous value (if any) is decref'ed.
1888
1889 - Returns 0 in case when type->tp_mro gets changed because of
1890 reentering here through a custom mro() (see a comment to mro_invoke).
1891
1892 In this case, a refcount of an old type->tp_mro is adjusted
1893 somewhere deeper in the call stack (by the innermost mro_internal
1894 or its caller) and may become zero upon returning from here.
1895 This also implies that the whole hierarchy of subclasses of the type
1896 has seen the new value and updated their MRO accordingly.
1897
1898 - Returns -1 in case of an error.
1899*/
1900static int
1901mro_internal(PyTypeObject *type, PyObject **p_old_mro)
1902{
1903 PyObject *new_mro, *old_mro;
1904 int reent;
1905
1906 /* Keep a reference to be able to do a reentrancy check below.
1907 Don't let old_mro be GC'ed and its address be reused for
1908 another object, like (suddenly!) a new tp_mro. */
1909 old_mro = type->tp_mro;
1910 Py_XINCREF(old_mro);
1911 new_mro = mro_invoke(type); /* might cause reentrance */
1912 reent = (type->tp_mro != old_mro);
1913 Py_XDECREF(old_mro);
1914 if (new_mro == NULL)
1915 return -1;
1916
1917 if (reent) {
1918 Py_DECREF(new_mro);
1919 return 0;
1920 }
1921
1922 type->tp_mro = new_mro;
Christian Heimesa62da1d2008-01-12 19:39:10 +00001923
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001924 type_mro_modified(type, type->tp_mro);
Florent Xiclunaaa6c1d22011-12-12 18:54:29 +01001925 /* corner case: the super class might have been hidden
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001926 from the custom MRO */
1927 type_mro_modified(type, type->tp_bases);
Christian Heimesa62da1d2008-01-12 19:39:10 +00001928
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001929 PyType_Modified(type);
Christian Heimesa62da1d2008-01-12 19:39:10 +00001930
Benjamin Peterson104b9e02015-02-05 22:29:14 -05001931 if (p_old_mro != NULL)
1932 *p_old_mro = old_mro; /* transfer the ownership */
1933 else
1934 Py_XDECREF(old_mro);
1935
1936 return 1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001937}
1938
1939
1940/* Calculate the best base amongst multiple base classes.
1941 This is the first one that's on the path to the "solid base". */
1942
1943static PyTypeObject *
1944best_base(PyObject *bases)
1945{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001946 Py_ssize_t i, n;
1947 PyTypeObject *base, *winner, *candidate, *base_i;
1948 PyObject *base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001949
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001950 assert(PyTuple_Check(bases));
1951 n = PyTuple_GET_SIZE(bases);
1952 assert(n > 0);
1953 base = NULL;
1954 winner = NULL;
1955 for (i = 0; i < n; i++) {
1956 base_proto = PyTuple_GET_ITEM(bases, i);
1957 if (!PyType_Check(base_proto)) {
1958 PyErr_SetString(
1959 PyExc_TypeError,
1960 "bases must be types");
1961 return NULL;
1962 }
1963 base_i = (PyTypeObject *)base_proto;
1964 if (base_i->tp_dict == NULL) {
1965 if (PyType_Ready(base_i) < 0)
1966 return NULL;
1967 }
1968 candidate = solid_base(base_i);
1969 if (winner == NULL) {
1970 winner = candidate;
1971 base = base_i;
1972 }
1973 else if (PyType_IsSubtype(winner, candidate))
1974 ;
1975 else if (PyType_IsSubtype(candidate, winner)) {
1976 winner = candidate;
1977 base = base_i;
1978 }
1979 else {
1980 PyErr_SetString(
1981 PyExc_TypeError,
1982 "multiple bases have "
1983 "instance lay-out conflict");
1984 return NULL;
1985 }
1986 }
Florent Xiclunaaa6c1d22011-12-12 18:54:29 +01001987 assert (base != NULL);
1988
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001989 return base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001990}
1991
1992static int
1993extra_ivars(PyTypeObject *type, PyTypeObject *base)
1994{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001995 size_t t_size = type->tp_basicsize;
1996 size_t b_size = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001997
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001998 assert(t_size >= b_size); /* Else type smaller than base! */
1999 if (type->tp_itemsize || base->tp_itemsize) {
2000 /* If itemsize is involved, stricter rules */
2001 return t_size != b_size ||
2002 type->tp_itemsize != base->tp_itemsize;
2003 }
2004 if (type->tp_weaklistoffset && base->tp_weaklistoffset == 0 &&
2005 type->tp_weaklistoffset + sizeof(PyObject *) == t_size &&
2006 type->tp_flags & Py_TPFLAGS_HEAPTYPE)
2007 t_size -= sizeof(PyObject *);
2008 if (type->tp_dictoffset && base->tp_dictoffset == 0 &&
2009 type->tp_dictoffset + sizeof(PyObject *) == t_size &&
2010 type->tp_flags & Py_TPFLAGS_HEAPTYPE)
2011 t_size -= sizeof(PyObject *);
Guido van Rossum9676b222001-08-17 20:32:36 +00002012
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002013 return t_size != b_size;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002014}
2015
2016static PyTypeObject *
2017solid_base(PyTypeObject *type)
2018{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002019 PyTypeObject *base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002020
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002021 if (type->tp_base)
2022 base = solid_base(type->tp_base);
2023 else
2024 base = &PyBaseObject_Type;
2025 if (extra_ivars(type, base))
2026 return type;
2027 else
2028 return base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002029}
2030
Jeremy Hylton938ace62002-07-17 16:30:39 +00002031static void object_dealloc(PyObject *);
2032static int object_init(PyObject *, PyObject *, PyObject *);
2033static int update_slot(PyTypeObject *, PyObject *);
2034static void fixup_slot_dispatchers(PyTypeObject *);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002035
Guido van Rossum360e4b82007-05-14 22:51:27 +00002036/*
2037 * Helpers for __dict__ descriptor. We don't want to expose the dicts
2038 * inherited from various builtin types. The builtin base usually provides
2039 * its own __dict__ descriptor, so we use that when we can.
2040 */
2041static PyTypeObject *
2042get_builtin_base_with_dict(PyTypeObject *type)
2043{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002044 while (type->tp_base != NULL) {
2045 if (type->tp_dictoffset != 0 &&
2046 !(type->tp_flags & Py_TPFLAGS_HEAPTYPE))
2047 return type;
2048 type = type->tp_base;
2049 }
2050 return NULL;
Guido van Rossum360e4b82007-05-14 22:51:27 +00002051}
2052
2053static PyObject *
2054get_dict_descriptor(PyTypeObject *type)
2055{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002056 PyObject *descr;
Guido van Rossum360e4b82007-05-14 22:51:27 +00002057
Victor Stinner3c1e4812012-03-26 22:10:51 +02002058 descr = _PyType_LookupId(type, &PyId___dict__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002059 if (descr == NULL || !PyDescr_IsData(descr))
2060 return NULL;
Guido van Rossum360e4b82007-05-14 22:51:27 +00002061
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002062 return descr;
Guido van Rossum360e4b82007-05-14 22:51:27 +00002063}
2064
2065static void
2066raise_dict_descr_error(PyObject *obj)
2067{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002068 PyErr_Format(PyExc_TypeError,
2069 "this __dict__ descriptor does not support "
2070 "'%.200s' objects", Py_TYPE(obj)->tp_name);
Guido van Rossum360e4b82007-05-14 22:51:27 +00002071}
2072
Tim Peters6d6c1a32001-08-02 04:15:00 +00002073static PyObject *
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00002074subtype_dict(PyObject *obj, void *context)
2075{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002076 PyTypeObject *base;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00002077
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002078 base = get_builtin_base_with_dict(Py_TYPE(obj));
2079 if (base != NULL) {
2080 descrgetfunc func;
2081 PyObject *descr = get_dict_descriptor(base);
2082 if (descr == NULL) {
2083 raise_dict_descr_error(obj);
2084 return NULL;
2085 }
2086 func = Py_TYPE(descr)->tp_descr_get;
2087 if (func == NULL) {
2088 raise_dict_descr_error(obj);
2089 return NULL;
2090 }
2091 return func(descr, obj, (PyObject *)(Py_TYPE(obj)));
2092 }
Benjamin Peterson8eb12692012-02-19 19:59:10 -05002093 return PyObject_GenericGetDict(obj, context);
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00002094}
2095
Guido van Rossum6661be32001-10-26 04:26:12 +00002096static int
2097subtype_setdict(PyObject *obj, PyObject *value, void *context)
2098{
Benjamin Peterson8eb12692012-02-19 19:59:10 -05002099 PyObject *dict, **dictptr;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002100 PyTypeObject *base;
Guido van Rossum6661be32001-10-26 04:26:12 +00002101
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002102 base = get_builtin_base_with_dict(Py_TYPE(obj));
2103 if (base != NULL) {
2104 descrsetfunc func;
2105 PyObject *descr = get_dict_descriptor(base);
2106 if (descr == NULL) {
2107 raise_dict_descr_error(obj);
2108 return -1;
2109 }
2110 func = Py_TYPE(descr)->tp_descr_set;
2111 if (func == NULL) {
2112 raise_dict_descr_error(obj);
2113 return -1;
2114 }
2115 return func(descr, obj, value);
2116 }
Benjamin Peterson8eb12692012-02-19 19:59:10 -05002117 /* Almost like PyObject_GenericSetDict, but allow __dict__ to be deleted. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002118 dictptr = _PyObject_GetDictPtr(obj);
2119 if (dictptr == NULL) {
2120 PyErr_SetString(PyExc_AttributeError,
2121 "This object has no __dict__");
2122 return -1;
2123 }
Benjamin Peterson006c5a22012-02-19 20:36:12 -05002124 if (value != NULL && !PyDict_Check(value)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002125 PyErr_Format(PyExc_TypeError,
2126 "__dict__ must be set to a dictionary, "
2127 "not a '%.200s'", Py_TYPE(value)->tp_name);
2128 return -1;
2129 }
2130 dict = *dictptr;
2131 Py_XINCREF(value);
2132 *dictptr = value;
2133 Py_XDECREF(dict);
2134 return 0;
Guido van Rossum6661be32001-10-26 04:26:12 +00002135}
2136
Guido van Rossumad47da02002-08-12 19:05:44 +00002137static PyObject *
2138subtype_getweakref(PyObject *obj, void *context)
2139{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002140 PyObject **weaklistptr;
2141 PyObject *result;
Guido van Rossumad47da02002-08-12 19:05:44 +00002142
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002143 if (Py_TYPE(obj)->tp_weaklistoffset == 0) {
2144 PyErr_SetString(PyExc_AttributeError,
2145 "This object has no __weakref__");
2146 return NULL;
2147 }
2148 assert(Py_TYPE(obj)->tp_weaklistoffset > 0);
2149 assert(Py_TYPE(obj)->tp_weaklistoffset + sizeof(PyObject *) <=
2150 (size_t)(Py_TYPE(obj)->tp_basicsize));
2151 weaklistptr = (PyObject **)
2152 ((char *)obj + Py_TYPE(obj)->tp_weaklistoffset);
2153 if (*weaklistptr == NULL)
2154 result = Py_None;
2155 else
2156 result = *weaklistptr;
2157 Py_INCREF(result);
2158 return result;
Guido van Rossumad47da02002-08-12 19:05:44 +00002159}
2160
Guido van Rossum373c7412003-01-07 13:41:37 +00002161/* Three variants on the subtype_getsets list. */
2162
2163static PyGetSetDef subtype_getsets_full[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002164 {"__dict__", subtype_dict, subtype_setdict,
2165 PyDoc_STR("dictionary for instance variables (if defined)")},
2166 {"__weakref__", subtype_getweakref, NULL,
2167 PyDoc_STR("list of weak references to the object (if defined)")},
2168 {0}
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00002169};
2170
Guido van Rossum373c7412003-01-07 13:41:37 +00002171static PyGetSetDef subtype_getsets_dict_only[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002172 {"__dict__", subtype_dict, subtype_setdict,
2173 PyDoc_STR("dictionary for instance variables (if defined)")},
2174 {0}
Guido van Rossum373c7412003-01-07 13:41:37 +00002175};
2176
2177static PyGetSetDef subtype_getsets_weakref_only[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002178 {"__weakref__", subtype_getweakref, NULL,
2179 PyDoc_STR("list of weak references to the object (if defined)")},
2180 {0}
Guido van Rossum373c7412003-01-07 13:41:37 +00002181};
2182
Guido van Rossum9923ffe2002-06-04 19:52:53 +00002183static int
2184valid_identifier(PyObject *s)
2185{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002186 if (!PyUnicode_Check(s)) {
2187 PyErr_Format(PyExc_TypeError,
2188 "__slots__ items must be strings, not '%.200s'",
2189 Py_TYPE(s)->tp_name);
2190 return 0;
2191 }
2192 if (!PyUnicode_IsIdentifier(s)) {
2193 PyErr_SetString(PyExc_TypeError,
2194 "__slots__ must be identifiers");
2195 return 0;
2196 }
2197 return 1;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00002198}
2199
Guido van Rossumd8faa362007-04-27 19:54:29 +00002200/* Forward */
2201static int
2202object_init(PyObject *self, PyObject *args, PyObject *kwds);
2203
2204static int
2205type_init(PyObject *cls, PyObject *args, PyObject *kwds)
2206{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002207 int res;
Guido van Rossumd8faa362007-04-27 19:54:29 +00002208
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002209 assert(args != NULL && PyTuple_Check(args));
2210 assert(kwds == NULL || PyDict_Check(kwds));
Guido van Rossumd8faa362007-04-27 19:54:29 +00002211
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002212 if (kwds != NULL && PyDict_Check(kwds) && PyDict_Size(kwds) != 0) {
2213 PyErr_SetString(PyExc_TypeError,
2214 "type.__init__() takes no keyword arguments");
2215 return -1;
2216 }
Guido van Rossumd8faa362007-04-27 19:54:29 +00002217
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002218 if (args != NULL && PyTuple_Check(args) &&
2219 (PyTuple_GET_SIZE(args) != 1 && PyTuple_GET_SIZE(args) != 3)) {
2220 PyErr_SetString(PyExc_TypeError,
2221 "type.__init__() takes 1 or 3 arguments");
2222 return -1;
2223 }
Guido van Rossumd8faa362007-04-27 19:54:29 +00002224
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002225 /* Call object.__init__(self) now. */
2226 /* XXX Could call super(type, cls).__init__() but what's the point? */
2227 args = PyTuple_GetSlice(args, 0, 0);
2228 res = object_init(cls, args, NULL);
2229 Py_DECREF(args);
2230 return res;
Guido van Rossumd8faa362007-04-27 19:54:29 +00002231}
2232
Victor Stinner4ca1cf32012-10-30 23:40:45 +01002233unsigned long
Martin v. Löwis738236d2011-02-05 20:35:29 +00002234PyType_GetFlags(PyTypeObject *type)
2235{
2236 return type->tp_flags;
2237}
2238
Nick Coghlande31b192011-10-23 22:04:16 +10002239/* Determine the most derived metatype. */
2240PyTypeObject *
2241_PyType_CalculateMetaclass(PyTypeObject *metatype, PyObject *bases)
2242{
2243 Py_ssize_t i, nbases;
2244 PyTypeObject *winner;
2245 PyObject *tmp;
2246 PyTypeObject *tmptype;
2247
2248 /* Determine the proper metatype to deal with this,
2249 and check for metatype conflicts while we're at it.
2250 Note that if some other metatype wins to contract,
2251 it's possible that its instances are not types. */
2252
2253 nbases = PyTuple_GET_SIZE(bases);
2254 winner = metatype;
2255 for (i = 0; i < nbases; i++) {
2256 tmp = PyTuple_GET_ITEM(bases, i);
2257 tmptype = Py_TYPE(tmp);
2258 if (PyType_IsSubtype(winner, tmptype))
2259 continue;
2260 if (PyType_IsSubtype(tmptype, winner)) {
2261 winner = tmptype;
2262 continue;
2263 }
2264 /* else: */
2265 PyErr_SetString(PyExc_TypeError,
2266 "metaclass conflict: "
2267 "the metaclass of a derived class "
2268 "must be a (non-strict) subclass "
2269 "of the metaclasses of all its bases");
2270 return NULL;
2271 }
2272 return winner;
2273}
2274
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00002275static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00002276type_new(PyTypeObject *metatype, PyObject *args, PyObject *kwds)
2277{
Victor Stinner6f738742012-02-25 01:22:36 +01002278 PyObject *name, *bases = NULL, *orig_dict, *dict = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002279 static char *kwlist[] = {"name", "bases", "dict", 0};
Victor Stinner6f738742012-02-25 01:22:36 +01002280 PyObject *qualname, *slots = NULL, *tmp, *newslots;
2281 PyTypeObject *type = NULL, *base, *tmptype, *winner;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002282 PyHeapTypeObject *et;
2283 PyMemberDef *mp;
2284 Py_ssize_t i, nbases, nslots, slotoffset, add_dict, add_weak;
2285 int j, may_add_dict, may_add_weak;
Victor Stinner3c1e4812012-03-26 22:10:51 +02002286 _Py_IDENTIFIER(__qualname__);
2287 _Py_IDENTIFIER(__slots__);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002288
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002289 assert(args != NULL && PyTuple_Check(args));
2290 assert(kwds == NULL || PyDict_Check(kwds));
Tim Peters3abca122001-10-27 19:37:48 +00002291
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002292 /* Special case: type(x) should return x->ob_type */
2293 {
2294 const Py_ssize_t nargs = PyTuple_GET_SIZE(args);
2295 const Py_ssize_t nkwds = kwds == NULL ? 0 : PyDict_Size(kwds);
Tim Peters3abca122001-10-27 19:37:48 +00002296
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002297 if (PyType_CheckExact(metatype) && nargs == 1 && nkwds == 0) {
2298 PyObject *x = PyTuple_GET_ITEM(args, 0);
2299 Py_INCREF(Py_TYPE(x));
2300 return (PyObject *) Py_TYPE(x);
2301 }
Tim Peters3abca122001-10-27 19:37:48 +00002302
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002303 /* SF bug 475327 -- if that didn't trigger, we need 3
2304 arguments. but PyArg_ParseTupleAndKeywords below may give
2305 a msg saying type() needs exactly 3. */
2306 if (nargs + nkwds != 3) {
2307 PyErr_SetString(PyExc_TypeError,
2308 "type() takes 1 or 3 arguments");
2309 return NULL;
2310 }
2311 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002312
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002313 /* Check arguments: (name, bases, dict) */
2314 if (!PyArg_ParseTupleAndKeywords(args, kwds, "UO!O!:type", kwlist,
2315 &name,
2316 &PyTuple_Type, &bases,
Victor Stinner6f738742012-02-25 01:22:36 +01002317 &PyDict_Type, &orig_dict))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002318 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002319
Nick Coghlande31b192011-10-23 22:04:16 +10002320 /* Determine the proper metatype to deal with this: */
2321 winner = _PyType_CalculateMetaclass(metatype, bases);
2322 if (winner == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002323 return NULL;
2324 }
Nick Coghlande31b192011-10-23 22:04:16 +10002325
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002326 if (winner != metatype) {
2327 if (winner->tp_new != type_new) /* Pass it to the winner */
2328 return winner->tp_new(winner, args, kwds);
2329 metatype = winner;
2330 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002331
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002332 /* Adjust for empty tuple bases */
Nick Coghlande31b192011-10-23 22:04:16 +10002333 nbases = PyTuple_GET_SIZE(bases);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002334 if (nbases == 0) {
2335 bases = PyTuple_Pack(1, &PyBaseObject_Type);
2336 if (bases == NULL)
Victor Stinner6f738742012-02-25 01:22:36 +01002337 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002338 nbases = 1;
2339 }
2340 else
2341 Py_INCREF(bases);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002342
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002343 /* Calculate best base, and check that all bases are type objects */
2344 base = best_base(bases);
2345 if (base == NULL) {
Victor Stinner6f738742012-02-25 01:22:36 +01002346 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002347 }
2348 if (!PyType_HasFeature(base, Py_TPFLAGS_BASETYPE)) {
2349 PyErr_Format(PyExc_TypeError,
2350 "type '%.100s' is not an acceptable base type",
2351 base->tp_name);
Victor Stinner6f738742012-02-25 01:22:36 +01002352 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002353 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002354
Victor Stinner6f738742012-02-25 01:22:36 +01002355 dict = PyDict_Copy(orig_dict);
2356 if (dict == NULL)
2357 goto error;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002358
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002359 /* Check for a __slots__ sequence variable in dict, and count it */
Victor Stinner3c1e4812012-03-26 22:10:51 +02002360 slots = _PyDict_GetItemId(dict, &PyId___slots__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002361 nslots = 0;
2362 add_dict = 0;
2363 add_weak = 0;
2364 may_add_dict = base->tp_dictoffset == 0;
2365 may_add_weak = base->tp_weaklistoffset == 0 && base->tp_itemsize == 0;
2366 if (slots == NULL) {
2367 if (may_add_dict) {
2368 add_dict++;
2369 }
2370 if (may_add_weak) {
2371 add_weak++;
2372 }
2373 }
2374 else {
2375 /* Have slots */
Guido van Rossumad47da02002-08-12 19:05:44 +00002376
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002377 /* Make it into a tuple */
2378 if (PyUnicode_Check(slots))
2379 slots = PyTuple_Pack(1, slots);
2380 else
2381 slots = PySequence_Tuple(slots);
Victor Stinner6f738742012-02-25 01:22:36 +01002382 if (slots == NULL)
2383 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002384 assert(PyTuple_Check(slots));
Guido van Rossumad47da02002-08-12 19:05:44 +00002385
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002386 /* Are slots allowed? */
2387 nslots = PyTuple_GET_SIZE(slots);
2388 if (nslots > 0 && base->tp_itemsize != 0) {
2389 PyErr_Format(PyExc_TypeError,
2390 "nonempty __slots__ "
2391 "not supported for subtype of '%s'",
2392 base->tp_name);
Victor Stinner6f738742012-02-25 01:22:36 +01002393 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002394 }
Guido van Rossumad47da02002-08-12 19:05:44 +00002395
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002396 /* Check for valid slot names and two special cases */
2397 for (i = 0; i < nslots; i++) {
2398 PyObject *tmp = PyTuple_GET_ITEM(slots, i);
2399 if (!valid_identifier(tmp))
Victor Stinner6f738742012-02-25 01:22:36 +01002400 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002401 assert(PyUnicode_Check(tmp));
Victor Stinnerad14ccd2013-11-07 00:46:04 +01002402 if (_PyUnicode_CompareWithId(tmp, &PyId___dict__) == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002403 if (!may_add_dict || add_dict) {
2404 PyErr_SetString(PyExc_TypeError,
2405 "__dict__ slot disallowed: "
2406 "we already got one");
Victor Stinner6f738742012-02-25 01:22:36 +01002407 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002408 }
2409 add_dict++;
2410 }
2411 if (PyUnicode_CompareWithASCIIString(tmp, "__weakref__") == 0) {
2412 if (!may_add_weak || add_weak) {
2413 PyErr_SetString(PyExc_TypeError,
2414 "__weakref__ slot disallowed: "
2415 "either we already got one, "
2416 "or __itemsize__ != 0");
Victor Stinner6f738742012-02-25 01:22:36 +01002417 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002418 }
2419 add_weak++;
2420 }
2421 }
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00002422
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002423 /* Copy slots into a list, mangle names and sort them.
2424 Sorted names are needed for __class__ assignment.
2425 Convert them back to tuple at the end.
2426 */
2427 newslots = PyList_New(nslots - add_dict - add_weak);
2428 if (newslots == NULL)
Victor Stinner6f738742012-02-25 01:22:36 +01002429 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002430 for (i = j = 0; i < nslots; i++) {
2431 tmp = PyTuple_GET_ITEM(slots, i);
2432 if ((add_dict &&
Victor Stinnerad14ccd2013-11-07 00:46:04 +01002433 _PyUnicode_CompareWithId(tmp, &PyId___dict__) == 0) ||
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002434 (add_weak &&
2435 PyUnicode_CompareWithASCIIString(tmp, "__weakref__") == 0))
2436 continue;
2437 tmp =_Py_Mangle(name, tmp);
Benjamin Petersonae13c882011-08-16 22:26:48 -05002438 if (!tmp) {
2439 Py_DECREF(newslots);
Victor Stinner6f738742012-02-25 01:22:36 +01002440 goto error;
Benjamin Petersonae13c882011-08-16 22:26:48 -05002441 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002442 PyList_SET_ITEM(newslots, j, tmp);
Benjamin Petersonc4085c82011-08-16 18:53:26 -05002443 if (PyDict_GetItem(dict, tmp)) {
2444 PyErr_Format(PyExc_ValueError,
2445 "%R in __slots__ conflicts with class variable",
2446 tmp);
Benjamin Petersond17cefc2011-08-16 22:28:23 -05002447 Py_DECREF(newslots);
Victor Stinner6f738742012-02-25 01:22:36 +01002448 goto error;
Benjamin Petersonc4085c82011-08-16 18:53:26 -05002449 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002450 j++;
2451 }
2452 assert(j == nslots - add_dict - add_weak);
2453 nslots = j;
Victor Stinner6f738742012-02-25 01:22:36 +01002454 Py_CLEAR(slots);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002455 if (PyList_Sort(newslots) == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002456 Py_DECREF(newslots);
Victor Stinner6f738742012-02-25 01:22:36 +01002457 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002458 }
2459 slots = PyList_AsTuple(newslots);
2460 Py_DECREF(newslots);
Victor Stinner6f738742012-02-25 01:22:36 +01002461 if (slots == NULL)
2462 goto error;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00002463
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002464 /* Secondary bases may provide weakrefs or dict */
2465 if (nbases > 1 &&
2466 ((may_add_dict && !add_dict) ||
2467 (may_add_weak && !add_weak))) {
2468 for (i = 0; i < nbases; i++) {
2469 tmp = PyTuple_GET_ITEM(bases, i);
2470 if (tmp == (PyObject *)base)
2471 continue; /* Skip primary base */
2472 assert(PyType_Check(tmp));
2473 tmptype = (PyTypeObject *)tmp;
2474 if (may_add_dict && !add_dict &&
2475 tmptype->tp_dictoffset != 0)
2476 add_dict++;
2477 if (may_add_weak && !add_weak &&
2478 tmptype->tp_weaklistoffset != 0)
2479 add_weak++;
2480 if (may_add_dict && !add_dict)
2481 continue;
2482 if (may_add_weak && !add_weak)
2483 continue;
2484 /* Nothing more to check */
2485 break;
2486 }
2487 }
2488 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002489
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002490 /* Allocate the type object */
2491 type = (PyTypeObject *)metatype->tp_alloc(metatype, nslots);
Victor Stinner6f738742012-02-25 01:22:36 +01002492 if (type == NULL)
2493 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002494
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002495 /* Keep name and slots alive in the extended type object */
2496 et = (PyHeapTypeObject *)type;
2497 Py_INCREF(name);
2498 et->ht_name = name;
2499 et->ht_slots = slots;
Victor Stinner6f738742012-02-25 01:22:36 +01002500 slots = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002501
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002502 /* Initialize tp_flags */
2503 type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE |
Antoine Pitrou796564c2013-07-30 19:59:21 +02002504 Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_FINALIZE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002505 if (base->tp_flags & Py_TPFLAGS_HAVE_GC)
2506 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossumdc91b992001-08-08 22:26:22 +00002507
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002508 /* Initialize essential fields */
Yury Selivanov75445082015-05-11 22:57:16 -04002509 type->tp_as_async = &et->as_async;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002510 type->tp_as_number = &et->as_number;
2511 type->tp_as_sequence = &et->as_sequence;
2512 type->tp_as_mapping = &et->as_mapping;
2513 type->tp_as_buffer = &et->as_buffer;
2514 type->tp_name = _PyUnicode_AsString(name);
Victor Stinner6f738742012-02-25 01:22:36 +01002515 if (!type->tp_name)
2516 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002517
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002518 /* Set tp_base and tp_bases */
2519 type->tp_bases = bases;
Victor Stinner6f738742012-02-25 01:22:36 +01002520 bases = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002521 Py_INCREF(base);
2522 type->tp_base = base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002523
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002524 /* Initialize tp_dict from passed-in dict */
Victor Stinner6f738742012-02-25 01:22:36 +01002525 Py_INCREF(dict);
2526 type->tp_dict = dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002527
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002528 /* Set __module__ in the dict */
Victor Stinner3c1e4812012-03-26 22:10:51 +02002529 if (_PyDict_GetItemId(dict, &PyId___module__) == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002530 tmp = PyEval_GetGlobals();
2531 if (tmp != NULL) {
Victor Stinner3c1e4812012-03-26 22:10:51 +02002532 tmp = _PyDict_GetItemId(tmp, &PyId___name__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002533 if (tmp != NULL) {
Victor Stinner3c1e4812012-03-26 22:10:51 +02002534 if (_PyDict_SetItemId(dict, &PyId___module__,
2535 tmp) < 0)
Victor Stinner6f738742012-02-25 01:22:36 +01002536 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002537 }
2538 }
2539 }
Guido van Rossumc3542212001-08-16 09:18:56 +00002540
Victor Stinner6f738742012-02-25 01:22:36 +01002541 /* Set ht_qualname to dict['__qualname__'] if available, else to
2542 __name__. The __qualname__ accessor will look for ht_qualname.
2543 */
Victor Stinner3c1e4812012-03-26 22:10:51 +02002544 qualname = _PyDict_GetItemId(dict, &PyId___qualname__);
Victor Stinner6f738742012-02-25 01:22:36 +01002545 if (qualname != NULL) {
2546 if (!PyUnicode_Check(qualname)) {
2547 PyErr_Format(PyExc_TypeError,
2548 "type __qualname__ must be a str, not %s",
2549 Py_TYPE(qualname)->tp_name);
2550 goto error;
2551 }
2552 }
Benjamin Peterson8afa7fa2012-10-30 23:51:03 -04002553 et->ht_qualname = qualname ? qualname : et->ht_name;
2554 Py_INCREF(et->ht_qualname);
2555 if (qualname != NULL && PyDict_DelItem(dict, PyId___qualname__.object) < 0)
2556 goto error;
Victor Stinner6f738742012-02-25 01:22:36 +01002557
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002558 /* Set tp_doc to a copy of dict['__doc__'], if the latter is there
2559 and is a string. The __doc__ accessor will first look for tp_doc;
2560 if that fails, it will still look into __dict__.
2561 */
2562 {
Victor Stinner3c1e4812012-03-26 22:10:51 +02002563 PyObject *doc = _PyDict_GetItemId(dict, &PyId___doc__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002564 if (doc != NULL && PyUnicode_Check(doc)) {
2565 Py_ssize_t len;
2566 char *doc_str;
2567 char *tp_doc;
Alexandre Vassalottia85998a2008-05-03 18:24:43 +00002568
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002569 doc_str = _PyUnicode_AsString(doc);
Victor Stinner6f738742012-02-25 01:22:36 +01002570 if (doc_str == NULL)
2571 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002572 /* Silently truncate the docstring if it contains null bytes. */
2573 len = strlen(doc_str);
2574 tp_doc = (char *)PyObject_MALLOC(len + 1);
Victor Stinner53510cd2013-07-15 19:34:20 +02002575 if (tp_doc == NULL) {
2576 PyErr_NoMemory();
Victor Stinner6f738742012-02-25 01:22:36 +01002577 goto error;
Victor Stinner53510cd2013-07-15 19:34:20 +02002578 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002579 memcpy(tp_doc, doc_str, len + 1);
2580 type->tp_doc = tp_doc;
2581 }
2582 }
Tim Peters2f93e282001-10-04 05:27:00 +00002583
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002584 /* Special-case __new__: if it's a plain function,
2585 make it a static function */
Victor Stinner3c1e4812012-03-26 22:10:51 +02002586 tmp = _PyDict_GetItemId(dict, &PyId___new__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002587 if (tmp != NULL && PyFunction_Check(tmp)) {
2588 tmp = PyStaticMethod_New(tmp);
Victor Stinner6f738742012-02-25 01:22:36 +01002589 if (tmp == NULL)
2590 goto error;
Victor Stinner3c1e4812012-03-26 22:10:51 +02002591 if (_PyDict_SetItemId(dict, &PyId___new__, tmp) < 0)
2592 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002593 Py_DECREF(tmp);
2594 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002595
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002596 /* Add descriptors for custom slots from __slots__, or for __dict__ */
2597 mp = PyHeapType_GET_MEMBERS(et);
2598 slotoffset = base->tp_basicsize;
Victor Stinner6f738742012-02-25 01:22:36 +01002599 if (et->ht_slots != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002600 for (i = 0; i < nslots; i++, mp++) {
2601 mp->name = _PyUnicode_AsString(
Victor Stinner6f738742012-02-25 01:22:36 +01002602 PyTuple_GET_ITEM(et->ht_slots, i));
2603 if (mp->name == NULL)
2604 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002605 mp->type = T_OBJECT_EX;
2606 mp->offset = slotoffset;
Guido van Rossumd8faa362007-04-27 19:54:29 +00002607
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002608 /* __dict__ and __weakref__ are already filtered out */
2609 assert(strcmp(mp->name, "__dict__") != 0);
2610 assert(strcmp(mp->name, "__weakref__") != 0);
Guido van Rossumd8faa362007-04-27 19:54:29 +00002611
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002612 slotoffset += sizeof(PyObject *);
2613 }
2614 }
2615 if (add_dict) {
2616 if (base->tp_itemsize)
2617 type->tp_dictoffset = -(long)sizeof(PyObject *);
2618 else
2619 type->tp_dictoffset = slotoffset;
2620 slotoffset += sizeof(PyObject *);
2621 }
2622 if (add_weak) {
2623 assert(!base->tp_itemsize);
2624 type->tp_weaklistoffset = slotoffset;
2625 slotoffset += sizeof(PyObject *);
2626 }
2627 type->tp_basicsize = slotoffset;
2628 type->tp_itemsize = base->tp_itemsize;
2629 type->tp_members = PyHeapType_GET_MEMBERS(et);
Guido van Rossum373c7412003-01-07 13:41:37 +00002630
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002631 if (type->tp_weaklistoffset && type->tp_dictoffset)
2632 type->tp_getset = subtype_getsets_full;
2633 else if (type->tp_weaklistoffset && !type->tp_dictoffset)
2634 type->tp_getset = subtype_getsets_weakref_only;
2635 else if (!type->tp_weaklistoffset && type->tp_dictoffset)
2636 type->tp_getset = subtype_getsets_dict_only;
2637 else
2638 type->tp_getset = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002639
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002640 /* Special case some slots */
2641 if (type->tp_dictoffset != 0 || nslots > 0) {
2642 if (base->tp_getattr == NULL && base->tp_getattro == NULL)
2643 type->tp_getattro = PyObject_GenericGetAttr;
2644 if (base->tp_setattr == NULL && base->tp_setattro == NULL)
2645 type->tp_setattro = PyObject_GenericSetAttr;
2646 }
2647 type->tp_dealloc = subtype_dealloc;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002648
Antoine Pitroua63cc212015-04-13 20:10:06 +02002649 /* Enable GC unless this class is not adding new instance variables and
2650 the base class did not use GC. */
2651 if ((base->tp_flags & Py_TPFLAGS_HAVE_GC) ||
2652 type->tp_basicsize > base->tp_basicsize)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002653 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossum9475a232001-10-05 20:51:39 +00002654
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002655 /* Always override allocation strategy to use regular heap */
2656 type->tp_alloc = PyType_GenericAlloc;
2657 if (type->tp_flags & Py_TPFLAGS_HAVE_GC) {
2658 type->tp_free = PyObject_GC_Del;
2659 type->tp_traverse = subtype_traverse;
2660 type->tp_clear = subtype_clear;
2661 }
2662 else
2663 type->tp_free = PyObject_Del;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002664
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002665 /* Initialize the rest */
Victor Stinner6f738742012-02-25 01:22:36 +01002666 if (PyType_Ready(type) < 0)
2667 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002668
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002669 /* Put the proper slots in place */
2670 fixup_slot_dispatchers(type);
Guido van Rossumf040ede2001-08-07 16:40:56 +00002671
Benjamin Petersondf813792014-03-17 15:57:17 -05002672 if (type->tp_dictoffset) {
2673 et->ht_cached_keys = _PyDict_NewKeysForClass();
2674 }
2675
Victor Stinner6f738742012-02-25 01:22:36 +01002676 Py_DECREF(dict);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002677 return (PyObject *)type;
Victor Stinner6f738742012-02-25 01:22:36 +01002678
2679error:
2680 Py_XDECREF(dict);
2681 Py_XDECREF(bases);
2682 Py_XDECREF(slots);
2683 Py_XDECREF(type);
2684 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002685}
2686
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002687static short slotoffsets[] = {
2688 -1, /* invalid slot */
2689#include "typeslots.inc"
2690};
2691
Benjamin Petersone28108c2012-01-29 20:13:18 -05002692PyObject *
Martin v. Löwis9c564092012-06-23 23:20:45 +02002693PyType_FromSpecWithBases(PyType_Spec *spec, PyObject *bases)
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002694{
2695 PyHeapTypeObject *res = (PyHeapTypeObject*)PyType_GenericAlloc(&PyType_Type, 0);
Martin v. Löwis9c564092012-06-23 23:20:45 +02002696 PyTypeObject *type, *base;
Nick Coghlana48db2b2015-05-24 01:03:46 +10002697 PyObject *modname;
Martin v. Löwis9c564092012-06-23 23:20:45 +02002698 char *s;
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002699 char *res_start = (char*)res;
2700 PyType_Slot *slot;
Victor Stinner54e4ca72013-07-11 22:42:25 +02002701
Martin v. Löwis9c564092012-06-23 23:20:45 +02002702 /* Set the type name and qualname */
2703 s = strrchr(spec->name, '.');
2704 if (s == NULL)
2705 s = (char*)spec->name;
2706 else
2707 s++;
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002708
Martin v. Löwis5e06a5d2011-02-21 16:24:00 +00002709 if (res == NULL)
Antoine Pitroubb78f572012-06-24 00:18:27 +02002710 return NULL;
2711 type = &res->ht_type;
Antoine Pitrou66a3a7e2012-06-24 00:42:59 +02002712 /* The flags must be initialized early, before the GC traverses us */
2713 type->tp_flags = spec->flags | Py_TPFLAGS_HEAPTYPE;
Martin v. Löwis9c564092012-06-23 23:20:45 +02002714 res->ht_name = PyUnicode_FromString(s);
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002715 if (!res->ht_name)
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002716 goto fail;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002717 res->ht_qualname = res->ht_name;
2718 Py_INCREF(res->ht_qualname);
Antoine Pitroubb78f572012-06-24 00:18:27 +02002719 type->tp_name = spec->name;
2720 if (!type->tp_name)
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002721 goto fail;
Victor Stinner54e4ca72013-07-11 22:42:25 +02002722
Martin v. Löwis9c564092012-06-23 23:20:45 +02002723 /* Adjust for empty tuple bases */
2724 if (!bases) {
2725 base = &PyBaseObject_Type;
2726 /* See whether Py_tp_base(s) was specified */
2727 for (slot = spec->slots; slot->slot; slot++) {
2728 if (slot->slot == Py_tp_base)
2729 base = slot->pfunc;
2730 else if (slot->slot == Py_tp_bases) {
2731 bases = slot->pfunc;
2732 Py_INCREF(bases);
2733 }
2734 }
2735 if (!bases)
2736 bases = PyTuple_Pack(1, base);
2737 if (!bases)
2738 goto fail;
2739 }
2740 else
2741 Py_INCREF(bases);
2742
2743 /* Calculate best base, and check that all bases are type objects */
2744 base = best_base(bases);
2745 if (base == NULL) {
2746 goto fail;
2747 }
2748 if (!PyType_HasFeature(base, Py_TPFLAGS_BASETYPE)) {
2749 PyErr_Format(PyExc_TypeError,
2750 "type '%.100s' is not an acceptable base type",
2751 base->tp_name);
2752 goto fail;
2753 }
2754
Martin v. Löwis9c564092012-06-23 23:20:45 +02002755 /* Initialize essential fields */
Yury Selivanov75445082015-05-11 22:57:16 -04002756 type->tp_as_async = &res->as_async;
Martin v. Löwis9c564092012-06-23 23:20:45 +02002757 type->tp_as_number = &res->as_number;
2758 type->tp_as_sequence = &res->as_sequence;
2759 type->tp_as_mapping = &res->as_mapping;
2760 type->tp_as_buffer = &res->as_buffer;
2761 /* Set tp_base and tp_bases */
2762 type->tp_bases = bases;
2763 bases = NULL;
2764 Py_INCREF(base);
2765 type->tp_base = base;
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002766
Antoine Pitroubb78f572012-06-24 00:18:27 +02002767 type->tp_basicsize = spec->basicsize;
2768 type->tp_itemsize = spec->itemsize;
Victor Stinner0fcab4a2011-01-04 12:59:15 +00002769
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002770 for (slot = spec->slots; slot->slot; slot++) {
Victor Stinner12174a52014-08-15 23:17:38 +02002771 if (slot->slot < 0
2772 || (size_t)slot->slot >= Py_ARRAY_LENGTH(slotoffsets)) {
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002773 PyErr_SetString(PyExc_RuntimeError, "invalid slot offset");
2774 goto fail;
2775 }
Martin v. Löwis9c564092012-06-23 23:20:45 +02002776 if (slot->slot == Py_tp_base || slot->slot == Py_tp_bases)
2777 /* Processed above */
2778 continue;
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002779 *(void**)(res_start + slotoffsets[slot->slot]) = slot->pfunc;
Georg Brandl032400b2011-02-19 21:47:02 +00002780
2781 /* need to make a copy of the docstring slot, which usually
2782 points to a static string literal */
2783 if (slot->slot == Py_tp_doc) {
Larry Hastings2623c8c2014-02-08 22:15:29 -08002784 const char *old_doc = _PyType_DocWithoutSignature(type->tp_name, slot->pfunc);
Larry Hastings5c661892014-01-24 06:17:25 -08002785 size_t len = strlen(old_doc)+1;
Georg Brandl032400b2011-02-19 21:47:02 +00002786 char *tp_doc = PyObject_MALLOC(len);
Victor Stinner53510cd2013-07-15 19:34:20 +02002787 if (tp_doc == NULL) {
2788 PyErr_NoMemory();
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002789 goto fail;
Victor Stinner53510cd2013-07-15 19:34:20 +02002790 }
Larry Hastings5c661892014-01-24 06:17:25 -08002791 memcpy(tp_doc, old_doc, len);
Antoine Pitroubb78f572012-06-24 00:18:27 +02002792 type->tp_doc = tp_doc;
Georg Brandl032400b2011-02-19 21:47:02 +00002793 }
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002794 }
Antoine Pitroubb78f572012-06-24 00:18:27 +02002795 if (type->tp_dealloc == NULL) {
Antoine Pitrou99cc6292012-06-23 14:42:38 +02002796 /* It's a heap type, so needs the heap types' dealloc.
2797 subtype_dealloc will call the base type's tp_dealloc, if
2798 necessary. */
Antoine Pitroubb78f572012-06-24 00:18:27 +02002799 type->tp_dealloc = subtype_dealloc;
Antoine Pitrou99cc6292012-06-23 14:42:38 +02002800 }
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002801
Antoine Pitroubb78f572012-06-24 00:18:27 +02002802 if (PyType_Ready(type) < 0)
Benjamin Peterson2652d252012-01-29 20:16:37 -05002803 goto fail;
2804
Benjamin Petersondf813792014-03-17 15:57:17 -05002805 if (type->tp_dictoffset) {
2806 res->ht_cached_keys = _PyDict_NewKeysForClass();
2807 }
2808
Martin v. Löwis9c564092012-06-23 23:20:45 +02002809 /* Set type.__module__ */
2810 s = strrchr(spec->name, '.');
Nick Coghlana48db2b2015-05-24 01:03:46 +10002811 if (s != NULL) {
2812 modname = PyUnicode_FromStringAndSize(
2813 spec->name, (Py_ssize_t)(s - spec->name));
2814 if (modname == NULL) {
2815 goto fail;
2816 }
2817 _PyDict_SetItemId(type->tp_dict, &PyId___module__, modname);
2818 Py_DECREF(modname);
2819 } else {
Serhiy Storchaka490055a2015-03-01 10:03:02 +02002820 if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
Serhiy Storchaka71c6f442015-03-01 14:39:20 +02002821 "builtin type %.200s has no __module__ attribute",
Serhiy Storchaka490055a2015-03-01 10:03:02 +02002822 spec->name))
2823 goto fail;
2824 }
Martin v. Löwis9c564092012-06-23 23:20:45 +02002825
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002826 return (PyObject*)res;
Victor Stinner0fcab4a2011-01-04 12:59:15 +00002827
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002828 fail:
2829 Py_DECREF(res);
2830 return NULL;
2831}
2832
Martin v. Löwis9c564092012-06-23 23:20:45 +02002833PyObject *
2834PyType_FromSpec(PyType_Spec *spec)
2835{
2836 return PyType_FromSpecWithBases(spec, NULL);
2837}
2838
Martin v. Löwisca7b0462014-02-04 09:33:05 +01002839void *
2840PyType_GetSlot(PyTypeObject *type, int slot)
2841{
Victor Stinner12174a52014-08-15 23:17:38 +02002842 if (!PyType_HasFeature(type, Py_TPFLAGS_HEAPTYPE) || slot < 0) {
Martin v. Löwisca7b0462014-02-04 09:33:05 +01002843 PyErr_BadInternalCall();
2844 return NULL;
2845 }
Victor Stinner12174a52014-08-15 23:17:38 +02002846 if ((size_t)slot >= Py_ARRAY_LENGTH(slotoffsets)) {
Martin v. Löwisca7b0462014-02-04 09:33:05 +01002847 /* Extension module requesting slot from a future version */
2848 return NULL;
2849 }
2850 return *(void**)(((char*)type) + slotoffsets[slot]);
2851}
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002852
Tim Peters6d6c1a32001-08-02 04:15:00 +00002853/* Internal API to look for a name through the MRO.
2854 This returns a borrowed reference, and doesn't set an exception! */
2855PyObject *
2856_PyType_Lookup(PyTypeObject *type, PyObject *name)
2857{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002858 Py_ssize_t i, n;
2859 PyObject *mro, *res, *base, *dict;
2860 unsigned int h;
Christian Heimesa62da1d2008-01-12 19:39:10 +00002861
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002862 if (MCACHE_CACHEABLE_NAME(name) &&
2863 PyType_HasFeature(type, Py_TPFLAGS_VALID_VERSION_TAG)) {
2864 /* fast path */
2865 h = MCACHE_HASH_METHOD(type, name);
2866 if (method_cache[h].version == type->tp_version_tag &&
Antoine Pitrou2a40e362014-11-15 00:56:27 +01002867 method_cache[h].name == name) {
2868#if MCACHE_STATS
2869 method_cache_hits++;
2870#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002871 return method_cache[h].value;
Antoine Pitrou2a40e362014-11-15 00:56:27 +01002872 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002873 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002874
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002875 /* Look in tp_dict of types in MRO */
2876 mro = type->tp_mro;
Guido van Rossum23094982002-06-10 14:30:43 +00002877
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002878 /* If mro is NULL, the type is either not yet initialized
2879 by PyType_Ready(), or already cleared by type_clear().
2880 Either way the safest thing to do is to return NULL. */
2881 if (mro == NULL)
2882 return NULL;
Guido van Rossum23094982002-06-10 14:30:43 +00002883
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002884 res = NULL;
Victor Stinnerd74782b2012-03-09 00:39:08 +01002885 /* keep a strong reference to mro because type->tp_mro can be replaced
2886 during PyDict_GetItem(dict, name) */
2887 Py_INCREF(mro);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002888 assert(PyTuple_Check(mro));
2889 n = PyTuple_GET_SIZE(mro);
2890 for (i = 0; i < n; i++) {
2891 base = PyTuple_GET_ITEM(mro, i);
2892 assert(PyType_Check(base));
2893 dict = ((PyTypeObject *)base)->tp_dict;
2894 assert(dict && PyDict_Check(dict));
2895 res = PyDict_GetItem(dict, name);
2896 if (res != NULL)
2897 break;
2898 }
Victor Stinnerd74782b2012-03-09 00:39:08 +01002899 Py_DECREF(mro);
Christian Heimesa62da1d2008-01-12 19:39:10 +00002900
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002901 if (MCACHE_CACHEABLE_NAME(name) && assign_version_tag(type)) {
2902 h = MCACHE_HASH_METHOD(type, name);
2903 method_cache[h].version = type->tp_version_tag;
2904 method_cache[h].value = res; /* borrowed */
2905 Py_INCREF(name);
Antoine Pitrou2a40e362014-11-15 00:56:27 +01002906 assert(((PyASCIIObject *)(name))->hash != -1);
2907#if MCACHE_STATS
2908 if (method_cache[h].name != Py_None && method_cache[h].name != name)
2909 method_cache_collisions++;
2910 else
2911 method_cache_misses++;
2912#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002913 Py_DECREF(method_cache[h].name);
2914 method_cache[h].name = name;
2915 }
2916 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002917}
2918
Raymond Hettinger2ff21902013-10-01 00:55:43 -07002919PyObject *
Victor Stinner3c1e4812012-03-26 22:10:51 +02002920_PyType_LookupId(PyTypeObject *type, struct _Py_Identifier *name)
2921{
2922 PyObject *oname;
2923 oname = _PyUnicode_FromId(name); /* borrowed */
2924 if (oname == NULL)
2925 return NULL;
2926 return _PyType_Lookup(type, oname);
2927}
2928
Tim Peters6d6c1a32001-08-02 04:15:00 +00002929/* This is similar to PyObject_GenericGetAttr(),
2930 but uses _PyType_Lookup() instead of just looking in type->tp_dict. */
2931static PyObject *
2932type_getattro(PyTypeObject *type, PyObject *name)
2933{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002934 PyTypeObject *metatype = Py_TYPE(type);
2935 PyObject *meta_attribute, *attribute;
2936 descrgetfunc meta_get;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002937
Benjamin Peterson16d84ac2012-03-16 09:32:59 -05002938 if (!PyUnicode_Check(name)) {
2939 PyErr_Format(PyExc_TypeError,
2940 "attribute name must be string, not '%.200s'",
2941 name->ob_type->tp_name);
2942 return NULL;
2943 }
2944
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002945 /* Initialize this type (we'll assume the metatype is initialized) */
2946 if (type->tp_dict == NULL) {
2947 if (PyType_Ready(type) < 0)
2948 return NULL;
2949 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002950
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002951 /* No readable descriptor found yet */
2952 meta_get = NULL;
Tim Peters34592512002-07-11 06:23:50 +00002953
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002954 /* Look for the attribute in the metatype */
2955 meta_attribute = _PyType_Lookup(metatype, name);
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002956
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002957 if (meta_attribute != NULL) {
2958 meta_get = Py_TYPE(meta_attribute)->tp_descr_get;
Tim Peters34592512002-07-11 06:23:50 +00002959
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002960 if (meta_get != NULL && PyDescr_IsData(meta_attribute)) {
2961 /* Data descriptors implement tp_descr_set to intercept
2962 * writes. Assume the attribute is not overridden in
2963 * type's tp_dict (and bases): call the descriptor now.
2964 */
2965 return meta_get(meta_attribute, (PyObject *)type,
2966 (PyObject *)metatype);
2967 }
2968 Py_INCREF(meta_attribute);
2969 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002970
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002971 /* No data descriptor found on metatype. Look in tp_dict of this
2972 * type and its bases */
2973 attribute = _PyType_Lookup(type, name);
2974 if (attribute != NULL) {
2975 /* Implement descriptor functionality, if any */
2976 descrgetfunc local_get = Py_TYPE(attribute)->tp_descr_get;
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00002977
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002978 Py_XDECREF(meta_attribute);
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00002979
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002980 if (local_get != NULL) {
2981 /* NULL 2nd argument indicates the descriptor was
2982 * found on the target object itself (or a base) */
2983 return local_get(attribute, (PyObject *)NULL,
2984 (PyObject *)type);
2985 }
Tim Peters34592512002-07-11 06:23:50 +00002986
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002987 Py_INCREF(attribute);
2988 return attribute;
2989 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002990
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002991 /* No attribute found in local __dict__ (or bases): use the
2992 * descriptor from the metatype, if any */
2993 if (meta_get != NULL) {
2994 PyObject *res;
2995 res = meta_get(meta_attribute, (PyObject *)type,
2996 (PyObject *)metatype);
2997 Py_DECREF(meta_attribute);
2998 return res;
2999 }
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00003000
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003001 /* If an ordinary attribute was found on the metatype, return it now */
3002 if (meta_attribute != NULL) {
3003 return meta_attribute;
3004 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003005
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003006 /* Give up */
3007 PyErr_Format(PyExc_AttributeError,
3008 "type object '%.50s' has no attribute '%U'",
3009 type->tp_name, name);
3010 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003011}
3012
3013static int
3014type_setattro(PyTypeObject *type, PyObject *name, PyObject *value)
3015{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003016 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
3017 PyErr_Format(
3018 PyExc_TypeError,
3019 "can't set attributes of built-in/extension type '%s'",
3020 type->tp_name);
3021 return -1;
3022 }
3023 if (PyObject_GenericSetAttr((PyObject *)type, name, value) < 0)
3024 return -1;
3025 return update_slot(type, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003026}
3027
Benjamin Peterson64acccf2012-04-27 15:07:36 -04003028extern void
3029_PyDictKeys_DecRef(PyDictKeysObject *keys);
3030
Tim Peters6d6c1a32001-08-02 04:15:00 +00003031static void
3032type_dealloc(PyTypeObject *type)
3033{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003034 PyHeapTypeObject *et;
Antoine Pitrou84745ab2013-10-29 21:31:25 +01003035 PyObject *tp, *val, *tb;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003036
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003037 /* Assert this is a heap-allocated type object */
3038 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
3039 _PyObject_GC_UNTRACK(type);
Antoine Pitrou84745ab2013-10-29 21:31:25 +01003040 PyErr_Fetch(&tp, &val, &tb);
3041 remove_all_subclasses(type, type->tp_bases);
3042 PyErr_Restore(tp, val, tb);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003043 PyObject_ClearWeakRefs((PyObject *)type);
3044 et = (PyHeapTypeObject *)type;
3045 Py_XDECREF(type->tp_base);
3046 Py_XDECREF(type->tp_dict);
3047 Py_XDECREF(type->tp_bases);
3048 Py_XDECREF(type->tp_mro);
3049 Py_XDECREF(type->tp_cache);
3050 Py_XDECREF(type->tp_subclasses);
3051 /* A type's tp_doc is heap allocated, unlike the tp_doc slots
3052 * of most other objects. It's okay to cast it to char *.
3053 */
3054 PyObject_Free((char *)type->tp_doc);
3055 Py_XDECREF(et->ht_name);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003056 Py_XDECREF(et->ht_qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003057 Py_XDECREF(et->ht_slots);
Benjamin Peterson64acccf2012-04-27 15:07:36 -04003058 if (et->ht_cached_keys)
3059 _PyDictKeys_DecRef(et->ht_cached_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003060 Py_TYPE(type)->tp_free((PyObject *)type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003061}
3062
Guido van Rossum1c450732001-10-08 15:18:27 +00003063static PyObject *
3064type_subclasses(PyTypeObject *type, PyObject *args_ignored)
3065{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003066 PyObject *list, *raw, *ref;
Antoine Pitrou84745ab2013-10-29 21:31:25 +01003067 Py_ssize_t i;
Guido van Rossum1c450732001-10-08 15:18:27 +00003068
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003069 list = PyList_New(0);
3070 if (list == NULL)
3071 return NULL;
3072 raw = type->tp_subclasses;
3073 if (raw == NULL)
3074 return list;
Antoine Pitrou84745ab2013-10-29 21:31:25 +01003075 assert(PyDict_CheckExact(raw));
3076 i = 0;
3077 while (PyDict_Next(raw, &i, NULL, &ref)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003078 assert(PyWeakref_CheckRef(ref));
3079 ref = PyWeakref_GET_OBJECT(ref);
3080 if (ref != Py_None) {
3081 if (PyList_Append(list, ref) < 0) {
3082 Py_DECREF(list);
3083 return NULL;
3084 }
3085 }
3086 }
3087 return list;
Guido van Rossum1c450732001-10-08 15:18:27 +00003088}
3089
Guido van Rossum47374822007-08-02 16:48:17 +00003090static PyObject *
3091type_prepare(PyObject *self, PyObject *args, PyObject *kwds)
3092{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003093 return PyDict_New();
Guido van Rossum47374822007-08-02 16:48:17 +00003094}
3095
Victor Stinner63941882011-09-29 00:42:28 +02003096/*
Benjamin Peterson82b00c12011-05-24 11:09:06 -05003097 Merge the __dict__ of aclass into dict, and recursively also all
3098 the __dict__s of aclass's base classes. The order of merging isn't
3099 defined, as it's expected that only the final set of dict keys is
3100 interesting.
3101 Return 0 on success, -1 on error.
3102*/
3103
3104static int
3105merge_class_dict(PyObject *dict, PyObject *aclass)
3106{
3107 PyObject *classdict;
3108 PyObject *bases;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02003109 _Py_IDENTIFIER(__bases__);
Benjamin Peterson82b00c12011-05-24 11:09:06 -05003110
3111 assert(PyDict_Check(dict));
3112 assert(aclass);
3113
3114 /* Merge in the type's dict (if any). */
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02003115 classdict = _PyObject_GetAttrId(aclass, &PyId___dict__);
Benjamin Peterson82b00c12011-05-24 11:09:06 -05003116 if (classdict == NULL)
3117 PyErr_Clear();
3118 else {
3119 int status = PyDict_Update(dict, classdict);
3120 Py_DECREF(classdict);
3121 if (status < 0)
3122 return -1;
3123 }
3124
3125 /* Recursively merge in the base types' (if any) dicts. */
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02003126 bases = _PyObject_GetAttrId(aclass, &PyId___bases__);
Benjamin Peterson82b00c12011-05-24 11:09:06 -05003127 if (bases == NULL)
3128 PyErr_Clear();
3129 else {
3130 /* We have no guarantee that bases is a real tuple */
3131 Py_ssize_t i, n;
3132 n = PySequence_Size(bases); /* This better be right */
3133 if (n < 0)
3134 PyErr_Clear();
3135 else {
3136 for (i = 0; i < n; i++) {
3137 int status;
3138 PyObject *base = PySequence_GetItem(bases, i);
3139 if (base == NULL) {
3140 Py_DECREF(bases);
3141 return -1;
3142 }
3143 status = merge_class_dict(dict, base);
3144 Py_DECREF(base);
3145 if (status < 0) {
3146 Py_DECREF(bases);
3147 return -1;
3148 }
3149 }
3150 }
3151 Py_DECREF(bases);
3152 }
3153 return 0;
3154}
3155
3156/* __dir__ for type objects: returns __dict__ and __bases__.
3157 We deliberately don't suck up its __class__, as methods belonging to the
3158 metaclass would probably be more confusing than helpful.
3159*/
3160static PyObject *
3161type_dir(PyObject *self, PyObject *args)
3162{
3163 PyObject *result = NULL;
3164 PyObject *dict = PyDict_New();
3165
3166 if (dict != NULL && merge_class_dict(dict, self) == 0)
3167 result = PyDict_Keys(dict);
3168
3169 Py_XDECREF(dict);
3170 return result;
3171}
3172
Martin v. Loewis4f2f3b62012-04-24 19:13:57 +02003173static PyObject*
3174type_sizeof(PyObject *self, PyObject *args_unused)
3175{
3176 Py_ssize_t size;
3177 PyTypeObject *type = (PyTypeObject*)self;
3178 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
3179 PyHeapTypeObject* et = (PyHeapTypeObject*)type;
3180 size = sizeof(PyHeapTypeObject);
3181 if (et->ht_cached_keys)
3182 size += _PyDict_KeysSize(et->ht_cached_keys);
3183 }
3184 else
3185 size = sizeof(PyTypeObject);
3186 return PyLong_FromSsize_t(size);
3187}
3188
Tim Peters6d6c1a32001-08-02 04:15:00 +00003189static PyMethodDef type_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003190 {"mro", (PyCFunction)mro_external, METH_NOARGS,
3191 PyDoc_STR("mro() -> list\nreturn a type's method resolution order")},
3192 {"__subclasses__", (PyCFunction)type_subclasses, METH_NOARGS,
3193 PyDoc_STR("__subclasses__() -> list of immediate subclasses")},
3194 {"__prepare__", (PyCFunction)type_prepare,
3195 METH_VARARGS | METH_KEYWORDS | METH_CLASS,
3196 PyDoc_STR("__prepare__() -> dict\n"
3197 "used to create the namespace for the class statement")},
3198 {"__instancecheck__", type___instancecheck__, METH_O,
Benjamin Petersonfbe56bb2011-05-24 12:42:51 -05003199 PyDoc_STR("__instancecheck__() -> bool\ncheck if an object is an instance")},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003200 {"__subclasscheck__", type___subclasscheck__, METH_O,
Benjamin Petersonfbe56bb2011-05-24 12:42:51 -05003201 PyDoc_STR("__subclasscheck__() -> bool\ncheck if a class is a subclass")},
Benjamin Peterson82b00c12011-05-24 11:09:06 -05003202 {"__dir__", type_dir, METH_NOARGS,
Benjamin Petersonc7284122011-05-24 12:46:15 -05003203 PyDoc_STR("__dir__() -> list\nspecialized __dir__ implementation for types")},
Martin v. Loewis4f2f3b62012-04-24 19:13:57 +02003204 {"__sizeof__", type_sizeof, METH_NOARGS,
3205 "__sizeof__() -> int\nreturn memory consumption of the type object"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003206 {0}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003207};
3208
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003209PyDoc_STRVAR(type_doc,
Larry Hastings5c661892014-01-24 06:17:25 -08003210/* this text signature cannot be accurate yet. will fix. --larry */
Larry Hastings2623c8c2014-02-08 22:15:29 -08003211"type(object_or_name, bases, dict)\n"
Tim Peters6d6c1a32001-08-02 04:15:00 +00003212"type(object) -> the object's type\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003213"type(name, bases, dict) -> a new type");
Tim Peters6d6c1a32001-08-02 04:15:00 +00003214
Guido van Rossum048eb752001-10-02 21:24:57 +00003215static int
3216type_traverse(PyTypeObject *type, visitproc visit, void *arg)
3217{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003218 /* Because of type_is_gc(), the collector only calls this
3219 for heaptypes. */
Antoine Pitrou1351ca62012-06-24 00:30:12 +02003220 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
3221 char msg[200];
3222 sprintf(msg, "type_traverse() called for non-heap type '%.100s'",
3223 type->tp_name);
3224 Py_FatalError(msg);
3225 }
Guido van Rossum048eb752001-10-02 21:24:57 +00003226
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003227 Py_VISIT(type->tp_dict);
3228 Py_VISIT(type->tp_cache);
3229 Py_VISIT(type->tp_mro);
3230 Py_VISIT(type->tp_bases);
3231 Py_VISIT(type->tp_base);
Guido van Rossuma3862092002-06-10 15:24:42 +00003232
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003233 /* There's no need to visit type->tp_subclasses or
3234 ((PyHeapTypeObject *)type)->ht_slots, because they can't be involved
3235 in cycles; tp_subclasses is a list of weak references,
3236 and slots is a tuple of strings. */
Guido van Rossum048eb752001-10-02 21:24:57 +00003237
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003238 return 0;
Guido van Rossum048eb752001-10-02 21:24:57 +00003239}
3240
3241static int
3242type_clear(PyTypeObject *type)
3243{
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003244 PyDictKeysObject *cached_keys;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003245 /* Because of type_is_gc(), the collector only calls this
3246 for heaptypes. */
3247 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00003248
Antoine Pitrou2e872082011-12-15 14:15:31 +01003249 /* We need to invalidate the method cache carefully before clearing
3250 the dict, so that other objects caught in a reference cycle
3251 don't start calling destroyed methods.
3252
3253 Otherwise, the only field we need to clear is tp_mro, which is
3254 part of a hard cycle (its first element is the class itself) that
3255 won't be broken otherwise (it's a tuple and tuples don't have a
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003256 tp_clear handler). None of the other fields need to be
3257 cleared, and here's why:
Guido van Rossum048eb752001-10-02 21:24:57 +00003258
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003259 tp_cache:
3260 Not used; if it were, it would be a dict.
Guido van Rossuma3862092002-06-10 15:24:42 +00003261
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003262 tp_bases, tp_base:
3263 If these are involved in a cycle, there must be at least
3264 one other, mutable object in the cycle, e.g. a base
3265 class's dict; the cycle will be broken that way.
Guido van Rossuma3862092002-06-10 15:24:42 +00003266
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003267 tp_subclasses:
Antoine Pitrou84745ab2013-10-29 21:31:25 +01003268 A dict of weak references can't be part of a cycle; and
3269 dicts have their own tp_clear.
Guido van Rossuma3862092002-06-10 15:24:42 +00003270
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003271 slots (in PyHeapTypeObject):
3272 A tuple of strings can't be part of a cycle.
3273 */
Guido van Rossuma3862092002-06-10 15:24:42 +00003274
Antoine Pitrou2e872082011-12-15 14:15:31 +01003275 PyType_Modified(type);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003276 cached_keys = ((PyHeapTypeObject *)type)->ht_cached_keys;
3277 if (cached_keys != NULL) {
3278 ((PyHeapTypeObject *)type)->ht_cached_keys = NULL;
3279 _PyDictKeys_DecRef(cached_keys);
3280 }
Antoine Pitrou2e872082011-12-15 14:15:31 +01003281 if (type->tp_dict)
3282 PyDict_Clear(type->tp_dict);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003283 Py_CLEAR(type->tp_mro);
Guido van Rossum048eb752001-10-02 21:24:57 +00003284
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003285 return 0;
Guido van Rossum048eb752001-10-02 21:24:57 +00003286}
3287
3288static int
3289type_is_gc(PyTypeObject *type)
3290{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003291 return type->tp_flags & Py_TPFLAGS_HEAPTYPE;
Guido van Rossum048eb752001-10-02 21:24:57 +00003292}
3293
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003294PyTypeObject PyType_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003295 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3296 "type", /* tp_name */
3297 sizeof(PyHeapTypeObject), /* tp_basicsize */
3298 sizeof(PyMemberDef), /* tp_itemsize */
3299 (destructor)type_dealloc, /* tp_dealloc */
3300 0, /* tp_print */
3301 0, /* tp_getattr */
3302 0, /* tp_setattr */
3303 0, /* tp_reserved */
3304 (reprfunc)type_repr, /* tp_repr */
3305 0, /* tp_as_number */
3306 0, /* tp_as_sequence */
3307 0, /* tp_as_mapping */
3308 0, /* tp_hash */
3309 (ternaryfunc)type_call, /* tp_call */
3310 0, /* tp_str */
3311 (getattrofunc)type_getattro, /* tp_getattro */
3312 (setattrofunc)type_setattro, /* tp_setattro */
3313 0, /* tp_as_buffer */
3314 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
3315 Py_TPFLAGS_BASETYPE | Py_TPFLAGS_TYPE_SUBCLASS, /* tp_flags */
3316 type_doc, /* tp_doc */
3317 (traverseproc)type_traverse, /* tp_traverse */
3318 (inquiry)type_clear, /* tp_clear */
3319 0, /* tp_richcompare */
3320 offsetof(PyTypeObject, tp_weaklist), /* tp_weaklistoffset */
3321 0, /* tp_iter */
3322 0, /* tp_iternext */
3323 type_methods, /* tp_methods */
3324 type_members, /* tp_members */
3325 type_getsets, /* tp_getset */
3326 0, /* tp_base */
3327 0, /* tp_dict */
3328 0, /* tp_descr_get */
3329 0, /* tp_descr_set */
3330 offsetof(PyTypeObject, tp_dict), /* tp_dictoffset */
3331 type_init, /* tp_init */
3332 0, /* tp_alloc */
3333 type_new, /* tp_new */
3334 PyObject_GC_Del, /* tp_free */
3335 (inquiry)type_is_gc, /* tp_is_gc */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003336};
Tim Peters6d6c1a32001-08-02 04:15:00 +00003337
3338
3339/* The base type of all types (eventually)... except itself. */
3340
Guido van Rossumd8faa362007-04-27 19:54:29 +00003341/* You may wonder why object.__new__() only complains about arguments
3342 when object.__init__() is not overridden, and vice versa.
3343
3344 Consider the use cases:
3345
3346 1. When neither is overridden, we want to hear complaints about
3347 excess (i.e., any) arguments, since their presence could
3348 indicate there's a bug.
3349
3350 2. When defining an Immutable type, we are likely to override only
3351 __new__(), since __init__() is called too late to initialize an
3352 Immutable object. Since __new__() defines the signature for the
3353 type, it would be a pain to have to override __init__() just to
3354 stop it from complaining about excess arguments.
3355
3356 3. When defining a Mutable type, we are likely to override only
3357 __init__(). So here the converse reasoning applies: we don't
3358 want to have to override __new__() just to stop it from
3359 complaining.
3360
3361 4. When __init__() is overridden, and the subclass __init__() calls
3362 object.__init__(), the latter should complain about excess
3363 arguments; ditto for __new__().
3364
3365 Use cases 2 and 3 make it unattractive to unconditionally check for
3366 excess arguments. The best solution that addresses all four use
3367 cases is as follows: __init__() complains about excess arguments
3368 unless __new__() is overridden and __init__() is not overridden
3369 (IOW, if __init__() is overridden or __new__() is not overridden);
3370 symmetrically, __new__() complains about excess arguments unless
3371 __init__() is overridden and __new__() is not overridden
3372 (IOW, if __new__() is overridden or __init__() is not overridden).
3373
3374 However, for backwards compatibility, this breaks too much code.
3375 Therefore, in 2.6, we'll *warn* about excess arguments when both
3376 methods are overridden; for all other cases we'll use the above
3377 rules.
3378
3379*/
3380
3381/* Forward */
3382static PyObject *
3383object_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
3384
3385static int
3386excess_args(PyObject *args, PyObject *kwds)
3387{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003388 return PyTuple_GET_SIZE(args) ||
3389 (kwds && PyDict_Check(kwds) && PyDict_Size(kwds));
Guido van Rossumd8faa362007-04-27 19:54:29 +00003390}
3391
Tim Peters6d6c1a32001-08-02 04:15:00 +00003392static int
3393object_init(PyObject *self, PyObject *args, PyObject *kwds)
3394{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003395 int err = 0;
Benjamin Peterson96384b92012-03-17 00:05:44 -05003396 PyTypeObject *type = Py_TYPE(self);
3397 if (excess_args(args, kwds) &&
3398 (type->tp_new == object_new || type->tp_init != object_init)) {
3399 PyErr_SetString(PyExc_TypeError, "object.__init__() takes no parameters");
3400 err = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003401 }
3402 return err;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003403}
3404
Guido van Rossum298e4212003-02-13 16:30:16 +00003405static PyObject *
3406object_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3407{
Benjamin Peterson96384b92012-03-17 00:05:44 -05003408 if (excess_args(args, kwds) &&
3409 (type->tp_init == object_init || type->tp_new != object_new)) {
R David Murray702a5dc2013-02-18 21:39:18 -05003410 PyErr_SetString(PyExc_TypeError, "object() takes no parameters");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003411 return NULL;
Benjamin Peterson96384b92012-03-17 00:05:44 -05003412 }
Victor Stinner3c1e4812012-03-26 22:10:51 +02003413
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003414 if (type->tp_flags & Py_TPFLAGS_IS_ABSTRACT) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003415 PyObject *abstract_methods = NULL;
3416 PyObject *builtins;
3417 PyObject *sorted;
3418 PyObject *sorted_methods = NULL;
3419 PyObject *joined = NULL;
Benjamin Peterson9a03ecf2012-03-16 20:15:54 -05003420 PyObject *comma;
3421 _Py_static_string(comma_id, ", ");
Victor Stinner3c1e4812012-03-26 22:10:51 +02003422 _Py_IDENTIFIER(sorted);
Christian Heimes9e7f1d22008-02-28 12:27:11 +00003423
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003424 /* Compute ", ".join(sorted(type.__abstractmethods__))
3425 into joined. */
3426 abstract_methods = type_abstractmethods(type, NULL);
3427 if (abstract_methods == NULL)
3428 goto error;
3429 builtins = PyEval_GetBuiltins();
3430 if (builtins == NULL)
3431 goto error;
Victor Stinner3c1e4812012-03-26 22:10:51 +02003432 sorted = _PyDict_GetItemId(builtins, &PyId_sorted);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003433 if (sorted == NULL)
3434 goto error;
3435 sorted_methods = PyObject_CallFunctionObjArgs(sorted,
3436 abstract_methods,
3437 NULL);
3438 if (sorted_methods == NULL)
3439 goto error;
Benjamin Peterson9a03ecf2012-03-16 20:15:54 -05003440 comma = _PyUnicode_FromId(&comma_id);
3441 if (comma == NULL)
3442 goto error;
3443 joined = PyUnicode_Join(comma, sorted_methods);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003444 if (joined == NULL)
3445 goto error;
Christian Heimes9e7f1d22008-02-28 12:27:11 +00003446
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003447 PyErr_Format(PyExc_TypeError,
3448 "Can't instantiate abstract class %s "
3449 "with abstract methods %U",
3450 type->tp_name,
3451 joined);
3452 error:
3453 Py_XDECREF(joined);
3454 Py_XDECREF(sorted_methods);
3455 Py_XDECREF(abstract_methods);
3456 return NULL;
3457 }
3458 return type->tp_alloc(type, 0);
Guido van Rossum298e4212003-02-13 16:30:16 +00003459}
3460
Tim Peters6d6c1a32001-08-02 04:15:00 +00003461static void
3462object_dealloc(PyObject *self)
3463{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003464 Py_TYPE(self)->tp_free(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003465}
3466
Guido van Rossum8e248182001-08-12 05:17:56 +00003467static PyObject *
3468object_repr(PyObject *self)
3469{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003470 PyTypeObject *type;
3471 PyObject *mod, *name, *rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00003472
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003473 type = Py_TYPE(self);
3474 mod = type_module(type, NULL);
3475 if (mod == NULL)
3476 PyErr_Clear();
3477 else if (!PyUnicode_Check(mod)) {
3478 Py_DECREF(mod);
3479 mod = NULL;
3480 }
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003481 name = type_qualname(type, NULL);
Christian Heimese81dc292012-09-10 16:57:36 +02003482 if (name == NULL) {
3483 Py_XDECREF(mod);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003484 return NULL;
Christian Heimese81dc292012-09-10 16:57:36 +02003485 }
Victor Stinnerbd303c12013-11-07 23:07:29 +01003486 if (mod != NULL && _PyUnicode_CompareWithId(mod, &PyId_builtins))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003487 rtn = PyUnicode_FromFormat("<%U.%U object at %p>", mod, name, self);
3488 else
3489 rtn = PyUnicode_FromFormat("<%s object at %p>",
3490 type->tp_name, self);
3491 Py_XDECREF(mod);
3492 Py_DECREF(name);
3493 return rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00003494}
3495
Guido van Rossumb8f63662001-08-15 23:57:02 +00003496static PyObject *
3497object_str(PyObject *self)
3498{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003499 unaryfunc f;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003500
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003501 f = Py_TYPE(self)->tp_repr;
Benjamin Peterson7b166872012-04-24 11:06:25 -04003502 if (f == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003503 f = object_repr;
3504 return f(self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003505}
3506
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003507static PyObject *
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003508object_richcompare(PyObject *self, PyObject *other, int op)
3509{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003510 PyObject *res;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003511
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003512 switch (op) {
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003513
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003514 case Py_EQ:
3515 /* Return NotImplemented instead of False, so if two
3516 objects are compared, both get a chance at the
3517 comparison. See issue #1393. */
3518 res = (self == other) ? Py_True : Py_NotImplemented;
3519 Py_INCREF(res);
3520 break;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003521
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003522 case Py_NE:
Serhiy Storchakaf4b7a022015-01-26 09:57:07 +02003523 /* By default, __ne__() delegates to __eq__() and inverts the result,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003524 unless the latter returns NotImplemented. */
Serhiy Storchakaf4b7a022015-01-26 09:57:07 +02003525 if (self->ob_type->tp_richcompare == NULL) {
3526 res = Py_NotImplemented;
3527 Py_INCREF(res);
3528 break;
3529 }
3530 res = (*self->ob_type->tp_richcompare)(self, other, Py_EQ);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003531 if (res != NULL && res != Py_NotImplemented) {
3532 int ok = PyObject_IsTrue(res);
3533 Py_DECREF(res);
3534 if (ok < 0)
3535 res = NULL;
3536 else {
3537 if (ok)
3538 res = Py_False;
3539 else
3540 res = Py_True;
3541 Py_INCREF(res);
3542 }
3543 }
3544 break;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003545
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003546 default:
3547 res = Py_NotImplemented;
3548 Py_INCREF(res);
3549 break;
3550 }
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003551
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003552 return res;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003553}
3554
3555static PyObject *
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003556object_get_class(PyObject *self, void *closure)
3557{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003558 Py_INCREF(Py_TYPE(self));
3559 return (PyObject *)(Py_TYPE(self));
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003560}
3561
3562static int
Benjamin Peterson9d4cbcc2015-01-30 13:33:42 -05003563compatible_with_tp_base(PyTypeObject *child)
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003564{
Benjamin Peterson9d4cbcc2015-01-30 13:33:42 -05003565 PyTypeObject *parent = child->tp_base;
3566 return (parent != NULL &&
3567 child->tp_basicsize == parent->tp_basicsize &&
3568 child->tp_itemsize == parent->tp_itemsize &&
3569 child->tp_dictoffset == parent->tp_dictoffset &&
3570 child->tp_weaklistoffset == parent->tp_weaklistoffset &&
3571 ((child->tp_flags & Py_TPFLAGS_HAVE_GC) ==
3572 (parent->tp_flags & Py_TPFLAGS_HAVE_GC)) &&
3573 (child->tp_dealloc == subtype_dealloc ||
3574 child->tp_dealloc == parent->tp_dealloc));
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003575}
3576
3577static int
3578same_slots_added(PyTypeObject *a, PyTypeObject *b)
3579{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003580 PyTypeObject *base = a->tp_base;
3581 Py_ssize_t size;
3582 PyObject *slots_a, *slots_b;
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003583
Benjamin Peterson67641d22011-01-17 19:24:34 +00003584 assert(base == b->tp_base);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003585 size = base->tp_basicsize;
3586 if (a->tp_dictoffset == size && b->tp_dictoffset == size)
3587 size += sizeof(PyObject *);
3588 if (a->tp_weaklistoffset == size && b->tp_weaklistoffset == size)
3589 size += sizeof(PyObject *);
Guido van Rossumd8faa362007-04-27 19:54:29 +00003590
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003591 /* Check slots compliance */
Benjamin Peterson9d4cbcc2015-01-30 13:33:42 -05003592 if (!(a->tp_flags & Py_TPFLAGS_HEAPTYPE) ||
3593 !(b->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
3594 return 0;
3595 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003596 slots_a = ((PyHeapTypeObject *)a)->ht_slots;
3597 slots_b = ((PyHeapTypeObject *)b)->ht_slots;
3598 if (slots_a && slots_b) {
3599 if (PyObject_RichCompareBool(slots_a, slots_b, Py_EQ) != 1)
3600 return 0;
3601 size += sizeof(PyObject *) * PyTuple_GET_SIZE(slots_a);
3602 }
3603 return size == a->tp_basicsize && size == b->tp_basicsize;
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003604}
3605
3606static int
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003607compatible_for_assignment(PyTypeObject* oldto, PyTypeObject* newto, char* attr)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003608{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003609 PyTypeObject *newbase, *oldbase;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003610
Benjamin Peterson9d4cbcc2015-01-30 13:33:42 -05003611 if (newto->tp_free != oldto->tp_free) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003612 PyErr_Format(PyExc_TypeError,
3613 "%s assignment: "
3614 "'%s' deallocator differs from '%s'",
3615 attr,
3616 newto->tp_name,
3617 oldto->tp_name);
3618 return 0;
3619 }
Benjamin Peterson9d4cbcc2015-01-30 13:33:42 -05003620 /*
3621 It's tricky to tell if two arbitrary types are sufficiently compatible as
3622 to be interchangeable; e.g., even if they have the same tp_basicsize, they
3623 might have totally different struct fields. It's much easier to tell if a
3624 type and its supertype are compatible; e.g., if they have the same
3625 tp_basicsize, then that means they have identical fields. So to check
3626 whether two arbitrary types are compatible, we first find the highest
3627 supertype that each is compatible with, and then if those supertypes are
3628 compatible then the original types must also be compatible.
3629 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003630 newbase = newto;
3631 oldbase = oldto;
Benjamin Peterson9d4cbcc2015-01-30 13:33:42 -05003632 while (compatible_with_tp_base(newbase))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003633 newbase = newbase->tp_base;
Benjamin Peterson9d4cbcc2015-01-30 13:33:42 -05003634 while (compatible_with_tp_base(oldbase))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003635 oldbase = oldbase->tp_base;
3636 if (newbase != oldbase &&
3637 (newbase->tp_base != oldbase->tp_base ||
3638 !same_slots_added(newbase, oldbase))) {
3639 PyErr_Format(PyExc_TypeError,
3640 "%s assignment: "
3641 "'%s' object layout differs from '%s'",
3642 attr,
3643 newto->tp_name,
3644 oldto->tp_name);
3645 return 0;
3646 }
Tim Petersea7f75d2002-12-07 21:39:16 +00003647
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003648 return 1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003649}
3650
3651static int
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003652object_set_class(PyObject *self, PyObject *value, void *closure)
3653{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003654 PyTypeObject *oldto = Py_TYPE(self);
3655 PyTypeObject *newto;
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003656
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003657 if (value == NULL) {
3658 PyErr_SetString(PyExc_TypeError,
3659 "can't delete __class__ attribute");
3660 return -1;
3661 }
3662 if (!PyType_Check(value)) {
3663 PyErr_Format(PyExc_TypeError,
Florent Xiclunaaa6c1d22011-12-12 18:54:29 +01003664 "__class__ must be set to a class, not '%s' object",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003665 Py_TYPE(value)->tp_name);
3666 return -1;
3667 }
3668 newto = (PyTypeObject *)value;
Guido van Rossum7d293ee2015-09-04 20:54:07 -07003669 /* In versions of CPython prior to 3.5, the code in
3670 compatible_for_assignment was not set up to correctly check for memory
3671 layout / slot / etc. compatibility for non-HEAPTYPE classes, so we just
3672 disallowed __class__ assignment in any case that wasn't HEAPTYPE ->
3673 HEAPTYPE.
3674
3675 During the 3.5 development cycle, we fixed the code in
3676 compatible_for_assignment to correctly check compatibility between
3677 arbitrary types, and started allowing __class__ assignment in all cases
3678 where the old and new types did in fact have compatible slots and
3679 memory layout (regardless of whether they were implemented as HEAPTYPEs
3680 or not).
3681
3682 Just before 3.5 was released, though, we discovered that this led to
3683 problems with immutable types like int, where the interpreter assumes
3684 they are immutable and interns some values. Formerly this wasn't a
3685 problem, because they really were immutable -- in particular, all the
3686 types where the interpreter applied this interning trick happened to
3687 also be statically allocated, so the old HEAPTYPE rules were
3688 "accidentally" stopping them from allowing __class__ assignment. But
3689 with the changes to __class__ assignment, we started allowing code like
3690
3691 class MyInt(int):
3692 ...
3693 # Modifies the type of *all* instances of 1 in the whole program,
3694 # including future instances (!), because the 1 object is interned.
3695 (1).__class__ = MyInt
3696
3697 (see https://bugs.python.org/issue24912).
3698
3699 In theory the proper fix would be to identify which classes rely on
3700 this invariant and somehow disallow __class__ assignment only for them,
3701 perhaps via some mechanism like a new Py_TPFLAGS_IMMUTABLE flag (a
3702 "blacklisting" approach). But in practice, since this problem wasn't
3703 noticed late in the 3.5 RC cycle, we're taking the conservative
3704 approach and reinstating the same HEAPTYPE->HEAPTYPE check that we used
3705 to have, plus a "whitelist". For now, the whitelist consists only of
3706 ModuleType subtypes, since those are the cases that motivated the patch
3707 in the first place -- see https://bugs.python.org/issue22986 -- and
3708 since module objects are mutable we can be sure that they are
3709 definitely not being interned. So now we allow HEAPTYPE->HEAPTYPE *or*
3710 ModuleType subtype -> ModuleType subtype.
3711
3712 So far as we know, all the code beyond the following 'if' statement
3713 will correctly handle non-HEAPTYPE classes, and the HEAPTYPE check is
3714 needed only to protect that subset of non-HEAPTYPE classes for which
3715 the interpreter has baked in the assumption that all instances are
3716 truly immutable.
3717 */
3718 if (!(PyType_IsSubtype(newto, &PyModule_Type) &&
3719 PyType_IsSubtype(oldto, &PyModule_Type)) &&
3720 (!(newto->tp_flags & Py_TPFLAGS_HEAPTYPE) ||
3721 !(oldto->tp_flags & Py_TPFLAGS_HEAPTYPE))) {
3722 PyErr_Format(PyExc_TypeError,
3723 "__class__ assignment only supported for heap types "
3724 "or ModuleType subclasses");
3725 return -1;
3726 }
3727
Christian Heimesde4d1832013-07-20 14:19:46 +02003728 if (compatible_for_assignment(oldto, newto, "__class__")) {
Benjamin Peterson9d4cbcc2015-01-30 13:33:42 -05003729 if (newto->tp_flags & Py_TPFLAGS_HEAPTYPE)
3730 Py_INCREF(newto);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003731 Py_TYPE(self) = newto;
Benjamin Peterson9d4cbcc2015-01-30 13:33:42 -05003732 if (oldto->tp_flags & Py_TPFLAGS_HEAPTYPE)
3733 Py_DECREF(oldto);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003734 return 0;
3735 }
3736 else {
3737 return -1;
3738 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003739}
3740
3741static PyGetSetDef object_getsets[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003742 {"__class__", object_get_class, object_set_class,
3743 PyDoc_STR("the object's class")},
3744 {0}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003745};
3746
Guido van Rossumc53f0092003-02-18 22:05:12 +00003747
Guido van Rossum036f9992003-02-21 22:02:54 +00003748/* Stuff to implement __reduce_ex__ for pickle protocols >= 2.
Alexandre Vassalottif7fa63d2008-05-11 08:55:36 +00003749 We fall back to helpers in copyreg for:
Guido van Rossum036f9992003-02-21 22:02:54 +00003750 - pickle protocols < 2
3751 - calculating the list of slot names (done only once per class)
3752 - the __newobj__ function (which is used as a token but never called)
3753*/
3754
3755static PyObject *
Alexandre Vassalottif7fa63d2008-05-11 08:55:36 +00003756import_copyreg(void)
Guido van Rossum036f9992003-02-21 22:02:54 +00003757{
Alexandre Vassalotti1a830702013-11-30 00:53:09 -08003758 PyObject *copyreg_str;
3759 PyObject *copyreg_module;
3760 PyInterpreterState *interp = PyThreadState_GET()->interp;
3761 _Py_IDENTIFIER(copyreg);
Guido van Rossum3926a632001-09-25 16:25:58 +00003762
Alexandre Vassalotti1a830702013-11-30 00:53:09 -08003763 copyreg_str = _PyUnicode_FromId(&PyId_copyreg);
3764 if (copyreg_str == NULL) {
3765 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003766 }
Alexandre Vassalotti1a830702013-11-30 00:53:09 -08003767 /* Try to fetch cached copy of copyreg from sys.modules first in an
3768 attempt to avoid the import overhead. Previously this was implemented
3769 by storing a reference to the cached module in a static variable, but
3770 this broke when multiple embeded interpreters were in use (see issue
3771 #17408 and #19088). */
3772 copyreg_module = PyDict_GetItemWithError(interp->modules, copyreg_str);
3773 if (copyreg_module != NULL) {
3774 Py_INCREF(copyreg_module);
3775 return copyreg_module;
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003776 }
Alexandre Vassalotti1a830702013-11-30 00:53:09 -08003777 if (PyErr_Occurred()) {
3778 return NULL;
3779 }
3780 return PyImport_Import(copyreg_str);
Guido van Rossum036f9992003-02-21 22:02:54 +00003781}
3782
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01003783Py_LOCAL(PyObject *)
3784_PyType_GetSlotNames(PyTypeObject *cls)
Guido van Rossum036f9992003-02-21 22:02:54 +00003785{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003786 PyObject *copyreg;
3787 PyObject *slotnames;
Victor Stinner3c1e4812012-03-26 22:10:51 +02003788 _Py_IDENTIFIER(__slotnames__);
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02003789 _Py_IDENTIFIER(_slotnames);
Guido van Rossum036f9992003-02-21 22:02:54 +00003790
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01003791 assert(PyType_Check(cls));
3792
3793 /* Get the slot names from the cache in the class if possible. */
3794 slotnames = _PyDict_GetItemIdWithError(cls->tp_dict, &PyId___slotnames__);
3795 if (slotnames != NULL) {
3796 if (slotnames != Py_None && !PyList_Check(slotnames)) {
3797 PyErr_Format(PyExc_TypeError,
3798 "%.200s.__slotnames__ should be a list or None, "
3799 "not %.200s",
3800 cls->tp_name, Py_TYPE(slotnames)->tp_name);
3801 return NULL;
3802 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003803 Py_INCREF(slotnames);
3804 return slotnames;
3805 }
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01003806 else {
3807 if (PyErr_Occurred()) {
3808 return NULL;
3809 }
3810 /* The class does not have the slot names cached yet. */
3811 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003812
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003813 copyreg = import_copyreg();
3814 if (copyreg == NULL)
3815 return NULL;
Guido van Rossum036f9992003-02-21 22:02:54 +00003816
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01003817 /* Use _slotnames function from the copyreg module to find the slots
3818 by this class and its bases. This function will cache the result
3819 in __slotnames__. */
3820 slotnames = _PyObject_CallMethodIdObjArgs(copyreg, &PyId__slotnames,
3821 cls, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003822 Py_DECREF(copyreg);
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01003823 if (slotnames == NULL)
3824 return NULL;
3825
3826 if (slotnames != Py_None && !PyList_Check(slotnames)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003827 PyErr_SetString(PyExc_TypeError,
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01003828 "copyreg._slotnames didn't return a list or None");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003829 Py_DECREF(slotnames);
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01003830 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003831 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003832
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003833 return slotnames;
Guido van Rossum036f9992003-02-21 22:02:54 +00003834}
3835
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01003836Py_LOCAL(PyObject *)
3837_PyObject_GetState(PyObject *obj)
Guido van Rossum036f9992003-02-21 22:02:54 +00003838{
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01003839 PyObject *state;
3840 PyObject *getstate;
Victor Stinner3c1e4812012-03-26 22:10:51 +02003841 _Py_IDENTIFIER(__getstate__);
Guido van Rossum036f9992003-02-21 22:02:54 +00003842
Victor Stinner3c1e4812012-03-26 22:10:51 +02003843 getstate = _PyObject_GetAttrId(obj, &PyId___getstate__);
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01003844 if (getstate == NULL) {
3845 PyObject *slotnames;
3846
3847 if (!PyErr_ExceptionMatches(PyExc_AttributeError)) {
3848 return NULL;
3849 }
3850 PyErr_Clear();
3851
3852 {
3853 PyObject **dict;
3854 dict = _PyObject_GetDictPtr(obj);
Larry Hastings5c661892014-01-24 06:17:25 -08003855 /* It is possible that the object's dict is not initialized
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01003856 yet. In this case, we will return None for the state.
3857 We also return None if the dict is empty to make the behavior
3858 consistent regardless whether the dict was initialized or not.
3859 This make unit testing easier. */
3860 if (dict != NULL && *dict != NULL && PyDict_Size(*dict) > 0) {
3861 state = *dict;
3862 }
3863 else {
3864 state = Py_None;
3865 }
3866 Py_INCREF(state);
3867 }
3868
3869 slotnames = _PyType_GetSlotNames(Py_TYPE(obj));
3870 if (slotnames == NULL) {
3871 Py_DECREF(state);
3872 return NULL;
3873 }
3874
3875 assert(slotnames == Py_None || PyList_Check(slotnames));
3876 if (slotnames != Py_None && Py_SIZE(slotnames) > 0) {
3877 PyObject *slots;
3878 Py_ssize_t slotnames_size, i;
3879
3880 slots = PyDict_New();
3881 if (slots == NULL) {
3882 Py_DECREF(slotnames);
3883 Py_DECREF(state);
3884 return NULL;
3885 }
3886
3887 slotnames_size = Py_SIZE(slotnames);
3888 for (i = 0; i < slotnames_size; i++) {
3889 PyObject *name, *value;
3890
3891 name = PyList_GET_ITEM(slotnames, i);
3892 value = PyObject_GetAttr(obj, name);
3893 if (value == NULL) {
3894 if (!PyErr_ExceptionMatches(PyExc_AttributeError)) {
3895 goto error;
3896 }
3897 /* It is not an error if the attribute is not present. */
3898 PyErr_Clear();
3899 }
3900 else {
3901 int err = PyDict_SetItem(slots, name, value);
3902 Py_DECREF(value);
3903 if (err) {
3904 goto error;
3905 }
3906 }
3907
3908 /* The list is stored on the class so it may mutates while we
3909 iterate over it */
3910 if (slotnames_size != Py_SIZE(slotnames)) {
3911 PyErr_Format(PyExc_RuntimeError,
3912 "__slotsname__ changed size during iteration");
3913 goto error;
3914 }
3915
3916 /* We handle errors within the loop here. */
3917 if (0) {
3918 error:
3919 Py_DECREF(slotnames);
3920 Py_DECREF(slots);
3921 Py_DECREF(state);
3922 return NULL;
3923 }
3924 }
3925
3926 /* If we found some slot attributes, pack them in a tuple along
3927 the orginal attribute dictionary. */
3928 if (PyDict_Size(slots) > 0) {
3929 PyObject *state2;
3930
3931 state2 = PyTuple_Pack(2, state, slots);
3932 Py_DECREF(state);
3933 if (state2 == NULL) {
3934 Py_DECREF(slotnames);
3935 Py_DECREF(slots);
3936 return NULL;
3937 }
3938 state = state2;
3939 }
3940 Py_DECREF(slots);
3941 }
3942 Py_DECREF(slotnames);
3943 }
3944 else { /* getstate != NULL */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003945 state = PyObject_CallObject(getstate, NULL);
3946 Py_DECREF(getstate);
3947 if (state == NULL)
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01003948 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003949 }
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01003950
3951 return state;
3952}
3953
3954Py_LOCAL(int)
3955_PyObject_GetNewArguments(PyObject *obj, PyObject **args, PyObject **kwargs)
3956{
3957 PyObject *getnewargs, *getnewargs_ex;
3958 _Py_IDENTIFIER(__getnewargs_ex__);
3959 _Py_IDENTIFIER(__getnewargs__);
3960
3961 if (args == NULL || kwargs == NULL) {
3962 PyErr_BadInternalCall();
3963 return -1;
3964 }
3965
3966 /* We first attempt to fetch the arguments for __new__ by calling
3967 __getnewargs_ex__ on the object. */
Benjamin Petersone686c5c2014-02-16 13:49:16 -05003968 getnewargs_ex = _PyObject_LookupSpecial(obj, &PyId___getnewargs_ex__);
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01003969 if (getnewargs_ex != NULL) {
3970 PyObject *newargs = PyObject_CallObject(getnewargs_ex, NULL);
3971 Py_DECREF(getnewargs_ex);
3972 if (newargs == NULL) {
3973 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003974 }
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01003975 if (!PyTuple_Check(newargs)) {
3976 PyErr_Format(PyExc_TypeError,
3977 "__getnewargs_ex__ should return a tuple, "
3978 "not '%.200s'", Py_TYPE(newargs)->tp_name);
3979 Py_DECREF(newargs);
3980 return -1;
3981 }
3982 if (Py_SIZE(newargs) != 2) {
3983 PyErr_Format(PyExc_ValueError,
3984 "__getnewargs_ex__ should return a tuple of "
3985 "length 2, not %zd", Py_SIZE(newargs));
3986 Py_DECREF(newargs);
3987 return -1;
3988 }
3989 *args = PyTuple_GET_ITEM(newargs, 0);
3990 Py_INCREF(*args);
3991 *kwargs = PyTuple_GET_ITEM(newargs, 1);
3992 Py_INCREF(*kwargs);
3993 Py_DECREF(newargs);
3994
3995 /* XXX We should perhaps allow None to be passed here. */
3996 if (!PyTuple_Check(*args)) {
3997 PyErr_Format(PyExc_TypeError,
3998 "first item of the tuple returned by "
3999 "__getnewargs_ex__ must be a tuple, not '%.200s'",
4000 Py_TYPE(*args)->tp_name);
4001 Py_CLEAR(*args);
4002 Py_CLEAR(*kwargs);
4003 return -1;
4004 }
4005 if (!PyDict_Check(*kwargs)) {
4006 PyErr_Format(PyExc_TypeError,
4007 "second item of the tuple returned by "
4008 "__getnewargs_ex__ must be a dict, not '%.200s'",
4009 Py_TYPE(*kwargs)->tp_name);
4010 Py_CLEAR(*args);
4011 Py_CLEAR(*kwargs);
4012 return -1;
4013 }
4014 return 0;
Benjamin Petersone686c5c2014-02-16 13:49:16 -05004015 } else if (PyErr_Occurred()) {
4016 return -1;
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004017 }
4018
4019 /* The object does not have __getnewargs_ex__ so we fallback on using
4020 __getnewargs__ instead. */
Benjamin Petersone686c5c2014-02-16 13:49:16 -05004021 getnewargs = _PyObject_LookupSpecial(obj, &PyId___getnewargs__);
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004022 if (getnewargs != NULL) {
4023 *args = PyObject_CallObject(getnewargs, NULL);
4024 Py_DECREF(getnewargs);
4025 if (*args == NULL) {
4026 return -1;
4027 }
4028 if (!PyTuple_Check(*args)) {
4029 PyErr_Format(PyExc_TypeError,
4030 "__getnewargs__ should return a tuple, "
4031 "not '%.200s'", Py_TYPE(*args)->tp_name);
4032 Py_CLEAR(*args);
4033 return -1;
4034 }
4035 *kwargs = NULL;
4036 return 0;
Benjamin Petersone686c5c2014-02-16 13:49:16 -05004037 } else if (PyErr_Occurred()) {
4038 return -1;
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004039 }
4040
4041 /* The object does not have __getnewargs_ex__ and __getnewargs__. This may
4042 means __new__ does not takes any arguments on this object, or that the
4043 object does not implement the reduce protocol for pickling or
4044 copying. */
4045 *args = NULL;
4046 *kwargs = NULL;
4047 return 0;
4048}
4049
4050Py_LOCAL(int)
4051_PyObject_GetItemsIter(PyObject *obj, PyObject **listitems,
4052 PyObject **dictitems)
4053{
4054 if (listitems == NULL || dictitems == NULL) {
4055 PyErr_BadInternalCall();
4056 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004057 }
Guido van Rossum036f9992003-02-21 22:02:54 +00004058
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004059 if (!PyList_Check(obj)) {
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004060 *listitems = Py_None;
4061 Py_INCREF(*listitems);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004062 }
4063 else {
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004064 *listitems = PyObject_GetIter(obj);
Christian Heimes2489bd82013-11-23 21:19:43 +01004065 if (*listitems == NULL)
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004066 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004067 }
Guido van Rossum036f9992003-02-21 22:02:54 +00004068
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004069 if (!PyDict_Check(obj)) {
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004070 *dictitems = Py_None;
4071 Py_INCREF(*dictitems);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004072 }
4073 else {
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004074 PyObject *items;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02004075 _Py_IDENTIFIER(items);
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004076
4077 items = _PyObject_CallMethodIdObjArgs(obj, &PyId_items, NULL);
4078 if (items == NULL) {
4079 Py_CLEAR(*listitems);
4080 return -1;
4081 }
4082 *dictitems = PyObject_GetIter(items);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004083 Py_DECREF(items);
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004084 if (*dictitems == NULL) {
4085 Py_CLEAR(*listitems);
4086 return -1;
4087 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004088 }
Guido van Rossum036f9992003-02-21 22:02:54 +00004089
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004090 assert(*listitems != NULL && *dictitems != NULL);
4091
4092 return 0;
4093}
4094
4095static PyObject *
Serhiy Storchaka707b5cc2014-12-16 19:43:46 +02004096reduce_newobj(PyObject *obj, int proto)
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004097{
4098 PyObject *args = NULL, *kwargs = NULL;
4099 PyObject *copyreg;
4100 PyObject *newobj, *newargs, *state, *listitems, *dictitems;
4101 PyObject *result;
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004102
Serhiy Storchaka707b5cc2014-12-16 19:43:46 +02004103 if (_PyObject_GetNewArguments(obj, &args, &kwargs) < 0)
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004104 return NULL;
Serhiy Storchaka707b5cc2014-12-16 19:43:46 +02004105
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004106 if (args == NULL) {
4107 args = PyTuple_New(0);
Serhiy Storchaka707b5cc2014-12-16 19:43:46 +02004108 if (args == NULL) {
4109 Py_XDECREF(kwargs);
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004110 return NULL;
Serhiy Storchaka707b5cc2014-12-16 19:43:46 +02004111 }
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004112 }
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004113 copyreg = import_copyreg();
4114 if (copyreg == NULL) {
4115 Py_DECREF(args);
Serhiy Storchaka707b5cc2014-12-16 19:43:46 +02004116 Py_XDECREF(kwargs);
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004117 return NULL;
4118 }
Serhiy Storchaka707b5cc2014-12-16 19:43:46 +02004119 if (kwargs == NULL || PyDict_Size(kwargs) == 0) {
4120 _Py_IDENTIFIER(__newobj__);
4121 PyObject *cls;
4122 Py_ssize_t i, n;
4123
4124 Py_XDECREF(kwargs);
4125 newobj = _PyObject_GetAttrId(copyreg, &PyId___newobj__);
4126 Py_DECREF(copyreg);
4127 if (newobj == NULL) {
4128 Py_DECREF(args);
4129 return NULL;
4130 }
4131 n = PyTuple_GET_SIZE(args);
4132 newargs = PyTuple_New(n+1);
4133 if (newargs == NULL) {
4134 Py_DECREF(args);
4135 Py_DECREF(newobj);
4136 return NULL;
4137 }
4138 cls = (PyObject *) Py_TYPE(obj);
4139 Py_INCREF(cls);
4140 PyTuple_SET_ITEM(newargs, 0, cls);
4141 for (i = 0; i < n; i++) {
4142 PyObject *v = PyTuple_GET_ITEM(args, i);
4143 Py_INCREF(v);
4144 PyTuple_SET_ITEM(newargs, i+1, v);
4145 }
4146 Py_DECREF(args);
4147 }
4148 else if (proto >= 4) {
4149 _Py_IDENTIFIER(__newobj_ex__);
4150
4151 newobj = _PyObject_GetAttrId(copyreg, &PyId___newobj_ex__);
4152 Py_DECREF(copyreg);
4153 if (newobj == NULL) {
4154 Py_DECREF(args);
4155 Py_DECREF(kwargs);
4156 return NULL;
4157 }
4158 newargs = PyTuple_Pack(3, Py_TYPE(obj), args, kwargs);
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004159 Py_DECREF(args);
4160 Py_DECREF(kwargs);
Serhiy Storchaka707b5cc2014-12-16 19:43:46 +02004161 if (newargs == NULL) {
4162 Py_DECREF(newobj);
4163 return NULL;
4164 }
4165 }
4166 else {
4167 PyErr_SetString(PyExc_ValueError,
4168 "must use protocol 4 or greater to copy this "
4169 "object; since __getnewargs_ex__ returned "
4170 "keyword arguments.");
4171 Py_DECREF(args);
4172 Py_DECREF(kwargs);
4173 Py_DECREF(copyreg);
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004174 return NULL;
4175 }
Serhiy Storchaka707b5cc2014-12-16 19:43:46 +02004176
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004177 state = _PyObject_GetState(obj);
4178 if (state == NULL) {
4179 Py_DECREF(newobj);
4180 Py_DECREF(newargs);
4181 return NULL;
4182 }
4183 if (_PyObject_GetItemsIter(obj, &listitems, &dictitems) < 0) {
4184 Py_DECREF(newobj);
4185 Py_DECREF(newargs);
4186 Py_DECREF(state);
4187 return NULL;
4188 }
4189
4190 result = PyTuple_Pack(5, newobj, newargs, state, listitems, dictitems);
4191 Py_DECREF(newobj);
4192 Py_DECREF(newargs);
4193 Py_DECREF(state);
4194 Py_DECREF(listitems);
4195 Py_DECREF(dictitems);
Larry Hastings5c661892014-01-24 06:17:25 -08004196 return result;
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004197}
4198
Guido van Rossumd8faa362007-04-27 19:54:29 +00004199/*
4200 * There were two problems when object.__reduce__ and object.__reduce_ex__
4201 * were implemented in the same function:
4202 * - trying to pickle an object with a custom __reduce__ method that
4203 * fell back to object.__reduce__ in certain circumstances led to
Yury Selivanovf488fb42015-07-03 01:04:23 -04004204 * infinite recursion at Python level and eventual RecursionError.
Guido van Rossumd8faa362007-04-27 19:54:29 +00004205 * - Pickling objects that lied about their type by overwriting the
4206 * __class__ descriptor could lead to infinite recursion at C level
4207 * and eventual segfault.
4208 *
4209 * Because of backwards compatibility, the two methods still have to
4210 * behave in the same way, even if this is not required by the pickle
4211 * protocol. This common functionality was moved to the _common_reduce
4212 * function.
4213 */
4214static PyObject *
4215_common_reduce(PyObject *self, int proto)
4216{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004217 PyObject *copyreg, *res;
Guido van Rossumd8faa362007-04-27 19:54:29 +00004218
Serhiy Storchaka707b5cc2014-12-16 19:43:46 +02004219 if (proto >= 2)
4220 return reduce_newobj(self, proto);
Guido van Rossumd8faa362007-04-27 19:54:29 +00004221
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004222 copyreg = import_copyreg();
4223 if (!copyreg)
4224 return NULL;
Guido van Rossumd8faa362007-04-27 19:54:29 +00004225
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004226 res = PyEval_CallMethod(copyreg, "_reduce_ex", "(Oi)", self, proto);
4227 Py_DECREF(copyreg);
Guido van Rossumd8faa362007-04-27 19:54:29 +00004228
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004229 return res;
Guido van Rossumd8faa362007-04-27 19:54:29 +00004230}
4231
4232static PyObject *
4233object_reduce(PyObject *self, PyObject *args)
4234{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004235 int proto = 0;
Guido van Rossumd8faa362007-04-27 19:54:29 +00004236
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004237 if (!PyArg_ParseTuple(args, "|i:__reduce__", &proto))
4238 return NULL;
Guido van Rossumd8faa362007-04-27 19:54:29 +00004239
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004240 return _common_reduce(self, proto);
Guido van Rossumd8faa362007-04-27 19:54:29 +00004241}
4242
Guido van Rossum036f9992003-02-21 22:02:54 +00004243static PyObject *
4244object_reduce_ex(PyObject *self, PyObject *args)
4245{
Victor Stinner3c1e4812012-03-26 22:10:51 +02004246 static PyObject *objreduce;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004247 PyObject *reduce, *res;
4248 int proto = 0;
Victor Stinner3c1e4812012-03-26 22:10:51 +02004249 _Py_IDENTIFIER(__reduce__);
Guido van Rossum036f9992003-02-21 22:02:54 +00004250
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004251 if (!PyArg_ParseTuple(args, "|i:__reduce_ex__", &proto))
4252 return NULL;
Guido van Rossum036f9992003-02-21 22:02:54 +00004253
Victor Stinner3c1e4812012-03-26 22:10:51 +02004254 if (objreduce == NULL) {
4255 objreduce = _PyDict_GetItemId(PyBaseObject_Type.tp_dict,
4256 &PyId___reduce__);
4257 if (objreduce == NULL)
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01004258 return NULL;
4259 }
4260
Victor Stinner3c1e4812012-03-26 22:10:51 +02004261 reduce = _PyObject_GetAttrId(self, &PyId___reduce__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004262 if (reduce == NULL)
4263 PyErr_Clear();
4264 else {
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01004265 PyObject *cls, *clsreduce;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004266 int override;
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01004267
4268 cls = (PyObject *) Py_TYPE(self);
Victor Stinner3c1e4812012-03-26 22:10:51 +02004269 clsreduce = _PyObject_GetAttrId(cls, &PyId___reduce__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004270 if (clsreduce == NULL) {
4271 Py_DECREF(reduce);
4272 return NULL;
4273 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004274 override = (clsreduce != objreduce);
4275 Py_DECREF(clsreduce);
4276 if (override) {
4277 res = PyObject_CallObject(reduce, NULL);
4278 Py_DECREF(reduce);
4279 return res;
4280 }
4281 else
4282 Py_DECREF(reduce);
4283 }
Guido van Rossum036f9992003-02-21 22:02:54 +00004284
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004285 return _common_reduce(self, proto);
Guido van Rossum3926a632001-09-25 16:25:58 +00004286}
4287
Christian Heimes9e7f1d22008-02-28 12:27:11 +00004288static PyObject *
4289object_subclasshook(PyObject *cls, PyObject *args)
4290{
Brian Curtindfc80e32011-08-10 20:28:54 -05004291 Py_RETURN_NOTIMPLEMENTED;
Christian Heimes9e7f1d22008-02-28 12:27:11 +00004292}
4293
4294PyDoc_STRVAR(object_subclasshook_doc,
4295"Abstract classes can override this to customize issubclass().\n"
4296"\n"
4297"This is invoked early on by abc.ABCMeta.__subclasscheck__().\n"
4298"It should return True, False or NotImplemented. If it returns\n"
4299"NotImplemented, the normal algorithm is used. Otherwise, it\n"
4300"overrides the normal algorithm (and the outcome is cached).\n");
Eric Smith8c663262007-08-25 02:26:07 +00004301
4302/*
4303 from PEP 3101, this code implements:
4304
4305 class object:
4306 def __format__(self, format_spec):
Serhiy Storchakad741a882015-06-11 00:06:39 +03004307 return format(str(self), format_spec)
Eric Smith8c663262007-08-25 02:26:07 +00004308*/
4309static PyObject *
4310object_format(PyObject *self, PyObject *args)
4311{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004312 PyObject *format_spec;
4313 PyObject *self_as_str = NULL;
4314 PyObject *result = NULL;
Eric Smith8c663262007-08-25 02:26:07 +00004315
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004316 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
4317 return NULL;
Eric Smith8c663262007-08-25 02:26:07 +00004318
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004319 self_as_str = PyObject_Str(self);
Eric Smithe4d63172010-09-13 20:48:43 +00004320 if (self_as_str != NULL) {
4321 /* Issue 7994: If we're converting to a string, we
Eric V. Smithb9cd3532011-03-12 10:08:48 -05004322 should reject format specifications */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004323 if (PyUnicode_GET_LENGTH(format_spec) > 0) {
Andrew Svetlov2cd8ce42012-12-23 14:27:17 +02004324 PyErr_SetString(PyExc_TypeError,
Eric V. Smithb9cd3532011-03-12 10:08:48 -05004325 "non-empty format string passed to object.__format__");
Andrew Svetlov2cd8ce42012-12-23 14:27:17 +02004326 goto done;
Eric V. Smithb9cd3532011-03-12 10:08:48 -05004327 }
Eric Smith8c663262007-08-25 02:26:07 +00004328
Eric V. Smithb9cd3532011-03-12 10:08:48 -05004329 result = PyObject_Format(self_as_str, format_spec);
Eric Smithe4d63172010-09-13 20:48:43 +00004330 }
4331
4332done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004333 Py_XDECREF(self_as_str);
Eric Smith8c663262007-08-25 02:26:07 +00004334
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004335 return result;
Eric Smith8c663262007-08-25 02:26:07 +00004336}
4337
Martin v. Löwis00709aa2008-06-04 14:18:43 +00004338static PyObject *
4339object_sizeof(PyObject *self, PyObject *args)
4340{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004341 Py_ssize_t res, isize;
Martin v. Löwis00709aa2008-06-04 14:18:43 +00004342
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004343 res = 0;
4344 isize = self->ob_type->tp_itemsize;
4345 if (isize > 0)
Antoine Pitroua6545102015-03-10 22:32:00 +01004346 res = Py_SIZE(self) * isize;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004347 res += self->ob_type->tp_basicsize;
Martin v. Löwis00709aa2008-06-04 14:18:43 +00004348
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004349 return PyLong_FromSsize_t(res);
Martin v. Löwis00709aa2008-06-04 14:18:43 +00004350}
4351
Benjamin Peterson82b00c12011-05-24 11:09:06 -05004352/* __dir__ for generic objects: returns __dict__, __class__,
4353 and recursively up the __class__.__bases__ chain.
4354*/
4355static PyObject *
4356object_dir(PyObject *self, PyObject *args)
4357{
4358 PyObject *result = NULL;
4359 PyObject *dict = NULL;
4360 PyObject *itsclass = NULL;
4361
4362 /* Get __dict__ (which may or may not be a real dict...) */
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02004363 dict = _PyObject_GetAttrId(self, &PyId___dict__);
Benjamin Peterson82b00c12011-05-24 11:09:06 -05004364 if (dict == NULL) {
4365 PyErr_Clear();
4366 dict = PyDict_New();
4367 }
4368 else if (!PyDict_Check(dict)) {
4369 Py_DECREF(dict);
4370 dict = PyDict_New();
4371 }
4372 else {
4373 /* Copy __dict__ to avoid mutating it. */
4374 PyObject *temp = PyDict_Copy(dict);
4375 Py_DECREF(dict);
4376 dict = temp;
4377 }
4378
4379 if (dict == NULL)
4380 goto error;
4381
4382 /* Merge in attrs reachable from its class. */
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02004383 itsclass = _PyObject_GetAttrId(self, &PyId___class__);
Benjamin Peterson82b00c12011-05-24 11:09:06 -05004384 if (itsclass == NULL)
4385 /* XXX(tomer): Perhaps fall back to obj->ob_type if no
4386 __class__ exists? */
4387 PyErr_Clear();
4388 else if (merge_class_dict(dict, itsclass) != 0)
4389 goto error;
4390
4391 result = PyDict_Keys(dict);
4392 /* fall through */
4393error:
4394 Py_XDECREF(itsclass);
4395 Py_XDECREF(dict);
4396 return result;
4397}
4398
Guido van Rossum3926a632001-09-25 16:25:58 +00004399static PyMethodDef object_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004400 {"__reduce_ex__", object_reduce_ex, METH_VARARGS,
4401 PyDoc_STR("helper for pickle")},
4402 {"__reduce__", object_reduce, METH_VARARGS,
4403 PyDoc_STR("helper for pickle")},
4404 {"__subclasshook__", object_subclasshook, METH_CLASS | METH_VARARGS,
4405 object_subclasshook_doc},
4406 {"__format__", object_format, METH_VARARGS,
4407 PyDoc_STR("default object formatter")},
4408 {"__sizeof__", object_sizeof, METH_NOARGS,
Benjamin Petersonfbe56bb2011-05-24 12:42:51 -05004409 PyDoc_STR("__sizeof__() -> int\nsize of object in memory, in bytes")},
Benjamin Peterson82b00c12011-05-24 11:09:06 -05004410 {"__dir__", object_dir, METH_NOARGS,
Benjamin Petersonc7284122011-05-24 12:46:15 -05004411 PyDoc_STR("__dir__() -> list\ndefault dir() implementation")},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004412 {0}
Guido van Rossum3926a632001-09-25 16:25:58 +00004413};
4414
Guido van Rossum036f9992003-02-21 22:02:54 +00004415
Tim Peters6d6c1a32001-08-02 04:15:00 +00004416PyTypeObject PyBaseObject_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004417 PyVarObject_HEAD_INIT(&PyType_Type, 0)
4418 "object", /* tp_name */
4419 sizeof(PyObject), /* tp_basicsize */
4420 0, /* tp_itemsize */
4421 object_dealloc, /* tp_dealloc */
4422 0, /* tp_print */
4423 0, /* tp_getattr */
4424 0, /* tp_setattr */
4425 0, /* tp_reserved */
4426 object_repr, /* tp_repr */
4427 0, /* tp_as_number */
4428 0, /* tp_as_sequence */
4429 0, /* tp_as_mapping */
4430 (hashfunc)_Py_HashPointer, /* tp_hash */
4431 0, /* tp_call */
4432 object_str, /* tp_str */
4433 PyObject_GenericGetAttr, /* tp_getattro */
4434 PyObject_GenericSetAttr, /* tp_setattro */
4435 0, /* tp_as_buffer */
Larry Hastings5c661892014-01-24 06:17:25 -08004436 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Larry Hastings2623c8c2014-02-08 22:15:29 -08004437 PyDoc_STR("object()\n--\n\nThe most base type"), /* tp_doc */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004438 0, /* tp_traverse */
4439 0, /* tp_clear */
4440 object_richcompare, /* tp_richcompare */
4441 0, /* tp_weaklistoffset */
4442 0, /* tp_iter */
4443 0, /* tp_iternext */
4444 object_methods, /* tp_methods */
4445 0, /* tp_members */
4446 object_getsets, /* tp_getset */
4447 0, /* tp_base */
4448 0, /* tp_dict */
4449 0, /* tp_descr_get */
4450 0, /* tp_descr_set */
4451 0, /* tp_dictoffset */
4452 object_init, /* tp_init */
4453 PyType_GenericAlloc, /* tp_alloc */
4454 object_new, /* tp_new */
4455 PyObject_Del, /* tp_free */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004456};
4457
4458
Guido van Rossum50e9fb92006-08-17 05:42:55 +00004459/* Add the methods from tp_methods to the __dict__ in a type object */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004460
4461static int
4462add_methods(PyTypeObject *type, PyMethodDef *meth)
4463{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004464 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004465
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004466 for (; meth->ml_name != NULL; meth++) {
4467 PyObject *descr;
Benjamin Peterson89a6e9a2012-05-08 09:22:24 -04004468 int err;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004469 if (PyDict_GetItemString(dict, meth->ml_name) &&
4470 !(meth->ml_flags & METH_COEXIST))
4471 continue;
4472 if (meth->ml_flags & METH_CLASS) {
4473 if (meth->ml_flags & METH_STATIC) {
4474 PyErr_SetString(PyExc_ValueError,
4475 "method cannot be both class and static");
4476 return -1;
4477 }
4478 descr = PyDescr_NewClassMethod(type, meth);
4479 }
4480 else if (meth->ml_flags & METH_STATIC) {
Andrew Svetlov3ba3a3e2012-12-25 13:32:35 +02004481 PyObject *cfunc = PyCFunction_NewEx(meth, (PyObject*)type, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004482 if (cfunc == NULL)
4483 return -1;
4484 descr = PyStaticMethod_New(cfunc);
4485 Py_DECREF(cfunc);
4486 }
4487 else {
4488 descr = PyDescr_NewMethod(type, meth);
4489 }
4490 if (descr == NULL)
4491 return -1;
Benjamin Peterson89a6e9a2012-05-08 09:22:24 -04004492 err = PyDict_SetItemString(dict, meth->ml_name, descr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004493 Py_DECREF(descr);
Benjamin Peterson89a6e9a2012-05-08 09:22:24 -04004494 if (err < 0)
4495 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004496 }
4497 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004498}
4499
4500static int
Guido van Rossum6f799372001-09-20 20:46:19 +00004501add_members(PyTypeObject *type, PyMemberDef *memb)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004502{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004503 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004504
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004505 for (; memb->name != NULL; memb++) {
4506 PyObject *descr;
4507 if (PyDict_GetItemString(dict, memb->name))
4508 continue;
4509 descr = PyDescr_NewMember(type, memb);
4510 if (descr == NULL)
4511 return -1;
4512 if (PyDict_SetItemString(dict, memb->name, descr) < 0)
4513 return -1;
4514 Py_DECREF(descr);
4515 }
4516 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004517}
4518
4519static int
Guido van Rossum32d34c82001-09-20 21:45:26 +00004520add_getset(PyTypeObject *type, PyGetSetDef *gsp)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004521{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004522 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004523
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004524 for (; gsp->name != NULL; gsp++) {
4525 PyObject *descr;
4526 if (PyDict_GetItemString(dict, gsp->name))
4527 continue;
4528 descr = PyDescr_NewGetSet(type, gsp);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004529
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004530 if (descr == NULL)
4531 return -1;
4532 if (PyDict_SetItemString(dict, gsp->name, descr) < 0)
4533 return -1;
4534 Py_DECREF(descr);
4535 }
4536 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004537}
4538
Guido van Rossum13d52f02001-08-10 21:24:08 +00004539static void
4540inherit_special(PyTypeObject *type, PyTypeObject *base)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004541{
Tim Peters6d6c1a32001-08-02 04:15:00 +00004542
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004543 /* Copying basicsize is connected to the GC flags */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004544 if (!(type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
4545 (base->tp_flags & Py_TPFLAGS_HAVE_GC) &&
4546 (!type->tp_traverse && !type->tp_clear)) {
4547 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
4548 if (type->tp_traverse == NULL)
4549 type->tp_traverse = base->tp_traverse;
4550 if (type->tp_clear == NULL)
4551 type->tp_clear = base->tp_clear;
4552 }
4553 {
4554 /* The condition below could use some explanation.
4555 It appears that tp_new is not inherited for static types
4556 whose base class is 'object'; this seems to be a precaution
4557 so that old extension types don't suddenly become
4558 callable (object.__new__ wouldn't insure the invariants
4559 that the extension type's own factory function ensures).
4560 Heap types, of course, are under our control, so they do
4561 inherit tp_new; static extension types that specify some
Florent Xiclunaaa6c1d22011-12-12 18:54:29 +01004562 other built-in type as the default also
4563 inherit object.__new__. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004564 if (base != &PyBaseObject_Type ||
4565 (type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
4566 if (type->tp_new == NULL)
4567 type->tp_new = base->tp_new;
4568 }
4569 }
Benjamin Petersona7465e22010-07-05 15:01:22 +00004570 if (type->tp_basicsize == 0)
4571 type->tp_basicsize = base->tp_basicsize;
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00004572
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004573 /* Copy other non-function slots */
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00004574
4575#undef COPYVAL
4576#define COPYVAL(SLOT) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004577 if (type->SLOT == 0) type->SLOT = base->SLOT
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00004578
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004579 COPYVAL(tp_itemsize);
4580 COPYVAL(tp_weaklistoffset);
4581 COPYVAL(tp_dictoffset);
Thomas Wouters27d517b2007-02-25 20:39:11 +00004582
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004583 /* Setup fast subclass flags */
4584 if (PyType_IsSubtype(base, (PyTypeObject*)PyExc_BaseException))
4585 type->tp_flags |= Py_TPFLAGS_BASE_EXC_SUBCLASS;
4586 else if (PyType_IsSubtype(base, &PyType_Type))
4587 type->tp_flags |= Py_TPFLAGS_TYPE_SUBCLASS;
4588 else if (PyType_IsSubtype(base, &PyLong_Type))
4589 type->tp_flags |= Py_TPFLAGS_LONG_SUBCLASS;
4590 else if (PyType_IsSubtype(base, &PyBytes_Type))
4591 type->tp_flags |= Py_TPFLAGS_BYTES_SUBCLASS;
4592 else if (PyType_IsSubtype(base, &PyUnicode_Type))
4593 type->tp_flags |= Py_TPFLAGS_UNICODE_SUBCLASS;
4594 else if (PyType_IsSubtype(base, &PyTuple_Type))
4595 type->tp_flags |= Py_TPFLAGS_TUPLE_SUBCLASS;
4596 else if (PyType_IsSubtype(base, &PyList_Type))
4597 type->tp_flags |= Py_TPFLAGS_LIST_SUBCLASS;
4598 else if (PyType_IsSubtype(base, &PyDict_Type))
4599 type->tp_flags |= Py_TPFLAGS_DICT_SUBCLASS;
Guido van Rossum13d52f02001-08-10 21:24:08 +00004600}
4601
Guido van Rossum38938152006-08-21 23:36:26 +00004602static int
Guido van Rossumf5243f02008-01-01 04:06:48 +00004603overrides_hash(PyTypeObject *type)
Guido van Rossum38938152006-08-21 23:36:26 +00004604{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004605 PyObject *dict = type->tp_dict;
Victor Stinner3c1e4812012-03-26 22:10:51 +02004606 _Py_IDENTIFIER(__eq__);
Guido van Rossum38938152006-08-21 23:36:26 +00004607
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004608 assert(dict != NULL);
Victor Stinner3c1e4812012-03-26 22:10:51 +02004609 if (_PyDict_GetItemId(dict, &PyId___eq__) != NULL)
4610 return 1;
4611 if (_PyDict_GetItemId(dict, &PyId___hash__) != NULL)
4612 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004613 return 0;
Guido van Rossum38938152006-08-21 23:36:26 +00004614}
4615
Guido van Rossum13d52f02001-08-10 21:24:08 +00004616static void
4617inherit_slots(PyTypeObject *type, PyTypeObject *base)
4618{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004619 PyTypeObject *basebase;
Guido van Rossum13d52f02001-08-10 21:24:08 +00004620
4621#undef SLOTDEFINED
Tim Peters6d6c1a32001-08-02 04:15:00 +00004622#undef COPYSLOT
4623#undef COPYNUM
4624#undef COPYSEQ
4625#undef COPYMAP
Guido van Rossum5af588b2001-10-12 14:13:21 +00004626#undef COPYBUF
Guido van Rossum13d52f02001-08-10 21:24:08 +00004627
4628#define SLOTDEFINED(SLOT) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004629 (base->SLOT != 0 && \
4630 (basebase == NULL || base->SLOT != basebase->SLOT))
Guido van Rossum13d52f02001-08-10 21:24:08 +00004631
Tim Peters6d6c1a32001-08-02 04:15:00 +00004632#define COPYSLOT(SLOT) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004633 if (!type->SLOT && SLOTDEFINED(SLOT)) type->SLOT = base->SLOT
Tim Peters6d6c1a32001-08-02 04:15:00 +00004634
Yury Selivanov75445082015-05-11 22:57:16 -04004635#define COPYASYNC(SLOT) COPYSLOT(tp_as_async->SLOT)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004636#define COPYNUM(SLOT) COPYSLOT(tp_as_number->SLOT)
4637#define COPYSEQ(SLOT) COPYSLOT(tp_as_sequence->SLOT)
4638#define COPYMAP(SLOT) COPYSLOT(tp_as_mapping->SLOT)
Tim Petersfc57ccb2001-10-12 02:38:24 +00004639#define COPYBUF(SLOT) COPYSLOT(tp_as_buffer->SLOT)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004640
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004641 /* This won't inherit indirect slots (from tp_as_number etc.)
4642 if type doesn't provide the space. */
Guido van Rossum13d52f02001-08-10 21:24:08 +00004643
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004644 if (type->tp_as_number != NULL && base->tp_as_number != NULL) {
4645 basebase = base->tp_base;
4646 if (basebase->tp_as_number == NULL)
4647 basebase = NULL;
4648 COPYNUM(nb_add);
4649 COPYNUM(nb_subtract);
4650 COPYNUM(nb_multiply);
4651 COPYNUM(nb_remainder);
4652 COPYNUM(nb_divmod);
4653 COPYNUM(nb_power);
4654 COPYNUM(nb_negative);
4655 COPYNUM(nb_positive);
4656 COPYNUM(nb_absolute);
4657 COPYNUM(nb_bool);
4658 COPYNUM(nb_invert);
4659 COPYNUM(nb_lshift);
4660 COPYNUM(nb_rshift);
4661 COPYNUM(nb_and);
4662 COPYNUM(nb_xor);
4663 COPYNUM(nb_or);
4664 COPYNUM(nb_int);
4665 COPYNUM(nb_float);
4666 COPYNUM(nb_inplace_add);
4667 COPYNUM(nb_inplace_subtract);
4668 COPYNUM(nb_inplace_multiply);
4669 COPYNUM(nb_inplace_remainder);
4670 COPYNUM(nb_inplace_power);
4671 COPYNUM(nb_inplace_lshift);
4672 COPYNUM(nb_inplace_rshift);
4673 COPYNUM(nb_inplace_and);
4674 COPYNUM(nb_inplace_xor);
4675 COPYNUM(nb_inplace_or);
4676 COPYNUM(nb_true_divide);
4677 COPYNUM(nb_floor_divide);
4678 COPYNUM(nb_inplace_true_divide);
4679 COPYNUM(nb_inplace_floor_divide);
4680 COPYNUM(nb_index);
Benjamin Petersond51374e2014-04-09 23:55:56 -04004681 COPYNUM(nb_matrix_multiply);
4682 COPYNUM(nb_inplace_matrix_multiply);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004683 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004684
Yury Selivanov75445082015-05-11 22:57:16 -04004685 if (type->tp_as_async != NULL && base->tp_as_async != NULL) {
4686 basebase = base->tp_base;
4687 if (basebase->tp_as_async == NULL)
4688 basebase = NULL;
4689 COPYASYNC(am_await);
4690 COPYASYNC(am_aiter);
4691 COPYASYNC(am_anext);
4692 }
4693
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004694 if (type->tp_as_sequence != NULL && base->tp_as_sequence != NULL) {
4695 basebase = base->tp_base;
4696 if (basebase->tp_as_sequence == NULL)
4697 basebase = NULL;
4698 COPYSEQ(sq_length);
4699 COPYSEQ(sq_concat);
4700 COPYSEQ(sq_repeat);
4701 COPYSEQ(sq_item);
4702 COPYSEQ(sq_ass_item);
4703 COPYSEQ(sq_contains);
4704 COPYSEQ(sq_inplace_concat);
4705 COPYSEQ(sq_inplace_repeat);
4706 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004707
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004708 if (type->tp_as_mapping != NULL && base->tp_as_mapping != NULL) {
4709 basebase = base->tp_base;
4710 if (basebase->tp_as_mapping == NULL)
4711 basebase = NULL;
4712 COPYMAP(mp_length);
4713 COPYMAP(mp_subscript);
4714 COPYMAP(mp_ass_subscript);
4715 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004716
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004717 if (type->tp_as_buffer != NULL && base->tp_as_buffer != NULL) {
4718 basebase = base->tp_base;
4719 if (basebase->tp_as_buffer == NULL)
4720 basebase = NULL;
4721 COPYBUF(bf_getbuffer);
4722 COPYBUF(bf_releasebuffer);
4723 }
Tim Petersfc57ccb2001-10-12 02:38:24 +00004724
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004725 basebase = base->tp_base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004726
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004727 COPYSLOT(tp_dealloc);
4728 if (type->tp_getattr == NULL && type->tp_getattro == NULL) {
4729 type->tp_getattr = base->tp_getattr;
4730 type->tp_getattro = base->tp_getattro;
4731 }
4732 if (type->tp_setattr == NULL && type->tp_setattro == NULL) {
4733 type->tp_setattr = base->tp_setattr;
4734 type->tp_setattro = base->tp_setattro;
4735 }
4736 /* tp_reserved is ignored */
4737 COPYSLOT(tp_repr);
4738 /* tp_hash see tp_richcompare */
4739 COPYSLOT(tp_call);
4740 COPYSLOT(tp_str);
4741 {
4742 /* Copy comparison-related slots only when
4743 not overriding them anywhere */
4744 if (type->tp_richcompare == NULL &&
4745 type->tp_hash == NULL &&
4746 !overrides_hash(type))
4747 {
4748 type->tp_richcompare = base->tp_richcompare;
4749 type->tp_hash = base->tp_hash;
4750 }
4751 }
4752 {
4753 COPYSLOT(tp_iter);
4754 COPYSLOT(tp_iternext);
4755 }
4756 {
4757 COPYSLOT(tp_descr_get);
4758 COPYSLOT(tp_descr_set);
4759 COPYSLOT(tp_dictoffset);
4760 COPYSLOT(tp_init);
4761 COPYSLOT(tp_alloc);
4762 COPYSLOT(tp_is_gc);
Antoine Pitrou796564c2013-07-30 19:59:21 +02004763 if ((type->tp_flags & Py_TPFLAGS_HAVE_FINALIZE) &&
4764 (base->tp_flags & Py_TPFLAGS_HAVE_FINALIZE)) {
4765 COPYSLOT(tp_finalize);
4766 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004767 if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) ==
4768 (base->tp_flags & Py_TPFLAGS_HAVE_GC)) {
4769 /* They agree about gc. */
4770 COPYSLOT(tp_free);
4771 }
4772 else if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
4773 type->tp_free == NULL &&
4774 base->tp_free == PyObject_Free) {
4775 /* A bit of magic to plug in the correct default
4776 * tp_free function when a derived class adds gc,
4777 * didn't define tp_free, and the base uses the
4778 * default non-gc tp_free.
4779 */
4780 type->tp_free = PyObject_GC_Del;
4781 }
4782 /* else they didn't agree about gc, and there isn't something
4783 * obvious to be done -- the type is on its own.
4784 */
4785 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004786}
4787
Jeremy Hylton938ace62002-07-17 16:30:39 +00004788static int add_operators(PyTypeObject *);
Guido van Rossum13d52f02001-08-10 21:24:08 +00004789
Tim Peters6d6c1a32001-08-02 04:15:00 +00004790int
Guido van Rossum528b7eb2001-08-07 17:24:28 +00004791PyType_Ready(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004792{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004793 PyObject *dict, *bases;
4794 PyTypeObject *base;
4795 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004796
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004797 if (type->tp_flags & Py_TPFLAGS_READY) {
4798 assert(type->tp_dict != NULL);
4799 return 0;
4800 }
4801 assert((type->tp_flags & Py_TPFLAGS_READYING) == 0);
Guido van Rossumd614f972001-08-10 17:39:49 +00004802
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004803 type->tp_flags |= Py_TPFLAGS_READYING;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004804
Tim Peters36eb4df2003-03-23 03:33:13 +00004805#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004806 /* PyType_Ready is the closest thing we have to a choke point
4807 * for type objects, so is the best place I can think of to try
4808 * to get type objects into the doubly-linked list of all objects.
4809 * Still, not all type objects go thru PyType_Ready.
4810 */
4811 _Py_AddToAllObjects((PyObject *)type, 0);
Tim Peters36eb4df2003-03-23 03:33:13 +00004812#endif
4813
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004814 /* Initialize tp_base (defaults to BaseObject unless that's us) */
4815 base = type->tp_base;
4816 if (base == NULL && type != &PyBaseObject_Type) {
4817 base = type->tp_base = &PyBaseObject_Type;
4818 Py_INCREF(base);
4819 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004820
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004821 /* Now the only way base can still be NULL is if type is
4822 * &PyBaseObject_Type.
4823 */
Guido van Rossum692cdbc2006-03-10 02:04:28 +00004824
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004825 /* Initialize the base class */
4826 if (base != NULL && base->tp_dict == NULL) {
4827 if (PyType_Ready(base) < 0)
4828 goto error;
4829 }
Guido van Rossum323a9cf2002-08-14 17:26:30 +00004830
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004831 /* Initialize ob_type if NULL. This means extensions that want to be
4832 compilable separately on Windows can call PyType_Ready() instead of
4833 initializing the ob_type field of their type objects. */
4834 /* The test for base != NULL is really unnecessary, since base is only
4835 NULL when type is &PyBaseObject_Type, and we know its ob_type is
4836 not NULL (it's initialized to &PyType_Type). But coverity doesn't
4837 know that. */
4838 if (Py_TYPE(type) == NULL && base != NULL)
4839 Py_TYPE(type) = Py_TYPE(base);
Guido van Rossum0986d822002-04-08 01:38:42 +00004840
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004841 /* Initialize tp_bases */
4842 bases = type->tp_bases;
4843 if (bases == NULL) {
4844 if (base == NULL)
4845 bases = PyTuple_New(0);
4846 else
4847 bases = PyTuple_Pack(1, base);
4848 if (bases == NULL)
4849 goto error;
4850 type->tp_bases = bases;
4851 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004852
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004853 /* Initialize tp_dict */
4854 dict = type->tp_dict;
4855 if (dict == NULL) {
4856 dict = PyDict_New();
4857 if (dict == NULL)
4858 goto error;
4859 type->tp_dict = dict;
4860 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004861
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004862 /* Add type-specific descriptors to tp_dict */
4863 if (add_operators(type) < 0)
4864 goto error;
4865 if (type->tp_methods != NULL) {
4866 if (add_methods(type, type->tp_methods) < 0)
4867 goto error;
4868 }
4869 if (type->tp_members != NULL) {
4870 if (add_members(type, type->tp_members) < 0)
4871 goto error;
4872 }
4873 if (type->tp_getset != NULL) {
4874 if (add_getset(type, type->tp_getset) < 0)
4875 goto error;
4876 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004877
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004878 /* Calculate method resolution order */
Benjamin Peterson104b9e02015-02-05 22:29:14 -05004879 if (mro_internal(type, NULL) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004880 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004881
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004882 /* Inherit special flags from dominant base */
4883 if (type->tp_base != NULL)
4884 inherit_special(type, type->tp_base);
Guido van Rossum13d52f02001-08-10 21:24:08 +00004885
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004886 /* Initialize tp_dict properly */
4887 bases = type->tp_mro;
4888 assert(bases != NULL);
4889 assert(PyTuple_Check(bases));
4890 n = PyTuple_GET_SIZE(bases);
4891 for (i = 1; i < n; i++) {
4892 PyObject *b = PyTuple_GET_ITEM(bases, i);
4893 if (PyType_Check(b))
4894 inherit_slots(type, (PyTypeObject *)b);
4895 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004896
Serhiy Storchakae09bcc82015-01-28 11:03:33 +02004897 /* All bases of statically allocated type should be statically allocated */
4898 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE))
4899 for (i = 0; i < n; i++) {
4900 PyObject *b = PyTuple_GET_ITEM(bases, i);
4901 if (PyType_Check(b) &&
4902 (((PyTypeObject *)b)->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
4903 PyErr_Format(PyExc_TypeError,
4904 "type '%.100s' is not dynamically allocated but "
4905 "its base type '%.100s' is dynamically allocated",
4906 type->tp_name, ((PyTypeObject *)b)->tp_name);
4907 goto error;
4908 }
4909 }
4910
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004911 /* Sanity check for tp_free. */
4912 if (PyType_IS_GC(type) && (type->tp_flags & Py_TPFLAGS_BASETYPE) &&
4913 (type->tp_free == NULL || type->tp_free == PyObject_Del)) {
4914 /* This base class needs to call tp_free, but doesn't have
4915 * one, or its tp_free is for non-gc'ed objects.
4916 */
4917 PyErr_Format(PyExc_TypeError, "type '%.100s' participates in "
4918 "gc and is a base type but has inappropriate "
4919 "tp_free slot",
4920 type->tp_name);
4921 goto error;
4922 }
Tim Peters3cfe7542003-05-21 21:29:48 +00004923
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004924 /* if the type dictionary doesn't contain a __doc__, set it from
4925 the tp_doc slot.
4926 */
Victor Stinner3c1e4812012-03-26 22:10:51 +02004927 if (_PyDict_GetItemId(type->tp_dict, &PyId___doc__) == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004928 if (type->tp_doc != NULL) {
Larry Hastings2623c8c2014-02-08 22:15:29 -08004929 const char *old_doc = _PyType_DocWithoutSignature(type->tp_name,
4930 type->tp_doc);
Larry Hastings5c661892014-01-24 06:17:25 -08004931 PyObject *doc = PyUnicode_FromString(old_doc);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004932 if (doc == NULL)
4933 goto error;
Victor Stinner5967bf42013-07-17 22:01:37 +02004934 if (_PyDict_SetItemId(type->tp_dict, &PyId___doc__, doc) < 0) {
4935 Py_DECREF(doc);
4936 goto error;
4937 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004938 Py_DECREF(doc);
4939 } else {
Victor Stinner5967bf42013-07-17 22:01:37 +02004940 if (_PyDict_SetItemId(type->tp_dict,
4941 &PyId___doc__, Py_None) < 0)
4942 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004943 }
4944 }
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00004945
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004946 /* Hack for tp_hash and __hash__.
4947 If after all that, tp_hash is still NULL, and __hash__ is not in
4948 tp_dict, set tp_hash to PyObject_HashNotImplemented and
4949 tp_dict['__hash__'] equal to None.
4950 This signals that __hash__ is not inherited.
4951 */
4952 if (type->tp_hash == NULL) {
Victor Stinner3c1e4812012-03-26 22:10:51 +02004953 if (_PyDict_GetItemId(type->tp_dict, &PyId___hash__) == NULL) {
4954 if (_PyDict_SetItemId(type->tp_dict, &PyId___hash__, Py_None) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004955 goto error;
4956 type->tp_hash = PyObject_HashNotImplemented;
4957 }
4958 }
Guido van Rossum38938152006-08-21 23:36:26 +00004959
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004960 /* Some more special stuff */
4961 base = type->tp_base;
4962 if (base != NULL) {
Yury Selivanov75445082015-05-11 22:57:16 -04004963 if (type->tp_as_async == NULL)
4964 type->tp_as_async = base->tp_as_async;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004965 if (type->tp_as_number == NULL)
4966 type->tp_as_number = base->tp_as_number;
4967 if (type->tp_as_sequence == NULL)
4968 type->tp_as_sequence = base->tp_as_sequence;
4969 if (type->tp_as_mapping == NULL)
4970 type->tp_as_mapping = base->tp_as_mapping;
4971 if (type->tp_as_buffer == NULL)
4972 type->tp_as_buffer = base->tp_as_buffer;
4973 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004974
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004975 /* Link into each base class's list of subclasses */
4976 bases = type->tp_bases;
4977 n = PyTuple_GET_SIZE(bases);
4978 for (i = 0; i < n; i++) {
4979 PyObject *b = PyTuple_GET_ITEM(bases, i);
4980 if (PyType_Check(b) &&
4981 add_subclass((PyTypeObject *)b, type) < 0)
4982 goto error;
4983 }
Guido van Rossum1c450732001-10-08 15:18:27 +00004984
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004985 /* All done -- set the ready flag */
4986 assert(type->tp_dict != NULL);
4987 type->tp_flags =
4988 (type->tp_flags & ~Py_TPFLAGS_READYING) | Py_TPFLAGS_READY;
4989 return 0;
Guido van Rossumd614f972001-08-10 17:39:49 +00004990
4991 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004992 type->tp_flags &= ~Py_TPFLAGS_READYING;
4993 return -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004994}
4995
Guido van Rossum1c450732001-10-08 15:18:27 +00004996static int
4997add_subclass(PyTypeObject *base, PyTypeObject *type)
4998{
Antoine Pitrou84745ab2013-10-29 21:31:25 +01004999 int result = -1;
5000 PyObject *dict, *key, *newobj;
Guido van Rossum1c450732001-10-08 15:18:27 +00005001
Antoine Pitrou84745ab2013-10-29 21:31:25 +01005002 dict = base->tp_subclasses;
5003 if (dict == NULL) {
5004 base->tp_subclasses = dict = PyDict_New();
5005 if (dict == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005006 return -1;
5007 }
Antoine Pitrou84745ab2013-10-29 21:31:25 +01005008 assert(PyDict_CheckExact(dict));
5009 key = PyLong_FromVoidPtr((void *) type);
5010 if (key == NULL)
Victor Stinner9812af82013-07-08 22:25:48 +02005011 return -1;
Antoine Pitrou84745ab2013-10-29 21:31:25 +01005012 newobj = PyWeakref_NewRef((PyObject *)type, NULL);
5013 if (newobj != NULL) {
5014 result = PyDict_SetItem(dict, key, newobj);
5015 Py_DECREF(newobj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005016 }
Antoine Pitrou84745ab2013-10-29 21:31:25 +01005017 Py_DECREF(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005018 return result;
Guido van Rossum1c450732001-10-08 15:18:27 +00005019}
5020
Benjamin Peterson104b9e02015-02-05 22:29:14 -05005021static int
5022add_all_subclasses(PyTypeObject *type, PyObject *bases)
5023{
5024 int res = 0;
5025
5026 if (bases) {
5027 Py_ssize_t i;
5028 for (i = 0; i < PyTuple_GET_SIZE(bases); i++) {
5029 PyObject *base = PyTuple_GET_ITEM(bases, i);
5030 if (PyType_Check(base) &&
5031 add_subclass((PyTypeObject*)base, type) < 0)
5032 res = -1;
5033 }
5034 }
5035
5036 return res;
5037}
5038
Michael W. Hudson98bbc492002-11-26 14:47:27 +00005039static void
5040remove_subclass(PyTypeObject *base, PyTypeObject *type)
5041{
Antoine Pitrou84745ab2013-10-29 21:31:25 +01005042 PyObject *dict, *key;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00005043
Antoine Pitrou84745ab2013-10-29 21:31:25 +01005044 dict = base->tp_subclasses;
5045 if (dict == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005046 return;
5047 }
Antoine Pitrou84745ab2013-10-29 21:31:25 +01005048 assert(PyDict_CheckExact(dict));
5049 key = PyLong_FromVoidPtr((void *) type);
5050 if (key == NULL || PyDict_DelItem(dict, key)) {
5051 /* This can happen if the type initialization errored out before
5052 the base subclasses were updated (e.g. a non-str __qualname__
5053 was passed in the type dict). */
5054 PyErr_Clear();
5055 }
5056 Py_XDECREF(key);
5057}
5058
5059static void
5060remove_all_subclasses(PyTypeObject *type, PyObject *bases)
5061{
5062 if (bases) {
5063 Py_ssize_t i;
5064 for (i = 0; i < PyTuple_GET_SIZE(bases); i++) {
5065 PyObject *base = PyTuple_GET_ITEM(bases, i);
5066 if (PyType_Check(base))
5067 remove_subclass((PyTypeObject*) base, type);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005068 }
5069 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +00005070}
Tim Peters6d6c1a32001-08-02 04:15:00 +00005071
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00005072static int
5073check_num_args(PyObject *ob, int n)
5074{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005075 if (!PyTuple_CheckExact(ob)) {
5076 PyErr_SetString(PyExc_SystemError,
5077 "PyArg_UnpackTuple() argument list is not a tuple");
5078 return 0;
5079 }
5080 if (n == PyTuple_GET_SIZE(ob))
5081 return 1;
5082 PyErr_Format(
5083 PyExc_TypeError,
5084 "expected %d arguments, got %zd", n, PyTuple_GET_SIZE(ob));
5085 return 0;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00005086}
5087
Tim Peters6d6c1a32001-08-02 04:15:00 +00005088/* Generic wrappers for overloadable 'operators' such as __getitem__ */
5089
5090/* There's a wrapper *function* for each distinct function typedef used
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005091 for type object slots (e.g. binaryfunc, ternaryfunc, etc.). There's a
Tim Peters6d6c1a32001-08-02 04:15:00 +00005092 wrapper *table* for each distinct operation (e.g. __len__, __add__).
5093 Most tables have only one entry; the tables for binary operators have two
5094 entries, one regular and one with reversed arguments. */
5095
5096static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00005097wrap_lenfunc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005098{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005099 lenfunc func = (lenfunc)wrapped;
5100 Py_ssize_t res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005101
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005102 if (!check_num_args(args, 0))
5103 return NULL;
5104 res = (*func)(self);
5105 if (res == -1 && PyErr_Occurred())
5106 return NULL;
5107 return PyLong_FromLong((long)res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005108}
5109
Tim Peters6d6c1a32001-08-02 04:15:00 +00005110static PyObject *
Raymond Hettingerf34f2642003-10-11 17:29:04 +00005111wrap_inquirypred(PyObject *self, PyObject *args, void *wrapped)
5112{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005113 inquiry func = (inquiry)wrapped;
5114 int res;
Raymond Hettingerf34f2642003-10-11 17:29:04 +00005115
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005116 if (!check_num_args(args, 0))
5117 return NULL;
5118 res = (*func)(self);
5119 if (res == -1 && PyErr_Occurred())
5120 return NULL;
5121 return PyBool_FromLong((long)res);
Raymond Hettingerf34f2642003-10-11 17:29:04 +00005122}
5123
5124static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00005125wrap_binaryfunc(PyObject *self, PyObject *args, void *wrapped)
5126{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005127 binaryfunc func = (binaryfunc)wrapped;
5128 PyObject *other;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005129
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005130 if (!check_num_args(args, 1))
5131 return NULL;
5132 other = PyTuple_GET_ITEM(args, 0);
5133 return (*func)(self, other);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005134}
5135
5136static PyObject *
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00005137wrap_binaryfunc_l(PyObject *self, PyObject *args, void *wrapped)
5138{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005139 binaryfunc func = (binaryfunc)wrapped;
5140 PyObject *other;
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00005141
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005142 if (!check_num_args(args, 1))
5143 return NULL;
5144 other = PyTuple_GET_ITEM(args, 0);
5145 return (*func)(self, other);
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00005146}
5147
5148static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00005149wrap_binaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
5150{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005151 binaryfunc func = (binaryfunc)wrapped;
5152 PyObject *other;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005153
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005154 if (!check_num_args(args, 1))
5155 return NULL;
5156 other = PyTuple_GET_ITEM(args, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005157 return (*func)(other, self);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005158}
5159
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00005160static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00005161wrap_ternaryfunc(PyObject *self, PyObject *args, void *wrapped)
5162{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005163 ternaryfunc func = (ternaryfunc)wrapped;
5164 PyObject *other;
5165 PyObject *third = Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005166
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005167 /* Note: This wrapper only works for __pow__() */
Tim Peters6d6c1a32001-08-02 04:15:00 +00005168
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005169 if (!PyArg_UnpackTuple(args, "", 1, 2, &other, &third))
5170 return NULL;
5171 return (*func)(self, other, third);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005172}
5173
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00005174static PyObject *
5175wrap_ternaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
5176{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005177 ternaryfunc func = (ternaryfunc)wrapped;
5178 PyObject *other;
5179 PyObject *third = Py_None;
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00005180
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005181 /* Note: This wrapper only works for __pow__() */
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00005182
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005183 if (!PyArg_UnpackTuple(args, "", 1, 2, &other, &third))
5184 return NULL;
5185 return (*func)(other, self, third);
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00005186}
5187
Tim Peters6d6c1a32001-08-02 04:15:00 +00005188static PyObject *
5189wrap_unaryfunc(PyObject *self, PyObject *args, void *wrapped)
5190{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005191 unaryfunc func = (unaryfunc)wrapped;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005192
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005193 if (!check_num_args(args, 0))
5194 return NULL;
5195 return (*func)(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005196}
5197
Tim Peters6d6c1a32001-08-02 04:15:00 +00005198static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00005199wrap_indexargfunc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005200{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005201 ssizeargfunc func = (ssizeargfunc)wrapped;
5202 PyObject* o;
5203 Py_ssize_t i;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005204
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005205 if (!PyArg_UnpackTuple(args, "", 1, 1, &o))
5206 return NULL;
5207 i = PyNumber_AsSsize_t(o, PyExc_OverflowError);
5208 if (i == -1 && PyErr_Occurred())
5209 return NULL;
5210 return (*func)(self, i);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005211}
5212
Martin v. Löwis18e16552006-02-15 17:27:45 +00005213static Py_ssize_t
Guido van Rossum5d815f32001-08-17 21:57:47 +00005214getindex(PyObject *self, PyObject *arg)
5215{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005216 Py_ssize_t i;
Guido van Rossum5d815f32001-08-17 21:57:47 +00005217
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005218 i = PyNumber_AsSsize_t(arg, PyExc_OverflowError);
5219 if (i == -1 && PyErr_Occurred())
5220 return -1;
5221 if (i < 0) {
5222 PySequenceMethods *sq = Py_TYPE(self)->tp_as_sequence;
5223 if (sq && sq->sq_length) {
5224 Py_ssize_t n = (*sq->sq_length)(self);
5225 if (n < 0)
5226 return -1;
5227 i += n;
5228 }
5229 }
5230 return i;
Guido van Rossum5d815f32001-08-17 21:57:47 +00005231}
5232
5233static PyObject *
5234wrap_sq_item(PyObject *self, PyObject *args, void *wrapped)
5235{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005236 ssizeargfunc func = (ssizeargfunc)wrapped;
5237 PyObject *arg;
5238 Py_ssize_t i;
Guido van Rossum5d815f32001-08-17 21:57:47 +00005239
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005240 if (PyTuple_GET_SIZE(args) == 1) {
5241 arg = PyTuple_GET_ITEM(args, 0);
5242 i = getindex(self, arg);
5243 if (i == -1 && PyErr_Occurred())
5244 return NULL;
5245 return (*func)(self, i);
5246 }
5247 check_num_args(args, 1);
5248 assert(PyErr_Occurred());
5249 return NULL;
Guido van Rossum5d815f32001-08-17 21:57:47 +00005250}
5251
Tim Peters6d6c1a32001-08-02 04:15:00 +00005252static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00005253wrap_sq_setitem(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005254{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005255 ssizeobjargproc func = (ssizeobjargproc)wrapped;
5256 Py_ssize_t i;
5257 int res;
5258 PyObject *arg, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005259
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005260 if (!PyArg_UnpackTuple(args, "", 2, 2, &arg, &value))
5261 return NULL;
5262 i = getindex(self, arg);
5263 if (i == -1 && PyErr_Occurred())
5264 return NULL;
5265 res = (*func)(self, i, value);
5266 if (res == -1 && PyErr_Occurred())
5267 return NULL;
5268 Py_INCREF(Py_None);
5269 return Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005270}
5271
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00005272static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00005273wrap_sq_delitem(PyObject *self, PyObject *args, void *wrapped)
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00005274{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005275 ssizeobjargproc func = (ssizeobjargproc)wrapped;
5276 Py_ssize_t i;
5277 int res;
5278 PyObject *arg;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00005279
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005280 if (!check_num_args(args, 1))
5281 return NULL;
5282 arg = PyTuple_GET_ITEM(args, 0);
5283 i = getindex(self, arg);
5284 if (i == -1 && PyErr_Occurred())
5285 return NULL;
5286 res = (*func)(self, i, NULL);
5287 if (res == -1 && PyErr_Occurred())
5288 return NULL;
5289 Py_INCREF(Py_None);
5290 return Py_None;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00005291}
5292
Tim Peters6d6c1a32001-08-02 04:15:00 +00005293/* XXX objobjproc is a misnomer; should be objargpred */
5294static PyObject *
5295wrap_objobjproc(PyObject *self, PyObject *args, void *wrapped)
5296{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005297 objobjproc func = (objobjproc)wrapped;
5298 int res;
5299 PyObject *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005300
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005301 if (!check_num_args(args, 1))
5302 return NULL;
5303 value = PyTuple_GET_ITEM(args, 0);
5304 res = (*func)(self, value);
5305 if (res == -1 && PyErr_Occurred())
5306 return NULL;
5307 else
5308 return PyBool_FromLong(res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005309}
5310
Tim Peters6d6c1a32001-08-02 04:15:00 +00005311static PyObject *
5312wrap_objobjargproc(PyObject *self, PyObject *args, void *wrapped)
5313{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005314 objobjargproc func = (objobjargproc)wrapped;
5315 int res;
5316 PyObject *key, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005317
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005318 if (!PyArg_UnpackTuple(args, "", 2, 2, &key, &value))
5319 return NULL;
5320 res = (*func)(self, key, value);
5321 if (res == -1 && PyErr_Occurred())
5322 return NULL;
5323 Py_INCREF(Py_None);
5324 return Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005325}
5326
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00005327static PyObject *
5328wrap_delitem(PyObject *self, PyObject *args, void *wrapped)
5329{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005330 objobjargproc func = (objobjargproc)wrapped;
5331 int res;
5332 PyObject *key;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00005333
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005334 if (!check_num_args(args, 1))
5335 return NULL;
5336 key = PyTuple_GET_ITEM(args, 0);
5337 res = (*func)(self, key, NULL);
5338 if (res == -1 && PyErr_Occurred())
5339 return NULL;
5340 Py_INCREF(Py_None);
5341 return Py_None;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00005342}
5343
Guido van Rossum4dcdb782003-04-14 21:46:03 +00005344/* Helper to check for object.__setattr__ or __delattr__ applied to a type.
Guido van Rossum52b27052003-04-15 20:05:10 +00005345 This is called the Carlo Verre hack after its discoverer. */
Guido van Rossum4dcdb782003-04-14 21:46:03 +00005346static int
5347hackcheck(PyObject *self, setattrofunc func, char *what)
5348{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005349 PyTypeObject *type = Py_TYPE(self);
5350 while (type && type->tp_flags & Py_TPFLAGS_HEAPTYPE)
5351 type = type->tp_base;
5352 /* If type is NULL now, this is a really weird type.
5353 In the spirit of backwards compatibility (?), just shut up. */
5354 if (type && type->tp_setattro != func) {
5355 PyErr_Format(PyExc_TypeError,
5356 "can't apply this %s to %s object",
5357 what,
5358 type->tp_name);
5359 return 0;
5360 }
5361 return 1;
Guido van Rossum4dcdb782003-04-14 21:46:03 +00005362}
5363
Tim Peters6d6c1a32001-08-02 04:15:00 +00005364static PyObject *
5365wrap_setattr(PyObject *self, PyObject *args, void *wrapped)
5366{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005367 setattrofunc func = (setattrofunc)wrapped;
5368 int res;
5369 PyObject *name, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005370
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005371 if (!PyArg_UnpackTuple(args, "", 2, 2, &name, &value))
5372 return NULL;
5373 if (!hackcheck(self, func, "__setattr__"))
5374 return NULL;
5375 res = (*func)(self, name, value);
5376 if (res < 0)
5377 return NULL;
5378 Py_INCREF(Py_None);
5379 return Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005380}
5381
5382static PyObject *
5383wrap_delattr(PyObject *self, PyObject *args, void *wrapped)
5384{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005385 setattrofunc func = (setattrofunc)wrapped;
5386 int res;
5387 PyObject *name;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005388
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005389 if (!check_num_args(args, 1))
5390 return NULL;
5391 name = PyTuple_GET_ITEM(args, 0);
5392 if (!hackcheck(self, func, "__delattr__"))
5393 return NULL;
5394 res = (*func)(self, name, NULL);
5395 if (res < 0)
5396 return NULL;
5397 Py_INCREF(Py_None);
5398 return Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005399}
5400
Tim Peters6d6c1a32001-08-02 04:15:00 +00005401static PyObject *
5402wrap_hashfunc(PyObject *self, PyObject *args, void *wrapped)
5403{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005404 hashfunc func = (hashfunc)wrapped;
Benjamin Peterson8035bc52010-10-23 16:20:50 +00005405 Py_hash_t res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005406
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005407 if (!check_num_args(args, 0))
5408 return NULL;
5409 res = (*func)(self);
5410 if (res == -1 && PyErr_Occurred())
5411 return NULL;
Benjamin Peterson8035bc52010-10-23 16:20:50 +00005412 return PyLong_FromSsize_t(res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005413}
5414
Tim Peters6d6c1a32001-08-02 04:15:00 +00005415static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00005416wrap_call(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005417{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005418 ternaryfunc func = (ternaryfunc)wrapped;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005419
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005420 return (*func)(self, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005421}
5422
Tim Peters6d6c1a32001-08-02 04:15:00 +00005423static PyObject *
Antoine Pitrou796564c2013-07-30 19:59:21 +02005424wrap_del(PyObject *self, PyObject *args, void *wrapped)
5425{
5426 destructor func = (destructor)wrapped;
5427
5428 if (!check_num_args(args, 0))
5429 return NULL;
5430
5431 (*func)(self);
5432 Py_RETURN_NONE;
5433}
5434
5435static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00005436wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op)
5437{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005438 richcmpfunc func = (richcmpfunc)wrapped;
5439 PyObject *other;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005440
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005441 if (!check_num_args(args, 1))
5442 return NULL;
5443 other = PyTuple_GET_ITEM(args, 0);
5444 return (*func)(self, other, op);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005445}
5446
5447#undef RICHCMP_WRAPPER
5448#define RICHCMP_WRAPPER(NAME, OP) \
5449static PyObject * \
5450richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \
5451{ \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005452 return wrap_richcmpfunc(self, args, wrapped, OP); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00005453}
5454
Jack Jansen8e938b42001-08-08 15:29:49 +00005455RICHCMP_WRAPPER(lt, Py_LT)
5456RICHCMP_WRAPPER(le, Py_LE)
5457RICHCMP_WRAPPER(eq, Py_EQ)
5458RICHCMP_WRAPPER(ne, Py_NE)
5459RICHCMP_WRAPPER(gt, Py_GT)
5460RICHCMP_WRAPPER(ge, Py_GE)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005461
Tim Peters6d6c1a32001-08-02 04:15:00 +00005462static PyObject *
5463wrap_next(PyObject *self, PyObject *args, void *wrapped)
5464{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005465 unaryfunc func = (unaryfunc)wrapped;
5466 PyObject *res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005467
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005468 if (!check_num_args(args, 0))
5469 return NULL;
5470 res = (*func)(self);
5471 if (res == NULL && !PyErr_Occurred())
5472 PyErr_SetNone(PyExc_StopIteration);
5473 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005474}
5475
Tim Peters6d6c1a32001-08-02 04:15:00 +00005476static PyObject *
5477wrap_descr_get(PyObject *self, PyObject *args, void *wrapped)
5478{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005479 descrgetfunc func = (descrgetfunc)wrapped;
5480 PyObject *obj;
5481 PyObject *type = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005482
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005483 if (!PyArg_UnpackTuple(args, "", 1, 2, &obj, &type))
5484 return NULL;
5485 if (obj == Py_None)
5486 obj = NULL;
5487 if (type == Py_None)
5488 type = NULL;
5489 if (type == NULL &&obj == NULL) {
5490 PyErr_SetString(PyExc_TypeError,
5491 "__get__(None, None) is invalid");
5492 return NULL;
5493 }
5494 return (*func)(self, obj, type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005495}
5496
Tim Peters6d6c1a32001-08-02 04:15:00 +00005497static PyObject *
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005498wrap_descr_set(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005499{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005500 descrsetfunc func = (descrsetfunc)wrapped;
5501 PyObject *obj, *value;
5502 int ret;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005503
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005504 if (!PyArg_UnpackTuple(args, "", 2, 2, &obj, &value))
5505 return NULL;
5506 ret = (*func)(self, obj, value);
5507 if (ret < 0)
5508 return NULL;
5509 Py_INCREF(Py_None);
5510 return Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005511}
Guido van Rossum22b13872002-08-06 21:41:44 +00005512
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00005513static PyObject *
5514wrap_descr_delete(PyObject *self, PyObject *args, void *wrapped)
5515{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005516 descrsetfunc func = (descrsetfunc)wrapped;
5517 PyObject *obj;
5518 int ret;
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00005519
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005520 if (!check_num_args(args, 1))
5521 return NULL;
5522 obj = PyTuple_GET_ITEM(args, 0);
5523 ret = (*func)(self, obj, NULL);
5524 if (ret < 0)
5525 return NULL;
5526 Py_INCREF(Py_None);
5527 return Py_None;
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00005528}
Tim Peters6d6c1a32001-08-02 04:15:00 +00005529
Tim Peters6d6c1a32001-08-02 04:15:00 +00005530static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00005531wrap_init(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005532{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005533 initproc func = (initproc)wrapped;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005534
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005535 if (func(self, args, kwds) < 0)
5536 return NULL;
5537 Py_INCREF(Py_None);
5538 return Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005539}
5540
Tim Peters6d6c1a32001-08-02 04:15:00 +00005541static PyObject *
Guido van Rossum0d231ed2001-08-06 16:50:37 +00005542tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005543{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005544 PyTypeObject *type, *subtype, *staticbase;
5545 PyObject *arg0, *res;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00005546
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005547 if (self == NULL || !PyType_Check(self))
5548 Py_FatalError("__new__() called with non-type 'self'");
5549 type = (PyTypeObject *)self;
5550 if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) {
5551 PyErr_Format(PyExc_TypeError,
5552 "%s.__new__(): not enough arguments",
5553 type->tp_name);
5554 return NULL;
5555 }
5556 arg0 = PyTuple_GET_ITEM(args, 0);
5557 if (!PyType_Check(arg0)) {
5558 PyErr_Format(PyExc_TypeError,
5559 "%s.__new__(X): X is not a type object (%s)",
5560 type->tp_name,
5561 Py_TYPE(arg0)->tp_name);
5562 return NULL;
5563 }
5564 subtype = (PyTypeObject *)arg0;
5565 if (!PyType_IsSubtype(subtype, type)) {
5566 PyErr_Format(PyExc_TypeError,
5567 "%s.__new__(%s): %s is not a subtype of %s",
5568 type->tp_name,
5569 subtype->tp_name,
5570 subtype->tp_name,
5571 type->tp_name);
5572 return NULL;
5573 }
Barry Warsaw60f01882001-08-22 19:24:42 +00005574
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005575 /* Check that the use doesn't do something silly and unsafe like
5576 object.__new__(dict). To do this, we check that the
5577 most derived base that's not a heap type is this type. */
5578 staticbase = subtype;
Martin v. Löwis9c564092012-06-23 23:20:45 +02005579 while (staticbase && (staticbase->tp_new == slot_tp_new))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005580 staticbase = staticbase->tp_base;
5581 /* If staticbase is NULL now, it is a really weird type.
5582 In the spirit of backwards compatibility (?), just shut up. */
5583 if (staticbase && staticbase->tp_new != type->tp_new) {
5584 PyErr_Format(PyExc_TypeError,
5585 "%s.__new__(%s) is not safe, use %s.__new__()",
5586 type->tp_name,
5587 subtype->tp_name,
Benjamin Petersone8239332014-11-26 23:03:11 -06005588 staticbase->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005589 return NULL;
5590 }
Barry Warsaw60f01882001-08-22 19:24:42 +00005591
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005592 args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
5593 if (args == NULL)
5594 return NULL;
5595 res = type->tp_new(subtype, args, kwds);
5596 Py_DECREF(args);
5597 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005598}
5599
Guido van Rossum0d231ed2001-08-06 16:50:37 +00005600static struct PyMethodDef tp_new_methoddef[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005601 {"__new__", (PyCFunction)tp_new_wrapper, METH_VARARGS|METH_KEYWORDS,
Larry Hastings2623c8c2014-02-08 22:15:29 -08005602 PyDoc_STR("__new__($type, *args, **kwargs)\n--\n\n"
Larry Hastings581ee362014-01-28 05:00:08 -08005603 "Create and return a new object. "
5604 "See help(type) for accurate signature.")},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005605 {0}
Tim Peters6d6c1a32001-08-02 04:15:00 +00005606};
5607
5608static int
Guido van Rossum0d231ed2001-08-06 16:50:37 +00005609add_tp_new_wrapper(PyTypeObject *type)
5610{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005611 PyObject *func;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00005612
Victor Stinner3c1e4812012-03-26 22:10:51 +02005613 if (_PyDict_GetItemId(type->tp_dict, &PyId___new__) != NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005614 return 0;
Andrew Svetlov3ba3a3e2012-12-25 13:32:35 +02005615 func = PyCFunction_NewEx(tp_new_methoddef, (PyObject *)type, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005616 if (func == NULL)
5617 return -1;
Victor Stinner3c1e4812012-03-26 22:10:51 +02005618 if (_PyDict_SetItemId(type->tp_dict, &PyId___new__, func)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005619 Py_DECREF(func);
5620 return -1;
5621 }
5622 Py_DECREF(func);
5623 return 0;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00005624}
5625
Guido van Rossumf040ede2001-08-07 16:40:56 +00005626/* Slot wrappers that call the corresponding __foo__ slot. See comments
5627 below at override_slots() for more explanation. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00005628
Guido van Rossumdc91b992001-08-08 22:26:22 +00005629#define SLOT0(FUNCNAME, OPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00005630static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00005631FUNCNAME(PyObject *self) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00005632{ \
Benjamin Petersonce798522012-01-22 11:24:29 -05005633 _Py_static_string(id, OPSTR); \
5634 return call_method(self, &id, "()"); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00005635}
5636
Guido van Rossumdc91b992001-08-08 22:26:22 +00005637#define SLOT1(FUNCNAME, OPSTR, ARG1TYPE, ARGCODES) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00005638static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00005639FUNCNAME(PyObject *self, ARG1TYPE arg1) \
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, "(" ARGCODES ")", arg1); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00005643}
5644
Guido van Rossumcd118802003-01-06 22:57:47 +00005645/* Boolean helper for SLOT1BINFULL().
5646 right.__class__ is a nontrivial subclass of left.__class__. */
5647static int
Victor Stinner3c1e4812012-03-26 22:10:51 +02005648method_is_overloaded(PyObject *left, PyObject *right, struct _Py_Identifier *name)
Guido van Rossumcd118802003-01-06 22:57:47 +00005649{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005650 PyObject *a, *b;
5651 int ok;
Guido van Rossumcd118802003-01-06 22:57:47 +00005652
Victor Stinner3c1e4812012-03-26 22:10:51 +02005653 b = _PyObject_GetAttrId((PyObject *)(Py_TYPE(right)), name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005654 if (b == NULL) {
5655 PyErr_Clear();
5656 /* If right doesn't have it, it's not overloaded */
5657 return 0;
5658 }
Guido van Rossumcd118802003-01-06 22:57:47 +00005659
Victor Stinner3c1e4812012-03-26 22:10:51 +02005660 a = _PyObject_GetAttrId((PyObject *)(Py_TYPE(left)), name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005661 if (a == NULL) {
5662 PyErr_Clear();
5663 Py_DECREF(b);
5664 /* If right has it but left doesn't, it's overloaded */
5665 return 1;
5666 }
Guido van Rossumcd118802003-01-06 22:57:47 +00005667
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005668 ok = PyObject_RichCompareBool(a, b, Py_NE);
5669 Py_DECREF(a);
5670 Py_DECREF(b);
5671 if (ok < 0) {
5672 PyErr_Clear();
5673 return 0;
5674 }
Guido van Rossumcd118802003-01-06 22:57:47 +00005675
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005676 return ok;
Guido van Rossumcd118802003-01-06 22:57:47 +00005677}
5678
Guido van Rossumdc91b992001-08-08 22:26:22 +00005679
5680#define SLOT1BINFULL(FUNCNAME, TESTFUNC, SLOTNAME, OPSTR, ROPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00005681static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00005682FUNCNAME(PyObject *self, PyObject *other) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00005683{ \
Benjamin Petersonce798522012-01-22 11:24:29 -05005684 _Py_static_string(op_id, OPSTR); \
5685 _Py_static_string(rop_id, ROPSTR); \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005686 int do_other = Py_TYPE(self) != Py_TYPE(other) && \
5687 Py_TYPE(other)->tp_as_number != NULL && \
5688 Py_TYPE(other)->tp_as_number->SLOTNAME == TESTFUNC; \
5689 if (Py_TYPE(self)->tp_as_number != NULL && \
5690 Py_TYPE(self)->tp_as_number->SLOTNAME == TESTFUNC) { \
5691 PyObject *r; \
5692 if (do_other && \
5693 PyType_IsSubtype(Py_TYPE(other), Py_TYPE(self)) && \
Victor Stinner3c1e4812012-03-26 22:10:51 +02005694 method_is_overloaded(self, other, &rop_id)) { \
Benjamin Petersonce798522012-01-22 11:24:29 -05005695 r = call_maybe(other, &rop_id, "(O)", self); \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005696 if (r != Py_NotImplemented) \
5697 return r; \
5698 Py_DECREF(r); \
5699 do_other = 0; \
5700 } \
Benjamin Petersonce798522012-01-22 11:24:29 -05005701 r = call_maybe(self, &op_id, "(O)", other); \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005702 if (r != Py_NotImplemented || \
5703 Py_TYPE(other) == Py_TYPE(self)) \
5704 return r; \
5705 Py_DECREF(r); \
5706 } \
5707 if (do_other) { \
Benjamin Petersonce798522012-01-22 11:24:29 -05005708 return call_maybe(other, &rop_id, "(O)", self); \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005709 } \
Brian Curtindfc80e32011-08-10 20:28:54 -05005710 Py_RETURN_NOTIMPLEMENTED; \
Guido van Rossumdc91b992001-08-08 22:26:22 +00005711}
5712
5713#define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005714 SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR)
Guido van Rossumdc91b992001-08-08 22:26:22 +00005715
5716#define SLOT2(FUNCNAME, OPSTR, ARG1TYPE, ARG2TYPE, ARGCODES) \
5717static PyObject * \
5718FUNCNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \
5719{ \
Benjamin Petersonce798522012-01-22 11:24:29 -05005720 _Py_static_string(id, #OPSTR); \
5721 return call_method(self, &id, "(" ARGCODES ")", arg1, arg2); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00005722}
5723
Martin v. Löwis18e16552006-02-15 17:27:45 +00005724static Py_ssize_t
Tim Peters6d6c1a32001-08-02 04:15:00 +00005725slot_sq_length(PyObject *self)
5726{
Benjamin Petersonce798522012-01-22 11:24:29 -05005727 PyObject *res = call_method(self, &PyId___len__, "()");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005728 Py_ssize_t len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005729
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005730 if (res == NULL)
5731 return -1;
5732 len = PyNumber_AsSsize_t(res, PyExc_OverflowError);
5733 Py_DECREF(res);
5734 if (len < 0) {
5735 if (!PyErr_Occurred())
5736 PyErr_SetString(PyExc_ValueError,
5737 "__len__() should return >= 0");
5738 return -1;
5739 }
5740 return len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005741}
5742
Guido van Rossumf4593e02001-10-03 12:09:30 +00005743/* Super-optimized version of slot_sq_item.
5744 Other slots could do the same... */
5745static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00005746slot_sq_item(PyObject *self, Py_ssize_t i)
Guido van Rossumf4593e02001-10-03 12:09:30 +00005747{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005748 PyObject *func, *args = NULL, *ival = NULL, *retval = NULL;
5749 descrgetfunc f;
Guido van Rossumf4593e02001-10-03 12:09:30 +00005750
Victor Stinner3c1e4812012-03-26 22:10:51 +02005751 func = _PyType_LookupId(Py_TYPE(self), &PyId___getitem__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005752 if (func != NULL) {
5753 if ((f = Py_TYPE(func)->tp_descr_get) == NULL)
5754 Py_INCREF(func);
5755 else {
5756 func = f(func, self, (PyObject *)(Py_TYPE(self)));
5757 if (func == NULL) {
5758 return NULL;
5759 }
5760 }
5761 ival = PyLong_FromSsize_t(i);
5762 if (ival != NULL) {
5763 args = PyTuple_New(1);
5764 if (args != NULL) {
5765 PyTuple_SET_ITEM(args, 0, ival);
5766 retval = PyObject_Call(func, args, NULL);
5767 Py_XDECREF(args);
5768 Py_XDECREF(func);
5769 return retval;
5770 }
5771 }
5772 }
5773 else {
Victor Stinner3c1e4812012-03-26 22:10:51 +02005774 PyObject *getitem_str = _PyUnicode_FromId(&PyId___getitem__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005775 PyErr_SetObject(PyExc_AttributeError, getitem_str);
5776 }
5777 Py_XDECREF(args);
5778 Py_XDECREF(ival);
5779 Py_XDECREF(func);
5780 return NULL;
Guido van Rossumf4593e02001-10-03 12:09:30 +00005781}
5782
Tim Peters6d6c1a32001-08-02 04:15:00 +00005783static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00005784slot_sq_ass_item(PyObject *self, Py_ssize_t index, PyObject *value)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005785{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005786 PyObject *res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005787
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005788 if (value == NULL)
Benjamin Petersonce798522012-01-22 11:24:29 -05005789 res = call_method(self, &PyId___delitem__, "(n)", index);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005790 else
Benjamin Petersonce798522012-01-22 11:24:29 -05005791 res = call_method(self, &PyId___setitem__, "(nO)", index, value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005792 if (res == NULL)
5793 return -1;
5794 Py_DECREF(res);
5795 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005796}
5797
5798static int
Tim Peters6d6c1a32001-08-02 04:15:00 +00005799slot_sq_contains(PyObject *self, PyObject *value)
5800{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005801 PyObject *func, *res, *args;
5802 int result = -1;
Benjamin Petersonce798522012-01-22 11:24:29 -05005803 _Py_IDENTIFIER(__contains__);
Tim Petersbf9b2442003-03-23 05:35:36 +00005804
Benjamin Petersonce798522012-01-22 11:24:29 -05005805 func = lookup_maybe(self, &PyId___contains__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005806 if (func != NULL) {
5807 args = PyTuple_Pack(1, value);
5808 if (args == NULL)
5809 res = NULL;
5810 else {
5811 res = PyObject_Call(func, args, NULL);
5812 Py_DECREF(args);
5813 }
5814 Py_DECREF(func);
5815 if (res != NULL) {
5816 result = PyObject_IsTrue(res);
5817 Py_DECREF(res);
5818 }
5819 }
5820 else if (! PyErr_Occurred()) {
5821 /* Possible results: -1 and 1 */
5822 result = (int)_PySequence_IterSearch(self, value,
5823 PY_ITERSEARCH_CONTAINS);
5824 }
5825 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005826}
5827
Tim Peters6d6c1a32001-08-02 04:15:00 +00005828#define slot_mp_length slot_sq_length
5829
Guido van Rossumdc91b992001-08-08 22:26:22 +00005830SLOT1(slot_mp_subscript, "__getitem__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00005831
5832static int
5833slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value)
5834{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005835 PyObject *res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005836
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005837 if (value == NULL)
Benjamin Petersonce798522012-01-22 11:24:29 -05005838 res = call_method(self, &PyId___delitem__, "(O)", key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005839 else
Benjamin Petersonce798522012-01-22 11:24:29 -05005840 res = call_method(self, &PyId___setitem__, "(OO)", key, value);
5841
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005842 if (res == NULL)
5843 return -1;
5844 Py_DECREF(res);
5845 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005846}
5847
Guido van Rossumdc91b992001-08-08 22:26:22 +00005848SLOT1BIN(slot_nb_add, nb_add, "__add__", "__radd__")
5849SLOT1BIN(slot_nb_subtract, nb_subtract, "__sub__", "__rsub__")
5850SLOT1BIN(slot_nb_multiply, nb_multiply, "__mul__", "__rmul__")
Benjamin Petersond51374e2014-04-09 23:55:56 -04005851SLOT1BIN(slot_nb_matrix_multiply, nb_matrix_multiply, "__matmul__", "__rmatmul__")
Guido van Rossumdc91b992001-08-08 22:26:22 +00005852SLOT1BIN(slot_nb_remainder, nb_remainder, "__mod__", "__rmod__")
5853SLOT1BIN(slot_nb_divmod, nb_divmod, "__divmod__", "__rdivmod__")
5854
Jeremy Hylton938ace62002-07-17 16:30:39 +00005855static PyObject *slot_nb_power(PyObject *, PyObject *, PyObject *);
Guido van Rossumdc91b992001-08-08 22:26:22 +00005856
5857SLOT1BINFULL(slot_nb_power_binary, slot_nb_power,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005858 nb_power, "__pow__", "__rpow__")
Guido van Rossumdc91b992001-08-08 22:26:22 +00005859
5860static PyObject *
5861slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus)
5862{
Benjamin Petersonce798522012-01-22 11:24:29 -05005863 _Py_IDENTIFIER(__pow__);
Guido van Rossum2730b132001-08-28 18:22:14 +00005864
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005865 if (modulus == Py_None)
5866 return slot_nb_power_binary(self, other);
5867 /* Three-arg power doesn't use __rpow__. But ternary_op
5868 can call this when the second argument's type uses
5869 slot_nb_power, so check before calling self.__pow__. */
5870 if (Py_TYPE(self)->tp_as_number != NULL &&
5871 Py_TYPE(self)->tp_as_number->nb_power == slot_nb_power) {
Benjamin Petersonce798522012-01-22 11:24:29 -05005872 return call_method(self, &PyId___pow__, "(OO)", other, modulus);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005873 }
Brian Curtindfc80e32011-08-10 20:28:54 -05005874 Py_RETURN_NOTIMPLEMENTED;
Guido van Rossumdc91b992001-08-08 22:26:22 +00005875}
5876
5877SLOT0(slot_nb_negative, "__neg__")
5878SLOT0(slot_nb_positive, "__pos__")
5879SLOT0(slot_nb_absolute, "__abs__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00005880
5881static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00005882slot_nb_bool(PyObject *self)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005883{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005884 PyObject *func, *args;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005885 int result = -1;
5886 int using_len = 0;
Benjamin Petersonce798522012-01-22 11:24:29 -05005887 _Py_IDENTIFIER(__bool__);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005888
Benjamin Petersonce798522012-01-22 11:24:29 -05005889 func = lookup_maybe(self, &PyId___bool__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005890 if (func == NULL) {
5891 if (PyErr_Occurred())
5892 return -1;
Benjamin Petersonce798522012-01-22 11:24:29 -05005893 func = lookup_maybe(self, &PyId___len__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005894 if (func == NULL)
5895 return PyErr_Occurred() ? -1 : 1;
5896 using_len = 1;
5897 }
5898 args = PyTuple_New(0);
5899 if (args != NULL) {
5900 PyObject *temp = PyObject_Call(func, args, NULL);
5901 Py_DECREF(args);
5902 if (temp != NULL) {
5903 if (using_len) {
5904 /* enforced by slot_nb_len */
5905 result = PyObject_IsTrue(temp);
5906 }
5907 else if (PyBool_Check(temp)) {
5908 result = PyObject_IsTrue(temp);
5909 }
5910 else {
5911 PyErr_Format(PyExc_TypeError,
5912 "__bool__ should return "
5913 "bool, returned %s",
5914 Py_TYPE(temp)->tp_name);
5915 result = -1;
5916 }
5917 Py_DECREF(temp);
5918 }
5919 }
5920 Py_DECREF(func);
5921 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005922}
5923
Guido van Rossum38fff8c2006-03-07 18:50:55 +00005924
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00005925static PyObject *
Guido van Rossum38fff8c2006-03-07 18:50:55 +00005926slot_nb_index(PyObject *self)
5927{
Benjamin Petersonce798522012-01-22 11:24:29 -05005928 _Py_IDENTIFIER(__index__);
5929 return call_method(self, &PyId___index__, "()");
Guido van Rossum38fff8c2006-03-07 18:50:55 +00005930}
5931
5932
Guido van Rossumdc91b992001-08-08 22:26:22 +00005933SLOT0(slot_nb_invert, "__invert__")
5934SLOT1BIN(slot_nb_lshift, nb_lshift, "__lshift__", "__rlshift__")
5935SLOT1BIN(slot_nb_rshift, nb_rshift, "__rshift__", "__rrshift__")
5936SLOT1BIN(slot_nb_and, nb_and, "__and__", "__rand__")
5937SLOT1BIN(slot_nb_xor, nb_xor, "__xor__", "__rxor__")
5938SLOT1BIN(slot_nb_or, nb_or, "__or__", "__ror__")
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00005939
Guido van Rossumdc91b992001-08-08 22:26:22 +00005940SLOT0(slot_nb_int, "__int__")
Guido van Rossumdc91b992001-08-08 22:26:22 +00005941SLOT0(slot_nb_float, "__float__")
Guido van Rossumdc91b992001-08-08 22:26:22 +00005942SLOT1(slot_nb_inplace_add, "__iadd__", PyObject *, "O")
5943SLOT1(slot_nb_inplace_subtract, "__isub__", PyObject *, "O")
5944SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *, "O")
Benjamin Petersond51374e2014-04-09 23:55:56 -04005945SLOT1(slot_nb_inplace_matrix_multiply, "__imatmul__", PyObject *, "O")
Guido van Rossumdc91b992001-08-08 22:26:22 +00005946SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *, "O")
Thomas Wouterscf297e42007-02-23 15:07:44 +00005947/* Can't use SLOT1 here, because nb_inplace_power is ternary */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005948static PyObject *
5949slot_nb_inplace_power(PyObject *self, PyObject * arg1, PyObject *arg2)
5950{
Benjamin Petersonce798522012-01-22 11:24:29 -05005951 _Py_IDENTIFIER(__ipow__);
5952 return call_method(self, &PyId___ipow__, "(" "O" ")", arg1);
Thomas Wouterscf297e42007-02-23 15:07:44 +00005953}
Guido van Rossumdc91b992001-08-08 22:26:22 +00005954SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *, "O")
5955SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *, "O")
5956SLOT1(slot_nb_inplace_and, "__iand__", PyObject *, "O")
5957SLOT1(slot_nb_inplace_xor, "__ixor__", PyObject *, "O")
5958SLOT1(slot_nb_inplace_or, "__ior__", PyObject *, "O")
5959SLOT1BIN(slot_nb_floor_divide, nb_floor_divide,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005960 "__floordiv__", "__rfloordiv__")
Guido van Rossumdc91b992001-08-08 22:26:22 +00005961SLOT1BIN(slot_nb_true_divide, nb_true_divide, "__truediv__", "__rtruediv__")
5962SLOT1(slot_nb_inplace_floor_divide, "__ifloordiv__", PyObject *, "O")
5963SLOT1(slot_nb_inplace_true_divide, "__itruediv__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00005964
Guido van Rossumb8f63662001-08-15 23:57:02 +00005965static PyObject *
5966slot_tp_repr(PyObject *self)
5967{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005968 PyObject *func, *res;
Benjamin Petersonce798522012-01-22 11:24:29 -05005969 _Py_IDENTIFIER(__repr__);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005970
Benjamin Petersonce798522012-01-22 11:24:29 -05005971 func = lookup_method(self, &PyId___repr__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005972 if (func != NULL) {
5973 res = PyEval_CallObject(func, NULL);
5974 Py_DECREF(func);
5975 return res;
5976 }
5977 PyErr_Clear();
5978 return PyUnicode_FromFormat("<%s object at %p>",
5979 Py_TYPE(self)->tp_name, self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005980}
5981
5982static PyObject *
5983slot_tp_str(PyObject *self)
5984{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005985 PyObject *func, *res;
Benjamin Petersonce798522012-01-22 11:24:29 -05005986 _Py_IDENTIFIER(__str__);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005987
Benjamin Petersonce798522012-01-22 11:24:29 -05005988 func = lookup_method(self, &PyId___str__);
Victor Stinner2e8474d2013-07-11 22:46:11 +02005989 if (func == NULL)
5990 return NULL;
Victor Stinnerbebba502013-10-29 10:56:34 +01005991 res = PyEval_CallObject(func, NULL);
5992 Py_DECREF(func);
5993 return res;
5994}
Tim Peters6d6c1a32001-08-02 04:15:00 +00005995
Benjamin Peterson8f67d082010-10-17 20:54:53 +00005996static Py_hash_t
Tim Peters6d6c1a32001-08-02 04:15:00 +00005997slot_tp_hash(PyObject *self)
5998{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005999 PyObject *func, *res;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00006000 Py_ssize_t h;
Tim Peters6d6c1a32001-08-02 04:15:00 +00006001
Benjamin Petersonce798522012-01-22 11:24:29 -05006002 func = lookup_method(self, &PyId___hash__);
Guido van Rossumb8f63662001-08-15 23:57:02 +00006003
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006004 if (func == Py_None) {
6005 Py_DECREF(func);
6006 func = NULL;
6007 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +00006008
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006009 if (func == NULL) {
6010 return PyObject_HashNotImplemented(self);
6011 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +00006012
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006013 res = PyEval_CallObject(func, NULL);
6014 Py_DECREF(func);
6015 if (res == NULL)
6016 return -1;
Mark Dickinsondc787d22010-05-23 13:33:13 +00006017
6018 if (!PyLong_Check(res)) {
6019 PyErr_SetString(PyExc_TypeError,
6020 "__hash__ method should return an integer");
6021 return -1;
6022 }
Benjamin Peterson8f67d082010-10-17 20:54:53 +00006023 /* Transform the PyLong `res` to a Py_hash_t `h`. For an existing
6024 hashable Python object x, hash(x) will always lie within the range of
6025 Py_hash_t. Therefore our transformation must preserve values that
6026 already lie within this range, to ensure that if x.__hash__() returns
6027 hash(y) then hash(x) == hash(y). */
6028 h = PyLong_AsSsize_t(res);
6029 if (h == -1 && PyErr_Occurred()) {
6030 /* res was not within the range of a Py_hash_t, so we're free to
Mark Dickinsondc787d22010-05-23 13:33:13 +00006031 use any sufficiently bit-mixing transformation;
6032 long.__hash__ will do nicely. */
Benjamin Peterson8f67d082010-10-17 20:54:53 +00006033 PyErr_Clear();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006034 h = PyLong_Type.tp_hash(res);
Benjamin Peterson8f67d082010-10-17 20:54:53 +00006035 }
Benjamin Petersone7dfeeb2010-10-17 21:27:01 +00006036 /* -1 is reserved for errors. */
6037 if (h == -1)
6038 h = -2;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006039 Py_DECREF(res);
Mark Dickinsondc787d22010-05-23 13:33:13 +00006040 return h;
Tim Peters6d6c1a32001-08-02 04:15:00 +00006041}
6042
6043static PyObject *
6044slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds)
6045{
Benjamin Petersonce798522012-01-22 11:24:29 -05006046 _Py_IDENTIFIER(__call__);
6047 PyObject *meth = lookup_method(self, &PyId___call__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006048 PyObject *res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00006049
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006050 if (meth == NULL)
6051 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006052
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006053 res = PyObject_Call(meth, args, kwds);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006054
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006055 Py_DECREF(meth);
6056 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00006057}
6058
Guido van Rossum14a6f832001-10-17 13:59:09 +00006059/* There are two slot dispatch functions for tp_getattro.
6060
6061 - slot_tp_getattro() is used when __getattribute__ is overridden
6062 but no __getattr__ hook is present;
6063
6064 - slot_tp_getattr_hook() is used when a __getattr__ hook is present.
6065
Guido van Rossumc334df52002-04-04 23:44:47 +00006066 The code in update_one_slot() always installs slot_tp_getattr_hook(); this
6067 detects the absence of __getattr__ and then installs the simpler slot if
6068 necessary. */
Guido van Rossum14a6f832001-10-17 13:59:09 +00006069
Tim Peters6d6c1a32001-08-02 04:15:00 +00006070static PyObject *
6071slot_tp_getattro(PyObject *self, PyObject *name)
6072{
Benjamin Petersonce798522012-01-22 11:24:29 -05006073 return call_method(self, &PyId___getattribute__, "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00006074}
6075
Guido van Rossum19c1cd52001-09-21 21:24:49 +00006076static PyObject *
Benjamin Peterson9262b842008-11-17 22:45:50 +00006077call_attribute(PyObject *self, PyObject *attr, PyObject *name)
6078{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006079 PyObject *res, *descr = NULL;
6080 descrgetfunc f = Py_TYPE(attr)->tp_descr_get;
Benjamin Peterson9262b842008-11-17 22:45:50 +00006081
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006082 if (f != NULL) {
6083 descr = f(attr, self, (PyObject *)(Py_TYPE(self)));
6084 if (descr == NULL)
6085 return NULL;
6086 else
6087 attr = descr;
6088 }
6089 res = PyObject_CallFunctionObjArgs(attr, name, NULL);
6090 Py_XDECREF(descr);
6091 return res;
Benjamin Peterson9262b842008-11-17 22:45:50 +00006092}
6093
6094static PyObject *
Guido van Rossum19c1cd52001-09-21 21:24:49 +00006095slot_tp_getattr_hook(PyObject *self, PyObject *name)
6096{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006097 PyTypeObject *tp = Py_TYPE(self);
6098 PyObject *getattr, *getattribute, *res;
Victor Stinner3c1e4812012-03-26 22:10:51 +02006099 _Py_IDENTIFIER(__getattr__);
Guido van Rossum19c1cd52001-09-21 21:24:49 +00006100
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006101 /* speed hack: we could use lookup_maybe, but that would resolve the
6102 method fully for each attribute lookup for classes with
6103 __getattr__, even when the attribute is present. So we use
6104 _PyType_Lookup and create the method only when needed, with
6105 call_attribute. */
Victor Stinner3c1e4812012-03-26 22:10:51 +02006106 getattr = _PyType_LookupId(tp, &PyId___getattr__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006107 if (getattr == NULL) {
6108 /* No __getattr__ hook: use a simpler dispatcher */
6109 tp->tp_getattro = slot_tp_getattro;
6110 return slot_tp_getattro(self, name);
6111 }
6112 Py_INCREF(getattr);
6113 /* speed hack: we could use lookup_maybe, but that would resolve the
6114 method fully for each attribute lookup for classes with
6115 __getattr__, even when self has the default __getattribute__
6116 method. So we use _PyType_Lookup and create the method only when
6117 needed, with call_attribute. */
Victor Stinner3c1e4812012-03-26 22:10:51 +02006118 getattribute = _PyType_LookupId(tp, &PyId___getattribute__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006119 if (getattribute == NULL ||
6120 (Py_TYPE(getattribute) == &PyWrapperDescr_Type &&
6121 ((PyWrapperDescrObject *)getattribute)->d_wrapped ==
6122 (void *)PyObject_GenericGetAttr))
6123 res = PyObject_GenericGetAttr(self, name);
6124 else {
6125 Py_INCREF(getattribute);
6126 res = call_attribute(self, getattribute, name);
6127 Py_DECREF(getattribute);
6128 }
6129 if (res == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) {
6130 PyErr_Clear();
6131 res = call_attribute(self, getattr, name);
6132 }
6133 Py_DECREF(getattr);
6134 return res;
Guido van Rossum19c1cd52001-09-21 21:24:49 +00006135}
6136
Tim Peters6d6c1a32001-08-02 04:15:00 +00006137static int
6138slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value)
6139{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006140 PyObject *res;
Benjamin Petersonce798522012-01-22 11:24:29 -05006141 _Py_IDENTIFIER(__delattr__);
6142 _Py_IDENTIFIER(__setattr__);
Tim Peters6d6c1a32001-08-02 04:15:00 +00006143
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006144 if (value == NULL)
Benjamin Petersonce798522012-01-22 11:24:29 -05006145 res = call_method(self, &PyId___delattr__, "(O)", name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006146 else
Benjamin Petersonce798522012-01-22 11:24:29 -05006147 res = call_method(self, &PyId___setattr__, "(OO)", name, value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006148 if (res == NULL)
6149 return -1;
6150 Py_DECREF(res);
6151 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00006152}
6153
Benjamin Petersonce798522012-01-22 11:24:29 -05006154static _Py_Identifier name_op[] = {
6155 {0, "__lt__", 0},
6156 {0, "__le__", 0},
6157 {0, "__eq__", 0},
6158 {0, "__ne__", 0},
6159 {0, "__gt__", 0},
6160 {0, "__ge__", 0}
Guido van Rossumf5243f02008-01-01 04:06:48 +00006161};
6162
Tim Peters6d6c1a32001-08-02 04:15:00 +00006163static PyObject *
Mark Dickinson6f1d0492009-11-15 13:58:49 +00006164slot_tp_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters6d6c1a32001-08-02 04:15:00 +00006165{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006166 PyObject *func, *args, *res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00006167
Benjamin Petersonce798522012-01-22 11:24:29 -05006168 func = lookup_method(self, &name_op[op]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006169 if (func == NULL) {
6170 PyErr_Clear();
Brian Curtindfc80e32011-08-10 20:28:54 -05006171 Py_RETURN_NOTIMPLEMENTED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006172 }
6173 args = PyTuple_Pack(1, other);
6174 if (args == NULL)
6175 res = NULL;
6176 else {
6177 res = PyObject_Call(func, args, NULL);
6178 Py_DECREF(args);
6179 }
6180 Py_DECREF(func);
6181 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00006182}
6183
Guido van Rossumb8f63662001-08-15 23:57:02 +00006184static PyObject *
Guido van Rossumb8f63662001-08-15 23:57:02 +00006185slot_tp_iter(PyObject *self)
6186{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006187 PyObject *func, *res;
Benjamin Petersonce798522012-01-22 11:24:29 -05006188 _Py_IDENTIFIER(__iter__);
Guido van Rossumb8f63662001-08-15 23:57:02 +00006189
Benjamin Petersonce798522012-01-22 11:24:29 -05006190 func = lookup_method(self, &PyId___iter__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006191 if (func != NULL) {
6192 PyObject *args;
6193 args = res = PyTuple_New(0);
6194 if (args != NULL) {
6195 res = PyObject_Call(func, args, NULL);
6196 Py_DECREF(args);
6197 }
6198 Py_DECREF(func);
6199 return res;
6200 }
6201 PyErr_Clear();
Benjamin Petersonce798522012-01-22 11:24:29 -05006202 func = lookup_method(self, &PyId___getitem__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006203 if (func == NULL) {
6204 PyErr_Format(PyExc_TypeError,
6205 "'%.200s' object is not iterable",
6206 Py_TYPE(self)->tp_name);
6207 return NULL;
6208 }
6209 Py_DECREF(func);
6210 return PySeqIter_New(self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00006211}
Tim Peters6d6c1a32001-08-02 04:15:00 +00006212
6213static PyObject *
6214slot_tp_iternext(PyObject *self)
6215{
Benjamin Petersonce798522012-01-22 11:24:29 -05006216 _Py_IDENTIFIER(__next__);
6217 return call_method(self, &PyId___next__, "()");
Tim Peters6d6c1a32001-08-02 04:15:00 +00006218}
6219
Guido van Rossum1a493502001-08-17 16:47:50 +00006220static PyObject *
6221slot_tp_descr_get(PyObject *self, PyObject *obj, PyObject *type)
6222{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006223 PyTypeObject *tp = Py_TYPE(self);
6224 PyObject *get;
Victor Stinner3c1e4812012-03-26 22:10:51 +02006225 _Py_IDENTIFIER(__get__);
Guido van Rossum1a493502001-08-17 16:47:50 +00006226
Victor Stinner3c1e4812012-03-26 22:10:51 +02006227 get = _PyType_LookupId(tp, &PyId___get__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006228 if (get == NULL) {
6229 /* Avoid further slowdowns */
6230 if (tp->tp_descr_get == slot_tp_descr_get)
6231 tp->tp_descr_get = NULL;
6232 Py_INCREF(self);
6233 return self;
6234 }
6235 if (obj == NULL)
6236 obj = Py_None;
6237 if (type == NULL)
6238 type = Py_None;
6239 return PyObject_CallFunctionObjArgs(get, self, obj, type, NULL);
Guido van Rossum1a493502001-08-17 16:47:50 +00006240}
Tim Peters6d6c1a32001-08-02 04:15:00 +00006241
6242static int
6243slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value)
6244{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006245 PyObject *res;
Benjamin Petersonce798522012-01-22 11:24:29 -05006246 _Py_IDENTIFIER(__delete__);
6247 _Py_IDENTIFIER(__set__);
Guido van Rossum2c252392001-08-24 10:13:31 +00006248
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006249 if (value == NULL)
Benjamin Petersonce798522012-01-22 11:24:29 -05006250 res = call_method(self, &PyId___delete__, "(O)", target);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006251 else
Benjamin Petersonce798522012-01-22 11:24:29 -05006252 res = call_method(self, &PyId___set__, "(OO)", target, value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006253 if (res == NULL)
6254 return -1;
6255 Py_DECREF(res);
6256 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00006257}
6258
6259static int
6260slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds)
6261{
Benjamin Petersonce798522012-01-22 11:24:29 -05006262 _Py_IDENTIFIER(__init__);
6263 PyObject *meth = lookup_method(self, &PyId___init__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006264 PyObject *res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00006265
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006266 if (meth == NULL)
6267 return -1;
6268 res = PyObject_Call(meth, args, kwds);
6269 Py_DECREF(meth);
6270 if (res == NULL)
6271 return -1;
6272 if (res != Py_None) {
6273 PyErr_Format(PyExc_TypeError,
6274 "__init__() should return None, not '%.200s'",
6275 Py_TYPE(res)->tp_name);
6276 Py_DECREF(res);
6277 return -1;
6278 }
6279 Py_DECREF(res);
6280 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00006281}
6282
6283static PyObject *
6284slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
6285{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006286 PyObject *func;
6287 PyObject *newargs, *x;
6288 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +00006289
Victor Stinner3c1e4812012-03-26 22:10:51 +02006290 func = _PyObject_GetAttrId((PyObject *)type, &PyId___new__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006291 if (func == NULL)
6292 return NULL;
6293 assert(PyTuple_Check(args));
6294 n = PyTuple_GET_SIZE(args);
6295 newargs = PyTuple_New(n+1);
6296 if (newargs == NULL)
6297 return NULL;
6298 Py_INCREF(type);
6299 PyTuple_SET_ITEM(newargs, 0, (PyObject *)type);
6300 for (i = 0; i < n; i++) {
6301 x = PyTuple_GET_ITEM(args, i);
6302 Py_INCREF(x);
6303 PyTuple_SET_ITEM(newargs, i+1, x);
6304 }
6305 x = PyObject_Call(func, newargs, kwds);
6306 Py_DECREF(newargs);
6307 Py_DECREF(func);
6308 return x;
Tim Peters6d6c1a32001-08-02 04:15:00 +00006309}
6310
Guido van Rossumfebd61d2002-08-08 20:55:20 +00006311static void
Antoine Pitrou796564c2013-07-30 19:59:21 +02006312slot_tp_finalize(PyObject *self)
Guido van Rossumfebd61d2002-08-08 20:55:20 +00006313{
Benjamin Petersonce798522012-01-22 11:24:29 -05006314 _Py_IDENTIFIER(__del__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006315 PyObject *del, *res;
6316 PyObject *error_type, *error_value, *error_traceback;
Guido van Rossumfebd61d2002-08-08 20:55:20 +00006317
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006318 /* Save the current exception, if any. */
6319 PyErr_Fetch(&error_type, &error_value, &error_traceback);
Guido van Rossumfebd61d2002-08-08 20:55:20 +00006320
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006321 /* Execute __del__ method, if any. */
Benjamin Petersonce798522012-01-22 11:24:29 -05006322 del = lookup_maybe(self, &PyId___del__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006323 if (del != NULL) {
6324 res = PyEval_CallObject(del, NULL);
6325 if (res == NULL)
6326 PyErr_WriteUnraisable(del);
6327 else
6328 Py_DECREF(res);
6329 Py_DECREF(del);
6330 }
Guido van Rossumfebd61d2002-08-08 20:55:20 +00006331
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006332 /* Restore the saved exception. */
6333 PyErr_Restore(error_type, error_value, error_traceback);
Guido van Rossumfebd61d2002-08-08 20:55:20 +00006334}
6335
Yury Selivanov75445082015-05-11 22:57:16 -04006336static PyObject *
6337slot_am_await(PyObject *self)
6338{
6339 PyObject *func, *res;
6340 _Py_IDENTIFIER(__await__);
6341
6342 func = lookup_method(self, &PyId___await__);
6343 if (func != NULL) {
6344 res = PyEval_CallObject(func, NULL);
6345 Py_DECREF(func);
6346 return res;
6347 }
6348 PyErr_Format(PyExc_AttributeError,
6349 "object %.50s does not have __await__ method",
6350 Py_TYPE(self)->tp_name);
6351 return NULL;
6352}
6353
6354static PyObject *
6355slot_am_aiter(PyObject *self)
6356{
6357 PyObject *func, *res;
6358 _Py_IDENTIFIER(__aiter__);
6359
6360 func = lookup_method(self, &PyId___aiter__);
6361 if (func != NULL) {
6362 res = PyEval_CallObject(func, NULL);
6363 Py_DECREF(func);
6364 return res;
6365 }
6366 PyErr_Format(PyExc_AttributeError,
6367 "object %.50s does not have __aiter__ method",
6368 Py_TYPE(self)->tp_name);
6369 return NULL;
6370}
6371
6372static PyObject *
6373slot_am_anext(PyObject *self)
6374{
6375 PyObject *func, *res;
6376 _Py_IDENTIFIER(__anext__);
6377
6378 func = lookup_method(self, &PyId___anext__);
6379 if (func != NULL) {
6380 res = PyEval_CallObject(func, NULL);
6381 Py_DECREF(func);
6382 return res;
6383 }
6384 PyErr_Format(PyExc_AttributeError,
6385 "object %.50s does not have __anext__ method",
6386 Py_TYPE(self)->tp_name);
6387 return NULL;
6388}
Guido van Rossum7b9144b2001-10-09 19:39:46 +00006389
Benjamin Peterson63952412013-04-01 17:41:41 -04006390/*
6391Table mapping __foo__ names to tp_foo offsets and slot_tp_foo wrapper functions.
6392
6393The table is ordered by offsets relative to the 'PyHeapTypeObject' structure,
6394which incorporates the additional structures used for numbers, sequences and
6395mappings. Note that multiple names may map to the same slot (e.g. __eq__,
6396__ne__ etc. all map to tp_richcompare) and one name may map to multiple slots
6397(e.g. __str__ affects tp_str as well as tp_repr). The table is terminated with
6398an all-zero entry. (This table is further initialized in init_slotdefs().)
6399*/
Guido van Rossum7b9144b2001-10-09 19:39:46 +00006400
Guido van Rossum6d204072001-10-21 00:44:31 +00006401typedef struct wrapperbase slotdef;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00006402
6403#undef TPSLOT
Guido van Rossumc8e56452001-10-22 00:43:43 +00006404#undef FLSLOT
Yury Selivanov75445082015-05-11 22:57:16 -04006405#undef AMSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00006406#undef ETSLOT
6407#undef SQSLOT
6408#undef MPSLOT
6409#undef NBSLOT
Guido van Rossum6d204072001-10-21 00:44:31 +00006410#undef UNSLOT
6411#undef IBSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00006412#undef BINSLOT
6413#undef RBINSLOT
6414
Guido van Rossum6d204072001-10-21 00:44:31 +00006415#define TPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006416 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
6417 PyDoc_STR(DOC)}
Guido van Rossumc8e56452001-10-22 00:43:43 +00006418#define FLSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC, FLAGS) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006419 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
6420 PyDoc_STR(DOC), FLAGS}
Guido van Rossum6d204072001-10-21 00:44:31 +00006421#define ETSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006422 {NAME, offsetof(PyHeapTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
6423 PyDoc_STR(DOC)}
Yury Selivanov75445082015-05-11 22:57:16 -04006424#define AMSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
6425 ETSLOT(NAME, as_async.SLOT, FUNCTION, WRAPPER, DOC)
Guido van Rossum6d204072001-10-21 00:44:31 +00006426#define SQSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006427 ETSLOT(NAME, as_sequence.SLOT, FUNCTION, WRAPPER, DOC)
Guido van Rossum6d204072001-10-21 00:44:31 +00006428#define MPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006429 ETSLOT(NAME, as_mapping.SLOT, FUNCTION, WRAPPER, DOC)
Guido van Rossum6d204072001-10-21 00:44:31 +00006430#define NBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006431 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, DOC)
Guido van Rossum6d204072001-10-21 00:44:31 +00006432#define UNSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006433 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
Larry Hastings69a25472014-02-09 22:22:38 -08006434 NAME "($self, /)\n--\n\n" DOC)
Guido van Rossum6d204072001-10-21 00:44:31 +00006435#define IBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006436 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
Larry Hastings69a25472014-02-09 22:22:38 -08006437 NAME "($self, value, /)\n--\n\nReturn self" DOC "value.")
Guido van Rossum6d204072001-10-21 00:44:31 +00006438#define BINSLOT(NAME, SLOT, FUNCTION, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006439 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
Larry Hastings69a25472014-02-09 22:22:38 -08006440 NAME "($self, value, /)\n--\n\nReturn self" DOC "value.")
Guido van Rossum6d204072001-10-21 00:44:31 +00006441#define RBINSLOT(NAME, SLOT, FUNCTION, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006442 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
Larry Hastings69a25472014-02-09 22:22:38 -08006443 NAME "($self, value, /)\n--\n\nReturn value" DOC "self.")
Anthony Baxter56616992005-06-03 14:12:21 +00006444#define BINSLOTNOTINFIX(NAME, SLOT, FUNCTION, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006445 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
Larry Hastings69a25472014-02-09 22:22:38 -08006446 NAME "($self, value, /)\n--\n\n" DOC)
Anthony Baxter56616992005-06-03 14:12:21 +00006447#define RBINSLOTNOTINFIX(NAME, SLOT, FUNCTION, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006448 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
Larry Hastings69a25472014-02-09 22:22:38 -08006449 NAME "($self, value, /)\n--\n\n" DOC)
Guido van Rossum7b9144b2001-10-09 19:39:46 +00006450
6451static slotdef slotdefs[] = {
Benjamin Peterson63952412013-04-01 17:41:41 -04006452 TPSLOT("__getattribute__", tp_getattr, NULL, NULL, ""),
6453 TPSLOT("__getattr__", tp_getattr, NULL, NULL, ""),
6454 TPSLOT("__setattr__", tp_setattr, NULL, NULL, ""),
6455 TPSLOT("__delattr__", tp_setattr, NULL, NULL, ""),
6456 TPSLOT("__repr__", tp_repr, slot_tp_repr, wrap_unaryfunc,
Larry Hastings69a25472014-02-09 22:22:38 -08006457 "__repr__($self, /)\n--\n\nReturn repr(self)."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006458 TPSLOT("__hash__", tp_hash, slot_tp_hash, wrap_hashfunc,
Larry Hastings69a25472014-02-09 22:22:38 -08006459 "__hash__($self, /)\n--\n\nReturn hash(self)."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006460 FLSLOT("__call__", tp_call, slot_tp_call, (wrapperfunc)wrap_call,
Larry Hastings69a25472014-02-09 22:22:38 -08006461 "__call__($self, /, *args, **kwargs)\n--\n\nCall self as a function.",
Larry Hastings5c661892014-01-24 06:17:25 -08006462 PyWrapperFlag_KEYWORDS),
Benjamin Peterson63952412013-04-01 17:41:41 -04006463 TPSLOT("__str__", tp_str, slot_tp_str, wrap_unaryfunc,
Larry Hastings69a25472014-02-09 22:22:38 -08006464 "__str__($self, /)\n--\n\nReturn str(self)."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006465 TPSLOT("__getattribute__", tp_getattro, slot_tp_getattr_hook,
Larry Hastings5c661892014-01-24 06:17:25 -08006466 wrap_binaryfunc,
Larry Hastings69a25472014-02-09 22:22:38 -08006467 "__getattribute__($self, name, /)\n--\n\nReturn getattr(self, name)."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006468 TPSLOT("__getattr__", tp_getattro, slot_tp_getattr_hook, NULL, ""),
6469 TPSLOT("__setattr__", tp_setattro, slot_tp_setattro, wrap_setattr,
Larry Hastings69a25472014-02-09 22:22:38 -08006470 "__setattr__($self, name, value, /)\n--\n\nImplement setattr(self, name, value)."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006471 TPSLOT("__delattr__", tp_setattro, slot_tp_setattro, wrap_delattr,
Larry Hastings69a25472014-02-09 22:22:38 -08006472 "__delattr__($self, name, /)\n--\n\nImplement delattr(self, name)."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006473 TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare, richcmp_lt,
Larry Hastings69a25472014-02-09 22:22:38 -08006474 "__lt__($self, value, /)\n--\n\nReturn self<value."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006475 TPSLOT("__le__", tp_richcompare, slot_tp_richcompare, richcmp_le,
Larry Hastings69a25472014-02-09 22:22:38 -08006476 "__le__($self, value, /)\n--\n\nReturn self<=value."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006477 TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare, richcmp_eq,
Larry Hastings69a25472014-02-09 22:22:38 -08006478 "__eq__($self, value, /)\n--\n\nReturn self==value."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006479 TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare, richcmp_ne,
Larry Hastings69a25472014-02-09 22:22:38 -08006480 "__ne__($self, value, /)\n--\n\nReturn self!=value."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006481 TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare, richcmp_gt,
Larry Hastings69a25472014-02-09 22:22:38 -08006482 "__gt__($self, value, /)\n--\n\nReturn self>value."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006483 TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare, richcmp_ge,
Zachary Wareea42b4c2014-04-18 09:14:31 -05006484 "__ge__($self, value, /)\n--\n\nReturn self>=value."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006485 TPSLOT("__iter__", tp_iter, slot_tp_iter, wrap_unaryfunc,
Larry Hastings69a25472014-02-09 22:22:38 -08006486 "__iter__($self, /)\n--\n\nImplement iter(self)."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006487 TPSLOT("__next__", tp_iternext, slot_tp_iternext, wrap_next,
Larry Hastings69a25472014-02-09 22:22:38 -08006488 "__next__($self, /)\n--\n\nImplement next(self)."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006489 TPSLOT("__get__", tp_descr_get, slot_tp_descr_get, wrap_descr_get,
Larry Hastings69a25472014-02-09 22:22:38 -08006490 "__get__($self, instance, owner, /)\n--\n\nReturn an attribute of instance, which is of type owner."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006491 TPSLOT("__set__", tp_descr_set, slot_tp_descr_set, wrap_descr_set,
Larry Hastings69a25472014-02-09 22:22:38 -08006492 "__set__($self, instance, value, /)\n--\n\nSet an attribute of instance to value."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006493 TPSLOT("__delete__", tp_descr_set, slot_tp_descr_set,
Larry Hastings5c661892014-01-24 06:17:25 -08006494 wrap_descr_delete,
Yury Selivanov056e2652014-03-02 12:25:27 -05006495 "__delete__($self, instance, /)\n--\n\nDelete an attribute of instance."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006496 FLSLOT("__init__", tp_init, slot_tp_init, (wrapperfunc)wrap_init,
Larry Hastings69a25472014-02-09 22:22:38 -08006497 "__init__($self, /, *args, **kwargs)\n--\n\n"
Larry Hastings581ee362014-01-28 05:00:08 -08006498 "Initialize self. See help(type(self)) for accurate signature.",
Benjamin Peterson63952412013-04-01 17:41:41 -04006499 PyWrapperFlag_KEYWORDS),
Larry Hastings5c661892014-01-24 06:17:25 -08006500 TPSLOT("__new__", tp_new, slot_tp_new, NULL,
Larry Hastings69a25472014-02-09 22:22:38 -08006501 "__new__(type, /, *args, **kwargs)\n--\n\n"
Larry Hastings581ee362014-01-28 05:00:08 -08006502 "Create and return new object. See help(type) for accurate signature."),
Antoine Pitrou796564c2013-07-30 19:59:21 +02006503 TPSLOT("__del__", tp_finalize, slot_tp_finalize, (wrapperfunc)wrap_del, ""),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00006504
Yury Selivanov75445082015-05-11 22:57:16 -04006505 AMSLOT("__await__", am_await, slot_am_await, wrap_unaryfunc,
6506 "__await__($self, /)\n--\n\nReturn an iterator to be used in await expression."),
6507 AMSLOT("__aiter__", am_aiter, slot_am_aiter, wrap_unaryfunc,
6508 "__aiter__($self, /)\n--\n\nReturn an awaitable, that resolves in asynchronous iterator."),
6509 AMSLOT("__anext__", am_anext, slot_am_anext, wrap_unaryfunc,
6510 "__anext__($self, /)\n--\n\nReturn a value or raise StopAsyncIteration."),
6511
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006512 BINSLOT("__add__", nb_add, slot_nb_add,
Larry Hastings5c661892014-01-24 06:17:25 -08006513 "+"),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006514 RBINSLOT("__radd__", nb_add, slot_nb_add,
Larry Hastings5c661892014-01-24 06:17:25 -08006515 "+"),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006516 BINSLOT("__sub__", nb_subtract, slot_nb_subtract,
Larry Hastings5c661892014-01-24 06:17:25 -08006517 "-"),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006518 RBINSLOT("__rsub__", nb_subtract, slot_nb_subtract,
Larry Hastings5c661892014-01-24 06:17:25 -08006519 "-"),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006520 BINSLOT("__mul__", nb_multiply, slot_nb_multiply,
Larry Hastings5c661892014-01-24 06:17:25 -08006521 "*"),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006522 RBINSLOT("__rmul__", nb_multiply, slot_nb_multiply,
Larry Hastings5c661892014-01-24 06:17:25 -08006523 "*"),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006524 BINSLOT("__mod__", nb_remainder, slot_nb_remainder,
Larry Hastings5c661892014-01-24 06:17:25 -08006525 "%"),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006526 RBINSLOT("__rmod__", nb_remainder, slot_nb_remainder,
Larry Hastings5c661892014-01-24 06:17:25 -08006527 "%"),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006528 BINSLOTNOTINFIX("__divmod__", nb_divmod, slot_nb_divmod,
Larry Hastings581ee362014-01-28 05:00:08 -08006529 "Return divmod(self, value)."),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006530 RBINSLOTNOTINFIX("__rdivmod__", nb_divmod, slot_nb_divmod,
Larry Hastings581ee362014-01-28 05:00:08 -08006531 "Return divmod(value, self)."),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006532 NBSLOT("__pow__", nb_power, slot_nb_power, wrap_ternaryfunc,
Larry Hastings69a25472014-02-09 22:22:38 -08006533 "__pow__($self, value, mod=None, /)\n--\n\nReturn pow(self, value, mod)."),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006534 NBSLOT("__rpow__", nb_power, slot_nb_power, wrap_ternaryfunc_r,
Larry Hastings69a25472014-02-09 22:22:38 -08006535 "__rpow__($self, value, mod=None, /)\n--\n\nReturn pow(value, self, mod)."),
Larry Hastings5c661892014-01-24 06:17:25 -08006536 UNSLOT("__neg__", nb_negative, slot_nb_negative, wrap_unaryfunc, "-self"),
6537 UNSLOT("__pos__", nb_positive, slot_nb_positive, wrap_unaryfunc, "+self"),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006538 UNSLOT("__abs__", nb_absolute, slot_nb_absolute, wrap_unaryfunc,
Larry Hastings5c661892014-01-24 06:17:25 -08006539 "abs(self)"),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006540 UNSLOT("__bool__", nb_bool, slot_nb_bool, wrap_inquirypred,
Larry Hastings5c661892014-01-24 06:17:25 -08006541 "self != 0"),
6542 UNSLOT("__invert__", nb_invert, slot_nb_invert, wrap_unaryfunc, "~self"),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006543 BINSLOT("__lshift__", nb_lshift, slot_nb_lshift, "<<"),
6544 RBINSLOT("__rlshift__", nb_lshift, slot_nb_lshift, "<<"),
6545 BINSLOT("__rshift__", nb_rshift, slot_nb_rshift, ">>"),
6546 RBINSLOT("__rrshift__", nb_rshift, slot_nb_rshift, ">>"),
6547 BINSLOT("__and__", nb_and, slot_nb_and, "&"),
6548 RBINSLOT("__rand__", nb_and, slot_nb_and, "&"),
6549 BINSLOT("__xor__", nb_xor, slot_nb_xor, "^"),
6550 RBINSLOT("__rxor__", nb_xor, slot_nb_xor, "^"),
6551 BINSLOT("__or__", nb_or, slot_nb_or, "|"),
6552 RBINSLOT("__ror__", nb_or, slot_nb_or, "|"),
6553 UNSLOT("__int__", nb_int, slot_nb_int, wrap_unaryfunc,
Larry Hastings5c661892014-01-24 06:17:25 -08006554 "int(self)"),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006555 UNSLOT("__float__", nb_float, slot_nb_float, wrap_unaryfunc,
Larry Hastings5c661892014-01-24 06:17:25 -08006556 "float(self)"),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006557 IBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add,
Eli Benderskyd3baae72011-11-11 16:57:05 +02006558 wrap_binaryfunc, "+="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006559 IBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract,
Eli Benderskyd3baae72011-11-11 16:57:05 +02006560 wrap_binaryfunc, "-="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006561 IBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply,
Eli Benderskyd3baae72011-11-11 16:57:05 +02006562 wrap_binaryfunc, "*="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006563 IBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder,
Eli Benderskyd3baae72011-11-11 16:57:05 +02006564 wrap_binaryfunc, "%="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006565 IBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power,
Eli Benderskyd3baae72011-11-11 16:57:05 +02006566 wrap_binaryfunc, "**="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006567 IBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift,
Eli Benderskyd3baae72011-11-11 16:57:05 +02006568 wrap_binaryfunc, "<<="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006569 IBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift,
Eli Benderskyd3baae72011-11-11 16:57:05 +02006570 wrap_binaryfunc, ">>="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006571 IBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and,
Eli Benderskyd3baae72011-11-11 16:57:05 +02006572 wrap_binaryfunc, "&="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006573 IBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor,
Eli Benderskyd3baae72011-11-11 16:57:05 +02006574 wrap_binaryfunc, "^="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006575 IBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or,
Eli Benderskyd3baae72011-11-11 16:57:05 +02006576 wrap_binaryfunc, "|="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006577 BINSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
6578 RBINSLOT("__rfloordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
6579 BINSLOT("__truediv__", nb_true_divide, slot_nb_true_divide, "/"),
6580 RBINSLOT("__rtruediv__", nb_true_divide, slot_nb_true_divide, "/"),
6581 IBSLOT("__ifloordiv__", nb_inplace_floor_divide,
Georg Brandle1d26f32014-10-31 13:12:57 +01006582 slot_nb_inplace_floor_divide, wrap_binaryfunc, "//="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006583 IBSLOT("__itruediv__", nb_inplace_true_divide,
Georg Brandle1d26f32014-10-31 13:12:57 +01006584 slot_nb_inplace_true_divide, wrap_binaryfunc, "/="),
Benjamin Peterson63952412013-04-01 17:41:41 -04006585 NBSLOT("__index__", nb_index, slot_nb_index, wrap_unaryfunc,
Larry Hastings69a25472014-02-09 22:22:38 -08006586 "__index__($self, /)\n--\n\n"
Zachary Ware715ef022014-04-18 09:23:14 -05006587 "Return self converted to an integer, if self is suitable "
Larry Hastings5c661892014-01-24 06:17:25 -08006588 "for use as an index into a list."),
Benjamin Petersond51374e2014-04-09 23:55:56 -04006589 BINSLOT("__matmul__", nb_matrix_multiply, slot_nb_matrix_multiply,
6590 "@"),
6591 RBINSLOT("__rmatmul__", nb_matrix_multiply, slot_nb_matrix_multiply,
6592 "@"),
6593 IBSLOT("__imatmul__", nb_inplace_matrix_multiply, slot_nb_inplace_matrix_multiply,
6594 wrap_binaryfunc, "@="),
Benjamin Peterson63952412013-04-01 17:41:41 -04006595 MPSLOT("__len__", mp_length, slot_mp_length, wrap_lenfunc,
Larry Hastings69a25472014-02-09 22:22:38 -08006596 "__len__($self, /)\n--\n\nReturn len(self)."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006597 MPSLOT("__getitem__", mp_subscript, slot_mp_subscript,
6598 wrap_binaryfunc,
Larry Hastings69a25472014-02-09 22:22:38 -08006599 "__getitem__($self, key, /)\n--\n\nReturn self[key]."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006600 MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript,
6601 wrap_objobjargproc,
Larry Hastings69a25472014-02-09 22:22:38 -08006602 "__setitem__($self, key, value, /)\n--\n\nSet self[key] to value."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006603 MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript,
6604 wrap_delitem,
Yury Selivanov056e2652014-03-02 12:25:27 -05006605 "__delitem__($self, key, /)\n--\n\nDelete self[key]."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006606
6607 SQSLOT("__len__", sq_length, slot_sq_length, wrap_lenfunc,
Larry Hastings69a25472014-02-09 22:22:38 -08006608 "__len__($self, /)\n--\n\nReturn len(self)."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006609 /* Heap types defining __add__/__mul__ have sq_concat/sq_repeat == NULL.
6610 The logic in abstract.c always falls back to nb_add/nb_multiply in
6611 this case. Defining both the nb_* and the sq_* slots to call the
6612 user-defined methods has unexpected side-effects, as shown by
6613 test_descr.notimplemented() */
6614 SQSLOT("__add__", sq_concat, NULL, wrap_binaryfunc,
Larry Hastings69a25472014-02-09 22:22:38 -08006615 "__add__($self, value, /)\n--\n\nReturn self+value."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006616 SQSLOT("__mul__", sq_repeat, NULL, wrap_indexargfunc,
Larry Hastings69a25472014-02-09 22:22:38 -08006617 "__mul__($self, value, /)\n--\n\nReturn self*value.n"),
Benjamin Peterson63952412013-04-01 17:41:41 -04006618 SQSLOT("__rmul__", sq_repeat, NULL, wrap_indexargfunc,
Larry Hastings69a25472014-02-09 22:22:38 -08006619 "__rmul__($self, value, /)\n--\n\nReturn self*value."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006620 SQSLOT("__getitem__", sq_item, slot_sq_item, wrap_sq_item,
Larry Hastings69a25472014-02-09 22:22:38 -08006621 "__getitem__($self, key, /)\n--\n\nReturn self[key]."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006622 SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_setitem,
Larry Hastings69a25472014-02-09 22:22:38 -08006623 "__setitem__($self, key, value, /)\n--\n\nSet self[key] to value."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006624 SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_delitem,
Larry Hastings69a25472014-02-09 22:22:38 -08006625 "__delitem__($self, key, /)\n--\n\nDelete self[key]."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006626 SQSLOT("__contains__", sq_contains, slot_sq_contains, wrap_objobjproc,
Larry Hastings69a25472014-02-09 22:22:38 -08006627 "__contains__($self, key, /)\n--\n\nReturn key in self."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006628 SQSLOT("__iadd__", sq_inplace_concat, NULL,
Larry Hastings5c661892014-01-24 06:17:25 -08006629 wrap_binaryfunc,
Larry Hastings69a25472014-02-09 22:22:38 -08006630 "__iadd__($self, value, /)\n--\n\nImplement self+=value."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006631 SQSLOT("__imul__", sq_inplace_repeat, NULL,
Larry Hastings5c661892014-01-24 06:17:25 -08006632 wrap_indexargfunc,
Larry Hastings69a25472014-02-09 22:22:38 -08006633 "__imul__($self, value, /)\n--\n\nImplement self*=value."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006634
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006635 {NULL}
Guido van Rossum7b9144b2001-10-09 19:39:46 +00006636};
6637
Guido van Rossumc334df52002-04-04 23:44:47 +00006638/* Given a type pointer and an offset gotten from a slotdef entry, return a
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006639 pointer to the actual slot. This is not quite the same as simply adding
Guido van Rossumc334df52002-04-04 23:44:47 +00006640 the offset to the type pointer, since it takes care to indirect through the
6641 proper indirection pointer (as_buffer, etc.); it returns NULL if the
6642 indirection pointer is NULL. */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00006643static void **
Martin v. Löwis18e16552006-02-15 17:27:45 +00006644slotptr(PyTypeObject *type, int ioffset)
Guido van Rossum7b9144b2001-10-09 19:39:46 +00006645{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006646 char *ptr;
6647 long offset = ioffset;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00006648
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006649 /* Note: this depends on the order of the members of PyHeapTypeObject! */
6650 assert(offset >= 0);
6651 assert((size_t)offset < offsetof(PyHeapTypeObject, as_buffer));
6652 if ((size_t)offset >= offsetof(PyHeapTypeObject, as_sequence)) {
6653 ptr = (char *)type->tp_as_sequence;
6654 offset -= offsetof(PyHeapTypeObject, as_sequence);
6655 }
6656 else if ((size_t)offset >= offsetof(PyHeapTypeObject, as_mapping)) {
6657 ptr = (char *)type->tp_as_mapping;
6658 offset -= offsetof(PyHeapTypeObject, as_mapping);
6659 }
6660 else if ((size_t)offset >= offsetof(PyHeapTypeObject, as_number)) {
6661 ptr = (char *)type->tp_as_number;
6662 offset -= offsetof(PyHeapTypeObject, as_number);
6663 }
Yury Selivanov75445082015-05-11 22:57:16 -04006664 else if ((size_t)offset >= offsetof(PyHeapTypeObject, as_async)) {
6665 ptr = (char *)type->tp_as_async;
6666 offset -= offsetof(PyHeapTypeObject, as_async);
6667 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006668 else {
6669 ptr = (char *)type;
6670 }
6671 if (ptr != NULL)
6672 ptr += offset;
6673 return (void **)ptr;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00006674}
Guido van Rossumf040ede2001-08-07 16:40:56 +00006675
Guido van Rossumc334df52002-04-04 23:44:47 +00006676/* Length of array of slotdef pointers used to store slots with the
6677 same __name__. There should be at most MAX_EQUIV-1 slotdef entries with
6678 the same __name__, for any __name__. Since that's a static property, it is
6679 appropriate to declare fixed-size arrays for this. */
6680#define MAX_EQUIV 10
6681
6682/* Return a slot pointer for a given name, but ONLY if the attribute has
6683 exactly one slot function. The name must be an interned string. */
6684static void **
6685resolve_slotdups(PyTypeObject *type, PyObject *name)
6686{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006687 /* XXX Maybe this could be optimized more -- but is it worth it? */
Guido van Rossumc334df52002-04-04 23:44:47 +00006688
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006689 /* pname and ptrs act as a little cache */
6690 static PyObject *pname;
6691 static slotdef *ptrs[MAX_EQUIV];
6692 slotdef *p, **pp;
6693 void **res, **ptr;
Guido van Rossumc334df52002-04-04 23:44:47 +00006694
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006695 if (pname != name) {
6696 /* Collect all slotdefs that match name into ptrs. */
6697 pname = name;
6698 pp = ptrs;
6699 for (p = slotdefs; p->name_strobj; p++) {
6700 if (p->name_strobj == name)
6701 *pp++ = p;
6702 }
6703 *pp = NULL;
6704 }
Guido van Rossumc334df52002-04-04 23:44:47 +00006705
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006706 /* Look in all matching slots of the type; if exactly one of these has
6707 a filled-in slot, return its value. Otherwise return NULL. */
6708 res = NULL;
6709 for (pp = ptrs; *pp; pp++) {
6710 ptr = slotptr(type, (*pp)->offset);
6711 if (ptr == NULL || *ptr == NULL)
6712 continue;
6713 if (res != NULL)
6714 return NULL;
6715 res = ptr;
6716 }
6717 return res;
Guido van Rossumc334df52002-04-04 23:44:47 +00006718}
6719
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006720/* Common code for update_slots_callback() and fixup_slot_dispatchers(). This
Guido van Rossumc334df52002-04-04 23:44:47 +00006721 does some incredibly complex thinking and then sticks something into the
6722 slot. (It sees if the adjacent slotdefs for the same slot have conflicting
6723 interests, and then stores a generic wrapper or a specific function into
6724 the slot.) Return a pointer to the next slotdef with a different offset,
6725 because that's convenient for fixup_slot_dispatchers(). */
6726static slotdef *
6727update_one_slot(PyTypeObject *type, slotdef *p)
6728{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006729 PyObject *descr;
6730 PyWrapperDescrObject *d;
6731 void *generic = NULL, *specific = NULL;
6732 int use_generic = 0;
6733 int offset = p->offset;
6734 void **ptr = slotptr(type, offset);
Guido van Rossumc334df52002-04-04 23:44:47 +00006735
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006736 if (ptr == NULL) {
6737 do {
6738 ++p;
6739 } while (p->offset == offset);
6740 return p;
6741 }
6742 do {
6743 descr = _PyType_Lookup(type, p->name_strobj);
6744 if (descr == NULL) {
6745 if (ptr == (void**)&type->tp_iternext) {
Trent Nelsonab02db22012-09-18 21:58:03 -04006746 specific = (void *)_PyObject_NextNotImplemented;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006747 }
6748 continue;
6749 }
Benjamin Peterson7b166872012-04-24 11:06:25 -04006750 if (Py_TYPE(descr) == &PyWrapperDescr_Type &&
6751 ((PyWrapperDescrObject *)descr)->d_base->name_strobj == p->name_strobj) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006752 void **tptr = resolve_slotdups(type, p->name_strobj);
6753 if (tptr == NULL || tptr == ptr)
6754 generic = p->function;
6755 d = (PyWrapperDescrObject *)descr;
6756 if (d->d_base->wrapper == p->wrapper &&
6757 PyType_IsSubtype(type, PyDescr_TYPE(d)))
6758 {
6759 if (specific == NULL ||
6760 specific == d->d_wrapped)
6761 specific = d->d_wrapped;
6762 else
6763 use_generic = 1;
6764 }
6765 }
6766 else if (Py_TYPE(descr) == &PyCFunction_Type &&
6767 PyCFunction_GET_FUNCTION(descr) ==
6768 (PyCFunction)tp_new_wrapper &&
6769 ptr == (void**)&type->tp_new)
6770 {
6771 /* The __new__ wrapper is not a wrapper descriptor,
6772 so must be special-cased differently.
6773 If we don't do this, creating an instance will
6774 always use slot_tp_new which will look up
6775 __new__ in the MRO which will call tp_new_wrapper
6776 which will look through the base classes looking
6777 for a static base and call its tp_new (usually
6778 PyType_GenericNew), after performing various
6779 sanity checks and constructing a new argument
6780 list. Cut all that nonsense short -- this speeds
6781 up instance creation tremendously. */
6782 specific = (void *)type->tp_new;
6783 /* XXX I'm not 100% sure that there isn't a hole
6784 in this reasoning that requires additional
6785 sanity checks. I'll buy the first person to
6786 point out a bug in this reasoning a beer. */
6787 }
6788 else if (descr == Py_None &&
6789 ptr == (void**)&type->tp_hash) {
6790 /* We specifically allow __hash__ to be set to None
6791 to prevent inheritance of the default
6792 implementation from object.__hash__ */
Trent Nelsonab02db22012-09-18 21:58:03 -04006793 specific = (void *)PyObject_HashNotImplemented;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006794 }
6795 else {
6796 use_generic = 1;
6797 generic = p->function;
6798 }
6799 } while ((++p)->offset == offset);
6800 if (specific && !use_generic)
6801 *ptr = specific;
6802 else
6803 *ptr = generic;
6804 return p;
Guido van Rossumc334df52002-04-04 23:44:47 +00006805}
6806
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006807/* In the type, update the slots whose slotdefs are gathered in the pp array.
6808 This is a callback for update_subclasses(). */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006809static int
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006810update_slots_callback(PyTypeObject *type, void *data)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006811{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006812 slotdef **pp = (slotdef **)data;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006813
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006814 for (; *pp; pp++)
6815 update_one_slot(type, *pp);
6816 return 0;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006817}
6818
Martin v. Löwis996b6712014-07-26 16:44:07 +02006819static int slotdefs_initialized = 0;
Guido van Rossumc334df52002-04-04 23:44:47 +00006820/* Initialize the slotdefs table by adding interned string objects for the
Martin v. Löwis5b561502014-07-26 15:25:04 +02006821 names. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006822static void
Guido van Rossumd396b9c2001-10-13 20:02:41 +00006823init_slotdefs(void)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006824{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006825 slotdef *p;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006826
Martin v. Löwis996b6712014-07-26 16:44:07 +02006827 if (slotdefs_initialized)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006828 return;
6829 for (p = slotdefs; p->name; p++) {
Benjamin Peterson63952412013-04-01 17:41:41 -04006830 /* Slots must be ordered by their offset in the PyHeapTypeObject. */
6831 assert(!p[1].name || p->offset <= p[1].offset);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006832 p->name_strobj = PyUnicode_InternFromString(p->name);
6833 if (!p->name_strobj)
6834 Py_FatalError("Out of memory interning slotdef names");
6835 }
Martin v. Löwis996b6712014-07-26 16:44:07 +02006836 slotdefs_initialized = 1;
6837}
6838
6839/* Undo init_slotdefs, releasing the interned strings. */
Victor Stinner331a7262014-07-27 16:11:30 +02006840static void clear_slotdefs(void)
Martin v. Löwis996b6712014-07-26 16:44:07 +02006841{
6842 slotdef *p;
6843 for (p = slotdefs; p->name; p++) {
6844 Py_CLEAR(p->name_strobj);
6845 }
6846 slotdefs_initialized = 0;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006847}
6848
Guido van Rossumc334df52002-04-04 23:44:47 +00006849/* Update the slots after assignment to a class (type) attribute. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006850static int
6851update_slot(PyTypeObject *type, PyObject *name)
6852{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006853 slotdef *ptrs[MAX_EQUIV];
6854 slotdef *p;
6855 slotdef **pp;
6856 int offset;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006857
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006858 /* Clear the VALID_VERSION flag of 'type' and all its
6859 subclasses. This could possibly be unified with the
6860 update_subclasses() recursion below, but carefully:
6861 they each have their own conditions on which to stop
6862 recursing into subclasses. */
6863 PyType_Modified(type);
Christian Heimesa62da1d2008-01-12 19:39:10 +00006864
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006865 init_slotdefs();
6866 pp = ptrs;
6867 for (p = slotdefs; p->name; p++) {
6868 /* XXX assume name is interned! */
6869 if (p->name_strobj == name)
6870 *pp++ = p;
6871 }
6872 *pp = NULL;
6873 for (pp = ptrs; *pp; pp++) {
6874 p = *pp;
6875 offset = p->offset;
6876 while (p > slotdefs && (p-1)->offset == offset)
6877 --p;
6878 *pp = p;
6879 }
6880 if (ptrs[0] == NULL)
6881 return 0; /* Not an attribute that affects any slots */
6882 return update_subclasses(type, name,
6883 update_slots_callback, (void *)ptrs);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006884}
6885
Guido van Rossumc334df52002-04-04 23:44:47 +00006886/* Store the proper functions in the slot dispatches at class (type)
6887 definition time, based upon which operations the class overrides in its
6888 dict. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00006889static void
Guido van Rossum7b9144b2001-10-09 19:39:46 +00006890fixup_slot_dispatchers(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00006891{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006892 slotdef *p;
Tim Peters6d6c1a32001-08-02 04:15:00 +00006893
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006894 init_slotdefs();
6895 for (p = slotdefs; p->name; )
6896 p = update_one_slot(type, p);
Tim Peters6d6c1a32001-08-02 04:15:00 +00006897}
Guido van Rossum705f0f52001-08-24 16:47:00 +00006898
Michael W. Hudson98bbc492002-11-26 14:47:27 +00006899static void
6900update_all_slots(PyTypeObject* type)
6901{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006902 slotdef *p;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00006903
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006904 init_slotdefs();
6905 for (p = slotdefs; p->name; p++) {
6906 /* update_slot returns int but can't actually fail */
6907 update_slot(type, p->name_strobj);
6908 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +00006909}
6910
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006911/* recurse_down_subclasses() and update_subclasses() are mutually
6912 recursive functions to call a callback for all subclasses,
6913 but refraining from recursing into subclasses that define 'name'. */
6914
6915static int
6916update_subclasses(PyTypeObject *type, PyObject *name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006917 update_callback callback, void *data)
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006918{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006919 if (callback(type, data) < 0)
6920 return -1;
6921 return recurse_down_subclasses(type, name, callback, data);
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006922}
6923
6924static int
6925recurse_down_subclasses(PyTypeObject *type, PyObject *name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006926 update_callback callback, void *data)
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006927{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006928 PyTypeObject *subclass;
6929 PyObject *ref, *subclasses, *dict;
Antoine Pitrou84745ab2013-10-29 21:31:25 +01006930 Py_ssize_t i;
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006931
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006932 subclasses = type->tp_subclasses;
6933 if (subclasses == NULL)
6934 return 0;
Antoine Pitrou84745ab2013-10-29 21:31:25 +01006935 assert(PyDict_CheckExact(subclasses));
6936 i = 0;
6937 while (PyDict_Next(subclasses, &i, NULL, &ref)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006938 assert(PyWeakref_CheckRef(ref));
6939 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
6940 assert(subclass != NULL);
6941 if ((PyObject *)subclass == Py_None)
6942 continue;
6943 assert(PyType_Check(subclass));
6944 /* Avoid recursing down into unaffected classes */
6945 dict = subclass->tp_dict;
6946 if (dict != NULL && PyDict_Check(dict) &&
6947 PyDict_GetItem(dict, name) != NULL)
6948 continue;
6949 if (update_subclasses(subclass, name, callback, data) < 0)
6950 return -1;
6951 }
6952 return 0;
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006953}
6954
Guido van Rossum6d204072001-10-21 00:44:31 +00006955/* This function is called by PyType_Ready() to populate the type's
6956 dictionary with method descriptors for function slots. For each
Guido van Rossum09638c12002-06-13 19:17:46 +00006957 function slot (like tp_repr) that's defined in the type, one or more
6958 corresponding descriptors are added in the type's tp_dict dictionary
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006959 under the appropriate name (like __repr__). Some function slots
Guido van Rossum09638c12002-06-13 19:17:46 +00006960 cause more than one descriptor to be added (for example, the nb_add
6961 slot adds both __add__ and __radd__ descriptors) and some function
6962 slots compete for the same descriptor (for example both sq_item and
6963 mp_subscript generate a __getitem__ descriptor).
6964
Ezio Melotti13925002011-03-16 11:05:33 +02006965 In the latter case, the first slotdef entry encountered wins. Since
Tim Petersbf9b2442003-03-23 05:35:36 +00006966 slotdef entries are sorted by the offset of the slot in the
Guido van Rossume5c691a2003-03-07 15:13:17 +00006967 PyHeapTypeObject, this gives us some control over disambiguating
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006968 between competing slots: the members of PyHeapTypeObject are listed
6969 from most general to least general, so the most general slot is
6970 preferred. In particular, because as_mapping comes before as_sequence,
6971 for a type that defines both mp_subscript and sq_item, mp_subscript
6972 wins.
Guido van Rossum09638c12002-06-13 19:17:46 +00006973
6974 This only adds new descriptors and doesn't overwrite entries in
6975 tp_dict that were previously defined. The descriptors contain a
6976 reference to the C function they must call, so that it's safe if they
6977 are copied into a subtype's __dict__ and the subtype has a different
6978 C function in its slot -- calling the method defined by the
6979 descriptor will call the C function that was used to create it,
6980 rather than the C function present in the slot when it is called.
6981 (This is important because a subtype may have a C function in the
6982 slot that calls the method from the dictionary, and we want to avoid
6983 infinite recursion here.) */
Guido van Rossum6d204072001-10-21 00:44:31 +00006984
6985static int
6986add_operators(PyTypeObject *type)
6987{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006988 PyObject *dict = type->tp_dict;
6989 slotdef *p;
6990 PyObject *descr;
6991 void **ptr;
Guido van Rossum6d204072001-10-21 00:44:31 +00006992
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006993 init_slotdefs();
6994 for (p = slotdefs; p->name; p++) {
6995 if (p->wrapper == NULL)
6996 continue;
6997 ptr = slotptr(type, p->offset);
6998 if (!ptr || !*ptr)
6999 continue;
7000 if (PyDict_GetItem(dict, p->name_strobj))
7001 continue;
Trent Nelsonab02db22012-09-18 21:58:03 -04007002 if (*ptr == (void *)PyObject_HashNotImplemented) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007003 /* Classes may prevent the inheritance of the tp_hash
7004 slot by storing PyObject_HashNotImplemented in it. Make it
7005 visible as a None value for the __hash__ attribute. */
7006 if (PyDict_SetItem(dict, p->name_strobj, Py_None) < 0)
7007 return -1;
7008 }
7009 else {
7010 descr = PyDescr_NewWrapper(type, p, *ptr);
7011 if (descr == NULL)
7012 return -1;
7013 if (PyDict_SetItem(dict, p->name_strobj, descr) < 0)
7014 return -1;
7015 Py_DECREF(descr);
7016 }
7017 }
7018 if (type->tp_new != NULL) {
7019 if (add_tp_new_wrapper(type) < 0)
7020 return -1;
7021 }
7022 return 0;
Guido van Rossum6d204072001-10-21 00:44:31 +00007023}
7024
Guido van Rossum705f0f52001-08-24 16:47:00 +00007025
7026/* Cooperative 'super' */
7027
7028typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007029 PyObject_HEAD
7030 PyTypeObject *type;
7031 PyObject *obj;
7032 PyTypeObject *obj_type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00007033} superobject;
7034
Guido van Rossum6f799372001-09-20 20:46:19 +00007035static PyMemberDef super_members[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007036 {"__thisclass__", T_OBJECT, offsetof(superobject, type), READONLY,
7037 "the class invoking super()"},
7038 {"__self__", T_OBJECT, offsetof(superobject, obj), READONLY,
7039 "the instance invoking super(); may be None"},
7040 {"__self_class__", T_OBJECT, offsetof(superobject, obj_type), READONLY,
7041 "the type of the instance invoking super(); may be None"},
7042 {0}
Guido van Rossum41eb14d2001-08-30 23:13:11 +00007043};
7044
Guido van Rossum705f0f52001-08-24 16:47:00 +00007045static void
7046super_dealloc(PyObject *self)
7047{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007048 superobject *su = (superobject *)self;
Guido van Rossum705f0f52001-08-24 16:47:00 +00007049
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007050 _PyObject_GC_UNTRACK(self);
7051 Py_XDECREF(su->obj);
7052 Py_XDECREF(su->type);
7053 Py_XDECREF(su->obj_type);
7054 Py_TYPE(self)->tp_free(self);
Guido van Rossum705f0f52001-08-24 16:47:00 +00007055}
7056
7057static PyObject *
Guido van Rossum41eb14d2001-08-30 23:13:11 +00007058super_repr(PyObject *self)
7059{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007060 superobject *su = (superobject *)self;
Guido van Rossum41eb14d2001-08-30 23:13:11 +00007061
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007062 if (su->obj_type)
7063 return PyUnicode_FromFormat(
7064 "<super: <class '%s'>, <%s object>>",
7065 su->type ? su->type->tp_name : "NULL",
7066 su->obj_type->tp_name);
7067 else
7068 return PyUnicode_FromFormat(
7069 "<super: <class '%s'>, NULL>",
7070 su->type ? su->type->tp_name : "NULL");
Guido van Rossum41eb14d2001-08-30 23:13:11 +00007071}
7072
7073static PyObject *
Guido van Rossum705f0f52001-08-24 16:47:00 +00007074super_getattro(PyObject *self, PyObject *name)
7075{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007076 superobject *su = (superobject *)self;
Benjamin Peterson104b9e02015-02-05 22:29:14 -05007077 PyTypeObject *starttype;
7078 PyObject *mro;
7079 Py_ssize_t i, n;
Guido van Rossum705f0f52001-08-24 16:47:00 +00007080
Benjamin Peterson104b9e02015-02-05 22:29:14 -05007081 starttype = su->obj_type;
7082 if (starttype == NULL)
7083 goto skip;
7084
7085 /* We want __class__ to return the class of the super object
7086 (i.e. super, or a subclass), not the class of su->obj. */
7087 if (PyUnicode_Check(name) &&
7088 PyUnicode_GET_LENGTH(name) == 9 &&
7089 _PyUnicode_CompareWithId(name, &PyId___class__) == 0)
7090 goto skip;
7091
7092 mro = starttype->tp_mro;
7093 if (mro == NULL)
7094 goto skip;
7095
7096 assert(PyTuple_Check(mro));
7097 n = PyTuple_GET_SIZE(mro);
7098
7099 /* No need to check the last one: it's gonna be skipped anyway. */
7100 for (i = 0; i+1 < n; i++) {
7101 if ((PyObject *)(su->type) == PyTuple_GET_ITEM(mro, i))
7102 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007103 }
Benjamin Peterson104b9e02015-02-05 22:29:14 -05007104 i++; /* skip su->type (if any) */
7105 if (i >= n)
7106 goto skip;
Guido van Rossum76ba09f2003-04-16 19:40:58 +00007107
Benjamin Peterson104b9e02015-02-05 22:29:14 -05007108 /* keep a strong reference to mro because starttype->tp_mro can be
7109 replaced during PyDict_GetItem(dict, name) */
7110 Py_INCREF(mro);
7111 do {
7112 PyObject *res, *tmp, *dict;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007113 descrgetfunc f;
Guido van Rossum705f0f52001-08-24 16:47:00 +00007114
Benjamin Peterson104b9e02015-02-05 22:29:14 -05007115 tmp = PyTuple_GET_ITEM(mro, i);
7116 assert(PyType_Check(tmp));
Guido van Rossum155db9a2002-04-02 17:53:47 +00007117
Benjamin Peterson104b9e02015-02-05 22:29:14 -05007118 dict = ((PyTypeObject *)tmp)->tp_dict;
7119 assert(dict != NULL && PyDict_Check(dict));
7120
7121 res = PyDict_GetItem(dict, name);
7122 if (res != NULL) {
7123 Py_INCREF(res);
7124
7125 f = Py_TYPE(res)->tp_descr_get;
7126 if (f != NULL) {
7127 tmp = f(res,
7128 /* Only pass 'obj' param if this is instance-mode super
7129 (See SF ID #743627) */
7130 (su->obj == (PyObject *)starttype) ? NULL : su->obj,
7131 (PyObject *)starttype);
7132 Py_DECREF(res);
7133 res = tmp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007134 }
Benjamin Peterson104b9e02015-02-05 22:29:14 -05007135
7136 Py_DECREF(mro);
7137 return res;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007138 }
Benjamin Peterson104b9e02015-02-05 22:29:14 -05007139
7140 i++;
7141 } while (i < n);
7142 Py_DECREF(mro);
7143
7144 skip:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007145 return PyObject_GenericGetAttr(self, name);
Guido van Rossum705f0f52001-08-24 16:47:00 +00007146}
7147
Guido van Rossuma89d10e2003-02-12 03:58:38 +00007148static PyTypeObject *
Guido van Rossum5b443c62001-12-03 15:38:28 +00007149supercheck(PyTypeObject *type, PyObject *obj)
7150{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007151 /* Check that a super() call makes sense. Return a type object.
Guido van Rossuma89d10e2003-02-12 03:58:38 +00007152
Florent Xiclunaaa6c1d22011-12-12 18:54:29 +01007153 obj can be a class, or an instance of one:
Guido van Rossuma89d10e2003-02-12 03:58:38 +00007154
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007155 - If it is a class, it must be a subclass of 'type'. This case is
7156 used for class methods; the return value is obj.
Guido van Rossuma89d10e2003-02-12 03:58:38 +00007157
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007158 - If it is an instance, it must be an instance of 'type'. This is
7159 the normal case; the return value is obj.__class__.
Guido van Rossuma89d10e2003-02-12 03:58:38 +00007160
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007161 But... when obj is an instance, we want to allow for the case where
7162 Py_TYPE(obj) is not a subclass of type, but obj.__class__ is!
7163 This will allow using super() with a proxy for obj.
7164 */
Guido van Rossuma89d10e2003-02-12 03:58:38 +00007165
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007166 /* Check for first bullet above (special case) */
7167 if (PyType_Check(obj) && PyType_IsSubtype((PyTypeObject *)obj, type)) {
7168 Py_INCREF(obj);
7169 return (PyTypeObject *)obj;
7170 }
Guido van Rossum8e80a722003-02-18 19:22:22 +00007171
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007172 /* Normal case */
7173 if (PyType_IsSubtype(Py_TYPE(obj), type)) {
7174 Py_INCREF(Py_TYPE(obj));
7175 return Py_TYPE(obj);
7176 }
7177 else {
7178 /* Try the slow way */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007179 PyObject *class_attr;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00007180
Martin v. Löwisbfc6d742011-10-13 20:03:57 +02007181 class_attr = _PyObject_GetAttrId(obj, &PyId___class__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007182 if (class_attr != NULL &&
7183 PyType_Check(class_attr) &&
7184 (PyTypeObject *)class_attr != Py_TYPE(obj))
7185 {
7186 int ok = PyType_IsSubtype(
7187 (PyTypeObject *)class_attr, type);
7188 if (ok)
7189 return (PyTypeObject *)class_attr;
7190 }
Guido van Rossuma89d10e2003-02-12 03:58:38 +00007191
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007192 if (class_attr == NULL)
7193 PyErr_Clear();
7194 else
7195 Py_DECREF(class_attr);
7196 }
Guido van Rossuma89d10e2003-02-12 03:58:38 +00007197
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007198 PyErr_SetString(PyExc_TypeError,
7199 "super(type, obj): "
7200 "obj must be an instance or subtype of type");
7201 return NULL;
Guido van Rossum5b443c62001-12-03 15:38:28 +00007202}
7203
Guido van Rossum705f0f52001-08-24 16:47:00 +00007204static PyObject *
7205super_descr_get(PyObject *self, PyObject *obj, PyObject *type)
7206{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007207 superobject *su = (superobject *)self;
7208 superobject *newobj;
Guido van Rossum705f0f52001-08-24 16:47:00 +00007209
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007210 if (obj == NULL || obj == Py_None || su->obj != NULL) {
7211 /* Not binding to an object, or already bound */
7212 Py_INCREF(self);
7213 return self;
7214 }
7215 if (Py_TYPE(su) != &PySuper_Type)
7216 /* If su is an instance of a (strict) subclass of super,
7217 call its type */
7218 return PyObject_CallFunctionObjArgs((PyObject *)Py_TYPE(su),
7219 su->type, obj, NULL);
7220 else {
7221 /* Inline the common case */
7222 PyTypeObject *obj_type = supercheck(su->type, obj);
7223 if (obj_type == NULL)
7224 return NULL;
7225 newobj = (superobject *)PySuper_Type.tp_new(&PySuper_Type,
7226 NULL, NULL);
7227 if (newobj == NULL)
7228 return NULL;
7229 Py_INCREF(su->type);
7230 Py_INCREF(obj);
7231 newobj->type = su->type;
7232 newobj->obj = obj;
7233 newobj->obj_type = obj_type;
7234 return (PyObject *)newobj;
7235 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00007236}
7237
7238static int
7239super_init(PyObject *self, PyObject *args, PyObject *kwds)
7240{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007241 superobject *su = (superobject *)self;
7242 PyTypeObject *type = NULL;
7243 PyObject *obj = NULL;
7244 PyTypeObject *obj_type = NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00007245
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007246 if (!_PyArg_NoKeywords("super", kwds))
7247 return -1;
7248 if (!PyArg_ParseTuple(args, "|O!O:super", &PyType_Type, &type, &obj))
7249 return -1;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00007250
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007251 if (type == NULL) {
7252 /* Call super(), without args -- fill in from __class__
7253 and first local variable on the stack. */
Victor Stinner1c6970f2014-05-13 01:32:36 +02007254 PyFrameObject *f;
7255 PyCodeObject *co;
Victor Stinner0fcab4a2011-01-04 12:59:15 +00007256 Py_ssize_t i, n;
Victor Stinner1c6970f2014-05-13 01:32:36 +02007257 f = PyThreadState_GET()->frame;
7258 if (f == NULL) {
7259 PyErr_SetString(PyExc_RuntimeError,
7260 "super(): no current frame");
7261 return -1;
7262 }
7263 co = f->f_code;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007264 if (co == NULL) {
Benjamin Peterson6a42bd62012-09-01 23:04:38 -04007265 PyErr_SetString(PyExc_RuntimeError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007266 "super(): no code object");
7267 return -1;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00007268 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007269 if (co->co_argcount == 0) {
Benjamin Peterson6a42bd62012-09-01 23:04:38 -04007270 PyErr_SetString(PyExc_RuntimeError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007271 "super(): no arguments");
7272 return -1;
7273 }
7274 obj = f->f_localsplus[0];
Benjamin Peterson159ae412013-05-12 18:16:06 -05007275 if (obj == NULL && co->co_cell2arg) {
7276 /* The first argument might be a cell. */
7277 n = PyTuple_GET_SIZE(co->co_cellvars);
7278 for (i = 0; i < n; i++) {
7279 if (co->co_cell2arg[i] == 0) {
7280 PyObject *cell = f->f_localsplus[co->co_nlocals + i];
7281 assert(PyCell_Check(cell));
7282 obj = PyCell_GET(cell);
7283 break;
7284 }
7285 }
Guido van Rossum6832c812013-05-10 08:47:42 -07007286 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007287 if (obj == NULL) {
Benjamin Peterson6a42bd62012-09-01 23:04:38 -04007288 PyErr_SetString(PyExc_RuntimeError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007289 "super(): arg[0] deleted");
7290 return -1;
7291 }
7292 if (co->co_freevars == NULL)
7293 n = 0;
7294 else {
7295 assert(PyTuple_Check(co->co_freevars));
7296 n = PyTuple_GET_SIZE(co->co_freevars);
7297 }
7298 for (i = 0; i < n; i++) {
7299 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
7300 assert(PyUnicode_Check(name));
Victor Stinnerad14ccd2013-11-07 00:46:04 +01007301 if (!_PyUnicode_CompareWithId(name, &PyId___class__)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007302 Py_ssize_t index = co->co_nlocals +
7303 PyTuple_GET_SIZE(co->co_cellvars) + i;
7304 PyObject *cell = f->f_localsplus[index];
7305 if (cell == NULL || !PyCell_Check(cell)) {
Benjamin Peterson6a42bd62012-09-01 23:04:38 -04007306 PyErr_SetString(PyExc_RuntimeError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007307 "super(): bad __class__ cell");
7308 return -1;
7309 }
7310 type = (PyTypeObject *) PyCell_GET(cell);
7311 if (type == NULL) {
Benjamin Peterson6a42bd62012-09-01 23:04:38 -04007312 PyErr_SetString(PyExc_RuntimeError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007313 "super(): empty __class__ cell");
7314 return -1;
7315 }
7316 if (!PyType_Check(type)) {
Benjamin Peterson6a42bd62012-09-01 23:04:38 -04007317 PyErr_Format(PyExc_RuntimeError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007318 "super(): __class__ is not a type (%s)",
7319 Py_TYPE(type)->tp_name);
7320 return -1;
7321 }
7322 break;
7323 }
7324 }
7325 if (type == NULL) {
Benjamin Peterson6a42bd62012-09-01 23:04:38 -04007326 PyErr_SetString(PyExc_RuntimeError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007327 "super(): __class__ cell not found");
7328 return -1;
7329 }
7330 }
Guido van Rossumcd16bf62007-06-13 18:07:49 +00007331
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007332 if (obj == Py_None)
7333 obj = NULL;
7334 if (obj != NULL) {
7335 obj_type = supercheck(type, obj);
7336 if (obj_type == NULL)
7337 return -1;
7338 Py_INCREF(obj);
7339 }
7340 Py_INCREF(type);
7341 su->type = type;
7342 su->obj = obj;
7343 su->obj_type = obj_type;
7344 return 0;
Guido van Rossum705f0f52001-08-24 16:47:00 +00007345}
7346
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007347PyDoc_STRVAR(super_doc,
Guido van Rossumcd16bf62007-06-13 18:07:49 +00007348"super() -> same as super(__class__, <first argument>)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00007349"super(type) -> unbound super object\n"
7350"super(type, obj) -> bound super object; requires isinstance(obj, type)\n"
Guido van Rossume705ef12001-08-29 15:47:06 +00007351"super(type, type2) -> bound super object; requires issubclass(type2, type)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00007352"Typical use to call a cooperative superclass method:\n"
7353"class C(B):\n"
7354" def meth(self, arg):\n"
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007355" super().meth(arg)\n"
Guido van Rossumcd16bf62007-06-13 18:07:49 +00007356"This works for class methods too:\n"
7357"class C(B):\n"
7358" @classmethod\n"
7359" def cmeth(cls, arg):\n"
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007360" super().cmeth(arg)\n");
Guido van Rossum705f0f52001-08-24 16:47:00 +00007361
Guido van Rossum048eb752001-10-02 21:24:57 +00007362static int
7363super_traverse(PyObject *self, visitproc visit, void *arg)
7364{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007365 superobject *su = (superobject *)self;
Guido van Rossum048eb752001-10-02 21:24:57 +00007366
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007367 Py_VISIT(su->obj);
7368 Py_VISIT(su->type);
7369 Py_VISIT(su->obj_type);
Guido van Rossum048eb752001-10-02 21:24:57 +00007370
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007371 return 0;
Guido van Rossum048eb752001-10-02 21:24:57 +00007372}
7373
Guido van Rossum705f0f52001-08-24 16:47:00 +00007374PyTypeObject PySuper_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007375 PyVarObject_HEAD_INIT(&PyType_Type, 0)
7376 "super", /* tp_name */
7377 sizeof(superobject), /* tp_basicsize */
7378 0, /* tp_itemsize */
7379 /* methods */
7380 super_dealloc, /* tp_dealloc */
7381 0, /* tp_print */
7382 0, /* tp_getattr */
7383 0, /* tp_setattr */
7384 0, /* tp_reserved */
7385 super_repr, /* tp_repr */
7386 0, /* tp_as_number */
7387 0, /* tp_as_sequence */
7388 0, /* tp_as_mapping */
7389 0, /* tp_hash */
7390 0, /* tp_call */
7391 0, /* tp_str */
7392 super_getattro, /* tp_getattro */
7393 0, /* tp_setattro */
7394 0, /* tp_as_buffer */
7395 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
7396 Py_TPFLAGS_BASETYPE, /* tp_flags */
7397 super_doc, /* tp_doc */
7398 super_traverse, /* tp_traverse */
7399 0, /* tp_clear */
7400 0, /* tp_richcompare */
7401 0, /* tp_weaklistoffset */
7402 0, /* tp_iter */
7403 0, /* tp_iternext */
7404 0, /* tp_methods */
7405 super_members, /* tp_members */
7406 0, /* tp_getset */
7407 0, /* tp_base */
7408 0, /* tp_dict */
7409 super_descr_get, /* tp_descr_get */
7410 0, /* tp_descr_set */
7411 0, /* tp_dictoffset */
7412 super_init, /* tp_init */
7413 PyType_GenericAlloc, /* tp_alloc */
7414 PyType_GenericNew, /* tp_new */
7415 PyObject_GC_Del, /* tp_free */
Guido van Rossum705f0f52001-08-24 16:47:00 +00007416};