blob: 6ea8e1dc83fab12d7685f5e055c291dc2699805c [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
Guido van Rossum6f799372001-09-20 20:46:19 +00009static PyMemberDef type_members[] = {
Tim Peters6d6c1a32001-08-02 04:15:00 +000010 {"__basicsize__", T_INT, offsetof(PyTypeObject,tp_basicsize),READONLY},
11 {"__itemsize__", T_INT, offsetof(PyTypeObject, tp_itemsize), READONLY},
12 {"__flags__", T_LONG, offsetof(PyTypeObject, tp_flags), READONLY},
Guido van Rossum9676b222001-08-17 20:32:36 +000013 {"__weakrefoffset__", T_LONG,
Tim Peters6d6c1a32001-08-02 04:15:00 +000014 offsetof(PyTypeObject, tp_weaklistoffset), READONLY},
15 {"__base__", T_OBJECT, offsetof(PyTypeObject, tp_base), READONLY},
16 {"__dictoffset__", T_LONG,
17 offsetof(PyTypeObject, tp_dictoffset), READONLY},
Tim Peters6d6c1a32001-08-02 04:15:00 +000018 {"__mro__", T_OBJECT, offsetof(PyTypeObject, tp_mro), READONLY},
19 {0}
20};
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000021
Guido van Rossumc0b618a1997-05-02 03:12:38 +000022static PyObject *
Guido van Rossumc3542212001-08-16 09:18:56 +000023type_name(PyTypeObject *type, void *context)
24{
Jeremy Hyltonaf68c872005-12-10 18:50:16 +000025 const char *s;
Guido van Rossumc3542212001-08-16 09:18:56 +000026
Michael W. Hudsonade8c8b22002-11-27 16:29:26 +000027 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
Guido van Rossume5c691a2003-03-07 15:13:17 +000028 PyHeapTypeObject* et = (PyHeapTypeObject*)type;
Tim Petersea7f75d2002-12-07 21:39:16 +000029
Georg Brandlc255c7b2006-02-20 22:27:28 +000030 Py_INCREF(et->ht_name);
31 return et->ht_name;
Michael W. Hudsonade8c8b22002-11-27 16:29:26 +000032 }
33 else {
34 s = strrchr(type->tp_name, '.');
35 if (s == NULL)
36 s = type->tp_name;
37 else
38 s++;
Martin v. Löwis5b222132007-06-10 09:51:05 +000039 return PyUnicode_FromString(s);
Michael W. Hudsonade8c8b22002-11-27 16:29:26 +000040 }
Guido van Rossumc3542212001-08-16 09:18:56 +000041}
42
Michael W. Hudson98bbc492002-11-26 14:47:27 +000043static int
44type_set_name(PyTypeObject *type, PyObject *value, void *context)
45{
Guido van Rossume5c691a2003-03-07 15:13:17 +000046 PyHeapTypeObject* et;
Michael W. Hudson98bbc492002-11-26 14:47:27 +000047
48 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
49 PyErr_Format(PyExc_TypeError,
50 "can't set %s.__name__", type->tp_name);
51 return -1;
52 }
53 if (!value) {
54 PyErr_Format(PyExc_TypeError,
55 "can't delete %s.__name__", type->tp_name);
56 return -1;
57 }
Thomas Hellerace8ba82007-07-11 20:01:43 +000058 if (PyUnicode_Check(value)) {
59 value = _PyUnicode_AsDefaultEncodedString(value, NULL);
Guido van Rossum55b4a7b2007-07-11 09:28:11 +000060 if (value == NULL)
61 return -1;
62 }
Thomas Hellerace8ba82007-07-11 20:01:43 +000063 if (!PyString_Check(value)) {
Michael W. Hudson98bbc492002-11-26 14:47:27 +000064 PyErr_Format(PyExc_TypeError,
65 "can only assign string to %s.__name__, not '%s'",
Martin v. Löwis9f2e3462007-07-21 17:22:18 +000066 type->tp_name, Py_Type(value)->tp_name);
Michael W. Hudson98bbc492002-11-26 14:47:27 +000067 return -1;
68 }
Thomas Hellerace8ba82007-07-11 20:01:43 +000069 if (strlen(PyString_AS_STRING(value))
70 != (size_t)PyString_GET_SIZE(value)) {
Michael W. Hudson98bbc492002-11-26 14:47:27 +000071 PyErr_Format(PyExc_ValueError,
72 "__name__ must not contain null bytes");
73 return -1;
74 }
75
Guido van Rossume5c691a2003-03-07 15:13:17 +000076 et = (PyHeapTypeObject*)type;
Michael W. Hudson98bbc492002-11-26 14:47:27 +000077
78 Py_INCREF(value);
79
Georg Brandlc255c7b2006-02-20 22:27:28 +000080 Py_DECREF(et->ht_name);
81 et->ht_name = value;
Michael W. Hudson98bbc492002-11-26 14:47:27 +000082
Thomas Hellerace8ba82007-07-11 20:01:43 +000083 type->tp_name = PyString_AS_STRING(value);
Michael W. Hudson98bbc492002-11-26 14:47:27 +000084
85 return 0;
86}
87
Guido van Rossumc3542212001-08-16 09:18:56 +000088static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +000089type_module(PyTypeObject *type, void *context)
Guido van Rossum29ca26e1995-01-07 11:58:15 +000090{
Guido van Rossumc3542212001-08-16 09:18:56 +000091 PyObject *mod;
92 char *s;
93
Michael W. Hudsonade8c8b22002-11-27 16:29:26 +000094 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
95 mod = PyDict_GetItemString(type->tp_dict, "__module__");
Anthony Baxter3ecdb252004-06-11 14:41:18 +000096 if (!mod) {
97 PyErr_Format(PyExc_AttributeError, "__module__");
98 return 0;
99 }
Michael W. Hudsonade8c8b22002-11-27 16:29:26 +0000100 Py_XINCREF(mod);
Guido van Rossumc3542212001-08-16 09:18:56 +0000101 return mod;
102 }
Michael W. Hudsonade8c8b22002-11-27 16:29:26 +0000103 else {
104 s = strrchr(type->tp_name, '.');
105 if (s != NULL)
Martin v. Löwis5b222132007-06-10 09:51:05 +0000106 return PyUnicode_FromStringAndSize(
Thomas Wouters89f507f2006-12-13 04:49:30 +0000107 type->tp_name, (Py_ssize_t)(s - type->tp_name));
Martin v. Löwis5b222132007-06-10 09:51:05 +0000108 return PyUnicode_FromString("__builtin__");
Michael W. Hudsonade8c8b22002-11-27 16:29:26 +0000109 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000110}
111
Guido van Rossum3926a632001-09-25 16:25:58 +0000112static int
113type_set_module(PyTypeObject *type, PyObject *value, void *context)
114{
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000115 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
Guido van Rossum3926a632001-09-25 16:25:58 +0000116 PyErr_Format(PyExc_TypeError,
117 "can't set %s.__module__", type->tp_name);
118 return -1;
119 }
120 if (!value) {
121 PyErr_Format(PyExc_TypeError,
122 "can't delete %s.__module__", type->tp_name);
123 return -1;
124 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000125
Guido van Rossum3926a632001-09-25 16:25:58 +0000126 return PyDict_SetItemString(type->tp_dict, "__module__", value);
127}
128
Tim Peters6d6c1a32001-08-02 04:15:00 +0000129static PyObject *
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000130type_get_bases(PyTypeObject *type, void *context)
131{
132 Py_INCREF(type->tp_bases);
133 return type->tp_bases;
134}
135
136static PyTypeObject *best_base(PyObject *);
137static int mro_internal(PyTypeObject *);
138static int compatible_for_assignment(PyTypeObject *, PyTypeObject *, char *);
139static int add_subclass(PyTypeObject*, PyTypeObject*);
140static void remove_subclass(PyTypeObject *, PyTypeObject *);
141static void update_all_slots(PyTypeObject *);
142
Guido van Rossum8d24ee92003-03-24 23:49:49 +0000143typedef int (*update_callback)(PyTypeObject *, void *);
144static int update_subclasses(PyTypeObject *type, PyObject *name,
145 update_callback callback, void *data);
146static int recurse_down_subclasses(PyTypeObject *type, PyObject *name,
147 update_callback callback, void *data);
148
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000149static int
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000150mro_subclasses(PyTypeObject *type, PyObject* temp)
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000151{
152 PyTypeObject *subclass;
153 PyObject *ref, *subclasses, *old_mro;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000154 Py_ssize_t i, n;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000155
156 subclasses = type->tp_subclasses;
157 if (subclasses == NULL)
158 return 0;
159 assert(PyList_Check(subclasses));
160 n = PyList_GET_SIZE(subclasses);
161 for (i = 0; i < n; i++) {
162 ref = PyList_GET_ITEM(subclasses, i);
163 assert(PyWeakref_CheckRef(ref));
164 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
165 assert(subclass != NULL);
166 if ((PyObject *)subclass == Py_None)
167 continue;
168 assert(PyType_Check(subclass));
169 old_mro = subclass->tp_mro;
170 if (mro_internal(subclass) < 0) {
171 subclass->tp_mro = old_mro;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000172 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000173 }
174 else {
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000175 PyObject* tuple;
Raymond Hettinger8ae46892003-10-12 19:09:37 +0000176 tuple = PyTuple_Pack(2, subclass, old_mro);
Guido van Rossum19a02ba2003-04-15 22:09:45 +0000177 Py_DECREF(old_mro);
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000178 if (!tuple)
179 return -1;
180 if (PyList_Append(temp, tuple) < 0)
181 return -1;
Guido van Rossum19a02ba2003-04-15 22:09:45 +0000182 Py_DECREF(tuple);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000183 }
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000184 if (mro_subclasses(subclass, temp) < 0)
185 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000186 }
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000187 return 0;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000188}
189
190static int
191type_set_bases(PyTypeObject *type, PyObject *value, void *context)
192{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000193 Py_ssize_t i;
194 int r = 0;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000195 PyObject *ob, *temp;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000196 PyTypeObject *new_base, *old_base;
197 PyObject *old_bases, *old_mro;
198
199 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
200 PyErr_Format(PyExc_TypeError,
201 "can't set %s.__bases__", type->tp_name);
202 return -1;
203 }
204 if (!value) {
205 PyErr_Format(PyExc_TypeError,
206 "can't delete %s.__bases__", type->tp_name);
207 return -1;
208 }
209 if (!PyTuple_Check(value)) {
210 PyErr_Format(PyExc_TypeError,
211 "can only assign tuple to %s.__bases__, not %s",
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000212 type->tp_name, Py_Type(value)->tp_name);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000213 return -1;
214 }
Guido van Rossum3bbc0ee2002-12-13 17:49:38 +0000215 if (PyTuple_GET_SIZE(value) == 0) {
216 PyErr_Format(PyExc_TypeError,
217 "can only assign non-empty tuple to %s.__bases__, not ()",
218 type->tp_name);
219 return -1;
220 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000221 for (i = 0; i < PyTuple_GET_SIZE(value); i++) {
222 ob = PyTuple_GET_ITEM(value, i);
Guido van Rossum50e9fb92006-08-17 05:42:55 +0000223 if (!PyType_Check(ob)) {
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000224 PyErr_Format(
225 PyExc_TypeError,
226 "%s.__bases__ must be tuple of old- or new-style classes, not '%s'",
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000227 type->tp_name, Py_Type(ob)->tp_name);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000228 return -1;
229 }
Michael W. Hudsoncaf17be2002-11-27 10:24:44 +0000230 if (PyType_Check(ob)) {
231 if (PyType_IsSubtype((PyTypeObject*)ob, type)) {
232 PyErr_SetString(PyExc_TypeError,
233 "a __bases__ item causes an inheritance cycle");
234 return -1;
235 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000236 }
237 }
238
239 new_base = best_base(value);
240
241 if (!new_base) {
242 return -1;
243 }
244
245 if (!compatible_for_assignment(type->tp_base, new_base, "__bases__"))
246 return -1;
247
248 Py_INCREF(new_base);
249 Py_INCREF(value);
250
251 old_bases = type->tp_bases;
252 old_base = type->tp_base;
253 old_mro = type->tp_mro;
254
255 type->tp_bases = value;
256 type->tp_base = new_base;
257
258 if (mro_internal(type) < 0) {
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000259 goto bail;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000260 }
261
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000262 temp = PyList_New(0);
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000263 if (!temp)
264 goto bail;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000265
266 r = mro_subclasses(type, temp);
267
268 if (r < 0) {
269 for (i = 0; i < PyList_Size(temp); i++) {
270 PyTypeObject* cls;
271 PyObject* mro;
Raymond Hettinger8ae46892003-10-12 19:09:37 +0000272 PyArg_UnpackTuple(PyList_GET_ITEM(temp, i),
273 "", 2, 2, &cls, &mro);
Guido van Rossumd8faa362007-04-27 19:54:29 +0000274 Py_INCREF(mro);
275 ob = cls->tp_mro;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000276 cls->tp_mro = mro;
Guido van Rossumd8faa362007-04-27 19:54:29 +0000277 Py_DECREF(ob);
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000278 }
279 Py_DECREF(temp);
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000280 goto bail;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000281 }
282
283 Py_DECREF(temp);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000284
285 /* any base that was in __bases__ but now isn't, we
Raymond Hettingera8285862002-12-14 17:17:56 +0000286 need to remove |type| from its tp_subclasses.
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000287 conversely, any class now in __bases__ that wasn't
Raymond Hettingera8285862002-12-14 17:17:56 +0000288 needs to have |type| added to its subclasses. */
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000289
290 /* for now, sod that: just remove from all old_bases,
291 add to all new_bases */
292
293 for (i = PyTuple_GET_SIZE(old_bases) - 1; i >= 0; i--) {
294 ob = PyTuple_GET_ITEM(old_bases, i);
295 if (PyType_Check(ob)) {
296 remove_subclass(
297 (PyTypeObject*)ob, type);
298 }
299 }
300
301 for (i = PyTuple_GET_SIZE(value) - 1; i >= 0; i--) {
302 ob = PyTuple_GET_ITEM(value, i);
303 if (PyType_Check(ob)) {
304 if (add_subclass((PyTypeObject*)ob, type) < 0)
305 r = -1;
306 }
307 }
308
309 update_all_slots(type);
310
311 Py_DECREF(old_bases);
312 Py_DECREF(old_base);
313 Py_DECREF(old_mro);
314
315 return r;
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000316
317 bail:
Michael W. Hudsone723e452003-08-07 14:58:10 +0000318 Py_DECREF(type->tp_bases);
319 Py_DECREF(type->tp_base);
320 if (type->tp_mro != old_mro) {
321 Py_DECREF(type->tp_mro);
322 }
323
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000324 type->tp_bases = old_bases;
325 type->tp_base = old_base;
326 type->tp_mro = old_mro;
Tim Petersea7f75d2002-12-07 21:39:16 +0000327
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000328 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000329}
330
331static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000332type_dict(PyTypeObject *type, void *context)
333{
334 if (type->tp_dict == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000335 Py_INCREF(Py_None);
336 return Py_None;
Guido van Rossum29ca26e1995-01-07 11:58:15 +0000337 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000338 return PyDictProxy_New(type->tp_dict);
Guido van Rossum29ca26e1995-01-07 11:58:15 +0000339}
340
Tim Peters24008312002-03-17 18:56:20 +0000341static PyObject *
342type_get_doc(PyTypeObject *type, void *context)
343{
344 PyObject *result;
Guido van Rossum6ca7d412002-04-18 00:22:00 +0000345 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE) && type->tp_doc != NULL)
Neal Norwitza369c5a2007-08-25 07:41:59 +0000346 return PyUnicode_FromString(type->tp_doc);
Tim Peters24008312002-03-17 18:56:20 +0000347 result = PyDict_GetItemString(type->tp_dict, "__doc__");
Guido van Rossum6ca7d412002-04-18 00:22:00 +0000348 if (result == NULL) {
349 result = Py_None;
350 Py_INCREF(result);
351 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000352 else if (Py_Type(result)->tp_descr_get) {
353 result = Py_Type(result)->tp_descr_get(result, NULL,
Tim Peters2b858972002-04-18 04:12:28 +0000354 (PyObject *)type);
Guido van Rossum6ca7d412002-04-18 00:22:00 +0000355 }
356 else {
357 Py_INCREF(result);
358 }
Tim Peters24008312002-03-17 18:56:20 +0000359 return result;
360}
361
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000362static PyGetSetDef type_getsets[] = {
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000363 {"__name__", (getter)type_name, (setter)type_set_name, NULL},
364 {"__bases__", (getter)type_get_bases, (setter)type_set_bases, NULL},
Guido van Rossum3926a632001-09-25 16:25:58 +0000365 {"__module__", (getter)type_module, (setter)type_set_module, NULL},
Tim Peters6d6c1a32001-08-02 04:15:00 +0000366 {"__dict__", (getter)type_dict, NULL, NULL},
Tim Peters24008312002-03-17 18:56:20 +0000367 {"__doc__", (getter)type_get_doc, NULL, NULL},
Tim Peters6d6c1a32001-08-02 04:15:00 +0000368 {0}
369};
370
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000371static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000372type_repr(PyTypeObject *type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000373{
Barry Warsaw7ce36942001-08-24 18:34:26 +0000374 PyObject *mod, *name, *rtn;
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000375 char *kind;
Guido van Rossumc3542212001-08-16 09:18:56 +0000376
377 mod = type_module(type, NULL);
378 if (mod == NULL)
379 PyErr_Clear();
Martin v. Löwis5b222132007-06-10 09:51:05 +0000380 else if (!PyUnicode_Check(mod)) {
Guido van Rossumc3542212001-08-16 09:18:56 +0000381 Py_DECREF(mod);
382 mod = NULL;
383 }
384 name = type_name(type, NULL);
385 if (name == NULL)
386 return NULL;
Barry Warsaw7ce36942001-08-24 18:34:26 +0000387
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000388 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
389 kind = "class";
390 else
391 kind = "type";
392
Walter Dörwald75163602007-06-11 15:47:13 +0000393 if (mod != NULL && PyUnicode_CompareWithASCIIString(mod, "__builtin__"))
394 rtn = PyUnicode_FromFormat("<%s '%U.%U'>", kind, mod, name);
Guido van Rossumc3542212001-08-16 09:18:56 +0000395 else
Walter Dörwald1ab83302007-05-18 17:15:44 +0000396 rtn = PyUnicode_FromFormat("<%s '%s'>", kind, type->tp_name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000397
Guido van Rossumc3542212001-08-16 09:18:56 +0000398 Py_XDECREF(mod);
399 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000400 return rtn;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000401}
402
Tim Peters6d6c1a32001-08-02 04:15:00 +0000403static PyObject *
404type_call(PyTypeObject *type, PyObject *args, PyObject *kwds)
405{
406 PyObject *obj;
407
408 if (type->tp_new == NULL) {
409 PyErr_Format(PyExc_TypeError,
410 "cannot create '%.100s' instances",
411 type->tp_name);
412 return NULL;
413 }
414
Tim Peters3f996e72001-09-13 19:18:27 +0000415 obj = type->tp_new(type, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000416 if (obj != NULL) {
Guido van Rossumf76de622001-10-18 15:49:21 +0000417 /* Ugly exception: when the call was type(something),
418 don't call tp_init on the result. */
419 if (type == &PyType_Type &&
420 PyTuple_Check(args) && PyTuple_GET_SIZE(args) == 1 &&
421 (kwds == NULL ||
422 (PyDict_Check(kwds) && PyDict_Size(kwds) == 0)))
423 return obj;
Guido van Rossum8ace1ab2002-04-06 01:05:01 +0000424 /* If the returned object is not an instance of type,
425 it won't be initialized. */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000426 if (!PyType_IsSubtype(Py_Type(obj), type))
Guido van Rossum8ace1ab2002-04-06 01:05:01 +0000427 return obj;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000428 type = Py_Type(obj);
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +0000429 if (type->tp_init != NULL &&
Tim Peters6d6c1a32001-08-02 04:15:00 +0000430 type->tp_init(obj, args, kwds) < 0) {
431 Py_DECREF(obj);
432 obj = NULL;
433 }
434 }
435 return obj;
436}
437
438PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000439PyType_GenericAlloc(PyTypeObject *type, Py_ssize_t nitems)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000440{
Tim Peters6d6c1a32001-08-02 04:15:00 +0000441 PyObject *obj;
Guido van Rossume5c691a2003-03-07 15:13:17 +0000442 const size_t size = _PyObject_VAR_SIZE(type, nitems+1);
443 /* note that we need to add one, for the sentinel */
Tim Peters406fe3b2001-10-06 19:04:01 +0000444
445 if (PyType_IS_GC(type))
Neil Schemenauer09a2ae52002-04-12 03:06:53 +0000446 obj = _PyObject_GC_Malloc(size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000447 else
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000448 obj = (PyObject *)PyObject_MALLOC(size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000449
Neil Schemenauerc806c882001-08-29 23:54:54 +0000450 if (obj == NULL)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000451 return PyErr_NoMemory();
Tim Peters406fe3b2001-10-06 19:04:01 +0000452
Neil Schemenauerc806c882001-08-29 23:54:54 +0000453 memset(obj, '\0', size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000454
Tim Peters6d6c1a32001-08-02 04:15:00 +0000455 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
456 Py_INCREF(type);
Tim Peters406fe3b2001-10-06 19:04:01 +0000457
Tim Peters6d6c1a32001-08-02 04:15:00 +0000458 if (type->tp_itemsize == 0)
459 PyObject_INIT(obj, type);
460 else
461 (void) PyObject_INIT_VAR((PyVarObject *)obj, type, nitems);
Tim Peters406fe3b2001-10-06 19:04:01 +0000462
Tim Peters6d6c1a32001-08-02 04:15:00 +0000463 if (PyType_IS_GC(type))
Neil Schemenauerc806c882001-08-29 23:54:54 +0000464 _PyObject_GC_TRACK(obj);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000465 return obj;
466}
467
468PyObject *
469PyType_GenericNew(PyTypeObject *type, PyObject *args, PyObject *kwds)
470{
471 return type->tp_alloc(type, 0);
472}
473
Guido van Rossum9475a232001-10-05 20:51:39 +0000474/* Helpers for subtyping */
475
476static int
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000477traverse_slots(PyTypeObject *type, PyObject *self, visitproc visit, void *arg)
478{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000479 Py_ssize_t i, n;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000480 PyMemberDef *mp;
481
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000482 n = Py_Size(type);
Guido van Rossume5c691a2003-03-07 15:13:17 +0000483 mp = PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000484 for (i = 0; i < n; i++, mp++) {
485 if (mp->type == T_OBJECT_EX) {
486 char *addr = (char *)self + mp->offset;
487 PyObject *obj = *(PyObject **)addr;
488 if (obj != NULL) {
489 int err = visit(obj, arg);
490 if (err)
491 return err;
492 }
493 }
494 }
495 return 0;
496}
497
498static int
Guido van Rossum9475a232001-10-05 20:51:39 +0000499subtype_traverse(PyObject *self, visitproc visit, void *arg)
500{
501 PyTypeObject *type, *base;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000502 traverseproc basetraverse;
Guido van Rossum9475a232001-10-05 20:51:39 +0000503
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000504 /* Find the nearest base with a different tp_traverse,
505 and traverse slots while we're at it */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000506 type = Py_Type(self);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000507 base = type;
508 while ((basetraverse = base->tp_traverse) == subtype_traverse) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000509 if (Py_Size(base)) {
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000510 int err = traverse_slots(base, self, visit, arg);
511 if (err)
512 return err;
513 }
Guido van Rossum9475a232001-10-05 20:51:39 +0000514 base = base->tp_base;
515 assert(base);
516 }
517
518 if (type->tp_dictoffset != base->tp_dictoffset) {
519 PyObject **dictptr = _PyObject_GetDictPtr(self);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000520 if (dictptr && *dictptr)
521 Py_VISIT(*dictptr);
Guido van Rossum9475a232001-10-05 20:51:39 +0000522 }
523
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000524 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
Guido van Rossuma3862092002-06-10 15:24:42 +0000525 /* For a heaptype, the instances count as references
Guido van Rossumd8faa362007-04-27 19:54:29 +0000526 to the type. Traverse the type so the collector
Guido van Rossuma3862092002-06-10 15:24:42 +0000527 can find cycles involving this link. */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000528 Py_VISIT(type);
Guido van Rossuma3862092002-06-10 15:24:42 +0000529
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000530 if (basetraverse)
531 return basetraverse(self, visit, arg);
532 return 0;
533}
534
535static void
536clear_slots(PyTypeObject *type, PyObject *self)
537{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000538 Py_ssize_t i, n;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000539 PyMemberDef *mp;
540
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000541 n = Py_Size(type);
Guido van Rossume5c691a2003-03-07 15:13:17 +0000542 mp = PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000543 for (i = 0; i < n; i++, mp++) {
544 if (mp->type == T_OBJECT_EX && !(mp->flags & READONLY)) {
545 char *addr = (char *)self + mp->offset;
546 PyObject *obj = *(PyObject **)addr;
547 if (obj != NULL) {
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000548 *(PyObject **)addr = NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000549 Py_DECREF(obj);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000550 }
551 }
552 }
553}
554
555static int
556subtype_clear(PyObject *self)
557{
558 PyTypeObject *type, *base;
559 inquiry baseclear;
560
561 /* Find the nearest base with a different tp_clear
562 and clear slots while we're at it */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000563 type = Py_Type(self);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000564 base = type;
565 while ((baseclear = base->tp_clear) == subtype_clear) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000566 if (Py_Size(base))
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000567 clear_slots(base, self);
568 base = base->tp_base;
569 assert(base);
570 }
571
Guido van Rossuma3862092002-06-10 15:24:42 +0000572 /* There's no need to clear the instance dict (if any);
573 the collector will call its tp_clear handler. */
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000574
575 if (baseclear)
576 return baseclear(self);
Guido van Rossum9475a232001-10-05 20:51:39 +0000577 return 0;
578}
Tim Peters6d6c1a32001-08-02 04:15:00 +0000579
580static void
581subtype_dealloc(PyObject *self)
582{
Guido van Rossum14227b42001-12-06 02:35:58 +0000583 PyTypeObject *type, *base;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000584 destructor basedealloc;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000585
Guido van Rossum22b13872002-08-06 21:41:44 +0000586 /* Extract the type; we expect it to be a heap type */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000587 type = Py_Type(self);
Guido van Rossum22b13872002-08-06 21:41:44 +0000588 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000589
Guido van Rossum22b13872002-08-06 21:41:44 +0000590 /* Test whether the type has GC exactly once */
591
592 if (!PyType_IS_GC(type)) {
593 /* It's really rare to find a dynamic type that doesn't have
594 GC; it can only happen when deriving from 'object' and not
595 adding any slots or instance variables. This allows
596 certain simplifications: there's no need to call
597 clear_slots(), or DECREF the dict, or clear weakrefs. */
598
599 /* Maybe call finalizer; exit early if resurrected */
Guido van Rossumfebd61d2002-08-08 20:55:20 +0000600 if (type->tp_del) {
601 type->tp_del(self);
602 if (self->ob_refcnt > 0)
603 return;
604 }
Guido van Rossum22b13872002-08-06 21:41:44 +0000605
606 /* Find the nearest base with a different tp_dealloc */
607 base = type;
608 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000609 assert(Py_Size(base) == 0);
Guido van Rossum22b13872002-08-06 21:41:44 +0000610 base = base->tp_base;
611 assert(base);
612 }
613
614 /* Call the base tp_dealloc() */
615 assert(basedealloc);
616 basedealloc(self);
617
618 /* Can't reference self beyond this point */
619 Py_DECREF(type);
620
621 /* Done */
622 return;
623 }
624
625 /* We get here only if the type has GC */
626
627 /* UnTrack and re-Track around the trashcan macro, alas */
Andrew M. Kuchlingc9172d32003-02-06 15:22:49 +0000628 /* See explanation at end of function for full disclosure */
Guido van Rossum0906e072002-08-07 20:42:09 +0000629 PyObject_GC_UnTrack(self);
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000630 ++_PyTrash_delete_nesting;
Guido van Rossum22b13872002-08-06 21:41:44 +0000631 Py_TRASHCAN_SAFE_BEGIN(self);
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000632 --_PyTrash_delete_nesting;
Tim Petersf7f9e992003-11-13 21:59:32 +0000633 /* DO NOT restore GC tracking at this point. weakref callbacks
634 * (if any, and whether directly here or indirectly in something we
635 * call) may trigger GC, and if self is tracked at that point, it
636 * will look like trash to GC and GC will try to delete self again.
Tim Petersadd09b42003-11-12 20:43:28 +0000637 */
Guido van Rossum22b13872002-08-06 21:41:44 +0000638
Guido van Rossum59195fd2003-06-13 20:54:40 +0000639 /* Find the nearest base with a different tp_dealloc */
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000640 base = type;
641 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
Tim Peters6d6c1a32001-08-02 04:15:00 +0000642 base = base->tp_base;
643 assert(base);
Guido van Rossum14227b42001-12-06 02:35:58 +0000644 }
645
Guido van Rossumd8faa362007-04-27 19:54:29 +0000646 /* If we added a weaklist, we clear it. Do this *before* calling
Guido van Rossum59195fd2003-06-13 20:54:40 +0000647 the finalizer (__del__), clearing slots, or clearing the instance
648 dict. */
649
Guido van Rossum1987c662003-05-29 14:29:23 +0000650 if (type->tp_weaklistoffset && !base->tp_weaklistoffset)
651 PyObject_ClearWeakRefs(self);
652
653 /* Maybe call finalizer; exit early if resurrected */
654 if (type->tp_del) {
Tim Petersf7f9e992003-11-13 21:59:32 +0000655 _PyObject_GC_TRACK(self);
Guido van Rossum1987c662003-05-29 14:29:23 +0000656 type->tp_del(self);
657 if (self->ob_refcnt > 0)
Tim Petersf7f9e992003-11-13 21:59:32 +0000658 goto endlabel; /* resurrected */
659 else
660 _PyObject_GC_UNTRACK(self);
Thomas Woutersb2137042007-02-01 18:02:27 +0000661 /* New weakrefs could be created during the finalizer call.
662 If this occurs, clear them out without calling their
663 finalizers since they might rely on part of the object
664 being finalized that has already been destroyed. */
665 if (type->tp_weaklistoffset && !base->tp_weaklistoffset) {
666 /* Modeled after GET_WEAKREFS_LISTPTR() */
667 PyWeakReference **list = (PyWeakReference **) \
668 PyObject_GET_WEAKREFS_LISTPTR(self);
669 while (*list)
670 _PyWeakref_ClearRef(*list);
671 }
Guido van Rossum1987c662003-05-29 14:29:23 +0000672 }
673
Guido van Rossum59195fd2003-06-13 20:54:40 +0000674 /* Clear slots up to the nearest base with a different tp_dealloc */
675 base = type;
676 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000677 if (Py_Size(base))
Guido van Rossum59195fd2003-06-13 20:54:40 +0000678 clear_slots(base, self);
679 base = base->tp_base;
680 assert(base);
681 }
682
Tim Peters6d6c1a32001-08-02 04:15:00 +0000683 /* If we added a dict, DECREF it */
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000684 if (type->tp_dictoffset && !base->tp_dictoffset) {
685 PyObject **dictptr = _PyObject_GetDictPtr(self);
686 if (dictptr != NULL) {
687 PyObject *dict = *dictptr;
688 if (dict != NULL) {
689 Py_DECREF(dict);
690 *dictptr = NULL;
691 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000692 }
693 }
694
Tim Peters0bd743c2003-11-13 22:50:00 +0000695 /* Call the base tp_dealloc(); first retrack self if
696 * basedealloc knows about gc.
697 */
698 if (PyType_IS_GC(base))
699 _PyObject_GC_TRACK(self);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000700 assert(basedealloc);
701 basedealloc(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000702
703 /* Can't reference self beyond this point */
Guido van Rossum22b13872002-08-06 21:41:44 +0000704 Py_DECREF(type);
705
Guido van Rossum0906e072002-08-07 20:42:09 +0000706 endlabel:
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000707 ++_PyTrash_delete_nesting;
Guido van Rossum22b13872002-08-06 21:41:44 +0000708 Py_TRASHCAN_SAFE_END(self);
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000709 --_PyTrash_delete_nesting;
710
711 /* Explanation of the weirdness around the trashcan macros:
712
713 Q. What do the trashcan macros do?
714
715 A. Read the comment titled "Trashcan mechanism" in object.h.
716 For one, this explains why there must be a call to GC-untrack
Guido van Rossumd8faa362007-04-27 19:54:29 +0000717 before the trashcan begin macro. Without understanding the
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000718 trashcan code, the answers to the following questions don't make
719 sense.
720
721 Q. Why do we GC-untrack before the trashcan and then immediately
722 GC-track again afterward?
723
724 A. In the case that the base class is GC-aware, the base class
Guido van Rossumd8faa362007-04-27 19:54:29 +0000725 probably GC-untracks the object. If it does that using the
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000726 UNTRACK macro, this will crash when the object is already
727 untracked. Because we don't know what the base class does, the
728 only safe thing is to make sure the object is tracked when we
729 call the base class dealloc. But... The trashcan begin macro
730 requires that the object is *untracked* before it is called. So
731 the dance becomes:
732
Guido van Rossumd8faa362007-04-27 19:54:29 +0000733 GC untrack
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000734 trashcan begin
735 GC track
736
Guido van Rossumd8faa362007-04-27 19:54:29 +0000737 Q. Why did the last question say "immediately GC-track again"?
738 It's nowhere near immediately.
Tim Petersf7f9e992003-11-13 21:59:32 +0000739
Guido van Rossumd8faa362007-04-27 19:54:29 +0000740 A. Because the code *used* to re-track immediately. Bad Idea.
741 self has a refcount of 0, and if gc ever gets its hands on it
742 (which can happen if any weakref callback gets invoked), it
743 looks like trash to gc too, and gc also tries to delete self
744 then. But we're already deleting self. Double dealloction is
745 a subtle disaster.
Tim Petersf7f9e992003-11-13 21:59:32 +0000746
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000747 Q. Why the bizarre (net-zero) manipulation of
748 _PyTrash_delete_nesting around the trashcan macros?
749
750 A. Some base classes (e.g. list) also use the trashcan mechanism.
751 The following scenario used to be possible:
752
753 - suppose the trashcan level is one below the trashcan limit
754
755 - subtype_dealloc() is called
756
757 - the trashcan limit is not yet reached, so the trashcan level
Guido van Rossumd8faa362007-04-27 19:54:29 +0000758 is incremented and the code between trashcan begin and end is
759 executed
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000760
761 - this destroys much of the object's contents, including its
Guido van Rossumd8faa362007-04-27 19:54:29 +0000762 slots and __dict__
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000763
764 - basedealloc() is called; this is really list_dealloc(), or
Guido van Rossumd8faa362007-04-27 19:54:29 +0000765 some other type which also uses the trashcan macros
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000766
767 - the trashcan limit is now reached, so the object is put on the
Guido van Rossumd8faa362007-04-27 19:54:29 +0000768 trashcan's to-be-deleted-later list
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000769
770 - basedealloc() returns
771
772 - subtype_dealloc() decrefs the object's type
773
774 - subtype_dealloc() returns
775
776 - later, the trashcan code starts deleting the objects from its
Guido van Rossumd8faa362007-04-27 19:54:29 +0000777 to-be-deleted-later list
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000778
779 - subtype_dealloc() is called *AGAIN* for the same object
780
781 - at the very least (if the destroyed slots and __dict__ don't
Guido van Rossumd8faa362007-04-27 19:54:29 +0000782 cause problems) the object's type gets decref'ed a second
783 time, which is *BAD*!!!
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000784
785 The remedy is to make sure that if the code between trashcan
786 begin and end in subtype_dealloc() is called, the code between
787 trashcan begin and end in basedealloc() will also be called.
788 This is done by decrementing the level after passing into the
789 trashcan block, and incrementing it just before leaving the
790 block.
791
792 But now it's possible that a chain of objects consisting solely
793 of objects whose deallocator is subtype_dealloc() will defeat
794 the trashcan mechanism completely: the decremented level means
Guido van Rossumd8faa362007-04-27 19:54:29 +0000795 that the effective level never reaches the limit. Therefore, we
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000796 *increment* the level *before* entering the trashcan block, and
797 matchingly decrement it after leaving. This means the trashcan
798 code will trigger a little early, but that's no big deal.
799
800 Q. Are there any live examples of code in need of all this
801 complexity?
802
803 A. Yes. See SF bug 668433 for code that crashed (when Python was
804 compiled in debug mode) before the trashcan level manipulations
805 were added. For more discussion, see SF patches 581742, 575073
806 and bug 574207.
807 */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000808}
809
Jeremy Hylton938ace62002-07-17 16:30:39 +0000810static PyTypeObject *solid_base(PyTypeObject *type);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000811
Tim Peters6d6c1a32001-08-02 04:15:00 +0000812/* type test with subclassing support */
813
814int
815PyType_IsSubtype(PyTypeObject *a, PyTypeObject *b)
816{
817 PyObject *mro;
818
819 mro = a->tp_mro;
820 if (mro != NULL) {
821 /* Deal with multiple inheritance without recursion
822 by walking the MRO tuple */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000823 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000824 assert(PyTuple_Check(mro));
825 n = PyTuple_GET_SIZE(mro);
826 for (i = 0; i < n; i++) {
827 if (PyTuple_GET_ITEM(mro, i) == (PyObject *)b)
828 return 1;
829 }
830 return 0;
831 }
832 else {
833 /* a is not completely initilized yet; follow tp_base */
834 do {
835 if (a == b)
836 return 1;
837 a = a->tp_base;
838 } while (a != NULL);
839 return b == &PyBaseObject_Type;
840 }
841}
842
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000843/* Internal routines to do a method lookup in the type
Guido van Rossum60718732001-08-28 17:47:51 +0000844 without looking in the instance dictionary
845 (so we can't use PyObject_GetAttr) but still binding
Guido van Rossumd8faa362007-04-27 19:54:29 +0000846 it to the instance. The arguments are the object,
Guido van Rossum60718732001-08-28 17:47:51 +0000847 the method name as a C string, and the address of a
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000848 static variable used to cache the interned Python string.
849
850 Two variants:
851
852 - lookup_maybe() returns NULL without raising an exception
853 when the _PyType_Lookup() call fails;
854
855 - lookup_method() always raises an exception upon errors.
856*/
Guido van Rossum60718732001-08-28 17:47:51 +0000857
858static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000859lookup_maybe(PyObject *self, char *attrstr, PyObject **attrobj)
Guido van Rossum60718732001-08-28 17:47:51 +0000860{
861 PyObject *res;
862
863 if (*attrobj == NULL) {
Martin v. Löwis5b222132007-06-10 09:51:05 +0000864 *attrobj = PyUnicode_InternFromString(attrstr);
Guido van Rossum60718732001-08-28 17:47:51 +0000865 if (*attrobj == NULL)
866 return NULL;
867 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000868 res = _PyType_Lookup(Py_Type(self), *attrobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000869 if (res != NULL) {
Guido van Rossum60718732001-08-28 17:47:51 +0000870 descrgetfunc f;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000871 if ((f = Py_Type(res)->tp_descr_get) == NULL)
Guido van Rossum60718732001-08-28 17:47:51 +0000872 Py_INCREF(res);
873 else
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000874 res = f(res, self, (PyObject *)(Py_Type(self)));
Guido van Rossum60718732001-08-28 17:47:51 +0000875 }
876 return res;
877}
878
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000879static PyObject *
880lookup_method(PyObject *self, char *attrstr, PyObject **attrobj)
881{
882 PyObject *res = lookup_maybe(self, attrstr, attrobj);
883 if (res == NULL && !PyErr_Occurred())
884 PyErr_SetObject(PyExc_AttributeError, *attrobj);
885 return res;
886}
887
Guido van Rossum2730b132001-08-28 18:22:14 +0000888/* A variation of PyObject_CallMethod that uses lookup_method()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000889 instead of PyObject_GetAttrString(). This uses the same convention
Guido van Rossum2730b132001-08-28 18:22:14 +0000890 as lookup_method to cache the interned name string object. */
891
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000892static PyObject *
Guido van Rossum2730b132001-08-28 18:22:14 +0000893call_method(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
894{
895 va_list va;
896 PyObject *args, *func = 0, *retval;
Guido van Rossum2730b132001-08-28 18:22:14 +0000897 va_start(va, format);
898
Guido van Rossumda21c012001-10-03 00:50:18 +0000899 func = lookup_maybe(o, name, nameobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000900 if (func == NULL) {
901 va_end(va);
902 if (!PyErr_Occurred())
Guido van Rossumda21c012001-10-03 00:50:18 +0000903 PyErr_SetObject(PyExc_AttributeError, *nameobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000904 return NULL;
905 }
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000906
907 if (format && *format)
908 args = Py_VaBuildValue(format, va);
909 else
910 args = PyTuple_New(0);
911
912 va_end(va);
913
914 if (args == NULL)
915 return NULL;
916
917 assert(PyTuple_Check(args));
918 retval = PyObject_Call(func, args, NULL);
919
920 Py_DECREF(args);
921 Py_DECREF(func);
922
923 return retval;
924}
925
926/* Clone of call_method() that returns NotImplemented when the lookup fails. */
927
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000928static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000929call_maybe(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
930{
931 va_list va;
932 PyObject *args, *func = 0, *retval;
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000933 va_start(va, format);
934
Guido van Rossumda21c012001-10-03 00:50:18 +0000935 func = lookup_maybe(o, name, nameobj);
Guido van Rossum2730b132001-08-28 18:22:14 +0000936 if (func == NULL) {
937 va_end(va);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000938 if (!PyErr_Occurred()) {
939 Py_INCREF(Py_NotImplemented);
940 return Py_NotImplemented;
941 }
Guido van Rossum717ce002001-09-14 16:58:08 +0000942 return NULL;
Guido van Rossum2730b132001-08-28 18:22:14 +0000943 }
944
945 if (format && *format)
946 args = Py_VaBuildValue(format, va);
947 else
948 args = PyTuple_New(0);
949
950 va_end(va);
951
Guido van Rossum717ce002001-09-14 16:58:08 +0000952 if (args == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +0000953 return NULL;
954
Guido van Rossum717ce002001-09-14 16:58:08 +0000955 assert(PyTuple_Check(args));
956 retval = PyObject_Call(func, args, NULL);
Guido van Rossum2730b132001-08-28 18:22:14 +0000957
958 Py_DECREF(args);
959 Py_DECREF(func);
960
961 return retval;
962}
963
Tim Petersea7f75d2002-12-07 21:39:16 +0000964/*
Guido van Rossum1f121312002-11-14 19:49:16 +0000965 Method resolution order algorithm C3 described in
966 "A Monotonic Superclass Linearization for Dylan",
967 by Kim Barrett, Bob Cassel, Paul Haahr,
Tim Petersea7f75d2002-12-07 21:39:16 +0000968 David A. Moon, Keith Playford, and P. Tucker Withington.
Guido van Rossum1f121312002-11-14 19:49:16 +0000969 (OOPSLA 1996)
970
Guido van Rossum98f33732002-11-25 21:36:54 +0000971 Some notes about the rules implied by C3:
972
Tim Petersea7f75d2002-12-07 21:39:16 +0000973 No duplicate bases.
Guido van Rossum98f33732002-11-25 21:36:54 +0000974 It isn't legal to repeat a class in a list of base classes.
975
976 The next three properties are the 3 constraints in "C3".
977
Tim Petersea7f75d2002-12-07 21:39:16 +0000978 Local precendece order.
Guido van Rossum98f33732002-11-25 21:36:54 +0000979 If A precedes B in C's MRO, then A will precede B in the MRO of all
980 subclasses of C.
981
982 Monotonicity.
983 The MRO of a class must be an extension without reordering of the
984 MRO of each of its superclasses.
985
986 Extended Precedence Graph (EPG).
987 Linearization is consistent if there is a path in the EPG from
988 each class to all its successors in the linearization. See
989 the paper for definition of EPG.
Guido van Rossum1f121312002-11-14 19:49:16 +0000990 */
991
Tim Petersea7f75d2002-12-07 21:39:16 +0000992static int
Guido van Rossum1f121312002-11-14 19:49:16 +0000993tail_contains(PyObject *list, int whence, PyObject *o) {
Martin v. Löwis18e16552006-02-15 17:27:45 +0000994 Py_ssize_t j, size;
Guido van Rossum1f121312002-11-14 19:49:16 +0000995 size = PyList_GET_SIZE(list);
996
997 for (j = whence+1; j < size; j++) {
998 if (PyList_GET_ITEM(list, j) == o)
999 return 1;
1000 }
1001 return 0;
1002}
1003
Guido van Rossum98f33732002-11-25 21:36:54 +00001004static PyObject *
1005class_name(PyObject *cls)
1006{
1007 PyObject *name = PyObject_GetAttrString(cls, "__name__");
1008 if (name == NULL) {
1009 PyErr_Clear();
1010 Py_XDECREF(name);
Walter Dörwald1ab83302007-05-18 17:15:44 +00001011 name = PyObject_ReprStr8(cls);
Guido van Rossum98f33732002-11-25 21:36:54 +00001012 }
1013 if (name == NULL)
1014 return NULL;
Martin v. Löwis9b9905b2007-06-10 21:13:34 +00001015 if (!PyUnicode_Check(name)) {
Guido van Rossum98f33732002-11-25 21:36:54 +00001016 Py_DECREF(name);
1017 return NULL;
1018 }
1019 return name;
1020}
1021
1022static int
1023check_duplicates(PyObject *list)
1024{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001025 Py_ssize_t i, j, n;
Guido van Rossum98f33732002-11-25 21:36:54 +00001026 /* Let's use a quadratic time algorithm,
1027 assuming that the bases lists is short.
1028 */
1029 n = PyList_GET_SIZE(list);
1030 for (i = 0; i < n; i++) {
1031 PyObject *o = PyList_GET_ITEM(list, i);
1032 for (j = i + 1; j < n; j++) {
1033 if (PyList_GET_ITEM(list, j) == o) {
1034 o = class_name(o);
1035 PyErr_Format(PyExc_TypeError,
1036 "duplicate base class %s",
Martin v. Löwis9b9905b2007-06-10 21:13:34 +00001037 o ? PyUnicode_AsString(o) : "?");
Guido van Rossum98f33732002-11-25 21:36:54 +00001038 Py_XDECREF(o);
1039 return -1;
1040 }
1041 }
1042 }
1043 return 0;
1044}
1045
1046/* Raise a TypeError for an MRO order disagreement.
1047
1048 It's hard to produce a good error message. In the absence of better
1049 insight into error reporting, report the classes that were candidates
Guido van Rossumd8faa362007-04-27 19:54:29 +00001050 to be put next into the MRO. There is some conflict between the
Guido van Rossum98f33732002-11-25 21:36:54 +00001051 order in which they should be put in the MRO, but it's hard to
1052 diagnose what constraint can't be satisfied.
1053*/
1054
1055static void
1056set_mro_error(PyObject *to_merge, int *remain)
1057{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001058 Py_ssize_t i, n, off, to_merge_size;
Guido van Rossum98f33732002-11-25 21:36:54 +00001059 char buf[1000];
1060 PyObject *k, *v;
1061 PyObject *set = PyDict_New();
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001062 if (!set) return;
Guido van Rossum98f33732002-11-25 21:36:54 +00001063
1064 to_merge_size = PyList_GET_SIZE(to_merge);
1065 for (i = 0; i < to_merge_size; i++) {
1066 PyObject *L = PyList_GET_ITEM(to_merge, i);
1067 if (remain[i] < PyList_GET_SIZE(L)) {
1068 PyObject *c = PyList_GET_ITEM(L, remain[i]);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001069 if (PyDict_SetItem(set, c, Py_None) < 0) {
1070 Py_DECREF(set);
Guido van Rossum98f33732002-11-25 21:36:54 +00001071 return;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001072 }
Guido van Rossum98f33732002-11-25 21:36:54 +00001073 }
1074 }
1075 n = PyDict_Size(set);
1076
Raymond Hettingerf394df42003-04-06 19:13:41 +00001077 off = PyOS_snprintf(buf, sizeof(buf), "Cannot create a \
1078consistent method resolution\norder (MRO) for bases");
Guido van Rossum98f33732002-11-25 21:36:54 +00001079 i = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001080 while (PyDict_Next(set, &i, &k, &v) && (size_t)off < sizeof(buf)) {
Guido van Rossum98f33732002-11-25 21:36:54 +00001081 PyObject *name = class_name(k);
1082 off += PyOS_snprintf(buf + off, sizeof(buf) - off, " %s",
Martin v. Löwis9b9905b2007-06-10 21:13:34 +00001083 name ? PyUnicode_AsString(name) : "?");
Guido van Rossum98f33732002-11-25 21:36:54 +00001084 Py_XDECREF(name);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001085 if (--n && (size_t)(off+1) < sizeof(buf)) {
Guido van Rossum98f33732002-11-25 21:36:54 +00001086 buf[off++] = ',';
1087 buf[off] = '\0';
1088 }
1089 }
1090 PyErr_SetString(PyExc_TypeError, buf);
1091 Py_DECREF(set);
1092}
1093
Tim Petersea7f75d2002-12-07 21:39:16 +00001094static int
Guido van Rossum1f121312002-11-14 19:49:16 +00001095pmerge(PyObject *acc, PyObject* to_merge) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001096 Py_ssize_t i, j, to_merge_size, empty_cnt;
Guido van Rossum1f121312002-11-14 19:49:16 +00001097 int *remain;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001098 int ok;
Tim Petersea7f75d2002-12-07 21:39:16 +00001099
Guido van Rossum1f121312002-11-14 19:49:16 +00001100 to_merge_size = PyList_GET_SIZE(to_merge);
1101
Guido van Rossum98f33732002-11-25 21:36:54 +00001102 /* remain stores an index into each sublist of to_merge.
1103 remain[i] is the index of the next base in to_merge[i]
1104 that is not included in acc.
1105 */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001106 remain = (int *)PyMem_MALLOC(SIZEOF_INT*to_merge_size);
Guido van Rossum1f121312002-11-14 19:49:16 +00001107 if (remain == NULL)
1108 return -1;
1109 for (i = 0; i < to_merge_size; i++)
1110 remain[i] = 0;
1111
1112 again:
1113 empty_cnt = 0;
1114 for (i = 0; i < to_merge_size; i++) {
1115 PyObject *candidate;
Tim Petersea7f75d2002-12-07 21:39:16 +00001116
Guido van Rossum1f121312002-11-14 19:49:16 +00001117 PyObject *cur_list = PyList_GET_ITEM(to_merge, i);
1118
1119 if (remain[i] >= PyList_GET_SIZE(cur_list)) {
1120 empty_cnt++;
1121 continue;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001122 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001123
Guido van Rossum98f33732002-11-25 21:36:54 +00001124 /* Choose next candidate for MRO.
1125
1126 The input sequences alone can determine the choice.
1127 If not, choose the class which appears in the MRO
1128 of the earliest direct superclass of the new class.
1129 */
1130
Guido van Rossum1f121312002-11-14 19:49:16 +00001131 candidate = PyList_GET_ITEM(cur_list, remain[i]);
1132 for (j = 0; j < to_merge_size; j++) {
1133 PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
Guido van Rossum98f33732002-11-25 21:36:54 +00001134 if (tail_contains(j_lst, remain[j], candidate)) {
Guido van Rossum1f121312002-11-14 19:49:16 +00001135 goto skip; /* continue outer loop */
Guido van Rossum98f33732002-11-25 21:36:54 +00001136 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001137 }
1138 ok = PyList_Append(acc, candidate);
1139 if (ok < 0) {
1140 PyMem_Free(remain);
1141 return -1;
1142 }
1143 for (j = 0; j < to_merge_size; j++) {
1144 PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
Guido van Rossum768158c2002-12-31 16:33:01 +00001145 if (remain[j] < PyList_GET_SIZE(j_lst) &&
1146 PyList_GET_ITEM(j_lst, remain[j]) == candidate) {
Guido van Rossum1f121312002-11-14 19:49:16 +00001147 remain[j]++;
1148 }
1149 }
1150 goto again;
Tim Peters9a6b8d82002-11-14 23:22:33 +00001151 skip: ;
Guido van Rossum1f121312002-11-14 19:49:16 +00001152 }
1153
Guido van Rossum98f33732002-11-25 21:36:54 +00001154 if (empty_cnt == to_merge_size) {
1155 PyMem_FREE(remain);
Guido van Rossum1f121312002-11-14 19:49:16 +00001156 return 0;
Guido van Rossum98f33732002-11-25 21:36:54 +00001157 }
1158 set_mro_error(to_merge, remain);
1159 PyMem_FREE(remain);
Guido van Rossum1f121312002-11-14 19:49:16 +00001160 return -1;
1161}
1162
Tim Peters6d6c1a32001-08-02 04:15:00 +00001163static PyObject *
1164mro_implementation(PyTypeObject *type)
1165{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001166 Py_ssize_t i, n;
1167 int ok;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001168 PyObject *bases, *result;
Guido van Rossum1f121312002-11-14 19:49:16 +00001169 PyObject *to_merge, *bases_aslist;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001170
Guido van Rossum63517572002-06-18 16:44:57 +00001171 if(type->tp_dict == NULL) {
1172 if(PyType_Ready(type) < 0)
1173 return NULL;
1174 }
1175
Guido van Rossum98f33732002-11-25 21:36:54 +00001176 /* Find a superclass linearization that honors the constraints
1177 of the explicit lists of bases and the constraints implied by
Tim Petersea7f75d2002-12-07 21:39:16 +00001178 each base class.
Guido van Rossum98f33732002-11-25 21:36:54 +00001179
1180 to_merge is a list of lists, where each list is a superclass
1181 linearization implied by a base class. The last element of
1182 to_merge is the declared list of bases.
1183 */
1184
Tim Peters6d6c1a32001-08-02 04:15:00 +00001185 bases = type->tp_bases;
1186 n = PyTuple_GET_SIZE(bases);
Guido van Rossum1f121312002-11-14 19:49:16 +00001187
1188 to_merge = PyList_New(n+1);
1189 if (to_merge == NULL)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001190 return NULL;
Guido van Rossum1f121312002-11-14 19:49:16 +00001191
Tim Peters6d6c1a32001-08-02 04:15:00 +00001192 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00001193 PyObject *base = PyTuple_GET_ITEM(bases, i);
1194 PyObject *parentMRO;
Guido van Rossum50e9fb92006-08-17 05:42:55 +00001195 parentMRO = PySequence_List(((PyTypeObject*)base)->tp_mro);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001196 if (parentMRO == NULL) {
Guido van Rossum1f121312002-11-14 19:49:16 +00001197 Py_DECREF(to_merge);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001198 return NULL;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001199 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001200
1201 PyList_SET_ITEM(to_merge, i, parentMRO);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001202 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001203
1204 bases_aslist = PySequence_List(bases);
1205 if (bases_aslist == NULL) {
1206 Py_DECREF(to_merge);
1207 return NULL;
1208 }
Guido van Rossum98f33732002-11-25 21:36:54 +00001209 /* This is just a basic sanity check. */
1210 if (check_duplicates(bases_aslist) < 0) {
1211 Py_DECREF(to_merge);
1212 Py_DECREF(bases_aslist);
1213 return NULL;
1214 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001215 PyList_SET_ITEM(to_merge, n, bases_aslist);
1216
1217 result = Py_BuildValue("[O]", (PyObject *)type);
1218 if (result == NULL) {
1219 Py_DECREF(to_merge);
1220 return NULL;
1221 }
1222
1223 ok = pmerge(result, to_merge);
1224 Py_DECREF(to_merge);
1225 if (ok < 0) {
1226 Py_DECREF(result);
1227 return NULL;
1228 }
1229
Tim Peters6d6c1a32001-08-02 04:15:00 +00001230 return result;
1231}
1232
1233static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001234mro_external(PyObject *self)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001235{
1236 PyTypeObject *type = (PyTypeObject *)self;
1237
Tim Peters6d6c1a32001-08-02 04:15:00 +00001238 return mro_implementation(type);
1239}
1240
1241static int
1242mro_internal(PyTypeObject *type)
1243{
1244 PyObject *mro, *result, *tuple;
Armin Rigo037d1e02005-12-29 17:07:39 +00001245 int checkit = 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001246
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001247 if (Py_Type(type) == &PyType_Type) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001248 result = mro_implementation(type);
1249 }
1250 else {
Guido van Rossum60718732001-08-28 17:47:51 +00001251 static PyObject *mro_str;
Armin Rigo037d1e02005-12-29 17:07:39 +00001252 checkit = 1;
Guido van Rossum60718732001-08-28 17:47:51 +00001253 mro = lookup_method((PyObject *)type, "mro", &mro_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001254 if (mro == NULL)
1255 return -1;
1256 result = PyObject_CallObject(mro, NULL);
1257 Py_DECREF(mro);
1258 }
1259 if (result == NULL)
1260 return -1;
1261 tuple = PySequence_Tuple(result);
1262 Py_DECREF(result);
Armin Rigo037d1e02005-12-29 17:07:39 +00001263 if (tuple == NULL)
1264 return -1;
1265 if (checkit) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001266 Py_ssize_t i, len;
Armin Rigo037d1e02005-12-29 17:07:39 +00001267 PyObject *cls;
1268 PyTypeObject *solid;
1269
1270 solid = solid_base(type);
1271
1272 len = PyTuple_GET_SIZE(tuple);
1273
1274 for (i = 0; i < len; i++) {
1275 PyTypeObject *t;
1276 cls = PyTuple_GET_ITEM(tuple, i);
Guido van Rossum50e9fb92006-08-17 05:42:55 +00001277 if (!PyType_Check(cls)) {
Armin Rigo037d1e02005-12-29 17:07:39 +00001278 PyErr_Format(PyExc_TypeError,
1279 "mro() returned a non-class ('%.500s')",
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001280 Py_Type(cls)->tp_name);
Neal Norwitz50bf51a2006-01-02 02:46:54 +00001281 Py_DECREF(tuple);
Armin Rigo037d1e02005-12-29 17:07:39 +00001282 return -1;
1283 }
1284 t = (PyTypeObject*)cls;
1285 if (!PyType_IsSubtype(solid, solid_base(t))) {
1286 PyErr_Format(PyExc_TypeError,
1287 "mro() returned base with unsuitable layout ('%.500s')",
1288 t->tp_name);
Neal Norwitz50bf51a2006-01-02 02:46:54 +00001289 Py_DECREF(tuple);
Armin Rigo037d1e02005-12-29 17:07:39 +00001290 return -1;
1291 }
1292 }
1293 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001294 type->tp_mro = tuple;
1295 return 0;
1296}
1297
1298
1299/* Calculate the best base amongst multiple base classes.
1300 This is the first one that's on the path to the "solid base". */
1301
1302static PyTypeObject *
1303best_base(PyObject *bases)
1304{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001305 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001306 PyTypeObject *base, *winner, *candidate, *base_i;
Tim Petersa91e9642001-11-14 23:32:33 +00001307 PyObject *base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001308
1309 assert(PyTuple_Check(bases));
1310 n = PyTuple_GET_SIZE(bases);
1311 assert(n > 0);
Tim Petersa91e9642001-11-14 23:32:33 +00001312 base = NULL;
1313 winner = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001314 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00001315 base_proto = PyTuple_GET_ITEM(bases, i);
Tim Petersa91e9642001-11-14 23:32:33 +00001316 if (!PyType_Check(base_proto)) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001317 PyErr_SetString(
1318 PyExc_TypeError,
1319 "bases must be types");
1320 return NULL;
1321 }
Tim Petersa91e9642001-11-14 23:32:33 +00001322 base_i = (PyTypeObject *)base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001323 if (base_i->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001324 if (PyType_Ready(base_i) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001325 return NULL;
1326 }
1327 candidate = solid_base(base_i);
Tim Petersa91e9642001-11-14 23:32:33 +00001328 if (winner == NULL) {
1329 winner = candidate;
1330 base = base_i;
1331 }
1332 else if (PyType_IsSubtype(winner, candidate))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001333 ;
1334 else if (PyType_IsSubtype(candidate, winner)) {
1335 winner = candidate;
1336 base = base_i;
1337 }
1338 else {
1339 PyErr_SetString(
1340 PyExc_TypeError,
1341 "multiple bases have "
1342 "instance lay-out conflict");
1343 return NULL;
1344 }
1345 }
Guido van Rossume54616c2001-12-14 04:19:56 +00001346 if (base == NULL)
1347 PyErr_SetString(PyExc_TypeError,
1348 "a new-style class can't have only classic bases");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001349 return base;
1350}
1351
1352static int
1353extra_ivars(PyTypeObject *type, PyTypeObject *base)
1354{
Neil Schemenauerc806c882001-08-29 23:54:54 +00001355 size_t t_size = type->tp_basicsize;
1356 size_t b_size = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001357
Guido van Rossum9676b222001-08-17 20:32:36 +00001358 assert(t_size >= b_size); /* Else type smaller than base! */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001359 if (type->tp_itemsize || base->tp_itemsize) {
1360 /* If itemsize is involved, stricter rules */
1361 return t_size != b_size ||
1362 type->tp_itemsize != base->tp_itemsize;
1363 }
Guido van Rossum9676b222001-08-17 20:32:36 +00001364 if (type->tp_weaklistoffset && base->tp_weaklistoffset == 0 &&
Guido van Rossum360e4b82007-05-14 22:51:27 +00001365 type->tp_weaklistoffset + sizeof(PyObject *) == t_size &&
1366 type->tp_flags & Py_TPFLAGS_HEAPTYPE)
Guido van Rossum9676b222001-08-17 20:32:36 +00001367 t_size -= sizeof(PyObject *);
1368 if (type->tp_dictoffset && base->tp_dictoffset == 0 &&
Guido van Rossum360e4b82007-05-14 22:51:27 +00001369 type->tp_dictoffset + sizeof(PyObject *) == t_size &&
1370 type->tp_flags & Py_TPFLAGS_HEAPTYPE)
Guido van Rossum9676b222001-08-17 20:32:36 +00001371 t_size -= sizeof(PyObject *);
1372
1373 return t_size != b_size;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001374}
1375
1376static PyTypeObject *
1377solid_base(PyTypeObject *type)
1378{
1379 PyTypeObject *base;
1380
1381 if (type->tp_base)
1382 base = solid_base(type->tp_base);
1383 else
1384 base = &PyBaseObject_Type;
1385 if (extra_ivars(type, base))
1386 return type;
1387 else
1388 return base;
1389}
1390
Jeremy Hylton938ace62002-07-17 16:30:39 +00001391static void object_dealloc(PyObject *);
1392static int object_init(PyObject *, PyObject *, PyObject *);
1393static int update_slot(PyTypeObject *, PyObject *);
1394static void fixup_slot_dispatchers(PyTypeObject *);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001395
Guido van Rossum360e4b82007-05-14 22:51:27 +00001396/*
1397 * Helpers for __dict__ descriptor. We don't want to expose the dicts
1398 * inherited from various builtin types. The builtin base usually provides
1399 * its own __dict__ descriptor, so we use that when we can.
1400 */
1401static PyTypeObject *
1402get_builtin_base_with_dict(PyTypeObject *type)
1403{
1404 while (type->tp_base != NULL) {
1405 if (type->tp_dictoffset != 0 &&
1406 !(type->tp_flags & Py_TPFLAGS_HEAPTYPE))
1407 return type;
1408 type = type->tp_base;
1409 }
1410 return NULL;
1411}
1412
1413static PyObject *
1414get_dict_descriptor(PyTypeObject *type)
1415{
1416 static PyObject *dict_str;
1417 PyObject *descr;
1418
1419 if (dict_str == NULL) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00001420 dict_str = PyUnicode_InternFromString("__dict__");
Guido van Rossum360e4b82007-05-14 22:51:27 +00001421 if (dict_str == NULL)
1422 return NULL;
1423 }
1424 descr = _PyType_Lookup(type, dict_str);
1425 if (descr == NULL || !PyDescr_IsData(descr))
1426 return NULL;
1427
1428 return descr;
1429}
1430
1431static void
1432raise_dict_descr_error(PyObject *obj)
1433{
1434 PyErr_Format(PyExc_TypeError,
1435 "this __dict__ descriptor does not support "
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001436 "'%.200s' objects", Py_Type(obj)->tp_name);
Guido van Rossum360e4b82007-05-14 22:51:27 +00001437}
1438
Tim Peters6d6c1a32001-08-02 04:15:00 +00001439static PyObject *
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001440subtype_dict(PyObject *obj, void *context)
1441{
Guido van Rossum360e4b82007-05-14 22:51:27 +00001442 PyObject **dictptr;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001443 PyObject *dict;
Guido van Rossum360e4b82007-05-14 22:51:27 +00001444 PyTypeObject *base;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001445
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001446 base = get_builtin_base_with_dict(Py_Type(obj));
Guido van Rossum360e4b82007-05-14 22:51:27 +00001447 if (base != NULL) {
1448 descrgetfunc func;
1449 PyObject *descr = get_dict_descriptor(base);
1450 if (descr == NULL) {
1451 raise_dict_descr_error(obj);
1452 return NULL;
1453 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001454 func = Py_Type(descr)->tp_descr_get;
Guido van Rossum360e4b82007-05-14 22:51:27 +00001455 if (func == NULL) {
1456 raise_dict_descr_error(obj);
1457 return NULL;
1458 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001459 return func(descr, obj, (PyObject *)(Py_Type(obj)));
Guido van Rossum360e4b82007-05-14 22:51:27 +00001460 }
1461
1462 dictptr = _PyObject_GetDictPtr(obj);
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001463 if (dictptr == NULL) {
1464 PyErr_SetString(PyExc_AttributeError,
1465 "This object has no __dict__");
1466 return NULL;
1467 }
1468 dict = *dictptr;
Guido van Rossum3926a632001-09-25 16:25:58 +00001469 if (dict == NULL)
1470 *dictptr = dict = PyDict_New();
1471 Py_XINCREF(dict);
1472 return dict;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001473}
1474
Guido van Rossum6661be32001-10-26 04:26:12 +00001475static int
1476subtype_setdict(PyObject *obj, PyObject *value, void *context)
1477{
Guido van Rossum360e4b82007-05-14 22:51:27 +00001478 PyObject **dictptr;
Guido van Rossum6661be32001-10-26 04:26:12 +00001479 PyObject *dict;
Guido van Rossum360e4b82007-05-14 22:51:27 +00001480 PyTypeObject *base;
Guido van Rossum6661be32001-10-26 04:26:12 +00001481
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001482 base = get_builtin_base_with_dict(Py_Type(obj));
Guido van Rossum360e4b82007-05-14 22:51:27 +00001483 if (base != NULL) {
1484 descrsetfunc func;
1485 PyObject *descr = get_dict_descriptor(base);
1486 if (descr == NULL) {
1487 raise_dict_descr_error(obj);
1488 return -1;
1489 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001490 func = Py_Type(descr)->tp_descr_set;
Guido van Rossum360e4b82007-05-14 22:51:27 +00001491 if (func == NULL) {
1492 raise_dict_descr_error(obj);
1493 return -1;
1494 }
1495 return func(descr, obj, value);
1496 }
1497
1498 dictptr = _PyObject_GetDictPtr(obj);
Guido van Rossum6661be32001-10-26 04:26:12 +00001499 if (dictptr == NULL) {
1500 PyErr_SetString(PyExc_AttributeError,
1501 "This object has no __dict__");
1502 return -1;
1503 }
Guido van Rossumd331cb52001-12-05 19:46:42 +00001504 if (value != NULL && !PyDict_Check(value)) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001505 PyErr_Format(PyExc_TypeError,
1506 "__dict__ must be set to a dictionary, "
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001507 "not a '%.200s'", Py_Type(value)->tp_name);
Guido van Rossum6661be32001-10-26 04:26:12 +00001508 return -1;
1509 }
1510 dict = *dictptr;
Guido van Rossumd331cb52001-12-05 19:46:42 +00001511 Py_XINCREF(value);
Guido van Rossum6661be32001-10-26 04:26:12 +00001512 *dictptr = value;
1513 Py_XDECREF(dict);
1514 return 0;
1515}
1516
Guido van Rossumad47da02002-08-12 19:05:44 +00001517static PyObject *
1518subtype_getweakref(PyObject *obj, void *context)
1519{
1520 PyObject **weaklistptr;
1521 PyObject *result;
1522
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001523 if (Py_Type(obj)->tp_weaklistoffset == 0) {
Guido van Rossumad47da02002-08-12 19:05:44 +00001524 PyErr_SetString(PyExc_AttributeError,
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001525 "This object has no __weakref__");
Guido van Rossumad47da02002-08-12 19:05:44 +00001526 return NULL;
1527 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001528 assert(Py_Type(obj)->tp_weaklistoffset > 0);
1529 assert(Py_Type(obj)->tp_weaklistoffset + sizeof(PyObject *) <=
1530 (size_t)(Py_Type(obj)->tp_basicsize));
Guido van Rossumad47da02002-08-12 19:05:44 +00001531 weaklistptr = (PyObject **)
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001532 ((char *)obj + Py_Type(obj)->tp_weaklistoffset);
Guido van Rossumad47da02002-08-12 19:05:44 +00001533 if (*weaklistptr == NULL)
1534 result = Py_None;
1535 else
1536 result = *weaklistptr;
1537 Py_INCREF(result);
1538 return result;
1539}
1540
Guido van Rossum373c7412003-01-07 13:41:37 +00001541/* Three variants on the subtype_getsets list. */
1542
1543static PyGetSetDef subtype_getsets_full[] = {
Guido van Rossumad47da02002-08-12 19:05:44 +00001544 {"__dict__", subtype_dict, subtype_setdict,
Neal Norwitz858e34f2002-08-13 17:18:45 +00001545 PyDoc_STR("dictionary for instance variables (if defined)")},
Guido van Rossumad47da02002-08-12 19:05:44 +00001546 {"__weakref__", subtype_getweakref, NULL,
Neal Norwitz858e34f2002-08-13 17:18:45 +00001547 PyDoc_STR("list of weak references to the object (if defined)")},
Guido van Rossumad47da02002-08-12 19:05:44 +00001548 {0}
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001549};
1550
Guido van Rossum373c7412003-01-07 13:41:37 +00001551static PyGetSetDef subtype_getsets_dict_only[] = {
1552 {"__dict__", subtype_dict, subtype_setdict,
1553 PyDoc_STR("dictionary for instance variables (if defined)")},
1554 {0}
1555};
1556
1557static PyGetSetDef subtype_getsets_weakref_only[] = {
1558 {"__weakref__", subtype_getweakref, NULL,
1559 PyDoc_STR("list of weak references to the object (if defined)")},
1560 {0}
1561};
1562
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001563static int
1564valid_identifier(PyObject *s)
1565{
Walter Dörwald7815c5e2007-06-11 14:55:19 +00001566 Py_UNICODE *p;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001567 Py_ssize_t i, n;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001568
Martin v. Löwis5b222132007-06-10 09:51:05 +00001569 if (!PyUnicode_Check(s)) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001570 PyErr_Format(PyExc_TypeError,
1571 "__slots__ items must be strings, not '%.200s'",
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001572 Py_Type(s)->tp_name);
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001573 return 0;
1574 }
Walter Dörwald7815c5e2007-06-11 14:55:19 +00001575 p = PyUnicode_AS_UNICODE(s);
1576 n = PyUnicode_GET_SIZE(s);
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001577 /* We must reject an empty name. As a hack, we bump the
1578 length to 1 so that the loop will balk on the trailing \0. */
1579 if (n == 0)
1580 n = 1;
1581 for (i = 0; i < n; i++, p++) {
Guido van Rossum1e2b7602007-08-04 16:43:59 +00001582 if (*p > 127 ||
1583 (!(i == 0 ? isalpha(*p) : isalnum(*p)) && *p != '_')) {
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001584 PyErr_SetString(PyExc_TypeError,
1585 "__slots__ must be identifiers");
1586 return 0;
1587 }
1588 }
1589 return 1;
1590}
1591
Guido van Rossumd8faa362007-04-27 19:54:29 +00001592/* Forward */
1593static int
1594object_init(PyObject *self, PyObject *args, PyObject *kwds);
1595
1596static int
1597type_init(PyObject *cls, PyObject *args, PyObject *kwds)
1598{
1599 int res;
1600
1601 assert(args != NULL && PyTuple_Check(args));
1602 assert(kwds == NULL || PyDict_Check(kwds));
1603
1604 if (kwds != NULL && PyDict_Check(kwds) && PyDict_Size(kwds) != 0) {
1605 PyErr_SetString(PyExc_TypeError,
1606 "type.__init__() takes no keyword arguments");
1607 return -1;
1608 }
1609
1610 if (args != NULL && PyTuple_Check(args) &&
1611 (PyTuple_GET_SIZE(args) != 1 && PyTuple_GET_SIZE(args) != 3)) {
1612 PyErr_SetString(PyExc_TypeError,
1613 "type.__init__() takes 1 or 3 arguments");
1614 return -1;
1615 }
1616
1617 /* Call object.__init__(self) now. */
1618 /* XXX Could call super(type, cls).__init__() but what's the point? */
1619 args = PyTuple_GetSlice(args, 0, 0);
1620 res = object_init(cls, args, NULL);
1621 Py_DECREF(args);
1622 return res;
1623}
1624
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001625static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00001626type_new(PyTypeObject *metatype, PyObject *args, PyObject *kwds)
1627{
1628 PyObject *name, *bases, *dict;
Martin v. Löwis15e62742006-02-27 16:46:16 +00001629 static char *kwlist[] = {"name", "bases", "dict", 0};
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001630 PyObject *slots, *tmp, *newslots;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001631 PyTypeObject *type, *base, *tmptype, *winner;
Guido van Rossume5c691a2003-03-07 15:13:17 +00001632 PyHeapTypeObject *et;
Guido van Rossum6f799372001-09-20 20:46:19 +00001633 PyMemberDef *mp;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001634 Py_ssize_t i, nbases, nslots, slotoffset, add_dict, add_weak;
Guido van Rossumad47da02002-08-12 19:05:44 +00001635 int j, may_add_dict, may_add_weak;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001636
Tim Peters3abca122001-10-27 19:37:48 +00001637 assert(args != NULL && PyTuple_Check(args));
1638 assert(kwds == NULL || PyDict_Check(kwds));
1639
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001640 /* Special case: type(x) should return x->ob_type */
Tim Peters3abca122001-10-27 19:37:48 +00001641 {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001642 const Py_ssize_t nargs = PyTuple_GET_SIZE(args);
1643 const Py_ssize_t nkwds = kwds == NULL ? 0 : PyDict_Size(kwds);
Tim Peters3abca122001-10-27 19:37:48 +00001644
1645 if (PyType_CheckExact(metatype) && nargs == 1 && nkwds == 0) {
1646 PyObject *x = PyTuple_GET_ITEM(args, 0);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001647 Py_INCREF(Py_Type(x));
1648 return (PyObject *) Py_Type(x);
Tim Peters3abca122001-10-27 19:37:48 +00001649 }
1650
1651 /* SF bug 475327 -- if that didn't trigger, we need 3
1652 arguments. but PyArg_ParseTupleAndKeywords below may give
1653 a msg saying type() needs exactly 3. */
1654 if (nargs + nkwds != 3) {
1655 PyErr_SetString(PyExc_TypeError,
1656 "type() takes 1 or 3 arguments");
1657 return NULL;
1658 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001659 }
1660
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001661 /* Check arguments: (name, bases, dict) */
Thomas Hellerace8ba82007-07-11 20:01:43 +00001662 if (!PyArg_ParseTupleAndKeywords(args, kwds, "SO!O!:type", kwlist,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001663 &name,
1664 &PyTuple_Type, &bases,
1665 &PyDict_Type, &dict))
1666 return NULL;
1667
1668 /* Determine the proper metatype to deal with this,
1669 and check for metatype conflicts while we're at it.
1670 Note that if some other metatype wins to contract,
1671 it's possible that its instances are not types. */
1672 nbases = PyTuple_GET_SIZE(bases);
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001673 winner = metatype;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001674 for (i = 0; i < nbases; i++) {
1675 tmp = PyTuple_GET_ITEM(bases, i);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001676 tmptype = Py_Type(tmp);
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001677 if (PyType_IsSubtype(winner, tmptype))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001678 continue;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001679 if (PyType_IsSubtype(tmptype, winner)) {
1680 winner = tmptype;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001681 continue;
1682 }
1683 PyErr_SetString(PyExc_TypeError,
Guido van Rossum636688d2003-04-23 12:07:22 +00001684 "metaclass conflict: "
1685 "the metaclass of a derived class "
1686 "must be a (non-strict) subclass "
1687 "of the metaclasses of all its bases");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001688 return NULL;
1689 }
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001690 if (winner != metatype) {
1691 if (winner->tp_new != type_new) /* Pass it to the winner */
1692 return winner->tp_new(winner, args, kwds);
1693 metatype = winner;
1694 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001695
1696 /* Adjust for empty tuple bases */
1697 if (nbases == 0) {
Raymond Hettinger8ae46892003-10-12 19:09:37 +00001698 bases = PyTuple_Pack(1, &PyBaseObject_Type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001699 if (bases == NULL)
1700 return NULL;
1701 nbases = 1;
1702 }
1703 else
1704 Py_INCREF(bases);
1705
1706 /* XXX From here until type is allocated, "return NULL" leaks bases! */
1707
1708 /* Calculate best base, and check that all bases are type objects */
1709 base = best_base(bases);
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001710 if (base == NULL) {
1711 Py_DECREF(bases);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001712 return NULL;
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001713 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001714 if (!PyType_HasFeature(base, Py_TPFLAGS_BASETYPE)) {
1715 PyErr_Format(PyExc_TypeError,
1716 "type '%.100s' is not an acceptable base type",
1717 base->tp_name);
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001718 Py_DECREF(bases);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001719 return NULL;
1720 }
1721
Tim Peters6d6c1a32001-08-02 04:15:00 +00001722 /* Check for a __slots__ sequence variable in dict, and count it */
1723 slots = PyDict_GetItemString(dict, "__slots__");
1724 nslots = 0;
Guido van Rossum9676b222001-08-17 20:32:36 +00001725 add_dict = 0;
1726 add_weak = 0;
Guido van Rossumad47da02002-08-12 19:05:44 +00001727 may_add_dict = base->tp_dictoffset == 0;
1728 may_add_weak = base->tp_weaklistoffset == 0 && base->tp_itemsize == 0;
1729 if (slots == NULL) {
1730 if (may_add_dict) {
1731 add_dict++;
1732 }
1733 if (may_add_weak) {
1734 add_weak++;
1735 }
1736 }
1737 else {
1738 /* Have slots */
1739
Tim Peters6d6c1a32001-08-02 04:15:00 +00001740 /* Make it into a tuple */
Guido van Rossumd8faa362007-04-27 19:54:29 +00001741 if (PyString_Check(slots) || PyUnicode_Check(slots))
Raymond Hettinger8ae46892003-10-12 19:09:37 +00001742 slots = PyTuple_Pack(1, slots);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001743 else
1744 slots = PySequence_Tuple(slots);
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001745 if (slots == NULL) {
1746 Py_DECREF(bases);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001747 return NULL;
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001748 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001749 assert(PyTuple_Check(slots));
1750
1751 /* Are slots allowed? */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001752 nslots = PyTuple_GET_SIZE(slots);
Jeremy Hylton1c7a0ea2003-07-16 16:08:23 +00001753 if (nslots > 0 && base->tp_itemsize != 0) {
Guido van Rossumc4141872001-08-30 04:43:35 +00001754 PyErr_Format(PyExc_TypeError,
1755 "nonempty __slots__ "
1756 "not supported for subtype of '%s'",
1757 base->tp_name);
Guido van Rossumad47da02002-08-12 19:05:44 +00001758 bad_slots:
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001759 Py_DECREF(bases);
Guido van Rossumad47da02002-08-12 19:05:44 +00001760 Py_DECREF(slots);
Guido van Rossumc4141872001-08-30 04:43:35 +00001761 return NULL;
1762 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001763
1764 /* Check for valid slot names and two special cases */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001765 for (i = 0; i < nslots; i++) {
Guido van Rossumad47da02002-08-12 19:05:44 +00001766 PyObject *tmp = PyTuple_GET_ITEM(slots, i);
Guido van Rossumad47da02002-08-12 19:05:44 +00001767 if (!valid_identifier(tmp))
1768 goto bad_slots;
Martin v. Löwis5b222132007-06-10 09:51:05 +00001769 assert(PyUnicode_Check(tmp));
1770 if (PyUnicode_CompareWithASCIIString(tmp, "__dict__") == 0) {
Guido van Rossumad47da02002-08-12 19:05:44 +00001771 if (!may_add_dict || add_dict) {
1772 PyErr_SetString(PyExc_TypeError,
1773 "__dict__ slot disallowed: "
1774 "we already got one");
1775 goto bad_slots;
1776 }
1777 add_dict++;
1778 }
Martin v. Löwis5b222132007-06-10 09:51:05 +00001779 if (PyUnicode_CompareWithASCIIString(tmp, "__weakref__") == 0) {
Guido van Rossumad47da02002-08-12 19:05:44 +00001780 if (!may_add_weak || add_weak) {
1781 PyErr_SetString(PyExc_TypeError,
1782 "__weakref__ slot disallowed: "
1783 "either we already got one, "
1784 "or __itemsize__ != 0");
1785 goto bad_slots;
1786 }
1787 add_weak++;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001788 }
1789 }
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001790
Guido van Rossumd8faa362007-04-27 19:54:29 +00001791 /* Copy slots into a list, mangle names and sort them.
1792 Sorted names are needed for __class__ assignment.
1793 Convert them back to tuple at the end.
1794 */
1795 newslots = PyList_New(nslots - add_dict - add_weak);
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001796 if (newslots == NULL)
Guido van Rossumad47da02002-08-12 19:05:44 +00001797 goto bad_slots;
1798 for (i = j = 0; i < nslots; i++) {
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001799 tmp = PyTuple_GET_ITEM(slots, i);
Martin v. Löwis5b222132007-06-10 09:51:05 +00001800 if ((add_dict &&
1801 PyUnicode_CompareWithASCIIString(tmp, "__dict__") == 0) ||
1802 (add_weak &&
1803 PyUnicode_CompareWithASCIIString(tmp, "__weakref__") == 0))
Guido van Rossumad47da02002-08-12 19:05:44 +00001804 continue;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001805 tmp =_Py_Mangle(name, tmp);
Guido van Rossumd8faa362007-04-27 19:54:29 +00001806 if (!tmp)
1807 goto bad_slots;
1808 PyList_SET_ITEM(newslots, j, tmp);
Guido van Rossumad47da02002-08-12 19:05:44 +00001809 j++;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001810 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001811 assert(j == nslots - add_dict - add_weak);
1812 nslots = j;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001813 Py_DECREF(slots);
Guido van Rossumd8faa362007-04-27 19:54:29 +00001814 if (PyList_Sort(newslots) == -1) {
1815 Py_DECREF(bases);
1816 Py_DECREF(newslots);
1817 return NULL;
1818 }
1819 slots = PyList_AsTuple(newslots);
1820 Py_DECREF(newslots);
1821 if (slots == NULL) {
1822 Py_DECREF(bases);
1823 return NULL;
1824 }
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001825
Guido van Rossumad47da02002-08-12 19:05:44 +00001826 /* Secondary bases may provide weakrefs or dict */
1827 if (nbases > 1 &&
1828 ((may_add_dict && !add_dict) ||
1829 (may_add_weak && !add_weak))) {
1830 for (i = 0; i < nbases; i++) {
1831 tmp = PyTuple_GET_ITEM(bases, i);
1832 if (tmp == (PyObject *)base)
1833 continue; /* Skip primary base */
Guido van Rossumad47da02002-08-12 19:05:44 +00001834 assert(PyType_Check(tmp));
1835 tmptype = (PyTypeObject *)tmp;
1836 if (may_add_dict && !add_dict &&
1837 tmptype->tp_dictoffset != 0)
1838 add_dict++;
1839 if (may_add_weak && !add_weak &&
1840 tmptype->tp_weaklistoffset != 0)
1841 add_weak++;
1842 if (may_add_dict && !add_dict)
1843 continue;
1844 if (may_add_weak && !add_weak)
1845 continue;
1846 /* Nothing more to check */
1847 break;
1848 }
1849 }
Guido van Rossum9676b222001-08-17 20:32:36 +00001850 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001851
1852 /* XXX From here until type is safely allocated,
1853 "return NULL" may leak slots! */
1854
1855 /* Allocate the type object */
1856 type = (PyTypeObject *)metatype->tp_alloc(metatype, nslots);
Guido van Rossumad47da02002-08-12 19:05:44 +00001857 if (type == NULL) {
1858 Py_XDECREF(slots);
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001859 Py_DECREF(bases);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001860 return NULL;
Guido van Rossumad47da02002-08-12 19:05:44 +00001861 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001862
1863 /* Keep name and slots alive in the extended type object */
Guido van Rossume5c691a2003-03-07 15:13:17 +00001864 et = (PyHeapTypeObject *)type;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001865 Py_INCREF(name);
Georg Brandlc255c7b2006-02-20 22:27:28 +00001866 et->ht_name = name;
1867 et->ht_slots = slots;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001868
Guido van Rossumdc91b992001-08-08 22:26:22 +00001869 /* Initialize tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001870 type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE |
1871 Py_TPFLAGS_BASETYPE;
Guido van Rossum048eb752001-10-02 21:24:57 +00001872 if (base->tp_flags & Py_TPFLAGS_HAVE_GC)
1873 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossumdc91b992001-08-08 22:26:22 +00001874
Guido van Rossumdc91b992001-08-08 22:26:22 +00001875 /* Initialize essential fields */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001876 type->tp_as_number = &et->as_number;
1877 type->tp_as_sequence = &et->as_sequence;
1878 type->tp_as_mapping = &et->as_mapping;
1879 type->tp_as_buffer = &et->as_buffer;
Martin v. Löwis5b222132007-06-10 09:51:05 +00001880 if (PyString_Check(name))
1881 type->tp_name = PyString_AsString(name);
1882 else {
1883 type->tp_name = PyUnicode_AsString(name);
1884 if (!type->tp_name) {
1885 Py_DECREF(type);
1886 return NULL;
1887 }
1888 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001889
1890 /* Set tp_base and tp_bases */
1891 type->tp_bases = bases;
1892 Py_INCREF(base);
1893 type->tp_base = base;
1894
Guido van Rossum687ae002001-10-15 22:03:32 +00001895 /* Initialize tp_dict from passed-in dict */
1896 type->tp_dict = dict = PyDict_Copy(dict);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001897 if (dict == NULL) {
1898 Py_DECREF(type);
1899 return NULL;
1900 }
1901
Guido van Rossumc3542212001-08-16 09:18:56 +00001902 /* Set __module__ in the dict */
1903 if (PyDict_GetItemString(dict, "__module__") == NULL) {
1904 tmp = PyEval_GetGlobals();
1905 if (tmp != NULL) {
1906 tmp = PyDict_GetItemString(tmp, "__name__");
1907 if (tmp != NULL) {
1908 if (PyDict_SetItemString(dict, "__module__",
1909 tmp) < 0)
1910 return NULL;
1911 }
1912 }
1913 }
1914
Tim Peters2f93e282001-10-04 05:27:00 +00001915 /* Set tp_doc to a copy of dict['__doc__'], if the latter is there
Tim Peters24008312002-03-17 18:56:20 +00001916 and is a string. The __doc__ accessor will first look for tp_doc;
1917 if that fails, it will still look into __dict__.
Tim Peters2f93e282001-10-04 05:27:00 +00001918 */
1919 {
1920 PyObject *doc = PyDict_GetItemString(dict, "__doc__");
Neal Norwitza369c5a2007-08-25 07:41:59 +00001921 if (doc != NULL) {
1922 char *tp_doc;
1923 const char *str = NULL;
1924 size_t n;
1925 if (PyString_Check(doc)) {
1926 str = PyString_AS_STRING(doc);
1927 n = (size_t)PyString_GET_SIZE(doc);
1928 } else if (PyUnicode_Check(doc)) {
1929 str = PyUnicode_AsString(doc);
1930 if (str == NULL) {
1931 Py_DECREF(type);
1932 return NULL;
1933 }
1934 n = strlen(str);
Tim Peters2f93e282001-10-04 05:27:00 +00001935 }
Neal Norwitza369c5a2007-08-25 07:41:59 +00001936 if (str != NULL) {
1937 tp_doc = (char *)PyObject_MALLOC(n+1);
1938 if (tp_doc == NULL) {
1939 Py_DECREF(type);
1940 return NULL;
1941 }
1942 memcpy(tp_doc, str, n+1);
1943 type->tp_doc = tp_doc;
1944 }
Tim Peters2f93e282001-10-04 05:27:00 +00001945 }
1946 }
1947
Tim Peters6d6c1a32001-08-02 04:15:00 +00001948 /* Special-case __new__: if it's a plain function,
1949 make it a static function */
1950 tmp = PyDict_GetItemString(dict, "__new__");
1951 if (tmp != NULL && PyFunction_Check(tmp)) {
1952 tmp = PyStaticMethod_New(tmp);
1953 if (tmp == NULL) {
1954 Py_DECREF(type);
1955 return NULL;
1956 }
1957 PyDict_SetItemString(dict, "__new__", tmp);
1958 Py_DECREF(tmp);
1959 }
1960
1961 /* Add descriptors for custom slots from __slots__, or for __dict__ */
Guido van Rossume5c691a2003-03-07 15:13:17 +00001962 mp = PyHeapType_GET_MEMBERS(et);
Neil Schemenauerc806c882001-08-29 23:54:54 +00001963 slotoffset = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001964 if (slots != NULL) {
1965 for (i = 0; i < nslots; i++, mp++) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00001966 mp->name = PyUnicode_AsString(
Tim Peters6d6c1a32001-08-02 04:15:00 +00001967 PyTuple_GET_ITEM(slots, i));
Guido van Rossum64b206c2001-12-04 17:13:22 +00001968 mp->type = T_OBJECT_EX;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001969 mp->offset = slotoffset;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001970
1971 /* __dict__ and __weakref__ are already filtered out */
1972 assert(strcmp(mp->name, "__dict__") != 0);
1973 assert(strcmp(mp->name, "__weakref__") != 0);
1974
Tim Peters6d6c1a32001-08-02 04:15:00 +00001975 slotoffset += sizeof(PyObject *);
1976 }
1977 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001978 if (add_dict) {
1979 if (base->tp_itemsize)
1980 type->tp_dictoffset = -(long)sizeof(PyObject *);
1981 else
1982 type->tp_dictoffset = slotoffset;
1983 slotoffset += sizeof(PyObject *);
1984 }
1985 if (add_weak) {
1986 assert(!base->tp_itemsize);
1987 type->tp_weaklistoffset = slotoffset;
1988 slotoffset += sizeof(PyObject *);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001989 }
1990 type->tp_basicsize = slotoffset;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001991 type->tp_itemsize = base->tp_itemsize;
Guido van Rossume5c691a2003-03-07 15:13:17 +00001992 type->tp_members = PyHeapType_GET_MEMBERS(et);
Guido van Rossum373c7412003-01-07 13:41:37 +00001993
1994 if (type->tp_weaklistoffset && type->tp_dictoffset)
1995 type->tp_getset = subtype_getsets_full;
1996 else if (type->tp_weaklistoffset && !type->tp_dictoffset)
1997 type->tp_getset = subtype_getsets_weakref_only;
1998 else if (!type->tp_weaklistoffset && type->tp_dictoffset)
1999 type->tp_getset = subtype_getsets_dict_only;
2000 else
2001 type->tp_getset = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002002
2003 /* Special case some slots */
2004 if (type->tp_dictoffset != 0 || nslots > 0) {
2005 if (base->tp_getattr == NULL && base->tp_getattro == NULL)
2006 type->tp_getattro = PyObject_GenericGetAttr;
2007 if (base->tp_setattr == NULL && base->tp_setattro == NULL)
2008 type->tp_setattro = PyObject_GenericSetAttr;
2009 }
2010 type->tp_dealloc = subtype_dealloc;
2011
Guido van Rossum9475a232001-10-05 20:51:39 +00002012 /* Enable GC unless there are really no instance variables possible */
2013 if (!(type->tp_basicsize == sizeof(PyObject) &&
2014 type->tp_itemsize == 0))
2015 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
2016
Tim Peters6d6c1a32001-08-02 04:15:00 +00002017 /* Always override allocation strategy to use regular heap */
2018 type->tp_alloc = PyType_GenericAlloc;
Guido van Rossum048eb752001-10-02 21:24:57 +00002019 if (type->tp_flags & Py_TPFLAGS_HAVE_GC) {
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00002020 type->tp_free = PyObject_GC_Del;
Guido van Rossum9475a232001-10-05 20:51:39 +00002021 type->tp_traverse = subtype_traverse;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00002022 type->tp_clear = subtype_clear;
Guido van Rossum048eb752001-10-02 21:24:57 +00002023 }
2024 else
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00002025 type->tp_free = PyObject_Del;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002026
2027 /* Initialize the rest */
Guido van Rossum528b7eb2001-08-07 17:24:28 +00002028 if (PyType_Ready(type) < 0) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00002029 Py_DECREF(type);
2030 return NULL;
2031 }
2032
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002033 /* Put the proper slots in place */
2034 fixup_slot_dispatchers(type);
Guido van Rossumf040ede2001-08-07 16:40:56 +00002035
Tim Peters6d6c1a32001-08-02 04:15:00 +00002036 return (PyObject *)type;
2037}
2038
2039/* Internal API to look for a name through the MRO.
2040 This returns a borrowed reference, and doesn't set an exception! */
2041PyObject *
2042_PyType_Lookup(PyTypeObject *type, PyObject *name)
2043{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002044 Py_ssize_t i, n;
Tim Petersa91e9642001-11-14 23:32:33 +00002045 PyObject *mro, *res, *base, *dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002046
Guido van Rossum687ae002001-10-15 22:03:32 +00002047 /* Look in tp_dict of types in MRO */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002048 mro = type->tp_mro;
Guido van Rossum23094982002-06-10 14:30:43 +00002049
2050 /* If mro is NULL, the type is either not yet initialized
2051 by PyType_Ready(), or already cleared by type_clear().
2052 Either way the safest thing to do is to return NULL. */
2053 if (mro == NULL)
2054 return NULL;
2055
Tim Peters6d6c1a32001-08-02 04:15:00 +00002056 assert(PyTuple_Check(mro));
2057 n = PyTuple_GET_SIZE(mro);
2058 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00002059 base = PyTuple_GET_ITEM(mro, i);
Guido van Rossum50e9fb92006-08-17 05:42:55 +00002060 assert(PyType_Check(base));
2061 dict = ((PyTypeObject *)base)->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002062 assert(dict && PyDict_Check(dict));
2063 res = PyDict_GetItem(dict, name);
2064 if (res != NULL)
2065 return res;
2066 }
2067 return NULL;
2068}
2069
2070/* This is similar to PyObject_GenericGetAttr(),
2071 but uses _PyType_Lookup() instead of just looking in type->tp_dict. */
2072static PyObject *
2073type_getattro(PyTypeObject *type, PyObject *name)
2074{
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002075 PyTypeObject *metatype = Py_Type(type);
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002076 PyObject *meta_attribute, *attribute;
2077 descrgetfunc meta_get;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002078
2079 /* Initialize this type (we'll assume the metatype is initialized) */
2080 if (type->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00002081 if (PyType_Ready(type) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002082 return NULL;
2083 }
2084
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002085 /* No readable descriptor found yet */
2086 meta_get = NULL;
Tim Peters34592512002-07-11 06:23:50 +00002087
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002088 /* Look for the attribute in the metatype */
2089 meta_attribute = _PyType_Lookup(metatype, name);
2090
2091 if (meta_attribute != NULL) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002092 meta_get = Py_Type(meta_attribute)->tp_descr_get;
Tim Peters34592512002-07-11 06:23:50 +00002093
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002094 if (meta_get != NULL && PyDescr_IsData(meta_attribute)) {
2095 /* Data descriptors implement tp_descr_set to intercept
2096 * writes. Assume the attribute is not overridden in
2097 * type's tp_dict (and bases): call the descriptor now.
2098 */
2099 return meta_get(meta_attribute, (PyObject *)type,
2100 (PyObject *)metatype);
2101 }
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00002102 Py_INCREF(meta_attribute);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002103 }
2104
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002105 /* No data descriptor found on metatype. Look in tp_dict of this
2106 * type and its bases */
2107 attribute = _PyType_Lookup(type, name);
2108 if (attribute != NULL) {
2109 /* Implement descriptor functionality, if any */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002110 descrgetfunc local_get = Py_Type(attribute)->tp_descr_get;
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00002111
2112 Py_XDECREF(meta_attribute);
2113
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002114 if (local_get != NULL) {
2115 /* NULL 2nd argument indicates the descriptor was
2116 * found on the target object itself (or a base) */
2117 return local_get(attribute, (PyObject *)NULL,
2118 (PyObject *)type);
2119 }
Tim Peters34592512002-07-11 06:23:50 +00002120
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002121 Py_INCREF(attribute);
2122 return attribute;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002123 }
2124
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002125 /* No attribute found in local __dict__ (or bases): use the
2126 * descriptor from the metatype, if any */
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00002127 if (meta_get != NULL) {
2128 PyObject *res;
2129 res = meta_get(meta_attribute, (PyObject *)type,
2130 (PyObject *)metatype);
2131 Py_DECREF(meta_attribute);
2132 return res;
2133 }
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002134
2135 /* If an ordinary attribute was found on the metatype, return it now */
2136 if (meta_attribute != NULL) {
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002137 return meta_attribute;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002138 }
2139
2140 /* Give up */
2141 PyErr_Format(PyExc_AttributeError,
Walter Dörwald75163602007-06-11 15:47:13 +00002142 "type object '%.50s' has no attribute '%U'",
2143 type->tp_name, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002144 return NULL;
2145}
2146
2147static int
2148type_setattro(PyTypeObject *type, PyObject *name, PyObject *value)
2149{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002150 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
2151 PyErr_Format(
2152 PyExc_TypeError,
2153 "can't set attributes of built-in/extension type '%s'",
2154 type->tp_name);
2155 return -1;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002156 }
Guido van Rossum8d24ee92003-03-24 23:49:49 +00002157 /* XXX Example of how I expect this to be used...
2158 if (update_subclasses(type, name, invalidate_cache, NULL) < 0)
2159 return -1;
2160 */
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002161 if (PyObject_GenericSetAttr((PyObject *)type, name, value) < 0)
2162 return -1;
2163 return update_slot(type, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002164}
2165
2166static void
2167type_dealloc(PyTypeObject *type)
2168{
Guido van Rossume5c691a2003-03-07 15:13:17 +00002169 PyHeapTypeObject *et;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002170
2171 /* Assert this is a heap-allocated type object */
2172 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002173 _PyObject_GC_UNTRACK(type);
Guido van Rossum1c450732001-10-08 15:18:27 +00002174 PyObject_ClearWeakRefs((PyObject *)type);
Guido van Rossume5c691a2003-03-07 15:13:17 +00002175 et = (PyHeapTypeObject *)type;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002176 Py_XDECREF(type->tp_base);
2177 Py_XDECREF(type->tp_dict);
2178 Py_XDECREF(type->tp_bases);
2179 Py_XDECREF(type->tp_mro);
Guido van Rossum687ae002001-10-15 22:03:32 +00002180 Py_XDECREF(type->tp_cache);
Guido van Rossum1c450732001-10-08 15:18:27 +00002181 Py_XDECREF(type->tp_subclasses);
Guido van Rossumd8faa362007-04-27 19:54:29 +00002182 /* A type's tp_doc is heap allocated, unlike the tp_doc slots
2183 * of most other objects. It's okay to cast it to char *.
2184 */
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00002185 PyObject_Free((char *)type->tp_doc);
Georg Brandlc255c7b2006-02-20 22:27:28 +00002186 Py_XDECREF(et->ht_name);
2187 Py_XDECREF(et->ht_slots);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002188 Py_Type(type)->tp_free((PyObject *)type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002189}
2190
Guido van Rossum1c450732001-10-08 15:18:27 +00002191static PyObject *
2192type_subclasses(PyTypeObject *type, PyObject *args_ignored)
2193{
2194 PyObject *list, *raw, *ref;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002195 Py_ssize_t i, n;
Guido van Rossum1c450732001-10-08 15:18:27 +00002196
2197 list = PyList_New(0);
2198 if (list == NULL)
2199 return NULL;
2200 raw = type->tp_subclasses;
2201 if (raw == NULL)
2202 return list;
2203 assert(PyList_Check(raw));
2204 n = PyList_GET_SIZE(raw);
2205 for (i = 0; i < n; i++) {
2206 ref = PyList_GET_ITEM(raw, i);
Tim Peters44383382001-10-08 16:49:26 +00002207 assert(PyWeakref_CheckRef(ref));
Guido van Rossum1c450732001-10-08 15:18:27 +00002208 ref = PyWeakref_GET_OBJECT(ref);
2209 if (ref != Py_None) {
2210 if (PyList_Append(list, ref) < 0) {
2211 Py_DECREF(list);
2212 return NULL;
2213 }
2214 }
2215 }
2216 return list;
2217}
2218
Guido van Rossum47374822007-08-02 16:48:17 +00002219static PyObject *
2220type_prepare(PyObject *self, PyObject *args, PyObject *kwds)
2221{
2222 return PyDict_New();
2223}
2224
Tim Peters6d6c1a32001-08-02 04:15:00 +00002225static PyMethodDef type_methods[] = {
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002226 {"mro", (PyCFunction)mro_external, METH_NOARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002227 PyDoc_STR("mro() -> list\nreturn a type's method resolution order")},
Guido van Rossum1c450732001-10-08 15:18:27 +00002228 {"__subclasses__", (PyCFunction)type_subclasses, METH_NOARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002229 PyDoc_STR("__subclasses__() -> list of immediate subclasses")},
Guido van Rossum47374822007-08-02 16:48:17 +00002230 {"__prepare__", (PyCFunction)type_prepare,
2231 METH_VARARGS | METH_KEYWORDS | METH_CLASS,
2232 PyDoc_STR("__prepare__() -> dict\n"
2233 "used to create the namespace for the class statement")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002234 {0}
2235};
2236
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002237PyDoc_STRVAR(type_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00002238"type(object) -> the object's type\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002239"type(name, bases, dict) -> a new type");
Tim Peters6d6c1a32001-08-02 04:15:00 +00002240
Guido van Rossum048eb752001-10-02 21:24:57 +00002241static int
2242type_traverse(PyTypeObject *type, visitproc visit, void *arg)
2243{
Guido van Rossuma3862092002-06-10 15:24:42 +00002244 /* Because of type_is_gc(), the collector only calls this
2245 for heaptypes. */
2246 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002247
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002248 Py_VISIT(type->tp_dict);
2249 Py_VISIT(type->tp_cache);
2250 Py_VISIT(type->tp_mro);
2251 Py_VISIT(type->tp_bases);
2252 Py_VISIT(type->tp_base);
Guido van Rossuma3862092002-06-10 15:24:42 +00002253
2254 /* There's no need to visit type->tp_subclasses or
Georg Brandlc255c7b2006-02-20 22:27:28 +00002255 ((PyHeapTypeObject *)type)->ht_slots, because they can't be involved
Guido van Rossuma3862092002-06-10 15:24:42 +00002256 in cycles; tp_subclasses is a list of weak references,
2257 and slots is a tuple of strings. */
Guido van Rossum048eb752001-10-02 21:24:57 +00002258
Guido van Rossum048eb752001-10-02 21:24:57 +00002259 return 0;
2260}
2261
2262static int
2263type_clear(PyTypeObject *type)
2264{
Guido van Rossuma3862092002-06-10 15:24:42 +00002265 /* Because of type_is_gc(), the collector only calls this
2266 for heaptypes. */
2267 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002268
Guido van Rossuma3862092002-06-10 15:24:42 +00002269 /* The only field we need to clear is tp_mro, which is part of a
2270 hard cycle (its first element is the class itself) that won't
2271 be broken otherwise (it's a tuple and tuples don't have a
2272 tp_clear handler). None of the other fields need to be
2273 cleared, and here's why:
Guido van Rossum048eb752001-10-02 21:24:57 +00002274
Guido van Rossuma3862092002-06-10 15:24:42 +00002275 tp_dict:
2276 It is a dict, so the collector will call its tp_clear.
2277
2278 tp_cache:
2279 Not used; if it were, it would be a dict.
2280
2281 tp_bases, tp_base:
2282 If these are involved in a cycle, there must be at least
2283 one other, mutable object in the cycle, e.g. a base
2284 class's dict; the cycle will be broken that way.
2285
2286 tp_subclasses:
2287 A list of weak references can't be part of a cycle; and
2288 lists have their own tp_clear.
2289
Guido van Rossume5c691a2003-03-07 15:13:17 +00002290 slots (in PyHeapTypeObject):
Guido van Rossuma3862092002-06-10 15:24:42 +00002291 A tuple of strings can't be part of a cycle.
2292 */
2293
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002294 Py_CLEAR(type->tp_mro);
Guido van Rossum048eb752001-10-02 21:24:57 +00002295
2296 return 0;
2297}
2298
2299static int
2300type_is_gc(PyTypeObject *type)
2301{
2302 return type->tp_flags & Py_TPFLAGS_HEAPTYPE;
2303}
2304
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002305PyTypeObject PyType_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002306 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002307 "type", /* tp_name */
Guido van Rossume5c691a2003-03-07 15:13:17 +00002308 sizeof(PyHeapTypeObject), /* tp_basicsize */
Guido van Rossum6f799372001-09-20 20:46:19 +00002309 sizeof(PyMemberDef), /* tp_itemsize */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002310 (destructor)type_dealloc, /* tp_dealloc */
2311 0, /* tp_print */
Guido van Rossumd8faa362007-04-27 19:54:29 +00002312 0, /* tp_getattr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002313 0, /* tp_setattr */
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002314 0, /* tp_compare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002315 (reprfunc)type_repr, /* tp_repr */
2316 0, /* tp_as_number */
2317 0, /* tp_as_sequence */
2318 0, /* tp_as_mapping */
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002319 0, /* tp_hash */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002320 (ternaryfunc)type_call, /* tp_call */
2321 0, /* tp_str */
2322 (getattrofunc)type_getattro, /* tp_getattro */
2323 (setattrofunc)type_setattro, /* tp_setattro */
2324 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00002325 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
Thomas Wouters27d517b2007-02-25 20:39:11 +00002326 Py_TPFLAGS_BASETYPE | Py_TPFLAGS_TYPE_SUBCLASS, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002327 type_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00002328 (traverseproc)type_traverse, /* tp_traverse */
2329 (inquiry)type_clear, /* tp_clear */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002330 0, /* tp_richcompare */
Guido van Rossum1c450732001-10-08 15:18:27 +00002331 offsetof(PyTypeObject, tp_weaklist), /* tp_weaklistoffset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002332 0, /* tp_iter */
2333 0, /* tp_iternext */
2334 type_methods, /* tp_methods */
2335 type_members, /* tp_members */
2336 type_getsets, /* tp_getset */
2337 0, /* tp_base */
2338 0, /* tp_dict */
2339 0, /* tp_descr_get */
2340 0, /* tp_descr_set */
2341 offsetof(PyTypeObject, tp_dict), /* tp_dictoffset */
Guido van Rossumd8faa362007-04-27 19:54:29 +00002342 type_init, /* tp_init */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002343 0, /* tp_alloc */
2344 type_new, /* tp_new */
Guido van Rossumd8faa362007-04-27 19:54:29 +00002345 PyObject_GC_Del, /* tp_free */
Guido van Rossum048eb752001-10-02 21:24:57 +00002346 (inquiry)type_is_gc, /* tp_is_gc */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002347};
Tim Peters6d6c1a32001-08-02 04:15:00 +00002348
2349
2350/* The base type of all types (eventually)... except itself. */
2351
Guido van Rossumd8faa362007-04-27 19:54:29 +00002352/* You may wonder why object.__new__() only complains about arguments
2353 when object.__init__() is not overridden, and vice versa.
2354
2355 Consider the use cases:
2356
2357 1. When neither is overridden, we want to hear complaints about
2358 excess (i.e., any) arguments, since their presence could
2359 indicate there's a bug.
2360
2361 2. When defining an Immutable type, we are likely to override only
2362 __new__(), since __init__() is called too late to initialize an
2363 Immutable object. Since __new__() defines the signature for the
2364 type, it would be a pain to have to override __init__() just to
2365 stop it from complaining about excess arguments.
2366
2367 3. When defining a Mutable type, we are likely to override only
2368 __init__(). So here the converse reasoning applies: we don't
2369 want to have to override __new__() just to stop it from
2370 complaining.
2371
2372 4. When __init__() is overridden, and the subclass __init__() calls
2373 object.__init__(), the latter should complain about excess
2374 arguments; ditto for __new__().
2375
2376 Use cases 2 and 3 make it unattractive to unconditionally check for
2377 excess arguments. The best solution that addresses all four use
2378 cases is as follows: __init__() complains about excess arguments
2379 unless __new__() is overridden and __init__() is not overridden
2380 (IOW, if __init__() is overridden or __new__() is not overridden);
2381 symmetrically, __new__() complains about excess arguments unless
2382 __init__() is overridden and __new__() is not overridden
2383 (IOW, if __new__() is overridden or __init__() is not overridden).
2384
2385 However, for backwards compatibility, this breaks too much code.
2386 Therefore, in 2.6, we'll *warn* about excess arguments when both
2387 methods are overridden; for all other cases we'll use the above
2388 rules.
2389
2390*/
2391
2392/* Forward */
2393static PyObject *
2394object_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
2395
2396static int
2397excess_args(PyObject *args, PyObject *kwds)
2398{
2399 return PyTuple_GET_SIZE(args) ||
2400 (kwds && PyDict_Check(kwds) && PyDict_Size(kwds));
2401}
2402
Tim Peters6d6c1a32001-08-02 04:15:00 +00002403static int
2404object_init(PyObject *self, PyObject *args, PyObject *kwds)
2405{
Guido van Rossumd8faa362007-04-27 19:54:29 +00002406 int err = 0;
2407 if (excess_args(args, kwds)) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002408 PyTypeObject *type = Py_Type(self);
Guido van Rossumd8faa362007-04-27 19:54:29 +00002409 if (type->tp_init != object_init &&
2410 type->tp_new != object_new)
2411 {
2412 err = PyErr_WarnEx(PyExc_DeprecationWarning,
2413 "object.__init__() takes no parameters",
2414 1);
2415 }
2416 else if (type->tp_init != object_init ||
2417 type->tp_new == object_new)
2418 {
2419 PyErr_SetString(PyExc_TypeError,
2420 "object.__init__() takes no parameters");
2421 err = -1;
2422 }
2423 }
2424 return err;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002425}
2426
Guido van Rossum298e4212003-02-13 16:30:16 +00002427static PyObject *
2428object_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2429{
Guido van Rossumd8faa362007-04-27 19:54:29 +00002430 int err = 0;
2431 if (excess_args(args, kwds)) {
2432 if (type->tp_new != object_new &&
2433 type->tp_init != object_init)
2434 {
2435 err = PyErr_WarnEx(PyExc_DeprecationWarning,
2436 "object.__new__() takes no parameters",
2437 1);
2438 }
2439 else if (type->tp_new != object_new ||
2440 type->tp_init == object_init)
2441 {
2442 PyErr_SetString(PyExc_TypeError,
2443 "object.__new__() takes no parameters");
2444 err = -1;
2445 }
Guido van Rossum298e4212003-02-13 16:30:16 +00002446 }
Guido van Rossumd8faa362007-04-27 19:54:29 +00002447 if (err < 0)
2448 return NULL;
Guido van Rossum298e4212003-02-13 16:30:16 +00002449 return type->tp_alloc(type, 0);
2450}
2451
Tim Peters6d6c1a32001-08-02 04:15:00 +00002452static void
2453object_dealloc(PyObject *self)
2454{
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002455 Py_Type(self)->tp_free(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002456}
2457
Guido van Rossum8e248182001-08-12 05:17:56 +00002458static PyObject *
2459object_repr(PyObject *self)
2460{
Guido van Rossum76e69632001-08-16 18:52:43 +00002461 PyTypeObject *type;
Barry Warsaw7ce36942001-08-24 18:34:26 +00002462 PyObject *mod, *name, *rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00002463
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002464 type = Py_Type(self);
Guido van Rossum76e69632001-08-16 18:52:43 +00002465 mod = type_module(type, NULL);
2466 if (mod == NULL)
2467 PyErr_Clear();
Martin v. Löwis5b222132007-06-10 09:51:05 +00002468 else if (!PyUnicode_Check(mod)) {
Guido van Rossum76e69632001-08-16 18:52:43 +00002469 Py_DECREF(mod);
2470 mod = NULL;
2471 }
2472 name = type_name(type, NULL);
2473 if (name == NULL)
2474 return NULL;
Walter Dörwald4dbd01b2007-06-11 14:03:45 +00002475 if (mod != NULL && PyUnicode_CompareWithASCIIString(mod, "__builtin__"))
2476 rtn = PyUnicode_FromFormat("<%U.%U object at %p>", mod, name, self);
Guido van Rossum76e69632001-08-16 18:52:43 +00002477 else
Walter Dörwald1ab83302007-05-18 17:15:44 +00002478 rtn = PyUnicode_FromFormat("<%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00002479 type->tp_name, self);
Guido van Rossum76e69632001-08-16 18:52:43 +00002480 Py_XDECREF(mod);
2481 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +00002482 return rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00002483}
2484
Guido van Rossumb8f63662001-08-15 23:57:02 +00002485static PyObject *
2486object_str(PyObject *self)
2487{
2488 unaryfunc f;
2489
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002490 f = Py_Type(self)->tp_repr;
Guido van Rossumb8f63662001-08-15 23:57:02 +00002491 if (f == NULL)
2492 f = object_repr;
2493 return f(self);
2494}
2495
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002496static PyObject *
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002497object_richcompare(PyObject *self, PyObject *other, int op)
2498{
2499 PyObject *res;
2500
2501 switch (op) {
2502
2503 case Py_EQ:
2504 res = (self == other) ? Py_True : Py_False;
Guido van Rossum6b18a5b2007-03-29 20:49:57 +00002505 Py_INCREF(res);
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002506 break;
2507
2508 case Py_NE:
Guido van Rossume27dc722007-03-27 22:37:34 +00002509 /* By default, != returns the opposite of ==,
2510 unless the latter returns NotImplemented. */
2511 res = PyObject_RichCompare(self, other, Py_EQ);
2512 if (res != NULL && res != Py_NotImplemented) {
2513 int ok = PyObject_IsTrue(res);
2514 Py_DECREF(res);
2515 if (ok < 0)
2516 res = NULL;
2517 else {
2518 if (ok)
2519 res = Py_False;
2520 else
2521 res = Py_True;
2522 Py_INCREF(res);
2523 }
2524 }
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002525 break;
2526
2527 default:
2528 res = Py_NotImplemented;
Guido van Rossum6b18a5b2007-03-29 20:49:57 +00002529 Py_INCREF(res);
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002530 break;
2531 }
2532
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002533 return res;
2534}
2535
2536static PyObject *
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002537object_get_class(PyObject *self, void *closure)
2538{
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002539 Py_INCREF(Py_Type(self));
2540 return (PyObject *)(Py_Type(self));
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002541}
2542
2543static int
2544equiv_structs(PyTypeObject *a, PyTypeObject *b)
2545{
2546 return a == b ||
2547 (a != NULL &&
2548 b != NULL &&
2549 a->tp_basicsize == b->tp_basicsize &&
2550 a->tp_itemsize == b->tp_itemsize &&
2551 a->tp_dictoffset == b->tp_dictoffset &&
2552 a->tp_weaklistoffset == b->tp_weaklistoffset &&
2553 ((a->tp_flags & Py_TPFLAGS_HAVE_GC) ==
2554 (b->tp_flags & Py_TPFLAGS_HAVE_GC)));
2555}
2556
2557static int
2558same_slots_added(PyTypeObject *a, PyTypeObject *b)
2559{
2560 PyTypeObject *base = a->tp_base;
Martin v. Löwiseb079f12006-02-16 14:32:27 +00002561 Py_ssize_t size;
Guido van Rossumd8faa362007-04-27 19:54:29 +00002562 PyObject *slots_a, *slots_b;
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002563
2564 if (base != b->tp_base)
2565 return 0;
2566 if (equiv_structs(a, base) && equiv_structs(b, base))
2567 return 1;
2568 size = base->tp_basicsize;
2569 if (a->tp_dictoffset == size && b->tp_dictoffset == size)
2570 size += sizeof(PyObject *);
2571 if (a->tp_weaklistoffset == size && b->tp_weaklistoffset == size)
2572 size += sizeof(PyObject *);
Guido van Rossumd8faa362007-04-27 19:54:29 +00002573
2574 /* Check slots compliance */
2575 slots_a = ((PyHeapTypeObject *)a)->ht_slots;
2576 slots_b = ((PyHeapTypeObject *)b)->ht_slots;
2577 if (slots_a && slots_b) {
2578 if (PyObject_Compare(slots_a, slots_b) != 0)
2579 return 0;
2580 size += sizeof(PyObject *) * PyTuple_GET_SIZE(slots_a);
2581 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002582 return size == a->tp_basicsize && size == b->tp_basicsize;
2583}
2584
2585static int
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002586compatible_for_assignment(PyTypeObject* oldto, PyTypeObject* newto, char* attr)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002587{
2588 PyTypeObject *newbase, *oldbase;
2589
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002590 if (newto->tp_dealloc != oldto->tp_dealloc ||
2591 newto->tp_free != oldto->tp_free)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002592 {
2593 PyErr_Format(PyExc_TypeError,
2594 "%s assignment: "
2595 "'%s' deallocator differs from '%s'",
2596 attr,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002597 newto->tp_name,
2598 oldto->tp_name);
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002599 return 0;
2600 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002601 newbase = newto;
2602 oldbase = oldto;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002603 while (equiv_structs(newbase, newbase->tp_base))
2604 newbase = newbase->tp_base;
2605 while (equiv_structs(oldbase, oldbase->tp_base))
2606 oldbase = oldbase->tp_base;
2607 if (newbase != oldbase &&
2608 (newbase->tp_base != oldbase->tp_base ||
2609 !same_slots_added(newbase, oldbase))) {
2610 PyErr_Format(PyExc_TypeError,
2611 "%s assignment: "
2612 "'%s' object layout differs from '%s'",
2613 attr,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002614 newto->tp_name,
2615 oldto->tp_name);
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002616 return 0;
2617 }
Tim Petersea7f75d2002-12-07 21:39:16 +00002618
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002619 return 1;
2620}
2621
2622static int
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002623object_set_class(PyObject *self, PyObject *value, void *closure)
2624{
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002625 PyTypeObject *oldto = Py_Type(self);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002626 PyTypeObject *newto;
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002627
Guido van Rossumb6b89422002-04-15 01:03:30 +00002628 if (value == NULL) {
2629 PyErr_SetString(PyExc_TypeError,
2630 "can't delete __class__ attribute");
2631 return -1;
2632 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002633 if (!PyType_Check(value)) {
2634 PyErr_Format(PyExc_TypeError,
2635 "__class__ must be set to new-style class, not '%s' object",
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002636 Py_Type(value)->tp_name);
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002637 return -1;
2638 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002639 newto = (PyTypeObject *)value;
2640 if (!(newto->tp_flags & Py_TPFLAGS_HEAPTYPE) ||
2641 !(oldto->tp_flags & Py_TPFLAGS_HEAPTYPE))
Guido van Rossum40af8892002-08-10 05:42:07 +00002642 {
2643 PyErr_Format(PyExc_TypeError,
2644 "__class__ assignment: only for heap types");
2645 return -1;
2646 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002647 if (compatible_for_assignment(newto, oldto, "__class__")) {
2648 Py_INCREF(newto);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002649 Py_Type(self) = newto;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002650 Py_DECREF(oldto);
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002651 return 0;
2652 }
2653 else {
Guido van Rossum9ee4b942002-05-24 18:47:47 +00002654 return -1;
2655 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002656}
2657
2658static PyGetSetDef object_getsets[] = {
2659 {"__class__", object_get_class, object_set_class,
Neal Norwitz858e34f2002-08-13 17:18:45 +00002660 PyDoc_STR("the object's class")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002661 {0}
2662};
2663
Guido van Rossumc53f0092003-02-18 22:05:12 +00002664
Guido van Rossum036f9992003-02-21 22:02:54 +00002665/* Stuff to implement __reduce_ex__ for pickle protocols >= 2.
2666 We fall back to helpers in copy_reg for:
2667 - pickle protocols < 2
2668 - calculating the list of slot names (done only once per class)
2669 - the __newobj__ function (which is used as a token but never called)
2670*/
2671
2672static PyObject *
2673import_copy_reg(void)
2674{
2675 static PyObject *copy_reg_str;
Guido van Rossum3926a632001-09-25 16:25:58 +00002676
2677 if (!copy_reg_str) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00002678 copy_reg_str = PyUnicode_InternFromString("copy_reg");
Guido van Rossum3926a632001-09-25 16:25:58 +00002679 if (copy_reg_str == NULL)
2680 return NULL;
2681 }
Guido van Rossum036f9992003-02-21 22:02:54 +00002682
2683 return PyImport_Import(copy_reg_str);
2684}
2685
2686static PyObject *
2687slotnames(PyObject *cls)
2688{
2689 PyObject *clsdict;
2690 PyObject *copy_reg;
2691 PyObject *slotnames;
2692
2693 if (!PyType_Check(cls)) {
2694 Py_INCREF(Py_None);
2695 return Py_None;
2696 }
2697
2698 clsdict = ((PyTypeObject *)cls)->tp_dict;
2699 slotnames = PyDict_GetItemString(clsdict, "__slotnames__");
Armin Rigoec862b92005-09-24 22:58:41 +00002700 if (slotnames != NULL && PyList_Check(slotnames)) {
Guido van Rossum036f9992003-02-21 22:02:54 +00002701 Py_INCREF(slotnames);
2702 return slotnames;
2703 }
2704
2705 copy_reg = import_copy_reg();
2706 if (copy_reg == NULL)
2707 return NULL;
2708
2709 slotnames = PyObject_CallMethod(copy_reg, "_slotnames", "O", cls);
2710 Py_DECREF(copy_reg);
2711 if (slotnames != NULL &&
2712 slotnames != Py_None &&
2713 !PyList_Check(slotnames))
2714 {
2715 PyErr_SetString(PyExc_TypeError,
2716 "copy_reg._slotnames didn't return a list or None");
2717 Py_DECREF(slotnames);
2718 slotnames = NULL;
2719 }
2720
2721 return slotnames;
2722}
2723
2724static PyObject *
2725reduce_2(PyObject *obj)
2726{
2727 PyObject *cls, *getnewargs;
2728 PyObject *args = NULL, *args2 = NULL;
2729 PyObject *getstate = NULL, *state = NULL, *names = NULL;
2730 PyObject *slots = NULL, *listitems = NULL, *dictitems = NULL;
2731 PyObject *copy_reg = NULL, *newobj = NULL, *res = NULL;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002732 Py_ssize_t i, n;
Guido van Rossum036f9992003-02-21 22:02:54 +00002733
2734 cls = PyObject_GetAttrString(obj, "__class__");
2735 if (cls == NULL)
2736 return NULL;
2737
2738 getnewargs = PyObject_GetAttrString(obj, "__getnewargs__");
2739 if (getnewargs != NULL) {
2740 args = PyObject_CallObject(getnewargs, NULL);
2741 Py_DECREF(getnewargs);
2742 if (args != NULL && !PyTuple_Check(args)) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002743 PyErr_Format(PyExc_TypeError,
2744 "__getnewargs__ should return a tuple, "
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002745 "not '%.200s'", Py_Type(args)->tp_name);
Guido van Rossum036f9992003-02-21 22:02:54 +00002746 goto end;
2747 }
2748 }
2749 else {
2750 PyErr_Clear();
2751 args = PyTuple_New(0);
2752 }
2753 if (args == NULL)
2754 goto end;
2755
2756 getstate = PyObject_GetAttrString(obj, "__getstate__");
2757 if (getstate != NULL) {
2758 state = PyObject_CallObject(getstate, NULL);
2759 Py_DECREF(getstate);
Neal Norwitze2fdc612003-06-08 13:19:58 +00002760 if (state == NULL)
2761 goto end;
Guido van Rossum036f9992003-02-21 22:02:54 +00002762 }
2763 else {
Jim Fulton8a1a5942004-02-08 04:21:26 +00002764 PyErr_Clear();
Guido van Rossum036f9992003-02-21 22:02:54 +00002765 state = PyObject_GetAttrString(obj, "__dict__");
2766 if (state == NULL) {
2767 PyErr_Clear();
2768 state = Py_None;
2769 Py_INCREF(state);
2770 }
2771 names = slotnames(cls);
2772 if (names == NULL)
2773 goto end;
2774 if (names != Py_None) {
2775 assert(PyList_Check(names));
2776 slots = PyDict_New();
2777 if (slots == NULL)
2778 goto end;
2779 n = 0;
2780 /* Can't pre-compute the list size; the list
2781 is stored on the class so accessible to other
2782 threads, which may be run by DECREF */
2783 for (i = 0; i < PyList_GET_SIZE(names); i++) {
2784 PyObject *name, *value;
2785 name = PyList_GET_ITEM(names, i);
2786 value = PyObject_GetAttr(obj, name);
2787 if (value == NULL)
2788 PyErr_Clear();
2789 else {
2790 int err = PyDict_SetItem(slots, name,
2791 value);
2792 Py_DECREF(value);
2793 if (err)
2794 goto end;
2795 n++;
2796 }
2797 }
2798 if (n) {
2799 state = Py_BuildValue("(NO)", state, slots);
2800 if (state == NULL)
2801 goto end;
2802 }
2803 }
2804 }
2805
2806 if (!PyList_Check(obj)) {
2807 listitems = Py_None;
2808 Py_INCREF(listitems);
2809 }
2810 else {
2811 listitems = PyObject_GetIter(obj);
2812 if (listitems == NULL)
2813 goto end;
2814 }
2815
2816 if (!PyDict_Check(obj)) {
2817 dictitems = Py_None;
2818 Py_INCREF(dictitems);
2819 }
2820 else {
Guido van Rossumcc2b0162007-02-11 06:12:03 +00002821 PyObject *items = PyObject_CallMethod(obj, "items", "");
2822 if (items == NULL)
2823 goto end;
2824 dictitems = PyObject_GetIter(items);
2825 Py_DECREF(items);
Guido van Rossum036f9992003-02-21 22:02:54 +00002826 if (dictitems == NULL)
2827 goto end;
2828 }
2829
2830 copy_reg = import_copy_reg();
2831 if (copy_reg == NULL)
2832 goto end;
2833 newobj = PyObject_GetAttrString(copy_reg, "__newobj__");
2834 if (newobj == NULL)
2835 goto end;
2836
2837 n = PyTuple_GET_SIZE(args);
2838 args2 = PyTuple_New(n+1);
2839 if (args2 == NULL)
2840 goto end;
2841 PyTuple_SET_ITEM(args2, 0, cls);
2842 cls = NULL;
2843 for (i = 0; i < n; i++) {
2844 PyObject *v = PyTuple_GET_ITEM(args, i);
2845 Py_INCREF(v);
2846 PyTuple_SET_ITEM(args2, i+1, v);
2847 }
2848
Raymond Hettinger8ae46892003-10-12 19:09:37 +00002849 res = PyTuple_Pack(5, newobj, args2, state, listitems, dictitems);
Guido van Rossum036f9992003-02-21 22:02:54 +00002850
2851 end:
2852 Py_XDECREF(cls);
2853 Py_XDECREF(args);
2854 Py_XDECREF(args2);
Jeremy Hyltond06483c2003-04-09 21:01:42 +00002855 Py_XDECREF(slots);
Guido van Rossum036f9992003-02-21 22:02:54 +00002856 Py_XDECREF(state);
2857 Py_XDECREF(names);
2858 Py_XDECREF(listitems);
2859 Py_XDECREF(dictitems);
2860 Py_XDECREF(copy_reg);
2861 Py_XDECREF(newobj);
2862 return res;
2863}
2864
Guido van Rossumd8faa362007-04-27 19:54:29 +00002865/*
2866 * There were two problems when object.__reduce__ and object.__reduce_ex__
2867 * were implemented in the same function:
2868 * - trying to pickle an object with a custom __reduce__ method that
2869 * fell back to object.__reduce__ in certain circumstances led to
2870 * infinite recursion at Python level and eventual RuntimeError.
2871 * - Pickling objects that lied about their type by overwriting the
2872 * __class__ descriptor could lead to infinite recursion at C level
2873 * and eventual segfault.
2874 *
2875 * Because of backwards compatibility, the two methods still have to
2876 * behave in the same way, even if this is not required by the pickle
2877 * protocol. This common functionality was moved to the _common_reduce
2878 * function.
2879 */
2880static PyObject *
2881_common_reduce(PyObject *self, int proto)
2882{
2883 PyObject *copy_reg, *res;
2884
2885 if (proto >= 2)
2886 return reduce_2(self);
2887
2888 copy_reg = import_copy_reg();
2889 if (!copy_reg)
2890 return NULL;
2891
2892 res = PyEval_CallMethod(copy_reg, "_reduce_ex", "(Oi)", self, proto);
2893 Py_DECREF(copy_reg);
2894
2895 return res;
2896}
2897
2898static PyObject *
2899object_reduce(PyObject *self, PyObject *args)
2900{
2901 int proto = 0;
2902
2903 if (!PyArg_ParseTuple(args, "|i:__reduce__", &proto))
2904 return NULL;
2905
2906 return _common_reduce(self, proto);
2907}
2908
Guido van Rossum036f9992003-02-21 22:02:54 +00002909static PyObject *
2910object_reduce_ex(PyObject *self, PyObject *args)
2911{
Guido van Rossumd8faa362007-04-27 19:54:29 +00002912 PyObject *reduce, *res;
Guido van Rossum036f9992003-02-21 22:02:54 +00002913 int proto = 0;
2914
2915 if (!PyArg_ParseTuple(args, "|i:__reduce_ex__", &proto))
2916 return NULL;
2917
2918 reduce = PyObject_GetAttrString(self, "__reduce__");
2919 if (reduce == NULL)
2920 PyErr_Clear();
2921 else {
2922 PyObject *cls, *clsreduce, *objreduce;
2923 int override;
2924 cls = PyObject_GetAttrString(self, "__class__");
2925 if (cls == NULL) {
2926 Py_DECREF(reduce);
2927 return NULL;
2928 }
2929 clsreduce = PyObject_GetAttrString(cls, "__reduce__");
2930 Py_DECREF(cls);
2931 if (clsreduce == NULL) {
2932 Py_DECREF(reduce);
2933 return NULL;
2934 }
2935 objreduce = PyDict_GetItemString(PyBaseObject_Type.tp_dict,
2936 "__reduce__");
2937 override = (clsreduce != objreduce);
2938 Py_DECREF(clsreduce);
2939 if (override) {
2940 res = PyObject_CallObject(reduce, NULL);
2941 Py_DECREF(reduce);
2942 return res;
2943 }
2944 else
2945 Py_DECREF(reduce);
2946 }
2947
Guido van Rossumd8faa362007-04-27 19:54:29 +00002948 return _common_reduce(self, proto);
Guido van Rossum3926a632001-09-25 16:25:58 +00002949}
2950
Eric Smith8c663262007-08-25 02:26:07 +00002951
2952/*
2953 from PEP 3101, this code implements:
2954
2955 class object:
2956 def __format__(self, format_spec):
2957 return format(str(self), format_spec)
2958*/
2959static PyObject *
2960object_format(PyObject *self, PyObject *args)
2961{
2962 PyObject *format_spec;
2963 PyObject *self_as_str = NULL;
2964 PyObject *result = NULL;
2965 PyObject *format_meth = NULL;
2966
2967 if (!PyArg_ParseTuple(args, "O:__format__", &format_spec))
2968 return NULL;
2969 if (!PyUnicode_Check(format_spec)) {
2970 PyErr_SetString(PyExc_TypeError, "Unicode object required");
2971 return NULL;
2972 }
2973
2974 self_as_str = PyObject_Unicode(self);
2975 if (self_as_str != NULL) {
2976 /* find the format function */
2977 format_meth = PyObject_GetAttrString(self_as_str, "__format__");
2978 if (format_meth != NULL) {
2979 /* and call it */
2980 result = PyObject_CallFunctionObjArgs(format_meth, format_spec, NULL);
2981 }
2982 }
2983
2984 Py_XDECREF(self_as_str);
2985 Py_XDECREF(format_meth);
2986
2987 return result;
2988}
2989
Guido van Rossum3926a632001-09-25 16:25:58 +00002990static PyMethodDef object_methods[] = {
Guido van Rossumc53f0092003-02-18 22:05:12 +00002991 {"__reduce_ex__", object_reduce_ex, METH_VARARGS,
2992 PyDoc_STR("helper for pickle")},
Guido van Rossumd8faa362007-04-27 19:54:29 +00002993 {"__reduce__", object_reduce, METH_VARARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002994 PyDoc_STR("helper for pickle")},
Eric Smith8c663262007-08-25 02:26:07 +00002995 {"__format__", object_format, METH_VARARGS,
2996 PyDoc_STR("default object formatter")},
Guido van Rossum3926a632001-09-25 16:25:58 +00002997 {0}
2998};
2999
Guido van Rossum036f9992003-02-21 22:02:54 +00003000
Tim Peters6d6c1a32001-08-02 04:15:00 +00003001PyTypeObject PyBaseObject_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003002 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003003 "object", /* tp_name */
3004 sizeof(PyObject), /* tp_basicsize */
3005 0, /* tp_itemsize */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003006 object_dealloc, /* tp_dealloc */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003007 0, /* tp_print */
Guido van Rossumd8faa362007-04-27 19:54:29 +00003008 0, /* tp_getattr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003009 0, /* tp_setattr */
3010 0, /* tp_compare */
Guido van Rossumb8f63662001-08-15 23:57:02 +00003011 object_repr, /* tp_repr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003012 0, /* tp_as_number */
3013 0, /* tp_as_sequence */
3014 0, /* tp_as_mapping */
Guido van Rossum50e9fb92006-08-17 05:42:55 +00003015 (hashfunc)_Py_HashPointer, /* tp_hash */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003016 0, /* tp_call */
Guido van Rossumb8f63662001-08-15 23:57:02 +00003017 object_str, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003018 PyObject_GenericGetAttr, /* tp_getattro */
Guido van Rossum13d52f02001-08-10 21:24:08 +00003019 PyObject_GenericSetAttr, /* tp_setattro */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003020 0, /* tp_as_buffer */
3021 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Neal Norwitz5dc2a372002-08-13 22:19:13 +00003022 PyDoc_STR("The most base type"), /* tp_doc */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003023 0, /* tp_traverse */
3024 0, /* tp_clear */
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003025 object_richcompare, /* tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003026 0, /* tp_weaklistoffset */
3027 0, /* tp_iter */
3028 0, /* tp_iternext */
Guido van Rossum3926a632001-09-25 16:25:58 +00003029 object_methods, /* tp_methods */
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003030 0, /* tp_members */
3031 object_getsets, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003032 0, /* tp_base */
3033 0, /* tp_dict */
3034 0, /* tp_descr_get */
3035 0, /* tp_descr_set */
3036 0, /* tp_dictoffset */
3037 object_init, /* tp_init */
3038 PyType_GenericAlloc, /* tp_alloc */
Guido van Rossum298e4212003-02-13 16:30:16 +00003039 object_new, /* tp_new */
Guido van Rossumd8faa362007-04-27 19:54:29 +00003040 PyObject_Del, /* tp_free */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003041};
3042
3043
Guido van Rossum50e9fb92006-08-17 05:42:55 +00003044/* Add the methods from tp_methods to the __dict__ in a type object */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003045
3046static int
3047add_methods(PyTypeObject *type, PyMethodDef *meth)
3048{
Guido van Rossum687ae002001-10-15 22:03:32 +00003049 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003050
3051 for (; meth->ml_name != NULL; meth++) {
3052 PyObject *descr;
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00003053 if (PyDict_GetItemString(dict, meth->ml_name) &&
3054 !(meth->ml_flags & METH_COEXIST))
3055 continue;
Fred Drake7bf97152002-03-28 05:33:33 +00003056 if (meth->ml_flags & METH_CLASS) {
3057 if (meth->ml_flags & METH_STATIC) {
3058 PyErr_SetString(PyExc_ValueError,
3059 "method cannot be both class and static");
3060 return -1;
3061 }
Tim Petersbca1cbc2002-12-09 22:56:13 +00003062 descr = PyDescr_NewClassMethod(type, meth);
Fred Drake7bf97152002-03-28 05:33:33 +00003063 }
3064 else if (meth->ml_flags & METH_STATIC) {
Guido van Rossum9af48ff2003-02-11 17:12:46 +00003065 PyObject *cfunc = PyCFunction_New(meth, NULL);
3066 if (cfunc == NULL)
3067 return -1;
3068 descr = PyStaticMethod_New(cfunc);
3069 Py_DECREF(cfunc);
Fred Drake7bf97152002-03-28 05:33:33 +00003070 }
3071 else {
3072 descr = PyDescr_NewMethod(type, meth);
3073 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003074 if (descr == NULL)
3075 return -1;
Fred Drake7bf97152002-03-28 05:33:33 +00003076 if (PyDict_SetItemString(dict, meth->ml_name, descr) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003077 return -1;
3078 Py_DECREF(descr);
3079 }
3080 return 0;
3081}
3082
3083static int
Guido van Rossum6f799372001-09-20 20:46:19 +00003084add_members(PyTypeObject *type, PyMemberDef *memb)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003085{
Guido van Rossum687ae002001-10-15 22:03:32 +00003086 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003087
3088 for (; memb->name != NULL; memb++) {
3089 PyObject *descr;
3090 if (PyDict_GetItemString(dict, memb->name))
3091 continue;
3092 descr = PyDescr_NewMember(type, memb);
3093 if (descr == NULL)
3094 return -1;
3095 if (PyDict_SetItemString(dict, memb->name, descr) < 0)
3096 return -1;
3097 Py_DECREF(descr);
3098 }
3099 return 0;
3100}
3101
3102static int
Guido van Rossum32d34c82001-09-20 21:45:26 +00003103add_getset(PyTypeObject *type, PyGetSetDef *gsp)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003104{
Guido van Rossum687ae002001-10-15 22:03:32 +00003105 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003106
3107 for (; gsp->name != NULL; gsp++) {
3108 PyObject *descr;
3109 if (PyDict_GetItemString(dict, gsp->name))
3110 continue;
3111 descr = PyDescr_NewGetSet(type, gsp);
3112
3113 if (descr == NULL)
3114 return -1;
3115 if (PyDict_SetItemString(dict, gsp->name, descr) < 0)
3116 return -1;
3117 Py_DECREF(descr);
3118 }
3119 return 0;
3120}
3121
Guido van Rossum13d52f02001-08-10 21:24:08 +00003122static void
3123inherit_special(PyTypeObject *type, PyTypeObject *base)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003124{
Martin v. Löwiseb079f12006-02-16 14:32:27 +00003125 Py_ssize_t oldsize, newsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003126
Guido van Rossum13d52f02001-08-10 21:24:08 +00003127 /* Copying basicsize is connected to the GC flags */
Neil Schemenauerc806c882001-08-29 23:54:54 +00003128 oldsize = base->tp_basicsize;
3129 newsize = type->tp_basicsize ? type->tp_basicsize : oldsize;
3130 if (!(type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
3131 (base->tp_flags & Py_TPFLAGS_HAVE_GC) &&
Guido van Rossum13d52f02001-08-10 21:24:08 +00003132 (!type->tp_traverse && !type->tp_clear)) {
Neil Schemenauerc806c882001-08-29 23:54:54 +00003133 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossum13d52f02001-08-10 21:24:08 +00003134 if (type->tp_traverse == NULL)
3135 type->tp_traverse = base->tp_traverse;
3136 if (type->tp_clear == NULL)
3137 type->tp_clear = base->tp_clear;
3138 }
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00003139 {
Guido van Rossumf884b742001-12-17 17:14:22 +00003140 /* The condition below could use some explanation.
3141 It appears that tp_new is not inherited for static types
3142 whose base class is 'object'; this seems to be a precaution
3143 so that old extension types don't suddenly become
3144 callable (object.__new__ wouldn't insure the invariants
3145 that the extension type's own factory function ensures).
3146 Heap types, of course, are under our control, so they do
3147 inherit tp_new; static extension types that specify some
3148 other built-in type as the default are considered
3149 new-style-aware so they also inherit object.__new__. */
Guido van Rossum13d52f02001-08-10 21:24:08 +00003150 if (base != &PyBaseObject_Type ||
3151 (type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
3152 if (type->tp_new == NULL)
3153 type->tp_new = base->tp_new;
3154 }
3155 }
Neil Schemenauerc806c882001-08-29 23:54:54 +00003156 type->tp_basicsize = newsize;
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00003157
3158 /* Copy other non-function slots */
3159
3160#undef COPYVAL
3161#define COPYVAL(SLOT) \
3162 if (type->SLOT == 0) type->SLOT = base->SLOT
3163
3164 COPYVAL(tp_itemsize);
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00003165 COPYVAL(tp_weaklistoffset);
3166 COPYVAL(tp_dictoffset);
Thomas Wouters27d517b2007-02-25 20:39:11 +00003167
3168 /* Setup fast subclass flags */
3169 if (PyType_IsSubtype(base, (PyTypeObject*)PyExc_BaseException))
3170 type->tp_flags |= Py_TPFLAGS_BASE_EXC_SUBCLASS;
3171 else if (PyType_IsSubtype(base, &PyType_Type))
3172 type->tp_flags |= Py_TPFLAGS_TYPE_SUBCLASS;
3173 else if (PyType_IsSubtype(base, &PyLong_Type))
3174 type->tp_flags |= Py_TPFLAGS_LONG_SUBCLASS;
3175 else if (PyType_IsSubtype(base, &PyString_Type))
3176 type->tp_flags |= Py_TPFLAGS_STRING_SUBCLASS;
3177 else if (PyType_IsSubtype(base, &PyUnicode_Type))
3178 type->tp_flags |= Py_TPFLAGS_UNICODE_SUBCLASS;
3179 else if (PyType_IsSubtype(base, &PyTuple_Type))
3180 type->tp_flags |= Py_TPFLAGS_TUPLE_SUBCLASS;
3181 else if (PyType_IsSubtype(base, &PyList_Type))
3182 type->tp_flags |= Py_TPFLAGS_LIST_SUBCLASS;
3183 else if (PyType_IsSubtype(base, &PyDict_Type))
3184 type->tp_flags |= Py_TPFLAGS_DICT_SUBCLASS;
Guido van Rossum13d52f02001-08-10 21:24:08 +00003185}
3186
Guido van Rossum38938152006-08-21 23:36:26 +00003187/* Map rich comparison operators to their __xx__ namesakes */
3188static char *name_op[] = {
3189 "__lt__",
3190 "__le__",
3191 "__eq__",
3192 "__ne__",
3193 "__gt__",
3194 "__ge__",
3195 /* These are only for overrides_cmp_or_hash(): */
3196 "__cmp__",
3197 "__hash__",
3198};
3199
3200static int
3201overrides_cmp_or_hash(PyTypeObject *type)
3202{
3203 int i;
3204 PyObject *dict = type->tp_dict;
3205
3206 assert(dict != NULL);
3207 for (i = 0; i < 8; i++) {
3208 if (PyDict_GetItemString(dict, name_op[i]) != NULL)
3209 return 1;
3210 }
3211 return 0;
3212}
3213
Guido van Rossum13d52f02001-08-10 21:24:08 +00003214static void
3215inherit_slots(PyTypeObject *type, PyTypeObject *base)
3216{
3217 PyTypeObject *basebase;
3218
3219#undef SLOTDEFINED
Tim Peters6d6c1a32001-08-02 04:15:00 +00003220#undef COPYSLOT
3221#undef COPYNUM
3222#undef COPYSEQ
3223#undef COPYMAP
Guido van Rossum5af588b2001-10-12 14:13:21 +00003224#undef COPYBUF
Guido van Rossum13d52f02001-08-10 21:24:08 +00003225
3226#define SLOTDEFINED(SLOT) \
3227 (base->SLOT != 0 && \
3228 (basebase == NULL || base->SLOT != basebase->SLOT))
3229
Tim Peters6d6c1a32001-08-02 04:15:00 +00003230#define COPYSLOT(SLOT) \
Guido van Rossum13d52f02001-08-10 21:24:08 +00003231 if (!type->SLOT && SLOTDEFINED(SLOT)) type->SLOT = base->SLOT
Tim Peters6d6c1a32001-08-02 04:15:00 +00003232
3233#define COPYNUM(SLOT) COPYSLOT(tp_as_number->SLOT)
3234#define COPYSEQ(SLOT) COPYSLOT(tp_as_sequence->SLOT)
3235#define COPYMAP(SLOT) COPYSLOT(tp_as_mapping->SLOT)
Tim Petersfc57ccb2001-10-12 02:38:24 +00003236#define COPYBUF(SLOT) COPYSLOT(tp_as_buffer->SLOT)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003237
Guido van Rossum13d52f02001-08-10 21:24:08 +00003238 /* This won't inherit indirect slots (from tp_as_number etc.)
3239 if type doesn't provide the space. */
3240
3241 if (type->tp_as_number != NULL && base->tp_as_number != NULL) {
3242 basebase = base->tp_base;
3243 if (basebase->tp_as_number == NULL)
3244 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003245 COPYNUM(nb_add);
3246 COPYNUM(nb_subtract);
3247 COPYNUM(nb_multiply);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003248 COPYNUM(nb_remainder);
3249 COPYNUM(nb_divmod);
3250 COPYNUM(nb_power);
3251 COPYNUM(nb_negative);
3252 COPYNUM(nb_positive);
3253 COPYNUM(nb_absolute);
Jack Diederich4dafcc42006-11-28 19:15:13 +00003254 COPYNUM(nb_bool);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003255 COPYNUM(nb_invert);
3256 COPYNUM(nb_lshift);
3257 COPYNUM(nb_rshift);
3258 COPYNUM(nb_and);
3259 COPYNUM(nb_xor);
3260 COPYNUM(nb_or);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003261 COPYNUM(nb_int);
3262 COPYNUM(nb_long);
3263 COPYNUM(nb_float);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003264 COPYNUM(nb_inplace_add);
3265 COPYNUM(nb_inplace_subtract);
3266 COPYNUM(nb_inplace_multiply);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003267 COPYNUM(nb_inplace_remainder);
3268 COPYNUM(nb_inplace_power);
3269 COPYNUM(nb_inplace_lshift);
3270 COPYNUM(nb_inplace_rshift);
3271 COPYNUM(nb_inplace_and);
3272 COPYNUM(nb_inplace_xor);
3273 COPYNUM(nb_inplace_or);
Neal Norwitzbcc0db82006-03-24 08:14:36 +00003274 COPYNUM(nb_true_divide);
3275 COPYNUM(nb_floor_divide);
3276 COPYNUM(nb_inplace_true_divide);
3277 COPYNUM(nb_inplace_floor_divide);
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00003278 COPYNUM(nb_index);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003279 }
3280
Guido van Rossum13d52f02001-08-10 21:24:08 +00003281 if (type->tp_as_sequence != NULL && base->tp_as_sequence != NULL) {
3282 basebase = base->tp_base;
3283 if (basebase->tp_as_sequence == NULL)
3284 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003285 COPYSEQ(sq_length);
3286 COPYSEQ(sq_concat);
3287 COPYSEQ(sq_repeat);
3288 COPYSEQ(sq_item);
3289 COPYSEQ(sq_slice);
3290 COPYSEQ(sq_ass_item);
3291 COPYSEQ(sq_ass_slice);
3292 COPYSEQ(sq_contains);
3293 COPYSEQ(sq_inplace_concat);
3294 COPYSEQ(sq_inplace_repeat);
3295 }
3296
Guido van Rossum13d52f02001-08-10 21:24:08 +00003297 if (type->tp_as_mapping != NULL && base->tp_as_mapping != NULL) {
3298 basebase = base->tp_base;
3299 if (basebase->tp_as_mapping == NULL)
3300 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003301 COPYMAP(mp_length);
3302 COPYMAP(mp_subscript);
3303 COPYMAP(mp_ass_subscript);
3304 }
3305
Tim Petersfc57ccb2001-10-12 02:38:24 +00003306 if (type->tp_as_buffer != NULL && base->tp_as_buffer != NULL) {
3307 basebase = base->tp_base;
3308 if (basebase->tp_as_buffer == NULL)
3309 basebase = NULL;
Travis E. Oliphantb99f7622007-08-18 11:21:56 +00003310 COPYBUF(bf_getbuffer);
3311 COPYBUF(bf_releasebuffer);
Tim Petersfc57ccb2001-10-12 02:38:24 +00003312 }
3313
Guido van Rossum13d52f02001-08-10 21:24:08 +00003314 basebase = base->tp_base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003315
Tim Peters6d6c1a32001-08-02 04:15:00 +00003316 COPYSLOT(tp_dealloc);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003317 if (type->tp_getattr == NULL && type->tp_getattro == NULL) {
3318 type->tp_getattr = base->tp_getattr;
3319 type->tp_getattro = base->tp_getattro;
3320 }
3321 if (type->tp_setattr == NULL && type->tp_setattro == NULL) {
3322 type->tp_setattr = base->tp_setattr;
3323 type->tp_setattro = base->tp_setattro;
3324 }
3325 /* tp_compare see tp_richcompare */
3326 COPYSLOT(tp_repr);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003327 /* tp_hash see tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003328 COPYSLOT(tp_call);
3329 COPYSLOT(tp_str);
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00003330 {
Guido van Rossum38938152006-08-21 23:36:26 +00003331 /* Copy comparison-related slots only when
3332 not overriding them anywhere */
Guido van Rossumb8f63662001-08-15 23:57:02 +00003333 if (type->tp_compare == NULL &&
3334 type->tp_richcompare == NULL &&
Guido van Rossum38938152006-08-21 23:36:26 +00003335 type->tp_hash == NULL &&
3336 !overrides_cmp_or_hash(type))
Guido van Rossumb8f63662001-08-15 23:57:02 +00003337 {
Tim Peters6d6c1a32001-08-02 04:15:00 +00003338 type->tp_compare = base->tp_compare;
3339 type->tp_richcompare = base->tp_richcompare;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003340 type->tp_hash = base->tp_hash;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003341 }
3342 }
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00003343 {
Tim Peters6d6c1a32001-08-02 04:15:00 +00003344 COPYSLOT(tp_iter);
3345 COPYSLOT(tp_iternext);
3346 }
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00003347 {
Tim Peters6d6c1a32001-08-02 04:15:00 +00003348 COPYSLOT(tp_descr_get);
3349 COPYSLOT(tp_descr_set);
3350 COPYSLOT(tp_dictoffset);
3351 COPYSLOT(tp_init);
3352 COPYSLOT(tp_alloc);
Guido van Rossumcc8fe042002-04-05 17:10:16 +00003353 COPYSLOT(tp_is_gc);
Tim Peters3cfe7542003-05-21 21:29:48 +00003354 if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) ==
3355 (base->tp_flags & Py_TPFLAGS_HAVE_GC)) {
3356 /* They agree about gc. */
3357 COPYSLOT(tp_free);
3358 }
3359 else if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
3360 type->tp_free == NULL &&
Neal Norwitz30d1c512007-08-19 22:48:23 +00003361 base->tp_free == PyObject_Free) {
Tim Peters3cfe7542003-05-21 21:29:48 +00003362 /* A bit of magic to plug in the correct default
3363 * tp_free function when a derived class adds gc,
3364 * didn't define tp_free, and the base uses the
3365 * default non-gc tp_free.
3366 */
3367 type->tp_free = PyObject_GC_Del;
3368 }
3369 /* else they didn't agree about gc, and there isn't something
3370 * obvious to be done -- the type is on its own.
3371 */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003372 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003373}
3374
Jeremy Hylton938ace62002-07-17 16:30:39 +00003375static int add_operators(PyTypeObject *);
Guido van Rossum13d52f02001-08-10 21:24:08 +00003376
Tim Peters6d6c1a32001-08-02 04:15:00 +00003377int
Guido van Rossum528b7eb2001-08-07 17:24:28 +00003378PyType_Ready(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003379{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00003380 PyObject *dict, *bases;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003381 PyTypeObject *base;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003382 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003383
Guido van Rossumcab05802002-06-10 15:29:03 +00003384 if (type->tp_flags & Py_TPFLAGS_READY) {
3385 assert(type->tp_dict != NULL);
Guido van Rossumd614f972001-08-10 17:39:49 +00003386 return 0;
Guido van Rossumcab05802002-06-10 15:29:03 +00003387 }
Guido van Rossumd614f972001-08-10 17:39:49 +00003388 assert((type->tp_flags & Py_TPFLAGS_READYING) == 0);
Guido van Rossumd614f972001-08-10 17:39:49 +00003389
3390 type->tp_flags |= Py_TPFLAGS_READYING;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003391
Tim Peters36eb4df2003-03-23 03:33:13 +00003392#ifdef Py_TRACE_REFS
3393 /* PyType_Ready is the closest thing we have to a choke point
3394 * for type objects, so is the best place I can think of to try
3395 * to get type objects into the doubly-linked list of all objects.
3396 * Still, not all type objects go thru PyType_Ready.
3397 */
Tim Peters7571a0f2003-03-23 17:52:28 +00003398 _Py_AddToAllObjects((PyObject *)type, 0);
Tim Peters36eb4df2003-03-23 03:33:13 +00003399#endif
3400
Tim Peters6d6c1a32001-08-02 04:15:00 +00003401 /* Initialize tp_base (defaults to BaseObject unless that's us) */
3402 base = type->tp_base;
Martin v. Löwisbf608752004-08-18 13:16:54 +00003403 if (base == NULL && type != &PyBaseObject_Type) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00003404 base = type->tp_base = &PyBaseObject_Type;
Martin v. Löwisbf608752004-08-18 13:16:54 +00003405 Py_INCREF(base);
3406 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003407
Guido van Rossumd8faa362007-04-27 19:54:29 +00003408 /* Now the only way base can still be NULL is if type is
3409 * &PyBaseObject_Type.
3410 */
Guido van Rossum692cdbc2006-03-10 02:04:28 +00003411
Guido van Rossum323a9cf2002-08-14 17:26:30 +00003412 /* Initialize the base class */
Guido van Rossum50e9fb92006-08-17 05:42:55 +00003413 if (base != NULL && base->tp_dict == NULL) {
Guido van Rossum323a9cf2002-08-14 17:26:30 +00003414 if (PyType_Ready(base) < 0)
3415 goto error;
3416 }
3417
Guido van Rossumd8faa362007-04-27 19:54:29 +00003418 /* Initialize ob_type if NULL. This means extensions that want to be
Guido van Rossum0986d822002-04-08 01:38:42 +00003419 compilable separately on Windows can call PyType_Ready() instead of
3420 initializing the ob_type field of their type objects. */
Guido van Rossumd8faa362007-04-27 19:54:29 +00003421 /* The test for base != NULL is really unnecessary, since base is only
3422 NULL when type is &PyBaseObject_Type, and we know its ob_type is
3423 not NULL (it's initialized to &PyType_Type). But coverity doesn't
3424 know that. */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003425 if (Py_Type(type) == NULL && base != NULL)
3426 Py_Type(type) = Py_Type(base);
Guido van Rossum0986d822002-04-08 01:38:42 +00003427
Tim Peters6d6c1a32001-08-02 04:15:00 +00003428 /* Initialize tp_bases */
3429 bases = type->tp_bases;
3430 if (bases == NULL) {
3431 if (base == NULL)
3432 bases = PyTuple_New(0);
3433 else
Raymond Hettinger8ae46892003-10-12 19:09:37 +00003434 bases = PyTuple_Pack(1, base);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003435 if (bases == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00003436 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003437 type->tp_bases = bases;
3438 }
3439
Guido van Rossum687ae002001-10-15 22:03:32 +00003440 /* Initialize tp_dict */
3441 dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003442 if (dict == NULL) {
3443 dict = PyDict_New();
3444 if (dict == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00003445 goto error;
Guido van Rossum687ae002001-10-15 22:03:32 +00003446 type->tp_dict = dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003447 }
3448
Guido van Rossum687ae002001-10-15 22:03:32 +00003449 /* Add type-specific descriptors to tp_dict */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003450 if (add_operators(type) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003451 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003452 if (type->tp_methods != NULL) {
3453 if (add_methods(type, type->tp_methods) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003454 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003455 }
3456 if (type->tp_members != NULL) {
3457 if (add_members(type, type->tp_members) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003458 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003459 }
3460 if (type->tp_getset != NULL) {
3461 if (add_getset(type, type->tp_getset) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003462 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003463 }
3464
Tim Peters6d6c1a32001-08-02 04:15:00 +00003465 /* Calculate method resolution order */
3466 if (mro_internal(type) < 0) {
Guido van Rossumd614f972001-08-10 17:39:49 +00003467 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003468 }
3469
Guido van Rossum13d52f02001-08-10 21:24:08 +00003470 /* Inherit special flags from dominant base */
3471 if (type->tp_base != NULL)
3472 inherit_special(type, type->tp_base);
3473
Tim Peters6d6c1a32001-08-02 04:15:00 +00003474 /* Initialize tp_dict properly */
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00003475 bases = type->tp_mro;
3476 assert(bases != NULL);
3477 assert(PyTuple_Check(bases));
3478 n = PyTuple_GET_SIZE(bases);
3479 for (i = 1; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00003480 PyObject *b = PyTuple_GET_ITEM(bases, i);
3481 if (PyType_Check(b))
3482 inherit_slots(type, (PyTypeObject *)b);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003483 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003484
Tim Peters3cfe7542003-05-21 21:29:48 +00003485 /* Sanity check for tp_free. */
3486 if (PyType_IS_GC(type) && (type->tp_flags & Py_TPFLAGS_BASETYPE) &&
3487 (type->tp_free == NULL || type->tp_free == PyObject_Del)) {
Guido van Rossumd8faa362007-04-27 19:54:29 +00003488 /* This base class needs to call tp_free, but doesn't have
3489 * one, or its tp_free is for non-gc'ed objects.
3490 */
Tim Peters3cfe7542003-05-21 21:29:48 +00003491 PyErr_Format(PyExc_TypeError, "type '%.100s' participates in "
3492 "gc and is a base type but has inappropriate "
3493 "tp_free slot",
3494 type->tp_name);
3495 goto error;
3496 }
3497
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00003498 /* if the type dictionary doesn't contain a __doc__, set it from
3499 the tp_doc slot.
3500 */
3501 if (PyDict_GetItemString(type->tp_dict, "__doc__") == NULL) {
3502 if (type->tp_doc != NULL) {
Neal Norwitza369c5a2007-08-25 07:41:59 +00003503 PyObject *doc = PyUnicode_FromString(type->tp_doc);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003504 if (doc == NULL)
3505 goto error;
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00003506 PyDict_SetItemString(type->tp_dict, "__doc__", doc);
3507 Py_DECREF(doc);
3508 } else {
Guido van Rossumd4641072002-04-03 02:13:37 +00003509 PyDict_SetItemString(type->tp_dict,
3510 "__doc__", Py_None);
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00003511 }
3512 }
3513
Guido van Rossum38938152006-08-21 23:36:26 +00003514 /* Hack for tp_hash and __hash__.
3515 If after all that, tp_hash is still NULL, and __hash__ is not in
3516 tp_dict, set tp_dict['__hash__'] equal to None.
3517 This signals that __hash__ is not inherited.
3518 */
3519 if (type->tp_hash == NULL) {
3520 if (PyDict_GetItemString(type->tp_dict, "__hash__") == NULL) {
3521 if (PyDict_SetItemString(type->tp_dict, "__hash__", Py_None) < 0)
3522 goto error;
3523 }
3524 }
3525
Guido van Rossum13d52f02001-08-10 21:24:08 +00003526 /* Some more special stuff */
3527 base = type->tp_base;
3528 if (base != NULL) {
3529 if (type->tp_as_number == NULL)
3530 type->tp_as_number = base->tp_as_number;
3531 if (type->tp_as_sequence == NULL)
3532 type->tp_as_sequence = base->tp_as_sequence;
3533 if (type->tp_as_mapping == NULL)
3534 type->tp_as_mapping = base->tp_as_mapping;
Guido van Rossumeea47182003-02-11 20:39:59 +00003535 if (type->tp_as_buffer == NULL)
3536 type->tp_as_buffer = base->tp_as_buffer;
Guido van Rossum13d52f02001-08-10 21:24:08 +00003537 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003538
Guido van Rossum1c450732001-10-08 15:18:27 +00003539 /* Link into each base class's list of subclasses */
3540 bases = type->tp_bases;
3541 n = PyTuple_GET_SIZE(bases);
3542 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00003543 PyObject *b = PyTuple_GET_ITEM(bases, i);
3544 if (PyType_Check(b) &&
3545 add_subclass((PyTypeObject *)b, type) < 0)
Guido van Rossum1c450732001-10-08 15:18:27 +00003546 goto error;
3547 }
3548
Guido van Rossum13d52f02001-08-10 21:24:08 +00003549 /* All done -- set the ready flag */
Guido van Rossumd614f972001-08-10 17:39:49 +00003550 assert(type->tp_dict != NULL);
3551 type->tp_flags =
3552 (type->tp_flags & ~Py_TPFLAGS_READYING) | Py_TPFLAGS_READY;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003553 return 0;
Guido van Rossumd614f972001-08-10 17:39:49 +00003554
3555 error:
3556 type->tp_flags &= ~Py_TPFLAGS_READYING;
3557 return -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003558}
3559
Guido van Rossum1c450732001-10-08 15:18:27 +00003560static int
3561add_subclass(PyTypeObject *base, PyTypeObject *type)
3562{
Martin v. Löwiseb079f12006-02-16 14:32:27 +00003563 Py_ssize_t i;
3564 int result;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003565 PyObject *list, *ref, *newobj;
Guido van Rossum1c450732001-10-08 15:18:27 +00003566
3567 list = base->tp_subclasses;
3568 if (list == NULL) {
3569 base->tp_subclasses = list = PyList_New(0);
3570 if (list == NULL)
3571 return -1;
3572 }
3573 assert(PyList_Check(list));
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003574 newobj = PyWeakref_NewRef((PyObject *)type, NULL);
Guido van Rossum1c450732001-10-08 15:18:27 +00003575 i = PyList_GET_SIZE(list);
3576 while (--i >= 0) {
3577 ref = PyList_GET_ITEM(list, i);
3578 assert(PyWeakref_CheckRef(ref));
Guido van Rossum3930bc32002-10-18 13:51:49 +00003579 if (PyWeakref_GET_OBJECT(ref) == Py_None)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003580 return PyList_SetItem(list, i, newobj);
Guido van Rossum1c450732001-10-08 15:18:27 +00003581 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003582 result = PyList_Append(list, newobj);
3583 Py_DECREF(newobj);
Martin v. Löwiseb079f12006-02-16 14:32:27 +00003584 return result;
Guido van Rossum1c450732001-10-08 15:18:27 +00003585}
3586
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003587static void
3588remove_subclass(PyTypeObject *base, PyTypeObject *type)
3589{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003590 Py_ssize_t i;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003591 PyObject *list, *ref;
3592
3593 list = base->tp_subclasses;
3594 if (list == NULL) {
3595 return;
3596 }
3597 assert(PyList_Check(list));
3598 i = PyList_GET_SIZE(list);
3599 while (--i >= 0) {
3600 ref = PyList_GET_ITEM(list, i);
3601 assert(PyWeakref_CheckRef(ref));
3602 if (PyWeakref_GET_OBJECT(ref) == (PyObject*)type) {
3603 /* this can't fail, right? */
3604 PySequence_DelItem(list, i);
3605 return;
3606 }
3607 }
3608}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003609
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003610static int
3611check_num_args(PyObject *ob, int n)
3612{
3613 if (!PyTuple_CheckExact(ob)) {
3614 PyErr_SetString(PyExc_SystemError,
3615 "PyArg_UnpackTuple() argument list is not a tuple");
3616 return 0;
3617 }
3618 if (n == PyTuple_GET_SIZE(ob))
3619 return 1;
3620 PyErr_Format(
3621 PyExc_TypeError,
Martin v. Löwis2c95cc62006-02-16 06:54:25 +00003622 "expected %d arguments, got %zd", n, PyTuple_GET_SIZE(ob));
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003623 return 0;
3624}
3625
Tim Peters6d6c1a32001-08-02 04:15:00 +00003626/* Generic wrappers for overloadable 'operators' such as __getitem__ */
3627
3628/* There's a wrapper *function* for each distinct function typedef used
Guido van Rossumd8faa362007-04-27 19:54:29 +00003629 for type object slots (e.g. binaryfunc, ternaryfunc, etc.). There's a
Tim Peters6d6c1a32001-08-02 04:15:00 +00003630 wrapper *table* for each distinct operation (e.g. __len__, __add__).
3631 Most tables have only one entry; the tables for binary operators have two
3632 entries, one regular and one with reversed arguments. */
3633
3634static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00003635wrap_lenfunc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003636{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003637 lenfunc func = (lenfunc)wrapped;
3638 Py_ssize_t res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003639
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003640 if (!check_num_args(args, 0))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003641 return NULL;
3642 res = (*func)(self);
3643 if (res == -1 && PyErr_Occurred())
3644 return NULL;
3645 return PyInt_FromLong((long)res);
3646}
3647
Tim Peters6d6c1a32001-08-02 04:15:00 +00003648static PyObject *
Raymond Hettingerf34f2642003-10-11 17:29:04 +00003649wrap_inquirypred(PyObject *self, PyObject *args, void *wrapped)
3650{
3651 inquiry func = (inquiry)wrapped;
3652 int res;
3653
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003654 if (!check_num_args(args, 0))
Raymond Hettingerf34f2642003-10-11 17:29:04 +00003655 return NULL;
3656 res = (*func)(self);
3657 if (res == -1 && PyErr_Occurred())
3658 return NULL;
3659 return PyBool_FromLong((long)res);
3660}
3661
3662static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00003663wrap_binaryfunc(PyObject *self, PyObject *args, void *wrapped)
3664{
3665 binaryfunc func = (binaryfunc)wrapped;
3666 PyObject *other;
3667
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003668 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003669 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003670 other = PyTuple_GET_ITEM(args, 0);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003671 return (*func)(self, other);
3672}
3673
3674static PyObject *
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003675wrap_binaryfunc_l(PyObject *self, PyObject *args, void *wrapped)
3676{
3677 binaryfunc func = (binaryfunc)wrapped;
3678 PyObject *other;
3679
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003680 if (!check_num_args(args, 1))
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003681 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003682 other = PyTuple_GET_ITEM(args, 0);
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003683 return (*func)(self, other);
3684}
3685
3686static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00003687wrap_binaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
3688{
3689 binaryfunc func = (binaryfunc)wrapped;
3690 PyObject *other;
3691
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003692 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003693 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003694 other = PyTuple_GET_ITEM(args, 0);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003695 if (!PyType_IsSubtype(Py_Type(other), Py_Type(self))) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003696 Py_INCREF(Py_NotImplemented);
3697 return Py_NotImplemented;
3698 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003699 return (*func)(other, self);
3700}
3701
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003702static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00003703wrap_ternaryfunc(PyObject *self, PyObject *args, void *wrapped)
3704{
3705 ternaryfunc func = (ternaryfunc)wrapped;
3706 PyObject *other;
3707 PyObject *third = Py_None;
3708
3709 /* Note: This wrapper only works for __pow__() */
3710
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00003711 if (!PyArg_UnpackTuple(args, "", 1, 2, &other, &third))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003712 return NULL;
3713 return (*func)(self, other, third);
3714}
3715
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00003716static PyObject *
3717wrap_ternaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
3718{
3719 ternaryfunc func = (ternaryfunc)wrapped;
3720 PyObject *other;
3721 PyObject *third = Py_None;
3722
3723 /* Note: This wrapper only works for __pow__() */
3724
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00003725 if (!PyArg_UnpackTuple(args, "", 1, 2, &other, &third))
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00003726 return NULL;
3727 return (*func)(other, self, third);
3728}
3729
Tim Peters6d6c1a32001-08-02 04:15:00 +00003730static PyObject *
3731wrap_unaryfunc(PyObject *self, PyObject *args, void *wrapped)
3732{
3733 unaryfunc func = (unaryfunc)wrapped;
3734
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003735 if (!check_num_args(args, 0))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003736 return NULL;
3737 return (*func)(self);
3738}
3739
Tim Peters6d6c1a32001-08-02 04:15:00 +00003740static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003741wrap_indexargfunc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003742{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003743 ssizeargfunc func = (ssizeargfunc)wrapped;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003744 PyObject* o;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003745 Py_ssize_t i;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003746
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003747 if (!PyArg_UnpackTuple(args, "", 1, 1, &o))
3748 return NULL;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00003749 i = PyNumber_AsSsize_t(o, PyExc_OverflowError);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003750 if (i == -1 && PyErr_Occurred())
Tim Peters6d6c1a32001-08-02 04:15:00 +00003751 return NULL;
3752 return (*func)(self, i);
3753}
3754
Martin v. Löwis18e16552006-02-15 17:27:45 +00003755static Py_ssize_t
Guido van Rossum5d815f32001-08-17 21:57:47 +00003756getindex(PyObject *self, PyObject *arg)
3757{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003758 Py_ssize_t i;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003759
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00003760 i = PyNumber_AsSsize_t(arg, PyExc_OverflowError);
Guido van Rossum5d815f32001-08-17 21:57:47 +00003761 if (i == -1 && PyErr_Occurred())
3762 return -1;
3763 if (i < 0) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003764 PySequenceMethods *sq = Py_Type(self)->tp_as_sequence;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003765 if (sq && sq->sq_length) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00003766 Py_ssize_t n = (*sq->sq_length)(self);
Guido van Rossum5d815f32001-08-17 21:57:47 +00003767 if (n < 0)
3768 return -1;
3769 i += n;
3770 }
3771 }
3772 return i;
3773}
3774
3775static PyObject *
3776wrap_sq_item(PyObject *self, PyObject *args, void *wrapped)
3777{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003778 ssizeargfunc func = (ssizeargfunc)wrapped;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003779 PyObject *arg;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003780 Py_ssize_t i;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003781
Guido van Rossumf4593e02001-10-03 12:09:30 +00003782 if (PyTuple_GET_SIZE(args) == 1) {
3783 arg = PyTuple_GET_ITEM(args, 0);
3784 i = getindex(self, arg);
3785 if (i == -1 && PyErr_Occurred())
3786 return NULL;
3787 return (*func)(self, i);
3788 }
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003789 check_num_args(args, 1);
Guido van Rossumf4593e02001-10-03 12:09:30 +00003790 assert(PyErr_Occurred());
3791 return NULL;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003792}
3793
Tim Peters6d6c1a32001-08-02 04:15:00 +00003794static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00003795wrap_ssizessizeargfunc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003796{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003797 ssizessizeargfunc func = (ssizessizeargfunc)wrapped;
3798 Py_ssize_t i, j;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003799
Martin v. Löwis18e16552006-02-15 17:27:45 +00003800 if (!PyArg_ParseTuple(args, "nn", &i, &j))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003801 return NULL;
3802 return (*func)(self, i, j);
3803}
3804
Tim Peters6d6c1a32001-08-02 04:15:00 +00003805static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00003806wrap_sq_setitem(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003807{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003808 ssizeobjargproc func = (ssizeobjargproc)wrapped;
3809 Py_ssize_t i;
3810 int res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003811 PyObject *arg, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003812
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00003813 if (!PyArg_UnpackTuple(args, "", 2, 2, &arg, &value))
Guido van Rossum5d815f32001-08-17 21:57:47 +00003814 return NULL;
3815 i = getindex(self, arg);
3816 if (i == -1 && PyErr_Occurred())
Tim Peters6d6c1a32001-08-02 04:15:00 +00003817 return NULL;
3818 res = (*func)(self, i, value);
3819 if (res == -1 && PyErr_Occurred())
3820 return NULL;
3821 Py_INCREF(Py_None);
3822 return Py_None;
3823}
3824
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003825static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00003826wrap_sq_delitem(PyObject *self, PyObject *args, void *wrapped)
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003827{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003828 ssizeobjargproc func = (ssizeobjargproc)wrapped;
3829 Py_ssize_t i;
3830 int res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003831 PyObject *arg;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003832
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003833 if (!check_num_args(args, 1))
Guido van Rossum5d815f32001-08-17 21:57:47 +00003834 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003835 arg = PyTuple_GET_ITEM(args, 0);
Guido van Rossum5d815f32001-08-17 21:57:47 +00003836 i = getindex(self, arg);
3837 if (i == -1 && PyErr_Occurred())
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003838 return NULL;
3839 res = (*func)(self, i, NULL);
3840 if (res == -1 && PyErr_Occurred())
3841 return NULL;
3842 Py_INCREF(Py_None);
3843 return Py_None;
3844}
3845
Tim Peters6d6c1a32001-08-02 04:15:00 +00003846static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00003847wrap_ssizessizeobjargproc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003848{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003849 ssizessizeobjargproc func = (ssizessizeobjargproc)wrapped;
3850 Py_ssize_t i, j;
3851 int res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003852 PyObject *value;
3853
Martin v. Löwis18e16552006-02-15 17:27:45 +00003854 if (!PyArg_ParseTuple(args, "nnO", &i, &j, &value))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003855 return NULL;
3856 res = (*func)(self, i, j, value);
3857 if (res == -1 && PyErr_Occurred())
3858 return NULL;
3859 Py_INCREF(Py_None);
3860 return Py_None;
3861}
3862
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003863static PyObject *
3864wrap_delslice(PyObject *self, PyObject *args, void *wrapped)
3865{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003866 ssizessizeobjargproc func = (ssizessizeobjargproc)wrapped;
3867 Py_ssize_t i, j;
3868 int res;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003869
Martin v. Löwis18e16552006-02-15 17:27:45 +00003870 if (!PyArg_ParseTuple(args, "nn", &i, &j))
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003871 return NULL;
3872 res = (*func)(self, i, j, NULL);
3873 if (res == -1 && PyErr_Occurred())
3874 return NULL;
3875 Py_INCREF(Py_None);
3876 return Py_None;
3877}
3878
Tim Peters6d6c1a32001-08-02 04:15:00 +00003879/* XXX objobjproc is a misnomer; should be objargpred */
3880static PyObject *
3881wrap_objobjproc(PyObject *self, PyObject *args, void *wrapped)
3882{
3883 objobjproc func = (objobjproc)wrapped;
3884 int res;
Guido van Rossum22c3dda2003-10-09 03:46:35 +00003885 PyObject *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003886
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003887 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003888 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003889 value = PyTuple_GET_ITEM(args, 0);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003890 res = (*func)(self, value);
3891 if (res == -1 && PyErr_Occurred())
3892 return NULL;
Guido van Rossum22c3dda2003-10-09 03:46:35 +00003893 else
3894 return PyBool_FromLong(res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003895}
3896
Tim Peters6d6c1a32001-08-02 04:15:00 +00003897static PyObject *
3898wrap_objobjargproc(PyObject *self, PyObject *args, void *wrapped)
3899{
3900 objobjargproc func = (objobjargproc)wrapped;
3901 int res;
3902 PyObject *key, *value;
3903
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00003904 if (!PyArg_UnpackTuple(args, "", 2, 2, &key, &value))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003905 return NULL;
3906 res = (*func)(self, key, value);
3907 if (res == -1 && PyErr_Occurred())
3908 return NULL;
3909 Py_INCREF(Py_None);
3910 return Py_None;
3911}
3912
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003913static PyObject *
3914wrap_delitem(PyObject *self, PyObject *args, void *wrapped)
3915{
3916 objobjargproc func = (objobjargproc)wrapped;
3917 int res;
3918 PyObject *key;
3919
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003920 if (!check_num_args(args, 1))
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003921 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003922 key = PyTuple_GET_ITEM(args, 0);
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003923 res = (*func)(self, key, NULL);
3924 if (res == -1 && PyErr_Occurred())
3925 return NULL;
3926 Py_INCREF(Py_None);
3927 return Py_None;
3928}
3929
Tim Peters6d6c1a32001-08-02 04:15:00 +00003930static PyObject *
3931wrap_cmpfunc(PyObject *self, PyObject *args, void *wrapped)
3932{
3933 cmpfunc func = (cmpfunc)wrapped;
3934 int res;
3935 PyObject *other;
3936
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003937 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003938 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003939 other = PyTuple_GET_ITEM(args, 0);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003940 if (Py_Type(other)->tp_compare != func &&
3941 !PyType_IsSubtype(Py_Type(other), Py_Type(self))) {
Guido van Rossumceccae52001-09-18 20:03:57 +00003942 PyErr_Format(
3943 PyExc_TypeError,
3944 "%s.__cmp__(x,y) requires y to be a '%s', not a '%s'",
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003945 Py_Type(self)->tp_name,
3946 Py_Type(self)->tp_name,
3947 Py_Type(other)->tp_name);
Guido van Rossumceccae52001-09-18 20:03:57 +00003948 return NULL;
3949 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003950 res = (*func)(self, other);
3951 if (PyErr_Occurred())
3952 return NULL;
3953 return PyInt_FromLong((long)res);
3954}
3955
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003956/* Helper to check for object.__setattr__ or __delattr__ applied to a type.
Guido van Rossum52b27052003-04-15 20:05:10 +00003957 This is called the Carlo Verre hack after its discoverer. */
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003958static int
3959hackcheck(PyObject *self, setattrofunc func, char *what)
3960{
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003961 PyTypeObject *type = Py_Type(self);
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003962 while (type && type->tp_flags & Py_TPFLAGS_HEAPTYPE)
3963 type = type->tp_base;
Guido van Rossumd8faa362007-04-27 19:54:29 +00003964 /* If type is NULL now, this is a really weird type.
3965 In the spirit of backwards compatibility (?), just shut up. */
Guido van Rossum692cdbc2006-03-10 02:04:28 +00003966 if (type && type->tp_setattro != func) {
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003967 PyErr_Format(PyExc_TypeError,
3968 "can't apply this %s to %s object",
3969 what,
3970 type->tp_name);
3971 return 0;
3972 }
3973 return 1;
3974}
3975
Tim Peters6d6c1a32001-08-02 04:15:00 +00003976static PyObject *
3977wrap_setattr(PyObject *self, PyObject *args, void *wrapped)
3978{
3979 setattrofunc func = (setattrofunc)wrapped;
3980 int res;
3981 PyObject *name, *value;
3982
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00003983 if (!PyArg_UnpackTuple(args, "", 2, 2, &name, &value))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003984 return NULL;
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003985 if (!hackcheck(self, func, "__setattr__"))
3986 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003987 res = (*func)(self, name, value);
3988 if (res < 0)
3989 return NULL;
3990 Py_INCREF(Py_None);
3991 return Py_None;
3992}
3993
3994static PyObject *
3995wrap_delattr(PyObject *self, PyObject *args, void *wrapped)
3996{
3997 setattrofunc func = (setattrofunc)wrapped;
3998 int res;
3999 PyObject *name;
4000
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004001 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004002 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004003 name = PyTuple_GET_ITEM(args, 0);
Guido van Rossum4dcdb782003-04-14 21:46:03 +00004004 if (!hackcheck(self, func, "__delattr__"))
4005 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004006 res = (*func)(self, name, NULL);
4007 if (res < 0)
4008 return NULL;
4009 Py_INCREF(Py_None);
4010 return Py_None;
4011}
4012
Tim Peters6d6c1a32001-08-02 04:15:00 +00004013static PyObject *
4014wrap_hashfunc(PyObject *self, PyObject *args, void *wrapped)
4015{
4016 hashfunc func = (hashfunc)wrapped;
4017 long res;
4018
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004019 if (!check_num_args(args, 0))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004020 return NULL;
4021 res = (*func)(self);
4022 if (res == -1 && PyErr_Occurred())
4023 return NULL;
4024 return PyInt_FromLong(res);
4025}
4026
Tim Peters6d6c1a32001-08-02 04:15:00 +00004027static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00004028wrap_call(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004029{
4030 ternaryfunc func = (ternaryfunc)wrapped;
4031
Guido van Rossumc8e56452001-10-22 00:43:43 +00004032 return (*func)(self, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004033}
4034
Tim Peters6d6c1a32001-08-02 04:15:00 +00004035static PyObject *
4036wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op)
4037{
4038 richcmpfunc func = (richcmpfunc)wrapped;
4039 PyObject *other;
4040
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004041 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004042 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004043 other = PyTuple_GET_ITEM(args, 0);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004044 return (*func)(self, other, op);
4045}
4046
4047#undef RICHCMP_WRAPPER
4048#define RICHCMP_WRAPPER(NAME, OP) \
4049static PyObject * \
4050richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \
4051{ \
4052 return wrap_richcmpfunc(self, args, wrapped, OP); \
4053}
4054
Jack Jansen8e938b42001-08-08 15:29:49 +00004055RICHCMP_WRAPPER(lt, Py_LT)
4056RICHCMP_WRAPPER(le, Py_LE)
4057RICHCMP_WRAPPER(eq, Py_EQ)
4058RICHCMP_WRAPPER(ne, Py_NE)
4059RICHCMP_WRAPPER(gt, Py_GT)
4060RICHCMP_WRAPPER(ge, Py_GE)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004061
Tim Peters6d6c1a32001-08-02 04:15:00 +00004062static PyObject *
4063wrap_next(PyObject *self, PyObject *args, void *wrapped)
4064{
4065 unaryfunc func = (unaryfunc)wrapped;
4066 PyObject *res;
4067
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004068 if (!check_num_args(args, 0))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004069 return NULL;
4070 res = (*func)(self);
4071 if (res == NULL && !PyErr_Occurred())
4072 PyErr_SetNone(PyExc_StopIteration);
4073 return res;
4074}
4075
Tim Peters6d6c1a32001-08-02 04:15:00 +00004076static PyObject *
4077wrap_descr_get(PyObject *self, PyObject *args, void *wrapped)
4078{
4079 descrgetfunc func = (descrgetfunc)wrapped;
4080 PyObject *obj;
4081 PyObject *type = NULL;
4082
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00004083 if (!PyArg_UnpackTuple(args, "", 1, 2, &obj, &type))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004084 return NULL;
Guido van Rossum82ed25c2003-02-11 16:25:43 +00004085 if (obj == Py_None)
4086 obj = NULL;
4087 if (type == Py_None)
4088 type = NULL;
4089 if (type == NULL &&obj == NULL) {
4090 PyErr_SetString(PyExc_TypeError,
4091 "__get__(None, None) is invalid");
4092 return NULL;
4093 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004094 return (*func)(self, obj, type);
4095}
4096
Tim Peters6d6c1a32001-08-02 04:15:00 +00004097static PyObject *
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004098wrap_descr_set(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004099{
4100 descrsetfunc func = (descrsetfunc)wrapped;
4101 PyObject *obj, *value;
4102 int ret;
4103
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00004104 if (!PyArg_UnpackTuple(args, "", 2, 2, &obj, &value))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004105 return NULL;
4106 ret = (*func)(self, obj, value);
4107 if (ret < 0)
4108 return NULL;
4109 Py_INCREF(Py_None);
4110 return Py_None;
4111}
Guido van Rossum22b13872002-08-06 21:41:44 +00004112
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00004113static PyObject *
4114wrap_descr_delete(PyObject *self, PyObject *args, void *wrapped)
4115{
4116 descrsetfunc func = (descrsetfunc)wrapped;
4117 PyObject *obj;
4118 int ret;
4119
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004120 if (!check_num_args(args, 1))
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00004121 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004122 obj = PyTuple_GET_ITEM(args, 0);
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00004123 ret = (*func)(self, obj, NULL);
4124 if (ret < 0)
4125 return NULL;
4126 Py_INCREF(Py_None);
4127 return Py_None;
4128}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004129
Tim Peters6d6c1a32001-08-02 04:15:00 +00004130static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00004131wrap_init(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004132{
4133 initproc func = (initproc)wrapped;
4134
Guido van Rossumc8e56452001-10-22 00:43:43 +00004135 if (func(self, args, kwds) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004136 return NULL;
4137 Py_INCREF(Py_None);
4138 return Py_None;
4139}
4140
Tim Peters6d6c1a32001-08-02 04:15:00 +00004141static PyObject *
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004142tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004143{
Barry Warsaw60f01882001-08-22 19:24:42 +00004144 PyTypeObject *type, *subtype, *staticbase;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004145 PyObject *arg0, *res;
4146
4147 if (self == NULL || !PyType_Check(self))
4148 Py_FatalError("__new__() called with non-type 'self'");
4149 type = (PyTypeObject *)self;
4150 if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) {
Barry Warsaw60f01882001-08-22 19:24:42 +00004151 PyErr_Format(PyExc_TypeError,
4152 "%s.__new__(): not enough arguments",
4153 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004154 return NULL;
4155 }
4156 arg0 = PyTuple_GET_ITEM(args, 0);
4157 if (!PyType_Check(arg0)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00004158 PyErr_Format(PyExc_TypeError,
4159 "%s.__new__(X): X is not a type object (%s)",
4160 type->tp_name,
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00004161 Py_Type(arg0)->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004162 return NULL;
4163 }
4164 subtype = (PyTypeObject *)arg0;
4165 if (!PyType_IsSubtype(subtype, type)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00004166 PyErr_Format(PyExc_TypeError,
4167 "%s.__new__(%s): %s is not a subtype of %s",
4168 type->tp_name,
4169 subtype->tp_name,
4170 subtype->tp_name,
4171 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004172 return NULL;
4173 }
Barry Warsaw60f01882001-08-22 19:24:42 +00004174
4175 /* Check that the use doesn't do something silly and unsafe like
Tim Petersa427a2b2001-10-29 22:25:45 +00004176 object.__new__(dict). To do this, we check that the
Barry Warsaw60f01882001-08-22 19:24:42 +00004177 most derived base that's not a heap type is this type. */
4178 staticbase = subtype;
4179 while (staticbase && (staticbase->tp_flags & Py_TPFLAGS_HEAPTYPE))
4180 staticbase = staticbase->tp_base;
Guido van Rossumd8faa362007-04-27 19:54:29 +00004181 /* If staticbase is NULL now, it is a really weird type.
4182 In the spirit of backwards compatibility (?), just shut up. */
Guido van Rossum692cdbc2006-03-10 02:04:28 +00004183 if (staticbase && staticbase->tp_new != type->tp_new) {
Barry Warsaw60f01882001-08-22 19:24:42 +00004184 PyErr_Format(PyExc_TypeError,
4185 "%s.__new__(%s) is not safe, use %s.__new__()",
4186 type->tp_name,
4187 subtype->tp_name,
4188 staticbase == NULL ? "?" : staticbase->tp_name);
4189 return NULL;
4190 }
4191
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004192 args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
4193 if (args == NULL)
4194 return NULL;
4195 res = type->tp_new(subtype, args, kwds);
4196 Py_DECREF(args);
4197 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004198}
4199
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004200static struct PyMethodDef tp_new_methoddef[] = {
Guido van Rossumd59da4b2007-05-22 18:11:13 +00004201 {"__new__", (PyCFunction)tp_new_wrapper, METH_VARARGS|METH_KEYWORDS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00004202 PyDoc_STR("T.__new__(S, ...) -> "
Guido van Rossumd8faa362007-04-27 19:54:29 +00004203 "a new object with type S, a subtype of T")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00004204 {0}
4205};
4206
4207static int
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004208add_tp_new_wrapper(PyTypeObject *type)
4209{
Guido van Rossumf040ede2001-08-07 16:40:56 +00004210 PyObject *func;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004211
Guido van Rossum687ae002001-10-15 22:03:32 +00004212 if (PyDict_GetItemString(type->tp_dict, "__new__") != NULL)
Guido van Rossumf040ede2001-08-07 16:40:56 +00004213 return 0;
4214 func = PyCFunction_New(tp_new_methoddef, (PyObject *)type);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004215 if (func == NULL)
4216 return -1;
Raymond Hettinger8d726ee2004-06-25 22:24:35 +00004217 if (PyDict_SetItemString(type->tp_dict, "__new__", func)) {
Raymond Hettingerd56cbe52004-06-25 22:17:39 +00004218 Py_DECREF(func);
4219 return -1;
4220 }
4221 Py_DECREF(func);
4222 return 0;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004223}
4224
Guido van Rossumf040ede2001-08-07 16:40:56 +00004225/* Slot wrappers that call the corresponding __foo__ slot. See comments
4226 below at override_slots() for more explanation. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004227
Guido van Rossumdc91b992001-08-08 22:26:22 +00004228#define SLOT0(FUNCNAME, OPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004229static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004230FUNCNAME(PyObject *self) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004231{ \
Guido van Rossum5592e4d2001-08-28 18:28:21 +00004232 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00004233 return call_method(self, OPSTR, &cache_str, "()"); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004234}
4235
Guido van Rossumdc91b992001-08-08 22:26:22 +00004236#define SLOT1(FUNCNAME, OPSTR, ARG1TYPE, ARGCODES) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004237static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004238FUNCNAME(PyObject *self, ARG1TYPE arg1) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004239{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00004240 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00004241 return call_method(self, OPSTR, &cache_str, "(" ARGCODES ")", arg1); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004242}
4243
Guido van Rossumcd118802003-01-06 22:57:47 +00004244/* Boolean helper for SLOT1BINFULL().
4245 right.__class__ is a nontrivial subclass of left.__class__. */
4246static int
4247method_is_overloaded(PyObject *left, PyObject *right, char *name)
4248{
4249 PyObject *a, *b;
4250 int ok;
4251
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00004252 b = PyObject_GetAttrString((PyObject *)(Py_Type(right)), name);
Guido van Rossumcd118802003-01-06 22:57:47 +00004253 if (b == NULL) {
4254 PyErr_Clear();
4255 /* If right doesn't have it, it's not overloaded */
4256 return 0;
4257 }
4258
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00004259 a = PyObject_GetAttrString((PyObject *)(Py_Type(left)), name);
Guido van Rossumcd118802003-01-06 22:57:47 +00004260 if (a == NULL) {
4261 PyErr_Clear();
4262 Py_DECREF(b);
4263 /* If right has it but left doesn't, it's overloaded */
4264 return 1;
4265 }
4266
4267 ok = PyObject_RichCompareBool(a, b, Py_NE);
4268 Py_DECREF(a);
4269 Py_DECREF(b);
4270 if (ok < 0) {
4271 PyErr_Clear();
4272 return 0;
4273 }
4274
4275 return ok;
4276}
4277
Guido van Rossumdc91b992001-08-08 22:26:22 +00004278
4279#define SLOT1BINFULL(FUNCNAME, TESTFUNC, SLOTNAME, OPSTR, ROPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004280static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004281FUNCNAME(PyObject *self, PyObject *other) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004282{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00004283 static PyObject *cache_str, *rcache_str; \
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00004284 int do_other = Py_Type(self) != Py_Type(other) && \
4285 Py_Type(other)->tp_as_number != NULL && \
4286 Py_Type(other)->tp_as_number->SLOTNAME == TESTFUNC; \
4287 if (Py_Type(self)->tp_as_number != NULL && \
4288 Py_Type(self)->tp_as_number->SLOTNAME == TESTFUNC) { \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004289 PyObject *r; \
Guido van Rossum55f20992001-10-01 17:18:22 +00004290 if (do_other && \
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00004291 PyType_IsSubtype(Py_Type(other), Py_Type(self)) && \
Guido van Rossumcd118802003-01-06 22:57:47 +00004292 method_is_overloaded(self, other, ROPSTR)) { \
Guido van Rossum55f20992001-10-01 17:18:22 +00004293 r = call_maybe( \
4294 other, ROPSTR, &rcache_str, "(O)", self); \
4295 if (r != Py_NotImplemented) \
4296 return r; \
4297 Py_DECREF(r); \
4298 do_other = 0; \
4299 } \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00004300 r = call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00004301 self, OPSTR, &cache_str, "(O)", other); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004302 if (r != Py_NotImplemented || \
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00004303 Py_Type(other) == Py_Type(self)) \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004304 return r; \
4305 Py_DECREF(r); \
4306 } \
Guido van Rossum55f20992001-10-01 17:18:22 +00004307 if (do_other) { \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00004308 return call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00004309 other, ROPSTR, &rcache_str, "(O)", self); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004310 } \
4311 Py_INCREF(Py_NotImplemented); \
4312 return Py_NotImplemented; \
4313}
4314
4315#define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) \
4316 SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR)
4317
4318#define SLOT2(FUNCNAME, OPSTR, ARG1TYPE, ARG2TYPE, ARGCODES) \
4319static PyObject * \
4320FUNCNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \
4321{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00004322 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00004323 return call_method(self, OPSTR, &cache_str, \
4324 "(" ARGCODES ")", arg1, arg2); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004325}
4326
Martin v. Löwis18e16552006-02-15 17:27:45 +00004327static Py_ssize_t
Tim Peters6d6c1a32001-08-02 04:15:00 +00004328slot_sq_length(PyObject *self)
4329{
Guido van Rossum2730b132001-08-28 18:22:14 +00004330 static PyObject *len_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00004331 PyObject *res = call_method(self, "__len__", &len_str, "()");
Martin v. Löwis18e16552006-02-15 17:27:45 +00004332 Py_ssize_t len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004333
4334 if (res == NULL)
4335 return -1;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00004336 len = PyInt_AsSsize_t(res);
Guido van Rossum26111622001-10-01 16:42:49 +00004337 Py_DECREF(res);
Jeremy Hyltonf20fcf92002-07-25 16:06:15 +00004338 if (len < 0) {
Thomas Wouters89f507f2006-12-13 04:49:30 +00004339 if (!PyErr_Occurred())
4340 PyErr_SetString(PyExc_ValueError,
4341 "__len__() should return >= 0");
Jeremy Hyltonf20fcf92002-07-25 16:06:15 +00004342 return -1;
4343 }
Guido van Rossum26111622001-10-01 16:42:49 +00004344 return len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004345}
4346
Guido van Rossumf4593e02001-10-03 12:09:30 +00004347/* Super-optimized version of slot_sq_item.
4348 Other slots could do the same... */
4349static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00004350slot_sq_item(PyObject *self, Py_ssize_t i)
Guido van Rossumf4593e02001-10-03 12:09:30 +00004351{
4352 static PyObject *getitem_str;
4353 PyObject *func, *args = NULL, *ival = NULL, *retval = NULL;
4354 descrgetfunc f;
4355
4356 if (getitem_str == NULL) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00004357 getitem_str = PyUnicode_InternFromString("__getitem__");
Guido van Rossumf4593e02001-10-03 12:09:30 +00004358 if (getitem_str == NULL)
4359 return NULL;
4360 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00004361 func = _PyType_Lookup(Py_Type(self), getitem_str);
Guido van Rossumf4593e02001-10-03 12:09:30 +00004362 if (func != NULL) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00004363 if ((f = Py_Type(func)->tp_descr_get) == NULL)
Guido van Rossumf4593e02001-10-03 12:09:30 +00004364 Py_INCREF(func);
Neal Norwitz673cd822002-10-18 16:33:13 +00004365 else {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00004366 func = f(func, self, (PyObject *)(Py_Type(self)));
Neal Norwitz673cd822002-10-18 16:33:13 +00004367 if (func == NULL) {
4368 return NULL;
4369 }
4370 }
Martin v. Löwiseb079f12006-02-16 14:32:27 +00004371 ival = PyInt_FromSsize_t(i);
Guido van Rossumf4593e02001-10-03 12:09:30 +00004372 if (ival != NULL) {
4373 args = PyTuple_New(1);
4374 if (args != NULL) {
4375 PyTuple_SET_ITEM(args, 0, ival);
4376 retval = PyObject_Call(func, args, NULL);
4377 Py_XDECREF(args);
4378 Py_XDECREF(func);
4379 return retval;
4380 }
4381 }
4382 }
4383 else {
4384 PyErr_SetObject(PyExc_AttributeError, getitem_str);
4385 }
4386 Py_XDECREF(args);
4387 Py_XDECREF(ival);
4388 Py_XDECREF(func);
4389 return NULL;
4390}
4391
Martin v. Löwis18e16552006-02-15 17:27:45 +00004392SLOT2(slot_sq_slice, "__getslice__", Py_ssize_t, Py_ssize_t, "nn")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004393
4394static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00004395slot_sq_ass_item(PyObject *self, Py_ssize_t index, PyObject *value)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004396{
4397 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004398 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004399
4400 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004401 res = call_method(self, "__delitem__", &delitem_str,
Thomas Wouters3fc2ca32006-04-21 11:28:17 +00004402 "(n)", index);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004403 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004404 res = call_method(self, "__setitem__", &setitem_str,
Thomas Wouters3fc2ca32006-04-21 11:28:17 +00004405 "(nO)", index, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004406 if (res == NULL)
4407 return -1;
4408 Py_DECREF(res);
4409 return 0;
4410}
4411
4412static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00004413slot_sq_ass_slice(PyObject *self, Py_ssize_t i, Py_ssize_t j, PyObject *value)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004414{
4415 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004416 static PyObject *delslice_str, *setslice_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004417
4418 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004419 res = call_method(self, "__delslice__", &delslice_str,
Thomas Wouters3fc2ca32006-04-21 11:28:17 +00004420 "(nn)", i, j);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004421 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004422 res = call_method(self, "__setslice__", &setslice_str,
Thomas Wouters3fc2ca32006-04-21 11:28:17 +00004423 "(nnO)", i, j, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004424 if (res == NULL)
4425 return -1;
4426 Py_DECREF(res);
4427 return 0;
4428}
4429
4430static int
4431slot_sq_contains(PyObject *self, PyObject *value)
4432{
Guido van Rossumb8f63662001-08-15 23:57:02 +00004433 PyObject *func, *res, *args;
Tim Petersbf9b2442003-03-23 05:35:36 +00004434 int result = -1;
4435
Guido van Rossum60718732001-08-28 17:47:51 +00004436 static PyObject *contains_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004437
Guido van Rossum55f20992001-10-01 17:18:22 +00004438 func = lookup_maybe(self, "__contains__", &contains_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004439 if (func != NULL) {
Raymond Hettinger8ae46892003-10-12 19:09:37 +00004440 args = PyTuple_Pack(1, value);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004441 if (args == NULL)
4442 res = NULL;
4443 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00004444 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004445 Py_DECREF(args);
4446 }
4447 Py_DECREF(func);
Tim Petersbf9b2442003-03-23 05:35:36 +00004448 if (res != NULL) {
4449 result = PyObject_IsTrue(res);
4450 Py_DECREF(res);
4451 }
Guido van Rossumb8f63662001-08-15 23:57:02 +00004452 }
Tim Petersbf9b2442003-03-23 05:35:36 +00004453 else if (! PyErr_Occurred()) {
Martin v. Löwis725507b2006-03-07 12:08:51 +00004454 /* Possible results: -1 and 1 */
4455 result = (int)_PySequence_IterSearch(self, value,
Tim Petersbf9b2442003-03-23 05:35:36 +00004456 PY_ITERSEARCH_CONTAINS);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004457 }
Tim Petersbf9b2442003-03-23 05:35:36 +00004458 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004459}
4460
Tim Peters6d6c1a32001-08-02 04:15:00 +00004461#define slot_mp_length slot_sq_length
4462
Guido van Rossumdc91b992001-08-08 22:26:22 +00004463SLOT1(slot_mp_subscript, "__getitem__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004464
4465static int
4466slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value)
4467{
4468 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004469 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004470
4471 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004472 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004473 "(O)", key);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004474 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004475 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004476 "(OO)", key, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004477 if (res == NULL)
4478 return -1;
4479 Py_DECREF(res);
4480 return 0;
4481}
4482
Guido van Rossumdc91b992001-08-08 22:26:22 +00004483SLOT1BIN(slot_nb_add, nb_add, "__add__", "__radd__")
4484SLOT1BIN(slot_nb_subtract, nb_subtract, "__sub__", "__rsub__")
4485SLOT1BIN(slot_nb_multiply, nb_multiply, "__mul__", "__rmul__")
Guido van Rossumdc91b992001-08-08 22:26:22 +00004486SLOT1BIN(slot_nb_remainder, nb_remainder, "__mod__", "__rmod__")
4487SLOT1BIN(slot_nb_divmod, nb_divmod, "__divmod__", "__rdivmod__")
4488
Jeremy Hylton938ace62002-07-17 16:30:39 +00004489static PyObject *slot_nb_power(PyObject *, PyObject *, PyObject *);
Guido van Rossumdc91b992001-08-08 22:26:22 +00004490
4491SLOT1BINFULL(slot_nb_power_binary, slot_nb_power,
4492 nb_power, "__pow__", "__rpow__")
4493
4494static PyObject *
4495slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus)
4496{
Guido van Rossum2730b132001-08-28 18:22:14 +00004497 static PyObject *pow_str;
4498
Guido van Rossumdc91b992001-08-08 22:26:22 +00004499 if (modulus == Py_None)
4500 return slot_nb_power_binary(self, other);
Guido van Rossum23094982002-06-10 14:30:43 +00004501 /* Three-arg power doesn't use __rpow__. But ternary_op
4502 can call this when the second argument's type uses
4503 slot_nb_power, so check before calling self.__pow__. */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00004504 if (Py_Type(self)->tp_as_number != NULL &&
4505 Py_Type(self)->tp_as_number->nb_power == slot_nb_power) {
Guido van Rossum23094982002-06-10 14:30:43 +00004506 return call_method(self, "__pow__", &pow_str,
4507 "(OO)", other, modulus);
4508 }
4509 Py_INCREF(Py_NotImplemented);
4510 return Py_NotImplemented;
Guido van Rossumdc91b992001-08-08 22:26:22 +00004511}
4512
4513SLOT0(slot_nb_negative, "__neg__")
4514SLOT0(slot_nb_positive, "__pos__")
4515SLOT0(slot_nb_absolute, "__abs__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004516
4517static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00004518slot_nb_bool(PyObject *self)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004519{
Tim Petersea7f75d2002-12-07 21:39:16 +00004520 PyObject *func, *args;
Jack Diederich4dafcc42006-11-28 19:15:13 +00004521 static PyObject *bool_str, *len_str;
Tim Petersea7f75d2002-12-07 21:39:16 +00004522 int result = -1;
Jack Diederich4dafcc42006-11-28 19:15:13 +00004523 int from_len = 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004524
Jack Diederich4dafcc42006-11-28 19:15:13 +00004525 func = lookup_maybe(self, "__bool__", &bool_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004526 if (func == NULL) {
Guido van Rossum55f20992001-10-01 17:18:22 +00004527 if (PyErr_Occurred())
Guido van Rossumb8f63662001-08-15 23:57:02 +00004528 return -1;
Guido van Rossum55f20992001-10-01 17:18:22 +00004529 func = lookup_maybe(self, "__len__", &len_str);
Tim Petersea7f75d2002-12-07 21:39:16 +00004530 if (func == NULL)
4531 return PyErr_Occurred() ? -1 : 1;
Jack Diederich4dafcc42006-11-28 19:15:13 +00004532 from_len = 1;
Tim Petersea7f75d2002-12-07 21:39:16 +00004533 }
4534 args = PyTuple_New(0);
4535 if (args != NULL) {
4536 PyObject *temp = PyObject_Call(func, args, NULL);
4537 Py_DECREF(args);
4538 if (temp != NULL) {
Jack Diederich4dafcc42006-11-28 19:15:13 +00004539 if (from_len) {
4540 /* enforced by slot_nb_len */
Jeremy Hylton090a3492003-06-27 16:46:45 +00004541 result = PyObject_IsTrue(temp);
Jack Diederich4dafcc42006-11-28 19:15:13 +00004542 }
4543 else if (PyBool_Check(temp)) {
4544 result = PyObject_IsTrue(temp);
4545 }
Jeremy Hylton090a3492003-06-27 16:46:45 +00004546 else {
4547 PyErr_Format(PyExc_TypeError,
Jack Diederich4dafcc42006-11-28 19:15:13 +00004548 "__bool__ should return "
4549 "bool, returned %s",
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00004550 Py_Type(temp)->tp_name);
Jeremy Hylton3e3159c2003-06-27 17:38:27 +00004551 result = -1;
Jeremy Hylton090a3492003-06-27 16:46:45 +00004552 }
Tim Petersea7f75d2002-12-07 21:39:16 +00004553 Py_DECREF(temp);
Guido van Rossum55f20992001-10-01 17:18:22 +00004554 }
Guido van Rossumb8f63662001-08-15 23:57:02 +00004555 }
Guido van Rossum55f20992001-10-01 17:18:22 +00004556 Py_DECREF(func);
Tim Petersea7f75d2002-12-07 21:39:16 +00004557 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004558}
4559
Guido van Rossum38fff8c2006-03-07 18:50:55 +00004560
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00004561static PyObject *
Guido van Rossum38fff8c2006-03-07 18:50:55 +00004562slot_nb_index(PyObject *self)
4563{
Guido van Rossum38fff8c2006-03-07 18:50:55 +00004564 static PyObject *index_str;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00004565 return call_method(self, "__index__", &index_str, "()");
Guido van Rossum38fff8c2006-03-07 18:50:55 +00004566}
4567
4568
Guido van Rossumdc91b992001-08-08 22:26:22 +00004569SLOT0(slot_nb_invert, "__invert__")
4570SLOT1BIN(slot_nb_lshift, nb_lshift, "__lshift__", "__rlshift__")
4571SLOT1BIN(slot_nb_rshift, nb_rshift, "__rshift__", "__rrshift__")
4572SLOT1BIN(slot_nb_and, nb_and, "__and__", "__rand__")
4573SLOT1BIN(slot_nb_xor, nb_xor, "__xor__", "__rxor__")
4574SLOT1BIN(slot_nb_or, nb_or, "__or__", "__ror__")
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004575
Guido van Rossumdc91b992001-08-08 22:26:22 +00004576SLOT0(slot_nb_int, "__int__")
4577SLOT0(slot_nb_long, "__long__")
4578SLOT0(slot_nb_float, "__float__")
Guido van Rossumdc91b992001-08-08 22:26:22 +00004579SLOT1(slot_nb_inplace_add, "__iadd__", PyObject *, "O")
4580SLOT1(slot_nb_inplace_subtract, "__isub__", PyObject *, "O")
4581SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *, "O")
Guido van Rossumdc91b992001-08-08 22:26:22 +00004582SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *, "O")
Thomas Wouterscf297e42007-02-23 15:07:44 +00004583/* Can't use SLOT1 here, because nb_inplace_power is ternary */
4584static PyObject *
4585slot_nb_inplace_power(PyObject *self, PyObject * arg1, PyObject *arg2)
4586{
4587 static PyObject *cache_str;
4588 return call_method(self, "__ipow__", &cache_str, "(" "O" ")", arg1);
4589}
Guido van Rossumdc91b992001-08-08 22:26:22 +00004590SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *, "O")
4591SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *, "O")
4592SLOT1(slot_nb_inplace_and, "__iand__", PyObject *, "O")
4593SLOT1(slot_nb_inplace_xor, "__ixor__", PyObject *, "O")
4594SLOT1(slot_nb_inplace_or, "__ior__", PyObject *, "O")
4595SLOT1BIN(slot_nb_floor_divide, nb_floor_divide,
4596 "__floordiv__", "__rfloordiv__")
4597SLOT1BIN(slot_nb_true_divide, nb_true_divide, "__truediv__", "__rtruediv__")
4598SLOT1(slot_nb_inplace_floor_divide, "__ifloordiv__", PyObject *, "O")
4599SLOT1(slot_nb_inplace_true_divide, "__itruediv__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004600
4601static int
Guido van Rossumb8f63662001-08-15 23:57:02 +00004602half_compare(PyObject *self, PyObject *other)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004603{
Guido van Rossumb8f63662001-08-15 23:57:02 +00004604 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004605 static PyObject *cmp_str;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004606 Py_ssize_t c;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004607
Guido van Rossum60718732001-08-28 17:47:51 +00004608 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004609 if (func == NULL) {
4610 PyErr_Clear();
4611 }
4612 else {
Raymond Hettinger8ae46892003-10-12 19:09:37 +00004613 args = PyTuple_Pack(1, other);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004614 if (args == NULL)
4615 res = NULL;
4616 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00004617 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004618 Py_DECREF(args);
4619 }
Raymond Hettingerab5dae32002-06-24 13:08:16 +00004620 Py_DECREF(func);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004621 if (res != Py_NotImplemented) {
4622 if (res == NULL)
4623 return -2;
4624 c = PyInt_AsLong(res);
4625 Py_DECREF(res);
4626 if (c == -1 && PyErr_Occurred())
4627 return -2;
4628 return (c < 0) ? -1 : (c > 0) ? 1 : 0;
4629 }
4630 Py_DECREF(res);
4631 }
4632 return 2;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004633}
4634
Guido van Rossumab3b0342001-09-18 20:38:53 +00004635/* This slot is published for the benefit of try_3way_compare in object.c */
4636int
4637_PyObject_SlotCompare(PyObject *self, PyObject *other)
Guido van Rossumb8f63662001-08-15 23:57:02 +00004638{
4639 int c;
4640
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00004641 if (Py_Type(self)->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00004642 c = half_compare(self, other);
4643 if (c <= 1)
4644 return c;
4645 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00004646 if (Py_Type(other)->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00004647 c = half_compare(other, self);
4648 if (c < -1)
4649 return -2;
4650 if (c <= 1)
4651 return -c;
4652 }
4653 return (void *)self < (void *)other ? -1 :
4654 (void *)self > (void *)other ? 1 : 0;
4655}
4656
4657static PyObject *
4658slot_tp_repr(PyObject *self)
4659{
4660 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004661 static PyObject *repr_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004662
Guido van Rossum60718732001-08-28 17:47:51 +00004663 func = lookup_method(self, "__repr__", &repr_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004664 if (func != NULL) {
4665 res = PyEval_CallObject(func, NULL);
4666 Py_DECREF(func);
4667 return res;
4668 }
Barry Warsaw7ce36942001-08-24 18:34:26 +00004669 PyErr_Clear();
Walter Dörwald1ab83302007-05-18 17:15:44 +00004670 return PyUnicode_FromFormat("<%s object at %p>",
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00004671 Py_Type(self)->tp_name, self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004672}
4673
4674static PyObject *
4675slot_tp_str(PyObject *self)
4676{
4677 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004678 static PyObject *str_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004679
Guido van Rossum60718732001-08-28 17:47:51 +00004680 func = lookup_method(self, "__str__", &str_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004681 if (func != NULL) {
4682 res = PyEval_CallObject(func, NULL);
4683 Py_DECREF(func);
4684 return res;
4685 }
4686 else {
Walter Dörwald1ab83302007-05-18 17:15:44 +00004687 PyObject *ress;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004688 PyErr_Clear();
Walter Dörwald1ab83302007-05-18 17:15:44 +00004689 res = slot_tp_repr(self);
4690 if (!res)
4691 return NULL;
4692 ress = _PyUnicode_AsDefaultEncodedString(res, NULL);
4693 Py_DECREF(res);
4694 return ress;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004695 }
4696}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004697
4698static long
4699slot_tp_hash(PyObject *self)
4700{
Guido van Rossum4011a242006-08-17 23:09:57 +00004701 PyObject *func, *res;
Guido van Rossum50e9fb92006-08-17 05:42:55 +00004702 static PyObject *hash_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004703 long h;
4704
Guido van Rossum60718732001-08-28 17:47:51 +00004705 func = lookup_method(self, "__hash__", &hash_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004706
Guido van Rossum50e9fb92006-08-17 05:42:55 +00004707 if (func == Py_None) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00004708 Py_DECREF(func);
Guido van Rossum50e9fb92006-08-17 05:42:55 +00004709 func = NULL;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004710 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +00004711
4712 if (func == NULL) {
Guido van Rossum50e9fb92006-08-17 05:42:55 +00004713 PyErr_Format(PyExc_TypeError, "unhashable type: '%.200s'",
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00004714 Py_Type(self)->tp_name);
Guido van Rossum50e9fb92006-08-17 05:42:55 +00004715 return -1;
4716 }
4717
Guido van Rossum4011a242006-08-17 23:09:57 +00004718 res = PyEval_CallObject(func, NULL);
Guido van Rossum50e9fb92006-08-17 05:42:55 +00004719 Py_DECREF(func);
4720 if (res == NULL)
4721 return -1;
4722 if (PyLong_Check(res))
4723 h = PyLong_Type.tp_hash(res);
4724 else
4725 h = PyInt_AsLong(res);
4726 Py_DECREF(res);
4727 if (h == -1 && !PyErr_Occurred())
4728 h = -2;
4729 return h;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004730}
4731
4732static PyObject *
4733slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds)
4734{
Guido van Rossum60718732001-08-28 17:47:51 +00004735 static PyObject *call_str;
4736 PyObject *meth = lookup_method(self, "__call__", &call_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004737 PyObject *res;
4738
4739 if (meth == NULL)
4740 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004741
4742 /* PyObject_Call() will end up calling slot_tp_call() again if
4743 the object returned for __call__ has __call__ itself defined
4744 upon it. This can be an infinite recursion if you set
4745 __call__ in a class to an instance of it. */
4746 if (Py_EnterRecursiveCall(" in __call__")) {
4747 Py_DECREF(meth);
4748 return NULL;
4749 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004750 res = PyObject_Call(meth, args, kwds);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004751 Py_LeaveRecursiveCall();
4752
Tim Peters6d6c1a32001-08-02 04:15:00 +00004753 Py_DECREF(meth);
4754 return res;
4755}
4756
Guido van Rossum14a6f832001-10-17 13:59:09 +00004757/* There are two slot dispatch functions for tp_getattro.
4758
4759 - slot_tp_getattro() is used when __getattribute__ is overridden
4760 but no __getattr__ hook is present;
4761
4762 - slot_tp_getattr_hook() is used when a __getattr__ hook is present.
4763
Guido van Rossumc334df52002-04-04 23:44:47 +00004764 The code in update_one_slot() always installs slot_tp_getattr_hook(); this
4765 detects the absence of __getattr__ and then installs the simpler slot if
4766 necessary. */
Guido van Rossum14a6f832001-10-17 13:59:09 +00004767
Tim Peters6d6c1a32001-08-02 04:15:00 +00004768static PyObject *
4769slot_tp_getattro(PyObject *self, PyObject *name)
4770{
Guido van Rossum14a6f832001-10-17 13:59:09 +00004771 static PyObject *getattribute_str = NULL;
4772 return call_method(self, "__getattribute__", &getattribute_str,
4773 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004774}
4775
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004776static PyObject *
4777slot_tp_getattr_hook(PyObject *self, PyObject *name)
4778{
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00004779 PyTypeObject *tp = Py_Type(self);
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004780 PyObject *getattr, *getattribute, *res;
4781 static PyObject *getattribute_str = NULL;
4782 static PyObject *getattr_str = NULL;
4783
4784 if (getattr_str == NULL) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00004785 getattr_str = PyUnicode_InternFromString("__getattr__");
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004786 if (getattr_str == NULL)
4787 return NULL;
4788 }
4789 if (getattribute_str == NULL) {
4790 getattribute_str =
Martin v. Löwis5b222132007-06-10 09:51:05 +00004791 PyUnicode_InternFromString("__getattribute__");
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004792 if (getattribute_str == NULL)
4793 return NULL;
4794 }
4795 getattr = _PyType_Lookup(tp, getattr_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00004796 if (getattr == NULL) {
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004797 /* No __getattr__ hook: use a simpler dispatcher */
4798 tp->tp_getattro = slot_tp_getattro;
4799 return slot_tp_getattro(self, name);
4800 }
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004801 getattribute = _PyType_Lookup(tp, getattribute_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00004802 if (getattribute == NULL ||
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00004803 (Py_Type(getattribute) == &PyWrapperDescr_Type &&
Guido van Rossum14a6f832001-10-17 13:59:09 +00004804 ((PyWrapperDescrObject *)getattribute)->d_wrapped ==
4805 (void *)PyObject_GenericGetAttr))
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004806 res = PyObject_GenericGetAttr(self, name);
4807 else
Thomas Wouters477c8d52006-05-27 19:21:47 +00004808 res = PyObject_CallFunctionObjArgs(getattribute, self, name, NULL);
Guido van Rossum14a6f832001-10-17 13:59:09 +00004809 if (res == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) {
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004810 PyErr_Clear();
Thomas Wouters477c8d52006-05-27 19:21:47 +00004811 res = PyObject_CallFunctionObjArgs(getattr, self, name, NULL);
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004812 }
4813 return res;
4814}
4815
Tim Peters6d6c1a32001-08-02 04:15:00 +00004816static int
4817slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value)
4818{
4819 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004820 static PyObject *delattr_str, *setattr_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004821
4822 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004823 res = call_method(self, "__delattr__", &delattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004824 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004825 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004826 res = call_method(self, "__setattr__", &setattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004827 "(OO)", name, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004828 if (res == NULL)
4829 return -1;
4830 Py_DECREF(res);
4831 return 0;
4832}
4833
Tim Peters6d6c1a32001-08-02 04:15:00 +00004834static PyObject *
Guido van Rossumb8f63662001-08-15 23:57:02 +00004835half_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004836{
Guido van Rossumb8f63662001-08-15 23:57:02 +00004837 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004838 static PyObject *op_str[6];
Tim Peters6d6c1a32001-08-02 04:15:00 +00004839
Guido van Rossum60718732001-08-28 17:47:51 +00004840 func = lookup_method(self, name_op[op], &op_str[op]);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004841 if (func == NULL) {
4842 PyErr_Clear();
4843 Py_INCREF(Py_NotImplemented);
4844 return Py_NotImplemented;
4845 }
Raymond Hettinger8ae46892003-10-12 19:09:37 +00004846 args = PyTuple_Pack(1, other);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004847 if (args == NULL)
4848 res = NULL;
4849 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00004850 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004851 Py_DECREF(args);
4852 }
4853 Py_DECREF(func);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004854 return res;
4855}
4856
Guido van Rossumb8f63662001-08-15 23:57:02 +00004857static PyObject *
4858slot_tp_richcompare(PyObject *self, PyObject *other, int op)
4859{
4860 PyObject *res;
4861
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00004862 if (Py_Type(self)->tp_richcompare == slot_tp_richcompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00004863 res = half_richcompare(self, other, op);
4864 if (res != Py_NotImplemented)
4865 return res;
4866 Py_DECREF(res);
4867 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00004868 if (Py_Type(other)->tp_richcompare == slot_tp_richcompare) {
Tim Petersf4aca752004-09-23 02:39:37 +00004869 res = half_richcompare(other, self, _Py_SwappedOp[op]);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004870 if (res != Py_NotImplemented) {
4871 return res;
4872 }
4873 Py_DECREF(res);
4874 }
4875 Py_INCREF(Py_NotImplemented);
4876 return Py_NotImplemented;
4877}
4878
4879static PyObject *
4880slot_tp_iter(PyObject *self)
4881{
4882 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004883 static PyObject *iter_str, *getitem_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004884
Guido van Rossum60718732001-08-28 17:47:51 +00004885 func = lookup_method(self, "__iter__", &iter_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004886 if (func != NULL) {
Guido van Rossum84b2bed2002-08-16 17:01:09 +00004887 PyObject *args;
4888 args = res = PyTuple_New(0);
4889 if (args != NULL) {
4890 res = PyObject_Call(func, args, NULL);
4891 Py_DECREF(args);
4892 }
4893 Py_DECREF(func);
4894 return res;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004895 }
4896 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00004897 func = lookup_method(self, "__getitem__", &getitem_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004898 if (func == NULL) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004899 PyErr_Format(PyExc_TypeError,
4900 "'%.200s' object is not iterable",
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00004901 Py_Type(self)->tp_name);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004902 return NULL;
4903 }
4904 Py_DECREF(func);
4905 return PySeqIter_New(self);
4906}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004907
4908static PyObject *
4909slot_tp_iternext(PyObject *self)
4910{
Guido van Rossum2730b132001-08-28 18:22:14 +00004911 static PyObject *next_str;
Georg Brandla18af4e2007-04-21 15:47:16 +00004912 return call_method(self, "__next__", &next_str, "()");
Tim Peters6d6c1a32001-08-02 04:15:00 +00004913}
4914
Guido van Rossum1a493502001-08-17 16:47:50 +00004915static PyObject *
4916slot_tp_descr_get(PyObject *self, PyObject *obj, PyObject *type)
4917{
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00004918 PyTypeObject *tp = Py_Type(self);
Guido van Rossum1a493502001-08-17 16:47:50 +00004919 PyObject *get;
4920 static PyObject *get_str = NULL;
4921
4922 if (get_str == NULL) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00004923 get_str = PyUnicode_InternFromString("__get__");
Guido van Rossum1a493502001-08-17 16:47:50 +00004924 if (get_str == NULL)
4925 return NULL;
4926 }
4927 get = _PyType_Lookup(tp, get_str);
4928 if (get == NULL) {
4929 /* Avoid further slowdowns */
4930 if (tp->tp_descr_get == slot_tp_descr_get)
4931 tp->tp_descr_get = NULL;
4932 Py_INCREF(self);
4933 return self;
4934 }
Guido van Rossum2c252392001-08-24 10:13:31 +00004935 if (obj == NULL)
4936 obj = Py_None;
4937 if (type == NULL)
4938 type = Py_None;
Thomas Wouters477c8d52006-05-27 19:21:47 +00004939 return PyObject_CallFunctionObjArgs(get, self, obj, type, NULL);
Guido van Rossum1a493502001-08-17 16:47:50 +00004940}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004941
4942static int
4943slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value)
4944{
Guido van Rossum2c252392001-08-24 10:13:31 +00004945 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004946 static PyObject *del_str, *set_str;
Guido van Rossum2c252392001-08-24 10:13:31 +00004947
4948 if (value == NULL)
Guido van Rossum1d5b3f22001-12-03 00:08:33 +00004949 res = call_method(self, "__delete__", &del_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004950 "(O)", target);
Guido van Rossum2c252392001-08-24 10:13:31 +00004951 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004952 res = call_method(self, "__set__", &set_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004953 "(OO)", target, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004954 if (res == NULL)
4955 return -1;
4956 Py_DECREF(res);
4957 return 0;
4958}
4959
4960static int
4961slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds)
4962{
Guido van Rossum60718732001-08-28 17:47:51 +00004963 static PyObject *init_str;
4964 PyObject *meth = lookup_method(self, "__init__", &init_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004965 PyObject *res;
4966
4967 if (meth == NULL)
4968 return -1;
4969 res = PyObject_Call(meth, args, kwds);
4970 Py_DECREF(meth);
4971 if (res == NULL)
4972 return -1;
Raymond Hettingerb67cc802005-03-03 16:45:19 +00004973 if (res != Py_None) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004974 PyErr_Format(PyExc_TypeError,
4975 "__init__() should return None, not '%.200s'",
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00004976 Py_Type(res)->tp_name);
Raymond Hettingerb67cc802005-03-03 16:45:19 +00004977 Py_DECREF(res);
4978 return -1;
4979 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004980 Py_DECREF(res);
4981 return 0;
4982}
4983
4984static PyObject *
4985slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
4986{
Guido van Rossum7bed2132002-08-08 21:57:53 +00004987 static PyObject *new_str;
4988 PyObject *func;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004989 PyObject *newargs, *x;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004990 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004991
Guido van Rossum7bed2132002-08-08 21:57:53 +00004992 if (new_str == NULL) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00004993 new_str = PyUnicode_InternFromString("__new__");
Guido van Rossum7bed2132002-08-08 21:57:53 +00004994 if (new_str == NULL)
4995 return NULL;
4996 }
4997 func = PyObject_GetAttr((PyObject *)type, new_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004998 if (func == NULL)
4999 return NULL;
5000 assert(PyTuple_Check(args));
5001 n = PyTuple_GET_SIZE(args);
5002 newargs = PyTuple_New(n+1);
5003 if (newargs == NULL)
5004 return NULL;
5005 Py_INCREF(type);
5006 PyTuple_SET_ITEM(newargs, 0, (PyObject *)type);
5007 for (i = 0; i < n; i++) {
5008 x = PyTuple_GET_ITEM(args, i);
5009 Py_INCREF(x);
5010 PyTuple_SET_ITEM(newargs, i+1, x);
5011 }
5012 x = PyObject_Call(func, newargs, kwds);
Guido van Rossum25d18072001-10-01 15:55:28 +00005013 Py_DECREF(newargs);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005014 Py_DECREF(func);
5015 return x;
5016}
5017
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005018static void
5019slot_tp_del(PyObject *self)
5020{
5021 static PyObject *del_str = NULL;
5022 PyObject *del, *res;
5023 PyObject *error_type, *error_value, *error_traceback;
5024
5025 /* Temporarily resurrect the object. */
5026 assert(self->ob_refcnt == 0);
5027 self->ob_refcnt = 1;
5028
5029 /* Save the current exception, if any. */
5030 PyErr_Fetch(&error_type, &error_value, &error_traceback);
5031
5032 /* Execute __del__ method, if any. */
5033 del = lookup_maybe(self, "__del__", &del_str);
5034 if (del != NULL) {
5035 res = PyEval_CallObject(del, NULL);
5036 if (res == NULL)
5037 PyErr_WriteUnraisable(del);
5038 else
5039 Py_DECREF(res);
5040 Py_DECREF(del);
5041 }
5042
5043 /* Restore the saved exception. */
5044 PyErr_Restore(error_type, error_value, error_traceback);
5045
5046 /* Undo the temporary resurrection; can't use DECREF here, it would
5047 * cause a recursive call.
5048 */
5049 assert(self->ob_refcnt > 0);
5050 if (--self->ob_refcnt == 0)
5051 return; /* this is the normal path out */
5052
5053 /* __del__ resurrected it! Make it look like the original Py_DECREF
5054 * never happened.
5055 */
5056 {
Martin v. Löwis725507b2006-03-07 12:08:51 +00005057 Py_ssize_t refcnt = self->ob_refcnt;
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005058 _Py_NewReference(self);
5059 self->ob_refcnt = refcnt;
5060 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00005061 assert(!PyType_IS_GC(Py_Type(self)) ||
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005062 _Py_AS_GC(self)->gc.gc_refs != _PyGC_REFS_UNTRACKED);
Michael W. Hudson3f3b6682004-08-03 10:21:03 +00005063 /* If Py_REF_DEBUG, _Py_NewReference bumped _Py_RefTotal, so
5064 * we need to undo that. */
5065 _Py_DEC_REFTOTAL;
5066 /* If Py_TRACE_REFS, _Py_NewReference re-added self to the object
5067 * chain, so no more to do there.
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005068 * If COUNT_ALLOCS, the original decref bumped tp_frees, and
5069 * _Py_NewReference bumped tp_allocs: both of those need to be
5070 * undone.
5071 */
5072#ifdef COUNT_ALLOCS
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00005073 --Py_Type(self)->tp_frees;
5074 --Py_Type(self)->tp_allocs;
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005075#endif
5076}
5077
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005078
5079/* Table mapping __foo__ names to tp_foo offsets and slot_tp_foo wrapper
Tim Petersbf9b2442003-03-23 05:35:36 +00005080 functions. The offsets here are relative to the 'PyHeapTypeObject'
Guido van Rossume5c691a2003-03-07 15:13:17 +00005081 structure, which incorporates the additional structures used for numbers,
5082 sequences and mappings.
5083 Note that multiple names may map to the same slot (e.g. __eq__,
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005084 __ne__ etc. all map to tp_richcompare) and one name may map to multiple
Guido van Rossumc334df52002-04-04 23:44:47 +00005085 slots (e.g. __str__ affects tp_str as well as tp_repr). The table is
5086 terminated with an all-zero entry. (This table is further initialized and
5087 sorted in init_slotdefs() below.) */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005088
Guido van Rossum6d204072001-10-21 00:44:31 +00005089typedef struct wrapperbase slotdef;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005090
5091#undef TPSLOT
Guido van Rossumc8e56452001-10-22 00:43:43 +00005092#undef FLSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005093#undef ETSLOT
5094#undef SQSLOT
5095#undef MPSLOT
5096#undef NBSLOT
Guido van Rossum6d204072001-10-21 00:44:31 +00005097#undef UNSLOT
5098#undef IBSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005099#undef BINSLOT
5100#undef RBINSLOT
5101
Guido van Rossum6d204072001-10-21 00:44:31 +00005102#define TPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Neal Norwitzd47714a2002-08-13 19:01:38 +00005103 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
5104 PyDoc_STR(DOC)}
Guido van Rossumc8e56452001-10-22 00:43:43 +00005105#define FLSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC, FLAGS) \
5106 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
Neal Norwitzd47714a2002-08-13 19:01:38 +00005107 PyDoc_STR(DOC), FLAGS}
Guido van Rossum6d204072001-10-21 00:44:31 +00005108#define ETSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Guido van Rossume5c691a2003-03-07 15:13:17 +00005109 {NAME, offsetof(PyHeapTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
Neal Norwitzd47714a2002-08-13 19:01:38 +00005110 PyDoc_STR(DOC)}
Guido van Rossum6d204072001-10-21 00:44:31 +00005111#define SQSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
5112 ETSLOT(NAME, as_sequence.SLOT, FUNCTION, WRAPPER, DOC)
5113#define MPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
5114 ETSLOT(NAME, as_mapping.SLOT, FUNCTION, WRAPPER, DOC)
5115#define NBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
5116 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, DOC)
5117#define UNSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
5118 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
5119 "x." NAME "() <==> " DOC)
5120#define IBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
5121 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
5122 "x." NAME "(y) <==> x" DOC "y")
5123#define BINSLOT(NAME, SLOT, FUNCTION, DOC) \
5124 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
5125 "x." NAME "(y) <==> x" DOC "y")
5126#define RBINSLOT(NAME, SLOT, FUNCTION, DOC) \
5127 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
5128 "x." NAME "(y) <==> y" DOC "x")
Anthony Baxter56616992005-06-03 14:12:21 +00005129#define BINSLOTNOTINFIX(NAME, SLOT, FUNCTION, DOC) \
5130 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
5131 "x." NAME "(y) <==> " DOC)
5132#define RBINSLOTNOTINFIX(NAME, SLOT, FUNCTION, DOC) \
5133 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
5134 "x." NAME "(y) <==> " DOC)
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005135
5136static slotdef slotdefs[] = {
Martin v. Löwis18e16552006-02-15 17:27:45 +00005137 SQSLOT("__len__", sq_length, slot_sq_length, wrap_lenfunc,
Guido van Rossum6d204072001-10-21 00:44:31 +00005138 "x.__len__() <==> len(x)"),
Armin Rigofd163f92005-12-29 15:59:19 +00005139 /* Heap types defining __add__/__mul__ have sq_concat/sq_repeat == NULL.
5140 The logic in abstract.c always falls back to nb_add/nb_multiply in
5141 this case. Defining both the nb_* and the sq_* slots to call the
5142 user-defined methods has unexpected side-effects, as shown by
5143 test_descr.notimplemented() */
5144 SQSLOT("__add__", sq_concat, NULL, wrap_binaryfunc,
Guido van Rossumd8faa362007-04-27 19:54:29 +00005145 "x.__add__(y) <==> x+y"),
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00005146 SQSLOT("__mul__", sq_repeat, NULL, wrap_indexargfunc,
Guido van Rossumd8faa362007-04-27 19:54:29 +00005147 "x.__mul__(n) <==> x*n"),
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00005148 SQSLOT("__rmul__", sq_repeat, NULL, wrap_indexargfunc,
Guido van Rossumd8faa362007-04-27 19:54:29 +00005149 "x.__rmul__(n) <==> n*x"),
Guido van Rossum6d204072001-10-21 00:44:31 +00005150 SQSLOT("__getitem__", sq_item, slot_sq_item, wrap_sq_item,
5151 "x.__getitem__(y) <==> x[y]"),
Martin v. Löwis18e16552006-02-15 17:27:45 +00005152 SQSLOT("__getslice__", sq_slice, slot_sq_slice, wrap_ssizessizeargfunc,
Brett Cannon154da9b2003-05-20 02:30:04 +00005153 "x.__getslice__(i, j) <==> x[i:j]\n\
Guido van Rossumd8faa362007-04-27 19:54:29 +00005154 \n\
5155 Use of negative indices is not supported."),
Guido van Rossum6d204072001-10-21 00:44:31 +00005156 SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_setitem,
Brett Cannonbe67d872003-05-20 02:40:12 +00005157 "x.__setitem__(i, y) <==> x[i]=y"),
Guido van Rossum6d204072001-10-21 00:44:31 +00005158 SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_delitem,
Brett Cannonbe67d872003-05-20 02:40:12 +00005159 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005160 SQSLOT("__setslice__", sq_ass_slice, slot_sq_ass_slice,
Martin v. Löwis18e16552006-02-15 17:27:45 +00005161 wrap_ssizessizeobjargproc,
Brett Cannonbe67d872003-05-20 02:40:12 +00005162 "x.__setslice__(i, j, y) <==> x[i:j]=y\n\
Guido van Rossumd8faa362007-04-27 19:54:29 +00005163 \n\
5164 Use of negative indices is not supported."),
Guido van Rossum6d204072001-10-21 00:44:31 +00005165 SQSLOT("__delslice__", sq_ass_slice, slot_sq_ass_slice, wrap_delslice,
Brett Cannonbe67d872003-05-20 02:40:12 +00005166 "x.__delslice__(i, j) <==> del x[i:j]\n\
Guido van Rossumd8faa362007-04-27 19:54:29 +00005167 \n\
5168 Use of negative indices is not supported."),
Guido van Rossum6d204072001-10-21 00:44:31 +00005169 SQSLOT("__contains__", sq_contains, slot_sq_contains, wrap_objobjproc,
5170 "x.__contains__(y) <==> y in x"),
Armin Rigofd163f92005-12-29 15:59:19 +00005171 SQSLOT("__iadd__", sq_inplace_concat, NULL,
Guido van Rossumd8faa362007-04-27 19:54:29 +00005172 wrap_binaryfunc, "x.__iadd__(y) <==> x+=y"),
Armin Rigofd163f92005-12-29 15:59:19 +00005173 SQSLOT("__imul__", sq_inplace_repeat, NULL,
Guido van Rossumd8faa362007-04-27 19:54:29 +00005174 wrap_indexargfunc, "x.__imul__(y) <==> x*=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005175
Martin v. Löwis18e16552006-02-15 17:27:45 +00005176 MPSLOT("__len__", mp_length, slot_mp_length, wrap_lenfunc,
Guido van Rossum6d204072001-10-21 00:44:31 +00005177 "x.__len__() <==> len(x)"),
Guido van Rossumfd38f8e2001-10-09 20:17:57 +00005178 MPSLOT("__getitem__", mp_subscript, slot_mp_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00005179 wrap_binaryfunc,
5180 "x.__getitem__(y) <==> x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005181 MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00005182 wrap_objobjargproc,
5183 "x.__setitem__(i, y) <==> x[i]=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005184 MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00005185 wrap_delitem,
5186 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005187
Guido van Rossum6d204072001-10-21 00:44:31 +00005188 BINSLOT("__add__", nb_add, slot_nb_add,
5189 "+"),
5190 RBINSLOT("__radd__", nb_add, slot_nb_add,
5191 "+"),
5192 BINSLOT("__sub__", nb_subtract, slot_nb_subtract,
5193 "-"),
5194 RBINSLOT("__rsub__", nb_subtract, slot_nb_subtract,
5195 "-"),
5196 BINSLOT("__mul__", nb_multiply, slot_nb_multiply,
5197 "*"),
5198 RBINSLOT("__rmul__", nb_multiply, slot_nb_multiply,
5199 "*"),
Guido van Rossum6d204072001-10-21 00:44:31 +00005200 BINSLOT("__mod__", nb_remainder, slot_nb_remainder,
5201 "%"),
5202 RBINSLOT("__rmod__", nb_remainder, slot_nb_remainder,
5203 "%"),
Anthony Baxter56616992005-06-03 14:12:21 +00005204 BINSLOTNOTINFIX("__divmod__", nb_divmod, slot_nb_divmod,
Guido van Rossum6d204072001-10-21 00:44:31 +00005205 "divmod(x, y)"),
Anthony Baxter56616992005-06-03 14:12:21 +00005206 RBINSLOTNOTINFIX("__rdivmod__", nb_divmod, slot_nb_divmod,
Guido van Rossum6d204072001-10-21 00:44:31 +00005207 "divmod(y, x)"),
5208 NBSLOT("__pow__", nb_power, slot_nb_power, wrap_ternaryfunc,
5209 "x.__pow__(y[, z]) <==> pow(x, y[, z])"),
5210 NBSLOT("__rpow__", nb_power, slot_nb_power, wrap_ternaryfunc_r,
5211 "y.__rpow__(x[, z]) <==> pow(x, y[, z])"),
5212 UNSLOT("__neg__", nb_negative, slot_nb_negative, wrap_unaryfunc, "-x"),
5213 UNSLOT("__pos__", nb_positive, slot_nb_positive, wrap_unaryfunc, "+x"),
5214 UNSLOT("__abs__", nb_absolute, slot_nb_absolute, wrap_unaryfunc,
5215 "abs(x)"),
Jack Diederich4dafcc42006-11-28 19:15:13 +00005216 UNSLOT("__bool__", nb_bool, slot_nb_bool, wrap_inquirypred,
Guido van Rossum6d204072001-10-21 00:44:31 +00005217 "x != 0"),
5218 UNSLOT("__invert__", nb_invert, slot_nb_invert, wrap_unaryfunc, "~x"),
5219 BINSLOT("__lshift__", nb_lshift, slot_nb_lshift, "<<"),
5220 RBINSLOT("__rlshift__", nb_lshift, slot_nb_lshift, "<<"),
5221 BINSLOT("__rshift__", nb_rshift, slot_nb_rshift, ">>"),
5222 RBINSLOT("__rrshift__", nb_rshift, slot_nb_rshift, ">>"),
5223 BINSLOT("__and__", nb_and, slot_nb_and, "&"),
5224 RBINSLOT("__rand__", nb_and, slot_nb_and, "&"),
5225 BINSLOT("__xor__", nb_xor, slot_nb_xor, "^"),
5226 RBINSLOT("__rxor__", nb_xor, slot_nb_xor, "^"),
5227 BINSLOT("__or__", nb_or, slot_nb_or, "|"),
5228 RBINSLOT("__ror__", nb_or, slot_nb_or, "|"),
Guido van Rossum6d204072001-10-21 00:44:31 +00005229 UNSLOT("__int__", nb_int, slot_nb_int, wrap_unaryfunc,
5230 "int(x)"),
5231 UNSLOT("__long__", nb_long, slot_nb_long, wrap_unaryfunc,
5232 "long(x)"),
5233 UNSLOT("__float__", nb_float, slot_nb_float, wrap_unaryfunc,
5234 "float(x)"),
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00005235 NBSLOT("__index__", nb_index, slot_nb_index, wrap_unaryfunc,
Guido van Rossum38fff8c2006-03-07 18:50:55 +00005236 "x[y:z] <==> x[y.__index__():z.__index__()]"),
Guido van Rossum6d204072001-10-21 00:44:31 +00005237 IBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add,
5238 wrap_binaryfunc, "+"),
5239 IBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract,
5240 wrap_binaryfunc, "-"),
5241 IBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply,
5242 wrap_binaryfunc, "*"),
Guido van Rossum6d204072001-10-21 00:44:31 +00005243 IBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder,
5244 wrap_binaryfunc, "%"),
5245 IBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power,
Guido van Rossum6e5680f2002-10-15 01:01:53 +00005246 wrap_binaryfunc, "**"),
Guido van Rossum6d204072001-10-21 00:44:31 +00005247 IBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift,
5248 wrap_binaryfunc, "<<"),
5249 IBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift,
5250 wrap_binaryfunc, ">>"),
5251 IBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and,
5252 wrap_binaryfunc, "&"),
5253 IBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor,
5254 wrap_binaryfunc, "^"),
5255 IBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or,
5256 wrap_binaryfunc, "|"),
5257 BINSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
5258 RBINSLOT("__rfloordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
5259 BINSLOT("__truediv__", nb_true_divide, slot_nb_true_divide, "/"),
5260 RBINSLOT("__rtruediv__", nb_true_divide, slot_nb_true_divide, "/"),
5261 IBSLOT("__ifloordiv__", nb_inplace_floor_divide,
5262 slot_nb_inplace_floor_divide, wrap_binaryfunc, "//"),
5263 IBSLOT("__itruediv__", nb_inplace_true_divide,
5264 slot_nb_inplace_true_divide, wrap_binaryfunc, "/"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005265
Guido van Rossum6d204072001-10-21 00:44:31 +00005266 TPSLOT("__str__", tp_str, slot_tp_str, wrap_unaryfunc,
5267 "x.__str__() <==> str(x)"),
5268 TPSLOT("__repr__", tp_repr, slot_tp_repr, wrap_unaryfunc,
5269 "x.__repr__() <==> repr(x)"),
5270 TPSLOT("__cmp__", tp_compare, _PyObject_SlotCompare, wrap_cmpfunc,
5271 "x.__cmp__(y) <==> cmp(x,y)"),
5272 TPSLOT("__hash__", tp_hash, slot_tp_hash, wrap_hashfunc,
5273 "x.__hash__() <==> hash(x)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00005274 FLSLOT("__call__", tp_call, slot_tp_call, (wrapperfunc)wrap_call,
5275 "x.__call__(...) <==> x(...)", PyWrapperFlag_KEYWORDS),
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005276 TPSLOT("__getattribute__", tp_getattro, slot_tp_getattr_hook,
Guido van Rossum6d204072001-10-21 00:44:31 +00005277 wrap_binaryfunc, "x.__getattribute__('name') <==> x.name"),
5278 TPSLOT("__getattribute__", tp_getattr, NULL, NULL, ""),
5279 TPSLOT("__getattr__", tp_getattro, slot_tp_getattr_hook, NULL, ""),
5280 TPSLOT("__getattr__", tp_getattr, NULL, NULL, ""),
5281 TPSLOT("__setattr__", tp_setattro, slot_tp_setattro, wrap_setattr,
5282 "x.__setattr__('name', value) <==> x.name = value"),
5283 TPSLOT("__setattr__", tp_setattr, NULL, NULL, ""),
5284 TPSLOT("__delattr__", tp_setattro, slot_tp_setattro, wrap_delattr,
5285 "x.__delattr__('name') <==> del x.name"),
5286 TPSLOT("__delattr__", tp_setattr, NULL, NULL, ""),
5287 TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare, richcmp_lt,
5288 "x.__lt__(y) <==> x<y"),
5289 TPSLOT("__le__", tp_richcompare, slot_tp_richcompare, richcmp_le,
5290 "x.__le__(y) <==> x<=y"),
5291 TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare, richcmp_eq,
5292 "x.__eq__(y) <==> x==y"),
5293 TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare, richcmp_ne,
5294 "x.__ne__(y) <==> x!=y"),
5295 TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare, richcmp_gt,
5296 "x.__gt__(y) <==> x>y"),
5297 TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare, richcmp_ge,
5298 "x.__ge__(y) <==> x>=y"),
5299 TPSLOT("__iter__", tp_iter, slot_tp_iter, wrap_unaryfunc,
5300 "x.__iter__() <==> iter(x)"),
Georg Brandla18af4e2007-04-21 15:47:16 +00005301 TPSLOT("__next__", tp_iternext, slot_tp_iternext, wrap_next,
5302 "x.__next__() <==> next(x)"),
Guido van Rossum6d204072001-10-21 00:44:31 +00005303 TPSLOT("__get__", tp_descr_get, slot_tp_descr_get, wrap_descr_get,
5304 "descr.__get__(obj[, type]) -> value"),
5305 TPSLOT("__set__", tp_descr_set, slot_tp_descr_set, wrap_descr_set,
5306 "descr.__set__(obj, value)"),
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00005307 TPSLOT("__delete__", tp_descr_set, slot_tp_descr_set,
5308 wrap_descr_delete, "descr.__delete__(obj)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00005309 FLSLOT("__init__", tp_init, slot_tp_init, (wrapperfunc)wrap_init,
Guido van Rossum6d204072001-10-21 00:44:31 +00005310 "x.__init__(...) initializes x; "
Guido van Rossumc8e56452001-10-22 00:43:43 +00005311 "see x.__class__.__doc__ for signature",
5312 PyWrapperFlag_KEYWORDS),
5313 TPSLOT("__new__", tp_new, slot_tp_new, NULL, ""),
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005314 TPSLOT("__del__", tp_del, slot_tp_del, NULL, ""),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005315 {NULL}
5316};
5317
Guido van Rossumc334df52002-04-04 23:44:47 +00005318/* Given a type pointer and an offset gotten from a slotdef entry, return a
Guido van Rossumd8faa362007-04-27 19:54:29 +00005319 pointer to the actual slot. This is not quite the same as simply adding
Guido van Rossumc334df52002-04-04 23:44:47 +00005320 the offset to the type pointer, since it takes care to indirect through the
5321 proper indirection pointer (as_buffer, etc.); it returns NULL if the
5322 indirection pointer is NULL. */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005323static void **
Martin v. Löwis18e16552006-02-15 17:27:45 +00005324slotptr(PyTypeObject *type, int ioffset)
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005325{
5326 char *ptr;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005327 long offset = ioffset;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005328
Guido van Rossume5c691a2003-03-07 15:13:17 +00005329 /* Note: this depends on the order of the members of PyHeapTypeObject! */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005330 assert(offset >= 0);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00005331 assert((size_t)offset < offsetof(PyHeapTypeObject, as_buffer));
5332 if ((size_t)offset >= offsetof(PyHeapTypeObject, as_sequence)) {
5333 ptr = (char *)type->tp_as_sequence;
Guido van Rossume5c691a2003-03-07 15:13:17 +00005334 offset -= offsetof(PyHeapTypeObject, as_sequence);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005335 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00005336 else if ((size_t)offset >= offsetof(PyHeapTypeObject, as_mapping)) {
5337 ptr = (char *)type->tp_as_mapping;
Guido van Rossume5c691a2003-03-07 15:13:17 +00005338 offset -= offsetof(PyHeapTypeObject, as_mapping);
Guido van Rossum09638c12002-06-13 19:17:46 +00005339 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00005340 else if ((size_t)offset >= offsetof(PyHeapTypeObject, as_number)) {
5341 ptr = (char *)type->tp_as_number;
Guido van Rossume5c691a2003-03-07 15:13:17 +00005342 offset -= offsetof(PyHeapTypeObject, as_number);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005343 }
5344 else {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00005345 ptr = (char *)type;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005346 }
5347 if (ptr != NULL)
5348 ptr += offset;
5349 return (void **)ptr;
5350}
Guido van Rossumf040ede2001-08-07 16:40:56 +00005351
Guido van Rossumc334df52002-04-04 23:44:47 +00005352/* Length of array of slotdef pointers used to store slots with the
5353 same __name__. There should be at most MAX_EQUIV-1 slotdef entries with
5354 the same __name__, for any __name__. Since that's a static property, it is
5355 appropriate to declare fixed-size arrays for this. */
5356#define MAX_EQUIV 10
5357
5358/* Return a slot pointer for a given name, but ONLY if the attribute has
5359 exactly one slot function. The name must be an interned string. */
5360static void **
5361resolve_slotdups(PyTypeObject *type, PyObject *name)
5362{
5363 /* XXX Maybe this could be optimized more -- but is it worth it? */
5364
5365 /* pname and ptrs act as a little cache */
5366 static PyObject *pname;
5367 static slotdef *ptrs[MAX_EQUIV];
5368 slotdef *p, **pp;
5369 void **res, **ptr;
5370
5371 if (pname != name) {
5372 /* Collect all slotdefs that match name into ptrs. */
5373 pname = name;
5374 pp = ptrs;
5375 for (p = slotdefs; p->name_strobj; p++) {
5376 if (p->name_strobj == name)
5377 *pp++ = p;
5378 }
5379 *pp = NULL;
5380 }
5381
5382 /* Look in all matching slots of the type; if exactly one of these has
Guido van Rossumd8faa362007-04-27 19:54:29 +00005383 a filled-in slot, return its value. Otherwise return NULL. */
Guido van Rossumc334df52002-04-04 23:44:47 +00005384 res = NULL;
5385 for (pp = ptrs; *pp; pp++) {
5386 ptr = slotptr(type, (*pp)->offset);
5387 if (ptr == NULL || *ptr == NULL)
5388 continue;
5389 if (res != NULL)
5390 return NULL;
5391 res = ptr;
5392 }
5393 return res;
5394}
5395
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005396/* Common code for update_slots_callback() and fixup_slot_dispatchers(). This
Guido van Rossumc334df52002-04-04 23:44:47 +00005397 does some incredibly complex thinking and then sticks something into the
5398 slot. (It sees if the adjacent slotdefs for the same slot have conflicting
5399 interests, and then stores a generic wrapper or a specific function into
5400 the slot.) Return a pointer to the next slotdef with a different offset,
5401 because that's convenient for fixup_slot_dispatchers(). */
5402static slotdef *
5403update_one_slot(PyTypeObject *type, slotdef *p)
5404{
5405 PyObject *descr;
5406 PyWrapperDescrObject *d;
5407 void *generic = NULL, *specific = NULL;
5408 int use_generic = 0;
5409 int offset = p->offset;
5410 void **ptr = slotptr(type, offset);
5411
5412 if (ptr == NULL) {
5413 do {
5414 ++p;
5415 } while (p->offset == offset);
5416 return p;
5417 }
5418 do {
5419 descr = _PyType_Lookup(type, p->name_strobj);
5420 if (descr == NULL)
5421 continue;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00005422 if (Py_Type(descr) == &PyWrapperDescr_Type) {
Guido van Rossumc334df52002-04-04 23:44:47 +00005423 void **tptr = resolve_slotdups(type, p->name_strobj);
5424 if (tptr == NULL || tptr == ptr)
5425 generic = p->function;
5426 d = (PyWrapperDescrObject *)descr;
5427 if (d->d_base->wrapper == p->wrapper &&
5428 PyType_IsSubtype(type, d->d_type))
5429 {
5430 if (specific == NULL ||
5431 specific == d->d_wrapped)
5432 specific = d->d_wrapped;
5433 else
5434 use_generic = 1;
5435 }
5436 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00005437 else if (Py_Type(descr) == &PyCFunction_Type &&
Guido van Rossum721f62e2002-08-09 02:14:34 +00005438 PyCFunction_GET_FUNCTION(descr) ==
5439 (PyCFunction)tp_new_wrapper &&
5440 strcmp(p->name, "__new__") == 0)
5441 {
5442 /* The __new__ wrapper is not a wrapper descriptor,
5443 so must be special-cased differently.
5444 If we don't do this, creating an instance will
5445 always use slot_tp_new which will look up
5446 __new__ in the MRO which will call tp_new_wrapper
5447 which will look through the base classes looking
5448 for a static base and call its tp_new (usually
5449 PyType_GenericNew), after performing various
5450 sanity checks and constructing a new argument
5451 list. Cut all that nonsense short -- this speeds
5452 up instance creation tremendously. */
Martin v. Löwisa94568a2003-05-10 07:36:56 +00005453 specific = (void *)type->tp_new;
Guido van Rossum721f62e2002-08-09 02:14:34 +00005454 /* XXX I'm not 100% sure that there isn't a hole
5455 in this reasoning that requires additional
5456 sanity checks. I'll buy the first person to
5457 point out a bug in this reasoning a beer. */
5458 }
Guido van Rossumc334df52002-04-04 23:44:47 +00005459 else {
5460 use_generic = 1;
5461 generic = p->function;
5462 }
5463 } while ((++p)->offset == offset);
5464 if (specific && !use_generic)
5465 *ptr = specific;
5466 else
5467 *ptr = generic;
5468 return p;
5469}
5470
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005471/* In the type, update the slots whose slotdefs are gathered in the pp array.
5472 This is a callback for update_subclasses(). */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005473static int
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005474update_slots_callback(PyTypeObject *type, void *data)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005475{
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005476 slotdef **pp = (slotdef **)data;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005477
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005478 for (; *pp; pp++)
Guido van Rossumc334df52002-04-04 23:44:47 +00005479 update_one_slot(type, *pp);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005480 return 0;
5481}
5482
Guido van Rossumc334df52002-04-04 23:44:47 +00005483/* Comparison function for qsort() to compare slotdefs by their offset, and
5484 for equal offset by their address (to force a stable sort). */
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005485static int
5486slotdef_cmp(const void *aa, const void *bb)
5487{
5488 const slotdef *a = (const slotdef *)aa, *b = (const slotdef *)bb;
5489 int c = a->offset - b->offset;
5490 if (c != 0)
5491 return c;
5492 else
Martin v. Löwis18e16552006-02-15 17:27:45 +00005493 /* Cannot use a-b, as this gives off_t,
5494 which may lose precision when converted to int. */
5495 return (a > b) ? 1 : (a < b) ? -1 : 0;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005496}
5497
Guido van Rossumc334df52002-04-04 23:44:47 +00005498/* Initialize the slotdefs table by adding interned string objects for the
5499 names and sorting the entries. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005500static void
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005501init_slotdefs(void)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005502{
5503 slotdef *p;
5504 static int initialized = 0;
5505
5506 if (initialized)
5507 return;
5508 for (p = slotdefs; p->name; p++) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00005509 p->name_strobj = PyUnicode_InternFromString(p->name);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005510 if (!p->name_strobj)
Guido van Rossumc334df52002-04-04 23:44:47 +00005511 Py_FatalError("Out of memory interning slotdef names");
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005512 }
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005513 qsort((void *)slotdefs, (size_t)(p-slotdefs), sizeof(slotdef),
5514 slotdef_cmp);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005515 initialized = 1;
5516}
5517
Guido van Rossumc334df52002-04-04 23:44:47 +00005518/* Update the slots after assignment to a class (type) attribute. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005519static int
5520update_slot(PyTypeObject *type, PyObject *name)
5521{
Guido van Rossumc334df52002-04-04 23:44:47 +00005522 slotdef *ptrs[MAX_EQUIV];
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005523 slotdef *p;
5524 slotdef **pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005525 int offset;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005526
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005527 init_slotdefs();
5528 pp = ptrs;
5529 for (p = slotdefs; p->name; p++) {
5530 /* XXX assume name is interned! */
5531 if (p->name_strobj == name)
5532 *pp++ = p;
5533 }
5534 *pp = NULL;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005535 for (pp = ptrs; *pp; pp++) {
5536 p = *pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005537 offset = p->offset;
5538 while (p > slotdefs && (p-1)->offset == offset)
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005539 --p;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005540 *pp = p;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005541 }
Guido van Rossumc334df52002-04-04 23:44:47 +00005542 if (ptrs[0] == NULL)
5543 return 0; /* Not an attribute that affects any slots */
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005544 return update_subclasses(type, name,
5545 update_slots_callback, (void *)ptrs);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005546}
5547
Guido van Rossumc334df52002-04-04 23:44:47 +00005548/* Store the proper functions in the slot dispatches at class (type)
5549 definition time, based upon which operations the class overrides in its
5550 dict. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00005551static void
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005552fixup_slot_dispatchers(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005553{
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005554 slotdef *p;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005555
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005556 init_slotdefs();
Guido van Rossumc334df52002-04-04 23:44:47 +00005557 for (p = slotdefs; p->name; )
5558 p = update_one_slot(type, p);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005559}
Guido van Rossum705f0f52001-08-24 16:47:00 +00005560
Michael W. Hudson98bbc492002-11-26 14:47:27 +00005561static void
5562update_all_slots(PyTypeObject* type)
5563{
5564 slotdef *p;
5565
5566 init_slotdefs();
5567 for (p = slotdefs; p->name; p++) {
5568 /* update_slot returns int but can't actually fail */
5569 update_slot(type, p->name_strobj);
5570 }
5571}
5572
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005573/* recurse_down_subclasses() and update_subclasses() are mutually
5574 recursive functions to call a callback for all subclasses,
5575 but refraining from recursing into subclasses that define 'name'. */
5576
5577static int
5578update_subclasses(PyTypeObject *type, PyObject *name,
5579 update_callback callback, void *data)
5580{
5581 if (callback(type, data) < 0)
5582 return -1;
5583 return recurse_down_subclasses(type, name, callback, data);
5584}
5585
5586static int
5587recurse_down_subclasses(PyTypeObject *type, PyObject *name,
5588 update_callback callback, void *data)
5589{
5590 PyTypeObject *subclass;
5591 PyObject *ref, *subclasses, *dict;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005592 Py_ssize_t i, n;
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005593
5594 subclasses = type->tp_subclasses;
5595 if (subclasses == NULL)
5596 return 0;
5597 assert(PyList_Check(subclasses));
5598 n = PyList_GET_SIZE(subclasses);
5599 for (i = 0; i < n; i++) {
5600 ref = PyList_GET_ITEM(subclasses, i);
5601 assert(PyWeakref_CheckRef(ref));
5602 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
5603 assert(subclass != NULL);
5604 if ((PyObject *)subclass == Py_None)
5605 continue;
5606 assert(PyType_Check(subclass));
5607 /* Avoid recursing down into unaffected classes */
5608 dict = subclass->tp_dict;
5609 if (dict != NULL && PyDict_Check(dict) &&
5610 PyDict_GetItem(dict, name) != NULL)
5611 continue;
5612 if (update_subclasses(subclass, name, callback, data) < 0)
5613 return -1;
5614 }
5615 return 0;
5616}
5617
Guido van Rossum6d204072001-10-21 00:44:31 +00005618/* This function is called by PyType_Ready() to populate the type's
5619 dictionary with method descriptors for function slots. For each
Guido van Rossum09638c12002-06-13 19:17:46 +00005620 function slot (like tp_repr) that's defined in the type, one or more
5621 corresponding descriptors are added in the type's tp_dict dictionary
Guido van Rossumd8faa362007-04-27 19:54:29 +00005622 under the appropriate name (like __repr__). Some function slots
Guido van Rossum09638c12002-06-13 19:17:46 +00005623 cause more than one descriptor to be added (for example, the nb_add
5624 slot adds both __add__ and __radd__ descriptors) and some function
5625 slots compete for the same descriptor (for example both sq_item and
5626 mp_subscript generate a __getitem__ descriptor).
5627
Guido van Rossumd8faa362007-04-27 19:54:29 +00005628 In the latter case, the first slotdef entry encoutered wins. Since
Tim Petersbf9b2442003-03-23 05:35:36 +00005629 slotdef entries are sorted by the offset of the slot in the
Guido van Rossume5c691a2003-03-07 15:13:17 +00005630 PyHeapTypeObject, this gives us some control over disambiguating
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005631 between competing slots: the members of PyHeapTypeObject are listed
5632 from most general to least general, so the most general slot is
5633 preferred. In particular, because as_mapping comes before as_sequence,
5634 for a type that defines both mp_subscript and sq_item, mp_subscript
5635 wins.
Guido van Rossum09638c12002-06-13 19:17:46 +00005636
5637 This only adds new descriptors and doesn't overwrite entries in
5638 tp_dict that were previously defined. The descriptors contain a
5639 reference to the C function they must call, so that it's safe if they
5640 are copied into a subtype's __dict__ and the subtype has a different
5641 C function in its slot -- calling the method defined by the
5642 descriptor will call the C function that was used to create it,
5643 rather than the C function present in the slot when it is called.
5644 (This is important because a subtype may have a C function in the
5645 slot that calls the method from the dictionary, and we want to avoid
5646 infinite recursion here.) */
Guido van Rossum6d204072001-10-21 00:44:31 +00005647
5648static int
5649add_operators(PyTypeObject *type)
5650{
5651 PyObject *dict = type->tp_dict;
5652 slotdef *p;
5653 PyObject *descr;
5654 void **ptr;
5655
5656 init_slotdefs();
5657 for (p = slotdefs; p->name; p++) {
5658 if (p->wrapper == NULL)
5659 continue;
5660 ptr = slotptr(type, p->offset);
5661 if (!ptr || !*ptr)
5662 continue;
5663 if (PyDict_GetItem(dict, p->name_strobj))
5664 continue;
5665 descr = PyDescr_NewWrapper(type, p, *ptr);
5666 if (descr == NULL)
5667 return -1;
5668 if (PyDict_SetItem(dict, p->name_strobj, descr) < 0)
5669 return -1;
5670 Py_DECREF(descr);
5671 }
5672 if (type->tp_new != NULL) {
5673 if (add_tp_new_wrapper(type) < 0)
5674 return -1;
5675 }
5676 return 0;
5677}
5678
Guido van Rossum705f0f52001-08-24 16:47:00 +00005679
5680/* Cooperative 'super' */
5681
5682typedef struct {
5683 PyObject_HEAD
Guido van Rossume705ef12001-08-29 15:47:06 +00005684 PyTypeObject *type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005685 PyObject *obj;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005686 PyTypeObject *obj_type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005687} superobject;
5688
Guido van Rossum6f799372001-09-20 20:46:19 +00005689static PyMemberDef super_members[] = {
5690 {"__thisclass__", T_OBJECT, offsetof(superobject, type), READONLY,
5691 "the class invoking super()"},
5692 {"__self__", T_OBJECT, offsetof(superobject, obj), READONLY,
5693 "the instance invoking super(); may be None"},
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005694 {"__self_class__", T_OBJECT, offsetof(superobject, obj_type), READONLY,
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +00005695 "the type of the instance invoking super(); may be None"},
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005696 {0}
5697};
5698
Guido van Rossum705f0f52001-08-24 16:47:00 +00005699static void
5700super_dealloc(PyObject *self)
5701{
5702 superobject *su = (superobject *)self;
5703
Guido van Rossum048eb752001-10-02 21:24:57 +00005704 _PyObject_GC_UNTRACK(self);
Guido van Rossum705f0f52001-08-24 16:47:00 +00005705 Py_XDECREF(su->obj);
5706 Py_XDECREF(su->type);
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005707 Py_XDECREF(su->obj_type);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00005708 Py_Type(self)->tp_free(self);
Guido van Rossum705f0f52001-08-24 16:47:00 +00005709}
5710
5711static PyObject *
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005712super_repr(PyObject *self)
5713{
5714 superobject *su = (superobject *)self;
5715
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005716 if (su->obj_type)
Walter Dörwald1ab83302007-05-18 17:15:44 +00005717 return PyUnicode_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00005718 "<super: <class '%s'>, <%s object>>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005719 su->type ? su->type->tp_name : "NULL",
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005720 su->obj_type->tp_name);
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005721 else
Walter Dörwald1ab83302007-05-18 17:15:44 +00005722 return PyUnicode_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00005723 "<super: <class '%s'>, NULL>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005724 su->type ? su->type->tp_name : "NULL");
5725}
5726
5727static PyObject *
Guido van Rossum705f0f52001-08-24 16:47:00 +00005728super_getattro(PyObject *self, PyObject *name)
5729{
5730 superobject *su = (superobject *)self;
Guido van Rossum76ba09f2003-04-16 19:40:58 +00005731 int skip = su->obj_type == NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005732
Guido van Rossum76ba09f2003-04-16 19:40:58 +00005733 if (!skip) {
5734 /* We want __class__ to return the class of the super object
5735 (i.e. super, or a subclass), not the class of su->obj. */
Martin v. Löwis5b222132007-06-10 09:51:05 +00005736 skip = (PyUnicode_Check(name) &&
5737 PyUnicode_GET_SIZE(name) == 9 &&
5738 PyUnicode_CompareWithASCIIString(name, "__class__") == 0);
Guido van Rossum76ba09f2003-04-16 19:40:58 +00005739 }
5740
5741 if (!skip) {
Tim Petersa91e9642001-11-14 23:32:33 +00005742 PyObject *mro, *res, *tmp, *dict;
Guido van Rossum155db9a2002-04-02 17:53:47 +00005743 PyTypeObject *starttype;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005744 descrgetfunc f;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005745 Py_ssize_t i, n;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005746
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005747 starttype = su->obj_type;
Guido van Rossum155db9a2002-04-02 17:53:47 +00005748 mro = starttype->tp_mro;
5749
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005750 if (mro == NULL)
5751 n = 0;
5752 else {
5753 assert(PyTuple_Check(mro));
5754 n = PyTuple_GET_SIZE(mro);
5755 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00005756 for (i = 0; i < n; i++) {
Guido van Rossume705ef12001-08-29 15:47:06 +00005757 if ((PyObject *)(su->type) == PyTuple_GET_ITEM(mro, i))
Guido van Rossum705f0f52001-08-24 16:47:00 +00005758 break;
5759 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00005760 i++;
5761 res = NULL;
5762 for (; i < n; i++) {
5763 tmp = PyTuple_GET_ITEM(mro, i);
Tim Petersa91e9642001-11-14 23:32:33 +00005764 if (PyType_Check(tmp))
5765 dict = ((PyTypeObject *)tmp)->tp_dict;
Tim Petersa91e9642001-11-14 23:32:33 +00005766 else
5767 continue;
5768 res = PyDict_GetItem(dict, name);
Guido van Rossum6cc5bb62003-04-16 20:01:36 +00005769 if (res != NULL) {
Guido van Rossum705f0f52001-08-24 16:47:00 +00005770 Py_INCREF(res);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00005771 f = Py_Type(res)->tp_descr_get;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005772 if (f != NULL) {
Phillip J. Eby91a968a2004-03-25 02:19:34 +00005773 tmp = f(res,
5774 /* Only pass 'obj' param if
5775 this is instance-mode super
5776 (See SF ID #743627)
5777 */
Hye-Shik Changff365c92004-03-25 16:37:03 +00005778 (su->obj == (PyObject *)
5779 su->obj_type
Phillip J. Eby91a968a2004-03-25 02:19:34 +00005780 ? (PyObject *)NULL
5781 : su->obj),
Guido van Rossumd4641072002-04-03 02:13:37 +00005782 (PyObject *)starttype);
Guido van Rossum705f0f52001-08-24 16:47:00 +00005783 Py_DECREF(res);
5784 res = tmp;
5785 }
5786 return res;
5787 }
5788 }
5789 }
5790 return PyObject_GenericGetAttr(self, name);
5791}
5792
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005793static PyTypeObject *
Guido van Rossum5b443c62001-12-03 15:38:28 +00005794supercheck(PyTypeObject *type, PyObject *obj)
5795{
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005796 /* Check that a super() call makes sense. Return a type object.
5797
5798 obj can be a new-style class, or an instance of one:
5799
Guido van Rossumd8faa362007-04-27 19:54:29 +00005800 - If it is a class, it must be a subclass of 'type'. This case is
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005801 used for class methods; the return value is obj.
5802
5803 - If it is an instance, it must be an instance of 'type'. This is
5804 the normal case; the return value is obj.__class__.
5805
5806 But... when obj is an instance, we want to allow for the case where
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00005807 Py_Type(obj) is not a subclass of type, but obj.__class__ is!
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005808 This will allow using super() with a proxy for obj.
5809 */
5810
Guido van Rossum8e80a722003-02-18 19:22:22 +00005811 /* Check for first bullet above (special case) */
5812 if (PyType_Check(obj) && PyType_IsSubtype((PyTypeObject *)obj, type)) {
5813 Py_INCREF(obj);
5814 return (PyTypeObject *)obj;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005815 }
Guido van Rossum8e80a722003-02-18 19:22:22 +00005816
5817 /* Normal case */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00005818 if (PyType_IsSubtype(Py_Type(obj), type)) {
5819 Py_INCREF(Py_Type(obj));
5820 return Py_Type(obj);
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005821 }
5822 else {
5823 /* Try the slow way */
5824 static PyObject *class_str = NULL;
5825 PyObject *class_attr;
5826
5827 if (class_str == NULL) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00005828 class_str = PyUnicode_FromString("__class__");
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005829 if (class_str == NULL)
5830 return NULL;
5831 }
5832
5833 class_attr = PyObject_GetAttr(obj, class_str);
5834
5835 if (class_attr != NULL &&
5836 PyType_Check(class_attr) &&
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00005837 (PyTypeObject *)class_attr != Py_Type(obj))
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005838 {
5839 int ok = PyType_IsSubtype(
5840 (PyTypeObject *)class_attr, type);
5841 if (ok)
5842 return (PyTypeObject *)class_attr;
5843 }
5844
5845 if (class_attr == NULL)
5846 PyErr_Clear();
5847 else
5848 Py_DECREF(class_attr);
5849 }
5850
Guido van Rossumd8faa362007-04-27 19:54:29 +00005851 PyErr_SetString(PyExc_TypeError,
Guido van Rossum5b443c62001-12-03 15:38:28 +00005852 "super(type, obj): "
5853 "obj must be an instance or subtype of type");
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005854 return NULL;
Guido van Rossum5b443c62001-12-03 15:38:28 +00005855}
5856
Guido van Rossum705f0f52001-08-24 16:47:00 +00005857static PyObject *
5858super_descr_get(PyObject *self, PyObject *obj, PyObject *type)
5859{
5860 superobject *su = (superobject *)self;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00005861 superobject *newobj;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005862
5863 if (obj == NULL || obj == Py_None || su->obj != NULL) {
5864 /* Not binding to an object, or already bound */
5865 Py_INCREF(self);
5866 return self;
5867 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00005868 if (Py_Type(su) != &PySuper_Type)
Armin Rigo7726dc02005-05-15 15:32:08 +00005869 /* If su is an instance of a (strict) subclass of super,
Guido van Rossum5b443c62001-12-03 15:38:28 +00005870 call its type */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00005871 return PyObject_CallFunctionObjArgs((PyObject *)Py_Type(su),
Guido van Rossumd8faa362007-04-27 19:54:29 +00005872 su->type, obj, NULL);
Guido van Rossum5b443c62001-12-03 15:38:28 +00005873 else {
5874 /* Inline the common case */
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005875 PyTypeObject *obj_type = supercheck(su->type, obj);
5876 if (obj_type == NULL)
Guido van Rossum5b443c62001-12-03 15:38:28 +00005877 return NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00005878 newobj = (superobject *)PySuper_Type.tp_new(&PySuper_Type,
Guido van Rossum5b443c62001-12-03 15:38:28 +00005879 NULL, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00005880 if (newobj == NULL)
Guido van Rossum5b443c62001-12-03 15:38:28 +00005881 return NULL;
5882 Py_INCREF(su->type);
5883 Py_INCREF(obj);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00005884 newobj->type = su->type;
5885 newobj->obj = obj;
5886 newobj->obj_type = obj_type;
5887 return (PyObject *)newobj;
Guido van Rossum5b443c62001-12-03 15:38:28 +00005888 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00005889}
5890
5891static int
5892super_init(PyObject *self, PyObject *args, PyObject *kwds)
5893{
5894 superobject *su = (superobject *)self;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00005895 PyTypeObject *type = NULL;
Guido van Rossume705ef12001-08-29 15:47:06 +00005896 PyObject *obj = NULL;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005897 PyTypeObject *obj_type = NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005898
Thomas Wouters89f507f2006-12-13 04:49:30 +00005899 if (!_PyArg_NoKeywords("super", kwds))
5900 return -1;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00005901 if (!PyArg_ParseTuple(args, "|O!O:super", &PyType_Type, &type, &obj))
Guido van Rossum705f0f52001-08-24 16:47:00 +00005902 return -1;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00005903
5904 if (type == NULL) {
5905 /* Call super(), without args -- fill in from __class__
5906 and first local variable on the stack. */
5907 PyFrameObject *f = PyThreadState_GET()->frame;
5908 PyCodeObject *co = f->f_code;
5909 int i, n;
5910 if (co == NULL) {
5911 PyErr_SetString(PyExc_SystemError,
5912 "super(): no code object");
5913 return -1;
5914 }
5915 if (co->co_argcount == 0) {
5916 PyErr_SetString(PyExc_SystemError,
5917 "super(): no arguments");
5918 return -1;
5919 }
5920 obj = f->f_localsplus[0];
5921 if (obj == NULL) {
5922 PyErr_SetString(PyExc_SystemError,
5923 "super(): arg[0] deleted");
5924 return -1;
5925 }
5926 if (co->co_freevars == NULL)
5927 n = 0;
5928 else {
5929 assert(PyTuple_Check(co->co_freevars));
5930 n = PyTuple_GET_SIZE(co->co_freevars);
5931 }
5932 for (i = 0; i < n; i++) {
5933 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
5934 assert(PyUnicode_Check(name));
5935 if (!PyUnicode_CompareWithASCIIString(name,
5936 "__class__")) {
5937 PyObject *cell =
5938 f->f_localsplus[co->co_nlocals + i];
5939 if (cell == NULL || !PyCell_Check(cell)) {
5940 PyErr_SetString(PyExc_SystemError,
5941 "super(): bad __class__ cell");
5942 return -1;
5943 }
5944 type = (PyTypeObject *) PyCell_GET(cell);
5945 if (type == NULL) {
5946 PyErr_SetString(PyExc_SystemError,
5947 "super(): empty __class__ cell");
5948 return -1;
5949 }
5950 if (!PyType_Check(type)) {
5951 PyErr_Format(PyExc_SystemError,
5952 "super(): __class__ is not a type (%s)",
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00005953 Py_Type(type)->tp_name);
Guido van Rossumcd16bf62007-06-13 18:07:49 +00005954 return -1;
5955 }
5956 break;
5957 }
5958 }
5959 if (type == NULL) {
5960 PyErr_SetString(PyExc_SystemError,
5961 "super(): __class__ cell not found");
5962 return -1;
5963 }
5964 }
5965
Guido van Rossum705f0f52001-08-24 16:47:00 +00005966 if (obj == Py_None)
5967 obj = NULL;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005968 if (obj != NULL) {
5969 obj_type = supercheck(type, obj);
5970 if (obj_type == NULL)
5971 return -1;
5972 Py_INCREF(obj);
5973 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00005974 Py_INCREF(type);
Guido van Rossum705f0f52001-08-24 16:47:00 +00005975 su->type = type;
5976 su->obj = obj;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005977 su->obj_type = obj_type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005978 return 0;
5979}
5980
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005981PyDoc_STRVAR(super_doc,
Guido van Rossumcd16bf62007-06-13 18:07:49 +00005982"super() -> same as super(__class__, <first argument>)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00005983"super(type) -> unbound super object\n"
5984"super(type, obj) -> bound super object; requires isinstance(obj, type)\n"
Guido van Rossume705ef12001-08-29 15:47:06 +00005985"super(type, type2) -> bound super object; requires issubclass(type2, type)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00005986"Typical use to call a cooperative superclass method:\n"
5987"class C(B):\n"
5988" def meth(self, arg):\n"
Guido van Rossumcd16bf62007-06-13 18:07:49 +00005989" super().meth(arg)\n"
5990"This works for class methods too:\n"
5991"class C(B):\n"
5992" @classmethod\n"
5993" def cmeth(cls, arg):\n"
5994" super().cmeth(arg)\n");
Guido van Rossum705f0f52001-08-24 16:47:00 +00005995
Guido van Rossum048eb752001-10-02 21:24:57 +00005996static int
5997super_traverse(PyObject *self, visitproc visit, void *arg)
5998{
5999 superobject *su = (superobject *)self;
Guido van Rossum048eb752001-10-02 21:24:57 +00006000
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00006001 Py_VISIT(su->obj);
6002 Py_VISIT(su->type);
6003 Py_VISIT(su->obj_type);
Guido van Rossum048eb752001-10-02 21:24:57 +00006004
6005 return 0;
6006}
6007
Guido van Rossum705f0f52001-08-24 16:47:00 +00006008PyTypeObject PySuper_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00006009 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Guido van Rossum705f0f52001-08-24 16:47:00 +00006010 "super", /* tp_name */
6011 sizeof(superobject), /* tp_basicsize */
6012 0, /* tp_itemsize */
6013 /* methods */
Guido van Rossumd8faa362007-04-27 19:54:29 +00006014 super_dealloc, /* tp_dealloc */
Guido van Rossum705f0f52001-08-24 16:47:00 +00006015 0, /* tp_print */
6016 0, /* tp_getattr */
6017 0, /* tp_setattr */
6018 0, /* tp_compare */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00006019 super_repr, /* tp_repr */
Guido van Rossum705f0f52001-08-24 16:47:00 +00006020 0, /* tp_as_number */
6021 0, /* tp_as_sequence */
Guido van Rossumd8faa362007-04-27 19:54:29 +00006022 0, /* tp_as_mapping */
Guido van Rossum705f0f52001-08-24 16:47:00 +00006023 0, /* tp_hash */
6024 0, /* tp_call */
6025 0, /* tp_str */
6026 super_getattro, /* tp_getattro */
6027 0, /* tp_setattro */
6028 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00006029 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
6030 Py_TPFLAGS_BASETYPE, /* tp_flags */
Guido van Rossumd8faa362007-04-27 19:54:29 +00006031 super_doc, /* tp_doc */
6032 super_traverse, /* tp_traverse */
6033 0, /* tp_clear */
Guido van Rossum705f0f52001-08-24 16:47:00 +00006034 0, /* tp_richcompare */
6035 0, /* tp_weaklistoffset */
6036 0, /* tp_iter */
6037 0, /* tp_iternext */
6038 0, /* tp_methods */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00006039 super_members, /* tp_members */
Guido van Rossum705f0f52001-08-24 16:47:00 +00006040 0, /* tp_getset */
6041 0, /* tp_base */
6042 0, /* tp_dict */
6043 super_descr_get, /* tp_descr_get */
6044 0, /* tp_descr_set */
6045 0, /* tp_dictoffset */
6046 super_init, /* tp_init */
6047 PyType_GenericAlloc, /* tp_alloc */
6048 PyType_GenericNew, /* tp_new */
Guido van Rossumd8faa362007-04-27 19:54:29 +00006049 PyObject_GC_Del, /* tp_free */
Guido van Rossum705f0f52001-08-24 16:47:00 +00006050};