blob: be9747a166cc53d56100169015935800e8b7a00f [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);
Benjamin Petersond51374e2014-04-09 23:55:56 -04004472 COPYNUM(nb_matrix_multiply);
4473 COPYNUM(nb_inplace_matrix_multiply);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004474 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004475
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004476 if (type->tp_as_sequence != NULL && base->tp_as_sequence != NULL) {
4477 basebase = base->tp_base;
4478 if (basebase->tp_as_sequence == NULL)
4479 basebase = NULL;
4480 COPYSEQ(sq_length);
4481 COPYSEQ(sq_concat);
4482 COPYSEQ(sq_repeat);
4483 COPYSEQ(sq_item);
4484 COPYSEQ(sq_ass_item);
4485 COPYSEQ(sq_contains);
4486 COPYSEQ(sq_inplace_concat);
4487 COPYSEQ(sq_inplace_repeat);
4488 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004489
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004490 if (type->tp_as_mapping != NULL && base->tp_as_mapping != NULL) {
4491 basebase = base->tp_base;
4492 if (basebase->tp_as_mapping == NULL)
4493 basebase = NULL;
4494 COPYMAP(mp_length);
4495 COPYMAP(mp_subscript);
4496 COPYMAP(mp_ass_subscript);
4497 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004498
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004499 if (type->tp_as_buffer != NULL && base->tp_as_buffer != NULL) {
4500 basebase = base->tp_base;
4501 if (basebase->tp_as_buffer == NULL)
4502 basebase = NULL;
4503 COPYBUF(bf_getbuffer);
4504 COPYBUF(bf_releasebuffer);
4505 }
Tim Petersfc57ccb2001-10-12 02:38:24 +00004506
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004507 basebase = base->tp_base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004508
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004509 COPYSLOT(tp_dealloc);
4510 if (type->tp_getattr == NULL && type->tp_getattro == NULL) {
4511 type->tp_getattr = base->tp_getattr;
4512 type->tp_getattro = base->tp_getattro;
4513 }
4514 if (type->tp_setattr == NULL && type->tp_setattro == NULL) {
4515 type->tp_setattr = base->tp_setattr;
4516 type->tp_setattro = base->tp_setattro;
4517 }
4518 /* tp_reserved is ignored */
4519 COPYSLOT(tp_repr);
4520 /* tp_hash see tp_richcompare */
4521 COPYSLOT(tp_call);
4522 COPYSLOT(tp_str);
4523 {
4524 /* Copy comparison-related slots only when
4525 not overriding them anywhere */
4526 if (type->tp_richcompare == NULL &&
4527 type->tp_hash == NULL &&
4528 !overrides_hash(type))
4529 {
4530 type->tp_richcompare = base->tp_richcompare;
4531 type->tp_hash = base->tp_hash;
4532 }
4533 }
4534 {
4535 COPYSLOT(tp_iter);
4536 COPYSLOT(tp_iternext);
4537 }
4538 {
4539 COPYSLOT(tp_descr_get);
4540 COPYSLOT(tp_descr_set);
4541 COPYSLOT(tp_dictoffset);
4542 COPYSLOT(tp_init);
4543 COPYSLOT(tp_alloc);
4544 COPYSLOT(tp_is_gc);
Antoine Pitrou796564c2013-07-30 19:59:21 +02004545 if ((type->tp_flags & Py_TPFLAGS_HAVE_FINALIZE) &&
4546 (base->tp_flags & Py_TPFLAGS_HAVE_FINALIZE)) {
4547 COPYSLOT(tp_finalize);
4548 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004549 if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) ==
4550 (base->tp_flags & Py_TPFLAGS_HAVE_GC)) {
4551 /* They agree about gc. */
4552 COPYSLOT(tp_free);
4553 }
4554 else if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
4555 type->tp_free == NULL &&
4556 base->tp_free == PyObject_Free) {
4557 /* A bit of magic to plug in the correct default
4558 * tp_free function when a derived class adds gc,
4559 * didn't define tp_free, and the base uses the
4560 * default non-gc tp_free.
4561 */
4562 type->tp_free = PyObject_GC_Del;
4563 }
4564 /* else they didn't agree about gc, and there isn't something
4565 * obvious to be done -- the type is on its own.
4566 */
4567 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004568}
4569
Jeremy Hylton938ace62002-07-17 16:30:39 +00004570static int add_operators(PyTypeObject *);
Guido van Rossum13d52f02001-08-10 21:24:08 +00004571
Tim Peters6d6c1a32001-08-02 04:15:00 +00004572int
Guido van Rossum528b7eb2001-08-07 17:24:28 +00004573PyType_Ready(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004574{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004575 PyObject *dict, *bases;
4576 PyTypeObject *base;
4577 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004578
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004579 if (type->tp_flags & Py_TPFLAGS_READY) {
4580 assert(type->tp_dict != NULL);
4581 return 0;
4582 }
4583 assert((type->tp_flags & Py_TPFLAGS_READYING) == 0);
Guido van Rossumd614f972001-08-10 17:39:49 +00004584
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004585 type->tp_flags |= Py_TPFLAGS_READYING;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004586
Tim Peters36eb4df2003-03-23 03:33:13 +00004587#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004588 /* PyType_Ready is the closest thing we have to a choke point
4589 * for type objects, so is the best place I can think of to try
4590 * to get type objects into the doubly-linked list of all objects.
4591 * Still, not all type objects go thru PyType_Ready.
4592 */
4593 _Py_AddToAllObjects((PyObject *)type, 0);
Tim Peters36eb4df2003-03-23 03:33:13 +00004594#endif
4595
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004596 /* Initialize tp_base (defaults to BaseObject unless that's us) */
4597 base = type->tp_base;
4598 if (base == NULL && type != &PyBaseObject_Type) {
4599 base = type->tp_base = &PyBaseObject_Type;
4600 Py_INCREF(base);
4601 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004602
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004603 /* Now the only way base can still be NULL is if type is
4604 * &PyBaseObject_Type.
4605 */
Guido van Rossum692cdbc2006-03-10 02:04:28 +00004606
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004607 /* Initialize the base class */
4608 if (base != NULL && base->tp_dict == NULL) {
4609 if (PyType_Ready(base) < 0)
4610 goto error;
4611 }
Guido van Rossum323a9cf2002-08-14 17:26:30 +00004612
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004613 /* Initialize ob_type if NULL. This means extensions that want to be
4614 compilable separately on Windows can call PyType_Ready() instead of
4615 initializing the ob_type field of their type objects. */
4616 /* The test for base != NULL is really unnecessary, since base is only
4617 NULL when type is &PyBaseObject_Type, and we know its ob_type is
4618 not NULL (it's initialized to &PyType_Type). But coverity doesn't
4619 know that. */
4620 if (Py_TYPE(type) == NULL && base != NULL)
4621 Py_TYPE(type) = Py_TYPE(base);
Guido van Rossum0986d822002-04-08 01:38:42 +00004622
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004623 /* Initialize tp_bases */
4624 bases = type->tp_bases;
4625 if (bases == NULL) {
4626 if (base == NULL)
4627 bases = PyTuple_New(0);
4628 else
4629 bases = PyTuple_Pack(1, base);
4630 if (bases == NULL)
4631 goto error;
4632 type->tp_bases = bases;
4633 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004634
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004635 /* Initialize tp_dict */
4636 dict = type->tp_dict;
4637 if (dict == NULL) {
4638 dict = PyDict_New();
4639 if (dict == NULL)
4640 goto error;
4641 type->tp_dict = dict;
4642 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004643
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004644 /* Add type-specific descriptors to tp_dict */
4645 if (add_operators(type) < 0)
4646 goto error;
4647 if (type->tp_methods != NULL) {
4648 if (add_methods(type, type->tp_methods) < 0)
4649 goto error;
4650 }
4651 if (type->tp_members != NULL) {
4652 if (add_members(type, type->tp_members) < 0)
4653 goto error;
4654 }
4655 if (type->tp_getset != NULL) {
4656 if (add_getset(type, type->tp_getset) < 0)
4657 goto error;
4658 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004659
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004660 /* Calculate method resolution order */
4661 if (mro_internal(type) < 0) {
4662 goto error;
4663 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004664
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004665 /* Inherit special flags from dominant base */
4666 if (type->tp_base != NULL)
4667 inherit_special(type, type->tp_base);
Guido van Rossum13d52f02001-08-10 21:24:08 +00004668
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004669 /* Initialize tp_dict properly */
4670 bases = type->tp_mro;
4671 assert(bases != NULL);
4672 assert(PyTuple_Check(bases));
4673 n = PyTuple_GET_SIZE(bases);
4674 for (i = 1; i < n; i++) {
4675 PyObject *b = PyTuple_GET_ITEM(bases, i);
4676 if (PyType_Check(b))
4677 inherit_slots(type, (PyTypeObject *)b);
4678 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004679
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004680 /* Sanity check for tp_free. */
4681 if (PyType_IS_GC(type) && (type->tp_flags & Py_TPFLAGS_BASETYPE) &&
4682 (type->tp_free == NULL || type->tp_free == PyObject_Del)) {
4683 /* This base class needs to call tp_free, but doesn't have
4684 * one, or its tp_free is for non-gc'ed objects.
4685 */
4686 PyErr_Format(PyExc_TypeError, "type '%.100s' participates in "
4687 "gc and is a base type but has inappropriate "
4688 "tp_free slot",
4689 type->tp_name);
4690 goto error;
4691 }
Tim Peters3cfe7542003-05-21 21:29:48 +00004692
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004693 /* if the type dictionary doesn't contain a __doc__, set it from
4694 the tp_doc slot.
4695 */
Victor Stinner3c1e4812012-03-26 22:10:51 +02004696 if (_PyDict_GetItemId(type->tp_dict, &PyId___doc__) == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004697 if (type->tp_doc != NULL) {
Larry Hastings2623c8c2014-02-08 22:15:29 -08004698 const char *old_doc = _PyType_DocWithoutSignature(type->tp_name,
4699 type->tp_doc);
Larry Hastings5c661892014-01-24 06:17:25 -08004700 PyObject *doc = PyUnicode_FromString(old_doc);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004701 if (doc == NULL)
4702 goto error;
Victor Stinner5967bf42013-07-17 22:01:37 +02004703 if (_PyDict_SetItemId(type->tp_dict, &PyId___doc__, doc) < 0) {
4704 Py_DECREF(doc);
4705 goto error;
4706 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004707 Py_DECREF(doc);
4708 } else {
Victor Stinner5967bf42013-07-17 22:01:37 +02004709 if (_PyDict_SetItemId(type->tp_dict,
4710 &PyId___doc__, Py_None) < 0)
4711 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004712 }
4713 }
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00004714
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004715 /* Hack for tp_hash and __hash__.
4716 If after all that, tp_hash is still NULL, and __hash__ is not in
4717 tp_dict, set tp_hash to PyObject_HashNotImplemented and
4718 tp_dict['__hash__'] equal to None.
4719 This signals that __hash__ is not inherited.
4720 */
4721 if (type->tp_hash == NULL) {
Victor Stinner3c1e4812012-03-26 22:10:51 +02004722 if (_PyDict_GetItemId(type->tp_dict, &PyId___hash__) == NULL) {
4723 if (_PyDict_SetItemId(type->tp_dict, &PyId___hash__, Py_None) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004724 goto error;
4725 type->tp_hash = PyObject_HashNotImplemented;
4726 }
4727 }
Guido van Rossum38938152006-08-21 23:36:26 +00004728
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004729 /* Some more special stuff */
4730 base = type->tp_base;
4731 if (base != NULL) {
4732 if (type->tp_as_number == NULL)
4733 type->tp_as_number = base->tp_as_number;
4734 if (type->tp_as_sequence == NULL)
4735 type->tp_as_sequence = base->tp_as_sequence;
4736 if (type->tp_as_mapping == NULL)
4737 type->tp_as_mapping = base->tp_as_mapping;
4738 if (type->tp_as_buffer == NULL)
4739 type->tp_as_buffer = base->tp_as_buffer;
4740 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004741
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004742 /* Link into each base class's list of subclasses */
4743 bases = type->tp_bases;
4744 n = PyTuple_GET_SIZE(bases);
4745 for (i = 0; i < n; i++) {
4746 PyObject *b = PyTuple_GET_ITEM(bases, i);
4747 if (PyType_Check(b) &&
4748 add_subclass((PyTypeObject *)b, type) < 0)
4749 goto error;
4750 }
Guido van Rossum1c450732001-10-08 15:18:27 +00004751
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004752 /* Warn for a type that implements tp_compare (now known as
4753 tp_reserved) but not tp_richcompare. */
4754 if (type->tp_reserved && !type->tp_richcompare) {
Andrew Svetlov2cd8ce42012-12-23 14:27:17 +02004755 PyErr_Format(PyExc_TypeError,
Victor Stinner4a2b7a12010-08-13 14:03:48 +00004756 "Type %.100s defines tp_reserved (formerly tp_compare) "
4757 "but not tp_richcompare. Comparisons may not behave as intended.",
4758 type->tp_name);
Andrew Svetlov2cd8ce42012-12-23 14:27:17 +02004759 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004760 }
Mark Dickinson2a7d45b2009-02-08 11:02:10 +00004761
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004762 /* All done -- set the ready flag */
4763 assert(type->tp_dict != NULL);
4764 type->tp_flags =
4765 (type->tp_flags & ~Py_TPFLAGS_READYING) | Py_TPFLAGS_READY;
4766 return 0;
Guido van Rossumd614f972001-08-10 17:39:49 +00004767
4768 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004769 type->tp_flags &= ~Py_TPFLAGS_READYING;
4770 return -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004771}
4772
Guido van Rossum1c450732001-10-08 15:18:27 +00004773static int
4774add_subclass(PyTypeObject *base, PyTypeObject *type)
4775{
Antoine Pitrou84745ab2013-10-29 21:31:25 +01004776 int result = -1;
4777 PyObject *dict, *key, *newobj;
Guido van Rossum1c450732001-10-08 15:18:27 +00004778
Antoine Pitrou84745ab2013-10-29 21:31:25 +01004779 dict = base->tp_subclasses;
4780 if (dict == NULL) {
4781 base->tp_subclasses = dict = PyDict_New();
4782 if (dict == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004783 return -1;
4784 }
Antoine Pitrou84745ab2013-10-29 21:31:25 +01004785 assert(PyDict_CheckExact(dict));
4786 key = PyLong_FromVoidPtr((void *) type);
4787 if (key == NULL)
Victor Stinner9812af82013-07-08 22:25:48 +02004788 return -1;
Antoine Pitrou84745ab2013-10-29 21:31:25 +01004789 newobj = PyWeakref_NewRef((PyObject *)type, NULL);
4790 if (newobj != NULL) {
4791 result = PyDict_SetItem(dict, key, newobj);
4792 Py_DECREF(newobj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004793 }
Antoine Pitrou84745ab2013-10-29 21:31:25 +01004794 Py_DECREF(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004795 return result;
Guido van Rossum1c450732001-10-08 15:18:27 +00004796}
4797
Michael W. Hudson98bbc492002-11-26 14:47:27 +00004798static void
4799remove_subclass(PyTypeObject *base, PyTypeObject *type)
4800{
Antoine Pitrou84745ab2013-10-29 21:31:25 +01004801 PyObject *dict, *key;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00004802
Antoine Pitrou84745ab2013-10-29 21:31:25 +01004803 dict = base->tp_subclasses;
4804 if (dict == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004805 return;
4806 }
Antoine Pitrou84745ab2013-10-29 21:31:25 +01004807 assert(PyDict_CheckExact(dict));
4808 key = PyLong_FromVoidPtr((void *) type);
4809 if (key == NULL || PyDict_DelItem(dict, key)) {
4810 /* This can happen if the type initialization errored out before
4811 the base subclasses were updated (e.g. a non-str __qualname__
4812 was passed in the type dict). */
4813 PyErr_Clear();
4814 }
4815 Py_XDECREF(key);
4816}
4817
4818static void
4819remove_all_subclasses(PyTypeObject *type, PyObject *bases)
4820{
4821 if (bases) {
4822 Py_ssize_t i;
4823 for (i = 0; i < PyTuple_GET_SIZE(bases); i++) {
4824 PyObject *base = PyTuple_GET_ITEM(bases, i);
4825 if (PyType_Check(base))
4826 remove_subclass((PyTypeObject*) base, type);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004827 }
4828 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +00004829}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004830
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004831static int
4832check_num_args(PyObject *ob, int n)
4833{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004834 if (!PyTuple_CheckExact(ob)) {
4835 PyErr_SetString(PyExc_SystemError,
4836 "PyArg_UnpackTuple() argument list is not a tuple");
4837 return 0;
4838 }
4839 if (n == PyTuple_GET_SIZE(ob))
4840 return 1;
4841 PyErr_Format(
4842 PyExc_TypeError,
4843 "expected %d arguments, got %zd", n, PyTuple_GET_SIZE(ob));
4844 return 0;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004845}
4846
Tim Peters6d6c1a32001-08-02 04:15:00 +00004847/* Generic wrappers for overloadable 'operators' such as __getitem__ */
4848
4849/* There's a wrapper *function* for each distinct function typedef used
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004850 for type object slots (e.g. binaryfunc, ternaryfunc, etc.). There's a
Tim Peters6d6c1a32001-08-02 04:15:00 +00004851 wrapper *table* for each distinct operation (e.g. __len__, __add__).
4852 Most tables have only one entry; the tables for binary operators have two
4853 entries, one regular and one with reversed arguments. */
4854
4855static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00004856wrap_lenfunc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004857{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004858 lenfunc func = (lenfunc)wrapped;
4859 Py_ssize_t res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004860
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004861 if (!check_num_args(args, 0))
4862 return NULL;
4863 res = (*func)(self);
4864 if (res == -1 && PyErr_Occurred())
4865 return NULL;
4866 return PyLong_FromLong((long)res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004867}
4868
Tim Peters6d6c1a32001-08-02 04:15:00 +00004869static PyObject *
Raymond Hettingerf34f2642003-10-11 17:29:04 +00004870wrap_inquirypred(PyObject *self, PyObject *args, void *wrapped)
4871{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004872 inquiry func = (inquiry)wrapped;
4873 int res;
Raymond Hettingerf34f2642003-10-11 17:29:04 +00004874
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004875 if (!check_num_args(args, 0))
4876 return NULL;
4877 res = (*func)(self);
4878 if (res == -1 && PyErr_Occurred())
4879 return NULL;
4880 return PyBool_FromLong((long)res);
Raymond Hettingerf34f2642003-10-11 17:29:04 +00004881}
4882
4883static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00004884wrap_binaryfunc(PyObject *self, PyObject *args, void *wrapped)
4885{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004886 binaryfunc func = (binaryfunc)wrapped;
4887 PyObject *other;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004888
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004889 if (!check_num_args(args, 1))
4890 return NULL;
4891 other = PyTuple_GET_ITEM(args, 0);
4892 return (*func)(self, other);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004893}
4894
4895static PyObject *
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00004896wrap_binaryfunc_l(PyObject *self, PyObject *args, void *wrapped)
4897{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004898 binaryfunc func = (binaryfunc)wrapped;
4899 PyObject *other;
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00004900
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004901 if (!check_num_args(args, 1))
4902 return NULL;
4903 other = PyTuple_GET_ITEM(args, 0);
4904 return (*func)(self, other);
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00004905}
4906
4907static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00004908wrap_binaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
4909{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004910 binaryfunc func = (binaryfunc)wrapped;
4911 PyObject *other;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004912
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004913 if (!check_num_args(args, 1))
4914 return NULL;
4915 other = PyTuple_GET_ITEM(args, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004916 return (*func)(other, self);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004917}
4918
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004919static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00004920wrap_ternaryfunc(PyObject *self, PyObject *args, void *wrapped)
4921{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004922 ternaryfunc func = (ternaryfunc)wrapped;
4923 PyObject *other;
4924 PyObject *third = Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004925
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004926 /* Note: This wrapper only works for __pow__() */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004927
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004928 if (!PyArg_UnpackTuple(args, "", 1, 2, &other, &third))
4929 return NULL;
4930 return (*func)(self, other, third);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004931}
4932
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00004933static PyObject *
4934wrap_ternaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
4935{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004936 ternaryfunc func = (ternaryfunc)wrapped;
4937 PyObject *other;
4938 PyObject *third = Py_None;
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00004939
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004940 /* Note: This wrapper only works for __pow__() */
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00004941
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004942 if (!PyArg_UnpackTuple(args, "", 1, 2, &other, &third))
4943 return NULL;
4944 return (*func)(other, self, third);
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00004945}
4946
Tim Peters6d6c1a32001-08-02 04:15:00 +00004947static PyObject *
4948wrap_unaryfunc(PyObject *self, PyObject *args, void *wrapped)
4949{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004950 unaryfunc func = (unaryfunc)wrapped;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004951
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004952 if (!check_num_args(args, 0))
4953 return NULL;
4954 return (*func)(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004955}
4956
Tim Peters6d6c1a32001-08-02 04:15:00 +00004957static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004958wrap_indexargfunc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004959{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004960 ssizeargfunc func = (ssizeargfunc)wrapped;
4961 PyObject* o;
4962 Py_ssize_t i;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004963
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004964 if (!PyArg_UnpackTuple(args, "", 1, 1, &o))
4965 return NULL;
4966 i = PyNumber_AsSsize_t(o, PyExc_OverflowError);
4967 if (i == -1 && PyErr_Occurred())
4968 return NULL;
4969 return (*func)(self, i);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004970}
4971
Martin v. Löwis18e16552006-02-15 17:27:45 +00004972static Py_ssize_t
Guido van Rossum5d815f32001-08-17 21:57:47 +00004973getindex(PyObject *self, PyObject *arg)
4974{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004975 Py_ssize_t i;
Guido van Rossum5d815f32001-08-17 21:57:47 +00004976
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004977 i = PyNumber_AsSsize_t(arg, PyExc_OverflowError);
4978 if (i == -1 && PyErr_Occurred())
4979 return -1;
4980 if (i < 0) {
4981 PySequenceMethods *sq = Py_TYPE(self)->tp_as_sequence;
4982 if (sq && sq->sq_length) {
4983 Py_ssize_t n = (*sq->sq_length)(self);
4984 if (n < 0)
4985 return -1;
4986 i += n;
4987 }
4988 }
4989 return i;
Guido van Rossum5d815f32001-08-17 21:57:47 +00004990}
4991
4992static PyObject *
4993wrap_sq_item(PyObject *self, PyObject *args, void *wrapped)
4994{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004995 ssizeargfunc func = (ssizeargfunc)wrapped;
4996 PyObject *arg;
4997 Py_ssize_t i;
Guido van Rossum5d815f32001-08-17 21:57:47 +00004998
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004999 if (PyTuple_GET_SIZE(args) == 1) {
5000 arg = PyTuple_GET_ITEM(args, 0);
5001 i = getindex(self, arg);
5002 if (i == -1 && PyErr_Occurred())
5003 return NULL;
5004 return (*func)(self, i);
5005 }
5006 check_num_args(args, 1);
5007 assert(PyErr_Occurred());
5008 return NULL;
Guido van Rossum5d815f32001-08-17 21:57:47 +00005009}
5010
Tim Peters6d6c1a32001-08-02 04:15:00 +00005011static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00005012wrap_sq_setitem(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005013{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005014 ssizeobjargproc func = (ssizeobjargproc)wrapped;
5015 Py_ssize_t i;
5016 int res;
5017 PyObject *arg, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005018
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005019 if (!PyArg_UnpackTuple(args, "", 2, 2, &arg, &value))
5020 return NULL;
5021 i = getindex(self, arg);
5022 if (i == -1 && PyErr_Occurred())
5023 return NULL;
5024 res = (*func)(self, i, value);
5025 if (res == -1 && PyErr_Occurred())
5026 return NULL;
5027 Py_INCREF(Py_None);
5028 return Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005029}
5030
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00005031static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00005032wrap_sq_delitem(PyObject *self, PyObject *args, void *wrapped)
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00005033{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005034 ssizeobjargproc func = (ssizeobjargproc)wrapped;
5035 Py_ssize_t i;
5036 int res;
5037 PyObject *arg;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00005038
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005039 if (!check_num_args(args, 1))
5040 return NULL;
5041 arg = PyTuple_GET_ITEM(args, 0);
5042 i = getindex(self, arg);
5043 if (i == -1 && PyErr_Occurred())
5044 return NULL;
5045 res = (*func)(self, i, NULL);
5046 if (res == -1 && PyErr_Occurred())
5047 return NULL;
5048 Py_INCREF(Py_None);
5049 return Py_None;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00005050}
5051
Tim Peters6d6c1a32001-08-02 04:15:00 +00005052/* XXX objobjproc is a misnomer; should be objargpred */
5053static PyObject *
5054wrap_objobjproc(PyObject *self, PyObject *args, void *wrapped)
5055{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005056 objobjproc func = (objobjproc)wrapped;
5057 int res;
5058 PyObject *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005059
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005060 if (!check_num_args(args, 1))
5061 return NULL;
5062 value = PyTuple_GET_ITEM(args, 0);
5063 res = (*func)(self, value);
5064 if (res == -1 && PyErr_Occurred())
5065 return NULL;
5066 else
5067 return PyBool_FromLong(res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005068}
5069
Tim Peters6d6c1a32001-08-02 04:15:00 +00005070static PyObject *
5071wrap_objobjargproc(PyObject *self, PyObject *args, void *wrapped)
5072{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005073 objobjargproc func = (objobjargproc)wrapped;
5074 int res;
5075 PyObject *key, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005076
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005077 if (!PyArg_UnpackTuple(args, "", 2, 2, &key, &value))
5078 return NULL;
5079 res = (*func)(self, key, value);
5080 if (res == -1 && PyErr_Occurred())
5081 return NULL;
5082 Py_INCREF(Py_None);
5083 return Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005084}
5085
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00005086static PyObject *
5087wrap_delitem(PyObject *self, PyObject *args, void *wrapped)
5088{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005089 objobjargproc func = (objobjargproc)wrapped;
5090 int res;
5091 PyObject *key;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00005092
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005093 if (!check_num_args(args, 1))
5094 return NULL;
5095 key = PyTuple_GET_ITEM(args, 0);
5096 res = (*func)(self, key, NULL);
5097 if (res == -1 && PyErr_Occurred())
5098 return NULL;
5099 Py_INCREF(Py_None);
5100 return Py_None;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00005101}
5102
Guido van Rossum4dcdb782003-04-14 21:46:03 +00005103/* Helper to check for object.__setattr__ or __delattr__ applied to a type.
Guido van Rossum52b27052003-04-15 20:05:10 +00005104 This is called the Carlo Verre hack after its discoverer. */
Guido van Rossum4dcdb782003-04-14 21:46:03 +00005105static int
5106hackcheck(PyObject *self, setattrofunc func, char *what)
5107{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005108 PyTypeObject *type = Py_TYPE(self);
5109 while (type && type->tp_flags & Py_TPFLAGS_HEAPTYPE)
5110 type = type->tp_base;
5111 /* If type is NULL now, this is a really weird type.
5112 In the spirit of backwards compatibility (?), just shut up. */
5113 if (type && type->tp_setattro != func) {
5114 PyErr_Format(PyExc_TypeError,
5115 "can't apply this %s to %s object",
5116 what,
5117 type->tp_name);
5118 return 0;
5119 }
5120 return 1;
Guido van Rossum4dcdb782003-04-14 21:46:03 +00005121}
5122
Tim Peters6d6c1a32001-08-02 04:15:00 +00005123static PyObject *
5124wrap_setattr(PyObject *self, PyObject *args, void *wrapped)
5125{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005126 setattrofunc func = (setattrofunc)wrapped;
5127 int res;
5128 PyObject *name, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005129
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005130 if (!PyArg_UnpackTuple(args, "", 2, 2, &name, &value))
5131 return NULL;
5132 if (!hackcheck(self, func, "__setattr__"))
5133 return NULL;
5134 res = (*func)(self, name, value);
5135 if (res < 0)
5136 return NULL;
5137 Py_INCREF(Py_None);
5138 return Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005139}
5140
5141static PyObject *
5142wrap_delattr(PyObject *self, PyObject *args, void *wrapped)
5143{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005144 setattrofunc func = (setattrofunc)wrapped;
5145 int res;
5146 PyObject *name;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005147
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005148 if (!check_num_args(args, 1))
5149 return NULL;
5150 name = PyTuple_GET_ITEM(args, 0);
5151 if (!hackcheck(self, func, "__delattr__"))
5152 return NULL;
5153 res = (*func)(self, name, NULL);
5154 if (res < 0)
5155 return NULL;
5156 Py_INCREF(Py_None);
5157 return Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005158}
5159
Tim Peters6d6c1a32001-08-02 04:15:00 +00005160static PyObject *
5161wrap_hashfunc(PyObject *self, PyObject *args, void *wrapped)
5162{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005163 hashfunc func = (hashfunc)wrapped;
Benjamin Peterson8035bc52010-10-23 16:20:50 +00005164 Py_hash_t res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005165
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005166 if (!check_num_args(args, 0))
5167 return NULL;
5168 res = (*func)(self);
5169 if (res == -1 && PyErr_Occurred())
5170 return NULL;
Benjamin Peterson8035bc52010-10-23 16:20:50 +00005171 return PyLong_FromSsize_t(res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005172}
5173
Tim Peters6d6c1a32001-08-02 04:15:00 +00005174static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00005175wrap_call(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005176{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005177 ternaryfunc func = (ternaryfunc)wrapped;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005178
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005179 return (*func)(self, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005180}
5181
Tim Peters6d6c1a32001-08-02 04:15:00 +00005182static PyObject *
Antoine Pitrou796564c2013-07-30 19:59:21 +02005183wrap_del(PyObject *self, PyObject *args, void *wrapped)
5184{
5185 destructor func = (destructor)wrapped;
5186
5187 if (!check_num_args(args, 0))
5188 return NULL;
5189
5190 (*func)(self);
5191 Py_RETURN_NONE;
5192}
5193
5194static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00005195wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op)
5196{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005197 richcmpfunc func = (richcmpfunc)wrapped;
5198 PyObject *other;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005199
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005200 if (!check_num_args(args, 1))
5201 return NULL;
5202 other = PyTuple_GET_ITEM(args, 0);
5203 return (*func)(self, other, op);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005204}
5205
5206#undef RICHCMP_WRAPPER
5207#define RICHCMP_WRAPPER(NAME, OP) \
5208static PyObject * \
5209richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \
5210{ \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005211 return wrap_richcmpfunc(self, args, wrapped, OP); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00005212}
5213
Jack Jansen8e938b42001-08-08 15:29:49 +00005214RICHCMP_WRAPPER(lt, Py_LT)
5215RICHCMP_WRAPPER(le, Py_LE)
5216RICHCMP_WRAPPER(eq, Py_EQ)
5217RICHCMP_WRAPPER(ne, Py_NE)
5218RICHCMP_WRAPPER(gt, Py_GT)
5219RICHCMP_WRAPPER(ge, Py_GE)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005220
Tim Peters6d6c1a32001-08-02 04:15:00 +00005221static PyObject *
5222wrap_next(PyObject *self, PyObject *args, void *wrapped)
5223{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005224 unaryfunc func = (unaryfunc)wrapped;
5225 PyObject *res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005226
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005227 if (!check_num_args(args, 0))
5228 return NULL;
5229 res = (*func)(self);
5230 if (res == NULL && !PyErr_Occurred())
5231 PyErr_SetNone(PyExc_StopIteration);
5232 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005233}
5234
Tim Peters6d6c1a32001-08-02 04:15:00 +00005235static PyObject *
5236wrap_descr_get(PyObject *self, PyObject *args, void *wrapped)
5237{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005238 descrgetfunc func = (descrgetfunc)wrapped;
5239 PyObject *obj;
5240 PyObject *type = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005241
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005242 if (!PyArg_UnpackTuple(args, "", 1, 2, &obj, &type))
5243 return NULL;
5244 if (obj == Py_None)
5245 obj = NULL;
5246 if (type == Py_None)
5247 type = NULL;
5248 if (type == NULL &&obj == NULL) {
5249 PyErr_SetString(PyExc_TypeError,
5250 "__get__(None, None) is invalid");
5251 return NULL;
5252 }
5253 return (*func)(self, obj, type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005254}
5255
Tim Peters6d6c1a32001-08-02 04:15:00 +00005256static PyObject *
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005257wrap_descr_set(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005258{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005259 descrsetfunc func = (descrsetfunc)wrapped;
5260 PyObject *obj, *value;
5261 int ret;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005262
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005263 if (!PyArg_UnpackTuple(args, "", 2, 2, &obj, &value))
5264 return NULL;
5265 ret = (*func)(self, obj, value);
5266 if (ret < 0)
5267 return NULL;
5268 Py_INCREF(Py_None);
5269 return Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005270}
Guido van Rossum22b13872002-08-06 21:41:44 +00005271
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00005272static PyObject *
5273wrap_descr_delete(PyObject *self, PyObject *args, void *wrapped)
5274{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005275 descrsetfunc func = (descrsetfunc)wrapped;
5276 PyObject *obj;
5277 int ret;
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00005278
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005279 if (!check_num_args(args, 1))
5280 return NULL;
5281 obj = PyTuple_GET_ITEM(args, 0);
5282 ret = (*func)(self, obj, NULL);
5283 if (ret < 0)
5284 return NULL;
5285 Py_INCREF(Py_None);
5286 return Py_None;
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00005287}
Tim Peters6d6c1a32001-08-02 04:15:00 +00005288
Tim Peters6d6c1a32001-08-02 04:15:00 +00005289static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00005290wrap_init(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005291{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005292 initproc func = (initproc)wrapped;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005293
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005294 if (func(self, args, kwds) < 0)
5295 return NULL;
5296 Py_INCREF(Py_None);
5297 return Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005298}
5299
Tim Peters6d6c1a32001-08-02 04:15:00 +00005300static PyObject *
Guido van Rossum0d231ed2001-08-06 16:50:37 +00005301tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005302{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005303 PyTypeObject *type, *subtype, *staticbase;
5304 PyObject *arg0, *res;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00005305
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005306 if (self == NULL || !PyType_Check(self))
5307 Py_FatalError("__new__() called with non-type 'self'");
5308 type = (PyTypeObject *)self;
5309 if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) {
5310 PyErr_Format(PyExc_TypeError,
5311 "%s.__new__(): not enough arguments",
5312 type->tp_name);
5313 return NULL;
5314 }
5315 arg0 = PyTuple_GET_ITEM(args, 0);
5316 if (!PyType_Check(arg0)) {
5317 PyErr_Format(PyExc_TypeError,
5318 "%s.__new__(X): X is not a type object (%s)",
5319 type->tp_name,
5320 Py_TYPE(arg0)->tp_name);
5321 return NULL;
5322 }
5323 subtype = (PyTypeObject *)arg0;
5324 if (!PyType_IsSubtype(subtype, type)) {
5325 PyErr_Format(PyExc_TypeError,
5326 "%s.__new__(%s): %s is not a subtype of %s",
5327 type->tp_name,
5328 subtype->tp_name,
5329 subtype->tp_name,
5330 type->tp_name);
5331 return NULL;
5332 }
Barry Warsaw60f01882001-08-22 19:24:42 +00005333
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005334 /* Check that the use doesn't do something silly and unsafe like
5335 object.__new__(dict). To do this, we check that the
5336 most derived base that's not a heap type is this type. */
5337 staticbase = subtype;
Martin v. Löwis9c564092012-06-23 23:20:45 +02005338 while (staticbase && (staticbase->tp_new == slot_tp_new))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005339 staticbase = staticbase->tp_base;
5340 /* If staticbase is NULL now, it is a really weird type.
5341 In the spirit of backwards compatibility (?), just shut up. */
5342 if (staticbase && staticbase->tp_new != type->tp_new) {
5343 PyErr_Format(PyExc_TypeError,
5344 "%s.__new__(%s) is not safe, use %s.__new__()",
5345 type->tp_name,
5346 subtype->tp_name,
5347 staticbase == NULL ? "?" : staticbase->tp_name);
5348 return NULL;
5349 }
Barry Warsaw60f01882001-08-22 19:24:42 +00005350
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005351 args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
5352 if (args == NULL)
5353 return NULL;
5354 res = type->tp_new(subtype, args, kwds);
5355 Py_DECREF(args);
5356 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005357}
5358
Guido van Rossum0d231ed2001-08-06 16:50:37 +00005359static struct PyMethodDef tp_new_methoddef[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005360 {"__new__", (PyCFunction)tp_new_wrapper, METH_VARARGS|METH_KEYWORDS,
Larry Hastings2623c8c2014-02-08 22:15:29 -08005361 PyDoc_STR("__new__($type, *args, **kwargs)\n--\n\n"
Larry Hastings581ee362014-01-28 05:00:08 -08005362 "Create and return a new object. "
5363 "See help(type) for accurate signature.")},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005364 {0}
Tim Peters6d6c1a32001-08-02 04:15:00 +00005365};
5366
5367static int
Guido van Rossum0d231ed2001-08-06 16:50:37 +00005368add_tp_new_wrapper(PyTypeObject *type)
5369{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005370 PyObject *func;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00005371
Victor Stinner3c1e4812012-03-26 22:10:51 +02005372 if (_PyDict_GetItemId(type->tp_dict, &PyId___new__) != NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005373 return 0;
Andrew Svetlov3ba3a3e2012-12-25 13:32:35 +02005374 func = PyCFunction_NewEx(tp_new_methoddef, (PyObject *)type, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005375 if (func == NULL)
5376 return -1;
Victor Stinner3c1e4812012-03-26 22:10:51 +02005377 if (_PyDict_SetItemId(type->tp_dict, &PyId___new__, func)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005378 Py_DECREF(func);
5379 return -1;
5380 }
5381 Py_DECREF(func);
5382 return 0;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00005383}
5384
Guido van Rossumf040ede2001-08-07 16:40:56 +00005385/* Slot wrappers that call the corresponding __foo__ slot. See comments
5386 below at override_slots() for more explanation. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00005387
Guido van Rossumdc91b992001-08-08 22:26:22 +00005388#define SLOT0(FUNCNAME, OPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00005389static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00005390FUNCNAME(PyObject *self) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00005391{ \
Benjamin Petersonce798522012-01-22 11:24:29 -05005392 _Py_static_string(id, OPSTR); \
5393 return call_method(self, &id, "()"); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00005394}
5395
Guido van Rossumdc91b992001-08-08 22:26:22 +00005396#define SLOT1(FUNCNAME, OPSTR, ARG1TYPE, ARGCODES) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00005397static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00005398FUNCNAME(PyObject *self, ARG1TYPE arg1) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00005399{ \
Benjamin Petersonce798522012-01-22 11:24:29 -05005400 _Py_static_string(id, OPSTR); \
5401 return call_method(self, &id, "(" ARGCODES ")", arg1); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00005402}
5403
Guido van Rossumcd118802003-01-06 22:57:47 +00005404/* Boolean helper for SLOT1BINFULL().
5405 right.__class__ is a nontrivial subclass of left.__class__. */
5406static int
Victor Stinner3c1e4812012-03-26 22:10:51 +02005407method_is_overloaded(PyObject *left, PyObject *right, struct _Py_Identifier *name)
Guido van Rossumcd118802003-01-06 22:57:47 +00005408{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005409 PyObject *a, *b;
5410 int ok;
Guido van Rossumcd118802003-01-06 22:57:47 +00005411
Victor Stinner3c1e4812012-03-26 22:10:51 +02005412 b = _PyObject_GetAttrId((PyObject *)(Py_TYPE(right)), name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005413 if (b == NULL) {
5414 PyErr_Clear();
5415 /* If right doesn't have it, it's not overloaded */
5416 return 0;
5417 }
Guido van Rossumcd118802003-01-06 22:57:47 +00005418
Victor Stinner3c1e4812012-03-26 22:10:51 +02005419 a = _PyObject_GetAttrId((PyObject *)(Py_TYPE(left)), name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005420 if (a == NULL) {
5421 PyErr_Clear();
5422 Py_DECREF(b);
5423 /* If right has it but left doesn't, it's overloaded */
5424 return 1;
5425 }
Guido van Rossumcd118802003-01-06 22:57:47 +00005426
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005427 ok = PyObject_RichCompareBool(a, b, Py_NE);
5428 Py_DECREF(a);
5429 Py_DECREF(b);
5430 if (ok < 0) {
5431 PyErr_Clear();
5432 return 0;
5433 }
Guido van Rossumcd118802003-01-06 22:57:47 +00005434
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005435 return ok;
Guido van Rossumcd118802003-01-06 22:57:47 +00005436}
5437
Guido van Rossumdc91b992001-08-08 22:26:22 +00005438
5439#define SLOT1BINFULL(FUNCNAME, TESTFUNC, SLOTNAME, OPSTR, ROPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00005440static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00005441FUNCNAME(PyObject *self, PyObject *other) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00005442{ \
Benjamin Petersonce798522012-01-22 11:24:29 -05005443 _Py_static_string(op_id, OPSTR); \
5444 _Py_static_string(rop_id, ROPSTR); \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005445 int do_other = Py_TYPE(self) != Py_TYPE(other) && \
5446 Py_TYPE(other)->tp_as_number != NULL && \
5447 Py_TYPE(other)->tp_as_number->SLOTNAME == TESTFUNC; \
5448 if (Py_TYPE(self)->tp_as_number != NULL && \
5449 Py_TYPE(self)->tp_as_number->SLOTNAME == TESTFUNC) { \
5450 PyObject *r; \
5451 if (do_other && \
5452 PyType_IsSubtype(Py_TYPE(other), Py_TYPE(self)) && \
Victor Stinner3c1e4812012-03-26 22:10:51 +02005453 method_is_overloaded(self, other, &rop_id)) { \
Benjamin Petersonce798522012-01-22 11:24:29 -05005454 r = call_maybe(other, &rop_id, "(O)", self); \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005455 if (r != Py_NotImplemented) \
5456 return r; \
5457 Py_DECREF(r); \
5458 do_other = 0; \
5459 } \
Benjamin Petersonce798522012-01-22 11:24:29 -05005460 r = call_maybe(self, &op_id, "(O)", other); \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005461 if (r != Py_NotImplemented || \
5462 Py_TYPE(other) == Py_TYPE(self)) \
5463 return r; \
5464 Py_DECREF(r); \
5465 } \
5466 if (do_other) { \
Benjamin Petersonce798522012-01-22 11:24:29 -05005467 return call_maybe(other, &rop_id, "(O)", self); \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005468 } \
Brian Curtindfc80e32011-08-10 20:28:54 -05005469 Py_RETURN_NOTIMPLEMENTED; \
Guido van Rossumdc91b992001-08-08 22:26:22 +00005470}
5471
5472#define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005473 SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR)
Guido van Rossumdc91b992001-08-08 22:26:22 +00005474
5475#define SLOT2(FUNCNAME, OPSTR, ARG1TYPE, ARG2TYPE, ARGCODES) \
5476static PyObject * \
5477FUNCNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \
5478{ \
Benjamin Petersonce798522012-01-22 11:24:29 -05005479 _Py_static_string(id, #OPSTR); \
5480 return call_method(self, &id, "(" ARGCODES ")", arg1, arg2); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00005481}
5482
Martin v. Löwis18e16552006-02-15 17:27:45 +00005483static Py_ssize_t
Tim Peters6d6c1a32001-08-02 04:15:00 +00005484slot_sq_length(PyObject *self)
5485{
Benjamin Petersonce798522012-01-22 11:24:29 -05005486 PyObject *res = call_method(self, &PyId___len__, "()");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005487 Py_ssize_t len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005488
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005489 if (res == NULL)
5490 return -1;
5491 len = PyNumber_AsSsize_t(res, PyExc_OverflowError);
5492 Py_DECREF(res);
5493 if (len < 0) {
5494 if (!PyErr_Occurred())
5495 PyErr_SetString(PyExc_ValueError,
5496 "__len__() should return >= 0");
5497 return -1;
5498 }
5499 return len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005500}
5501
Guido van Rossumf4593e02001-10-03 12:09:30 +00005502/* Super-optimized version of slot_sq_item.
5503 Other slots could do the same... */
5504static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00005505slot_sq_item(PyObject *self, Py_ssize_t i)
Guido van Rossumf4593e02001-10-03 12:09:30 +00005506{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005507 PyObject *func, *args = NULL, *ival = NULL, *retval = NULL;
5508 descrgetfunc f;
Guido van Rossumf4593e02001-10-03 12:09:30 +00005509
Victor Stinner3c1e4812012-03-26 22:10:51 +02005510 func = _PyType_LookupId(Py_TYPE(self), &PyId___getitem__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005511 if (func != NULL) {
5512 if ((f = Py_TYPE(func)->tp_descr_get) == NULL)
5513 Py_INCREF(func);
5514 else {
5515 func = f(func, self, (PyObject *)(Py_TYPE(self)));
5516 if (func == NULL) {
5517 return NULL;
5518 }
5519 }
5520 ival = PyLong_FromSsize_t(i);
5521 if (ival != NULL) {
5522 args = PyTuple_New(1);
5523 if (args != NULL) {
5524 PyTuple_SET_ITEM(args, 0, ival);
5525 retval = PyObject_Call(func, args, NULL);
5526 Py_XDECREF(args);
5527 Py_XDECREF(func);
5528 return retval;
5529 }
5530 }
5531 }
5532 else {
Victor Stinner3c1e4812012-03-26 22:10:51 +02005533 PyObject *getitem_str = _PyUnicode_FromId(&PyId___getitem__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005534 PyErr_SetObject(PyExc_AttributeError, getitem_str);
5535 }
5536 Py_XDECREF(args);
5537 Py_XDECREF(ival);
5538 Py_XDECREF(func);
5539 return NULL;
Guido van Rossumf4593e02001-10-03 12:09:30 +00005540}
5541
Tim Peters6d6c1a32001-08-02 04:15:00 +00005542static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00005543slot_sq_ass_item(PyObject *self, Py_ssize_t index, PyObject *value)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005544{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005545 PyObject *res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005546
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005547 if (value == NULL)
Benjamin Petersonce798522012-01-22 11:24:29 -05005548 res = call_method(self, &PyId___delitem__, "(n)", index);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005549 else
Benjamin Petersonce798522012-01-22 11:24:29 -05005550 res = call_method(self, &PyId___setitem__, "(nO)", index, value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005551 if (res == NULL)
5552 return -1;
5553 Py_DECREF(res);
5554 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005555}
5556
5557static int
Tim Peters6d6c1a32001-08-02 04:15:00 +00005558slot_sq_contains(PyObject *self, PyObject *value)
5559{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005560 PyObject *func, *res, *args;
5561 int result = -1;
Benjamin Petersonce798522012-01-22 11:24:29 -05005562 _Py_IDENTIFIER(__contains__);
Tim Petersbf9b2442003-03-23 05:35:36 +00005563
Benjamin Petersonce798522012-01-22 11:24:29 -05005564 func = lookup_maybe(self, &PyId___contains__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005565 if (func != NULL) {
5566 args = PyTuple_Pack(1, value);
5567 if (args == NULL)
5568 res = NULL;
5569 else {
5570 res = PyObject_Call(func, args, NULL);
5571 Py_DECREF(args);
5572 }
5573 Py_DECREF(func);
5574 if (res != NULL) {
5575 result = PyObject_IsTrue(res);
5576 Py_DECREF(res);
5577 }
5578 }
5579 else if (! PyErr_Occurred()) {
5580 /* Possible results: -1 and 1 */
5581 result = (int)_PySequence_IterSearch(self, value,
5582 PY_ITERSEARCH_CONTAINS);
5583 }
5584 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005585}
5586
Tim Peters6d6c1a32001-08-02 04:15:00 +00005587#define slot_mp_length slot_sq_length
5588
Guido van Rossumdc91b992001-08-08 22:26:22 +00005589SLOT1(slot_mp_subscript, "__getitem__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00005590
5591static int
5592slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value)
5593{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005594 PyObject *res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005595
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005596 if (value == NULL)
Benjamin Petersonce798522012-01-22 11:24:29 -05005597 res = call_method(self, &PyId___delitem__, "(O)", key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005598 else
Benjamin Petersonce798522012-01-22 11:24:29 -05005599 res = call_method(self, &PyId___setitem__, "(OO)", key, value);
5600
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005601 if (res == NULL)
5602 return -1;
5603 Py_DECREF(res);
5604 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005605}
5606
Guido van Rossumdc91b992001-08-08 22:26:22 +00005607SLOT1BIN(slot_nb_add, nb_add, "__add__", "__radd__")
5608SLOT1BIN(slot_nb_subtract, nb_subtract, "__sub__", "__rsub__")
5609SLOT1BIN(slot_nb_multiply, nb_multiply, "__mul__", "__rmul__")
Benjamin Petersond51374e2014-04-09 23:55:56 -04005610SLOT1BIN(slot_nb_matrix_multiply, nb_matrix_multiply, "__matmul__", "__rmatmul__")
Guido van Rossumdc91b992001-08-08 22:26:22 +00005611SLOT1BIN(slot_nb_remainder, nb_remainder, "__mod__", "__rmod__")
5612SLOT1BIN(slot_nb_divmod, nb_divmod, "__divmod__", "__rdivmod__")
5613
Jeremy Hylton938ace62002-07-17 16:30:39 +00005614static PyObject *slot_nb_power(PyObject *, PyObject *, PyObject *);
Guido van Rossumdc91b992001-08-08 22:26:22 +00005615
5616SLOT1BINFULL(slot_nb_power_binary, slot_nb_power,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005617 nb_power, "__pow__", "__rpow__")
Guido van Rossumdc91b992001-08-08 22:26:22 +00005618
5619static PyObject *
5620slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus)
5621{
Benjamin Petersonce798522012-01-22 11:24:29 -05005622 _Py_IDENTIFIER(__pow__);
Guido van Rossum2730b132001-08-28 18:22:14 +00005623
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005624 if (modulus == Py_None)
5625 return slot_nb_power_binary(self, other);
5626 /* Three-arg power doesn't use __rpow__. But ternary_op
5627 can call this when the second argument's type uses
5628 slot_nb_power, so check before calling self.__pow__. */
5629 if (Py_TYPE(self)->tp_as_number != NULL &&
5630 Py_TYPE(self)->tp_as_number->nb_power == slot_nb_power) {
Benjamin Petersonce798522012-01-22 11:24:29 -05005631 return call_method(self, &PyId___pow__, "(OO)", other, modulus);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005632 }
Brian Curtindfc80e32011-08-10 20:28:54 -05005633 Py_RETURN_NOTIMPLEMENTED;
Guido van Rossumdc91b992001-08-08 22:26:22 +00005634}
5635
5636SLOT0(slot_nb_negative, "__neg__")
5637SLOT0(slot_nb_positive, "__pos__")
5638SLOT0(slot_nb_absolute, "__abs__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00005639
5640static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00005641slot_nb_bool(PyObject *self)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005642{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005643 PyObject *func, *args;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005644 int result = -1;
5645 int using_len = 0;
Benjamin Petersonce798522012-01-22 11:24:29 -05005646 _Py_IDENTIFIER(__bool__);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005647
Benjamin Petersonce798522012-01-22 11:24:29 -05005648 func = lookup_maybe(self, &PyId___bool__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005649 if (func == NULL) {
5650 if (PyErr_Occurred())
5651 return -1;
Benjamin Petersonce798522012-01-22 11:24:29 -05005652 func = lookup_maybe(self, &PyId___len__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005653 if (func == NULL)
5654 return PyErr_Occurred() ? -1 : 1;
5655 using_len = 1;
5656 }
5657 args = PyTuple_New(0);
5658 if (args != NULL) {
5659 PyObject *temp = PyObject_Call(func, args, NULL);
5660 Py_DECREF(args);
5661 if (temp != NULL) {
5662 if (using_len) {
5663 /* enforced by slot_nb_len */
5664 result = PyObject_IsTrue(temp);
5665 }
5666 else if (PyBool_Check(temp)) {
5667 result = PyObject_IsTrue(temp);
5668 }
5669 else {
5670 PyErr_Format(PyExc_TypeError,
5671 "__bool__ should return "
5672 "bool, returned %s",
5673 Py_TYPE(temp)->tp_name);
5674 result = -1;
5675 }
5676 Py_DECREF(temp);
5677 }
5678 }
5679 Py_DECREF(func);
5680 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005681}
5682
Guido van Rossum38fff8c2006-03-07 18:50:55 +00005683
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00005684static PyObject *
Guido van Rossum38fff8c2006-03-07 18:50:55 +00005685slot_nb_index(PyObject *self)
5686{
Benjamin Petersonce798522012-01-22 11:24:29 -05005687 _Py_IDENTIFIER(__index__);
5688 return call_method(self, &PyId___index__, "()");
Guido van Rossum38fff8c2006-03-07 18:50:55 +00005689}
5690
5691
Guido van Rossumdc91b992001-08-08 22:26:22 +00005692SLOT0(slot_nb_invert, "__invert__")
5693SLOT1BIN(slot_nb_lshift, nb_lshift, "__lshift__", "__rlshift__")
5694SLOT1BIN(slot_nb_rshift, nb_rshift, "__rshift__", "__rrshift__")
5695SLOT1BIN(slot_nb_and, nb_and, "__and__", "__rand__")
5696SLOT1BIN(slot_nb_xor, nb_xor, "__xor__", "__rxor__")
5697SLOT1BIN(slot_nb_or, nb_or, "__or__", "__ror__")
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00005698
Guido van Rossumdc91b992001-08-08 22:26:22 +00005699SLOT0(slot_nb_int, "__int__")
Guido van Rossumdc91b992001-08-08 22:26:22 +00005700SLOT0(slot_nb_float, "__float__")
Guido van Rossumdc91b992001-08-08 22:26:22 +00005701SLOT1(slot_nb_inplace_add, "__iadd__", PyObject *, "O")
5702SLOT1(slot_nb_inplace_subtract, "__isub__", PyObject *, "O")
5703SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *, "O")
Benjamin Petersond51374e2014-04-09 23:55:56 -04005704SLOT1(slot_nb_inplace_matrix_multiply, "__imatmul__", PyObject *, "O")
Guido van Rossumdc91b992001-08-08 22:26:22 +00005705SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *, "O")
Thomas Wouterscf297e42007-02-23 15:07:44 +00005706/* Can't use SLOT1 here, because nb_inplace_power is ternary */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005707static PyObject *
5708slot_nb_inplace_power(PyObject *self, PyObject * arg1, PyObject *arg2)
5709{
Benjamin Petersonce798522012-01-22 11:24:29 -05005710 _Py_IDENTIFIER(__ipow__);
5711 return call_method(self, &PyId___ipow__, "(" "O" ")", arg1);
Thomas Wouterscf297e42007-02-23 15:07:44 +00005712}
Guido van Rossumdc91b992001-08-08 22:26:22 +00005713SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *, "O")
5714SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *, "O")
5715SLOT1(slot_nb_inplace_and, "__iand__", PyObject *, "O")
5716SLOT1(slot_nb_inplace_xor, "__ixor__", PyObject *, "O")
5717SLOT1(slot_nb_inplace_or, "__ior__", PyObject *, "O")
5718SLOT1BIN(slot_nb_floor_divide, nb_floor_divide,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005719 "__floordiv__", "__rfloordiv__")
Guido van Rossumdc91b992001-08-08 22:26:22 +00005720SLOT1BIN(slot_nb_true_divide, nb_true_divide, "__truediv__", "__rtruediv__")
5721SLOT1(slot_nb_inplace_floor_divide, "__ifloordiv__", PyObject *, "O")
5722SLOT1(slot_nb_inplace_true_divide, "__itruediv__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00005723
Guido van Rossumb8f63662001-08-15 23:57:02 +00005724static PyObject *
5725slot_tp_repr(PyObject *self)
5726{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005727 PyObject *func, *res;
Benjamin Petersonce798522012-01-22 11:24:29 -05005728 _Py_IDENTIFIER(__repr__);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005729
Benjamin Petersonce798522012-01-22 11:24:29 -05005730 func = lookup_method(self, &PyId___repr__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005731 if (func != NULL) {
5732 res = PyEval_CallObject(func, NULL);
5733 Py_DECREF(func);
5734 return res;
5735 }
5736 PyErr_Clear();
5737 return PyUnicode_FromFormat("<%s object at %p>",
5738 Py_TYPE(self)->tp_name, self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005739}
5740
5741static PyObject *
5742slot_tp_str(PyObject *self)
5743{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005744 PyObject *func, *res;
Benjamin Petersonce798522012-01-22 11:24:29 -05005745 _Py_IDENTIFIER(__str__);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005746
Benjamin Petersonce798522012-01-22 11:24:29 -05005747 func = lookup_method(self, &PyId___str__);
Victor Stinner2e8474d2013-07-11 22:46:11 +02005748 if (func == NULL)
5749 return NULL;
Victor Stinnerbebba502013-10-29 10:56:34 +01005750 res = PyEval_CallObject(func, NULL);
5751 Py_DECREF(func);
5752 return res;
5753}
Tim Peters6d6c1a32001-08-02 04:15:00 +00005754
Benjamin Peterson8f67d082010-10-17 20:54:53 +00005755static Py_hash_t
Tim Peters6d6c1a32001-08-02 04:15:00 +00005756slot_tp_hash(PyObject *self)
5757{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005758 PyObject *func, *res;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00005759 Py_ssize_t h;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005760
Benjamin Petersonce798522012-01-22 11:24:29 -05005761 func = lookup_method(self, &PyId___hash__);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005762
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005763 if (func == Py_None) {
5764 Py_DECREF(func);
5765 func = NULL;
5766 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +00005767
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005768 if (func == NULL) {
5769 return PyObject_HashNotImplemented(self);
5770 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +00005771
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005772 res = PyEval_CallObject(func, NULL);
5773 Py_DECREF(func);
5774 if (res == NULL)
5775 return -1;
Mark Dickinsondc787d22010-05-23 13:33:13 +00005776
5777 if (!PyLong_Check(res)) {
5778 PyErr_SetString(PyExc_TypeError,
5779 "__hash__ method should return an integer");
5780 return -1;
5781 }
Benjamin Peterson8f67d082010-10-17 20:54:53 +00005782 /* Transform the PyLong `res` to a Py_hash_t `h`. For an existing
5783 hashable Python object x, hash(x) will always lie within the range of
5784 Py_hash_t. Therefore our transformation must preserve values that
5785 already lie within this range, to ensure that if x.__hash__() returns
5786 hash(y) then hash(x) == hash(y). */
5787 h = PyLong_AsSsize_t(res);
5788 if (h == -1 && PyErr_Occurred()) {
5789 /* res was not within the range of a Py_hash_t, so we're free to
Mark Dickinsondc787d22010-05-23 13:33:13 +00005790 use any sufficiently bit-mixing transformation;
5791 long.__hash__ will do nicely. */
Benjamin Peterson8f67d082010-10-17 20:54:53 +00005792 PyErr_Clear();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005793 h = PyLong_Type.tp_hash(res);
Benjamin Peterson8f67d082010-10-17 20:54:53 +00005794 }
Benjamin Petersone7dfeeb2010-10-17 21:27:01 +00005795 /* -1 is reserved for errors. */
5796 if (h == -1)
5797 h = -2;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005798 Py_DECREF(res);
Mark Dickinsondc787d22010-05-23 13:33:13 +00005799 return h;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005800}
5801
5802static PyObject *
5803slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds)
5804{
Benjamin Petersonce798522012-01-22 11:24:29 -05005805 _Py_IDENTIFIER(__call__);
5806 PyObject *meth = lookup_method(self, &PyId___call__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005807 PyObject *res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005808
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005809 if (meth == NULL)
5810 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005811
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005812 res = PyObject_Call(meth, args, kwds);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005813
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005814 Py_DECREF(meth);
5815 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005816}
5817
Guido van Rossum14a6f832001-10-17 13:59:09 +00005818/* There are two slot dispatch functions for tp_getattro.
5819
5820 - slot_tp_getattro() is used when __getattribute__ is overridden
5821 but no __getattr__ hook is present;
5822
5823 - slot_tp_getattr_hook() is used when a __getattr__ hook is present.
5824
Guido van Rossumc334df52002-04-04 23:44:47 +00005825 The code in update_one_slot() always installs slot_tp_getattr_hook(); this
5826 detects the absence of __getattr__ and then installs the simpler slot if
5827 necessary. */
Guido van Rossum14a6f832001-10-17 13:59:09 +00005828
Tim Peters6d6c1a32001-08-02 04:15:00 +00005829static PyObject *
5830slot_tp_getattro(PyObject *self, PyObject *name)
5831{
Benjamin Petersonce798522012-01-22 11:24:29 -05005832 return call_method(self, &PyId___getattribute__, "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005833}
5834
Guido van Rossum19c1cd52001-09-21 21:24:49 +00005835static PyObject *
Benjamin Peterson9262b842008-11-17 22:45:50 +00005836call_attribute(PyObject *self, PyObject *attr, PyObject *name)
5837{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005838 PyObject *res, *descr = NULL;
5839 descrgetfunc f = Py_TYPE(attr)->tp_descr_get;
Benjamin Peterson9262b842008-11-17 22:45:50 +00005840
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005841 if (f != NULL) {
5842 descr = f(attr, self, (PyObject *)(Py_TYPE(self)));
5843 if (descr == NULL)
5844 return NULL;
5845 else
5846 attr = descr;
5847 }
5848 res = PyObject_CallFunctionObjArgs(attr, name, NULL);
5849 Py_XDECREF(descr);
5850 return res;
Benjamin Peterson9262b842008-11-17 22:45:50 +00005851}
5852
5853static PyObject *
Guido van Rossum19c1cd52001-09-21 21:24:49 +00005854slot_tp_getattr_hook(PyObject *self, PyObject *name)
5855{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005856 PyTypeObject *tp = Py_TYPE(self);
5857 PyObject *getattr, *getattribute, *res;
Victor Stinner3c1e4812012-03-26 22:10:51 +02005858 _Py_IDENTIFIER(__getattr__);
Guido van Rossum19c1cd52001-09-21 21:24:49 +00005859
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005860 /* speed hack: we could use lookup_maybe, but that would resolve the
5861 method fully for each attribute lookup for classes with
5862 __getattr__, even when the attribute is present. So we use
5863 _PyType_Lookup and create the method only when needed, with
5864 call_attribute. */
Victor Stinner3c1e4812012-03-26 22:10:51 +02005865 getattr = _PyType_LookupId(tp, &PyId___getattr__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005866 if (getattr == NULL) {
5867 /* No __getattr__ hook: use a simpler dispatcher */
5868 tp->tp_getattro = slot_tp_getattro;
5869 return slot_tp_getattro(self, name);
5870 }
5871 Py_INCREF(getattr);
5872 /* speed hack: we could use lookup_maybe, but that would resolve the
5873 method fully for each attribute lookup for classes with
5874 __getattr__, even when self has the default __getattribute__
5875 method. So we use _PyType_Lookup and create the method only when
5876 needed, with call_attribute. */
Victor Stinner3c1e4812012-03-26 22:10:51 +02005877 getattribute = _PyType_LookupId(tp, &PyId___getattribute__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005878 if (getattribute == NULL ||
5879 (Py_TYPE(getattribute) == &PyWrapperDescr_Type &&
5880 ((PyWrapperDescrObject *)getattribute)->d_wrapped ==
5881 (void *)PyObject_GenericGetAttr))
5882 res = PyObject_GenericGetAttr(self, name);
5883 else {
5884 Py_INCREF(getattribute);
5885 res = call_attribute(self, getattribute, name);
5886 Py_DECREF(getattribute);
5887 }
5888 if (res == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) {
5889 PyErr_Clear();
5890 res = call_attribute(self, getattr, name);
5891 }
5892 Py_DECREF(getattr);
5893 return res;
Guido van Rossum19c1cd52001-09-21 21:24:49 +00005894}
5895
Tim Peters6d6c1a32001-08-02 04:15:00 +00005896static int
5897slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value)
5898{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005899 PyObject *res;
Benjamin Petersonce798522012-01-22 11:24:29 -05005900 _Py_IDENTIFIER(__delattr__);
5901 _Py_IDENTIFIER(__setattr__);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005902
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005903 if (value == NULL)
Benjamin Petersonce798522012-01-22 11:24:29 -05005904 res = call_method(self, &PyId___delattr__, "(O)", name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005905 else
Benjamin Petersonce798522012-01-22 11:24:29 -05005906 res = call_method(self, &PyId___setattr__, "(OO)", name, value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005907 if (res == NULL)
5908 return -1;
5909 Py_DECREF(res);
5910 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005911}
5912
Benjamin Petersonce798522012-01-22 11:24:29 -05005913static _Py_Identifier name_op[] = {
5914 {0, "__lt__", 0},
5915 {0, "__le__", 0},
5916 {0, "__eq__", 0},
5917 {0, "__ne__", 0},
5918 {0, "__gt__", 0},
5919 {0, "__ge__", 0}
Guido van Rossumf5243f02008-01-01 04:06:48 +00005920};
5921
Tim Peters6d6c1a32001-08-02 04:15:00 +00005922static PyObject *
Mark Dickinson6f1d0492009-11-15 13:58:49 +00005923slot_tp_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005924{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005925 PyObject *func, *args, *res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005926
Benjamin Petersonce798522012-01-22 11:24:29 -05005927 func = lookup_method(self, &name_op[op]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005928 if (func == NULL) {
5929 PyErr_Clear();
Brian Curtindfc80e32011-08-10 20:28:54 -05005930 Py_RETURN_NOTIMPLEMENTED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005931 }
5932 args = PyTuple_Pack(1, other);
5933 if (args == NULL)
5934 res = NULL;
5935 else {
5936 res = PyObject_Call(func, args, NULL);
5937 Py_DECREF(args);
5938 }
5939 Py_DECREF(func);
5940 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005941}
5942
Guido van Rossumb8f63662001-08-15 23:57:02 +00005943static PyObject *
Guido van Rossumb8f63662001-08-15 23:57:02 +00005944slot_tp_iter(PyObject *self)
5945{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005946 PyObject *func, *res;
Benjamin Petersonce798522012-01-22 11:24:29 -05005947 _Py_IDENTIFIER(__iter__);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005948
Benjamin Petersonce798522012-01-22 11:24:29 -05005949 func = lookup_method(self, &PyId___iter__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005950 if (func != NULL) {
5951 PyObject *args;
5952 args = res = PyTuple_New(0);
5953 if (args != NULL) {
5954 res = PyObject_Call(func, args, NULL);
5955 Py_DECREF(args);
5956 }
5957 Py_DECREF(func);
5958 return res;
5959 }
5960 PyErr_Clear();
Benjamin Petersonce798522012-01-22 11:24:29 -05005961 func = lookup_method(self, &PyId___getitem__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005962 if (func == NULL) {
5963 PyErr_Format(PyExc_TypeError,
5964 "'%.200s' object is not iterable",
5965 Py_TYPE(self)->tp_name);
5966 return NULL;
5967 }
5968 Py_DECREF(func);
5969 return PySeqIter_New(self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005970}
Tim Peters6d6c1a32001-08-02 04:15:00 +00005971
5972static PyObject *
5973slot_tp_iternext(PyObject *self)
5974{
Benjamin Petersonce798522012-01-22 11:24:29 -05005975 _Py_IDENTIFIER(__next__);
5976 return call_method(self, &PyId___next__, "()");
Tim Peters6d6c1a32001-08-02 04:15:00 +00005977}
5978
Guido van Rossum1a493502001-08-17 16:47:50 +00005979static PyObject *
5980slot_tp_descr_get(PyObject *self, PyObject *obj, PyObject *type)
5981{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005982 PyTypeObject *tp = Py_TYPE(self);
5983 PyObject *get;
Victor Stinner3c1e4812012-03-26 22:10:51 +02005984 _Py_IDENTIFIER(__get__);
Guido van Rossum1a493502001-08-17 16:47:50 +00005985
Victor Stinner3c1e4812012-03-26 22:10:51 +02005986 get = _PyType_LookupId(tp, &PyId___get__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005987 if (get == NULL) {
5988 /* Avoid further slowdowns */
5989 if (tp->tp_descr_get == slot_tp_descr_get)
5990 tp->tp_descr_get = NULL;
5991 Py_INCREF(self);
5992 return self;
5993 }
5994 if (obj == NULL)
5995 obj = Py_None;
5996 if (type == NULL)
5997 type = Py_None;
5998 return PyObject_CallFunctionObjArgs(get, self, obj, type, NULL);
Guido van Rossum1a493502001-08-17 16:47:50 +00005999}
Tim Peters6d6c1a32001-08-02 04:15:00 +00006000
6001static int
6002slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value)
6003{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006004 PyObject *res;
Benjamin Petersonce798522012-01-22 11:24:29 -05006005 _Py_IDENTIFIER(__delete__);
6006 _Py_IDENTIFIER(__set__);
Guido van Rossum2c252392001-08-24 10:13:31 +00006007
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006008 if (value == NULL)
Benjamin Petersonce798522012-01-22 11:24:29 -05006009 res = call_method(self, &PyId___delete__, "(O)", target);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006010 else
Benjamin Petersonce798522012-01-22 11:24:29 -05006011 res = call_method(self, &PyId___set__, "(OO)", target, value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006012 if (res == NULL)
6013 return -1;
6014 Py_DECREF(res);
6015 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00006016}
6017
6018static int
6019slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds)
6020{
Benjamin Petersonce798522012-01-22 11:24:29 -05006021 _Py_IDENTIFIER(__init__);
6022 PyObject *meth = lookup_method(self, &PyId___init__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006023 PyObject *res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00006024
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006025 if (meth == NULL)
6026 return -1;
6027 res = PyObject_Call(meth, args, kwds);
6028 Py_DECREF(meth);
6029 if (res == NULL)
6030 return -1;
6031 if (res != Py_None) {
6032 PyErr_Format(PyExc_TypeError,
6033 "__init__() should return None, not '%.200s'",
6034 Py_TYPE(res)->tp_name);
6035 Py_DECREF(res);
6036 return -1;
6037 }
6038 Py_DECREF(res);
6039 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00006040}
6041
6042static PyObject *
6043slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
6044{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006045 PyObject *func;
6046 PyObject *newargs, *x;
6047 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +00006048
Victor Stinner3c1e4812012-03-26 22:10:51 +02006049 func = _PyObject_GetAttrId((PyObject *)type, &PyId___new__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006050 if (func == NULL)
6051 return NULL;
6052 assert(PyTuple_Check(args));
6053 n = PyTuple_GET_SIZE(args);
6054 newargs = PyTuple_New(n+1);
6055 if (newargs == NULL)
6056 return NULL;
6057 Py_INCREF(type);
6058 PyTuple_SET_ITEM(newargs, 0, (PyObject *)type);
6059 for (i = 0; i < n; i++) {
6060 x = PyTuple_GET_ITEM(args, i);
6061 Py_INCREF(x);
6062 PyTuple_SET_ITEM(newargs, i+1, x);
6063 }
6064 x = PyObject_Call(func, newargs, kwds);
6065 Py_DECREF(newargs);
6066 Py_DECREF(func);
6067 return x;
Tim Peters6d6c1a32001-08-02 04:15:00 +00006068}
6069
Guido van Rossumfebd61d2002-08-08 20:55:20 +00006070static void
Antoine Pitrou796564c2013-07-30 19:59:21 +02006071slot_tp_finalize(PyObject *self)
Guido van Rossumfebd61d2002-08-08 20:55:20 +00006072{
Benjamin Petersonce798522012-01-22 11:24:29 -05006073 _Py_IDENTIFIER(__del__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006074 PyObject *del, *res;
6075 PyObject *error_type, *error_value, *error_traceback;
Guido van Rossumfebd61d2002-08-08 20:55:20 +00006076
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006077 /* Save the current exception, if any. */
6078 PyErr_Fetch(&error_type, &error_value, &error_traceback);
Guido van Rossumfebd61d2002-08-08 20:55:20 +00006079
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006080 /* Execute __del__ method, if any. */
Benjamin Petersonce798522012-01-22 11:24:29 -05006081 del = lookup_maybe(self, &PyId___del__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006082 if (del != NULL) {
6083 res = PyEval_CallObject(del, NULL);
6084 if (res == NULL)
6085 PyErr_WriteUnraisable(del);
6086 else
6087 Py_DECREF(res);
6088 Py_DECREF(del);
6089 }
Guido van Rossumfebd61d2002-08-08 20:55:20 +00006090
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006091 /* Restore the saved exception. */
6092 PyErr_Restore(error_type, error_value, error_traceback);
Guido van Rossumfebd61d2002-08-08 20:55:20 +00006093}
6094
Guido van Rossum7b9144b2001-10-09 19:39:46 +00006095
Benjamin Peterson63952412013-04-01 17:41:41 -04006096/*
6097Table mapping __foo__ names to tp_foo offsets and slot_tp_foo wrapper functions.
6098
6099The table is ordered by offsets relative to the 'PyHeapTypeObject' structure,
6100which incorporates the additional structures used for numbers, sequences and
6101mappings. Note that multiple names may map to the same slot (e.g. __eq__,
6102__ne__ etc. all map to tp_richcompare) and one name may map to multiple slots
6103(e.g. __str__ affects tp_str as well as tp_repr). The table is terminated with
6104an all-zero entry. (This table is further initialized in init_slotdefs().)
6105*/
Guido van Rossum7b9144b2001-10-09 19:39:46 +00006106
Guido van Rossum6d204072001-10-21 00:44:31 +00006107typedef struct wrapperbase slotdef;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00006108
6109#undef TPSLOT
Guido van Rossumc8e56452001-10-22 00:43:43 +00006110#undef FLSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00006111#undef ETSLOT
6112#undef SQSLOT
6113#undef MPSLOT
6114#undef NBSLOT
Guido van Rossum6d204072001-10-21 00:44:31 +00006115#undef UNSLOT
6116#undef IBSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00006117#undef BINSLOT
6118#undef RBINSLOT
6119
Guido van Rossum6d204072001-10-21 00:44:31 +00006120#define TPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006121 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
6122 PyDoc_STR(DOC)}
Guido van Rossumc8e56452001-10-22 00:43:43 +00006123#define FLSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC, FLAGS) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006124 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
6125 PyDoc_STR(DOC), FLAGS}
Guido van Rossum6d204072001-10-21 00:44:31 +00006126#define ETSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006127 {NAME, offsetof(PyHeapTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
6128 PyDoc_STR(DOC)}
Guido van Rossum6d204072001-10-21 00:44:31 +00006129#define SQSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006130 ETSLOT(NAME, as_sequence.SLOT, FUNCTION, WRAPPER, DOC)
Guido van Rossum6d204072001-10-21 00:44:31 +00006131#define MPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006132 ETSLOT(NAME, as_mapping.SLOT, FUNCTION, WRAPPER, DOC)
Guido van Rossum6d204072001-10-21 00:44:31 +00006133#define NBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006134 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, DOC)
Guido van Rossum6d204072001-10-21 00:44:31 +00006135#define UNSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006136 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
Larry Hastings69a25472014-02-09 22:22:38 -08006137 NAME "($self, /)\n--\n\n" DOC)
Guido van Rossum6d204072001-10-21 00:44:31 +00006138#define IBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006139 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
Larry Hastings69a25472014-02-09 22:22:38 -08006140 NAME "($self, value, /)\n--\n\nReturn self" DOC "value.")
Guido van Rossum6d204072001-10-21 00:44:31 +00006141#define BINSLOT(NAME, SLOT, FUNCTION, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006142 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
Larry Hastings69a25472014-02-09 22:22:38 -08006143 NAME "($self, value, /)\n--\n\nReturn self" DOC "value.")
Guido van Rossum6d204072001-10-21 00:44:31 +00006144#define RBINSLOT(NAME, SLOT, FUNCTION, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006145 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
Larry Hastings69a25472014-02-09 22:22:38 -08006146 NAME "($self, value, /)\n--\n\nReturn value" DOC "self.")
Anthony Baxter56616992005-06-03 14:12:21 +00006147#define BINSLOTNOTINFIX(NAME, SLOT, FUNCTION, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006148 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
Larry Hastings69a25472014-02-09 22:22:38 -08006149 NAME "($self, value, /)\n--\n\n" DOC)
Anthony Baxter56616992005-06-03 14:12:21 +00006150#define RBINSLOTNOTINFIX(NAME, SLOT, FUNCTION, DOC) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006151 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
Larry Hastings69a25472014-02-09 22:22:38 -08006152 NAME "($self, value, /)\n--\n\n" DOC)
Guido van Rossum7b9144b2001-10-09 19:39:46 +00006153
6154static slotdef slotdefs[] = {
Benjamin Peterson63952412013-04-01 17:41:41 -04006155 TPSLOT("__getattribute__", tp_getattr, NULL, NULL, ""),
6156 TPSLOT("__getattr__", tp_getattr, NULL, NULL, ""),
6157 TPSLOT("__setattr__", tp_setattr, NULL, NULL, ""),
6158 TPSLOT("__delattr__", tp_setattr, NULL, NULL, ""),
6159 TPSLOT("__repr__", tp_repr, slot_tp_repr, wrap_unaryfunc,
Larry Hastings69a25472014-02-09 22:22:38 -08006160 "__repr__($self, /)\n--\n\nReturn repr(self)."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006161 TPSLOT("__hash__", tp_hash, slot_tp_hash, wrap_hashfunc,
Larry Hastings69a25472014-02-09 22:22:38 -08006162 "__hash__($self, /)\n--\n\nReturn hash(self)."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006163 FLSLOT("__call__", tp_call, slot_tp_call, (wrapperfunc)wrap_call,
Larry Hastings69a25472014-02-09 22:22:38 -08006164 "__call__($self, /, *args, **kwargs)\n--\n\nCall self as a function.",
Larry Hastings5c661892014-01-24 06:17:25 -08006165 PyWrapperFlag_KEYWORDS),
Benjamin Peterson63952412013-04-01 17:41:41 -04006166 TPSLOT("__str__", tp_str, slot_tp_str, wrap_unaryfunc,
Larry Hastings69a25472014-02-09 22:22:38 -08006167 "__str__($self, /)\n--\n\nReturn str(self)."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006168 TPSLOT("__getattribute__", tp_getattro, slot_tp_getattr_hook,
Larry Hastings5c661892014-01-24 06:17:25 -08006169 wrap_binaryfunc,
Larry Hastings69a25472014-02-09 22:22:38 -08006170 "__getattribute__($self, name, /)\n--\n\nReturn getattr(self, name)."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006171 TPSLOT("__getattr__", tp_getattro, slot_tp_getattr_hook, NULL, ""),
6172 TPSLOT("__setattr__", tp_setattro, slot_tp_setattro, wrap_setattr,
Larry Hastings69a25472014-02-09 22:22:38 -08006173 "__setattr__($self, name, value, /)\n--\n\nImplement setattr(self, name, value)."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006174 TPSLOT("__delattr__", tp_setattro, slot_tp_setattro, wrap_delattr,
Larry Hastings69a25472014-02-09 22:22:38 -08006175 "__delattr__($self, name, /)\n--\n\nImplement delattr(self, name)."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006176 TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare, richcmp_lt,
Larry Hastings69a25472014-02-09 22:22:38 -08006177 "__lt__($self, value, /)\n--\n\nReturn self<value."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006178 TPSLOT("__le__", tp_richcompare, slot_tp_richcompare, richcmp_le,
Larry Hastings69a25472014-02-09 22:22:38 -08006179 "__le__($self, value, /)\n--\n\nReturn self<=value."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006180 TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare, richcmp_eq,
Larry Hastings69a25472014-02-09 22:22:38 -08006181 "__eq__($self, value, /)\n--\n\nReturn self==value."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006182 TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare, richcmp_ne,
Larry Hastings69a25472014-02-09 22:22:38 -08006183 "__ne__($self, value, /)\n--\n\nReturn self!=value."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006184 TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare, richcmp_gt,
Larry Hastings69a25472014-02-09 22:22:38 -08006185 "__gt__($self, value, /)\n--\n\nReturn self>value."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006186 TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare, richcmp_ge,
Zachary Wareea42b4c2014-04-18 09:14:31 -05006187 "__ge__($self, value, /)\n--\n\nReturn self>=value."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006188 TPSLOT("__iter__", tp_iter, slot_tp_iter, wrap_unaryfunc,
Larry Hastings69a25472014-02-09 22:22:38 -08006189 "__iter__($self, /)\n--\n\nImplement iter(self)."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006190 TPSLOT("__next__", tp_iternext, slot_tp_iternext, wrap_next,
Larry Hastings69a25472014-02-09 22:22:38 -08006191 "__next__($self, /)\n--\n\nImplement next(self)."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006192 TPSLOT("__get__", tp_descr_get, slot_tp_descr_get, wrap_descr_get,
Larry Hastings69a25472014-02-09 22:22:38 -08006193 "__get__($self, instance, owner, /)\n--\n\nReturn an attribute of instance, which is of type owner."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006194 TPSLOT("__set__", tp_descr_set, slot_tp_descr_set, wrap_descr_set,
Larry Hastings69a25472014-02-09 22:22:38 -08006195 "__set__($self, instance, value, /)\n--\n\nSet an attribute of instance to value."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006196 TPSLOT("__delete__", tp_descr_set, slot_tp_descr_set,
Larry Hastings5c661892014-01-24 06:17:25 -08006197 wrap_descr_delete,
Yury Selivanov056e2652014-03-02 12:25:27 -05006198 "__delete__($self, instance, /)\n--\n\nDelete an attribute of instance."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006199 FLSLOT("__init__", tp_init, slot_tp_init, (wrapperfunc)wrap_init,
Larry Hastings69a25472014-02-09 22:22:38 -08006200 "__init__($self, /, *args, **kwargs)\n--\n\n"
Larry Hastings581ee362014-01-28 05:00:08 -08006201 "Initialize self. See help(type(self)) for accurate signature.",
Benjamin Peterson63952412013-04-01 17:41:41 -04006202 PyWrapperFlag_KEYWORDS),
Larry Hastings5c661892014-01-24 06:17:25 -08006203 TPSLOT("__new__", tp_new, slot_tp_new, NULL,
Larry Hastings69a25472014-02-09 22:22:38 -08006204 "__new__(type, /, *args, **kwargs)\n--\n\n"
Larry Hastings581ee362014-01-28 05:00:08 -08006205 "Create and return new object. See help(type) for accurate signature."),
Antoine Pitrou796564c2013-07-30 19:59:21 +02006206 TPSLOT("__del__", tp_finalize, slot_tp_finalize, (wrapperfunc)wrap_del, ""),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00006207
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006208 BINSLOT("__add__", nb_add, slot_nb_add,
Larry Hastings5c661892014-01-24 06:17:25 -08006209 "+"),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006210 RBINSLOT("__radd__", nb_add, slot_nb_add,
Larry Hastings5c661892014-01-24 06:17:25 -08006211 "+"),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006212 BINSLOT("__sub__", nb_subtract, slot_nb_subtract,
Larry Hastings5c661892014-01-24 06:17:25 -08006213 "-"),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006214 RBINSLOT("__rsub__", nb_subtract, slot_nb_subtract,
Larry Hastings5c661892014-01-24 06:17:25 -08006215 "-"),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006216 BINSLOT("__mul__", nb_multiply, slot_nb_multiply,
Larry Hastings5c661892014-01-24 06:17:25 -08006217 "*"),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006218 RBINSLOT("__rmul__", nb_multiply, slot_nb_multiply,
Larry Hastings5c661892014-01-24 06:17:25 -08006219 "*"),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006220 BINSLOT("__mod__", nb_remainder, slot_nb_remainder,
Larry Hastings5c661892014-01-24 06:17:25 -08006221 "%"),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006222 RBINSLOT("__rmod__", nb_remainder, slot_nb_remainder,
Larry Hastings5c661892014-01-24 06:17:25 -08006223 "%"),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006224 BINSLOTNOTINFIX("__divmod__", nb_divmod, slot_nb_divmod,
Larry Hastings581ee362014-01-28 05:00:08 -08006225 "Return divmod(self, value)."),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006226 RBINSLOTNOTINFIX("__rdivmod__", nb_divmod, slot_nb_divmod,
Larry Hastings581ee362014-01-28 05:00:08 -08006227 "Return divmod(value, self)."),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006228 NBSLOT("__pow__", nb_power, slot_nb_power, wrap_ternaryfunc,
Larry Hastings69a25472014-02-09 22:22:38 -08006229 "__pow__($self, value, mod=None, /)\n--\n\nReturn pow(self, value, mod)."),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006230 NBSLOT("__rpow__", nb_power, slot_nb_power, wrap_ternaryfunc_r,
Larry Hastings69a25472014-02-09 22:22:38 -08006231 "__rpow__($self, value, mod=None, /)\n--\n\nReturn pow(value, self, mod)."),
Larry Hastings5c661892014-01-24 06:17:25 -08006232 UNSLOT("__neg__", nb_negative, slot_nb_negative, wrap_unaryfunc, "-self"),
6233 UNSLOT("__pos__", nb_positive, slot_nb_positive, wrap_unaryfunc, "+self"),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006234 UNSLOT("__abs__", nb_absolute, slot_nb_absolute, wrap_unaryfunc,
Larry Hastings5c661892014-01-24 06:17:25 -08006235 "abs(self)"),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006236 UNSLOT("__bool__", nb_bool, slot_nb_bool, wrap_inquirypred,
Larry Hastings5c661892014-01-24 06:17:25 -08006237 "self != 0"),
6238 UNSLOT("__invert__", nb_invert, slot_nb_invert, wrap_unaryfunc, "~self"),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006239 BINSLOT("__lshift__", nb_lshift, slot_nb_lshift, "<<"),
6240 RBINSLOT("__rlshift__", nb_lshift, slot_nb_lshift, "<<"),
6241 BINSLOT("__rshift__", nb_rshift, slot_nb_rshift, ">>"),
6242 RBINSLOT("__rrshift__", nb_rshift, slot_nb_rshift, ">>"),
6243 BINSLOT("__and__", nb_and, slot_nb_and, "&"),
6244 RBINSLOT("__rand__", nb_and, slot_nb_and, "&"),
6245 BINSLOT("__xor__", nb_xor, slot_nb_xor, "^"),
6246 RBINSLOT("__rxor__", nb_xor, slot_nb_xor, "^"),
6247 BINSLOT("__or__", nb_or, slot_nb_or, "|"),
6248 RBINSLOT("__ror__", nb_or, slot_nb_or, "|"),
6249 UNSLOT("__int__", nb_int, slot_nb_int, wrap_unaryfunc,
Larry Hastings5c661892014-01-24 06:17:25 -08006250 "int(self)"),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006251 UNSLOT("__float__", nb_float, slot_nb_float, wrap_unaryfunc,
Larry Hastings5c661892014-01-24 06:17:25 -08006252 "float(self)"),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006253 IBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add,
Eli Benderskyd3baae72011-11-11 16:57:05 +02006254 wrap_binaryfunc, "+="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006255 IBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract,
Eli Benderskyd3baae72011-11-11 16:57:05 +02006256 wrap_binaryfunc, "-="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006257 IBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply,
Eli Benderskyd3baae72011-11-11 16:57:05 +02006258 wrap_binaryfunc, "*="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006259 IBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder,
Eli Benderskyd3baae72011-11-11 16:57:05 +02006260 wrap_binaryfunc, "%="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006261 IBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power,
Eli Benderskyd3baae72011-11-11 16:57:05 +02006262 wrap_binaryfunc, "**="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006263 IBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift,
Eli Benderskyd3baae72011-11-11 16:57:05 +02006264 wrap_binaryfunc, "<<="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006265 IBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift,
Eli Benderskyd3baae72011-11-11 16:57:05 +02006266 wrap_binaryfunc, ">>="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006267 IBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and,
Eli Benderskyd3baae72011-11-11 16:57:05 +02006268 wrap_binaryfunc, "&="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006269 IBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor,
Eli Benderskyd3baae72011-11-11 16:57:05 +02006270 wrap_binaryfunc, "^="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006271 IBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or,
Eli Benderskyd3baae72011-11-11 16:57:05 +02006272 wrap_binaryfunc, "|="),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006273 BINSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
6274 RBINSLOT("__rfloordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
6275 BINSLOT("__truediv__", nb_true_divide, slot_nb_true_divide, "/"),
6276 RBINSLOT("__rtruediv__", nb_true_divide, slot_nb_true_divide, "/"),
6277 IBSLOT("__ifloordiv__", nb_inplace_floor_divide,
6278 slot_nb_inplace_floor_divide, wrap_binaryfunc, "//"),
6279 IBSLOT("__itruediv__", nb_inplace_true_divide,
6280 slot_nb_inplace_true_divide, wrap_binaryfunc, "/"),
Benjamin Peterson63952412013-04-01 17:41:41 -04006281 NBSLOT("__index__", nb_index, slot_nb_index, wrap_unaryfunc,
Larry Hastings69a25472014-02-09 22:22:38 -08006282 "__index__($self, /)\n--\n\n"
Zachary Ware715ef022014-04-18 09:23:14 -05006283 "Return self converted to an integer, if self is suitable "
Larry Hastings5c661892014-01-24 06:17:25 -08006284 "for use as an index into a list."),
Benjamin Petersond51374e2014-04-09 23:55:56 -04006285 BINSLOT("__matmul__", nb_matrix_multiply, slot_nb_matrix_multiply,
6286 "@"),
6287 RBINSLOT("__rmatmul__", nb_matrix_multiply, slot_nb_matrix_multiply,
6288 "@"),
6289 IBSLOT("__imatmul__", nb_inplace_matrix_multiply, slot_nb_inplace_matrix_multiply,
6290 wrap_binaryfunc, "@="),
Benjamin Peterson63952412013-04-01 17:41:41 -04006291 MPSLOT("__len__", mp_length, slot_mp_length, wrap_lenfunc,
Larry Hastings69a25472014-02-09 22:22:38 -08006292 "__len__($self, /)\n--\n\nReturn len(self)."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006293 MPSLOT("__getitem__", mp_subscript, slot_mp_subscript,
6294 wrap_binaryfunc,
Larry Hastings69a25472014-02-09 22:22:38 -08006295 "__getitem__($self, key, /)\n--\n\nReturn self[key]."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006296 MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript,
6297 wrap_objobjargproc,
Larry Hastings69a25472014-02-09 22:22:38 -08006298 "__setitem__($self, key, value, /)\n--\n\nSet self[key] to value."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006299 MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript,
6300 wrap_delitem,
Yury Selivanov056e2652014-03-02 12:25:27 -05006301 "__delitem__($self, key, /)\n--\n\nDelete self[key]."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006302
6303 SQSLOT("__len__", sq_length, slot_sq_length, wrap_lenfunc,
Larry Hastings69a25472014-02-09 22:22:38 -08006304 "__len__($self, /)\n--\n\nReturn len(self)."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006305 /* Heap types defining __add__/__mul__ have sq_concat/sq_repeat == NULL.
6306 The logic in abstract.c always falls back to nb_add/nb_multiply in
6307 this case. Defining both the nb_* and the sq_* slots to call the
6308 user-defined methods has unexpected side-effects, as shown by
6309 test_descr.notimplemented() */
6310 SQSLOT("__add__", sq_concat, NULL, wrap_binaryfunc,
Larry Hastings69a25472014-02-09 22:22:38 -08006311 "__add__($self, value, /)\n--\n\nReturn self+value."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006312 SQSLOT("__mul__", sq_repeat, NULL, wrap_indexargfunc,
Larry Hastings69a25472014-02-09 22:22:38 -08006313 "__mul__($self, value, /)\n--\n\nReturn self*value.n"),
Benjamin Peterson63952412013-04-01 17:41:41 -04006314 SQSLOT("__rmul__", sq_repeat, NULL, wrap_indexargfunc,
Larry Hastings69a25472014-02-09 22:22:38 -08006315 "__rmul__($self, value, /)\n--\n\nReturn self*value."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006316 SQSLOT("__getitem__", sq_item, slot_sq_item, wrap_sq_item,
Larry Hastings69a25472014-02-09 22:22:38 -08006317 "__getitem__($self, key, /)\n--\n\nReturn self[key]."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006318 SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_setitem,
Larry Hastings69a25472014-02-09 22:22:38 -08006319 "__setitem__($self, key, value, /)\n--\n\nSet self[key] to value."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006320 SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_delitem,
Larry Hastings69a25472014-02-09 22:22:38 -08006321 "__delitem__($self, key, /)\n--\n\nDelete self[key]."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006322 SQSLOT("__contains__", sq_contains, slot_sq_contains, wrap_objobjproc,
Larry Hastings69a25472014-02-09 22:22:38 -08006323 "__contains__($self, key, /)\n--\n\nReturn key in self."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006324 SQSLOT("__iadd__", sq_inplace_concat, NULL,
Larry Hastings5c661892014-01-24 06:17:25 -08006325 wrap_binaryfunc,
Larry Hastings69a25472014-02-09 22:22:38 -08006326 "__iadd__($self, value, /)\n--\n\nImplement self+=value."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006327 SQSLOT("__imul__", sq_inplace_repeat, NULL,
Larry Hastings5c661892014-01-24 06:17:25 -08006328 wrap_indexargfunc,
Larry Hastings69a25472014-02-09 22:22:38 -08006329 "__imul__($self, value, /)\n--\n\nImplement self*=value."),
Benjamin Peterson63952412013-04-01 17:41:41 -04006330
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006331 {NULL}
Guido van Rossum7b9144b2001-10-09 19:39:46 +00006332};
6333
Guido van Rossumc334df52002-04-04 23:44:47 +00006334/* Given a type pointer and an offset gotten from a slotdef entry, return a
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006335 pointer to the actual slot. This is not quite the same as simply adding
Guido van Rossumc334df52002-04-04 23:44:47 +00006336 the offset to the type pointer, since it takes care to indirect through the
6337 proper indirection pointer (as_buffer, etc.); it returns NULL if the
6338 indirection pointer is NULL. */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00006339static void **
Martin v. Löwis18e16552006-02-15 17:27:45 +00006340slotptr(PyTypeObject *type, int ioffset)
Guido van Rossum7b9144b2001-10-09 19:39:46 +00006341{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006342 char *ptr;
6343 long offset = ioffset;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00006344
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006345 /* Note: this depends on the order of the members of PyHeapTypeObject! */
6346 assert(offset >= 0);
6347 assert((size_t)offset < offsetof(PyHeapTypeObject, as_buffer));
6348 if ((size_t)offset >= offsetof(PyHeapTypeObject, as_sequence)) {
6349 ptr = (char *)type->tp_as_sequence;
6350 offset -= offsetof(PyHeapTypeObject, as_sequence);
6351 }
6352 else if ((size_t)offset >= offsetof(PyHeapTypeObject, as_mapping)) {
6353 ptr = (char *)type->tp_as_mapping;
6354 offset -= offsetof(PyHeapTypeObject, as_mapping);
6355 }
6356 else if ((size_t)offset >= offsetof(PyHeapTypeObject, as_number)) {
6357 ptr = (char *)type->tp_as_number;
6358 offset -= offsetof(PyHeapTypeObject, as_number);
6359 }
6360 else {
6361 ptr = (char *)type;
6362 }
6363 if (ptr != NULL)
6364 ptr += offset;
6365 return (void **)ptr;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00006366}
Guido van Rossumf040ede2001-08-07 16:40:56 +00006367
Guido van Rossumc334df52002-04-04 23:44:47 +00006368/* Length of array of slotdef pointers used to store slots with the
6369 same __name__. There should be at most MAX_EQUIV-1 slotdef entries with
6370 the same __name__, for any __name__. Since that's a static property, it is
6371 appropriate to declare fixed-size arrays for this. */
6372#define MAX_EQUIV 10
6373
6374/* Return a slot pointer for a given name, but ONLY if the attribute has
6375 exactly one slot function. The name must be an interned string. */
6376static void **
6377resolve_slotdups(PyTypeObject *type, PyObject *name)
6378{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006379 /* XXX Maybe this could be optimized more -- but is it worth it? */
Guido van Rossumc334df52002-04-04 23:44:47 +00006380
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006381 /* pname and ptrs act as a little cache */
6382 static PyObject *pname;
6383 static slotdef *ptrs[MAX_EQUIV];
6384 slotdef *p, **pp;
6385 void **res, **ptr;
Guido van Rossumc334df52002-04-04 23:44:47 +00006386
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006387 if (pname != name) {
6388 /* Collect all slotdefs that match name into ptrs. */
6389 pname = name;
6390 pp = ptrs;
6391 for (p = slotdefs; p->name_strobj; p++) {
6392 if (p->name_strobj == name)
6393 *pp++ = p;
6394 }
6395 *pp = NULL;
6396 }
Guido van Rossumc334df52002-04-04 23:44:47 +00006397
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006398 /* Look in all matching slots of the type; if exactly one of these has
6399 a filled-in slot, return its value. Otherwise return NULL. */
6400 res = NULL;
6401 for (pp = ptrs; *pp; pp++) {
6402 ptr = slotptr(type, (*pp)->offset);
6403 if (ptr == NULL || *ptr == NULL)
6404 continue;
6405 if (res != NULL)
6406 return NULL;
6407 res = ptr;
6408 }
6409 return res;
Guido van Rossumc334df52002-04-04 23:44:47 +00006410}
6411
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006412/* Common code for update_slots_callback() and fixup_slot_dispatchers(). This
Guido van Rossumc334df52002-04-04 23:44:47 +00006413 does some incredibly complex thinking and then sticks something into the
6414 slot. (It sees if the adjacent slotdefs for the same slot have conflicting
6415 interests, and then stores a generic wrapper or a specific function into
6416 the slot.) Return a pointer to the next slotdef with a different offset,
6417 because that's convenient for fixup_slot_dispatchers(). */
6418static slotdef *
6419update_one_slot(PyTypeObject *type, slotdef *p)
6420{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006421 PyObject *descr;
6422 PyWrapperDescrObject *d;
6423 void *generic = NULL, *specific = NULL;
6424 int use_generic = 0;
6425 int offset = p->offset;
6426 void **ptr = slotptr(type, offset);
Guido van Rossumc334df52002-04-04 23:44:47 +00006427
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006428 if (ptr == NULL) {
6429 do {
6430 ++p;
6431 } while (p->offset == offset);
6432 return p;
6433 }
6434 do {
6435 descr = _PyType_Lookup(type, p->name_strobj);
6436 if (descr == NULL) {
6437 if (ptr == (void**)&type->tp_iternext) {
Trent Nelsonab02db22012-09-18 21:58:03 -04006438 specific = (void *)_PyObject_NextNotImplemented;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006439 }
6440 continue;
6441 }
Benjamin Peterson7b166872012-04-24 11:06:25 -04006442 if (Py_TYPE(descr) == &PyWrapperDescr_Type &&
6443 ((PyWrapperDescrObject *)descr)->d_base->name_strobj == p->name_strobj) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006444 void **tptr = resolve_slotdups(type, p->name_strobj);
6445 if (tptr == NULL || tptr == ptr)
6446 generic = p->function;
6447 d = (PyWrapperDescrObject *)descr;
6448 if (d->d_base->wrapper == p->wrapper &&
6449 PyType_IsSubtype(type, PyDescr_TYPE(d)))
6450 {
6451 if (specific == NULL ||
6452 specific == d->d_wrapped)
6453 specific = d->d_wrapped;
6454 else
6455 use_generic = 1;
6456 }
6457 }
6458 else if (Py_TYPE(descr) == &PyCFunction_Type &&
6459 PyCFunction_GET_FUNCTION(descr) ==
6460 (PyCFunction)tp_new_wrapper &&
6461 ptr == (void**)&type->tp_new)
6462 {
6463 /* The __new__ wrapper is not a wrapper descriptor,
6464 so must be special-cased differently.
6465 If we don't do this, creating an instance will
6466 always use slot_tp_new which will look up
6467 __new__ in the MRO which will call tp_new_wrapper
6468 which will look through the base classes looking
6469 for a static base and call its tp_new (usually
6470 PyType_GenericNew), after performing various
6471 sanity checks and constructing a new argument
6472 list. Cut all that nonsense short -- this speeds
6473 up instance creation tremendously. */
6474 specific = (void *)type->tp_new;
6475 /* XXX I'm not 100% sure that there isn't a hole
6476 in this reasoning that requires additional
6477 sanity checks. I'll buy the first person to
6478 point out a bug in this reasoning a beer. */
6479 }
6480 else if (descr == Py_None &&
6481 ptr == (void**)&type->tp_hash) {
6482 /* We specifically allow __hash__ to be set to None
6483 to prevent inheritance of the default
6484 implementation from object.__hash__ */
Trent Nelsonab02db22012-09-18 21:58:03 -04006485 specific = (void *)PyObject_HashNotImplemented;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006486 }
6487 else {
6488 use_generic = 1;
6489 generic = p->function;
6490 }
6491 } while ((++p)->offset == offset);
6492 if (specific && !use_generic)
6493 *ptr = specific;
6494 else
6495 *ptr = generic;
6496 return p;
Guido van Rossumc334df52002-04-04 23:44:47 +00006497}
6498
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006499/* In the type, update the slots whose slotdefs are gathered in the pp array.
6500 This is a callback for update_subclasses(). */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006501static int
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006502update_slots_callback(PyTypeObject *type, void *data)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006503{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006504 slotdef **pp = (slotdef **)data;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006505
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006506 for (; *pp; pp++)
6507 update_one_slot(type, *pp);
6508 return 0;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006509}
6510
Guido van Rossumc334df52002-04-04 23:44:47 +00006511/* Initialize the slotdefs table by adding interned string objects for the
6512 names and sorting the entries. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006513static void
Guido van Rossumd396b9c2001-10-13 20:02:41 +00006514init_slotdefs(void)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006515{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006516 slotdef *p;
6517 static int initialized = 0;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006518
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006519 if (initialized)
6520 return;
6521 for (p = slotdefs; p->name; p++) {
Benjamin Peterson63952412013-04-01 17:41:41 -04006522 /* Slots must be ordered by their offset in the PyHeapTypeObject. */
6523 assert(!p[1].name || p->offset <= p[1].offset);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006524 p->name_strobj = PyUnicode_InternFromString(p->name);
6525 if (!p->name_strobj)
6526 Py_FatalError("Out of memory interning slotdef names");
6527 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006528 initialized = 1;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006529}
6530
Guido van Rossumc334df52002-04-04 23:44:47 +00006531/* Update the slots after assignment to a class (type) attribute. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006532static int
6533update_slot(PyTypeObject *type, PyObject *name)
6534{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006535 slotdef *ptrs[MAX_EQUIV];
6536 slotdef *p;
6537 slotdef **pp;
6538 int offset;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006539
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006540 /* Clear the VALID_VERSION flag of 'type' and all its
6541 subclasses. This could possibly be unified with the
6542 update_subclasses() recursion below, but carefully:
6543 they each have their own conditions on which to stop
6544 recursing into subclasses. */
6545 PyType_Modified(type);
Christian Heimesa62da1d2008-01-12 19:39:10 +00006546
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006547 init_slotdefs();
6548 pp = ptrs;
6549 for (p = slotdefs; p->name; p++) {
6550 /* XXX assume name is interned! */
6551 if (p->name_strobj == name)
6552 *pp++ = p;
6553 }
6554 *pp = NULL;
6555 for (pp = ptrs; *pp; pp++) {
6556 p = *pp;
6557 offset = p->offset;
6558 while (p > slotdefs && (p-1)->offset == offset)
6559 --p;
6560 *pp = p;
6561 }
6562 if (ptrs[0] == NULL)
6563 return 0; /* Not an attribute that affects any slots */
6564 return update_subclasses(type, name,
6565 update_slots_callback, (void *)ptrs);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006566}
6567
Guido van Rossumc334df52002-04-04 23:44:47 +00006568/* Store the proper functions in the slot dispatches at class (type)
6569 definition time, based upon which operations the class overrides in its
6570 dict. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00006571static void
Guido van Rossum7b9144b2001-10-09 19:39:46 +00006572fixup_slot_dispatchers(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00006573{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006574 slotdef *p;
Tim Peters6d6c1a32001-08-02 04:15:00 +00006575
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006576 init_slotdefs();
6577 for (p = slotdefs; p->name; )
6578 p = update_one_slot(type, p);
Tim Peters6d6c1a32001-08-02 04:15:00 +00006579}
Guido van Rossum705f0f52001-08-24 16:47:00 +00006580
Michael W. Hudson98bbc492002-11-26 14:47:27 +00006581static void
6582update_all_slots(PyTypeObject* type)
6583{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006584 slotdef *p;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00006585
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006586 init_slotdefs();
6587 for (p = slotdefs; p->name; p++) {
6588 /* update_slot returns int but can't actually fail */
6589 update_slot(type, p->name_strobj);
6590 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +00006591}
6592
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006593/* recurse_down_subclasses() and update_subclasses() are mutually
6594 recursive functions to call a callback for all subclasses,
6595 but refraining from recursing into subclasses that define 'name'. */
6596
6597static int
6598update_subclasses(PyTypeObject *type, PyObject *name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006599 update_callback callback, void *data)
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006600{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006601 if (callback(type, data) < 0)
6602 return -1;
6603 return recurse_down_subclasses(type, name, callback, data);
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006604}
6605
6606static int
6607recurse_down_subclasses(PyTypeObject *type, PyObject *name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006608 update_callback callback, void *data)
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006609{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006610 PyTypeObject *subclass;
6611 PyObject *ref, *subclasses, *dict;
Antoine Pitrou84745ab2013-10-29 21:31:25 +01006612 Py_ssize_t i;
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006613
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006614 subclasses = type->tp_subclasses;
6615 if (subclasses == NULL)
6616 return 0;
Antoine Pitrou84745ab2013-10-29 21:31:25 +01006617 assert(PyDict_CheckExact(subclasses));
6618 i = 0;
6619 while (PyDict_Next(subclasses, &i, NULL, &ref)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006620 assert(PyWeakref_CheckRef(ref));
6621 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
6622 assert(subclass != NULL);
6623 if ((PyObject *)subclass == Py_None)
6624 continue;
6625 assert(PyType_Check(subclass));
6626 /* Avoid recursing down into unaffected classes */
6627 dict = subclass->tp_dict;
6628 if (dict != NULL && PyDict_Check(dict) &&
6629 PyDict_GetItem(dict, name) != NULL)
6630 continue;
6631 if (update_subclasses(subclass, name, callback, data) < 0)
6632 return -1;
6633 }
6634 return 0;
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006635}
6636
Guido van Rossum6d204072001-10-21 00:44:31 +00006637/* This function is called by PyType_Ready() to populate the type's
6638 dictionary with method descriptors for function slots. For each
Guido van Rossum09638c12002-06-13 19:17:46 +00006639 function slot (like tp_repr) that's defined in the type, one or more
6640 corresponding descriptors are added in the type's tp_dict dictionary
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006641 under the appropriate name (like __repr__). Some function slots
Guido van Rossum09638c12002-06-13 19:17:46 +00006642 cause more than one descriptor to be added (for example, the nb_add
6643 slot adds both __add__ and __radd__ descriptors) and some function
6644 slots compete for the same descriptor (for example both sq_item and
6645 mp_subscript generate a __getitem__ descriptor).
6646
Ezio Melotti13925002011-03-16 11:05:33 +02006647 In the latter case, the first slotdef entry encountered wins. Since
Tim Petersbf9b2442003-03-23 05:35:36 +00006648 slotdef entries are sorted by the offset of the slot in the
Guido van Rossume5c691a2003-03-07 15:13:17 +00006649 PyHeapTypeObject, this gives us some control over disambiguating
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006650 between competing slots: the members of PyHeapTypeObject are listed
6651 from most general to least general, so the most general slot is
6652 preferred. In particular, because as_mapping comes before as_sequence,
6653 for a type that defines both mp_subscript and sq_item, mp_subscript
6654 wins.
Guido van Rossum09638c12002-06-13 19:17:46 +00006655
6656 This only adds new descriptors and doesn't overwrite entries in
6657 tp_dict that were previously defined. The descriptors contain a
6658 reference to the C function they must call, so that it's safe if they
6659 are copied into a subtype's __dict__ and the subtype has a different
6660 C function in its slot -- calling the method defined by the
6661 descriptor will call the C function that was used to create it,
6662 rather than the C function present in the slot when it is called.
6663 (This is important because a subtype may have a C function in the
6664 slot that calls the method from the dictionary, and we want to avoid
6665 infinite recursion here.) */
Guido van Rossum6d204072001-10-21 00:44:31 +00006666
6667static int
6668add_operators(PyTypeObject *type)
6669{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006670 PyObject *dict = type->tp_dict;
6671 slotdef *p;
6672 PyObject *descr;
6673 void **ptr;
Guido van Rossum6d204072001-10-21 00:44:31 +00006674
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006675 init_slotdefs();
6676 for (p = slotdefs; p->name; p++) {
6677 if (p->wrapper == NULL)
6678 continue;
6679 ptr = slotptr(type, p->offset);
6680 if (!ptr || !*ptr)
6681 continue;
6682 if (PyDict_GetItem(dict, p->name_strobj))
6683 continue;
Trent Nelsonab02db22012-09-18 21:58:03 -04006684 if (*ptr == (void *)PyObject_HashNotImplemented) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006685 /* Classes may prevent the inheritance of the tp_hash
6686 slot by storing PyObject_HashNotImplemented in it. Make it
6687 visible as a None value for the __hash__ attribute. */
6688 if (PyDict_SetItem(dict, p->name_strobj, Py_None) < 0)
6689 return -1;
6690 }
6691 else {
6692 descr = PyDescr_NewWrapper(type, p, *ptr);
6693 if (descr == NULL)
6694 return -1;
6695 if (PyDict_SetItem(dict, p->name_strobj, descr) < 0)
6696 return -1;
6697 Py_DECREF(descr);
6698 }
6699 }
6700 if (type->tp_new != NULL) {
6701 if (add_tp_new_wrapper(type) < 0)
6702 return -1;
6703 }
6704 return 0;
Guido van Rossum6d204072001-10-21 00:44:31 +00006705}
6706
Guido van Rossum705f0f52001-08-24 16:47:00 +00006707
6708/* Cooperative 'super' */
6709
6710typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006711 PyObject_HEAD
6712 PyTypeObject *type;
6713 PyObject *obj;
6714 PyTypeObject *obj_type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006715} superobject;
6716
Guido van Rossum6f799372001-09-20 20:46:19 +00006717static PyMemberDef super_members[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006718 {"__thisclass__", T_OBJECT, offsetof(superobject, type), READONLY,
6719 "the class invoking super()"},
6720 {"__self__", T_OBJECT, offsetof(superobject, obj), READONLY,
6721 "the instance invoking super(); may be None"},
6722 {"__self_class__", T_OBJECT, offsetof(superobject, obj_type), READONLY,
6723 "the type of the instance invoking super(); may be None"},
6724 {0}
Guido van Rossum41eb14d2001-08-30 23:13:11 +00006725};
6726
Guido van Rossum705f0f52001-08-24 16:47:00 +00006727static void
6728super_dealloc(PyObject *self)
6729{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006730 superobject *su = (superobject *)self;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006731
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006732 _PyObject_GC_UNTRACK(self);
6733 Py_XDECREF(su->obj);
6734 Py_XDECREF(su->type);
6735 Py_XDECREF(su->obj_type);
6736 Py_TYPE(self)->tp_free(self);
Guido van Rossum705f0f52001-08-24 16:47:00 +00006737}
6738
6739static PyObject *
Guido van Rossum41eb14d2001-08-30 23:13:11 +00006740super_repr(PyObject *self)
6741{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006742 superobject *su = (superobject *)self;
Guido van Rossum41eb14d2001-08-30 23:13:11 +00006743
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006744 if (su->obj_type)
6745 return PyUnicode_FromFormat(
6746 "<super: <class '%s'>, <%s object>>",
6747 su->type ? su->type->tp_name : "NULL",
6748 su->obj_type->tp_name);
6749 else
6750 return PyUnicode_FromFormat(
6751 "<super: <class '%s'>, NULL>",
6752 su->type ? su->type->tp_name : "NULL");
Guido van Rossum41eb14d2001-08-30 23:13:11 +00006753}
6754
6755static PyObject *
Guido van Rossum705f0f52001-08-24 16:47:00 +00006756super_getattro(PyObject *self, PyObject *name)
6757{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006758 superobject *su = (superobject *)self;
6759 int skip = su->obj_type == NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006760
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006761 if (!skip) {
6762 /* We want __class__ to return the class of the super object
6763 (i.e. super, or a subclass), not the class of su->obj. */
6764 skip = (PyUnicode_Check(name) &&
Victor Stinnerad14ccd2013-11-07 00:46:04 +01006765 PyUnicode_GET_LENGTH(name) == 9 &&
6766 _PyUnicode_CompareWithId(name, &PyId___class__) == 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006767 }
Guido van Rossum76ba09f2003-04-16 19:40:58 +00006768
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006769 if (!skip) {
6770 PyObject *mro, *res, *tmp, *dict;
6771 PyTypeObject *starttype;
6772 descrgetfunc f;
6773 Py_ssize_t i, n;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006774
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006775 starttype = su->obj_type;
6776 mro = starttype->tp_mro;
Guido van Rossum155db9a2002-04-02 17:53:47 +00006777
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006778 if (mro == NULL)
6779 n = 0;
6780 else {
6781 assert(PyTuple_Check(mro));
6782 n = PyTuple_GET_SIZE(mro);
6783 }
6784 for (i = 0; i < n; i++) {
6785 if ((PyObject *)(su->type) == PyTuple_GET_ITEM(mro, i))
6786 break;
6787 }
6788 i++;
6789 res = NULL;
Victor Stinnerd74782b2012-03-09 00:39:08 +01006790 /* keep a strong reference to mro because starttype->tp_mro can be
6791 replaced during PyDict_GetItem(dict, name) */
6792 Py_INCREF(mro);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006793 for (; i < n; i++) {
6794 tmp = PyTuple_GET_ITEM(mro, i);
6795 if (PyType_Check(tmp))
6796 dict = ((PyTypeObject *)tmp)->tp_dict;
6797 else
6798 continue;
6799 res = PyDict_GetItem(dict, name);
6800 if (res != NULL) {
6801 Py_INCREF(res);
6802 f = Py_TYPE(res)->tp_descr_get;
6803 if (f != NULL) {
6804 tmp = f(res,
6805 /* Only pass 'obj' param if
6806 this is instance-mode super
6807 (See SF ID #743627)
6808 */
6809 (su->obj == (PyObject *)
6810 su->obj_type
6811 ? (PyObject *)NULL
6812 : su->obj),
6813 (PyObject *)starttype);
6814 Py_DECREF(res);
6815 res = tmp;
6816 }
Victor Stinnerd74782b2012-03-09 00:39:08 +01006817 Py_DECREF(mro);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006818 return res;
6819 }
6820 }
Victor Stinnerd74782b2012-03-09 00:39:08 +01006821 Py_DECREF(mro);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006822 }
6823 return PyObject_GenericGetAttr(self, name);
Guido van Rossum705f0f52001-08-24 16:47:00 +00006824}
6825
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006826static PyTypeObject *
Guido van Rossum5b443c62001-12-03 15:38:28 +00006827supercheck(PyTypeObject *type, PyObject *obj)
6828{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006829 /* Check that a super() call makes sense. Return a type object.
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006830
Florent Xiclunaaa6c1d22011-12-12 18:54:29 +01006831 obj can be a class, or an instance of one:
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006832
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006833 - If it is a class, it must be a subclass of 'type'. This case is
6834 used for class methods; the return value is obj.
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006835
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006836 - If it is an instance, it must be an instance of 'type'. This is
6837 the normal case; the return value is obj.__class__.
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006838
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006839 But... when obj is an instance, we want to allow for the case where
6840 Py_TYPE(obj) is not a subclass of type, but obj.__class__ is!
6841 This will allow using super() with a proxy for obj.
6842 */
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006843
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006844 /* Check for first bullet above (special case) */
6845 if (PyType_Check(obj) && PyType_IsSubtype((PyTypeObject *)obj, type)) {
6846 Py_INCREF(obj);
6847 return (PyTypeObject *)obj;
6848 }
Guido van Rossum8e80a722003-02-18 19:22:22 +00006849
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006850 /* Normal case */
6851 if (PyType_IsSubtype(Py_TYPE(obj), type)) {
6852 Py_INCREF(Py_TYPE(obj));
6853 return Py_TYPE(obj);
6854 }
6855 else {
6856 /* Try the slow way */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006857 PyObject *class_attr;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006858
Martin v. Löwisbfc6d742011-10-13 20:03:57 +02006859 class_attr = _PyObject_GetAttrId(obj, &PyId___class__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006860 if (class_attr != NULL &&
6861 PyType_Check(class_attr) &&
6862 (PyTypeObject *)class_attr != Py_TYPE(obj))
6863 {
6864 int ok = PyType_IsSubtype(
6865 (PyTypeObject *)class_attr, type);
6866 if (ok)
6867 return (PyTypeObject *)class_attr;
6868 }
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006869
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006870 if (class_attr == NULL)
6871 PyErr_Clear();
6872 else
6873 Py_DECREF(class_attr);
6874 }
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006875
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006876 PyErr_SetString(PyExc_TypeError,
6877 "super(type, obj): "
6878 "obj must be an instance or subtype of type");
6879 return NULL;
Guido van Rossum5b443c62001-12-03 15:38:28 +00006880}
6881
Guido van Rossum705f0f52001-08-24 16:47:00 +00006882static PyObject *
6883super_descr_get(PyObject *self, PyObject *obj, PyObject *type)
6884{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006885 superobject *su = (superobject *)self;
6886 superobject *newobj;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006887
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006888 if (obj == NULL || obj == Py_None || su->obj != NULL) {
6889 /* Not binding to an object, or already bound */
6890 Py_INCREF(self);
6891 return self;
6892 }
6893 if (Py_TYPE(su) != &PySuper_Type)
6894 /* If su is an instance of a (strict) subclass of super,
6895 call its type */
6896 return PyObject_CallFunctionObjArgs((PyObject *)Py_TYPE(su),
6897 su->type, obj, NULL);
6898 else {
6899 /* Inline the common case */
6900 PyTypeObject *obj_type = supercheck(su->type, obj);
6901 if (obj_type == NULL)
6902 return NULL;
6903 newobj = (superobject *)PySuper_Type.tp_new(&PySuper_Type,
6904 NULL, NULL);
6905 if (newobj == NULL)
6906 return NULL;
6907 Py_INCREF(su->type);
6908 Py_INCREF(obj);
6909 newobj->type = su->type;
6910 newobj->obj = obj;
6911 newobj->obj_type = obj_type;
6912 return (PyObject *)newobj;
6913 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00006914}
6915
6916static int
6917super_init(PyObject *self, PyObject *args, PyObject *kwds)
6918{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006919 superobject *su = (superobject *)self;
6920 PyTypeObject *type = NULL;
6921 PyObject *obj = NULL;
6922 PyTypeObject *obj_type = NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006923
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006924 if (!_PyArg_NoKeywords("super", kwds))
6925 return -1;
6926 if (!PyArg_ParseTuple(args, "|O!O:super", &PyType_Type, &type, &obj))
6927 return -1;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00006928
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006929 if (type == NULL) {
6930 /* Call super(), without args -- fill in from __class__
6931 and first local variable on the stack. */
6932 PyFrameObject *f = PyThreadState_GET()->frame;
6933 PyCodeObject *co = f->f_code;
Victor Stinner0fcab4a2011-01-04 12:59:15 +00006934 Py_ssize_t i, n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006935 if (co == NULL) {
Benjamin Peterson6a42bd62012-09-01 23:04:38 -04006936 PyErr_SetString(PyExc_RuntimeError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006937 "super(): no code object");
6938 return -1;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00006939 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006940 if (co->co_argcount == 0) {
Benjamin Peterson6a42bd62012-09-01 23:04:38 -04006941 PyErr_SetString(PyExc_RuntimeError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006942 "super(): no arguments");
6943 return -1;
6944 }
6945 obj = f->f_localsplus[0];
Benjamin Peterson159ae412013-05-12 18:16:06 -05006946 if (obj == NULL && co->co_cell2arg) {
6947 /* The first argument might be a cell. */
6948 n = PyTuple_GET_SIZE(co->co_cellvars);
6949 for (i = 0; i < n; i++) {
6950 if (co->co_cell2arg[i] == 0) {
6951 PyObject *cell = f->f_localsplus[co->co_nlocals + i];
6952 assert(PyCell_Check(cell));
6953 obj = PyCell_GET(cell);
6954 break;
6955 }
6956 }
Guido van Rossum6832c812013-05-10 08:47:42 -07006957 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006958 if (obj == NULL) {
Benjamin Peterson6a42bd62012-09-01 23:04:38 -04006959 PyErr_SetString(PyExc_RuntimeError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006960 "super(): arg[0] deleted");
6961 return -1;
6962 }
6963 if (co->co_freevars == NULL)
6964 n = 0;
6965 else {
6966 assert(PyTuple_Check(co->co_freevars));
6967 n = PyTuple_GET_SIZE(co->co_freevars);
6968 }
6969 for (i = 0; i < n; i++) {
6970 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
6971 assert(PyUnicode_Check(name));
Victor Stinnerad14ccd2013-11-07 00:46:04 +01006972 if (!_PyUnicode_CompareWithId(name, &PyId___class__)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006973 Py_ssize_t index = co->co_nlocals +
6974 PyTuple_GET_SIZE(co->co_cellvars) + i;
6975 PyObject *cell = f->f_localsplus[index];
6976 if (cell == NULL || !PyCell_Check(cell)) {
Benjamin Peterson6a42bd62012-09-01 23:04:38 -04006977 PyErr_SetString(PyExc_RuntimeError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006978 "super(): bad __class__ cell");
6979 return -1;
6980 }
6981 type = (PyTypeObject *) PyCell_GET(cell);
6982 if (type == NULL) {
Benjamin Peterson6a42bd62012-09-01 23:04:38 -04006983 PyErr_SetString(PyExc_RuntimeError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006984 "super(): empty __class__ cell");
6985 return -1;
6986 }
6987 if (!PyType_Check(type)) {
Benjamin Peterson6a42bd62012-09-01 23:04:38 -04006988 PyErr_Format(PyExc_RuntimeError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006989 "super(): __class__ is not a type (%s)",
6990 Py_TYPE(type)->tp_name);
6991 return -1;
6992 }
6993 break;
6994 }
6995 }
6996 if (type == NULL) {
Benjamin Peterson6a42bd62012-09-01 23:04:38 -04006997 PyErr_SetString(PyExc_RuntimeError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006998 "super(): __class__ cell not found");
6999 return -1;
7000 }
7001 }
Guido van Rossumcd16bf62007-06-13 18:07:49 +00007002
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007003 if (obj == Py_None)
7004 obj = NULL;
7005 if (obj != NULL) {
7006 obj_type = supercheck(type, obj);
7007 if (obj_type == NULL)
7008 return -1;
7009 Py_INCREF(obj);
7010 }
7011 Py_INCREF(type);
7012 su->type = type;
7013 su->obj = obj;
7014 su->obj_type = obj_type;
7015 return 0;
Guido van Rossum705f0f52001-08-24 16:47:00 +00007016}
7017
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007018PyDoc_STRVAR(super_doc,
Guido van Rossumcd16bf62007-06-13 18:07:49 +00007019"super() -> same as super(__class__, <first argument>)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00007020"super(type) -> unbound super object\n"
7021"super(type, obj) -> bound super object; requires isinstance(obj, type)\n"
Guido van Rossume705ef12001-08-29 15:47:06 +00007022"super(type, type2) -> bound super object; requires issubclass(type2, type)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00007023"Typical use to call a cooperative superclass method:\n"
7024"class C(B):\n"
7025" def meth(self, arg):\n"
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007026" super().meth(arg)\n"
Guido van Rossumcd16bf62007-06-13 18:07:49 +00007027"This works for class methods too:\n"
7028"class C(B):\n"
7029" @classmethod\n"
7030" def cmeth(cls, arg):\n"
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007031" super().cmeth(arg)\n");
Guido van Rossum705f0f52001-08-24 16:47:00 +00007032
Guido van Rossum048eb752001-10-02 21:24:57 +00007033static int
7034super_traverse(PyObject *self, visitproc visit, void *arg)
7035{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007036 superobject *su = (superobject *)self;
Guido van Rossum048eb752001-10-02 21:24:57 +00007037
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007038 Py_VISIT(su->obj);
7039 Py_VISIT(su->type);
7040 Py_VISIT(su->obj_type);
Guido van Rossum048eb752001-10-02 21:24:57 +00007041
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007042 return 0;
Guido van Rossum048eb752001-10-02 21:24:57 +00007043}
7044
Guido van Rossum705f0f52001-08-24 16:47:00 +00007045PyTypeObject PySuper_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007046 PyVarObject_HEAD_INIT(&PyType_Type, 0)
7047 "super", /* tp_name */
7048 sizeof(superobject), /* tp_basicsize */
7049 0, /* tp_itemsize */
7050 /* methods */
7051 super_dealloc, /* tp_dealloc */
7052 0, /* tp_print */
7053 0, /* tp_getattr */
7054 0, /* tp_setattr */
7055 0, /* tp_reserved */
7056 super_repr, /* tp_repr */
7057 0, /* tp_as_number */
7058 0, /* tp_as_sequence */
7059 0, /* tp_as_mapping */
7060 0, /* tp_hash */
7061 0, /* tp_call */
7062 0, /* tp_str */
7063 super_getattro, /* tp_getattro */
7064 0, /* tp_setattro */
7065 0, /* tp_as_buffer */
7066 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
7067 Py_TPFLAGS_BASETYPE, /* tp_flags */
7068 super_doc, /* tp_doc */
7069 super_traverse, /* tp_traverse */
7070 0, /* tp_clear */
7071 0, /* tp_richcompare */
7072 0, /* tp_weaklistoffset */
7073 0, /* tp_iter */
7074 0, /* tp_iternext */
7075 0, /* tp_methods */
7076 super_members, /* tp_members */
7077 0, /* tp_getset */
7078 0, /* tp_base */
7079 0, /* tp_dict */
7080 super_descr_get, /* tp_descr_get */
7081 0, /* tp_descr_set */
7082 0, /* tp_dictoffset */
7083 super_init, /* tp_init */
7084 PyType_GenericAlloc, /* tp_alloc */
7085 PyType_GenericNew, /* tp_new */
7086 PyObject_GC_Del, /* tp_free */
Guido van Rossum705f0f52001-08-24 16:47:00 +00007087};