blob: 7438dedfa62ff839a24f409fc346bf182239da9d [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
Benjamin Peterson7d95e402012-04-23 11:24:50 -040017#define MCACHE_SIZE_EXP 9
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000018#define MCACHE_HASH(version, name_hash) \
19 (((unsigned int)(version) * (unsigned int)(name_hash)) \
20 >> (8*sizeof(unsigned int) - MCACHE_SIZE_EXP))
Christian Heimesa62da1d2008-01-12 19:39:10 +000021#define MCACHE_HASH_METHOD(type, name) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000022 MCACHE_HASH((type)->tp_version_tag, \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020023 ((PyASCIIObject *)(name))->hash)
Christian Heimesa62da1d2008-01-12 19:39:10 +000024#define MCACHE_CACHEABLE_NAME(name) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000025 PyUnicode_CheckExact(name) && \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020026 PyUnicode_READY(name) != -1 && \
27 PyUnicode_GET_LENGTH(name) <= MCACHE_MAX_ATTR_SIZE
Christian Heimesa62da1d2008-01-12 19:39:10 +000028
29struct method_cache_entry {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000030 unsigned int version;
31 PyObject *name; /* reference to exactly a str or None */
32 PyObject *value; /* borrowed */
Christian Heimesa62da1d2008-01-12 19:39:10 +000033};
34
35static struct method_cache_entry method_cache[1 << MCACHE_SIZE_EXP];
36static unsigned int next_version_tag = 0;
Christian Heimes26855632008-01-27 23:50:43 +000037
Martin v. Löwise75fc142013-11-07 18:46:53 +010038/* alphabetical order */
39_Py_IDENTIFIER(__abstractmethods__);
Martin v. Löwisbd928fe2011-10-14 10:20:37 +020040_Py_IDENTIFIER(__class__);
Martin v. Löwise75fc142013-11-07 18:46:53 +010041_Py_IDENTIFIER(__delitem__);
Victor Stinner3c1e4812012-03-26 22:10:51 +020042_Py_IDENTIFIER(__dict__);
43_Py_IDENTIFIER(__doc__);
Victor Stinner3c1e4812012-03-26 22:10:51 +020044_Py_IDENTIFIER(__getattribute__);
Martin v. Löwise75fc142013-11-07 18:46:53 +010045_Py_IDENTIFIER(__getitem__);
Victor Stinner3c1e4812012-03-26 22:10:51 +020046_Py_IDENTIFIER(__hash__);
Martin v. Löwise75fc142013-11-07 18:46:53 +010047_Py_IDENTIFIER(__len__);
Victor Stinner3c1e4812012-03-26 22:10:51 +020048_Py_IDENTIFIER(__module__);
49_Py_IDENTIFIER(__name__);
50_Py_IDENTIFIER(__new__);
Martin v. Löwise75fc142013-11-07 18:46:53 +010051_Py_IDENTIFIER(__setitem__);
Victor Stinnerbd303c12013-11-07 23:07:29 +010052_Py_IDENTIFIER(builtins);
Victor Stinner3c1e4812012-03-26 22:10:51 +020053
54static PyObject *
Martin v. Löwis9c564092012-06-23 23:20:45 +020055slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
56
Martin v. Löwis996b6712014-07-26 16:44:07 +020057static void
Victor Stinner331a7262014-07-27 16:11:30 +020058clear_slotdefs(void);
Martin v. Löwis996b6712014-07-26 16:44:07 +020059
Larry Hastings5c661892014-01-24 06:17:25 -080060/*
Larry Hastings2623c8c2014-02-08 22:15:29 -080061 * finds the beginning of the docstring's introspection signature.
Larry Hastings5c661892014-01-24 06:17:25 -080062 * if present, returns a pointer pointing to the first '('.
63 * otherwise returns NULL.
Larry Hastings2623c8c2014-02-08 22:15:29 -080064 *
65 * doesn't guarantee that the signature is valid, only that it
66 * has a valid prefix. (the signature must also pass skip_signature.)
Larry Hastings5c661892014-01-24 06:17:25 -080067 */
68static const char *
Larry Hastings2623c8c2014-02-08 22:15:29 -080069find_signature(const char *name, const char *doc)
Larry Hastings5c661892014-01-24 06:17:25 -080070{
Larry Hastings2623c8c2014-02-08 22:15:29 -080071 const char *dot;
72 size_t length;
73
74 if (!doc)
75 return NULL;
76
77 assert(name != NULL);
78
79 /* for dotted names like classes, only use the last component */
80 dot = strrchr(name, '.');
81 if (dot)
82 name = dot + 1;
83
84 length = strlen(name);
85 if (strncmp(doc, name, length))
86 return NULL;
87 doc += length;
88 if (*doc != '(')
89 return NULL;
90 return doc;
Larry Hastings5c661892014-01-24 06:17:25 -080091}
92
Larry Hastings2623c8c2014-02-08 22:15:29 -080093#define SIGNATURE_END_MARKER ")\n--\n\n"
94#define SIGNATURE_END_MARKER_LENGTH 6
Larry Hastings5c661892014-01-24 06:17:25 -080095/*
Larry Hastings2623c8c2014-02-08 22:15:29 -080096 * skips past the end of the docstring's instrospection signature.
97 * (assumes doc starts with a valid signature prefix.)
Larry Hastings5c661892014-01-24 06:17:25 -080098 */
99static const char *
100skip_signature(const char *doc)
101{
Larry Hastings2623c8c2014-02-08 22:15:29 -0800102 while (*doc) {
103 if ((*doc == *SIGNATURE_END_MARKER) &&
104 !strncmp(doc, SIGNATURE_END_MARKER, SIGNATURE_END_MARKER_LENGTH))
105 return doc + SIGNATURE_END_MARKER_LENGTH;
106 if ((*doc == '\n') && (doc[1] == '\n'))
107 return NULL;
Larry Hastings5c661892014-01-24 06:17:25 -0800108 doc++;
Larry Hastings2623c8c2014-02-08 22:15:29 -0800109 }
110 return NULL;
Larry Hastings5c661892014-01-24 06:17:25 -0800111}
112
113static const char *
Larry Hastings2623c8c2014-02-08 22:15:29 -0800114_PyType_DocWithoutSignature(const char *name, const char *internal_doc)
Larry Hastings5c661892014-01-24 06:17:25 -0800115{
Larry Hastings2623c8c2014-02-08 22:15:29 -0800116 const char *doc = find_signature(name, internal_doc);
Larry Hastings5c661892014-01-24 06:17:25 -0800117
Larry Hastings2623c8c2014-02-08 22:15:29 -0800118 if (doc) {
119 doc = skip_signature(doc);
120 if (doc)
121 return doc;
122 }
Larry Hastings5c661892014-01-24 06:17:25 -0800123 return internal_doc;
124}
125
126PyObject *
Larry Hastings2623c8c2014-02-08 22:15:29 -0800127_PyType_GetDocFromInternalDoc(const char *name, const char *internal_doc)
Larry Hastings5c661892014-01-24 06:17:25 -0800128{
Larry Hastings2623c8c2014-02-08 22:15:29 -0800129 const char *doc = _PyType_DocWithoutSignature(name, internal_doc);
Larry Hastings5c661892014-01-24 06:17:25 -0800130
131 if (!doc) {
132 Py_INCREF(Py_None);
133 return Py_None;
134 }
135
136 return PyUnicode_FromString(doc);
137}
138
139PyObject *
Larry Hastings2623c8c2014-02-08 22:15:29 -0800140_PyType_GetTextSignatureFromInternalDoc(const char *name, const char *internal_doc)
Larry Hastings5c661892014-01-24 06:17:25 -0800141{
Larry Hastings2623c8c2014-02-08 22:15:29 -0800142 const char *start = find_signature(name, internal_doc);
143 const char *end;
Larry Hastings5c661892014-01-24 06:17:25 -0800144
Larry Hastings2623c8c2014-02-08 22:15:29 -0800145 if (start)
146 end = skip_signature(start);
147 else
148 end = NULL;
149 if (!end) {
Larry Hastings5c661892014-01-24 06:17:25 -0800150 Py_INCREF(Py_None);
151 return Py_None;
152 }
153
Larry Hastings2623c8c2014-02-08 22:15:29 -0800154 /* back "end" up until it points just past the final ')' */
155 end -= SIGNATURE_END_MARKER_LENGTH - 1;
156 assert((end - start) >= 2); /* should be "()" at least */
157 assert(end[-1] == ')');
158 assert(end[0] == '\n');
159 return PyUnicode_FromStringAndSize(start, end - start);
Larry Hastings5c661892014-01-24 06:17:25 -0800160}
161
Christian Heimes26855632008-01-27 23:50:43 +0000162unsigned int
163PyType_ClearCache(void)
164{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000165 Py_ssize_t i;
166 unsigned int cur_version_tag = next_version_tag - 1;
167
168 for (i = 0; i < (1 << MCACHE_SIZE_EXP); i++) {
169 method_cache[i].version = 0;
170 Py_CLEAR(method_cache[i].name);
171 method_cache[i].value = NULL;
172 }
173 next_version_tag = 0;
174 /* mark all version tags as invalid */
175 PyType_Modified(&PyBaseObject_Type);
176 return cur_version_tag;
Christian Heimes26855632008-01-27 23:50:43 +0000177}
Christian Heimesa62da1d2008-01-12 19:39:10 +0000178
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000179void
Antoine Pitrou957a23b2013-05-04 20:45:02 +0200180_PyType_Fini(void)
181{
182 PyType_ClearCache();
Martin v. Löwis996b6712014-07-26 16:44:07 +0200183 clear_slotdefs();
Antoine Pitrou957a23b2013-05-04 20:45:02 +0200184}
185
186void
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000187PyType_Modified(PyTypeObject *type)
Christian Heimesa62da1d2008-01-12 19:39:10 +0000188{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000189 /* Invalidate any cached data for the specified type and all
190 subclasses. This function is called after the base
191 classes, mro, or attributes of the type are altered.
Christian Heimesa62da1d2008-01-12 19:39:10 +0000192
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000193 Invariants:
Christian Heimesa62da1d2008-01-12 19:39:10 +0000194
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000195 - Py_TPFLAGS_VALID_VERSION_TAG is never set if
196 Py_TPFLAGS_HAVE_VERSION_TAG is not set (e.g. on type
197 objects coming from non-recompiled extension modules)
Christian Heimesa62da1d2008-01-12 19:39:10 +0000198
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000199 - before Py_TPFLAGS_VALID_VERSION_TAG can be set on a type,
200 it must first be set on all super types.
Christian Heimesa62da1d2008-01-12 19:39:10 +0000201
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000202 This function clears the Py_TPFLAGS_VALID_VERSION_TAG of a
203 type (so it must first clear it on all subclasses). The
204 tp_version_tag value is meaningless unless this flag is set.
205 We don't assign new version tags eagerly, but only as
206 needed.
207 */
208 PyObject *raw, *ref;
Antoine Pitrou84745ab2013-10-29 21:31:25 +0100209 Py_ssize_t i;
Christian Heimesa62da1d2008-01-12 19:39:10 +0000210
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000211 if (!PyType_HasFeature(type, Py_TPFLAGS_VALID_VERSION_TAG))
212 return;
Christian Heimesa62da1d2008-01-12 19:39:10 +0000213
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000214 raw = type->tp_subclasses;
215 if (raw != NULL) {
Antoine Pitrou84745ab2013-10-29 21:31:25 +0100216 assert(PyDict_CheckExact(raw));
217 i = 0;
218 while (PyDict_Next(raw, &i, NULL, &ref)) {
219 assert(PyWeakref_CheckRef(ref));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000220 ref = PyWeakref_GET_OBJECT(ref);
221 if (ref != Py_None) {
222 PyType_Modified((PyTypeObject *)ref);
223 }
224 }
225 }
226 type->tp_flags &= ~Py_TPFLAGS_VALID_VERSION_TAG;
Christian Heimesa62da1d2008-01-12 19:39:10 +0000227}
228
229static void
230type_mro_modified(PyTypeObject *type, PyObject *bases) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000231 /*
Florent Xiclunaaa6c1d22011-12-12 18:54:29 +0100232 Check that all base classes or elements of the MRO of type are
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000233 able to be cached. This function is called after the base
234 classes or mro of the type are altered.
Christian Heimesa62da1d2008-01-12 19:39:10 +0000235
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000236 Unset HAVE_VERSION_TAG and VALID_VERSION_TAG if the type
Florent Xiclunaaa6c1d22011-12-12 18:54:29 +0100237 has a custom MRO that includes a type which is not officially
238 super type.
Christian Heimesa62da1d2008-01-12 19:39:10 +0000239
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000240 Called from mro_internal, which will subsequently be called on
241 each subclass when their mro is recursively updated.
242 */
243 Py_ssize_t i, n;
244 int clear = 0;
Christian Heimesa62da1d2008-01-12 19:39:10 +0000245
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000246 if (!PyType_HasFeature(type, Py_TPFLAGS_HAVE_VERSION_TAG))
247 return;
Christian Heimesa62da1d2008-01-12 19:39:10 +0000248
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000249 n = PyTuple_GET_SIZE(bases);
250 for (i = 0; i < n; i++) {
251 PyObject *b = PyTuple_GET_ITEM(bases, i);
252 PyTypeObject *cls;
Christian Heimesa62da1d2008-01-12 19:39:10 +0000253
Florent Xiclunaaa6c1d22011-12-12 18:54:29 +0100254 assert(PyType_Check(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000255 cls = (PyTypeObject *)b;
Christian Heimesa62da1d2008-01-12 19:39:10 +0000256
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000257 if (!PyType_HasFeature(cls, Py_TPFLAGS_HAVE_VERSION_TAG) ||
258 !PyType_IsSubtype(type, cls)) {
259 clear = 1;
260 break;
261 }
262 }
Christian Heimesa62da1d2008-01-12 19:39:10 +0000263
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000264 if (clear)
265 type->tp_flags &= ~(Py_TPFLAGS_HAVE_VERSION_TAG|
266 Py_TPFLAGS_VALID_VERSION_TAG);
Christian Heimesa62da1d2008-01-12 19:39:10 +0000267}
268
269static int
270assign_version_tag(PyTypeObject *type)
271{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000272 /* Ensure that the tp_version_tag is valid and set
273 Py_TPFLAGS_VALID_VERSION_TAG. To respect the invariant, this
274 must first be done on all super classes. Return 0 if this
275 cannot be done, 1 if Py_TPFLAGS_VALID_VERSION_TAG.
276 */
277 Py_ssize_t i, n;
278 PyObject *bases;
Christian Heimesa62da1d2008-01-12 19:39:10 +0000279
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000280 if (PyType_HasFeature(type, Py_TPFLAGS_VALID_VERSION_TAG))
281 return 1;
282 if (!PyType_HasFeature(type, Py_TPFLAGS_HAVE_VERSION_TAG))
283 return 0;
284 if (!PyType_HasFeature(type, Py_TPFLAGS_READY))
285 return 0;
Christian Heimesa62da1d2008-01-12 19:39:10 +0000286
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000287 type->tp_version_tag = next_version_tag++;
288 /* for stress-testing: next_version_tag &= 0xFF; */
Christian Heimesa62da1d2008-01-12 19:39:10 +0000289
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000290 if (type->tp_version_tag == 0) {
291 /* wrap-around or just starting Python - clear the whole
292 cache by filling names with references to Py_None.
293 Values are also set to NULL for added protection, as they
294 are borrowed reference */
295 for (i = 0; i < (1 << MCACHE_SIZE_EXP); i++) {
296 method_cache[i].value = NULL;
297 Py_XDECREF(method_cache[i].name);
298 method_cache[i].name = Py_None;
299 Py_INCREF(Py_None);
300 }
301 /* mark all version tags as invalid */
302 PyType_Modified(&PyBaseObject_Type);
303 return 1;
304 }
305 bases = type->tp_bases;
306 n = PyTuple_GET_SIZE(bases);
307 for (i = 0; i < n; i++) {
308 PyObject *b = PyTuple_GET_ITEM(bases, i);
309 assert(PyType_Check(b));
310 if (!assign_version_tag((PyTypeObject *)b))
311 return 0;
312 }
313 type->tp_flags |= Py_TPFLAGS_VALID_VERSION_TAG;
314 return 1;
Christian Heimesa62da1d2008-01-12 19:39:10 +0000315}
316
317
Guido van Rossum6f799372001-09-20 20:46:19 +0000318static PyMemberDef type_members[] = {
Benjamin Peterson0e102062010-08-25 23:13:17 +0000319 {"__basicsize__", T_PYSSIZET, offsetof(PyTypeObject,tp_basicsize),READONLY},
320 {"__itemsize__", T_PYSSIZET, offsetof(PyTypeObject, tp_itemsize), READONLY},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000321 {"__flags__", T_LONG, offsetof(PyTypeObject, tp_flags), READONLY},
322 {"__weakrefoffset__", T_LONG,
323 offsetof(PyTypeObject, tp_weaklistoffset), READONLY},
324 {"__base__", T_OBJECT, offsetof(PyTypeObject, tp_base), READONLY},
325 {"__dictoffset__", T_LONG,
326 offsetof(PyTypeObject, tp_dictoffset), READONLY},
327 {"__mro__", T_OBJECT, offsetof(PyTypeObject, tp_mro), READONLY},
328 {0}
Tim Peters6d6c1a32001-08-02 04:15:00 +0000329};
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000330
Benjamin Petersond9f23d22011-08-17 11:54:03 -0500331static int
332check_set_special_type_attr(PyTypeObject *type, PyObject *value, const char *name)
333{
334 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
335 PyErr_Format(PyExc_TypeError,
336 "can't set %s.%s", type->tp_name, name);
337 return 0;
338 }
339 if (!value) {
340 PyErr_Format(PyExc_TypeError,
341 "can't delete %s.%s", type->tp_name, name);
342 return 0;
343 }
344 return 1;
345}
346
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000347static PyObject *
Guido van Rossumc3542212001-08-16 09:18:56 +0000348type_name(PyTypeObject *type, void *context)
349{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000350 const char *s;
Guido van Rossumc3542212001-08-16 09:18:56 +0000351
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000352 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
353 PyHeapTypeObject* et = (PyHeapTypeObject*)type;
Tim Petersea7f75d2002-12-07 21:39:16 +0000354
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000355 Py_INCREF(et->ht_name);
356 return et->ht_name;
357 }
358 else {
359 s = strrchr(type->tp_name, '.');
360 if (s == NULL)
361 s = type->tp_name;
362 else
363 s++;
364 return PyUnicode_FromString(s);
365 }
Guido van Rossumc3542212001-08-16 09:18:56 +0000366}
367
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100368static PyObject *
369type_qualname(PyTypeObject *type, void *context)
370{
371 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
372 PyHeapTypeObject* et = (PyHeapTypeObject*)type;
373 Py_INCREF(et->ht_qualname);
374 return et->ht_qualname;
375 }
376 else {
377 return type_name(type, context);
378 }
379}
380
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000381static int
382type_set_name(PyTypeObject *type, PyObject *value, void *context)
383{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000384 PyHeapTypeObject* et;
385 char *tp_name;
386 PyObject *tmp;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000387
Benjamin Petersond9f23d22011-08-17 11:54:03 -0500388 if (!check_set_special_type_attr(type, value, "__name__"))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000389 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000390 if (!PyUnicode_Check(value)) {
391 PyErr_Format(PyExc_TypeError,
392 "can only assign string to %s.__name__, not '%s'",
393 type->tp_name, Py_TYPE(value)->tp_name);
394 return -1;
395 }
Guido van Rossume845c0f2007-11-02 23:07:07 +0000396
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000397 /* Check absence of null characters */
398 tmp = PyUnicode_FromStringAndSize("\0", 1);
399 if (tmp == NULL)
400 return -1;
401 if (PyUnicode_Contains(value, tmp) != 0) {
402 Py_DECREF(tmp);
403 PyErr_Format(PyExc_ValueError,
404 "__name__ must not contain null bytes");
405 return -1;
406 }
407 Py_DECREF(tmp);
Guido van Rossume845c0f2007-11-02 23:07:07 +0000408
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000409 tp_name = _PyUnicode_AsString(value);
410 if (tp_name == NULL)
411 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000412
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000413 et = (PyHeapTypeObject*)type;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000414
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000415 Py_INCREF(value);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000416
Mark Dickinson64aafeb2013-04-13 15:26:58 +0100417 /* Wait until et is a sane state before Py_DECREF'ing the old et->ht_name
418 value. (Bug #16447.) */
419 tmp = et->ht_name;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000420 et->ht_name = value;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000421
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000422 type->tp_name = tp_name;
Mark Dickinson64aafeb2013-04-13 15:26:58 +0100423 Py_DECREF(tmp);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000424
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000425 return 0;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000426}
427
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100428static int
429type_set_qualname(PyTypeObject *type, PyObject *value, void *context)
430{
431 PyHeapTypeObject* et;
432
Benjamin Peterson2c05a2e2012-10-31 00:01:15 -0400433 if (!check_set_special_type_attr(type, value, "__qualname__"))
434 return -1;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100435 if (!PyUnicode_Check(value)) {
436 PyErr_Format(PyExc_TypeError,
437 "can only assign string to %s.__qualname__, not '%s'",
438 type->tp_name, Py_TYPE(value)->tp_name);
439 return -1;
440 }
441
442 et = (PyHeapTypeObject*)type;
443 Py_INCREF(value);
444 Py_DECREF(et->ht_qualname);
445 et->ht_qualname = value;
446 return 0;
447}
448
Guido van Rossumc3542212001-08-16 09:18:56 +0000449static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000450type_module(PyTypeObject *type, void *context)
Guido van Rossum29ca26e1995-01-07 11:58:15 +0000451{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000452 char *s;
Guido van Rossumc3542212001-08-16 09:18:56 +0000453
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000454 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
Victor Stinnerad14ccd2013-11-07 00:46:04 +0100455 PyObject *mod = _PyDict_GetItemId(type->tp_dict, &PyId___module__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000456 if (!mod) {
457 PyErr_Format(PyExc_AttributeError, "__module__");
458 return 0;
459 }
460 Py_XINCREF(mod);
461 return mod;
462 }
463 else {
Victor Stinnerad14ccd2013-11-07 00:46:04 +0100464 PyObject *name;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000465 s = strrchr(type->tp_name, '.');
466 if (s != NULL)
467 return PyUnicode_FromStringAndSize(
468 type->tp_name, (Py_ssize_t)(s - type->tp_name));
Victor Stinnerbd303c12013-11-07 23:07:29 +0100469 name = _PyUnicode_FromId(&PyId_builtins);
Victor Stinnerad14ccd2013-11-07 00:46:04 +0100470 Py_XINCREF(name);
471 return name;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000472 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000473}
474
Guido van Rossum3926a632001-09-25 16:25:58 +0000475static int
476type_set_module(PyTypeObject *type, PyObject *value, void *context)
477{
Benjamin Petersond9f23d22011-08-17 11:54:03 -0500478 if (!check_set_special_type_attr(type, value, "__module__"))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000479 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000480
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000481 PyType_Modified(type);
Christian Heimesa62da1d2008-01-12 19:39:10 +0000482
Victor Stinner3c1e4812012-03-26 22:10:51 +0200483 return _PyDict_SetItemId(type->tp_dict, &PyId___module__, value);
Guido van Rossum3926a632001-09-25 16:25:58 +0000484}
485
Tim Peters6d6c1a32001-08-02 04:15:00 +0000486static PyObject *
Christian Heimes9e7f1d22008-02-28 12:27:11 +0000487type_abstractmethods(PyTypeObject *type, void *context)
488{
Benjamin Petersonaec5fd12010-10-02 00:03:31 +0000489 PyObject *mod = NULL;
Benjamin Peterson84060b82010-10-03 02:13:39 +0000490 /* type itself has an __abstractmethods__ descriptor (this). Don't return
491 that. */
Benjamin Petersonaec5fd12010-10-02 00:03:31 +0000492 if (type != &PyType_Type)
Victor Stinner3688aa92013-11-06 18:59:18 +0100493 mod = _PyDict_GetItemId(type->tp_dict, &PyId___abstractmethods__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000494 if (!mod) {
Victor Stinner3688aa92013-11-06 18:59:18 +0100495 PyObject *message = _PyUnicode_FromId(&PyId___abstractmethods__);
496 if (message)
497 PyErr_SetObject(PyExc_AttributeError, message);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000498 return NULL;
499 }
500 Py_XINCREF(mod);
501 return mod;
Christian Heimes9e7f1d22008-02-28 12:27:11 +0000502}
503
504static int
505type_set_abstractmethods(PyTypeObject *type, PyObject *value, void *context)
506{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000507 /* __abstractmethods__ should only be set once on a type, in
508 abc.ABCMeta.__new__, so this function doesn't do anything
509 special to update subclasses.
510 */
Antoine Pitrou6f430e42012-08-15 23:18:25 +0200511 int abstract, res;
Benjamin Peterson477ba912011-01-12 15:34:01 +0000512 if (value != NULL) {
Antoine Pitrou6f430e42012-08-15 23:18:25 +0200513 abstract = PyObject_IsTrue(value);
514 if (abstract < 0)
515 return -1;
Victor Stinner3688aa92013-11-06 18:59:18 +0100516 res = _PyDict_SetItemId(type->tp_dict, &PyId___abstractmethods__, value);
Benjamin Peterson477ba912011-01-12 15:34:01 +0000517 }
518 else {
Antoine Pitrou6f430e42012-08-15 23:18:25 +0200519 abstract = 0;
Victor Stinner3688aa92013-11-06 18:59:18 +0100520 res = _PyDict_DelItemId(type->tp_dict, &PyId___abstractmethods__);
Benjamin Peterson477ba912011-01-12 15:34:01 +0000521 if (res && PyErr_ExceptionMatches(PyExc_KeyError)) {
Victor Stinner3688aa92013-11-06 18:59:18 +0100522 PyObject *message = _PyUnicode_FromId(&PyId___abstractmethods__);
523 if (message)
524 PyErr_SetObject(PyExc_AttributeError, message);
Benjamin Peterson477ba912011-01-12 15:34:01 +0000525 return -1;
526 }
527 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000528 if (res == 0) {
529 PyType_Modified(type);
Antoine Pitrou6f430e42012-08-15 23:18:25 +0200530 if (abstract)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000531 type->tp_flags |= Py_TPFLAGS_IS_ABSTRACT;
Antoine Pitrou6f430e42012-08-15 23:18:25 +0200532 else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000533 type->tp_flags &= ~Py_TPFLAGS_IS_ABSTRACT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000534 }
535 return res;
Christian Heimes9e7f1d22008-02-28 12:27:11 +0000536}
537
538static PyObject *
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000539type_get_bases(PyTypeObject *type, void *context)
540{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000541 Py_INCREF(type->tp_bases);
542 return type->tp_bases;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000543}
544
545static PyTypeObject *best_base(PyObject *);
546static int mro_internal(PyTypeObject *);
547static int compatible_for_assignment(PyTypeObject *, PyTypeObject *, char *);
548static int add_subclass(PyTypeObject*, PyTypeObject*);
549static void remove_subclass(PyTypeObject *, PyTypeObject *);
Antoine Pitrou84745ab2013-10-29 21:31:25 +0100550static void remove_all_subclasses(PyTypeObject *type, PyObject *bases);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000551static void update_all_slots(PyTypeObject *);
552
Guido van Rossum8d24ee92003-03-24 23:49:49 +0000553typedef int (*update_callback)(PyTypeObject *, void *);
554static int update_subclasses(PyTypeObject *type, PyObject *name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000555 update_callback callback, void *data);
Guido van Rossum8d24ee92003-03-24 23:49:49 +0000556static int recurse_down_subclasses(PyTypeObject *type, PyObject *name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000557 update_callback callback, void *data);
Guido van Rossum8d24ee92003-03-24 23:49:49 +0000558
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000559static int
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000560mro_subclasses(PyTypeObject *type, PyObject* temp)
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000561{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000562 PyTypeObject *subclass;
563 PyObject *ref, *subclasses, *old_mro;
Antoine Pitrou84745ab2013-10-29 21:31:25 +0100564 Py_ssize_t i;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000565
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000566 subclasses = type->tp_subclasses;
567 if (subclasses == NULL)
568 return 0;
Antoine Pitrou84745ab2013-10-29 21:31:25 +0100569 assert(PyDict_CheckExact(subclasses));
570 i = 0;
571
572 while (PyDict_Next(subclasses, &i, NULL, &ref)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000573 assert(PyWeakref_CheckRef(ref));
574 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
575 assert(subclass != NULL);
576 if ((PyObject *)subclass == Py_None)
577 continue;
578 assert(PyType_Check(subclass));
579 old_mro = subclass->tp_mro;
580 if (mro_internal(subclass) < 0) {
581 subclass->tp_mro = old_mro;
582 return -1;
583 }
584 else {
585 PyObject* tuple;
586 tuple = PyTuple_Pack(2, subclass, old_mro);
587 Py_DECREF(old_mro);
588 if (!tuple)
589 return -1;
590 if (PyList_Append(temp, tuple) < 0)
591 return -1;
592 Py_DECREF(tuple);
593 }
594 if (mro_subclasses(subclass, temp) < 0)
595 return -1;
596 }
597 return 0;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000598}
599
600static int
601type_set_bases(PyTypeObject *type, PyObject *value, void *context)
602{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000603 Py_ssize_t i;
604 int r = 0;
605 PyObject *ob, *temp;
606 PyTypeObject *new_base, *old_base;
607 PyObject *old_bases, *old_mro;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000608
Benjamin Petersond9f23d22011-08-17 11:54:03 -0500609 if (!check_set_special_type_attr(type, value, "__bases__"))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000610 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000611 if (!PyTuple_Check(value)) {
612 PyErr_Format(PyExc_TypeError,
613 "can only assign tuple to %s.__bases__, not %s",
614 type->tp_name, Py_TYPE(value)->tp_name);
615 return -1;
616 }
617 if (PyTuple_GET_SIZE(value) == 0) {
618 PyErr_Format(PyExc_TypeError,
619 "can only assign non-empty tuple to %s.__bases__, not ()",
620 type->tp_name);
621 return -1;
622 }
623 for (i = 0; i < PyTuple_GET_SIZE(value); i++) {
624 ob = PyTuple_GET_ITEM(value, i);
625 if (!PyType_Check(ob)) {
Benjamin Petersonb6af60c2012-04-01 18:49:54 -0400626 PyErr_Format(PyExc_TypeError,
Benjamin Peterson9ee601e2012-04-01 18:51:37 -0400627 "%s.__bases__ must be tuple of classes, not '%s'",
Benjamin Petersonb6af60c2012-04-01 18:49:54 -0400628 type->tp_name, Py_TYPE(ob)->tp_name);
629 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000630 }
Benjamin Peterson3471bb62012-04-01 18:48:40 -0400631 if (PyType_IsSubtype((PyTypeObject*)ob, type)) {
632 PyErr_SetString(PyExc_TypeError,
633 "a __bases__ item causes an inheritance cycle");
634 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000635 }
636 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000637
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000638 new_base = best_base(value);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000639
Benjamin Petersonab3c1c12012-04-01 18:48:02 -0400640 if (!new_base)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000641 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000642
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000643 if (!compatible_for_assignment(type->tp_base, new_base, "__bases__"))
644 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000645
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000646 Py_INCREF(new_base);
647 Py_INCREF(value);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000648
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000649 old_bases = type->tp_bases;
650 old_base = type->tp_base;
651 old_mro = type->tp_mro;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000652
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000653 type->tp_bases = value;
654 type->tp_base = new_base;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000655
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000656 if (mro_internal(type) < 0) {
657 goto bail;
658 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000659
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000660 temp = PyList_New(0);
661 if (!temp)
662 goto bail;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000663
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000664 r = mro_subclasses(type, temp);
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000665
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000666 if (r < 0) {
667 for (i = 0; i < PyList_Size(temp); i++) {
668 PyTypeObject* cls;
669 PyObject* mro;
670 PyArg_UnpackTuple(PyList_GET_ITEM(temp, i),
671 "", 2, 2, &cls, &mro);
672 Py_INCREF(mro);
673 ob = cls->tp_mro;
674 cls->tp_mro = mro;
675 Py_DECREF(ob);
676 }
677 Py_DECREF(temp);
678 goto bail;
679 }
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000680
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000681 Py_DECREF(temp);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000682
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000683 /* any base that was in __bases__ but now isn't, we
684 need to remove |type| from its tp_subclasses.
685 conversely, any class now in __bases__ that wasn't
686 needs to have |type| added to its subclasses. */
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000687
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000688 /* for now, sod that: just remove from all old_bases,
689 add to all new_bases */
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000690
Antoine Pitrou84745ab2013-10-29 21:31:25 +0100691 remove_all_subclasses(type, old_bases);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000692
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000693 for (i = PyTuple_GET_SIZE(value) - 1; i >= 0; i--) {
694 ob = PyTuple_GET_ITEM(value, i);
695 if (PyType_Check(ob)) {
696 if (add_subclass((PyTypeObject*)ob, type) < 0)
697 r = -1;
698 }
699 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000700
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000701 update_all_slots(type);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000702
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000703 Py_DECREF(old_bases);
704 Py_DECREF(old_base);
705 Py_DECREF(old_mro);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000706
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000707 return r;
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000708
709 bail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000710 Py_DECREF(type->tp_bases);
711 Py_DECREF(type->tp_base);
712 if (type->tp_mro != old_mro) {
713 Py_DECREF(type->tp_mro);
714 }
Michael W. Hudsone723e452003-08-07 14:58:10 +0000715
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000716 type->tp_bases = old_bases;
717 type->tp_base = old_base;
718 type->tp_mro = old_mro;
Tim Petersea7f75d2002-12-07 21:39:16 +0000719
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000720 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000721}
722
723static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000724type_dict(PyTypeObject *type, void *context)
725{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000726 if (type->tp_dict == NULL) {
727 Py_INCREF(Py_None);
728 return Py_None;
729 }
730 return PyDictProxy_New(type->tp_dict);
Guido van Rossum29ca26e1995-01-07 11:58:15 +0000731}
732
Tim Peters24008312002-03-17 18:56:20 +0000733static PyObject *
734type_get_doc(PyTypeObject *type, void *context)
735{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000736 PyObject *result;
Larry Hastings5c661892014-01-24 06:17:25 -0800737 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE) && type->tp_doc != NULL) {
Larry Hastings2623c8c2014-02-08 22:15:29 -0800738 return _PyType_GetDocFromInternalDoc(type->tp_name, type->tp_doc);
Larry Hastings5c661892014-01-24 06:17:25 -0800739 }
Victor Stinner3c1e4812012-03-26 22:10:51 +0200740 result = _PyDict_GetItemId(type->tp_dict, &PyId___doc__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000741 if (result == NULL) {
742 result = Py_None;
743 Py_INCREF(result);
744 }
745 else if (Py_TYPE(result)->tp_descr_get) {
746 result = Py_TYPE(result)->tp_descr_get(result, NULL,
747 (PyObject *)type);
748 }
749 else {
750 Py_INCREF(result);
751 }
752 return result;
Tim Peters24008312002-03-17 18:56:20 +0000753}
754
Larry Hastings5c661892014-01-24 06:17:25 -0800755static PyObject *
756type_get_text_signature(PyTypeObject *type, void *context)
757{
Larry Hastings2623c8c2014-02-08 22:15:29 -0800758 return _PyType_GetTextSignatureFromInternalDoc(type->tp_name, type->tp_doc);
Larry Hastings5c661892014-01-24 06:17:25 -0800759}
760
Benjamin Peterson01fc6cd2011-08-17 12:03:47 -0500761static int
762type_set_doc(PyTypeObject *type, PyObject *value, void *context)
763{
764 if (!check_set_special_type_attr(type, value, "__doc__"))
765 return -1;
766 PyType_Modified(type);
Victor Stinner3c1e4812012-03-26 22:10:51 +0200767 return _PyDict_SetItemId(type->tp_dict, &PyId___doc__, value);
Benjamin Peterson01fc6cd2011-08-17 12:03:47 -0500768}
769
Antoine Pitrouec569b72008-08-26 22:40:48 +0000770static PyObject *
771type___instancecheck__(PyObject *type, PyObject *inst)
772{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000773 switch (_PyObject_RealIsInstance(inst, type)) {
774 case -1:
775 return NULL;
776 case 0:
777 Py_RETURN_FALSE;
778 default:
779 Py_RETURN_TRUE;
780 }
Antoine Pitrouec569b72008-08-26 22:40:48 +0000781}
782
783
784static PyObject *
Antoine Pitrouec569b72008-08-26 22:40:48 +0000785type___subclasscheck__(PyObject *type, PyObject *inst)
786{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000787 switch (_PyObject_RealIsSubclass(inst, type)) {
788 case -1:
789 return NULL;
790 case 0:
791 Py_RETURN_FALSE;
792 default:
793 Py_RETURN_TRUE;
794 }
Antoine Pitrouec569b72008-08-26 22:40:48 +0000795}
796
Antoine Pitrouec569b72008-08-26 22:40:48 +0000797
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000798static PyGetSetDef type_getsets[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000799 {"__name__", (getter)type_name, (setter)type_set_name, NULL},
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100800 {"__qualname__", (getter)type_qualname, (setter)type_set_qualname, NULL},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000801 {"__bases__", (getter)type_get_bases, (setter)type_set_bases, NULL},
802 {"__module__", (getter)type_module, (setter)type_set_module, NULL},
803 {"__abstractmethods__", (getter)type_abstractmethods,
804 (setter)type_set_abstractmethods, NULL},
805 {"__dict__", (getter)type_dict, NULL, NULL},
Benjamin Peterson01fc6cd2011-08-17 12:03:47 -0500806 {"__doc__", (getter)type_get_doc, (setter)type_set_doc, NULL},
Larry Hastings5c661892014-01-24 06:17:25 -0800807 {"__text_signature__", (getter)type_get_text_signature, NULL, NULL},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000808 {0}
Tim Peters6d6c1a32001-08-02 04:15:00 +0000809};
810
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000811static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000812type_repr(PyTypeObject *type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000813{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000814 PyObject *mod, *name, *rtn;
Guido van Rossumc3542212001-08-16 09:18:56 +0000815
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000816 mod = type_module(type, NULL);
817 if (mod == NULL)
818 PyErr_Clear();
819 else if (!PyUnicode_Check(mod)) {
820 Py_DECREF(mod);
821 mod = NULL;
822 }
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100823 name = type_qualname(type, NULL);
Christian Heimesa0e7e412012-09-10 03:00:14 +0200824 if (name == NULL) {
825 Py_XDECREF(mod);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000826 return NULL;
Christian Heimesa0e7e412012-09-10 03:00:14 +0200827 }
Barry Warsaw7ce36942001-08-24 18:34:26 +0000828
Victor Stinnerbd303c12013-11-07 23:07:29 +0100829 if (mod != NULL && _PyUnicode_CompareWithId(mod, &PyId_builtins))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000830 rtn = PyUnicode_FromFormat("<class '%U.%U'>", mod, name);
831 else
832 rtn = PyUnicode_FromFormat("<class '%s'>", type->tp_name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000833
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000834 Py_XDECREF(mod);
835 Py_DECREF(name);
836 return rtn;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000837}
838
Tim Peters6d6c1a32001-08-02 04:15:00 +0000839static PyObject *
840type_call(PyTypeObject *type, PyObject *args, PyObject *kwds)
841{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000842 PyObject *obj;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000843
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000844 if (type->tp_new == NULL) {
845 PyErr_Format(PyExc_TypeError,
846 "cannot create '%.100s' instances",
847 type->tp_name);
848 return NULL;
849 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000850
Victor Stinner33824f62013-08-26 14:05:19 +0200851#ifdef Py_DEBUG
852 /* type_call() must not be called with an exception set,
853 because it may clear it (directly or indirectly) and so the
854 caller looses its exception */
855 assert(!PyErr_Occurred());
856#endif
857
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000858 obj = type->tp_new(type, args, kwds);
859 if (obj != NULL) {
860 /* Ugly exception: when the call was type(something),
861 don't call tp_init on the result. */
862 if (type == &PyType_Type &&
863 PyTuple_Check(args) && PyTuple_GET_SIZE(args) == 1 &&
864 (kwds == NULL ||
865 (PyDict_Check(kwds) && PyDict_Size(kwds) == 0)))
866 return obj;
867 /* If the returned object is not an instance of type,
868 it won't be initialized. */
869 if (!PyType_IsSubtype(Py_TYPE(obj), type))
870 return obj;
871 type = Py_TYPE(obj);
Victor Stinner3997cfd2013-07-16 22:51:21 +0200872 if (type->tp_init != NULL) {
873 int res = type->tp_init(obj, args, kwds);
874 if (res < 0) {
875 Py_DECREF(obj);
876 obj = NULL;
877 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000878 }
879 }
880 return obj;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000881}
882
883PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000884PyType_GenericAlloc(PyTypeObject *type, Py_ssize_t nitems)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000885{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000886 PyObject *obj;
887 const size_t size = _PyObject_VAR_SIZE(type, nitems+1);
888 /* note that we need to add one, for the sentinel */
Tim Peters406fe3b2001-10-06 19:04:01 +0000889
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000890 if (PyType_IS_GC(type))
891 obj = _PyObject_GC_Malloc(size);
892 else
893 obj = (PyObject *)PyObject_MALLOC(size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000894
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000895 if (obj == NULL)
896 return PyErr_NoMemory();
Tim Peters406fe3b2001-10-06 19:04:01 +0000897
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000898 memset(obj, '\0', size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000899
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000900 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
901 Py_INCREF(type);
Tim Peters406fe3b2001-10-06 19:04:01 +0000902
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000903 if (type->tp_itemsize == 0)
Christian Heimesd3afe782013-12-04 09:27:47 +0100904 (void)PyObject_INIT(obj, type);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000905 else
906 (void) PyObject_INIT_VAR((PyVarObject *)obj, type, nitems);
Tim Peters406fe3b2001-10-06 19:04:01 +0000907
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000908 if (PyType_IS_GC(type))
909 _PyObject_GC_TRACK(obj);
910 return obj;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000911}
912
913PyObject *
914PyType_GenericNew(PyTypeObject *type, PyObject *args, PyObject *kwds)
915{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000916 return type->tp_alloc(type, 0);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000917}
918
Guido van Rossum9475a232001-10-05 20:51:39 +0000919/* Helpers for subtyping */
920
921static int
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000922traverse_slots(PyTypeObject *type, PyObject *self, visitproc visit, void *arg)
923{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000924 Py_ssize_t i, n;
925 PyMemberDef *mp;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000926
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000927 n = Py_SIZE(type);
928 mp = PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type);
929 for (i = 0; i < n; i++, mp++) {
930 if (mp->type == T_OBJECT_EX) {
931 char *addr = (char *)self + mp->offset;
932 PyObject *obj = *(PyObject **)addr;
933 if (obj != NULL) {
934 int err = visit(obj, arg);
935 if (err)
936 return err;
937 }
938 }
939 }
940 return 0;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000941}
942
943static int
Guido van Rossum9475a232001-10-05 20:51:39 +0000944subtype_traverse(PyObject *self, visitproc visit, void *arg)
945{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000946 PyTypeObject *type, *base;
947 traverseproc basetraverse;
Guido van Rossum9475a232001-10-05 20:51:39 +0000948
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000949 /* Find the nearest base with a different tp_traverse,
950 and traverse slots while we're at it */
951 type = Py_TYPE(self);
952 base = type;
953 while ((basetraverse = base->tp_traverse) == subtype_traverse) {
954 if (Py_SIZE(base)) {
955 int err = traverse_slots(base, self, visit, arg);
956 if (err)
957 return err;
958 }
959 base = base->tp_base;
960 assert(base);
961 }
Guido van Rossum9475a232001-10-05 20:51:39 +0000962
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000963 if (type->tp_dictoffset != base->tp_dictoffset) {
964 PyObject **dictptr = _PyObject_GetDictPtr(self);
965 if (dictptr && *dictptr)
966 Py_VISIT(*dictptr);
967 }
Guido van Rossum9475a232001-10-05 20:51:39 +0000968
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000969 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
970 /* For a heaptype, the instances count as references
971 to the type. Traverse the type so the collector
972 can find cycles involving this link. */
973 Py_VISIT(type);
Guido van Rossuma3862092002-06-10 15:24:42 +0000974
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000975 if (basetraverse)
976 return basetraverse(self, visit, arg);
977 return 0;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000978}
979
980static void
981clear_slots(PyTypeObject *type, PyObject *self)
982{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000983 Py_ssize_t i, n;
984 PyMemberDef *mp;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000985
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000986 n = Py_SIZE(type);
987 mp = PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type);
988 for (i = 0; i < n; i++, mp++) {
989 if (mp->type == T_OBJECT_EX && !(mp->flags & READONLY)) {
990 char *addr = (char *)self + mp->offset;
991 PyObject *obj = *(PyObject **)addr;
992 if (obj != NULL) {
993 *(PyObject **)addr = NULL;
994 Py_DECREF(obj);
995 }
996 }
997 }
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000998}
999
1000static int
1001subtype_clear(PyObject *self)
1002{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001003 PyTypeObject *type, *base;
1004 inquiry baseclear;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001005
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001006 /* Find the nearest base with a different tp_clear
1007 and clear slots while we're at it */
1008 type = Py_TYPE(self);
1009 base = type;
1010 while ((baseclear = base->tp_clear) == subtype_clear) {
1011 if (Py_SIZE(base))
1012 clear_slots(base, self);
1013 base = base->tp_base;
1014 assert(base);
1015 }
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001016
Benjamin Peterson52c42432012-03-07 18:41:11 -06001017 /* Clear the instance dict (if any), to break cycles involving only
1018 __dict__ slots (as in the case 'self.__dict__ is self'). */
1019 if (type->tp_dictoffset != base->tp_dictoffset) {
1020 PyObject **dictptr = _PyObject_GetDictPtr(self);
1021 if (dictptr && *dictptr)
1022 Py_CLEAR(*dictptr);
1023 }
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001024
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001025 if (baseclear)
1026 return baseclear(self);
1027 return 0;
Guido van Rossum9475a232001-10-05 20:51:39 +00001028}
Tim Peters6d6c1a32001-08-02 04:15:00 +00001029
1030static void
1031subtype_dealloc(PyObject *self)
1032{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001033 PyTypeObject *type, *base;
1034 destructor basedealloc;
Antoine Pitrou56cd62c2012-09-06 00:59:49 +02001035 PyThreadState *tstate = PyThreadState_GET();
Antoine Pitrou796564c2013-07-30 19:59:21 +02001036 int has_finalizer;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001037
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001038 /* Extract the type; we expect it to be a heap type */
1039 type = Py_TYPE(self);
1040 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001041
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001042 /* Test whether the type has GC exactly once */
Guido van Rossum22b13872002-08-06 21:41:44 +00001043
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001044 if (!PyType_IS_GC(type)) {
1045 /* It's really rare to find a dynamic type that doesn't have
1046 GC; it can only happen when deriving from 'object' and not
1047 adding any slots or instance variables. This allows
1048 certain simplifications: there's no need to call
1049 clear_slots(), or DECREF the dict, or clear weakrefs. */
Guido van Rossum22b13872002-08-06 21:41:44 +00001050
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001051 /* Maybe call finalizer; exit early if resurrected */
Antoine Pitrou796564c2013-07-30 19:59:21 +02001052 if (type->tp_finalize) {
1053 if (PyObject_CallFinalizerFromDealloc(self) < 0)
1054 return;
1055 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001056 if (type->tp_del) {
1057 type->tp_del(self);
1058 if (self->ob_refcnt > 0)
1059 return;
1060 }
Guido van Rossum22b13872002-08-06 21:41:44 +00001061
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001062 /* Find the nearest base with a different tp_dealloc */
1063 base = type;
1064 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
1065 assert(Py_SIZE(base) == 0);
1066 base = base->tp_base;
1067 assert(base);
1068 }
Guido van Rossum22b13872002-08-06 21:41:44 +00001069
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001070 /* Extract the type again; tp_del may have changed it */
1071 type = Py_TYPE(self);
Benjamin Peterson193152c2009-04-25 01:08:45 +00001072
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001073 /* Call the base tp_dealloc() */
1074 assert(basedealloc);
1075 basedealloc(self);
Guido van Rossum22b13872002-08-06 21:41:44 +00001076
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001077 /* Can't reference self beyond this point */
1078 Py_DECREF(type);
Guido van Rossum22b13872002-08-06 21:41:44 +00001079
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001080 /* Done */
1081 return;
1082 }
Guido van Rossum22b13872002-08-06 21:41:44 +00001083
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001084 /* We get here only if the type has GC */
Guido van Rossum22b13872002-08-06 21:41:44 +00001085
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001086 /* UnTrack and re-Track around the trashcan macro, alas */
1087 /* See explanation at end of function for full disclosure */
1088 PyObject_GC_UnTrack(self);
1089 ++_PyTrash_delete_nesting;
Antoine Pitrou56cd62c2012-09-06 00:59:49 +02001090 ++ tstate->trash_delete_nesting;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001091 Py_TRASHCAN_SAFE_BEGIN(self);
1092 --_PyTrash_delete_nesting;
Antoine Pitrou56cd62c2012-09-06 00:59:49 +02001093 -- tstate->trash_delete_nesting;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001094 /* DO NOT restore GC tracking at this point. weakref callbacks
1095 * (if any, and whether directly here or indirectly in something we
1096 * call) may trigger GC, and if self is tracked at that point, it
1097 * will look like trash to GC and GC will try to delete self again.
1098 */
Guido van Rossum22b13872002-08-06 21:41:44 +00001099
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001100 /* Find the nearest base with a different tp_dealloc */
1101 base = type;
Brett Cannonb94767f2011-02-22 20:15:44 +00001102 while ((/*basedealloc =*/ base->tp_dealloc) == subtype_dealloc) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001103 base = base->tp_base;
1104 assert(base);
1105 }
Guido van Rossum14227b42001-12-06 02:35:58 +00001106
Antoine Pitrou796564c2013-07-30 19:59:21 +02001107 has_finalizer = type->tp_finalize || type->tp_del;
Guido van Rossum59195fd2003-06-13 20:54:40 +00001108
Antoine Pitrou796564c2013-07-30 19:59:21 +02001109 /* Maybe call finalizer; exit early if resurrected */
1110 if (has_finalizer)
1111 _PyObject_GC_TRACK(self);
1112
1113 if (type->tp_finalize) {
1114 if (PyObject_CallFinalizerFromDealloc(self) < 0) {
1115 /* Resurrected */
1116 goto endlabel;
1117 }
1118 }
1119 /* If we added a weaklist, we clear it. Do this *before* calling
1120 tp_del, clearing slots, or clearing the instance dict. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001121 if (type->tp_weaklistoffset && !base->tp_weaklistoffset)
1122 PyObject_ClearWeakRefs(self);
Guido van Rossum1987c662003-05-29 14:29:23 +00001123
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001124 if (type->tp_del) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001125 type->tp_del(self);
Antoine Pitrou796564c2013-07-30 19:59:21 +02001126 if (self->ob_refcnt > 0) {
1127 /* Resurrected */
1128 goto endlabel;
1129 }
1130 }
1131 if (has_finalizer) {
1132 _PyObject_GC_UNTRACK(self);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001133 /* New weakrefs could be created during the finalizer call.
Antoine Pitrou796564c2013-07-30 19:59:21 +02001134 If this occurs, clear them out without calling their
1135 finalizers since they might rely on part of the object
1136 being finalized that has already been destroyed. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001137 if (type->tp_weaklistoffset && !base->tp_weaklistoffset) {
1138 /* Modeled after GET_WEAKREFS_LISTPTR() */
1139 PyWeakReference **list = (PyWeakReference **) \
1140 PyObject_GET_WEAKREFS_LISTPTR(self);
1141 while (*list)
1142 _PyWeakref_ClearRef(*list);
1143 }
1144 }
Guido van Rossum1987c662003-05-29 14:29:23 +00001145
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001146 /* Clear slots up to the nearest base with a different tp_dealloc */
1147 base = type;
1148 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
1149 if (Py_SIZE(base))
1150 clear_slots(base, self);
1151 base = base->tp_base;
1152 assert(base);
1153 }
Guido van Rossum59195fd2003-06-13 20:54:40 +00001154
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001155 /* If we added a dict, DECREF it */
1156 if (type->tp_dictoffset && !base->tp_dictoffset) {
1157 PyObject **dictptr = _PyObject_GetDictPtr(self);
1158 if (dictptr != NULL) {
1159 PyObject *dict = *dictptr;
1160 if (dict != NULL) {
1161 Py_DECREF(dict);
1162 *dictptr = NULL;
1163 }
1164 }
1165 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001166
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001167 /* Extract the type again; tp_del may have changed it */
1168 type = Py_TYPE(self);
Benjamin Peterson193152c2009-04-25 01:08:45 +00001169
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001170 /* Call the base tp_dealloc(); first retrack self if
1171 * basedealloc knows about gc.
1172 */
1173 if (PyType_IS_GC(base))
1174 _PyObject_GC_TRACK(self);
1175 assert(basedealloc);
1176 basedealloc(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001177
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001178 /* Can't reference self beyond this point */
1179 Py_DECREF(type);
Guido van Rossum22b13872002-08-06 21:41:44 +00001180
Guido van Rossum0906e072002-08-07 20:42:09 +00001181 endlabel:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001182 ++_PyTrash_delete_nesting;
Antoine Pitrou56cd62c2012-09-06 00:59:49 +02001183 ++ tstate->trash_delete_nesting;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001184 Py_TRASHCAN_SAFE_END(self);
1185 --_PyTrash_delete_nesting;
Antoine Pitrou56cd62c2012-09-06 00:59:49 +02001186 -- tstate->trash_delete_nesting;
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001187
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001188 /* Explanation of the weirdness around the trashcan macros:
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001189
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001190 Q. What do the trashcan macros do?
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001191
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001192 A. Read the comment titled "Trashcan mechanism" in object.h.
1193 For one, this explains why there must be a call to GC-untrack
1194 before the trashcan begin macro. Without understanding the
1195 trashcan code, the answers to the following questions don't make
1196 sense.
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001197
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001198 Q. Why do we GC-untrack before the trashcan and then immediately
1199 GC-track again afterward?
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001200
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001201 A. In the case that the base class is GC-aware, the base class
1202 probably GC-untracks the object. If it does that using the
1203 UNTRACK macro, this will crash when the object is already
1204 untracked. Because we don't know what the base class does, the
1205 only safe thing is to make sure the object is tracked when we
1206 call the base class dealloc. But... The trashcan begin macro
1207 requires that the object is *untracked* before it is called. So
1208 the dance becomes:
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001209
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001210 GC untrack
1211 trashcan begin
1212 GC track
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001213
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001214 Q. Why did the last question say "immediately GC-track again"?
1215 It's nowhere near immediately.
Tim Petersf7f9e992003-11-13 21:59:32 +00001216
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001217 A. Because the code *used* to re-track immediately. Bad Idea.
1218 self has a refcount of 0, and if gc ever gets its hands on it
1219 (which can happen if any weakref callback gets invoked), it
1220 looks like trash to gc too, and gc also tries to delete self
Ezio Melotti13925002011-03-16 11:05:33 +02001221 then. But we're already deleting self. Double deallocation is
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001222 a subtle disaster.
Tim Petersf7f9e992003-11-13 21:59:32 +00001223
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001224 Q. Why the bizarre (net-zero) manipulation of
1225 _PyTrash_delete_nesting around the trashcan macros?
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001226
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001227 A. Some base classes (e.g. list) also use the trashcan mechanism.
1228 The following scenario used to be possible:
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001229
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001230 - suppose the trashcan level is one below the trashcan limit
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001231
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001232 - subtype_dealloc() is called
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001233
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001234 - the trashcan limit is not yet reached, so the trashcan level
1235 is incremented and the code between trashcan begin and end is
1236 executed
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001237
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001238 - this destroys much of the object's contents, including its
1239 slots and __dict__
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001240
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001241 - basedealloc() is called; this is really list_dealloc(), or
1242 some other type which also uses the trashcan macros
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001243
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001244 - the trashcan limit is now reached, so the object is put on the
1245 trashcan's to-be-deleted-later list
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001246
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001247 - basedealloc() returns
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001248
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001249 - subtype_dealloc() decrefs the object's type
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001250
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001251 - subtype_dealloc() returns
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001252
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001253 - later, the trashcan code starts deleting the objects from its
1254 to-be-deleted-later list
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001255
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001256 - subtype_dealloc() is called *AGAIN* for the same object
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001257
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001258 - at the very least (if the destroyed slots and __dict__ don't
1259 cause problems) the object's type gets decref'ed a second
1260 time, which is *BAD*!!!
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001261
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001262 The remedy is to make sure that if the code between trashcan
1263 begin and end in subtype_dealloc() is called, the code between
1264 trashcan begin and end in basedealloc() will also be called.
1265 This is done by decrementing the level after passing into the
1266 trashcan block, and incrementing it just before leaving the
1267 block.
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001268
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001269 But now it's possible that a chain of objects consisting solely
1270 of objects whose deallocator is subtype_dealloc() will defeat
1271 the trashcan mechanism completely: the decremented level means
1272 that the effective level never reaches the limit. Therefore, we
1273 *increment* the level *before* entering the trashcan block, and
1274 matchingly decrement it after leaving. This means the trashcan
1275 code will trigger a little early, but that's no big deal.
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001276
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001277 Q. Are there any live examples of code in need of all this
1278 complexity?
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001279
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001280 A. Yes. See SF bug 668433 for code that crashed (when Python was
1281 compiled in debug mode) before the trashcan level manipulations
1282 were added. For more discussion, see SF patches 581742, 575073
1283 and bug 574207.
1284 */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001285}
1286
Jeremy Hylton938ace62002-07-17 16:30:39 +00001287static PyTypeObject *solid_base(PyTypeObject *type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001288
Tim Peters6d6c1a32001-08-02 04:15:00 +00001289/* type test with subclassing support */
1290
1291int
1292PyType_IsSubtype(PyTypeObject *a, PyTypeObject *b)
1293{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001294 PyObject *mro;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001295
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001296 mro = a->tp_mro;
1297 if (mro != NULL) {
1298 /* Deal with multiple inheritance without recursion
1299 by walking the MRO tuple */
1300 Py_ssize_t i, n;
1301 assert(PyTuple_Check(mro));
1302 n = PyTuple_GET_SIZE(mro);
1303 for (i = 0; i < n; i++) {
1304 if (PyTuple_GET_ITEM(mro, i) == (PyObject *)b)
1305 return 1;
1306 }
1307 return 0;
1308 }
1309 else {
1310 /* a is not completely initilized yet; follow tp_base */
1311 do {
1312 if (a == b)
1313 return 1;
1314 a = a->tp_base;
1315 } while (a != NULL);
1316 return b == &PyBaseObject_Type;
1317 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001318}
1319
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001320/* Internal routines to do a method lookup in the type
Guido van Rossum60718732001-08-28 17:47:51 +00001321 without looking in the instance dictionary
1322 (so we can't use PyObject_GetAttr) but still binding
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001323 it to the instance. The arguments are the object,
Guido van Rossum60718732001-08-28 17:47:51 +00001324 the method name as a C string, and the address of a
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001325 static variable used to cache the interned Python string.
1326
1327 Two variants:
1328
1329 - lookup_maybe() returns NULL without raising an exception
1330 when the _PyType_Lookup() call fails;
1331
1332 - lookup_method() always raises an exception upon errors.
Benjamin Peterson224205f2009-05-08 03:25:19 +00001333
1334 - _PyObject_LookupSpecial() exported for the benefit of other places.
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001335*/
Guido van Rossum60718732001-08-28 17:47:51 +00001336
1337static PyObject *
Benjamin Petersonce798522012-01-22 11:24:29 -05001338lookup_maybe(PyObject *self, _Py_Identifier *attrid)
Guido van Rossum60718732001-08-28 17:47:51 +00001339{
Victor Stinner3c1e4812012-03-26 22:10:51 +02001340 PyObject *res;
Guido van Rossum60718732001-08-28 17:47:51 +00001341
Victor Stinner3c1e4812012-03-26 22:10:51 +02001342 res = _PyType_LookupId(Py_TYPE(self), attrid);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001343 if (res != NULL) {
1344 descrgetfunc f;
1345 if ((f = Py_TYPE(res)->tp_descr_get) == NULL)
1346 Py_INCREF(res);
1347 else
1348 res = f(res, self, (PyObject *)(Py_TYPE(self)));
1349 }
1350 return res;
Guido van Rossum60718732001-08-28 17:47:51 +00001351}
1352
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001353static PyObject *
Benjamin Petersonce798522012-01-22 11:24:29 -05001354lookup_method(PyObject *self, _Py_Identifier *attrid)
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001355{
Benjamin Petersonce798522012-01-22 11:24:29 -05001356 PyObject *res = lookup_maybe(self, attrid);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001357 if (res == NULL && !PyErr_Occurred())
Benjamin Petersonce798522012-01-22 11:24:29 -05001358 PyErr_SetObject(PyExc_AttributeError, attrid->object);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001359 return res;
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001360}
1361
Benjamin Peterson224205f2009-05-08 03:25:19 +00001362PyObject *
Benjamin Petersonce798522012-01-22 11:24:29 -05001363_PyObject_LookupSpecial(PyObject *self, _Py_Identifier *attrid)
Benjamin Peterson224205f2009-05-08 03:25:19 +00001364{
Benjamin Petersonce798522012-01-22 11:24:29 -05001365 return lookup_maybe(self, attrid);
Benjamin Peterson224205f2009-05-08 03:25:19 +00001366}
1367
Guido van Rossum2730b132001-08-28 18:22:14 +00001368/* A variation of PyObject_CallMethod that uses lookup_method()
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001369 instead of PyObject_GetAttrString(). This uses the same convention
Guido van Rossum2730b132001-08-28 18:22:14 +00001370 as lookup_method to cache the interned name string object. */
1371
Neil Schemenauerf23473f2001-10-21 22:28:58 +00001372static PyObject *
Benjamin Petersonce798522012-01-22 11:24:29 -05001373call_method(PyObject *o, _Py_Identifier *nameid, char *format, ...)
Guido van Rossum2730b132001-08-28 18:22:14 +00001374{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001375 va_list va;
1376 PyObject *args, *func = 0, *retval;
1377 va_start(va, format);
Guido van Rossum2730b132001-08-28 18:22:14 +00001378
Benjamin Petersonce798522012-01-22 11:24:29 -05001379 func = lookup_maybe(o, nameid);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001380 if (func == NULL) {
1381 va_end(va);
1382 if (!PyErr_Occurred())
Benjamin Petersonce798522012-01-22 11:24:29 -05001383 PyErr_SetObject(PyExc_AttributeError, nameid->object);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001384 return NULL;
1385 }
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001386
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001387 if (format && *format)
1388 args = Py_VaBuildValue(format, va);
1389 else
1390 args = PyTuple_New(0);
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001391
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001392 va_end(va);
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001393
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001394 if (args == NULL)
1395 return NULL;
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001396
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001397 assert(PyTuple_Check(args));
1398 retval = PyObject_Call(func, args, NULL);
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001399
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001400 Py_DECREF(args);
1401 Py_DECREF(func);
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001402
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001403 return retval;
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001404}
1405
1406/* Clone of call_method() that returns NotImplemented when the lookup fails. */
1407
Neil Schemenauerf23473f2001-10-21 22:28:58 +00001408static PyObject *
Benjamin Petersonce798522012-01-22 11:24:29 -05001409call_maybe(PyObject *o, _Py_Identifier *nameid, char *format, ...)
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001410{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001411 va_list va;
1412 PyObject *args, *func = 0, *retval;
1413 va_start(va, format);
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001414
Benjamin Petersonce798522012-01-22 11:24:29 -05001415 func = lookup_maybe(o, nameid);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001416 if (func == NULL) {
1417 va_end(va);
Brian Curtindfc80e32011-08-10 20:28:54 -05001418 if (!PyErr_Occurred())
1419 Py_RETURN_NOTIMPLEMENTED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001420 return NULL;
1421 }
Guido van Rossum2730b132001-08-28 18:22:14 +00001422
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001423 if (format && *format)
1424 args = Py_VaBuildValue(format, va);
1425 else
1426 args = PyTuple_New(0);
Guido van Rossum2730b132001-08-28 18:22:14 +00001427
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001428 va_end(va);
Guido van Rossum2730b132001-08-28 18:22:14 +00001429
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001430 if (args == NULL)
1431 return NULL;
Guido van Rossum2730b132001-08-28 18:22:14 +00001432
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001433 assert(PyTuple_Check(args));
1434 retval = PyObject_Call(func, args, NULL);
Guido van Rossum2730b132001-08-28 18:22:14 +00001435
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001436 Py_DECREF(args);
1437 Py_DECREF(func);
Guido van Rossum2730b132001-08-28 18:22:14 +00001438
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001439 return retval;
Guido van Rossum2730b132001-08-28 18:22:14 +00001440}
1441
Tim Petersea7f75d2002-12-07 21:39:16 +00001442/*
Guido van Rossum1f121312002-11-14 19:49:16 +00001443 Method resolution order algorithm C3 described in
1444 "A Monotonic Superclass Linearization for Dylan",
1445 by Kim Barrett, Bob Cassel, Paul Haahr,
Tim Petersea7f75d2002-12-07 21:39:16 +00001446 David A. Moon, Keith Playford, and P. Tucker Withington.
Guido van Rossum1f121312002-11-14 19:49:16 +00001447 (OOPSLA 1996)
1448
Guido van Rossum98f33732002-11-25 21:36:54 +00001449 Some notes about the rules implied by C3:
1450
Tim Petersea7f75d2002-12-07 21:39:16 +00001451 No duplicate bases.
Guido van Rossum98f33732002-11-25 21:36:54 +00001452 It isn't legal to repeat a class in a list of base classes.
1453
1454 The next three properties are the 3 constraints in "C3".
1455
Tim Petersea7f75d2002-12-07 21:39:16 +00001456 Local precendece order.
Guido van Rossum98f33732002-11-25 21:36:54 +00001457 If A precedes B in C's MRO, then A will precede B in the MRO of all
1458 subclasses of C.
1459
1460 Monotonicity.
1461 The MRO of a class must be an extension without reordering of the
1462 MRO of each of its superclasses.
1463
1464 Extended Precedence Graph (EPG).
1465 Linearization is consistent if there is a path in the EPG from
1466 each class to all its successors in the linearization. See
1467 the paper for definition of EPG.
Guido van Rossum1f121312002-11-14 19:49:16 +00001468 */
1469
Tim Petersea7f75d2002-12-07 21:39:16 +00001470static int
Guido van Rossum1f121312002-11-14 19:49:16 +00001471tail_contains(PyObject *list, int whence, PyObject *o) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001472 Py_ssize_t j, size;
1473 size = PyList_GET_SIZE(list);
Guido van Rossum1f121312002-11-14 19:49:16 +00001474
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001475 for (j = whence+1; j < size; j++) {
1476 if (PyList_GET_ITEM(list, j) == o)
1477 return 1;
1478 }
1479 return 0;
Guido van Rossum1f121312002-11-14 19:49:16 +00001480}
1481
Guido van Rossum98f33732002-11-25 21:36:54 +00001482static PyObject *
1483class_name(PyObject *cls)
1484{
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001485 PyObject *name = _PyObject_GetAttrId(cls, &PyId___name__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001486 if (name == NULL) {
1487 PyErr_Clear();
1488 Py_XDECREF(name);
1489 name = PyObject_Repr(cls);
1490 }
1491 if (name == NULL)
1492 return NULL;
1493 if (!PyUnicode_Check(name)) {
1494 Py_DECREF(name);
1495 return NULL;
1496 }
1497 return name;
Guido van Rossum98f33732002-11-25 21:36:54 +00001498}
1499
1500static int
1501check_duplicates(PyObject *list)
1502{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001503 Py_ssize_t i, j, n;
1504 /* Let's use a quadratic time algorithm,
1505 assuming that the bases lists is short.
1506 */
1507 n = PyList_GET_SIZE(list);
1508 for (i = 0; i < n; i++) {
1509 PyObject *o = PyList_GET_ITEM(list, i);
1510 for (j = i + 1; j < n; j++) {
1511 if (PyList_GET_ITEM(list, j) == o) {
1512 o = class_name(o);
1513 if (o != NULL) {
1514 PyErr_Format(PyExc_TypeError,
1515 "duplicate base class %U",
1516 o);
1517 Py_DECREF(o);
1518 } else {
1519 PyErr_SetString(PyExc_TypeError,
1520 "duplicate base class");
1521 }
1522 return -1;
1523 }
1524 }
1525 }
1526 return 0;
Guido van Rossum98f33732002-11-25 21:36:54 +00001527}
1528
1529/* Raise a TypeError for an MRO order disagreement.
1530
1531 It's hard to produce a good error message. In the absence of better
1532 insight into error reporting, report the classes that were candidates
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001533 to be put next into the MRO. There is some conflict between the
Guido van Rossum98f33732002-11-25 21:36:54 +00001534 order in which they should be put in the MRO, but it's hard to
1535 diagnose what constraint can't be satisfied.
1536*/
1537
1538static void
1539set_mro_error(PyObject *to_merge, int *remain)
1540{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001541 Py_ssize_t i, n, off, to_merge_size;
1542 char buf[1000];
1543 PyObject *k, *v;
1544 PyObject *set = PyDict_New();
1545 if (!set) return;
Guido van Rossum98f33732002-11-25 21:36:54 +00001546
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001547 to_merge_size = PyList_GET_SIZE(to_merge);
1548 for (i = 0; i < to_merge_size; i++) {
1549 PyObject *L = PyList_GET_ITEM(to_merge, i);
1550 if (remain[i] < PyList_GET_SIZE(L)) {
1551 PyObject *c = PyList_GET_ITEM(L, remain[i]);
1552 if (PyDict_SetItem(set, c, Py_None) < 0) {
1553 Py_DECREF(set);
1554 return;
1555 }
1556 }
1557 }
1558 n = PyDict_Size(set);
Guido van Rossum98f33732002-11-25 21:36:54 +00001559
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001560 off = PyOS_snprintf(buf, sizeof(buf), "Cannot create a \
Raymond Hettingerf394df42003-04-06 19:13:41 +00001561consistent method resolution\norder (MRO) for bases");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001562 i = 0;
1563 while (PyDict_Next(set, &i, &k, &v) && (size_t)off < sizeof(buf)) {
1564 PyObject *name = class_name(k);
Victor Stinnere5f99f32010-05-19 01:42:46 +00001565 char *name_str;
1566 if (name != NULL) {
1567 name_str = _PyUnicode_AsString(name);
1568 if (name_str == NULL)
Victor Stinnerba644a62010-05-19 01:50:45 +00001569 name_str = "?";
Victor Stinnere5f99f32010-05-19 01:42:46 +00001570 } else
Victor Stinnerba644a62010-05-19 01:50:45 +00001571 name_str = "?";
Victor Stinnere5f99f32010-05-19 01:42:46 +00001572 off += PyOS_snprintf(buf + off, sizeof(buf) - off, " %s", name_str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001573 Py_XDECREF(name);
1574 if (--n && (size_t)(off+1) < sizeof(buf)) {
1575 buf[off++] = ',';
1576 buf[off] = '\0';
1577 }
1578 }
1579 PyErr_SetString(PyExc_TypeError, buf);
1580 Py_DECREF(set);
Guido van Rossum98f33732002-11-25 21:36:54 +00001581}
1582
Tim Petersea7f75d2002-12-07 21:39:16 +00001583static int
Guido van Rossum1f121312002-11-14 19:49:16 +00001584pmerge(PyObject *acc, PyObject* to_merge) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001585 Py_ssize_t i, j, to_merge_size, empty_cnt;
1586 int *remain;
1587 int ok;
Tim Petersea7f75d2002-12-07 21:39:16 +00001588
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001589 to_merge_size = PyList_GET_SIZE(to_merge);
Guido van Rossum1f121312002-11-14 19:49:16 +00001590
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001591 /* remain stores an index into each sublist of to_merge.
1592 remain[i] is the index of the next base in to_merge[i]
1593 that is not included in acc.
1594 */
1595 remain = (int *)PyMem_MALLOC(SIZEOF_INT*to_merge_size);
Victor Stinnera41f0852013-07-12 00:42:14 +02001596 if (remain == NULL) {
1597 PyErr_NoMemory();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001598 return -1;
Victor Stinnera41f0852013-07-12 00:42:14 +02001599 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001600 for (i = 0; i < to_merge_size; i++)
1601 remain[i] = 0;
Guido van Rossum1f121312002-11-14 19:49:16 +00001602
1603 again:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001604 empty_cnt = 0;
1605 for (i = 0; i < to_merge_size; i++) {
1606 PyObject *candidate;
Tim Petersea7f75d2002-12-07 21:39:16 +00001607
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001608 PyObject *cur_list = PyList_GET_ITEM(to_merge, i);
Guido van Rossum1f121312002-11-14 19:49:16 +00001609
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001610 if (remain[i] >= PyList_GET_SIZE(cur_list)) {
1611 empty_cnt++;
1612 continue;
1613 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001614
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001615 /* Choose next candidate for MRO.
Guido van Rossum98f33732002-11-25 21:36:54 +00001616
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001617 The input sequences alone can determine the choice.
1618 If not, choose the class which appears in the MRO
1619 of the earliest direct superclass of the new class.
1620 */
Guido van Rossum98f33732002-11-25 21:36:54 +00001621
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001622 candidate = PyList_GET_ITEM(cur_list, remain[i]);
1623 for (j = 0; j < to_merge_size; j++) {
1624 PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
1625 if (tail_contains(j_lst, remain[j], candidate)) {
1626 goto skip; /* continue outer loop */
1627 }
1628 }
1629 ok = PyList_Append(acc, candidate);
1630 if (ok < 0) {
Victor Stinnera41f0852013-07-12 00:42:14 +02001631 PyMem_FREE(remain);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001632 return -1;
1633 }
1634 for (j = 0; j < to_merge_size; j++) {
1635 PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
1636 if (remain[j] < PyList_GET_SIZE(j_lst) &&
1637 PyList_GET_ITEM(j_lst, remain[j]) == candidate) {
1638 remain[j]++;
1639 }
1640 }
1641 goto again;
1642 skip: ;
1643 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001644
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001645 if (empty_cnt == to_merge_size) {
1646 PyMem_FREE(remain);
1647 return 0;
1648 }
1649 set_mro_error(to_merge, remain);
1650 PyMem_FREE(remain);
1651 return -1;
Guido van Rossum1f121312002-11-14 19:49:16 +00001652}
1653
Tim Peters6d6c1a32001-08-02 04:15:00 +00001654static PyObject *
1655mro_implementation(PyTypeObject *type)
1656{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001657 Py_ssize_t i, n;
1658 int ok;
1659 PyObject *bases, *result;
1660 PyObject *to_merge, *bases_aslist;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001661
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001662 if (type->tp_dict == NULL) {
1663 if (PyType_Ready(type) < 0)
1664 return NULL;
1665 }
Guido van Rossum63517572002-06-18 16:44:57 +00001666
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001667 /* Find a superclass linearization that honors the constraints
1668 of the explicit lists of bases and the constraints implied by
1669 each base class.
Guido van Rossum98f33732002-11-25 21:36:54 +00001670
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001671 to_merge is a list of lists, where each list is a superclass
1672 linearization implied by a base class. The last element of
1673 to_merge is the declared list of bases.
1674 */
Guido van Rossum98f33732002-11-25 21:36:54 +00001675
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001676 bases = type->tp_bases;
1677 n = PyTuple_GET_SIZE(bases);
Guido van Rossum1f121312002-11-14 19:49:16 +00001678
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001679 to_merge = PyList_New(n+1);
1680 if (to_merge == NULL)
1681 return NULL;
Guido van Rossum1f121312002-11-14 19:49:16 +00001682
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001683 for (i = 0; i < n; i++) {
1684 PyObject *base = PyTuple_GET_ITEM(bases, i);
1685 PyObject *parentMRO;
1686 parentMRO = PySequence_List(((PyTypeObject*)base)->tp_mro);
1687 if (parentMRO == NULL) {
1688 Py_DECREF(to_merge);
1689 return NULL;
1690 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001691
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001692 PyList_SET_ITEM(to_merge, i, parentMRO);
1693 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001694
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001695 bases_aslist = PySequence_List(bases);
1696 if (bases_aslist == NULL) {
1697 Py_DECREF(to_merge);
1698 return NULL;
1699 }
1700 /* This is just a basic sanity check. */
1701 if (check_duplicates(bases_aslist) < 0) {
1702 Py_DECREF(to_merge);
1703 Py_DECREF(bases_aslist);
1704 return NULL;
1705 }
1706 PyList_SET_ITEM(to_merge, n, bases_aslist);
Guido van Rossum1f121312002-11-14 19:49:16 +00001707
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001708 result = Py_BuildValue("[O]", (PyObject *)type);
1709 if (result == NULL) {
1710 Py_DECREF(to_merge);
1711 return NULL;
1712 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001713
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001714 ok = pmerge(result, to_merge);
1715 Py_DECREF(to_merge);
1716 if (ok < 0) {
1717 Py_DECREF(result);
1718 return NULL;
1719 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001720
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001721 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001722}
1723
1724static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001725mro_external(PyObject *self)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001726{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001727 PyTypeObject *type = (PyTypeObject *)self;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001728
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001729 return mro_implementation(type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001730}
1731
1732static int
1733mro_internal(PyTypeObject *type)
1734{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001735 PyObject *mro, *result, *tuple;
1736 int checkit = 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001737
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001738 if (Py_TYPE(type) == &PyType_Type) {
1739 result = mro_implementation(type);
1740 }
1741 else {
Benjamin Petersonce798522012-01-22 11:24:29 -05001742 _Py_IDENTIFIER(mro);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001743 checkit = 1;
Benjamin Petersonce798522012-01-22 11:24:29 -05001744 mro = lookup_method((PyObject *)type, &PyId_mro);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001745 if (mro == NULL)
1746 return -1;
1747 result = PyObject_CallObject(mro, NULL);
1748 Py_DECREF(mro);
1749 }
1750 if (result == NULL)
1751 return -1;
1752 tuple = PySequence_Tuple(result);
1753 Py_DECREF(result);
1754 if (tuple == NULL)
1755 return -1;
1756 if (checkit) {
1757 Py_ssize_t i, len;
1758 PyObject *cls;
1759 PyTypeObject *solid;
Armin Rigo037d1e02005-12-29 17:07:39 +00001760
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001761 solid = solid_base(type);
Armin Rigo037d1e02005-12-29 17:07:39 +00001762
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001763 len = PyTuple_GET_SIZE(tuple);
Armin Rigo037d1e02005-12-29 17:07:39 +00001764
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001765 for (i = 0; i < len; i++) {
1766 PyTypeObject *t;
1767 cls = PyTuple_GET_ITEM(tuple, i);
1768 if (!PyType_Check(cls)) {
1769 PyErr_Format(PyExc_TypeError,
1770 "mro() returned a non-class ('%.500s')",
1771 Py_TYPE(cls)->tp_name);
1772 Py_DECREF(tuple);
1773 return -1;
1774 }
1775 t = (PyTypeObject*)cls;
1776 if (!PyType_IsSubtype(solid, solid_base(t))) {
1777 PyErr_Format(PyExc_TypeError,
1778 "mro() returned base with unsuitable layout ('%.500s')",
1779 t->tp_name);
1780 Py_DECREF(tuple);
1781 return -1;
1782 }
1783 }
1784 }
1785 type->tp_mro = tuple;
Christian Heimesa62da1d2008-01-12 19:39:10 +00001786
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001787 type_mro_modified(type, type->tp_mro);
Florent Xiclunaaa6c1d22011-12-12 18:54:29 +01001788 /* corner case: the super class might have been hidden
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001789 from the custom MRO */
1790 type_mro_modified(type, type->tp_bases);
Christian Heimesa62da1d2008-01-12 19:39:10 +00001791
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001792 PyType_Modified(type);
Christian Heimesa62da1d2008-01-12 19:39:10 +00001793
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001794 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001795}
1796
1797
1798/* Calculate the best base amongst multiple base classes.
1799 This is the first one that's on the path to the "solid base". */
1800
1801static PyTypeObject *
1802best_base(PyObject *bases)
1803{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001804 Py_ssize_t i, n;
1805 PyTypeObject *base, *winner, *candidate, *base_i;
1806 PyObject *base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001807
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001808 assert(PyTuple_Check(bases));
1809 n = PyTuple_GET_SIZE(bases);
1810 assert(n > 0);
1811 base = NULL;
1812 winner = NULL;
1813 for (i = 0; i < n; i++) {
1814 base_proto = PyTuple_GET_ITEM(bases, i);
1815 if (!PyType_Check(base_proto)) {
1816 PyErr_SetString(
1817 PyExc_TypeError,
1818 "bases must be types");
1819 return NULL;
1820 }
1821 base_i = (PyTypeObject *)base_proto;
1822 if (base_i->tp_dict == NULL) {
1823 if (PyType_Ready(base_i) < 0)
1824 return NULL;
1825 }
1826 candidate = solid_base(base_i);
1827 if (winner == NULL) {
1828 winner = candidate;
1829 base = base_i;
1830 }
1831 else if (PyType_IsSubtype(winner, candidate))
1832 ;
1833 else if (PyType_IsSubtype(candidate, winner)) {
1834 winner = candidate;
1835 base = base_i;
1836 }
1837 else {
1838 PyErr_SetString(
1839 PyExc_TypeError,
1840 "multiple bases have "
1841 "instance lay-out conflict");
1842 return NULL;
1843 }
1844 }
Florent Xiclunaaa6c1d22011-12-12 18:54:29 +01001845 assert (base != NULL);
1846
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001847 return base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001848}
1849
1850static int
1851extra_ivars(PyTypeObject *type, PyTypeObject *base)
1852{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001853 size_t t_size = type->tp_basicsize;
1854 size_t b_size = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001855
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001856 assert(t_size >= b_size); /* Else type smaller than base! */
1857 if (type->tp_itemsize || base->tp_itemsize) {
1858 /* If itemsize is involved, stricter rules */
1859 return t_size != b_size ||
1860 type->tp_itemsize != base->tp_itemsize;
1861 }
1862 if (type->tp_weaklistoffset && base->tp_weaklistoffset == 0 &&
1863 type->tp_weaklistoffset + sizeof(PyObject *) == t_size &&
1864 type->tp_flags & Py_TPFLAGS_HEAPTYPE)
1865 t_size -= sizeof(PyObject *);
1866 if (type->tp_dictoffset && base->tp_dictoffset == 0 &&
1867 type->tp_dictoffset + sizeof(PyObject *) == t_size &&
1868 type->tp_flags & Py_TPFLAGS_HEAPTYPE)
1869 t_size -= sizeof(PyObject *);
Guido van Rossum9676b222001-08-17 20:32:36 +00001870
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001871 return t_size != b_size;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001872}
1873
1874static PyTypeObject *
1875solid_base(PyTypeObject *type)
1876{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001877 PyTypeObject *base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001878
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001879 if (type->tp_base)
1880 base = solid_base(type->tp_base);
1881 else
1882 base = &PyBaseObject_Type;
1883 if (extra_ivars(type, base))
1884 return type;
1885 else
1886 return base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001887}
1888
Jeremy Hylton938ace62002-07-17 16:30:39 +00001889static void object_dealloc(PyObject *);
1890static int object_init(PyObject *, PyObject *, PyObject *);
1891static int update_slot(PyTypeObject *, PyObject *);
1892static void fixup_slot_dispatchers(PyTypeObject *);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001893
Guido van Rossum360e4b82007-05-14 22:51:27 +00001894/*
1895 * Helpers for __dict__ descriptor. We don't want to expose the dicts
1896 * inherited from various builtin types. The builtin base usually provides
1897 * its own __dict__ descriptor, so we use that when we can.
1898 */
1899static PyTypeObject *
1900get_builtin_base_with_dict(PyTypeObject *type)
1901{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001902 while (type->tp_base != NULL) {
1903 if (type->tp_dictoffset != 0 &&
1904 !(type->tp_flags & Py_TPFLAGS_HEAPTYPE))
1905 return type;
1906 type = type->tp_base;
1907 }
1908 return NULL;
Guido van Rossum360e4b82007-05-14 22:51:27 +00001909}
1910
1911static PyObject *
1912get_dict_descriptor(PyTypeObject *type)
1913{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001914 PyObject *descr;
Guido van Rossum360e4b82007-05-14 22:51:27 +00001915
Victor Stinner3c1e4812012-03-26 22:10:51 +02001916 descr = _PyType_LookupId(type, &PyId___dict__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001917 if (descr == NULL || !PyDescr_IsData(descr))
1918 return NULL;
Guido van Rossum360e4b82007-05-14 22:51:27 +00001919
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001920 return descr;
Guido van Rossum360e4b82007-05-14 22:51:27 +00001921}
1922
1923static void
1924raise_dict_descr_error(PyObject *obj)
1925{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001926 PyErr_Format(PyExc_TypeError,
1927 "this __dict__ descriptor does not support "
1928 "'%.200s' objects", Py_TYPE(obj)->tp_name);
Guido van Rossum360e4b82007-05-14 22:51:27 +00001929}
1930
Tim Peters6d6c1a32001-08-02 04:15:00 +00001931static PyObject *
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001932subtype_dict(PyObject *obj, void *context)
1933{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001934 PyTypeObject *base;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001935
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001936 base = get_builtin_base_with_dict(Py_TYPE(obj));
1937 if (base != NULL) {
1938 descrgetfunc func;
1939 PyObject *descr = get_dict_descriptor(base);
1940 if (descr == NULL) {
1941 raise_dict_descr_error(obj);
1942 return NULL;
1943 }
1944 func = Py_TYPE(descr)->tp_descr_get;
1945 if (func == NULL) {
1946 raise_dict_descr_error(obj);
1947 return NULL;
1948 }
1949 return func(descr, obj, (PyObject *)(Py_TYPE(obj)));
1950 }
Benjamin Peterson8eb12692012-02-19 19:59:10 -05001951 return PyObject_GenericGetDict(obj, context);
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001952}
1953
Guido van Rossum6661be32001-10-26 04:26:12 +00001954static int
1955subtype_setdict(PyObject *obj, PyObject *value, void *context)
1956{
Benjamin Peterson8eb12692012-02-19 19:59:10 -05001957 PyObject *dict, **dictptr;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001958 PyTypeObject *base;
Guido van Rossum6661be32001-10-26 04:26:12 +00001959
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001960 base = get_builtin_base_with_dict(Py_TYPE(obj));
1961 if (base != NULL) {
1962 descrsetfunc func;
1963 PyObject *descr = get_dict_descriptor(base);
1964 if (descr == NULL) {
1965 raise_dict_descr_error(obj);
1966 return -1;
1967 }
1968 func = Py_TYPE(descr)->tp_descr_set;
1969 if (func == NULL) {
1970 raise_dict_descr_error(obj);
1971 return -1;
1972 }
1973 return func(descr, obj, value);
1974 }
Benjamin Peterson8eb12692012-02-19 19:59:10 -05001975 /* Almost like PyObject_GenericSetDict, but allow __dict__ to be deleted. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001976 dictptr = _PyObject_GetDictPtr(obj);
1977 if (dictptr == NULL) {
1978 PyErr_SetString(PyExc_AttributeError,
1979 "This object has no __dict__");
1980 return -1;
1981 }
Benjamin Peterson006c5a22012-02-19 20:36:12 -05001982 if (value != NULL && !PyDict_Check(value)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001983 PyErr_Format(PyExc_TypeError,
1984 "__dict__ must be set to a dictionary, "
1985 "not a '%.200s'", Py_TYPE(value)->tp_name);
1986 return -1;
1987 }
1988 dict = *dictptr;
1989 Py_XINCREF(value);
1990 *dictptr = value;
1991 Py_XDECREF(dict);
1992 return 0;
Guido van Rossum6661be32001-10-26 04:26:12 +00001993}
1994
Guido van Rossumad47da02002-08-12 19:05:44 +00001995static PyObject *
1996subtype_getweakref(PyObject *obj, void *context)
1997{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001998 PyObject **weaklistptr;
1999 PyObject *result;
Guido van Rossumad47da02002-08-12 19:05:44 +00002000
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002001 if (Py_TYPE(obj)->tp_weaklistoffset == 0) {
2002 PyErr_SetString(PyExc_AttributeError,
2003 "This object has no __weakref__");
2004 return NULL;
2005 }
2006 assert(Py_TYPE(obj)->tp_weaklistoffset > 0);
2007 assert(Py_TYPE(obj)->tp_weaklistoffset + sizeof(PyObject *) <=
2008 (size_t)(Py_TYPE(obj)->tp_basicsize));
2009 weaklistptr = (PyObject **)
2010 ((char *)obj + Py_TYPE(obj)->tp_weaklistoffset);
2011 if (*weaklistptr == NULL)
2012 result = Py_None;
2013 else
2014 result = *weaklistptr;
2015 Py_INCREF(result);
2016 return result;
Guido van Rossumad47da02002-08-12 19:05:44 +00002017}
2018
Guido van Rossum373c7412003-01-07 13:41:37 +00002019/* Three variants on the subtype_getsets list. */
2020
2021static PyGetSetDef subtype_getsets_full[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002022 {"__dict__", subtype_dict, subtype_setdict,
2023 PyDoc_STR("dictionary for instance variables (if defined)")},
2024 {"__weakref__", subtype_getweakref, NULL,
2025 PyDoc_STR("list of weak references to the object (if defined)")},
2026 {0}
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00002027};
2028
Guido van Rossum373c7412003-01-07 13:41:37 +00002029static PyGetSetDef subtype_getsets_dict_only[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002030 {"__dict__", subtype_dict, subtype_setdict,
2031 PyDoc_STR("dictionary for instance variables (if defined)")},
2032 {0}
Guido van Rossum373c7412003-01-07 13:41:37 +00002033};
2034
2035static PyGetSetDef subtype_getsets_weakref_only[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002036 {"__weakref__", subtype_getweakref, NULL,
2037 PyDoc_STR("list of weak references to the object (if defined)")},
2038 {0}
Guido van Rossum373c7412003-01-07 13:41:37 +00002039};
2040
Guido van Rossum9923ffe2002-06-04 19:52:53 +00002041static int
2042valid_identifier(PyObject *s)
2043{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002044 if (!PyUnicode_Check(s)) {
2045 PyErr_Format(PyExc_TypeError,
2046 "__slots__ items must be strings, not '%.200s'",
2047 Py_TYPE(s)->tp_name);
2048 return 0;
2049 }
2050 if (!PyUnicode_IsIdentifier(s)) {
2051 PyErr_SetString(PyExc_TypeError,
2052 "__slots__ must be identifiers");
2053 return 0;
2054 }
2055 return 1;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00002056}
2057
Guido van Rossumd8faa362007-04-27 19:54:29 +00002058/* Forward */
2059static int
2060object_init(PyObject *self, PyObject *args, PyObject *kwds);
2061
2062static int
2063type_init(PyObject *cls, PyObject *args, PyObject *kwds)
2064{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002065 int res;
Guido van Rossumd8faa362007-04-27 19:54:29 +00002066
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002067 assert(args != NULL && PyTuple_Check(args));
2068 assert(kwds == NULL || PyDict_Check(kwds));
Guido van Rossumd8faa362007-04-27 19:54:29 +00002069
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002070 if (kwds != NULL && PyDict_Check(kwds) && PyDict_Size(kwds) != 0) {
2071 PyErr_SetString(PyExc_TypeError,
2072 "type.__init__() takes no keyword arguments");
2073 return -1;
2074 }
Guido van Rossumd8faa362007-04-27 19:54:29 +00002075
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002076 if (args != NULL && PyTuple_Check(args) &&
2077 (PyTuple_GET_SIZE(args) != 1 && PyTuple_GET_SIZE(args) != 3)) {
2078 PyErr_SetString(PyExc_TypeError,
2079 "type.__init__() takes 1 or 3 arguments");
2080 return -1;
2081 }
Guido van Rossumd8faa362007-04-27 19:54:29 +00002082
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002083 /* Call object.__init__(self) now. */
2084 /* XXX Could call super(type, cls).__init__() but what's the point? */
2085 args = PyTuple_GetSlice(args, 0, 0);
2086 res = object_init(cls, args, NULL);
2087 Py_DECREF(args);
2088 return res;
Guido van Rossumd8faa362007-04-27 19:54:29 +00002089}
2090
Victor Stinner4ca1cf32012-10-30 23:40:45 +01002091unsigned long
Martin v. Löwis738236d2011-02-05 20:35:29 +00002092PyType_GetFlags(PyTypeObject *type)
2093{
2094 return type->tp_flags;
2095}
2096
Nick Coghlande31b192011-10-23 22:04:16 +10002097/* Determine the most derived metatype. */
2098PyTypeObject *
2099_PyType_CalculateMetaclass(PyTypeObject *metatype, PyObject *bases)
2100{
2101 Py_ssize_t i, nbases;
2102 PyTypeObject *winner;
2103 PyObject *tmp;
2104 PyTypeObject *tmptype;
2105
2106 /* Determine the proper metatype to deal with this,
2107 and check for metatype conflicts while we're at it.
2108 Note that if some other metatype wins to contract,
2109 it's possible that its instances are not types. */
2110
2111 nbases = PyTuple_GET_SIZE(bases);
2112 winner = metatype;
2113 for (i = 0; i < nbases; i++) {
2114 tmp = PyTuple_GET_ITEM(bases, i);
2115 tmptype = Py_TYPE(tmp);
2116 if (PyType_IsSubtype(winner, tmptype))
2117 continue;
2118 if (PyType_IsSubtype(tmptype, winner)) {
2119 winner = tmptype;
2120 continue;
2121 }
2122 /* else: */
2123 PyErr_SetString(PyExc_TypeError,
2124 "metaclass conflict: "
2125 "the metaclass of a derived class "
2126 "must be a (non-strict) subclass "
2127 "of the metaclasses of all its bases");
2128 return NULL;
2129 }
2130 return winner;
2131}
2132
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00002133static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00002134type_new(PyTypeObject *metatype, PyObject *args, PyObject *kwds)
2135{
Victor Stinner6f738742012-02-25 01:22:36 +01002136 PyObject *name, *bases = NULL, *orig_dict, *dict = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002137 static char *kwlist[] = {"name", "bases", "dict", 0};
Victor Stinner6f738742012-02-25 01:22:36 +01002138 PyObject *qualname, *slots = NULL, *tmp, *newslots;
2139 PyTypeObject *type = NULL, *base, *tmptype, *winner;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002140 PyHeapTypeObject *et;
2141 PyMemberDef *mp;
2142 Py_ssize_t i, nbases, nslots, slotoffset, add_dict, add_weak;
2143 int j, may_add_dict, may_add_weak;
Victor Stinner3c1e4812012-03-26 22:10:51 +02002144 _Py_IDENTIFIER(__qualname__);
2145 _Py_IDENTIFIER(__slots__);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002146
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002147 assert(args != NULL && PyTuple_Check(args));
2148 assert(kwds == NULL || PyDict_Check(kwds));
Tim Peters3abca122001-10-27 19:37:48 +00002149
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002150 /* Special case: type(x) should return x->ob_type */
2151 {
2152 const Py_ssize_t nargs = PyTuple_GET_SIZE(args);
2153 const Py_ssize_t nkwds = kwds == NULL ? 0 : PyDict_Size(kwds);
Tim Peters3abca122001-10-27 19:37:48 +00002154
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002155 if (PyType_CheckExact(metatype) && nargs == 1 && nkwds == 0) {
2156 PyObject *x = PyTuple_GET_ITEM(args, 0);
2157 Py_INCREF(Py_TYPE(x));
2158 return (PyObject *) Py_TYPE(x);
2159 }
Tim Peters3abca122001-10-27 19:37:48 +00002160
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002161 /* SF bug 475327 -- if that didn't trigger, we need 3
2162 arguments. but PyArg_ParseTupleAndKeywords below may give
2163 a msg saying type() needs exactly 3. */
2164 if (nargs + nkwds != 3) {
2165 PyErr_SetString(PyExc_TypeError,
2166 "type() takes 1 or 3 arguments");
2167 return NULL;
2168 }
2169 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002170
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002171 /* Check arguments: (name, bases, dict) */
2172 if (!PyArg_ParseTupleAndKeywords(args, kwds, "UO!O!:type", kwlist,
2173 &name,
2174 &PyTuple_Type, &bases,
Victor Stinner6f738742012-02-25 01:22:36 +01002175 &PyDict_Type, &orig_dict))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002176 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002177
Nick Coghlande31b192011-10-23 22:04:16 +10002178 /* Determine the proper metatype to deal with this: */
2179 winner = _PyType_CalculateMetaclass(metatype, bases);
2180 if (winner == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002181 return NULL;
2182 }
Nick Coghlande31b192011-10-23 22:04:16 +10002183
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002184 if (winner != metatype) {
2185 if (winner->tp_new != type_new) /* Pass it to the winner */
2186 return winner->tp_new(winner, args, kwds);
2187 metatype = winner;
2188 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002189
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002190 /* Adjust for empty tuple bases */
Nick Coghlande31b192011-10-23 22:04:16 +10002191 nbases = PyTuple_GET_SIZE(bases);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002192 if (nbases == 0) {
2193 bases = PyTuple_Pack(1, &PyBaseObject_Type);
2194 if (bases == NULL)
Victor Stinner6f738742012-02-25 01:22:36 +01002195 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002196 nbases = 1;
2197 }
2198 else
2199 Py_INCREF(bases);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002200
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002201 /* Calculate best base, and check that all bases are type objects */
2202 base = best_base(bases);
2203 if (base == NULL) {
Victor Stinner6f738742012-02-25 01:22:36 +01002204 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002205 }
2206 if (!PyType_HasFeature(base, Py_TPFLAGS_BASETYPE)) {
2207 PyErr_Format(PyExc_TypeError,
2208 "type '%.100s' is not an acceptable base type",
2209 base->tp_name);
Victor Stinner6f738742012-02-25 01:22:36 +01002210 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002211 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002212
Victor Stinner6f738742012-02-25 01:22:36 +01002213 dict = PyDict_Copy(orig_dict);
2214 if (dict == NULL)
2215 goto error;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002216
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002217 /* Check for a __slots__ sequence variable in dict, and count it */
Victor Stinner3c1e4812012-03-26 22:10:51 +02002218 slots = _PyDict_GetItemId(dict, &PyId___slots__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002219 nslots = 0;
2220 add_dict = 0;
2221 add_weak = 0;
2222 may_add_dict = base->tp_dictoffset == 0;
2223 may_add_weak = base->tp_weaklistoffset == 0 && base->tp_itemsize == 0;
2224 if (slots == NULL) {
2225 if (may_add_dict) {
2226 add_dict++;
2227 }
2228 if (may_add_weak) {
2229 add_weak++;
2230 }
2231 }
2232 else {
2233 /* Have slots */
Guido van Rossumad47da02002-08-12 19:05:44 +00002234
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002235 /* Make it into a tuple */
2236 if (PyUnicode_Check(slots))
2237 slots = PyTuple_Pack(1, slots);
2238 else
2239 slots = PySequence_Tuple(slots);
Victor Stinner6f738742012-02-25 01:22:36 +01002240 if (slots == NULL)
2241 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002242 assert(PyTuple_Check(slots));
Guido van Rossumad47da02002-08-12 19:05:44 +00002243
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002244 /* Are slots allowed? */
2245 nslots = PyTuple_GET_SIZE(slots);
2246 if (nslots > 0 && base->tp_itemsize != 0) {
2247 PyErr_Format(PyExc_TypeError,
2248 "nonempty __slots__ "
2249 "not supported for subtype of '%s'",
2250 base->tp_name);
Victor Stinner6f738742012-02-25 01:22:36 +01002251 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002252 }
Guido van Rossumad47da02002-08-12 19:05:44 +00002253
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002254 /* Check for valid slot names and two special cases */
2255 for (i = 0; i < nslots; i++) {
2256 PyObject *tmp = PyTuple_GET_ITEM(slots, i);
2257 if (!valid_identifier(tmp))
Victor Stinner6f738742012-02-25 01:22:36 +01002258 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002259 assert(PyUnicode_Check(tmp));
Victor Stinnerad14ccd2013-11-07 00:46:04 +01002260 if (_PyUnicode_CompareWithId(tmp, &PyId___dict__) == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002261 if (!may_add_dict || add_dict) {
2262 PyErr_SetString(PyExc_TypeError,
2263 "__dict__ slot disallowed: "
2264 "we already got one");
Victor Stinner6f738742012-02-25 01:22:36 +01002265 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002266 }
2267 add_dict++;
2268 }
2269 if (PyUnicode_CompareWithASCIIString(tmp, "__weakref__") == 0) {
2270 if (!may_add_weak || add_weak) {
2271 PyErr_SetString(PyExc_TypeError,
2272 "__weakref__ slot disallowed: "
2273 "either we already got one, "
2274 "or __itemsize__ != 0");
Victor Stinner6f738742012-02-25 01:22:36 +01002275 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002276 }
2277 add_weak++;
2278 }
2279 }
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00002280
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002281 /* Copy slots into a list, mangle names and sort them.
2282 Sorted names are needed for __class__ assignment.
2283 Convert them back to tuple at the end.
2284 */
2285 newslots = PyList_New(nslots - add_dict - add_weak);
2286 if (newslots == NULL)
Victor Stinner6f738742012-02-25 01:22:36 +01002287 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002288 for (i = j = 0; i < nslots; i++) {
2289 tmp = PyTuple_GET_ITEM(slots, i);
2290 if ((add_dict &&
Victor Stinnerad14ccd2013-11-07 00:46:04 +01002291 _PyUnicode_CompareWithId(tmp, &PyId___dict__) == 0) ||
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002292 (add_weak &&
2293 PyUnicode_CompareWithASCIIString(tmp, "__weakref__") == 0))
2294 continue;
2295 tmp =_Py_Mangle(name, tmp);
Benjamin Petersonae13c882011-08-16 22:26:48 -05002296 if (!tmp) {
2297 Py_DECREF(newslots);
Victor Stinner6f738742012-02-25 01:22:36 +01002298 goto error;
Benjamin Petersonae13c882011-08-16 22:26:48 -05002299 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002300 PyList_SET_ITEM(newslots, j, tmp);
Benjamin Petersonc4085c82011-08-16 18:53:26 -05002301 if (PyDict_GetItem(dict, tmp)) {
2302 PyErr_Format(PyExc_ValueError,
2303 "%R in __slots__ conflicts with class variable",
2304 tmp);
Benjamin Petersond17cefc2011-08-16 22:28:23 -05002305 Py_DECREF(newslots);
Victor Stinner6f738742012-02-25 01:22:36 +01002306 goto error;
Benjamin Petersonc4085c82011-08-16 18:53:26 -05002307 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002308 j++;
2309 }
2310 assert(j == nslots - add_dict - add_weak);
2311 nslots = j;
Victor Stinner6f738742012-02-25 01:22:36 +01002312 Py_CLEAR(slots);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002313 if (PyList_Sort(newslots) == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002314 Py_DECREF(newslots);
Victor Stinner6f738742012-02-25 01:22:36 +01002315 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002316 }
2317 slots = PyList_AsTuple(newslots);
2318 Py_DECREF(newslots);
Victor Stinner6f738742012-02-25 01:22:36 +01002319 if (slots == NULL)
2320 goto error;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00002321
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002322 /* Secondary bases may provide weakrefs or dict */
2323 if (nbases > 1 &&
2324 ((may_add_dict && !add_dict) ||
2325 (may_add_weak && !add_weak))) {
2326 for (i = 0; i < nbases; i++) {
2327 tmp = PyTuple_GET_ITEM(bases, i);
2328 if (tmp == (PyObject *)base)
2329 continue; /* Skip primary base */
2330 assert(PyType_Check(tmp));
2331 tmptype = (PyTypeObject *)tmp;
2332 if (may_add_dict && !add_dict &&
2333 tmptype->tp_dictoffset != 0)
2334 add_dict++;
2335 if (may_add_weak && !add_weak &&
2336 tmptype->tp_weaklistoffset != 0)
2337 add_weak++;
2338 if (may_add_dict && !add_dict)
2339 continue;
2340 if (may_add_weak && !add_weak)
2341 continue;
2342 /* Nothing more to check */
2343 break;
2344 }
2345 }
2346 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002347
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002348 /* Allocate the type object */
2349 type = (PyTypeObject *)metatype->tp_alloc(metatype, nslots);
Victor Stinner6f738742012-02-25 01:22:36 +01002350 if (type == NULL)
2351 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002352
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002353 /* Keep name and slots alive in the extended type object */
2354 et = (PyHeapTypeObject *)type;
2355 Py_INCREF(name);
2356 et->ht_name = name;
2357 et->ht_slots = slots;
Victor Stinner6f738742012-02-25 01:22:36 +01002358 slots = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002359
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002360 /* Initialize tp_flags */
2361 type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE |
Antoine Pitrou796564c2013-07-30 19:59:21 +02002362 Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_FINALIZE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002363 if (base->tp_flags & Py_TPFLAGS_HAVE_GC)
2364 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossumdc91b992001-08-08 22:26:22 +00002365
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002366 /* Initialize essential fields */
2367 type->tp_as_number = &et->as_number;
2368 type->tp_as_sequence = &et->as_sequence;
2369 type->tp_as_mapping = &et->as_mapping;
2370 type->tp_as_buffer = &et->as_buffer;
2371 type->tp_name = _PyUnicode_AsString(name);
Victor Stinner6f738742012-02-25 01:22:36 +01002372 if (!type->tp_name)
2373 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002374
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002375 /* Set tp_base and tp_bases */
2376 type->tp_bases = bases;
Victor Stinner6f738742012-02-25 01:22:36 +01002377 bases = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002378 Py_INCREF(base);
2379 type->tp_base = base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002380
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002381 /* Initialize tp_dict from passed-in dict */
Victor Stinner6f738742012-02-25 01:22:36 +01002382 Py_INCREF(dict);
2383 type->tp_dict = dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002384
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002385 /* Set __module__ in the dict */
Victor Stinner3c1e4812012-03-26 22:10:51 +02002386 if (_PyDict_GetItemId(dict, &PyId___module__) == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002387 tmp = PyEval_GetGlobals();
2388 if (tmp != NULL) {
Victor Stinner3c1e4812012-03-26 22:10:51 +02002389 tmp = _PyDict_GetItemId(tmp, &PyId___name__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002390 if (tmp != NULL) {
Victor Stinner3c1e4812012-03-26 22:10:51 +02002391 if (_PyDict_SetItemId(dict, &PyId___module__,
2392 tmp) < 0)
Victor Stinner6f738742012-02-25 01:22:36 +01002393 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002394 }
2395 }
2396 }
Guido van Rossumc3542212001-08-16 09:18:56 +00002397
Victor Stinner6f738742012-02-25 01:22:36 +01002398 /* Set ht_qualname to dict['__qualname__'] if available, else to
2399 __name__. The __qualname__ accessor will look for ht_qualname.
2400 */
Victor Stinner3c1e4812012-03-26 22:10:51 +02002401 qualname = _PyDict_GetItemId(dict, &PyId___qualname__);
Victor Stinner6f738742012-02-25 01:22:36 +01002402 if (qualname != NULL) {
2403 if (!PyUnicode_Check(qualname)) {
2404 PyErr_Format(PyExc_TypeError,
2405 "type __qualname__ must be a str, not %s",
2406 Py_TYPE(qualname)->tp_name);
2407 goto error;
2408 }
2409 }
Benjamin Peterson8afa7fa2012-10-30 23:51:03 -04002410 et->ht_qualname = qualname ? qualname : et->ht_name;
2411 Py_INCREF(et->ht_qualname);
2412 if (qualname != NULL && PyDict_DelItem(dict, PyId___qualname__.object) < 0)
2413 goto error;
Victor Stinner6f738742012-02-25 01:22:36 +01002414
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002415 /* Set tp_doc to a copy of dict['__doc__'], if the latter is there
2416 and is a string. The __doc__ accessor will first look for tp_doc;
2417 if that fails, it will still look into __dict__.
2418 */
2419 {
Victor Stinner3c1e4812012-03-26 22:10:51 +02002420 PyObject *doc = _PyDict_GetItemId(dict, &PyId___doc__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002421 if (doc != NULL && PyUnicode_Check(doc)) {
2422 Py_ssize_t len;
2423 char *doc_str;
2424 char *tp_doc;
Alexandre Vassalottia85998a2008-05-03 18:24:43 +00002425
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002426 doc_str = _PyUnicode_AsString(doc);
Victor Stinner6f738742012-02-25 01:22:36 +01002427 if (doc_str == NULL)
2428 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002429 /* Silently truncate the docstring if it contains null bytes. */
2430 len = strlen(doc_str);
2431 tp_doc = (char *)PyObject_MALLOC(len + 1);
Victor Stinner53510cd2013-07-15 19:34:20 +02002432 if (tp_doc == NULL) {
2433 PyErr_NoMemory();
Victor Stinner6f738742012-02-25 01:22:36 +01002434 goto error;
Victor Stinner53510cd2013-07-15 19:34:20 +02002435 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002436 memcpy(tp_doc, doc_str, len + 1);
2437 type->tp_doc = tp_doc;
2438 }
2439 }
Tim Peters2f93e282001-10-04 05:27:00 +00002440
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002441 /* Special-case __new__: if it's a plain function,
2442 make it a static function */
Victor Stinner3c1e4812012-03-26 22:10:51 +02002443 tmp = _PyDict_GetItemId(dict, &PyId___new__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002444 if (tmp != NULL && PyFunction_Check(tmp)) {
2445 tmp = PyStaticMethod_New(tmp);
Victor Stinner6f738742012-02-25 01:22:36 +01002446 if (tmp == NULL)
2447 goto error;
Victor Stinner3c1e4812012-03-26 22:10:51 +02002448 if (_PyDict_SetItemId(dict, &PyId___new__, tmp) < 0)
2449 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002450 Py_DECREF(tmp);
2451 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002452
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002453 /* Add descriptors for custom slots from __slots__, or for __dict__ */
2454 mp = PyHeapType_GET_MEMBERS(et);
2455 slotoffset = base->tp_basicsize;
Victor Stinner6f738742012-02-25 01:22:36 +01002456 if (et->ht_slots != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002457 for (i = 0; i < nslots; i++, mp++) {
2458 mp->name = _PyUnicode_AsString(
Victor Stinner6f738742012-02-25 01:22:36 +01002459 PyTuple_GET_ITEM(et->ht_slots, i));
2460 if (mp->name == NULL)
2461 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002462 mp->type = T_OBJECT_EX;
2463 mp->offset = slotoffset;
Guido van Rossumd8faa362007-04-27 19:54:29 +00002464
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002465 /* __dict__ and __weakref__ are already filtered out */
2466 assert(strcmp(mp->name, "__dict__") != 0);
2467 assert(strcmp(mp->name, "__weakref__") != 0);
Guido van Rossumd8faa362007-04-27 19:54:29 +00002468
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002469 slotoffset += sizeof(PyObject *);
2470 }
2471 }
2472 if (add_dict) {
2473 if (base->tp_itemsize)
2474 type->tp_dictoffset = -(long)sizeof(PyObject *);
2475 else
2476 type->tp_dictoffset = slotoffset;
2477 slotoffset += sizeof(PyObject *);
2478 }
2479 if (add_weak) {
2480 assert(!base->tp_itemsize);
2481 type->tp_weaklistoffset = slotoffset;
2482 slotoffset += sizeof(PyObject *);
2483 }
2484 type->tp_basicsize = slotoffset;
2485 type->tp_itemsize = base->tp_itemsize;
2486 type->tp_members = PyHeapType_GET_MEMBERS(et);
Guido van Rossum373c7412003-01-07 13:41:37 +00002487
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002488 if (type->tp_weaklistoffset && type->tp_dictoffset)
2489 type->tp_getset = subtype_getsets_full;
2490 else if (type->tp_weaklistoffset && !type->tp_dictoffset)
2491 type->tp_getset = subtype_getsets_weakref_only;
2492 else if (!type->tp_weaklistoffset && type->tp_dictoffset)
2493 type->tp_getset = subtype_getsets_dict_only;
2494 else
2495 type->tp_getset = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002496
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002497 /* Special case some slots */
2498 if (type->tp_dictoffset != 0 || nslots > 0) {
2499 if (base->tp_getattr == NULL && base->tp_getattro == NULL)
2500 type->tp_getattro = PyObject_GenericGetAttr;
2501 if (base->tp_setattr == NULL && base->tp_setattro == NULL)
2502 type->tp_setattro = PyObject_GenericSetAttr;
2503 }
2504 type->tp_dealloc = subtype_dealloc;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002505
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002506 /* Enable GC unless there are really no instance variables possible */
2507 if (!(type->tp_basicsize == sizeof(PyObject) &&
2508 type->tp_itemsize == 0))
2509 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossum9475a232001-10-05 20:51:39 +00002510
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002511 /* Always override allocation strategy to use regular heap */
2512 type->tp_alloc = PyType_GenericAlloc;
2513 if (type->tp_flags & Py_TPFLAGS_HAVE_GC) {
2514 type->tp_free = PyObject_GC_Del;
2515 type->tp_traverse = subtype_traverse;
2516 type->tp_clear = subtype_clear;
2517 }
2518 else
2519 type->tp_free = PyObject_Del;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002520
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002521 /* Initialize the rest */
Victor Stinner6f738742012-02-25 01:22:36 +01002522 if (PyType_Ready(type) < 0)
2523 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002524
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002525 /* Put the proper slots in place */
2526 fixup_slot_dispatchers(type);
Guido van Rossumf040ede2001-08-07 16:40:56 +00002527
Benjamin Petersondf813792014-03-17 15:57:17 -05002528 if (type->tp_dictoffset) {
2529 et->ht_cached_keys = _PyDict_NewKeysForClass();
2530 }
2531
Victor Stinner6f738742012-02-25 01:22:36 +01002532 Py_DECREF(dict);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002533 return (PyObject *)type;
Victor Stinner6f738742012-02-25 01:22:36 +01002534
2535error:
2536 Py_XDECREF(dict);
2537 Py_XDECREF(bases);
2538 Py_XDECREF(slots);
2539 Py_XDECREF(type);
2540 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002541}
2542
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002543static short slotoffsets[] = {
2544 -1, /* invalid slot */
2545#include "typeslots.inc"
2546};
2547
Benjamin Petersone28108c2012-01-29 20:13:18 -05002548PyObject *
Martin v. Löwis9c564092012-06-23 23:20:45 +02002549PyType_FromSpecWithBases(PyType_Spec *spec, PyObject *bases)
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002550{
2551 PyHeapTypeObject *res = (PyHeapTypeObject*)PyType_GenericAlloc(&PyType_Type, 0);
Martin v. Löwis9c564092012-06-23 23:20:45 +02002552 PyTypeObject *type, *base;
2553 char *s;
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002554 char *res_start = (char*)res;
2555 PyType_Slot *slot;
Victor Stinner54e4ca72013-07-11 22:42:25 +02002556
Martin v. Löwis9c564092012-06-23 23:20:45 +02002557 /* Set the type name and qualname */
2558 s = strrchr(spec->name, '.');
2559 if (s == NULL)
2560 s = (char*)spec->name;
2561 else
2562 s++;
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002563
Martin v. Löwis5e06a5d2011-02-21 16:24:00 +00002564 if (res == NULL)
Antoine Pitroubb78f572012-06-24 00:18:27 +02002565 return NULL;
2566 type = &res->ht_type;
Antoine Pitrou66a3a7e2012-06-24 00:42:59 +02002567 /* The flags must be initialized early, before the GC traverses us */
2568 type->tp_flags = spec->flags | Py_TPFLAGS_HEAPTYPE;
Martin v. Löwis9c564092012-06-23 23:20:45 +02002569 res->ht_name = PyUnicode_FromString(s);
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002570 if (!res->ht_name)
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002571 goto fail;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002572 res->ht_qualname = res->ht_name;
2573 Py_INCREF(res->ht_qualname);
Antoine Pitroubb78f572012-06-24 00:18:27 +02002574 type->tp_name = spec->name;
2575 if (!type->tp_name)
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002576 goto fail;
Victor Stinner54e4ca72013-07-11 22:42:25 +02002577
Martin v. Löwis9c564092012-06-23 23:20:45 +02002578 /* Adjust for empty tuple bases */
2579 if (!bases) {
2580 base = &PyBaseObject_Type;
2581 /* See whether Py_tp_base(s) was specified */
2582 for (slot = spec->slots; slot->slot; slot++) {
2583 if (slot->slot == Py_tp_base)
2584 base = slot->pfunc;
2585 else if (slot->slot == Py_tp_bases) {
2586 bases = slot->pfunc;
2587 Py_INCREF(bases);
2588 }
2589 }
2590 if (!bases)
2591 bases = PyTuple_Pack(1, base);
2592 if (!bases)
2593 goto fail;
2594 }
2595 else
2596 Py_INCREF(bases);
2597
2598 /* Calculate best base, and check that all bases are type objects */
2599 base = best_base(bases);
2600 if (base == NULL) {
2601 goto fail;
2602 }
2603 if (!PyType_HasFeature(base, Py_TPFLAGS_BASETYPE)) {
2604 PyErr_Format(PyExc_TypeError,
2605 "type '%.100s' is not an acceptable base type",
2606 base->tp_name);
2607 goto fail;
2608 }
2609
Martin v. Löwis9c564092012-06-23 23:20:45 +02002610 /* Initialize essential fields */
2611 type->tp_as_number = &res->as_number;
2612 type->tp_as_sequence = &res->as_sequence;
2613 type->tp_as_mapping = &res->as_mapping;
2614 type->tp_as_buffer = &res->as_buffer;
2615 /* Set tp_base and tp_bases */
2616 type->tp_bases = bases;
2617 bases = NULL;
2618 Py_INCREF(base);
2619 type->tp_base = base;
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002620
Antoine Pitroubb78f572012-06-24 00:18:27 +02002621 type->tp_basicsize = spec->basicsize;
2622 type->tp_itemsize = spec->itemsize;
Victor Stinner0fcab4a2011-01-04 12:59:15 +00002623
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002624 for (slot = spec->slots; slot->slot; slot++) {
Victor Stinner12174a52014-08-15 23:17:38 +02002625 if (slot->slot < 0
2626 || (size_t)slot->slot >= Py_ARRAY_LENGTH(slotoffsets)) {
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002627 PyErr_SetString(PyExc_RuntimeError, "invalid slot offset");
2628 goto fail;
2629 }
Martin v. Löwis9c564092012-06-23 23:20:45 +02002630 if (slot->slot == Py_tp_base || slot->slot == Py_tp_bases)
2631 /* Processed above */
2632 continue;
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002633 *(void**)(res_start + slotoffsets[slot->slot]) = slot->pfunc;
Georg Brandl032400b2011-02-19 21:47:02 +00002634
2635 /* need to make a copy of the docstring slot, which usually
2636 points to a static string literal */
2637 if (slot->slot == Py_tp_doc) {
Larry Hastings2623c8c2014-02-08 22:15:29 -08002638 const char *old_doc = _PyType_DocWithoutSignature(type->tp_name, slot->pfunc);
Larry Hastings5c661892014-01-24 06:17:25 -08002639 size_t len = strlen(old_doc)+1;
Georg Brandl032400b2011-02-19 21:47:02 +00002640 char *tp_doc = PyObject_MALLOC(len);
Victor Stinner53510cd2013-07-15 19:34:20 +02002641 if (tp_doc == NULL) {
2642 PyErr_NoMemory();
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002643 goto fail;
Victor Stinner53510cd2013-07-15 19:34:20 +02002644 }
Larry Hastings5c661892014-01-24 06:17:25 -08002645 memcpy(tp_doc, old_doc, len);
Antoine Pitroubb78f572012-06-24 00:18:27 +02002646 type->tp_doc = tp_doc;
Georg Brandl032400b2011-02-19 21:47:02 +00002647 }
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002648 }
Antoine Pitroubb78f572012-06-24 00:18:27 +02002649 if (type->tp_dealloc == NULL) {
Antoine Pitrou99cc6292012-06-23 14:42:38 +02002650 /* It's a heap type, so needs the heap types' dealloc.
2651 subtype_dealloc will call the base type's tp_dealloc, if
2652 necessary. */
Antoine Pitroubb78f572012-06-24 00:18:27 +02002653 type->tp_dealloc = subtype_dealloc;
Antoine Pitrou99cc6292012-06-23 14:42:38 +02002654 }
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002655
Antoine Pitroubb78f572012-06-24 00:18:27 +02002656 if (PyType_Ready(type) < 0)
Benjamin Peterson2652d252012-01-29 20:16:37 -05002657 goto fail;
2658
Benjamin Petersondf813792014-03-17 15:57:17 -05002659 if (type->tp_dictoffset) {
2660 res->ht_cached_keys = _PyDict_NewKeysForClass();
2661 }
2662
Martin v. Löwis9c564092012-06-23 23:20:45 +02002663 /* Set type.__module__ */
2664 s = strrchr(spec->name, '.');
2665 if (s != NULL)
Victor Stinner54e4ca72013-07-11 22:42:25 +02002666 _PyDict_SetItemId(type->tp_dict, &PyId___module__,
Martin v. Löwis9c564092012-06-23 23:20:45 +02002667 PyUnicode_FromStringAndSize(
2668 spec->name, (Py_ssize_t)(s - spec->name)));
2669
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002670 return (PyObject*)res;
Victor Stinner0fcab4a2011-01-04 12:59:15 +00002671
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002672 fail:
2673 Py_DECREF(res);
2674 return NULL;
2675}
2676
Martin v. Löwis9c564092012-06-23 23:20:45 +02002677PyObject *
2678PyType_FromSpec(PyType_Spec *spec)
2679{
2680 return PyType_FromSpecWithBases(spec, NULL);
2681}
2682
Martin v. Löwisca7b0462014-02-04 09:33:05 +01002683void *
2684PyType_GetSlot(PyTypeObject *type, int slot)
2685{
Victor Stinner12174a52014-08-15 23:17:38 +02002686 if (!PyType_HasFeature(type, Py_TPFLAGS_HEAPTYPE) || slot < 0) {
Martin v. Löwisca7b0462014-02-04 09:33:05 +01002687 PyErr_BadInternalCall();
2688 return NULL;
2689 }
Victor Stinner12174a52014-08-15 23:17:38 +02002690 if ((size_t)slot >= Py_ARRAY_LENGTH(slotoffsets)) {
Martin v. Löwisca7b0462014-02-04 09:33:05 +01002691 /* Extension module requesting slot from a future version */
2692 return NULL;
2693 }
2694 return *(void**)(((char*)type) + slotoffsets[slot]);
2695}
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002696
Tim Peters6d6c1a32001-08-02 04:15:00 +00002697/* Internal API to look for a name through the MRO.
2698 This returns a borrowed reference, and doesn't set an exception! */
2699PyObject *
2700_PyType_Lookup(PyTypeObject *type, PyObject *name)
2701{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002702 Py_ssize_t i, n;
2703 PyObject *mro, *res, *base, *dict;
2704 unsigned int h;
Christian Heimesa62da1d2008-01-12 19:39:10 +00002705
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002706 if (MCACHE_CACHEABLE_NAME(name) &&
2707 PyType_HasFeature(type, Py_TPFLAGS_VALID_VERSION_TAG)) {
2708 /* fast path */
2709 h = MCACHE_HASH_METHOD(type, name);
2710 if (method_cache[h].version == type->tp_version_tag &&
2711 method_cache[h].name == name)
2712 return method_cache[h].value;
2713 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002714
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002715 /* Look in tp_dict of types in MRO */
2716 mro = type->tp_mro;
Guido van Rossum23094982002-06-10 14:30:43 +00002717
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002718 /* If mro is NULL, the type is either not yet initialized
2719 by PyType_Ready(), or already cleared by type_clear().
2720 Either way the safest thing to do is to return NULL. */
2721 if (mro == NULL)
2722 return NULL;
Guido van Rossum23094982002-06-10 14:30:43 +00002723
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002724 res = NULL;
Victor Stinnerd74782b2012-03-09 00:39:08 +01002725 /* keep a strong reference to mro because type->tp_mro can be replaced
2726 during PyDict_GetItem(dict, name) */
2727 Py_INCREF(mro);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002728 assert(PyTuple_Check(mro));
2729 n = PyTuple_GET_SIZE(mro);
2730 for (i = 0; i < n; i++) {
2731 base = PyTuple_GET_ITEM(mro, i);
2732 assert(PyType_Check(base));
2733 dict = ((PyTypeObject *)base)->tp_dict;
2734 assert(dict && PyDict_Check(dict));
2735 res = PyDict_GetItem(dict, name);
2736 if (res != NULL)
2737 break;
2738 }
Victor Stinnerd74782b2012-03-09 00:39:08 +01002739 Py_DECREF(mro);
Christian Heimesa62da1d2008-01-12 19:39:10 +00002740
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002741 if (MCACHE_CACHEABLE_NAME(name) && assign_version_tag(type)) {
2742 h = MCACHE_HASH_METHOD(type, name);
2743 method_cache[h].version = type->tp_version_tag;
2744 method_cache[h].value = res; /* borrowed */
2745 Py_INCREF(name);
2746 Py_DECREF(method_cache[h].name);
2747 method_cache[h].name = name;
2748 }
2749 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002750}
2751
Raymond Hettinger2ff21902013-10-01 00:55:43 -07002752PyObject *
Victor Stinner3c1e4812012-03-26 22:10:51 +02002753_PyType_LookupId(PyTypeObject *type, struct _Py_Identifier *name)
2754{
2755 PyObject *oname;
2756 oname = _PyUnicode_FromId(name); /* borrowed */
2757 if (oname == NULL)
2758 return NULL;
2759 return _PyType_Lookup(type, oname);
2760}
2761
Tim Peters6d6c1a32001-08-02 04:15:00 +00002762/* This is similar to PyObject_GenericGetAttr(),
2763 but uses _PyType_Lookup() instead of just looking in type->tp_dict. */
2764static PyObject *
2765type_getattro(PyTypeObject *type, PyObject *name)
2766{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002767 PyTypeObject *metatype = Py_TYPE(type);
2768 PyObject *meta_attribute, *attribute;
2769 descrgetfunc meta_get;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002770
Benjamin Peterson16d84ac2012-03-16 09:32:59 -05002771 if (!PyUnicode_Check(name)) {
2772 PyErr_Format(PyExc_TypeError,
2773 "attribute name must be string, not '%.200s'",
2774 name->ob_type->tp_name);
2775 return NULL;
2776 }
2777
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002778 /* Initialize this type (we'll assume the metatype is initialized) */
2779 if (type->tp_dict == NULL) {
2780 if (PyType_Ready(type) < 0)
2781 return NULL;
2782 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002783
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002784 /* No readable descriptor found yet */
2785 meta_get = NULL;
Tim Peters34592512002-07-11 06:23:50 +00002786
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002787 /* Look for the attribute in the metatype */
2788 meta_attribute = _PyType_Lookup(metatype, name);
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002789
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002790 if (meta_attribute != NULL) {
2791 meta_get = Py_TYPE(meta_attribute)->tp_descr_get;
Tim Peters34592512002-07-11 06:23:50 +00002792
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002793 if (meta_get != NULL && PyDescr_IsData(meta_attribute)) {
2794 /* Data descriptors implement tp_descr_set to intercept
2795 * writes. Assume the attribute is not overridden in
2796 * type's tp_dict (and bases): call the descriptor now.
2797 */
2798 return meta_get(meta_attribute, (PyObject *)type,
2799 (PyObject *)metatype);
2800 }
2801 Py_INCREF(meta_attribute);
2802 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002803
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002804 /* No data descriptor found on metatype. Look in tp_dict of this
2805 * type and its bases */
2806 attribute = _PyType_Lookup(type, name);
2807 if (attribute != NULL) {
2808 /* Implement descriptor functionality, if any */
2809 descrgetfunc local_get = Py_TYPE(attribute)->tp_descr_get;
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00002810
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002811 Py_XDECREF(meta_attribute);
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00002812
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002813 if (local_get != NULL) {
2814 /* NULL 2nd argument indicates the descriptor was
2815 * found on the target object itself (or a base) */
2816 return local_get(attribute, (PyObject *)NULL,
2817 (PyObject *)type);
2818 }
Tim Peters34592512002-07-11 06:23:50 +00002819
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002820 Py_INCREF(attribute);
2821 return attribute;
2822 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002823
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002824 /* No attribute found in local __dict__ (or bases): use the
2825 * descriptor from the metatype, if any */
2826 if (meta_get != NULL) {
2827 PyObject *res;
2828 res = meta_get(meta_attribute, (PyObject *)type,
2829 (PyObject *)metatype);
2830 Py_DECREF(meta_attribute);
2831 return res;
2832 }
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002833
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002834 /* If an ordinary attribute was found on the metatype, return it now */
2835 if (meta_attribute != NULL) {
2836 return meta_attribute;
2837 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002838
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002839 /* Give up */
2840 PyErr_Format(PyExc_AttributeError,
2841 "type object '%.50s' has no attribute '%U'",
2842 type->tp_name, name);
2843 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002844}
2845
2846static int
2847type_setattro(PyTypeObject *type, PyObject *name, PyObject *value)
2848{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002849 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
2850 PyErr_Format(
2851 PyExc_TypeError,
2852 "can't set attributes of built-in/extension type '%s'",
2853 type->tp_name);
2854 return -1;
2855 }
2856 if (PyObject_GenericSetAttr((PyObject *)type, name, value) < 0)
2857 return -1;
2858 return update_slot(type, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002859}
2860
Benjamin Peterson64acccf2012-04-27 15:07:36 -04002861extern void
2862_PyDictKeys_DecRef(PyDictKeysObject *keys);
2863
Tim Peters6d6c1a32001-08-02 04:15:00 +00002864static void
2865type_dealloc(PyTypeObject *type)
2866{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002867 PyHeapTypeObject *et;
Antoine Pitrou84745ab2013-10-29 21:31:25 +01002868 PyObject *tp, *val, *tb;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002869
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002870 /* Assert this is a heap-allocated type object */
2871 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
2872 _PyObject_GC_UNTRACK(type);
Antoine Pitrou84745ab2013-10-29 21:31:25 +01002873 PyErr_Fetch(&tp, &val, &tb);
2874 remove_all_subclasses(type, type->tp_bases);
2875 PyErr_Restore(tp, val, tb);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002876 PyObject_ClearWeakRefs((PyObject *)type);
2877 et = (PyHeapTypeObject *)type;
2878 Py_XDECREF(type->tp_base);
2879 Py_XDECREF(type->tp_dict);
2880 Py_XDECREF(type->tp_bases);
2881 Py_XDECREF(type->tp_mro);
2882 Py_XDECREF(type->tp_cache);
2883 Py_XDECREF(type->tp_subclasses);
2884 /* A type's tp_doc is heap allocated, unlike the tp_doc slots
2885 * of most other objects. It's okay to cast it to char *.
2886 */
2887 PyObject_Free((char *)type->tp_doc);
2888 Py_XDECREF(et->ht_name);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002889 Py_XDECREF(et->ht_qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002890 Py_XDECREF(et->ht_slots);
Benjamin Peterson64acccf2012-04-27 15:07:36 -04002891 if (et->ht_cached_keys)
2892 _PyDictKeys_DecRef(et->ht_cached_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002893 Py_TYPE(type)->tp_free((PyObject *)type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002894}
2895
Guido van Rossum1c450732001-10-08 15:18:27 +00002896static PyObject *
2897type_subclasses(PyTypeObject *type, PyObject *args_ignored)
2898{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002899 PyObject *list, *raw, *ref;
Antoine Pitrou84745ab2013-10-29 21:31:25 +01002900 Py_ssize_t i;
Guido van Rossum1c450732001-10-08 15:18:27 +00002901
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002902 list = PyList_New(0);
2903 if (list == NULL)
2904 return NULL;
2905 raw = type->tp_subclasses;
2906 if (raw == NULL)
2907 return list;
Antoine Pitrou84745ab2013-10-29 21:31:25 +01002908 assert(PyDict_CheckExact(raw));
2909 i = 0;
2910 while (PyDict_Next(raw, &i, NULL, &ref)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002911 assert(PyWeakref_CheckRef(ref));
2912 ref = PyWeakref_GET_OBJECT(ref);
2913 if (ref != Py_None) {
2914 if (PyList_Append(list, ref) < 0) {
2915 Py_DECREF(list);
2916 return NULL;
2917 }
2918 }
2919 }
2920 return list;
Guido van Rossum1c450732001-10-08 15:18:27 +00002921}
2922
Guido van Rossum47374822007-08-02 16:48:17 +00002923static PyObject *
2924type_prepare(PyObject *self, PyObject *args, PyObject *kwds)
2925{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002926 return PyDict_New();
Guido van Rossum47374822007-08-02 16:48:17 +00002927}
2928
Victor Stinner63941882011-09-29 00:42:28 +02002929/*
Benjamin Peterson82b00c12011-05-24 11:09:06 -05002930 Merge the __dict__ of aclass into dict, and recursively also all
2931 the __dict__s of aclass's base classes. The order of merging isn't
2932 defined, as it's expected that only the final set of dict keys is
2933 interesting.
2934 Return 0 on success, -1 on error.
2935*/
2936
2937static int
2938merge_class_dict(PyObject *dict, PyObject *aclass)
2939{
2940 PyObject *classdict;
2941 PyObject *bases;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02002942 _Py_IDENTIFIER(__bases__);
Benjamin Peterson82b00c12011-05-24 11:09:06 -05002943
2944 assert(PyDict_Check(dict));
2945 assert(aclass);
2946
2947 /* Merge in the type's dict (if any). */
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002948 classdict = _PyObject_GetAttrId(aclass, &PyId___dict__);
Benjamin Peterson82b00c12011-05-24 11:09:06 -05002949 if (classdict == NULL)
2950 PyErr_Clear();
2951 else {
2952 int status = PyDict_Update(dict, classdict);
2953 Py_DECREF(classdict);
2954 if (status < 0)
2955 return -1;
2956 }
2957
2958 /* Recursively merge in the base types' (if any) dicts. */
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002959 bases = _PyObject_GetAttrId(aclass, &PyId___bases__);
Benjamin Peterson82b00c12011-05-24 11:09:06 -05002960 if (bases == NULL)
2961 PyErr_Clear();
2962 else {
2963 /* We have no guarantee that bases is a real tuple */
2964 Py_ssize_t i, n;
2965 n = PySequence_Size(bases); /* This better be right */
2966 if (n < 0)
2967 PyErr_Clear();
2968 else {
2969 for (i = 0; i < n; i++) {
2970 int status;
2971 PyObject *base = PySequence_GetItem(bases, i);
2972 if (base == NULL) {
2973 Py_DECREF(bases);
2974 return -1;
2975 }
2976 status = merge_class_dict(dict, base);
2977 Py_DECREF(base);
2978 if (status < 0) {
2979 Py_DECREF(bases);
2980 return -1;
2981 }
2982 }
2983 }
2984 Py_DECREF(bases);
2985 }
2986 return 0;
2987}
2988
2989/* __dir__ for type objects: returns __dict__ and __bases__.
2990 We deliberately don't suck up its __class__, as methods belonging to the
2991 metaclass would probably be more confusing than helpful.
2992*/
2993static PyObject *
2994type_dir(PyObject *self, PyObject *args)
2995{
2996 PyObject *result = NULL;
2997 PyObject *dict = PyDict_New();
2998
2999 if (dict != NULL && merge_class_dict(dict, self) == 0)
3000 result = PyDict_Keys(dict);
3001
3002 Py_XDECREF(dict);
3003 return result;
3004}
3005
Martin v. Loewis4f2f3b62012-04-24 19:13:57 +02003006static PyObject*
3007type_sizeof(PyObject *self, PyObject *args_unused)
3008{
3009 Py_ssize_t size;
3010 PyTypeObject *type = (PyTypeObject*)self;
3011 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
3012 PyHeapTypeObject* et = (PyHeapTypeObject*)type;
3013 size = sizeof(PyHeapTypeObject);
3014 if (et->ht_cached_keys)
3015 size += _PyDict_KeysSize(et->ht_cached_keys);
3016 }
3017 else
3018 size = sizeof(PyTypeObject);
3019 return PyLong_FromSsize_t(size);
3020}
3021
Tim Peters6d6c1a32001-08-02 04:15:00 +00003022static PyMethodDef type_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003023 {"mro", (PyCFunction)mro_external, METH_NOARGS,
3024 PyDoc_STR("mro() -> list\nreturn a type's method resolution order")},
3025 {"__subclasses__", (PyCFunction)type_subclasses, METH_NOARGS,
3026 PyDoc_STR("__subclasses__() -> list of immediate subclasses")},
3027 {"__prepare__", (PyCFunction)type_prepare,
3028 METH_VARARGS | METH_KEYWORDS | METH_CLASS,
3029 PyDoc_STR("__prepare__() -> dict\n"
3030 "used to create the namespace for the class statement")},
3031 {"__instancecheck__", type___instancecheck__, METH_O,
Benjamin Petersonfbe56bb2011-05-24 12:42:51 -05003032 PyDoc_STR("__instancecheck__() -> bool\ncheck if an object is an instance")},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003033 {"__subclasscheck__", type___subclasscheck__, METH_O,
Benjamin Petersonfbe56bb2011-05-24 12:42:51 -05003034 PyDoc_STR("__subclasscheck__() -> bool\ncheck if a class is a subclass")},
Benjamin Peterson82b00c12011-05-24 11:09:06 -05003035 {"__dir__", type_dir, METH_NOARGS,
Benjamin Petersonc7284122011-05-24 12:46:15 -05003036 PyDoc_STR("__dir__() -> list\nspecialized __dir__ implementation for types")},
Martin v. Loewis4f2f3b62012-04-24 19:13:57 +02003037 {"__sizeof__", type_sizeof, METH_NOARGS,
3038 "__sizeof__() -> int\nreturn memory consumption of the type object"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003039 {0}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003040};
3041
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003042PyDoc_STRVAR(type_doc,
Larry Hastings5c661892014-01-24 06:17:25 -08003043/* this text signature cannot be accurate yet. will fix. --larry */
Larry Hastings2623c8c2014-02-08 22:15:29 -08003044"type(object_or_name, bases, dict)\n"
Tim Peters6d6c1a32001-08-02 04:15:00 +00003045"type(object) -> the object's type\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003046"type(name, bases, dict) -> a new type");
Tim Peters6d6c1a32001-08-02 04:15:00 +00003047
Guido van Rossum048eb752001-10-02 21:24:57 +00003048static int
3049type_traverse(PyTypeObject *type, visitproc visit, void *arg)
3050{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003051 /* Because of type_is_gc(), the collector only calls this
3052 for heaptypes. */
Antoine Pitrou1351ca62012-06-24 00:30:12 +02003053 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
3054 char msg[200];
3055 sprintf(msg, "type_traverse() called for non-heap type '%.100s'",
3056 type->tp_name);
3057 Py_FatalError(msg);
3058 }
Guido van Rossum048eb752001-10-02 21:24:57 +00003059
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003060 Py_VISIT(type->tp_dict);
3061 Py_VISIT(type->tp_cache);
3062 Py_VISIT(type->tp_mro);
3063 Py_VISIT(type->tp_bases);
3064 Py_VISIT(type->tp_base);
Guido van Rossuma3862092002-06-10 15:24:42 +00003065
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003066 /* There's no need to visit type->tp_subclasses or
3067 ((PyHeapTypeObject *)type)->ht_slots, because they can't be involved
3068 in cycles; tp_subclasses is a list of weak references,
3069 and slots is a tuple of strings. */
Guido van Rossum048eb752001-10-02 21:24:57 +00003070
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003071 return 0;
Guido van Rossum048eb752001-10-02 21:24:57 +00003072}
3073
3074static int
3075type_clear(PyTypeObject *type)
3076{
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003077 PyDictKeysObject *cached_keys;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003078 /* Because of type_is_gc(), the collector only calls this
3079 for heaptypes. */
3080 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00003081
Antoine Pitrou2e872082011-12-15 14:15:31 +01003082 /* We need to invalidate the method cache carefully before clearing
3083 the dict, so that other objects caught in a reference cycle
3084 don't start calling destroyed methods.
3085
3086 Otherwise, the only field we need to clear is tp_mro, which is
3087 part of a hard cycle (its first element is the class itself) that
3088 won't be broken otherwise (it's a tuple and tuples don't have a
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003089 tp_clear handler). None of the other fields need to be
3090 cleared, and here's why:
Guido van Rossum048eb752001-10-02 21:24:57 +00003091
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003092 tp_cache:
3093 Not used; if it were, it would be a dict.
Guido van Rossuma3862092002-06-10 15:24:42 +00003094
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003095 tp_bases, tp_base:
3096 If these are involved in a cycle, there must be at least
3097 one other, mutable object in the cycle, e.g. a base
3098 class's dict; the cycle will be broken that way.
Guido van Rossuma3862092002-06-10 15:24:42 +00003099
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003100 tp_subclasses:
Antoine Pitrou84745ab2013-10-29 21:31:25 +01003101 A dict of weak references can't be part of a cycle; and
3102 dicts have their own tp_clear.
Guido van Rossuma3862092002-06-10 15:24:42 +00003103
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003104 slots (in PyHeapTypeObject):
3105 A tuple of strings can't be part of a cycle.
3106 */
Guido van Rossuma3862092002-06-10 15:24:42 +00003107
Antoine Pitrou2e872082011-12-15 14:15:31 +01003108 PyType_Modified(type);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003109 cached_keys = ((PyHeapTypeObject *)type)->ht_cached_keys;
3110 if (cached_keys != NULL) {
3111 ((PyHeapTypeObject *)type)->ht_cached_keys = NULL;
3112 _PyDictKeys_DecRef(cached_keys);
3113 }
Antoine Pitrou2e872082011-12-15 14:15:31 +01003114 if (type->tp_dict)
3115 PyDict_Clear(type->tp_dict);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003116 Py_CLEAR(type->tp_mro);
Guido van Rossum048eb752001-10-02 21:24:57 +00003117
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003118 return 0;
Guido van Rossum048eb752001-10-02 21:24:57 +00003119}
3120
3121static int
3122type_is_gc(PyTypeObject *type)
3123{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003124 return type->tp_flags & Py_TPFLAGS_HEAPTYPE;
Guido van Rossum048eb752001-10-02 21:24:57 +00003125}
3126
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003127PyTypeObject PyType_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003128 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3129 "type", /* tp_name */
3130 sizeof(PyHeapTypeObject), /* tp_basicsize */
3131 sizeof(PyMemberDef), /* tp_itemsize */
3132 (destructor)type_dealloc, /* tp_dealloc */
3133 0, /* tp_print */
3134 0, /* tp_getattr */
3135 0, /* tp_setattr */
3136 0, /* tp_reserved */
3137 (reprfunc)type_repr, /* tp_repr */
3138 0, /* tp_as_number */
3139 0, /* tp_as_sequence */
3140 0, /* tp_as_mapping */
3141 0, /* tp_hash */
3142 (ternaryfunc)type_call, /* tp_call */
3143 0, /* tp_str */
3144 (getattrofunc)type_getattro, /* tp_getattro */
3145 (setattrofunc)type_setattro, /* tp_setattro */
3146 0, /* tp_as_buffer */
3147 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
3148 Py_TPFLAGS_BASETYPE | Py_TPFLAGS_TYPE_SUBCLASS, /* tp_flags */
3149 type_doc, /* tp_doc */
3150 (traverseproc)type_traverse, /* tp_traverse */
3151 (inquiry)type_clear, /* tp_clear */
3152 0, /* tp_richcompare */
3153 offsetof(PyTypeObject, tp_weaklist), /* tp_weaklistoffset */
3154 0, /* tp_iter */
3155 0, /* tp_iternext */
3156 type_methods, /* tp_methods */
3157 type_members, /* tp_members */
3158 type_getsets, /* tp_getset */
3159 0, /* tp_base */
3160 0, /* tp_dict */
3161 0, /* tp_descr_get */
3162 0, /* tp_descr_set */
3163 offsetof(PyTypeObject, tp_dict), /* tp_dictoffset */
3164 type_init, /* tp_init */
3165 0, /* tp_alloc */
3166 type_new, /* tp_new */
3167 PyObject_GC_Del, /* tp_free */
3168 (inquiry)type_is_gc, /* tp_is_gc */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003169};
Tim Peters6d6c1a32001-08-02 04:15:00 +00003170
3171
3172/* The base type of all types (eventually)... except itself. */
3173
Guido van Rossumd8faa362007-04-27 19:54:29 +00003174/* You may wonder why object.__new__() only complains about arguments
3175 when object.__init__() is not overridden, and vice versa.
3176
3177 Consider the use cases:
3178
3179 1. When neither is overridden, we want to hear complaints about
3180 excess (i.e., any) arguments, since their presence could
3181 indicate there's a bug.
3182
3183 2. When defining an Immutable type, we are likely to override only
3184 __new__(), since __init__() is called too late to initialize an
3185 Immutable object. Since __new__() defines the signature for the
3186 type, it would be a pain to have to override __init__() just to
3187 stop it from complaining about excess arguments.
3188
3189 3. When defining a Mutable type, we are likely to override only
3190 __init__(). So here the converse reasoning applies: we don't
3191 want to have to override __new__() just to stop it from
3192 complaining.
3193
3194 4. When __init__() is overridden, and the subclass __init__() calls
3195 object.__init__(), the latter should complain about excess
3196 arguments; ditto for __new__().
3197
3198 Use cases 2 and 3 make it unattractive to unconditionally check for
3199 excess arguments. The best solution that addresses all four use
3200 cases is as follows: __init__() complains about excess arguments
3201 unless __new__() is overridden and __init__() is not overridden
3202 (IOW, if __init__() is overridden or __new__() is not overridden);
3203 symmetrically, __new__() complains about excess arguments unless
3204 __init__() is overridden and __new__() is not overridden
3205 (IOW, if __new__() is overridden or __init__() is not overridden).
3206
3207 However, for backwards compatibility, this breaks too much code.
3208 Therefore, in 2.6, we'll *warn* about excess arguments when both
3209 methods are overridden; for all other cases we'll use the above
3210 rules.
3211
3212*/
3213
3214/* Forward */
3215static PyObject *
3216object_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
3217
3218static int
3219excess_args(PyObject *args, PyObject *kwds)
3220{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003221 return PyTuple_GET_SIZE(args) ||
3222 (kwds && PyDict_Check(kwds) && PyDict_Size(kwds));
Guido van Rossumd8faa362007-04-27 19:54:29 +00003223}
3224
Tim Peters6d6c1a32001-08-02 04:15:00 +00003225static int
3226object_init(PyObject *self, PyObject *args, PyObject *kwds)
3227{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003228 int err = 0;
Benjamin Peterson96384b92012-03-17 00:05:44 -05003229 PyTypeObject *type = Py_TYPE(self);
3230 if (excess_args(args, kwds) &&
3231 (type->tp_new == object_new || type->tp_init != object_init)) {
3232 PyErr_SetString(PyExc_TypeError, "object.__init__() takes no parameters");
3233 err = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003234 }
3235 return err;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003236}
3237
Guido van Rossum298e4212003-02-13 16:30:16 +00003238static PyObject *
3239object_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3240{
Benjamin Peterson96384b92012-03-17 00:05:44 -05003241 if (excess_args(args, kwds) &&
3242 (type->tp_init == object_init || type->tp_new != object_new)) {
R David Murray702a5dc2013-02-18 21:39:18 -05003243 PyErr_SetString(PyExc_TypeError, "object() takes no parameters");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003244 return NULL;
Benjamin Peterson96384b92012-03-17 00:05:44 -05003245 }
Victor Stinner3c1e4812012-03-26 22:10:51 +02003246
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003247 if (type->tp_flags & Py_TPFLAGS_IS_ABSTRACT) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003248 PyObject *abstract_methods = NULL;
3249 PyObject *builtins;
3250 PyObject *sorted;
3251 PyObject *sorted_methods = NULL;
3252 PyObject *joined = NULL;
Benjamin Peterson9a03ecf2012-03-16 20:15:54 -05003253 PyObject *comma;
3254 _Py_static_string(comma_id, ", ");
Victor Stinner3c1e4812012-03-26 22:10:51 +02003255 _Py_IDENTIFIER(sorted);
Christian Heimes9e7f1d22008-02-28 12:27:11 +00003256
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003257 /* Compute ", ".join(sorted(type.__abstractmethods__))
3258 into joined. */
3259 abstract_methods = type_abstractmethods(type, NULL);
3260 if (abstract_methods == NULL)
3261 goto error;
3262 builtins = PyEval_GetBuiltins();
3263 if (builtins == NULL)
3264 goto error;
Victor Stinner3c1e4812012-03-26 22:10:51 +02003265 sorted = _PyDict_GetItemId(builtins, &PyId_sorted);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003266 if (sorted == NULL)
3267 goto error;
3268 sorted_methods = PyObject_CallFunctionObjArgs(sorted,
3269 abstract_methods,
3270 NULL);
3271 if (sorted_methods == NULL)
3272 goto error;
Benjamin Peterson9a03ecf2012-03-16 20:15:54 -05003273 comma = _PyUnicode_FromId(&comma_id);
3274 if (comma == NULL)
3275 goto error;
3276 joined = PyUnicode_Join(comma, sorted_methods);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003277 if (joined == NULL)
3278 goto error;
Christian Heimes9e7f1d22008-02-28 12:27:11 +00003279
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003280 PyErr_Format(PyExc_TypeError,
3281 "Can't instantiate abstract class %s "
3282 "with abstract methods %U",
3283 type->tp_name,
3284 joined);
3285 error:
3286 Py_XDECREF(joined);
3287 Py_XDECREF(sorted_methods);
3288 Py_XDECREF(abstract_methods);
3289 return NULL;
3290 }
3291 return type->tp_alloc(type, 0);
Guido van Rossum298e4212003-02-13 16:30:16 +00003292}
3293
Tim Peters6d6c1a32001-08-02 04:15:00 +00003294static void
3295object_dealloc(PyObject *self)
3296{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003297 Py_TYPE(self)->tp_free(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003298}
3299
Guido van Rossum8e248182001-08-12 05:17:56 +00003300static PyObject *
3301object_repr(PyObject *self)
3302{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003303 PyTypeObject *type;
3304 PyObject *mod, *name, *rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00003305
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003306 type = Py_TYPE(self);
3307 mod = type_module(type, NULL);
3308 if (mod == NULL)
3309 PyErr_Clear();
3310 else if (!PyUnicode_Check(mod)) {
3311 Py_DECREF(mod);
3312 mod = NULL;
3313 }
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003314 name = type_qualname(type, NULL);
Christian Heimese81dc292012-09-10 16:57:36 +02003315 if (name == NULL) {
3316 Py_XDECREF(mod);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003317 return NULL;
Christian Heimese81dc292012-09-10 16:57:36 +02003318 }
Victor Stinnerbd303c12013-11-07 23:07:29 +01003319 if (mod != NULL && _PyUnicode_CompareWithId(mod, &PyId_builtins))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003320 rtn = PyUnicode_FromFormat("<%U.%U object at %p>", mod, name, self);
3321 else
3322 rtn = PyUnicode_FromFormat("<%s object at %p>",
3323 type->tp_name, self);
3324 Py_XDECREF(mod);
3325 Py_DECREF(name);
3326 return rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00003327}
3328
Guido van Rossumb8f63662001-08-15 23:57:02 +00003329static PyObject *
3330object_str(PyObject *self)
3331{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003332 unaryfunc f;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003333
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003334 f = Py_TYPE(self)->tp_repr;
Benjamin Peterson7b166872012-04-24 11:06:25 -04003335 if (f == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003336 f = object_repr;
3337 return f(self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003338}
3339
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003340static PyObject *
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003341object_richcompare(PyObject *self, PyObject *other, int op)
3342{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003343 PyObject *res;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003344
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003345 switch (op) {
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003346
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003347 case Py_EQ:
3348 /* Return NotImplemented instead of False, so if two
3349 objects are compared, both get a chance at the
3350 comparison. See issue #1393. */
3351 res = (self == other) ? Py_True : Py_NotImplemented;
3352 Py_INCREF(res);
3353 break;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003354
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003355 case Py_NE:
3356 /* By default, != returns the opposite of ==,
3357 unless the latter returns NotImplemented. */
3358 res = PyObject_RichCompare(self, other, Py_EQ);
3359 if (res != NULL && res != Py_NotImplemented) {
3360 int ok = PyObject_IsTrue(res);
3361 Py_DECREF(res);
3362 if (ok < 0)
3363 res = NULL;
3364 else {
3365 if (ok)
3366 res = Py_False;
3367 else
3368 res = Py_True;
3369 Py_INCREF(res);
3370 }
3371 }
3372 break;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003373
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003374 default:
3375 res = Py_NotImplemented;
3376 Py_INCREF(res);
3377 break;
3378 }
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003379
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003380 return res;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003381}
3382
3383static PyObject *
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003384object_get_class(PyObject *self, void *closure)
3385{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003386 Py_INCREF(Py_TYPE(self));
3387 return (PyObject *)(Py_TYPE(self));
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003388}
3389
3390static int
3391equiv_structs(PyTypeObject *a, PyTypeObject *b)
3392{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003393 return a == b ||
3394 (a != NULL &&
3395 b != NULL &&
3396 a->tp_basicsize == b->tp_basicsize &&
3397 a->tp_itemsize == b->tp_itemsize &&
3398 a->tp_dictoffset == b->tp_dictoffset &&
3399 a->tp_weaklistoffset == b->tp_weaklistoffset &&
3400 ((a->tp_flags & Py_TPFLAGS_HAVE_GC) ==
3401 (b->tp_flags & Py_TPFLAGS_HAVE_GC)));
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003402}
3403
3404static int
3405same_slots_added(PyTypeObject *a, PyTypeObject *b)
3406{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003407 PyTypeObject *base = a->tp_base;
3408 Py_ssize_t size;
3409 PyObject *slots_a, *slots_b;
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003410
Benjamin Peterson67641d22011-01-17 19:24:34 +00003411 assert(base == b->tp_base);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003412 size = base->tp_basicsize;
3413 if (a->tp_dictoffset == size && b->tp_dictoffset == size)
3414 size += sizeof(PyObject *);
3415 if (a->tp_weaklistoffset == size && b->tp_weaklistoffset == size)
3416 size += sizeof(PyObject *);
Guido van Rossumd8faa362007-04-27 19:54:29 +00003417
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003418 /* Check slots compliance */
3419 slots_a = ((PyHeapTypeObject *)a)->ht_slots;
3420 slots_b = ((PyHeapTypeObject *)b)->ht_slots;
3421 if (slots_a && slots_b) {
3422 if (PyObject_RichCompareBool(slots_a, slots_b, Py_EQ) != 1)
3423 return 0;
3424 size += sizeof(PyObject *) * PyTuple_GET_SIZE(slots_a);
3425 }
3426 return size == a->tp_basicsize && size == b->tp_basicsize;
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003427}
3428
3429static int
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003430compatible_for_assignment(PyTypeObject* oldto, PyTypeObject* newto, char* attr)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003431{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003432 PyTypeObject *newbase, *oldbase;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003433
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003434 if (newto->tp_dealloc != oldto->tp_dealloc ||
3435 newto->tp_free != oldto->tp_free)
3436 {
3437 PyErr_Format(PyExc_TypeError,
3438 "%s assignment: "
3439 "'%s' deallocator differs from '%s'",
3440 attr,
3441 newto->tp_name,
3442 oldto->tp_name);
3443 return 0;
3444 }
3445 newbase = newto;
3446 oldbase = oldto;
3447 while (equiv_structs(newbase, newbase->tp_base))
3448 newbase = newbase->tp_base;
3449 while (equiv_structs(oldbase, oldbase->tp_base))
3450 oldbase = oldbase->tp_base;
3451 if (newbase != oldbase &&
3452 (newbase->tp_base != oldbase->tp_base ||
3453 !same_slots_added(newbase, oldbase))) {
3454 PyErr_Format(PyExc_TypeError,
3455 "%s assignment: "
3456 "'%s' object layout differs from '%s'",
3457 attr,
3458 newto->tp_name,
3459 oldto->tp_name);
3460 return 0;
3461 }
Tim Petersea7f75d2002-12-07 21:39:16 +00003462
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003463 return 1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003464}
3465
3466static int
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003467object_set_class(PyObject *self, PyObject *value, void *closure)
3468{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003469 PyTypeObject *oldto = Py_TYPE(self);
3470 PyTypeObject *newto;
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003471
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003472 if (value == NULL) {
3473 PyErr_SetString(PyExc_TypeError,
3474 "can't delete __class__ attribute");
3475 return -1;
3476 }
3477 if (!PyType_Check(value)) {
3478 PyErr_Format(PyExc_TypeError,
Florent Xiclunaaa6c1d22011-12-12 18:54:29 +01003479 "__class__ must be set to a class, not '%s' object",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003480 Py_TYPE(value)->tp_name);
3481 return -1;
3482 }
3483 newto = (PyTypeObject *)value;
3484 if (!(newto->tp_flags & Py_TPFLAGS_HEAPTYPE) ||
3485 !(oldto->tp_flags & Py_TPFLAGS_HEAPTYPE))
3486 {
3487 PyErr_Format(PyExc_TypeError,
3488 "__class__ assignment: only for heap types");
3489 return -1;
3490 }
Christian Heimesde4d1832013-07-20 14:19:46 +02003491 if (compatible_for_assignment(oldto, newto, "__class__")) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003492 Py_INCREF(newto);
3493 Py_TYPE(self) = newto;
3494 Py_DECREF(oldto);
3495 return 0;
3496 }
3497 else {
3498 return -1;
3499 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003500}
3501
3502static PyGetSetDef object_getsets[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003503 {"__class__", object_get_class, object_set_class,
3504 PyDoc_STR("the object's class")},
3505 {0}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003506};
3507
Guido van Rossumc53f0092003-02-18 22:05:12 +00003508
Guido van Rossum036f9992003-02-21 22:02:54 +00003509/* Stuff to implement __reduce_ex__ for pickle protocols >= 2.
Alexandre Vassalottif7fa63d2008-05-11 08:55:36 +00003510 We fall back to helpers in copyreg for:
Guido van Rossum036f9992003-02-21 22:02:54 +00003511 - pickle protocols < 2
3512 - calculating the list of slot names (done only once per class)
3513 - the __newobj__ function (which is used as a token but never called)
3514*/
3515
3516static PyObject *
Alexandre Vassalottif7fa63d2008-05-11 08:55:36 +00003517import_copyreg(void)
Guido van Rossum036f9992003-02-21 22:02:54 +00003518{
Alexandre Vassalotti1a830702013-11-30 00:53:09 -08003519 PyObject *copyreg_str;
3520 PyObject *copyreg_module;
3521 PyInterpreterState *interp = PyThreadState_GET()->interp;
3522 _Py_IDENTIFIER(copyreg);
Guido van Rossum3926a632001-09-25 16:25:58 +00003523
Alexandre Vassalotti1a830702013-11-30 00:53:09 -08003524 copyreg_str = _PyUnicode_FromId(&PyId_copyreg);
3525 if (copyreg_str == NULL) {
3526 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003527 }
Alexandre Vassalotti1a830702013-11-30 00:53:09 -08003528 /* Try to fetch cached copy of copyreg from sys.modules first in an
3529 attempt to avoid the import overhead. Previously this was implemented
3530 by storing a reference to the cached module in a static variable, but
3531 this broke when multiple embeded interpreters were in use (see issue
3532 #17408 and #19088). */
3533 copyreg_module = PyDict_GetItemWithError(interp->modules, copyreg_str);
3534 if (copyreg_module != NULL) {
3535 Py_INCREF(copyreg_module);
3536 return copyreg_module;
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003537 }
Alexandre Vassalotti1a830702013-11-30 00:53:09 -08003538 if (PyErr_Occurred()) {
3539 return NULL;
3540 }
3541 return PyImport_Import(copyreg_str);
Guido van Rossum036f9992003-02-21 22:02:54 +00003542}
3543
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01003544Py_LOCAL(PyObject *)
3545_PyType_GetSlotNames(PyTypeObject *cls)
Guido van Rossum036f9992003-02-21 22:02:54 +00003546{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003547 PyObject *copyreg;
3548 PyObject *slotnames;
Victor Stinner3c1e4812012-03-26 22:10:51 +02003549 _Py_IDENTIFIER(__slotnames__);
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02003550 _Py_IDENTIFIER(_slotnames);
Guido van Rossum036f9992003-02-21 22:02:54 +00003551
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01003552 assert(PyType_Check(cls));
3553
3554 /* Get the slot names from the cache in the class if possible. */
3555 slotnames = _PyDict_GetItemIdWithError(cls->tp_dict, &PyId___slotnames__);
3556 if (slotnames != NULL) {
3557 if (slotnames != Py_None && !PyList_Check(slotnames)) {
3558 PyErr_Format(PyExc_TypeError,
3559 "%.200s.__slotnames__ should be a list or None, "
3560 "not %.200s",
3561 cls->tp_name, Py_TYPE(slotnames)->tp_name);
3562 return NULL;
3563 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003564 Py_INCREF(slotnames);
3565 return slotnames;
3566 }
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01003567 else {
3568 if (PyErr_Occurred()) {
3569 return NULL;
3570 }
3571 /* The class does not have the slot names cached yet. */
3572 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003573
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003574 copyreg = import_copyreg();
3575 if (copyreg == NULL)
3576 return NULL;
Guido van Rossum036f9992003-02-21 22:02:54 +00003577
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01003578 /* Use _slotnames function from the copyreg module to find the slots
3579 by this class and its bases. This function will cache the result
3580 in __slotnames__. */
3581 slotnames = _PyObject_CallMethodIdObjArgs(copyreg, &PyId__slotnames,
3582 cls, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003583 Py_DECREF(copyreg);
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01003584 if (slotnames == NULL)
3585 return NULL;
3586
3587 if (slotnames != Py_None && !PyList_Check(slotnames)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003588 PyErr_SetString(PyExc_TypeError,
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01003589 "copyreg._slotnames didn't return a list or None");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003590 Py_DECREF(slotnames);
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01003591 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003592 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003593
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003594 return slotnames;
Guido van Rossum036f9992003-02-21 22:02:54 +00003595}
3596
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01003597Py_LOCAL(PyObject *)
3598_PyObject_GetState(PyObject *obj)
Guido van Rossum036f9992003-02-21 22:02:54 +00003599{
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01003600 PyObject *state;
3601 PyObject *getstate;
Victor Stinner3c1e4812012-03-26 22:10:51 +02003602 _Py_IDENTIFIER(__getstate__);
Guido van Rossum036f9992003-02-21 22:02:54 +00003603
Victor Stinner3c1e4812012-03-26 22:10:51 +02003604 getstate = _PyObject_GetAttrId(obj, &PyId___getstate__);
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01003605 if (getstate == NULL) {
3606 PyObject *slotnames;
3607
3608 if (!PyErr_ExceptionMatches(PyExc_AttributeError)) {
3609 return NULL;
3610 }
3611 PyErr_Clear();
3612
3613 {
3614 PyObject **dict;
3615 dict = _PyObject_GetDictPtr(obj);
Larry Hastings5c661892014-01-24 06:17:25 -08003616 /* It is possible that the object's dict is not initialized
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01003617 yet. In this case, we will return None for the state.
3618 We also return None if the dict is empty to make the behavior
3619 consistent regardless whether the dict was initialized or not.
3620 This make unit testing easier. */
3621 if (dict != NULL && *dict != NULL && PyDict_Size(*dict) > 0) {
3622 state = *dict;
3623 }
3624 else {
3625 state = Py_None;
3626 }
3627 Py_INCREF(state);
3628 }
3629
3630 slotnames = _PyType_GetSlotNames(Py_TYPE(obj));
3631 if (slotnames == NULL) {
3632 Py_DECREF(state);
3633 return NULL;
3634 }
3635
3636 assert(slotnames == Py_None || PyList_Check(slotnames));
3637 if (slotnames != Py_None && Py_SIZE(slotnames) > 0) {
3638 PyObject *slots;
3639 Py_ssize_t slotnames_size, i;
3640
3641 slots = PyDict_New();
3642 if (slots == NULL) {
3643 Py_DECREF(slotnames);
3644 Py_DECREF(state);
3645 return NULL;
3646 }
3647
3648 slotnames_size = Py_SIZE(slotnames);
3649 for (i = 0; i < slotnames_size; i++) {
3650 PyObject *name, *value;
3651
3652 name = PyList_GET_ITEM(slotnames, i);
3653 value = PyObject_GetAttr(obj, name);
3654 if (value == NULL) {
3655 if (!PyErr_ExceptionMatches(PyExc_AttributeError)) {
3656 goto error;
3657 }
3658 /* It is not an error if the attribute is not present. */
3659 PyErr_Clear();
3660 }
3661 else {
3662 int err = PyDict_SetItem(slots, name, value);
3663 Py_DECREF(value);
3664 if (err) {
3665 goto error;
3666 }
3667 }
3668
3669 /* The list is stored on the class so it may mutates while we
3670 iterate over it */
3671 if (slotnames_size != Py_SIZE(slotnames)) {
3672 PyErr_Format(PyExc_RuntimeError,
3673 "__slotsname__ changed size during iteration");
3674 goto error;
3675 }
3676
3677 /* We handle errors within the loop here. */
3678 if (0) {
3679 error:
3680 Py_DECREF(slotnames);
3681 Py_DECREF(slots);
3682 Py_DECREF(state);
3683 return NULL;
3684 }
3685 }
3686
3687 /* If we found some slot attributes, pack them in a tuple along
3688 the orginal attribute dictionary. */
3689 if (PyDict_Size(slots) > 0) {
3690 PyObject *state2;
3691
3692 state2 = PyTuple_Pack(2, state, slots);
3693 Py_DECREF(state);
3694 if (state2 == NULL) {
3695 Py_DECREF(slotnames);
3696 Py_DECREF(slots);
3697 return NULL;
3698 }
3699 state = state2;
3700 }
3701 Py_DECREF(slots);
3702 }
3703 Py_DECREF(slotnames);
3704 }
3705 else { /* getstate != NULL */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003706 state = PyObject_CallObject(getstate, NULL);
3707 Py_DECREF(getstate);
3708 if (state == NULL)
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01003709 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003710 }
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01003711
3712 return state;
3713}
3714
3715Py_LOCAL(int)
3716_PyObject_GetNewArguments(PyObject *obj, PyObject **args, PyObject **kwargs)
3717{
3718 PyObject *getnewargs, *getnewargs_ex;
3719 _Py_IDENTIFIER(__getnewargs_ex__);
3720 _Py_IDENTIFIER(__getnewargs__);
3721
3722 if (args == NULL || kwargs == NULL) {
3723 PyErr_BadInternalCall();
3724 return -1;
3725 }
3726
3727 /* We first attempt to fetch the arguments for __new__ by calling
3728 __getnewargs_ex__ on the object. */
Benjamin Petersone686c5c2014-02-16 13:49:16 -05003729 getnewargs_ex = _PyObject_LookupSpecial(obj, &PyId___getnewargs_ex__);
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01003730 if (getnewargs_ex != NULL) {
3731 PyObject *newargs = PyObject_CallObject(getnewargs_ex, NULL);
3732 Py_DECREF(getnewargs_ex);
3733 if (newargs == NULL) {
3734 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003735 }
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01003736 if (!PyTuple_Check(newargs)) {
3737 PyErr_Format(PyExc_TypeError,
3738 "__getnewargs_ex__ should return a tuple, "
3739 "not '%.200s'", Py_TYPE(newargs)->tp_name);
3740 Py_DECREF(newargs);
3741 return -1;
3742 }
3743 if (Py_SIZE(newargs) != 2) {
3744 PyErr_Format(PyExc_ValueError,
3745 "__getnewargs_ex__ should return a tuple of "
3746 "length 2, not %zd", Py_SIZE(newargs));
3747 Py_DECREF(newargs);
3748 return -1;
3749 }
3750 *args = PyTuple_GET_ITEM(newargs, 0);
3751 Py_INCREF(*args);
3752 *kwargs = PyTuple_GET_ITEM(newargs, 1);
3753 Py_INCREF(*kwargs);
3754 Py_DECREF(newargs);
3755
3756 /* XXX We should perhaps allow None to be passed here. */
3757 if (!PyTuple_Check(*args)) {
3758 PyErr_Format(PyExc_TypeError,
3759 "first item of the tuple returned by "
3760 "__getnewargs_ex__ must be a tuple, not '%.200s'",
3761 Py_TYPE(*args)->tp_name);
3762 Py_CLEAR(*args);
3763 Py_CLEAR(*kwargs);
3764 return -1;
3765 }
3766 if (!PyDict_Check(*kwargs)) {
3767 PyErr_Format(PyExc_TypeError,
3768 "second item of the tuple returned by "
3769 "__getnewargs_ex__ must be a dict, not '%.200s'",
3770 Py_TYPE(*kwargs)->tp_name);
3771 Py_CLEAR(*args);
3772 Py_CLEAR(*kwargs);
3773 return -1;
3774 }
3775 return 0;
Benjamin Petersone686c5c2014-02-16 13:49:16 -05003776 } else if (PyErr_Occurred()) {
3777 return -1;
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01003778 }
3779
3780 /* The object does not have __getnewargs_ex__ so we fallback on using
3781 __getnewargs__ instead. */
Benjamin Petersone686c5c2014-02-16 13:49:16 -05003782 getnewargs = _PyObject_LookupSpecial(obj, &PyId___getnewargs__);
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01003783 if (getnewargs != NULL) {
3784 *args = PyObject_CallObject(getnewargs, NULL);
3785 Py_DECREF(getnewargs);
3786 if (*args == NULL) {
3787 return -1;
3788 }
3789 if (!PyTuple_Check(*args)) {
3790 PyErr_Format(PyExc_TypeError,
3791 "__getnewargs__ should return a tuple, "
3792 "not '%.200s'", Py_TYPE(*args)->tp_name);
3793 Py_CLEAR(*args);
3794 return -1;
3795 }
3796 *kwargs = NULL;
3797 return 0;
Benjamin Petersone686c5c2014-02-16 13:49:16 -05003798 } else if (PyErr_Occurred()) {
3799 return -1;
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01003800 }
3801
3802 /* The object does not have __getnewargs_ex__ and __getnewargs__. This may
3803 means __new__ does not takes any arguments on this object, or that the
3804 object does not implement the reduce protocol for pickling or
3805 copying. */
3806 *args = NULL;
3807 *kwargs = NULL;
3808 return 0;
3809}
3810
3811Py_LOCAL(int)
3812_PyObject_GetItemsIter(PyObject *obj, PyObject **listitems,
3813 PyObject **dictitems)
3814{
3815 if (listitems == NULL || dictitems == NULL) {
3816 PyErr_BadInternalCall();
3817 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003818 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003819
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003820 if (!PyList_Check(obj)) {
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01003821 *listitems = Py_None;
3822 Py_INCREF(*listitems);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003823 }
3824 else {
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01003825 *listitems = PyObject_GetIter(obj);
Christian Heimes2489bd82013-11-23 21:19:43 +01003826 if (*listitems == NULL)
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01003827 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003828 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003829
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003830 if (!PyDict_Check(obj)) {
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01003831 *dictitems = Py_None;
3832 Py_INCREF(*dictitems);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003833 }
3834 else {
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01003835 PyObject *items;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02003836 _Py_IDENTIFIER(items);
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01003837
3838 items = _PyObject_CallMethodIdObjArgs(obj, &PyId_items, NULL);
3839 if (items == NULL) {
3840 Py_CLEAR(*listitems);
3841 return -1;
3842 }
3843 *dictitems = PyObject_GetIter(items);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003844 Py_DECREF(items);
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01003845 if (*dictitems == NULL) {
3846 Py_CLEAR(*listitems);
3847 return -1;
3848 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003849 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003850
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01003851 assert(*listitems != NULL && *dictitems != NULL);
3852
3853 return 0;
3854}
3855
3856static PyObject *
3857reduce_4(PyObject *obj)
3858{
3859 PyObject *args = NULL, *kwargs = NULL;
3860 PyObject *copyreg;
3861 PyObject *newobj, *newargs, *state, *listitems, *dictitems;
3862 PyObject *result;
3863 _Py_IDENTIFIER(__newobj_ex__);
3864
3865 if (_PyObject_GetNewArguments(obj, &args, &kwargs) < 0) {
3866 return NULL;
3867 }
3868 if (args == NULL) {
3869 args = PyTuple_New(0);
3870 if (args == NULL)
3871 return NULL;
3872 }
3873 if (kwargs == NULL) {
3874 kwargs = PyDict_New();
3875 if (kwargs == NULL)
3876 return NULL;
3877 }
3878
3879 copyreg = import_copyreg();
3880 if (copyreg == NULL) {
3881 Py_DECREF(args);
3882 Py_DECREF(kwargs);
3883 return NULL;
3884 }
3885 newobj = _PyObject_GetAttrId(copyreg, &PyId___newobj_ex__);
3886 Py_DECREF(copyreg);
3887 if (newobj == NULL) {
3888 Py_DECREF(args);
3889 Py_DECREF(kwargs);
3890 return NULL;
3891 }
3892 newargs = PyTuple_Pack(3, Py_TYPE(obj), args, kwargs);
3893 Py_DECREF(args);
3894 Py_DECREF(kwargs);
3895 if (newargs == NULL) {
3896 Py_DECREF(newobj);
3897 return NULL;
3898 }
3899 state = _PyObject_GetState(obj);
3900 if (state == NULL) {
3901 Py_DECREF(newobj);
3902 Py_DECREF(newargs);
3903 return NULL;
3904 }
3905 if (_PyObject_GetItemsIter(obj, &listitems, &dictitems) < 0) {
3906 Py_DECREF(newobj);
3907 Py_DECREF(newargs);
3908 Py_DECREF(state);
3909 return NULL;
3910 }
3911
3912 result = PyTuple_Pack(5, newobj, newargs, state, listitems, dictitems);
3913 Py_DECREF(newobj);
3914 Py_DECREF(newargs);
3915 Py_DECREF(state);
3916 Py_DECREF(listitems);
3917 Py_DECREF(dictitems);
Larry Hastings5c661892014-01-24 06:17:25 -08003918 return result;
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01003919}
3920
3921static PyObject *
3922reduce_2(PyObject *obj)
3923{
3924 PyObject *cls;
3925 PyObject *args = NULL, *args2 = NULL, *kwargs = NULL;
3926 PyObject *state = NULL, *listitems = NULL, *dictitems = NULL;
3927 PyObject *copyreg = NULL, *newobj = NULL, *res = NULL;
3928 Py_ssize_t i, n;
3929 _Py_IDENTIFIER(__newobj__);
3930
3931 if (_PyObject_GetNewArguments(obj, &args, &kwargs) < 0) {
3932 return NULL;
3933 }
3934 if (args == NULL) {
3935 assert(kwargs == NULL);
3936 args = PyTuple_New(0);
3937 if (args == NULL) {
3938 return NULL;
3939 }
3940 }
3941 else if (kwargs != NULL) {
3942 if (PyDict_Size(kwargs) > 0) {
Larry Hastings5c661892014-01-24 06:17:25 -08003943 PyErr_SetString(PyExc_ValueError,
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01003944 "must use protocol 4 or greater to copy this "
3945 "object; since __getnewargs_ex__ returned "
3946 "keyword arguments.");
3947 Py_DECREF(args);
3948 Py_DECREF(kwargs);
3949 return NULL;
3950 }
3951 Py_CLEAR(kwargs);
3952 }
3953
3954 state = _PyObject_GetState(obj);
3955 if (state == NULL)
3956 goto end;
3957
3958 if (_PyObject_GetItemsIter(obj, &listitems, &dictitems) < 0)
3959 goto end;
3960
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003961 copyreg = import_copyreg();
3962 if (copyreg == NULL)
3963 goto end;
Victor Stinner3c1e4812012-03-26 22:10:51 +02003964 newobj = _PyObject_GetAttrId(copyreg, &PyId___newobj__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003965 if (newobj == NULL)
3966 goto end;
Guido van Rossum036f9992003-02-21 22:02:54 +00003967
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003968 n = PyTuple_GET_SIZE(args);
3969 args2 = PyTuple_New(n+1);
3970 if (args2 == NULL)
3971 goto end;
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01003972 cls = (PyObject *) Py_TYPE(obj);
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003973 Py_INCREF(cls);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003974 PyTuple_SET_ITEM(args2, 0, cls);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003975 for (i = 0; i < n; i++) {
3976 PyObject *v = PyTuple_GET_ITEM(args, i);
3977 Py_INCREF(v);
3978 PyTuple_SET_ITEM(args2, i+1, v);
3979 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003980
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003981 res = PyTuple_Pack(5, newobj, args2, state, listitems, dictitems);
Guido van Rossum036f9992003-02-21 22:02:54 +00003982
3983 end:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003984 Py_XDECREF(args);
3985 Py_XDECREF(args2);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003986 Py_XDECREF(state);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003987 Py_XDECREF(listitems);
3988 Py_XDECREF(dictitems);
3989 Py_XDECREF(copyreg);
3990 Py_XDECREF(newobj);
3991 return res;
Guido van Rossum036f9992003-02-21 22:02:54 +00003992}
3993
Guido van Rossumd8faa362007-04-27 19:54:29 +00003994/*
3995 * There were two problems when object.__reduce__ and object.__reduce_ex__
3996 * were implemented in the same function:
3997 * - trying to pickle an object with a custom __reduce__ method that
3998 * fell back to object.__reduce__ in certain circumstances led to
3999 * infinite recursion at Python level and eventual RuntimeError.
4000 * - Pickling objects that lied about their type by overwriting the
4001 * __class__ descriptor could lead to infinite recursion at C level
4002 * and eventual segfault.
4003 *
4004 * Because of backwards compatibility, the two methods still have to
4005 * behave in the same way, even if this is not required by the pickle
4006 * protocol. This common functionality was moved to the _common_reduce
4007 * function.
4008 */
4009static PyObject *
4010_common_reduce(PyObject *self, int proto)
4011{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004012 PyObject *copyreg, *res;
Guido van Rossumd8faa362007-04-27 19:54:29 +00004013
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004014 if (proto >= 4)
4015 return reduce_4(self);
4016 else if (proto >= 2)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004017 return reduce_2(self);
Guido van Rossumd8faa362007-04-27 19:54:29 +00004018
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004019 copyreg = import_copyreg();
4020 if (!copyreg)
4021 return NULL;
Guido van Rossumd8faa362007-04-27 19:54:29 +00004022
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004023 res = PyEval_CallMethod(copyreg, "_reduce_ex", "(Oi)", self, proto);
4024 Py_DECREF(copyreg);
Guido van Rossumd8faa362007-04-27 19:54:29 +00004025
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004026 return res;
Guido van Rossumd8faa362007-04-27 19:54:29 +00004027}
4028
4029static PyObject *
4030object_reduce(PyObject *self, PyObject *args)
4031{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004032 int proto = 0;
Guido van Rossumd8faa362007-04-27 19:54:29 +00004033
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004034 if (!PyArg_ParseTuple(args, "|i:__reduce__", &proto))
4035 return NULL;
Guido van Rossumd8faa362007-04-27 19:54:29 +00004036
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004037 return _common_reduce(self, proto);
Guido van Rossumd8faa362007-04-27 19:54:29 +00004038}
4039
Guido van Rossum036f9992003-02-21 22:02:54 +00004040static PyObject *
4041object_reduce_ex(PyObject *self, PyObject *args)
4042{
Victor Stinner3c1e4812012-03-26 22:10:51 +02004043 static PyObject *objreduce;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004044 PyObject *reduce, *res;
4045 int proto = 0;
Victor Stinner3c1e4812012-03-26 22:10:51 +02004046 _Py_IDENTIFIER(__reduce__);
Guido van Rossum036f9992003-02-21 22:02:54 +00004047
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004048 if (!PyArg_ParseTuple(args, "|i:__reduce_ex__", &proto))
4049 return NULL;
Guido van Rossum036f9992003-02-21 22:02:54 +00004050
Victor Stinner3c1e4812012-03-26 22:10:51 +02004051 if (objreduce == NULL) {
4052 objreduce = _PyDict_GetItemId(PyBaseObject_Type.tp_dict,
4053 &PyId___reduce__);
4054 if (objreduce == NULL)
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01004055 return NULL;
4056 }
4057
Victor Stinner3c1e4812012-03-26 22:10:51 +02004058 reduce = _PyObject_GetAttrId(self, &PyId___reduce__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004059 if (reduce == NULL)
4060 PyErr_Clear();
4061 else {
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01004062 PyObject *cls, *clsreduce;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004063 int override;
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01004064
4065 cls = (PyObject *) Py_TYPE(self);
Victor Stinner3c1e4812012-03-26 22:10:51 +02004066 clsreduce = _PyObject_GetAttrId(cls, &PyId___reduce__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004067 if (clsreduce == NULL) {
4068 Py_DECREF(reduce);
4069 return NULL;
4070 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004071 override = (clsreduce != objreduce);
4072 Py_DECREF(clsreduce);
4073 if (override) {
4074 res = PyObject_CallObject(reduce, NULL);
4075 Py_DECREF(reduce);
4076 return res;
4077 }
4078 else
4079 Py_DECREF(reduce);
4080 }
Guido van Rossum036f9992003-02-21 22:02:54 +00004081
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004082 return _common_reduce(self, proto);
Guido van Rossum3926a632001-09-25 16:25:58 +00004083}
4084
Christian Heimes9e7f1d22008-02-28 12:27:11 +00004085static PyObject *
4086object_subclasshook(PyObject *cls, PyObject *args)
4087{
Brian Curtindfc80e32011-08-10 20:28:54 -05004088 Py_RETURN_NOTIMPLEMENTED;
Christian Heimes9e7f1d22008-02-28 12:27:11 +00004089}
4090
4091PyDoc_STRVAR(object_subclasshook_doc,
4092"Abstract classes can override this to customize issubclass().\n"
4093"\n"
4094"This is invoked early on by abc.ABCMeta.__subclasscheck__().\n"
4095"It should return True, False or NotImplemented. If it returns\n"
4096"NotImplemented, the normal algorithm is used. Otherwise, it\n"
4097"overrides the normal algorithm (and the outcome is cached).\n");
Eric Smith8c663262007-08-25 02:26:07 +00004098
4099/*
4100 from PEP 3101, this code implements:
4101
4102 class object:
4103 def __format__(self, format_spec):
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004104 return format(str(self), format_spec)
Eric Smith8c663262007-08-25 02:26:07 +00004105*/
4106static PyObject *
4107object_format(PyObject *self, PyObject *args)
4108{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004109 PyObject *format_spec;
4110 PyObject *self_as_str = NULL;
4111 PyObject *result = NULL;
Eric Smith8c663262007-08-25 02:26:07 +00004112
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004113 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
4114 return NULL;
Eric Smith8c663262007-08-25 02:26:07 +00004115
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004116 self_as_str = PyObject_Str(self);
Eric Smithe4d63172010-09-13 20:48:43 +00004117 if (self_as_str != NULL) {
4118 /* Issue 7994: If we're converting to a string, we
Eric V. Smithb9cd3532011-03-12 10:08:48 -05004119 should reject format specifications */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004120 if (PyUnicode_GET_LENGTH(format_spec) > 0) {
Andrew Svetlov2cd8ce42012-12-23 14:27:17 +02004121 PyErr_SetString(PyExc_TypeError,
Eric V. Smithb9cd3532011-03-12 10:08:48 -05004122 "non-empty format string passed to object.__format__");
Andrew Svetlov2cd8ce42012-12-23 14:27:17 +02004123 goto done;
Eric V. Smithb9cd3532011-03-12 10:08:48 -05004124 }
Eric Smith8c663262007-08-25 02:26:07 +00004125
Eric V. Smithb9cd3532011-03-12 10:08:48 -05004126 result = PyObject_Format(self_as_str, format_spec);
Eric Smithe4d63172010-09-13 20:48:43 +00004127 }
4128
4129done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004130 Py_XDECREF(self_as_str);
Eric Smith8c663262007-08-25 02:26:07 +00004131
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004132 return result;
Eric Smith8c663262007-08-25 02:26:07 +00004133}
4134
Martin v. Löwis00709aa2008-06-04 14:18:43 +00004135static PyObject *
4136object_sizeof(PyObject *self, PyObject *args)
4137{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004138 Py_ssize_t res, isize;
Martin v. Löwis00709aa2008-06-04 14:18:43 +00004139
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004140 res = 0;
4141 isize = self->ob_type->tp_itemsize;
4142 if (isize > 0)
4143 res = Py_SIZE(self->ob_type) * isize;
4144 res += self->ob_type->tp_basicsize;
Martin v. Löwis00709aa2008-06-04 14:18:43 +00004145
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004146 return PyLong_FromSsize_t(res);
Martin v. Löwis00709aa2008-06-04 14:18:43 +00004147}
4148
Benjamin Peterson82b00c12011-05-24 11:09:06 -05004149/* __dir__ for generic objects: returns __dict__, __class__,
4150 and recursively up the __class__.__bases__ chain.
4151*/
4152static PyObject *
4153object_dir(PyObject *self, PyObject *args)
4154{
4155 PyObject *result = NULL;
4156 PyObject *dict = NULL;
4157 PyObject *itsclass = NULL;
4158
4159 /* Get __dict__ (which may or may not be a real dict...) */
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02004160 dict = _PyObject_GetAttrId(self, &PyId___dict__);
Benjamin Peterson82b00c12011-05-24 11:09:06 -05004161 if (dict == NULL) {
4162 PyErr_Clear();
4163 dict = PyDict_New();
4164 }
4165 else if (!PyDict_Check(dict)) {
4166 Py_DECREF(dict);
4167 dict = PyDict_New();
4168 }
4169 else {
4170 /* Copy __dict__ to avoid mutating it. */
4171 PyObject *temp = PyDict_Copy(dict);
4172 Py_DECREF(dict);
4173 dict = temp;
4174 }
4175
4176 if (dict == NULL)
4177 goto error;
4178
4179 /* Merge in attrs reachable from its class. */
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02004180 itsclass = _PyObject_GetAttrId(self, &PyId___class__);
Benjamin Peterson82b00c12011-05-24 11:09:06 -05004181 if (itsclass == NULL)
4182 /* XXX(tomer): Perhaps fall back to obj->ob_type if no
4183 __class__ exists? */
4184 PyErr_Clear();
4185 else if (merge_class_dict(dict, itsclass) != 0)
4186 goto error;
4187
4188 result = PyDict_Keys(dict);
4189 /* fall through */
4190error:
4191 Py_XDECREF(itsclass);
4192 Py_XDECREF(dict);
4193 return result;
4194}
4195
Guido van Rossum3926a632001-09-25 16:25:58 +00004196static PyMethodDef object_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004197 {"__reduce_ex__", object_reduce_ex, METH_VARARGS,
4198 PyDoc_STR("helper for pickle")},
4199 {"__reduce__", object_reduce, METH_VARARGS,
4200 PyDoc_STR("helper for pickle")},
4201 {"__subclasshook__", object_subclasshook, METH_CLASS | METH_VARARGS,
4202 object_subclasshook_doc},
4203 {"__format__", object_format, METH_VARARGS,
4204 PyDoc_STR("default object formatter")},
4205 {"__sizeof__", object_sizeof, METH_NOARGS,
Benjamin Petersonfbe56bb2011-05-24 12:42:51 -05004206 PyDoc_STR("__sizeof__() -> int\nsize of object in memory, in bytes")},
Benjamin Peterson82b00c12011-05-24 11:09:06 -05004207 {"__dir__", object_dir, METH_NOARGS,
Benjamin Petersonc7284122011-05-24 12:46:15 -05004208 PyDoc_STR("__dir__() -> list\ndefault dir() implementation")},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004209 {0}
Guido van Rossum3926a632001-09-25 16:25:58 +00004210};
4211
Guido van Rossum036f9992003-02-21 22:02:54 +00004212
Tim Peters6d6c1a32001-08-02 04:15:00 +00004213PyTypeObject PyBaseObject_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004214 PyVarObject_HEAD_INIT(&PyType_Type, 0)
4215 "object", /* tp_name */
4216 sizeof(PyObject), /* tp_basicsize */
4217 0, /* tp_itemsize */
4218 object_dealloc, /* tp_dealloc */
4219 0, /* tp_print */
4220 0, /* tp_getattr */
4221 0, /* tp_setattr */
4222 0, /* tp_reserved */
4223 object_repr, /* tp_repr */
4224 0, /* tp_as_number */
4225 0, /* tp_as_sequence */
4226 0, /* tp_as_mapping */
4227 (hashfunc)_Py_HashPointer, /* tp_hash */
4228 0, /* tp_call */
4229 object_str, /* tp_str */
4230 PyObject_GenericGetAttr, /* tp_getattro */
4231 PyObject_GenericSetAttr, /* tp_setattro */
4232 0, /* tp_as_buffer */
Larry Hastings5c661892014-01-24 06:17:25 -08004233 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Larry Hastings2623c8c2014-02-08 22:15:29 -08004234 PyDoc_STR("object()\n--\n\nThe most base type"), /* tp_doc */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004235 0, /* tp_traverse */
4236 0, /* tp_clear */
4237 object_richcompare, /* tp_richcompare */
4238 0, /* tp_weaklistoffset */
4239 0, /* tp_iter */
4240 0, /* tp_iternext */
4241 object_methods, /* tp_methods */
4242 0, /* tp_members */
4243 object_getsets, /* tp_getset */
4244 0, /* tp_base */
4245 0, /* tp_dict */
4246 0, /* tp_descr_get */
4247 0, /* tp_descr_set */
4248 0, /* tp_dictoffset */
4249 object_init, /* tp_init */
4250 PyType_GenericAlloc, /* tp_alloc */
4251 object_new, /* tp_new */
4252 PyObject_Del, /* tp_free */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004253};
4254
4255
Guido van Rossum50e9fb92006-08-17 05:42:55 +00004256/* Add the methods from tp_methods to the __dict__ in a type object */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004257
4258static int
4259add_methods(PyTypeObject *type, PyMethodDef *meth)
4260{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004261 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004262
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004263 for (; meth->ml_name != NULL; meth++) {
4264 PyObject *descr;
Benjamin Peterson89a6e9a2012-05-08 09:22:24 -04004265 int err;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004266 if (PyDict_GetItemString(dict, meth->ml_name) &&
4267 !(meth->ml_flags & METH_COEXIST))
4268 continue;
4269 if (meth->ml_flags & METH_CLASS) {
4270 if (meth->ml_flags & METH_STATIC) {
4271 PyErr_SetString(PyExc_ValueError,
4272 "method cannot be both class and static");
4273 return -1;
4274 }
4275 descr = PyDescr_NewClassMethod(type, meth);
4276 }
4277 else if (meth->ml_flags & METH_STATIC) {
Andrew Svetlov3ba3a3e2012-12-25 13:32:35 +02004278 PyObject *cfunc = PyCFunction_NewEx(meth, (PyObject*)type, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004279 if (cfunc == NULL)
4280 return -1;
4281 descr = PyStaticMethod_New(cfunc);
4282 Py_DECREF(cfunc);
4283 }
4284 else {
4285 descr = PyDescr_NewMethod(type, meth);
4286 }
4287 if (descr == NULL)
4288 return -1;
Benjamin Peterson89a6e9a2012-05-08 09:22:24 -04004289 err = PyDict_SetItemString(dict, meth->ml_name, descr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004290 Py_DECREF(descr);
Benjamin Peterson89a6e9a2012-05-08 09:22:24 -04004291 if (err < 0)
4292 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004293 }
4294 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004295}
4296
4297static int
Guido van Rossum6f799372001-09-20 20:46:19 +00004298add_members(PyTypeObject *type, PyMemberDef *memb)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004299{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004300 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004301
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004302 for (; memb->name != NULL; memb++) {
4303 PyObject *descr;
4304 if (PyDict_GetItemString(dict, memb->name))
4305 continue;
4306 descr = PyDescr_NewMember(type, memb);
4307 if (descr == NULL)
4308 return -1;
4309 if (PyDict_SetItemString(dict, memb->name, descr) < 0)
4310 return -1;
4311 Py_DECREF(descr);
4312 }
4313 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004314}
4315
4316static int
Guido van Rossum32d34c82001-09-20 21:45:26 +00004317add_getset(PyTypeObject *type, PyGetSetDef *gsp)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004318{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004319 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004320
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004321 for (; gsp->name != NULL; gsp++) {
4322 PyObject *descr;
4323 if (PyDict_GetItemString(dict, gsp->name))
4324 continue;
4325 descr = PyDescr_NewGetSet(type, gsp);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004326
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004327 if (descr == NULL)
4328 return -1;
4329 if (PyDict_SetItemString(dict, gsp->name, descr) < 0)
4330 return -1;
4331 Py_DECREF(descr);
4332 }
4333 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004334}
4335
Guido van Rossum13d52f02001-08-10 21:24:08 +00004336static void
4337inherit_special(PyTypeObject *type, PyTypeObject *base)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004338{
Tim Peters6d6c1a32001-08-02 04:15:00 +00004339
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004340 /* Copying basicsize is connected to the GC flags */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004341 if (!(type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
4342 (base->tp_flags & Py_TPFLAGS_HAVE_GC) &&
4343 (!type->tp_traverse && !type->tp_clear)) {
4344 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
4345 if (type->tp_traverse == NULL)
4346 type->tp_traverse = base->tp_traverse;
4347 if (type->tp_clear == NULL)
4348 type->tp_clear = base->tp_clear;
4349 }
4350 {
4351 /* The condition below could use some explanation.
4352 It appears that tp_new is not inherited for static types
4353 whose base class is 'object'; this seems to be a precaution
4354 so that old extension types don't suddenly become
4355 callable (object.__new__ wouldn't insure the invariants
4356 that the extension type's own factory function ensures).
4357 Heap types, of course, are under our control, so they do
4358 inherit tp_new; static extension types that specify some
Florent Xiclunaaa6c1d22011-12-12 18:54:29 +01004359 other built-in type as the default also
4360 inherit object.__new__. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004361 if (base != &PyBaseObject_Type ||
4362 (type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
4363 if (type->tp_new == NULL)
4364 type->tp_new = base->tp_new;
4365 }
4366 }
Benjamin Petersona7465e22010-07-05 15:01:22 +00004367 if (type->tp_basicsize == 0)
4368 type->tp_basicsize = base->tp_basicsize;
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00004369
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004370 /* Copy other non-function slots */
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00004371
4372#undef COPYVAL
4373#define COPYVAL(SLOT) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004374 if (type->SLOT == 0) type->SLOT = base->SLOT
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00004375
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004376 COPYVAL(tp_itemsize);
4377 COPYVAL(tp_weaklistoffset);
4378 COPYVAL(tp_dictoffset);
Thomas Wouters27d517b2007-02-25 20:39:11 +00004379
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004380 /* Setup fast subclass flags */
4381 if (PyType_IsSubtype(base, (PyTypeObject*)PyExc_BaseException))
4382 type->tp_flags |= Py_TPFLAGS_BASE_EXC_SUBCLASS;
4383 else if (PyType_IsSubtype(base, &PyType_Type))
4384 type->tp_flags |= Py_TPFLAGS_TYPE_SUBCLASS;
4385 else if (PyType_IsSubtype(base, &PyLong_Type))
4386 type->tp_flags |= Py_TPFLAGS_LONG_SUBCLASS;
4387 else if (PyType_IsSubtype(base, &PyBytes_Type))
4388 type->tp_flags |= Py_TPFLAGS_BYTES_SUBCLASS;
4389 else if (PyType_IsSubtype(base, &PyUnicode_Type))
4390 type->tp_flags |= Py_TPFLAGS_UNICODE_SUBCLASS;
4391 else if (PyType_IsSubtype(base, &PyTuple_Type))
4392 type->tp_flags |= Py_TPFLAGS_TUPLE_SUBCLASS;
4393 else if (PyType_IsSubtype(base, &PyList_Type))
4394 type->tp_flags |= Py_TPFLAGS_LIST_SUBCLASS;
4395 else if (PyType_IsSubtype(base, &PyDict_Type))
4396 type->tp_flags |= Py_TPFLAGS_DICT_SUBCLASS;
Guido van Rossum13d52f02001-08-10 21:24:08 +00004397}
4398
Guido van Rossum38938152006-08-21 23:36:26 +00004399static int
Guido van Rossumf5243f02008-01-01 04:06:48 +00004400overrides_hash(PyTypeObject *type)
Guido van Rossum38938152006-08-21 23:36:26 +00004401{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004402 PyObject *dict = type->tp_dict;
Victor Stinner3c1e4812012-03-26 22:10:51 +02004403 _Py_IDENTIFIER(__eq__);
Guido van Rossum38938152006-08-21 23:36:26 +00004404
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004405 assert(dict != NULL);
Victor Stinner3c1e4812012-03-26 22:10:51 +02004406 if (_PyDict_GetItemId(dict, &PyId___eq__) != NULL)
4407 return 1;
4408 if (_PyDict_GetItemId(dict, &PyId___hash__) != NULL)
4409 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004410 return 0;
Guido van Rossum38938152006-08-21 23:36:26 +00004411}
4412
Guido van Rossum13d52f02001-08-10 21:24:08 +00004413static void
4414inherit_slots(PyTypeObject *type, PyTypeObject *base)
4415{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004416 PyTypeObject *basebase;
Guido van Rossum13d52f02001-08-10 21:24:08 +00004417
4418#undef SLOTDEFINED
Tim Peters6d6c1a32001-08-02 04:15:00 +00004419#undef COPYSLOT
4420#undef COPYNUM
4421#undef COPYSEQ
4422#undef COPYMAP
Guido van Rossum5af588b2001-10-12 14:13:21 +00004423#undef COPYBUF
Guido van Rossum13d52f02001-08-10 21:24:08 +00004424
4425#define SLOTDEFINED(SLOT) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004426 (base->SLOT != 0 && \
4427 (basebase == NULL || base->SLOT != basebase->SLOT))
Guido van Rossum13d52f02001-08-10 21:24:08 +00004428
Tim Peters6d6c1a32001-08-02 04:15:00 +00004429#define COPYSLOT(SLOT) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004430 if (!type->SLOT && SLOTDEFINED(SLOT)) type->SLOT = base->SLOT
Tim Peters6d6c1a32001-08-02 04:15:00 +00004431
4432#define COPYNUM(SLOT) COPYSLOT(tp_as_number->SLOT)
4433#define COPYSEQ(SLOT) COPYSLOT(tp_as_sequence->SLOT)
4434#define COPYMAP(SLOT) COPYSLOT(tp_as_mapping->SLOT)
Tim Petersfc57ccb2001-10-12 02:38:24 +00004435#define COPYBUF(SLOT) COPYSLOT(tp_as_buffer->SLOT)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004436
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004437 /* This won't inherit indirect slots (from tp_as_number etc.)
4438 if type doesn't provide the space. */
Guido van Rossum13d52f02001-08-10 21:24:08 +00004439
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004440 if (type->tp_as_number != NULL && base->tp_as_number != NULL) {
4441 basebase = base->tp_base;
4442 if (basebase->tp_as_number == NULL)
4443 basebase = NULL;
4444 COPYNUM(nb_add);
4445 COPYNUM(nb_subtract);
4446 COPYNUM(nb_multiply);
4447 COPYNUM(nb_remainder);
4448 COPYNUM(nb_divmod);
4449 COPYNUM(nb_power);
4450 COPYNUM(nb_negative);
4451 COPYNUM(nb_positive);
4452 COPYNUM(nb_absolute);
4453 COPYNUM(nb_bool);
4454 COPYNUM(nb_invert);
4455 COPYNUM(nb_lshift);
4456 COPYNUM(nb_rshift);
4457 COPYNUM(nb_and);
4458 COPYNUM(nb_xor);
4459 COPYNUM(nb_or);
4460 COPYNUM(nb_int);
4461 COPYNUM(nb_float);
4462 COPYNUM(nb_inplace_add);
4463 COPYNUM(nb_inplace_subtract);
4464 COPYNUM(nb_inplace_multiply);
4465 COPYNUM(nb_inplace_remainder);
4466 COPYNUM(nb_inplace_power);
4467 COPYNUM(nb_inplace_lshift);
4468 COPYNUM(nb_inplace_rshift);
4469 COPYNUM(nb_inplace_and);
4470 COPYNUM(nb_inplace_xor);
4471 COPYNUM(nb_inplace_or);
4472 COPYNUM(nb_true_divide);
4473 COPYNUM(nb_floor_divide);
4474 COPYNUM(nb_inplace_true_divide);
4475 COPYNUM(nb_inplace_floor_divide);
4476 COPYNUM(nb_index);
Benjamin Petersond51374e2014-04-09 23:55:56 -04004477 COPYNUM(nb_matrix_multiply);
4478 COPYNUM(nb_inplace_matrix_multiply);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004479 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004480
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004481 if (type->tp_as_sequence != NULL && base->tp_as_sequence != NULL) {
4482 basebase = base->tp_base;
4483 if (basebase->tp_as_sequence == NULL)
4484 basebase = NULL;
4485 COPYSEQ(sq_length);
4486 COPYSEQ(sq_concat);
4487 COPYSEQ(sq_repeat);
4488 COPYSEQ(sq_item);
4489 COPYSEQ(sq_ass_item);
4490 COPYSEQ(sq_contains);
4491 COPYSEQ(sq_inplace_concat);
4492 COPYSEQ(sq_inplace_repeat);
4493 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004494
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004495 if (type->tp_as_mapping != NULL && base->tp_as_mapping != NULL) {
4496 basebase = base->tp_base;
4497 if (basebase->tp_as_mapping == NULL)
4498 basebase = NULL;
4499 COPYMAP(mp_length);
4500 COPYMAP(mp_subscript);
4501 COPYMAP(mp_ass_subscript);
4502 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004503
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004504 if (type->tp_as_buffer != NULL && base->tp_as_buffer != NULL) {
4505 basebase = base->tp_base;
4506 if (basebase->tp_as_buffer == NULL)
4507 basebase = NULL;
4508 COPYBUF(bf_getbuffer);
4509 COPYBUF(bf_releasebuffer);
4510 }
Tim Petersfc57ccb2001-10-12 02:38:24 +00004511
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004512 basebase = base->tp_base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004513
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004514 COPYSLOT(tp_dealloc);
4515 if (type->tp_getattr == NULL && type->tp_getattro == NULL) {
4516 type->tp_getattr = base->tp_getattr;
4517 type->tp_getattro = base->tp_getattro;
4518 }
4519 if (type->tp_setattr == NULL && type->tp_setattro == NULL) {
4520 type->tp_setattr = base->tp_setattr;
4521 type->tp_setattro = base->tp_setattro;
4522 }
4523 /* tp_reserved is ignored */
4524 COPYSLOT(tp_repr);
4525 /* tp_hash see tp_richcompare */
4526 COPYSLOT(tp_call);
4527 COPYSLOT(tp_str);
4528 {
4529 /* Copy comparison-related slots only when
4530 not overriding them anywhere */
4531 if (type->tp_richcompare == NULL &&
4532 type->tp_hash == NULL &&
4533 !overrides_hash(type))
4534 {
4535 type->tp_richcompare = base->tp_richcompare;
4536 type->tp_hash = base->tp_hash;
4537 }
4538 }
4539 {
4540 COPYSLOT(tp_iter);
4541 COPYSLOT(tp_iternext);
4542 }
4543 {
4544 COPYSLOT(tp_descr_get);
4545 COPYSLOT(tp_descr_set);
4546 COPYSLOT(tp_dictoffset);
4547 COPYSLOT(tp_init);
4548 COPYSLOT(tp_alloc);
4549 COPYSLOT(tp_is_gc);
Antoine Pitrou796564c2013-07-30 19:59:21 +02004550 if ((type->tp_flags & Py_TPFLAGS_HAVE_FINALIZE) &&
4551 (base->tp_flags & Py_TPFLAGS_HAVE_FINALIZE)) {
4552 COPYSLOT(tp_finalize);
4553 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004554 if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) ==
4555 (base->tp_flags & Py_TPFLAGS_HAVE_GC)) {
4556 /* They agree about gc. */
4557 COPYSLOT(tp_free);
4558 }
4559 else if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
4560 type->tp_free == NULL &&
4561 base->tp_free == PyObject_Free) {
4562 /* A bit of magic to plug in the correct default
4563 * tp_free function when a derived class adds gc,
4564 * didn't define tp_free, and the base uses the
4565 * default non-gc tp_free.
4566 */
4567 type->tp_free = PyObject_GC_Del;
4568 }
4569 /* else they didn't agree about gc, and there isn't something
4570 * obvious to be done -- the type is on its own.
4571 */
4572 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004573}
4574
Jeremy Hylton938ace62002-07-17 16:30:39 +00004575static int add_operators(PyTypeObject *);
Guido van Rossum13d52f02001-08-10 21:24:08 +00004576
Tim Peters6d6c1a32001-08-02 04:15:00 +00004577int
Guido van Rossum528b7eb2001-08-07 17:24:28 +00004578PyType_Ready(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004579{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004580 PyObject *dict, *bases;
4581 PyTypeObject *base;
4582 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004583
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004584 if (type->tp_flags & Py_TPFLAGS_READY) {
4585 assert(type->tp_dict != NULL);
4586 return 0;
4587 }
4588 assert((type->tp_flags & Py_TPFLAGS_READYING) == 0);
Guido van Rossumd614f972001-08-10 17:39:49 +00004589
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004590 type->tp_flags |= Py_TPFLAGS_READYING;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004591
Tim Peters36eb4df2003-03-23 03:33:13 +00004592#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004593 /* PyType_Ready is the closest thing we have to a choke point
4594 * for type objects, so is the best place I can think of to try
4595 * to get type objects into the doubly-linked list of all objects.
4596 * Still, not all type objects go thru PyType_Ready.
4597 */
4598 _Py_AddToAllObjects((PyObject *)type, 0);
Tim Peters36eb4df2003-03-23 03:33:13 +00004599#endif
4600
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004601 /* Initialize tp_base (defaults to BaseObject unless that's us) */
4602 base = type->tp_base;
4603 if (base == NULL && type != &PyBaseObject_Type) {
4604 base = type->tp_base = &PyBaseObject_Type;
4605 Py_INCREF(base);
4606 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004607
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004608 /* Now the only way base can still be NULL is if type is
4609 * &PyBaseObject_Type.
4610 */
Guido van Rossum692cdbc2006-03-10 02:04:28 +00004611
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004612 /* Initialize the base class */
4613 if (base != NULL && base->tp_dict == NULL) {
4614 if (PyType_Ready(base) < 0)
4615 goto error;
4616 }
Guido van Rossum323a9cf2002-08-14 17:26:30 +00004617
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004618 /* Initialize ob_type if NULL. This means extensions that want to be
4619 compilable separately on Windows can call PyType_Ready() instead of
4620 initializing the ob_type field of their type objects. */
4621 /* The test for base != NULL is really unnecessary, since base is only
4622 NULL when type is &PyBaseObject_Type, and we know its ob_type is
4623 not NULL (it's initialized to &PyType_Type). But coverity doesn't
4624 know that. */
4625 if (Py_TYPE(type) == NULL && base != NULL)
4626 Py_TYPE(type) = Py_TYPE(base);
Guido van Rossum0986d822002-04-08 01:38:42 +00004627
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004628 /* Initialize tp_bases */
4629 bases = type->tp_bases;
4630 if (bases == NULL) {
4631 if (base == NULL)
4632 bases = PyTuple_New(0);
4633 else
4634 bases = PyTuple_Pack(1, base);
4635 if (bases == NULL)
4636 goto error;
4637 type->tp_bases = bases;
4638 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004639
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004640 /* Initialize tp_dict */
4641 dict = type->tp_dict;
4642 if (dict == NULL) {
4643 dict = PyDict_New();
4644 if (dict == NULL)
4645 goto error;
4646 type->tp_dict = dict;
4647 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004648
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004649 /* Add type-specific descriptors to tp_dict */
4650 if (add_operators(type) < 0)
4651 goto error;
4652 if (type->tp_methods != NULL) {
4653 if (add_methods(type, type->tp_methods) < 0)
4654 goto error;
4655 }
4656 if (type->tp_members != NULL) {
4657 if (add_members(type, type->tp_members) < 0)
4658 goto error;
4659 }
4660 if (type->tp_getset != NULL) {
4661 if (add_getset(type, type->tp_getset) < 0)
4662 goto error;
4663 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004664
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004665 /* Calculate method resolution order */
4666 if (mro_internal(type) < 0) {
4667 goto error;
4668 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004669
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004670 /* Inherit special flags from dominant base */
4671 if (type->tp_base != NULL)
4672 inherit_special(type, type->tp_base);
Guido van Rossum13d52f02001-08-10 21:24:08 +00004673
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004674 /* Initialize tp_dict properly */
4675 bases = type->tp_mro;
4676 assert(bases != NULL);
4677 assert(PyTuple_Check(bases));
4678 n = PyTuple_GET_SIZE(bases);
4679 for (i = 1; i < n; i++) {
4680 PyObject *b = PyTuple_GET_ITEM(bases, i);
4681 if (PyType_Check(b))
4682 inherit_slots(type, (PyTypeObject *)b);
4683 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004684
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004685 /* Sanity check for tp_free. */
4686 if (PyType_IS_GC(type) && (type->tp_flags & Py_TPFLAGS_BASETYPE) &&
4687 (type->tp_free == NULL || type->tp_free == PyObject_Del)) {
4688 /* This base class needs to call tp_free, but doesn't have
4689 * one, or its tp_free is for non-gc'ed objects.
4690 */
4691 PyErr_Format(PyExc_TypeError, "type '%.100s' participates in "
4692 "gc and is a base type but has inappropriate "
4693 "tp_free slot",
4694 type->tp_name);
4695 goto error;
4696 }
Tim Peters3cfe7542003-05-21 21:29:48 +00004697
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004698 /* if the type dictionary doesn't contain a __doc__, set it from
4699 the tp_doc slot.
4700 */
Victor Stinner3c1e4812012-03-26 22:10:51 +02004701 if (_PyDict_GetItemId(type->tp_dict, &PyId___doc__) == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004702 if (type->tp_doc != NULL) {
Larry Hastings2623c8c2014-02-08 22:15:29 -08004703 const char *old_doc = _PyType_DocWithoutSignature(type->tp_name,
4704 type->tp_doc);
Larry Hastings5c661892014-01-24 06:17:25 -08004705 PyObject *doc = PyUnicode_FromString(old_doc);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004706 if (doc == NULL)
4707 goto error;
Victor Stinner5967bf42013-07-17 22:01:37 +02004708 if (_PyDict_SetItemId(type->tp_dict, &PyId___doc__, doc) < 0) {
4709 Py_DECREF(doc);
4710 goto error;
4711 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004712 Py_DECREF(doc);
4713 } else {
Victor Stinner5967bf42013-07-17 22:01:37 +02004714 if (_PyDict_SetItemId(type->tp_dict,
4715 &PyId___doc__, Py_None) < 0)
4716 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004717 }
4718 }
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00004719
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004720 /* Hack for tp_hash and __hash__.
4721 If after all that, tp_hash is still NULL, and __hash__ is not in
4722 tp_dict, set tp_hash to PyObject_HashNotImplemented and
4723 tp_dict['__hash__'] equal to None.
4724 This signals that __hash__ is not inherited.
4725 */
4726 if (type->tp_hash == NULL) {
Victor Stinner3c1e4812012-03-26 22:10:51 +02004727 if (_PyDict_GetItemId(type->tp_dict, &PyId___hash__) == NULL) {
4728 if (_PyDict_SetItemId(type->tp_dict, &PyId___hash__, Py_None) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004729 goto error;
4730 type->tp_hash = PyObject_HashNotImplemented;
4731 }
4732 }
Guido van Rossum38938152006-08-21 23:36:26 +00004733
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004734 /* Some more special stuff */
4735 base = type->tp_base;
4736 if (base != NULL) {
4737 if (type->tp_as_number == NULL)
4738 type->tp_as_number = base->tp_as_number;
4739 if (type->tp_as_sequence == NULL)
4740 type->tp_as_sequence = base->tp_as_sequence;
4741 if (type->tp_as_mapping == NULL)
4742 type->tp_as_mapping = base->tp_as_mapping;
4743 if (type->tp_as_buffer == NULL)
4744 type->tp_as_buffer = base->tp_as_buffer;
4745 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004746
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004747 /* Link into each base class's list of subclasses */
4748 bases = type->tp_bases;
4749 n = PyTuple_GET_SIZE(bases);
4750 for (i = 0; i < n; i++) {
4751 PyObject *b = PyTuple_GET_ITEM(bases, i);
4752 if (PyType_Check(b) &&
4753 add_subclass((PyTypeObject *)b, type) < 0)
4754 goto error;
4755 }
Guido van Rossum1c450732001-10-08 15:18:27 +00004756
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004757 /* Warn for a type that implements tp_compare (now known as
4758 tp_reserved) but not tp_richcompare. */
4759 if (type->tp_reserved && !type->tp_richcompare) {
Andrew Svetlov2cd8ce42012-12-23 14:27:17 +02004760 PyErr_Format(PyExc_TypeError,
Victor Stinner4a2b7a12010-08-13 14:03:48 +00004761 "Type %.100s defines tp_reserved (formerly tp_compare) "
4762 "but not tp_richcompare. Comparisons may not behave as intended.",
4763 type->tp_name);
Andrew Svetlov2cd8ce42012-12-23 14:27:17 +02004764 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004765 }
Mark Dickinson2a7d45b2009-02-08 11:02:10 +00004766
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004767 /* All done -- set the ready flag */
4768 assert(type->tp_dict != NULL);
4769 type->tp_flags =
4770 (type->tp_flags & ~Py_TPFLAGS_READYING) | Py_TPFLAGS_READY;
4771 return 0;
Guido van Rossumd614f972001-08-10 17:39:49 +00004772
4773 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004774 type->tp_flags &= ~Py_TPFLAGS_READYING;
4775 return -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004776}
4777
Guido van Rossum1c450732001-10-08 15:18:27 +00004778static int
4779add_subclass(PyTypeObject *base, PyTypeObject *type)
4780{
Antoine Pitrou84745ab2013-10-29 21:31:25 +01004781 int result = -1;
4782 PyObject *dict, *key, *newobj;
Guido van Rossum1c450732001-10-08 15:18:27 +00004783
Antoine Pitrou84745ab2013-10-29 21:31:25 +01004784 dict = base->tp_subclasses;
4785 if (dict == NULL) {
4786 base->tp_subclasses = dict = PyDict_New();
4787 if (dict == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004788 return -1;
4789 }
Antoine Pitrou84745ab2013-10-29 21:31:25 +01004790 assert(PyDict_CheckExact(dict));
4791 key = PyLong_FromVoidPtr((void *) type);
4792 if (key == NULL)
Victor Stinner9812af82013-07-08 22:25:48 +02004793 return -1;
Antoine Pitrou84745ab2013-10-29 21:31:25 +01004794 newobj = PyWeakref_NewRef((PyObject *)type, NULL);
4795 if (newobj != NULL) {
4796 result = PyDict_SetItem(dict, key, newobj);
4797 Py_DECREF(newobj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004798 }
Antoine Pitrou84745ab2013-10-29 21:31:25 +01004799 Py_DECREF(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004800 return result;
Guido van Rossum1c450732001-10-08 15:18:27 +00004801}
4802
Michael W. Hudson98bbc492002-11-26 14:47:27 +00004803static void
4804remove_subclass(PyTypeObject *base, PyTypeObject *type)
4805{
Antoine Pitrou84745ab2013-10-29 21:31:25 +01004806 PyObject *dict, *key;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00004807
Antoine Pitrou84745ab2013-10-29 21:31:25 +01004808 dict = base->tp_subclasses;
4809 if (dict == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004810 return;
4811 }
Antoine Pitrou84745ab2013-10-29 21:31:25 +01004812 assert(PyDict_CheckExact(dict));
4813 key = PyLong_FromVoidPtr((void *) type);
4814 if (key == NULL || PyDict_DelItem(dict, key)) {
4815 /* This can happen if the type initialization errored out before
4816 the base subclasses were updated (e.g. a non-str __qualname__
4817 was passed in the type dict). */
4818 PyErr_Clear();
4819 }
4820 Py_XDECREF(key);
4821}
4822
4823static void
4824remove_all_subclasses(PyTypeObject *type, PyObject *bases)
4825{
4826 if (bases) {
4827 Py_ssize_t i;
4828 for (i = 0; i < PyTuple_GET_SIZE(bases); i++) {
4829 PyObject *base = PyTuple_GET_ITEM(bases, i);
4830 if (PyType_Check(base))
4831 remove_subclass((PyTypeObject*) base, type);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004832 }
4833 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +00004834}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004835
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004836static int
4837check_num_args(PyObject *ob, int n)
4838{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004839 if (!PyTuple_CheckExact(ob)) {
4840 PyErr_SetString(PyExc_SystemError,
4841 "PyArg_UnpackTuple() argument list is not a tuple");
4842 return 0;
4843 }
4844 if (n == PyTuple_GET_SIZE(ob))
4845 return 1;
4846 PyErr_Format(
4847 PyExc_TypeError,
4848 "expected %d arguments, got %zd", n, PyTuple_GET_SIZE(ob));
4849 return 0;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004850}
4851
Tim Peters6d6c1a32001-08-02 04:15:00 +00004852/* Generic wrappers for overloadable 'operators' such as __getitem__ */
4853
4854/* There's a wrapper *function* for each distinct function typedef used
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004855 for type object slots (e.g. binaryfunc, ternaryfunc, etc.). There's a
Tim Peters6d6c1a32001-08-02 04:15:00 +00004856 wrapper *table* for each distinct operation (e.g. __len__, __add__).
4857 Most tables have only one entry; the tables for binary operators have two
4858 entries, one regular and one with reversed arguments. */
4859
4860static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00004861wrap_lenfunc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004862{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004863 lenfunc func = (lenfunc)wrapped;
4864 Py_ssize_t res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004865
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004866 if (!check_num_args(args, 0))
4867 return NULL;
4868 res = (*func)(self);
4869 if (res == -1 && PyErr_Occurred())
4870 return NULL;
4871 return PyLong_FromLong((long)res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004872}
4873
Tim Peters6d6c1a32001-08-02 04:15:00 +00004874static PyObject *
Raymond Hettingerf34f2642003-10-11 17:29:04 +00004875wrap_inquirypred(PyObject *self, PyObject *args, void *wrapped)
4876{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004877 inquiry func = (inquiry)wrapped;
4878 int res;
Raymond Hettingerf34f2642003-10-11 17:29:04 +00004879
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004880 if (!check_num_args(args, 0))
4881 return NULL;
4882 res = (*func)(self);
4883 if (res == -1 && PyErr_Occurred())
4884 return NULL;
4885 return PyBool_FromLong((long)res);
Raymond Hettingerf34f2642003-10-11 17:29:04 +00004886}
4887
4888static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00004889wrap_binaryfunc(PyObject *self, PyObject *args, void *wrapped)
4890{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004891 binaryfunc func = (binaryfunc)wrapped;
4892 PyObject *other;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004893
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004894 if (!check_num_args(args, 1))
4895 return NULL;
4896 other = PyTuple_GET_ITEM(args, 0);
4897 return (*func)(self, other);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004898}
4899
4900static PyObject *
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00004901wrap_binaryfunc_l(PyObject *self, PyObject *args, void *wrapped)
4902{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004903 binaryfunc func = (binaryfunc)wrapped;
4904 PyObject *other;
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00004905
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004906 if (!check_num_args(args, 1))
4907 return NULL;
4908 other = PyTuple_GET_ITEM(args, 0);
4909 return (*func)(self, other);
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00004910}
4911
4912static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00004913wrap_binaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
4914{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004915 binaryfunc func = (binaryfunc)wrapped;
4916 PyObject *other;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004917
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004918 if (!check_num_args(args, 1))
4919 return NULL;
4920 other = PyTuple_GET_ITEM(args, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004921 return (*func)(other, self);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004922}
4923
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004924static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00004925wrap_ternaryfunc(PyObject *self, PyObject *args, void *wrapped)
4926{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004927 ternaryfunc func = (ternaryfunc)wrapped;
4928 PyObject *other;
4929 PyObject *third = Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004930
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004931 /* Note: This wrapper only works for __pow__() */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004932
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004933 if (!PyArg_UnpackTuple(args, "", 1, 2, &other, &third))
4934 return NULL;
4935 return (*func)(self, other, third);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004936}
4937
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00004938static PyObject *
4939wrap_ternaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
4940{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004941 ternaryfunc func = (ternaryfunc)wrapped;
4942 PyObject *other;
4943 PyObject *third = Py_None;
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00004944
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004945 /* Note: This wrapper only works for __pow__() */
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00004946
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004947 if (!PyArg_UnpackTuple(args, "", 1, 2, &other, &third))
4948 return NULL;
4949 return (*func)(other, self, third);
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00004950}
4951
Tim Peters6d6c1a32001-08-02 04:15:00 +00004952static PyObject *
4953wrap_unaryfunc(PyObject *self, PyObject *args, void *wrapped)
4954{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004955 unaryfunc func = (unaryfunc)wrapped;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004956
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004957 if (!check_num_args(args, 0))
4958 return NULL;
4959 return (*func)(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004960}
4961
Tim Peters6d6c1a32001-08-02 04:15:00 +00004962static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004963wrap_indexargfunc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004964{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004965 ssizeargfunc func = (ssizeargfunc)wrapped;
4966 PyObject* o;
4967 Py_ssize_t i;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004968
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004969 if (!PyArg_UnpackTuple(args, "", 1, 1, &o))
4970 return NULL;
4971 i = PyNumber_AsSsize_t(o, PyExc_OverflowError);
4972 if (i == -1 && PyErr_Occurred())
4973 return NULL;
4974 return (*func)(self, i);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004975}
4976
Martin v. Löwis18e16552006-02-15 17:27:45 +00004977static Py_ssize_t
Guido van Rossum5d815f32001-08-17 21:57:47 +00004978getindex(PyObject *self, PyObject *arg)
4979{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004980 Py_ssize_t i;
Guido van Rossum5d815f32001-08-17 21:57:47 +00004981
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004982 i = PyNumber_AsSsize_t(arg, PyExc_OverflowError);
4983 if (i == -1 && PyErr_Occurred())
4984 return -1;
4985 if (i < 0) {
4986 PySequenceMethods *sq = Py_TYPE(self)->tp_as_sequence;
4987 if (sq && sq->sq_length) {
4988 Py_ssize_t n = (*sq->sq_length)(self);
4989 if (n < 0)
4990 return -1;
4991 i += n;
4992 }
4993 }
4994 return i;
Guido van Rossum5d815f32001-08-17 21:57:47 +00004995}
4996
4997static PyObject *
4998wrap_sq_item(PyObject *self, PyObject *args, void *wrapped)
4999{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005000 ssizeargfunc func = (ssizeargfunc)wrapped;
5001 PyObject *arg;
5002 Py_ssize_t i;
Guido van Rossum5d815f32001-08-17 21:57:47 +00005003
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005004 if (PyTuple_GET_SIZE(args) == 1) {
5005 arg = PyTuple_GET_ITEM(args, 0);
5006 i = getindex(self, arg);
5007 if (i == -1 && PyErr_Occurred())
5008 return NULL;
5009 return (*func)(self, i);
5010 }
5011 check_num_args(args, 1);
5012 assert(PyErr_Occurred());
5013 return NULL;
Guido van Rossum5d815f32001-08-17 21:57:47 +00005014}
5015
Tim Peters6d6c1a32001-08-02 04:15:00 +00005016static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00005017wrap_sq_setitem(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005018{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005019 ssizeobjargproc func = (ssizeobjargproc)wrapped;
5020 Py_ssize_t i;
5021 int res;
5022 PyObject *arg, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005023
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005024 if (!PyArg_UnpackTuple(args, "", 2, 2, &arg, &value))
5025 return NULL;
5026 i = getindex(self, arg);
5027 if (i == -1 && PyErr_Occurred())
5028 return NULL;
5029 res = (*func)(self, i, value);
5030 if (res == -1 && PyErr_Occurred())
5031 return NULL;
5032 Py_INCREF(Py_None);
5033 return Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005034}
5035
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00005036static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00005037wrap_sq_delitem(PyObject *self, PyObject *args, void *wrapped)
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00005038{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005039 ssizeobjargproc func = (ssizeobjargproc)wrapped;
5040 Py_ssize_t i;
5041 int res;
5042 PyObject *arg;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00005043
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005044 if (!check_num_args(args, 1))
5045 return NULL;
5046 arg = PyTuple_GET_ITEM(args, 0);
5047 i = getindex(self, arg);
5048 if (i == -1 && PyErr_Occurred())
5049 return NULL;
5050 res = (*func)(self, i, NULL);
5051 if (res == -1 && PyErr_Occurred())
5052 return NULL;
5053 Py_INCREF(Py_None);
5054 return Py_None;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00005055}
5056
Tim Peters6d6c1a32001-08-02 04:15:00 +00005057/* XXX objobjproc is a misnomer; should be objargpred */
5058static PyObject *
5059wrap_objobjproc(PyObject *self, PyObject *args, void *wrapped)
5060{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005061 objobjproc func = (objobjproc)wrapped;
5062 int res;
5063 PyObject *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005064
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005065 if (!check_num_args(args, 1))
5066 return NULL;
5067 value = PyTuple_GET_ITEM(args, 0);
5068 res = (*func)(self, value);
5069 if (res == -1 && PyErr_Occurred())
5070 return NULL;
5071 else
5072 return PyBool_FromLong(res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005073}
5074
Tim Peters6d6c1a32001-08-02 04:15:00 +00005075static PyObject *
5076wrap_objobjargproc(PyObject *self, PyObject *args, void *wrapped)
5077{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005078 objobjargproc func = (objobjargproc)wrapped;
5079 int res;
5080 PyObject *key, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005081
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005082 if (!PyArg_UnpackTuple(args, "", 2, 2, &key, &value))
5083 return NULL;
5084 res = (*func)(self, key, value);
5085 if (res == -1 && PyErr_Occurred())
5086 return NULL;
5087 Py_INCREF(Py_None);
5088 return Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005089}
5090
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00005091static PyObject *
5092wrap_delitem(PyObject *self, PyObject *args, void *wrapped)
5093{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005094 objobjargproc func = (objobjargproc)wrapped;
5095 int res;
5096 PyObject *key;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00005097
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005098 if (!check_num_args(args, 1))
5099 return NULL;
5100 key = PyTuple_GET_ITEM(args, 0);
5101 res = (*func)(self, key, NULL);
5102 if (res == -1 && PyErr_Occurred())
5103 return NULL;
5104 Py_INCREF(Py_None);
5105 return Py_None;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00005106}
5107
Guido van Rossum4dcdb782003-04-14 21:46:03 +00005108/* Helper to check for object.__setattr__ or __delattr__ applied to a type.
Guido van Rossum52b27052003-04-15 20:05:10 +00005109 This is called the Carlo Verre hack after its discoverer. */
Guido van Rossum4dcdb782003-04-14 21:46:03 +00005110static int
5111hackcheck(PyObject *self, setattrofunc func, char *what)
5112{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005113 PyTypeObject *type = Py_TYPE(self);
5114 while (type && type->tp_flags & Py_TPFLAGS_HEAPTYPE)
5115 type = type->tp_base;
5116 /* If type is NULL now, this is a really weird type.
5117 In the spirit of backwards compatibility (?), just shut up. */
5118 if (type && type->tp_setattro != func) {
5119 PyErr_Format(PyExc_TypeError,
5120 "can't apply this %s to %s object",
5121 what,
5122 type->tp_name);
5123 return 0;
5124 }
5125 return 1;
Guido van Rossum4dcdb782003-04-14 21:46:03 +00005126}
5127
Tim Peters6d6c1a32001-08-02 04:15:00 +00005128static PyObject *
5129wrap_setattr(PyObject *self, PyObject *args, void *wrapped)
5130{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005131 setattrofunc func = (setattrofunc)wrapped;
5132 int res;
5133 PyObject *name, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005134
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005135 if (!PyArg_UnpackTuple(args, "", 2, 2, &name, &value))
5136 return NULL;
5137 if (!hackcheck(self, func, "__setattr__"))
5138 return NULL;
5139 res = (*func)(self, name, value);
5140 if (res < 0)
5141 return NULL;
5142 Py_INCREF(Py_None);
5143 return Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005144}
5145
5146static PyObject *
5147wrap_delattr(PyObject *self, PyObject *args, void *wrapped)
5148{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005149 setattrofunc func = (setattrofunc)wrapped;
5150 int res;
5151 PyObject *name;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005152
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005153 if (!check_num_args(args, 1))
5154 return NULL;
5155 name = PyTuple_GET_ITEM(args, 0);
5156 if (!hackcheck(self, func, "__delattr__"))
5157 return NULL;
5158 res = (*func)(self, name, NULL);
5159 if (res < 0)
5160 return NULL;
5161 Py_INCREF(Py_None);
5162 return Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005163}
5164
Tim Peters6d6c1a32001-08-02 04:15:00 +00005165static PyObject *
5166wrap_hashfunc(PyObject *self, PyObject *args, void *wrapped)
5167{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005168 hashfunc func = (hashfunc)wrapped;
Benjamin Peterson8035bc52010-10-23 16:20:50 +00005169 Py_hash_t res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005170
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005171 if (!check_num_args(args, 0))
5172 return NULL;
5173 res = (*func)(self);
5174 if (res == -1 && PyErr_Occurred())
5175 return NULL;
Benjamin Peterson8035bc52010-10-23 16:20:50 +00005176 return PyLong_FromSsize_t(res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005177}
5178
Tim Peters6d6c1a32001-08-02 04:15:00 +00005179static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00005180wrap_call(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005181{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005182 ternaryfunc func = (ternaryfunc)wrapped;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005183
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005184 return (*func)(self, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005185}
5186
Tim Peters6d6c1a32001-08-02 04:15:00 +00005187static PyObject *
Antoine Pitrou796564c2013-07-30 19:59:21 +02005188wrap_del(PyObject *self, PyObject *args, void *wrapped)
5189{
5190 destructor func = (destructor)wrapped;
5191
5192 if (!check_num_args(args, 0))
5193 return NULL;
5194
5195 (*func)(self);
5196 Py_RETURN_NONE;
5197}
5198
5199static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00005200wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op)
5201{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005202 richcmpfunc func = (richcmpfunc)wrapped;
5203 PyObject *other;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005204
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005205 if (!check_num_args(args, 1))
5206 return NULL;
5207 other = PyTuple_GET_ITEM(args, 0);
5208 return (*func)(self, other, op);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005209}
5210
5211#undef RICHCMP_WRAPPER
5212#define RICHCMP_WRAPPER(NAME, OP) \
5213static PyObject * \
5214richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \
5215{ \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005216 return wrap_richcmpfunc(self, args, wrapped, OP); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00005217}
5218
Jack Jansen8e938b42001-08-08 15:29:49 +00005219RICHCMP_WRAPPER(lt, Py_LT)
5220RICHCMP_WRAPPER(le, Py_LE)
5221RICHCMP_WRAPPER(eq, Py_EQ)
5222RICHCMP_WRAPPER(ne, Py_NE)
5223RICHCMP_WRAPPER(gt, Py_GT)
5224RICHCMP_WRAPPER(ge, Py_GE)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005225
Tim Peters6d6c1a32001-08-02 04:15:00 +00005226static PyObject *
5227wrap_next(PyObject *self, PyObject *args, void *wrapped)
5228{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005229 unaryfunc func = (unaryfunc)wrapped;
5230 PyObject *res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005231
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005232 if (!check_num_args(args, 0))
5233 return NULL;
5234 res = (*func)(self);
5235 if (res == NULL && !PyErr_Occurred())
5236 PyErr_SetNone(PyExc_StopIteration);
5237 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005238}
5239
Tim Peters6d6c1a32001-08-02 04:15:00 +00005240static PyObject *
5241wrap_descr_get(PyObject *self, PyObject *args, void *wrapped)
5242{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005243 descrgetfunc func = (descrgetfunc)wrapped;
5244 PyObject *obj;
5245 PyObject *type = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005246
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005247 if (!PyArg_UnpackTuple(args, "", 1, 2, &obj, &type))
5248 return NULL;
5249 if (obj == Py_None)
5250 obj = NULL;
5251 if (type == Py_None)
5252 type = NULL;
5253 if (type == NULL &&obj == NULL) {
5254 PyErr_SetString(PyExc_TypeError,
5255 "__get__(None, None) is invalid");
5256 return NULL;
5257 }
5258 return (*func)(self, obj, type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005259}
5260
Tim Peters6d6c1a32001-08-02 04:15:00 +00005261static PyObject *
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005262wrap_descr_set(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005263{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005264 descrsetfunc func = (descrsetfunc)wrapped;
5265 PyObject *obj, *value;
5266 int ret;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005267
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005268 if (!PyArg_UnpackTuple(args, "", 2, 2, &obj, &value))
5269 return NULL;
5270 ret = (*func)(self, obj, value);
5271 if (ret < 0)
5272 return NULL;
5273 Py_INCREF(Py_None);
5274 return Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005275}
Guido van Rossum22b13872002-08-06 21:41:44 +00005276
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00005277static PyObject *
5278wrap_descr_delete(PyObject *self, PyObject *args, void *wrapped)
5279{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005280 descrsetfunc func = (descrsetfunc)wrapped;
5281 PyObject *obj;
5282 int ret;
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00005283
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005284 if (!check_num_args(args, 1))
5285 return NULL;
5286 obj = PyTuple_GET_ITEM(args, 0);
5287 ret = (*func)(self, obj, NULL);
5288 if (ret < 0)
5289 return NULL;
5290 Py_INCREF(Py_None);
5291 return Py_None;
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00005292}
Tim Peters6d6c1a32001-08-02 04:15:00 +00005293
Tim Peters6d6c1a32001-08-02 04:15:00 +00005294static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00005295wrap_init(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005296{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005297 initproc func = (initproc)wrapped;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005298
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005299 if (func(self, args, kwds) < 0)
5300 return NULL;
5301 Py_INCREF(Py_None);
5302 return Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005303}
5304
Tim Peters6d6c1a32001-08-02 04:15:00 +00005305static PyObject *
Guido van Rossum0d231ed2001-08-06 16:50:37 +00005306tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005307{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005308 PyTypeObject *type, *subtype, *staticbase;
5309 PyObject *arg0, *res;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00005310
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005311 if (self == NULL || !PyType_Check(self))
5312 Py_FatalError("__new__() called with non-type 'self'");
5313 type = (PyTypeObject *)self;
5314 if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) {
5315 PyErr_Format(PyExc_TypeError,
5316 "%s.__new__(): not enough arguments",
5317 type->tp_name);
5318 return NULL;
5319 }
5320 arg0 = PyTuple_GET_ITEM(args, 0);
5321 if (!PyType_Check(arg0)) {
5322 PyErr_Format(PyExc_TypeError,
5323 "%s.__new__(X): X is not a type object (%s)",
5324 type->tp_name,
5325 Py_TYPE(arg0)->tp_name);
5326 return NULL;
5327 }
5328 subtype = (PyTypeObject *)arg0;
5329 if (!PyType_IsSubtype(subtype, type)) {
5330 PyErr_Format(PyExc_TypeError,
5331 "%s.__new__(%s): %s is not a subtype of %s",
5332 type->tp_name,
5333 subtype->tp_name,
5334 subtype->tp_name,
5335 type->tp_name);
5336 return NULL;
5337 }
Barry Warsaw60f01882001-08-22 19:24:42 +00005338
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005339 /* Check that the use doesn't do something silly and unsafe like
5340 object.__new__(dict). To do this, we check that the
5341 most derived base that's not a heap type is this type. */
5342 staticbase = subtype;
Martin v. Löwis9c564092012-06-23 23:20:45 +02005343 while (staticbase && (staticbase->tp_new == slot_tp_new))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005344 staticbase = staticbase->tp_base;
5345 /* If staticbase is NULL now, it is a really weird type.
5346 In the spirit of backwards compatibility (?), just shut up. */
5347 if (staticbase && staticbase->tp_new != type->tp_new) {
5348 PyErr_Format(PyExc_TypeError,
5349 "%s.__new__(%s) is not safe, use %s.__new__()",
5350 type->tp_name,
5351 subtype->tp_name,
5352 staticbase == NULL ? "?" : staticbase->tp_name);
5353 return NULL;
5354 }
Barry Warsaw60f01882001-08-22 19:24:42 +00005355
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005356 args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
5357 if (args == NULL)
5358 return NULL;
5359 res = type->tp_new(subtype, args, kwds);
5360 Py_DECREF(args);
5361 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005362}
5363
Guido van Rossum0d231ed2001-08-06 16:50:37 +00005364static struct PyMethodDef tp_new_methoddef[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005365 {"__new__", (PyCFunction)tp_new_wrapper, METH_VARARGS|METH_KEYWORDS,
Larry Hastings2623c8c2014-02-08 22:15:29 -08005366 PyDoc_STR("__new__($type, *args, **kwargs)\n--\n\n"
Larry Hastings581ee362014-01-28 05:00:08 -08005367 "Create and return a new object. "
5368 "See help(type) for accurate signature.")},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005369 {0}
Tim Peters6d6c1a32001-08-02 04:15:00 +00005370};
5371
5372static int
Guido van Rossum0d231ed2001-08-06 16:50:37 +00005373add_tp_new_wrapper(PyTypeObject *type)
5374{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005375 PyObject *func;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00005376
Victor Stinner3c1e4812012-03-26 22:10:51 +02005377 if (_PyDict_GetItemId(type->tp_dict, &PyId___new__) != NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005378 return 0;
Andrew Svetlov3ba3a3e2012-12-25 13:32:35 +02005379 func = PyCFunction_NewEx(tp_new_methoddef, (PyObject *)type, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005380 if (func == NULL)
5381 return -1;
Victor Stinner3c1e4812012-03-26 22:10:51 +02005382 if (_PyDict_SetItemId(type->tp_dict, &PyId___new__, func)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005383 Py_DECREF(func);
5384 return -1;
5385 }
5386 Py_DECREF(func);
5387 return 0;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00005388}
5389
Guido van Rossumf040ede2001-08-07 16:40:56 +00005390/* Slot wrappers that call the corresponding __foo__ slot. See comments
5391 below at override_slots() for more explanation. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00005392
Guido van Rossumdc91b992001-08-08 22:26:22 +00005393#define SLOT0(FUNCNAME, OPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00005394static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00005395FUNCNAME(PyObject *self) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00005396{ \
Benjamin Petersonce798522012-01-22 11:24:29 -05005397 _Py_static_string(id, OPSTR); \
5398 return call_method(self, &id, "()"); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00005399}
5400
Guido van Rossumdc91b992001-08-08 22:26:22 +00005401#define SLOT1(FUNCNAME, OPSTR, ARG1TYPE, ARGCODES) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00005402static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00005403FUNCNAME(PyObject *self, ARG1TYPE arg1) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00005404{ \
Benjamin Petersonce798522012-01-22 11:24:29 -05005405 _Py_static_string(id, OPSTR); \
5406 return call_method(self, &id, "(" ARGCODES ")", arg1); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00005407}
5408
Guido van Rossumcd118802003-01-06 22:57:47 +00005409/* Boolean helper for SLOT1BINFULL().
5410 right.__class__ is a nontrivial subclass of left.__class__. */
5411static int
Victor Stinner3c1e4812012-03-26 22:10:51 +02005412method_is_overloaded(PyObject *left, PyObject *right, struct _Py_Identifier *name)
Guido van Rossumcd118802003-01-06 22:57:47 +00005413{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005414 PyObject *a, *b;
5415 int ok;
Guido van Rossumcd118802003-01-06 22:57:47 +00005416
Victor Stinner3c1e4812012-03-26 22:10:51 +02005417 b = _PyObject_GetAttrId((PyObject *)(Py_TYPE(right)), name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005418 if (b == NULL) {
5419 PyErr_Clear();
5420 /* If right doesn't have it, it's not overloaded */
5421 return 0;
5422 }
Guido van Rossumcd118802003-01-06 22:57:47 +00005423
Victor Stinner3c1e4812012-03-26 22:10:51 +02005424 a = _PyObject_GetAttrId((PyObject *)(Py_TYPE(left)), name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005425 if (a == NULL) {
5426 PyErr_Clear();
5427 Py_DECREF(b);
5428 /* If right has it but left doesn't, it's overloaded */
5429 return 1;
5430 }
Guido van Rossumcd118802003-01-06 22:57:47 +00005431
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005432 ok = PyObject_RichCompareBool(a, b, Py_NE);
5433 Py_DECREF(a);
5434 Py_DECREF(b);
5435 if (ok < 0) {
5436 PyErr_Clear();
5437 return 0;
5438 }
Guido van Rossumcd118802003-01-06 22:57:47 +00005439
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005440 return ok;
Guido van Rossumcd118802003-01-06 22:57:47 +00005441}
5442
Guido van Rossumdc91b992001-08-08 22:26:22 +00005443
5444#define SLOT1BINFULL(FUNCNAME, TESTFUNC, SLOTNAME, OPSTR, ROPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00005445static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00005446FUNCNAME(PyObject *self, PyObject *other) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00005447{ \
Benjamin Petersonce798522012-01-22 11:24:29 -05005448 _Py_static_string(op_id, OPSTR); \
5449 _Py_static_string(rop_id, ROPSTR); \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005450 int do_other = Py_TYPE(self) != Py_TYPE(other) && \
5451 Py_TYPE(other)->tp_as_number != NULL && \
5452 Py_TYPE(other)->tp_as_number->SLOTNAME == TESTFUNC; \
5453 if (Py_TYPE(self)->tp_as_number != NULL && \
5454 Py_TYPE(self)->tp_as_number->SLOTNAME == TESTFUNC) { \
5455 PyObject *r; \
5456 if (do_other && \
5457 PyType_IsSubtype(Py_TYPE(other), Py_TYPE(self)) && \
Victor Stinner3c1e4812012-03-26 22:10:51 +02005458 method_is_overloaded(self, other, &rop_id)) { \
Benjamin Petersonce798522012-01-22 11:24:29 -05005459 r = call_maybe(other, &rop_id, "(O)", self); \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005460 if (r != Py_NotImplemented) \
5461 return r; \
5462 Py_DECREF(r); \
5463 do_other = 0; \
5464 } \
Benjamin Petersonce798522012-01-22 11:24:29 -05005465 r = call_maybe(self, &op_id, "(O)", other); \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005466 if (r != Py_NotImplemented || \
5467 Py_TYPE(other) == Py_TYPE(self)) \
5468 return r; \
5469 Py_DECREF(r); \
5470 } \
5471 if (do_other) { \
Benjamin Petersonce798522012-01-22 11:24:29 -05005472 return call_maybe(other, &rop_id, "(O)", self); \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005473 } \
Brian Curtindfc80e32011-08-10 20:28:54 -05005474 Py_RETURN_NOTIMPLEMENTED; \
Guido van Rossumdc91b992001-08-08 22:26:22 +00005475}
5476
5477#define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005478 SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR)
Guido van Rossumdc91b992001-08-08 22:26:22 +00005479
5480#define SLOT2(FUNCNAME, OPSTR, ARG1TYPE, ARG2TYPE, ARGCODES) \
5481static PyObject * \
5482FUNCNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \
5483{ \
Benjamin Petersonce798522012-01-22 11:24:29 -05005484 _Py_static_string(id, #OPSTR); \
5485 return call_method(self, &id, "(" ARGCODES ")", arg1, arg2); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00005486}
5487
Martin v. Löwis18e16552006-02-15 17:27:45 +00005488static Py_ssize_t
Tim Peters6d6c1a32001-08-02 04:15:00 +00005489slot_sq_length(PyObject *self)
5490{
Benjamin Petersonce798522012-01-22 11:24:29 -05005491 PyObject *res = call_method(self, &PyId___len__, "()");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005492 Py_ssize_t len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005493
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005494 if (res == NULL)
5495 return -1;
5496 len = PyNumber_AsSsize_t(res, PyExc_OverflowError);
5497 Py_DECREF(res);
5498 if (len < 0) {
5499 if (!PyErr_Occurred())
5500 PyErr_SetString(PyExc_ValueError,
5501 "__len__() should return >= 0");
5502 return -1;
5503 }
5504 return len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005505}
5506
Guido van Rossumf4593e02001-10-03 12:09:30 +00005507/* Super-optimized version of slot_sq_item.
5508 Other slots could do the same... */
5509static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00005510slot_sq_item(PyObject *self, Py_ssize_t i)
Guido van Rossumf4593e02001-10-03 12:09:30 +00005511{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005512 PyObject *func, *args = NULL, *ival = NULL, *retval = NULL;
5513 descrgetfunc f;
Guido van Rossumf4593e02001-10-03 12:09:30 +00005514
Victor Stinner3c1e4812012-03-26 22:10:51 +02005515 func = _PyType_LookupId(Py_TYPE(self), &PyId___getitem__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005516 if (func != NULL) {
5517 if ((f = Py_TYPE(func)->tp_descr_get) == NULL)
5518 Py_INCREF(func);
5519 else {
5520 func = f(func, self, (PyObject *)(Py_TYPE(self)));
5521 if (func == NULL) {
5522 return NULL;
5523 }
5524 }
5525 ival = PyLong_FromSsize_t(i);
5526 if (ival != NULL) {
5527 args = PyTuple_New(1);
5528 if (args != NULL) {
5529 PyTuple_SET_ITEM(args, 0, ival);
5530 retval = PyObject_Call(func, args, NULL);
5531 Py_XDECREF(args);
5532 Py_XDECREF(func);
5533 return retval;
5534 }
5535 }
5536 }
5537 else {
Victor Stinner3c1e4812012-03-26 22:10:51 +02005538 PyObject *getitem_str = _PyUnicode_FromId(&PyId___getitem__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005539 PyErr_SetObject(PyExc_AttributeError, getitem_str);
5540 }
5541 Py_XDECREF(args);
5542 Py_XDECREF(ival);
5543 Py_XDECREF(func);
5544 return NULL;
Guido van Rossumf4593e02001-10-03 12:09:30 +00005545}
5546
Tim Peters6d6c1a32001-08-02 04:15:00 +00005547static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00005548slot_sq_ass_item(PyObject *self, Py_ssize_t index, PyObject *value)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005549{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005550 PyObject *res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005551
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005552 if (value == NULL)
Benjamin Petersonce798522012-01-22 11:24:29 -05005553 res = call_method(self, &PyId___delitem__, "(n)", index);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005554 else
Benjamin Petersonce798522012-01-22 11:24:29 -05005555 res = call_method(self, &PyId___setitem__, "(nO)", index, value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005556 if (res == NULL)
5557 return -1;
5558 Py_DECREF(res);
5559 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005560}
5561
5562static int
Tim Peters6d6c1a32001-08-02 04:15:00 +00005563slot_sq_contains(PyObject *self, PyObject *value)
5564{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005565 PyObject *func, *res, *args;
5566 int result = -1;
Benjamin Petersonce798522012-01-22 11:24:29 -05005567 _Py_IDENTIFIER(__contains__);
Tim Petersbf9b2442003-03-23 05:35:36 +00005568
Benjamin Petersonce798522012-01-22 11:24:29 -05005569 func = lookup_maybe(self, &PyId___contains__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005570 if (func != NULL) {
5571 args = PyTuple_Pack(1, value);
5572 if (args == NULL)
5573 res = NULL;
5574 else {
5575 res = PyObject_Call(func, args, NULL);
5576 Py_DECREF(args);
5577 }
5578 Py_DECREF(func);
5579 if (res != NULL) {
5580 result = PyObject_IsTrue(res);
5581 Py_DECREF(res);
5582 }
5583 }
5584 else if (! PyErr_Occurred()) {
5585 /* Possible results: -1 and 1 */
5586 result = (int)_PySequence_IterSearch(self, value,
5587 PY_ITERSEARCH_CONTAINS);
5588 }
5589 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005590}
5591
Tim Peters6d6c1a32001-08-02 04:15:00 +00005592#define slot_mp_length slot_sq_length
5593
Guido van Rossumdc91b992001-08-08 22:26:22 +00005594SLOT1(slot_mp_subscript, "__getitem__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00005595
5596static int
5597slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value)
5598{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005599 PyObject *res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005600
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005601 if (value == NULL)
Benjamin Petersonce798522012-01-22 11:24:29 -05005602 res = call_method(self, &PyId___delitem__, "(O)", key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005603 else
Benjamin Petersonce798522012-01-22 11:24:29 -05005604 res = call_method(self, &PyId___setitem__, "(OO)", key, value);
5605
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005606 if (res == NULL)
5607 return -1;
5608 Py_DECREF(res);
5609 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005610}
5611
Guido van Rossumdc91b992001-08-08 22:26:22 +00005612SLOT1BIN(slot_nb_add, nb_add, "__add__", "__radd__")
5613SLOT1BIN(slot_nb_subtract, nb_subtract, "__sub__", "__rsub__")
5614SLOT1BIN(slot_nb_multiply, nb_multiply, "__mul__", "__rmul__")
Benjamin Petersond51374e2014-04-09 23:55:56 -04005615SLOT1BIN(slot_nb_matrix_multiply, nb_matrix_multiply, "__matmul__", "__rmatmul__")
Guido van Rossumdc91b992001-08-08 22:26:22 +00005616SLOT1BIN(slot_nb_remainder, nb_remainder, "__mod__", "__rmod__")
5617SLOT1BIN(slot_nb_divmod, nb_divmod, "__divmod__", "__rdivmod__")
5618
Jeremy Hylton938ace62002-07-17 16:30:39 +00005619static PyObject *slot_nb_power(PyObject *, PyObject *, PyObject *);
Guido van Rossumdc91b992001-08-08 22:26:22 +00005620
5621SLOT1BINFULL(slot_nb_power_binary, slot_nb_power,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005622 nb_power, "__pow__", "__rpow__")
Guido van Rossumdc91b992001-08-08 22:26:22 +00005623
5624static PyObject *
5625slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus)
5626{
Benjamin Petersonce798522012-01-22 11:24:29 -05005627 _Py_IDENTIFIER(__pow__);
Guido van Rossum2730b132001-08-28 18:22:14 +00005628
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005629 if (modulus == Py_None)
5630 return slot_nb_power_binary(self, other);
5631 /* Three-arg power doesn't use __rpow__. But ternary_op
5632 can call this when the second argument's type uses
5633 slot_nb_power, so check before calling self.__pow__. */
5634 if (Py_TYPE(self)->tp_as_number != NULL &&
5635 Py_TYPE(self)->tp_as_number->nb_power == slot_nb_power) {
Benjamin Petersonce798522012-01-22 11:24:29 -05005636 return call_method(self, &PyId___pow__, "(OO)", other, modulus);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005637 }
Brian Curtindfc80e32011-08-10 20:28:54 -05005638 Py_RETURN_NOTIMPLEMENTED;
Guido van Rossumdc91b992001-08-08 22:26:22 +00005639}
5640
5641SLOT0(slot_nb_negative, "__neg__")
5642SLOT0(slot_nb_positive, "__pos__")
5643SLOT0(slot_nb_absolute, "__abs__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00005644
5645static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00005646slot_nb_bool(PyObject *self)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005647{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005648 PyObject *func, *args;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005649 int result = -1;
5650 int using_len = 0;
Benjamin Petersonce798522012-01-22 11:24:29 -05005651 _Py_IDENTIFIER(__bool__);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005652
Benjamin Petersonce798522012-01-22 11:24:29 -05005653 func = lookup_maybe(self, &PyId___bool__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005654 if (func == NULL) {
5655 if (PyErr_Occurred())
5656 return -1;
Benjamin Petersonce798522012-01-22 11:24:29 -05005657 func = lookup_maybe(self, &PyId___len__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005658 if (func == NULL)
5659 return PyErr_Occurred() ? -1 : 1;
5660 using_len = 1;
5661 }
5662 args = PyTuple_New(0);
5663 if (args != NULL) {
5664 PyObject *temp = PyObject_Call(func, args, NULL);
5665 Py_DECREF(args);
5666 if (temp != NULL) {
5667 if (using_len) {
5668 /* enforced by slot_nb_len */
5669 result = PyObject_IsTrue(temp);
5670 }
5671 else if (PyBool_Check(temp)) {
5672 result = PyObject_IsTrue(temp);
5673 }
5674 else {
5675 PyErr_Format(PyExc_TypeError,
5676 "__bool__ should return "
5677 "bool, returned %s",
5678 Py_TYPE(temp)->tp_name);
5679 result = -1;
5680 }
5681 Py_DECREF(temp);
5682 }
5683 }
5684 Py_DECREF(func);
5685 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005686}
5687
Guido van Rossum38fff8c2006-03-07 18:50:55 +00005688
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00005689static PyObject *
Guido van Rossum38fff8c2006-03-07 18:50:55 +00005690slot_nb_index(PyObject *self)
5691{
Benjamin Petersonce798522012-01-22 11:24:29 -05005692 _Py_IDENTIFIER(__index__);
5693 return call_method(self, &PyId___index__, "()");
Guido van Rossum38fff8c2006-03-07 18:50:55 +00005694}
5695
5696
Guido van Rossumdc91b992001-08-08 22:26:22 +00005697SLOT0(slot_nb_invert, "__invert__")
5698SLOT1BIN(slot_nb_lshift, nb_lshift, "__lshift__", "__rlshift__")
5699SLOT1BIN(slot_nb_rshift, nb_rshift, "__rshift__", "__rrshift__")
5700SLOT1BIN(slot_nb_and, nb_and, "__and__", "__rand__")
5701SLOT1BIN(slot_nb_xor, nb_xor, "__xor__", "__rxor__")
5702SLOT1BIN(slot_nb_or, nb_or, "__or__", "__ror__")
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00005703
Guido van Rossumdc91b992001-08-08 22:26:22 +00005704SLOT0(slot_nb_int, "__int__")
Guido van Rossumdc91b992001-08-08 22:26:22 +00005705SLOT0(slot_nb_float, "__float__")
Guido van Rossumdc91b992001-08-08 22:26:22 +00005706SLOT1(slot_nb_inplace_add, "__iadd__", PyObject *, "O")
5707SLOT1(slot_nb_inplace_subtract, "__isub__", PyObject *, "O")
5708SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *, "O")
Benjamin Petersond51374e2014-04-09 23:55:56 -04005709SLOT1(slot_nb_inplace_matrix_multiply, "__imatmul__", PyObject *, "O")
Guido van Rossumdc91b992001-08-08 22:26:22 +00005710SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *, "O")
Thomas Wouterscf297e42007-02-23 15:07:44 +00005711/* Can't use SLOT1 here, because nb_inplace_power is ternary */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005712static PyObject *
5713slot_nb_inplace_power(PyObject *self, PyObject * arg1, PyObject *arg2)
5714{
Benjamin Petersonce798522012-01-22 11:24:29 -05005715 _Py_IDENTIFIER(__ipow__);
5716 return call_method(self, &PyId___ipow__, "(" "O" ")", arg1);
Thomas Wouterscf297e42007-02-23 15:07:44 +00005717}
Guido van Rossumdc91b992001-08-08 22:26:22 +00005718SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *, "O")
5719SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *, "O")
5720SLOT1(slot_nb_inplace_and, "__iand__", PyObject *, "O")
5721SLOT1(slot_nb_inplace_xor, "__ixor__", PyObject *, "O")
5722SLOT1(slot_nb_inplace_or, "__ior__", PyObject *, "O")
5723SLOT1BIN(slot_nb_floor_divide, nb_floor_divide,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005724 "__floordiv__", "__rfloordiv__")
Guido van Rossumdc91b992001-08-08 22:26:22 +00005725SLOT1BIN(slot_nb_true_divide, nb_true_divide, "__truediv__", "__rtruediv__")
5726SLOT1(slot_nb_inplace_floor_divide, "__ifloordiv__", PyObject *, "O")
5727SLOT1(slot_nb_inplace_true_divide, "__itruediv__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00005728
Guido van Rossumb8f63662001-08-15 23:57:02 +00005729static PyObject *
5730slot_tp_repr(PyObject *self)
5731{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005732 PyObject *func, *res;
Benjamin Petersonce798522012-01-22 11:24:29 -05005733 _Py_IDENTIFIER(__repr__);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005734
Benjamin Petersonce798522012-01-22 11:24:29 -05005735 func = lookup_method(self, &PyId___repr__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005736 if (func != NULL) {
5737 res = PyEval_CallObject(func, NULL);
5738 Py_DECREF(func);
5739 return res;
5740 }
5741 PyErr_Clear();
5742 return PyUnicode_FromFormat("<%s object at %p>",
5743 Py_TYPE(self)->tp_name, self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005744}
5745
5746static PyObject *
5747slot_tp_str(PyObject *self)
5748{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005749 PyObject *func, *res;
Benjamin Petersonce798522012-01-22 11:24:29 -05005750 _Py_IDENTIFIER(__str__);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005751
Benjamin Petersonce798522012-01-22 11:24:29 -05005752 func = lookup_method(self, &PyId___str__);
Victor Stinner2e8474d2013-07-11 22:46:11 +02005753 if (func == NULL)
5754 return NULL;
Victor Stinnerbebba502013-10-29 10:56:34 +01005755 res = PyEval_CallObject(func, NULL);
5756 Py_DECREF(func);
5757 return res;
5758}
Tim Peters6d6c1a32001-08-02 04:15:00 +00005759
Benjamin Peterson8f67d082010-10-17 20:54:53 +00005760static Py_hash_t
Tim Peters6d6c1a32001-08-02 04:15:00 +00005761slot_tp_hash(PyObject *self)
5762{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005763 PyObject *func, *res;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00005764 Py_ssize_t h;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005765
Benjamin Petersonce798522012-01-22 11:24:29 -05005766 func = lookup_method(self, &PyId___hash__);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005767
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005768 if (func == Py_None) {
5769 Py_DECREF(func);
5770 func = NULL;
5771 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +00005772
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005773 if (func == NULL) {
5774 return PyObject_HashNotImplemented(self);
5775 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +00005776
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005777 res = PyEval_CallObject(func, NULL);
5778 Py_DECREF(func);
5779 if (res == NULL)
5780 return -1;
Mark Dickinsondc787d22010-05-23 13:33:13 +00005781
5782 if (!PyLong_Check(res)) {
5783 PyErr_SetString(PyExc_TypeError,
5784 "__hash__ method should return an integer");
5785 return -1;
5786 }
Benjamin Peterson8f67d082010-10-17 20:54:53 +00005787 /* Transform the PyLong `res` to a Py_hash_t `h`. For an existing
5788 hashable Python object x, hash(x) will always lie within the range of
5789 Py_hash_t. Therefore our transformation must preserve values that
5790 already lie within this range, to ensure that if x.__hash__() returns
5791 hash(y) then hash(x) == hash(y). */
5792 h = PyLong_AsSsize_t(res);
5793 if (h == -1 && PyErr_Occurred()) {
5794 /* res was not within the range of a Py_hash_t, so we're free to
Mark Dickinsondc787d22010-05-23 13:33:13 +00005795 use any sufficiently bit-mixing transformation;
5796 long.__hash__ will do nicely. */
Benjamin Peterson8f67d082010-10-17 20:54:53 +00005797 PyErr_Clear();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005798 h = PyLong_Type.tp_hash(res);
Benjamin Peterson8f67d082010-10-17 20:54:53 +00005799 }
Benjamin Petersone7dfeeb2010-10-17 21:27:01 +00005800 /* -1 is reserved for errors. */
5801 if (h == -1)
5802 h = -2;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005803 Py_DECREF(res);
Mark Dickinsondc787d22010-05-23 13:33:13 +00005804 return h;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005805}
5806
5807static PyObject *
5808slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds)
5809{
Benjamin Petersonce798522012-01-22 11:24:29 -05005810 _Py_IDENTIFIER(__call__);
5811 PyObject *meth = lookup_method(self, &PyId___call__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005812 PyObject *res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005813
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005814 if (meth == NULL)
5815 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005816
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005817 res = PyObject_Call(meth, args, kwds);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005818
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005819 Py_DECREF(meth);
5820 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005821}
5822
Guido van Rossum14a6f832001-10-17 13:59:09 +00005823/* There are two slot dispatch functions for tp_getattro.
5824
5825 - slot_tp_getattro() is used when __getattribute__ is overridden
5826 but no __getattr__ hook is present;
5827
5828 - slot_tp_getattr_hook() is used when a __getattr__ hook is present.
5829
Guido van Rossumc334df52002-04-04 23:44:47 +00005830 The code in update_one_slot() always installs slot_tp_getattr_hook(); this
5831 detects the absence of __getattr__ and then installs the simpler slot if
5832 necessary. */
Guido van Rossum14a6f832001-10-17 13:59:09 +00005833
Tim Peters6d6c1a32001-08-02 04:15:00 +00005834static PyObject *
5835slot_tp_getattro(PyObject *self, PyObject *name)
5836{
Benjamin Petersonce798522012-01-22 11:24:29 -05005837 return call_method(self, &PyId___getattribute__, "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005838}
5839
Guido van Rossum19c1cd52001-09-21 21:24:49 +00005840static PyObject *
Benjamin Peterson9262b842008-11-17 22:45:50 +00005841call_attribute(PyObject *self, PyObject *attr, PyObject *name)
5842{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005843 PyObject *res, *descr = NULL;
5844 descrgetfunc f = Py_TYPE(attr)->tp_descr_get;
Benjamin Peterson9262b842008-11-17 22:45:50 +00005845
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005846 if (f != NULL) {
5847 descr = f(attr, self, (PyObject *)(Py_TYPE(self)));
5848 if (descr == NULL)
5849 return NULL;
5850 else
5851 attr = descr;
5852 }
5853 res = PyObject_CallFunctionObjArgs(attr, name, NULL);
5854 Py_XDECREF(descr);
5855 return res;
Benjamin Peterson9262b842008-11-17 22:45:50 +00005856}
5857
5858static PyObject *
Guido van Rossum19c1cd52001-09-21 21:24:49 +00005859slot_tp_getattr_hook(PyObject *self, PyObject *name)
5860{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005861 PyTypeObject *tp = Py_TYPE(self);
5862 PyObject *getattr, *getattribute, *res;
Victor Stinner3c1e4812012-03-26 22:10:51 +02005863 _Py_IDENTIFIER(__getattr__);
Guido van Rossum19c1cd52001-09-21 21:24:49 +00005864
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005865 /* speed hack: we could use lookup_maybe, but that would resolve the
5866 method fully for each attribute lookup for classes with
5867 __getattr__, even when the attribute is present. So we use
5868 _PyType_Lookup and create the method only when needed, with
5869 call_attribute. */
Victor Stinner3c1e4812012-03-26 22:10:51 +02005870 getattr = _PyType_LookupId(tp, &PyId___getattr__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005871 if (getattr == NULL) {
5872 /* No __getattr__ hook: use a simpler dispatcher */
5873 tp->tp_getattro = slot_tp_getattro;
5874 return slot_tp_getattro(self, name);
5875 }
5876 Py_INCREF(getattr);
5877 /* speed hack: we could use lookup_maybe, but that would resolve the
5878 method fully for each attribute lookup for classes with
5879 __getattr__, even when self has the default __getattribute__
5880 method. So we use _PyType_Lookup and create the method only when
5881 needed, with call_attribute. */
Victor Stinner3c1e4812012-03-26 22:10:51 +02005882 getattribute = _PyType_LookupId(tp, &PyId___getattribute__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005883 if (getattribute == NULL ||
5884 (Py_TYPE(getattribute) == &PyWrapperDescr_Type &&
5885 ((PyWrapperDescrObject *)getattribute)->d_wrapped ==
5886 (void *)PyObject_GenericGetAttr))
5887 res = PyObject_GenericGetAttr(self, name);
5888 else {
5889 Py_INCREF(getattribute);
5890 res = call_attribute(self, getattribute, name);
5891 Py_DECREF(getattribute);
5892 }
5893 if (res == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) {
5894 PyErr_Clear();
5895 res = call_attribute(self, getattr, name);
5896 }
5897 Py_DECREF(getattr);
5898 return res;
Guido van Rossum19c1cd52001-09-21 21:24:49 +00005899}
5900
Tim Peters6d6c1a32001-08-02 04:15:00 +00005901static int
5902slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value)
5903{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005904 PyObject *res;
Benjamin Petersonce798522012-01-22 11:24:29 -05005905 _Py_IDENTIFIER(__delattr__);
5906 _Py_IDENTIFIER(__setattr__);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005907
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005908 if (value == NULL)
Benjamin Petersonce798522012-01-22 11:24:29 -05005909 res = call_method(self, &PyId___delattr__, "(O)", name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005910 else
Benjamin Petersonce798522012-01-22 11:24:29 -05005911 res = call_method(self, &PyId___setattr__, "(OO)", name, value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005912 if (res == NULL)
5913 return -1;
5914 Py_DECREF(res);
5915 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005916}
5917
Benjamin Petersonce798522012-01-22 11:24:29 -05005918static _Py_Identifier name_op[] = {
5919 {0, "__lt__", 0},
5920 {0, "__le__", 0},
5921 {0, "__eq__", 0},
5922 {0, "__ne__", 0},
5923 {0, "__gt__", 0},
5924 {0, "__ge__", 0}
Guido van Rossumf5243f02008-01-01 04:06:48 +00005925};
5926
Tim Peters6d6c1a32001-08-02 04:15:00 +00005927static PyObject *
Mark Dickinson6f1d0492009-11-15 13:58:49 +00005928slot_tp_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005929{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005930 PyObject *func, *args, *res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005931
Benjamin Petersonce798522012-01-22 11:24:29 -05005932 func = lookup_method(self, &name_op[op]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005933 if (func == NULL) {
5934 PyErr_Clear();
Brian Curtindfc80e32011-08-10 20:28:54 -05005935 Py_RETURN_NOTIMPLEMENTED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005936 }
5937 args = PyTuple_Pack(1, other);
5938 if (args == NULL)
5939 res = NULL;
5940 else {
5941 res = PyObject_Call(func, args, NULL);
5942 Py_DECREF(args);
5943 }
5944 Py_DECREF(func);
5945 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005946}
5947
Guido van Rossumb8f63662001-08-15 23:57:02 +00005948static PyObject *
Guido van Rossumb8f63662001-08-15 23:57:02 +00005949slot_tp_iter(PyObject *self)
5950{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005951 PyObject *func, *res;
Benjamin Petersonce798522012-01-22 11:24:29 -05005952 _Py_IDENTIFIER(__iter__);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005953
Benjamin Petersonce798522012-01-22 11:24:29 -05005954 func = lookup_method(self, &PyId___iter__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005955 if (func != NULL) {
5956 PyObject *args;
5957 args = res = PyTuple_New(0);
5958 if (args != NULL) {
5959 res = PyObject_Call(func, args, NULL);
5960 Py_DECREF(args);
5961 }
5962 Py_DECREF(func);
5963 return res;
5964 }
5965 PyErr_Clear();
Benjamin Petersonce798522012-01-22 11:24:29 -05005966 func = lookup_method(self, &PyId___getitem__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005967 if (func == NULL) {
5968 PyErr_Format(PyExc_TypeError,
5969 "'%.200s' object is not iterable",
5970 Py_TYPE(self)->tp_name);
5971 return NULL;
5972 }
5973 Py_DECREF(func);
5974 return PySeqIter_New(self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005975}
Tim Peters6d6c1a32001-08-02 04:15:00 +00005976
5977static PyObject *
5978slot_tp_iternext(PyObject *self)
5979{
Benjamin Petersonce798522012-01-22 11:24:29 -05005980 _Py_IDENTIFIER(__next__);
5981 return call_method(self, &PyId___next__, "()");
Tim Peters6d6c1a32001-08-02 04:15:00 +00005982}
5983
Guido van Rossum1a493502001-08-17 16:47:50 +00005984static PyObject *
5985slot_tp_descr_get(PyObject *self, PyObject *obj, PyObject *type)
5986{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005987 PyTypeObject *tp = Py_TYPE(self);
5988 PyObject *get;
Victor Stinner3c1e4812012-03-26 22:10:51 +02005989 _Py_IDENTIFIER(__get__);
Guido van Rossum1a493502001-08-17 16:47:50 +00005990
Victor Stinner3c1e4812012-03-26 22:10:51 +02005991 get = _PyType_LookupId(tp, &PyId___get__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005992 if (get == NULL) {
5993 /* Avoid further slowdowns */
5994 if (tp->tp_descr_get == slot_tp_descr_get)
5995 tp->tp_descr_get = NULL;
5996 Py_INCREF(self);
5997 return self;
5998 }
5999 if (obj == NULL)
6000 obj = Py_None;
6001 if (type == NULL)
6002 type = Py_None;
6003 return PyObject_CallFunctionObjArgs(get, self, obj, type, NULL);
Guido van Rossum1a493502001-08-17 16:47:50 +00006004}
Tim Peters6d6c1a32001-08-02 04:15:00 +00006005
6006static int
6007slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value)
6008{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006009 PyObject *res;
Benjamin Petersonce798522012-01-22 11:24:29 -05006010 _Py_IDENTIFIER(__delete__);
6011 _Py_IDENTIFIER(__set__);
Guido van Rossum2c252392001-08-24 10:13:31 +00006012
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006013 if (value == NULL)
Benjamin Petersonce798522012-01-22 11:24:29 -05006014 res = call_method(self, &PyId___delete__, "(O)", target);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006015 else
Benjamin Petersonce798522012-01-22 11:24:29 -05006016 res = call_method(self, &PyId___set__, "(OO)", target, value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006017 if (res == NULL)
6018 return -1;
6019 Py_DECREF(res);
6020 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00006021}
6022
6023static int
6024slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds)
6025{
Benjamin Petersonce798522012-01-22 11:24:29 -05006026 _Py_IDENTIFIER(__init__);
6027 PyObject *meth = lookup_method(self, &PyId___init__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006028 PyObject *res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00006029
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006030 if (meth == NULL)
6031 return -1;
6032 res = PyObject_Call(meth, args, kwds);
6033 Py_DECREF(meth);
6034 if (res == NULL)
6035 return -1;
6036 if (res != Py_None) {
6037 PyErr_Format(PyExc_TypeError,
6038 "__init__() should return None, not '%.200s'",
6039 Py_TYPE(res)->tp_name);
6040 Py_DECREF(res);
6041 return -1;
6042 }
6043 Py_DECREF(res);
6044 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00006045}
6046
6047static PyObject *
6048slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
6049{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006050 PyObject *func;
6051 PyObject *newargs, *x;
6052 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +00006053
Victor Stinner3c1e4812012-03-26 22:10:51 +02006054 func = _PyObject_GetAttrId((PyObject *)type, &PyId___new__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006055 if (func == NULL)
6056 return NULL;
6057 assert(PyTuple_Check(args));
6058 n = PyTuple_GET_SIZE(args);
6059 newargs = PyTuple_New(n+1);
6060 if (newargs == NULL)
6061 return NULL;
6062 Py_INCREF(type);
6063 PyTuple_SET_ITEM(newargs, 0, (PyObject *)type);
6064 for (i = 0; i < n; i++) {
6065 x = PyTuple_GET_ITEM(args, i);
6066 Py_INCREF(x);
6067 PyTuple_SET_ITEM(newargs, i+1, x);
6068 }
6069 x = PyObject_Call(func, newargs, kwds);
6070 Py_DECREF(newargs);
6071 Py_DECREF(func);
6072 return x;
Tim Peters6d6c1a32001-08-02 04:15:00 +00006073}
6074
Guido van Rossumfebd61d2002-08-08 20:55:20 +00006075static void
Antoine Pitrou796564c2013-07-30 19:59:21 +02006076slot_tp_finalize(PyObject *self)
Guido van Rossumfebd61d2002-08-08 20:55:20 +00006077{
Benjamin Petersonce798522012-01-22 11:24:29 -05006078 _Py_IDENTIFIER(__del__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006079 PyObject *del, *res;
6080 PyObject *error_type, *error_value, *error_traceback;
Guido van Rossumfebd61d2002-08-08 20:55:20 +00006081
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006082 /* Save the current exception, if any. */
6083 PyErr_Fetch(&error_type, &error_value, &error_traceback);
Guido van Rossumfebd61d2002-08-08 20:55:20 +00006084
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006085 /* Execute __del__ method, if any. */
Benjamin Petersonce798522012-01-22 11:24:29 -05006086 del = lookup_maybe(self, &PyId___del__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006087 if (del != NULL) {
6088 res = PyEval_CallObject(del, NULL);
6089 if (res == NULL)
6090 PyErr_WriteUnraisable(del);
6091 else
6092 Py_DECREF(res);
6093 Py_DECREF(del);
6094 }
Guido van Rossumfebd61d2002-08-08 20:55:20 +00006095
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006096 /* Restore the saved exception. */
6097 PyErr_Restore(error_type, error_value, error_traceback);
Guido van Rossumfebd61d2002-08-08 20:55:20 +00006098}
6099
Guido van Rossum7b9144b2001-10-09 19:39:46 +00006100
Benjamin Peterson63952412013-04-01 17:41:41 -04006101/*
6102Table mapping __foo__ names to tp_foo offsets and slot_tp_foo wrapper functions.
6103
6104The table is ordered by offsets relative to the 'PyHeapTypeObject' structure,
6105which incorporates the additional structures used for numbers, sequences and
6106mappings. Note that multiple names may map to the same slot (e.g. __eq__,
6107__ne__ etc. all map to tp_richcompare) and one name may map to multiple slots
6108(e.g. __str__ affects tp_str as well as tp_repr). The table is terminated with
6109an all-zero entry. (This table is further initialized in init_slotdefs().)
6110*/
Guido van Rossum7b9144b2001-10-09 19:39:46 +00006111
Guido van Rossum6d204072001-10-21 00:44:31 +00006112typedef struct wrapperbase slotdef;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00006113
6114#undef TPSLOT
Guido van Rossumc8e56452001-10-22 00:43:43 +00006115#undef FLSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00006116#undef ETSLOT
6117#undef SQSLOT
6118#undef MPSLOT
6119#undef NBSLOT
Guido van Rossum6d204072001-10-21 00:44:31 +00006120#undef UNSLOT
6121#undef IBSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00006122#undef BINSLOT
6123#undef RBINSLOT
6124
Guido van Rossum6d204072001-10-21 00:44:31 +00006125#define TPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006126 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
6127 PyDoc_STR(DOC)}
Guido van Rossumc8e56452001-10-22 00:43:43 +00006128#define FLSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC, FLAGS) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006129 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
6130 PyDoc_STR(DOC), FLAGS}
Guido van Rossum6d204072001-10-21 00:44:31 +00006131#define ETSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006132 {NAME, offsetof(PyHeapTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
6133 PyDoc_STR(DOC)}
Guido van Rossum6d204072001-10-21 00:44:31 +00006134#define SQSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006135 ETSLOT(NAME, as_sequence.SLOT, FUNCTION, WRAPPER, DOC)
Guido van Rossum6d204072001-10-21 00:44:31 +00006136#define MPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006137 ETSLOT(NAME, as_mapping.SLOT, FUNCTION, WRAPPER, DOC)
Guido van Rossum6d204072001-10-21 00:44:31 +00006138#define NBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006139 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, DOC)
Guido van Rossum6d204072001-10-21 00:44:31 +00006140#define UNSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006141 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
Larry Hastings69a25472014-02-09 22:22:38 -08006142 NAME "($self, /)\n--\n\n" DOC)
Guido van Rossum6d204072001-10-21 00:44:31 +00006143#define IBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006144 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
Larry Hastings69a25472014-02-09 22:22:38 -08006145 NAME "($self, value, /)\n--\n\nReturn self" DOC "value.")
Guido van Rossum6d204072001-10-21 00:44:31 +00006146#define BINSLOT(NAME, SLOT, FUNCTION, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006147 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
Larry Hastings69a25472014-02-09 22:22:38 -08006148 NAME "($self, value, /)\n--\n\nReturn self" DOC "value.")
Guido van Rossum6d204072001-10-21 00:44:31 +00006149#define RBINSLOT(NAME, SLOT, FUNCTION, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006150 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
Larry Hastings69a25472014-02-09 22:22:38 -08006151 NAME "($self, value, /)\n--\n\nReturn value" DOC "self.")
Anthony Baxter56616992005-06-03 14:12:21 +00006152#define BINSLOTNOTINFIX(NAME, SLOT, FUNCTION, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006153 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
Larry Hastings69a25472014-02-09 22:22:38 -08006154 NAME "($self, value, /)\n--\n\n" DOC)
Anthony Baxter56616992005-06-03 14:12:21 +00006155#define RBINSLOTNOTINFIX(NAME, SLOT, FUNCTION, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006156 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
Larry Hastings69a25472014-02-09 22:22:38 -08006157 NAME "($self, value, /)\n--\n\n" DOC)
Guido van Rossum7b9144b2001-10-09 19:39:46 +00006158
6159static slotdef slotdefs[] = {
Benjamin Peterson63952412013-04-01 17:41:41 -04006160 TPSLOT("__getattribute__", tp_getattr, NULL, NULL, ""),
6161 TPSLOT("__getattr__", tp_getattr, NULL, NULL, ""),
6162 TPSLOT("__setattr__", tp_setattr, NULL, NULL, ""),
6163 TPSLOT("__delattr__", tp_setattr, NULL, NULL, ""),
6164 TPSLOT("__repr__", tp_repr, slot_tp_repr, wrap_unaryfunc,
Larry Hastings69a25472014-02-09 22:22:38 -08006165 "__repr__($self, /)\n--\n\nReturn repr(self)."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006166 TPSLOT("__hash__", tp_hash, slot_tp_hash, wrap_hashfunc,
Larry Hastings69a25472014-02-09 22:22:38 -08006167 "__hash__($self, /)\n--\n\nReturn hash(self)."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006168 FLSLOT("__call__", tp_call, slot_tp_call, (wrapperfunc)wrap_call,
Larry Hastings69a25472014-02-09 22:22:38 -08006169 "__call__($self, /, *args, **kwargs)\n--\n\nCall self as a function.",
Larry Hastings5c661892014-01-24 06:17:25 -08006170 PyWrapperFlag_KEYWORDS),
Benjamin Peterson63952412013-04-01 17:41:41 -04006171 TPSLOT("__str__", tp_str, slot_tp_str, wrap_unaryfunc,
Larry Hastings69a25472014-02-09 22:22:38 -08006172 "__str__($self, /)\n--\n\nReturn str(self)."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006173 TPSLOT("__getattribute__", tp_getattro, slot_tp_getattr_hook,
Larry Hastings5c661892014-01-24 06:17:25 -08006174 wrap_binaryfunc,
Larry Hastings69a25472014-02-09 22:22:38 -08006175 "__getattribute__($self, name, /)\n--\n\nReturn getattr(self, name)."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006176 TPSLOT("__getattr__", tp_getattro, slot_tp_getattr_hook, NULL, ""),
6177 TPSLOT("__setattr__", tp_setattro, slot_tp_setattro, wrap_setattr,
Larry Hastings69a25472014-02-09 22:22:38 -08006178 "__setattr__($self, name, value, /)\n--\n\nImplement setattr(self, name, value)."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006179 TPSLOT("__delattr__", tp_setattro, slot_tp_setattro, wrap_delattr,
Larry Hastings69a25472014-02-09 22:22:38 -08006180 "__delattr__($self, name, /)\n--\n\nImplement delattr(self, name)."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006181 TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare, richcmp_lt,
Larry Hastings69a25472014-02-09 22:22:38 -08006182 "__lt__($self, value, /)\n--\n\nReturn self<value."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006183 TPSLOT("__le__", tp_richcompare, slot_tp_richcompare, richcmp_le,
Larry Hastings69a25472014-02-09 22:22:38 -08006184 "__le__($self, value, /)\n--\n\nReturn self<=value."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006185 TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare, richcmp_eq,
Larry Hastings69a25472014-02-09 22:22:38 -08006186 "__eq__($self, value, /)\n--\n\nReturn self==value."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006187 TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare, richcmp_ne,
Larry Hastings69a25472014-02-09 22:22:38 -08006188 "__ne__($self, value, /)\n--\n\nReturn self!=value."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006189 TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare, richcmp_gt,
Larry Hastings69a25472014-02-09 22:22:38 -08006190 "__gt__($self, value, /)\n--\n\nReturn self>value."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006191 TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare, richcmp_ge,
Zachary Wareea42b4c2014-04-18 09:14:31 -05006192 "__ge__($self, value, /)\n--\n\nReturn self>=value."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006193 TPSLOT("__iter__", tp_iter, slot_tp_iter, wrap_unaryfunc,
Larry Hastings69a25472014-02-09 22:22:38 -08006194 "__iter__($self, /)\n--\n\nImplement iter(self)."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006195 TPSLOT("__next__", tp_iternext, slot_tp_iternext, wrap_next,
Larry Hastings69a25472014-02-09 22:22:38 -08006196 "__next__($self, /)\n--\n\nImplement next(self)."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006197 TPSLOT("__get__", tp_descr_get, slot_tp_descr_get, wrap_descr_get,
Larry Hastings69a25472014-02-09 22:22:38 -08006198 "__get__($self, instance, owner, /)\n--\n\nReturn an attribute of instance, which is of type owner."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006199 TPSLOT("__set__", tp_descr_set, slot_tp_descr_set, wrap_descr_set,
Larry Hastings69a25472014-02-09 22:22:38 -08006200 "__set__($self, instance, value, /)\n--\n\nSet an attribute of instance to value."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006201 TPSLOT("__delete__", tp_descr_set, slot_tp_descr_set,
Larry Hastings5c661892014-01-24 06:17:25 -08006202 wrap_descr_delete,
Yury Selivanov056e2652014-03-02 12:25:27 -05006203 "__delete__($self, instance, /)\n--\n\nDelete an attribute of instance."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006204 FLSLOT("__init__", tp_init, slot_tp_init, (wrapperfunc)wrap_init,
Larry Hastings69a25472014-02-09 22:22:38 -08006205 "__init__($self, /, *args, **kwargs)\n--\n\n"
Larry Hastings581ee362014-01-28 05:00:08 -08006206 "Initialize self. See help(type(self)) for accurate signature.",
Benjamin Peterson63952412013-04-01 17:41:41 -04006207 PyWrapperFlag_KEYWORDS),
Larry Hastings5c661892014-01-24 06:17:25 -08006208 TPSLOT("__new__", tp_new, slot_tp_new, NULL,
Larry Hastings69a25472014-02-09 22:22:38 -08006209 "__new__(type, /, *args, **kwargs)\n--\n\n"
Larry Hastings581ee362014-01-28 05:00:08 -08006210 "Create and return new object. See help(type) for accurate signature."),
Antoine Pitrou796564c2013-07-30 19:59:21 +02006211 TPSLOT("__del__", tp_finalize, slot_tp_finalize, (wrapperfunc)wrap_del, ""),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00006212
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006213 BINSLOT("__add__", nb_add, slot_nb_add,
Larry Hastings5c661892014-01-24 06:17:25 -08006214 "+"),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006215 RBINSLOT("__radd__", nb_add, slot_nb_add,
Larry Hastings5c661892014-01-24 06:17:25 -08006216 "+"),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006217 BINSLOT("__sub__", nb_subtract, slot_nb_subtract,
Larry Hastings5c661892014-01-24 06:17:25 -08006218 "-"),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006219 RBINSLOT("__rsub__", nb_subtract, slot_nb_subtract,
Larry Hastings5c661892014-01-24 06:17:25 -08006220 "-"),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006221 BINSLOT("__mul__", nb_multiply, slot_nb_multiply,
Larry Hastings5c661892014-01-24 06:17:25 -08006222 "*"),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006223 RBINSLOT("__rmul__", nb_multiply, slot_nb_multiply,
Larry Hastings5c661892014-01-24 06:17:25 -08006224 "*"),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006225 BINSLOT("__mod__", nb_remainder, slot_nb_remainder,
Larry Hastings5c661892014-01-24 06:17:25 -08006226 "%"),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006227 RBINSLOT("__rmod__", nb_remainder, slot_nb_remainder,
Larry Hastings5c661892014-01-24 06:17:25 -08006228 "%"),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006229 BINSLOTNOTINFIX("__divmod__", nb_divmod, slot_nb_divmod,
Larry Hastings581ee362014-01-28 05:00:08 -08006230 "Return divmod(self, value)."),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006231 RBINSLOTNOTINFIX("__rdivmod__", nb_divmod, slot_nb_divmod,
Larry Hastings581ee362014-01-28 05:00:08 -08006232 "Return divmod(value, self)."),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006233 NBSLOT("__pow__", nb_power, slot_nb_power, wrap_ternaryfunc,
Larry Hastings69a25472014-02-09 22:22:38 -08006234 "__pow__($self, value, mod=None, /)\n--\n\nReturn pow(self, value, mod)."),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006235 NBSLOT("__rpow__", nb_power, slot_nb_power, wrap_ternaryfunc_r,
Larry Hastings69a25472014-02-09 22:22:38 -08006236 "__rpow__($self, value, mod=None, /)\n--\n\nReturn pow(value, self, mod)."),
Larry Hastings5c661892014-01-24 06:17:25 -08006237 UNSLOT("__neg__", nb_negative, slot_nb_negative, wrap_unaryfunc, "-self"),
6238 UNSLOT("__pos__", nb_positive, slot_nb_positive, wrap_unaryfunc, "+self"),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006239 UNSLOT("__abs__", nb_absolute, slot_nb_absolute, wrap_unaryfunc,
Larry Hastings5c661892014-01-24 06:17:25 -08006240 "abs(self)"),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006241 UNSLOT("__bool__", nb_bool, slot_nb_bool, wrap_inquirypred,
Larry Hastings5c661892014-01-24 06:17:25 -08006242 "self != 0"),
6243 UNSLOT("__invert__", nb_invert, slot_nb_invert, wrap_unaryfunc, "~self"),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006244 BINSLOT("__lshift__", nb_lshift, slot_nb_lshift, "<<"),
6245 RBINSLOT("__rlshift__", nb_lshift, slot_nb_lshift, "<<"),
6246 BINSLOT("__rshift__", nb_rshift, slot_nb_rshift, ">>"),
6247 RBINSLOT("__rrshift__", nb_rshift, slot_nb_rshift, ">>"),
6248 BINSLOT("__and__", nb_and, slot_nb_and, "&"),
6249 RBINSLOT("__rand__", nb_and, slot_nb_and, "&"),
6250 BINSLOT("__xor__", nb_xor, slot_nb_xor, "^"),
6251 RBINSLOT("__rxor__", nb_xor, slot_nb_xor, "^"),
6252 BINSLOT("__or__", nb_or, slot_nb_or, "|"),
6253 RBINSLOT("__ror__", nb_or, slot_nb_or, "|"),
6254 UNSLOT("__int__", nb_int, slot_nb_int, wrap_unaryfunc,
Larry Hastings5c661892014-01-24 06:17:25 -08006255 "int(self)"),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006256 UNSLOT("__float__", nb_float, slot_nb_float, wrap_unaryfunc,
Larry Hastings5c661892014-01-24 06:17:25 -08006257 "float(self)"),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006258 IBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add,
Eli Benderskyd3baae72011-11-11 16:57:05 +02006259 wrap_binaryfunc, "+="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006260 IBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract,
Eli Benderskyd3baae72011-11-11 16:57:05 +02006261 wrap_binaryfunc, "-="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006262 IBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply,
Eli Benderskyd3baae72011-11-11 16:57:05 +02006263 wrap_binaryfunc, "*="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006264 IBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder,
Eli Benderskyd3baae72011-11-11 16:57:05 +02006265 wrap_binaryfunc, "%="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006266 IBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power,
Eli Benderskyd3baae72011-11-11 16:57:05 +02006267 wrap_binaryfunc, "**="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006268 IBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift,
Eli Benderskyd3baae72011-11-11 16:57:05 +02006269 wrap_binaryfunc, "<<="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006270 IBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift,
Eli Benderskyd3baae72011-11-11 16:57:05 +02006271 wrap_binaryfunc, ">>="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006272 IBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and,
Eli Benderskyd3baae72011-11-11 16:57:05 +02006273 wrap_binaryfunc, "&="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006274 IBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor,
Eli Benderskyd3baae72011-11-11 16:57:05 +02006275 wrap_binaryfunc, "^="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006276 IBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or,
Eli Benderskyd3baae72011-11-11 16:57:05 +02006277 wrap_binaryfunc, "|="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006278 BINSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
6279 RBINSLOT("__rfloordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
6280 BINSLOT("__truediv__", nb_true_divide, slot_nb_true_divide, "/"),
6281 RBINSLOT("__rtruediv__", nb_true_divide, slot_nb_true_divide, "/"),
6282 IBSLOT("__ifloordiv__", nb_inplace_floor_divide,
6283 slot_nb_inplace_floor_divide, wrap_binaryfunc, "//"),
6284 IBSLOT("__itruediv__", nb_inplace_true_divide,
6285 slot_nb_inplace_true_divide, wrap_binaryfunc, "/"),
Benjamin Peterson63952412013-04-01 17:41:41 -04006286 NBSLOT("__index__", nb_index, slot_nb_index, wrap_unaryfunc,
Larry Hastings69a25472014-02-09 22:22:38 -08006287 "__index__($self, /)\n--\n\n"
Zachary Ware715ef022014-04-18 09:23:14 -05006288 "Return self converted to an integer, if self is suitable "
Larry Hastings5c661892014-01-24 06:17:25 -08006289 "for use as an index into a list."),
Benjamin Petersond51374e2014-04-09 23:55:56 -04006290 BINSLOT("__matmul__", nb_matrix_multiply, slot_nb_matrix_multiply,
6291 "@"),
6292 RBINSLOT("__rmatmul__", nb_matrix_multiply, slot_nb_matrix_multiply,
6293 "@"),
6294 IBSLOT("__imatmul__", nb_inplace_matrix_multiply, slot_nb_inplace_matrix_multiply,
6295 wrap_binaryfunc, "@="),
Benjamin Peterson63952412013-04-01 17:41:41 -04006296 MPSLOT("__len__", mp_length, slot_mp_length, wrap_lenfunc,
Larry Hastings69a25472014-02-09 22:22:38 -08006297 "__len__($self, /)\n--\n\nReturn len(self)."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006298 MPSLOT("__getitem__", mp_subscript, slot_mp_subscript,
6299 wrap_binaryfunc,
Larry Hastings69a25472014-02-09 22:22:38 -08006300 "__getitem__($self, key, /)\n--\n\nReturn self[key]."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006301 MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript,
6302 wrap_objobjargproc,
Larry Hastings69a25472014-02-09 22:22:38 -08006303 "__setitem__($self, key, value, /)\n--\n\nSet self[key] to value."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006304 MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript,
6305 wrap_delitem,
Yury Selivanov056e2652014-03-02 12:25:27 -05006306 "__delitem__($self, key, /)\n--\n\nDelete self[key]."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006307
6308 SQSLOT("__len__", sq_length, slot_sq_length, wrap_lenfunc,
Larry Hastings69a25472014-02-09 22:22:38 -08006309 "__len__($self, /)\n--\n\nReturn len(self)."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006310 /* Heap types defining __add__/__mul__ have sq_concat/sq_repeat == NULL.
6311 The logic in abstract.c always falls back to nb_add/nb_multiply in
6312 this case. Defining both the nb_* and the sq_* slots to call the
6313 user-defined methods has unexpected side-effects, as shown by
6314 test_descr.notimplemented() */
6315 SQSLOT("__add__", sq_concat, NULL, wrap_binaryfunc,
Larry Hastings69a25472014-02-09 22:22:38 -08006316 "__add__($self, value, /)\n--\n\nReturn self+value."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006317 SQSLOT("__mul__", sq_repeat, NULL, wrap_indexargfunc,
Larry Hastings69a25472014-02-09 22:22:38 -08006318 "__mul__($self, value, /)\n--\n\nReturn self*value.n"),
Benjamin Peterson63952412013-04-01 17:41:41 -04006319 SQSLOT("__rmul__", sq_repeat, NULL, wrap_indexargfunc,
Larry Hastings69a25472014-02-09 22:22:38 -08006320 "__rmul__($self, value, /)\n--\n\nReturn self*value."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006321 SQSLOT("__getitem__", sq_item, slot_sq_item, wrap_sq_item,
Larry Hastings69a25472014-02-09 22:22:38 -08006322 "__getitem__($self, key, /)\n--\n\nReturn self[key]."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006323 SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_setitem,
Larry Hastings69a25472014-02-09 22:22:38 -08006324 "__setitem__($self, key, value, /)\n--\n\nSet self[key] to value."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006325 SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_delitem,
Larry Hastings69a25472014-02-09 22:22:38 -08006326 "__delitem__($self, key, /)\n--\n\nDelete self[key]."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006327 SQSLOT("__contains__", sq_contains, slot_sq_contains, wrap_objobjproc,
Larry Hastings69a25472014-02-09 22:22:38 -08006328 "__contains__($self, key, /)\n--\n\nReturn key in self."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006329 SQSLOT("__iadd__", sq_inplace_concat, NULL,
Larry Hastings5c661892014-01-24 06:17:25 -08006330 wrap_binaryfunc,
Larry Hastings69a25472014-02-09 22:22:38 -08006331 "__iadd__($self, value, /)\n--\n\nImplement self+=value."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006332 SQSLOT("__imul__", sq_inplace_repeat, NULL,
Larry Hastings5c661892014-01-24 06:17:25 -08006333 wrap_indexargfunc,
Larry Hastings69a25472014-02-09 22:22:38 -08006334 "__imul__($self, value, /)\n--\n\nImplement self*=value."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006335
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006336 {NULL}
Guido van Rossum7b9144b2001-10-09 19:39:46 +00006337};
6338
Guido van Rossumc334df52002-04-04 23:44:47 +00006339/* Given a type pointer and an offset gotten from a slotdef entry, return a
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006340 pointer to the actual slot. This is not quite the same as simply adding
Guido van Rossumc334df52002-04-04 23:44:47 +00006341 the offset to the type pointer, since it takes care to indirect through the
6342 proper indirection pointer (as_buffer, etc.); it returns NULL if the
6343 indirection pointer is NULL. */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00006344static void **
Martin v. Löwis18e16552006-02-15 17:27:45 +00006345slotptr(PyTypeObject *type, int ioffset)
Guido van Rossum7b9144b2001-10-09 19:39:46 +00006346{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006347 char *ptr;
6348 long offset = ioffset;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00006349
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006350 /* Note: this depends on the order of the members of PyHeapTypeObject! */
6351 assert(offset >= 0);
6352 assert((size_t)offset < offsetof(PyHeapTypeObject, as_buffer));
6353 if ((size_t)offset >= offsetof(PyHeapTypeObject, as_sequence)) {
6354 ptr = (char *)type->tp_as_sequence;
6355 offset -= offsetof(PyHeapTypeObject, as_sequence);
6356 }
6357 else if ((size_t)offset >= offsetof(PyHeapTypeObject, as_mapping)) {
6358 ptr = (char *)type->tp_as_mapping;
6359 offset -= offsetof(PyHeapTypeObject, as_mapping);
6360 }
6361 else if ((size_t)offset >= offsetof(PyHeapTypeObject, as_number)) {
6362 ptr = (char *)type->tp_as_number;
6363 offset -= offsetof(PyHeapTypeObject, as_number);
6364 }
6365 else {
6366 ptr = (char *)type;
6367 }
6368 if (ptr != NULL)
6369 ptr += offset;
6370 return (void **)ptr;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00006371}
Guido van Rossumf040ede2001-08-07 16:40:56 +00006372
Guido van Rossumc334df52002-04-04 23:44:47 +00006373/* Length of array of slotdef pointers used to store slots with the
6374 same __name__. There should be at most MAX_EQUIV-1 slotdef entries with
6375 the same __name__, for any __name__. Since that's a static property, it is
6376 appropriate to declare fixed-size arrays for this. */
6377#define MAX_EQUIV 10
6378
6379/* Return a slot pointer for a given name, but ONLY if the attribute has
6380 exactly one slot function. The name must be an interned string. */
6381static void **
6382resolve_slotdups(PyTypeObject *type, PyObject *name)
6383{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006384 /* XXX Maybe this could be optimized more -- but is it worth it? */
Guido van Rossumc334df52002-04-04 23:44:47 +00006385
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006386 /* pname and ptrs act as a little cache */
6387 static PyObject *pname;
6388 static slotdef *ptrs[MAX_EQUIV];
6389 slotdef *p, **pp;
6390 void **res, **ptr;
Guido van Rossumc334df52002-04-04 23:44:47 +00006391
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006392 if (pname != name) {
6393 /* Collect all slotdefs that match name into ptrs. */
6394 pname = name;
6395 pp = ptrs;
6396 for (p = slotdefs; p->name_strobj; p++) {
6397 if (p->name_strobj == name)
6398 *pp++ = p;
6399 }
6400 *pp = NULL;
6401 }
Guido van Rossumc334df52002-04-04 23:44:47 +00006402
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006403 /* Look in all matching slots of the type; if exactly one of these has
6404 a filled-in slot, return its value. Otherwise return NULL. */
6405 res = NULL;
6406 for (pp = ptrs; *pp; pp++) {
6407 ptr = slotptr(type, (*pp)->offset);
6408 if (ptr == NULL || *ptr == NULL)
6409 continue;
6410 if (res != NULL)
6411 return NULL;
6412 res = ptr;
6413 }
6414 return res;
Guido van Rossumc334df52002-04-04 23:44:47 +00006415}
6416
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006417/* Common code for update_slots_callback() and fixup_slot_dispatchers(). This
Guido van Rossumc334df52002-04-04 23:44:47 +00006418 does some incredibly complex thinking and then sticks something into the
6419 slot. (It sees if the adjacent slotdefs for the same slot have conflicting
6420 interests, and then stores a generic wrapper or a specific function into
6421 the slot.) Return a pointer to the next slotdef with a different offset,
6422 because that's convenient for fixup_slot_dispatchers(). */
6423static slotdef *
6424update_one_slot(PyTypeObject *type, slotdef *p)
6425{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006426 PyObject *descr;
6427 PyWrapperDescrObject *d;
6428 void *generic = NULL, *specific = NULL;
6429 int use_generic = 0;
6430 int offset = p->offset;
6431 void **ptr = slotptr(type, offset);
Guido van Rossumc334df52002-04-04 23:44:47 +00006432
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006433 if (ptr == NULL) {
6434 do {
6435 ++p;
6436 } while (p->offset == offset);
6437 return p;
6438 }
6439 do {
6440 descr = _PyType_Lookup(type, p->name_strobj);
6441 if (descr == NULL) {
6442 if (ptr == (void**)&type->tp_iternext) {
Trent Nelsonab02db22012-09-18 21:58:03 -04006443 specific = (void *)_PyObject_NextNotImplemented;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006444 }
6445 continue;
6446 }
Benjamin Peterson7b166872012-04-24 11:06:25 -04006447 if (Py_TYPE(descr) == &PyWrapperDescr_Type &&
6448 ((PyWrapperDescrObject *)descr)->d_base->name_strobj == p->name_strobj) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006449 void **tptr = resolve_slotdups(type, p->name_strobj);
6450 if (tptr == NULL || tptr == ptr)
6451 generic = p->function;
6452 d = (PyWrapperDescrObject *)descr;
6453 if (d->d_base->wrapper == p->wrapper &&
6454 PyType_IsSubtype(type, PyDescr_TYPE(d)))
6455 {
6456 if (specific == NULL ||
6457 specific == d->d_wrapped)
6458 specific = d->d_wrapped;
6459 else
6460 use_generic = 1;
6461 }
6462 }
6463 else if (Py_TYPE(descr) == &PyCFunction_Type &&
6464 PyCFunction_GET_FUNCTION(descr) ==
6465 (PyCFunction)tp_new_wrapper &&
6466 ptr == (void**)&type->tp_new)
6467 {
6468 /* The __new__ wrapper is not a wrapper descriptor,
6469 so must be special-cased differently.
6470 If we don't do this, creating an instance will
6471 always use slot_tp_new which will look up
6472 __new__ in the MRO which will call tp_new_wrapper
6473 which will look through the base classes looking
6474 for a static base and call its tp_new (usually
6475 PyType_GenericNew), after performing various
6476 sanity checks and constructing a new argument
6477 list. Cut all that nonsense short -- this speeds
6478 up instance creation tremendously. */
6479 specific = (void *)type->tp_new;
6480 /* XXX I'm not 100% sure that there isn't a hole
6481 in this reasoning that requires additional
6482 sanity checks. I'll buy the first person to
6483 point out a bug in this reasoning a beer. */
6484 }
6485 else if (descr == Py_None &&
6486 ptr == (void**)&type->tp_hash) {
6487 /* We specifically allow __hash__ to be set to None
6488 to prevent inheritance of the default
6489 implementation from object.__hash__ */
Trent Nelsonab02db22012-09-18 21:58:03 -04006490 specific = (void *)PyObject_HashNotImplemented;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006491 }
6492 else {
6493 use_generic = 1;
6494 generic = p->function;
6495 }
6496 } while ((++p)->offset == offset);
6497 if (specific && !use_generic)
6498 *ptr = specific;
6499 else
6500 *ptr = generic;
6501 return p;
Guido van Rossumc334df52002-04-04 23:44:47 +00006502}
6503
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006504/* In the type, update the slots whose slotdefs are gathered in the pp array.
6505 This is a callback for update_subclasses(). */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006506static int
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006507update_slots_callback(PyTypeObject *type, void *data)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006508{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006509 slotdef **pp = (slotdef **)data;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006510
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006511 for (; *pp; pp++)
6512 update_one_slot(type, *pp);
6513 return 0;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006514}
6515
Martin v. Löwis996b6712014-07-26 16:44:07 +02006516static int slotdefs_initialized = 0;
Guido van Rossumc334df52002-04-04 23:44:47 +00006517/* Initialize the slotdefs table by adding interned string objects for the
Martin v. Löwis5b561502014-07-26 15:25:04 +02006518 names. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006519static void
Guido van Rossumd396b9c2001-10-13 20:02:41 +00006520init_slotdefs(void)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006521{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006522 slotdef *p;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006523
Martin v. Löwis996b6712014-07-26 16:44:07 +02006524 if (slotdefs_initialized)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006525 return;
6526 for (p = slotdefs; p->name; p++) {
Benjamin Peterson63952412013-04-01 17:41:41 -04006527 /* Slots must be ordered by their offset in the PyHeapTypeObject. */
6528 assert(!p[1].name || p->offset <= p[1].offset);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006529 p->name_strobj = PyUnicode_InternFromString(p->name);
6530 if (!p->name_strobj)
6531 Py_FatalError("Out of memory interning slotdef names");
6532 }
Martin v. Löwis996b6712014-07-26 16:44:07 +02006533 slotdefs_initialized = 1;
6534}
6535
6536/* Undo init_slotdefs, releasing the interned strings. */
Victor Stinner331a7262014-07-27 16:11:30 +02006537static void clear_slotdefs(void)
Martin v. Löwis996b6712014-07-26 16:44:07 +02006538{
6539 slotdef *p;
6540 for (p = slotdefs; p->name; p++) {
6541 Py_CLEAR(p->name_strobj);
6542 }
6543 slotdefs_initialized = 0;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006544}
6545
Guido van Rossumc334df52002-04-04 23:44:47 +00006546/* Update the slots after assignment to a class (type) attribute. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006547static int
6548update_slot(PyTypeObject *type, PyObject *name)
6549{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006550 slotdef *ptrs[MAX_EQUIV];
6551 slotdef *p;
6552 slotdef **pp;
6553 int offset;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006554
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006555 /* Clear the VALID_VERSION flag of 'type' and all its
6556 subclasses. This could possibly be unified with the
6557 update_subclasses() recursion below, but carefully:
6558 they each have their own conditions on which to stop
6559 recursing into subclasses. */
6560 PyType_Modified(type);
Christian Heimesa62da1d2008-01-12 19:39:10 +00006561
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006562 init_slotdefs();
6563 pp = ptrs;
6564 for (p = slotdefs; p->name; p++) {
6565 /* XXX assume name is interned! */
6566 if (p->name_strobj == name)
6567 *pp++ = p;
6568 }
6569 *pp = NULL;
6570 for (pp = ptrs; *pp; pp++) {
6571 p = *pp;
6572 offset = p->offset;
6573 while (p > slotdefs && (p-1)->offset == offset)
6574 --p;
6575 *pp = p;
6576 }
6577 if (ptrs[0] == NULL)
6578 return 0; /* Not an attribute that affects any slots */
6579 return update_subclasses(type, name,
6580 update_slots_callback, (void *)ptrs);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006581}
6582
Guido van Rossumc334df52002-04-04 23:44:47 +00006583/* Store the proper functions in the slot dispatches at class (type)
6584 definition time, based upon which operations the class overrides in its
6585 dict. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00006586static void
Guido van Rossum7b9144b2001-10-09 19:39:46 +00006587fixup_slot_dispatchers(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00006588{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006589 slotdef *p;
Tim Peters6d6c1a32001-08-02 04:15:00 +00006590
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006591 init_slotdefs();
6592 for (p = slotdefs; p->name; )
6593 p = update_one_slot(type, p);
Tim Peters6d6c1a32001-08-02 04:15:00 +00006594}
Guido van Rossum705f0f52001-08-24 16:47:00 +00006595
Michael W. Hudson98bbc492002-11-26 14:47:27 +00006596static void
6597update_all_slots(PyTypeObject* type)
6598{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006599 slotdef *p;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00006600
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006601 init_slotdefs();
6602 for (p = slotdefs; p->name; p++) {
6603 /* update_slot returns int but can't actually fail */
6604 update_slot(type, p->name_strobj);
6605 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +00006606}
6607
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006608/* recurse_down_subclasses() and update_subclasses() are mutually
6609 recursive functions to call a callback for all subclasses,
6610 but refraining from recursing into subclasses that define 'name'. */
6611
6612static int
6613update_subclasses(PyTypeObject *type, PyObject *name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006614 update_callback callback, void *data)
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006615{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006616 if (callback(type, data) < 0)
6617 return -1;
6618 return recurse_down_subclasses(type, name, callback, data);
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006619}
6620
6621static int
6622recurse_down_subclasses(PyTypeObject *type, PyObject *name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006623 update_callback callback, void *data)
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006624{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006625 PyTypeObject *subclass;
6626 PyObject *ref, *subclasses, *dict;
Antoine Pitrou84745ab2013-10-29 21:31:25 +01006627 Py_ssize_t i;
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006628
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006629 subclasses = type->tp_subclasses;
6630 if (subclasses == NULL)
6631 return 0;
Antoine Pitrou84745ab2013-10-29 21:31:25 +01006632 assert(PyDict_CheckExact(subclasses));
6633 i = 0;
6634 while (PyDict_Next(subclasses, &i, NULL, &ref)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006635 assert(PyWeakref_CheckRef(ref));
6636 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
6637 assert(subclass != NULL);
6638 if ((PyObject *)subclass == Py_None)
6639 continue;
6640 assert(PyType_Check(subclass));
6641 /* Avoid recursing down into unaffected classes */
6642 dict = subclass->tp_dict;
6643 if (dict != NULL && PyDict_Check(dict) &&
6644 PyDict_GetItem(dict, name) != NULL)
6645 continue;
6646 if (update_subclasses(subclass, name, callback, data) < 0)
6647 return -1;
6648 }
6649 return 0;
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006650}
6651
Guido van Rossum6d204072001-10-21 00:44:31 +00006652/* This function is called by PyType_Ready() to populate the type's
6653 dictionary with method descriptors for function slots. For each
Guido van Rossum09638c12002-06-13 19:17:46 +00006654 function slot (like tp_repr) that's defined in the type, one or more
6655 corresponding descriptors are added in the type's tp_dict dictionary
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006656 under the appropriate name (like __repr__). Some function slots
Guido van Rossum09638c12002-06-13 19:17:46 +00006657 cause more than one descriptor to be added (for example, the nb_add
6658 slot adds both __add__ and __radd__ descriptors) and some function
6659 slots compete for the same descriptor (for example both sq_item and
6660 mp_subscript generate a __getitem__ descriptor).
6661
Ezio Melotti13925002011-03-16 11:05:33 +02006662 In the latter case, the first slotdef entry encountered wins. Since
Tim Petersbf9b2442003-03-23 05:35:36 +00006663 slotdef entries are sorted by the offset of the slot in the
Guido van Rossume5c691a2003-03-07 15:13:17 +00006664 PyHeapTypeObject, this gives us some control over disambiguating
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006665 between competing slots: the members of PyHeapTypeObject are listed
6666 from most general to least general, so the most general slot is
6667 preferred. In particular, because as_mapping comes before as_sequence,
6668 for a type that defines both mp_subscript and sq_item, mp_subscript
6669 wins.
Guido van Rossum09638c12002-06-13 19:17:46 +00006670
6671 This only adds new descriptors and doesn't overwrite entries in
6672 tp_dict that were previously defined. The descriptors contain a
6673 reference to the C function they must call, so that it's safe if they
6674 are copied into a subtype's __dict__ and the subtype has a different
6675 C function in its slot -- calling the method defined by the
6676 descriptor will call the C function that was used to create it,
6677 rather than the C function present in the slot when it is called.
6678 (This is important because a subtype may have a C function in the
6679 slot that calls the method from the dictionary, and we want to avoid
6680 infinite recursion here.) */
Guido van Rossum6d204072001-10-21 00:44:31 +00006681
6682static int
6683add_operators(PyTypeObject *type)
6684{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006685 PyObject *dict = type->tp_dict;
6686 slotdef *p;
6687 PyObject *descr;
6688 void **ptr;
Guido van Rossum6d204072001-10-21 00:44:31 +00006689
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006690 init_slotdefs();
6691 for (p = slotdefs; p->name; p++) {
6692 if (p->wrapper == NULL)
6693 continue;
6694 ptr = slotptr(type, p->offset);
6695 if (!ptr || !*ptr)
6696 continue;
6697 if (PyDict_GetItem(dict, p->name_strobj))
6698 continue;
Trent Nelsonab02db22012-09-18 21:58:03 -04006699 if (*ptr == (void *)PyObject_HashNotImplemented) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006700 /* Classes may prevent the inheritance of the tp_hash
6701 slot by storing PyObject_HashNotImplemented in it. Make it
6702 visible as a None value for the __hash__ attribute. */
6703 if (PyDict_SetItem(dict, p->name_strobj, Py_None) < 0)
6704 return -1;
6705 }
6706 else {
6707 descr = PyDescr_NewWrapper(type, p, *ptr);
6708 if (descr == NULL)
6709 return -1;
6710 if (PyDict_SetItem(dict, p->name_strobj, descr) < 0)
6711 return -1;
6712 Py_DECREF(descr);
6713 }
6714 }
6715 if (type->tp_new != NULL) {
6716 if (add_tp_new_wrapper(type) < 0)
6717 return -1;
6718 }
6719 return 0;
Guido van Rossum6d204072001-10-21 00:44:31 +00006720}
6721
Guido van Rossum705f0f52001-08-24 16:47:00 +00006722
6723/* Cooperative 'super' */
6724
6725typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006726 PyObject_HEAD
6727 PyTypeObject *type;
6728 PyObject *obj;
6729 PyTypeObject *obj_type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006730} superobject;
6731
Guido van Rossum6f799372001-09-20 20:46:19 +00006732static PyMemberDef super_members[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006733 {"__thisclass__", T_OBJECT, offsetof(superobject, type), READONLY,
6734 "the class invoking super()"},
6735 {"__self__", T_OBJECT, offsetof(superobject, obj), READONLY,
6736 "the instance invoking super(); may be None"},
6737 {"__self_class__", T_OBJECT, offsetof(superobject, obj_type), READONLY,
6738 "the type of the instance invoking super(); may be None"},
6739 {0}
Guido van Rossum41eb14d2001-08-30 23:13:11 +00006740};
6741
Guido van Rossum705f0f52001-08-24 16:47:00 +00006742static void
6743super_dealloc(PyObject *self)
6744{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006745 superobject *su = (superobject *)self;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006746
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006747 _PyObject_GC_UNTRACK(self);
6748 Py_XDECREF(su->obj);
6749 Py_XDECREF(su->type);
6750 Py_XDECREF(su->obj_type);
6751 Py_TYPE(self)->tp_free(self);
Guido van Rossum705f0f52001-08-24 16:47:00 +00006752}
6753
6754static PyObject *
Guido van Rossum41eb14d2001-08-30 23:13:11 +00006755super_repr(PyObject *self)
6756{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006757 superobject *su = (superobject *)self;
Guido van Rossum41eb14d2001-08-30 23:13:11 +00006758
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006759 if (su->obj_type)
6760 return PyUnicode_FromFormat(
6761 "<super: <class '%s'>, <%s object>>",
6762 su->type ? su->type->tp_name : "NULL",
6763 su->obj_type->tp_name);
6764 else
6765 return PyUnicode_FromFormat(
6766 "<super: <class '%s'>, NULL>",
6767 su->type ? su->type->tp_name : "NULL");
Guido van Rossum41eb14d2001-08-30 23:13:11 +00006768}
6769
6770static PyObject *
Guido van Rossum705f0f52001-08-24 16:47:00 +00006771super_getattro(PyObject *self, PyObject *name)
6772{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006773 superobject *su = (superobject *)self;
6774 int skip = su->obj_type == NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006775
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006776 if (!skip) {
6777 /* We want __class__ to return the class of the super object
6778 (i.e. super, or a subclass), not the class of su->obj. */
6779 skip = (PyUnicode_Check(name) &&
Victor Stinnerad14ccd2013-11-07 00:46:04 +01006780 PyUnicode_GET_LENGTH(name) == 9 &&
6781 _PyUnicode_CompareWithId(name, &PyId___class__) == 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006782 }
Guido van Rossum76ba09f2003-04-16 19:40:58 +00006783
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006784 if (!skip) {
6785 PyObject *mro, *res, *tmp, *dict;
6786 PyTypeObject *starttype;
6787 descrgetfunc f;
6788 Py_ssize_t i, n;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006789
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006790 starttype = su->obj_type;
6791 mro = starttype->tp_mro;
Guido van Rossum155db9a2002-04-02 17:53:47 +00006792
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006793 if (mro == NULL)
6794 n = 0;
6795 else {
6796 assert(PyTuple_Check(mro));
6797 n = PyTuple_GET_SIZE(mro);
6798 }
6799 for (i = 0; i < n; i++) {
6800 if ((PyObject *)(su->type) == PyTuple_GET_ITEM(mro, i))
6801 break;
6802 }
6803 i++;
6804 res = NULL;
Victor Stinnerd74782b2012-03-09 00:39:08 +01006805 /* keep a strong reference to mro because starttype->tp_mro can be
6806 replaced during PyDict_GetItem(dict, name) */
6807 Py_INCREF(mro);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006808 for (; i < n; i++) {
6809 tmp = PyTuple_GET_ITEM(mro, i);
6810 if (PyType_Check(tmp))
6811 dict = ((PyTypeObject *)tmp)->tp_dict;
6812 else
6813 continue;
6814 res = PyDict_GetItem(dict, name);
6815 if (res != NULL) {
6816 Py_INCREF(res);
6817 f = Py_TYPE(res)->tp_descr_get;
6818 if (f != NULL) {
6819 tmp = f(res,
6820 /* Only pass 'obj' param if
6821 this is instance-mode super
6822 (See SF ID #743627)
6823 */
6824 (su->obj == (PyObject *)
6825 su->obj_type
6826 ? (PyObject *)NULL
6827 : su->obj),
6828 (PyObject *)starttype);
6829 Py_DECREF(res);
6830 res = tmp;
6831 }
Victor Stinnerd74782b2012-03-09 00:39:08 +01006832 Py_DECREF(mro);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006833 return res;
6834 }
6835 }
Victor Stinnerd74782b2012-03-09 00:39:08 +01006836 Py_DECREF(mro);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006837 }
6838 return PyObject_GenericGetAttr(self, name);
Guido van Rossum705f0f52001-08-24 16:47:00 +00006839}
6840
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006841static PyTypeObject *
Guido van Rossum5b443c62001-12-03 15:38:28 +00006842supercheck(PyTypeObject *type, PyObject *obj)
6843{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006844 /* Check that a super() call makes sense. Return a type object.
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006845
Florent Xiclunaaa6c1d22011-12-12 18:54:29 +01006846 obj can be a class, or an instance of one:
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006847
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006848 - If it is a class, it must be a subclass of 'type'. This case is
6849 used for class methods; the return value is obj.
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006850
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006851 - If it is an instance, it must be an instance of 'type'. This is
6852 the normal case; the return value is obj.__class__.
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006853
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006854 But... when obj is an instance, we want to allow for the case where
6855 Py_TYPE(obj) is not a subclass of type, but obj.__class__ is!
6856 This will allow using super() with a proxy for obj.
6857 */
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006858
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006859 /* Check for first bullet above (special case) */
6860 if (PyType_Check(obj) && PyType_IsSubtype((PyTypeObject *)obj, type)) {
6861 Py_INCREF(obj);
6862 return (PyTypeObject *)obj;
6863 }
Guido van Rossum8e80a722003-02-18 19:22:22 +00006864
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006865 /* Normal case */
6866 if (PyType_IsSubtype(Py_TYPE(obj), type)) {
6867 Py_INCREF(Py_TYPE(obj));
6868 return Py_TYPE(obj);
6869 }
6870 else {
6871 /* Try the slow way */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006872 PyObject *class_attr;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006873
Martin v. Löwisbfc6d742011-10-13 20:03:57 +02006874 class_attr = _PyObject_GetAttrId(obj, &PyId___class__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006875 if (class_attr != NULL &&
6876 PyType_Check(class_attr) &&
6877 (PyTypeObject *)class_attr != Py_TYPE(obj))
6878 {
6879 int ok = PyType_IsSubtype(
6880 (PyTypeObject *)class_attr, type);
6881 if (ok)
6882 return (PyTypeObject *)class_attr;
6883 }
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006884
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006885 if (class_attr == NULL)
6886 PyErr_Clear();
6887 else
6888 Py_DECREF(class_attr);
6889 }
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006890
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006891 PyErr_SetString(PyExc_TypeError,
6892 "super(type, obj): "
6893 "obj must be an instance or subtype of type");
6894 return NULL;
Guido van Rossum5b443c62001-12-03 15:38:28 +00006895}
6896
Guido van Rossum705f0f52001-08-24 16:47:00 +00006897static PyObject *
6898super_descr_get(PyObject *self, PyObject *obj, PyObject *type)
6899{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006900 superobject *su = (superobject *)self;
6901 superobject *newobj;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006902
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006903 if (obj == NULL || obj == Py_None || su->obj != NULL) {
6904 /* Not binding to an object, or already bound */
6905 Py_INCREF(self);
6906 return self;
6907 }
6908 if (Py_TYPE(su) != &PySuper_Type)
6909 /* If su is an instance of a (strict) subclass of super,
6910 call its type */
6911 return PyObject_CallFunctionObjArgs((PyObject *)Py_TYPE(su),
6912 su->type, obj, NULL);
6913 else {
6914 /* Inline the common case */
6915 PyTypeObject *obj_type = supercheck(su->type, obj);
6916 if (obj_type == NULL)
6917 return NULL;
6918 newobj = (superobject *)PySuper_Type.tp_new(&PySuper_Type,
6919 NULL, NULL);
6920 if (newobj == NULL)
6921 return NULL;
6922 Py_INCREF(su->type);
6923 Py_INCREF(obj);
6924 newobj->type = su->type;
6925 newobj->obj = obj;
6926 newobj->obj_type = obj_type;
6927 return (PyObject *)newobj;
6928 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00006929}
6930
6931static int
6932super_init(PyObject *self, PyObject *args, PyObject *kwds)
6933{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006934 superobject *su = (superobject *)self;
6935 PyTypeObject *type = NULL;
6936 PyObject *obj = NULL;
6937 PyTypeObject *obj_type = NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006938
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006939 if (!_PyArg_NoKeywords("super", kwds))
6940 return -1;
6941 if (!PyArg_ParseTuple(args, "|O!O:super", &PyType_Type, &type, &obj))
6942 return -1;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00006943
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006944 if (type == NULL) {
6945 /* Call super(), without args -- fill in from __class__
6946 and first local variable on the stack. */
Victor Stinner1c6970f2014-05-13 01:32:36 +02006947 PyFrameObject *f;
6948 PyCodeObject *co;
Victor Stinner0fcab4a2011-01-04 12:59:15 +00006949 Py_ssize_t i, n;
Victor Stinner1c6970f2014-05-13 01:32:36 +02006950 f = PyThreadState_GET()->frame;
6951 if (f == NULL) {
6952 PyErr_SetString(PyExc_RuntimeError,
6953 "super(): no current frame");
6954 return -1;
6955 }
6956 co = f->f_code;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006957 if (co == NULL) {
Benjamin Peterson6a42bd62012-09-01 23:04:38 -04006958 PyErr_SetString(PyExc_RuntimeError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006959 "super(): no code object");
6960 return -1;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00006961 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006962 if (co->co_argcount == 0) {
Benjamin Peterson6a42bd62012-09-01 23:04:38 -04006963 PyErr_SetString(PyExc_RuntimeError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006964 "super(): no arguments");
6965 return -1;
6966 }
6967 obj = f->f_localsplus[0];
Benjamin Peterson159ae412013-05-12 18:16:06 -05006968 if (obj == NULL && co->co_cell2arg) {
6969 /* The first argument might be a cell. */
6970 n = PyTuple_GET_SIZE(co->co_cellvars);
6971 for (i = 0; i < n; i++) {
6972 if (co->co_cell2arg[i] == 0) {
6973 PyObject *cell = f->f_localsplus[co->co_nlocals + i];
6974 assert(PyCell_Check(cell));
6975 obj = PyCell_GET(cell);
6976 break;
6977 }
6978 }
Guido van Rossum6832c812013-05-10 08:47:42 -07006979 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006980 if (obj == NULL) {
Benjamin Peterson6a42bd62012-09-01 23:04:38 -04006981 PyErr_SetString(PyExc_RuntimeError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006982 "super(): arg[0] deleted");
6983 return -1;
6984 }
6985 if (co->co_freevars == NULL)
6986 n = 0;
6987 else {
6988 assert(PyTuple_Check(co->co_freevars));
6989 n = PyTuple_GET_SIZE(co->co_freevars);
6990 }
6991 for (i = 0; i < n; i++) {
6992 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
6993 assert(PyUnicode_Check(name));
Victor Stinnerad14ccd2013-11-07 00:46:04 +01006994 if (!_PyUnicode_CompareWithId(name, &PyId___class__)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006995 Py_ssize_t index = co->co_nlocals +
6996 PyTuple_GET_SIZE(co->co_cellvars) + i;
6997 PyObject *cell = f->f_localsplus[index];
6998 if (cell == NULL || !PyCell_Check(cell)) {
Benjamin Peterson6a42bd62012-09-01 23:04:38 -04006999 PyErr_SetString(PyExc_RuntimeError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007000 "super(): bad __class__ cell");
7001 return -1;
7002 }
7003 type = (PyTypeObject *) PyCell_GET(cell);
7004 if (type == NULL) {
Benjamin Peterson6a42bd62012-09-01 23:04:38 -04007005 PyErr_SetString(PyExc_RuntimeError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007006 "super(): empty __class__ cell");
7007 return -1;
7008 }
7009 if (!PyType_Check(type)) {
Benjamin Peterson6a42bd62012-09-01 23:04:38 -04007010 PyErr_Format(PyExc_RuntimeError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007011 "super(): __class__ is not a type (%s)",
7012 Py_TYPE(type)->tp_name);
7013 return -1;
7014 }
7015 break;
7016 }
7017 }
7018 if (type == NULL) {
Benjamin Peterson6a42bd62012-09-01 23:04:38 -04007019 PyErr_SetString(PyExc_RuntimeError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007020 "super(): __class__ cell not found");
7021 return -1;
7022 }
7023 }
Guido van Rossumcd16bf62007-06-13 18:07:49 +00007024
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007025 if (obj == Py_None)
7026 obj = NULL;
7027 if (obj != NULL) {
7028 obj_type = supercheck(type, obj);
7029 if (obj_type == NULL)
7030 return -1;
7031 Py_INCREF(obj);
7032 }
7033 Py_INCREF(type);
7034 su->type = type;
7035 su->obj = obj;
7036 su->obj_type = obj_type;
7037 return 0;
Guido van Rossum705f0f52001-08-24 16:47:00 +00007038}
7039
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007040PyDoc_STRVAR(super_doc,
Guido van Rossumcd16bf62007-06-13 18:07:49 +00007041"super() -> same as super(__class__, <first argument>)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00007042"super(type) -> unbound super object\n"
7043"super(type, obj) -> bound super object; requires isinstance(obj, type)\n"
Guido van Rossume705ef12001-08-29 15:47:06 +00007044"super(type, type2) -> bound super object; requires issubclass(type2, type)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00007045"Typical use to call a cooperative superclass method:\n"
7046"class C(B):\n"
7047" def meth(self, arg):\n"
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007048" super().meth(arg)\n"
Guido van Rossumcd16bf62007-06-13 18:07:49 +00007049"This works for class methods too:\n"
7050"class C(B):\n"
7051" @classmethod\n"
7052" def cmeth(cls, arg):\n"
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007053" super().cmeth(arg)\n");
Guido van Rossum705f0f52001-08-24 16:47:00 +00007054
Guido van Rossum048eb752001-10-02 21:24:57 +00007055static int
7056super_traverse(PyObject *self, visitproc visit, void *arg)
7057{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007058 superobject *su = (superobject *)self;
Guido van Rossum048eb752001-10-02 21:24:57 +00007059
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007060 Py_VISIT(su->obj);
7061 Py_VISIT(su->type);
7062 Py_VISIT(su->obj_type);
Guido van Rossum048eb752001-10-02 21:24:57 +00007063
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007064 return 0;
Guido van Rossum048eb752001-10-02 21:24:57 +00007065}
7066
Guido van Rossum705f0f52001-08-24 16:47:00 +00007067PyTypeObject PySuper_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007068 PyVarObject_HEAD_INIT(&PyType_Type, 0)
7069 "super", /* tp_name */
7070 sizeof(superobject), /* tp_basicsize */
7071 0, /* tp_itemsize */
7072 /* methods */
7073 super_dealloc, /* tp_dealloc */
7074 0, /* tp_print */
7075 0, /* tp_getattr */
7076 0, /* tp_setattr */
7077 0, /* tp_reserved */
7078 super_repr, /* tp_repr */
7079 0, /* tp_as_number */
7080 0, /* tp_as_sequence */
7081 0, /* tp_as_mapping */
7082 0, /* tp_hash */
7083 0, /* tp_call */
7084 0, /* tp_str */
7085 super_getattro, /* tp_getattro */
7086 0, /* tp_setattro */
7087 0, /* tp_as_buffer */
7088 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
7089 Py_TPFLAGS_BASETYPE, /* tp_flags */
7090 super_doc, /* tp_doc */
7091 super_traverse, /* tp_traverse */
7092 0, /* tp_clear */
7093 0, /* tp_richcompare */
7094 0, /* tp_weaklistoffset */
7095 0, /* tp_iter */
7096 0, /* tp_iternext */
7097 0, /* tp_methods */
7098 super_members, /* tp_members */
7099 0, /* tp_getset */
7100 0, /* tp_base */
7101 0, /* tp_dict */
7102 super_descr_get, /* tp_descr_get */
7103 0, /* tp_descr_set */
7104 0, /* tp_dictoffset */
7105 super_init, /* tp_init */
7106 PyType_GenericAlloc, /* tp_alloc */
7107 PyType_GenericNew, /* tp_new */
7108 PyObject_GC_Del, /* tp_free */
Guido van Rossum705f0f52001-08-24 16:47:00 +00007109};