blob: 222207ca2b9dc7efe6792b13d51b86efe2be34dd [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)
Tim Peters24008312002-03-17 18:56:20 +0000346 return PyString_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__");
1921 if (doc != NULL && PyString_Check(doc)) {
1922 const size_t n = (size_t)PyString_GET_SIZE(doc);
Guido van Rossumd8faa362007-04-27 19:54:29 +00001923 char *tp_doc = (char *)PyObject_MALLOC(n+1);
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00001924 if (tp_doc == NULL) {
Tim Peters2f93e282001-10-04 05:27:00 +00001925 Py_DECREF(type);
1926 return NULL;
1927 }
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00001928 memcpy(tp_doc, PyString_AS_STRING(doc), n+1);
Guido van Rossumd8faa362007-04-27 19:54:29 +00001929 type->tp_doc = tp_doc;
Tim Peters2f93e282001-10-04 05:27:00 +00001930 }
1931 }
1932
Tim Peters6d6c1a32001-08-02 04:15:00 +00001933 /* Special-case __new__: if it's a plain function,
1934 make it a static function */
1935 tmp = PyDict_GetItemString(dict, "__new__");
1936 if (tmp != NULL && PyFunction_Check(tmp)) {
1937 tmp = PyStaticMethod_New(tmp);
1938 if (tmp == NULL) {
1939 Py_DECREF(type);
1940 return NULL;
1941 }
1942 PyDict_SetItemString(dict, "__new__", tmp);
1943 Py_DECREF(tmp);
1944 }
1945
1946 /* Add descriptors for custom slots from __slots__, or for __dict__ */
Guido van Rossume5c691a2003-03-07 15:13:17 +00001947 mp = PyHeapType_GET_MEMBERS(et);
Neil Schemenauerc806c882001-08-29 23:54:54 +00001948 slotoffset = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001949 if (slots != NULL) {
1950 for (i = 0; i < nslots; i++, mp++) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00001951 mp->name = PyUnicode_AsString(
Tim Peters6d6c1a32001-08-02 04:15:00 +00001952 PyTuple_GET_ITEM(slots, i));
Guido van Rossum64b206c2001-12-04 17:13:22 +00001953 mp->type = T_OBJECT_EX;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001954 mp->offset = slotoffset;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001955
1956 /* __dict__ and __weakref__ are already filtered out */
1957 assert(strcmp(mp->name, "__dict__") != 0);
1958 assert(strcmp(mp->name, "__weakref__") != 0);
1959
Tim Peters6d6c1a32001-08-02 04:15:00 +00001960 slotoffset += sizeof(PyObject *);
1961 }
1962 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001963 if (add_dict) {
1964 if (base->tp_itemsize)
1965 type->tp_dictoffset = -(long)sizeof(PyObject *);
1966 else
1967 type->tp_dictoffset = slotoffset;
1968 slotoffset += sizeof(PyObject *);
1969 }
1970 if (add_weak) {
1971 assert(!base->tp_itemsize);
1972 type->tp_weaklistoffset = slotoffset;
1973 slotoffset += sizeof(PyObject *);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001974 }
1975 type->tp_basicsize = slotoffset;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001976 type->tp_itemsize = base->tp_itemsize;
Guido van Rossume5c691a2003-03-07 15:13:17 +00001977 type->tp_members = PyHeapType_GET_MEMBERS(et);
Guido van Rossum373c7412003-01-07 13:41:37 +00001978
1979 if (type->tp_weaklistoffset && type->tp_dictoffset)
1980 type->tp_getset = subtype_getsets_full;
1981 else if (type->tp_weaklistoffset && !type->tp_dictoffset)
1982 type->tp_getset = subtype_getsets_weakref_only;
1983 else if (!type->tp_weaklistoffset && type->tp_dictoffset)
1984 type->tp_getset = subtype_getsets_dict_only;
1985 else
1986 type->tp_getset = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001987
1988 /* Special case some slots */
1989 if (type->tp_dictoffset != 0 || nslots > 0) {
1990 if (base->tp_getattr == NULL && base->tp_getattro == NULL)
1991 type->tp_getattro = PyObject_GenericGetAttr;
1992 if (base->tp_setattr == NULL && base->tp_setattro == NULL)
1993 type->tp_setattro = PyObject_GenericSetAttr;
1994 }
1995 type->tp_dealloc = subtype_dealloc;
1996
Guido van Rossum9475a232001-10-05 20:51:39 +00001997 /* Enable GC unless there are really no instance variables possible */
1998 if (!(type->tp_basicsize == sizeof(PyObject) &&
1999 type->tp_itemsize == 0))
2000 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
2001
Tim Peters6d6c1a32001-08-02 04:15:00 +00002002 /* Always override allocation strategy to use regular heap */
2003 type->tp_alloc = PyType_GenericAlloc;
Guido van Rossum048eb752001-10-02 21:24:57 +00002004 if (type->tp_flags & Py_TPFLAGS_HAVE_GC) {
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00002005 type->tp_free = PyObject_GC_Del;
Guido van Rossum9475a232001-10-05 20:51:39 +00002006 type->tp_traverse = subtype_traverse;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00002007 type->tp_clear = subtype_clear;
Guido van Rossum048eb752001-10-02 21:24:57 +00002008 }
2009 else
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00002010 type->tp_free = PyObject_Del;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002011
2012 /* Initialize the rest */
Guido van Rossum528b7eb2001-08-07 17:24:28 +00002013 if (PyType_Ready(type) < 0) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00002014 Py_DECREF(type);
2015 return NULL;
2016 }
2017
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002018 /* Put the proper slots in place */
2019 fixup_slot_dispatchers(type);
Guido van Rossumf040ede2001-08-07 16:40:56 +00002020
Tim Peters6d6c1a32001-08-02 04:15:00 +00002021 return (PyObject *)type;
2022}
2023
2024/* Internal API to look for a name through the MRO.
2025 This returns a borrowed reference, and doesn't set an exception! */
2026PyObject *
2027_PyType_Lookup(PyTypeObject *type, PyObject *name)
2028{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002029 Py_ssize_t i, n;
Tim Petersa91e9642001-11-14 23:32:33 +00002030 PyObject *mro, *res, *base, *dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002031
Guido van Rossum687ae002001-10-15 22:03:32 +00002032 /* Look in tp_dict of types in MRO */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002033 mro = type->tp_mro;
Guido van Rossum23094982002-06-10 14:30:43 +00002034
2035 /* If mro is NULL, the type is either not yet initialized
2036 by PyType_Ready(), or already cleared by type_clear().
2037 Either way the safest thing to do is to return NULL. */
2038 if (mro == NULL)
2039 return NULL;
2040
Tim Peters6d6c1a32001-08-02 04:15:00 +00002041 assert(PyTuple_Check(mro));
2042 n = PyTuple_GET_SIZE(mro);
2043 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00002044 base = PyTuple_GET_ITEM(mro, i);
Guido van Rossum50e9fb92006-08-17 05:42:55 +00002045 assert(PyType_Check(base));
2046 dict = ((PyTypeObject *)base)->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002047 assert(dict && PyDict_Check(dict));
2048 res = PyDict_GetItem(dict, name);
2049 if (res != NULL)
2050 return res;
2051 }
2052 return NULL;
2053}
2054
2055/* This is similar to PyObject_GenericGetAttr(),
2056 but uses _PyType_Lookup() instead of just looking in type->tp_dict. */
2057static PyObject *
2058type_getattro(PyTypeObject *type, PyObject *name)
2059{
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002060 PyTypeObject *metatype = Py_Type(type);
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002061 PyObject *meta_attribute, *attribute;
2062 descrgetfunc meta_get;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002063
2064 /* Initialize this type (we'll assume the metatype is initialized) */
2065 if (type->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00002066 if (PyType_Ready(type) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002067 return NULL;
2068 }
2069
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002070 /* No readable descriptor found yet */
2071 meta_get = NULL;
Tim Peters34592512002-07-11 06:23:50 +00002072
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002073 /* Look for the attribute in the metatype */
2074 meta_attribute = _PyType_Lookup(metatype, name);
2075
2076 if (meta_attribute != NULL) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002077 meta_get = Py_Type(meta_attribute)->tp_descr_get;
Tim Peters34592512002-07-11 06:23:50 +00002078
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002079 if (meta_get != NULL && PyDescr_IsData(meta_attribute)) {
2080 /* Data descriptors implement tp_descr_set to intercept
2081 * writes. Assume the attribute is not overridden in
2082 * type's tp_dict (and bases): call the descriptor now.
2083 */
2084 return meta_get(meta_attribute, (PyObject *)type,
2085 (PyObject *)metatype);
2086 }
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00002087 Py_INCREF(meta_attribute);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002088 }
2089
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002090 /* No data descriptor found on metatype. Look in tp_dict of this
2091 * type and its bases */
2092 attribute = _PyType_Lookup(type, name);
2093 if (attribute != NULL) {
2094 /* Implement descriptor functionality, if any */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002095 descrgetfunc local_get = Py_Type(attribute)->tp_descr_get;
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00002096
2097 Py_XDECREF(meta_attribute);
2098
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002099 if (local_get != NULL) {
2100 /* NULL 2nd argument indicates the descriptor was
2101 * found on the target object itself (or a base) */
2102 return local_get(attribute, (PyObject *)NULL,
2103 (PyObject *)type);
2104 }
Tim Peters34592512002-07-11 06:23:50 +00002105
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002106 Py_INCREF(attribute);
2107 return attribute;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002108 }
2109
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002110 /* No attribute found in local __dict__ (or bases): use the
2111 * descriptor from the metatype, if any */
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00002112 if (meta_get != NULL) {
2113 PyObject *res;
2114 res = meta_get(meta_attribute, (PyObject *)type,
2115 (PyObject *)metatype);
2116 Py_DECREF(meta_attribute);
2117 return res;
2118 }
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002119
2120 /* If an ordinary attribute was found on the metatype, return it now */
2121 if (meta_attribute != NULL) {
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002122 return meta_attribute;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002123 }
2124
2125 /* Give up */
2126 PyErr_Format(PyExc_AttributeError,
Walter Dörwald75163602007-06-11 15:47:13 +00002127 "type object '%.50s' has no attribute '%U'",
2128 type->tp_name, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002129 return NULL;
2130}
2131
2132static int
2133type_setattro(PyTypeObject *type, PyObject *name, PyObject *value)
2134{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002135 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
2136 PyErr_Format(
2137 PyExc_TypeError,
2138 "can't set attributes of built-in/extension type '%s'",
2139 type->tp_name);
2140 return -1;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002141 }
Guido van Rossum8d24ee92003-03-24 23:49:49 +00002142 /* XXX Example of how I expect this to be used...
2143 if (update_subclasses(type, name, invalidate_cache, NULL) < 0)
2144 return -1;
2145 */
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002146 if (PyObject_GenericSetAttr((PyObject *)type, name, value) < 0)
2147 return -1;
2148 return update_slot(type, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002149}
2150
2151static void
2152type_dealloc(PyTypeObject *type)
2153{
Guido van Rossume5c691a2003-03-07 15:13:17 +00002154 PyHeapTypeObject *et;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002155
2156 /* Assert this is a heap-allocated type object */
2157 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002158 _PyObject_GC_UNTRACK(type);
Guido van Rossum1c450732001-10-08 15:18:27 +00002159 PyObject_ClearWeakRefs((PyObject *)type);
Guido van Rossume5c691a2003-03-07 15:13:17 +00002160 et = (PyHeapTypeObject *)type;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002161 Py_XDECREF(type->tp_base);
2162 Py_XDECREF(type->tp_dict);
2163 Py_XDECREF(type->tp_bases);
2164 Py_XDECREF(type->tp_mro);
Guido van Rossum687ae002001-10-15 22:03:32 +00002165 Py_XDECREF(type->tp_cache);
Guido van Rossum1c450732001-10-08 15:18:27 +00002166 Py_XDECREF(type->tp_subclasses);
Guido van Rossumd8faa362007-04-27 19:54:29 +00002167 /* A type's tp_doc is heap allocated, unlike the tp_doc slots
2168 * of most other objects. It's okay to cast it to char *.
2169 */
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00002170 PyObject_Free((char *)type->tp_doc);
Georg Brandlc255c7b2006-02-20 22:27:28 +00002171 Py_XDECREF(et->ht_name);
2172 Py_XDECREF(et->ht_slots);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002173 Py_Type(type)->tp_free((PyObject *)type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002174}
2175
Guido van Rossum1c450732001-10-08 15:18:27 +00002176static PyObject *
2177type_subclasses(PyTypeObject *type, PyObject *args_ignored)
2178{
2179 PyObject *list, *raw, *ref;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002180 Py_ssize_t i, n;
Guido van Rossum1c450732001-10-08 15:18:27 +00002181
2182 list = PyList_New(0);
2183 if (list == NULL)
2184 return NULL;
2185 raw = type->tp_subclasses;
2186 if (raw == NULL)
2187 return list;
2188 assert(PyList_Check(raw));
2189 n = PyList_GET_SIZE(raw);
2190 for (i = 0; i < n; i++) {
2191 ref = PyList_GET_ITEM(raw, i);
Tim Peters44383382001-10-08 16:49:26 +00002192 assert(PyWeakref_CheckRef(ref));
Guido van Rossum1c450732001-10-08 15:18:27 +00002193 ref = PyWeakref_GET_OBJECT(ref);
2194 if (ref != Py_None) {
2195 if (PyList_Append(list, ref) < 0) {
2196 Py_DECREF(list);
2197 return NULL;
2198 }
2199 }
2200 }
2201 return list;
2202}
2203
Guido van Rossum47374822007-08-02 16:48:17 +00002204static PyObject *
2205type_prepare(PyObject *self, PyObject *args, PyObject *kwds)
2206{
2207 return PyDict_New();
2208}
2209
Tim Peters6d6c1a32001-08-02 04:15:00 +00002210static PyMethodDef type_methods[] = {
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002211 {"mro", (PyCFunction)mro_external, METH_NOARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002212 PyDoc_STR("mro() -> list\nreturn a type's method resolution order")},
Guido van Rossum1c450732001-10-08 15:18:27 +00002213 {"__subclasses__", (PyCFunction)type_subclasses, METH_NOARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002214 PyDoc_STR("__subclasses__() -> list of immediate subclasses")},
Guido van Rossum47374822007-08-02 16:48:17 +00002215 {"__prepare__", (PyCFunction)type_prepare,
2216 METH_VARARGS | METH_KEYWORDS | METH_CLASS,
2217 PyDoc_STR("__prepare__() -> dict\n"
2218 "used to create the namespace for the class statement")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002219 {0}
2220};
2221
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002222PyDoc_STRVAR(type_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00002223"type(object) -> the object's type\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002224"type(name, bases, dict) -> a new type");
Tim Peters6d6c1a32001-08-02 04:15:00 +00002225
Guido van Rossum048eb752001-10-02 21:24:57 +00002226static int
2227type_traverse(PyTypeObject *type, visitproc visit, void *arg)
2228{
Guido van Rossuma3862092002-06-10 15:24:42 +00002229 /* Because of type_is_gc(), the collector only calls this
2230 for heaptypes. */
2231 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002232
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002233 Py_VISIT(type->tp_dict);
2234 Py_VISIT(type->tp_cache);
2235 Py_VISIT(type->tp_mro);
2236 Py_VISIT(type->tp_bases);
2237 Py_VISIT(type->tp_base);
Guido van Rossuma3862092002-06-10 15:24:42 +00002238
2239 /* There's no need to visit type->tp_subclasses or
Georg Brandlc255c7b2006-02-20 22:27:28 +00002240 ((PyHeapTypeObject *)type)->ht_slots, because they can't be involved
Guido van Rossuma3862092002-06-10 15:24:42 +00002241 in cycles; tp_subclasses is a list of weak references,
2242 and slots is a tuple of strings. */
Guido van Rossum048eb752001-10-02 21:24:57 +00002243
Guido van Rossum048eb752001-10-02 21:24:57 +00002244 return 0;
2245}
2246
2247static int
2248type_clear(PyTypeObject *type)
2249{
Guido van Rossuma3862092002-06-10 15:24:42 +00002250 /* Because of type_is_gc(), the collector only calls this
2251 for heaptypes. */
2252 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002253
Guido van Rossuma3862092002-06-10 15:24:42 +00002254 /* The only field we need to clear is tp_mro, which is part of a
2255 hard cycle (its first element is the class itself) that won't
2256 be broken otherwise (it's a tuple and tuples don't have a
2257 tp_clear handler). None of the other fields need to be
2258 cleared, and here's why:
Guido van Rossum048eb752001-10-02 21:24:57 +00002259
Guido van Rossuma3862092002-06-10 15:24:42 +00002260 tp_dict:
2261 It is a dict, so the collector will call its tp_clear.
2262
2263 tp_cache:
2264 Not used; if it were, it would be a dict.
2265
2266 tp_bases, tp_base:
2267 If these are involved in a cycle, there must be at least
2268 one other, mutable object in the cycle, e.g. a base
2269 class's dict; the cycle will be broken that way.
2270
2271 tp_subclasses:
2272 A list of weak references can't be part of a cycle; and
2273 lists have their own tp_clear.
2274
Guido van Rossume5c691a2003-03-07 15:13:17 +00002275 slots (in PyHeapTypeObject):
Guido van Rossuma3862092002-06-10 15:24:42 +00002276 A tuple of strings can't be part of a cycle.
2277 */
2278
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002279 Py_CLEAR(type->tp_mro);
Guido van Rossum048eb752001-10-02 21:24:57 +00002280
2281 return 0;
2282}
2283
2284static int
2285type_is_gc(PyTypeObject *type)
2286{
2287 return type->tp_flags & Py_TPFLAGS_HEAPTYPE;
2288}
2289
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002290PyTypeObject PyType_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002291 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002292 "type", /* tp_name */
Guido van Rossume5c691a2003-03-07 15:13:17 +00002293 sizeof(PyHeapTypeObject), /* tp_basicsize */
Guido van Rossum6f799372001-09-20 20:46:19 +00002294 sizeof(PyMemberDef), /* tp_itemsize */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002295 (destructor)type_dealloc, /* tp_dealloc */
2296 0, /* tp_print */
Guido van Rossumd8faa362007-04-27 19:54:29 +00002297 0, /* tp_getattr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002298 0, /* tp_setattr */
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002299 0, /* tp_compare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002300 (reprfunc)type_repr, /* tp_repr */
2301 0, /* tp_as_number */
2302 0, /* tp_as_sequence */
2303 0, /* tp_as_mapping */
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002304 0, /* tp_hash */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002305 (ternaryfunc)type_call, /* tp_call */
2306 0, /* tp_str */
2307 (getattrofunc)type_getattro, /* tp_getattro */
2308 (setattrofunc)type_setattro, /* tp_setattro */
2309 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00002310 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
Thomas Wouters27d517b2007-02-25 20:39:11 +00002311 Py_TPFLAGS_BASETYPE | Py_TPFLAGS_TYPE_SUBCLASS, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002312 type_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00002313 (traverseproc)type_traverse, /* tp_traverse */
2314 (inquiry)type_clear, /* tp_clear */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002315 0, /* tp_richcompare */
Guido van Rossum1c450732001-10-08 15:18:27 +00002316 offsetof(PyTypeObject, tp_weaklist), /* tp_weaklistoffset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002317 0, /* tp_iter */
2318 0, /* tp_iternext */
2319 type_methods, /* tp_methods */
2320 type_members, /* tp_members */
2321 type_getsets, /* tp_getset */
2322 0, /* tp_base */
2323 0, /* tp_dict */
2324 0, /* tp_descr_get */
2325 0, /* tp_descr_set */
2326 offsetof(PyTypeObject, tp_dict), /* tp_dictoffset */
Guido van Rossumd8faa362007-04-27 19:54:29 +00002327 type_init, /* tp_init */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002328 0, /* tp_alloc */
2329 type_new, /* tp_new */
Guido van Rossumd8faa362007-04-27 19:54:29 +00002330 PyObject_GC_Del, /* tp_free */
Guido van Rossum048eb752001-10-02 21:24:57 +00002331 (inquiry)type_is_gc, /* tp_is_gc */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002332};
Tim Peters6d6c1a32001-08-02 04:15:00 +00002333
2334
2335/* The base type of all types (eventually)... except itself. */
2336
Guido van Rossumd8faa362007-04-27 19:54:29 +00002337/* You may wonder why object.__new__() only complains about arguments
2338 when object.__init__() is not overridden, and vice versa.
2339
2340 Consider the use cases:
2341
2342 1. When neither is overridden, we want to hear complaints about
2343 excess (i.e., any) arguments, since their presence could
2344 indicate there's a bug.
2345
2346 2. When defining an Immutable type, we are likely to override only
2347 __new__(), since __init__() is called too late to initialize an
2348 Immutable object. Since __new__() defines the signature for the
2349 type, it would be a pain to have to override __init__() just to
2350 stop it from complaining about excess arguments.
2351
2352 3. When defining a Mutable type, we are likely to override only
2353 __init__(). So here the converse reasoning applies: we don't
2354 want to have to override __new__() just to stop it from
2355 complaining.
2356
2357 4. When __init__() is overridden, and the subclass __init__() calls
2358 object.__init__(), the latter should complain about excess
2359 arguments; ditto for __new__().
2360
2361 Use cases 2 and 3 make it unattractive to unconditionally check for
2362 excess arguments. The best solution that addresses all four use
2363 cases is as follows: __init__() complains about excess arguments
2364 unless __new__() is overridden and __init__() is not overridden
2365 (IOW, if __init__() is overridden or __new__() is not overridden);
2366 symmetrically, __new__() complains about excess arguments unless
2367 __init__() is overridden and __new__() is not overridden
2368 (IOW, if __new__() is overridden or __init__() is not overridden).
2369
2370 However, for backwards compatibility, this breaks too much code.
2371 Therefore, in 2.6, we'll *warn* about excess arguments when both
2372 methods are overridden; for all other cases we'll use the above
2373 rules.
2374
2375*/
2376
2377/* Forward */
2378static PyObject *
2379object_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
2380
2381static int
2382excess_args(PyObject *args, PyObject *kwds)
2383{
2384 return PyTuple_GET_SIZE(args) ||
2385 (kwds && PyDict_Check(kwds) && PyDict_Size(kwds));
2386}
2387
Tim Peters6d6c1a32001-08-02 04:15:00 +00002388static int
2389object_init(PyObject *self, PyObject *args, PyObject *kwds)
2390{
Guido van Rossumd8faa362007-04-27 19:54:29 +00002391 int err = 0;
2392 if (excess_args(args, kwds)) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002393 PyTypeObject *type = Py_Type(self);
Guido van Rossumd8faa362007-04-27 19:54:29 +00002394 if (type->tp_init != object_init &&
2395 type->tp_new != object_new)
2396 {
2397 err = PyErr_WarnEx(PyExc_DeprecationWarning,
2398 "object.__init__() takes no parameters",
2399 1);
2400 }
2401 else if (type->tp_init != object_init ||
2402 type->tp_new == object_new)
2403 {
2404 PyErr_SetString(PyExc_TypeError,
2405 "object.__init__() takes no parameters");
2406 err = -1;
2407 }
2408 }
2409 return err;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002410}
2411
Guido van Rossum298e4212003-02-13 16:30:16 +00002412static PyObject *
2413object_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2414{
Guido van Rossumd8faa362007-04-27 19:54:29 +00002415 int err = 0;
2416 if (excess_args(args, kwds)) {
2417 if (type->tp_new != object_new &&
2418 type->tp_init != object_init)
2419 {
2420 err = PyErr_WarnEx(PyExc_DeprecationWarning,
2421 "object.__new__() takes no parameters",
2422 1);
2423 }
2424 else if (type->tp_new != object_new ||
2425 type->tp_init == object_init)
2426 {
2427 PyErr_SetString(PyExc_TypeError,
2428 "object.__new__() takes no parameters");
2429 err = -1;
2430 }
Guido van Rossum298e4212003-02-13 16:30:16 +00002431 }
Guido van Rossumd8faa362007-04-27 19:54:29 +00002432 if (err < 0)
2433 return NULL;
Guido van Rossum298e4212003-02-13 16:30:16 +00002434 return type->tp_alloc(type, 0);
2435}
2436
Tim Peters6d6c1a32001-08-02 04:15:00 +00002437static void
2438object_dealloc(PyObject *self)
2439{
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002440 Py_Type(self)->tp_free(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002441}
2442
Guido van Rossum8e248182001-08-12 05:17:56 +00002443static PyObject *
2444object_repr(PyObject *self)
2445{
Guido van Rossum76e69632001-08-16 18:52:43 +00002446 PyTypeObject *type;
Barry Warsaw7ce36942001-08-24 18:34:26 +00002447 PyObject *mod, *name, *rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00002448
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002449 type = Py_Type(self);
Guido van Rossum76e69632001-08-16 18:52:43 +00002450 mod = type_module(type, NULL);
2451 if (mod == NULL)
2452 PyErr_Clear();
Martin v. Löwis5b222132007-06-10 09:51:05 +00002453 else if (!PyUnicode_Check(mod)) {
Guido van Rossum76e69632001-08-16 18:52:43 +00002454 Py_DECREF(mod);
2455 mod = NULL;
2456 }
2457 name = type_name(type, NULL);
2458 if (name == NULL)
2459 return NULL;
Walter Dörwald4dbd01b2007-06-11 14:03:45 +00002460 if (mod != NULL && PyUnicode_CompareWithASCIIString(mod, "__builtin__"))
2461 rtn = PyUnicode_FromFormat("<%U.%U object at %p>", mod, name, self);
Guido van Rossum76e69632001-08-16 18:52:43 +00002462 else
Walter Dörwald1ab83302007-05-18 17:15:44 +00002463 rtn = PyUnicode_FromFormat("<%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00002464 type->tp_name, self);
Guido van Rossum76e69632001-08-16 18:52:43 +00002465 Py_XDECREF(mod);
2466 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +00002467 return rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00002468}
2469
Guido van Rossumb8f63662001-08-15 23:57:02 +00002470static PyObject *
2471object_str(PyObject *self)
2472{
2473 unaryfunc f;
2474
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002475 f = Py_Type(self)->tp_repr;
Guido van Rossumb8f63662001-08-15 23:57:02 +00002476 if (f == NULL)
2477 f = object_repr;
2478 return f(self);
2479}
2480
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002481static PyObject *
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002482object_richcompare(PyObject *self, PyObject *other, int op)
2483{
2484 PyObject *res;
2485
2486 switch (op) {
2487
2488 case Py_EQ:
2489 res = (self == other) ? Py_True : Py_False;
Guido van Rossum6b18a5b2007-03-29 20:49:57 +00002490 Py_INCREF(res);
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002491 break;
2492
2493 case Py_NE:
Guido van Rossume27dc722007-03-27 22:37:34 +00002494 /* By default, != returns the opposite of ==,
2495 unless the latter returns NotImplemented. */
2496 res = PyObject_RichCompare(self, other, Py_EQ);
2497 if (res != NULL && res != Py_NotImplemented) {
2498 int ok = PyObject_IsTrue(res);
2499 Py_DECREF(res);
2500 if (ok < 0)
2501 res = NULL;
2502 else {
2503 if (ok)
2504 res = Py_False;
2505 else
2506 res = Py_True;
2507 Py_INCREF(res);
2508 }
2509 }
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002510 break;
2511
2512 default:
2513 res = Py_NotImplemented;
Guido van Rossum6b18a5b2007-03-29 20:49:57 +00002514 Py_INCREF(res);
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002515 break;
2516 }
2517
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002518 return res;
2519}
2520
2521static PyObject *
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002522object_get_class(PyObject *self, void *closure)
2523{
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002524 Py_INCREF(Py_Type(self));
2525 return (PyObject *)(Py_Type(self));
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002526}
2527
2528static int
2529equiv_structs(PyTypeObject *a, PyTypeObject *b)
2530{
2531 return a == b ||
2532 (a != NULL &&
2533 b != NULL &&
2534 a->tp_basicsize == b->tp_basicsize &&
2535 a->tp_itemsize == b->tp_itemsize &&
2536 a->tp_dictoffset == b->tp_dictoffset &&
2537 a->tp_weaklistoffset == b->tp_weaklistoffset &&
2538 ((a->tp_flags & Py_TPFLAGS_HAVE_GC) ==
2539 (b->tp_flags & Py_TPFLAGS_HAVE_GC)));
2540}
2541
2542static int
2543same_slots_added(PyTypeObject *a, PyTypeObject *b)
2544{
2545 PyTypeObject *base = a->tp_base;
Martin v. Löwiseb079f12006-02-16 14:32:27 +00002546 Py_ssize_t size;
Guido van Rossumd8faa362007-04-27 19:54:29 +00002547 PyObject *slots_a, *slots_b;
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002548
2549 if (base != b->tp_base)
2550 return 0;
2551 if (equiv_structs(a, base) && equiv_structs(b, base))
2552 return 1;
2553 size = base->tp_basicsize;
2554 if (a->tp_dictoffset == size && b->tp_dictoffset == size)
2555 size += sizeof(PyObject *);
2556 if (a->tp_weaklistoffset == size && b->tp_weaklistoffset == size)
2557 size += sizeof(PyObject *);
Guido van Rossumd8faa362007-04-27 19:54:29 +00002558
2559 /* Check slots compliance */
2560 slots_a = ((PyHeapTypeObject *)a)->ht_slots;
2561 slots_b = ((PyHeapTypeObject *)b)->ht_slots;
2562 if (slots_a && slots_b) {
2563 if (PyObject_Compare(slots_a, slots_b) != 0)
2564 return 0;
2565 size += sizeof(PyObject *) * PyTuple_GET_SIZE(slots_a);
2566 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002567 return size == a->tp_basicsize && size == b->tp_basicsize;
2568}
2569
2570static int
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002571compatible_for_assignment(PyTypeObject* oldto, PyTypeObject* newto, char* attr)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002572{
2573 PyTypeObject *newbase, *oldbase;
2574
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002575 if (newto->tp_dealloc != oldto->tp_dealloc ||
2576 newto->tp_free != oldto->tp_free)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002577 {
2578 PyErr_Format(PyExc_TypeError,
2579 "%s assignment: "
2580 "'%s' deallocator differs from '%s'",
2581 attr,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002582 newto->tp_name,
2583 oldto->tp_name);
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002584 return 0;
2585 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002586 newbase = newto;
2587 oldbase = oldto;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002588 while (equiv_structs(newbase, newbase->tp_base))
2589 newbase = newbase->tp_base;
2590 while (equiv_structs(oldbase, oldbase->tp_base))
2591 oldbase = oldbase->tp_base;
2592 if (newbase != oldbase &&
2593 (newbase->tp_base != oldbase->tp_base ||
2594 !same_slots_added(newbase, oldbase))) {
2595 PyErr_Format(PyExc_TypeError,
2596 "%s assignment: "
2597 "'%s' object layout differs from '%s'",
2598 attr,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002599 newto->tp_name,
2600 oldto->tp_name);
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002601 return 0;
2602 }
Tim Petersea7f75d2002-12-07 21:39:16 +00002603
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002604 return 1;
2605}
2606
2607static int
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002608object_set_class(PyObject *self, PyObject *value, void *closure)
2609{
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002610 PyTypeObject *oldto = Py_Type(self);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002611 PyTypeObject *newto;
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002612
Guido van Rossumb6b89422002-04-15 01:03:30 +00002613 if (value == NULL) {
2614 PyErr_SetString(PyExc_TypeError,
2615 "can't delete __class__ attribute");
2616 return -1;
2617 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002618 if (!PyType_Check(value)) {
2619 PyErr_Format(PyExc_TypeError,
2620 "__class__ must be set to new-style class, not '%s' object",
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002621 Py_Type(value)->tp_name);
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002622 return -1;
2623 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002624 newto = (PyTypeObject *)value;
2625 if (!(newto->tp_flags & Py_TPFLAGS_HEAPTYPE) ||
2626 !(oldto->tp_flags & Py_TPFLAGS_HEAPTYPE))
Guido van Rossum40af8892002-08-10 05:42:07 +00002627 {
2628 PyErr_Format(PyExc_TypeError,
2629 "__class__ assignment: only for heap types");
2630 return -1;
2631 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002632 if (compatible_for_assignment(newto, oldto, "__class__")) {
2633 Py_INCREF(newto);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002634 Py_Type(self) = newto;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002635 Py_DECREF(oldto);
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002636 return 0;
2637 }
2638 else {
Guido van Rossum9ee4b942002-05-24 18:47:47 +00002639 return -1;
2640 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002641}
2642
2643static PyGetSetDef object_getsets[] = {
2644 {"__class__", object_get_class, object_set_class,
Neal Norwitz858e34f2002-08-13 17:18:45 +00002645 PyDoc_STR("the object's class")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002646 {0}
2647};
2648
Guido van Rossumc53f0092003-02-18 22:05:12 +00002649
Guido van Rossum036f9992003-02-21 22:02:54 +00002650/* Stuff to implement __reduce_ex__ for pickle protocols >= 2.
2651 We fall back to helpers in copy_reg for:
2652 - pickle protocols < 2
2653 - calculating the list of slot names (done only once per class)
2654 - the __newobj__ function (which is used as a token but never called)
2655*/
2656
2657static PyObject *
2658import_copy_reg(void)
2659{
2660 static PyObject *copy_reg_str;
Guido van Rossum3926a632001-09-25 16:25:58 +00002661
2662 if (!copy_reg_str) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00002663 copy_reg_str = PyUnicode_InternFromString("copy_reg");
Guido van Rossum3926a632001-09-25 16:25:58 +00002664 if (copy_reg_str == NULL)
2665 return NULL;
2666 }
Guido van Rossum036f9992003-02-21 22:02:54 +00002667
2668 return PyImport_Import(copy_reg_str);
2669}
2670
2671static PyObject *
2672slotnames(PyObject *cls)
2673{
2674 PyObject *clsdict;
2675 PyObject *copy_reg;
2676 PyObject *slotnames;
2677
2678 if (!PyType_Check(cls)) {
2679 Py_INCREF(Py_None);
2680 return Py_None;
2681 }
2682
2683 clsdict = ((PyTypeObject *)cls)->tp_dict;
2684 slotnames = PyDict_GetItemString(clsdict, "__slotnames__");
Armin Rigoec862b92005-09-24 22:58:41 +00002685 if (slotnames != NULL && PyList_Check(slotnames)) {
Guido van Rossum036f9992003-02-21 22:02:54 +00002686 Py_INCREF(slotnames);
2687 return slotnames;
2688 }
2689
2690 copy_reg = import_copy_reg();
2691 if (copy_reg == NULL)
2692 return NULL;
2693
2694 slotnames = PyObject_CallMethod(copy_reg, "_slotnames", "O", cls);
2695 Py_DECREF(copy_reg);
2696 if (slotnames != NULL &&
2697 slotnames != Py_None &&
2698 !PyList_Check(slotnames))
2699 {
2700 PyErr_SetString(PyExc_TypeError,
2701 "copy_reg._slotnames didn't return a list or None");
2702 Py_DECREF(slotnames);
2703 slotnames = NULL;
2704 }
2705
2706 return slotnames;
2707}
2708
2709static PyObject *
2710reduce_2(PyObject *obj)
2711{
2712 PyObject *cls, *getnewargs;
2713 PyObject *args = NULL, *args2 = NULL;
2714 PyObject *getstate = NULL, *state = NULL, *names = NULL;
2715 PyObject *slots = NULL, *listitems = NULL, *dictitems = NULL;
2716 PyObject *copy_reg = NULL, *newobj = NULL, *res = NULL;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002717 Py_ssize_t i, n;
Guido van Rossum036f9992003-02-21 22:02:54 +00002718
2719 cls = PyObject_GetAttrString(obj, "__class__");
2720 if (cls == NULL)
2721 return NULL;
2722
2723 getnewargs = PyObject_GetAttrString(obj, "__getnewargs__");
2724 if (getnewargs != NULL) {
2725 args = PyObject_CallObject(getnewargs, NULL);
2726 Py_DECREF(getnewargs);
2727 if (args != NULL && !PyTuple_Check(args)) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002728 PyErr_Format(PyExc_TypeError,
2729 "__getnewargs__ should return a tuple, "
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002730 "not '%.200s'", Py_Type(args)->tp_name);
Guido van Rossum036f9992003-02-21 22:02:54 +00002731 goto end;
2732 }
2733 }
2734 else {
2735 PyErr_Clear();
2736 args = PyTuple_New(0);
2737 }
2738 if (args == NULL)
2739 goto end;
2740
2741 getstate = PyObject_GetAttrString(obj, "__getstate__");
2742 if (getstate != NULL) {
2743 state = PyObject_CallObject(getstate, NULL);
2744 Py_DECREF(getstate);
Neal Norwitze2fdc612003-06-08 13:19:58 +00002745 if (state == NULL)
2746 goto end;
Guido van Rossum036f9992003-02-21 22:02:54 +00002747 }
2748 else {
Jim Fulton8a1a5942004-02-08 04:21:26 +00002749 PyErr_Clear();
Guido van Rossum036f9992003-02-21 22:02:54 +00002750 state = PyObject_GetAttrString(obj, "__dict__");
2751 if (state == NULL) {
2752 PyErr_Clear();
2753 state = Py_None;
2754 Py_INCREF(state);
2755 }
2756 names = slotnames(cls);
2757 if (names == NULL)
2758 goto end;
2759 if (names != Py_None) {
2760 assert(PyList_Check(names));
2761 slots = PyDict_New();
2762 if (slots == NULL)
2763 goto end;
2764 n = 0;
2765 /* Can't pre-compute the list size; the list
2766 is stored on the class so accessible to other
2767 threads, which may be run by DECREF */
2768 for (i = 0; i < PyList_GET_SIZE(names); i++) {
2769 PyObject *name, *value;
2770 name = PyList_GET_ITEM(names, i);
2771 value = PyObject_GetAttr(obj, name);
2772 if (value == NULL)
2773 PyErr_Clear();
2774 else {
2775 int err = PyDict_SetItem(slots, name,
2776 value);
2777 Py_DECREF(value);
2778 if (err)
2779 goto end;
2780 n++;
2781 }
2782 }
2783 if (n) {
2784 state = Py_BuildValue("(NO)", state, slots);
2785 if (state == NULL)
2786 goto end;
2787 }
2788 }
2789 }
2790
2791 if (!PyList_Check(obj)) {
2792 listitems = Py_None;
2793 Py_INCREF(listitems);
2794 }
2795 else {
2796 listitems = PyObject_GetIter(obj);
2797 if (listitems == NULL)
2798 goto end;
2799 }
2800
2801 if (!PyDict_Check(obj)) {
2802 dictitems = Py_None;
2803 Py_INCREF(dictitems);
2804 }
2805 else {
Guido van Rossumcc2b0162007-02-11 06:12:03 +00002806 PyObject *items = PyObject_CallMethod(obj, "items", "");
2807 if (items == NULL)
2808 goto end;
2809 dictitems = PyObject_GetIter(items);
2810 Py_DECREF(items);
Guido van Rossum036f9992003-02-21 22:02:54 +00002811 if (dictitems == NULL)
2812 goto end;
2813 }
2814
2815 copy_reg = import_copy_reg();
2816 if (copy_reg == NULL)
2817 goto end;
2818 newobj = PyObject_GetAttrString(copy_reg, "__newobj__");
2819 if (newobj == NULL)
2820 goto end;
2821
2822 n = PyTuple_GET_SIZE(args);
2823 args2 = PyTuple_New(n+1);
2824 if (args2 == NULL)
2825 goto end;
2826 PyTuple_SET_ITEM(args2, 0, cls);
2827 cls = NULL;
2828 for (i = 0; i < n; i++) {
2829 PyObject *v = PyTuple_GET_ITEM(args, i);
2830 Py_INCREF(v);
2831 PyTuple_SET_ITEM(args2, i+1, v);
2832 }
2833
Raymond Hettinger8ae46892003-10-12 19:09:37 +00002834 res = PyTuple_Pack(5, newobj, args2, state, listitems, dictitems);
Guido van Rossum036f9992003-02-21 22:02:54 +00002835
2836 end:
2837 Py_XDECREF(cls);
2838 Py_XDECREF(args);
2839 Py_XDECREF(args2);
Jeremy Hyltond06483c2003-04-09 21:01:42 +00002840 Py_XDECREF(slots);
Guido van Rossum036f9992003-02-21 22:02:54 +00002841 Py_XDECREF(state);
2842 Py_XDECREF(names);
2843 Py_XDECREF(listitems);
2844 Py_XDECREF(dictitems);
2845 Py_XDECREF(copy_reg);
2846 Py_XDECREF(newobj);
2847 return res;
2848}
2849
Guido van Rossumd8faa362007-04-27 19:54:29 +00002850/*
2851 * There were two problems when object.__reduce__ and object.__reduce_ex__
2852 * were implemented in the same function:
2853 * - trying to pickle an object with a custom __reduce__ method that
2854 * fell back to object.__reduce__ in certain circumstances led to
2855 * infinite recursion at Python level and eventual RuntimeError.
2856 * - Pickling objects that lied about their type by overwriting the
2857 * __class__ descriptor could lead to infinite recursion at C level
2858 * and eventual segfault.
2859 *
2860 * Because of backwards compatibility, the two methods still have to
2861 * behave in the same way, even if this is not required by the pickle
2862 * protocol. This common functionality was moved to the _common_reduce
2863 * function.
2864 */
2865static PyObject *
2866_common_reduce(PyObject *self, int proto)
2867{
2868 PyObject *copy_reg, *res;
2869
2870 if (proto >= 2)
2871 return reduce_2(self);
2872
2873 copy_reg = import_copy_reg();
2874 if (!copy_reg)
2875 return NULL;
2876
2877 res = PyEval_CallMethod(copy_reg, "_reduce_ex", "(Oi)", self, proto);
2878 Py_DECREF(copy_reg);
2879
2880 return res;
2881}
2882
2883static PyObject *
2884object_reduce(PyObject *self, PyObject *args)
2885{
2886 int proto = 0;
2887
2888 if (!PyArg_ParseTuple(args, "|i:__reduce__", &proto))
2889 return NULL;
2890
2891 return _common_reduce(self, proto);
2892}
2893
Guido van Rossum036f9992003-02-21 22:02:54 +00002894static PyObject *
2895object_reduce_ex(PyObject *self, PyObject *args)
2896{
Guido van Rossumd8faa362007-04-27 19:54:29 +00002897 PyObject *reduce, *res;
Guido van Rossum036f9992003-02-21 22:02:54 +00002898 int proto = 0;
2899
2900 if (!PyArg_ParseTuple(args, "|i:__reduce_ex__", &proto))
2901 return NULL;
2902
2903 reduce = PyObject_GetAttrString(self, "__reduce__");
2904 if (reduce == NULL)
2905 PyErr_Clear();
2906 else {
2907 PyObject *cls, *clsreduce, *objreduce;
2908 int override;
2909 cls = PyObject_GetAttrString(self, "__class__");
2910 if (cls == NULL) {
2911 Py_DECREF(reduce);
2912 return NULL;
2913 }
2914 clsreduce = PyObject_GetAttrString(cls, "__reduce__");
2915 Py_DECREF(cls);
2916 if (clsreduce == NULL) {
2917 Py_DECREF(reduce);
2918 return NULL;
2919 }
2920 objreduce = PyDict_GetItemString(PyBaseObject_Type.tp_dict,
2921 "__reduce__");
2922 override = (clsreduce != objreduce);
2923 Py_DECREF(clsreduce);
2924 if (override) {
2925 res = PyObject_CallObject(reduce, NULL);
2926 Py_DECREF(reduce);
2927 return res;
2928 }
2929 else
2930 Py_DECREF(reduce);
2931 }
2932
Guido van Rossumd8faa362007-04-27 19:54:29 +00002933 return _common_reduce(self, proto);
Guido van Rossum3926a632001-09-25 16:25:58 +00002934}
2935
2936static PyMethodDef object_methods[] = {
Guido van Rossumc53f0092003-02-18 22:05:12 +00002937 {"__reduce_ex__", object_reduce_ex, METH_VARARGS,
2938 PyDoc_STR("helper for pickle")},
Guido van Rossumd8faa362007-04-27 19:54:29 +00002939 {"__reduce__", object_reduce, METH_VARARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002940 PyDoc_STR("helper for pickle")},
Guido van Rossum3926a632001-09-25 16:25:58 +00002941 {0}
2942};
2943
Guido van Rossum036f9992003-02-21 22:02:54 +00002944
Tim Peters6d6c1a32001-08-02 04:15:00 +00002945PyTypeObject PyBaseObject_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002946 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002947 "object", /* tp_name */
2948 sizeof(PyObject), /* tp_basicsize */
2949 0, /* tp_itemsize */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002950 object_dealloc, /* tp_dealloc */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002951 0, /* tp_print */
Guido van Rossumd8faa362007-04-27 19:54:29 +00002952 0, /* tp_getattr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002953 0, /* tp_setattr */
2954 0, /* tp_compare */
Guido van Rossumb8f63662001-08-15 23:57:02 +00002955 object_repr, /* tp_repr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002956 0, /* tp_as_number */
2957 0, /* tp_as_sequence */
2958 0, /* tp_as_mapping */
Guido van Rossum50e9fb92006-08-17 05:42:55 +00002959 (hashfunc)_Py_HashPointer, /* tp_hash */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002960 0, /* tp_call */
Guido van Rossumb8f63662001-08-15 23:57:02 +00002961 object_str, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002962 PyObject_GenericGetAttr, /* tp_getattro */
Guido van Rossum13d52f02001-08-10 21:24:08 +00002963 PyObject_GenericSetAttr, /* tp_setattro */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002964 0, /* tp_as_buffer */
2965 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002966 PyDoc_STR("The most base type"), /* tp_doc */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002967 0, /* tp_traverse */
2968 0, /* tp_clear */
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002969 object_richcompare, /* tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002970 0, /* tp_weaklistoffset */
2971 0, /* tp_iter */
2972 0, /* tp_iternext */
Guido van Rossum3926a632001-09-25 16:25:58 +00002973 object_methods, /* tp_methods */
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002974 0, /* tp_members */
2975 object_getsets, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002976 0, /* tp_base */
2977 0, /* tp_dict */
2978 0, /* tp_descr_get */
2979 0, /* tp_descr_set */
2980 0, /* tp_dictoffset */
2981 object_init, /* tp_init */
2982 PyType_GenericAlloc, /* tp_alloc */
Guido van Rossum298e4212003-02-13 16:30:16 +00002983 object_new, /* tp_new */
Guido van Rossumd8faa362007-04-27 19:54:29 +00002984 PyObject_Del, /* tp_free */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002985};
2986
2987
Guido van Rossum50e9fb92006-08-17 05:42:55 +00002988/* Add the methods from tp_methods to the __dict__ in a type object */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002989
2990static int
2991add_methods(PyTypeObject *type, PyMethodDef *meth)
2992{
Guido van Rossum687ae002001-10-15 22:03:32 +00002993 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002994
2995 for (; meth->ml_name != NULL; meth++) {
2996 PyObject *descr;
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00002997 if (PyDict_GetItemString(dict, meth->ml_name) &&
2998 !(meth->ml_flags & METH_COEXIST))
2999 continue;
Fred Drake7bf97152002-03-28 05:33:33 +00003000 if (meth->ml_flags & METH_CLASS) {
3001 if (meth->ml_flags & METH_STATIC) {
3002 PyErr_SetString(PyExc_ValueError,
3003 "method cannot be both class and static");
3004 return -1;
3005 }
Tim Petersbca1cbc2002-12-09 22:56:13 +00003006 descr = PyDescr_NewClassMethod(type, meth);
Fred Drake7bf97152002-03-28 05:33:33 +00003007 }
3008 else if (meth->ml_flags & METH_STATIC) {
Guido van Rossum9af48ff2003-02-11 17:12:46 +00003009 PyObject *cfunc = PyCFunction_New(meth, NULL);
3010 if (cfunc == NULL)
3011 return -1;
3012 descr = PyStaticMethod_New(cfunc);
3013 Py_DECREF(cfunc);
Fred Drake7bf97152002-03-28 05:33:33 +00003014 }
3015 else {
3016 descr = PyDescr_NewMethod(type, meth);
3017 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003018 if (descr == NULL)
3019 return -1;
Fred Drake7bf97152002-03-28 05:33:33 +00003020 if (PyDict_SetItemString(dict, meth->ml_name, descr) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003021 return -1;
3022 Py_DECREF(descr);
3023 }
3024 return 0;
3025}
3026
3027static int
Guido van Rossum6f799372001-09-20 20:46:19 +00003028add_members(PyTypeObject *type, PyMemberDef *memb)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003029{
Guido van Rossum687ae002001-10-15 22:03:32 +00003030 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003031
3032 for (; memb->name != NULL; memb++) {
3033 PyObject *descr;
3034 if (PyDict_GetItemString(dict, memb->name))
3035 continue;
3036 descr = PyDescr_NewMember(type, memb);
3037 if (descr == NULL)
3038 return -1;
3039 if (PyDict_SetItemString(dict, memb->name, descr) < 0)
3040 return -1;
3041 Py_DECREF(descr);
3042 }
3043 return 0;
3044}
3045
3046static int
Guido van Rossum32d34c82001-09-20 21:45:26 +00003047add_getset(PyTypeObject *type, PyGetSetDef *gsp)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003048{
Guido van Rossum687ae002001-10-15 22:03:32 +00003049 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003050
3051 for (; gsp->name != NULL; gsp++) {
3052 PyObject *descr;
3053 if (PyDict_GetItemString(dict, gsp->name))
3054 continue;
3055 descr = PyDescr_NewGetSet(type, gsp);
3056
3057 if (descr == NULL)
3058 return -1;
3059 if (PyDict_SetItemString(dict, gsp->name, descr) < 0)
3060 return -1;
3061 Py_DECREF(descr);
3062 }
3063 return 0;
3064}
3065
Guido van Rossum13d52f02001-08-10 21:24:08 +00003066static void
3067inherit_special(PyTypeObject *type, PyTypeObject *base)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003068{
Martin v. Löwiseb079f12006-02-16 14:32:27 +00003069 Py_ssize_t oldsize, newsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003070
Guido van Rossum13d52f02001-08-10 21:24:08 +00003071 /* Copying basicsize is connected to the GC flags */
Neil Schemenauerc806c882001-08-29 23:54:54 +00003072 oldsize = base->tp_basicsize;
3073 newsize = type->tp_basicsize ? type->tp_basicsize : oldsize;
3074 if (!(type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
3075 (base->tp_flags & Py_TPFLAGS_HAVE_GC) &&
Guido van Rossum13d52f02001-08-10 21:24:08 +00003076 (!type->tp_traverse && !type->tp_clear)) {
Neil Schemenauerc806c882001-08-29 23:54:54 +00003077 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossum13d52f02001-08-10 21:24:08 +00003078 if (type->tp_traverse == NULL)
3079 type->tp_traverse = base->tp_traverse;
3080 if (type->tp_clear == NULL)
3081 type->tp_clear = base->tp_clear;
3082 }
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00003083 {
Guido van Rossumf884b742001-12-17 17:14:22 +00003084 /* The condition below could use some explanation.
3085 It appears that tp_new is not inherited for static types
3086 whose base class is 'object'; this seems to be a precaution
3087 so that old extension types don't suddenly become
3088 callable (object.__new__ wouldn't insure the invariants
3089 that the extension type's own factory function ensures).
3090 Heap types, of course, are under our control, so they do
3091 inherit tp_new; static extension types that specify some
3092 other built-in type as the default are considered
3093 new-style-aware so they also inherit object.__new__. */
Guido van Rossum13d52f02001-08-10 21:24:08 +00003094 if (base != &PyBaseObject_Type ||
3095 (type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
3096 if (type->tp_new == NULL)
3097 type->tp_new = base->tp_new;
3098 }
3099 }
Neil Schemenauerc806c882001-08-29 23:54:54 +00003100 type->tp_basicsize = newsize;
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00003101
3102 /* Copy other non-function slots */
3103
3104#undef COPYVAL
3105#define COPYVAL(SLOT) \
3106 if (type->SLOT == 0) type->SLOT = base->SLOT
3107
3108 COPYVAL(tp_itemsize);
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00003109 COPYVAL(tp_weaklistoffset);
3110 COPYVAL(tp_dictoffset);
Thomas Wouters27d517b2007-02-25 20:39:11 +00003111
3112 /* Setup fast subclass flags */
3113 if (PyType_IsSubtype(base, (PyTypeObject*)PyExc_BaseException))
3114 type->tp_flags |= Py_TPFLAGS_BASE_EXC_SUBCLASS;
3115 else if (PyType_IsSubtype(base, &PyType_Type))
3116 type->tp_flags |= Py_TPFLAGS_TYPE_SUBCLASS;
3117 else if (PyType_IsSubtype(base, &PyLong_Type))
3118 type->tp_flags |= Py_TPFLAGS_LONG_SUBCLASS;
3119 else if (PyType_IsSubtype(base, &PyString_Type))
3120 type->tp_flags |= Py_TPFLAGS_STRING_SUBCLASS;
3121 else if (PyType_IsSubtype(base, &PyUnicode_Type))
3122 type->tp_flags |= Py_TPFLAGS_UNICODE_SUBCLASS;
3123 else if (PyType_IsSubtype(base, &PyTuple_Type))
3124 type->tp_flags |= Py_TPFLAGS_TUPLE_SUBCLASS;
3125 else if (PyType_IsSubtype(base, &PyList_Type))
3126 type->tp_flags |= Py_TPFLAGS_LIST_SUBCLASS;
3127 else if (PyType_IsSubtype(base, &PyDict_Type))
3128 type->tp_flags |= Py_TPFLAGS_DICT_SUBCLASS;
Guido van Rossum13d52f02001-08-10 21:24:08 +00003129}
3130
Guido van Rossum38938152006-08-21 23:36:26 +00003131/* Map rich comparison operators to their __xx__ namesakes */
3132static char *name_op[] = {
3133 "__lt__",
3134 "__le__",
3135 "__eq__",
3136 "__ne__",
3137 "__gt__",
3138 "__ge__",
3139 /* These are only for overrides_cmp_or_hash(): */
3140 "__cmp__",
3141 "__hash__",
3142};
3143
3144static int
3145overrides_cmp_or_hash(PyTypeObject *type)
3146{
3147 int i;
3148 PyObject *dict = type->tp_dict;
3149
3150 assert(dict != NULL);
3151 for (i = 0; i < 8; i++) {
3152 if (PyDict_GetItemString(dict, name_op[i]) != NULL)
3153 return 1;
3154 }
3155 return 0;
3156}
3157
Guido van Rossum13d52f02001-08-10 21:24:08 +00003158static void
3159inherit_slots(PyTypeObject *type, PyTypeObject *base)
3160{
3161 PyTypeObject *basebase;
3162
3163#undef SLOTDEFINED
Tim Peters6d6c1a32001-08-02 04:15:00 +00003164#undef COPYSLOT
3165#undef COPYNUM
3166#undef COPYSEQ
3167#undef COPYMAP
Guido van Rossum5af588b2001-10-12 14:13:21 +00003168#undef COPYBUF
Guido van Rossum13d52f02001-08-10 21:24:08 +00003169
3170#define SLOTDEFINED(SLOT) \
3171 (base->SLOT != 0 && \
3172 (basebase == NULL || base->SLOT != basebase->SLOT))
3173
Tim Peters6d6c1a32001-08-02 04:15:00 +00003174#define COPYSLOT(SLOT) \
Guido van Rossum13d52f02001-08-10 21:24:08 +00003175 if (!type->SLOT && SLOTDEFINED(SLOT)) type->SLOT = base->SLOT
Tim Peters6d6c1a32001-08-02 04:15:00 +00003176
3177#define COPYNUM(SLOT) COPYSLOT(tp_as_number->SLOT)
3178#define COPYSEQ(SLOT) COPYSLOT(tp_as_sequence->SLOT)
3179#define COPYMAP(SLOT) COPYSLOT(tp_as_mapping->SLOT)
Tim Petersfc57ccb2001-10-12 02:38:24 +00003180#define COPYBUF(SLOT) COPYSLOT(tp_as_buffer->SLOT)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003181
Guido van Rossum13d52f02001-08-10 21:24:08 +00003182 /* This won't inherit indirect slots (from tp_as_number etc.)
3183 if type doesn't provide the space. */
3184
3185 if (type->tp_as_number != NULL && base->tp_as_number != NULL) {
3186 basebase = base->tp_base;
3187 if (basebase->tp_as_number == NULL)
3188 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003189 COPYNUM(nb_add);
3190 COPYNUM(nb_subtract);
3191 COPYNUM(nb_multiply);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003192 COPYNUM(nb_remainder);
3193 COPYNUM(nb_divmod);
3194 COPYNUM(nb_power);
3195 COPYNUM(nb_negative);
3196 COPYNUM(nb_positive);
3197 COPYNUM(nb_absolute);
Jack Diederich4dafcc42006-11-28 19:15:13 +00003198 COPYNUM(nb_bool);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003199 COPYNUM(nb_invert);
3200 COPYNUM(nb_lshift);
3201 COPYNUM(nb_rshift);
3202 COPYNUM(nb_and);
3203 COPYNUM(nb_xor);
3204 COPYNUM(nb_or);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003205 COPYNUM(nb_int);
3206 COPYNUM(nb_long);
3207 COPYNUM(nb_float);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003208 COPYNUM(nb_inplace_add);
3209 COPYNUM(nb_inplace_subtract);
3210 COPYNUM(nb_inplace_multiply);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003211 COPYNUM(nb_inplace_remainder);
3212 COPYNUM(nb_inplace_power);
3213 COPYNUM(nb_inplace_lshift);
3214 COPYNUM(nb_inplace_rshift);
3215 COPYNUM(nb_inplace_and);
3216 COPYNUM(nb_inplace_xor);
3217 COPYNUM(nb_inplace_or);
Neal Norwitzbcc0db82006-03-24 08:14:36 +00003218 COPYNUM(nb_true_divide);
3219 COPYNUM(nb_floor_divide);
3220 COPYNUM(nb_inplace_true_divide);
3221 COPYNUM(nb_inplace_floor_divide);
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00003222 COPYNUM(nb_index);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003223 }
3224
Guido van Rossum13d52f02001-08-10 21:24:08 +00003225 if (type->tp_as_sequence != NULL && base->tp_as_sequence != NULL) {
3226 basebase = base->tp_base;
3227 if (basebase->tp_as_sequence == NULL)
3228 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003229 COPYSEQ(sq_length);
3230 COPYSEQ(sq_concat);
3231 COPYSEQ(sq_repeat);
3232 COPYSEQ(sq_item);
3233 COPYSEQ(sq_slice);
3234 COPYSEQ(sq_ass_item);
3235 COPYSEQ(sq_ass_slice);
3236 COPYSEQ(sq_contains);
3237 COPYSEQ(sq_inplace_concat);
3238 COPYSEQ(sq_inplace_repeat);
3239 }
3240
Guido van Rossum13d52f02001-08-10 21:24:08 +00003241 if (type->tp_as_mapping != NULL && base->tp_as_mapping != NULL) {
3242 basebase = base->tp_base;
3243 if (basebase->tp_as_mapping == NULL)
3244 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003245 COPYMAP(mp_length);
3246 COPYMAP(mp_subscript);
3247 COPYMAP(mp_ass_subscript);
3248 }
3249
Tim Petersfc57ccb2001-10-12 02:38:24 +00003250 if (type->tp_as_buffer != NULL && base->tp_as_buffer != NULL) {
3251 basebase = base->tp_base;
3252 if (basebase->tp_as_buffer == NULL)
3253 basebase = NULL;
Travis E. Oliphantb99f7622007-08-18 11:21:56 +00003254 COPYBUF(bf_getbuffer);
3255 COPYBUF(bf_releasebuffer);
Tim Petersfc57ccb2001-10-12 02:38:24 +00003256 }
3257
Guido van Rossum13d52f02001-08-10 21:24:08 +00003258 basebase = base->tp_base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003259
Tim Peters6d6c1a32001-08-02 04:15:00 +00003260 COPYSLOT(tp_dealloc);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003261 if (type->tp_getattr == NULL && type->tp_getattro == NULL) {
3262 type->tp_getattr = base->tp_getattr;
3263 type->tp_getattro = base->tp_getattro;
3264 }
3265 if (type->tp_setattr == NULL && type->tp_setattro == NULL) {
3266 type->tp_setattr = base->tp_setattr;
3267 type->tp_setattro = base->tp_setattro;
3268 }
3269 /* tp_compare see tp_richcompare */
3270 COPYSLOT(tp_repr);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003271 /* tp_hash see tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003272 COPYSLOT(tp_call);
3273 COPYSLOT(tp_str);
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00003274 {
Guido van Rossum38938152006-08-21 23:36:26 +00003275 /* Copy comparison-related slots only when
3276 not overriding them anywhere */
Guido van Rossumb8f63662001-08-15 23:57:02 +00003277 if (type->tp_compare == NULL &&
3278 type->tp_richcompare == NULL &&
Guido van Rossum38938152006-08-21 23:36:26 +00003279 type->tp_hash == NULL &&
3280 !overrides_cmp_or_hash(type))
Guido van Rossumb8f63662001-08-15 23:57:02 +00003281 {
Tim Peters6d6c1a32001-08-02 04:15:00 +00003282 type->tp_compare = base->tp_compare;
3283 type->tp_richcompare = base->tp_richcompare;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003284 type->tp_hash = base->tp_hash;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003285 }
3286 }
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00003287 {
Tim Peters6d6c1a32001-08-02 04:15:00 +00003288 COPYSLOT(tp_iter);
3289 COPYSLOT(tp_iternext);
3290 }
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00003291 {
Tim Peters6d6c1a32001-08-02 04:15:00 +00003292 COPYSLOT(tp_descr_get);
3293 COPYSLOT(tp_descr_set);
3294 COPYSLOT(tp_dictoffset);
3295 COPYSLOT(tp_init);
3296 COPYSLOT(tp_alloc);
Guido van Rossumcc8fe042002-04-05 17:10:16 +00003297 COPYSLOT(tp_is_gc);
Tim Peters3cfe7542003-05-21 21:29:48 +00003298 if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) ==
3299 (base->tp_flags & Py_TPFLAGS_HAVE_GC)) {
3300 /* They agree about gc. */
3301 COPYSLOT(tp_free);
3302 }
3303 else if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
3304 type->tp_free == NULL &&
Neal Norwitz30d1c512007-08-19 22:48:23 +00003305 base->tp_free == PyObject_Free) {
Tim Peters3cfe7542003-05-21 21:29:48 +00003306 /* A bit of magic to plug in the correct default
3307 * tp_free function when a derived class adds gc,
3308 * didn't define tp_free, and the base uses the
3309 * default non-gc tp_free.
3310 */
3311 type->tp_free = PyObject_GC_Del;
3312 }
3313 /* else they didn't agree about gc, and there isn't something
3314 * obvious to be done -- the type is on its own.
3315 */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003316 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003317}
3318
Jeremy Hylton938ace62002-07-17 16:30:39 +00003319static int add_operators(PyTypeObject *);
Guido van Rossum13d52f02001-08-10 21:24:08 +00003320
Tim Peters6d6c1a32001-08-02 04:15:00 +00003321int
Guido van Rossum528b7eb2001-08-07 17:24:28 +00003322PyType_Ready(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003323{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00003324 PyObject *dict, *bases;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003325 PyTypeObject *base;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003326 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003327
Guido van Rossumcab05802002-06-10 15:29:03 +00003328 if (type->tp_flags & Py_TPFLAGS_READY) {
3329 assert(type->tp_dict != NULL);
Guido van Rossumd614f972001-08-10 17:39:49 +00003330 return 0;
Guido van Rossumcab05802002-06-10 15:29:03 +00003331 }
Guido van Rossumd614f972001-08-10 17:39:49 +00003332 assert((type->tp_flags & Py_TPFLAGS_READYING) == 0);
Guido van Rossumd614f972001-08-10 17:39:49 +00003333
3334 type->tp_flags |= Py_TPFLAGS_READYING;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003335
Tim Peters36eb4df2003-03-23 03:33:13 +00003336#ifdef Py_TRACE_REFS
3337 /* PyType_Ready is the closest thing we have to a choke point
3338 * for type objects, so is the best place I can think of to try
3339 * to get type objects into the doubly-linked list of all objects.
3340 * Still, not all type objects go thru PyType_Ready.
3341 */
Tim Peters7571a0f2003-03-23 17:52:28 +00003342 _Py_AddToAllObjects((PyObject *)type, 0);
Tim Peters36eb4df2003-03-23 03:33:13 +00003343#endif
3344
Tim Peters6d6c1a32001-08-02 04:15:00 +00003345 /* Initialize tp_base (defaults to BaseObject unless that's us) */
3346 base = type->tp_base;
Martin v. Löwisbf608752004-08-18 13:16:54 +00003347 if (base == NULL && type != &PyBaseObject_Type) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00003348 base = type->tp_base = &PyBaseObject_Type;
Martin v. Löwisbf608752004-08-18 13:16:54 +00003349 Py_INCREF(base);
3350 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003351
Guido van Rossumd8faa362007-04-27 19:54:29 +00003352 /* Now the only way base can still be NULL is if type is
3353 * &PyBaseObject_Type.
3354 */
Guido van Rossum692cdbc2006-03-10 02:04:28 +00003355
Guido van Rossum323a9cf2002-08-14 17:26:30 +00003356 /* Initialize the base class */
Guido van Rossum50e9fb92006-08-17 05:42:55 +00003357 if (base != NULL && base->tp_dict == NULL) {
Guido van Rossum323a9cf2002-08-14 17:26:30 +00003358 if (PyType_Ready(base) < 0)
3359 goto error;
3360 }
3361
Guido van Rossumd8faa362007-04-27 19:54:29 +00003362 /* Initialize ob_type if NULL. This means extensions that want to be
Guido van Rossum0986d822002-04-08 01:38:42 +00003363 compilable separately on Windows can call PyType_Ready() instead of
3364 initializing the ob_type field of their type objects. */
Guido van Rossumd8faa362007-04-27 19:54:29 +00003365 /* The test for base != NULL is really unnecessary, since base is only
3366 NULL when type is &PyBaseObject_Type, and we know its ob_type is
3367 not NULL (it's initialized to &PyType_Type). But coverity doesn't
3368 know that. */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003369 if (Py_Type(type) == NULL && base != NULL)
3370 Py_Type(type) = Py_Type(base);
Guido van Rossum0986d822002-04-08 01:38:42 +00003371
Tim Peters6d6c1a32001-08-02 04:15:00 +00003372 /* Initialize tp_bases */
3373 bases = type->tp_bases;
3374 if (bases == NULL) {
3375 if (base == NULL)
3376 bases = PyTuple_New(0);
3377 else
Raymond Hettinger8ae46892003-10-12 19:09:37 +00003378 bases = PyTuple_Pack(1, base);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003379 if (bases == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00003380 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003381 type->tp_bases = bases;
3382 }
3383
Guido van Rossum687ae002001-10-15 22:03:32 +00003384 /* Initialize tp_dict */
3385 dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003386 if (dict == NULL) {
3387 dict = PyDict_New();
3388 if (dict == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00003389 goto error;
Guido van Rossum687ae002001-10-15 22:03:32 +00003390 type->tp_dict = dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003391 }
3392
Guido van Rossum687ae002001-10-15 22:03:32 +00003393 /* Add type-specific descriptors to tp_dict */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003394 if (add_operators(type) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003395 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003396 if (type->tp_methods != NULL) {
3397 if (add_methods(type, type->tp_methods) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003398 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003399 }
3400 if (type->tp_members != NULL) {
3401 if (add_members(type, type->tp_members) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003402 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003403 }
3404 if (type->tp_getset != NULL) {
3405 if (add_getset(type, type->tp_getset) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003406 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003407 }
3408
Tim Peters6d6c1a32001-08-02 04:15:00 +00003409 /* Calculate method resolution order */
3410 if (mro_internal(type) < 0) {
Guido van Rossumd614f972001-08-10 17:39:49 +00003411 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003412 }
3413
Guido van Rossum13d52f02001-08-10 21:24:08 +00003414 /* Inherit special flags from dominant base */
3415 if (type->tp_base != NULL)
3416 inherit_special(type, type->tp_base);
3417
Tim Peters6d6c1a32001-08-02 04:15:00 +00003418 /* Initialize tp_dict properly */
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00003419 bases = type->tp_mro;
3420 assert(bases != NULL);
3421 assert(PyTuple_Check(bases));
3422 n = PyTuple_GET_SIZE(bases);
3423 for (i = 1; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00003424 PyObject *b = PyTuple_GET_ITEM(bases, i);
3425 if (PyType_Check(b))
3426 inherit_slots(type, (PyTypeObject *)b);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003427 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003428
Tim Peters3cfe7542003-05-21 21:29:48 +00003429 /* Sanity check for tp_free. */
3430 if (PyType_IS_GC(type) && (type->tp_flags & Py_TPFLAGS_BASETYPE) &&
3431 (type->tp_free == NULL || type->tp_free == PyObject_Del)) {
Guido van Rossumd8faa362007-04-27 19:54:29 +00003432 /* This base class needs to call tp_free, but doesn't have
3433 * one, or its tp_free is for non-gc'ed objects.
3434 */
Tim Peters3cfe7542003-05-21 21:29:48 +00003435 PyErr_Format(PyExc_TypeError, "type '%.100s' participates in "
3436 "gc and is a base type but has inappropriate "
3437 "tp_free slot",
3438 type->tp_name);
3439 goto error;
3440 }
3441
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00003442 /* if the type dictionary doesn't contain a __doc__, set it from
3443 the tp_doc slot.
3444 */
3445 if (PyDict_GetItemString(type->tp_dict, "__doc__") == NULL) {
3446 if (type->tp_doc != NULL) {
3447 PyObject *doc = PyString_FromString(type->tp_doc);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003448 if (doc == NULL)
3449 goto error;
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00003450 PyDict_SetItemString(type->tp_dict, "__doc__", doc);
3451 Py_DECREF(doc);
3452 } else {
Guido van Rossumd4641072002-04-03 02:13:37 +00003453 PyDict_SetItemString(type->tp_dict,
3454 "__doc__", Py_None);
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00003455 }
3456 }
3457
Guido van Rossum38938152006-08-21 23:36:26 +00003458 /* Hack for tp_hash and __hash__.
3459 If after all that, tp_hash is still NULL, and __hash__ is not in
3460 tp_dict, set tp_dict['__hash__'] equal to None.
3461 This signals that __hash__ is not inherited.
3462 */
3463 if (type->tp_hash == NULL) {
3464 if (PyDict_GetItemString(type->tp_dict, "__hash__") == NULL) {
3465 if (PyDict_SetItemString(type->tp_dict, "__hash__", Py_None) < 0)
3466 goto error;
3467 }
3468 }
3469
Guido van Rossum13d52f02001-08-10 21:24:08 +00003470 /* Some more special stuff */
3471 base = type->tp_base;
3472 if (base != NULL) {
3473 if (type->tp_as_number == NULL)
3474 type->tp_as_number = base->tp_as_number;
3475 if (type->tp_as_sequence == NULL)
3476 type->tp_as_sequence = base->tp_as_sequence;
3477 if (type->tp_as_mapping == NULL)
3478 type->tp_as_mapping = base->tp_as_mapping;
Guido van Rossumeea47182003-02-11 20:39:59 +00003479 if (type->tp_as_buffer == NULL)
3480 type->tp_as_buffer = base->tp_as_buffer;
Guido van Rossum13d52f02001-08-10 21:24:08 +00003481 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003482
Guido van Rossum1c450732001-10-08 15:18:27 +00003483 /* Link into each base class's list of subclasses */
3484 bases = type->tp_bases;
3485 n = PyTuple_GET_SIZE(bases);
3486 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00003487 PyObject *b = PyTuple_GET_ITEM(bases, i);
3488 if (PyType_Check(b) &&
3489 add_subclass((PyTypeObject *)b, type) < 0)
Guido van Rossum1c450732001-10-08 15:18:27 +00003490 goto error;
3491 }
3492
Guido van Rossum13d52f02001-08-10 21:24:08 +00003493 /* All done -- set the ready flag */
Guido van Rossumd614f972001-08-10 17:39:49 +00003494 assert(type->tp_dict != NULL);
3495 type->tp_flags =
3496 (type->tp_flags & ~Py_TPFLAGS_READYING) | Py_TPFLAGS_READY;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003497 return 0;
Guido van Rossumd614f972001-08-10 17:39:49 +00003498
3499 error:
3500 type->tp_flags &= ~Py_TPFLAGS_READYING;
3501 return -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003502}
3503
Guido van Rossum1c450732001-10-08 15:18:27 +00003504static int
3505add_subclass(PyTypeObject *base, PyTypeObject *type)
3506{
Martin v. Löwiseb079f12006-02-16 14:32:27 +00003507 Py_ssize_t i;
3508 int result;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003509 PyObject *list, *ref, *newobj;
Guido van Rossum1c450732001-10-08 15:18:27 +00003510
3511 list = base->tp_subclasses;
3512 if (list == NULL) {
3513 base->tp_subclasses = list = PyList_New(0);
3514 if (list == NULL)
3515 return -1;
3516 }
3517 assert(PyList_Check(list));
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003518 newobj = PyWeakref_NewRef((PyObject *)type, NULL);
Guido van Rossum1c450732001-10-08 15:18:27 +00003519 i = PyList_GET_SIZE(list);
3520 while (--i >= 0) {
3521 ref = PyList_GET_ITEM(list, i);
3522 assert(PyWeakref_CheckRef(ref));
Guido van Rossum3930bc32002-10-18 13:51:49 +00003523 if (PyWeakref_GET_OBJECT(ref) == Py_None)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003524 return PyList_SetItem(list, i, newobj);
Guido van Rossum1c450732001-10-08 15:18:27 +00003525 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003526 result = PyList_Append(list, newobj);
3527 Py_DECREF(newobj);
Martin v. Löwiseb079f12006-02-16 14:32:27 +00003528 return result;
Guido van Rossum1c450732001-10-08 15:18:27 +00003529}
3530
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003531static void
3532remove_subclass(PyTypeObject *base, PyTypeObject *type)
3533{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003534 Py_ssize_t i;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003535 PyObject *list, *ref;
3536
3537 list = base->tp_subclasses;
3538 if (list == NULL) {
3539 return;
3540 }
3541 assert(PyList_Check(list));
3542 i = PyList_GET_SIZE(list);
3543 while (--i >= 0) {
3544 ref = PyList_GET_ITEM(list, i);
3545 assert(PyWeakref_CheckRef(ref));
3546 if (PyWeakref_GET_OBJECT(ref) == (PyObject*)type) {
3547 /* this can't fail, right? */
3548 PySequence_DelItem(list, i);
3549 return;
3550 }
3551 }
3552}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003553
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003554static int
3555check_num_args(PyObject *ob, int n)
3556{
3557 if (!PyTuple_CheckExact(ob)) {
3558 PyErr_SetString(PyExc_SystemError,
3559 "PyArg_UnpackTuple() argument list is not a tuple");
3560 return 0;
3561 }
3562 if (n == PyTuple_GET_SIZE(ob))
3563 return 1;
3564 PyErr_Format(
3565 PyExc_TypeError,
Martin v. Löwis2c95cc62006-02-16 06:54:25 +00003566 "expected %d arguments, got %zd", n, PyTuple_GET_SIZE(ob));
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003567 return 0;
3568}
3569
Tim Peters6d6c1a32001-08-02 04:15:00 +00003570/* Generic wrappers for overloadable 'operators' such as __getitem__ */
3571
3572/* There's a wrapper *function* for each distinct function typedef used
Guido van Rossumd8faa362007-04-27 19:54:29 +00003573 for type object slots (e.g. binaryfunc, ternaryfunc, etc.). There's a
Tim Peters6d6c1a32001-08-02 04:15:00 +00003574 wrapper *table* for each distinct operation (e.g. __len__, __add__).
3575 Most tables have only one entry; the tables for binary operators have two
3576 entries, one regular and one with reversed arguments. */
3577
3578static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00003579wrap_lenfunc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003580{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003581 lenfunc func = (lenfunc)wrapped;
3582 Py_ssize_t res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003583
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003584 if (!check_num_args(args, 0))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003585 return NULL;
3586 res = (*func)(self);
3587 if (res == -1 && PyErr_Occurred())
3588 return NULL;
3589 return PyInt_FromLong((long)res);
3590}
3591
Tim Peters6d6c1a32001-08-02 04:15:00 +00003592static PyObject *
Raymond Hettingerf34f2642003-10-11 17:29:04 +00003593wrap_inquirypred(PyObject *self, PyObject *args, void *wrapped)
3594{
3595 inquiry func = (inquiry)wrapped;
3596 int res;
3597
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003598 if (!check_num_args(args, 0))
Raymond Hettingerf34f2642003-10-11 17:29:04 +00003599 return NULL;
3600 res = (*func)(self);
3601 if (res == -1 && PyErr_Occurred())
3602 return NULL;
3603 return PyBool_FromLong((long)res);
3604}
3605
3606static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00003607wrap_binaryfunc(PyObject *self, PyObject *args, void *wrapped)
3608{
3609 binaryfunc func = (binaryfunc)wrapped;
3610 PyObject *other;
3611
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003612 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003613 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003614 other = PyTuple_GET_ITEM(args, 0);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003615 return (*func)(self, other);
3616}
3617
3618static PyObject *
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003619wrap_binaryfunc_l(PyObject *self, PyObject *args, void *wrapped)
3620{
3621 binaryfunc func = (binaryfunc)wrapped;
3622 PyObject *other;
3623
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003624 if (!check_num_args(args, 1))
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003625 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003626 other = PyTuple_GET_ITEM(args, 0);
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003627 return (*func)(self, other);
3628}
3629
3630static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00003631wrap_binaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
3632{
3633 binaryfunc func = (binaryfunc)wrapped;
3634 PyObject *other;
3635
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003636 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003637 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003638 other = PyTuple_GET_ITEM(args, 0);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003639 if (!PyType_IsSubtype(Py_Type(other), Py_Type(self))) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003640 Py_INCREF(Py_NotImplemented);
3641 return Py_NotImplemented;
3642 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003643 return (*func)(other, self);
3644}
3645
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003646static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00003647wrap_ternaryfunc(PyObject *self, PyObject *args, void *wrapped)
3648{
3649 ternaryfunc func = (ternaryfunc)wrapped;
3650 PyObject *other;
3651 PyObject *third = Py_None;
3652
3653 /* Note: This wrapper only works for __pow__() */
3654
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00003655 if (!PyArg_UnpackTuple(args, "", 1, 2, &other, &third))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003656 return NULL;
3657 return (*func)(self, other, third);
3658}
3659
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00003660static PyObject *
3661wrap_ternaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
3662{
3663 ternaryfunc func = (ternaryfunc)wrapped;
3664 PyObject *other;
3665 PyObject *third = Py_None;
3666
3667 /* Note: This wrapper only works for __pow__() */
3668
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00003669 if (!PyArg_UnpackTuple(args, "", 1, 2, &other, &third))
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00003670 return NULL;
3671 return (*func)(other, self, third);
3672}
3673
Tim Peters6d6c1a32001-08-02 04:15:00 +00003674static PyObject *
3675wrap_unaryfunc(PyObject *self, PyObject *args, void *wrapped)
3676{
3677 unaryfunc func = (unaryfunc)wrapped;
3678
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003679 if (!check_num_args(args, 0))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003680 return NULL;
3681 return (*func)(self);
3682}
3683
Tim Peters6d6c1a32001-08-02 04:15:00 +00003684static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003685wrap_indexargfunc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003686{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003687 ssizeargfunc func = (ssizeargfunc)wrapped;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003688 PyObject* o;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003689 Py_ssize_t i;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003690
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003691 if (!PyArg_UnpackTuple(args, "", 1, 1, &o))
3692 return NULL;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00003693 i = PyNumber_AsSsize_t(o, PyExc_OverflowError);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003694 if (i == -1 && PyErr_Occurred())
Tim Peters6d6c1a32001-08-02 04:15:00 +00003695 return NULL;
3696 return (*func)(self, i);
3697}
3698
Martin v. Löwis18e16552006-02-15 17:27:45 +00003699static Py_ssize_t
Guido van Rossum5d815f32001-08-17 21:57:47 +00003700getindex(PyObject *self, PyObject *arg)
3701{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003702 Py_ssize_t i;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003703
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00003704 i = PyNumber_AsSsize_t(arg, PyExc_OverflowError);
Guido van Rossum5d815f32001-08-17 21:57:47 +00003705 if (i == -1 && PyErr_Occurred())
3706 return -1;
3707 if (i < 0) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003708 PySequenceMethods *sq = Py_Type(self)->tp_as_sequence;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003709 if (sq && sq->sq_length) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00003710 Py_ssize_t n = (*sq->sq_length)(self);
Guido van Rossum5d815f32001-08-17 21:57:47 +00003711 if (n < 0)
3712 return -1;
3713 i += n;
3714 }
3715 }
3716 return i;
3717}
3718
3719static PyObject *
3720wrap_sq_item(PyObject *self, PyObject *args, void *wrapped)
3721{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003722 ssizeargfunc func = (ssizeargfunc)wrapped;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003723 PyObject *arg;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003724 Py_ssize_t i;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003725
Guido van Rossumf4593e02001-10-03 12:09:30 +00003726 if (PyTuple_GET_SIZE(args) == 1) {
3727 arg = PyTuple_GET_ITEM(args, 0);
3728 i = getindex(self, arg);
3729 if (i == -1 && PyErr_Occurred())
3730 return NULL;
3731 return (*func)(self, i);
3732 }
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003733 check_num_args(args, 1);
Guido van Rossumf4593e02001-10-03 12:09:30 +00003734 assert(PyErr_Occurred());
3735 return NULL;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003736}
3737
Tim Peters6d6c1a32001-08-02 04:15:00 +00003738static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00003739wrap_ssizessizeargfunc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003740{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003741 ssizessizeargfunc func = (ssizessizeargfunc)wrapped;
3742 Py_ssize_t i, j;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003743
Martin v. Löwis18e16552006-02-15 17:27:45 +00003744 if (!PyArg_ParseTuple(args, "nn", &i, &j))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003745 return NULL;
3746 return (*func)(self, i, j);
3747}
3748
Tim Peters6d6c1a32001-08-02 04:15:00 +00003749static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00003750wrap_sq_setitem(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003751{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003752 ssizeobjargproc func = (ssizeobjargproc)wrapped;
3753 Py_ssize_t i;
3754 int res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003755 PyObject *arg, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003756
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00003757 if (!PyArg_UnpackTuple(args, "", 2, 2, &arg, &value))
Guido van Rossum5d815f32001-08-17 21:57:47 +00003758 return NULL;
3759 i = getindex(self, arg);
3760 if (i == -1 && PyErr_Occurred())
Tim Peters6d6c1a32001-08-02 04:15:00 +00003761 return NULL;
3762 res = (*func)(self, i, value);
3763 if (res == -1 && PyErr_Occurred())
3764 return NULL;
3765 Py_INCREF(Py_None);
3766 return Py_None;
3767}
3768
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003769static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00003770wrap_sq_delitem(PyObject *self, PyObject *args, void *wrapped)
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003771{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003772 ssizeobjargproc func = (ssizeobjargproc)wrapped;
3773 Py_ssize_t i;
3774 int res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003775 PyObject *arg;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003776
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003777 if (!check_num_args(args, 1))
Guido van Rossum5d815f32001-08-17 21:57:47 +00003778 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003779 arg = PyTuple_GET_ITEM(args, 0);
Guido van Rossum5d815f32001-08-17 21:57:47 +00003780 i = getindex(self, arg);
3781 if (i == -1 && PyErr_Occurred())
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003782 return NULL;
3783 res = (*func)(self, i, NULL);
3784 if (res == -1 && PyErr_Occurred())
3785 return NULL;
3786 Py_INCREF(Py_None);
3787 return Py_None;
3788}
3789
Tim Peters6d6c1a32001-08-02 04:15:00 +00003790static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00003791wrap_ssizessizeobjargproc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003792{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003793 ssizessizeobjargproc func = (ssizessizeobjargproc)wrapped;
3794 Py_ssize_t i, j;
3795 int res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003796 PyObject *value;
3797
Martin v. Löwis18e16552006-02-15 17:27:45 +00003798 if (!PyArg_ParseTuple(args, "nnO", &i, &j, &value))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003799 return NULL;
3800 res = (*func)(self, i, j, value);
3801 if (res == -1 && PyErr_Occurred())
3802 return NULL;
3803 Py_INCREF(Py_None);
3804 return Py_None;
3805}
3806
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003807static PyObject *
3808wrap_delslice(PyObject *self, PyObject *args, void *wrapped)
3809{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003810 ssizessizeobjargproc func = (ssizessizeobjargproc)wrapped;
3811 Py_ssize_t i, j;
3812 int res;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003813
Martin v. Löwis18e16552006-02-15 17:27:45 +00003814 if (!PyArg_ParseTuple(args, "nn", &i, &j))
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003815 return NULL;
3816 res = (*func)(self, i, j, NULL);
3817 if (res == -1 && PyErr_Occurred())
3818 return NULL;
3819 Py_INCREF(Py_None);
3820 return Py_None;
3821}
3822
Tim Peters6d6c1a32001-08-02 04:15:00 +00003823/* XXX objobjproc is a misnomer; should be objargpred */
3824static PyObject *
3825wrap_objobjproc(PyObject *self, PyObject *args, void *wrapped)
3826{
3827 objobjproc func = (objobjproc)wrapped;
3828 int res;
Guido van Rossum22c3dda2003-10-09 03:46:35 +00003829 PyObject *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003830
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003831 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003832 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003833 value = PyTuple_GET_ITEM(args, 0);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003834 res = (*func)(self, value);
3835 if (res == -1 && PyErr_Occurred())
3836 return NULL;
Guido van Rossum22c3dda2003-10-09 03:46:35 +00003837 else
3838 return PyBool_FromLong(res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003839}
3840
Tim Peters6d6c1a32001-08-02 04:15:00 +00003841static PyObject *
3842wrap_objobjargproc(PyObject *self, PyObject *args, void *wrapped)
3843{
3844 objobjargproc func = (objobjargproc)wrapped;
3845 int res;
3846 PyObject *key, *value;
3847
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00003848 if (!PyArg_UnpackTuple(args, "", 2, 2, &key, &value))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003849 return NULL;
3850 res = (*func)(self, key, value);
3851 if (res == -1 && PyErr_Occurred())
3852 return NULL;
3853 Py_INCREF(Py_None);
3854 return Py_None;
3855}
3856
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003857static PyObject *
3858wrap_delitem(PyObject *self, PyObject *args, void *wrapped)
3859{
3860 objobjargproc func = (objobjargproc)wrapped;
3861 int res;
3862 PyObject *key;
3863
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003864 if (!check_num_args(args, 1))
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003865 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003866 key = PyTuple_GET_ITEM(args, 0);
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003867 res = (*func)(self, key, NULL);
3868 if (res == -1 && PyErr_Occurred())
3869 return NULL;
3870 Py_INCREF(Py_None);
3871 return Py_None;
3872}
3873
Tim Peters6d6c1a32001-08-02 04:15:00 +00003874static PyObject *
3875wrap_cmpfunc(PyObject *self, PyObject *args, void *wrapped)
3876{
3877 cmpfunc func = (cmpfunc)wrapped;
3878 int res;
3879 PyObject *other;
3880
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003881 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003882 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003883 other = PyTuple_GET_ITEM(args, 0);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003884 if (Py_Type(other)->tp_compare != func &&
3885 !PyType_IsSubtype(Py_Type(other), Py_Type(self))) {
Guido van Rossumceccae52001-09-18 20:03:57 +00003886 PyErr_Format(
3887 PyExc_TypeError,
3888 "%s.__cmp__(x,y) requires y to be a '%s', not a '%s'",
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003889 Py_Type(self)->tp_name,
3890 Py_Type(self)->tp_name,
3891 Py_Type(other)->tp_name);
Guido van Rossumceccae52001-09-18 20:03:57 +00003892 return NULL;
3893 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003894 res = (*func)(self, other);
3895 if (PyErr_Occurred())
3896 return NULL;
3897 return PyInt_FromLong((long)res);
3898}
3899
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003900/* Helper to check for object.__setattr__ or __delattr__ applied to a type.
Guido van Rossum52b27052003-04-15 20:05:10 +00003901 This is called the Carlo Verre hack after its discoverer. */
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003902static int
3903hackcheck(PyObject *self, setattrofunc func, char *what)
3904{
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003905 PyTypeObject *type = Py_Type(self);
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003906 while (type && type->tp_flags & Py_TPFLAGS_HEAPTYPE)
3907 type = type->tp_base;
Guido van Rossumd8faa362007-04-27 19:54:29 +00003908 /* If type is NULL now, this is a really weird type.
3909 In the spirit of backwards compatibility (?), just shut up. */
Guido van Rossum692cdbc2006-03-10 02:04:28 +00003910 if (type && type->tp_setattro != func) {
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003911 PyErr_Format(PyExc_TypeError,
3912 "can't apply this %s to %s object",
3913 what,
3914 type->tp_name);
3915 return 0;
3916 }
3917 return 1;
3918}
3919
Tim Peters6d6c1a32001-08-02 04:15:00 +00003920static PyObject *
3921wrap_setattr(PyObject *self, PyObject *args, void *wrapped)
3922{
3923 setattrofunc func = (setattrofunc)wrapped;
3924 int res;
3925 PyObject *name, *value;
3926
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00003927 if (!PyArg_UnpackTuple(args, "", 2, 2, &name, &value))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003928 return NULL;
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003929 if (!hackcheck(self, func, "__setattr__"))
3930 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003931 res = (*func)(self, name, value);
3932 if (res < 0)
3933 return NULL;
3934 Py_INCREF(Py_None);
3935 return Py_None;
3936}
3937
3938static PyObject *
3939wrap_delattr(PyObject *self, PyObject *args, void *wrapped)
3940{
3941 setattrofunc func = (setattrofunc)wrapped;
3942 int res;
3943 PyObject *name;
3944
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003945 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003946 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003947 name = PyTuple_GET_ITEM(args, 0);
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003948 if (!hackcheck(self, func, "__delattr__"))
3949 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003950 res = (*func)(self, name, NULL);
3951 if (res < 0)
3952 return NULL;
3953 Py_INCREF(Py_None);
3954 return Py_None;
3955}
3956
Tim Peters6d6c1a32001-08-02 04:15:00 +00003957static PyObject *
3958wrap_hashfunc(PyObject *self, PyObject *args, void *wrapped)
3959{
3960 hashfunc func = (hashfunc)wrapped;
3961 long res;
3962
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003963 if (!check_num_args(args, 0))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003964 return NULL;
3965 res = (*func)(self);
3966 if (res == -1 && PyErr_Occurred())
3967 return NULL;
3968 return PyInt_FromLong(res);
3969}
3970
Tim Peters6d6c1a32001-08-02 04:15:00 +00003971static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00003972wrap_call(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003973{
3974 ternaryfunc func = (ternaryfunc)wrapped;
3975
Guido van Rossumc8e56452001-10-22 00:43:43 +00003976 return (*func)(self, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003977}
3978
Tim Peters6d6c1a32001-08-02 04:15:00 +00003979static PyObject *
3980wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op)
3981{
3982 richcmpfunc func = (richcmpfunc)wrapped;
3983 PyObject *other;
3984
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003985 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003986 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003987 other = PyTuple_GET_ITEM(args, 0);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003988 return (*func)(self, other, op);
3989}
3990
3991#undef RICHCMP_WRAPPER
3992#define RICHCMP_WRAPPER(NAME, OP) \
3993static PyObject * \
3994richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \
3995{ \
3996 return wrap_richcmpfunc(self, args, wrapped, OP); \
3997}
3998
Jack Jansen8e938b42001-08-08 15:29:49 +00003999RICHCMP_WRAPPER(lt, Py_LT)
4000RICHCMP_WRAPPER(le, Py_LE)
4001RICHCMP_WRAPPER(eq, Py_EQ)
4002RICHCMP_WRAPPER(ne, Py_NE)
4003RICHCMP_WRAPPER(gt, Py_GT)
4004RICHCMP_WRAPPER(ge, Py_GE)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004005
Tim Peters6d6c1a32001-08-02 04:15:00 +00004006static PyObject *
4007wrap_next(PyObject *self, PyObject *args, void *wrapped)
4008{
4009 unaryfunc func = (unaryfunc)wrapped;
4010 PyObject *res;
4011
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004012 if (!check_num_args(args, 0))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004013 return NULL;
4014 res = (*func)(self);
4015 if (res == NULL && !PyErr_Occurred())
4016 PyErr_SetNone(PyExc_StopIteration);
4017 return res;
4018}
4019
Tim Peters6d6c1a32001-08-02 04:15:00 +00004020static PyObject *
4021wrap_descr_get(PyObject *self, PyObject *args, void *wrapped)
4022{
4023 descrgetfunc func = (descrgetfunc)wrapped;
4024 PyObject *obj;
4025 PyObject *type = NULL;
4026
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00004027 if (!PyArg_UnpackTuple(args, "", 1, 2, &obj, &type))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004028 return NULL;
Guido van Rossum82ed25c2003-02-11 16:25:43 +00004029 if (obj == Py_None)
4030 obj = NULL;
4031 if (type == Py_None)
4032 type = NULL;
4033 if (type == NULL &&obj == NULL) {
4034 PyErr_SetString(PyExc_TypeError,
4035 "__get__(None, None) is invalid");
4036 return NULL;
4037 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004038 return (*func)(self, obj, type);
4039}
4040
Tim Peters6d6c1a32001-08-02 04:15:00 +00004041static PyObject *
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004042wrap_descr_set(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004043{
4044 descrsetfunc func = (descrsetfunc)wrapped;
4045 PyObject *obj, *value;
4046 int ret;
4047
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00004048 if (!PyArg_UnpackTuple(args, "", 2, 2, &obj, &value))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004049 return NULL;
4050 ret = (*func)(self, obj, value);
4051 if (ret < 0)
4052 return NULL;
4053 Py_INCREF(Py_None);
4054 return Py_None;
4055}
Guido van Rossum22b13872002-08-06 21:41:44 +00004056
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00004057static PyObject *
4058wrap_descr_delete(PyObject *self, PyObject *args, void *wrapped)
4059{
4060 descrsetfunc func = (descrsetfunc)wrapped;
4061 PyObject *obj;
4062 int ret;
4063
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004064 if (!check_num_args(args, 1))
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00004065 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004066 obj = PyTuple_GET_ITEM(args, 0);
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00004067 ret = (*func)(self, obj, NULL);
4068 if (ret < 0)
4069 return NULL;
4070 Py_INCREF(Py_None);
4071 return Py_None;
4072}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004073
Tim Peters6d6c1a32001-08-02 04:15:00 +00004074static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00004075wrap_init(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004076{
4077 initproc func = (initproc)wrapped;
4078
Guido van Rossumc8e56452001-10-22 00:43:43 +00004079 if (func(self, args, kwds) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004080 return NULL;
4081 Py_INCREF(Py_None);
4082 return Py_None;
4083}
4084
Tim Peters6d6c1a32001-08-02 04:15:00 +00004085static PyObject *
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004086tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004087{
Barry Warsaw60f01882001-08-22 19:24:42 +00004088 PyTypeObject *type, *subtype, *staticbase;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004089 PyObject *arg0, *res;
4090
4091 if (self == NULL || !PyType_Check(self))
4092 Py_FatalError("__new__() called with non-type 'self'");
4093 type = (PyTypeObject *)self;
4094 if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) {
Barry Warsaw60f01882001-08-22 19:24:42 +00004095 PyErr_Format(PyExc_TypeError,
4096 "%s.__new__(): not enough arguments",
4097 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004098 return NULL;
4099 }
4100 arg0 = PyTuple_GET_ITEM(args, 0);
4101 if (!PyType_Check(arg0)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00004102 PyErr_Format(PyExc_TypeError,
4103 "%s.__new__(X): X is not a type object (%s)",
4104 type->tp_name,
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00004105 Py_Type(arg0)->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004106 return NULL;
4107 }
4108 subtype = (PyTypeObject *)arg0;
4109 if (!PyType_IsSubtype(subtype, type)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00004110 PyErr_Format(PyExc_TypeError,
4111 "%s.__new__(%s): %s is not a subtype of %s",
4112 type->tp_name,
4113 subtype->tp_name,
4114 subtype->tp_name,
4115 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004116 return NULL;
4117 }
Barry Warsaw60f01882001-08-22 19:24:42 +00004118
4119 /* Check that the use doesn't do something silly and unsafe like
Tim Petersa427a2b2001-10-29 22:25:45 +00004120 object.__new__(dict). To do this, we check that the
Barry Warsaw60f01882001-08-22 19:24:42 +00004121 most derived base that's not a heap type is this type. */
4122 staticbase = subtype;
4123 while (staticbase && (staticbase->tp_flags & Py_TPFLAGS_HEAPTYPE))
4124 staticbase = staticbase->tp_base;
Guido van Rossumd8faa362007-04-27 19:54:29 +00004125 /* If staticbase is NULL now, it is a really weird type.
4126 In the spirit of backwards compatibility (?), just shut up. */
Guido van Rossum692cdbc2006-03-10 02:04:28 +00004127 if (staticbase && staticbase->tp_new != type->tp_new) {
Barry Warsaw60f01882001-08-22 19:24:42 +00004128 PyErr_Format(PyExc_TypeError,
4129 "%s.__new__(%s) is not safe, use %s.__new__()",
4130 type->tp_name,
4131 subtype->tp_name,
4132 staticbase == NULL ? "?" : staticbase->tp_name);
4133 return NULL;
4134 }
4135
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004136 args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
4137 if (args == NULL)
4138 return NULL;
4139 res = type->tp_new(subtype, args, kwds);
4140 Py_DECREF(args);
4141 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004142}
4143
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004144static struct PyMethodDef tp_new_methoddef[] = {
Guido van Rossumd59da4b2007-05-22 18:11:13 +00004145 {"__new__", (PyCFunction)tp_new_wrapper, METH_VARARGS|METH_KEYWORDS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00004146 PyDoc_STR("T.__new__(S, ...) -> "
Guido van Rossumd8faa362007-04-27 19:54:29 +00004147 "a new object with type S, a subtype of T")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00004148 {0}
4149};
4150
4151static int
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004152add_tp_new_wrapper(PyTypeObject *type)
4153{
Guido van Rossumf040ede2001-08-07 16:40:56 +00004154 PyObject *func;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004155
Guido van Rossum687ae002001-10-15 22:03:32 +00004156 if (PyDict_GetItemString(type->tp_dict, "__new__") != NULL)
Guido van Rossumf040ede2001-08-07 16:40:56 +00004157 return 0;
4158 func = PyCFunction_New(tp_new_methoddef, (PyObject *)type);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004159 if (func == NULL)
4160 return -1;
Raymond Hettinger8d726ee2004-06-25 22:24:35 +00004161 if (PyDict_SetItemString(type->tp_dict, "__new__", func)) {
Raymond Hettingerd56cbe52004-06-25 22:17:39 +00004162 Py_DECREF(func);
4163 return -1;
4164 }
4165 Py_DECREF(func);
4166 return 0;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004167}
4168
Guido van Rossumf040ede2001-08-07 16:40:56 +00004169/* Slot wrappers that call the corresponding __foo__ slot. See comments
4170 below at override_slots() for more explanation. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004171
Guido van Rossumdc91b992001-08-08 22:26:22 +00004172#define SLOT0(FUNCNAME, OPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004173static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004174FUNCNAME(PyObject *self) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004175{ \
Guido van Rossum5592e4d2001-08-28 18:28:21 +00004176 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00004177 return call_method(self, OPSTR, &cache_str, "()"); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004178}
4179
Guido van Rossumdc91b992001-08-08 22:26:22 +00004180#define SLOT1(FUNCNAME, OPSTR, ARG1TYPE, ARGCODES) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004181static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004182FUNCNAME(PyObject *self, ARG1TYPE arg1) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004183{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00004184 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00004185 return call_method(self, OPSTR, &cache_str, "(" ARGCODES ")", arg1); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004186}
4187
Guido van Rossumcd118802003-01-06 22:57:47 +00004188/* Boolean helper for SLOT1BINFULL().
4189 right.__class__ is a nontrivial subclass of left.__class__. */
4190static int
4191method_is_overloaded(PyObject *left, PyObject *right, char *name)
4192{
4193 PyObject *a, *b;
4194 int ok;
4195
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00004196 b = PyObject_GetAttrString((PyObject *)(Py_Type(right)), name);
Guido van Rossumcd118802003-01-06 22:57:47 +00004197 if (b == NULL) {
4198 PyErr_Clear();
4199 /* If right doesn't have it, it's not overloaded */
4200 return 0;
4201 }
4202
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00004203 a = PyObject_GetAttrString((PyObject *)(Py_Type(left)), name);
Guido van Rossumcd118802003-01-06 22:57:47 +00004204 if (a == NULL) {
4205 PyErr_Clear();
4206 Py_DECREF(b);
4207 /* If right has it but left doesn't, it's overloaded */
4208 return 1;
4209 }
4210
4211 ok = PyObject_RichCompareBool(a, b, Py_NE);
4212 Py_DECREF(a);
4213 Py_DECREF(b);
4214 if (ok < 0) {
4215 PyErr_Clear();
4216 return 0;
4217 }
4218
4219 return ok;
4220}
4221
Guido van Rossumdc91b992001-08-08 22:26:22 +00004222
4223#define SLOT1BINFULL(FUNCNAME, TESTFUNC, SLOTNAME, OPSTR, ROPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004224static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004225FUNCNAME(PyObject *self, PyObject *other) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004226{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00004227 static PyObject *cache_str, *rcache_str; \
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00004228 int do_other = Py_Type(self) != Py_Type(other) && \
4229 Py_Type(other)->tp_as_number != NULL && \
4230 Py_Type(other)->tp_as_number->SLOTNAME == TESTFUNC; \
4231 if (Py_Type(self)->tp_as_number != NULL && \
4232 Py_Type(self)->tp_as_number->SLOTNAME == TESTFUNC) { \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004233 PyObject *r; \
Guido van Rossum55f20992001-10-01 17:18:22 +00004234 if (do_other && \
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00004235 PyType_IsSubtype(Py_Type(other), Py_Type(self)) && \
Guido van Rossumcd118802003-01-06 22:57:47 +00004236 method_is_overloaded(self, other, ROPSTR)) { \
Guido van Rossum55f20992001-10-01 17:18:22 +00004237 r = call_maybe( \
4238 other, ROPSTR, &rcache_str, "(O)", self); \
4239 if (r != Py_NotImplemented) \
4240 return r; \
4241 Py_DECREF(r); \
4242 do_other = 0; \
4243 } \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00004244 r = call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00004245 self, OPSTR, &cache_str, "(O)", other); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004246 if (r != Py_NotImplemented || \
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00004247 Py_Type(other) == Py_Type(self)) \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004248 return r; \
4249 Py_DECREF(r); \
4250 } \
Guido van Rossum55f20992001-10-01 17:18:22 +00004251 if (do_other) { \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00004252 return call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00004253 other, ROPSTR, &rcache_str, "(O)", self); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004254 } \
4255 Py_INCREF(Py_NotImplemented); \
4256 return Py_NotImplemented; \
4257}
4258
4259#define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) \
4260 SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR)
4261
4262#define SLOT2(FUNCNAME, OPSTR, ARG1TYPE, ARG2TYPE, ARGCODES) \
4263static PyObject * \
4264FUNCNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \
4265{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00004266 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00004267 return call_method(self, OPSTR, &cache_str, \
4268 "(" ARGCODES ")", arg1, arg2); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004269}
4270
Martin v. Löwis18e16552006-02-15 17:27:45 +00004271static Py_ssize_t
Tim Peters6d6c1a32001-08-02 04:15:00 +00004272slot_sq_length(PyObject *self)
4273{
Guido van Rossum2730b132001-08-28 18:22:14 +00004274 static PyObject *len_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00004275 PyObject *res = call_method(self, "__len__", &len_str, "()");
Martin v. Löwis18e16552006-02-15 17:27:45 +00004276 Py_ssize_t len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004277
4278 if (res == NULL)
4279 return -1;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00004280 len = PyInt_AsSsize_t(res);
Guido van Rossum26111622001-10-01 16:42:49 +00004281 Py_DECREF(res);
Jeremy Hyltonf20fcf92002-07-25 16:06:15 +00004282 if (len < 0) {
Thomas Wouters89f507f2006-12-13 04:49:30 +00004283 if (!PyErr_Occurred())
4284 PyErr_SetString(PyExc_ValueError,
4285 "__len__() should return >= 0");
Jeremy Hyltonf20fcf92002-07-25 16:06:15 +00004286 return -1;
4287 }
Guido van Rossum26111622001-10-01 16:42:49 +00004288 return len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004289}
4290
Guido van Rossumf4593e02001-10-03 12:09:30 +00004291/* Super-optimized version of slot_sq_item.
4292 Other slots could do the same... */
4293static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00004294slot_sq_item(PyObject *self, Py_ssize_t i)
Guido van Rossumf4593e02001-10-03 12:09:30 +00004295{
4296 static PyObject *getitem_str;
4297 PyObject *func, *args = NULL, *ival = NULL, *retval = NULL;
4298 descrgetfunc f;
4299
4300 if (getitem_str == NULL) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00004301 getitem_str = PyUnicode_InternFromString("__getitem__");
Guido van Rossumf4593e02001-10-03 12:09:30 +00004302 if (getitem_str == NULL)
4303 return NULL;
4304 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00004305 func = _PyType_Lookup(Py_Type(self), getitem_str);
Guido van Rossumf4593e02001-10-03 12:09:30 +00004306 if (func != NULL) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00004307 if ((f = Py_Type(func)->tp_descr_get) == NULL)
Guido van Rossumf4593e02001-10-03 12:09:30 +00004308 Py_INCREF(func);
Neal Norwitz673cd822002-10-18 16:33:13 +00004309 else {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00004310 func = f(func, self, (PyObject *)(Py_Type(self)));
Neal Norwitz673cd822002-10-18 16:33:13 +00004311 if (func == NULL) {
4312 return NULL;
4313 }
4314 }
Martin v. Löwiseb079f12006-02-16 14:32:27 +00004315 ival = PyInt_FromSsize_t(i);
Guido van Rossumf4593e02001-10-03 12:09:30 +00004316 if (ival != NULL) {
4317 args = PyTuple_New(1);
4318 if (args != NULL) {
4319 PyTuple_SET_ITEM(args, 0, ival);
4320 retval = PyObject_Call(func, args, NULL);
4321 Py_XDECREF(args);
4322 Py_XDECREF(func);
4323 return retval;
4324 }
4325 }
4326 }
4327 else {
4328 PyErr_SetObject(PyExc_AttributeError, getitem_str);
4329 }
4330 Py_XDECREF(args);
4331 Py_XDECREF(ival);
4332 Py_XDECREF(func);
4333 return NULL;
4334}
4335
Martin v. Löwis18e16552006-02-15 17:27:45 +00004336SLOT2(slot_sq_slice, "__getslice__", Py_ssize_t, Py_ssize_t, "nn")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004337
4338static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00004339slot_sq_ass_item(PyObject *self, Py_ssize_t index, PyObject *value)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004340{
4341 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004342 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004343
4344 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004345 res = call_method(self, "__delitem__", &delitem_str,
Thomas Wouters3fc2ca32006-04-21 11:28:17 +00004346 "(n)", index);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004347 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004348 res = call_method(self, "__setitem__", &setitem_str,
Thomas Wouters3fc2ca32006-04-21 11:28:17 +00004349 "(nO)", index, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004350 if (res == NULL)
4351 return -1;
4352 Py_DECREF(res);
4353 return 0;
4354}
4355
4356static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00004357slot_sq_ass_slice(PyObject *self, Py_ssize_t i, Py_ssize_t j, PyObject *value)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004358{
4359 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004360 static PyObject *delslice_str, *setslice_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004361
4362 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004363 res = call_method(self, "__delslice__", &delslice_str,
Thomas Wouters3fc2ca32006-04-21 11:28:17 +00004364 "(nn)", i, j);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004365 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004366 res = call_method(self, "__setslice__", &setslice_str,
Thomas Wouters3fc2ca32006-04-21 11:28:17 +00004367 "(nnO)", i, j, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004368 if (res == NULL)
4369 return -1;
4370 Py_DECREF(res);
4371 return 0;
4372}
4373
4374static int
4375slot_sq_contains(PyObject *self, PyObject *value)
4376{
Guido van Rossumb8f63662001-08-15 23:57:02 +00004377 PyObject *func, *res, *args;
Tim Petersbf9b2442003-03-23 05:35:36 +00004378 int result = -1;
4379
Guido van Rossum60718732001-08-28 17:47:51 +00004380 static PyObject *contains_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004381
Guido van Rossum55f20992001-10-01 17:18:22 +00004382 func = lookup_maybe(self, "__contains__", &contains_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004383 if (func != NULL) {
Raymond Hettinger8ae46892003-10-12 19:09:37 +00004384 args = PyTuple_Pack(1, value);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004385 if (args == NULL)
4386 res = NULL;
4387 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00004388 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004389 Py_DECREF(args);
4390 }
4391 Py_DECREF(func);
Tim Petersbf9b2442003-03-23 05:35:36 +00004392 if (res != NULL) {
4393 result = PyObject_IsTrue(res);
4394 Py_DECREF(res);
4395 }
Guido van Rossumb8f63662001-08-15 23:57:02 +00004396 }
Tim Petersbf9b2442003-03-23 05:35:36 +00004397 else if (! PyErr_Occurred()) {
Martin v. Löwis725507b2006-03-07 12:08:51 +00004398 /* Possible results: -1 and 1 */
4399 result = (int)_PySequence_IterSearch(self, value,
Tim Petersbf9b2442003-03-23 05:35:36 +00004400 PY_ITERSEARCH_CONTAINS);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004401 }
Tim Petersbf9b2442003-03-23 05:35:36 +00004402 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004403}
4404
Tim Peters6d6c1a32001-08-02 04:15:00 +00004405#define slot_mp_length slot_sq_length
4406
Guido van Rossumdc91b992001-08-08 22:26:22 +00004407SLOT1(slot_mp_subscript, "__getitem__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004408
4409static int
4410slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value)
4411{
4412 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004413 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004414
4415 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004416 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004417 "(O)", key);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004418 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004419 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004420 "(OO)", key, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004421 if (res == NULL)
4422 return -1;
4423 Py_DECREF(res);
4424 return 0;
4425}
4426
Guido van Rossumdc91b992001-08-08 22:26:22 +00004427SLOT1BIN(slot_nb_add, nb_add, "__add__", "__radd__")
4428SLOT1BIN(slot_nb_subtract, nb_subtract, "__sub__", "__rsub__")
4429SLOT1BIN(slot_nb_multiply, nb_multiply, "__mul__", "__rmul__")
Guido van Rossumdc91b992001-08-08 22:26:22 +00004430SLOT1BIN(slot_nb_remainder, nb_remainder, "__mod__", "__rmod__")
4431SLOT1BIN(slot_nb_divmod, nb_divmod, "__divmod__", "__rdivmod__")
4432
Jeremy Hylton938ace62002-07-17 16:30:39 +00004433static PyObject *slot_nb_power(PyObject *, PyObject *, PyObject *);
Guido van Rossumdc91b992001-08-08 22:26:22 +00004434
4435SLOT1BINFULL(slot_nb_power_binary, slot_nb_power,
4436 nb_power, "__pow__", "__rpow__")
4437
4438static PyObject *
4439slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus)
4440{
Guido van Rossum2730b132001-08-28 18:22:14 +00004441 static PyObject *pow_str;
4442
Guido van Rossumdc91b992001-08-08 22:26:22 +00004443 if (modulus == Py_None)
4444 return slot_nb_power_binary(self, other);
Guido van Rossum23094982002-06-10 14:30:43 +00004445 /* Three-arg power doesn't use __rpow__. But ternary_op
4446 can call this when the second argument's type uses
4447 slot_nb_power, so check before calling self.__pow__. */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00004448 if (Py_Type(self)->tp_as_number != NULL &&
4449 Py_Type(self)->tp_as_number->nb_power == slot_nb_power) {
Guido van Rossum23094982002-06-10 14:30:43 +00004450 return call_method(self, "__pow__", &pow_str,
4451 "(OO)", other, modulus);
4452 }
4453 Py_INCREF(Py_NotImplemented);
4454 return Py_NotImplemented;
Guido van Rossumdc91b992001-08-08 22:26:22 +00004455}
4456
4457SLOT0(slot_nb_negative, "__neg__")
4458SLOT0(slot_nb_positive, "__pos__")
4459SLOT0(slot_nb_absolute, "__abs__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004460
4461static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00004462slot_nb_bool(PyObject *self)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004463{
Tim Petersea7f75d2002-12-07 21:39:16 +00004464 PyObject *func, *args;
Jack Diederich4dafcc42006-11-28 19:15:13 +00004465 static PyObject *bool_str, *len_str;
Tim Petersea7f75d2002-12-07 21:39:16 +00004466 int result = -1;
Jack Diederich4dafcc42006-11-28 19:15:13 +00004467 int from_len = 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004468
Jack Diederich4dafcc42006-11-28 19:15:13 +00004469 func = lookup_maybe(self, "__bool__", &bool_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004470 if (func == NULL) {
Guido van Rossum55f20992001-10-01 17:18:22 +00004471 if (PyErr_Occurred())
Guido van Rossumb8f63662001-08-15 23:57:02 +00004472 return -1;
Guido van Rossum55f20992001-10-01 17:18:22 +00004473 func = lookup_maybe(self, "__len__", &len_str);
Tim Petersea7f75d2002-12-07 21:39:16 +00004474 if (func == NULL)
4475 return PyErr_Occurred() ? -1 : 1;
Jack Diederich4dafcc42006-11-28 19:15:13 +00004476 from_len = 1;
Tim Petersea7f75d2002-12-07 21:39:16 +00004477 }
4478 args = PyTuple_New(0);
4479 if (args != NULL) {
4480 PyObject *temp = PyObject_Call(func, args, NULL);
4481 Py_DECREF(args);
4482 if (temp != NULL) {
Jack Diederich4dafcc42006-11-28 19:15:13 +00004483 if (from_len) {
4484 /* enforced by slot_nb_len */
Jeremy Hylton090a3492003-06-27 16:46:45 +00004485 result = PyObject_IsTrue(temp);
Jack Diederich4dafcc42006-11-28 19:15:13 +00004486 }
4487 else if (PyBool_Check(temp)) {
4488 result = PyObject_IsTrue(temp);
4489 }
Jeremy Hylton090a3492003-06-27 16:46:45 +00004490 else {
4491 PyErr_Format(PyExc_TypeError,
Jack Diederich4dafcc42006-11-28 19:15:13 +00004492 "__bool__ should return "
4493 "bool, returned %s",
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00004494 Py_Type(temp)->tp_name);
Jeremy Hylton3e3159c2003-06-27 17:38:27 +00004495 result = -1;
Jeremy Hylton090a3492003-06-27 16:46:45 +00004496 }
Tim Petersea7f75d2002-12-07 21:39:16 +00004497 Py_DECREF(temp);
Guido van Rossum55f20992001-10-01 17:18:22 +00004498 }
Guido van Rossumb8f63662001-08-15 23:57:02 +00004499 }
Guido van Rossum55f20992001-10-01 17:18:22 +00004500 Py_DECREF(func);
Tim Petersea7f75d2002-12-07 21:39:16 +00004501 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004502}
4503
Guido van Rossum38fff8c2006-03-07 18:50:55 +00004504
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00004505static PyObject *
Guido van Rossum38fff8c2006-03-07 18:50:55 +00004506slot_nb_index(PyObject *self)
4507{
Guido van Rossum38fff8c2006-03-07 18:50:55 +00004508 static PyObject *index_str;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00004509 return call_method(self, "__index__", &index_str, "()");
Guido van Rossum38fff8c2006-03-07 18:50:55 +00004510}
4511
4512
Guido van Rossumdc91b992001-08-08 22:26:22 +00004513SLOT0(slot_nb_invert, "__invert__")
4514SLOT1BIN(slot_nb_lshift, nb_lshift, "__lshift__", "__rlshift__")
4515SLOT1BIN(slot_nb_rshift, nb_rshift, "__rshift__", "__rrshift__")
4516SLOT1BIN(slot_nb_and, nb_and, "__and__", "__rand__")
4517SLOT1BIN(slot_nb_xor, nb_xor, "__xor__", "__rxor__")
4518SLOT1BIN(slot_nb_or, nb_or, "__or__", "__ror__")
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004519
Guido van Rossumdc91b992001-08-08 22:26:22 +00004520SLOT0(slot_nb_int, "__int__")
4521SLOT0(slot_nb_long, "__long__")
4522SLOT0(slot_nb_float, "__float__")
Guido van Rossumdc91b992001-08-08 22:26:22 +00004523SLOT1(slot_nb_inplace_add, "__iadd__", PyObject *, "O")
4524SLOT1(slot_nb_inplace_subtract, "__isub__", PyObject *, "O")
4525SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *, "O")
Guido van Rossumdc91b992001-08-08 22:26:22 +00004526SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *, "O")
Thomas Wouterscf297e42007-02-23 15:07:44 +00004527/* Can't use SLOT1 here, because nb_inplace_power is ternary */
4528static PyObject *
4529slot_nb_inplace_power(PyObject *self, PyObject * arg1, PyObject *arg2)
4530{
4531 static PyObject *cache_str;
4532 return call_method(self, "__ipow__", &cache_str, "(" "O" ")", arg1);
4533}
Guido van Rossumdc91b992001-08-08 22:26:22 +00004534SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *, "O")
4535SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *, "O")
4536SLOT1(slot_nb_inplace_and, "__iand__", PyObject *, "O")
4537SLOT1(slot_nb_inplace_xor, "__ixor__", PyObject *, "O")
4538SLOT1(slot_nb_inplace_or, "__ior__", PyObject *, "O")
4539SLOT1BIN(slot_nb_floor_divide, nb_floor_divide,
4540 "__floordiv__", "__rfloordiv__")
4541SLOT1BIN(slot_nb_true_divide, nb_true_divide, "__truediv__", "__rtruediv__")
4542SLOT1(slot_nb_inplace_floor_divide, "__ifloordiv__", PyObject *, "O")
4543SLOT1(slot_nb_inplace_true_divide, "__itruediv__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004544
4545static int
Guido van Rossumb8f63662001-08-15 23:57:02 +00004546half_compare(PyObject *self, PyObject *other)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004547{
Guido van Rossumb8f63662001-08-15 23:57:02 +00004548 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004549 static PyObject *cmp_str;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004550 Py_ssize_t c;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004551
Guido van Rossum60718732001-08-28 17:47:51 +00004552 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004553 if (func == NULL) {
4554 PyErr_Clear();
4555 }
4556 else {
Raymond Hettinger8ae46892003-10-12 19:09:37 +00004557 args = PyTuple_Pack(1, other);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004558 if (args == NULL)
4559 res = NULL;
4560 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00004561 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004562 Py_DECREF(args);
4563 }
Raymond Hettingerab5dae32002-06-24 13:08:16 +00004564 Py_DECREF(func);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004565 if (res != Py_NotImplemented) {
4566 if (res == NULL)
4567 return -2;
4568 c = PyInt_AsLong(res);
4569 Py_DECREF(res);
4570 if (c == -1 && PyErr_Occurred())
4571 return -2;
4572 return (c < 0) ? -1 : (c > 0) ? 1 : 0;
4573 }
4574 Py_DECREF(res);
4575 }
4576 return 2;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004577}
4578
Guido van Rossumab3b0342001-09-18 20:38:53 +00004579/* This slot is published for the benefit of try_3way_compare in object.c */
4580int
4581_PyObject_SlotCompare(PyObject *self, PyObject *other)
Guido van Rossumb8f63662001-08-15 23:57:02 +00004582{
4583 int c;
4584
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00004585 if (Py_Type(self)->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00004586 c = half_compare(self, other);
4587 if (c <= 1)
4588 return c;
4589 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00004590 if (Py_Type(other)->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00004591 c = half_compare(other, self);
4592 if (c < -1)
4593 return -2;
4594 if (c <= 1)
4595 return -c;
4596 }
4597 return (void *)self < (void *)other ? -1 :
4598 (void *)self > (void *)other ? 1 : 0;
4599}
4600
4601static PyObject *
4602slot_tp_repr(PyObject *self)
4603{
4604 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004605 static PyObject *repr_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004606
Guido van Rossum60718732001-08-28 17:47:51 +00004607 func = lookup_method(self, "__repr__", &repr_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004608 if (func != NULL) {
4609 res = PyEval_CallObject(func, NULL);
4610 Py_DECREF(func);
4611 return res;
4612 }
Barry Warsaw7ce36942001-08-24 18:34:26 +00004613 PyErr_Clear();
Walter Dörwald1ab83302007-05-18 17:15:44 +00004614 return PyUnicode_FromFormat("<%s object at %p>",
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00004615 Py_Type(self)->tp_name, self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004616}
4617
4618static PyObject *
4619slot_tp_str(PyObject *self)
4620{
4621 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004622 static PyObject *str_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004623
Guido van Rossum60718732001-08-28 17:47:51 +00004624 func = lookup_method(self, "__str__", &str_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004625 if (func != NULL) {
4626 res = PyEval_CallObject(func, NULL);
4627 Py_DECREF(func);
4628 return res;
4629 }
4630 else {
Walter Dörwald1ab83302007-05-18 17:15:44 +00004631 PyObject *ress;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004632 PyErr_Clear();
Walter Dörwald1ab83302007-05-18 17:15:44 +00004633 res = slot_tp_repr(self);
4634 if (!res)
4635 return NULL;
4636 ress = _PyUnicode_AsDefaultEncodedString(res, NULL);
4637 Py_DECREF(res);
4638 return ress;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004639 }
4640}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004641
4642static long
4643slot_tp_hash(PyObject *self)
4644{
Guido van Rossum4011a242006-08-17 23:09:57 +00004645 PyObject *func, *res;
Guido van Rossum50e9fb92006-08-17 05:42:55 +00004646 static PyObject *hash_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004647 long h;
4648
Guido van Rossum60718732001-08-28 17:47:51 +00004649 func = lookup_method(self, "__hash__", &hash_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004650
Guido van Rossum50e9fb92006-08-17 05:42:55 +00004651 if (func == Py_None) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00004652 Py_DECREF(func);
Guido van Rossum50e9fb92006-08-17 05:42:55 +00004653 func = NULL;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004654 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +00004655
4656 if (func == NULL) {
Guido van Rossum50e9fb92006-08-17 05:42:55 +00004657 PyErr_Format(PyExc_TypeError, "unhashable type: '%.200s'",
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00004658 Py_Type(self)->tp_name);
Guido van Rossum50e9fb92006-08-17 05:42:55 +00004659 return -1;
4660 }
4661
Guido van Rossum4011a242006-08-17 23:09:57 +00004662 res = PyEval_CallObject(func, NULL);
Guido van Rossum50e9fb92006-08-17 05:42:55 +00004663 Py_DECREF(func);
4664 if (res == NULL)
4665 return -1;
4666 if (PyLong_Check(res))
4667 h = PyLong_Type.tp_hash(res);
4668 else
4669 h = PyInt_AsLong(res);
4670 Py_DECREF(res);
4671 if (h == -1 && !PyErr_Occurred())
4672 h = -2;
4673 return h;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004674}
4675
4676static PyObject *
4677slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds)
4678{
Guido van Rossum60718732001-08-28 17:47:51 +00004679 static PyObject *call_str;
4680 PyObject *meth = lookup_method(self, "__call__", &call_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004681 PyObject *res;
4682
4683 if (meth == NULL)
4684 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004685
4686 /* PyObject_Call() will end up calling slot_tp_call() again if
4687 the object returned for __call__ has __call__ itself defined
4688 upon it. This can be an infinite recursion if you set
4689 __call__ in a class to an instance of it. */
4690 if (Py_EnterRecursiveCall(" in __call__")) {
4691 Py_DECREF(meth);
4692 return NULL;
4693 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004694 res = PyObject_Call(meth, args, kwds);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004695 Py_LeaveRecursiveCall();
4696
Tim Peters6d6c1a32001-08-02 04:15:00 +00004697 Py_DECREF(meth);
4698 return res;
4699}
4700
Guido van Rossum14a6f832001-10-17 13:59:09 +00004701/* There are two slot dispatch functions for tp_getattro.
4702
4703 - slot_tp_getattro() is used when __getattribute__ is overridden
4704 but no __getattr__ hook is present;
4705
4706 - slot_tp_getattr_hook() is used when a __getattr__ hook is present.
4707
Guido van Rossumc334df52002-04-04 23:44:47 +00004708 The code in update_one_slot() always installs slot_tp_getattr_hook(); this
4709 detects the absence of __getattr__ and then installs the simpler slot if
4710 necessary. */
Guido van Rossum14a6f832001-10-17 13:59:09 +00004711
Tim Peters6d6c1a32001-08-02 04:15:00 +00004712static PyObject *
4713slot_tp_getattro(PyObject *self, PyObject *name)
4714{
Guido van Rossum14a6f832001-10-17 13:59:09 +00004715 static PyObject *getattribute_str = NULL;
4716 return call_method(self, "__getattribute__", &getattribute_str,
4717 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004718}
4719
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004720static PyObject *
4721slot_tp_getattr_hook(PyObject *self, PyObject *name)
4722{
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00004723 PyTypeObject *tp = Py_Type(self);
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004724 PyObject *getattr, *getattribute, *res;
4725 static PyObject *getattribute_str = NULL;
4726 static PyObject *getattr_str = NULL;
4727
4728 if (getattr_str == NULL) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00004729 getattr_str = PyUnicode_InternFromString("__getattr__");
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004730 if (getattr_str == NULL)
4731 return NULL;
4732 }
4733 if (getattribute_str == NULL) {
4734 getattribute_str =
Martin v. Löwis5b222132007-06-10 09:51:05 +00004735 PyUnicode_InternFromString("__getattribute__");
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004736 if (getattribute_str == NULL)
4737 return NULL;
4738 }
4739 getattr = _PyType_Lookup(tp, getattr_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00004740 if (getattr == NULL) {
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004741 /* No __getattr__ hook: use a simpler dispatcher */
4742 tp->tp_getattro = slot_tp_getattro;
4743 return slot_tp_getattro(self, name);
4744 }
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004745 getattribute = _PyType_Lookup(tp, getattribute_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00004746 if (getattribute == NULL ||
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00004747 (Py_Type(getattribute) == &PyWrapperDescr_Type &&
Guido van Rossum14a6f832001-10-17 13:59:09 +00004748 ((PyWrapperDescrObject *)getattribute)->d_wrapped ==
4749 (void *)PyObject_GenericGetAttr))
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004750 res = PyObject_GenericGetAttr(self, name);
4751 else
Thomas Wouters477c8d52006-05-27 19:21:47 +00004752 res = PyObject_CallFunctionObjArgs(getattribute, self, name, NULL);
Guido van Rossum14a6f832001-10-17 13:59:09 +00004753 if (res == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) {
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004754 PyErr_Clear();
Thomas Wouters477c8d52006-05-27 19:21:47 +00004755 res = PyObject_CallFunctionObjArgs(getattr, self, name, NULL);
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004756 }
4757 return res;
4758}
4759
Tim Peters6d6c1a32001-08-02 04:15:00 +00004760static int
4761slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value)
4762{
4763 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004764 static PyObject *delattr_str, *setattr_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004765
4766 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004767 res = call_method(self, "__delattr__", &delattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004768 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004769 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004770 res = call_method(self, "__setattr__", &setattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004771 "(OO)", name, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004772 if (res == NULL)
4773 return -1;
4774 Py_DECREF(res);
4775 return 0;
4776}
4777
Tim Peters6d6c1a32001-08-02 04:15:00 +00004778static PyObject *
Guido van Rossumb8f63662001-08-15 23:57:02 +00004779half_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004780{
Guido van Rossumb8f63662001-08-15 23:57:02 +00004781 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004782 static PyObject *op_str[6];
Tim Peters6d6c1a32001-08-02 04:15:00 +00004783
Guido van Rossum60718732001-08-28 17:47:51 +00004784 func = lookup_method(self, name_op[op], &op_str[op]);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004785 if (func == NULL) {
4786 PyErr_Clear();
4787 Py_INCREF(Py_NotImplemented);
4788 return Py_NotImplemented;
4789 }
Raymond Hettinger8ae46892003-10-12 19:09:37 +00004790 args = PyTuple_Pack(1, other);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004791 if (args == NULL)
4792 res = NULL;
4793 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00004794 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004795 Py_DECREF(args);
4796 }
4797 Py_DECREF(func);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004798 return res;
4799}
4800
Guido van Rossumb8f63662001-08-15 23:57:02 +00004801static PyObject *
4802slot_tp_richcompare(PyObject *self, PyObject *other, int op)
4803{
4804 PyObject *res;
4805
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00004806 if (Py_Type(self)->tp_richcompare == slot_tp_richcompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00004807 res = half_richcompare(self, other, op);
4808 if (res != Py_NotImplemented)
4809 return res;
4810 Py_DECREF(res);
4811 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00004812 if (Py_Type(other)->tp_richcompare == slot_tp_richcompare) {
Tim Petersf4aca752004-09-23 02:39:37 +00004813 res = half_richcompare(other, self, _Py_SwappedOp[op]);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004814 if (res != Py_NotImplemented) {
4815 return res;
4816 }
4817 Py_DECREF(res);
4818 }
4819 Py_INCREF(Py_NotImplemented);
4820 return Py_NotImplemented;
4821}
4822
4823static PyObject *
4824slot_tp_iter(PyObject *self)
4825{
4826 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004827 static PyObject *iter_str, *getitem_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004828
Guido van Rossum60718732001-08-28 17:47:51 +00004829 func = lookup_method(self, "__iter__", &iter_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004830 if (func != NULL) {
Guido van Rossum84b2bed2002-08-16 17:01:09 +00004831 PyObject *args;
4832 args = res = PyTuple_New(0);
4833 if (args != NULL) {
4834 res = PyObject_Call(func, args, NULL);
4835 Py_DECREF(args);
4836 }
4837 Py_DECREF(func);
4838 return res;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004839 }
4840 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00004841 func = lookup_method(self, "__getitem__", &getitem_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004842 if (func == NULL) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004843 PyErr_Format(PyExc_TypeError,
4844 "'%.200s' object is not iterable",
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00004845 Py_Type(self)->tp_name);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004846 return NULL;
4847 }
4848 Py_DECREF(func);
4849 return PySeqIter_New(self);
4850}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004851
4852static PyObject *
4853slot_tp_iternext(PyObject *self)
4854{
Guido van Rossum2730b132001-08-28 18:22:14 +00004855 static PyObject *next_str;
Georg Brandla18af4e2007-04-21 15:47:16 +00004856 return call_method(self, "__next__", &next_str, "()");
Tim Peters6d6c1a32001-08-02 04:15:00 +00004857}
4858
Guido van Rossum1a493502001-08-17 16:47:50 +00004859static PyObject *
4860slot_tp_descr_get(PyObject *self, PyObject *obj, PyObject *type)
4861{
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00004862 PyTypeObject *tp = Py_Type(self);
Guido van Rossum1a493502001-08-17 16:47:50 +00004863 PyObject *get;
4864 static PyObject *get_str = NULL;
4865
4866 if (get_str == NULL) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00004867 get_str = PyUnicode_InternFromString("__get__");
Guido van Rossum1a493502001-08-17 16:47:50 +00004868 if (get_str == NULL)
4869 return NULL;
4870 }
4871 get = _PyType_Lookup(tp, get_str);
4872 if (get == NULL) {
4873 /* Avoid further slowdowns */
4874 if (tp->tp_descr_get == slot_tp_descr_get)
4875 tp->tp_descr_get = NULL;
4876 Py_INCREF(self);
4877 return self;
4878 }
Guido van Rossum2c252392001-08-24 10:13:31 +00004879 if (obj == NULL)
4880 obj = Py_None;
4881 if (type == NULL)
4882 type = Py_None;
Thomas Wouters477c8d52006-05-27 19:21:47 +00004883 return PyObject_CallFunctionObjArgs(get, self, obj, type, NULL);
Guido van Rossum1a493502001-08-17 16:47:50 +00004884}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004885
4886static int
4887slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value)
4888{
Guido van Rossum2c252392001-08-24 10:13:31 +00004889 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004890 static PyObject *del_str, *set_str;
Guido van Rossum2c252392001-08-24 10:13:31 +00004891
4892 if (value == NULL)
Guido van Rossum1d5b3f22001-12-03 00:08:33 +00004893 res = call_method(self, "__delete__", &del_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004894 "(O)", target);
Guido van Rossum2c252392001-08-24 10:13:31 +00004895 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004896 res = call_method(self, "__set__", &set_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004897 "(OO)", target, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004898 if (res == NULL)
4899 return -1;
4900 Py_DECREF(res);
4901 return 0;
4902}
4903
4904static int
4905slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds)
4906{
Guido van Rossum60718732001-08-28 17:47:51 +00004907 static PyObject *init_str;
4908 PyObject *meth = lookup_method(self, "__init__", &init_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004909 PyObject *res;
4910
4911 if (meth == NULL)
4912 return -1;
4913 res = PyObject_Call(meth, args, kwds);
4914 Py_DECREF(meth);
4915 if (res == NULL)
4916 return -1;
Raymond Hettingerb67cc802005-03-03 16:45:19 +00004917 if (res != Py_None) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004918 PyErr_Format(PyExc_TypeError,
4919 "__init__() should return None, not '%.200s'",
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00004920 Py_Type(res)->tp_name);
Raymond Hettingerb67cc802005-03-03 16:45:19 +00004921 Py_DECREF(res);
4922 return -1;
4923 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004924 Py_DECREF(res);
4925 return 0;
4926}
4927
4928static PyObject *
4929slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
4930{
Guido van Rossum7bed2132002-08-08 21:57:53 +00004931 static PyObject *new_str;
4932 PyObject *func;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004933 PyObject *newargs, *x;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004934 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004935
Guido van Rossum7bed2132002-08-08 21:57:53 +00004936 if (new_str == NULL) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00004937 new_str = PyUnicode_InternFromString("__new__");
Guido van Rossum7bed2132002-08-08 21:57:53 +00004938 if (new_str == NULL)
4939 return NULL;
4940 }
4941 func = PyObject_GetAttr((PyObject *)type, new_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004942 if (func == NULL)
4943 return NULL;
4944 assert(PyTuple_Check(args));
4945 n = PyTuple_GET_SIZE(args);
4946 newargs = PyTuple_New(n+1);
4947 if (newargs == NULL)
4948 return NULL;
4949 Py_INCREF(type);
4950 PyTuple_SET_ITEM(newargs, 0, (PyObject *)type);
4951 for (i = 0; i < n; i++) {
4952 x = PyTuple_GET_ITEM(args, i);
4953 Py_INCREF(x);
4954 PyTuple_SET_ITEM(newargs, i+1, x);
4955 }
4956 x = PyObject_Call(func, newargs, kwds);
Guido van Rossum25d18072001-10-01 15:55:28 +00004957 Py_DECREF(newargs);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004958 Py_DECREF(func);
4959 return x;
4960}
4961
Guido van Rossumfebd61d2002-08-08 20:55:20 +00004962static void
4963slot_tp_del(PyObject *self)
4964{
4965 static PyObject *del_str = NULL;
4966 PyObject *del, *res;
4967 PyObject *error_type, *error_value, *error_traceback;
4968
4969 /* Temporarily resurrect the object. */
4970 assert(self->ob_refcnt == 0);
4971 self->ob_refcnt = 1;
4972
4973 /* Save the current exception, if any. */
4974 PyErr_Fetch(&error_type, &error_value, &error_traceback);
4975
4976 /* Execute __del__ method, if any. */
4977 del = lookup_maybe(self, "__del__", &del_str);
4978 if (del != NULL) {
4979 res = PyEval_CallObject(del, NULL);
4980 if (res == NULL)
4981 PyErr_WriteUnraisable(del);
4982 else
4983 Py_DECREF(res);
4984 Py_DECREF(del);
4985 }
4986
4987 /* Restore the saved exception. */
4988 PyErr_Restore(error_type, error_value, error_traceback);
4989
4990 /* Undo the temporary resurrection; can't use DECREF here, it would
4991 * cause a recursive call.
4992 */
4993 assert(self->ob_refcnt > 0);
4994 if (--self->ob_refcnt == 0)
4995 return; /* this is the normal path out */
4996
4997 /* __del__ resurrected it! Make it look like the original Py_DECREF
4998 * never happened.
4999 */
5000 {
Martin v. Löwis725507b2006-03-07 12:08:51 +00005001 Py_ssize_t refcnt = self->ob_refcnt;
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005002 _Py_NewReference(self);
5003 self->ob_refcnt = refcnt;
5004 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00005005 assert(!PyType_IS_GC(Py_Type(self)) ||
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005006 _Py_AS_GC(self)->gc.gc_refs != _PyGC_REFS_UNTRACKED);
Michael W. Hudson3f3b6682004-08-03 10:21:03 +00005007 /* If Py_REF_DEBUG, _Py_NewReference bumped _Py_RefTotal, so
5008 * we need to undo that. */
5009 _Py_DEC_REFTOTAL;
5010 /* If Py_TRACE_REFS, _Py_NewReference re-added self to the object
5011 * chain, so no more to do there.
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005012 * If COUNT_ALLOCS, the original decref bumped tp_frees, and
5013 * _Py_NewReference bumped tp_allocs: both of those need to be
5014 * undone.
5015 */
5016#ifdef COUNT_ALLOCS
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00005017 --Py_Type(self)->tp_frees;
5018 --Py_Type(self)->tp_allocs;
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005019#endif
5020}
5021
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005022
5023/* Table mapping __foo__ names to tp_foo offsets and slot_tp_foo wrapper
Tim Petersbf9b2442003-03-23 05:35:36 +00005024 functions. The offsets here are relative to the 'PyHeapTypeObject'
Guido van Rossume5c691a2003-03-07 15:13:17 +00005025 structure, which incorporates the additional structures used for numbers,
5026 sequences and mappings.
5027 Note that multiple names may map to the same slot (e.g. __eq__,
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005028 __ne__ etc. all map to tp_richcompare) and one name may map to multiple
Guido van Rossumc334df52002-04-04 23:44:47 +00005029 slots (e.g. __str__ affects tp_str as well as tp_repr). The table is
5030 terminated with an all-zero entry. (This table is further initialized and
5031 sorted in init_slotdefs() below.) */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005032
Guido van Rossum6d204072001-10-21 00:44:31 +00005033typedef struct wrapperbase slotdef;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005034
5035#undef TPSLOT
Guido van Rossumc8e56452001-10-22 00:43:43 +00005036#undef FLSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005037#undef ETSLOT
5038#undef SQSLOT
5039#undef MPSLOT
5040#undef NBSLOT
Guido van Rossum6d204072001-10-21 00:44:31 +00005041#undef UNSLOT
5042#undef IBSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005043#undef BINSLOT
5044#undef RBINSLOT
5045
Guido van Rossum6d204072001-10-21 00:44:31 +00005046#define TPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Neal Norwitzd47714a2002-08-13 19:01:38 +00005047 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
5048 PyDoc_STR(DOC)}
Guido van Rossumc8e56452001-10-22 00:43:43 +00005049#define FLSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC, FLAGS) \
5050 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
Neal Norwitzd47714a2002-08-13 19:01:38 +00005051 PyDoc_STR(DOC), FLAGS}
Guido van Rossum6d204072001-10-21 00:44:31 +00005052#define ETSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Guido van Rossume5c691a2003-03-07 15:13:17 +00005053 {NAME, offsetof(PyHeapTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
Neal Norwitzd47714a2002-08-13 19:01:38 +00005054 PyDoc_STR(DOC)}
Guido van Rossum6d204072001-10-21 00:44:31 +00005055#define SQSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
5056 ETSLOT(NAME, as_sequence.SLOT, FUNCTION, WRAPPER, DOC)
5057#define MPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
5058 ETSLOT(NAME, as_mapping.SLOT, FUNCTION, WRAPPER, DOC)
5059#define NBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
5060 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, DOC)
5061#define UNSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
5062 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
5063 "x." NAME "() <==> " DOC)
5064#define IBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
5065 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
5066 "x." NAME "(y) <==> x" DOC "y")
5067#define BINSLOT(NAME, SLOT, FUNCTION, DOC) \
5068 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
5069 "x." NAME "(y) <==> x" DOC "y")
5070#define RBINSLOT(NAME, SLOT, FUNCTION, DOC) \
5071 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
5072 "x." NAME "(y) <==> y" DOC "x")
Anthony Baxter56616992005-06-03 14:12:21 +00005073#define BINSLOTNOTINFIX(NAME, SLOT, FUNCTION, DOC) \
5074 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
5075 "x." NAME "(y) <==> " DOC)
5076#define RBINSLOTNOTINFIX(NAME, SLOT, FUNCTION, DOC) \
5077 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
5078 "x." NAME "(y) <==> " DOC)
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005079
5080static slotdef slotdefs[] = {
Martin v. Löwis18e16552006-02-15 17:27:45 +00005081 SQSLOT("__len__", sq_length, slot_sq_length, wrap_lenfunc,
Guido van Rossum6d204072001-10-21 00:44:31 +00005082 "x.__len__() <==> len(x)"),
Armin Rigofd163f92005-12-29 15:59:19 +00005083 /* Heap types defining __add__/__mul__ have sq_concat/sq_repeat == NULL.
5084 The logic in abstract.c always falls back to nb_add/nb_multiply in
5085 this case. Defining both the nb_* and the sq_* slots to call the
5086 user-defined methods has unexpected side-effects, as shown by
5087 test_descr.notimplemented() */
5088 SQSLOT("__add__", sq_concat, NULL, wrap_binaryfunc,
Guido van Rossumd8faa362007-04-27 19:54:29 +00005089 "x.__add__(y) <==> x+y"),
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00005090 SQSLOT("__mul__", sq_repeat, NULL, wrap_indexargfunc,
Guido van Rossumd8faa362007-04-27 19:54:29 +00005091 "x.__mul__(n) <==> x*n"),
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00005092 SQSLOT("__rmul__", sq_repeat, NULL, wrap_indexargfunc,
Guido van Rossumd8faa362007-04-27 19:54:29 +00005093 "x.__rmul__(n) <==> n*x"),
Guido van Rossum6d204072001-10-21 00:44:31 +00005094 SQSLOT("__getitem__", sq_item, slot_sq_item, wrap_sq_item,
5095 "x.__getitem__(y) <==> x[y]"),
Martin v. Löwis18e16552006-02-15 17:27:45 +00005096 SQSLOT("__getslice__", sq_slice, slot_sq_slice, wrap_ssizessizeargfunc,
Brett Cannon154da9b2003-05-20 02:30:04 +00005097 "x.__getslice__(i, j) <==> x[i:j]\n\
Guido van Rossumd8faa362007-04-27 19:54:29 +00005098 \n\
5099 Use of negative indices is not supported."),
Guido van Rossum6d204072001-10-21 00:44:31 +00005100 SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_setitem,
Brett Cannonbe67d872003-05-20 02:40:12 +00005101 "x.__setitem__(i, y) <==> x[i]=y"),
Guido van Rossum6d204072001-10-21 00:44:31 +00005102 SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_delitem,
Brett Cannonbe67d872003-05-20 02:40:12 +00005103 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005104 SQSLOT("__setslice__", sq_ass_slice, slot_sq_ass_slice,
Martin v. Löwis18e16552006-02-15 17:27:45 +00005105 wrap_ssizessizeobjargproc,
Brett Cannonbe67d872003-05-20 02:40:12 +00005106 "x.__setslice__(i, j, y) <==> x[i:j]=y\n\
Guido van Rossumd8faa362007-04-27 19:54:29 +00005107 \n\
5108 Use of negative indices is not supported."),
Guido van Rossum6d204072001-10-21 00:44:31 +00005109 SQSLOT("__delslice__", sq_ass_slice, slot_sq_ass_slice, wrap_delslice,
Brett Cannonbe67d872003-05-20 02:40:12 +00005110 "x.__delslice__(i, j) <==> del x[i:j]\n\
Guido van Rossumd8faa362007-04-27 19:54:29 +00005111 \n\
5112 Use of negative indices is not supported."),
Guido van Rossum6d204072001-10-21 00:44:31 +00005113 SQSLOT("__contains__", sq_contains, slot_sq_contains, wrap_objobjproc,
5114 "x.__contains__(y) <==> y in x"),
Armin Rigofd163f92005-12-29 15:59:19 +00005115 SQSLOT("__iadd__", sq_inplace_concat, NULL,
Guido van Rossumd8faa362007-04-27 19:54:29 +00005116 wrap_binaryfunc, "x.__iadd__(y) <==> x+=y"),
Armin Rigofd163f92005-12-29 15:59:19 +00005117 SQSLOT("__imul__", sq_inplace_repeat, NULL,
Guido van Rossumd8faa362007-04-27 19:54:29 +00005118 wrap_indexargfunc, "x.__imul__(y) <==> x*=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005119
Martin v. Löwis18e16552006-02-15 17:27:45 +00005120 MPSLOT("__len__", mp_length, slot_mp_length, wrap_lenfunc,
Guido van Rossum6d204072001-10-21 00:44:31 +00005121 "x.__len__() <==> len(x)"),
Guido van Rossumfd38f8e2001-10-09 20:17:57 +00005122 MPSLOT("__getitem__", mp_subscript, slot_mp_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00005123 wrap_binaryfunc,
5124 "x.__getitem__(y) <==> x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005125 MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00005126 wrap_objobjargproc,
5127 "x.__setitem__(i, y) <==> x[i]=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005128 MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00005129 wrap_delitem,
5130 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005131
Guido van Rossum6d204072001-10-21 00:44:31 +00005132 BINSLOT("__add__", nb_add, slot_nb_add,
5133 "+"),
5134 RBINSLOT("__radd__", nb_add, slot_nb_add,
5135 "+"),
5136 BINSLOT("__sub__", nb_subtract, slot_nb_subtract,
5137 "-"),
5138 RBINSLOT("__rsub__", nb_subtract, slot_nb_subtract,
5139 "-"),
5140 BINSLOT("__mul__", nb_multiply, slot_nb_multiply,
5141 "*"),
5142 RBINSLOT("__rmul__", nb_multiply, slot_nb_multiply,
5143 "*"),
Guido van Rossum6d204072001-10-21 00:44:31 +00005144 BINSLOT("__mod__", nb_remainder, slot_nb_remainder,
5145 "%"),
5146 RBINSLOT("__rmod__", nb_remainder, slot_nb_remainder,
5147 "%"),
Anthony Baxter56616992005-06-03 14:12:21 +00005148 BINSLOTNOTINFIX("__divmod__", nb_divmod, slot_nb_divmod,
Guido van Rossum6d204072001-10-21 00:44:31 +00005149 "divmod(x, y)"),
Anthony Baxter56616992005-06-03 14:12:21 +00005150 RBINSLOTNOTINFIX("__rdivmod__", nb_divmod, slot_nb_divmod,
Guido van Rossum6d204072001-10-21 00:44:31 +00005151 "divmod(y, x)"),
5152 NBSLOT("__pow__", nb_power, slot_nb_power, wrap_ternaryfunc,
5153 "x.__pow__(y[, z]) <==> pow(x, y[, z])"),
5154 NBSLOT("__rpow__", nb_power, slot_nb_power, wrap_ternaryfunc_r,
5155 "y.__rpow__(x[, z]) <==> pow(x, y[, z])"),
5156 UNSLOT("__neg__", nb_negative, slot_nb_negative, wrap_unaryfunc, "-x"),
5157 UNSLOT("__pos__", nb_positive, slot_nb_positive, wrap_unaryfunc, "+x"),
5158 UNSLOT("__abs__", nb_absolute, slot_nb_absolute, wrap_unaryfunc,
5159 "abs(x)"),
Jack Diederich4dafcc42006-11-28 19:15:13 +00005160 UNSLOT("__bool__", nb_bool, slot_nb_bool, wrap_inquirypred,
Guido van Rossum6d204072001-10-21 00:44:31 +00005161 "x != 0"),
5162 UNSLOT("__invert__", nb_invert, slot_nb_invert, wrap_unaryfunc, "~x"),
5163 BINSLOT("__lshift__", nb_lshift, slot_nb_lshift, "<<"),
5164 RBINSLOT("__rlshift__", nb_lshift, slot_nb_lshift, "<<"),
5165 BINSLOT("__rshift__", nb_rshift, slot_nb_rshift, ">>"),
5166 RBINSLOT("__rrshift__", nb_rshift, slot_nb_rshift, ">>"),
5167 BINSLOT("__and__", nb_and, slot_nb_and, "&"),
5168 RBINSLOT("__rand__", nb_and, slot_nb_and, "&"),
5169 BINSLOT("__xor__", nb_xor, slot_nb_xor, "^"),
5170 RBINSLOT("__rxor__", nb_xor, slot_nb_xor, "^"),
5171 BINSLOT("__or__", nb_or, slot_nb_or, "|"),
5172 RBINSLOT("__ror__", nb_or, slot_nb_or, "|"),
Guido van Rossum6d204072001-10-21 00:44:31 +00005173 UNSLOT("__int__", nb_int, slot_nb_int, wrap_unaryfunc,
5174 "int(x)"),
5175 UNSLOT("__long__", nb_long, slot_nb_long, wrap_unaryfunc,
5176 "long(x)"),
5177 UNSLOT("__float__", nb_float, slot_nb_float, wrap_unaryfunc,
5178 "float(x)"),
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00005179 NBSLOT("__index__", nb_index, slot_nb_index, wrap_unaryfunc,
Guido van Rossum38fff8c2006-03-07 18:50:55 +00005180 "x[y:z] <==> x[y.__index__():z.__index__()]"),
Guido van Rossum6d204072001-10-21 00:44:31 +00005181 IBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add,
5182 wrap_binaryfunc, "+"),
5183 IBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract,
5184 wrap_binaryfunc, "-"),
5185 IBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply,
5186 wrap_binaryfunc, "*"),
Guido van Rossum6d204072001-10-21 00:44:31 +00005187 IBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder,
5188 wrap_binaryfunc, "%"),
5189 IBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power,
Guido van Rossum6e5680f2002-10-15 01:01:53 +00005190 wrap_binaryfunc, "**"),
Guido van Rossum6d204072001-10-21 00:44:31 +00005191 IBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift,
5192 wrap_binaryfunc, "<<"),
5193 IBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift,
5194 wrap_binaryfunc, ">>"),
5195 IBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and,
5196 wrap_binaryfunc, "&"),
5197 IBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor,
5198 wrap_binaryfunc, "^"),
5199 IBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or,
5200 wrap_binaryfunc, "|"),
5201 BINSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
5202 RBINSLOT("__rfloordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
5203 BINSLOT("__truediv__", nb_true_divide, slot_nb_true_divide, "/"),
5204 RBINSLOT("__rtruediv__", nb_true_divide, slot_nb_true_divide, "/"),
5205 IBSLOT("__ifloordiv__", nb_inplace_floor_divide,
5206 slot_nb_inplace_floor_divide, wrap_binaryfunc, "//"),
5207 IBSLOT("__itruediv__", nb_inplace_true_divide,
5208 slot_nb_inplace_true_divide, wrap_binaryfunc, "/"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005209
Guido van Rossum6d204072001-10-21 00:44:31 +00005210 TPSLOT("__str__", tp_str, slot_tp_str, wrap_unaryfunc,
5211 "x.__str__() <==> str(x)"),
5212 TPSLOT("__repr__", tp_repr, slot_tp_repr, wrap_unaryfunc,
5213 "x.__repr__() <==> repr(x)"),
5214 TPSLOT("__cmp__", tp_compare, _PyObject_SlotCompare, wrap_cmpfunc,
5215 "x.__cmp__(y) <==> cmp(x,y)"),
5216 TPSLOT("__hash__", tp_hash, slot_tp_hash, wrap_hashfunc,
5217 "x.__hash__() <==> hash(x)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00005218 FLSLOT("__call__", tp_call, slot_tp_call, (wrapperfunc)wrap_call,
5219 "x.__call__(...) <==> x(...)", PyWrapperFlag_KEYWORDS),
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005220 TPSLOT("__getattribute__", tp_getattro, slot_tp_getattr_hook,
Guido van Rossum6d204072001-10-21 00:44:31 +00005221 wrap_binaryfunc, "x.__getattribute__('name') <==> x.name"),
5222 TPSLOT("__getattribute__", tp_getattr, NULL, NULL, ""),
5223 TPSLOT("__getattr__", tp_getattro, slot_tp_getattr_hook, NULL, ""),
5224 TPSLOT("__getattr__", tp_getattr, NULL, NULL, ""),
5225 TPSLOT("__setattr__", tp_setattro, slot_tp_setattro, wrap_setattr,
5226 "x.__setattr__('name', value) <==> x.name = value"),
5227 TPSLOT("__setattr__", tp_setattr, NULL, NULL, ""),
5228 TPSLOT("__delattr__", tp_setattro, slot_tp_setattro, wrap_delattr,
5229 "x.__delattr__('name') <==> del x.name"),
5230 TPSLOT("__delattr__", tp_setattr, NULL, NULL, ""),
5231 TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare, richcmp_lt,
5232 "x.__lt__(y) <==> x<y"),
5233 TPSLOT("__le__", tp_richcompare, slot_tp_richcompare, richcmp_le,
5234 "x.__le__(y) <==> x<=y"),
5235 TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare, richcmp_eq,
5236 "x.__eq__(y) <==> x==y"),
5237 TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare, richcmp_ne,
5238 "x.__ne__(y) <==> x!=y"),
5239 TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare, richcmp_gt,
5240 "x.__gt__(y) <==> x>y"),
5241 TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare, richcmp_ge,
5242 "x.__ge__(y) <==> x>=y"),
5243 TPSLOT("__iter__", tp_iter, slot_tp_iter, wrap_unaryfunc,
5244 "x.__iter__() <==> iter(x)"),
Georg Brandla18af4e2007-04-21 15:47:16 +00005245 TPSLOT("__next__", tp_iternext, slot_tp_iternext, wrap_next,
5246 "x.__next__() <==> next(x)"),
Guido van Rossum6d204072001-10-21 00:44:31 +00005247 TPSLOT("__get__", tp_descr_get, slot_tp_descr_get, wrap_descr_get,
5248 "descr.__get__(obj[, type]) -> value"),
5249 TPSLOT("__set__", tp_descr_set, slot_tp_descr_set, wrap_descr_set,
5250 "descr.__set__(obj, value)"),
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00005251 TPSLOT("__delete__", tp_descr_set, slot_tp_descr_set,
5252 wrap_descr_delete, "descr.__delete__(obj)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00005253 FLSLOT("__init__", tp_init, slot_tp_init, (wrapperfunc)wrap_init,
Guido van Rossum6d204072001-10-21 00:44:31 +00005254 "x.__init__(...) initializes x; "
Guido van Rossumc8e56452001-10-22 00:43:43 +00005255 "see x.__class__.__doc__ for signature",
5256 PyWrapperFlag_KEYWORDS),
5257 TPSLOT("__new__", tp_new, slot_tp_new, NULL, ""),
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005258 TPSLOT("__del__", tp_del, slot_tp_del, NULL, ""),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005259 {NULL}
5260};
5261
Guido van Rossumc334df52002-04-04 23:44:47 +00005262/* Given a type pointer and an offset gotten from a slotdef entry, return a
Guido van Rossumd8faa362007-04-27 19:54:29 +00005263 pointer to the actual slot. This is not quite the same as simply adding
Guido van Rossumc334df52002-04-04 23:44:47 +00005264 the offset to the type pointer, since it takes care to indirect through the
5265 proper indirection pointer (as_buffer, etc.); it returns NULL if the
5266 indirection pointer is NULL. */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005267static void **
Martin v. Löwis18e16552006-02-15 17:27:45 +00005268slotptr(PyTypeObject *type, int ioffset)
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005269{
5270 char *ptr;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005271 long offset = ioffset;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005272
Guido van Rossume5c691a2003-03-07 15:13:17 +00005273 /* Note: this depends on the order of the members of PyHeapTypeObject! */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005274 assert(offset >= 0);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00005275 assert((size_t)offset < offsetof(PyHeapTypeObject, as_buffer));
5276 if ((size_t)offset >= offsetof(PyHeapTypeObject, as_sequence)) {
5277 ptr = (char *)type->tp_as_sequence;
Guido van Rossume5c691a2003-03-07 15:13:17 +00005278 offset -= offsetof(PyHeapTypeObject, as_sequence);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005279 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00005280 else if ((size_t)offset >= offsetof(PyHeapTypeObject, as_mapping)) {
5281 ptr = (char *)type->tp_as_mapping;
Guido van Rossume5c691a2003-03-07 15:13:17 +00005282 offset -= offsetof(PyHeapTypeObject, as_mapping);
Guido van Rossum09638c12002-06-13 19:17:46 +00005283 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00005284 else if ((size_t)offset >= offsetof(PyHeapTypeObject, as_number)) {
5285 ptr = (char *)type->tp_as_number;
Guido van Rossume5c691a2003-03-07 15:13:17 +00005286 offset -= offsetof(PyHeapTypeObject, as_number);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005287 }
5288 else {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00005289 ptr = (char *)type;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005290 }
5291 if (ptr != NULL)
5292 ptr += offset;
5293 return (void **)ptr;
5294}
Guido van Rossumf040ede2001-08-07 16:40:56 +00005295
Guido van Rossumc334df52002-04-04 23:44:47 +00005296/* Length of array of slotdef pointers used to store slots with the
5297 same __name__. There should be at most MAX_EQUIV-1 slotdef entries with
5298 the same __name__, for any __name__. Since that's a static property, it is
5299 appropriate to declare fixed-size arrays for this. */
5300#define MAX_EQUIV 10
5301
5302/* Return a slot pointer for a given name, but ONLY if the attribute has
5303 exactly one slot function. The name must be an interned string. */
5304static void **
5305resolve_slotdups(PyTypeObject *type, PyObject *name)
5306{
5307 /* XXX Maybe this could be optimized more -- but is it worth it? */
5308
5309 /* pname and ptrs act as a little cache */
5310 static PyObject *pname;
5311 static slotdef *ptrs[MAX_EQUIV];
5312 slotdef *p, **pp;
5313 void **res, **ptr;
5314
5315 if (pname != name) {
5316 /* Collect all slotdefs that match name into ptrs. */
5317 pname = name;
5318 pp = ptrs;
5319 for (p = slotdefs; p->name_strobj; p++) {
5320 if (p->name_strobj == name)
5321 *pp++ = p;
5322 }
5323 *pp = NULL;
5324 }
5325
5326 /* Look in all matching slots of the type; if exactly one of these has
Guido van Rossumd8faa362007-04-27 19:54:29 +00005327 a filled-in slot, return its value. Otherwise return NULL. */
Guido van Rossumc334df52002-04-04 23:44:47 +00005328 res = NULL;
5329 for (pp = ptrs; *pp; pp++) {
5330 ptr = slotptr(type, (*pp)->offset);
5331 if (ptr == NULL || *ptr == NULL)
5332 continue;
5333 if (res != NULL)
5334 return NULL;
5335 res = ptr;
5336 }
5337 return res;
5338}
5339
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005340/* Common code for update_slots_callback() and fixup_slot_dispatchers(). This
Guido van Rossumc334df52002-04-04 23:44:47 +00005341 does some incredibly complex thinking and then sticks something into the
5342 slot. (It sees if the adjacent slotdefs for the same slot have conflicting
5343 interests, and then stores a generic wrapper or a specific function into
5344 the slot.) Return a pointer to the next slotdef with a different offset,
5345 because that's convenient for fixup_slot_dispatchers(). */
5346static slotdef *
5347update_one_slot(PyTypeObject *type, slotdef *p)
5348{
5349 PyObject *descr;
5350 PyWrapperDescrObject *d;
5351 void *generic = NULL, *specific = NULL;
5352 int use_generic = 0;
5353 int offset = p->offset;
5354 void **ptr = slotptr(type, offset);
5355
5356 if (ptr == NULL) {
5357 do {
5358 ++p;
5359 } while (p->offset == offset);
5360 return p;
5361 }
5362 do {
5363 descr = _PyType_Lookup(type, p->name_strobj);
5364 if (descr == NULL)
5365 continue;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00005366 if (Py_Type(descr) == &PyWrapperDescr_Type) {
Guido van Rossumc334df52002-04-04 23:44:47 +00005367 void **tptr = resolve_slotdups(type, p->name_strobj);
5368 if (tptr == NULL || tptr == ptr)
5369 generic = p->function;
5370 d = (PyWrapperDescrObject *)descr;
5371 if (d->d_base->wrapper == p->wrapper &&
5372 PyType_IsSubtype(type, d->d_type))
5373 {
5374 if (specific == NULL ||
5375 specific == d->d_wrapped)
5376 specific = d->d_wrapped;
5377 else
5378 use_generic = 1;
5379 }
5380 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00005381 else if (Py_Type(descr) == &PyCFunction_Type &&
Guido van Rossum721f62e2002-08-09 02:14:34 +00005382 PyCFunction_GET_FUNCTION(descr) ==
5383 (PyCFunction)tp_new_wrapper &&
5384 strcmp(p->name, "__new__") == 0)
5385 {
5386 /* The __new__ wrapper is not a wrapper descriptor,
5387 so must be special-cased differently.
5388 If we don't do this, creating an instance will
5389 always use slot_tp_new which will look up
5390 __new__ in the MRO which will call tp_new_wrapper
5391 which will look through the base classes looking
5392 for a static base and call its tp_new (usually
5393 PyType_GenericNew), after performing various
5394 sanity checks and constructing a new argument
5395 list. Cut all that nonsense short -- this speeds
5396 up instance creation tremendously. */
Martin v. Löwisa94568a2003-05-10 07:36:56 +00005397 specific = (void *)type->tp_new;
Guido van Rossum721f62e2002-08-09 02:14:34 +00005398 /* XXX I'm not 100% sure that there isn't a hole
5399 in this reasoning that requires additional
5400 sanity checks. I'll buy the first person to
5401 point out a bug in this reasoning a beer. */
5402 }
Guido van Rossumc334df52002-04-04 23:44:47 +00005403 else {
5404 use_generic = 1;
5405 generic = p->function;
5406 }
5407 } while ((++p)->offset == offset);
5408 if (specific && !use_generic)
5409 *ptr = specific;
5410 else
5411 *ptr = generic;
5412 return p;
5413}
5414
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005415/* In the type, update the slots whose slotdefs are gathered in the pp array.
5416 This is a callback for update_subclasses(). */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005417static int
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005418update_slots_callback(PyTypeObject *type, void *data)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005419{
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005420 slotdef **pp = (slotdef **)data;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005421
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005422 for (; *pp; pp++)
Guido van Rossumc334df52002-04-04 23:44:47 +00005423 update_one_slot(type, *pp);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005424 return 0;
5425}
5426
Guido van Rossumc334df52002-04-04 23:44:47 +00005427/* Comparison function for qsort() to compare slotdefs by their offset, and
5428 for equal offset by their address (to force a stable sort). */
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005429static int
5430slotdef_cmp(const void *aa, const void *bb)
5431{
5432 const slotdef *a = (const slotdef *)aa, *b = (const slotdef *)bb;
5433 int c = a->offset - b->offset;
5434 if (c != 0)
5435 return c;
5436 else
Martin v. Löwis18e16552006-02-15 17:27:45 +00005437 /* Cannot use a-b, as this gives off_t,
5438 which may lose precision when converted to int. */
5439 return (a > b) ? 1 : (a < b) ? -1 : 0;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005440}
5441
Guido van Rossumc334df52002-04-04 23:44:47 +00005442/* Initialize the slotdefs table by adding interned string objects for the
5443 names and sorting the entries. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005444static void
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005445init_slotdefs(void)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005446{
5447 slotdef *p;
5448 static int initialized = 0;
5449
5450 if (initialized)
5451 return;
5452 for (p = slotdefs; p->name; p++) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00005453 p->name_strobj = PyUnicode_InternFromString(p->name);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005454 if (!p->name_strobj)
Guido van Rossumc334df52002-04-04 23:44:47 +00005455 Py_FatalError("Out of memory interning slotdef names");
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005456 }
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005457 qsort((void *)slotdefs, (size_t)(p-slotdefs), sizeof(slotdef),
5458 slotdef_cmp);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005459 initialized = 1;
5460}
5461
Guido van Rossumc334df52002-04-04 23:44:47 +00005462/* Update the slots after assignment to a class (type) attribute. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005463static int
5464update_slot(PyTypeObject *type, PyObject *name)
5465{
Guido van Rossumc334df52002-04-04 23:44:47 +00005466 slotdef *ptrs[MAX_EQUIV];
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005467 slotdef *p;
5468 slotdef **pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005469 int offset;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005470
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005471 init_slotdefs();
5472 pp = ptrs;
5473 for (p = slotdefs; p->name; p++) {
5474 /* XXX assume name is interned! */
5475 if (p->name_strobj == name)
5476 *pp++ = p;
5477 }
5478 *pp = NULL;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005479 for (pp = ptrs; *pp; pp++) {
5480 p = *pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005481 offset = p->offset;
5482 while (p > slotdefs && (p-1)->offset == offset)
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005483 --p;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005484 *pp = p;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005485 }
Guido van Rossumc334df52002-04-04 23:44:47 +00005486 if (ptrs[0] == NULL)
5487 return 0; /* Not an attribute that affects any slots */
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005488 return update_subclasses(type, name,
5489 update_slots_callback, (void *)ptrs);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005490}
5491
Guido van Rossumc334df52002-04-04 23:44:47 +00005492/* Store the proper functions in the slot dispatches at class (type)
5493 definition time, based upon which operations the class overrides in its
5494 dict. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00005495static void
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005496fixup_slot_dispatchers(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005497{
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005498 slotdef *p;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005499
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005500 init_slotdefs();
Guido van Rossumc334df52002-04-04 23:44:47 +00005501 for (p = slotdefs; p->name; )
5502 p = update_one_slot(type, p);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005503}
Guido van Rossum705f0f52001-08-24 16:47:00 +00005504
Michael W. Hudson98bbc492002-11-26 14:47:27 +00005505static void
5506update_all_slots(PyTypeObject* type)
5507{
5508 slotdef *p;
5509
5510 init_slotdefs();
5511 for (p = slotdefs; p->name; p++) {
5512 /* update_slot returns int but can't actually fail */
5513 update_slot(type, p->name_strobj);
5514 }
5515}
5516
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005517/* recurse_down_subclasses() and update_subclasses() are mutually
5518 recursive functions to call a callback for all subclasses,
5519 but refraining from recursing into subclasses that define 'name'. */
5520
5521static int
5522update_subclasses(PyTypeObject *type, PyObject *name,
5523 update_callback callback, void *data)
5524{
5525 if (callback(type, data) < 0)
5526 return -1;
5527 return recurse_down_subclasses(type, name, callback, data);
5528}
5529
5530static int
5531recurse_down_subclasses(PyTypeObject *type, PyObject *name,
5532 update_callback callback, void *data)
5533{
5534 PyTypeObject *subclass;
5535 PyObject *ref, *subclasses, *dict;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005536 Py_ssize_t i, n;
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005537
5538 subclasses = type->tp_subclasses;
5539 if (subclasses == NULL)
5540 return 0;
5541 assert(PyList_Check(subclasses));
5542 n = PyList_GET_SIZE(subclasses);
5543 for (i = 0; i < n; i++) {
5544 ref = PyList_GET_ITEM(subclasses, i);
5545 assert(PyWeakref_CheckRef(ref));
5546 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
5547 assert(subclass != NULL);
5548 if ((PyObject *)subclass == Py_None)
5549 continue;
5550 assert(PyType_Check(subclass));
5551 /* Avoid recursing down into unaffected classes */
5552 dict = subclass->tp_dict;
5553 if (dict != NULL && PyDict_Check(dict) &&
5554 PyDict_GetItem(dict, name) != NULL)
5555 continue;
5556 if (update_subclasses(subclass, name, callback, data) < 0)
5557 return -1;
5558 }
5559 return 0;
5560}
5561
Guido van Rossum6d204072001-10-21 00:44:31 +00005562/* This function is called by PyType_Ready() to populate the type's
5563 dictionary with method descriptors for function slots. For each
Guido van Rossum09638c12002-06-13 19:17:46 +00005564 function slot (like tp_repr) that's defined in the type, one or more
5565 corresponding descriptors are added in the type's tp_dict dictionary
Guido van Rossumd8faa362007-04-27 19:54:29 +00005566 under the appropriate name (like __repr__). Some function slots
Guido van Rossum09638c12002-06-13 19:17:46 +00005567 cause more than one descriptor to be added (for example, the nb_add
5568 slot adds both __add__ and __radd__ descriptors) and some function
5569 slots compete for the same descriptor (for example both sq_item and
5570 mp_subscript generate a __getitem__ descriptor).
5571
Guido van Rossumd8faa362007-04-27 19:54:29 +00005572 In the latter case, the first slotdef entry encoutered wins. Since
Tim Petersbf9b2442003-03-23 05:35:36 +00005573 slotdef entries are sorted by the offset of the slot in the
Guido van Rossume5c691a2003-03-07 15:13:17 +00005574 PyHeapTypeObject, this gives us some control over disambiguating
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005575 between competing slots: the members of PyHeapTypeObject are listed
5576 from most general to least general, so the most general slot is
5577 preferred. In particular, because as_mapping comes before as_sequence,
5578 for a type that defines both mp_subscript and sq_item, mp_subscript
5579 wins.
Guido van Rossum09638c12002-06-13 19:17:46 +00005580
5581 This only adds new descriptors and doesn't overwrite entries in
5582 tp_dict that were previously defined. The descriptors contain a
5583 reference to the C function they must call, so that it's safe if they
5584 are copied into a subtype's __dict__ and the subtype has a different
5585 C function in its slot -- calling the method defined by the
5586 descriptor will call the C function that was used to create it,
5587 rather than the C function present in the slot when it is called.
5588 (This is important because a subtype may have a C function in the
5589 slot that calls the method from the dictionary, and we want to avoid
5590 infinite recursion here.) */
Guido van Rossum6d204072001-10-21 00:44:31 +00005591
5592static int
5593add_operators(PyTypeObject *type)
5594{
5595 PyObject *dict = type->tp_dict;
5596 slotdef *p;
5597 PyObject *descr;
5598 void **ptr;
5599
5600 init_slotdefs();
5601 for (p = slotdefs; p->name; p++) {
5602 if (p->wrapper == NULL)
5603 continue;
5604 ptr = slotptr(type, p->offset);
5605 if (!ptr || !*ptr)
5606 continue;
5607 if (PyDict_GetItem(dict, p->name_strobj))
5608 continue;
5609 descr = PyDescr_NewWrapper(type, p, *ptr);
5610 if (descr == NULL)
5611 return -1;
5612 if (PyDict_SetItem(dict, p->name_strobj, descr) < 0)
5613 return -1;
5614 Py_DECREF(descr);
5615 }
5616 if (type->tp_new != NULL) {
5617 if (add_tp_new_wrapper(type) < 0)
5618 return -1;
5619 }
5620 return 0;
5621}
5622
Guido van Rossum705f0f52001-08-24 16:47:00 +00005623
5624/* Cooperative 'super' */
5625
5626typedef struct {
5627 PyObject_HEAD
Guido van Rossume705ef12001-08-29 15:47:06 +00005628 PyTypeObject *type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005629 PyObject *obj;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005630 PyTypeObject *obj_type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005631} superobject;
5632
Guido van Rossum6f799372001-09-20 20:46:19 +00005633static PyMemberDef super_members[] = {
5634 {"__thisclass__", T_OBJECT, offsetof(superobject, type), READONLY,
5635 "the class invoking super()"},
5636 {"__self__", T_OBJECT, offsetof(superobject, obj), READONLY,
5637 "the instance invoking super(); may be None"},
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005638 {"__self_class__", T_OBJECT, offsetof(superobject, obj_type), READONLY,
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +00005639 "the type of the instance invoking super(); may be None"},
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005640 {0}
5641};
5642
Guido van Rossum705f0f52001-08-24 16:47:00 +00005643static void
5644super_dealloc(PyObject *self)
5645{
5646 superobject *su = (superobject *)self;
5647
Guido van Rossum048eb752001-10-02 21:24:57 +00005648 _PyObject_GC_UNTRACK(self);
Guido van Rossum705f0f52001-08-24 16:47:00 +00005649 Py_XDECREF(su->obj);
5650 Py_XDECREF(su->type);
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005651 Py_XDECREF(su->obj_type);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00005652 Py_Type(self)->tp_free(self);
Guido van Rossum705f0f52001-08-24 16:47:00 +00005653}
5654
5655static PyObject *
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005656super_repr(PyObject *self)
5657{
5658 superobject *su = (superobject *)self;
5659
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005660 if (su->obj_type)
Walter Dörwald1ab83302007-05-18 17:15:44 +00005661 return PyUnicode_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00005662 "<super: <class '%s'>, <%s object>>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005663 su->type ? su->type->tp_name : "NULL",
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005664 su->obj_type->tp_name);
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005665 else
Walter Dörwald1ab83302007-05-18 17:15:44 +00005666 return PyUnicode_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00005667 "<super: <class '%s'>, NULL>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005668 su->type ? su->type->tp_name : "NULL");
5669}
5670
5671static PyObject *
Guido van Rossum705f0f52001-08-24 16:47:00 +00005672super_getattro(PyObject *self, PyObject *name)
5673{
5674 superobject *su = (superobject *)self;
Guido van Rossum76ba09f2003-04-16 19:40:58 +00005675 int skip = su->obj_type == NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005676
Guido van Rossum76ba09f2003-04-16 19:40:58 +00005677 if (!skip) {
5678 /* We want __class__ to return the class of the super object
5679 (i.e. super, or a subclass), not the class of su->obj. */
Martin v. Löwis5b222132007-06-10 09:51:05 +00005680 skip = (PyUnicode_Check(name) &&
5681 PyUnicode_GET_SIZE(name) == 9 &&
5682 PyUnicode_CompareWithASCIIString(name, "__class__") == 0);
Guido van Rossum76ba09f2003-04-16 19:40:58 +00005683 }
5684
5685 if (!skip) {
Tim Petersa91e9642001-11-14 23:32:33 +00005686 PyObject *mro, *res, *tmp, *dict;
Guido van Rossum155db9a2002-04-02 17:53:47 +00005687 PyTypeObject *starttype;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005688 descrgetfunc f;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005689 Py_ssize_t i, n;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005690
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005691 starttype = su->obj_type;
Guido van Rossum155db9a2002-04-02 17:53:47 +00005692 mro = starttype->tp_mro;
5693
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005694 if (mro == NULL)
5695 n = 0;
5696 else {
5697 assert(PyTuple_Check(mro));
5698 n = PyTuple_GET_SIZE(mro);
5699 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00005700 for (i = 0; i < n; i++) {
Guido van Rossume705ef12001-08-29 15:47:06 +00005701 if ((PyObject *)(su->type) == PyTuple_GET_ITEM(mro, i))
Guido van Rossum705f0f52001-08-24 16:47:00 +00005702 break;
5703 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00005704 i++;
5705 res = NULL;
5706 for (; i < n; i++) {
5707 tmp = PyTuple_GET_ITEM(mro, i);
Tim Petersa91e9642001-11-14 23:32:33 +00005708 if (PyType_Check(tmp))
5709 dict = ((PyTypeObject *)tmp)->tp_dict;
Tim Petersa91e9642001-11-14 23:32:33 +00005710 else
5711 continue;
5712 res = PyDict_GetItem(dict, name);
Guido van Rossum6cc5bb62003-04-16 20:01:36 +00005713 if (res != NULL) {
Guido van Rossum705f0f52001-08-24 16:47:00 +00005714 Py_INCREF(res);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00005715 f = Py_Type(res)->tp_descr_get;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005716 if (f != NULL) {
Phillip J. Eby91a968a2004-03-25 02:19:34 +00005717 tmp = f(res,
5718 /* Only pass 'obj' param if
5719 this is instance-mode super
5720 (See SF ID #743627)
5721 */
Hye-Shik Changff365c92004-03-25 16:37:03 +00005722 (su->obj == (PyObject *)
5723 su->obj_type
Phillip J. Eby91a968a2004-03-25 02:19:34 +00005724 ? (PyObject *)NULL
5725 : su->obj),
Guido van Rossumd4641072002-04-03 02:13:37 +00005726 (PyObject *)starttype);
Guido van Rossum705f0f52001-08-24 16:47:00 +00005727 Py_DECREF(res);
5728 res = tmp;
5729 }
5730 return res;
5731 }
5732 }
5733 }
5734 return PyObject_GenericGetAttr(self, name);
5735}
5736
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005737static PyTypeObject *
Guido van Rossum5b443c62001-12-03 15:38:28 +00005738supercheck(PyTypeObject *type, PyObject *obj)
5739{
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005740 /* Check that a super() call makes sense. Return a type object.
5741
5742 obj can be a new-style class, or an instance of one:
5743
Guido van Rossumd8faa362007-04-27 19:54:29 +00005744 - If it is a class, it must be a subclass of 'type'. This case is
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005745 used for class methods; the return value is obj.
5746
5747 - If it is an instance, it must be an instance of 'type'. This is
5748 the normal case; the return value is obj.__class__.
5749
5750 But... when obj is an instance, we want to allow for the case where
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00005751 Py_Type(obj) is not a subclass of type, but obj.__class__ is!
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005752 This will allow using super() with a proxy for obj.
5753 */
5754
Guido van Rossum8e80a722003-02-18 19:22:22 +00005755 /* Check for first bullet above (special case) */
5756 if (PyType_Check(obj) && PyType_IsSubtype((PyTypeObject *)obj, type)) {
5757 Py_INCREF(obj);
5758 return (PyTypeObject *)obj;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005759 }
Guido van Rossum8e80a722003-02-18 19:22:22 +00005760
5761 /* Normal case */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00005762 if (PyType_IsSubtype(Py_Type(obj), type)) {
5763 Py_INCREF(Py_Type(obj));
5764 return Py_Type(obj);
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005765 }
5766 else {
5767 /* Try the slow way */
5768 static PyObject *class_str = NULL;
5769 PyObject *class_attr;
5770
5771 if (class_str == NULL) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00005772 class_str = PyUnicode_FromString("__class__");
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005773 if (class_str == NULL)
5774 return NULL;
5775 }
5776
5777 class_attr = PyObject_GetAttr(obj, class_str);
5778
5779 if (class_attr != NULL &&
5780 PyType_Check(class_attr) &&
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00005781 (PyTypeObject *)class_attr != Py_Type(obj))
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005782 {
5783 int ok = PyType_IsSubtype(
5784 (PyTypeObject *)class_attr, type);
5785 if (ok)
5786 return (PyTypeObject *)class_attr;
5787 }
5788
5789 if (class_attr == NULL)
5790 PyErr_Clear();
5791 else
5792 Py_DECREF(class_attr);
5793 }
5794
Guido van Rossumd8faa362007-04-27 19:54:29 +00005795 PyErr_SetString(PyExc_TypeError,
Guido van Rossum5b443c62001-12-03 15:38:28 +00005796 "super(type, obj): "
5797 "obj must be an instance or subtype of type");
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005798 return NULL;
Guido van Rossum5b443c62001-12-03 15:38:28 +00005799}
5800
Guido van Rossum705f0f52001-08-24 16:47:00 +00005801static PyObject *
5802super_descr_get(PyObject *self, PyObject *obj, PyObject *type)
5803{
5804 superobject *su = (superobject *)self;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00005805 superobject *newobj;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005806
5807 if (obj == NULL || obj == Py_None || su->obj != NULL) {
5808 /* Not binding to an object, or already bound */
5809 Py_INCREF(self);
5810 return self;
5811 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00005812 if (Py_Type(su) != &PySuper_Type)
Armin Rigo7726dc02005-05-15 15:32:08 +00005813 /* If su is an instance of a (strict) subclass of super,
Guido van Rossum5b443c62001-12-03 15:38:28 +00005814 call its type */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00005815 return PyObject_CallFunctionObjArgs((PyObject *)Py_Type(su),
Guido van Rossumd8faa362007-04-27 19:54:29 +00005816 su->type, obj, NULL);
Guido van Rossum5b443c62001-12-03 15:38:28 +00005817 else {
5818 /* Inline the common case */
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005819 PyTypeObject *obj_type = supercheck(su->type, obj);
5820 if (obj_type == NULL)
Guido van Rossum5b443c62001-12-03 15:38:28 +00005821 return NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00005822 newobj = (superobject *)PySuper_Type.tp_new(&PySuper_Type,
Guido van Rossum5b443c62001-12-03 15:38:28 +00005823 NULL, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00005824 if (newobj == NULL)
Guido van Rossum5b443c62001-12-03 15:38:28 +00005825 return NULL;
5826 Py_INCREF(su->type);
5827 Py_INCREF(obj);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00005828 newobj->type = su->type;
5829 newobj->obj = obj;
5830 newobj->obj_type = obj_type;
5831 return (PyObject *)newobj;
Guido van Rossum5b443c62001-12-03 15:38:28 +00005832 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00005833}
5834
5835static int
5836super_init(PyObject *self, PyObject *args, PyObject *kwds)
5837{
5838 superobject *su = (superobject *)self;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00005839 PyTypeObject *type = NULL;
Guido van Rossume705ef12001-08-29 15:47:06 +00005840 PyObject *obj = NULL;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005841 PyTypeObject *obj_type = NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005842
Thomas Wouters89f507f2006-12-13 04:49:30 +00005843 if (!_PyArg_NoKeywords("super", kwds))
5844 return -1;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00005845 if (!PyArg_ParseTuple(args, "|O!O:super", &PyType_Type, &type, &obj))
Guido van Rossum705f0f52001-08-24 16:47:00 +00005846 return -1;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00005847
5848 if (type == NULL) {
5849 /* Call super(), without args -- fill in from __class__
5850 and first local variable on the stack. */
5851 PyFrameObject *f = PyThreadState_GET()->frame;
5852 PyCodeObject *co = f->f_code;
5853 int i, n;
5854 if (co == NULL) {
5855 PyErr_SetString(PyExc_SystemError,
5856 "super(): no code object");
5857 return -1;
5858 }
5859 if (co->co_argcount == 0) {
5860 PyErr_SetString(PyExc_SystemError,
5861 "super(): no arguments");
5862 return -1;
5863 }
5864 obj = f->f_localsplus[0];
5865 if (obj == NULL) {
5866 PyErr_SetString(PyExc_SystemError,
5867 "super(): arg[0] deleted");
5868 return -1;
5869 }
5870 if (co->co_freevars == NULL)
5871 n = 0;
5872 else {
5873 assert(PyTuple_Check(co->co_freevars));
5874 n = PyTuple_GET_SIZE(co->co_freevars);
5875 }
5876 for (i = 0; i < n; i++) {
5877 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
5878 assert(PyUnicode_Check(name));
5879 if (!PyUnicode_CompareWithASCIIString(name,
5880 "__class__")) {
5881 PyObject *cell =
5882 f->f_localsplus[co->co_nlocals + i];
5883 if (cell == NULL || !PyCell_Check(cell)) {
5884 PyErr_SetString(PyExc_SystemError,
5885 "super(): bad __class__ cell");
5886 return -1;
5887 }
5888 type = (PyTypeObject *) PyCell_GET(cell);
5889 if (type == NULL) {
5890 PyErr_SetString(PyExc_SystemError,
5891 "super(): empty __class__ cell");
5892 return -1;
5893 }
5894 if (!PyType_Check(type)) {
5895 PyErr_Format(PyExc_SystemError,
5896 "super(): __class__ is not a type (%s)",
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00005897 Py_Type(type)->tp_name);
Guido van Rossumcd16bf62007-06-13 18:07:49 +00005898 return -1;
5899 }
5900 break;
5901 }
5902 }
5903 if (type == NULL) {
5904 PyErr_SetString(PyExc_SystemError,
5905 "super(): __class__ cell not found");
5906 return -1;
5907 }
5908 }
5909
Guido van Rossum705f0f52001-08-24 16:47:00 +00005910 if (obj == Py_None)
5911 obj = NULL;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005912 if (obj != NULL) {
5913 obj_type = supercheck(type, obj);
5914 if (obj_type == NULL)
5915 return -1;
5916 Py_INCREF(obj);
5917 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00005918 Py_INCREF(type);
Guido van Rossum705f0f52001-08-24 16:47:00 +00005919 su->type = type;
5920 su->obj = obj;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005921 su->obj_type = obj_type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005922 return 0;
5923}
5924
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005925PyDoc_STRVAR(super_doc,
Guido van Rossumcd16bf62007-06-13 18:07:49 +00005926"super() -> same as super(__class__, <first argument>)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00005927"super(type) -> unbound super object\n"
5928"super(type, obj) -> bound super object; requires isinstance(obj, type)\n"
Guido van Rossume705ef12001-08-29 15:47:06 +00005929"super(type, type2) -> bound super object; requires issubclass(type2, type)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00005930"Typical use to call a cooperative superclass method:\n"
5931"class C(B):\n"
5932" def meth(self, arg):\n"
Guido van Rossumcd16bf62007-06-13 18:07:49 +00005933" super().meth(arg)\n"
5934"This works for class methods too:\n"
5935"class C(B):\n"
5936" @classmethod\n"
5937" def cmeth(cls, arg):\n"
5938" super().cmeth(arg)\n");
Guido van Rossum705f0f52001-08-24 16:47:00 +00005939
Guido van Rossum048eb752001-10-02 21:24:57 +00005940static int
5941super_traverse(PyObject *self, visitproc visit, void *arg)
5942{
5943 superobject *su = (superobject *)self;
Guido van Rossum048eb752001-10-02 21:24:57 +00005944
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00005945 Py_VISIT(su->obj);
5946 Py_VISIT(su->type);
5947 Py_VISIT(su->obj_type);
Guido van Rossum048eb752001-10-02 21:24:57 +00005948
5949 return 0;
5950}
5951
Guido van Rossum705f0f52001-08-24 16:47:00 +00005952PyTypeObject PySuper_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00005953 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Guido van Rossum705f0f52001-08-24 16:47:00 +00005954 "super", /* tp_name */
5955 sizeof(superobject), /* tp_basicsize */
5956 0, /* tp_itemsize */
5957 /* methods */
Guido van Rossumd8faa362007-04-27 19:54:29 +00005958 super_dealloc, /* tp_dealloc */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005959 0, /* tp_print */
5960 0, /* tp_getattr */
5961 0, /* tp_setattr */
5962 0, /* tp_compare */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005963 super_repr, /* tp_repr */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005964 0, /* tp_as_number */
5965 0, /* tp_as_sequence */
Guido van Rossumd8faa362007-04-27 19:54:29 +00005966 0, /* tp_as_mapping */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005967 0, /* tp_hash */
5968 0, /* tp_call */
5969 0, /* tp_str */
5970 super_getattro, /* tp_getattro */
5971 0, /* tp_setattro */
5972 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00005973 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
5974 Py_TPFLAGS_BASETYPE, /* tp_flags */
Guido van Rossumd8faa362007-04-27 19:54:29 +00005975 super_doc, /* tp_doc */
5976 super_traverse, /* tp_traverse */
5977 0, /* tp_clear */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005978 0, /* tp_richcompare */
5979 0, /* tp_weaklistoffset */
5980 0, /* tp_iter */
5981 0, /* tp_iternext */
5982 0, /* tp_methods */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005983 super_members, /* tp_members */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005984 0, /* tp_getset */
5985 0, /* tp_base */
5986 0, /* tp_dict */
5987 super_descr_get, /* tp_descr_get */
5988 0, /* tp_descr_set */
5989 0, /* tp_dictoffset */
5990 super_init, /* tp_init */
5991 PyType_GenericAlloc, /* tp_alloc */
5992 PyType_GenericNew, /* tp_new */
Guido van Rossumd8faa362007-04-27 19:54:29 +00005993 PyObject_GC_Del, /* tp_free */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005994};