blob: 3b1d1891954255f1f40ac6f27859778f4fd9ee2c [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
Larry Hastings5c661892014-01-24 06:17:25 -080057/*
Larry Hastings2623c8c2014-02-08 22:15:29 -080058 * finds the beginning of the docstring's introspection signature.
Larry Hastings5c661892014-01-24 06:17:25 -080059 * if present, returns a pointer pointing to the first '('.
60 * otherwise returns NULL.
Larry Hastings2623c8c2014-02-08 22:15:29 -080061 *
62 * doesn't guarantee that the signature is valid, only that it
63 * has a valid prefix. (the signature must also pass skip_signature.)
Larry Hastings5c661892014-01-24 06:17:25 -080064 */
65static const char *
Larry Hastings2623c8c2014-02-08 22:15:29 -080066find_signature(const char *name, const char *doc)
Larry Hastings5c661892014-01-24 06:17:25 -080067{
Larry Hastings2623c8c2014-02-08 22:15:29 -080068 const char *dot;
69 size_t length;
70
71 if (!doc)
72 return NULL;
73
74 assert(name != NULL);
75
76 /* for dotted names like classes, only use the last component */
77 dot = strrchr(name, '.');
78 if (dot)
79 name = dot + 1;
80
81 length = strlen(name);
82 if (strncmp(doc, name, length))
83 return NULL;
84 doc += length;
85 if (*doc != '(')
86 return NULL;
87 return doc;
Larry Hastings5c661892014-01-24 06:17:25 -080088}
89
Larry Hastings2623c8c2014-02-08 22:15:29 -080090#define SIGNATURE_END_MARKER ")\n--\n\n"
91#define SIGNATURE_END_MARKER_LENGTH 6
Larry Hastings5c661892014-01-24 06:17:25 -080092/*
Larry Hastings2623c8c2014-02-08 22:15:29 -080093 * skips past the end of the docstring's instrospection signature.
94 * (assumes doc starts with a valid signature prefix.)
Larry Hastings5c661892014-01-24 06:17:25 -080095 */
96static const char *
97skip_signature(const char *doc)
98{
Larry Hastings2623c8c2014-02-08 22:15:29 -080099 while (*doc) {
100 if ((*doc == *SIGNATURE_END_MARKER) &&
101 !strncmp(doc, SIGNATURE_END_MARKER, SIGNATURE_END_MARKER_LENGTH))
102 return doc + SIGNATURE_END_MARKER_LENGTH;
103 if ((*doc == '\n') && (doc[1] == '\n'))
104 return NULL;
Larry Hastings5c661892014-01-24 06:17:25 -0800105 doc++;
Larry Hastings2623c8c2014-02-08 22:15:29 -0800106 }
107 return NULL;
Larry Hastings5c661892014-01-24 06:17:25 -0800108}
109
110static const char *
Larry Hastings2623c8c2014-02-08 22:15:29 -0800111_PyType_DocWithoutSignature(const char *name, const char *internal_doc)
Larry Hastings5c661892014-01-24 06:17:25 -0800112{
Larry Hastings2623c8c2014-02-08 22:15:29 -0800113 const char *doc = find_signature(name, internal_doc);
Larry Hastings5c661892014-01-24 06:17:25 -0800114
Larry Hastings2623c8c2014-02-08 22:15:29 -0800115 if (doc) {
116 doc = skip_signature(doc);
117 if (doc)
118 return doc;
119 }
Larry Hastings5c661892014-01-24 06:17:25 -0800120 return internal_doc;
121}
122
123PyObject *
Larry Hastings2623c8c2014-02-08 22:15:29 -0800124_PyType_GetDocFromInternalDoc(const char *name, const char *internal_doc)
Larry Hastings5c661892014-01-24 06:17:25 -0800125{
Larry Hastings2623c8c2014-02-08 22:15:29 -0800126 const char *doc = _PyType_DocWithoutSignature(name, internal_doc);
Larry Hastings5c661892014-01-24 06:17:25 -0800127
128 if (!doc) {
129 Py_INCREF(Py_None);
130 return Py_None;
131 }
132
133 return PyUnicode_FromString(doc);
134}
135
136PyObject *
Larry Hastings2623c8c2014-02-08 22:15:29 -0800137_PyType_GetTextSignatureFromInternalDoc(const char *name, const char *internal_doc)
Larry Hastings5c661892014-01-24 06:17:25 -0800138{
Larry Hastings2623c8c2014-02-08 22:15:29 -0800139 const char *start = find_signature(name, internal_doc);
140 const char *end;
Larry Hastings5c661892014-01-24 06:17:25 -0800141
Larry Hastings2623c8c2014-02-08 22:15:29 -0800142 if (start)
143 end = skip_signature(start);
144 else
145 end = NULL;
146 if (!end) {
Larry Hastings5c661892014-01-24 06:17:25 -0800147 Py_INCREF(Py_None);
148 return Py_None;
149 }
150
Larry Hastings2623c8c2014-02-08 22:15:29 -0800151 /* back "end" up until it points just past the final ')' */
152 end -= SIGNATURE_END_MARKER_LENGTH - 1;
153 assert((end - start) >= 2); /* should be "()" at least */
154 assert(end[-1] == ')');
155 assert(end[0] == '\n');
156 return PyUnicode_FromStringAndSize(start, end - start);
Larry Hastings5c661892014-01-24 06:17:25 -0800157}
158
Christian Heimes26855632008-01-27 23:50:43 +0000159unsigned int
160PyType_ClearCache(void)
161{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000162 Py_ssize_t i;
163 unsigned int cur_version_tag = next_version_tag - 1;
164
165 for (i = 0; i < (1 << MCACHE_SIZE_EXP); i++) {
166 method_cache[i].version = 0;
167 Py_CLEAR(method_cache[i].name);
168 method_cache[i].value = NULL;
169 }
170 next_version_tag = 0;
171 /* mark all version tags as invalid */
172 PyType_Modified(&PyBaseObject_Type);
173 return cur_version_tag;
Christian Heimes26855632008-01-27 23:50:43 +0000174}
Christian Heimesa62da1d2008-01-12 19:39:10 +0000175
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000176void
Antoine Pitrou957a23b2013-05-04 20:45:02 +0200177_PyType_Fini(void)
178{
179 PyType_ClearCache();
Antoine Pitrou957a23b2013-05-04 20:45:02 +0200180}
181
182void
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000183PyType_Modified(PyTypeObject *type)
Christian Heimesa62da1d2008-01-12 19:39:10 +0000184{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000185 /* Invalidate any cached data for the specified type and all
186 subclasses. This function is called after the base
187 classes, mro, or attributes of the type are altered.
Christian Heimesa62da1d2008-01-12 19:39:10 +0000188
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000189 Invariants:
Christian Heimesa62da1d2008-01-12 19:39:10 +0000190
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000191 - Py_TPFLAGS_VALID_VERSION_TAG is never set if
192 Py_TPFLAGS_HAVE_VERSION_TAG is not set (e.g. on type
193 objects coming from non-recompiled extension modules)
Christian Heimesa62da1d2008-01-12 19:39:10 +0000194
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000195 - before Py_TPFLAGS_VALID_VERSION_TAG can be set on a type,
196 it must first be set on all super types.
Christian Heimesa62da1d2008-01-12 19:39:10 +0000197
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000198 This function clears the Py_TPFLAGS_VALID_VERSION_TAG of a
199 type (so it must first clear it on all subclasses). The
200 tp_version_tag value is meaningless unless this flag is set.
201 We don't assign new version tags eagerly, but only as
202 needed.
203 */
204 PyObject *raw, *ref;
Antoine Pitrou84745ab2013-10-29 21:31:25 +0100205 Py_ssize_t i;
Christian Heimesa62da1d2008-01-12 19:39:10 +0000206
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000207 if (!PyType_HasFeature(type, Py_TPFLAGS_VALID_VERSION_TAG))
208 return;
Christian Heimesa62da1d2008-01-12 19:39:10 +0000209
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000210 raw = type->tp_subclasses;
211 if (raw != NULL) {
Antoine Pitrou84745ab2013-10-29 21:31:25 +0100212 assert(PyDict_CheckExact(raw));
213 i = 0;
214 while (PyDict_Next(raw, &i, NULL, &ref)) {
215 assert(PyWeakref_CheckRef(ref));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000216 ref = PyWeakref_GET_OBJECT(ref);
217 if (ref != Py_None) {
218 PyType_Modified((PyTypeObject *)ref);
219 }
220 }
221 }
222 type->tp_flags &= ~Py_TPFLAGS_VALID_VERSION_TAG;
Christian Heimesa62da1d2008-01-12 19:39:10 +0000223}
224
225static void
226type_mro_modified(PyTypeObject *type, PyObject *bases) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000227 /*
Florent Xiclunaaa6c1d22011-12-12 18:54:29 +0100228 Check that all base classes or elements of the MRO of type are
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000229 able to be cached. This function is called after the base
230 classes or mro of the type are altered.
Christian Heimesa62da1d2008-01-12 19:39:10 +0000231
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000232 Unset HAVE_VERSION_TAG and VALID_VERSION_TAG if the type
Florent Xiclunaaa6c1d22011-12-12 18:54:29 +0100233 has a custom MRO that includes a type which is not officially
234 super type.
Christian Heimesa62da1d2008-01-12 19:39:10 +0000235
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000236 Called from mro_internal, which will subsequently be called on
237 each subclass when their mro is recursively updated.
238 */
239 Py_ssize_t i, n;
240 int clear = 0;
Christian Heimesa62da1d2008-01-12 19:39:10 +0000241
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000242 if (!PyType_HasFeature(type, Py_TPFLAGS_HAVE_VERSION_TAG))
243 return;
Christian Heimesa62da1d2008-01-12 19:39:10 +0000244
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000245 n = PyTuple_GET_SIZE(bases);
246 for (i = 0; i < n; i++) {
247 PyObject *b = PyTuple_GET_ITEM(bases, i);
248 PyTypeObject *cls;
Christian Heimesa62da1d2008-01-12 19:39:10 +0000249
Florent Xiclunaaa6c1d22011-12-12 18:54:29 +0100250 assert(PyType_Check(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000251 cls = (PyTypeObject *)b;
Christian Heimesa62da1d2008-01-12 19:39:10 +0000252
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000253 if (!PyType_HasFeature(cls, Py_TPFLAGS_HAVE_VERSION_TAG) ||
254 !PyType_IsSubtype(type, cls)) {
255 clear = 1;
256 break;
257 }
258 }
Christian Heimesa62da1d2008-01-12 19:39:10 +0000259
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000260 if (clear)
261 type->tp_flags &= ~(Py_TPFLAGS_HAVE_VERSION_TAG|
262 Py_TPFLAGS_VALID_VERSION_TAG);
Christian Heimesa62da1d2008-01-12 19:39:10 +0000263}
264
265static int
266assign_version_tag(PyTypeObject *type)
267{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000268 /* Ensure that the tp_version_tag is valid and set
269 Py_TPFLAGS_VALID_VERSION_TAG. To respect the invariant, this
270 must first be done on all super classes. Return 0 if this
271 cannot be done, 1 if Py_TPFLAGS_VALID_VERSION_TAG.
272 */
273 Py_ssize_t i, n;
274 PyObject *bases;
Christian Heimesa62da1d2008-01-12 19:39:10 +0000275
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000276 if (PyType_HasFeature(type, Py_TPFLAGS_VALID_VERSION_TAG))
277 return 1;
278 if (!PyType_HasFeature(type, Py_TPFLAGS_HAVE_VERSION_TAG))
279 return 0;
280 if (!PyType_HasFeature(type, Py_TPFLAGS_READY))
281 return 0;
Christian Heimesa62da1d2008-01-12 19:39:10 +0000282
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000283 type->tp_version_tag = next_version_tag++;
284 /* for stress-testing: next_version_tag &= 0xFF; */
Christian Heimesa62da1d2008-01-12 19:39:10 +0000285
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000286 if (type->tp_version_tag == 0) {
287 /* wrap-around or just starting Python - clear the whole
288 cache by filling names with references to Py_None.
289 Values are also set to NULL for added protection, as they
290 are borrowed reference */
291 for (i = 0; i < (1 << MCACHE_SIZE_EXP); i++) {
292 method_cache[i].value = NULL;
293 Py_XDECREF(method_cache[i].name);
294 method_cache[i].name = Py_None;
295 Py_INCREF(Py_None);
296 }
297 /* mark all version tags as invalid */
298 PyType_Modified(&PyBaseObject_Type);
299 return 1;
300 }
301 bases = type->tp_bases;
302 n = PyTuple_GET_SIZE(bases);
303 for (i = 0; i < n; i++) {
304 PyObject *b = PyTuple_GET_ITEM(bases, i);
305 assert(PyType_Check(b));
306 if (!assign_version_tag((PyTypeObject *)b))
307 return 0;
308 }
309 type->tp_flags |= Py_TPFLAGS_VALID_VERSION_TAG;
310 return 1;
Christian Heimesa62da1d2008-01-12 19:39:10 +0000311}
312
313
Guido van Rossum6f799372001-09-20 20:46:19 +0000314static PyMemberDef type_members[] = {
Benjamin Peterson0e102062010-08-25 23:13:17 +0000315 {"__basicsize__", T_PYSSIZET, offsetof(PyTypeObject,tp_basicsize),READONLY},
316 {"__itemsize__", T_PYSSIZET, offsetof(PyTypeObject, tp_itemsize), READONLY},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000317 {"__flags__", T_LONG, offsetof(PyTypeObject, tp_flags), READONLY},
318 {"__weakrefoffset__", T_LONG,
319 offsetof(PyTypeObject, tp_weaklistoffset), READONLY},
320 {"__base__", T_OBJECT, offsetof(PyTypeObject, tp_base), READONLY},
321 {"__dictoffset__", T_LONG,
322 offsetof(PyTypeObject, tp_dictoffset), READONLY},
323 {"__mro__", T_OBJECT, offsetof(PyTypeObject, tp_mro), READONLY},
324 {0}
Tim Peters6d6c1a32001-08-02 04:15:00 +0000325};
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000326
Benjamin Petersond9f23d22011-08-17 11:54:03 -0500327static int
328check_set_special_type_attr(PyTypeObject *type, PyObject *value, const char *name)
329{
330 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
331 PyErr_Format(PyExc_TypeError,
332 "can't set %s.%s", type->tp_name, name);
333 return 0;
334 }
335 if (!value) {
336 PyErr_Format(PyExc_TypeError,
337 "can't delete %s.%s", type->tp_name, name);
338 return 0;
339 }
340 return 1;
341}
342
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000343static PyObject *
Guido van Rossumc3542212001-08-16 09:18:56 +0000344type_name(PyTypeObject *type, void *context)
345{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000346 const char *s;
Guido van Rossumc3542212001-08-16 09:18:56 +0000347
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000348 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
349 PyHeapTypeObject* et = (PyHeapTypeObject*)type;
Tim Petersea7f75d2002-12-07 21:39:16 +0000350
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000351 Py_INCREF(et->ht_name);
352 return et->ht_name;
353 }
354 else {
355 s = strrchr(type->tp_name, '.');
356 if (s == NULL)
357 s = type->tp_name;
358 else
359 s++;
360 return PyUnicode_FromString(s);
361 }
Guido van Rossumc3542212001-08-16 09:18:56 +0000362}
363
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100364static PyObject *
365type_qualname(PyTypeObject *type, void *context)
366{
367 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
368 PyHeapTypeObject* et = (PyHeapTypeObject*)type;
369 Py_INCREF(et->ht_qualname);
370 return et->ht_qualname;
371 }
372 else {
373 return type_name(type, context);
374 }
375}
376
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000377static int
378type_set_name(PyTypeObject *type, PyObject *value, void *context)
379{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000380 PyHeapTypeObject* et;
381 char *tp_name;
382 PyObject *tmp;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000383
Benjamin Petersond9f23d22011-08-17 11:54:03 -0500384 if (!check_set_special_type_attr(type, value, "__name__"))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000385 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000386 if (!PyUnicode_Check(value)) {
387 PyErr_Format(PyExc_TypeError,
388 "can only assign string to %s.__name__, not '%s'",
389 type->tp_name, Py_TYPE(value)->tp_name);
390 return -1;
391 }
Guido van Rossume845c0f2007-11-02 23:07:07 +0000392
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000393 /* Check absence of null characters */
394 tmp = PyUnicode_FromStringAndSize("\0", 1);
395 if (tmp == NULL)
396 return -1;
397 if (PyUnicode_Contains(value, tmp) != 0) {
398 Py_DECREF(tmp);
399 PyErr_Format(PyExc_ValueError,
400 "__name__ must not contain null bytes");
401 return -1;
402 }
403 Py_DECREF(tmp);
Guido van Rossume845c0f2007-11-02 23:07:07 +0000404
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000405 tp_name = _PyUnicode_AsString(value);
406 if (tp_name == NULL)
407 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000408
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000409 et = (PyHeapTypeObject*)type;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000410
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000411 Py_INCREF(value);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000412
Mark Dickinson64aafeb2013-04-13 15:26:58 +0100413 /* Wait until et is a sane state before Py_DECREF'ing the old et->ht_name
414 value. (Bug #16447.) */
415 tmp = et->ht_name;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000416 et->ht_name = value;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000417
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000418 type->tp_name = tp_name;
Mark Dickinson64aafeb2013-04-13 15:26:58 +0100419 Py_DECREF(tmp);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000420
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000421 return 0;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000422}
423
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100424static int
425type_set_qualname(PyTypeObject *type, PyObject *value, void *context)
426{
427 PyHeapTypeObject* et;
428
Benjamin Peterson2c05a2e2012-10-31 00:01:15 -0400429 if (!check_set_special_type_attr(type, value, "__qualname__"))
430 return -1;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100431 if (!PyUnicode_Check(value)) {
432 PyErr_Format(PyExc_TypeError,
433 "can only assign string to %s.__qualname__, not '%s'",
434 type->tp_name, Py_TYPE(value)->tp_name);
435 return -1;
436 }
437
438 et = (PyHeapTypeObject*)type;
439 Py_INCREF(value);
440 Py_DECREF(et->ht_qualname);
441 et->ht_qualname = value;
442 return 0;
443}
444
Guido van Rossumc3542212001-08-16 09:18:56 +0000445static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000446type_module(PyTypeObject *type, void *context)
Guido van Rossum29ca26e1995-01-07 11:58:15 +0000447{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000448 char *s;
Guido van Rossumc3542212001-08-16 09:18:56 +0000449
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000450 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
Victor Stinnerad14ccd2013-11-07 00:46:04 +0100451 PyObject *mod = _PyDict_GetItemId(type->tp_dict, &PyId___module__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000452 if (!mod) {
453 PyErr_Format(PyExc_AttributeError, "__module__");
454 return 0;
455 }
456 Py_XINCREF(mod);
457 return mod;
458 }
459 else {
Victor Stinnerad14ccd2013-11-07 00:46:04 +0100460 PyObject *name;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000461 s = strrchr(type->tp_name, '.');
462 if (s != NULL)
463 return PyUnicode_FromStringAndSize(
464 type->tp_name, (Py_ssize_t)(s - type->tp_name));
Victor Stinnerbd303c12013-11-07 23:07:29 +0100465 name = _PyUnicode_FromId(&PyId_builtins);
Victor Stinnerad14ccd2013-11-07 00:46:04 +0100466 Py_XINCREF(name);
467 return name;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000468 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000469}
470
Guido van Rossum3926a632001-09-25 16:25:58 +0000471static int
472type_set_module(PyTypeObject *type, PyObject *value, void *context)
473{
Benjamin Petersond9f23d22011-08-17 11:54:03 -0500474 if (!check_set_special_type_attr(type, value, "__module__"))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000475 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000476
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000477 PyType_Modified(type);
Christian Heimesa62da1d2008-01-12 19:39:10 +0000478
Victor Stinner3c1e4812012-03-26 22:10:51 +0200479 return _PyDict_SetItemId(type->tp_dict, &PyId___module__, value);
Guido van Rossum3926a632001-09-25 16:25:58 +0000480}
481
Tim Peters6d6c1a32001-08-02 04:15:00 +0000482static PyObject *
Christian Heimes9e7f1d22008-02-28 12:27:11 +0000483type_abstractmethods(PyTypeObject *type, void *context)
484{
Benjamin Petersonaec5fd12010-10-02 00:03:31 +0000485 PyObject *mod = NULL;
Benjamin Peterson84060b82010-10-03 02:13:39 +0000486 /* type itself has an __abstractmethods__ descriptor (this). Don't return
487 that. */
Benjamin Petersonaec5fd12010-10-02 00:03:31 +0000488 if (type != &PyType_Type)
Victor Stinner3688aa92013-11-06 18:59:18 +0100489 mod = _PyDict_GetItemId(type->tp_dict, &PyId___abstractmethods__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000490 if (!mod) {
Victor Stinner3688aa92013-11-06 18:59:18 +0100491 PyObject *message = _PyUnicode_FromId(&PyId___abstractmethods__);
492 if (message)
493 PyErr_SetObject(PyExc_AttributeError, message);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000494 return NULL;
495 }
496 Py_XINCREF(mod);
497 return mod;
Christian Heimes9e7f1d22008-02-28 12:27:11 +0000498}
499
500static int
501type_set_abstractmethods(PyTypeObject *type, PyObject *value, void *context)
502{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000503 /* __abstractmethods__ should only be set once on a type, in
504 abc.ABCMeta.__new__, so this function doesn't do anything
505 special to update subclasses.
506 */
Antoine Pitrou6f430e42012-08-15 23:18:25 +0200507 int abstract, res;
Benjamin Peterson477ba912011-01-12 15:34:01 +0000508 if (value != NULL) {
Antoine Pitrou6f430e42012-08-15 23:18:25 +0200509 abstract = PyObject_IsTrue(value);
510 if (abstract < 0)
511 return -1;
Victor Stinner3688aa92013-11-06 18:59:18 +0100512 res = _PyDict_SetItemId(type->tp_dict, &PyId___abstractmethods__, value);
Benjamin Peterson477ba912011-01-12 15:34:01 +0000513 }
514 else {
Antoine Pitrou6f430e42012-08-15 23:18:25 +0200515 abstract = 0;
Victor Stinner3688aa92013-11-06 18:59:18 +0100516 res = _PyDict_DelItemId(type->tp_dict, &PyId___abstractmethods__);
Benjamin Peterson477ba912011-01-12 15:34:01 +0000517 if (res && PyErr_ExceptionMatches(PyExc_KeyError)) {
Victor Stinner3688aa92013-11-06 18:59:18 +0100518 PyObject *message = _PyUnicode_FromId(&PyId___abstractmethods__);
519 if (message)
520 PyErr_SetObject(PyExc_AttributeError, message);
Benjamin Peterson477ba912011-01-12 15:34:01 +0000521 return -1;
522 }
523 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000524 if (res == 0) {
525 PyType_Modified(type);
Antoine Pitrou6f430e42012-08-15 23:18:25 +0200526 if (abstract)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000527 type->tp_flags |= Py_TPFLAGS_IS_ABSTRACT;
Antoine Pitrou6f430e42012-08-15 23:18:25 +0200528 else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000529 type->tp_flags &= ~Py_TPFLAGS_IS_ABSTRACT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000530 }
531 return res;
Christian Heimes9e7f1d22008-02-28 12:27:11 +0000532}
533
534static PyObject *
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000535type_get_bases(PyTypeObject *type, void *context)
536{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000537 Py_INCREF(type->tp_bases);
538 return type->tp_bases;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000539}
540
541static PyTypeObject *best_base(PyObject *);
542static int mro_internal(PyTypeObject *);
543static int compatible_for_assignment(PyTypeObject *, PyTypeObject *, char *);
544static int add_subclass(PyTypeObject*, PyTypeObject*);
545static void remove_subclass(PyTypeObject *, PyTypeObject *);
Antoine Pitrou84745ab2013-10-29 21:31:25 +0100546static void remove_all_subclasses(PyTypeObject *type, PyObject *bases);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000547static void update_all_slots(PyTypeObject *);
548
Guido van Rossum8d24ee92003-03-24 23:49:49 +0000549typedef int (*update_callback)(PyTypeObject *, void *);
550static int update_subclasses(PyTypeObject *type, PyObject *name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000551 update_callback callback, void *data);
Guido van Rossum8d24ee92003-03-24 23:49:49 +0000552static int recurse_down_subclasses(PyTypeObject *type, PyObject *name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000553 update_callback callback, void *data);
Guido van Rossum8d24ee92003-03-24 23:49:49 +0000554
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000555static int
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000556mro_subclasses(PyTypeObject *type, PyObject* temp)
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000557{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000558 PyTypeObject *subclass;
559 PyObject *ref, *subclasses, *old_mro;
Antoine Pitrou84745ab2013-10-29 21:31:25 +0100560 Py_ssize_t i;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000561
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000562 subclasses = type->tp_subclasses;
563 if (subclasses == NULL)
564 return 0;
Antoine Pitrou84745ab2013-10-29 21:31:25 +0100565 assert(PyDict_CheckExact(subclasses));
566 i = 0;
567
568 while (PyDict_Next(subclasses, &i, NULL, &ref)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000569 assert(PyWeakref_CheckRef(ref));
570 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
571 assert(subclass != NULL);
572 if ((PyObject *)subclass == Py_None)
573 continue;
574 assert(PyType_Check(subclass));
575 old_mro = subclass->tp_mro;
576 if (mro_internal(subclass) < 0) {
577 subclass->tp_mro = old_mro;
578 return -1;
579 }
580 else {
581 PyObject* tuple;
582 tuple = PyTuple_Pack(2, subclass, old_mro);
583 Py_DECREF(old_mro);
584 if (!tuple)
585 return -1;
586 if (PyList_Append(temp, tuple) < 0)
587 return -1;
588 Py_DECREF(tuple);
589 }
590 if (mro_subclasses(subclass, temp) < 0)
591 return -1;
592 }
593 return 0;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000594}
595
596static int
597type_set_bases(PyTypeObject *type, PyObject *value, void *context)
598{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000599 Py_ssize_t i;
600 int r = 0;
601 PyObject *ob, *temp;
602 PyTypeObject *new_base, *old_base;
603 PyObject *old_bases, *old_mro;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000604
Benjamin Petersond9f23d22011-08-17 11:54:03 -0500605 if (!check_set_special_type_attr(type, value, "__bases__"))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000606 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000607 if (!PyTuple_Check(value)) {
608 PyErr_Format(PyExc_TypeError,
609 "can only assign tuple to %s.__bases__, not %s",
610 type->tp_name, Py_TYPE(value)->tp_name);
611 return -1;
612 }
613 if (PyTuple_GET_SIZE(value) == 0) {
614 PyErr_Format(PyExc_TypeError,
615 "can only assign non-empty tuple to %s.__bases__, not ()",
616 type->tp_name);
617 return -1;
618 }
619 for (i = 0; i < PyTuple_GET_SIZE(value); i++) {
620 ob = PyTuple_GET_ITEM(value, i);
621 if (!PyType_Check(ob)) {
Benjamin Petersonb6af60c2012-04-01 18:49:54 -0400622 PyErr_Format(PyExc_TypeError,
Benjamin Peterson9ee601e2012-04-01 18:51:37 -0400623 "%s.__bases__ must be tuple of classes, not '%s'",
Benjamin Petersonb6af60c2012-04-01 18:49:54 -0400624 type->tp_name, Py_TYPE(ob)->tp_name);
625 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000626 }
Benjamin Peterson3471bb62012-04-01 18:48:40 -0400627 if (PyType_IsSubtype((PyTypeObject*)ob, type)) {
628 PyErr_SetString(PyExc_TypeError,
629 "a __bases__ item causes an inheritance cycle");
630 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000631 }
632 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000633
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000634 new_base = best_base(value);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000635
Benjamin Petersonab3c1c12012-04-01 18:48:02 -0400636 if (!new_base)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000637 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000638
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000639 if (!compatible_for_assignment(type->tp_base, new_base, "__bases__"))
640 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000641
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000642 Py_INCREF(new_base);
643 Py_INCREF(value);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000644
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000645 old_bases = type->tp_bases;
646 old_base = type->tp_base;
647 old_mro = type->tp_mro;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000648
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000649 type->tp_bases = value;
650 type->tp_base = new_base;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000651
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000652 if (mro_internal(type) < 0) {
653 goto bail;
654 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000655
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000656 temp = PyList_New(0);
657 if (!temp)
658 goto bail;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000659
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000660 r = mro_subclasses(type, temp);
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000661
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000662 if (r < 0) {
663 for (i = 0; i < PyList_Size(temp); i++) {
664 PyTypeObject* cls;
665 PyObject* mro;
666 PyArg_UnpackTuple(PyList_GET_ITEM(temp, i),
667 "", 2, 2, &cls, &mro);
668 Py_INCREF(mro);
669 ob = cls->tp_mro;
670 cls->tp_mro = mro;
671 Py_DECREF(ob);
672 }
673 Py_DECREF(temp);
674 goto bail;
675 }
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000676
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000677 Py_DECREF(temp);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000678
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000679 /* any base that was in __bases__ but now isn't, we
680 need to remove |type| from its tp_subclasses.
681 conversely, any class now in __bases__ that wasn't
682 needs to have |type| added to its subclasses. */
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000683
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000684 /* for now, sod that: just remove from all old_bases,
685 add to all new_bases */
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000686
Antoine Pitrou84745ab2013-10-29 21:31:25 +0100687 remove_all_subclasses(type, old_bases);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000688
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000689 for (i = PyTuple_GET_SIZE(value) - 1; i >= 0; i--) {
690 ob = PyTuple_GET_ITEM(value, i);
691 if (PyType_Check(ob)) {
692 if (add_subclass((PyTypeObject*)ob, type) < 0)
693 r = -1;
694 }
695 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000696
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000697 update_all_slots(type);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000698
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000699 Py_DECREF(old_bases);
700 Py_DECREF(old_base);
701 Py_DECREF(old_mro);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000702
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000703 return r;
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000704
705 bail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000706 Py_DECREF(type->tp_bases);
707 Py_DECREF(type->tp_base);
708 if (type->tp_mro != old_mro) {
709 Py_DECREF(type->tp_mro);
710 }
Michael W. Hudsone723e452003-08-07 14:58:10 +0000711
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000712 type->tp_bases = old_bases;
713 type->tp_base = old_base;
714 type->tp_mro = old_mro;
Tim Petersea7f75d2002-12-07 21:39:16 +0000715
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000716 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000717}
718
719static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000720type_dict(PyTypeObject *type, void *context)
721{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000722 if (type->tp_dict == NULL) {
723 Py_INCREF(Py_None);
724 return Py_None;
725 }
726 return PyDictProxy_New(type->tp_dict);
Guido van Rossum29ca26e1995-01-07 11:58:15 +0000727}
728
Tim Peters24008312002-03-17 18:56:20 +0000729static PyObject *
730type_get_doc(PyTypeObject *type, void *context)
731{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000732 PyObject *result;
Larry Hastings5c661892014-01-24 06:17:25 -0800733 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE) && type->tp_doc != NULL) {
Larry Hastings2623c8c2014-02-08 22:15:29 -0800734 return _PyType_GetDocFromInternalDoc(type->tp_name, type->tp_doc);
Larry Hastings5c661892014-01-24 06:17:25 -0800735 }
Victor Stinner3c1e4812012-03-26 22:10:51 +0200736 result = _PyDict_GetItemId(type->tp_dict, &PyId___doc__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000737 if (result == NULL) {
738 result = Py_None;
739 Py_INCREF(result);
740 }
741 else if (Py_TYPE(result)->tp_descr_get) {
742 result = Py_TYPE(result)->tp_descr_get(result, NULL,
743 (PyObject *)type);
744 }
745 else {
746 Py_INCREF(result);
747 }
748 return result;
Tim Peters24008312002-03-17 18:56:20 +0000749}
750
Larry Hastings5c661892014-01-24 06:17:25 -0800751static PyObject *
752type_get_text_signature(PyTypeObject *type, void *context)
753{
Larry Hastings2623c8c2014-02-08 22:15:29 -0800754 return _PyType_GetTextSignatureFromInternalDoc(type->tp_name, type->tp_doc);
Larry Hastings5c661892014-01-24 06:17:25 -0800755}
756
Benjamin Peterson01fc6cd2011-08-17 12:03:47 -0500757static int
758type_set_doc(PyTypeObject *type, PyObject *value, void *context)
759{
760 if (!check_set_special_type_attr(type, value, "__doc__"))
761 return -1;
762 PyType_Modified(type);
Victor Stinner3c1e4812012-03-26 22:10:51 +0200763 return _PyDict_SetItemId(type->tp_dict, &PyId___doc__, value);
Benjamin Peterson01fc6cd2011-08-17 12:03:47 -0500764}
765
Antoine Pitrouec569b72008-08-26 22:40:48 +0000766static PyObject *
767type___instancecheck__(PyObject *type, PyObject *inst)
768{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000769 switch (_PyObject_RealIsInstance(inst, type)) {
770 case -1:
771 return NULL;
772 case 0:
773 Py_RETURN_FALSE;
774 default:
775 Py_RETURN_TRUE;
776 }
Antoine Pitrouec569b72008-08-26 22:40:48 +0000777}
778
779
780static PyObject *
Antoine Pitrouec569b72008-08-26 22:40:48 +0000781type___subclasscheck__(PyObject *type, PyObject *inst)
782{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000783 switch (_PyObject_RealIsSubclass(inst, type)) {
784 case -1:
785 return NULL;
786 case 0:
787 Py_RETURN_FALSE;
788 default:
789 Py_RETURN_TRUE;
790 }
Antoine Pitrouec569b72008-08-26 22:40:48 +0000791}
792
Antoine Pitrouec569b72008-08-26 22:40:48 +0000793
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000794static PyGetSetDef type_getsets[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000795 {"__name__", (getter)type_name, (setter)type_set_name, NULL},
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100796 {"__qualname__", (getter)type_qualname, (setter)type_set_qualname, NULL},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000797 {"__bases__", (getter)type_get_bases, (setter)type_set_bases, NULL},
798 {"__module__", (getter)type_module, (setter)type_set_module, NULL},
799 {"__abstractmethods__", (getter)type_abstractmethods,
800 (setter)type_set_abstractmethods, NULL},
801 {"__dict__", (getter)type_dict, NULL, NULL},
Benjamin Peterson01fc6cd2011-08-17 12:03:47 -0500802 {"__doc__", (getter)type_get_doc, (setter)type_set_doc, NULL},
Larry Hastings5c661892014-01-24 06:17:25 -0800803 {"__text_signature__", (getter)type_get_text_signature, NULL, NULL},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000804 {0}
Tim Peters6d6c1a32001-08-02 04:15:00 +0000805};
806
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000807static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000808type_repr(PyTypeObject *type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000809{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000810 PyObject *mod, *name, *rtn;
Guido van Rossumc3542212001-08-16 09:18:56 +0000811
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000812 mod = type_module(type, NULL);
813 if (mod == NULL)
814 PyErr_Clear();
815 else if (!PyUnicode_Check(mod)) {
816 Py_DECREF(mod);
817 mod = NULL;
818 }
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100819 name = type_qualname(type, NULL);
Christian Heimesa0e7e412012-09-10 03:00:14 +0200820 if (name == NULL) {
821 Py_XDECREF(mod);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000822 return NULL;
Christian Heimesa0e7e412012-09-10 03:00:14 +0200823 }
Barry Warsaw7ce36942001-08-24 18:34:26 +0000824
Victor Stinnerbd303c12013-11-07 23:07:29 +0100825 if (mod != NULL && _PyUnicode_CompareWithId(mod, &PyId_builtins))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000826 rtn = PyUnicode_FromFormat("<class '%U.%U'>", mod, name);
827 else
828 rtn = PyUnicode_FromFormat("<class '%s'>", type->tp_name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000829
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000830 Py_XDECREF(mod);
831 Py_DECREF(name);
832 return rtn;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000833}
834
Tim Peters6d6c1a32001-08-02 04:15:00 +0000835static PyObject *
836type_call(PyTypeObject *type, PyObject *args, PyObject *kwds)
837{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000838 PyObject *obj;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000839
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000840 if (type->tp_new == NULL) {
841 PyErr_Format(PyExc_TypeError,
842 "cannot create '%.100s' instances",
843 type->tp_name);
844 return NULL;
845 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000846
Victor Stinner33824f62013-08-26 14:05:19 +0200847#ifdef Py_DEBUG
848 /* type_call() must not be called with an exception set,
849 because it may clear it (directly or indirectly) and so the
850 caller looses its exception */
851 assert(!PyErr_Occurred());
852#endif
853
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000854 obj = type->tp_new(type, args, kwds);
855 if (obj != NULL) {
856 /* Ugly exception: when the call was type(something),
857 don't call tp_init on the result. */
858 if (type == &PyType_Type &&
859 PyTuple_Check(args) && PyTuple_GET_SIZE(args) == 1 &&
860 (kwds == NULL ||
861 (PyDict_Check(kwds) && PyDict_Size(kwds) == 0)))
862 return obj;
863 /* If the returned object is not an instance of type,
864 it won't be initialized. */
865 if (!PyType_IsSubtype(Py_TYPE(obj), type))
866 return obj;
867 type = Py_TYPE(obj);
Victor Stinner3997cfd2013-07-16 22:51:21 +0200868 if (type->tp_init != NULL) {
869 int res = type->tp_init(obj, args, kwds);
870 if (res < 0) {
871 Py_DECREF(obj);
872 obj = NULL;
873 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000874 }
875 }
876 return obj;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000877}
878
879PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000880PyType_GenericAlloc(PyTypeObject *type, Py_ssize_t nitems)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000881{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000882 PyObject *obj;
883 const size_t size = _PyObject_VAR_SIZE(type, nitems+1);
884 /* note that we need to add one, for the sentinel */
Tim Peters406fe3b2001-10-06 19:04:01 +0000885
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000886 if (PyType_IS_GC(type))
887 obj = _PyObject_GC_Malloc(size);
888 else
889 obj = (PyObject *)PyObject_MALLOC(size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000890
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000891 if (obj == NULL)
892 return PyErr_NoMemory();
Tim Peters406fe3b2001-10-06 19:04:01 +0000893
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000894 memset(obj, '\0', size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000895
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000896 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
897 Py_INCREF(type);
Tim Peters406fe3b2001-10-06 19:04:01 +0000898
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000899 if (type->tp_itemsize == 0)
Christian Heimesd3afe782013-12-04 09:27:47 +0100900 (void)PyObject_INIT(obj, type);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000901 else
902 (void) PyObject_INIT_VAR((PyVarObject *)obj, type, nitems);
Tim Peters406fe3b2001-10-06 19:04:01 +0000903
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000904 if (PyType_IS_GC(type))
905 _PyObject_GC_TRACK(obj);
906 return obj;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000907}
908
909PyObject *
910PyType_GenericNew(PyTypeObject *type, PyObject *args, PyObject *kwds)
911{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000912 return type->tp_alloc(type, 0);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000913}
914
Guido van Rossum9475a232001-10-05 20:51:39 +0000915/* Helpers for subtyping */
916
917static int
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000918traverse_slots(PyTypeObject *type, PyObject *self, visitproc visit, void *arg)
919{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000920 Py_ssize_t i, n;
921 PyMemberDef *mp;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000922
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000923 n = Py_SIZE(type);
924 mp = PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type);
925 for (i = 0; i < n; i++, mp++) {
926 if (mp->type == T_OBJECT_EX) {
927 char *addr = (char *)self + mp->offset;
928 PyObject *obj = *(PyObject **)addr;
929 if (obj != NULL) {
930 int err = visit(obj, arg);
931 if (err)
932 return err;
933 }
934 }
935 }
936 return 0;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000937}
938
939static int
Guido van Rossum9475a232001-10-05 20:51:39 +0000940subtype_traverse(PyObject *self, visitproc visit, void *arg)
941{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000942 PyTypeObject *type, *base;
943 traverseproc basetraverse;
Guido van Rossum9475a232001-10-05 20:51:39 +0000944
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000945 /* Find the nearest base with a different tp_traverse,
946 and traverse slots while we're at it */
947 type = Py_TYPE(self);
948 base = type;
949 while ((basetraverse = base->tp_traverse) == subtype_traverse) {
950 if (Py_SIZE(base)) {
951 int err = traverse_slots(base, self, visit, arg);
952 if (err)
953 return err;
954 }
955 base = base->tp_base;
956 assert(base);
957 }
Guido van Rossum9475a232001-10-05 20:51:39 +0000958
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000959 if (type->tp_dictoffset != base->tp_dictoffset) {
960 PyObject **dictptr = _PyObject_GetDictPtr(self);
961 if (dictptr && *dictptr)
962 Py_VISIT(*dictptr);
963 }
Guido van Rossum9475a232001-10-05 20:51:39 +0000964
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000965 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
966 /* For a heaptype, the instances count as references
967 to the type. Traverse the type so the collector
968 can find cycles involving this link. */
969 Py_VISIT(type);
Guido van Rossuma3862092002-06-10 15:24:42 +0000970
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000971 if (basetraverse)
972 return basetraverse(self, visit, arg);
973 return 0;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000974}
975
976static void
977clear_slots(PyTypeObject *type, PyObject *self)
978{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000979 Py_ssize_t i, n;
980 PyMemberDef *mp;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000981
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000982 n = Py_SIZE(type);
983 mp = PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type);
984 for (i = 0; i < n; i++, mp++) {
985 if (mp->type == T_OBJECT_EX && !(mp->flags & READONLY)) {
986 char *addr = (char *)self + mp->offset;
987 PyObject *obj = *(PyObject **)addr;
988 if (obj != NULL) {
989 *(PyObject **)addr = NULL;
990 Py_DECREF(obj);
991 }
992 }
993 }
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000994}
995
996static int
997subtype_clear(PyObject *self)
998{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000999 PyTypeObject *type, *base;
1000 inquiry baseclear;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001001
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001002 /* Find the nearest base with a different tp_clear
1003 and clear slots while we're at it */
1004 type = Py_TYPE(self);
1005 base = type;
1006 while ((baseclear = base->tp_clear) == subtype_clear) {
1007 if (Py_SIZE(base))
1008 clear_slots(base, self);
1009 base = base->tp_base;
1010 assert(base);
1011 }
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001012
Benjamin Peterson52c42432012-03-07 18:41:11 -06001013 /* Clear the instance dict (if any), to break cycles involving only
1014 __dict__ slots (as in the case 'self.__dict__ is self'). */
1015 if (type->tp_dictoffset != base->tp_dictoffset) {
1016 PyObject **dictptr = _PyObject_GetDictPtr(self);
1017 if (dictptr && *dictptr)
1018 Py_CLEAR(*dictptr);
1019 }
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001020
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001021 if (baseclear)
1022 return baseclear(self);
1023 return 0;
Guido van Rossum9475a232001-10-05 20:51:39 +00001024}
Tim Peters6d6c1a32001-08-02 04:15:00 +00001025
1026static void
1027subtype_dealloc(PyObject *self)
1028{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001029 PyTypeObject *type, *base;
1030 destructor basedealloc;
Antoine Pitrou56cd62c2012-09-06 00:59:49 +02001031 PyThreadState *tstate = PyThreadState_GET();
Antoine Pitrou796564c2013-07-30 19:59:21 +02001032 int has_finalizer;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001033
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001034 /* Extract the type; we expect it to be a heap type */
1035 type = Py_TYPE(self);
1036 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001037
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001038 /* Test whether the type has GC exactly once */
Guido van Rossum22b13872002-08-06 21:41:44 +00001039
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001040 if (!PyType_IS_GC(type)) {
1041 /* It's really rare to find a dynamic type that doesn't have
1042 GC; it can only happen when deriving from 'object' and not
1043 adding any slots or instance variables. This allows
1044 certain simplifications: there's no need to call
1045 clear_slots(), or DECREF the dict, or clear weakrefs. */
Guido van Rossum22b13872002-08-06 21:41:44 +00001046
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001047 /* Maybe call finalizer; exit early if resurrected */
Antoine Pitrou796564c2013-07-30 19:59:21 +02001048 if (type->tp_finalize) {
1049 if (PyObject_CallFinalizerFromDealloc(self) < 0)
1050 return;
1051 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001052 if (type->tp_del) {
1053 type->tp_del(self);
1054 if (self->ob_refcnt > 0)
1055 return;
1056 }
Guido van Rossum22b13872002-08-06 21:41:44 +00001057
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001058 /* Find the nearest base with a different tp_dealloc */
1059 base = type;
1060 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
1061 assert(Py_SIZE(base) == 0);
1062 base = base->tp_base;
1063 assert(base);
1064 }
Guido van Rossum22b13872002-08-06 21:41:44 +00001065
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001066 /* Extract the type again; tp_del may have changed it */
1067 type = Py_TYPE(self);
Benjamin Peterson193152c2009-04-25 01:08:45 +00001068
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001069 /* Call the base tp_dealloc() */
1070 assert(basedealloc);
1071 basedealloc(self);
Guido van Rossum22b13872002-08-06 21:41:44 +00001072
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001073 /* Can't reference self beyond this point */
1074 Py_DECREF(type);
Guido van Rossum22b13872002-08-06 21:41:44 +00001075
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001076 /* Done */
1077 return;
1078 }
Guido van Rossum22b13872002-08-06 21:41:44 +00001079
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001080 /* We get here only if the type has GC */
Guido van Rossum22b13872002-08-06 21:41:44 +00001081
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001082 /* UnTrack and re-Track around the trashcan macro, alas */
1083 /* See explanation at end of function for full disclosure */
1084 PyObject_GC_UnTrack(self);
1085 ++_PyTrash_delete_nesting;
Antoine Pitrou56cd62c2012-09-06 00:59:49 +02001086 ++ tstate->trash_delete_nesting;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001087 Py_TRASHCAN_SAFE_BEGIN(self);
1088 --_PyTrash_delete_nesting;
Antoine Pitrou56cd62c2012-09-06 00:59:49 +02001089 -- tstate->trash_delete_nesting;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001090 /* DO NOT restore GC tracking at this point. weakref callbacks
1091 * (if any, and whether directly here or indirectly in something we
1092 * call) may trigger GC, and if self is tracked at that point, it
1093 * will look like trash to GC and GC will try to delete self again.
1094 */
Guido van Rossum22b13872002-08-06 21:41:44 +00001095
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001096 /* Find the nearest base with a different tp_dealloc */
1097 base = type;
Brett Cannonb94767f2011-02-22 20:15:44 +00001098 while ((/*basedealloc =*/ base->tp_dealloc) == subtype_dealloc) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001099 base = base->tp_base;
1100 assert(base);
1101 }
Guido van Rossum14227b42001-12-06 02:35:58 +00001102
Antoine Pitrou796564c2013-07-30 19:59:21 +02001103 has_finalizer = type->tp_finalize || type->tp_del;
Guido van Rossum59195fd2003-06-13 20:54:40 +00001104
Antoine Pitrou796564c2013-07-30 19:59:21 +02001105 /* Maybe call finalizer; exit early if resurrected */
1106 if (has_finalizer)
1107 _PyObject_GC_TRACK(self);
1108
1109 if (type->tp_finalize) {
1110 if (PyObject_CallFinalizerFromDealloc(self) < 0) {
1111 /* Resurrected */
1112 goto endlabel;
1113 }
1114 }
1115 /* If we added a weaklist, we clear it. Do this *before* calling
1116 tp_del, clearing slots, or clearing the instance dict. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001117 if (type->tp_weaklistoffset && !base->tp_weaklistoffset)
1118 PyObject_ClearWeakRefs(self);
Guido van Rossum1987c662003-05-29 14:29:23 +00001119
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001120 if (type->tp_del) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001121 type->tp_del(self);
Antoine Pitrou796564c2013-07-30 19:59:21 +02001122 if (self->ob_refcnt > 0) {
1123 /* Resurrected */
1124 goto endlabel;
1125 }
1126 }
1127 if (has_finalizer) {
1128 _PyObject_GC_UNTRACK(self);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001129 /* New weakrefs could be created during the finalizer call.
Antoine Pitrou796564c2013-07-30 19:59:21 +02001130 If this occurs, clear them out without calling their
1131 finalizers since they might rely on part of the object
1132 being finalized that has already been destroyed. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001133 if (type->tp_weaklistoffset && !base->tp_weaklistoffset) {
1134 /* Modeled after GET_WEAKREFS_LISTPTR() */
1135 PyWeakReference **list = (PyWeakReference **) \
1136 PyObject_GET_WEAKREFS_LISTPTR(self);
1137 while (*list)
1138 _PyWeakref_ClearRef(*list);
1139 }
1140 }
Guido van Rossum1987c662003-05-29 14:29:23 +00001141
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001142 /* Clear slots up to the nearest base with a different tp_dealloc */
1143 base = type;
1144 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
1145 if (Py_SIZE(base))
1146 clear_slots(base, self);
1147 base = base->tp_base;
1148 assert(base);
1149 }
Guido van Rossum59195fd2003-06-13 20:54:40 +00001150
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001151 /* If we added a dict, DECREF it */
1152 if (type->tp_dictoffset && !base->tp_dictoffset) {
1153 PyObject **dictptr = _PyObject_GetDictPtr(self);
1154 if (dictptr != NULL) {
1155 PyObject *dict = *dictptr;
1156 if (dict != NULL) {
1157 Py_DECREF(dict);
1158 *dictptr = NULL;
1159 }
1160 }
1161 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001162
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001163 /* Extract the type again; tp_del may have changed it */
1164 type = Py_TYPE(self);
Benjamin Peterson193152c2009-04-25 01:08:45 +00001165
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001166 /* Call the base tp_dealloc(); first retrack self if
1167 * basedealloc knows about gc.
1168 */
1169 if (PyType_IS_GC(base))
1170 _PyObject_GC_TRACK(self);
1171 assert(basedealloc);
1172 basedealloc(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001173
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001174 /* Can't reference self beyond this point */
1175 Py_DECREF(type);
Guido van Rossum22b13872002-08-06 21:41:44 +00001176
Guido van Rossum0906e072002-08-07 20:42:09 +00001177 endlabel:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001178 ++_PyTrash_delete_nesting;
Antoine Pitrou56cd62c2012-09-06 00:59:49 +02001179 ++ tstate->trash_delete_nesting;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001180 Py_TRASHCAN_SAFE_END(self);
1181 --_PyTrash_delete_nesting;
Antoine Pitrou56cd62c2012-09-06 00:59:49 +02001182 -- tstate->trash_delete_nesting;
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001183
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001184 /* Explanation of the weirdness around the trashcan macros:
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001185
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001186 Q. What do the trashcan macros do?
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001187
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001188 A. Read the comment titled "Trashcan mechanism" in object.h.
1189 For one, this explains why there must be a call to GC-untrack
1190 before the trashcan begin macro. Without understanding the
1191 trashcan code, the answers to the following questions don't make
1192 sense.
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001193
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001194 Q. Why do we GC-untrack before the trashcan and then immediately
1195 GC-track again afterward?
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001196
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001197 A. In the case that the base class is GC-aware, the base class
1198 probably GC-untracks the object. If it does that using the
1199 UNTRACK macro, this will crash when the object is already
1200 untracked. Because we don't know what the base class does, the
1201 only safe thing is to make sure the object is tracked when we
1202 call the base class dealloc. But... The trashcan begin macro
1203 requires that the object is *untracked* before it is called. So
1204 the dance becomes:
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001205
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001206 GC untrack
1207 trashcan begin
1208 GC track
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001209
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001210 Q. Why did the last question say "immediately GC-track again"?
1211 It's nowhere near immediately.
Tim Petersf7f9e992003-11-13 21:59:32 +00001212
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001213 A. Because the code *used* to re-track immediately. Bad Idea.
1214 self has a refcount of 0, and if gc ever gets its hands on it
1215 (which can happen if any weakref callback gets invoked), it
1216 looks like trash to gc too, and gc also tries to delete self
Ezio Melotti13925002011-03-16 11:05:33 +02001217 then. But we're already deleting self. Double deallocation is
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001218 a subtle disaster.
Tim Petersf7f9e992003-11-13 21:59:32 +00001219
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001220 Q. Why the bizarre (net-zero) manipulation of
1221 _PyTrash_delete_nesting around the trashcan macros?
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001222
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001223 A. Some base classes (e.g. list) also use the trashcan mechanism.
1224 The following scenario used to be possible:
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001225
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001226 - suppose the trashcan level is one below the trashcan limit
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001227
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001228 - subtype_dealloc() is called
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001229
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001230 - the trashcan limit is not yet reached, so the trashcan level
1231 is incremented and the code between trashcan begin and end is
1232 executed
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001233
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001234 - this destroys much of the object's contents, including its
1235 slots and __dict__
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001236
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001237 - basedealloc() is called; this is really list_dealloc(), or
1238 some other type which also uses the trashcan macros
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001239
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001240 - the trashcan limit is now reached, so the object is put on the
1241 trashcan's to-be-deleted-later list
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001242
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001243 - basedealloc() returns
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001244
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001245 - subtype_dealloc() decrefs the object's type
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001246
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001247 - subtype_dealloc() returns
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001248
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001249 - later, the trashcan code starts deleting the objects from its
1250 to-be-deleted-later list
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001251
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001252 - subtype_dealloc() is called *AGAIN* for the same object
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001253
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001254 - at the very least (if the destroyed slots and __dict__ don't
1255 cause problems) the object's type gets decref'ed a second
1256 time, which is *BAD*!!!
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001257
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001258 The remedy is to make sure that if the code between trashcan
1259 begin and end in subtype_dealloc() is called, the code between
1260 trashcan begin and end in basedealloc() will also be called.
1261 This is done by decrementing the level after passing into the
1262 trashcan block, and incrementing it just before leaving the
1263 block.
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001264
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001265 But now it's possible that a chain of objects consisting solely
1266 of objects whose deallocator is subtype_dealloc() will defeat
1267 the trashcan mechanism completely: the decremented level means
1268 that the effective level never reaches the limit. Therefore, we
1269 *increment* the level *before* entering the trashcan block, and
1270 matchingly decrement it after leaving. This means the trashcan
1271 code will trigger a little early, but that's no big deal.
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001272
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001273 Q. Are there any live examples of code in need of all this
1274 complexity?
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001275
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001276 A. Yes. See SF bug 668433 for code that crashed (when Python was
1277 compiled in debug mode) before the trashcan level manipulations
1278 were added. For more discussion, see SF patches 581742, 575073
1279 and bug 574207.
1280 */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001281}
1282
Jeremy Hylton938ace62002-07-17 16:30:39 +00001283static PyTypeObject *solid_base(PyTypeObject *type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001284
Tim Peters6d6c1a32001-08-02 04:15:00 +00001285/* type test with subclassing support */
1286
1287int
1288PyType_IsSubtype(PyTypeObject *a, PyTypeObject *b)
1289{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001290 PyObject *mro;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001291
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001292 mro = a->tp_mro;
1293 if (mro != NULL) {
1294 /* Deal with multiple inheritance without recursion
1295 by walking the MRO tuple */
1296 Py_ssize_t i, n;
1297 assert(PyTuple_Check(mro));
1298 n = PyTuple_GET_SIZE(mro);
1299 for (i = 0; i < n; i++) {
1300 if (PyTuple_GET_ITEM(mro, i) == (PyObject *)b)
1301 return 1;
1302 }
1303 return 0;
1304 }
1305 else {
1306 /* a is not completely initilized yet; follow tp_base */
1307 do {
1308 if (a == b)
1309 return 1;
1310 a = a->tp_base;
1311 } while (a != NULL);
1312 return b == &PyBaseObject_Type;
1313 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001314}
1315
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001316/* Internal routines to do a method lookup in the type
Guido van Rossum60718732001-08-28 17:47:51 +00001317 without looking in the instance dictionary
1318 (so we can't use PyObject_GetAttr) but still binding
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001319 it to the instance. The arguments are the object,
Guido van Rossum60718732001-08-28 17:47:51 +00001320 the method name as a C string, and the address of a
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001321 static variable used to cache the interned Python string.
1322
1323 Two variants:
1324
1325 - lookup_maybe() returns NULL without raising an exception
1326 when the _PyType_Lookup() call fails;
1327
1328 - lookup_method() always raises an exception upon errors.
Benjamin Peterson224205f2009-05-08 03:25:19 +00001329
1330 - _PyObject_LookupSpecial() exported for the benefit of other places.
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001331*/
Guido van Rossum60718732001-08-28 17:47:51 +00001332
1333static PyObject *
Benjamin Petersonce798522012-01-22 11:24:29 -05001334lookup_maybe(PyObject *self, _Py_Identifier *attrid)
Guido van Rossum60718732001-08-28 17:47:51 +00001335{
Victor Stinner3c1e4812012-03-26 22:10:51 +02001336 PyObject *res;
Guido van Rossum60718732001-08-28 17:47:51 +00001337
Victor Stinner3c1e4812012-03-26 22:10:51 +02001338 res = _PyType_LookupId(Py_TYPE(self), attrid);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001339 if (res != NULL) {
1340 descrgetfunc f;
1341 if ((f = Py_TYPE(res)->tp_descr_get) == NULL)
1342 Py_INCREF(res);
1343 else
1344 res = f(res, self, (PyObject *)(Py_TYPE(self)));
1345 }
1346 return res;
Guido van Rossum60718732001-08-28 17:47:51 +00001347}
1348
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001349static PyObject *
Benjamin Petersonce798522012-01-22 11:24:29 -05001350lookup_method(PyObject *self, _Py_Identifier *attrid)
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001351{
Benjamin Petersonce798522012-01-22 11:24:29 -05001352 PyObject *res = lookup_maybe(self, attrid);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001353 if (res == NULL && !PyErr_Occurred())
Benjamin Petersonce798522012-01-22 11:24:29 -05001354 PyErr_SetObject(PyExc_AttributeError, attrid->object);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001355 return res;
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001356}
1357
Benjamin Peterson224205f2009-05-08 03:25:19 +00001358PyObject *
Benjamin Petersonce798522012-01-22 11:24:29 -05001359_PyObject_LookupSpecial(PyObject *self, _Py_Identifier *attrid)
Benjamin Peterson224205f2009-05-08 03:25:19 +00001360{
Benjamin Petersonce798522012-01-22 11:24:29 -05001361 return lookup_maybe(self, attrid);
Benjamin Peterson224205f2009-05-08 03:25:19 +00001362}
1363
Guido van Rossum2730b132001-08-28 18:22:14 +00001364/* A variation of PyObject_CallMethod that uses lookup_method()
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001365 instead of PyObject_GetAttrString(). This uses the same convention
Guido van Rossum2730b132001-08-28 18:22:14 +00001366 as lookup_method to cache the interned name string object. */
1367
Neil Schemenauerf23473f2001-10-21 22:28:58 +00001368static PyObject *
Benjamin Petersonce798522012-01-22 11:24:29 -05001369call_method(PyObject *o, _Py_Identifier *nameid, char *format, ...)
Guido van Rossum2730b132001-08-28 18:22:14 +00001370{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001371 va_list va;
1372 PyObject *args, *func = 0, *retval;
1373 va_start(va, format);
Guido van Rossum2730b132001-08-28 18:22:14 +00001374
Benjamin Petersonce798522012-01-22 11:24:29 -05001375 func = lookup_maybe(o, nameid);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001376 if (func == NULL) {
1377 va_end(va);
1378 if (!PyErr_Occurred())
Benjamin Petersonce798522012-01-22 11:24:29 -05001379 PyErr_SetObject(PyExc_AttributeError, nameid->object);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001380 return NULL;
1381 }
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001382
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001383 if (format && *format)
1384 args = Py_VaBuildValue(format, va);
1385 else
1386 args = PyTuple_New(0);
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001387
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001388 va_end(va);
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001389
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001390 if (args == NULL)
1391 return NULL;
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001392
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001393 assert(PyTuple_Check(args));
1394 retval = PyObject_Call(func, args, NULL);
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001395
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001396 Py_DECREF(args);
1397 Py_DECREF(func);
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001398
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001399 return retval;
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001400}
1401
1402/* Clone of call_method() that returns NotImplemented when the lookup fails. */
1403
Neil Schemenauerf23473f2001-10-21 22:28:58 +00001404static PyObject *
Benjamin Petersonce798522012-01-22 11:24:29 -05001405call_maybe(PyObject *o, _Py_Identifier *nameid, char *format, ...)
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001406{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001407 va_list va;
1408 PyObject *args, *func = 0, *retval;
1409 va_start(va, format);
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001410
Benjamin Petersonce798522012-01-22 11:24:29 -05001411 func = lookup_maybe(o, nameid);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001412 if (func == NULL) {
1413 va_end(va);
Brian Curtindfc80e32011-08-10 20:28:54 -05001414 if (!PyErr_Occurred())
1415 Py_RETURN_NOTIMPLEMENTED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001416 return NULL;
1417 }
Guido van Rossum2730b132001-08-28 18:22:14 +00001418
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001419 if (format && *format)
1420 args = Py_VaBuildValue(format, va);
1421 else
1422 args = PyTuple_New(0);
Guido van Rossum2730b132001-08-28 18:22:14 +00001423
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001424 va_end(va);
Guido van Rossum2730b132001-08-28 18:22:14 +00001425
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001426 if (args == NULL)
1427 return NULL;
Guido van Rossum2730b132001-08-28 18:22:14 +00001428
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001429 assert(PyTuple_Check(args));
1430 retval = PyObject_Call(func, args, NULL);
Guido van Rossum2730b132001-08-28 18:22:14 +00001431
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001432 Py_DECREF(args);
1433 Py_DECREF(func);
Guido van Rossum2730b132001-08-28 18:22:14 +00001434
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001435 return retval;
Guido van Rossum2730b132001-08-28 18:22:14 +00001436}
1437
Tim Petersea7f75d2002-12-07 21:39:16 +00001438/*
Guido van Rossum1f121312002-11-14 19:49:16 +00001439 Method resolution order algorithm C3 described in
1440 "A Monotonic Superclass Linearization for Dylan",
1441 by Kim Barrett, Bob Cassel, Paul Haahr,
Tim Petersea7f75d2002-12-07 21:39:16 +00001442 David A. Moon, Keith Playford, and P. Tucker Withington.
Guido van Rossum1f121312002-11-14 19:49:16 +00001443 (OOPSLA 1996)
1444
Guido van Rossum98f33732002-11-25 21:36:54 +00001445 Some notes about the rules implied by C3:
1446
Tim Petersea7f75d2002-12-07 21:39:16 +00001447 No duplicate bases.
Guido van Rossum98f33732002-11-25 21:36:54 +00001448 It isn't legal to repeat a class in a list of base classes.
1449
1450 The next three properties are the 3 constraints in "C3".
1451
Tim Petersea7f75d2002-12-07 21:39:16 +00001452 Local precendece order.
Guido van Rossum98f33732002-11-25 21:36:54 +00001453 If A precedes B in C's MRO, then A will precede B in the MRO of all
1454 subclasses of C.
1455
1456 Monotonicity.
1457 The MRO of a class must be an extension without reordering of the
1458 MRO of each of its superclasses.
1459
1460 Extended Precedence Graph (EPG).
1461 Linearization is consistent if there is a path in the EPG from
1462 each class to all its successors in the linearization. See
1463 the paper for definition of EPG.
Guido van Rossum1f121312002-11-14 19:49:16 +00001464 */
1465
Tim Petersea7f75d2002-12-07 21:39:16 +00001466static int
Guido van Rossum1f121312002-11-14 19:49:16 +00001467tail_contains(PyObject *list, int whence, PyObject *o) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001468 Py_ssize_t j, size;
1469 size = PyList_GET_SIZE(list);
Guido van Rossum1f121312002-11-14 19:49:16 +00001470
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001471 for (j = whence+1; j < size; j++) {
1472 if (PyList_GET_ITEM(list, j) == o)
1473 return 1;
1474 }
1475 return 0;
Guido van Rossum1f121312002-11-14 19:49:16 +00001476}
1477
Guido van Rossum98f33732002-11-25 21:36:54 +00001478static PyObject *
1479class_name(PyObject *cls)
1480{
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001481 PyObject *name = _PyObject_GetAttrId(cls, &PyId___name__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001482 if (name == NULL) {
1483 PyErr_Clear();
1484 Py_XDECREF(name);
1485 name = PyObject_Repr(cls);
1486 }
1487 if (name == NULL)
1488 return NULL;
1489 if (!PyUnicode_Check(name)) {
1490 Py_DECREF(name);
1491 return NULL;
1492 }
1493 return name;
Guido van Rossum98f33732002-11-25 21:36:54 +00001494}
1495
1496static int
1497check_duplicates(PyObject *list)
1498{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001499 Py_ssize_t i, j, n;
1500 /* Let's use a quadratic time algorithm,
1501 assuming that the bases lists is short.
1502 */
1503 n = PyList_GET_SIZE(list);
1504 for (i = 0; i < n; i++) {
1505 PyObject *o = PyList_GET_ITEM(list, i);
1506 for (j = i + 1; j < n; j++) {
1507 if (PyList_GET_ITEM(list, j) == o) {
1508 o = class_name(o);
1509 if (o != NULL) {
1510 PyErr_Format(PyExc_TypeError,
1511 "duplicate base class %U",
1512 o);
1513 Py_DECREF(o);
1514 } else {
1515 PyErr_SetString(PyExc_TypeError,
1516 "duplicate base class");
1517 }
1518 return -1;
1519 }
1520 }
1521 }
1522 return 0;
Guido van Rossum98f33732002-11-25 21:36:54 +00001523}
1524
1525/* Raise a TypeError for an MRO order disagreement.
1526
1527 It's hard to produce a good error message. In the absence of better
1528 insight into error reporting, report the classes that were candidates
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001529 to be put next into the MRO. There is some conflict between the
Guido van Rossum98f33732002-11-25 21:36:54 +00001530 order in which they should be put in the MRO, but it's hard to
1531 diagnose what constraint can't be satisfied.
1532*/
1533
1534static void
1535set_mro_error(PyObject *to_merge, int *remain)
1536{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001537 Py_ssize_t i, n, off, to_merge_size;
1538 char buf[1000];
1539 PyObject *k, *v;
1540 PyObject *set = PyDict_New();
1541 if (!set) return;
Guido van Rossum98f33732002-11-25 21:36:54 +00001542
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001543 to_merge_size = PyList_GET_SIZE(to_merge);
1544 for (i = 0; i < to_merge_size; i++) {
1545 PyObject *L = PyList_GET_ITEM(to_merge, i);
1546 if (remain[i] < PyList_GET_SIZE(L)) {
1547 PyObject *c = PyList_GET_ITEM(L, remain[i]);
1548 if (PyDict_SetItem(set, c, Py_None) < 0) {
1549 Py_DECREF(set);
1550 return;
1551 }
1552 }
1553 }
1554 n = PyDict_Size(set);
Guido van Rossum98f33732002-11-25 21:36:54 +00001555
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001556 off = PyOS_snprintf(buf, sizeof(buf), "Cannot create a \
Raymond Hettingerf394df42003-04-06 19:13:41 +00001557consistent method resolution\norder (MRO) for bases");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001558 i = 0;
1559 while (PyDict_Next(set, &i, &k, &v) && (size_t)off < sizeof(buf)) {
1560 PyObject *name = class_name(k);
Victor Stinnere5f99f32010-05-19 01:42:46 +00001561 char *name_str;
1562 if (name != NULL) {
1563 name_str = _PyUnicode_AsString(name);
1564 if (name_str == NULL)
Victor Stinnerba644a62010-05-19 01:50:45 +00001565 name_str = "?";
Victor Stinnere5f99f32010-05-19 01:42:46 +00001566 } else
Victor Stinnerba644a62010-05-19 01:50:45 +00001567 name_str = "?";
Victor Stinnere5f99f32010-05-19 01:42:46 +00001568 off += PyOS_snprintf(buf + off, sizeof(buf) - off, " %s", name_str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001569 Py_XDECREF(name);
1570 if (--n && (size_t)(off+1) < sizeof(buf)) {
1571 buf[off++] = ',';
1572 buf[off] = '\0';
1573 }
1574 }
1575 PyErr_SetString(PyExc_TypeError, buf);
1576 Py_DECREF(set);
Guido van Rossum98f33732002-11-25 21:36:54 +00001577}
1578
Tim Petersea7f75d2002-12-07 21:39:16 +00001579static int
Guido van Rossum1f121312002-11-14 19:49:16 +00001580pmerge(PyObject *acc, PyObject* to_merge) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001581 Py_ssize_t i, j, to_merge_size, empty_cnt;
1582 int *remain;
1583 int ok;
Tim Petersea7f75d2002-12-07 21:39:16 +00001584
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001585 to_merge_size = PyList_GET_SIZE(to_merge);
Guido van Rossum1f121312002-11-14 19:49:16 +00001586
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001587 /* remain stores an index into each sublist of to_merge.
1588 remain[i] is the index of the next base in to_merge[i]
1589 that is not included in acc.
1590 */
1591 remain = (int *)PyMem_MALLOC(SIZEOF_INT*to_merge_size);
Victor Stinnera41f0852013-07-12 00:42:14 +02001592 if (remain == NULL) {
1593 PyErr_NoMemory();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001594 return -1;
Victor Stinnera41f0852013-07-12 00:42:14 +02001595 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001596 for (i = 0; i < to_merge_size; i++)
1597 remain[i] = 0;
Guido van Rossum1f121312002-11-14 19:49:16 +00001598
1599 again:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001600 empty_cnt = 0;
1601 for (i = 0; i < to_merge_size; i++) {
1602 PyObject *candidate;
Tim Petersea7f75d2002-12-07 21:39:16 +00001603
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001604 PyObject *cur_list = PyList_GET_ITEM(to_merge, i);
Guido van Rossum1f121312002-11-14 19:49:16 +00001605
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001606 if (remain[i] >= PyList_GET_SIZE(cur_list)) {
1607 empty_cnt++;
1608 continue;
1609 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001610
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001611 /* Choose next candidate for MRO.
Guido van Rossum98f33732002-11-25 21:36:54 +00001612
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001613 The input sequences alone can determine the choice.
1614 If not, choose the class which appears in the MRO
1615 of the earliest direct superclass of the new class.
1616 */
Guido van Rossum98f33732002-11-25 21:36:54 +00001617
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001618 candidate = PyList_GET_ITEM(cur_list, remain[i]);
1619 for (j = 0; j < to_merge_size; j++) {
1620 PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
1621 if (tail_contains(j_lst, remain[j], candidate)) {
1622 goto skip; /* continue outer loop */
1623 }
1624 }
1625 ok = PyList_Append(acc, candidate);
1626 if (ok < 0) {
Victor Stinnera41f0852013-07-12 00:42:14 +02001627 PyMem_FREE(remain);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001628 return -1;
1629 }
1630 for (j = 0; j < to_merge_size; j++) {
1631 PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
1632 if (remain[j] < PyList_GET_SIZE(j_lst) &&
1633 PyList_GET_ITEM(j_lst, remain[j]) == candidate) {
1634 remain[j]++;
1635 }
1636 }
1637 goto again;
1638 skip: ;
1639 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001640
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001641 if (empty_cnt == to_merge_size) {
1642 PyMem_FREE(remain);
1643 return 0;
1644 }
1645 set_mro_error(to_merge, remain);
1646 PyMem_FREE(remain);
1647 return -1;
Guido van Rossum1f121312002-11-14 19:49:16 +00001648}
1649
Tim Peters6d6c1a32001-08-02 04:15:00 +00001650static PyObject *
1651mro_implementation(PyTypeObject *type)
1652{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001653 Py_ssize_t i, n;
1654 int ok;
1655 PyObject *bases, *result;
1656 PyObject *to_merge, *bases_aslist;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001657
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001658 if (type->tp_dict == NULL) {
1659 if (PyType_Ready(type) < 0)
1660 return NULL;
1661 }
Guido van Rossum63517572002-06-18 16:44:57 +00001662
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001663 /* Find a superclass linearization that honors the constraints
1664 of the explicit lists of bases and the constraints implied by
1665 each base class.
Guido van Rossum98f33732002-11-25 21:36:54 +00001666
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001667 to_merge is a list of lists, where each list is a superclass
1668 linearization implied by a base class. The last element of
1669 to_merge is the declared list of bases.
1670 */
Guido van Rossum98f33732002-11-25 21:36:54 +00001671
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001672 bases = type->tp_bases;
1673 n = PyTuple_GET_SIZE(bases);
Guido van Rossum1f121312002-11-14 19:49:16 +00001674
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001675 to_merge = PyList_New(n+1);
1676 if (to_merge == NULL)
1677 return NULL;
Guido van Rossum1f121312002-11-14 19:49:16 +00001678
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001679 for (i = 0; i < n; i++) {
1680 PyObject *base = PyTuple_GET_ITEM(bases, i);
1681 PyObject *parentMRO;
1682 parentMRO = PySequence_List(((PyTypeObject*)base)->tp_mro);
1683 if (parentMRO == NULL) {
1684 Py_DECREF(to_merge);
1685 return NULL;
1686 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001687
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001688 PyList_SET_ITEM(to_merge, i, parentMRO);
1689 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001690
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001691 bases_aslist = PySequence_List(bases);
1692 if (bases_aslist == NULL) {
1693 Py_DECREF(to_merge);
1694 return NULL;
1695 }
1696 /* This is just a basic sanity check. */
1697 if (check_duplicates(bases_aslist) < 0) {
1698 Py_DECREF(to_merge);
1699 Py_DECREF(bases_aslist);
1700 return NULL;
1701 }
1702 PyList_SET_ITEM(to_merge, n, bases_aslist);
Guido van Rossum1f121312002-11-14 19:49:16 +00001703
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001704 result = Py_BuildValue("[O]", (PyObject *)type);
1705 if (result == NULL) {
1706 Py_DECREF(to_merge);
1707 return NULL;
1708 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001709
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001710 ok = pmerge(result, to_merge);
1711 Py_DECREF(to_merge);
1712 if (ok < 0) {
1713 Py_DECREF(result);
1714 return NULL;
1715 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001716
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001717 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001718}
1719
1720static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001721mro_external(PyObject *self)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001722{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001723 PyTypeObject *type = (PyTypeObject *)self;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001724
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001725 return mro_implementation(type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001726}
1727
1728static int
1729mro_internal(PyTypeObject *type)
1730{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001731 PyObject *mro, *result, *tuple;
1732 int checkit = 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001733
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001734 if (Py_TYPE(type) == &PyType_Type) {
1735 result = mro_implementation(type);
1736 }
1737 else {
Benjamin Petersonce798522012-01-22 11:24:29 -05001738 _Py_IDENTIFIER(mro);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001739 checkit = 1;
Benjamin Petersonce798522012-01-22 11:24:29 -05001740 mro = lookup_method((PyObject *)type, &PyId_mro);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001741 if (mro == NULL)
1742 return -1;
1743 result = PyObject_CallObject(mro, NULL);
1744 Py_DECREF(mro);
1745 }
1746 if (result == NULL)
1747 return -1;
1748 tuple = PySequence_Tuple(result);
1749 Py_DECREF(result);
1750 if (tuple == NULL)
1751 return -1;
1752 if (checkit) {
1753 Py_ssize_t i, len;
1754 PyObject *cls;
1755 PyTypeObject *solid;
Armin Rigo037d1e02005-12-29 17:07:39 +00001756
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001757 solid = solid_base(type);
Armin Rigo037d1e02005-12-29 17:07:39 +00001758
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001759 len = PyTuple_GET_SIZE(tuple);
Armin Rigo037d1e02005-12-29 17:07:39 +00001760
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001761 for (i = 0; i < len; i++) {
1762 PyTypeObject *t;
1763 cls = PyTuple_GET_ITEM(tuple, i);
1764 if (!PyType_Check(cls)) {
1765 PyErr_Format(PyExc_TypeError,
1766 "mro() returned a non-class ('%.500s')",
1767 Py_TYPE(cls)->tp_name);
1768 Py_DECREF(tuple);
1769 return -1;
1770 }
1771 t = (PyTypeObject*)cls;
1772 if (!PyType_IsSubtype(solid, solid_base(t))) {
1773 PyErr_Format(PyExc_TypeError,
1774 "mro() returned base with unsuitable layout ('%.500s')",
1775 t->tp_name);
1776 Py_DECREF(tuple);
1777 return -1;
1778 }
1779 }
1780 }
1781 type->tp_mro = tuple;
Christian Heimesa62da1d2008-01-12 19:39:10 +00001782
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001783 type_mro_modified(type, type->tp_mro);
Florent Xiclunaaa6c1d22011-12-12 18:54:29 +01001784 /* corner case: the super class might have been hidden
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001785 from the custom MRO */
1786 type_mro_modified(type, type->tp_bases);
Christian Heimesa62da1d2008-01-12 19:39:10 +00001787
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001788 PyType_Modified(type);
Christian Heimesa62da1d2008-01-12 19:39:10 +00001789
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001790 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001791}
1792
1793
1794/* Calculate the best base amongst multiple base classes.
1795 This is the first one that's on the path to the "solid base". */
1796
1797static PyTypeObject *
1798best_base(PyObject *bases)
1799{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001800 Py_ssize_t i, n;
1801 PyTypeObject *base, *winner, *candidate, *base_i;
1802 PyObject *base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001803
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001804 assert(PyTuple_Check(bases));
1805 n = PyTuple_GET_SIZE(bases);
1806 assert(n > 0);
1807 base = NULL;
1808 winner = NULL;
1809 for (i = 0; i < n; i++) {
1810 base_proto = PyTuple_GET_ITEM(bases, i);
1811 if (!PyType_Check(base_proto)) {
1812 PyErr_SetString(
1813 PyExc_TypeError,
1814 "bases must be types");
1815 return NULL;
1816 }
1817 base_i = (PyTypeObject *)base_proto;
1818 if (base_i->tp_dict == NULL) {
1819 if (PyType_Ready(base_i) < 0)
1820 return NULL;
1821 }
1822 candidate = solid_base(base_i);
1823 if (winner == NULL) {
1824 winner = candidate;
1825 base = base_i;
1826 }
1827 else if (PyType_IsSubtype(winner, candidate))
1828 ;
1829 else if (PyType_IsSubtype(candidate, winner)) {
1830 winner = candidate;
1831 base = base_i;
1832 }
1833 else {
1834 PyErr_SetString(
1835 PyExc_TypeError,
1836 "multiple bases have "
1837 "instance lay-out conflict");
1838 return NULL;
1839 }
1840 }
Florent Xiclunaaa6c1d22011-12-12 18:54:29 +01001841 assert (base != NULL);
1842
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001843 return base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001844}
1845
1846static int
1847extra_ivars(PyTypeObject *type, PyTypeObject *base)
1848{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001849 size_t t_size = type->tp_basicsize;
1850 size_t b_size = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001851
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001852 assert(t_size >= b_size); /* Else type smaller than base! */
1853 if (type->tp_itemsize || base->tp_itemsize) {
1854 /* If itemsize is involved, stricter rules */
1855 return t_size != b_size ||
1856 type->tp_itemsize != base->tp_itemsize;
1857 }
1858 if (type->tp_weaklistoffset && base->tp_weaklistoffset == 0 &&
1859 type->tp_weaklistoffset + sizeof(PyObject *) == t_size &&
1860 type->tp_flags & Py_TPFLAGS_HEAPTYPE)
1861 t_size -= sizeof(PyObject *);
1862 if (type->tp_dictoffset && base->tp_dictoffset == 0 &&
1863 type->tp_dictoffset + sizeof(PyObject *) == t_size &&
1864 type->tp_flags & Py_TPFLAGS_HEAPTYPE)
1865 t_size -= sizeof(PyObject *);
Guido van Rossum9676b222001-08-17 20:32:36 +00001866
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001867 return t_size != b_size;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001868}
1869
1870static PyTypeObject *
1871solid_base(PyTypeObject *type)
1872{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001873 PyTypeObject *base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001874
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001875 if (type->tp_base)
1876 base = solid_base(type->tp_base);
1877 else
1878 base = &PyBaseObject_Type;
1879 if (extra_ivars(type, base))
1880 return type;
1881 else
1882 return base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001883}
1884
Jeremy Hylton938ace62002-07-17 16:30:39 +00001885static void object_dealloc(PyObject *);
1886static int object_init(PyObject *, PyObject *, PyObject *);
1887static int update_slot(PyTypeObject *, PyObject *);
1888static void fixup_slot_dispatchers(PyTypeObject *);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001889
Guido van Rossum360e4b82007-05-14 22:51:27 +00001890/*
1891 * Helpers for __dict__ descriptor. We don't want to expose the dicts
1892 * inherited from various builtin types. The builtin base usually provides
1893 * its own __dict__ descriptor, so we use that when we can.
1894 */
1895static PyTypeObject *
1896get_builtin_base_with_dict(PyTypeObject *type)
1897{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001898 while (type->tp_base != NULL) {
1899 if (type->tp_dictoffset != 0 &&
1900 !(type->tp_flags & Py_TPFLAGS_HEAPTYPE))
1901 return type;
1902 type = type->tp_base;
1903 }
1904 return NULL;
Guido van Rossum360e4b82007-05-14 22:51:27 +00001905}
1906
1907static PyObject *
1908get_dict_descriptor(PyTypeObject *type)
1909{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001910 PyObject *descr;
Guido van Rossum360e4b82007-05-14 22:51:27 +00001911
Victor Stinner3c1e4812012-03-26 22:10:51 +02001912 descr = _PyType_LookupId(type, &PyId___dict__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001913 if (descr == NULL || !PyDescr_IsData(descr))
1914 return NULL;
Guido van Rossum360e4b82007-05-14 22:51:27 +00001915
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001916 return descr;
Guido van Rossum360e4b82007-05-14 22:51:27 +00001917}
1918
1919static void
1920raise_dict_descr_error(PyObject *obj)
1921{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001922 PyErr_Format(PyExc_TypeError,
1923 "this __dict__ descriptor does not support "
1924 "'%.200s' objects", Py_TYPE(obj)->tp_name);
Guido van Rossum360e4b82007-05-14 22:51:27 +00001925}
1926
Tim Peters6d6c1a32001-08-02 04:15:00 +00001927static PyObject *
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001928subtype_dict(PyObject *obj, void *context)
1929{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001930 PyTypeObject *base;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001931
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001932 base = get_builtin_base_with_dict(Py_TYPE(obj));
1933 if (base != NULL) {
1934 descrgetfunc func;
1935 PyObject *descr = get_dict_descriptor(base);
1936 if (descr == NULL) {
1937 raise_dict_descr_error(obj);
1938 return NULL;
1939 }
1940 func = Py_TYPE(descr)->tp_descr_get;
1941 if (func == NULL) {
1942 raise_dict_descr_error(obj);
1943 return NULL;
1944 }
1945 return func(descr, obj, (PyObject *)(Py_TYPE(obj)));
1946 }
Benjamin Peterson8eb12692012-02-19 19:59:10 -05001947 return PyObject_GenericGetDict(obj, context);
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001948}
1949
Guido van Rossum6661be32001-10-26 04:26:12 +00001950static int
1951subtype_setdict(PyObject *obj, PyObject *value, void *context)
1952{
Benjamin Peterson8eb12692012-02-19 19:59:10 -05001953 PyObject *dict, **dictptr;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001954 PyTypeObject *base;
Guido van Rossum6661be32001-10-26 04:26:12 +00001955
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001956 base = get_builtin_base_with_dict(Py_TYPE(obj));
1957 if (base != NULL) {
1958 descrsetfunc func;
1959 PyObject *descr = get_dict_descriptor(base);
1960 if (descr == NULL) {
1961 raise_dict_descr_error(obj);
1962 return -1;
1963 }
1964 func = Py_TYPE(descr)->tp_descr_set;
1965 if (func == NULL) {
1966 raise_dict_descr_error(obj);
1967 return -1;
1968 }
1969 return func(descr, obj, value);
1970 }
Benjamin Peterson8eb12692012-02-19 19:59:10 -05001971 /* Almost like PyObject_GenericSetDict, but allow __dict__ to be deleted. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001972 dictptr = _PyObject_GetDictPtr(obj);
1973 if (dictptr == NULL) {
1974 PyErr_SetString(PyExc_AttributeError,
1975 "This object has no __dict__");
1976 return -1;
1977 }
Benjamin Peterson006c5a22012-02-19 20:36:12 -05001978 if (value != NULL && !PyDict_Check(value)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001979 PyErr_Format(PyExc_TypeError,
1980 "__dict__ must be set to a dictionary, "
1981 "not a '%.200s'", Py_TYPE(value)->tp_name);
1982 return -1;
1983 }
1984 dict = *dictptr;
1985 Py_XINCREF(value);
1986 *dictptr = value;
1987 Py_XDECREF(dict);
1988 return 0;
Guido van Rossum6661be32001-10-26 04:26:12 +00001989}
1990
Guido van Rossumad47da02002-08-12 19:05:44 +00001991static PyObject *
1992subtype_getweakref(PyObject *obj, void *context)
1993{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001994 PyObject **weaklistptr;
1995 PyObject *result;
Guido van Rossumad47da02002-08-12 19:05:44 +00001996
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001997 if (Py_TYPE(obj)->tp_weaklistoffset == 0) {
1998 PyErr_SetString(PyExc_AttributeError,
1999 "This object has no __weakref__");
2000 return NULL;
2001 }
2002 assert(Py_TYPE(obj)->tp_weaklistoffset > 0);
2003 assert(Py_TYPE(obj)->tp_weaklistoffset + sizeof(PyObject *) <=
2004 (size_t)(Py_TYPE(obj)->tp_basicsize));
2005 weaklistptr = (PyObject **)
2006 ((char *)obj + Py_TYPE(obj)->tp_weaklistoffset);
2007 if (*weaklistptr == NULL)
2008 result = Py_None;
2009 else
2010 result = *weaklistptr;
2011 Py_INCREF(result);
2012 return result;
Guido van Rossumad47da02002-08-12 19:05:44 +00002013}
2014
Guido van Rossum373c7412003-01-07 13:41:37 +00002015/* Three variants on the subtype_getsets list. */
2016
2017static PyGetSetDef subtype_getsets_full[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002018 {"__dict__", subtype_dict, subtype_setdict,
2019 PyDoc_STR("dictionary for instance variables (if defined)")},
2020 {"__weakref__", subtype_getweakref, NULL,
2021 PyDoc_STR("list of weak references to the object (if defined)")},
2022 {0}
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00002023};
2024
Guido van Rossum373c7412003-01-07 13:41:37 +00002025static PyGetSetDef subtype_getsets_dict_only[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002026 {"__dict__", subtype_dict, subtype_setdict,
2027 PyDoc_STR("dictionary for instance variables (if defined)")},
2028 {0}
Guido van Rossum373c7412003-01-07 13:41:37 +00002029};
2030
2031static PyGetSetDef subtype_getsets_weakref_only[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002032 {"__weakref__", subtype_getweakref, NULL,
2033 PyDoc_STR("list of weak references to the object (if defined)")},
2034 {0}
Guido van Rossum373c7412003-01-07 13:41:37 +00002035};
2036
Guido van Rossum9923ffe2002-06-04 19:52:53 +00002037static int
2038valid_identifier(PyObject *s)
2039{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002040 if (!PyUnicode_Check(s)) {
2041 PyErr_Format(PyExc_TypeError,
2042 "__slots__ items must be strings, not '%.200s'",
2043 Py_TYPE(s)->tp_name);
2044 return 0;
2045 }
2046 if (!PyUnicode_IsIdentifier(s)) {
2047 PyErr_SetString(PyExc_TypeError,
2048 "__slots__ must be identifiers");
2049 return 0;
2050 }
2051 return 1;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00002052}
2053
Guido van Rossumd8faa362007-04-27 19:54:29 +00002054/* Forward */
2055static int
2056object_init(PyObject *self, PyObject *args, PyObject *kwds);
2057
2058static int
2059type_init(PyObject *cls, PyObject *args, PyObject *kwds)
2060{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002061 int res;
Guido van Rossumd8faa362007-04-27 19:54:29 +00002062
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002063 assert(args != NULL && PyTuple_Check(args));
2064 assert(kwds == NULL || PyDict_Check(kwds));
Guido van Rossumd8faa362007-04-27 19:54:29 +00002065
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002066 if (kwds != NULL && PyDict_Check(kwds) && PyDict_Size(kwds) != 0) {
2067 PyErr_SetString(PyExc_TypeError,
2068 "type.__init__() takes no keyword arguments");
2069 return -1;
2070 }
Guido van Rossumd8faa362007-04-27 19:54:29 +00002071
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002072 if (args != NULL && PyTuple_Check(args) &&
2073 (PyTuple_GET_SIZE(args) != 1 && PyTuple_GET_SIZE(args) != 3)) {
2074 PyErr_SetString(PyExc_TypeError,
2075 "type.__init__() takes 1 or 3 arguments");
2076 return -1;
2077 }
Guido van Rossumd8faa362007-04-27 19:54:29 +00002078
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002079 /* Call object.__init__(self) now. */
2080 /* XXX Could call super(type, cls).__init__() but what's the point? */
2081 args = PyTuple_GetSlice(args, 0, 0);
2082 res = object_init(cls, args, NULL);
2083 Py_DECREF(args);
2084 return res;
Guido van Rossumd8faa362007-04-27 19:54:29 +00002085}
2086
Victor Stinner4ca1cf32012-10-30 23:40:45 +01002087unsigned long
Martin v. Löwis738236d2011-02-05 20:35:29 +00002088PyType_GetFlags(PyTypeObject *type)
2089{
2090 return type->tp_flags;
2091}
2092
Nick Coghlande31b192011-10-23 22:04:16 +10002093/* Determine the most derived metatype. */
2094PyTypeObject *
2095_PyType_CalculateMetaclass(PyTypeObject *metatype, PyObject *bases)
2096{
2097 Py_ssize_t i, nbases;
2098 PyTypeObject *winner;
2099 PyObject *tmp;
2100 PyTypeObject *tmptype;
2101
2102 /* Determine the proper metatype to deal with this,
2103 and check for metatype conflicts while we're at it.
2104 Note that if some other metatype wins to contract,
2105 it's possible that its instances are not types. */
2106
2107 nbases = PyTuple_GET_SIZE(bases);
2108 winner = metatype;
2109 for (i = 0; i < nbases; i++) {
2110 tmp = PyTuple_GET_ITEM(bases, i);
2111 tmptype = Py_TYPE(tmp);
2112 if (PyType_IsSubtype(winner, tmptype))
2113 continue;
2114 if (PyType_IsSubtype(tmptype, winner)) {
2115 winner = tmptype;
2116 continue;
2117 }
2118 /* else: */
2119 PyErr_SetString(PyExc_TypeError,
2120 "metaclass conflict: "
2121 "the metaclass of a derived class "
2122 "must be a (non-strict) subclass "
2123 "of the metaclasses of all its bases");
2124 return NULL;
2125 }
2126 return winner;
2127}
2128
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00002129static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00002130type_new(PyTypeObject *metatype, PyObject *args, PyObject *kwds)
2131{
Victor Stinner6f738742012-02-25 01:22:36 +01002132 PyObject *name, *bases = NULL, *orig_dict, *dict = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002133 static char *kwlist[] = {"name", "bases", "dict", 0};
Victor Stinner6f738742012-02-25 01:22:36 +01002134 PyObject *qualname, *slots = NULL, *tmp, *newslots;
2135 PyTypeObject *type = NULL, *base, *tmptype, *winner;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002136 PyHeapTypeObject *et;
2137 PyMemberDef *mp;
2138 Py_ssize_t i, nbases, nslots, slotoffset, add_dict, add_weak;
2139 int j, may_add_dict, may_add_weak;
Victor Stinner3c1e4812012-03-26 22:10:51 +02002140 _Py_IDENTIFIER(__qualname__);
2141 _Py_IDENTIFIER(__slots__);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002142
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002143 assert(args != NULL && PyTuple_Check(args));
2144 assert(kwds == NULL || PyDict_Check(kwds));
Tim Peters3abca122001-10-27 19:37:48 +00002145
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002146 /* Special case: type(x) should return x->ob_type */
2147 {
2148 const Py_ssize_t nargs = PyTuple_GET_SIZE(args);
2149 const Py_ssize_t nkwds = kwds == NULL ? 0 : PyDict_Size(kwds);
Tim Peters3abca122001-10-27 19:37:48 +00002150
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002151 if (PyType_CheckExact(metatype) && nargs == 1 && nkwds == 0) {
2152 PyObject *x = PyTuple_GET_ITEM(args, 0);
2153 Py_INCREF(Py_TYPE(x));
2154 return (PyObject *) Py_TYPE(x);
2155 }
Tim Peters3abca122001-10-27 19:37:48 +00002156
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002157 /* SF bug 475327 -- if that didn't trigger, we need 3
2158 arguments. but PyArg_ParseTupleAndKeywords below may give
2159 a msg saying type() needs exactly 3. */
2160 if (nargs + nkwds != 3) {
2161 PyErr_SetString(PyExc_TypeError,
2162 "type() takes 1 or 3 arguments");
2163 return NULL;
2164 }
2165 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002166
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002167 /* Check arguments: (name, bases, dict) */
2168 if (!PyArg_ParseTupleAndKeywords(args, kwds, "UO!O!:type", kwlist,
2169 &name,
2170 &PyTuple_Type, &bases,
Victor Stinner6f738742012-02-25 01:22:36 +01002171 &PyDict_Type, &orig_dict))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002172 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002173
Nick Coghlande31b192011-10-23 22:04:16 +10002174 /* Determine the proper metatype to deal with this: */
2175 winner = _PyType_CalculateMetaclass(metatype, bases);
2176 if (winner == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002177 return NULL;
2178 }
Nick Coghlande31b192011-10-23 22:04:16 +10002179
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002180 if (winner != metatype) {
2181 if (winner->tp_new != type_new) /* Pass it to the winner */
2182 return winner->tp_new(winner, args, kwds);
2183 metatype = winner;
2184 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002185
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002186 /* Adjust for empty tuple bases */
Nick Coghlande31b192011-10-23 22:04:16 +10002187 nbases = PyTuple_GET_SIZE(bases);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002188 if (nbases == 0) {
2189 bases = PyTuple_Pack(1, &PyBaseObject_Type);
2190 if (bases == NULL)
Victor Stinner6f738742012-02-25 01:22:36 +01002191 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002192 nbases = 1;
2193 }
2194 else
2195 Py_INCREF(bases);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002196
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002197 /* Calculate best base, and check that all bases are type objects */
2198 base = best_base(bases);
2199 if (base == NULL) {
Victor Stinner6f738742012-02-25 01:22:36 +01002200 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002201 }
2202 if (!PyType_HasFeature(base, Py_TPFLAGS_BASETYPE)) {
2203 PyErr_Format(PyExc_TypeError,
2204 "type '%.100s' is not an acceptable base type",
2205 base->tp_name);
Victor Stinner6f738742012-02-25 01:22:36 +01002206 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002207 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002208
Victor Stinner6f738742012-02-25 01:22:36 +01002209 dict = PyDict_Copy(orig_dict);
2210 if (dict == NULL)
2211 goto error;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002212
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002213 /* Check for a __slots__ sequence variable in dict, and count it */
Victor Stinner3c1e4812012-03-26 22:10:51 +02002214 slots = _PyDict_GetItemId(dict, &PyId___slots__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002215 nslots = 0;
2216 add_dict = 0;
2217 add_weak = 0;
2218 may_add_dict = base->tp_dictoffset == 0;
2219 may_add_weak = base->tp_weaklistoffset == 0 && base->tp_itemsize == 0;
2220 if (slots == NULL) {
2221 if (may_add_dict) {
2222 add_dict++;
2223 }
2224 if (may_add_weak) {
2225 add_weak++;
2226 }
2227 }
2228 else {
2229 /* Have slots */
Guido van Rossumad47da02002-08-12 19:05:44 +00002230
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002231 /* Make it into a tuple */
2232 if (PyUnicode_Check(slots))
2233 slots = PyTuple_Pack(1, slots);
2234 else
2235 slots = PySequence_Tuple(slots);
Victor Stinner6f738742012-02-25 01:22:36 +01002236 if (slots == NULL)
2237 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002238 assert(PyTuple_Check(slots));
Guido van Rossumad47da02002-08-12 19:05:44 +00002239
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002240 /* Are slots allowed? */
2241 nslots = PyTuple_GET_SIZE(slots);
2242 if (nslots > 0 && base->tp_itemsize != 0) {
2243 PyErr_Format(PyExc_TypeError,
2244 "nonempty __slots__ "
2245 "not supported for subtype of '%s'",
2246 base->tp_name);
Victor Stinner6f738742012-02-25 01:22:36 +01002247 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002248 }
Guido van Rossumad47da02002-08-12 19:05:44 +00002249
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002250 /* Check for valid slot names and two special cases */
2251 for (i = 0; i < nslots; i++) {
2252 PyObject *tmp = PyTuple_GET_ITEM(slots, i);
2253 if (!valid_identifier(tmp))
Victor Stinner6f738742012-02-25 01:22:36 +01002254 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002255 assert(PyUnicode_Check(tmp));
Victor Stinnerad14ccd2013-11-07 00:46:04 +01002256 if (_PyUnicode_CompareWithId(tmp, &PyId___dict__) == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002257 if (!may_add_dict || add_dict) {
2258 PyErr_SetString(PyExc_TypeError,
2259 "__dict__ slot disallowed: "
2260 "we already got one");
Victor Stinner6f738742012-02-25 01:22:36 +01002261 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002262 }
2263 add_dict++;
2264 }
2265 if (PyUnicode_CompareWithASCIIString(tmp, "__weakref__") == 0) {
2266 if (!may_add_weak || add_weak) {
2267 PyErr_SetString(PyExc_TypeError,
2268 "__weakref__ slot disallowed: "
2269 "either we already got one, "
2270 "or __itemsize__ != 0");
Victor Stinner6f738742012-02-25 01:22:36 +01002271 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002272 }
2273 add_weak++;
2274 }
2275 }
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00002276
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002277 /* Copy slots into a list, mangle names and sort them.
2278 Sorted names are needed for __class__ assignment.
2279 Convert them back to tuple at the end.
2280 */
2281 newslots = PyList_New(nslots - add_dict - add_weak);
2282 if (newslots == NULL)
Victor Stinner6f738742012-02-25 01:22:36 +01002283 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002284 for (i = j = 0; i < nslots; i++) {
2285 tmp = PyTuple_GET_ITEM(slots, i);
2286 if ((add_dict &&
Victor Stinnerad14ccd2013-11-07 00:46:04 +01002287 _PyUnicode_CompareWithId(tmp, &PyId___dict__) == 0) ||
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002288 (add_weak &&
2289 PyUnicode_CompareWithASCIIString(tmp, "__weakref__") == 0))
2290 continue;
2291 tmp =_Py_Mangle(name, tmp);
Benjamin Petersonae13c882011-08-16 22:26:48 -05002292 if (!tmp) {
2293 Py_DECREF(newslots);
Victor Stinner6f738742012-02-25 01:22:36 +01002294 goto error;
Benjamin Petersonae13c882011-08-16 22:26:48 -05002295 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002296 PyList_SET_ITEM(newslots, j, tmp);
Benjamin Petersonc4085c82011-08-16 18:53:26 -05002297 if (PyDict_GetItem(dict, tmp)) {
2298 PyErr_Format(PyExc_ValueError,
2299 "%R in __slots__ conflicts with class variable",
2300 tmp);
Benjamin Petersond17cefc2011-08-16 22:28:23 -05002301 Py_DECREF(newslots);
Victor Stinner6f738742012-02-25 01:22:36 +01002302 goto error;
Benjamin Petersonc4085c82011-08-16 18:53:26 -05002303 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002304 j++;
2305 }
2306 assert(j == nslots - add_dict - add_weak);
2307 nslots = j;
Victor Stinner6f738742012-02-25 01:22:36 +01002308 Py_CLEAR(slots);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002309 if (PyList_Sort(newslots) == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002310 Py_DECREF(newslots);
Victor Stinner6f738742012-02-25 01:22:36 +01002311 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002312 }
2313 slots = PyList_AsTuple(newslots);
2314 Py_DECREF(newslots);
Victor Stinner6f738742012-02-25 01:22:36 +01002315 if (slots == NULL)
2316 goto error;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00002317
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002318 /* Secondary bases may provide weakrefs or dict */
2319 if (nbases > 1 &&
2320 ((may_add_dict && !add_dict) ||
2321 (may_add_weak && !add_weak))) {
2322 for (i = 0; i < nbases; i++) {
2323 tmp = PyTuple_GET_ITEM(bases, i);
2324 if (tmp == (PyObject *)base)
2325 continue; /* Skip primary base */
2326 assert(PyType_Check(tmp));
2327 tmptype = (PyTypeObject *)tmp;
2328 if (may_add_dict && !add_dict &&
2329 tmptype->tp_dictoffset != 0)
2330 add_dict++;
2331 if (may_add_weak && !add_weak &&
2332 tmptype->tp_weaklistoffset != 0)
2333 add_weak++;
2334 if (may_add_dict && !add_dict)
2335 continue;
2336 if (may_add_weak && !add_weak)
2337 continue;
2338 /* Nothing more to check */
2339 break;
2340 }
2341 }
2342 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002343
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002344 /* Allocate the type object */
2345 type = (PyTypeObject *)metatype->tp_alloc(metatype, nslots);
Victor Stinner6f738742012-02-25 01:22:36 +01002346 if (type == NULL)
2347 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002348
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002349 /* Keep name and slots alive in the extended type object */
2350 et = (PyHeapTypeObject *)type;
2351 Py_INCREF(name);
2352 et->ht_name = name;
2353 et->ht_slots = slots;
Victor Stinner6f738742012-02-25 01:22:36 +01002354 slots = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002355
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002356 /* Initialize tp_flags */
2357 type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE |
Antoine Pitrou796564c2013-07-30 19:59:21 +02002358 Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_FINALIZE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002359 if (base->tp_flags & Py_TPFLAGS_HAVE_GC)
2360 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossumdc91b992001-08-08 22:26:22 +00002361
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002362 /* Initialize essential fields */
2363 type->tp_as_number = &et->as_number;
2364 type->tp_as_sequence = &et->as_sequence;
2365 type->tp_as_mapping = &et->as_mapping;
2366 type->tp_as_buffer = &et->as_buffer;
2367 type->tp_name = _PyUnicode_AsString(name);
Victor Stinner6f738742012-02-25 01:22:36 +01002368 if (!type->tp_name)
2369 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002370
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002371 /* Set tp_base and tp_bases */
2372 type->tp_bases = bases;
Victor Stinner6f738742012-02-25 01:22:36 +01002373 bases = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002374 Py_INCREF(base);
2375 type->tp_base = base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002376
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002377 /* Initialize tp_dict from passed-in dict */
Victor Stinner6f738742012-02-25 01:22:36 +01002378 Py_INCREF(dict);
2379 type->tp_dict = dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002380
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002381 /* Set __module__ in the dict */
Victor Stinner3c1e4812012-03-26 22:10:51 +02002382 if (_PyDict_GetItemId(dict, &PyId___module__) == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002383 tmp = PyEval_GetGlobals();
2384 if (tmp != NULL) {
Victor Stinner3c1e4812012-03-26 22:10:51 +02002385 tmp = _PyDict_GetItemId(tmp, &PyId___name__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002386 if (tmp != NULL) {
Victor Stinner3c1e4812012-03-26 22:10:51 +02002387 if (_PyDict_SetItemId(dict, &PyId___module__,
2388 tmp) < 0)
Victor Stinner6f738742012-02-25 01:22:36 +01002389 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002390 }
2391 }
2392 }
Guido van Rossumc3542212001-08-16 09:18:56 +00002393
Victor Stinner6f738742012-02-25 01:22:36 +01002394 /* Set ht_qualname to dict['__qualname__'] if available, else to
2395 __name__. The __qualname__ accessor will look for ht_qualname.
2396 */
Victor Stinner3c1e4812012-03-26 22:10:51 +02002397 qualname = _PyDict_GetItemId(dict, &PyId___qualname__);
Victor Stinner6f738742012-02-25 01:22:36 +01002398 if (qualname != NULL) {
2399 if (!PyUnicode_Check(qualname)) {
2400 PyErr_Format(PyExc_TypeError,
2401 "type __qualname__ must be a str, not %s",
2402 Py_TYPE(qualname)->tp_name);
2403 goto error;
2404 }
2405 }
Benjamin Peterson8afa7fa2012-10-30 23:51:03 -04002406 et->ht_qualname = qualname ? qualname : et->ht_name;
2407 Py_INCREF(et->ht_qualname);
2408 if (qualname != NULL && PyDict_DelItem(dict, PyId___qualname__.object) < 0)
2409 goto error;
Victor Stinner6f738742012-02-25 01:22:36 +01002410
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002411 /* Set tp_doc to a copy of dict['__doc__'], if the latter is there
2412 and is a string. The __doc__ accessor will first look for tp_doc;
2413 if that fails, it will still look into __dict__.
2414 */
2415 {
Victor Stinner3c1e4812012-03-26 22:10:51 +02002416 PyObject *doc = _PyDict_GetItemId(dict, &PyId___doc__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002417 if (doc != NULL && PyUnicode_Check(doc)) {
2418 Py_ssize_t len;
2419 char *doc_str;
2420 char *tp_doc;
Alexandre Vassalottia85998a2008-05-03 18:24:43 +00002421
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002422 doc_str = _PyUnicode_AsString(doc);
Victor Stinner6f738742012-02-25 01:22:36 +01002423 if (doc_str == NULL)
2424 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002425 /* Silently truncate the docstring if it contains null bytes. */
2426 len = strlen(doc_str);
2427 tp_doc = (char *)PyObject_MALLOC(len + 1);
Victor Stinner53510cd2013-07-15 19:34:20 +02002428 if (tp_doc == NULL) {
2429 PyErr_NoMemory();
Victor Stinner6f738742012-02-25 01:22:36 +01002430 goto error;
Victor Stinner53510cd2013-07-15 19:34:20 +02002431 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002432 memcpy(tp_doc, doc_str, len + 1);
2433 type->tp_doc = tp_doc;
2434 }
2435 }
Tim Peters2f93e282001-10-04 05:27:00 +00002436
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002437 /* Special-case __new__: if it's a plain function,
2438 make it a static function */
Victor Stinner3c1e4812012-03-26 22:10:51 +02002439 tmp = _PyDict_GetItemId(dict, &PyId___new__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002440 if (tmp != NULL && PyFunction_Check(tmp)) {
2441 tmp = PyStaticMethod_New(tmp);
Victor Stinner6f738742012-02-25 01:22:36 +01002442 if (tmp == NULL)
2443 goto error;
Victor Stinner3c1e4812012-03-26 22:10:51 +02002444 if (_PyDict_SetItemId(dict, &PyId___new__, tmp) < 0)
2445 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002446 Py_DECREF(tmp);
2447 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002448
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002449 /* Add descriptors for custom slots from __slots__, or for __dict__ */
2450 mp = PyHeapType_GET_MEMBERS(et);
2451 slotoffset = base->tp_basicsize;
Victor Stinner6f738742012-02-25 01:22:36 +01002452 if (et->ht_slots != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002453 for (i = 0; i < nslots; i++, mp++) {
2454 mp->name = _PyUnicode_AsString(
Victor Stinner6f738742012-02-25 01:22:36 +01002455 PyTuple_GET_ITEM(et->ht_slots, i));
2456 if (mp->name == NULL)
2457 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002458 mp->type = T_OBJECT_EX;
2459 mp->offset = slotoffset;
Guido van Rossumd8faa362007-04-27 19:54:29 +00002460
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002461 /* __dict__ and __weakref__ are already filtered out */
2462 assert(strcmp(mp->name, "__dict__") != 0);
2463 assert(strcmp(mp->name, "__weakref__") != 0);
Guido van Rossumd8faa362007-04-27 19:54:29 +00002464
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002465 slotoffset += sizeof(PyObject *);
2466 }
2467 }
2468 if (add_dict) {
2469 if (base->tp_itemsize)
2470 type->tp_dictoffset = -(long)sizeof(PyObject *);
2471 else
2472 type->tp_dictoffset = slotoffset;
2473 slotoffset += sizeof(PyObject *);
2474 }
2475 if (add_weak) {
2476 assert(!base->tp_itemsize);
2477 type->tp_weaklistoffset = slotoffset;
2478 slotoffset += sizeof(PyObject *);
2479 }
2480 type->tp_basicsize = slotoffset;
2481 type->tp_itemsize = base->tp_itemsize;
2482 type->tp_members = PyHeapType_GET_MEMBERS(et);
Guido van Rossum373c7412003-01-07 13:41:37 +00002483
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002484 if (type->tp_weaklistoffset && type->tp_dictoffset)
2485 type->tp_getset = subtype_getsets_full;
2486 else if (type->tp_weaklistoffset && !type->tp_dictoffset)
2487 type->tp_getset = subtype_getsets_weakref_only;
2488 else if (!type->tp_weaklistoffset && type->tp_dictoffset)
2489 type->tp_getset = subtype_getsets_dict_only;
2490 else
2491 type->tp_getset = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002492
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002493 /* Special case some slots */
2494 if (type->tp_dictoffset != 0 || nslots > 0) {
2495 if (base->tp_getattr == NULL && base->tp_getattro == NULL)
2496 type->tp_getattro = PyObject_GenericGetAttr;
2497 if (base->tp_setattr == NULL && base->tp_setattro == NULL)
2498 type->tp_setattro = PyObject_GenericSetAttr;
2499 }
2500 type->tp_dealloc = subtype_dealloc;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002501
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002502 /* Enable GC unless there are really no instance variables possible */
2503 if (!(type->tp_basicsize == sizeof(PyObject) &&
2504 type->tp_itemsize == 0))
2505 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossum9475a232001-10-05 20:51:39 +00002506
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002507 /* Always override allocation strategy to use regular heap */
2508 type->tp_alloc = PyType_GenericAlloc;
2509 if (type->tp_flags & Py_TPFLAGS_HAVE_GC) {
2510 type->tp_free = PyObject_GC_Del;
2511 type->tp_traverse = subtype_traverse;
2512 type->tp_clear = subtype_clear;
2513 }
2514 else
2515 type->tp_free = PyObject_Del;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002516
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002517 /* Initialize the rest */
Victor Stinner6f738742012-02-25 01:22:36 +01002518 if (PyType_Ready(type) < 0)
2519 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002520
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002521 /* Put the proper slots in place */
2522 fixup_slot_dispatchers(type);
Guido van Rossumf040ede2001-08-07 16:40:56 +00002523
Benjamin Petersondf813792014-03-17 15:57:17 -05002524 if (type->tp_dictoffset) {
2525 et->ht_cached_keys = _PyDict_NewKeysForClass();
2526 }
2527
Victor Stinner6f738742012-02-25 01:22:36 +01002528 Py_DECREF(dict);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002529 return (PyObject *)type;
Victor Stinner6f738742012-02-25 01:22:36 +01002530
2531error:
2532 Py_XDECREF(dict);
2533 Py_XDECREF(bases);
2534 Py_XDECREF(slots);
2535 Py_XDECREF(type);
2536 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002537}
2538
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002539static short slotoffsets[] = {
2540 -1, /* invalid slot */
2541#include "typeslots.inc"
2542};
2543
Benjamin Petersone28108c2012-01-29 20:13:18 -05002544PyObject *
Martin v. Löwis9c564092012-06-23 23:20:45 +02002545PyType_FromSpecWithBases(PyType_Spec *spec, PyObject *bases)
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002546{
2547 PyHeapTypeObject *res = (PyHeapTypeObject*)PyType_GenericAlloc(&PyType_Type, 0);
Martin v. Löwis9c564092012-06-23 23:20:45 +02002548 PyTypeObject *type, *base;
2549 char *s;
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002550 char *res_start = (char*)res;
2551 PyType_Slot *slot;
Victor Stinner54e4ca72013-07-11 22:42:25 +02002552
Martin v. Löwis9c564092012-06-23 23:20:45 +02002553 /* Set the type name and qualname */
2554 s = strrchr(spec->name, '.');
2555 if (s == NULL)
2556 s = (char*)spec->name;
2557 else
2558 s++;
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002559
Martin v. Löwis5e06a5d2011-02-21 16:24:00 +00002560 if (res == NULL)
Antoine Pitroubb78f572012-06-24 00:18:27 +02002561 return NULL;
2562 type = &res->ht_type;
Antoine Pitrou66a3a7e2012-06-24 00:42:59 +02002563 /* The flags must be initialized early, before the GC traverses us */
2564 type->tp_flags = spec->flags | Py_TPFLAGS_HEAPTYPE;
Martin v. Löwis9c564092012-06-23 23:20:45 +02002565 res->ht_name = PyUnicode_FromString(s);
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002566 if (!res->ht_name)
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002567 goto fail;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002568 res->ht_qualname = res->ht_name;
2569 Py_INCREF(res->ht_qualname);
Antoine Pitroubb78f572012-06-24 00:18:27 +02002570 type->tp_name = spec->name;
2571 if (!type->tp_name)
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002572 goto fail;
Victor Stinner54e4ca72013-07-11 22:42:25 +02002573
Martin v. Löwis9c564092012-06-23 23:20:45 +02002574 /* Adjust for empty tuple bases */
2575 if (!bases) {
2576 base = &PyBaseObject_Type;
2577 /* See whether Py_tp_base(s) was specified */
2578 for (slot = spec->slots; slot->slot; slot++) {
2579 if (slot->slot == Py_tp_base)
2580 base = slot->pfunc;
2581 else if (slot->slot == Py_tp_bases) {
2582 bases = slot->pfunc;
2583 Py_INCREF(bases);
2584 }
2585 }
2586 if (!bases)
2587 bases = PyTuple_Pack(1, base);
2588 if (!bases)
2589 goto fail;
2590 }
2591 else
2592 Py_INCREF(bases);
2593
2594 /* Calculate best base, and check that all bases are type objects */
2595 base = best_base(bases);
2596 if (base == NULL) {
2597 goto fail;
2598 }
2599 if (!PyType_HasFeature(base, Py_TPFLAGS_BASETYPE)) {
2600 PyErr_Format(PyExc_TypeError,
2601 "type '%.100s' is not an acceptable base type",
2602 base->tp_name);
2603 goto fail;
2604 }
2605
Martin v. Löwis9c564092012-06-23 23:20:45 +02002606 /* Initialize essential fields */
2607 type->tp_as_number = &res->as_number;
2608 type->tp_as_sequence = &res->as_sequence;
2609 type->tp_as_mapping = &res->as_mapping;
2610 type->tp_as_buffer = &res->as_buffer;
2611 /* Set tp_base and tp_bases */
2612 type->tp_bases = bases;
2613 bases = NULL;
2614 Py_INCREF(base);
2615 type->tp_base = base;
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002616
Antoine Pitroubb78f572012-06-24 00:18:27 +02002617 type->tp_basicsize = spec->basicsize;
2618 type->tp_itemsize = spec->itemsize;
Victor Stinner0fcab4a2011-01-04 12:59:15 +00002619
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002620 for (slot = spec->slots; slot->slot; slot++) {
Victor Stinner63941882011-09-29 00:42:28 +02002621 if (slot->slot >= Py_ARRAY_LENGTH(slotoffsets)) {
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002622 PyErr_SetString(PyExc_RuntimeError, "invalid slot offset");
2623 goto fail;
2624 }
Martin v. Löwis9c564092012-06-23 23:20:45 +02002625 if (slot->slot == Py_tp_base || slot->slot == Py_tp_bases)
2626 /* Processed above */
2627 continue;
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002628 *(void**)(res_start + slotoffsets[slot->slot]) = slot->pfunc;
Georg Brandl032400b2011-02-19 21:47:02 +00002629
2630 /* need to make a copy of the docstring slot, which usually
2631 points to a static string literal */
2632 if (slot->slot == Py_tp_doc) {
Larry Hastings2623c8c2014-02-08 22:15:29 -08002633 const char *old_doc = _PyType_DocWithoutSignature(type->tp_name, slot->pfunc);
Larry Hastings5c661892014-01-24 06:17:25 -08002634 size_t len = strlen(old_doc)+1;
Georg Brandl032400b2011-02-19 21:47:02 +00002635 char *tp_doc = PyObject_MALLOC(len);
Victor Stinner53510cd2013-07-15 19:34:20 +02002636 if (tp_doc == NULL) {
2637 PyErr_NoMemory();
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002638 goto fail;
Victor Stinner53510cd2013-07-15 19:34:20 +02002639 }
Larry Hastings5c661892014-01-24 06:17:25 -08002640 memcpy(tp_doc, old_doc, len);
Antoine Pitroubb78f572012-06-24 00:18:27 +02002641 type->tp_doc = tp_doc;
Georg Brandl032400b2011-02-19 21:47:02 +00002642 }
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002643 }
Antoine Pitroubb78f572012-06-24 00:18:27 +02002644 if (type->tp_dealloc == NULL) {
Antoine Pitrou99cc6292012-06-23 14:42:38 +02002645 /* It's a heap type, so needs the heap types' dealloc.
2646 subtype_dealloc will call the base type's tp_dealloc, if
2647 necessary. */
Antoine Pitroubb78f572012-06-24 00:18:27 +02002648 type->tp_dealloc = subtype_dealloc;
Antoine Pitrou99cc6292012-06-23 14:42:38 +02002649 }
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002650
Antoine Pitroubb78f572012-06-24 00:18:27 +02002651 if (PyType_Ready(type) < 0)
Benjamin Peterson2652d252012-01-29 20:16:37 -05002652 goto fail;
2653
Benjamin Petersondf813792014-03-17 15:57:17 -05002654 if (type->tp_dictoffset) {
2655 res->ht_cached_keys = _PyDict_NewKeysForClass();
2656 }
2657
Martin v. Löwis9c564092012-06-23 23:20:45 +02002658 /* Set type.__module__ */
2659 s = strrchr(spec->name, '.');
2660 if (s != NULL)
Victor Stinner54e4ca72013-07-11 22:42:25 +02002661 _PyDict_SetItemId(type->tp_dict, &PyId___module__,
Martin v. Löwis9c564092012-06-23 23:20:45 +02002662 PyUnicode_FromStringAndSize(
2663 spec->name, (Py_ssize_t)(s - spec->name)));
2664
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002665 return (PyObject*)res;
Victor Stinner0fcab4a2011-01-04 12:59:15 +00002666
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002667 fail:
2668 Py_DECREF(res);
2669 return NULL;
2670}
2671
Martin v. Löwis9c564092012-06-23 23:20:45 +02002672PyObject *
2673PyType_FromSpec(PyType_Spec *spec)
2674{
2675 return PyType_FromSpecWithBases(spec, NULL);
2676}
2677
Martin v. Löwisca7b0462014-02-04 09:33:05 +01002678void *
2679PyType_GetSlot(PyTypeObject *type, int slot)
2680{
Victor Stinner1ea4e412014-02-04 09:49:14 +01002681 if (!PyType_HasFeature(type, Py_TPFLAGS_HEAPTYPE)) {
Martin v. Löwisca7b0462014-02-04 09:33:05 +01002682 PyErr_BadInternalCall();
2683 return NULL;
2684 }
2685 if (slot >= Py_ARRAY_LENGTH(slotoffsets)) {
2686 /* Extension module requesting slot from a future version */
2687 return NULL;
2688 }
2689 return *(void**)(((char*)type) + slotoffsets[slot]);
2690}
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002691
Tim Peters6d6c1a32001-08-02 04:15:00 +00002692/* Internal API to look for a name through the MRO.
2693 This returns a borrowed reference, and doesn't set an exception! */
2694PyObject *
2695_PyType_Lookup(PyTypeObject *type, PyObject *name)
2696{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002697 Py_ssize_t i, n;
2698 PyObject *mro, *res, *base, *dict;
2699 unsigned int h;
Christian Heimesa62da1d2008-01-12 19:39:10 +00002700
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002701 if (MCACHE_CACHEABLE_NAME(name) &&
2702 PyType_HasFeature(type, Py_TPFLAGS_VALID_VERSION_TAG)) {
2703 /* fast path */
2704 h = MCACHE_HASH_METHOD(type, name);
2705 if (method_cache[h].version == type->tp_version_tag &&
2706 method_cache[h].name == name)
2707 return method_cache[h].value;
2708 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002709
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002710 /* Look in tp_dict of types in MRO */
2711 mro = type->tp_mro;
Guido van Rossum23094982002-06-10 14:30:43 +00002712
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002713 /* If mro is NULL, the type is either not yet initialized
2714 by PyType_Ready(), or already cleared by type_clear().
2715 Either way the safest thing to do is to return NULL. */
2716 if (mro == NULL)
2717 return NULL;
Guido van Rossum23094982002-06-10 14:30:43 +00002718
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002719 res = NULL;
Victor Stinnerd74782b2012-03-09 00:39:08 +01002720 /* keep a strong reference to mro because type->tp_mro can be replaced
2721 during PyDict_GetItem(dict, name) */
2722 Py_INCREF(mro);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002723 assert(PyTuple_Check(mro));
2724 n = PyTuple_GET_SIZE(mro);
2725 for (i = 0; i < n; i++) {
2726 base = PyTuple_GET_ITEM(mro, i);
2727 assert(PyType_Check(base));
2728 dict = ((PyTypeObject *)base)->tp_dict;
2729 assert(dict && PyDict_Check(dict));
2730 res = PyDict_GetItem(dict, name);
2731 if (res != NULL)
2732 break;
2733 }
Victor Stinnerd74782b2012-03-09 00:39:08 +01002734 Py_DECREF(mro);
Christian Heimesa62da1d2008-01-12 19:39:10 +00002735
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002736 if (MCACHE_CACHEABLE_NAME(name) && assign_version_tag(type)) {
2737 h = MCACHE_HASH_METHOD(type, name);
2738 method_cache[h].version = type->tp_version_tag;
2739 method_cache[h].value = res; /* borrowed */
2740 Py_INCREF(name);
2741 Py_DECREF(method_cache[h].name);
2742 method_cache[h].name = name;
2743 }
2744 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002745}
2746
Raymond Hettinger2ff21902013-10-01 00:55:43 -07002747PyObject *
Victor Stinner3c1e4812012-03-26 22:10:51 +02002748_PyType_LookupId(PyTypeObject *type, struct _Py_Identifier *name)
2749{
2750 PyObject *oname;
2751 oname = _PyUnicode_FromId(name); /* borrowed */
2752 if (oname == NULL)
2753 return NULL;
2754 return _PyType_Lookup(type, oname);
2755}
2756
Tim Peters6d6c1a32001-08-02 04:15:00 +00002757/* This is similar to PyObject_GenericGetAttr(),
2758 but uses _PyType_Lookup() instead of just looking in type->tp_dict. */
2759static PyObject *
2760type_getattro(PyTypeObject *type, PyObject *name)
2761{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002762 PyTypeObject *metatype = Py_TYPE(type);
2763 PyObject *meta_attribute, *attribute;
2764 descrgetfunc meta_get;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002765
Benjamin Peterson16d84ac2012-03-16 09:32:59 -05002766 if (!PyUnicode_Check(name)) {
2767 PyErr_Format(PyExc_TypeError,
2768 "attribute name must be string, not '%.200s'",
2769 name->ob_type->tp_name);
2770 return NULL;
2771 }
2772
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002773 /* Initialize this type (we'll assume the metatype is initialized) */
2774 if (type->tp_dict == NULL) {
2775 if (PyType_Ready(type) < 0)
2776 return NULL;
2777 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002778
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002779 /* No readable descriptor found yet */
2780 meta_get = NULL;
Tim Peters34592512002-07-11 06:23:50 +00002781
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002782 /* Look for the attribute in the metatype */
2783 meta_attribute = _PyType_Lookup(metatype, name);
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002784
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002785 if (meta_attribute != NULL) {
2786 meta_get = Py_TYPE(meta_attribute)->tp_descr_get;
Tim Peters34592512002-07-11 06:23:50 +00002787
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002788 if (meta_get != NULL && PyDescr_IsData(meta_attribute)) {
2789 /* Data descriptors implement tp_descr_set to intercept
2790 * writes. Assume the attribute is not overridden in
2791 * type's tp_dict (and bases): call the descriptor now.
2792 */
2793 return meta_get(meta_attribute, (PyObject *)type,
2794 (PyObject *)metatype);
2795 }
2796 Py_INCREF(meta_attribute);
2797 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002798
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002799 /* No data descriptor found on metatype. Look in tp_dict of this
2800 * type and its bases */
2801 attribute = _PyType_Lookup(type, name);
2802 if (attribute != NULL) {
2803 /* Implement descriptor functionality, if any */
2804 descrgetfunc local_get = Py_TYPE(attribute)->tp_descr_get;
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00002805
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002806 Py_XDECREF(meta_attribute);
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00002807
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002808 if (local_get != NULL) {
2809 /* NULL 2nd argument indicates the descriptor was
2810 * found on the target object itself (or a base) */
2811 return local_get(attribute, (PyObject *)NULL,
2812 (PyObject *)type);
2813 }
Tim Peters34592512002-07-11 06:23:50 +00002814
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002815 Py_INCREF(attribute);
2816 return attribute;
2817 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002818
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002819 /* No attribute found in local __dict__ (or bases): use the
2820 * descriptor from the metatype, if any */
2821 if (meta_get != NULL) {
2822 PyObject *res;
2823 res = meta_get(meta_attribute, (PyObject *)type,
2824 (PyObject *)metatype);
2825 Py_DECREF(meta_attribute);
2826 return res;
2827 }
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002828
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002829 /* If an ordinary attribute was found on the metatype, return it now */
2830 if (meta_attribute != NULL) {
2831 return meta_attribute;
2832 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002833
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002834 /* Give up */
2835 PyErr_Format(PyExc_AttributeError,
2836 "type object '%.50s' has no attribute '%U'",
2837 type->tp_name, name);
2838 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002839}
2840
2841static int
2842type_setattro(PyTypeObject *type, PyObject *name, PyObject *value)
2843{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002844 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
2845 PyErr_Format(
2846 PyExc_TypeError,
2847 "can't set attributes of built-in/extension type '%s'",
2848 type->tp_name);
2849 return -1;
2850 }
2851 if (PyObject_GenericSetAttr((PyObject *)type, name, value) < 0)
2852 return -1;
2853 return update_slot(type, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002854}
2855
Benjamin Peterson64acccf2012-04-27 15:07:36 -04002856extern void
2857_PyDictKeys_DecRef(PyDictKeysObject *keys);
2858
Tim Peters6d6c1a32001-08-02 04:15:00 +00002859static void
2860type_dealloc(PyTypeObject *type)
2861{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002862 PyHeapTypeObject *et;
Antoine Pitrou84745ab2013-10-29 21:31:25 +01002863 PyObject *tp, *val, *tb;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002864
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002865 /* Assert this is a heap-allocated type object */
2866 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
2867 _PyObject_GC_UNTRACK(type);
Antoine Pitrou84745ab2013-10-29 21:31:25 +01002868 PyErr_Fetch(&tp, &val, &tb);
2869 remove_all_subclasses(type, type->tp_bases);
2870 PyErr_Restore(tp, val, tb);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002871 PyObject_ClearWeakRefs((PyObject *)type);
2872 et = (PyHeapTypeObject *)type;
2873 Py_XDECREF(type->tp_base);
2874 Py_XDECREF(type->tp_dict);
2875 Py_XDECREF(type->tp_bases);
2876 Py_XDECREF(type->tp_mro);
2877 Py_XDECREF(type->tp_cache);
2878 Py_XDECREF(type->tp_subclasses);
2879 /* A type's tp_doc is heap allocated, unlike the tp_doc slots
2880 * of most other objects. It's okay to cast it to char *.
2881 */
2882 PyObject_Free((char *)type->tp_doc);
2883 Py_XDECREF(et->ht_name);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002884 Py_XDECREF(et->ht_qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002885 Py_XDECREF(et->ht_slots);
Benjamin Peterson64acccf2012-04-27 15:07:36 -04002886 if (et->ht_cached_keys)
2887 _PyDictKeys_DecRef(et->ht_cached_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002888 Py_TYPE(type)->tp_free((PyObject *)type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002889}
2890
Guido van Rossum1c450732001-10-08 15:18:27 +00002891static PyObject *
2892type_subclasses(PyTypeObject *type, PyObject *args_ignored)
2893{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002894 PyObject *list, *raw, *ref;
Antoine Pitrou84745ab2013-10-29 21:31:25 +01002895 Py_ssize_t i;
Guido van Rossum1c450732001-10-08 15:18:27 +00002896
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002897 list = PyList_New(0);
2898 if (list == NULL)
2899 return NULL;
2900 raw = type->tp_subclasses;
2901 if (raw == NULL)
2902 return list;
Antoine Pitrou84745ab2013-10-29 21:31:25 +01002903 assert(PyDict_CheckExact(raw));
2904 i = 0;
2905 while (PyDict_Next(raw, &i, NULL, &ref)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002906 assert(PyWeakref_CheckRef(ref));
2907 ref = PyWeakref_GET_OBJECT(ref);
2908 if (ref != Py_None) {
2909 if (PyList_Append(list, ref) < 0) {
2910 Py_DECREF(list);
2911 return NULL;
2912 }
2913 }
2914 }
2915 return list;
Guido van Rossum1c450732001-10-08 15:18:27 +00002916}
2917
Guido van Rossum47374822007-08-02 16:48:17 +00002918static PyObject *
2919type_prepare(PyObject *self, PyObject *args, PyObject *kwds)
2920{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002921 return PyDict_New();
Guido van Rossum47374822007-08-02 16:48:17 +00002922}
2923
Victor Stinner63941882011-09-29 00:42:28 +02002924/*
Benjamin Peterson82b00c12011-05-24 11:09:06 -05002925 Merge the __dict__ of aclass into dict, and recursively also all
2926 the __dict__s of aclass's base classes. The order of merging isn't
2927 defined, as it's expected that only the final set of dict keys is
2928 interesting.
2929 Return 0 on success, -1 on error.
2930*/
2931
2932static int
2933merge_class_dict(PyObject *dict, PyObject *aclass)
2934{
2935 PyObject *classdict;
2936 PyObject *bases;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02002937 _Py_IDENTIFIER(__bases__);
Benjamin Peterson82b00c12011-05-24 11:09:06 -05002938
2939 assert(PyDict_Check(dict));
2940 assert(aclass);
2941
2942 /* Merge in the type's dict (if any). */
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002943 classdict = _PyObject_GetAttrId(aclass, &PyId___dict__);
Benjamin Peterson82b00c12011-05-24 11:09:06 -05002944 if (classdict == NULL)
2945 PyErr_Clear();
2946 else {
2947 int status = PyDict_Update(dict, classdict);
2948 Py_DECREF(classdict);
2949 if (status < 0)
2950 return -1;
2951 }
2952
2953 /* Recursively merge in the base types' (if any) dicts. */
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002954 bases = _PyObject_GetAttrId(aclass, &PyId___bases__);
Benjamin Peterson82b00c12011-05-24 11:09:06 -05002955 if (bases == NULL)
2956 PyErr_Clear();
2957 else {
2958 /* We have no guarantee that bases is a real tuple */
2959 Py_ssize_t i, n;
2960 n = PySequence_Size(bases); /* This better be right */
2961 if (n < 0)
2962 PyErr_Clear();
2963 else {
2964 for (i = 0; i < n; i++) {
2965 int status;
2966 PyObject *base = PySequence_GetItem(bases, i);
2967 if (base == NULL) {
2968 Py_DECREF(bases);
2969 return -1;
2970 }
2971 status = merge_class_dict(dict, base);
2972 Py_DECREF(base);
2973 if (status < 0) {
2974 Py_DECREF(bases);
2975 return -1;
2976 }
2977 }
2978 }
2979 Py_DECREF(bases);
2980 }
2981 return 0;
2982}
2983
2984/* __dir__ for type objects: returns __dict__ and __bases__.
2985 We deliberately don't suck up its __class__, as methods belonging to the
2986 metaclass would probably be more confusing than helpful.
2987*/
2988static PyObject *
2989type_dir(PyObject *self, PyObject *args)
2990{
2991 PyObject *result = NULL;
2992 PyObject *dict = PyDict_New();
2993
2994 if (dict != NULL && merge_class_dict(dict, self) == 0)
2995 result = PyDict_Keys(dict);
2996
2997 Py_XDECREF(dict);
2998 return result;
2999}
3000
Martin v. Loewis4f2f3b62012-04-24 19:13:57 +02003001static PyObject*
3002type_sizeof(PyObject *self, PyObject *args_unused)
3003{
3004 Py_ssize_t size;
3005 PyTypeObject *type = (PyTypeObject*)self;
3006 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
3007 PyHeapTypeObject* et = (PyHeapTypeObject*)type;
3008 size = sizeof(PyHeapTypeObject);
3009 if (et->ht_cached_keys)
3010 size += _PyDict_KeysSize(et->ht_cached_keys);
3011 }
3012 else
3013 size = sizeof(PyTypeObject);
3014 return PyLong_FromSsize_t(size);
3015}
3016
Tim Peters6d6c1a32001-08-02 04:15:00 +00003017static PyMethodDef type_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003018 {"mro", (PyCFunction)mro_external, METH_NOARGS,
3019 PyDoc_STR("mro() -> list\nreturn a type's method resolution order")},
3020 {"__subclasses__", (PyCFunction)type_subclasses, METH_NOARGS,
3021 PyDoc_STR("__subclasses__() -> list of immediate subclasses")},
3022 {"__prepare__", (PyCFunction)type_prepare,
3023 METH_VARARGS | METH_KEYWORDS | METH_CLASS,
3024 PyDoc_STR("__prepare__() -> dict\n"
3025 "used to create the namespace for the class statement")},
3026 {"__instancecheck__", type___instancecheck__, METH_O,
Benjamin Petersonfbe56bb2011-05-24 12:42:51 -05003027 PyDoc_STR("__instancecheck__() -> bool\ncheck if an object is an instance")},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003028 {"__subclasscheck__", type___subclasscheck__, METH_O,
Benjamin Petersonfbe56bb2011-05-24 12:42:51 -05003029 PyDoc_STR("__subclasscheck__() -> bool\ncheck if a class is a subclass")},
Benjamin Peterson82b00c12011-05-24 11:09:06 -05003030 {"__dir__", type_dir, METH_NOARGS,
Benjamin Petersonc7284122011-05-24 12:46:15 -05003031 PyDoc_STR("__dir__() -> list\nspecialized __dir__ implementation for types")},
Martin v. Loewis4f2f3b62012-04-24 19:13:57 +02003032 {"__sizeof__", type_sizeof, METH_NOARGS,
3033 "__sizeof__() -> int\nreturn memory consumption of the type object"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003034 {0}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003035};
3036
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003037PyDoc_STRVAR(type_doc,
Larry Hastings5c661892014-01-24 06:17:25 -08003038/* this text signature cannot be accurate yet. will fix. --larry */
Larry Hastings2623c8c2014-02-08 22:15:29 -08003039"type(object_or_name, bases, dict)\n"
Tim Peters6d6c1a32001-08-02 04:15:00 +00003040"type(object) -> the object's type\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003041"type(name, bases, dict) -> a new type");
Tim Peters6d6c1a32001-08-02 04:15:00 +00003042
Guido van Rossum048eb752001-10-02 21:24:57 +00003043static int
3044type_traverse(PyTypeObject *type, visitproc visit, void *arg)
3045{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003046 /* Because of type_is_gc(), the collector only calls this
3047 for heaptypes. */
Antoine Pitrou1351ca62012-06-24 00:30:12 +02003048 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
3049 char msg[200];
3050 sprintf(msg, "type_traverse() called for non-heap type '%.100s'",
3051 type->tp_name);
3052 Py_FatalError(msg);
3053 }
Guido van Rossum048eb752001-10-02 21:24:57 +00003054
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003055 Py_VISIT(type->tp_dict);
3056 Py_VISIT(type->tp_cache);
3057 Py_VISIT(type->tp_mro);
3058 Py_VISIT(type->tp_bases);
3059 Py_VISIT(type->tp_base);
Guido van Rossuma3862092002-06-10 15:24:42 +00003060
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003061 /* There's no need to visit type->tp_subclasses or
3062 ((PyHeapTypeObject *)type)->ht_slots, because they can't be involved
3063 in cycles; tp_subclasses is a list of weak references,
3064 and slots is a tuple of strings. */
Guido van Rossum048eb752001-10-02 21:24:57 +00003065
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003066 return 0;
Guido van Rossum048eb752001-10-02 21:24:57 +00003067}
3068
3069static int
3070type_clear(PyTypeObject *type)
3071{
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003072 PyDictKeysObject *cached_keys;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003073 /* Because of type_is_gc(), the collector only calls this
3074 for heaptypes. */
3075 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00003076
Antoine Pitrou2e872082011-12-15 14:15:31 +01003077 /* We need to invalidate the method cache carefully before clearing
3078 the dict, so that other objects caught in a reference cycle
3079 don't start calling destroyed methods.
3080
3081 Otherwise, the only field we need to clear is tp_mro, which is
3082 part of a hard cycle (its first element is the class itself) that
3083 won't be broken otherwise (it's a tuple and tuples don't have a
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003084 tp_clear handler). None of the other fields need to be
3085 cleared, and here's why:
Guido van Rossum048eb752001-10-02 21:24:57 +00003086
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003087 tp_cache:
3088 Not used; if it were, it would be a dict.
Guido van Rossuma3862092002-06-10 15:24:42 +00003089
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003090 tp_bases, tp_base:
3091 If these are involved in a cycle, there must be at least
3092 one other, mutable object in the cycle, e.g. a base
3093 class's dict; the cycle will be broken that way.
Guido van Rossuma3862092002-06-10 15:24:42 +00003094
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003095 tp_subclasses:
Antoine Pitrou84745ab2013-10-29 21:31:25 +01003096 A dict of weak references can't be part of a cycle; and
3097 dicts have their own tp_clear.
Guido van Rossuma3862092002-06-10 15:24:42 +00003098
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003099 slots (in PyHeapTypeObject):
3100 A tuple of strings can't be part of a cycle.
3101 */
Guido van Rossuma3862092002-06-10 15:24:42 +00003102
Antoine Pitrou2e872082011-12-15 14:15:31 +01003103 PyType_Modified(type);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003104 cached_keys = ((PyHeapTypeObject *)type)->ht_cached_keys;
3105 if (cached_keys != NULL) {
3106 ((PyHeapTypeObject *)type)->ht_cached_keys = NULL;
3107 _PyDictKeys_DecRef(cached_keys);
3108 }
Antoine Pitrou2e872082011-12-15 14:15:31 +01003109 if (type->tp_dict)
3110 PyDict_Clear(type->tp_dict);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003111 Py_CLEAR(type->tp_mro);
Guido van Rossum048eb752001-10-02 21:24:57 +00003112
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003113 return 0;
Guido van Rossum048eb752001-10-02 21:24:57 +00003114}
3115
3116static int
3117type_is_gc(PyTypeObject *type)
3118{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003119 return type->tp_flags & Py_TPFLAGS_HEAPTYPE;
Guido van Rossum048eb752001-10-02 21:24:57 +00003120}
3121
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003122PyTypeObject PyType_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003123 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3124 "type", /* tp_name */
3125 sizeof(PyHeapTypeObject), /* tp_basicsize */
3126 sizeof(PyMemberDef), /* tp_itemsize */
3127 (destructor)type_dealloc, /* tp_dealloc */
3128 0, /* tp_print */
3129 0, /* tp_getattr */
3130 0, /* tp_setattr */
3131 0, /* tp_reserved */
3132 (reprfunc)type_repr, /* tp_repr */
3133 0, /* tp_as_number */
3134 0, /* tp_as_sequence */
3135 0, /* tp_as_mapping */
3136 0, /* tp_hash */
3137 (ternaryfunc)type_call, /* tp_call */
3138 0, /* tp_str */
3139 (getattrofunc)type_getattro, /* tp_getattro */
3140 (setattrofunc)type_setattro, /* tp_setattro */
3141 0, /* tp_as_buffer */
3142 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
3143 Py_TPFLAGS_BASETYPE | Py_TPFLAGS_TYPE_SUBCLASS, /* tp_flags */
3144 type_doc, /* tp_doc */
3145 (traverseproc)type_traverse, /* tp_traverse */
3146 (inquiry)type_clear, /* tp_clear */
3147 0, /* tp_richcompare */
3148 offsetof(PyTypeObject, tp_weaklist), /* tp_weaklistoffset */
3149 0, /* tp_iter */
3150 0, /* tp_iternext */
3151 type_methods, /* tp_methods */
3152 type_members, /* tp_members */
3153 type_getsets, /* tp_getset */
3154 0, /* tp_base */
3155 0, /* tp_dict */
3156 0, /* tp_descr_get */
3157 0, /* tp_descr_set */
3158 offsetof(PyTypeObject, tp_dict), /* tp_dictoffset */
3159 type_init, /* tp_init */
3160 0, /* tp_alloc */
3161 type_new, /* tp_new */
3162 PyObject_GC_Del, /* tp_free */
3163 (inquiry)type_is_gc, /* tp_is_gc */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003164};
Tim Peters6d6c1a32001-08-02 04:15:00 +00003165
3166
3167/* The base type of all types (eventually)... except itself. */
3168
Guido van Rossumd8faa362007-04-27 19:54:29 +00003169/* You may wonder why object.__new__() only complains about arguments
3170 when object.__init__() is not overridden, and vice versa.
3171
3172 Consider the use cases:
3173
3174 1. When neither is overridden, we want to hear complaints about
3175 excess (i.e., any) arguments, since their presence could
3176 indicate there's a bug.
3177
3178 2. When defining an Immutable type, we are likely to override only
3179 __new__(), since __init__() is called too late to initialize an
3180 Immutable object. Since __new__() defines the signature for the
3181 type, it would be a pain to have to override __init__() just to
3182 stop it from complaining about excess arguments.
3183
3184 3. When defining a Mutable type, we are likely to override only
3185 __init__(). So here the converse reasoning applies: we don't
3186 want to have to override __new__() just to stop it from
3187 complaining.
3188
3189 4. When __init__() is overridden, and the subclass __init__() calls
3190 object.__init__(), the latter should complain about excess
3191 arguments; ditto for __new__().
3192
3193 Use cases 2 and 3 make it unattractive to unconditionally check for
3194 excess arguments. The best solution that addresses all four use
3195 cases is as follows: __init__() complains about excess arguments
3196 unless __new__() is overridden and __init__() is not overridden
3197 (IOW, if __init__() is overridden or __new__() is not overridden);
3198 symmetrically, __new__() complains about excess arguments unless
3199 __init__() is overridden and __new__() is not overridden
3200 (IOW, if __new__() is overridden or __init__() is not overridden).
3201
3202 However, for backwards compatibility, this breaks too much code.
3203 Therefore, in 2.6, we'll *warn* about excess arguments when both
3204 methods are overridden; for all other cases we'll use the above
3205 rules.
3206
3207*/
3208
3209/* Forward */
3210static PyObject *
3211object_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
3212
3213static int
3214excess_args(PyObject *args, PyObject *kwds)
3215{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003216 return PyTuple_GET_SIZE(args) ||
3217 (kwds && PyDict_Check(kwds) && PyDict_Size(kwds));
Guido van Rossumd8faa362007-04-27 19:54:29 +00003218}
3219
Tim Peters6d6c1a32001-08-02 04:15:00 +00003220static int
3221object_init(PyObject *self, PyObject *args, PyObject *kwds)
3222{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003223 int err = 0;
Benjamin Peterson96384b92012-03-17 00:05:44 -05003224 PyTypeObject *type = Py_TYPE(self);
3225 if (excess_args(args, kwds) &&
3226 (type->tp_new == object_new || type->tp_init != object_init)) {
3227 PyErr_SetString(PyExc_TypeError, "object.__init__() takes no parameters");
3228 err = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003229 }
3230 return err;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003231}
3232
Guido van Rossum298e4212003-02-13 16:30:16 +00003233static PyObject *
3234object_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3235{
Benjamin Peterson96384b92012-03-17 00:05:44 -05003236 if (excess_args(args, kwds) &&
3237 (type->tp_init == object_init || type->tp_new != object_new)) {
R David Murray702a5dc2013-02-18 21:39:18 -05003238 PyErr_SetString(PyExc_TypeError, "object() takes no parameters");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003239 return NULL;
Benjamin Peterson96384b92012-03-17 00:05:44 -05003240 }
Victor Stinner3c1e4812012-03-26 22:10:51 +02003241
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003242 if (type->tp_flags & Py_TPFLAGS_IS_ABSTRACT) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003243 PyObject *abstract_methods = NULL;
3244 PyObject *builtins;
3245 PyObject *sorted;
3246 PyObject *sorted_methods = NULL;
3247 PyObject *joined = NULL;
Benjamin Peterson9a03ecf2012-03-16 20:15:54 -05003248 PyObject *comma;
3249 _Py_static_string(comma_id, ", ");
Victor Stinner3c1e4812012-03-26 22:10:51 +02003250 _Py_IDENTIFIER(sorted);
Christian Heimes9e7f1d22008-02-28 12:27:11 +00003251
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003252 /* Compute ", ".join(sorted(type.__abstractmethods__))
3253 into joined. */
3254 abstract_methods = type_abstractmethods(type, NULL);
3255 if (abstract_methods == NULL)
3256 goto error;
3257 builtins = PyEval_GetBuiltins();
3258 if (builtins == NULL)
3259 goto error;
Victor Stinner3c1e4812012-03-26 22:10:51 +02003260 sorted = _PyDict_GetItemId(builtins, &PyId_sorted);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003261 if (sorted == NULL)
3262 goto error;
3263 sorted_methods = PyObject_CallFunctionObjArgs(sorted,
3264 abstract_methods,
3265 NULL);
3266 if (sorted_methods == NULL)
3267 goto error;
Benjamin Peterson9a03ecf2012-03-16 20:15:54 -05003268 comma = _PyUnicode_FromId(&comma_id);
3269 if (comma == NULL)
3270 goto error;
3271 joined = PyUnicode_Join(comma, sorted_methods);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003272 if (joined == NULL)
3273 goto error;
Christian Heimes9e7f1d22008-02-28 12:27:11 +00003274
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003275 PyErr_Format(PyExc_TypeError,
3276 "Can't instantiate abstract class %s "
3277 "with abstract methods %U",
3278 type->tp_name,
3279 joined);
3280 error:
3281 Py_XDECREF(joined);
3282 Py_XDECREF(sorted_methods);
3283 Py_XDECREF(abstract_methods);
3284 return NULL;
3285 }
3286 return type->tp_alloc(type, 0);
Guido van Rossum298e4212003-02-13 16:30:16 +00003287}
3288
Tim Peters6d6c1a32001-08-02 04:15:00 +00003289static void
3290object_dealloc(PyObject *self)
3291{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003292 Py_TYPE(self)->tp_free(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003293}
3294
Guido van Rossum8e248182001-08-12 05:17:56 +00003295static PyObject *
3296object_repr(PyObject *self)
3297{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003298 PyTypeObject *type;
3299 PyObject *mod, *name, *rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00003300
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003301 type = Py_TYPE(self);
3302 mod = type_module(type, NULL);
3303 if (mod == NULL)
3304 PyErr_Clear();
3305 else if (!PyUnicode_Check(mod)) {
3306 Py_DECREF(mod);
3307 mod = NULL;
3308 }
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003309 name = type_qualname(type, NULL);
Christian Heimese81dc292012-09-10 16:57:36 +02003310 if (name == NULL) {
3311 Py_XDECREF(mod);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003312 return NULL;
Christian Heimese81dc292012-09-10 16:57:36 +02003313 }
Victor Stinnerbd303c12013-11-07 23:07:29 +01003314 if (mod != NULL && _PyUnicode_CompareWithId(mod, &PyId_builtins))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003315 rtn = PyUnicode_FromFormat("<%U.%U object at %p>", mod, name, self);
3316 else
3317 rtn = PyUnicode_FromFormat("<%s object at %p>",
3318 type->tp_name, self);
3319 Py_XDECREF(mod);
3320 Py_DECREF(name);
3321 return rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00003322}
3323
Guido van Rossumb8f63662001-08-15 23:57:02 +00003324static PyObject *
3325object_str(PyObject *self)
3326{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003327 unaryfunc f;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003328
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003329 f = Py_TYPE(self)->tp_repr;
Benjamin Peterson7b166872012-04-24 11:06:25 -04003330 if (f == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003331 f = object_repr;
3332 return f(self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003333}
3334
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003335static PyObject *
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003336object_richcompare(PyObject *self, PyObject *other, int op)
3337{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003338 PyObject *res;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003339
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003340 switch (op) {
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003341
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003342 case Py_EQ:
3343 /* Return NotImplemented instead of False, so if two
3344 objects are compared, both get a chance at the
3345 comparison. See issue #1393. */
3346 res = (self == other) ? Py_True : Py_NotImplemented;
3347 Py_INCREF(res);
3348 break;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003349
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003350 case Py_NE:
3351 /* By default, != returns the opposite of ==,
3352 unless the latter returns NotImplemented. */
3353 res = PyObject_RichCompare(self, other, Py_EQ);
3354 if (res != NULL && res != Py_NotImplemented) {
3355 int ok = PyObject_IsTrue(res);
3356 Py_DECREF(res);
3357 if (ok < 0)
3358 res = NULL;
3359 else {
3360 if (ok)
3361 res = Py_False;
3362 else
3363 res = Py_True;
3364 Py_INCREF(res);
3365 }
3366 }
3367 break;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003368
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003369 default:
3370 res = Py_NotImplemented;
3371 Py_INCREF(res);
3372 break;
3373 }
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003374
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003375 return res;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003376}
3377
3378static PyObject *
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003379object_get_class(PyObject *self, void *closure)
3380{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003381 Py_INCREF(Py_TYPE(self));
3382 return (PyObject *)(Py_TYPE(self));
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003383}
3384
3385static int
3386equiv_structs(PyTypeObject *a, PyTypeObject *b)
3387{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003388 return a == b ||
3389 (a != NULL &&
3390 b != NULL &&
3391 a->tp_basicsize == b->tp_basicsize &&
3392 a->tp_itemsize == b->tp_itemsize &&
3393 a->tp_dictoffset == b->tp_dictoffset &&
3394 a->tp_weaklistoffset == b->tp_weaklistoffset &&
3395 ((a->tp_flags & Py_TPFLAGS_HAVE_GC) ==
3396 (b->tp_flags & Py_TPFLAGS_HAVE_GC)));
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003397}
3398
3399static int
3400same_slots_added(PyTypeObject *a, PyTypeObject *b)
3401{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003402 PyTypeObject *base = a->tp_base;
3403 Py_ssize_t size;
3404 PyObject *slots_a, *slots_b;
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003405
Benjamin Peterson67641d22011-01-17 19:24:34 +00003406 assert(base == b->tp_base);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003407 size = base->tp_basicsize;
3408 if (a->tp_dictoffset == size && b->tp_dictoffset == size)
3409 size += sizeof(PyObject *);
3410 if (a->tp_weaklistoffset == size && b->tp_weaklistoffset == size)
3411 size += sizeof(PyObject *);
Guido van Rossumd8faa362007-04-27 19:54:29 +00003412
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003413 /* Check slots compliance */
3414 slots_a = ((PyHeapTypeObject *)a)->ht_slots;
3415 slots_b = ((PyHeapTypeObject *)b)->ht_slots;
3416 if (slots_a && slots_b) {
3417 if (PyObject_RichCompareBool(slots_a, slots_b, Py_EQ) != 1)
3418 return 0;
3419 size += sizeof(PyObject *) * PyTuple_GET_SIZE(slots_a);
3420 }
3421 return size == a->tp_basicsize && size == b->tp_basicsize;
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003422}
3423
3424static int
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003425compatible_for_assignment(PyTypeObject* oldto, PyTypeObject* newto, char* attr)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003426{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003427 PyTypeObject *newbase, *oldbase;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003428
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003429 if (newto->tp_dealloc != oldto->tp_dealloc ||
3430 newto->tp_free != oldto->tp_free)
3431 {
3432 PyErr_Format(PyExc_TypeError,
3433 "%s assignment: "
3434 "'%s' deallocator differs from '%s'",
3435 attr,
3436 newto->tp_name,
3437 oldto->tp_name);
3438 return 0;
3439 }
3440 newbase = newto;
3441 oldbase = oldto;
3442 while (equiv_structs(newbase, newbase->tp_base))
3443 newbase = newbase->tp_base;
3444 while (equiv_structs(oldbase, oldbase->tp_base))
3445 oldbase = oldbase->tp_base;
3446 if (newbase != oldbase &&
3447 (newbase->tp_base != oldbase->tp_base ||
3448 !same_slots_added(newbase, oldbase))) {
3449 PyErr_Format(PyExc_TypeError,
3450 "%s assignment: "
3451 "'%s' object layout differs from '%s'",
3452 attr,
3453 newto->tp_name,
3454 oldto->tp_name);
3455 return 0;
3456 }
Tim Petersea7f75d2002-12-07 21:39:16 +00003457
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003458 return 1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003459}
3460
3461static int
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003462object_set_class(PyObject *self, PyObject *value, void *closure)
3463{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003464 PyTypeObject *oldto = Py_TYPE(self);
3465 PyTypeObject *newto;
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003466
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003467 if (value == NULL) {
3468 PyErr_SetString(PyExc_TypeError,
3469 "can't delete __class__ attribute");
3470 return -1;
3471 }
3472 if (!PyType_Check(value)) {
3473 PyErr_Format(PyExc_TypeError,
Florent Xiclunaaa6c1d22011-12-12 18:54:29 +01003474 "__class__ must be set to a class, not '%s' object",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003475 Py_TYPE(value)->tp_name);
3476 return -1;
3477 }
3478 newto = (PyTypeObject *)value;
3479 if (!(newto->tp_flags & Py_TPFLAGS_HEAPTYPE) ||
3480 !(oldto->tp_flags & Py_TPFLAGS_HEAPTYPE))
3481 {
3482 PyErr_Format(PyExc_TypeError,
3483 "__class__ assignment: only for heap types");
3484 return -1;
3485 }
Christian Heimesde4d1832013-07-20 14:19:46 +02003486 if (compatible_for_assignment(oldto, newto, "__class__")) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003487 Py_INCREF(newto);
3488 Py_TYPE(self) = newto;
3489 Py_DECREF(oldto);
3490 return 0;
3491 }
3492 else {
3493 return -1;
3494 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003495}
3496
3497static PyGetSetDef object_getsets[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003498 {"__class__", object_get_class, object_set_class,
3499 PyDoc_STR("the object's class")},
3500 {0}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003501};
3502
Guido van Rossumc53f0092003-02-18 22:05:12 +00003503
Guido van Rossum036f9992003-02-21 22:02:54 +00003504/* Stuff to implement __reduce_ex__ for pickle protocols >= 2.
Alexandre Vassalottif7fa63d2008-05-11 08:55:36 +00003505 We fall back to helpers in copyreg for:
Guido van Rossum036f9992003-02-21 22:02:54 +00003506 - pickle protocols < 2
3507 - calculating the list of slot names (done only once per class)
3508 - the __newobj__ function (which is used as a token but never called)
3509*/
3510
3511static PyObject *
Alexandre Vassalottif7fa63d2008-05-11 08:55:36 +00003512import_copyreg(void)
Guido van Rossum036f9992003-02-21 22:02:54 +00003513{
Alexandre Vassalotti1a830702013-11-30 00:53:09 -08003514 PyObject *copyreg_str;
3515 PyObject *copyreg_module;
3516 PyInterpreterState *interp = PyThreadState_GET()->interp;
3517 _Py_IDENTIFIER(copyreg);
Guido van Rossum3926a632001-09-25 16:25:58 +00003518
Alexandre Vassalotti1a830702013-11-30 00:53:09 -08003519 copyreg_str = _PyUnicode_FromId(&PyId_copyreg);
3520 if (copyreg_str == NULL) {
3521 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003522 }
Alexandre Vassalotti1a830702013-11-30 00:53:09 -08003523 /* Try to fetch cached copy of copyreg from sys.modules first in an
3524 attempt to avoid the import overhead. Previously this was implemented
3525 by storing a reference to the cached module in a static variable, but
3526 this broke when multiple embeded interpreters were in use (see issue
3527 #17408 and #19088). */
3528 copyreg_module = PyDict_GetItemWithError(interp->modules, copyreg_str);
3529 if (copyreg_module != NULL) {
3530 Py_INCREF(copyreg_module);
3531 return copyreg_module;
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003532 }
Alexandre Vassalotti1a830702013-11-30 00:53:09 -08003533 if (PyErr_Occurred()) {
3534 return NULL;
3535 }
3536 return PyImport_Import(copyreg_str);
Guido van Rossum036f9992003-02-21 22:02:54 +00003537}
3538
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01003539Py_LOCAL(PyObject *)
3540_PyType_GetSlotNames(PyTypeObject *cls)
Guido van Rossum036f9992003-02-21 22:02:54 +00003541{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003542 PyObject *copyreg;
3543 PyObject *slotnames;
Victor Stinner3c1e4812012-03-26 22:10:51 +02003544 _Py_IDENTIFIER(__slotnames__);
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02003545 _Py_IDENTIFIER(_slotnames);
Guido van Rossum036f9992003-02-21 22:02:54 +00003546
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01003547 assert(PyType_Check(cls));
3548
3549 /* Get the slot names from the cache in the class if possible. */
3550 slotnames = _PyDict_GetItemIdWithError(cls->tp_dict, &PyId___slotnames__);
3551 if (slotnames != NULL) {
3552 if (slotnames != Py_None && !PyList_Check(slotnames)) {
3553 PyErr_Format(PyExc_TypeError,
3554 "%.200s.__slotnames__ should be a list or None, "
3555 "not %.200s",
3556 cls->tp_name, Py_TYPE(slotnames)->tp_name);
3557 return NULL;
3558 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003559 Py_INCREF(slotnames);
3560 return slotnames;
3561 }
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01003562 else {
3563 if (PyErr_Occurred()) {
3564 return NULL;
3565 }
3566 /* The class does not have the slot names cached yet. */
3567 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003568
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003569 copyreg = import_copyreg();
3570 if (copyreg == NULL)
3571 return NULL;
Guido van Rossum036f9992003-02-21 22:02:54 +00003572
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01003573 /* Use _slotnames function from the copyreg module to find the slots
3574 by this class and its bases. This function will cache the result
3575 in __slotnames__. */
3576 slotnames = _PyObject_CallMethodIdObjArgs(copyreg, &PyId__slotnames,
3577 cls, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003578 Py_DECREF(copyreg);
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01003579 if (slotnames == NULL)
3580 return NULL;
3581
3582 if (slotnames != Py_None && !PyList_Check(slotnames)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003583 PyErr_SetString(PyExc_TypeError,
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01003584 "copyreg._slotnames didn't return a list or None");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003585 Py_DECREF(slotnames);
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01003586 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003587 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003588
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003589 return slotnames;
Guido van Rossum036f9992003-02-21 22:02:54 +00003590}
3591
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01003592Py_LOCAL(PyObject *)
3593_PyObject_GetState(PyObject *obj)
Guido van Rossum036f9992003-02-21 22:02:54 +00003594{
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01003595 PyObject *state;
3596 PyObject *getstate;
Victor Stinner3c1e4812012-03-26 22:10:51 +02003597 _Py_IDENTIFIER(__getstate__);
Guido van Rossum036f9992003-02-21 22:02:54 +00003598
Victor Stinner3c1e4812012-03-26 22:10:51 +02003599 getstate = _PyObject_GetAttrId(obj, &PyId___getstate__);
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01003600 if (getstate == NULL) {
3601 PyObject *slotnames;
3602
3603 if (!PyErr_ExceptionMatches(PyExc_AttributeError)) {
3604 return NULL;
3605 }
3606 PyErr_Clear();
3607
3608 {
3609 PyObject **dict;
3610 dict = _PyObject_GetDictPtr(obj);
Larry Hastings5c661892014-01-24 06:17:25 -08003611 /* It is possible that the object's dict is not initialized
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01003612 yet. In this case, we will return None for the state.
3613 We also return None if the dict is empty to make the behavior
3614 consistent regardless whether the dict was initialized or not.
3615 This make unit testing easier. */
3616 if (dict != NULL && *dict != NULL && PyDict_Size(*dict) > 0) {
3617 state = *dict;
3618 }
3619 else {
3620 state = Py_None;
3621 }
3622 Py_INCREF(state);
3623 }
3624
3625 slotnames = _PyType_GetSlotNames(Py_TYPE(obj));
3626 if (slotnames == NULL) {
3627 Py_DECREF(state);
3628 return NULL;
3629 }
3630
3631 assert(slotnames == Py_None || PyList_Check(slotnames));
3632 if (slotnames != Py_None && Py_SIZE(slotnames) > 0) {
3633 PyObject *slots;
3634 Py_ssize_t slotnames_size, i;
3635
3636 slots = PyDict_New();
3637 if (slots == NULL) {
3638 Py_DECREF(slotnames);
3639 Py_DECREF(state);
3640 return NULL;
3641 }
3642
3643 slotnames_size = Py_SIZE(slotnames);
3644 for (i = 0; i < slotnames_size; i++) {
3645 PyObject *name, *value;
3646
3647 name = PyList_GET_ITEM(slotnames, i);
3648 value = PyObject_GetAttr(obj, name);
3649 if (value == NULL) {
3650 if (!PyErr_ExceptionMatches(PyExc_AttributeError)) {
3651 goto error;
3652 }
3653 /* It is not an error if the attribute is not present. */
3654 PyErr_Clear();
3655 }
3656 else {
3657 int err = PyDict_SetItem(slots, name, value);
3658 Py_DECREF(value);
3659 if (err) {
3660 goto error;
3661 }
3662 }
3663
3664 /* The list is stored on the class so it may mutates while we
3665 iterate over it */
3666 if (slotnames_size != Py_SIZE(slotnames)) {
3667 PyErr_Format(PyExc_RuntimeError,
3668 "__slotsname__ changed size during iteration");
3669 goto error;
3670 }
3671
3672 /* We handle errors within the loop here. */
3673 if (0) {
3674 error:
3675 Py_DECREF(slotnames);
3676 Py_DECREF(slots);
3677 Py_DECREF(state);
3678 return NULL;
3679 }
3680 }
3681
3682 /* If we found some slot attributes, pack them in a tuple along
3683 the orginal attribute dictionary. */
3684 if (PyDict_Size(slots) > 0) {
3685 PyObject *state2;
3686
3687 state2 = PyTuple_Pack(2, state, slots);
3688 Py_DECREF(state);
3689 if (state2 == NULL) {
3690 Py_DECREF(slotnames);
3691 Py_DECREF(slots);
3692 return NULL;
3693 }
3694 state = state2;
3695 }
3696 Py_DECREF(slots);
3697 }
3698 Py_DECREF(slotnames);
3699 }
3700 else { /* getstate != NULL */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003701 state = PyObject_CallObject(getstate, NULL);
3702 Py_DECREF(getstate);
3703 if (state == NULL)
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01003704 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003705 }
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01003706
3707 return state;
3708}
3709
3710Py_LOCAL(int)
3711_PyObject_GetNewArguments(PyObject *obj, PyObject **args, PyObject **kwargs)
3712{
3713 PyObject *getnewargs, *getnewargs_ex;
3714 _Py_IDENTIFIER(__getnewargs_ex__);
3715 _Py_IDENTIFIER(__getnewargs__);
3716
3717 if (args == NULL || kwargs == NULL) {
3718 PyErr_BadInternalCall();
3719 return -1;
3720 }
3721
3722 /* We first attempt to fetch the arguments for __new__ by calling
3723 __getnewargs_ex__ on the object. */
Benjamin Petersone686c5c2014-02-16 13:49:16 -05003724 getnewargs_ex = _PyObject_LookupSpecial(obj, &PyId___getnewargs_ex__);
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01003725 if (getnewargs_ex != NULL) {
3726 PyObject *newargs = PyObject_CallObject(getnewargs_ex, NULL);
3727 Py_DECREF(getnewargs_ex);
3728 if (newargs == NULL) {
3729 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003730 }
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01003731 if (!PyTuple_Check(newargs)) {
3732 PyErr_Format(PyExc_TypeError,
3733 "__getnewargs_ex__ should return a tuple, "
3734 "not '%.200s'", Py_TYPE(newargs)->tp_name);
3735 Py_DECREF(newargs);
3736 return -1;
3737 }
3738 if (Py_SIZE(newargs) != 2) {
3739 PyErr_Format(PyExc_ValueError,
3740 "__getnewargs_ex__ should return a tuple of "
3741 "length 2, not %zd", Py_SIZE(newargs));
3742 Py_DECREF(newargs);
3743 return -1;
3744 }
3745 *args = PyTuple_GET_ITEM(newargs, 0);
3746 Py_INCREF(*args);
3747 *kwargs = PyTuple_GET_ITEM(newargs, 1);
3748 Py_INCREF(*kwargs);
3749 Py_DECREF(newargs);
3750
3751 /* XXX We should perhaps allow None to be passed here. */
3752 if (!PyTuple_Check(*args)) {
3753 PyErr_Format(PyExc_TypeError,
3754 "first item of the tuple returned by "
3755 "__getnewargs_ex__ must be a tuple, not '%.200s'",
3756 Py_TYPE(*args)->tp_name);
3757 Py_CLEAR(*args);
3758 Py_CLEAR(*kwargs);
3759 return -1;
3760 }
3761 if (!PyDict_Check(*kwargs)) {
3762 PyErr_Format(PyExc_TypeError,
3763 "second item of the tuple returned by "
3764 "__getnewargs_ex__ must be a dict, not '%.200s'",
3765 Py_TYPE(*kwargs)->tp_name);
3766 Py_CLEAR(*args);
3767 Py_CLEAR(*kwargs);
3768 return -1;
3769 }
3770 return 0;
Benjamin Petersone686c5c2014-02-16 13:49:16 -05003771 } else if (PyErr_Occurred()) {
3772 return -1;
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01003773 }
3774
3775 /* The object does not have __getnewargs_ex__ so we fallback on using
3776 __getnewargs__ instead. */
Benjamin Petersone686c5c2014-02-16 13:49:16 -05003777 getnewargs = _PyObject_LookupSpecial(obj, &PyId___getnewargs__);
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01003778 if (getnewargs != NULL) {
3779 *args = PyObject_CallObject(getnewargs, NULL);
3780 Py_DECREF(getnewargs);
3781 if (*args == NULL) {
3782 return -1;
3783 }
3784 if (!PyTuple_Check(*args)) {
3785 PyErr_Format(PyExc_TypeError,
3786 "__getnewargs__ should return a tuple, "
3787 "not '%.200s'", Py_TYPE(*args)->tp_name);
3788 Py_CLEAR(*args);
3789 return -1;
3790 }
3791 *kwargs = NULL;
3792 return 0;
Benjamin Petersone686c5c2014-02-16 13:49:16 -05003793 } else if (PyErr_Occurred()) {
3794 return -1;
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01003795 }
3796
3797 /* The object does not have __getnewargs_ex__ and __getnewargs__. This may
3798 means __new__ does not takes any arguments on this object, or that the
3799 object does not implement the reduce protocol for pickling or
3800 copying. */
3801 *args = NULL;
3802 *kwargs = NULL;
3803 return 0;
3804}
3805
3806Py_LOCAL(int)
3807_PyObject_GetItemsIter(PyObject *obj, PyObject **listitems,
3808 PyObject **dictitems)
3809{
3810 if (listitems == NULL || dictitems == NULL) {
3811 PyErr_BadInternalCall();
3812 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003813 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003814
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003815 if (!PyList_Check(obj)) {
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01003816 *listitems = Py_None;
3817 Py_INCREF(*listitems);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003818 }
3819 else {
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01003820 *listitems = PyObject_GetIter(obj);
Christian Heimes2489bd82013-11-23 21:19:43 +01003821 if (*listitems == NULL)
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01003822 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003823 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003824
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003825 if (!PyDict_Check(obj)) {
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01003826 *dictitems = Py_None;
3827 Py_INCREF(*dictitems);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003828 }
3829 else {
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01003830 PyObject *items;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02003831 _Py_IDENTIFIER(items);
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01003832
3833 items = _PyObject_CallMethodIdObjArgs(obj, &PyId_items, NULL);
3834 if (items == NULL) {
3835 Py_CLEAR(*listitems);
3836 return -1;
3837 }
3838 *dictitems = PyObject_GetIter(items);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003839 Py_DECREF(items);
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01003840 if (*dictitems == NULL) {
3841 Py_CLEAR(*listitems);
3842 return -1;
3843 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003844 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003845
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01003846 assert(*listitems != NULL && *dictitems != NULL);
3847
3848 return 0;
3849}
3850
3851static PyObject *
3852reduce_4(PyObject *obj)
3853{
3854 PyObject *args = NULL, *kwargs = NULL;
3855 PyObject *copyreg;
3856 PyObject *newobj, *newargs, *state, *listitems, *dictitems;
3857 PyObject *result;
3858 _Py_IDENTIFIER(__newobj_ex__);
3859
3860 if (_PyObject_GetNewArguments(obj, &args, &kwargs) < 0) {
3861 return NULL;
3862 }
3863 if (args == NULL) {
3864 args = PyTuple_New(0);
3865 if (args == NULL)
3866 return NULL;
3867 }
3868 if (kwargs == NULL) {
3869 kwargs = PyDict_New();
3870 if (kwargs == NULL)
3871 return NULL;
3872 }
3873
3874 copyreg = import_copyreg();
3875 if (copyreg == NULL) {
3876 Py_DECREF(args);
3877 Py_DECREF(kwargs);
3878 return NULL;
3879 }
3880 newobj = _PyObject_GetAttrId(copyreg, &PyId___newobj_ex__);
3881 Py_DECREF(copyreg);
3882 if (newobj == NULL) {
3883 Py_DECREF(args);
3884 Py_DECREF(kwargs);
3885 return NULL;
3886 }
3887 newargs = PyTuple_Pack(3, Py_TYPE(obj), args, kwargs);
3888 Py_DECREF(args);
3889 Py_DECREF(kwargs);
3890 if (newargs == NULL) {
3891 Py_DECREF(newobj);
3892 return NULL;
3893 }
3894 state = _PyObject_GetState(obj);
3895 if (state == NULL) {
3896 Py_DECREF(newobj);
3897 Py_DECREF(newargs);
3898 return NULL;
3899 }
3900 if (_PyObject_GetItemsIter(obj, &listitems, &dictitems) < 0) {
3901 Py_DECREF(newobj);
3902 Py_DECREF(newargs);
3903 Py_DECREF(state);
3904 return NULL;
3905 }
3906
3907 result = PyTuple_Pack(5, newobj, newargs, state, listitems, dictitems);
3908 Py_DECREF(newobj);
3909 Py_DECREF(newargs);
3910 Py_DECREF(state);
3911 Py_DECREF(listitems);
3912 Py_DECREF(dictitems);
Larry Hastings5c661892014-01-24 06:17:25 -08003913 return result;
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01003914}
3915
3916static PyObject *
3917reduce_2(PyObject *obj)
3918{
3919 PyObject *cls;
3920 PyObject *args = NULL, *args2 = NULL, *kwargs = NULL;
3921 PyObject *state = NULL, *listitems = NULL, *dictitems = NULL;
3922 PyObject *copyreg = NULL, *newobj = NULL, *res = NULL;
3923 Py_ssize_t i, n;
3924 _Py_IDENTIFIER(__newobj__);
3925
3926 if (_PyObject_GetNewArguments(obj, &args, &kwargs) < 0) {
3927 return NULL;
3928 }
3929 if (args == NULL) {
3930 assert(kwargs == NULL);
3931 args = PyTuple_New(0);
3932 if (args == NULL) {
3933 return NULL;
3934 }
3935 }
3936 else if (kwargs != NULL) {
3937 if (PyDict_Size(kwargs) > 0) {
Larry Hastings5c661892014-01-24 06:17:25 -08003938 PyErr_SetString(PyExc_ValueError,
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01003939 "must use protocol 4 or greater to copy this "
3940 "object; since __getnewargs_ex__ returned "
3941 "keyword arguments.");
3942 Py_DECREF(args);
3943 Py_DECREF(kwargs);
3944 return NULL;
3945 }
3946 Py_CLEAR(kwargs);
3947 }
3948
3949 state = _PyObject_GetState(obj);
3950 if (state == NULL)
3951 goto end;
3952
3953 if (_PyObject_GetItemsIter(obj, &listitems, &dictitems) < 0)
3954 goto end;
3955
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003956 copyreg = import_copyreg();
3957 if (copyreg == NULL)
3958 goto end;
Victor Stinner3c1e4812012-03-26 22:10:51 +02003959 newobj = _PyObject_GetAttrId(copyreg, &PyId___newobj__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003960 if (newobj == NULL)
3961 goto end;
Guido van Rossum036f9992003-02-21 22:02:54 +00003962
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003963 n = PyTuple_GET_SIZE(args);
3964 args2 = PyTuple_New(n+1);
3965 if (args2 == NULL)
3966 goto end;
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01003967 cls = (PyObject *) Py_TYPE(obj);
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01003968 Py_INCREF(cls);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003969 PyTuple_SET_ITEM(args2, 0, cls);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003970 for (i = 0; i < n; i++) {
3971 PyObject *v = PyTuple_GET_ITEM(args, i);
3972 Py_INCREF(v);
3973 PyTuple_SET_ITEM(args2, i+1, v);
3974 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003975
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003976 res = PyTuple_Pack(5, newobj, args2, state, listitems, dictitems);
Guido van Rossum036f9992003-02-21 22:02:54 +00003977
3978 end:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003979 Py_XDECREF(args);
3980 Py_XDECREF(args2);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003981 Py_XDECREF(state);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003982 Py_XDECREF(listitems);
3983 Py_XDECREF(dictitems);
3984 Py_XDECREF(copyreg);
3985 Py_XDECREF(newobj);
3986 return res;
Guido van Rossum036f9992003-02-21 22:02:54 +00003987}
3988
Guido van Rossumd8faa362007-04-27 19:54:29 +00003989/*
3990 * There were two problems when object.__reduce__ and object.__reduce_ex__
3991 * were implemented in the same function:
3992 * - trying to pickle an object with a custom __reduce__ method that
3993 * fell back to object.__reduce__ in certain circumstances led to
3994 * infinite recursion at Python level and eventual RuntimeError.
3995 * - Pickling objects that lied about their type by overwriting the
3996 * __class__ descriptor could lead to infinite recursion at C level
3997 * and eventual segfault.
3998 *
3999 * Because of backwards compatibility, the two methods still have to
4000 * behave in the same way, even if this is not required by the pickle
4001 * protocol. This common functionality was moved to the _common_reduce
4002 * function.
4003 */
4004static PyObject *
4005_common_reduce(PyObject *self, int proto)
4006{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004007 PyObject *copyreg, *res;
Guido van Rossumd8faa362007-04-27 19:54:29 +00004008
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004009 if (proto >= 4)
4010 return reduce_4(self);
4011 else if (proto >= 2)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004012 return reduce_2(self);
Guido van Rossumd8faa362007-04-27 19:54:29 +00004013
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004014 copyreg = import_copyreg();
4015 if (!copyreg)
4016 return NULL;
Guido van Rossumd8faa362007-04-27 19:54:29 +00004017
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004018 res = PyEval_CallMethod(copyreg, "_reduce_ex", "(Oi)", self, proto);
4019 Py_DECREF(copyreg);
Guido van Rossumd8faa362007-04-27 19:54:29 +00004020
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004021 return res;
Guido van Rossumd8faa362007-04-27 19:54:29 +00004022}
4023
4024static PyObject *
4025object_reduce(PyObject *self, PyObject *args)
4026{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004027 int proto = 0;
Guido van Rossumd8faa362007-04-27 19:54:29 +00004028
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004029 if (!PyArg_ParseTuple(args, "|i:__reduce__", &proto))
4030 return NULL;
Guido van Rossumd8faa362007-04-27 19:54:29 +00004031
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004032 return _common_reduce(self, proto);
Guido van Rossumd8faa362007-04-27 19:54:29 +00004033}
4034
Guido van Rossum036f9992003-02-21 22:02:54 +00004035static PyObject *
4036object_reduce_ex(PyObject *self, PyObject *args)
4037{
Victor Stinner3c1e4812012-03-26 22:10:51 +02004038 static PyObject *objreduce;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004039 PyObject *reduce, *res;
4040 int proto = 0;
Victor Stinner3c1e4812012-03-26 22:10:51 +02004041 _Py_IDENTIFIER(__reduce__);
Guido van Rossum036f9992003-02-21 22:02:54 +00004042
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004043 if (!PyArg_ParseTuple(args, "|i:__reduce_ex__", &proto))
4044 return NULL;
Guido van Rossum036f9992003-02-21 22:02:54 +00004045
Victor Stinner3c1e4812012-03-26 22:10:51 +02004046 if (objreduce == NULL) {
4047 objreduce = _PyDict_GetItemId(PyBaseObject_Type.tp_dict,
4048 &PyId___reduce__);
4049 if (objreduce == NULL)
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01004050 return NULL;
4051 }
4052
Victor Stinner3c1e4812012-03-26 22:10:51 +02004053 reduce = _PyObject_GetAttrId(self, &PyId___reduce__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004054 if (reduce == NULL)
4055 PyErr_Clear();
4056 else {
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01004057 PyObject *cls, *clsreduce;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004058 int override;
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01004059
4060 cls = (PyObject *) Py_TYPE(self);
Victor Stinner3c1e4812012-03-26 22:10:51 +02004061 clsreduce = _PyObject_GetAttrId(cls, &PyId___reduce__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004062 if (clsreduce == NULL) {
4063 Py_DECREF(reduce);
4064 return NULL;
4065 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004066 override = (clsreduce != objreduce);
4067 Py_DECREF(clsreduce);
4068 if (override) {
4069 res = PyObject_CallObject(reduce, NULL);
4070 Py_DECREF(reduce);
4071 return res;
4072 }
4073 else
4074 Py_DECREF(reduce);
4075 }
Guido van Rossum036f9992003-02-21 22:02:54 +00004076
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004077 return _common_reduce(self, proto);
Guido van Rossum3926a632001-09-25 16:25:58 +00004078}
4079
Christian Heimes9e7f1d22008-02-28 12:27:11 +00004080static PyObject *
4081object_subclasshook(PyObject *cls, PyObject *args)
4082{
Brian Curtindfc80e32011-08-10 20:28:54 -05004083 Py_RETURN_NOTIMPLEMENTED;
Christian Heimes9e7f1d22008-02-28 12:27:11 +00004084}
4085
4086PyDoc_STRVAR(object_subclasshook_doc,
4087"Abstract classes can override this to customize issubclass().\n"
4088"\n"
4089"This is invoked early on by abc.ABCMeta.__subclasscheck__().\n"
4090"It should return True, False or NotImplemented. If it returns\n"
4091"NotImplemented, the normal algorithm is used. Otherwise, it\n"
4092"overrides the normal algorithm (and the outcome is cached).\n");
Eric Smith8c663262007-08-25 02:26:07 +00004093
4094/*
4095 from PEP 3101, this code implements:
4096
4097 class object:
4098 def __format__(self, format_spec):
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004099 return format(str(self), format_spec)
Eric Smith8c663262007-08-25 02:26:07 +00004100*/
4101static PyObject *
4102object_format(PyObject *self, PyObject *args)
4103{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004104 PyObject *format_spec;
4105 PyObject *self_as_str = NULL;
4106 PyObject *result = NULL;
Eric Smith8c663262007-08-25 02:26:07 +00004107
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004108 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
4109 return NULL;
Eric Smith8c663262007-08-25 02:26:07 +00004110
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004111 self_as_str = PyObject_Str(self);
Eric Smithe4d63172010-09-13 20:48:43 +00004112 if (self_as_str != NULL) {
4113 /* Issue 7994: If we're converting to a string, we
Eric V. Smithb9cd3532011-03-12 10:08:48 -05004114 should reject format specifications */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004115 if (PyUnicode_GET_LENGTH(format_spec) > 0) {
Andrew Svetlov2cd8ce42012-12-23 14:27:17 +02004116 PyErr_SetString(PyExc_TypeError,
Eric V. Smithb9cd3532011-03-12 10:08:48 -05004117 "non-empty format string passed to object.__format__");
Andrew Svetlov2cd8ce42012-12-23 14:27:17 +02004118 goto done;
Eric V. Smithb9cd3532011-03-12 10:08:48 -05004119 }
Eric Smith8c663262007-08-25 02:26:07 +00004120
Eric V. Smithb9cd3532011-03-12 10:08:48 -05004121 result = PyObject_Format(self_as_str, format_spec);
Eric Smithe4d63172010-09-13 20:48:43 +00004122 }
4123
4124done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004125 Py_XDECREF(self_as_str);
Eric Smith8c663262007-08-25 02:26:07 +00004126
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004127 return result;
Eric Smith8c663262007-08-25 02:26:07 +00004128}
4129
Martin v. Löwis00709aa2008-06-04 14:18:43 +00004130static PyObject *
4131object_sizeof(PyObject *self, PyObject *args)
4132{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004133 Py_ssize_t res, isize;
Martin v. Löwis00709aa2008-06-04 14:18:43 +00004134
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004135 res = 0;
4136 isize = self->ob_type->tp_itemsize;
4137 if (isize > 0)
4138 res = Py_SIZE(self->ob_type) * isize;
4139 res += self->ob_type->tp_basicsize;
Martin v. Löwis00709aa2008-06-04 14:18:43 +00004140
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004141 return PyLong_FromSsize_t(res);
Martin v. Löwis00709aa2008-06-04 14:18:43 +00004142}
4143
Benjamin Peterson82b00c12011-05-24 11:09:06 -05004144/* __dir__ for generic objects: returns __dict__, __class__,
4145 and recursively up the __class__.__bases__ chain.
4146*/
4147static PyObject *
4148object_dir(PyObject *self, PyObject *args)
4149{
4150 PyObject *result = NULL;
4151 PyObject *dict = NULL;
4152 PyObject *itsclass = NULL;
4153
4154 /* Get __dict__ (which may or may not be a real dict...) */
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02004155 dict = _PyObject_GetAttrId(self, &PyId___dict__);
Benjamin Peterson82b00c12011-05-24 11:09:06 -05004156 if (dict == NULL) {
4157 PyErr_Clear();
4158 dict = PyDict_New();
4159 }
4160 else if (!PyDict_Check(dict)) {
4161 Py_DECREF(dict);
4162 dict = PyDict_New();
4163 }
4164 else {
4165 /* Copy __dict__ to avoid mutating it. */
4166 PyObject *temp = PyDict_Copy(dict);
4167 Py_DECREF(dict);
4168 dict = temp;
4169 }
4170
4171 if (dict == NULL)
4172 goto error;
4173
4174 /* Merge in attrs reachable from its class. */
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02004175 itsclass = _PyObject_GetAttrId(self, &PyId___class__);
Benjamin Peterson82b00c12011-05-24 11:09:06 -05004176 if (itsclass == NULL)
4177 /* XXX(tomer): Perhaps fall back to obj->ob_type if no
4178 __class__ exists? */
4179 PyErr_Clear();
4180 else if (merge_class_dict(dict, itsclass) != 0)
4181 goto error;
4182
4183 result = PyDict_Keys(dict);
4184 /* fall through */
4185error:
4186 Py_XDECREF(itsclass);
4187 Py_XDECREF(dict);
4188 return result;
4189}
4190
Guido van Rossum3926a632001-09-25 16:25:58 +00004191static PyMethodDef object_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004192 {"__reduce_ex__", object_reduce_ex, METH_VARARGS,
4193 PyDoc_STR("helper for pickle")},
4194 {"__reduce__", object_reduce, METH_VARARGS,
4195 PyDoc_STR("helper for pickle")},
4196 {"__subclasshook__", object_subclasshook, METH_CLASS | METH_VARARGS,
4197 object_subclasshook_doc},
4198 {"__format__", object_format, METH_VARARGS,
4199 PyDoc_STR("default object formatter")},
4200 {"__sizeof__", object_sizeof, METH_NOARGS,
Benjamin Petersonfbe56bb2011-05-24 12:42:51 -05004201 PyDoc_STR("__sizeof__() -> int\nsize of object in memory, in bytes")},
Benjamin Peterson82b00c12011-05-24 11:09:06 -05004202 {"__dir__", object_dir, METH_NOARGS,
Benjamin Petersonc7284122011-05-24 12:46:15 -05004203 PyDoc_STR("__dir__() -> list\ndefault dir() implementation")},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004204 {0}
Guido van Rossum3926a632001-09-25 16:25:58 +00004205};
4206
Guido van Rossum036f9992003-02-21 22:02:54 +00004207
Tim Peters6d6c1a32001-08-02 04:15:00 +00004208PyTypeObject PyBaseObject_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004209 PyVarObject_HEAD_INIT(&PyType_Type, 0)
4210 "object", /* tp_name */
4211 sizeof(PyObject), /* tp_basicsize */
4212 0, /* tp_itemsize */
4213 object_dealloc, /* tp_dealloc */
4214 0, /* tp_print */
4215 0, /* tp_getattr */
4216 0, /* tp_setattr */
4217 0, /* tp_reserved */
4218 object_repr, /* tp_repr */
4219 0, /* tp_as_number */
4220 0, /* tp_as_sequence */
4221 0, /* tp_as_mapping */
4222 (hashfunc)_Py_HashPointer, /* tp_hash */
4223 0, /* tp_call */
4224 object_str, /* tp_str */
4225 PyObject_GenericGetAttr, /* tp_getattro */
4226 PyObject_GenericSetAttr, /* tp_setattro */
4227 0, /* tp_as_buffer */
Larry Hastings5c661892014-01-24 06:17:25 -08004228 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Larry Hastings2623c8c2014-02-08 22:15:29 -08004229 PyDoc_STR("object()\n--\n\nThe most base type"), /* tp_doc */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004230 0, /* tp_traverse */
4231 0, /* tp_clear */
4232 object_richcompare, /* tp_richcompare */
4233 0, /* tp_weaklistoffset */
4234 0, /* tp_iter */
4235 0, /* tp_iternext */
4236 object_methods, /* tp_methods */
4237 0, /* tp_members */
4238 object_getsets, /* tp_getset */
4239 0, /* tp_base */
4240 0, /* tp_dict */
4241 0, /* tp_descr_get */
4242 0, /* tp_descr_set */
4243 0, /* tp_dictoffset */
4244 object_init, /* tp_init */
4245 PyType_GenericAlloc, /* tp_alloc */
4246 object_new, /* tp_new */
4247 PyObject_Del, /* tp_free */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004248};
4249
4250
Guido van Rossum50e9fb92006-08-17 05:42:55 +00004251/* Add the methods from tp_methods to the __dict__ in a type object */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004252
4253static int
4254add_methods(PyTypeObject *type, PyMethodDef *meth)
4255{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004256 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004257
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004258 for (; meth->ml_name != NULL; meth++) {
4259 PyObject *descr;
Benjamin Peterson89a6e9a2012-05-08 09:22:24 -04004260 int err;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004261 if (PyDict_GetItemString(dict, meth->ml_name) &&
4262 !(meth->ml_flags & METH_COEXIST))
4263 continue;
4264 if (meth->ml_flags & METH_CLASS) {
4265 if (meth->ml_flags & METH_STATIC) {
4266 PyErr_SetString(PyExc_ValueError,
4267 "method cannot be both class and static");
4268 return -1;
4269 }
4270 descr = PyDescr_NewClassMethod(type, meth);
4271 }
4272 else if (meth->ml_flags & METH_STATIC) {
Andrew Svetlov3ba3a3e2012-12-25 13:32:35 +02004273 PyObject *cfunc = PyCFunction_NewEx(meth, (PyObject*)type, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004274 if (cfunc == NULL)
4275 return -1;
4276 descr = PyStaticMethod_New(cfunc);
4277 Py_DECREF(cfunc);
4278 }
4279 else {
4280 descr = PyDescr_NewMethod(type, meth);
4281 }
4282 if (descr == NULL)
4283 return -1;
Benjamin Peterson89a6e9a2012-05-08 09:22:24 -04004284 err = PyDict_SetItemString(dict, meth->ml_name, descr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004285 Py_DECREF(descr);
Benjamin Peterson89a6e9a2012-05-08 09:22:24 -04004286 if (err < 0)
4287 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004288 }
4289 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004290}
4291
4292static int
Guido van Rossum6f799372001-09-20 20:46:19 +00004293add_members(PyTypeObject *type, PyMemberDef *memb)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004294{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004295 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004296
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004297 for (; memb->name != NULL; memb++) {
4298 PyObject *descr;
4299 if (PyDict_GetItemString(dict, memb->name))
4300 continue;
4301 descr = PyDescr_NewMember(type, memb);
4302 if (descr == NULL)
4303 return -1;
4304 if (PyDict_SetItemString(dict, memb->name, descr) < 0)
4305 return -1;
4306 Py_DECREF(descr);
4307 }
4308 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004309}
4310
4311static int
Guido van Rossum32d34c82001-09-20 21:45:26 +00004312add_getset(PyTypeObject *type, PyGetSetDef *gsp)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004313{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004314 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004315
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004316 for (; gsp->name != NULL; gsp++) {
4317 PyObject *descr;
4318 if (PyDict_GetItemString(dict, gsp->name))
4319 continue;
4320 descr = PyDescr_NewGetSet(type, gsp);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004321
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004322 if (descr == NULL)
4323 return -1;
4324 if (PyDict_SetItemString(dict, gsp->name, descr) < 0)
4325 return -1;
4326 Py_DECREF(descr);
4327 }
4328 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004329}
4330
Guido van Rossum13d52f02001-08-10 21:24:08 +00004331static void
4332inherit_special(PyTypeObject *type, PyTypeObject *base)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004333{
Tim Peters6d6c1a32001-08-02 04:15:00 +00004334
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004335 /* Copying basicsize is connected to the GC flags */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004336 if (!(type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
4337 (base->tp_flags & Py_TPFLAGS_HAVE_GC) &&
4338 (!type->tp_traverse && !type->tp_clear)) {
4339 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
4340 if (type->tp_traverse == NULL)
4341 type->tp_traverse = base->tp_traverse;
4342 if (type->tp_clear == NULL)
4343 type->tp_clear = base->tp_clear;
4344 }
4345 {
4346 /* The condition below could use some explanation.
4347 It appears that tp_new is not inherited for static types
4348 whose base class is 'object'; this seems to be a precaution
4349 so that old extension types don't suddenly become
4350 callable (object.__new__ wouldn't insure the invariants
4351 that the extension type's own factory function ensures).
4352 Heap types, of course, are under our control, so they do
4353 inherit tp_new; static extension types that specify some
Florent Xiclunaaa6c1d22011-12-12 18:54:29 +01004354 other built-in type as the default also
4355 inherit object.__new__. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004356 if (base != &PyBaseObject_Type ||
4357 (type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
4358 if (type->tp_new == NULL)
4359 type->tp_new = base->tp_new;
4360 }
4361 }
Benjamin Petersona7465e22010-07-05 15:01:22 +00004362 if (type->tp_basicsize == 0)
4363 type->tp_basicsize = base->tp_basicsize;
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00004364
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004365 /* Copy other non-function slots */
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00004366
4367#undef COPYVAL
4368#define COPYVAL(SLOT) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004369 if (type->SLOT == 0) type->SLOT = base->SLOT
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00004370
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004371 COPYVAL(tp_itemsize);
4372 COPYVAL(tp_weaklistoffset);
4373 COPYVAL(tp_dictoffset);
Thomas Wouters27d517b2007-02-25 20:39:11 +00004374
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004375 /* Setup fast subclass flags */
4376 if (PyType_IsSubtype(base, (PyTypeObject*)PyExc_BaseException))
4377 type->tp_flags |= Py_TPFLAGS_BASE_EXC_SUBCLASS;
4378 else if (PyType_IsSubtype(base, &PyType_Type))
4379 type->tp_flags |= Py_TPFLAGS_TYPE_SUBCLASS;
4380 else if (PyType_IsSubtype(base, &PyLong_Type))
4381 type->tp_flags |= Py_TPFLAGS_LONG_SUBCLASS;
4382 else if (PyType_IsSubtype(base, &PyBytes_Type))
4383 type->tp_flags |= Py_TPFLAGS_BYTES_SUBCLASS;
4384 else if (PyType_IsSubtype(base, &PyUnicode_Type))
4385 type->tp_flags |= Py_TPFLAGS_UNICODE_SUBCLASS;
4386 else if (PyType_IsSubtype(base, &PyTuple_Type))
4387 type->tp_flags |= Py_TPFLAGS_TUPLE_SUBCLASS;
4388 else if (PyType_IsSubtype(base, &PyList_Type))
4389 type->tp_flags |= Py_TPFLAGS_LIST_SUBCLASS;
4390 else if (PyType_IsSubtype(base, &PyDict_Type))
4391 type->tp_flags |= Py_TPFLAGS_DICT_SUBCLASS;
Guido van Rossum13d52f02001-08-10 21:24:08 +00004392}
4393
Guido van Rossum38938152006-08-21 23:36:26 +00004394static int
Guido van Rossumf5243f02008-01-01 04:06:48 +00004395overrides_hash(PyTypeObject *type)
Guido van Rossum38938152006-08-21 23:36:26 +00004396{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004397 PyObject *dict = type->tp_dict;
Victor Stinner3c1e4812012-03-26 22:10:51 +02004398 _Py_IDENTIFIER(__eq__);
Guido van Rossum38938152006-08-21 23:36:26 +00004399
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004400 assert(dict != NULL);
Victor Stinner3c1e4812012-03-26 22:10:51 +02004401 if (_PyDict_GetItemId(dict, &PyId___eq__) != NULL)
4402 return 1;
4403 if (_PyDict_GetItemId(dict, &PyId___hash__) != NULL)
4404 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004405 return 0;
Guido van Rossum38938152006-08-21 23:36:26 +00004406}
4407
Guido van Rossum13d52f02001-08-10 21:24:08 +00004408static void
4409inherit_slots(PyTypeObject *type, PyTypeObject *base)
4410{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004411 PyTypeObject *basebase;
Guido van Rossum13d52f02001-08-10 21:24:08 +00004412
4413#undef SLOTDEFINED
Tim Peters6d6c1a32001-08-02 04:15:00 +00004414#undef COPYSLOT
4415#undef COPYNUM
4416#undef COPYSEQ
4417#undef COPYMAP
Guido van Rossum5af588b2001-10-12 14:13:21 +00004418#undef COPYBUF
Guido van Rossum13d52f02001-08-10 21:24:08 +00004419
4420#define SLOTDEFINED(SLOT) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004421 (base->SLOT != 0 && \
4422 (basebase == NULL || base->SLOT != basebase->SLOT))
Guido van Rossum13d52f02001-08-10 21:24:08 +00004423
Tim Peters6d6c1a32001-08-02 04:15:00 +00004424#define COPYSLOT(SLOT) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004425 if (!type->SLOT && SLOTDEFINED(SLOT)) type->SLOT = base->SLOT
Tim Peters6d6c1a32001-08-02 04:15:00 +00004426
4427#define COPYNUM(SLOT) COPYSLOT(tp_as_number->SLOT)
4428#define COPYSEQ(SLOT) COPYSLOT(tp_as_sequence->SLOT)
4429#define COPYMAP(SLOT) COPYSLOT(tp_as_mapping->SLOT)
Tim Petersfc57ccb2001-10-12 02:38:24 +00004430#define COPYBUF(SLOT) COPYSLOT(tp_as_buffer->SLOT)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004431
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004432 /* This won't inherit indirect slots (from tp_as_number etc.)
4433 if type doesn't provide the space. */
Guido van Rossum13d52f02001-08-10 21:24:08 +00004434
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004435 if (type->tp_as_number != NULL && base->tp_as_number != NULL) {
4436 basebase = base->tp_base;
4437 if (basebase->tp_as_number == NULL)
4438 basebase = NULL;
4439 COPYNUM(nb_add);
4440 COPYNUM(nb_subtract);
4441 COPYNUM(nb_multiply);
4442 COPYNUM(nb_remainder);
4443 COPYNUM(nb_divmod);
4444 COPYNUM(nb_power);
4445 COPYNUM(nb_negative);
4446 COPYNUM(nb_positive);
4447 COPYNUM(nb_absolute);
4448 COPYNUM(nb_bool);
4449 COPYNUM(nb_invert);
4450 COPYNUM(nb_lshift);
4451 COPYNUM(nb_rshift);
4452 COPYNUM(nb_and);
4453 COPYNUM(nb_xor);
4454 COPYNUM(nb_or);
4455 COPYNUM(nb_int);
4456 COPYNUM(nb_float);
4457 COPYNUM(nb_inplace_add);
4458 COPYNUM(nb_inplace_subtract);
4459 COPYNUM(nb_inplace_multiply);
4460 COPYNUM(nb_inplace_remainder);
4461 COPYNUM(nb_inplace_power);
4462 COPYNUM(nb_inplace_lshift);
4463 COPYNUM(nb_inplace_rshift);
4464 COPYNUM(nb_inplace_and);
4465 COPYNUM(nb_inplace_xor);
4466 COPYNUM(nb_inplace_or);
4467 COPYNUM(nb_true_divide);
4468 COPYNUM(nb_floor_divide);
4469 COPYNUM(nb_inplace_true_divide);
4470 COPYNUM(nb_inplace_floor_divide);
4471 COPYNUM(nb_index);
4472 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004473
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004474 if (type->tp_as_sequence != NULL && base->tp_as_sequence != NULL) {
4475 basebase = base->tp_base;
4476 if (basebase->tp_as_sequence == NULL)
4477 basebase = NULL;
4478 COPYSEQ(sq_length);
4479 COPYSEQ(sq_concat);
4480 COPYSEQ(sq_repeat);
4481 COPYSEQ(sq_item);
4482 COPYSEQ(sq_ass_item);
4483 COPYSEQ(sq_contains);
4484 COPYSEQ(sq_inplace_concat);
4485 COPYSEQ(sq_inplace_repeat);
4486 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004487
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004488 if (type->tp_as_mapping != NULL && base->tp_as_mapping != NULL) {
4489 basebase = base->tp_base;
4490 if (basebase->tp_as_mapping == NULL)
4491 basebase = NULL;
4492 COPYMAP(mp_length);
4493 COPYMAP(mp_subscript);
4494 COPYMAP(mp_ass_subscript);
4495 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004496
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004497 if (type->tp_as_buffer != NULL && base->tp_as_buffer != NULL) {
4498 basebase = base->tp_base;
4499 if (basebase->tp_as_buffer == NULL)
4500 basebase = NULL;
4501 COPYBUF(bf_getbuffer);
4502 COPYBUF(bf_releasebuffer);
4503 }
Tim Petersfc57ccb2001-10-12 02:38:24 +00004504
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004505 basebase = base->tp_base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004506
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004507 COPYSLOT(tp_dealloc);
4508 if (type->tp_getattr == NULL && type->tp_getattro == NULL) {
4509 type->tp_getattr = base->tp_getattr;
4510 type->tp_getattro = base->tp_getattro;
4511 }
4512 if (type->tp_setattr == NULL && type->tp_setattro == NULL) {
4513 type->tp_setattr = base->tp_setattr;
4514 type->tp_setattro = base->tp_setattro;
4515 }
4516 /* tp_reserved is ignored */
4517 COPYSLOT(tp_repr);
4518 /* tp_hash see tp_richcompare */
4519 COPYSLOT(tp_call);
4520 COPYSLOT(tp_str);
4521 {
4522 /* Copy comparison-related slots only when
4523 not overriding them anywhere */
4524 if (type->tp_richcompare == NULL &&
4525 type->tp_hash == NULL &&
4526 !overrides_hash(type))
4527 {
4528 type->tp_richcompare = base->tp_richcompare;
4529 type->tp_hash = base->tp_hash;
4530 }
4531 }
4532 {
4533 COPYSLOT(tp_iter);
4534 COPYSLOT(tp_iternext);
4535 }
4536 {
4537 COPYSLOT(tp_descr_get);
4538 COPYSLOT(tp_descr_set);
4539 COPYSLOT(tp_dictoffset);
4540 COPYSLOT(tp_init);
4541 COPYSLOT(tp_alloc);
4542 COPYSLOT(tp_is_gc);
Antoine Pitrou796564c2013-07-30 19:59:21 +02004543 if ((type->tp_flags & Py_TPFLAGS_HAVE_FINALIZE) &&
4544 (base->tp_flags & Py_TPFLAGS_HAVE_FINALIZE)) {
4545 COPYSLOT(tp_finalize);
4546 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004547 if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) ==
4548 (base->tp_flags & Py_TPFLAGS_HAVE_GC)) {
4549 /* They agree about gc. */
4550 COPYSLOT(tp_free);
4551 }
4552 else if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
4553 type->tp_free == NULL &&
4554 base->tp_free == PyObject_Free) {
4555 /* A bit of magic to plug in the correct default
4556 * tp_free function when a derived class adds gc,
4557 * didn't define tp_free, and the base uses the
4558 * default non-gc tp_free.
4559 */
4560 type->tp_free = PyObject_GC_Del;
4561 }
4562 /* else they didn't agree about gc, and there isn't something
4563 * obvious to be done -- the type is on its own.
4564 */
4565 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004566}
4567
Jeremy Hylton938ace62002-07-17 16:30:39 +00004568static int add_operators(PyTypeObject *);
Guido van Rossum13d52f02001-08-10 21:24:08 +00004569
Tim Peters6d6c1a32001-08-02 04:15:00 +00004570int
Guido van Rossum528b7eb2001-08-07 17:24:28 +00004571PyType_Ready(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004572{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004573 PyObject *dict, *bases;
4574 PyTypeObject *base;
4575 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004576
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004577 if (type->tp_flags & Py_TPFLAGS_READY) {
4578 assert(type->tp_dict != NULL);
4579 return 0;
4580 }
4581 assert((type->tp_flags & Py_TPFLAGS_READYING) == 0);
Guido van Rossumd614f972001-08-10 17:39:49 +00004582
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004583 type->tp_flags |= Py_TPFLAGS_READYING;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004584
Tim Peters36eb4df2003-03-23 03:33:13 +00004585#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004586 /* PyType_Ready is the closest thing we have to a choke point
4587 * for type objects, so is the best place I can think of to try
4588 * to get type objects into the doubly-linked list of all objects.
4589 * Still, not all type objects go thru PyType_Ready.
4590 */
4591 _Py_AddToAllObjects((PyObject *)type, 0);
Tim Peters36eb4df2003-03-23 03:33:13 +00004592#endif
4593
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004594 /* Initialize tp_base (defaults to BaseObject unless that's us) */
4595 base = type->tp_base;
4596 if (base == NULL && type != &PyBaseObject_Type) {
4597 base = type->tp_base = &PyBaseObject_Type;
4598 Py_INCREF(base);
4599 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004600
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004601 /* Now the only way base can still be NULL is if type is
4602 * &PyBaseObject_Type.
4603 */
Guido van Rossum692cdbc2006-03-10 02:04:28 +00004604
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004605 /* Initialize the base class */
4606 if (base != NULL && base->tp_dict == NULL) {
4607 if (PyType_Ready(base) < 0)
4608 goto error;
4609 }
Guido van Rossum323a9cf2002-08-14 17:26:30 +00004610
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004611 /* Initialize ob_type if NULL. This means extensions that want to be
4612 compilable separately on Windows can call PyType_Ready() instead of
4613 initializing the ob_type field of their type objects. */
4614 /* The test for base != NULL is really unnecessary, since base is only
4615 NULL when type is &PyBaseObject_Type, and we know its ob_type is
4616 not NULL (it's initialized to &PyType_Type). But coverity doesn't
4617 know that. */
4618 if (Py_TYPE(type) == NULL && base != NULL)
4619 Py_TYPE(type) = Py_TYPE(base);
Guido van Rossum0986d822002-04-08 01:38:42 +00004620
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004621 /* Initialize tp_bases */
4622 bases = type->tp_bases;
4623 if (bases == NULL) {
4624 if (base == NULL)
4625 bases = PyTuple_New(0);
4626 else
4627 bases = PyTuple_Pack(1, base);
4628 if (bases == NULL)
4629 goto error;
4630 type->tp_bases = bases;
4631 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004632
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004633 /* Initialize tp_dict */
4634 dict = type->tp_dict;
4635 if (dict == NULL) {
4636 dict = PyDict_New();
4637 if (dict == NULL)
4638 goto error;
4639 type->tp_dict = dict;
4640 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004641
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004642 /* Add type-specific descriptors to tp_dict */
4643 if (add_operators(type) < 0)
4644 goto error;
4645 if (type->tp_methods != NULL) {
4646 if (add_methods(type, type->tp_methods) < 0)
4647 goto error;
4648 }
4649 if (type->tp_members != NULL) {
4650 if (add_members(type, type->tp_members) < 0)
4651 goto error;
4652 }
4653 if (type->tp_getset != NULL) {
4654 if (add_getset(type, type->tp_getset) < 0)
4655 goto error;
4656 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004657
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004658 /* Calculate method resolution order */
4659 if (mro_internal(type) < 0) {
4660 goto error;
4661 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004662
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004663 /* Inherit special flags from dominant base */
4664 if (type->tp_base != NULL)
4665 inherit_special(type, type->tp_base);
Guido van Rossum13d52f02001-08-10 21:24:08 +00004666
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004667 /* Initialize tp_dict properly */
4668 bases = type->tp_mro;
4669 assert(bases != NULL);
4670 assert(PyTuple_Check(bases));
4671 n = PyTuple_GET_SIZE(bases);
4672 for (i = 1; i < n; i++) {
4673 PyObject *b = PyTuple_GET_ITEM(bases, i);
4674 if (PyType_Check(b))
4675 inherit_slots(type, (PyTypeObject *)b);
4676 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004677
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004678 /* Sanity check for tp_free. */
4679 if (PyType_IS_GC(type) && (type->tp_flags & Py_TPFLAGS_BASETYPE) &&
4680 (type->tp_free == NULL || type->tp_free == PyObject_Del)) {
4681 /* This base class needs to call tp_free, but doesn't have
4682 * one, or its tp_free is for non-gc'ed objects.
4683 */
4684 PyErr_Format(PyExc_TypeError, "type '%.100s' participates in "
4685 "gc and is a base type but has inappropriate "
4686 "tp_free slot",
4687 type->tp_name);
4688 goto error;
4689 }
Tim Peters3cfe7542003-05-21 21:29:48 +00004690
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004691 /* if the type dictionary doesn't contain a __doc__, set it from
4692 the tp_doc slot.
4693 */
Victor Stinner3c1e4812012-03-26 22:10:51 +02004694 if (_PyDict_GetItemId(type->tp_dict, &PyId___doc__) == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004695 if (type->tp_doc != NULL) {
Larry Hastings2623c8c2014-02-08 22:15:29 -08004696 const char *old_doc = _PyType_DocWithoutSignature(type->tp_name,
4697 type->tp_doc);
Larry Hastings5c661892014-01-24 06:17:25 -08004698 PyObject *doc = PyUnicode_FromString(old_doc);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004699 if (doc == NULL)
4700 goto error;
Victor Stinner5967bf42013-07-17 22:01:37 +02004701 if (_PyDict_SetItemId(type->tp_dict, &PyId___doc__, doc) < 0) {
4702 Py_DECREF(doc);
4703 goto error;
4704 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004705 Py_DECREF(doc);
4706 } else {
Victor Stinner5967bf42013-07-17 22:01:37 +02004707 if (_PyDict_SetItemId(type->tp_dict,
4708 &PyId___doc__, Py_None) < 0)
4709 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004710 }
4711 }
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00004712
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004713 /* Hack for tp_hash and __hash__.
4714 If after all that, tp_hash is still NULL, and __hash__ is not in
4715 tp_dict, set tp_hash to PyObject_HashNotImplemented and
4716 tp_dict['__hash__'] equal to None.
4717 This signals that __hash__ is not inherited.
4718 */
4719 if (type->tp_hash == NULL) {
Victor Stinner3c1e4812012-03-26 22:10:51 +02004720 if (_PyDict_GetItemId(type->tp_dict, &PyId___hash__) == NULL) {
4721 if (_PyDict_SetItemId(type->tp_dict, &PyId___hash__, Py_None) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004722 goto error;
4723 type->tp_hash = PyObject_HashNotImplemented;
4724 }
4725 }
Guido van Rossum38938152006-08-21 23:36:26 +00004726
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004727 /* Some more special stuff */
4728 base = type->tp_base;
4729 if (base != NULL) {
4730 if (type->tp_as_number == NULL)
4731 type->tp_as_number = base->tp_as_number;
4732 if (type->tp_as_sequence == NULL)
4733 type->tp_as_sequence = base->tp_as_sequence;
4734 if (type->tp_as_mapping == NULL)
4735 type->tp_as_mapping = base->tp_as_mapping;
4736 if (type->tp_as_buffer == NULL)
4737 type->tp_as_buffer = base->tp_as_buffer;
4738 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004739
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004740 /* Link into each base class's list of subclasses */
4741 bases = type->tp_bases;
4742 n = PyTuple_GET_SIZE(bases);
4743 for (i = 0; i < n; i++) {
4744 PyObject *b = PyTuple_GET_ITEM(bases, i);
4745 if (PyType_Check(b) &&
4746 add_subclass((PyTypeObject *)b, type) < 0)
4747 goto error;
4748 }
Guido van Rossum1c450732001-10-08 15:18:27 +00004749
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004750 /* Warn for a type that implements tp_compare (now known as
4751 tp_reserved) but not tp_richcompare. */
4752 if (type->tp_reserved && !type->tp_richcompare) {
Andrew Svetlov2cd8ce42012-12-23 14:27:17 +02004753 PyErr_Format(PyExc_TypeError,
Victor Stinner4a2b7a12010-08-13 14:03:48 +00004754 "Type %.100s defines tp_reserved (formerly tp_compare) "
4755 "but not tp_richcompare. Comparisons may not behave as intended.",
4756 type->tp_name);
Andrew Svetlov2cd8ce42012-12-23 14:27:17 +02004757 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004758 }
Mark Dickinson2a7d45b2009-02-08 11:02:10 +00004759
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004760 /* All done -- set the ready flag */
4761 assert(type->tp_dict != NULL);
4762 type->tp_flags =
4763 (type->tp_flags & ~Py_TPFLAGS_READYING) | Py_TPFLAGS_READY;
4764 return 0;
Guido van Rossumd614f972001-08-10 17:39:49 +00004765
4766 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004767 type->tp_flags &= ~Py_TPFLAGS_READYING;
4768 return -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004769}
4770
Guido van Rossum1c450732001-10-08 15:18:27 +00004771static int
4772add_subclass(PyTypeObject *base, PyTypeObject *type)
4773{
Antoine Pitrou84745ab2013-10-29 21:31:25 +01004774 int result = -1;
4775 PyObject *dict, *key, *newobj;
Guido van Rossum1c450732001-10-08 15:18:27 +00004776
Antoine Pitrou84745ab2013-10-29 21:31:25 +01004777 dict = base->tp_subclasses;
4778 if (dict == NULL) {
4779 base->tp_subclasses = dict = PyDict_New();
4780 if (dict == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004781 return -1;
4782 }
Antoine Pitrou84745ab2013-10-29 21:31:25 +01004783 assert(PyDict_CheckExact(dict));
4784 key = PyLong_FromVoidPtr((void *) type);
4785 if (key == NULL)
Victor Stinner9812af82013-07-08 22:25:48 +02004786 return -1;
Antoine Pitrou84745ab2013-10-29 21:31:25 +01004787 newobj = PyWeakref_NewRef((PyObject *)type, NULL);
4788 if (newobj != NULL) {
4789 result = PyDict_SetItem(dict, key, newobj);
4790 Py_DECREF(newobj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004791 }
Antoine Pitrou84745ab2013-10-29 21:31:25 +01004792 Py_DECREF(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004793 return result;
Guido van Rossum1c450732001-10-08 15:18:27 +00004794}
4795
Michael W. Hudson98bbc492002-11-26 14:47:27 +00004796static void
4797remove_subclass(PyTypeObject *base, PyTypeObject *type)
4798{
Antoine Pitrou84745ab2013-10-29 21:31:25 +01004799 PyObject *dict, *key;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00004800
Antoine Pitrou84745ab2013-10-29 21:31:25 +01004801 dict = base->tp_subclasses;
4802 if (dict == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004803 return;
4804 }
Antoine Pitrou84745ab2013-10-29 21:31:25 +01004805 assert(PyDict_CheckExact(dict));
4806 key = PyLong_FromVoidPtr((void *) type);
4807 if (key == NULL || PyDict_DelItem(dict, key)) {
4808 /* This can happen if the type initialization errored out before
4809 the base subclasses were updated (e.g. a non-str __qualname__
4810 was passed in the type dict). */
4811 PyErr_Clear();
4812 }
4813 Py_XDECREF(key);
4814}
4815
4816static void
4817remove_all_subclasses(PyTypeObject *type, PyObject *bases)
4818{
4819 if (bases) {
4820 Py_ssize_t i;
4821 for (i = 0; i < PyTuple_GET_SIZE(bases); i++) {
4822 PyObject *base = PyTuple_GET_ITEM(bases, i);
4823 if (PyType_Check(base))
4824 remove_subclass((PyTypeObject*) base, type);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004825 }
4826 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +00004827}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004828
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004829static int
4830check_num_args(PyObject *ob, int n)
4831{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004832 if (!PyTuple_CheckExact(ob)) {
4833 PyErr_SetString(PyExc_SystemError,
4834 "PyArg_UnpackTuple() argument list is not a tuple");
4835 return 0;
4836 }
4837 if (n == PyTuple_GET_SIZE(ob))
4838 return 1;
4839 PyErr_Format(
4840 PyExc_TypeError,
4841 "expected %d arguments, got %zd", n, PyTuple_GET_SIZE(ob));
4842 return 0;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004843}
4844
Tim Peters6d6c1a32001-08-02 04:15:00 +00004845/* Generic wrappers for overloadable 'operators' such as __getitem__ */
4846
4847/* There's a wrapper *function* for each distinct function typedef used
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004848 for type object slots (e.g. binaryfunc, ternaryfunc, etc.). There's a
Tim Peters6d6c1a32001-08-02 04:15:00 +00004849 wrapper *table* for each distinct operation (e.g. __len__, __add__).
4850 Most tables have only one entry; the tables for binary operators have two
4851 entries, one regular and one with reversed arguments. */
4852
4853static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00004854wrap_lenfunc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004855{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004856 lenfunc func = (lenfunc)wrapped;
4857 Py_ssize_t res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004858
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004859 if (!check_num_args(args, 0))
4860 return NULL;
4861 res = (*func)(self);
4862 if (res == -1 && PyErr_Occurred())
4863 return NULL;
4864 return PyLong_FromLong((long)res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004865}
4866
Tim Peters6d6c1a32001-08-02 04:15:00 +00004867static PyObject *
Raymond Hettingerf34f2642003-10-11 17:29:04 +00004868wrap_inquirypred(PyObject *self, PyObject *args, void *wrapped)
4869{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004870 inquiry func = (inquiry)wrapped;
4871 int res;
Raymond Hettingerf34f2642003-10-11 17:29:04 +00004872
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004873 if (!check_num_args(args, 0))
4874 return NULL;
4875 res = (*func)(self);
4876 if (res == -1 && PyErr_Occurred())
4877 return NULL;
4878 return PyBool_FromLong((long)res);
Raymond Hettingerf34f2642003-10-11 17:29:04 +00004879}
4880
4881static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00004882wrap_binaryfunc(PyObject *self, PyObject *args, void *wrapped)
4883{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004884 binaryfunc func = (binaryfunc)wrapped;
4885 PyObject *other;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004886
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004887 if (!check_num_args(args, 1))
4888 return NULL;
4889 other = PyTuple_GET_ITEM(args, 0);
4890 return (*func)(self, other);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004891}
4892
4893static PyObject *
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00004894wrap_binaryfunc_l(PyObject *self, PyObject *args, void *wrapped)
4895{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004896 binaryfunc func = (binaryfunc)wrapped;
4897 PyObject *other;
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00004898
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004899 if (!check_num_args(args, 1))
4900 return NULL;
4901 other = PyTuple_GET_ITEM(args, 0);
4902 return (*func)(self, other);
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00004903}
4904
4905static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00004906wrap_binaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
4907{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004908 binaryfunc func = (binaryfunc)wrapped;
4909 PyObject *other;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004910
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004911 if (!check_num_args(args, 1))
4912 return NULL;
4913 other = PyTuple_GET_ITEM(args, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004914 return (*func)(other, self);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004915}
4916
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004917static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00004918wrap_ternaryfunc(PyObject *self, PyObject *args, void *wrapped)
4919{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004920 ternaryfunc func = (ternaryfunc)wrapped;
4921 PyObject *other;
4922 PyObject *third = Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004923
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004924 /* Note: This wrapper only works for __pow__() */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004925
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004926 if (!PyArg_UnpackTuple(args, "", 1, 2, &other, &third))
4927 return NULL;
4928 return (*func)(self, other, third);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004929}
4930
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00004931static PyObject *
4932wrap_ternaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
4933{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004934 ternaryfunc func = (ternaryfunc)wrapped;
4935 PyObject *other;
4936 PyObject *third = Py_None;
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00004937
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004938 /* Note: This wrapper only works for __pow__() */
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00004939
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004940 if (!PyArg_UnpackTuple(args, "", 1, 2, &other, &third))
4941 return NULL;
4942 return (*func)(other, self, third);
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00004943}
4944
Tim Peters6d6c1a32001-08-02 04:15:00 +00004945static PyObject *
4946wrap_unaryfunc(PyObject *self, PyObject *args, void *wrapped)
4947{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004948 unaryfunc func = (unaryfunc)wrapped;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004949
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004950 if (!check_num_args(args, 0))
4951 return NULL;
4952 return (*func)(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004953}
4954
Tim Peters6d6c1a32001-08-02 04:15:00 +00004955static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004956wrap_indexargfunc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004957{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004958 ssizeargfunc func = (ssizeargfunc)wrapped;
4959 PyObject* o;
4960 Py_ssize_t i;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004961
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004962 if (!PyArg_UnpackTuple(args, "", 1, 1, &o))
4963 return NULL;
4964 i = PyNumber_AsSsize_t(o, PyExc_OverflowError);
4965 if (i == -1 && PyErr_Occurred())
4966 return NULL;
4967 return (*func)(self, i);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004968}
4969
Martin v. Löwis18e16552006-02-15 17:27:45 +00004970static Py_ssize_t
Guido van Rossum5d815f32001-08-17 21:57:47 +00004971getindex(PyObject *self, PyObject *arg)
4972{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004973 Py_ssize_t i;
Guido van Rossum5d815f32001-08-17 21:57:47 +00004974
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004975 i = PyNumber_AsSsize_t(arg, PyExc_OverflowError);
4976 if (i == -1 && PyErr_Occurred())
4977 return -1;
4978 if (i < 0) {
4979 PySequenceMethods *sq = Py_TYPE(self)->tp_as_sequence;
4980 if (sq && sq->sq_length) {
4981 Py_ssize_t n = (*sq->sq_length)(self);
4982 if (n < 0)
4983 return -1;
4984 i += n;
4985 }
4986 }
4987 return i;
Guido van Rossum5d815f32001-08-17 21:57:47 +00004988}
4989
4990static PyObject *
4991wrap_sq_item(PyObject *self, PyObject *args, void *wrapped)
4992{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004993 ssizeargfunc func = (ssizeargfunc)wrapped;
4994 PyObject *arg;
4995 Py_ssize_t i;
Guido van Rossum5d815f32001-08-17 21:57:47 +00004996
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004997 if (PyTuple_GET_SIZE(args) == 1) {
4998 arg = PyTuple_GET_ITEM(args, 0);
4999 i = getindex(self, arg);
5000 if (i == -1 && PyErr_Occurred())
5001 return NULL;
5002 return (*func)(self, i);
5003 }
5004 check_num_args(args, 1);
5005 assert(PyErr_Occurred());
5006 return NULL;
Guido van Rossum5d815f32001-08-17 21:57:47 +00005007}
5008
Tim Peters6d6c1a32001-08-02 04:15:00 +00005009static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00005010wrap_sq_setitem(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005011{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005012 ssizeobjargproc func = (ssizeobjargproc)wrapped;
5013 Py_ssize_t i;
5014 int res;
5015 PyObject *arg, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005016
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005017 if (!PyArg_UnpackTuple(args, "", 2, 2, &arg, &value))
5018 return NULL;
5019 i = getindex(self, arg);
5020 if (i == -1 && PyErr_Occurred())
5021 return NULL;
5022 res = (*func)(self, i, value);
5023 if (res == -1 && PyErr_Occurred())
5024 return NULL;
5025 Py_INCREF(Py_None);
5026 return Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005027}
5028
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00005029static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00005030wrap_sq_delitem(PyObject *self, PyObject *args, void *wrapped)
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00005031{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005032 ssizeobjargproc func = (ssizeobjargproc)wrapped;
5033 Py_ssize_t i;
5034 int res;
5035 PyObject *arg;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00005036
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005037 if (!check_num_args(args, 1))
5038 return NULL;
5039 arg = PyTuple_GET_ITEM(args, 0);
5040 i = getindex(self, arg);
5041 if (i == -1 && PyErr_Occurred())
5042 return NULL;
5043 res = (*func)(self, i, NULL);
5044 if (res == -1 && PyErr_Occurred())
5045 return NULL;
5046 Py_INCREF(Py_None);
5047 return Py_None;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00005048}
5049
Tim Peters6d6c1a32001-08-02 04:15:00 +00005050/* XXX objobjproc is a misnomer; should be objargpred */
5051static PyObject *
5052wrap_objobjproc(PyObject *self, PyObject *args, void *wrapped)
5053{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005054 objobjproc func = (objobjproc)wrapped;
5055 int res;
5056 PyObject *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005057
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005058 if (!check_num_args(args, 1))
5059 return NULL;
5060 value = PyTuple_GET_ITEM(args, 0);
5061 res = (*func)(self, value);
5062 if (res == -1 && PyErr_Occurred())
5063 return NULL;
5064 else
5065 return PyBool_FromLong(res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005066}
5067
Tim Peters6d6c1a32001-08-02 04:15:00 +00005068static PyObject *
5069wrap_objobjargproc(PyObject *self, PyObject *args, void *wrapped)
5070{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005071 objobjargproc func = (objobjargproc)wrapped;
5072 int res;
5073 PyObject *key, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005074
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005075 if (!PyArg_UnpackTuple(args, "", 2, 2, &key, &value))
5076 return NULL;
5077 res = (*func)(self, key, value);
5078 if (res == -1 && PyErr_Occurred())
5079 return NULL;
5080 Py_INCREF(Py_None);
5081 return Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005082}
5083
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00005084static PyObject *
5085wrap_delitem(PyObject *self, PyObject *args, void *wrapped)
5086{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005087 objobjargproc func = (objobjargproc)wrapped;
5088 int res;
5089 PyObject *key;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00005090
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005091 if (!check_num_args(args, 1))
5092 return NULL;
5093 key = PyTuple_GET_ITEM(args, 0);
5094 res = (*func)(self, key, NULL);
5095 if (res == -1 && PyErr_Occurred())
5096 return NULL;
5097 Py_INCREF(Py_None);
5098 return Py_None;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00005099}
5100
Guido van Rossum4dcdb782003-04-14 21:46:03 +00005101/* Helper to check for object.__setattr__ or __delattr__ applied to a type.
Guido van Rossum52b27052003-04-15 20:05:10 +00005102 This is called the Carlo Verre hack after its discoverer. */
Guido van Rossum4dcdb782003-04-14 21:46:03 +00005103static int
5104hackcheck(PyObject *self, setattrofunc func, char *what)
5105{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005106 PyTypeObject *type = Py_TYPE(self);
5107 while (type && type->tp_flags & Py_TPFLAGS_HEAPTYPE)
5108 type = type->tp_base;
5109 /* If type is NULL now, this is a really weird type.
5110 In the spirit of backwards compatibility (?), just shut up. */
5111 if (type && type->tp_setattro != func) {
5112 PyErr_Format(PyExc_TypeError,
5113 "can't apply this %s to %s object",
5114 what,
5115 type->tp_name);
5116 return 0;
5117 }
5118 return 1;
Guido van Rossum4dcdb782003-04-14 21:46:03 +00005119}
5120
Tim Peters6d6c1a32001-08-02 04:15:00 +00005121static PyObject *
5122wrap_setattr(PyObject *self, PyObject *args, void *wrapped)
5123{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005124 setattrofunc func = (setattrofunc)wrapped;
5125 int res;
5126 PyObject *name, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005127
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005128 if (!PyArg_UnpackTuple(args, "", 2, 2, &name, &value))
5129 return NULL;
5130 if (!hackcheck(self, func, "__setattr__"))
5131 return NULL;
5132 res = (*func)(self, name, value);
5133 if (res < 0)
5134 return NULL;
5135 Py_INCREF(Py_None);
5136 return Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005137}
5138
5139static PyObject *
5140wrap_delattr(PyObject *self, PyObject *args, void *wrapped)
5141{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005142 setattrofunc func = (setattrofunc)wrapped;
5143 int res;
5144 PyObject *name;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005145
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005146 if (!check_num_args(args, 1))
5147 return NULL;
5148 name = PyTuple_GET_ITEM(args, 0);
5149 if (!hackcheck(self, func, "__delattr__"))
5150 return NULL;
5151 res = (*func)(self, name, NULL);
5152 if (res < 0)
5153 return NULL;
5154 Py_INCREF(Py_None);
5155 return Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005156}
5157
Tim Peters6d6c1a32001-08-02 04:15:00 +00005158static PyObject *
5159wrap_hashfunc(PyObject *self, PyObject *args, void *wrapped)
5160{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005161 hashfunc func = (hashfunc)wrapped;
Benjamin Peterson8035bc52010-10-23 16:20:50 +00005162 Py_hash_t res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005163
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005164 if (!check_num_args(args, 0))
5165 return NULL;
5166 res = (*func)(self);
5167 if (res == -1 && PyErr_Occurred())
5168 return NULL;
Benjamin Peterson8035bc52010-10-23 16:20:50 +00005169 return PyLong_FromSsize_t(res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005170}
5171
Tim Peters6d6c1a32001-08-02 04:15:00 +00005172static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00005173wrap_call(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005174{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005175 ternaryfunc func = (ternaryfunc)wrapped;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005176
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005177 return (*func)(self, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005178}
5179
Tim Peters6d6c1a32001-08-02 04:15:00 +00005180static PyObject *
Antoine Pitrou796564c2013-07-30 19:59:21 +02005181wrap_del(PyObject *self, PyObject *args, void *wrapped)
5182{
5183 destructor func = (destructor)wrapped;
5184
5185 if (!check_num_args(args, 0))
5186 return NULL;
5187
5188 (*func)(self);
5189 Py_RETURN_NONE;
5190}
5191
5192static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00005193wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op)
5194{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005195 richcmpfunc func = (richcmpfunc)wrapped;
5196 PyObject *other;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005197
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005198 if (!check_num_args(args, 1))
5199 return NULL;
5200 other = PyTuple_GET_ITEM(args, 0);
5201 return (*func)(self, other, op);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005202}
5203
5204#undef RICHCMP_WRAPPER
5205#define RICHCMP_WRAPPER(NAME, OP) \
5206static PyObject * \
5207richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \
5208{ \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005209 return wrap_richcmpfunc(self, args, wrapped, OP); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00005210}
5211
Jack Jansen8e938b42001-08-08 15:29:49 +00005212RICHCMP_WRAPPER(lt, Py_LT)
5213RICHCMP_WRAPPER(le, Py_LE)
5214RICHCMP_WRAPPER(eq, Py_EQ)
5215RICHCMP_WRAPPER(ne, Py_NE)
5216RICHCMP_WRAPPER(gt, Py_GT)
5217RICHCMP_WRAPPER(ge, Py_GE)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005218
Tim Peters6d6c1a32001-08-02 04:15:00 +00005219static PyObject *
5220wrap_next(PyObject *self, PyObject *args, void *wrapped)
5221{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005222 unaryfunc func = (unaryfunc)wrapped;
5223 PyObject *res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005224
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005225 if (!check_num_args(args, 0))
5226 return NULL;
5227 res = (*func)(self);
5228 if (res == NULL && !PyErr_Occurred())
5229 PyErr_SetNone(PyExc_StopIteration);
5230 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005231}
5232
Tim Peters6d6c1a32001-08-02 04:15:00 +00005233static PyObject *
5234wrap_descr_get(PyObject *self, PyObject *args, void *wrapped)
5235{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005236 descrgetfunc func = (descrgetfunc)wrapped;
5237 PyObject *obj;
5238 PyObject *type = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005239
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005240 if (!PyArg_UnpackTuple(args, "", 1, 2, &obj, &type))
5241 return NULL;
5242 if (obj == Py_None)
5243 obj = NULL;
5244 if (type == Py_None)
5245 type = NULL;
5246 if (type == NULL &&obj == NULL) {
5247 PyErr_SetString(PyExc_TypeError,
5248 "__get__(None, None) is invalid");
5249 return NULL;
5250 }
5251 return (*func)(self, obj, type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005252}
5253
Tim Peters6d6c1a32001-08-02 04:15:00 +00005254static PyObject *
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005255wrap_descr_set(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005256{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005257 descrsetfunc func = (descrsetfunc)wrapped;
5258 PyObject *obj, *value;
5259 int ret;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005260
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005261 if (!PyArg_UnpackTuple(args, "", 2, 2, &obj, &value))
5262 return NULL;
5263 ret = (*func)(self, obj, value);
5264 if (ret < 0)
5265 return NULL;
5266 Py_INCREF(Py_None);
5267 return Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005268}
Guido van Rossum22b13872002-08-06 21:41:44 +00005269
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00005270static PyObject *
5271wrap_descr_delete(PyObject *self, PyObject *args, void *wrapped)
5272{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005273 descrsetfunc func = (descrsetfunc)wrapped;
5274 PyObject *obj;
5275 int ret;
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00005276
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005277 if (!check_num_args(args, 1))
5278 return NULL;
5279 obj = PyTuple_GET_ITEM(args, 0);
5280 ret = (*func)(self, obj, NULL);
5281 if (ret < 0)
5282 return NULL;
5283 Py_INCREF(Py_None);
5284 return Py_None;
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00005285}
Tim Peters6d6c1a32001-08-02 04:15:00 +00005286
Tim Peters6d6c1a32001-08-02 04:15:00 +00005287static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00005288wrap_init(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005289{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005290 initproc func = (initproc)wrapped;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005291
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005292 if (func(self, args, kwds) < 0)
5293 return NULL;
5294 Py_INCREF(Py_None);
5295 return Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005296}
5297
Tim Peters6d6c1a32001-08-02 04:15:00 +00005298static PyObject *
Guido van Rossum0d231ed2001-08-06 16:50:37 +00005299tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005300{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005301 PyTypeObject *type, *subtype, *staticbase;
5302 PyObject *arg0, *res;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00005303
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005304 if (self == NULL || !PyType_Check(self))
5305 Py_FatalError("__new__() called with non-type 'self'");
5306 type = (PyTypeObject *)self;
5307 if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) {
5308 PyErr_Format(PyExc_TypeError,
5309 "%s.__new__(): not enough arguments",
5310 type->tp_name);
5311 return NULL;
5312 }
5313 arg0 = PyTuple_GET_ITEM(args, 0);
5314 if (!PyType_Check(arg0)) {
5315 PyErr_Format(PyExc_TypeError,
5316 "%s.__new__(X): X is not a type object (%s)",
5317 type->tp_name,
5318 Py_TYPE(arg0)->tp_name);
5319 return NULL;
5320 }
5321 subtype = (PyTypeObject *)arg0;
5322 if (!PyType_IsSubtype(subtype, type)) {
5323 PyErr_Format(PyExc_TypeError,
5324 "%s.__new__(%s): %s is not a subtype of %s",
5325 type->tp_name,
5326 subtype->tp_name,
5327 subtype->tp_name,
5328 type->tp_name);
5329 return NULL;
5330 }
Barry Warsaw60f01882001-08-22 19:24:42 +00005331
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005332 /* Check that the use doesn't do something silly and unsafe like
5333 object.__new__(dict). To do this, we check that the
5334 most derived base that's not a heap type is this type. */
5335 staticbase = subtype;
Martin v. Löwis9c564092012-06-23 23:20:45 +02005336 while (staticbase && (staticbase->tp_new == slot_tp_new))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005337 staticbase = staticbase->tp_base;
5338 /* If staticbase is NULL now, it is a really weird type.
5339 In the spirit of backwards compatibility (?), just shut up. */
5340 if (staticbase && staticbase->tp_new != type->tp_new) {
5341 PyErr_Format(PyExc_TypeError,
5342 "%s.__new__(%s) is not safe, use %s.__new__()",
5343 type->tp_name,
5344 subtype->tp_name,
Benjamin Petersone8239332014-11-26 23:03:11 -06005345 staticbase->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005346 return NULL;
5347 }
Barry Warsaw60f01882001-08-22 19:24:42 +00005348
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005349 args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
5350 if (args == NULL)
5351 return NULL;
5352 res = type->tp_new(subtype, args, kwds);
5353 Py_DECREF(args);
5354 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005355}
5356
Guido van Rossum0d231ed2001-08-06 16:50:37 +00005357static struct PyMethodDef tp_new_methoddef[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005358 {"__new__", (PyCFunction)tp_new_wrapper, METH_VARARGS|METH_KEYWORDS,
Larry Hastings2623c8c2014-02-08 22:15:29 -08005359 PyDoc_STR("__new__($type, *args, **kwargs)\n--\n\n"
Larry Hastings581ee362014-01-28 05:00:08 -08005360 "Create and return a new object. "
5361 "See help(type) for accurate signature.")},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005362 {0}
Tim Peters6d6c1a32001-08-02 04:15:00 +00005363};
5364
5365static int
Guido van Rossum0d231ed2001-08-06 16:50:37 +00005366add_tp_new_wrapper(PyTypeObject *type)
5367{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005368 PyObject *func;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00005369
Victor Stinner3c1e4812012-03-26 22:10:51 +02005370 if (_PyDict_GetItemId(type->tp_dict, &PyId___new__) != NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005371 return 0;
Andrew Svetlov3ba3a3e2012-12-25 13:32:35 +02005372 func = PyCFunction_NewEx(tp_new_methoddef, (PyObject *)type, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005373 if (func == NULL)
5374 return -1;
Victor Stinner3c1e4812012-03-26 22:10:51 +02005375 if (_PyDict_SetItemId(type->tp_dict, &PyId___new__, func)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005376 Py_DECREF(func);
5377 return -1;
5378 }
5379 Py_DECREF(func);
5380 return 0;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00005381}
5382
Guido van Rossumf040ede2001-08-07 16:40:56 +00005383/* Slot wrappers that call the corresponding __foo__ slot. See comments
5384 below at override_slots() for more explanation. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00005385
Guido van Rossumdc91b992001-08-08 22:26:22 +00005386#define SLOT0(FUNCNAME, OPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00005387static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00005388FUNCNAME(PyObject *self) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00005389{ \
Benjamin Petersonce798522012-01-22 11:24:29 -05005390 _Py_static_string(id, OPSTR); \
5391 return call_method(self, &id, "()"); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00005392}
5393
Guido van Rossumdc91b992001-08-08 22:26:22 +00005394#define SLOT1(FUNCNAME, OPSTR, ARG1TYPE, ARGCODES) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00005395static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00005396FUNCNAME(PyObject *self, ARG1TYPE arg1) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00005397{ \
Benjamin Petersonce798522012-01-22 11:24:29 -05005398 _Py_static_string(id, OPSTR); \
5399 return call_method(self, &id, "(" ARGCODES ")", arg1); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00005400}
5401
Guido van Rossumcd118802003-01-06 22:57:47 +00005402/* Boolean helper for SLOT1BINFULL().
5403 right.__class__ is a nontrivial subclass of left.__class__. */
5404static int
Victor Stinner3c1e4812012-03-26 22:10:51 +02005405method_is_overloaded(PyObject *left, PyObject *right, struct _Py_Identifier *name)
Guido van Rossumcd118802003-01-06 22:57:47 +00005406{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005407 PyObject *a, *b;
5408 int ok;
Guido van Rossumcd118802003-01-06 22:57:47 +00005409
Victor Stinner3c1e4812012-03-26 22:10:51 +02005410 b = _PyObject_GetAttrId((PyObject *)(Py_TYPE(right)), name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005411 if (b == NULL) {
5412 PyErr_Clear();
5413 /* If right doesn't have it, it's not overloaded */
5414 return 0;
5415 }
Guido van Rossumcd118802003-01-06 22:57:47 +00005416
Victor Stinner3c1e4812012-03-26 22:10:51 +02005417 a = _PyObject_GetAttrId((PyObject *)(Py_TYPE(left)), name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005418 if (a == NULL) {
5419 PyErr_Clear();
5420 Py_DECREF(b);
5421 /* If right has it but left doesn't, it's overloaded */
5422 return 1;
5423 }
Guido van Rossumcd118802003-01-06 22:57:47 +00005424
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005425 ok = PyObject_RichCompareBool(a, b, Py_NE);
5426 Py_DECREF(a);
5427 Py_DECREF(b);
5428 if (ok < 0) {
5429 PyErr_Clear();
5430 return 0;
5431 }
Guido van Rossumcd118802003-01-06 22:57:47 +00005432
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005433 return ok;
Guido van Rossumcd118802003-01-06 22:57:47 +00005434}
5435
Guido van Rossumdc91b992001-08-08 22:26:22 +00005436
5437#define SLOT1BINFULL(FUNCNAME, TESTFUNC, SLOTNAME, OPSTR, ROPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00005438static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00005439FUNCNAME(PyObject *self, PyObject *other) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00005440{ \
Benjamin Petersonce798522012-01-22 11:24:29 -05005441 _Py_static_string(op_id, OPSTR); \
5442 _Py_static_string(rop_id, ROPSTR); \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005443 int do_other = Py_TYPE(self) != Py_TYPE(other) && \
5444 Py_TYPE(other)->tp_as_number != NULL && \
5445 Py_TYPE(other)->tp_as_number->SLOTNAME == TESTFUNC; \
5446 if (Py_TYPE(self)->tp_as_number != NULL && \
5447 Py_TYPE(self)->tp_as_number->SLOTNAME == TESTFUNC) { \
5448 PyObject *r; \
5449 if (do_other && \
5450 PyType_IsSubtype(Py_TYPE(other), Py_TYPE(self)) && \
Victor Stinner3c1e4812012-03-26 22:10:51 +02005451 method_is_overloaded(self, other, &rop_id)) { \
Benjamin Petersonce798522012-01-22 11:24:29 -05005452 r = call_maybe(other, &rop_id, "(O)", self); \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005453 if (r != Py_NotImplemented) \
5454 return r; \
5455 Py_DECREF(r); \
5456 do_other = 0; \
5457 } \
Benjamin Petersonce798522012-01-22 11:24:29 -05005458 r = call_maybe(self, &op_id, "(O)", other); \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005459 if (r != Py_NotImplemented || \
5460 Py_TYPE(other) == Py_TYPE(self)) \
5461 return r; \
5462 Py_DECREF(r); \
5463 } \
5464 if (do_other) { \
Benjamin Petersonce798522012-01-22 11:24:29 -05005465 return call_maybe(other, &rop_id, "(O)", self); \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005466 } \
Brian Curtindfc80e32011-08-10 20:28:54 -05005467 Py_RETURN_NOTIMPLEMENTED; \
Guido van Rossumdc91b992001-08-08 22:26:22 +00005468}
5469
5470#define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005471 SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR)
Guido van Rossumdc91b992001-08-08 22:26:22 +00005472
5473#define SLOT2(FUNCNAME, OPSTR, ARG1TYPE, ARG2TYPE, ARGCODES) \
5474static PyObject * \
5475FUNCNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \
5476{ \
Benjamin Petersonce798522012-01-22 11:24:29 -05005477 _Py_static_string(id, #OPSTR); \
5478 return call_method(self, &id, "(" ARGCODES ")", arg1, arg2); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00005479}
5480
Martin v. Löwis18e16552006-02-15 17:27:45 +00005481static Py_ssize_t
Tim Peters6d6c1a32001-08-02 04:15:00 +00005482slot_sq_length(PyObject *self)
5483{
Benjamin Petersonce798522012-01-22 11:24:29 -05005484 PyObject *res = call_method(self, &PyId___len__, "()");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005485 Py_ssize_t len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005486
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005487 if (res == NULL)
5488 return -1;
5489 len = PyNumber_AsSsize_t(res, PyExc_OverflowError);
5490 Py_DECREF(res);
5491 if (len < 0) {
5492 if (!PyErr_Occurred())
5493 PyErr_SetString(PyExc_ValueError,
5494 "__len__() should return >= 0");
5495 return -1;
5496 }
5497 return len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005498}
5499
Guido van Rossumf4593e02001-10-03 12:09:30 +00005500/* Super-optimized version of slot_sq_item.
5501 Other slots could do the same... */
5502static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00005503slot_sq_item(PyObject *self, Py_ssize_t i)
Guido van Rossumf4593e02001-10-03 12:09:30 +00005504{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005505 PyObject *func, *args = NULL, *ival = NULL, *retval = NULL;
5506 descrgetfunc f;
Guido van Rossumf4593e02001-10-03 12:09:30 +00005507
Victor Stinner3c1e4812012-03-26 22:10:51 +02005508 func = _PyType_LookupId(Py_TYPE(self), &PyId___getitem__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005509 if (func != NULL) {
5510 if ((f = Py_TYPE(func)->tp_descr_get) == NULL)
5511 Py_INCREF(func);
5512 else {
5513 func = f(func, self, (PyObject *)(Py_TYPE(self)));
5514 if (func == NULL) {
5515 return NULL;
5516 }
5517 }
5518 ival = PyLong_FromSsize_t(i);
5519 if (ival != NULL) {
5520 args = PyTuple_New(1);
5521 if (args != NULL) {
5522 PyTuple_SET_ITEM(args, 0, ival);
5523 retval = PyObject_Call(func, args, NULL);
5524 Py_XDECREF(args);
5525 Py_XDECREF(func);
5526 return retval;
5527 }
5528 }
5529 }
5530 else {
Victor Stinner3c1e4812012-03-26 22:10:51 +02005531 PyObject *getitem_str = _PyUnicode_FromId(&PyId___getitem__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005532 PyErr_SetObject(PyExc_AttributeError, getitem_str);
5533 }
5534 Py_XDECREF(args);
5535 Py_XDECREF(ival);
5536 Py_XDECREF(func);
5537 return NULL;
Guido van Rossumf4593e02001-10-03 12:09:30 +00005538}
5539
Tim Peters6d6c1a32001-08-02 04:15:00 +00005540static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00005541slot_sq_ass_item(PyObject *self, Py_ssize_t index, PyObject *value)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005542{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005543 PyObject *res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005544
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005545 if (value == NULL)
Benjamin Petersonce798522012-01-22 11:24:29 -05005546 res = call_method(self, &PyId___delitem__, "(n)", index);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005547 else
Benjamin Petersonce798522012-01-22 11:24:29 -05005548 res = call_method(self, &PyId___setitem__, "(nO)", index, value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005549 if (res == NULL)
5550 return -1;
5551 Py_DECREF(res);
5552 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005553}
5554
5555static int
Tim Peters6d6c1a32001-08-02 04:15:00 +00005556slot_sq_contains(PyObject *self, PyObject *value)
5557{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005558 PyObject *func, *res, *args;
5559 int result = -1;
Benjamin Petersonce798522012-01-22 11:24:29 -05005560 _Py_IDENTIFIER(__contains__);
Tim Petersbf9b2442003-03-23 05:35:36 +00005561
Benjamin Petersonce798522012-01-22 11:24:29 -05005562 func = lookup_maybe(self, &PyId___contains__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005563 if (func != NULL) {
5564 args = PyTuple_Pack(1, value);
5565 if (args == NULL)
5566 res = NULL;
5567 else {
5568 res = PyObject_Call(func, args, NULL);
5569 Py_DECREF(args);
5570 }
5571 Py_DECREF(func);
5572 if (res != NULL) {
5573 result = PyObject_IsTrue(res);
5574 Py_DECREF(res);
5575 }
5576 }
5577 else if (! PyErr_Occurred()) {
5578 /* Possible results: -1 and 1 */
5579 result = (int)_PySequence_IterSearch(self, value,
5580 PY_ITERSEARCH_CONTAINS);
5581 }
5582 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005583}
5584
Tim Peters6d6c1a32001-08-02 04:15:00 +00005585#define slot_mp_length slot_sq_length
5586
Guido van Rossumdc91b992001-08-08 22:26:22 +00005587SLOT1(slot_mp_subscript, "__getitem__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00005588
5589static int
5590slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value)
5591{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005592 PyObject *res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005593
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005594 if (value == NULL)
Benjamin Petersonce798522012-01-22 11:24:29 -05005595 res = call_method(self, &PyId___delitem__, "(O)", key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005596 else
Benjamin Petersonce798522012-01-22 11:24:29 -05005597 res = call_method(self, &PyId___setitem__, "(OO)", key, value);
5598
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005599 if (res == NULL)
5600 return -1;
5601 Py_DECREF(res);
5602 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005603}
5604
Guido van Rossumdc91b992001-08-08 22:26:22 +00005605SLOT1BIN(slot_nb_add, nb_add, "__add__", "__radd__")
5606SLOT1BIN(slot_nb_subtract, nb_subtract, "__sub__", "__rsub__")
5607SLOT1BIN(slot_nb_multiply, nb_multiply, "__mul__", "__rmul__")
Guido van Rossumdc91b992001-08-08 22:26:22 +00005608SLOT1BIN(slot_nb_remainder, nb_remainder, "__mod__", "__rmod__")
5609SLOT1BIN(slot_nb_divmod, nb_divmod, "__divmod__", "__rdivmod__")
5610
Jeremy Hylton938ace62002-07-17 16:30:39 +00005611static PyObject *slot_nb_power(PyObject *, PyObject *, PyObject *);
Guido van Rossumdc91b992001-08-08 22:26:22 +00005612
5613SLOT1BINFULL(slot_nb_power_binary, slot_nb_power,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005614 nb_power, "__pow__", "__rpow__")
Guido van Rossumdc91b992001-08-08 22:26:22 +00005615
5616static PyObject *
5617slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus)
5618{
Benjamin Petersonce798522012-01-22 11:24:29 -05005619 _Py_IDENTIFIER(__pow__);
Guido van Rossum2730b132001-08-28 18:22:14 +00005620
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005621 if (modulus == Py_None)
5622 return slot_nb_power_binary(self, other);
5623 /* Three-arg power doesn't use __rpow__. But ternary_op
5624 can call this when the second argument's type uses
5625 slot_nb_power, so check before calling self.__pow__. */
5626 if (Py_TYPE(self)->tp_as_number != NULL &&
5627 Py_TYPE(self)->tp_as_number->nb_power == slot_nb_power) {
Benjamin Petersonce798522012-01-22 11:24:29 -05005628 return call_method(self, &PyId___pow__, "(OO)", other, modulus);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005629 }
Brian Curtindfc80e32011-08-10 20:28:54 -05005630 Py_RETURN_NOTIMPLEMENTED;
Guido van Rossumdc91b992001-08-08 22:26:22 +00005631}
5632
5633SLOT0(slot_nb_negative, "__neg__")
5634SLOT0(slot_nb_positive, "__pos__")
5635SLOT0(slot_nb_absolute, "__abs__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00005636
5637static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00005638slot_nb_bool(PyObject *self)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005639{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005640 PyObject *func, *args;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005641 int result = -1;
5642 int using_len = 0;
Benjamin Petersonce798522012-01-22 11:24:29 -05005643 _Py_IDENTIFIER(__bool__);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005644
Benjamin Petersonce798522012-01-22 11:24:29 -05005645 func = lookup_maybe(self, &PyId___bool__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005646 if (func == NULL) {
5647 if (PyErr_Occurred())
5648 return -1;
Benjamin Petersonce798522012-01-22 11:24:29 -05005649 func = lookup_maybe(self, &PyId___len__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005650 if (func == NULL)
5651 return PyErr_Occurred() ? -1 : 1;
5652 using_len = 1;
5653 }
5654 args = PyTuple_New(0);
5655 if (args != NULL) {
5656 PyObject *temp = PyObject_Call(func, args, NULL);
5657 Py_DECREF(args);
5658 if (temp != NULL) {
5659 if (using_len) {
5660 /* enforced by slot_nb_len */
5661 result = PyObject_IsTrue(temp);
5662 }
5663 else if (PyBool_Check(temp)) {
5664 result = PyObject_IsTrue(temp);
5665 }
5666 else {
5667 PyErr_Format(PyExc_TypeError,
5668 "__bool__ should return "
5669 "bool, returned %s",
5670 Py_TYPE(temp)->tp_name);
5671 result = -1;
5672 }
5673 Py_DECREF(temp);
5674 }
5675 }
5676 Py_DECREF(func);
5677 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005678}
5679
Guido van Rossum38fff8c2006-03-07 18:50:55 +00005680
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00005681static PyObject *
Guido van Rossum38fff8c2006-03-07 18:50:55 +00005682slot_nb_index(PyObject *self)
5683{
Benjamin Petersonce798522012-01-22 11:24:29 -05005684 _Py_IDENTIFIER(__index__);
5685 return call_method(self, &PyId___index__, "()");
Guido van Rossum38fff8c2006-03-07 18:50:55 +00005686}
5687
5688
Guido van Rossumdc91b992001-08-08 22:26:22 +00005689SLOT0(slot_nb_invert, "__invert__")
5690SLOT1BIN(slot_nb_lshift, nb_lshift, "__lshift__", "__rlshift__")
5691SLOT1BIN(slot_nb_rshift, nb_rshift, "__rshift__", "__rrshift__")
5692SLOT1BIN(slot_nb_and, nb_and, "__and__", "__rand__")
5693SLOT1BIN(slot_nb_xor, nb_xor, "__xor__", "__rxor__")
5694SLOT1BIN(slot_nb_or, nb_or, "__or__", "__ror__")
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00005695
Guido van Rossumdc91b992001-08-08 22:26:22 +00005696SLOT0(slot_nb_int, "__int__")
Guido van Rossumdc91b992001-08-08 22:26:22 +00005697SLOT0(slot_nb_float, "__float__")
Guido van Rossumdc91b992001-08-08 22:26:22 +00005698SLOT1(slot_nb_inplace_add, "__iadd__", PyObject *, "O")
5699SLOT1(slot_nb_inplace_subtract, "__isub__", PyObject *, "O")
5700SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *, "O")
Guido van Rossumdc91b992001-08-08 22:26:22 +00005701SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *, "O")
Thomas Wouterscf297e42007-02-23 15:07:44 +00005702/* Can't use SLOT1 here, because nb_inplace_power is ternary */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005703static PyObject *
5704slot_nb_inplace_power(PyObject *self, PyObject * arg1, PyObject *arg2)
5705{
Benjamin Petersonce798522012-01-22 11:24:29 -05005706 _Py_IDENTIFIER(__ipow__);
5707 return call_method(self, &PyId___ipow__, "(" "O" ")", arg1);
Thomas Wouterscf297e42007-02-23 15:07:44 +00005708}
Guido van Rossumdc91b992001-08-08 22:26:22 +00005709SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *, "O")
5710SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *, "O")
5711SLOT1(slot_nb_inplace_and, "__iand__", PyObject *, "O")
5712SLOT1(slot_nb_inplace_xor, "__ixor__", PyObject *, "O")
5713SLOT1(slot_nb_inplace_or, "__ior__", PyObject *, "O")
5714SLOT1BIN(slot_nb_floor_divide, nb_floor_divide,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005715 "__floordiv__", "__rfloordiv__")
Guido van Rossumdc91b992001-08-08 22:26:22 +00005716SLOT1BIN(slot_nb_true_divide, nb_true_divide, "__truediv__", "__rtruediv__")
5717SLOT1(slot_nb_inplace_floor_divide, "__ifloordiv__", PyObject *, "O")
5718SLOT1(slot_nb_inplace_true_divide, "__itruediv__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00005719
Guido van Rossumb8f63662001-08-15 23:57:02 +00005720static PyObject *
5721slot_tp_repr(PyObject *self)
5722{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005723 PyObject *func, *res;
Benjamin Petersonce798522012-01-22 11:24:29 -05005724 _Py_IDENTIFIER(__repr__);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005725
Benjamin Petersonce798522012-01-22 11:24:29 -05005726 func = lookup_method(self, &PyId___repr__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005727 if (func != NULL) {
5728 res = PyEval_CallObject(func, NULL);
5729 Py_DECREF(func);
5730 return res;
5731 }
5732 PyErr_Clear();
5733 return PyUnicode_FromFormat("<%s object at %p>",
5734 Py_TYPE(self)->tp_name, self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005735}
5736
5737static PyObject *
5738slot_tp_str(PyObject *self)
5739{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005740 PyObject *func, *res;
Benjamin Petersonce798522012-01-22 11:24:29 -05005741 _Py_IDENTIFIER(__str__);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005742
Benjamin Petersonce798522012-01-22 11:24:29 -05005743 func = lookup_method(self, &PyId___str__);
Victor Stinner2e8474d2013-07-11 22:46:11 +02005744 if (func == NULL)
5745 return NULL;
Victor Stinnerbebba502013-10-29 10:56:34 +01005746 res = PyEval_CallObject(func, NULL);
5747 Py_DECREF(func);
5748 return res;
5749}
Tim Peters6d6c1a32001-08-02 04:15:00 +00005750
Benjamin Peterson8f67d082010-10-17 20:54:53 +00005751static Py_hash_t
Tim Peters6d6c1a32001-08-02 04:15:00 +00005752slot_tp_hash(PyObject *self)
5753{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005754 PyObject *func, *res;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00005755 Py_ssize_t h;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005756
Benjamin Petersonce798522012-01-22 11:24:29 -05005757 func = lookup_method(self, &PyId___hash__);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005758
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005759 if (func == Py_None) {
5760 Py_DECREF(func);
5761 func = NULL;
5762 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +00005763
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005764 if (func == NULL) {
5765 return PyObject_HashNotImplemented(self);
5766 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +00005767
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005768 res = PyEval_CallObject(func, NULL);
5769 Py_DECREF(func);
5770 if (res == NULL)
5771 return -1;
Mark Dickinsondc787d22010-05-23 13:33:13 +00005772
5773 if (!PyLong_Check(res)) {
5774 PyErr_SetString(PyExc_TypeError,
5775 "__hash__ method should return an integer");
5776 return -1;
5777 }
Benjamin Peterson8f67d082010-10-17 20:54:53 +00005778 /* Transform the PyLong `res` to a Py_hash_t `h`. For an existing
5779 hashable Python object x, hash(x) will always lie within the range of
5780 Py_hash_t. Therefore our transformation must preserve values that
5781 already lie within this range, to ensure that if x.__hash__() returns
5782 hash(y) then hash(x) == hash(y). */
5783 h = PyLong_AsSsize_t(res);
5784 if (h == -1 && PyErr_Occurred()) {
5785 /* res was not within the range of a Py_hash_t, so we're free to
Mark Dickinsondc787d22010-05-23 13:33:13 +00005786 use any sufficiently bit-mixing transformation;
5787 long.__hash__ will do nicely. */
Benjamin Peterson8f67d082010-10-17 20:54:53 +00005788 PyErr_Clear();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005789 h = PyLong_Type.tp_hash(res);
Benjamin Peterson8f67d082010-10-17 20:54:53 +00005790 }
Benjamin Petersone7dfeeb2010-10-17 21:27:01 +00005791 /* -1 is reserved for errors. */
5792 if (h == -1)
5793 h = -2;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005794 Py_DECREF(res);
Mark Dickinsondc787d22010-05-23 13:33:13 +00005795 return h;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005796}
5797
5798static PyObject *
5799slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds)
5800{
Benjamin Petersonce798522012-01-22 11:24:29 -05005801 _Py_IDENTIFIER(__call__);
5802 PyObject *meth = lookup_method(self, &PyId___call__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005803 PyObject *res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005804
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005805 if (meth == NULL)
5806 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005807
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005808 res = PyObject_Call(meth, args, kwds);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005809
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005810 Py_DECREF(meth);
5811 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005812}
5813
Guido van Rossum14a6f832001-10-17 13:59:09 +00005814/* There are two slot dispatch functions for tp_getattro.
5815
5816 - slot_tp_getattro() is used when __getattribute__ is overridden
5817 but no __getattr__ hook is present;
5818
5819 - slot_tp_getattr_hook() is used when a __getattr__ hook is present.
5820
Guido van Rossumc334df52002-04-04 23:44:47 +00005821 The code in update_one_slot() always installs slot_tp_getattr_hook(); this
5822 detects the absence of __getattr__ and then installs the simpler slot if
5823 necessary. */
Guido van Rossum14a6f832001-10-17 13:59:09 +00005824
Tim Peters6d6c1a32001-08-02 04:15:00 +00005825static PyObject *
5826slot_tp_getattro(PyObject *self, PyObject *name)
5827{
Benjamin Petersonce798522012-01-22 11:24:29 -05005828 return call_method(self, &PyId___getattribute__, "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005829}
5830
Guido van Rossum19c1cd52001-09-21 21:24:49 +00005831static PyObject *
Benjamin Peterson9262b842008-11-17 22:45:50 +00005832call_attribute(PyObject *self, PyObject *attr, PyObject *name)
5833{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005834 PyObject *res, *descr = NULL;
5835 descrgetfunc f = Py_TYPE(attr)->tp_descr_get;
Benjamin Peterson9262b842008-11-17 22:45:50 +00005836
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005837 if (f != NULL) {
5838 descr = f(attr, self, (PyObject *)(Py_TYPE(self)));
5839 if (descr == NULL)
5840 return NULL;
5841 else
5842 attr = descr;
5843 }
5844 res = PyObject_CallFunctionObjArgs(attr, name, NULL);
5845 Py_XDECREF(descr);
5846 return res;
Benjamin Peterson9262b842008-11-17 22:45:50 +00005847}
5848
5849static PyObject *
Guido van Rossum19c1cd52001-09-21 21:24:49 +00005850slot_tp_getattr_hook(PyObject *self, PyObject *name)
5851{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005852 PyTypeObject *tp = Py_TYPE(self);
5853 PyObject *getattr, *getattribute, *res;
Victor Stinner3c1e4812012-03-26 22:10:51 +02005854 _Py_IDENTIFIER(__getattr__);
Guido van Rossum19c1cd52001-09-21 21:24:49 +00005855
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005856 /* speed hack: we could use lookup_maybe, but that would resolve the
5857 method fully for each attribute lookup for classes with
5858 __getattr__, even when the attribute is present. So we use
5859 _PyType_Lookup and create the method only when needed, with
5860 call_attribute. */
Victor Stinner3c1e4812012-03-26 22:10:51 +02005861 getattr = _PyType_LookupId(tp, &PyId___getattr__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005862 if (getattr == NULL) {
5863 /* No __getattr__ hook: use a simpler dispatcher */
5864 tp->tp_getattro = slot_tp_getattro;
5865 return slot_tp_getattro(self, name);
5866 }
5867 Py_INCREF(getattr);
5868 /* speed hack: we could use lookup_maybe, but that would resolve the
5869 method fully for each attribute lookup for classes with
5870 __getattr__, even when self has the default __getattribute__
5871 method. So we use _PyType_Lookup and create the method only when
5872 needed, with call_attribute. */
Victor Stinner3c1e4812012-03-26 22:10:51 +02005873 getattribute = _PyType_LookupId(tp, &PyId___getattribute__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005874 if (getattribute == NULL ||
5875 (Py_TYPE(getattribute) == &PyWrapperDescr_Type &&
5876 ((PyWrapperDescrObject *)getattribute)->d_wrapped ==
5877 (void *)PyObject_GenericGetAttr))
5878 res = PyObject_GenericGetAttr(self, name);
5879 else {
5880 Py_INCREF(getattribute);
5881 res = call_attribute(self, getattribute, name);
5882 Py_DECREF(getattribute);
5883 }
5884 if (res == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) {
5885 PyErr_Clear();
5886 res = call_attribute(self, getattr, name);
5887 }
5888 Py_DECREF(getattr);
5889 return res;
Guido van Rossum19c1cd52001-09-21 21:24:49 +00005890}
5891
Tim Peters6d6c1a32001-08-02 04:15:00 +00005892static int
5893slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value)
5894{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005895 PyObject *res;
Benjamin Petersonce798522012-01-22 11:24:29 -05005896 _Py_IDENTIFIER(__delattr__);
5897 _Py_IDENTIFIER(__setattr__);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005898
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005899 if (value == NULL)
Benjamin Petersonce798522012-01-22 11:24:29 -05005900 res = call_method(self, &PyId___delattr__, "(O)", name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005901 else
Benjamin Petersonce798522012-01-22 11:24:29 -05005902 res = call_method(self, &PyId___setattr__, "(OO)", name, value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005903 if (res == NULL)
5904 return -1;
5905 Py_DECREF(res);
5906 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005907}
5908
Benjamin Petersonce798522012-01-22 11:24:29 -05005909static _Py_Identifier name_op[] = {
5910 {0, "__lt__", 0},
5911 {0, "__le__", 0},
5912 {0, "__eq__", 0},
5913 {0, "__ne__", 0},
5914 {0, "__gt__", 0},
5915 {0, "__ge__", 0}
Guido van Rossumf5243f02008-01-01 04:06:48 +00005916};
5917
Tim Peters6d6c1a32001-08-02 04:15:00 +00005918static PyObject *
Mark Dickinson6f1d0492009-11-15 13:58:49 +00005919slot_tp_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005920{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005921 PyObject *func, *args, *res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005922
Benjamin Petersonce798522012-01-22 11:24:29 -05005923 func = lookup_method(self, &name_op[op]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005924 if (func == NULL) {
5925 PyErr_Clear();
Brian Curtindfc80e32011-08-10 20:28:54 -05005926 Py_RETURN_NOTIMPLEMENTED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005927 }
5928 args = PyTuple_Pack(1, other);
5929 if (args == NULL)
5930 res = NULL;
5931 else {
5932 res = PyObject_Call(func, args, NULL);
5933 Py_DECREF(args);
5934 }
5935 Py_DECREF(func);
5936 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005937}
5938
Guido van Rossumb8f63662001-08-15 23:57:02 +00005939static PyObject *
Guido van Rossumb8f63662001-08-15 23:57:02 +00005940slot_tp_iter(PyObject *self)
5941{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005942 PyObject *func, *res;
Benjamin Petersonce798522012-01-22 11:24:29 -05005943 _Py_IDENTIFIER(__iter__);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005944
Benjamin Petersonce798522012-01-22 11:24:29 -05005945 func = lookup_method(self, &PyId___iter__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005946 if (func != NULL) {
5947 PyObject *args;
5948 args = res = PyTuple_New(0);
5949 if (args != NULL) {
5950 res = PyObject_Call(func, args, NULL);
5951 Py_DECREF(args);
5952 }
5953 Py_DECREF(func);
5954 return res;
5955 }
5956 PyErr_Clear();
Benjamin Petersonce798522012-01-22 11:24:29 -05005957 func = lookup_method(self, &PyId___getitem__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005958 if (func == NULL) {
5959 PyErr_Format(PyExc_TypeError,
5960 "'%.200s' object is not iterable",
5961 Py_TYPE(self)->tp_name);
5962 return NULL;
5963 }
5964 Py_DECREF(func);
5965 return PySeqIter_New(self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005966}
Tim Peters6d6c1a32001-08-02 04:15:00 +00005967
5968static PyObject *
5969slot_tp_iternext(PyObject *self)
5970{
Benjamin Petersonce798522012-01-22 11:24:29 -05005971 _Py_IDENTIFIER(__next__);
5972 return call_method(self, &PyId___next__, "()");
Tim Peters6d6c1a32001-08-02 04:15:00 +00005973}
5974
Guido van Rossum1a493502001-08-17 16:47:50 +00005975static PyObject *
5976slot_tp_descr_get(PyObject *self, PyObject *obj, PyObject *type)
5977{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005978 PyTypeObject *tp = Py_TYPE(self);
5979 PyObject *get;
Victor Stinner3c1e4812012-03-26 22:10:51 +02005980 _Py_IDENTIFIER(__get__);
Guido van Rossum1a493502001-08-17 16:47:50 +00005981
Victor Stinner3c1e4812012-03-26 22:10:51 +02005982 get = _PyType_LookupId(tp, &PyId___get__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005983 if (get == NULL) {
5984 /* Avoid further slowdowns */
5985 if (tp->tp_descr_get == slot_tp_descr_get)
5986 tp->tp_descr_get = NULL;
5987 Py_INCREF(self);
5988 return self;
5989 }
5990 if (obj == NULL)
5991 obj = Py_None;
5992 if (type == NULL)
5993 type = Py_None;
5994 return PyObject_CallFunctionObjArgs(get, self, obj, type, NULL);
Guido van Rossum1a493502001-08-17 16:47:50 +00005995}
Tim Peters6d6c1a32001-08-02 04:15:00 +00005996
5997static int
5998slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value)
5999{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006000 PyObject *res;
Benjamin Petersonce798522012-01-22 11:24:29 -05006001 _Py_IDENTIFIER(__delete__);
6002 _Py_IDENTIFIER(__set__);
Guido van Rossum2c252392001-08-24 10:13:31 +00006003
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006004 if (value == NULL)
Benjamin Petersonce798522012-01-22 11:24:29 -05006005 res = call_method(self, &PyId___delete__, "(O)", target);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006006 else
Benjamin Petersonce798522012-01-22 11:24:29 -05006007 res = call_method(self, &PyId___set__, "(OO)", target, value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006008 if (res == NULL)
6009 return -1;
6010 Py_DECREF(res);
6011 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00006012}
6013
6014static int
6015slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds)
6016{
Benjamin Petersonce798522012-01-22 11:24:29 -05006017 _Py_IDENTIFIER(__init__);
6018 PyObject *meth = lookup_method(self, &PyId___init__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006019 PyObject *res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00006020
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006021 if (meth == NULL)
6022 return -1;
6023 res = PyObject_Call(meth, args, kwds);
6024 Py_DECREF(meth);
6025 if (res == NULL)
6026 return -1;
6027 if (res != Py_None) {
6028 PyErr_Format(PyExc_TypeError,
6029 "__init__() should return None, not '%.200s'",
6030 Py_TYPE(res)->tp_name);
6031 Py_DECREF(res);
6032 return -1;
6033 }
6034 Py_DECREF(res);
6035 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00006036}
6037
6038static PyObject *
6039slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
6040{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006041 PyObject *func;
6042 PyObject *newargs, *x;
6043 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +00006044
Victor Stinner3c1e4812012-03-26 22:10:51 +02006045 func = _PyObject_GetAttrId((PyObject *)type, &PyId___new__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006046 if (func == NULL)
6047 return NULL;
6048 assert(PyTuple_Check(args));
6049 n = PyTuple_GET_SIZE(args);
6050 newargs = PyTuple_New(n+1);
6051 if (newargs == NULL)
6052 return NULL;
6053 Py_INCREF(type);
6054 PyTuple_SET_ITEM(newargs, 0, (PyObject *)type);
6055 for (i = 0; i < n; i++) {
6056 x = PyTuple_GET_ITEM(args, i);
6057 Py_INCREF(x);
6058 PyTuple_SET_ITEM(newargs, i+1, x);
6059 }
6060 x = PyObject_Call(func, newargs, kwds);
6061 Py_DECREF(newargs);
6062 Py_DECREF(func);
6063 return x;
Tim Peters6d6c1a32001-08-02 04:15:00 +00006064}
6065
Guido van Rossumfebd61d2002-08-08 20:55:20 +00006066static void
Antoine Pitrou796564c2013-07-30 19:59:21 +02006067slot_tp_finalize(PyObject *self)
Guido van Rossumfebd61d2002-08-08 20:55:20 +00006068{
Benjamin Petersonce798522012-01-22 11:24:29 -05006069 _Py_IDENTIFIER(__del__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006070 PyObject *del, *res;
6071 PyObject *error_type, *error_value, *error_traceback;
Guido van Rossumfebd61d2002-08-08 20:55:20 +00006072
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006073 /* Save the current exception, if any. */
6074 PyErr_Fetch(&error_type, &error_value, &error_traceback);
Guido van Rossumfebd61d2002-08-08 20:55:20 +00006075
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006076 /* Execute __del__ method, if any. */
Benjamin Petersonce798522012-01-22 11:24:29 -05006077 del = lookup_maybe(self, &PyId___del__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006078 if (del != NULL) {
6079 res = PyEval_CallObject(del, NULL);
6080 if (res == NULL)
6081 PyErr_WriteUnraisable(del);
6082 else
6083 Py_DECREF(res);
6084 Py_DECREF(del);
6085 }
Guido van Rossumfebd61d2002-08-08 20:55:20 +00006086
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006087 /* Restore the saved exception. */
6088 PyErr_Restore(error_type, error_value, error_traceback);
Guido van Rossumfebd61d2002-08-08 20:55:20 +00006089}
6090
Guido van Rossum7b9144b2001-10-09 19:39:46 +00006091
Benjamin Peterson63952412013-04-01 17:41:41 -04006092/*
6093Table mapping __foo__ names to tp_foo offsets and slot_tp_foo wrapper functions.
6094
6095The table is ordered by offsets relative to the 'PyHeapTypeObject' structure,
6096which incorporates the additional structures used for numbers, sequences and
6097mappings. Note that multiple names may map to the same slot (e.g. __eq__,
6098__ne__ etc. all map to tp_richcompare) and one name may map to multiple slots
6099(e.g. __str__ affects tp_str as well as tp_repr). The table is terminated with
6100an all-zero entry. (This table is further initialized in init_slotdefs().)
6101*/
Guido van Rossum7b9144b2001-10-09 19:39:46 +00006102
Guido van Rossum6d204072001-10-21 00:44:31 +00006103typedef struct wrapperbase slotdef;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00006104
6105#undef TPSLOT
Guido van Rossumc8e56452001-10-22 00:43:43 +00006106#undef FLSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00006107#undef ETSLOT
6108#undef SQSLOT
6109#undef MPSLOT
6110#undef NBSLOT
Guido van Rossum6d204072001-10-21 00:44:31 +00006111#undef UNSLOT
6112#undef IBSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00006113#undef BINSLOT
6114#undef RBINSLOT
6115
Guido van Rossum6d204072001-10-21 00:44:31 +00006116#define TPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006117 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
6118 PyDoc_STR(DOC)}
Guido van Rossumc8e56452001-10-22 00:43:43 +00006119#define FLSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC, FLAGS) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006120 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
6121 PyDoc_STR(DOC), FLAGS}
Guido van Rossum6d204072001-10-21 00:44:31 +00006122#define ETSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006123 {NAME, offsetof(PyHeapTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
6124 PyDoc_STR(DOC)}
Guido van Rossum6d204072001-10-21 00:44:31 +00006125#define SQSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006126 ETSLOT(NAME, as_sequence.SLOT, FUNCTION, WRAPPER, DOC)
Guido van Rossum6d204072001-10-21 00:44:31 +00006127#define MPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006128 ETSLOT(NAME, as_mapping.SLOT, FUNCTION, WRAPPER, DOC)
Guido van Rossum6d204072001-10-21 00:44:31 +00006129#define NBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006130 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, DOC)
Guido van Rossum6d204072001-10-21 00:44:31 +00006131#define UNSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006132 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
Larry Hastings69a25472014-02-09 22:22:38 -08006133 NAME "($self, /)\n--\n\n" DOC)
Guido van Rossum6d204072001-10-21 00:44:31 +00006134#define IBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006135 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
Larry Hastings69a25472014-02-09 22:22:38 -08006136 NAME "($self, value, /)\n--\n\nReturn self" DOC "value.")
Guido van Rossum6d204072001-10-21 00:44:31 +00006137#define BINSLOT(NAME, SLOT, FUNCTION, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006138 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
Larry Hastings69a25472014-02-09 22:22:38 -08006139 NAME "($self, value, /)\n--\n\nReturn self" DOC "value.")
Guido van Rossum6d204072001-10-21 00:44:31 +00006140#define RBINSLOT(NAME, SLOT, FUNCTION, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006141 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
Larry Hastings69a25472014-02-09 22:22:38 -08006142 NAME "($self, value, /)\n--\n\nReturn value" DOC "self.")
Anthony Baxter56616992005-06-03 14:12:21 +00006143#define BINSLOTNOTINFIX(NAME, SLOT, FUNCTION, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006144 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
Larry Hastings69a25472014-02-09 22:22:38 -08006145 NAME "($self, value, /)\n--\n\n" DOC)
Anthony Baxter56616992005-06-03 14:12:21 +00006146#define RBINSLOTNOTINFIX(NAME, SLOT, FUNCTION, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006147 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
Larry Hastings69a25472014-02-09 22:22:38 -08006148 NAME "($self, value, /)\n--\n\n" DOC)
Guido van Rossum7b9144b2001-10-09 19:39:46 +00006149
6150static slotdef slotdefs[] = {
Benjamin Peterson63952412013-04-01 17:41:41 -04006151 TPSLOT("__getattribute__", tp_getattr, NULL, NULL, ""),
6152 TPSLOT("__getattr__", tp_getattr, NULL, NULL, ""),
6153 TPSLOT("__setattr__", tp_setattr, NULL, NULL, ""),
6154 TPSLOT("__delattr__", tp_setattr, NULL, NULL, ""),
6155 TPSLOT("__repr__", tp_repr, slot_tp_repr, wrap_unaryfunc,
Larry Hastings69a25472014-02-09 22:22:38 -08006156 "__repr__($self, /)\n--\n\nReturn repr(self)."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006157 TPSLOT("__hash__", tp_hash, slot_tp_hash, wrap_hashfunc,
Larry Hastings69a25472014-02-09 22:22:38 -08006158 "__hash__($self, /)\n--\n\nReturn hash(self)."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006159 FLSLOT("__call__", tp_call, slot_tp_call, (wrapperfunc)wrap_call,
Larry Hastings69a25472014-02-09 22:22:38 -08006160 "__call__($self, /, *args, **kwargs)\n--\n\nCall self as a function.",
Larry Hastings5c661892014-01-24 06:17:25 -08006161 PyWrapperFlag_KEYWORDS),
Benjamin Peterson63952412013-04-01 17:41:41 -04006162 TPSLOT("__str__", tp_str, slot_tp_str, wrap_unaryfunc,
Larry Hastings69a25472014-02-09 22:22:38 -08006163 "__str__($self, /)\n--\n\nReturn str(self)."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006164 TPSLOT("__getattribute__", tp_getattro, slot_tp_getattr_hook,
Larry Hastings5c661892014-01-24 06:17:25 -08006165 wrap_binaryfunc,
Larry Hastings69a25472014-02-09 22:22:38 -08006166 "__getattribute__($self, name, /)\n--\n\nReturn getattr(self, name)."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006167 TPSLOT("__getattr__", tp_getattro, slot_tp_getattr_hook, NULL, ""),
6168 TPSLOT("__setattr__", tp_setattro, slot_tp_setattro, wrap_setattr,
Larry Hastings69a25472014-02-09 22:22:38 -08006169 "__setattr__($self, name, value, /)\n--\n\nImplement setattr(self, name, value)."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006170 TPSLOT("__delattr__", tp_setattro, slot_tp_setattro, wrap_delattr,
Larry Hastings69a25472014-02-09 22:22:38 -08006171 "__delattr__($self, name, /)\n--\n\nImplement delattr(self, name)."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006172 TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare, richcmp_lt,
Larry Hastings69a25472014-02-09 22:22:38 -08006173 "__lt__($self, value, /)\n--\n\nReturn self<value."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006174 TPSLOT("__le__", tp_richcompare, slot_tp_richcompare, richcmp_le,
Larry Hastings69a25472014-02-09 22:22:38 -08006175 "__le__($self, value, /)\n--\n\nReturn self<=value."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006176 TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare, richcmp_eq,
Larry Hastings69a25472014-02-09 22:22:38 -08006177 "__eq__($self, value, /)\n--\n\nReturn self==value."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006178 TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare, richcmp_ne,
Larry Hastings69a25472014-02-09 22:22:38 -08006179 "__ne__($self, value, /)\n--\n\nReturn self!=value."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006180 TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare, richcmp_gt,
Larry Hastings69a25472014-02-09 22:22:38 -08006181 "__gt__($self, value, /)\n--\n\nReturn self>value."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006182 TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare, richcmp_ge,
Zachary Wareea42b4c2014-04-18 09:14:31 -05006183 "__ge__($self, value, /)\n--\n\nReturn self>=value."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006184 TPSLOT("__iter__", tp_iter, slot_tp_iter, wrap_unaryfunc,
Larry Hastings69a25472014-02-09 22:22:38 -08006185 "__iter__($self, /)\n--\n\nImplement iter(self)."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006186 TPSLOT("__next__", tp_iternext, slot_tp_iternext, wrap_next,
Larry Hastings69a25472014-02-09 22:22:38 -08006187 "__next__($self, /)\n--\n\nImplement next(self)."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006188 TPSLOT("__get__", tp_descr_get, slot_tp_descr_get, wrap_descr_get,
Larry Hastings69a25472014-02-09 22:22:38 -08006189 "__get__($self, instance, owner, /)\n--\n\nReturn an attribute of instance, which is of type owner."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006190 TPSLOT("__set__", tp_descr_set, slot_tp_descr_set, wrap_descr_set,
Larry Hastings69a25472014-02-09 22:22:38 -08006191 "__set__($self, instance, value, /)\n--\n\nSet an attribute of instance to value."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006192 TPSLOT("__delete__", tp_descr_set, slot_tp_descr_set,
Larry Hastings5c661892014-01-24 06:17:25 -08006193 wrap_descr_delete,
Yury Selivanov056e2652014-03-02 12:25:27 -05006194 "__delete__($self, instance, /)\n--\n\nDelete an attribute of instance."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006195 FLSLOT("__init__", tp_init, slot_tp_init, (wrapperfunc)wrap_init,
Larry Hastings69a25472014-02-09 22:22:38 -08006196 "__init__($self, /, *args, **kwargs)\n--\n\n"
Larry Hastings581ee362014-01-28 05:00:08 -08006197 "Initialize self. See help(type(self)) for accurate signature.",
Benjamin Peterson63952412013-04-01 17:41:41 -04006198 PyWrapperFlag_KEYWORDS),
Larry Hastings5c661892014-01-24 06:17:25 -08006199 TPSLOT("__new__", tp_new, slot_tp_new, NULL,
Larry Hastings69a25472014-02-09 22:22:38 -08006200 "__new__(type, /, *args, **kwargs)\n--\n\n"
Larry Hastings581ee362014-01-28 05:00:08 -08006201 "Create and return new object. See help(type) for accurate signature."),
Antoine Pitrou796564c2013-07-30 19:59:21 +02006202 TPSLOT("__del__", tp_finalize, slot_tp_finalize, (wrapperfunc)wrap_del, ""),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00006203
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006204 BINSLOT("__add__", nb_add, slot_nb_add,
Larry Hastings5c661892014-01-24 06:17:25 -08006205 "+"),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006206 RBINSLOT("__radd__", nb_add, slot_nb_add,
Larry Hastings5c661892014-01-24 06:17:25 -08006207 "+"),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006208 BINSLOT("__sub__", nb_subtract, slot_nb_subtract,
Larry Hastings5c661892014-01-24 06:17:25 -08006209 "-"),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006210 RBINSLOT("__rsub__", nb_subtract, slot_nb_subtract,
Larry Hastings5c661892014-01-24 06:17:25 -08006211 "-"),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006212 BINSLOT("__mul__", nb_multiply, slot_nb_multiply,
Larry Hastings5c661892014-01-24 06:17:25 -08006213 "*"),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006214 RBINSLOT("__rmul__", nb_multiply, slot_nb_multiply,
Larry Hastings5c661892014-01-24 06:17:25 -08006215 "*"),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006216 BINSLOT("__mod__", nb_remainder, slot_nb_remainder,
Larry Hastings5c661892014-01-24 06:17:25 -08006217 "%"),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006218 RBINSLOT("__rmod__", nb_remainder, slot_nb_remainder,
Larry Hastings5c661892014-01-24 06:17:25 -08006219 "%"),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006220 BINSLOTNOTINFIX("__divmod__", nb_divmod, slot_nb_divmod,
Larry Hastings581ee362014-01-28 05:00:08 -08006221 "Return divmod(self, value)."),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006222 RBINSLOTNOTINFIX("__rdivmod__", nb_divmod, slot_nb_divmod,
Larry Hastings581ee362014-01-28 05:00:08 -08006223 "Return divmod(value, self)."),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006224 NBSLOT("__pow__", nb_power, slot_nb_power, wrap_ternaryfunc,
Larry Hastings69a25472014-02-09 22:22:38 -08006225 "__pow__($self, value, mod=None, /)\n--\n\nReturn pow(self, value, mod)."),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006226 NBSLOT("__rpow__", nb_power, slot_nb_power, wrap_ternaryfunc_r,
Larry Hastings69a25472014-02-09 22:22:38 -08006227 "__rpow__($self, value, mod=None, /)\n--\n\nReturn pow(value, self, mod)."),
Larry Hastings5c661892014-01-24 06:17:25 -08006228 UNSLOT("__neg__", nb_negative, slot_nb_negative, wrap_unaryfunc, "-self"),
6229 UNSLOT("__pos__", nb_positive, slot_nb_positive, wrap_unaryfunc, "+self"),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006230 UNSLOT("__abs__", nb_absolute, slot_nb_absolute, wrap_unaryfunc,
Larry Hastings5c661892014-01-24 06:17:25 -08006231 "abs(self)"),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006232 UNSLOT("__bool__", nb_bool, slot_nb_bool, wrap_inquirypred,
Larry Hastings5c661892014-01-24 06:17:25 -08006233 "self != 0"),
6234 UNSLOT("__invert__", nb_invert, slot_nb_invert, wrap_unaryfunc, "~self"),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006235 BINSLOT("__lshift__", nb_lshift, slot_nb_lshift, "<<"),
6236 RBINSLOT("__rlshift__", nb_lshift, slot_nb_lshift, "<<"),
6237 BINSLOT("__rshift__", nb_rshift, slot_nb_rshift, ">>"),
6238 RBINSLOT("__rrshift__", nb_rshift, slot_nb_rshift, ">>"),
6239 BINSLOT("__and__", nb_and, slot_nb_and, "&"),
6240 RBINSLOT("__rand__", nb_and, slot_nb_and, "&"),
6241 BINSLOT("__xor__", nb_xor, slot_nb_xor, "^"),
6242 RBINSLOT("__rxor__", nb_xor, slot_nb_xor, "^"),
6243 BINSLOT("__or__", nb_or, slot_nb_or, "|"),
6244 RBINSLOT("__ror__", nb_or, slot_nb_or, "|"),
6245 UNSLOT("__int__", nb_int, slot_nb_int, wrap_unaryfunc,
Larry Hastings5c661892014-01-24 06:17:25 -08006246 "int(self)"),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006247 UNSLOT("__float__", nb_float, slot_nb_float, wrap_unaryfunc,
Larry Hastings5c661892014-01-24 06:17:25 -08006248 "float(self)"),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006249 IBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add,
Eli Benderskyd3baae72011-11-11 16:57:05 +02006250 wrap_binaryfunc, "+="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006251 IBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract,
Eli Benderskyd3baae72011-11-11 16:57:05 +02006252 wrap_binaryfunc, "-="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006253 IBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply,
Eli Benderskyd3baae72011-11-11 16:57:05 +02006254 wrap_binaryfunc, "*="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006255 IBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder,
Eli Benderskyd3baae72011-11-11 16:57:05 +02006256 wrap_binaryfunc, "%="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006257 IBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power,
Eli Benderskyd3baae72011-11-11 16:57:05 +02006258 wrap_binaryfunc, "**="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006259 IBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift,
Eli Benderskyd3baae72011-11-11 16:57:05 +02006260 wrap_binaryfunc, "<<="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006261 IBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift,
Eli Benderskyd3baae72011-11-11 16:57:05 +02006262 wrap_binaryfunc, ">>="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006263 IBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and,
Eli Benderskyd3baae72011-11-11 16:57:05 +02006264 wrap_binaryfunc, "&="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006265 IBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor,
Eli Benderskyd3baae72011-11-11 16:57:05 +02006266 wrap_binaryfunc, "^="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006267 IBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or,
Eli Benderskyd3baae72011-11-11 16:57:05 +02006268 wrap_binaryfunc, "|="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006269 BINSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
6270 RBINSLOT("__rfloordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
6271 BINSLOT("__truediv__", nb_true_divide, slot_nb_true_divide, "/"),
6272 RBINSLOT("__rtruediv__", nb_true_divide, slot_nb_true_divide, "/"),
6273 IBSLOT("__ifloordiv__", nb_inplace_floor_divide,
Georg Brandle1d26f32014-10-31 13:12:57 +01006274 slot_nb_inplace_floor_divide, wrap_binaryfunc, "//="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006275 IBSLOT("__itruediv__", nb_inplace_true_divide,
Georg Brandle1d26f32014-10-31 13:12:57 +01006276 slot_nb_inplace_true_divide, wrap_binaryfunc, "/="),
Benjamin Peterson63952412013-04-01 17:41:41 -04006277 NBSLOT("__index__", nb_index, slot_nb_index, wrap_unaryfunc,
Larry Hastings69a25472014-02-09 22:22:38 -08006278 "__index__($self, /)\n--\n\n"
Zachary Ware715ef022014-04-18 09:23:14 -05006279 "Return self converted to an integer, if self is suitable "
Larry Hastings5c661892014-01-24 06:17:25 -08006280 "for use as an index into a list."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006281 MPSLOT("__len__", mp_length, slot_mp_length, wrap_lenfunc,
Larry Hastings69a25472014-02-09 22:22:38 -08006282 "__len__($self, /)\n--\n\nReturn len(self)."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006283 MPSLOT("__getitem__", mp_subscript, slot_mp_subscript,
6284 wrap_binaryfunc,
Larry Hastings69a25472014-02-09 22:22:38 -08006285 "__getitem__($self, key, /)\n--\n\nReturn self[key]."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006286 MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript,
6287 wrap_objobjargproc,
Larry Hastings69a25472014-02-09 22:22:38 -08006288 "__setitem__($self, key, value, /)\n--\n\nSet self[key] to value."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006289 MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript,
6290 wrap_delitem,
Yury Selivanov056e2652014-03-02 12:25:27 -05006291 "__delitem__($self, key, /)\n--\n\nDelete self[key]."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006292
6293 SQSLOT("__len__", sq_length, slot_sq_length, wrap_lenfunc,
Larry Hastings69a25472014-02-09 22:22:38 -08006294 "__len__($self, /)\n--\n\nReturn len(self)."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006295 /* Heap types defining __add__/__mul__ have sq_concat/sq_repeat == NULL.
6296 The logic in abstract.c always falls back to nb_add/nb_multiply in
6297 this case. Defining both the nb_* and the sq_* slots to call the
6298 user-defined methods has unexpected side-effects, as shown by
6299 test_descr.notimplemented() */
6300 SQSLOT("__add__", sq_concat, NULL, wrap_binaryfunc,
Larry Hastings69a25472014-02-09 22:22:38 -08006301 "__add__($self, value, /)\n--\n\nReturn self+value."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006302 SQSLOT("__mul__", sq_repeat, NULL, wrap_indexargfunc,
Larry Hastings69a25472014-02-09 22:22:38 -08006303 "__mul__($self, value, /)\n--\n\nReturn self*value.n"),
Benjamin Peterson63952412013-04-01 17:41:41 -04006304 SQSLOT("__rmul__", sq_repeat, NULL, wrap_indexargfunc,
Larry Hastings69a25472014-02-09 22:22:38 -08006305 "__rmul__($self, value, /)\n--\n\nReturn self*value."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006306 SQSLOT("__getitem__", sq_item, slot_sq_item, wrap_sq_item,
Larry Hastings69a25472014-02-09 22:22:38 -08006307 "__getitem__($self, key, /)\n--\n\nReturn self[key]."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006308 SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_setitem,
Larry Hastings69a25472014-02-09 22:22:38 -08006309 "__setitem__($self, key, value, /)\n--\n\nSet self[key] to value."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006310 SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_delitem,
Larry Hastings69a25472014-02-09 22:22:38 -08006311 "__delitem__($self, key, /)\n--\n\nDelete self[key]."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006312 SQSLOT("__contains__", sq_contains, slot_sq_contains, wrap_objobjproc,
Larry Hastings69a25472014-02-09 22:22:38 -08006313 "__contains__($self, key, /)\n--\n\nReturn key in self."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006314 SQSLOT("__iadd__", sq_inplace_concat, NULL,
Larry Hastings5c661892014-01-24 06:17:25 -08006315 wrap_binaryfunc,
Larry Hastings69a25472014-02-09 22:22:38 -08006316 "__iadd__($self, value, /)\n--\n\nImplement self+=value."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006317 SQSLOT("__imul__", sq_inplace_repeat, NULL,
Larry Hastings5c661892014-01-24 06:17:25 -08006318 wrap_indexargfunc,
Larry Hastings69a25472014-02-09 22:22:38 -08006319 "__imul__($self, value, /)\n--\n\nImplement self*=value."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006320
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006321 {NULL}
Guido van Rossum7b9144b2001-10-09 19:39:46 +00006322};
6323
Guido van Rossumc334df52002-04-04 23:44:47 +00006324/* Given a type pointer and an offset gotten from a slotdef entry, return a
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006325 pointer to the actual slot. This is not quite the same as simply adding
Guido van Rossumc334df52002-04-04 23:44:47 +00006326 the offset to the type pointer, since it takes care to indirect through the
6327 proper indirection pointer (as_buffer, etc.); it returns NULL if the
6328 indirection pointer is NULL. */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00006329static void **
Martin v. Löwis18e16552006-02-15 17:27:45 +00006330slotptr(PyTypeObject *type, int ioffset)
Guido van Rossum7b9144b2001-10-09 19:39:46 +00006331{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006332 char *ptr;
6333 long offset = ioffset;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00006334
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006335 /* Note: this depends on the order of the members of PyHeapTypeObject! */
6336 assert(offset >= 0);
6337 assert((size_t)offset < offsetof(PyHeapTypeObject, as_buffer));
6338 if ((size_t)offset >= offsetof(PyHeapTypeObject, as_sequence)) {
6339 ptr = (char *)type->tp_as_sequence;
6340 offset -= offsetof(PyHeapTypeObject, as_sequence);
6341 }
6342 else if ((size_t)offset >= offsetof(PyHeapTypeObject, as_mapping)) {
6343 ptr = (char *)type->tp_as_mapping;
6344 offset -= offsetof(PyHeapTypeObject, as_mapping);
6345 }
6346 else if ((size_t)offset >= offsetof(PyHeapTypeObject, as_number)) {
6347 ptr = (char *)type->tp_as_number;
6348 offset -= offsetof(PyHeapTypeObject, as_number);
6349 }
6350 else {
6351 ptr = (char *)type;
6352 }
6353 if (ptr != NULL)
6354 ptr += offset;
6355 return (void **)ptr;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00006356}
Guido van Rossumf040ede2001-08-07 16:40:56 +00006357
Guido van Rossumc334df52002-04-04 23:44:47 +00006358/* Length of array of slotdef pointers used to store slots with the
6359 same __name__. There should be at most MAX_EQUIV-1 slotdef entries with
6360 the same __name__, for any __name__. Since that's a static property, it is
6361 appropriate to declare fixed-size arrays for this. */
6362#define MAX_EQUIV 10
6363
6364/* Return a slot pointer for a given name, but ONLY if the attribute has
6365 exactly one slot function. The name must be an interned string. */
6366static void **
6367resolve_slotdups(PyTypeObject *type, PyObject *name)
6368{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006369 /* XXX Maybe this could be optimized more -- but is it worth it? */
Guido van Rossumc334df52002-04-04 23:44:47 +00006370
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006371 /* pname and ptrs act as a little cache */
6372 static PyObject *pname;
6373 static slotdef *ptrs[MAX_EQUIV];
6374 slotdef *p, **pp;
6375 void **res, **ptr;
Guido van Rossumc334df52002-04-04 23:44:47 +00006376
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006377 if (pname != name) {
6378 /* Collect all slotdefs that match name into ptrs. */
6379 pname = name;
6380 pp = ptrs;
6381 for (p = slotdefs; p->name_strobj; p++) {
6382 if (p->name_strobj == name)
6383 *pp++ = p;
6384 }
6385 *pp = NULL;
6386 }
Guido van Rossumc334df52002-04-04 23:44:47 +00006387
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006388 /* Look in all matching slots of the type; if exactly one of these has
6389 a filled-in slot, return its value. Otherwise return NULL. */
6390 res = NULL;
6391 for (pp = ptrs; *pp; pp++) {
6392 ptr = slotptr(type, (*pp)->offset);
6393 if (ptr == NULL || *ptr == NULL)
6394 continue;
6395 if (res != NULL)
6396 return NULL;
6397 res = ptr;
6398 }
6399 return res;
Guido van Rossumc334df52002-04-04 23:44:47 +00006400}
6401
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006402/* Common code for update_slots_callback() and fixup_slot_dispatchers(). This
Guido van Rossumc334df52002-04-04 23:44:47 +00006403 does some incredibly complex thinking and then sticks something into the
6404 slot. (It sees if the adjacent slotdefs for the same slot have conflicting
6405 interests, and then stores a generic wrapper or a specific function into
6406 the slot.) Return a pointer to the next slotdef with a different offset,
6407 because that's convenient for fixup_slot_dispatchers(). */
6408static slotdef *
6409update_one_slot(PyTypeObject *type, slotdef *p)
6410{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006411 PyObject *descr;
6412 PyWrapperDescrObject *d;
6413 void *generic = NULL, *specific = NULL;
6414 int use_generic = 0;
6415 int offset = p->offset;
6416 void **ptr = slotptr(type, offset);
Guido van Rossumc334df52002-04-04 23:44:47 +00006417
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006418 if (ptr == NULL) {
6419 do {
6420 ++p;
6421 } while (p->offset == offset);
6422 return p;
6423 }
6424 do {
6425 descr = _PyType_Lookup(type, p->name_strobj);
6426 if (descr == NULL) {
6427 if (ptr == (void**)&type->tp_iternext) {
Trent Nelsonab02db22012-09-18 21:58:03 -04006428 specific = (void *)_PyObject_NextNotImplemented;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006429 }
6430 continue;
6431 }
Benjamin Peterson7b166872012-04-24 11:06:25 -04006432 if (Py_TYPE(descr) == &PyWrapperDescr_Type &&
6433 ((PyWrapperDescrObject *)descr)->d_base->name_strobj == p->name_strobj) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006434 void **tptr = resolve_slotdups(type, p->name_strobj);
6435 if (tptr == NULL || tptr == ptr)
6436 generic = p->function;
6437 d = (PyWrapperDescrObject *)descr;
6438 if (d->d_base->wrapper == p->wrapper &&
6439 PyType_IsSubtype(type, PyDescr_TYPE(d)))
6440 {
6441 if (specific == NULL ||
6442 specific == d->d_wrapped)
6443 specific = d->d_wrapped;
6444 else
6445 use_generic = 1;
6446 }
6447 }
6448 else if (Py_TYPE(descr) == &PyCFunction_Type &&
6449 PyCFunction_GET_FUNCTION(descr) ==
6450 (PyCFunction)tp_new_wrapper &&
6451 ptr == (void**)&type->tp_new)
6452 {
6453 /* The __new__ wrapper is not a wrapper descriptor,
6454 so must be special-cased differently.
6455 If we don't do this, creating an instance will
6456 always use slot_tp_new which will look up
6457 __new__ in the MRO which will call tp_new_wrapper
6458 which will look through the base classes looking
6459 for a static base and call its tp_new (usually
6460 PyType_GenericNew), after performing various
6461 sanity checks and constructing a new argument
6462 list. Cut all that nonsense short -- this speeds
6463 up instance creation tremendously. */
6464 specific = (void *)type->tp_new;
6465 /* XXX I'm not 100% sure that there isn't a hole
6466 in this reasoning that requires additional
6467 sanity checks. I'll buy the first person to
6468 point out a bug in this reasoning a beer. */
6469 }
6470 else if (descr == Py_None &&
6471 ptr == (void**)&type->tp_hash) {
6472 /* We specifically allow __hash__ to be set to None
6473 to prevent inheritance of the default
6474 implementation from object.__hash__ */
Trent Nelsonab02db22012-09-18 21:58:03 -04006475 specific = (void *)PyObject_HashNotImplemented;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006476 }
6477 else {
6478 use_generic = 1;
6479 generic = p->function;
6480 }
6481 } while ((++p)->offset == offset);
6482 if (specific && !use_generic)
6483 *ptr = specific;
6484 else
6485 *ptr = generic;
6486 return p;
Guido van Rossumc334df52002-04-04 23:44:47 +00006487}
6488
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006489/* In the type, update the slots whose slotdefs are gathered in the pp array.
6490 This is a callback for update_subclasses(). */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006491static int
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006492update_slots_callback(PyTypeObject *type, void *data)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006493{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006494 slotdef **pp = (slotdef **)data;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006495
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006496 for (; *pp; pp++)
6497 update_one_slot(type, *pp);
6498 return 0;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006499}
6500
Guido van Rossumc334df52002-04-04 23:44:47 +00006501/* Initialize the slotdefs table by adding interned string objects for the
6502 names and sorting the entries. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006503static void
Guido van Rossumd396b9c2001-10-13 20:02:41 +00006504init_slotdefs(void)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006505{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006506 slotdef *p;
6507 static int initialized = 0;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006508
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006509 if (initialized)
6510 return;
6511 for (p = slotdefs; p->name; p++) {
Benjamin Peterson63952412013-04-01 17:41:41 -04006512 /* Slots must be ordered by their offset in the PyHeapTypeObject. */
6513 assert(!p[1].name || p->offset <= p[1].offset);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006514 p->name_strobj = PyUnicode_InternFromString(p->name);
6515 if (!p->name_strobj)
6516 Py_FatalError("Out of memory interning slotdef names");
6517 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006518 initialized = 1;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006519}
6520
Guido van Rossumc334df52002-04-04 23:44:47 +00006521/* Update the slots after assignment to a class (type) attribute. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006522static int
6523update_slot(PyTypeObject *type, PyObject *name)
6524{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006525 slotdef *ptrs[MAX_EQUIV];
6526 slotdef *p;
6527 slotdef **pp;
6528 int offset;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006529
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006530 /* Clear the VALID_VERSION flag of 'type' and all its
6531 subclasses. This could possibly be unified with the
6532 update_subclasses() recursion below, but carefully:
6533 they each have their own conditions on which to stop
6534 recursing into subclasses. */
6535 PyType_Modified(type);
Christian Heimesa62da1d2008-01-12 19:39:10 +00006536
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006537 init_slotdefs();
6538 pp = ptrs;
6539 for (p = slotdefs; p->name; p++) {
6540 /* XXX assume name is interned! */
6541 if (p->name_strobj == name)
6542 *pp++ = p;
6543 }
6544 *pp = NULL;
6545 for (pp = ptrs; *pp; pp++) {
6546 p = *pp;
6547 offset = p->offset;
6548 while (p > slotdefs && (p-1)->offset == offset)
6549 --p;
6550 *pp = p;
6551 }
6552 if (ptrs[0] == NULL)
6553 return 0; /* Not an attribute that affects any slots */
6554 return update_subclasses(type, name,
6555 update_slots_callback, (void *)ptrs);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006556}
6557
Guido van Rossumc334df52002-04-04 23:44:47 +00006558/* Store the proper functions in the slot dispatches at class (type)
6559 definition time, based upon which operations the class overrides in its
6560 dict. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00006561static void
Guido van Rossum7b9144b2001-10-09 19:39:46 +00006562fixup_slot_dispatchers(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00006563{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006564 slotdef *p;
Tim Peters6d6c1a32001-08-02 04:15:00 +00006565
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006566 init_slotdefs();
6567 for (p = slotdefs; p->name; )
6568 p = update_one_slot(type, p);
Tim Peters6d6c1a32001-08-02 04:15:00 +00006569}
Guido van Rossum705f0f52001-08-24 16:47:00 +00006570
Michael W. Hudson98bbc492002-11-26 14:47:27 +00006571static void
6572update_all_slots(PyTypeObject* type)
6573{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006574 slotdef *p;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00006575
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006576 init_slotdefs();
6577 for (p = slotdefs; p->name; p++) {
6578 /* update_slot returns int but can't actually fail */
6579 update_slot(type, p->name_strobj);
6580 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +00006581}
6582
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006583/* recurse_down_subclasses() and update_subclasses() are mutually
6584 recursive functions to call a callback for all subclasses,
6585 but refraining from recursing into subclasses that define 'name'. */
6586
6587static int
6588update_subclasses(PyTypeObject *type, PyObject *name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006589 update_callback callback, void *data)
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006590{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006591 if (callback(type, data) < 0)
6592 return -1;
6593 return recurse_down_subclasses(type, name, callback, data);
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006594}
6595
6596static int
6597recurse_down_subclasses(PyTypeObject *type, PyObject *name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006598 update_callback callback, void *data)
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006599{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006600 PyTypeObject *subclass;
6601 PyObject *ref, *subclasses, *dict;
Antoine Pitrou84745ab2013-10-29 21:31:25 +01006602 Py_ssize_t i;
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006603
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006604 subclasses = type->tp_subclasses;
6605 if (subclasses == NULL)
6606 return 0;
Antoine Pitrou84745ab2013-10-29 21:31:25 +01006607 assert(PyDict_CheckExact(subclasses));
6608 i = 0;
6609 while (PyDict_Next(subclasses, &i, NULL, &ref)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006610 assert(PyWeakref_CheckRef(ref));
6611 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
6612 assert(subclass != NULL);
6613 if ((PyObject *)subclass == Py_None)
6614 continue;
6615 assert(PyType_Check(subclass));
6616 /* Avoid recursing down into unaffected classes */
6617 dict = subclass->tp_dict;
6618 if (dict != NULL && PyDict_Check(dict) &&
6619 PyDict_GetItem(dict, name) != NULL)
6620 continue;
6621 if (update_subclasses(subclass, name, callback, data) < 0)
6622 return -1;
6623 }
6624 return 0;
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006625}
6626
Guido van Rossum6d204072001-10-21 00:44:31 +00006627/* This function is called by PyType_Ready() to populate the type's
6628 dictionary with method descriptors for function slots. For each
Guido van Rossum09638c12002-06-13 19:17:46 +00006629 function slot (like tp_repr) that's defined in the type, one or more
6630 corresponding descriptors are added in the type's tp_dict dictionary
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006631 under the appropriate name (like __repr__). Some function slots
Guido van Rossum09638c12002-06-13 19:17:46 +00006632 cause more than one descriptor to be added (for example, the nb_add
6633 slot adds both __add__ and __radd__ descriptors) and some function
6634 slots compete for the same descriptor (for example both sq_item and
6635 mp_subscript generate a __getitem__ descriptor).
6636
Ezio Melotti13925002011-03-16 11:05:33 +02006637 In the latter case, the first slotdef entry encountered wins. Since
Tim Petersbf9b2442003-03-23 05:35:36 +00006638 slotdef entries are sorted by the offset of the slot in the
Guido van Rossume5c691a2003-03-07 15:13:17 +00006639 PyHeapTypeObject, this gives us some control over disambiguating
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006640 between competing slots: the members of PyHeapTypeObject are listed
6641 from most general to least general, so the most general slot is
6642 preferred. In particular, because as_mapping comes before as_sequence,
6643 for a type that defines both mp_subscript and sq_item, mp_subscript
6644 wins.
Guido van Rossum09638c12002-06-13 19:17:46 +00006645
6646 This only adds new descriptors and doesn't overwrite entries in
6647 tp_dict that were previously defined. The descriptors contain a
6648 reference to the C function they must call, so that it's safe if they
6649 are copied into a subtype's __dict__ and the subtype has a different
6650 C function in its slot -- calling the method defined by the
6651 descriptor will call the C function that was used to create it,
6652 rather than the C function present in the slot when it is called.
6653 (This is important because a subtype may have a C function in the
6654 slot that calls the method from the dictionary, and we want to avoid
6655 infinite recursion here.) */
Guido van Rossum6d204072001-10-21 00:44:31 +00006656
6657static int
6658add_operators(PyTypeObject *type)
6659{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006660 PyObject *dict = type->tp_dict;
6661 slotdef *p;
6662 PyObject *descr;
6663 void **ptr;
Guido van Rossum6d204072001-10-21 00:44:31 +00006664
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006665 init_slotdefs();
6666 for (p = slotdefs; p->name; p++) {
6667 if (p->wrapper == NULL)
6668 continue;
6669 ptr = slotptr(type, p->offset);
6670 if (!ptr || !*ptr)
6671 continue;
6672 if (PyDict_GetItem(dict, p->name_strobj))
6673 continue;
Trent Nelsonab02db22012-09-18 21:58:03 -04006674 if (*ptr == (void *)PyObject_HashNotImplemented) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006675 /* Classes may prevent the inheritance of the tp_hash
6676 slot by storing PyObject_HashNotImplemented in it. Make it
6677 visible as a None value for the __hash__ attribute. */
6678 if (PyDict_SetItem(dict, p->name_strobj, Py_None) < 0)
6679 return -1;
6680 }
6681 else {
6682 descr = PyDescr_NewWrapper(type, p, *ptr);
6683 if (descr == NULL)
6684 return -1;
6685 if (PyDict_SetItem(dict, p->name_strobj, descr) < 0)
6686 return -1;
6687 Py_DECREF(descr);
6688 }
6689 }
6690 if (type->tp_new != NULL) {
6691 if (add_tp_new_wrapper(type) < 0)
6692 return -1;
6693 }
6694 return 0;
Guido van Rossum6d204072001-10-21 00:44:31 +00006695}
6696
Guido van Rossum705f0f52001-08-24 16:47:00 +00006697
6698/* Cooperative 'super' */
6699
6700typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006701 PyObject_HEAD
6702 PyTypeObject *type;
6703 PyObject *obj;
6704 PyTypeObject *obj_type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006705} superobject;
6706
Guido van Rossum6f799372001-09-20 20:46:19 +00006707static PyMemberDef super_members[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006708 {"__thisclass__", T_OBJECT, offsetof(superobject, type), READONLY,
6709 "the class invoking super()"},
6710 {"__self__", T_OBJECT, offsetof(superobject, obj), READONLY,
6711 "the instance invoking super(); may be None"},
6712 {"__self_class__", T_OBJECT, offsetof(superobject, obj_type), READONLY,
6713 "the type of the instance invoking super(); may be None"},
6714 {0}
Guido van Rossum41eb14d2001-08-30 23:13:11 +00006715};
6716
Guido van Rossum705f0f52001-08-24 16:47:00 +00006717static void
6718super_dealloc(PyObject *self)
6719{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006720 superobject *su = (superobject *)self;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006721
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006722 _PyObject_GC_UNTRACK(self);
6723 Py_XDECREF(su->obj);
6724 Py_XDECREF(su->type);
6725 Py_XDECREF(su->obj_type);
6726 Py_TYPE(self)->tp_free(self);
Guido van Rossum705f0f52001-08-24 16:47:00 +00006727}
6728
6729static PyObject *
Guido van Rossum41eb14d2001-08-30 23:13:11 +00006730super_repr(PyObject *self)
6731{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006732 superobject *su = (superobject *)self;
Guido van Rossum41eb14d2001-08-30 23:13:11 +00006733
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006734 if (su->obj_type)
6735 return PyUnicode_FromFormat(
6736 "<super: <class '%s'>, <%s object>>",
6737 su->type ? su->type->tp_name : "NULL",
6738 su->obj_type->tp_name);
6739 else
6740 return PyUnicode_FromFormat(
6741 "<super: <class '%s'>, NULL>",
6742 su->type ? su->type->tp_name : "NULL");
Guido van Rossum41eb14d2001-08-30 23:13:11 +00006743}
6744
6745static PyObject *
Guido van Rossum705f0f52001-08-24 16:47:00 +00006746super_getattro(PyObject *self, PyObject *name)
6747{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006748 superobject *su = (superobject *)self;
6749 int skip = su->obj_type == NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006750
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006751 if (!skip) {
6752 /* We want __class__ to return the class of the super object
6753 (i.e. super, or a subclass), not the class of su->obj. */
6754 skip = (PyUnicode_Check(name) &&
Victor Stinnerad14ccd2013-11-07 00:46:04 +01006755 PyUnicode_GET_LENGTH(name) == 9 &&
6756 _PyUnicode_CompareWithId(name, &PyId___class__) == 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006757 }
Guido van Rossum76ba09f2003-04-16 19:40:58 +00006758
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006759 if (!skip) {
6760 PyObject *mro, *res, *tmp, *dict;
6761 PyTypeObject *starttype;
6762 descrgetfunc f;
6763 Py_ssize_t i, n;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006764
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006765 starttype = su->obj_type;
6766 mro = starttype->tp_mro;
Guido van Rossum155db9a2002-04-02 17:53:47 +00006767
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006768 if (mro == NULL)
6769 n = 0;
6770 else {
6771 assert(PyTuple_Check(mro));
6772 n = PyTuple_GET_SIZE(mro);
6773 }
6774 for (i = 0; i < n; i++) {
6775 if ((PyObject *)(su->type) == PyTuple_GET_ITEM(mro, i))
6776 break;
6777 }
6778 i++;
6779 res = NULL;
Victor Stinnerd74782b2012-03-09 00:39:08 +01006780 /* keep a strong reference to mro because starttype->tp_mro can be
6781 replaced during PyDict_GetItem(dict, name) */
6782 Py_INCREF(mro);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006783 for (; i < n; i++) {
6784 tmp = PyTuple_GET_ITEM(mro, i);
6785 if (PyType_Check(tmp))
6786 dict = ((PyTypeObject *)tmp)->tp_dict;
6787 else
6788 continue;
6789 res = PyDict_GetItem(dict, name);
6790 if (res != NULL) {
6791 Py_INCREF(res);
6792 f = Py_TYPE(res)->tp_descr_get;
6793 if (f != NULL) {
6794 tmp = f(res,
6795 /* Only pass 'obj' param if
6796 this is instance-mode super
6797 (See SF ID #743627)
6798 */
6799 (su->obj == (PyObject *)
6800 su->obj_type
6801 ? (PyObject *)NULL
6802 : su->obj),
6803 (PyObject *)starttype);
6804 Py_DECREF(res);
6805 res = tmp;
6806 }
Victor Stinnerd74782b2012-03-09 00:39:08 +01006807 Py_DECREF(mro);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006808 return res;
6809 }
6810 }
Victor Stinnerd74782b2012-03-09 00:39:08 +01006811 Py_DECREF(mro);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006812 }
6813 return PyObject_GenericGetAttr(self, name);
Guido van Rossum705f0f52001-08-24 16:47:00 +00006814}
6815
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006816static PyTypeObject *
Guido van Rossum5b443c62001-12-03 15:38:28 +00006817supercheck(PyTypeObject *type, PyObject *obj)
6818{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006819 /* Check that a super() call makes sense. Return a type object.
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006820
Florent Xiclunaaa6c1d22011-12-12 18:54:29 +01006821 obj can be a class, or an instance of one:
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006822
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006823 - If it is a class, it must be a subclass of 'type'. This case is
6824 used for class methods; the return value is obj.
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006825
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006826 - If it is an instance, it must be an instance of 'type'. This is
6827 the normal case; the return value is obj.__class__.
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006828
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006829 But... when obj is an instance, we want to allow for the case where
6830 Py_TYPE(obj) is not a subclass of type, but obj.__class__ is!
6831 This will allow using super() with a proxy for obj.
6832 */
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006833
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006834 /* Check for first bullet above (special case) */
6835 if (PyType_Check(obj) && PyType_IsSubtype((PyTypeObject *)obj, type)) {
6836 Py_INCREF(obj);
6837 return (PyTypeObject *)obj;
6838 }
Guido van Rossum8e80a722003-02-18 19:22:22 +00006839
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006840 /* Normal case */
6841 if (PyType_IsSubtype(Py_TYPE(obj), type)) {
6842 Py_INCREF(Py_TYPE(obj));
6843 return Py_TYPE(obj);
6844 }
6845 else {
6846 /* Try the slow way */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006847 PyObject *class_attr;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006848
Martin v. Löwisbfc6d742011-10-13 20:03:57 +02006849 class_attr = _PyObject_GetAttrId(obj, &PyId___class__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006850 if (class_attr != NULL &&
6851 PyType_Check(class_attr) &&
6852 (PyTypeObject *)class_attr != Py_TYPE(obj))
6853 {
6854 int ok = PyType_IsSubtype(
6855 (PyTypeObject *)class_attr, type);
6856 if (ok)
6857 return (PyTypeObject *)class_attr;
6858 }
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006859
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006860 if (class_attr == NULL)
6861 PyErr_Clear();
6862 else
6863 Py_DECREF(class_attr);
6864 }
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006865
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006866 PyErr_SetString(PyExc_TypeError,
6867 "super(type, obj): "
6868 "obj must be an instance or subtype of type");
6869 return NULL;
Guido van Rossum5b443c62001-12-03 15:38:28 +00006870}
6871
Guido van Rossum705f0f52001-08-24 16:47:00 +00006872static PyObject *
6873super_descr_get(PyObject *self, PyObject *obj, PyObject *type)
6874{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006875 superobject *su = (superobject *)self;
6876 superobject *newobj;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006877
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006878 if (obj == NULL || obj == Py_None || su->obj != NULL) {
6879 /* Not binding to an object, or already bound */
6880 Py_INCREF(self);
6881 return self;
6882 }
6883 if (Py_TYPE(su) != &PySuper_Type)
6884 /* If su is an instance of a (strict) subclass of super,
6885 call its type */
6886 return PyObject_CallFunctionObjArgs((PyObject *)Py_TYPE(su),
6887 su->type, obj, NULL);
6888 else {
6889 /* Inline the common case */
6890 PyTypeObject *obj_type = supercheck(su->type, obj);
6891 if (obj_type == NULL)
6892 return NULL;
6893 newobj = (superobject *)PySuper_Type.tp_new(&PySuper_Type,
6894 NULL, NULL);
6895 if (newobj == NULL)
6896 return NULL;
6897 Py_INCREF(su->type);
6898 Py_INCREF(obj);
6899 newobj->type = su->type;
6900 newobj->obj = obj;
6901 newobj->obj_type = obj_type;
6902 return (PyObject *)newobj;
6903 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00006904}
6905
6906static int
6907super_init(PyObject *self, PyObject *args, PyObject *kwds)
6908{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006909 superobject *su = (superobject *)self;
6910 PyTypeObject *type = NULL;
6911 PyObject *obj = NULL;
6912 PyTypeObject *obj_type = NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006913
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006914 if (!_PyArg_NoKeywords("super", kwds))
6915 return -1;
6916 if (!PyArg_ParseTuple(args, "|O!O:super", &PyType_Type, &type, &obj))
6917 return -1;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00006918
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006919 if (type == NULL) {
6920 /* Call super(), without args -- fill in from __class__
6921 and first local variable on the stack. */
Victor Stinner1c6970f2014-05-13 01:32:36 +02006922 PyFrameObject *f;
6923 PyCodeObject *co;
Victor Stinner0fcab4a2011-01-04 12:59:15 +00006924 Py_ssize_t i, n;
Victor Stinner1c6970f2014-05-13 01:32:36 +02006925 f = PyThreadState_GET()->frame;
6926 if (f == NULL) {
6927 PyErr_SetString(PyExc_RuntimeError,
6928 "super(): no current frame");
6929 return -1;
6930 }
6931 co = f->f_code;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006932 if (co == NULL) {
Benjamin Peterson6a42bd62012-09-01 23:04:38 -04006933 PyErr_SetString(PyExc_RuntimeError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006934 "super(): no code object");
6935 return -1;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00006936 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006937 if (co->co_argcount == 0) {
Benjamin Peterson6a42bd62012-09-01 23:04:38 -04006938 PyErr_SetString(PyExc_RuntimeError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006939 "super(): no arguments");
6940 return -1;
6941 }
6942 obj = f->f_localsplus[0];
Benjamin Peterson159ae412013-05-12 18:16:06 -05006943 if (obj == NULL && co->co_cell2arg) {
6944 /* The first argument might be a cell. */
6945 n = PyTuple_GET_SIZE(co->co_cellvars);
6946 for (i = 0; i < n; i++) {
6947 if (co->co_cell2arg[i] == 0) {
6948 PyObject *cell = f->f_localsplus[co->co_nlocals + i];
6949 assert(PyCell_Check(cell));
6950 obj = PyCell_GET(cell);
6951 break;
6952 }
6953 }
Guido van Rossum6832c812013-05-10 08:47:42 -07006954 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006955 if (obj == NULL) {
Benjamin Peterson6a42bd62012-09-01 23:04:38 -04006956 PyErr_SetString(PyExc_RuntimeError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006957 "super(): arg[0] deleted");
6958 return -1;
6959 }
6960 if (co->co_freevars == NULL)
6961 n = 0;
6962 else {
6963 assert(PyTuple_Check(co->co_freevars));
6964 n = PyTuple_GET_SIZE(co->co_freevars);
6965 }
6966 for (i = 0; i < n; i++) {
6967 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
6968 assert(PyUnicode_Check(name));
Victor Stinnerad14ccd2013-11-07 00:46:04 +01006969 if (!_PyUnicode_CompareWithId(name, &PyId___class__)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006970 Py_ssize_t index = co->co_nlocals +
6971 PyTuple_GET_SIZE(co->co_cellvars) + i;
6972 PyObject *cell = f->f_localsplus[index];
6973 if (cell == NULL || !PyCell_Check(cell)) {
Benjamin Peterson6a42bd62012-09-01 23:04:38 -04006974 PyErr_SetString(PyExc_RuntimeError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006975 "super(): bad __class__ cell");
6976 return -1;
6977 }
6978 type = (PyTypeObject *) PyCell_GET(cell);
6979 if (type == NULL) {
Benjamin Peterson6a42bd62012-09-01 23:04:38 -04006980 PyErr_SetString(PyExc_RuntimeError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006981 "super(): empty __class__ cell");
6982 return -1;
6983 }
6984 if (!PyType_Check(type)) {
Benjamin Peterson6a42bd62012-09-01 23:04:38 -04006985 PyErr_Format(PyExc_RuntimeError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006986 "super(): __class__ is not a type (%s)",
6987 Py_TYPE(type)->tp_name);
6988 return -1;
6989 }
6990 break;
6991 }
6992 }
6993 if (type == NULL) {
Benjamin Peterson6a42bd62012-09-01 23:04:38 -04006994 PyErr_SetString(PyExc_RuntimeError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006995 "super(): __class__ cell not found");
6996 return -1;
6997 }
6998 }
Guido van Rossumcd16bf62007-06-13 18:07:49 +00006999
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007000 if (obj == Py_None)
7001 obj = NULL;
7002 if (obj != NULL) {
7003 obj_type = supercheck(type, obj);
7004 if (obj_type == NULL)
7005 return -1;
7006 Py_INCREF(obj);
7007 }
7008 Py_INCREF(type);
7009 su->type = type;
7010 su->obj = obj;
7011 su->obj_type = obj_type;
7012 return 0;
Guido van Rossum705f0f52001-08-24 16:47:00 +00007013}
7014
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007015PyDoc_STRVAR(super_doc,
Guido van Rossumcd16bf62007-06-13 18:07:49 +00007016"super() -> same as super(__class__, <first argument>)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00007017"super(type) -> unbound super object\n"
7018"super(type, obj) -> bound super object; requires isinstance(obj, type)\n"
Guido van Rossume705ef12001-08-29 15:47:06 +00007019"super(type, type2) -> bound super object; requires issubclass(type2, type)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00007020"Typical use to call a cooperative superclass method:\n"
7021"class C(B):\n"
7022" def meth(self, arg):\n"
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007023" super().meth(arg)\n"
Guido van Rossumcd16bf62007-06-13 18:07:49 +00007024"This works for class methods too:\n"
7025"class C(B):\n"
7026" @classmethod\n"
7027" def cmeth(cls, arg):\n"
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007028" super().cmeth(arg)\n");
Guido van Rossum705f0f52001-08-24 16:47:00 +00007029
Guido van Rossum048eb752001-10-02 21:24:57 +00007030static int
7031super_traverse(PyObject *self, visitproc visit, void *arg)
7032{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007033 superobject *su = (superobject *)self;
Guido van Rossum048eb752001-10-02 21:24:57 +00007034
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007035 Py_VISIT(su->obj);
7036 Py_VISIT(su->type);
7037 Py_VISIT(su->obj_type);
Guido van Rossum048eb752001-10-02 21:24:57 +00007038
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007039 return 0;
Guido van Rossum048eb752001-10-02 21:24:57 +00007040}
7041
Guido van Rossum705f0f52001-08-24 16:47:00 +00007042PyTypeObject PySuper_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007043 PyVarObject_HEAD_INIT(&PyType_Type, 0)
7044 "super", /* tp_name */
7045 sizeof(superobject), /* tp_basicsize */
7046 0, /* tp_itemsize */
7047 /* methods */
7048 super_dealloc, /* tp_dealloc */
7049 0, /* tp_print */
7050 0, /* tp_getattr */
7051 0, /* tp_setattr */
7052 0, /* tp_reserved */
7053 super_repr, /* tp_repr */
7054 0, /* tp_as_number */
7055 0, /* tp_as_sequence */
7056 0, /* tp_as_mapping */
7057 0, /* tp_hash */
7058 0, /* tp_call */
7059 0, /* tp_str */
7060 super_getattro, /* tp_getattro */
7061 0, /* tp_setattro */
7062 0, /* tp_as_buffer */
7063 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
7064 Py_TPFLAGS_BASETYPE, /* tp_flags */
7065 super_doc, /* tp_doc */
7066 super_traverse, /* tp_traverse */
7067 0, /* tp_clear */
7068 0, /* tp_richcompare */
7069 0, /* tp_weaklistoffset */
7070 0, /* tp_iter */
7071 0, /* tp_iternext */
7072 0, /* tp_methods */
7073 super_members, /* tp_members */
7074 0, /* tp_getset */
7075 0, /* tp_base */
7076 0, /* tp_dict */
7077 super_descr_get, /* tp_descr_get */
7078 0, /* tp_descr_set */
7079 0, /* tp_dictoffset */
7080 super_init, /* tp_init */
7081 PyType_GenericAlloc, /* tp_alloc */
7082 PyType_GenericNew, /* tp_new */
7083 PyObject_GC_Del, /* tp_free */
Guido van Rossum705f0f52001-08-24 16:47:00 +00007084};