blob: 4fc51a626ab9fc5bd98a9b0207ea1568deb00790 [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"
Tim Peters6d6c1a32001-08-02 04:15:00 +00004#include "structmember.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00005
Guido van Rossum9923ffe2002-06-04 19:52:53 +00006#include <ctype.h>
7
Guido van Rossum6f799372001-09-20 20:46:19 +00008static PyMemberDef type_members[] = {
Tim Peters6d6c1a32001-08-02 04:15:00 +00009 {"__basicsize__", T_INT, offsetof(PyTypeObject,tp_basicsize),READONLY},
10 {"__itemsize__", T_INT, offsetof(PyTypeObject, tp_itemsize), READONLY},
11 {"__flags__", T_LONG, offsetof(PyTypeObject, tp_flags), READONLY},
Guido van Rossum9676b222001-08-17 20:32:36 +000012 {"__weakrefoffset__", T_LONG,
Tim Peters6d6c1a32001-08-02 04:15:00 +000013 offsetof(PyTypeObject, tp_weaklistoffset), READONLY},
14 {"__base__", T_OBJECT, offsetof(PyTypeObject, tp_base), READONLY},
15 {"__dictoffset__", T_LONG,
16 offsetof(PyTypeObject, tp_dictoffset), READONLY},
Tim Peters6d6c1a32001-08-02 04:15:00 +000017 {"__mro__", T_OBJECT, offsetof(PyTypeObject, tp_mro), READONLY},
18 {0}
19};
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000020
Guido van Rossumc0b618a1997-05-02 03:12:38 +000021static PyObject *
Guido van Rossumc3542212001-08-16 09:18:56 +000022type_name(PyTypeObject *type, void *context)
23{
Jeremy Hyltonaf68c872005-12-10 18:50:16 +000024 const char *s;
Guido van Rossumc3542212001-08-16 09:18:56 +000025
Michael W. Hudsonade8c8b22002-11-27 16:29:26 +000026 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
Guido van Rossume5c691a2003-03-07 15:13:17 +000027 PyHeapTypeObject* et = (PyHeapTypeObject*)type;
Tim Petersea7f75d2002-12-07 21:39:16 +000028
Georg Brandlc255c7b2006-02-20 22:27:28 +000029 Py_INCREF(et->ht_name);
30 return et->ht_name;
Michael W. Hudsonade8c8b22002-11-27 16:29:26 +000031 }
32 else {
33 s = strrchr(type->tp_name, '.');
34 if (s == NULL)
35 s = type->tp_name;
36 else
37 s++;
Martin v. Löwis5b222132007-06-10 09:51:05 +000038 return PyUnicode_FromString(s);
Michael W. Hudsonade8c8b22002-11-27 16:29:26 +000039 }
Guido van Rossumc3542212001-08-16 09:18:56 +000040}
41
Michael W. Hudson98bbc492002-11-26 14:47:27 +000042static int
43type_set_name(PyTypeObject *type, PyObject *value, void *context)
44{
Guido van Rossume5c691a2003-03-07 15:13:17 +000045 PyHeapTypeObject* et;
Michael W. Hudson98bbc492002-11-26 14:47:27 +000046
47 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
48 PyErr_Format(PyExc_TypeError,
49 "can't set %s.__name__", type->tp_name);
50 return -1;
51 }
52 if (!value) {
53 PyErr_Format(PyExc_TypeError,
54 "can't delete %s.__name__", type->tp_name);
55 return -1;
56 }
57 if (!PyString_Check(value)) {
58 PyErr_Format(PyExc_TypeError,
59 "can only assign string to %s.__name__, not '%s'",
60 type->tp_name, value->ob_type->tp_name);
61 return -1;
62 }
Tim Petersea7f75d2002-12-07 21:39:16 +000063 if (strlen(PyString_AS_STRING(value))
Michael W. Hudson98bbc492002-11-26 14:47:27 +000064 != (size_t)PyString_GET_SIZE(value)) {
65 PyErr_Format(PyExc_ValueError,
66 "__name__ must not contain null bytes");
67 return -1;
68 }
69
Guido van Rossume5c691a2003-03-07 15:13:17 +000070 et = (PyHeapTypeObject*)type;
Michael W. Hudson98bbc492002-11-26 14:47:27 +000071
72 Py_INCREF(value);
73
Georg Brandlc255c7b2006-02-20 22:27:28 +000074 Py_DECREF(et->ht_name);
75 et->ht_name = value;
Michael W. Hudson98bbc492002-11-26 14:47:27 +000076
77 type->tp_name = PyString_AS_STRING(value);
78
79 return 0;
80}
81
Guido van Rossumc3542212001-08-16 09:18:56 +000082static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +000083type_module(PyTypeObject *type, void *context)
Guido van Rossum29ca26e1995-01-07 11:58:15 +000084{
Guido van Rossumc3542212001-08-16 09:18:56 +000085 PyObject *mod;
86 char *s;
87
Michael W. Hudsonade8c8b22002-11-27 16:29:26 +000088 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
89 mod = PyDict_GetItemString(type->tp_dict, "__module__");
Anthony Baxter3ecdb252004-06-11 14:41:18 +000090 if (!mod) {
91 PyErr_Format(PyExc_AttributeError, "__module__");
92 return 0;
93 }
Michael W. Hudsonade8c8b22002-11-27 16:29:26 +000094 Py_XINCREF(mod);
Guido van Rossumc3542212001-08-16 09:18:56 +000095 return mod;
96 }
Michael W. Hudsonade8c8b22002-11-27 16:29:26 +000097 else {
98 s = strrchr(type->tp_name, '.');
99 if (s != NULL)
Martin v. Löwis5b222132007-06-10 09:51:05 +0000100 return PyUnicode_FromStringAndSize(
Thomas Wouters89f507f2006-12-13 04:49:30 +0000101 type->tp_name, (Py_ssize_t)(s - type->tp_name));
Martin v. Löwis5b222132007-06-10 09:51:05 +0000102 return PyUnicode_FromString("__builtin__");
Michael W. Hudsonade8c8b22002-11-27 16:29:26 +0000103 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000104}
105
Guido van Rossum3926a632001-09-25 16:25:58 +0000106static int
107type_set_module(PyTypeObject *type, PyObject *value, void *context)
108{
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000109 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
Guido van Rossum3926a632001-09-25 16:25:58 +0000110 PyErr_Format(PyExc_TypeError,
111 "can't set %s.__module__", type->tp_name);
112 return -1;
113 }
114 if (!value) {
115 PyErr_Format(PyExc_TypeError,
116 "can't delete %s.__module__", type->tp_name);
117 return -1;
118 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000119
Guido van Rossum3926a632001-09-25 16:25:58 +0000120 return PyDict_SetItemString(type->tp_dict, "__module__", value);
121}
122
Tim Peters6d6c1a32001-08-02 04:15:00 +0000123static PyObject *
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000124type_get_bases(PyTypeObject *type, void *context)
125{
126 Py_INCREF(type->tp_bases);
127 return type->tp_bases;
128}
129
130static PyTypeObject *best_base(PyObject *);
131static int mro_internal(PyTypeObject *);
132static int compatible_for_assignment(PyTypeObject *, PyTypeObject *, char *);
133static int add_subclass(PyTypeObject*, PyTypeObject*);
134static void remove_subclass(PyTypeObject *, PyTypeObject *);
135static void update_all_slots(PyTypeObject *);
136
Guido van Rossum8d24ee92003-03-24 23:49:49 +0000137typedef int (*update_callback)(PyTypeObject *, void *);
138static int update_subclasses(PyTypeObject *type, PyObject *name,
139 update_callback callback, void *data);
140static int recurse_down_subclasses(PyTypeObject *type, PyObject *name,
141 update_callback callback, void *data);
142
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000143static int
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000144mro_subclasses(PyTypeObject *type, PyObject* temp)
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000145{
146 PyTypeObject *subclass;
147 PyObject *ref, *subclasses, *old_mro;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000148 Py_ssize_t i, n;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000149
150 subclasses = type->tp_subclasses;
151 if (subclasses == NULL)
152 return 0;
153 assert(PyList_Check(subclasses));
154 n = PyList_GET_SIZE(subclasses);
155 for (i = 0; i < n; i++) {
156 ref = PyList_GET_ITEM(subclasses, i);
157 assert(PyWeakref_CheckRef(ref));
158 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
159 assert(subclass != NULL);
160 if ((PyObject *)subclass == Py_None)
161 continue;
162 assert(PyType_Check(subclass));
163 old_mro = subclass->tp_mro;
164 if (mro_internal(subclass) < 0) {
165 subclass->tp_mro = old_mro;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000166 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000167 }
168 else {
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000169 PyObject* tuple;
Raymond Hettinger8ae46892003-10-12 19:09:37 +0000170 tuple = PyTuple_Pack(2, subclass, old_mro);
Guido van Rossum19a02ba2003-04-15 22:09:45 +0000171 Py_DECREF(old_mro);
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000172 if (!tuple)
173 return -1;
174 if (PyList_Append(temp, tuple) < 0)
175 return -1;
Guido van Rossum19a02ba2003-04-15 22:09:45 +0000176 Py_DECREF(tuple);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000177 }
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000178 if (mro_subclasses(subclass, temp) < 0)
179 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000180 }
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000181 return 0;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000182}
183
184static int
185type_set_bases(PyTypeObject *type, PyObject *value, void *context)
186{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000187 Py_ssize_t i;
188 int r = 0;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000189 PyObject *ob, *temp;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000190 PyTypeObject *new_base, *old_base;
191 PyObject *old_bases, *old_mro;
192
193 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
194 PyErr_Format(PyExc_TypeError,
195 "can't set %s.__bases__", type->tp_name);
196 return -1;
197 }
198 if (!value) {
199 PyErr_Format(PyExc_TypeError,
200 "can't delete %s.__bases__", type->tp_name);
201 return -1;
202 }
203 if (!PyTuple_Check(value)) {
204 PyErr_Format(PyExc_TypeError,
205 "can only assign tuple to %s.__bases__, not %s",
206 type->tp_name, value->ob_type->tp_name);
207 return -1;
208 }
Guido van Rossum3bbc0ee2002-12-13 17:49:38 +0000209 if (PyTuple_GET_SIZE(value) == 0) {
210 PyErr_Format(PyExc_TypeError,
211 "can only assign non-empty tuple to %s.__bases__, not ()",
212 type->tp_name);
213 return -1;
214 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000215 for (i = 0; i < PyTuple_GET_SIZE(value); i++) {
216 ob = PyTuple_GET_ITEM(value, i);
Guido van Rossum50e9fb92006-08-17 05:42:55 +0000217 if (!PyType_Check(ob)) {
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000218 PyErr_Format(
219 PyExc_TypeError,
220 "%s.__bases__ must be tuple of old- or new-style classes, not '%s'",
221 type->tp_name, ob->ob_type->tp_name);
222 return -1;
223 }
Michael W. Hudsoncaf17be2002-11-27 10:24:44 +0000224 if (PyType_Check(ob)) {
225 if (PyType_IsSubtype((PyTypeObject*)ob, type)) {
226 PyErr_SetString(PyExc_TypeError,
227 "a __bases__ item causes an inheritance cycle");
228 return -1;
229 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000230 }
231 }
232
233 new_base = best_base(value);
234
235 if (!new_base) {
236 return -1;
237 }
238
239 if (!compatible_for_assignment(type->tp_base, new_base, "__bases__"))
240 return -1;
241
242 Py_INCREF(new_base);
243 Py_INCREF(value);
244
245 old_bases = type->tp_bases;
246 old_base = type->tp_base;
247 old_mro = type->tp_mro;
248
249 type->tp_bases = value;
250 type->tp_base = new_base;
251
252 if (mro_internal(type) < 0) {
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000253 goto bail;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000254 }
255
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000256 temp = PyList_New(0);
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000257 if (!temp)
258 goto bail;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000259
260 r = mro_subclasses(type, temp);
261
262 if (r < 0) {
263 for (i = 0; i < PyList_Size(temp); i++) {
264 PyTypeObject* cls;
265 PyObject* mro;
Raymond Hettinger8ae46892003-10-12 19:09:37 +0000266 PyArg_UnpackTuple(PyList_GET_ITEM(temp, i),
267 "", 2, 2, &cls, &mro);
Guido van Rossumd8faa362007-04-27 19:54:29 +0000268 Py_INCREF(mro);
269 ob = cls->tp_mro;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000270 cls->tp_mro = mro;
Guido van Rossumd8faa362007-04-27 19:54:29 +0000271 Py_DECREF(ob);
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000272 }
273 Py_DECREF(temp);
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000274 goto bail;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000275 }
276
277 Py_DECREF(temp);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000278
279 /* any base that was in __bases__ but now isn't, we
Raymond Hettingera8285862002-12-14 17:17:56 +0000280 need to remove |type| from its tp_subclasses.
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000281 conversely, any class now in __bases__ that wasn't
Raymond Hettingera8285862002-12-14 17:17:56 +0000282 needs to have |type| added to its subclasses. */
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000283
284 /* for now, sod that: just remove from all old_bases,
285 add to all new_bases */
286
287 for (i = PyTuple_GET_SIZE(old_bases) - 1; i >= 0; i--) {
288 ob = PyTuple_GET_ITEM(old_bases, i);
289 if (PyType_Check(ob)) {
290 remove_subclass(
291 (PyTypeObject*)ob, type);
292 }
293 }
294
295 for (i = PyTuple_GET_SIZE(value) - 1; i >= 0; i--) {
296 ob = PyTuple_GET_ITEM(value, i);
297 if (PyType_Check(ob)) {
298 if (add_subclass((PyTypeObject*)ob, type) < 0)
299 r = -1;
300 }
301 }
302
303 update_all_slots(type);
304
305 Py_DECREF(old_bases);
306 Py_DECREF(old_base);
307 Py_DECREF(old_mro);
308
309 return r;
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000310
311 bail:
Michael W. Hudsone723e452003-08-07 14:58:10 +0000312 Py_DECREF(type->tp_bases);
313 Py_DECREF(type->tp_base);
314 if (type->tp_mro != old_mro) {
315 Py_DECREF(type->tp_mro);
316 }
317
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000318 type->tp_bases = old_bases;
319 type->tp_base = old_base;
320 type->tp_mro = old_mro;
Tim Petersea7f75d2002-12-07 21:39:16 +0000321
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000322 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000323}
324
325static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000326type_dict(PyTypeObject *type, void *context)
327{
328 if (type->tp_dict == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000329 Py_INCREF(Py_None);
330 return Py_None;
Guido van Rossum29ca26e1995-01-07 11:58:15 +0000331 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000332 return PyDictProxy_New(type->tp_dict);
Guido van Rossum29ca26e1995-01-07 11:58:15 +0000333}
334
Tim Peters24008312002-03-17 18:56:20 +0000335static PyObject *
336type_get_doc(PyTypeObject *type, void *context)
337{
338 PyObject *result;
Guido van Rossum6ca7d412002-04-18 00:22:00 +0000339 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE) && type->tp_doc != NULL)
Tim Peters24008312002-03-17 18:56:20 +0000340 return PyString_FromString(type->tp_doc);
Tim Peters24008312002-03-17 18:56:20 +0000341 result = PyDict_GetItemString(type->tp_dict, "__doc__");
Guido van Rossum6ca7d412002-04-18 00:22:00 +0000342 if (result == NULL) {
343 result = Py_None;
344 Py_INCREF(result);
345 }
346 else if (result->ob_type->tp_descr_get) {
Tim Peters2b858972002-04-18 04:12:28 +0000347 result = result->ob_type->tp_descr_get(result, NULL,
348 (PyObject *)type);
Guido van Rossum6ca7d412002-04-18 00:22:00 +0000349 }
350 else {
351 Py_INCREF(result);
352 }
Tim Peters24008312002-03-17 18:56:20 +0000353 return result;
354}
355
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000356static PyGetSetDef type_getsets[] = {
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000357 {"__name__", (getter)type_name, (setter)type_set_name, NULL},
358 {"__bases__", (getter)type_get_bases, (setter)type_set_bases, NULL},
Guido van Rossum3926a632001-09-25 16:25:58 +0000359 {"__module__", (getter)type_module, (setter)type_set_module, NULL},
Tim Peters6d6c1a32001-08-02 04:15:00 +0000360 {"__dict__", (getter)type_dict, NULL, NULL},
Tim Peters24008312002-03-17 18:56:20 +0000361 {"__doc__", (getter)type_get_doc, NULL, NULL},
Tim Peters6d6c1a32001-08-02 04:15:00 +0000362 {0}
363};
364
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000365static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000366type_repr(PyTypeObject *type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000367{
Barry Warsaw7ce36942001-08-24 18:34:26 +0000368 PyObject *mod, *name, *rtn;
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000369 char *kind;
Guido van Rossumc3542212001-08-16 09:18:56 +0000370
371 mod = type_module(type, NULL);
372 if (mod == NULL)
373 PyErr_Clear();
Martin v. Löwis5b222132007-06-10 09:51:05 +0000374 else if (!PyUnicode_Check(mod)) {
Guido van Rossumc3542212001-08-16 09:18:56 +0000375 Py_DECREF(mod);
376 mod = NULL;
377 }
378 name = type_name(type, NULL);
379 if (name == NULL)
380 return NULL;
Barry Warsaw7ce36942001-08-24 18:34:26 +0000381
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000382 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
383 kind = "class";
384 else
385 kind = "type";
386
Martin v. Löwis5b222132007-06-10 09:51:05 +0000387 if (mod != NULL && strcmp(PyUnicode_AsString(mod), "__builtin__")) {
Walter Dörwald1ab83302007-05-18 17:15:44 +0000388 rtn = PyUnicode_FromFormat("<%s '%s.%s'>",
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000389 kind,
Martin v. Löwis5b222132007-06-10 09:51:05 +0000390 PyUnicode_AsString(mod),
391 PyUnicode_AsString(name));
Barry Warsaw7ce36942001-08-24 18:34:26 +0000392 }
Guido van Rossumc3542212001-08-16 09:18:56 +0000393 else
Walter Dörwald1ab83302007-05-18 17:15:44 +0000394 rtn = PyUnicode_FromFormat("<%s '%s'>", kind, type->tp_name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000395
Guido van Rossumc3542212001-08-16 09:18:56 +0000396 Py_XDECREF(mod);
397 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000398 return rtn;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000399}
400
Tim Peters6d6c1a32001-08-02 04:15:00 +0000401static PyObject *
402type_call(PyTypeObject *type, PyObject *args, PyObject *kwds)
403{
404 PyObject *obj;
405
406 if (type->tp_new == NULL) {
407 PyErr_Format(PyExc_TypeError,
408 "cannot create '%.100s' instances",
409 type->tp_name);
410 return NULL;
411 }
412
Tim Peters3f996e72001-09-13 19:18:27 +0000413 obj = type->tp_new(type, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000414 if (obj != NULL) {
Guido van Rossumf76de622001-10-18 15:49:21 +0000415 /* Ugly exception: when the call was type(something),
416 don't call tp_init on the result. */
417 if (type == &PyType_Type &&
418 PyTuple_Check(args) && PyTuple_GET_SIZE(args) == 1 &&
419 (kwds == NULL ||
420 (PyDict_Check(kwds) && PyDict_Size(kwds) == 0)))
421 return obj;
Guido van Rossum8ace1ab2002-04-06 01:05:01 +0000422 /* If the returned object is not an instance of type,
423 it won't be initialized. */
424 if (!PyType_IsSubtype(obj->ob_type, type))
425 return obj;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000426 type = obj->ob_type;
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +0000427 if (type->tp_init != NULL &&
Tim Peters6d6c1a32001-08-02 04:15:00 +0000428 type->tp_init(obj, args, kwds) < 0) {
429 Py_DECREF(obj);
430 obj = NULL;
431 }
432 }
433 return obj;
434}
435
436PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000437PyType_GenericAlloc(PyTypeObject *type, Py_ssize_t nitems)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000438{
Tim Peters6d6c1a32001-08-02 04:15:00 +0000439 PyObject *obj;
Guido van Rossume5c691a2003-03-07 15:13:17 +0000440 const size_t size = _PyObject_VAR_SIZE(type, nitems+1);
441 /* note that we need to add one, for the sentinel */
Tim Peters406fe3b2001-10-06 19:04:01 +0000442
443 if (PyType_IS_GC(type))
Neil Schemenauer09a2ae52002-04-12 03:06:53 +0000444 obj = _PyObject_GC_Malloc(size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000445 else
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000446 obj = (PyObject *)PyObject_MALLOC(size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000447
Neil Schemenauerc806c882001-08-29 23:54:54 +0000448 if (obj == NULL)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000449 return PyErr_NoMemory();
Tim Peters406fe3b2001-10-06 19:04:01 +0000450
Neil Schemenauerc806c882001-08-29 23:54:54 +0000451 memset(obj, '\0', size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000452
Tim Peters6d6c1a32001-08-02 04:15:00 +0000453 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
454 Py_INCREF(type);
Tim Peters406fe3b2001-10-06 19:04:01 +0000455
Tim Peters6d6c1a32001-08-02 04:15:00 +0000456 if (type->tp_itemsize == 0)
457 PyObject_INIT(obj, type);
458 else
459 (void) PyObject_INIT_VAR((PyVarObject *)obj, type, nitems);
Tim Peters406fe3b2001-10-06 19:04:01 +0000460
Tim Peters6d6c1a32001-08-02 04:15:00 +0000461 if (PyType_IS_GC(type))
Neil Schemenauerc806c882001-08-29 23:54:54 +0000462 _PyObject_GC_TRACK(obj);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000463 return obj;
464}
465
466PyObject *
467PyType_GenericNew(PyTypeObject *type, PyObject *args, PyObject *kwds)
468{
469 return type->tp_alloc(type, 0);
470}
471
Guido van Rossum9475a232001-10-05 20:51:39 +0000472/* Helpers for subtyping */
473
474static int
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000475traverse_slots(PyTypeObject *type, PyObject *self, visitproc visit, void *arg)
476{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000477 Py_ssize_t i, n;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000478 PyMemberDef *mp;
479
480 n = type->ob_size;
Guido van Rossume5c691a2003-03-07 15:13:17 +0000481 mp = PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000482 for (i = 0; i < n; i++, mp++) {
483 if (mp->type == T_OBJECT_EX) {
484 char *addr = (char *)self + mp->offset;
485 PyObject *obj = *(PyObject **)addr;
486 if (obj != NULL) {
487 int err = visit(obj, arg);
488 if (err)
489 return err;
490 }
491 }
492 }
493 return 0;
494}
495
496static int
Guido van Rossum9475a232001-10-05 20:51:39 +0000497subtype_traverse(PyObject *self, visitproc visit, void *arg)
498{
499 PyTypeObject *type, *base;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000500 traverseproc basetraverse;
Guido van Rossum9475a232001-10-05 20:51:39 +0000501
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000502 /* Find the nearest base with a different tp_traverse,
503 and traverse slots while we're at it */
Guido van Rossum9475a232001-10-05 20:51:39 +0000504 type = self->ob_type;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000505 base = type;
506 while ((basetraverse = base->tp_traverse) == subtype_traverse) {
507 if (base->ob_size) {
508 int err = traverse_slots(base, self, visit, arg);
509 if (err)
510 return err;
511 }
Guido van Rossum9475a232001-10-05 20:51:39 +0000512 base = base->tp_base;
513 assert(base);
514 }
515
516 if (type->tp_dictoffset != base->tp_dictoffset) {
517 PyObject **dictptr = _PyObject_GetDictPtr(self);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000518 if (dictptr && *dictptr)
519 Py_VISIT(*dictptr);
Guido van Rossum9475a232001-10-05 20:51:39 +0000520 }
521
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000522 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
Guido van Rossuma3862092002-06-10 15:24:42 +0000523 /* For a heaptype, the instances count as references
Guido van Rossumd8faa362007-04-27 19:54:29 +0000524 to the type. Traverse the type so the collector
Guido van Rossuma3862092002-06-10 15:24:42 +0000525 can find cycles involving this link. */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000526 Py_VISIT(type);
Guido van Rossuma3862092002-06-10 15:24:42 +0000527
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000528 if (basetraverse)
529 return basetraverse(self, visit, arg);
530 return 0;
531}
532
533static void
534clear_slots(PyTypeObject *type, PyObject *self)
535{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000536 Py_ssize_t i, n;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000537 PyMemberDef *mp;
538
539 n = type->ob_size;
Guido van Rossume5c691a2003-03-07 15:13:17 +0000540 mp = PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000541 for (i = 0; i < n; i++, mp++) {
542 if (mp->type == T_OBJECT_EX && !(mp->flags & READONLY)) {
543 char *addr = (char *)self + mp->offset;
544 PyObject *obj = *(PyObject **)addr;
545 if (obj != NULL) {
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000546 *(PyObject **)addr = NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000547 Py_DECREF(obj);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000548 }
549 }
550 }
551}
552
553static int
554subtype_clear(PyObject *self)
555{
556 PyTypeObject *type, *base;
557 inquiry baseclear;
558
559 /* Find the nearest base with a different tp_clear
560 and clear slots while we're at it */
561 type = self->ob_type;
562 base = type;
563 while ((baseclear = base->tp_clear) == subtype_clear) {
564 if (base->ob_size)
565 clear_slots(base, self);
566 base = base->tp_base;
567 assert(base);
568 }
569
Guido van Rossuma3862092002-06-10 15:24:42 +0000570 /* There's no need to clear the instance dict (if any);
571 the collector will call its tp_clear handler. */
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000572
573 if (baseclear)
574 return baseclear(self);
Guido van Rossum9475a232001-10-05 20:51:39 +0000575 return 0;
576}
Tim Peters6d6c1a32001-08-02 04:15:00 +0000577
578static void
579subtype_dealloc(PyObject *self)
580{
Guido van Rossum14227b42001-12-06 02:35:58 +0000581 PyTypeObject *type, *base;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000582 destructor basedealloc;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000583
Guido van Rossum22b13872002-08-06 21:41:44 +0000584 /* Extract the type; we expect it to be a heap type */
585 type = self->ob_type;
586 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000587
Guido van Rossum22b13872002-08-06 21:41:44 +0000588 /* Test whether the type has GC exactly once */
589
590 if (!PyType_IS_GC(type)) {
591 /* It's really rare to find a dynamic type that doesn't have
592 GC; it can only happen when deriving from 'object' and not
593 adding any slots or instance variables. This allows
594 certain simplifications: there's no need to call
595 clear_slots(), or DECREF the dict, or clear weakrefs. */
596
597 /* Maybe call finalizer; exit early if resurrected */
Guido van Rossumfebd61d2002-08-08 20:55:20 +0000598 if (type->tp_del) {
599 type->tp_del(self);
600 if (self->ob_refcnt > 0)
601 return;
602 }
Guido van Rossum22b13872002-08-06 21:41:44 +0000603
604 /* Find the nearest base with a different tp_dealloc */
605 base = type;
606 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
607 assert(base->ob_size == 0);
608 base = base->tp_base;
609 assert(base);
610 }
611
612 /* Call the base tp_dealloc() */
613 assert(basedealloc);
614 basedealloc(self);
615
616 /* Can't reference self beyond this point */
617 Py_DECREF(type);
618
619 /* Done */
620 return;
621 }
622
623 /* We get here only if the type has GC */
624
625 /* UnTrack and re-Track around the trashcan macro, alas */
Andrew M. Kuchlingc9172d32003-02-06 15:22:49 +0000626 /* See explanation at end of function for full disclosure */
Guido van Rossum0906e072002-08-07 20:42:09 +0000627 PyObject_GC_UnTrack(self);
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000628 ++_PyTrash_delete_nesting;
Guido van Rossum22b13872002-08-06 21:41:44 +0000629 Py_TRASHCAN_SAFE_BEGIN(self);
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000630 --_PyTrash_delete_nesting;
Tim Petersf7f9e992003-11-13 21:59:32 +0000631 /* DO NOT restore GC tracking at this point. weakref callbacks
632 * (if any, and whether directly here or indirectly in something we
633 * call) may trigger GC, and if self is tracked at that point, it
634 * will look like trash to GC and GC will try to delete self again.
Tim Petersadd09b42003-11-12 20:43:28 +0000635 */
Guido van Rossum22b13872002-08-06 21:41:44 +0000636
Guido van Rossum59195fd2003-06-13 20:54:40 +0000637 /* Find the nearest base with a different tp_dealloc */
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000638 base = type;
639 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
Tim Peters6d6c1a32001-08-02 04:15:00 +0000640 base = base->tp_base;
641 assert(base);
Guido van Rossum14227b42001-12-06 02:35:58 +0000642 }
643
Guido van Rossumd8faa362007-04-27 19:54:29 +0000644 /* If we added a weaklist, we clear it. Do this *before* calling
Guido van Rossum59195fd2003-06-13 20:54:40 +0000645 the finalizer (__del__), clearing slots, or clearing the instance
646 dict. */
647
Guido van Rossum1987c662003-05-29 14:29:23 +0000648 if (type->tp_weaklistoffset && !base->tp_weaklistoffset)
649 PyObject_ClearWeakRefs(self);
650
651 /* Maybe call finalizer; exit early if resurrected */
652 if (type->tp_del) {
Tim Petersf7f9e992003-11-13 21:59:32 +0000653 _PyObject_GC_TRACK(self);
Guido van Rossum1987c662003-05-29 14:29:23 +0000654 type->tp_del(self);
655 if (self->ob_refcnt > 0)
Tim Petersf7f9e992003-11-13 21:59:32 +0000656 goto endlabel; /* resurrected */
657 else
658 _PyObject_GC_UNTRACK(self);
Thomas Woutersb2137042007-02-01 18:02:27 +0000659 /* New weakrefs could be created during the finalizer call.
660 If this occurs, clear them out without calling their
661 finalizers since they might rely on part of the object
662 being finalized that has already been destroyed. */
663 if (type->tp_weaklistoffset && !base->tp_weaklistoffset) {
664 /* Modeled after GET_WEAKREFS_LISTPTR() */
665 PyWeakReference **list = (PyWeakReference **) \
666 PyObject_GET_WEAKREFS_LISTPTR(self);
667 while (*list)
668 _PyWeakref_ClearRef(*list);
669 }
Guido van Rossum1987c662003-05-29 14:29:23 +0000670 }
671
Guido van Rossum59195fd2003-06-13 20:54:40 +0000672 /* Clear slots up to the nearest base with a different tp_dealloc */
673 base = type;
674 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
675 if (base->ob_size)
676 clear_slots(base, self);
677 base = base->tp_base;
678 assert(base);
679 }
680
Tim Peters6d6c1a32001-08-02 04:15:00 +0000681 /* If we added a dict, DECREF it */
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000682 if (type->tp_dictoffset && !base->tp_dictoffset) {
683 PyObject **dictptr = _PyObject_GetDictPtr(self);
684 if (dictptr != NULL) {
685 PyObject *dict = *dictptr;
686 if (dict != NULL) {
687 Py_DECREF(dict);
688 *dictptr = NULL;
689 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000690 }
691 }
692
Tim Peters0bd743c2003-11-13 22:50:00 +0000693 /* Call the base tp_dealloc(); first retrack self if
694 * basedealloc knows about gc.
695 */
696 if (PyType_IS_GC(base))
697 _PyObject_GC_TRACK(self);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000698 assert(basedealloc);
699 basedealloc(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000700
701 /* Can't reference self beyond this point */
Guido van Rossum22b13872002-08-06 21:41:44 +0000702 Py_DECREF(type);
703
Guido van Rossum0906e072002-08-07 20:42:09 +0000704 endlabel:
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000705 ++_PyTrash_delete_nesting;
Guido van Rossum22b13872002-08-06 21:41:44 +0000706 Py_TRASHCAN_SAFE_END(self);
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000707 --_PyTrash_delete_nesting;
708
709 /* Explanation of the weirdness around the trashcan macros:
710
711 Q. What do the trashcan macros do?
712
713 A. Read the comment titled "Trashcan mechanism" in object.h.
714 For one, this explains why there must be a call to GC-untrack
Guido van Rossumd8faa362007-04-27 19:54:29 +0000715 before the trashcan begin macro. Without understanding the
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000716 trashcan code, the answers to the following questions don't make
717 sense.
718
719 Q. Why do we GC-untrack before the trashcan and then immediately
720 GC-track again afterward?
721
722 A. In the case that the base class is GC-aware, the base class
Guido van Rossumd8faa362007-04-27 19:54:29 +0000723 probably GC-untracks the object. If it does that using the
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000724 UNTRACK macro, this will crash when the object is already
725 untracked. Because we don't know what the base class does, the
726 only safe thing is to make sure the object is tracked when we
727 call the base class dealloc. But... The trashcan begin macro
728 requires that the object is *untracked* before it is called. So
729 the dance becomes:
730
Guido van Rossumd8faa362007-04-27 19:54:29 +0000731 GC untrack
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000732 trashcan begin
733 GC track
734
Guido van Rossumd8faa362007-04-27 19:54:29 +0000735 Q. Why did the last question say "immediately GC-track again"?
736 It's nowhere near immediately.
Tim Petersf7f9e992003-11-13 21:59:32 +0000737
Guido van Rossumd8faa362007-04-27 19:54:29 +0000738 A. Because the code *used* to re-track immediately. Bad Idea.
739 self has a refcount of 0, and if gc ever gets its hands on it
740 (which can happen if any weakref callback gets invoked), it
741 looks like trash to gc too, and gc also tries to delete self
742 then. But we're already deleting self. Double dealloction is
743 a subtle disaster.
Tim Petersf7f9e992003-11-13 21:59:32 +0000744
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000745 Q. Why the bizarre (net-zero) manipulation of
746 _PyTrash_delete_nesting around the trashcan macros?
747
748 A. Some base classes (e.g. list) also use the trashcan mechanism.
749 The following scenario used to be possible:
750
751 - suppose the trashcan level is one below the trashcan limit
752
753 - subtype_dealloc() is called
754
755 - the trashcan limit is not yet reached, so the trashcan level
Guido van Rossumd8faa362007-04-27 19:54:29 +0000756 is incremented and the code between trashcan begin and end is
757 executed
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000758
759 - this destroys much of the object's contents, including its
Guido van Rossumd8faa362007-04-27 19:54:29 +0000760 slots and __dict__
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000761
762 - basedealloc() is called; this is really list_dealloc(), or
Guido van Rossumd8faa362007-04-27 19:54:29 +0000763 some other type which also uses the trashcan macros
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000764
765 - the trashcan limit is now reached, so the object is put on the
Guido van Rossumd8faa362007-04-27 19:54:29 +0000766 trashcan's to-be-deleted-later list
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000767
768 - basedealloc() returns
769
770 - subtype_dealloc() decrefs the object's type
771
772 - subtype_dealloc() returns
773
774 - later, the trashcan code starts deleting the objects from its
Guido van Rossumd8faa362007-04-27 19:54:29 +0000775 to-be-deleted-later list
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000776
777 - subtype_dealloc() is called *AGAIN* for the same object
778
779 - at the very least (if the destroyed slots and __dict__ don't
Guido van Rossumd8faa362007-04-27 19:54:29 +0000780 cause problems) the object's type gets decref'ed a second
781 time, which is *BAD*!!!
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000782
783 The remedy is to make sure that if the code between trashcan
784 begin and end in subtype_dealloc() is called, the code between
785 trashcan begin and end in basedealloc() will also be called.
786 This is done by decrementing the level after passing into the
787 trashcan block, and incrementing it just before leaving the
788 block.
789
790 But now it's possible that a chain of objects consisting solely
791 of objects whose deallocator is subtype_dealloc() will defeat
792 the trashcan mechanism completely: the decremented level means
Guido van Rossumd8faa362007-04-27 19:54:29 +0000793 that the effective level never reaches the limit. Therefore, we
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000794 *increment* the level *before* entering the trashcan block, and
795 matchingly decrement it after leaving. This means the trashcan
796 code will trigger a little early, but that's no big deal.
797
798 Q. Are there any live examples of code in need of all this
799 complexity?
800
801 A. Yes. See SF bug 668433 for code that crashed (when Python was
802 compiled in debug mode) before the trashcan level manipulations
803 were added. For more discussion, see SF patches 581742, 575073
804 and bug 574207.
805 */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000806}
807
Jeremy Hylton938ace62002-07-17 16:30:39 +0000808static PyTypeObject *solid_base(PyTypeObject *type);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000809
Tim Peters6d6c1a32001-08-02 04:15:00 +0000810/* type test with subclassing support */
811
812int
813PyType_IsSubtype(PyTypeObject *a, PyTypeObject *b)
814{
815 PyObject *mro;
816
817 mro = a->tp_mro;
818 if (mro != NULL) {
819 /* Deal with multiple inheritance without recursion
820 by walking the MRO tuple */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000821 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000822 assert(PyTuple_Check(mro));
823 n = PyTuple_GET_SIZE(mro);
824 for (i = 0; i < n; i++) {
825 if (PyTuple_GET_ITEM(mro, i) == (PyObject *)b)
826 return 1;
827 }
828 return 0;
829 }
830 else {
831 /* a is not completely initilized yet; follow tp_base */
832 do {
833 if (a == b)
834 return 1;
835 a = a->tp_base;
836 } while (a != NULL);
837 return b == &PyBaseObject_Type;
838 }
839}
840
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000841/* Internal routines to do a method lookup in the type
Guido van Rossum60718732001-08-28 17:47:51 +0000842 without looking in the instance dictionary
843 (so we can't use PyObject_GetAttr) but still binding
Guido van Rossumd8faa362007-04-27 19:54:29 +0000844 it to the instance. The arguments are the object,
Guido van Rossum60718732001-08-28 17:47:51 +0000845 the method name as a C string, and the address of a
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000846 static variable used to cache the interned Python string.
847
848 Two variants:
849
850 - lookup_maybe() returns NULL without raising an exception
851 when the _PyType_Lookup() call fails;
852
853 - lookup_method() always raises an exception upon errors.
854*/
Guido van Rossum60718732001-08-28 17:47:51 +0000855
856static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000857lookup_maybe(PyObject *self, char *attrstr, PyObject **attrobj)
Guido van Rossum60718732001-08-28 17:47:51 +0000858{
859 PyObject *res;
860
861 if (*attrobj == NULL) {
Martin v. Löwis5b222132007-06-10 09:51:05 +0000862 *attrobj = PyUnicode_InternFromString(attrstr);
Guido van Rossum60718732001-08-28 17:47:51 +0000863 if (*attrobj == NULL)
864 return NULL;
865 }
866 res = _PyType_Lookup(self->ob_type, *attrobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000867 if (res != NULL) {
Guido van Rossum60718732001-08-28 17:47:51 +0000868 descrgetfunc f;
869 if ((f = res->ob_type->tp_descr_get) == NULL)
870 Py_INCREF(res);
871 else
872 res = f(res, self, (PyObject *)(self->ob_type));
873 }
874 return res;
875}
876
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000877static PyObject *
878lookup_method(PyObject *self, char *attrstr, PyObject **attrobj)
879{
880 PyObject *res = lookup_maybe(self, attrstr, attrobj);
881 if (res == NULL && !PyErr_Occurred())
882 PyErr_SetObject(PyExc_AttributeError, *attrobj);
883 return res;
884}
885
Guido van Rossum2730b132001-08-28 18:22:14 +0000886/* A variation of PyObject_CallMethod that uses lookup_method()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000887 instead of PyObject_GetAttrString(). This uses the same convention
Guido van Rossum2730b132001-08-28 18:22:14 +0000888 as lookup_method to cache the interned name string object. */
889
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000890static PyObject *
Guido van Rossum2730b132001-08-28 18:22:14 +0000891call_method(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
892{
893 va_list va;
894 PyObject *args, *func = 0, *retval;
Guido van Rossum2730b132001-08-28 18:22:14 +0000895 va_start(va, format);
896
Guido van Rossumda21c012001-10-03 00:50:18 +0000897 func = lookup_maybe(o, name, nameobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000898 if (func == NULL) {
899 va_end(va);
900 if (!PyErr_Occurred())
Guido van Rossumda21c012001-10-03 00:50:18 +0000901 PyErr_SetObject(PyExc_AttributeError, *nameobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000902 return NULL;
903 }
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000904
905 if (format && *format)
906 args = Py_VaBuildValue(format, va);
907 else
908 args = PyTuple_New(0);
909
910 va_end(va);
911
912 if (args == NULL)
913 return NULL;
914
915 assert(PyTuple_Check(args));
916 retval = PyObject_Call(func, args, NULL);
917
918 Py_DECREF(args);
919 Py_DECREF(func);
920
921 return retval;
922}
923
924/* Clone of call_method() that returns NotImplemented when the lookup fails. */
925
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000926static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000927call_maybe(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
928{
929 va_list va;
930 PyObject *args, *func = 0, *retval;
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000931 va_start(va, format);
932
Guido van Rossumda21c012001-10-03 00:50:18 +0000933 func = lookup_maybe(o, name, nameobj);
Guido van Rossum2730b132001-08-28 18:22:14 +0000934 if (func == NULL) {
935 va_end(va);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000936 if (!PyErr_Occurred()) {
937 Py_INCREF(Py_NotImplemented);
938 return Py_NotImplemented;
939 }
Guido van Rossum717ce002001-09-14 16:58:08 +0000940 return NULL;
Guido van Rossum2730b132001-08-28 18:22:14 +0000941 }
942
943 if (format && *format)
944 args = Py_VaBuildValue(format, va);
945 else
946 args = PyTuple_New(0);
947
948 va_end(va);
949
Guido van Rossum717ce002001-09-14 16:58:08 +0000950 if (args == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +0000951 return NULL;
952
Guido van Rossum717ce002001-09-14 16:58:08 +0000953 assert(PyTuple_Check(args));
954 retval = PyObject_Call(func, args, NULL);
Guido van Rossum2730b132001-08-28 18:22:14 +0000955
956 Py_DECREF(args);
957 Py_DECREF(func);
958
959 return retval;
960}
961
Tim Petersea7f75d2002-12-07 21:39:16 +0000962/*
Guido van Rossum1f121312002-11-14 19:49:16 +0000963 Method resolution order algorithm C3 described in
964 "A Monotonic Superclass Linearization for Dylan",
965 by Kim Barrett, Bob Cassel, Paul Haahr,
Tim Petersea7f75d2002-12-07 21:39:16 +0000966 David A. Moon, Keith Playford, and P. Tucker Withington.
Guido van Rossum1f121312002-11-14 19:49:16 +0000967 (OOPSLA 1996)
968
Guido van Rossum98f33732002-11-25 21:36:54 +0000969 Some notes about the rules implied by C3:
970
Tim Petersea7f75d2002-12-07 21:39:16 +0000971 No duplicate bases.
Guido van Rossum98f33732002-11-25 21:36:54 +0000972 It isn't legal to repeat a class in a list of base classes.
973
974 The next three properties are the 3 constraints in "C3".
975
Tim Petersea7f75d2002-12-07 21:39:16 +0000976 Local precendece order.
Guido van Rossum98f33732002-11-25 21:36:54 +0000977 If A precedes B in C's MRO, then A will precede B in the MRO of all
978 subclasses of C.
979
980 Monotonicity.
981 The MRO of a class must be an extension without reordering of the
982 MRO of each of its superclasses.
983
984 Extended Precedence Graph (EPG).
985 Linearization is consistent if there is a path in the EPG from
986 each class to all its successors in the linearization. See
987 the paper for definition of EPG.
Guido van Rossum1f121312002-11-14 19:49:16 +0000988 */
989
Tim Petersea7f75d2002-12-07 21:39:16 +0000990static int
Guido van Rossum1f121312002-11-14 19:49:16 +0000991tail_contains(PyObject *list, int whence, PyObject *o) {
Martin v. Löwis18e16552006-02-15 17:27:45 +0000992 Py_ssize_t j, size;
Guido van Rossum1f121312002-11-14 19:49:16 +0000993 size = PyList_GET_SIZE(list);
994
995 for (j = whence+1; j < size; j++) {
996 if (PyList_GET_ITEM(list, j) == o)
997 return 1;
998 }
999 return 0;
1000}
1001
Guido van Rossum98f33732002-11-25 21:36:54 +00001002static PyObject *
1003class_name(PyObject *cls)
1004{
1005 PyObject *name = PyObject_GetAttrString(cls, "__name__");
1006 if (name == NULL) {
1007 PyErr_Clear();
1008 Py_XDECREF(name);
Walter Dörwald1ab83302007-05-18 17:15:44 +00001009 name = PyObject_ReprStr8(cls);
Guido van Rossum98f33732002-11-25 21:36:54 +00001010 }
1011 if (name == NULL)
1012 return NULL;
Martin v. Löwis9b9905b2007-06-10 21:13:34 +00001013 if (!PyUnicode_Check(name)) {
Guido van Rossum98f33732002-11-25 21:36:54 +00001014 Py_DECREF(name);
1015 return NULL;
1016 }
1017 return name;
1018}
1019
1020static int
1021check_duplicates(PyObject *list)
1022{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001023 Py_ssize_t i, j, n;
Guido van Rossum98f33732002-11-25 21:36:54 +00001024 /* Let's use a quadratic time algorithm,
1025 assuming that the bases lists is short.
1026 */
1027 n = PyList_GET_SIZE(list);
1028 for (i = 0; i < n; i++) {
1029 PyObject *o = PyList_GET_ITEM(list, i);
1030 for (j = i + 1; j < n; j++) {
1031 if (PyList_GET_ITEM(list, j) == o) {
1032 o = class_name(o);
1033 PyErr_Format(PyExc_TypeError,
1034 "duplicate base class %s",
Martin v. Löwis9b9905b2007-06-10 21:13:34 +00001035 o ? PyUnicode_AsString(o) : "?");
Guido van Rossum98f33732002-11-25 21:36:54 +00001036 Py_XDECREF(o);
1037 return -1;
1038 }
1039 }
1040 }
1041 return 0;
1042}
1043
1044/* Raise a TypeError for an MRO order disagreement.
1045
1046 It's hard to produce a good error message. In the absence of better
1047 insight into error reporting, report the classes that were candidates
Guido van Rossumd8faa362007-04-27 19:54:29 +00001048 to be put next into the MRO. There is some conflict between the
Guido van Rossum98f33732002-11-25 21:36:54 +00001049 order in which they should be put in the MRO, but it's hard to
1050 diagnose what constraint can't be satisfied.
1051*/
1052
1053static void
1054set_mro_error(PyObject *to_merge, int *remain)
1055{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001056 Py_ssize_t i, n, off, to_merge_size;
Guido van Rossum98f33732002-11-25 21:36:54 +00001057 char buf[1000];
1058 PyObject *k, *v;
1059 PyObject *set = PyDict_New();
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001060 if (!set) return;
Guido van Rossum98f33732002-11-25 21:36:54 +00001061
1062 to_merge_size = PyList_GET_SIZE(to_merge);
1063 for (i = 0; i < to_merge_size; i++) {
1064 PyObject *L = PyList_GET_ITEM(to_merge, i);
1065 if (remain[i] < PyList_GET_SIZE(L)) {
1066 PyObject *c = PyList_GET_ITEM(L, remain[i]);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001067 if (PyDict_SetItem(set, c, Py_None) < 0) {
1068 Py_DECREF(set);
Guido van Rossum98f33732002-11-25 21:36:54 +00001069 return;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001070 }
Guido van Rossum98f33732002-11-25 21:36:54 +00001071 }
1072 }
1073 n = PyDict_Size(set);
1074
Raymond Hettingerf394df42003-04-06 19:13:41 +00001075 off = PyOS_snprintf(buf, sizeof(buf), "Cannot create a \
1076consistent method resolution\norder (MRO) for bases");
Guido van Rossum98f33732002-11-25 21:36:54 +00001077 i = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001078 while (PyDict_Next(set, &i, &k, &v) && (size_t)off < sizeof(buf)) {
Guido van Rossum98f33732002-11-25 21:36:54 +00001079 PyObject *name = class_name(k);
1080 off += PyOS_snprintf(buf + off, sizeof(buf) - off, " %s",
Martin v. Löwis9b9905b2007-06-10 21:13:34 +00001081 name ? PyUnicode_AsString(name) : "?");
Guido van Rossum98f33732002-11-25 21:36:54 +00001082 Py_XDECREF(name);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001083 if (--n && (size_t)(off+1) < sizeof(buf)) {
Guido van Rossum98f33732002-11-25 21:36:54 +00001084 buf[off++] = ',';
1085 buf[off] = '\0';
1086 }
1087 }
1088 PyErr_SetString(PyExc_TypeError, buf);
1089 Py_DECREF(set);
1090}
1091
Tim Petersea7f75d2002-12-07 21:39:16 +00001092static int
Guido van Rossum1f121312002-11-14 19:49:16 +00001093pmerge(PyObject *acc, PyObject* to_merge) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001094 Py_ssize_t i, j, to_merge_size, empty_cnt;
Guido van Rossum1f121312002-11-14 19:49:16 +00001095 int *remain;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001096 int ok;
Tim Petersea7f75d2002-12-07 21:39:16 +00001097
Guido van Rossum1f121312002-11-14 19:49:16 +00001098 to_merge_size = PyList_GET_SIZE(to_merge);
1099
Guido van Rossum98f33732002-11-25 21:36:54 +00001100 /* remain stores an index into each sublist of to_merge.
1101 remain[i] is the index of the next base in to_merge[i]
1102 that is not included in acc.
1103 */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001104 remain = (int *)PyMem_MALLOC(SIZEOF_INT*to_merge_size);
Guido van Rossum1f121312002-11-14 19:49:16 +00001105 if (remain == NULL)
1106 return -1;
1107 for (i = 0; i < to_merge_size; i++)
1108 remain[i] = 0;
1109
1110 again:
1111 empty_cnt = 0;
1112 for (i = 0; i < to_merge_size; i++) {
1113 PyObject *candidate;
Tim Petersea7f75d2002-12-07 21:39:16 +00001114
Guido van Rossum1f121312002-11-14 19:49:16 +00001115 PyObject *cur_list = PyList_GET_ITEM(to_merge, i);
1116
1117 if (remain[i] >= PyList_GET_SIZE(cur_list)) {
1118 empty_cnt++;
1119 continue;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001120 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001121
Guido van Rossum98f33732002-11-25 21:36:54 +00001122 /* Choose next candidate for MRO.
1123
1124 The input sequences alone can determine the choice.
1125 If not, choose the class which appears in the MRO
1126 of the earliest direct superclass of the new class.
1127 */
1128
Guido van Rossum1f121312002-11-14 19:49:16 +00001129 candidate = PyList_GET_ITEM(cur_list, remain[i]);
1130 for (j = 0; j < to_merge_size; j++) {
1131 PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
Guido van Rossum98f33732002-11-25 21:36:54 +00001132 if (tail_contains(j_lst, remain[j], candidate)) {
Guido van Rossum1f121312002-11-14 19:49:16 +00001133 goto skip; /* continue outer loop */
Guido van Rossum98f33732002-11-25 21:36:54 +00001134 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001135 }
1136 ok = PyList_Append(acc, candidate);
1137 if (ok < 0) {
1138 PyMem_Free(remain);
1139 return -1;
1140 }
1141 for (j = 0; j < to_merge_size; j++) {
1142 PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
Guido van Rossum768158c2002-12-31 16:33:01 +00001143 if (remain[j] < PyList_GET_SIZE(j_lst) &&
1144 PyList_GET_ITEM(j_lst, remain[j]) == candidate) {
Guido van Rossum1f121312002-11-14 19:49:16 +00001145 remain[j]++;
1146 }
1147 }
1148 goto again;
Tim Peters9a6b8d82002-11-14 23:22:33 +00001149 skip: ;
Guido van Rossum1f121312002-11-14 19:49:16 +00001150 }
1151
Guido van Rossum98f33732002-11-25 21:36:54 +00001152 if (empty_cnt == to_merge_size) {
1153 PyMem_FREE(remain);
Guido van Rossum1f121312002-11-14 19:49:16 +00001154 return 0;
Guido van Rossum98f33732002-11-25 21:36:54 +00001155 }
1156 set_mro_error(to_merge, remain);
1157 PyMem_FREE(remain);
Guido van Rossum1f121312002-11-14 19:49:16 +00001158 return -1;
1159}
1160
Tim Peters6d6c1a32001-08-02 04:15:00 +00001161static PyObject *
1162mro_implementation(PyTypeObject *type)
1163{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001164 Py_ssize_t i, n;
1165 int ok;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001166 PyObject *bases, *result;
Guido van Rossum1f121312002-11-14 19:49:16 +00001167 PyObject *to_merge, *bases_aslist;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001168
Guido van Rossum63517572002-06-18 16:44:57 +00001169 if(type->tp_dict == NULL) {
1170 if(PyType_Ready(type) < 0)
1171 return NULL;
1172 }
1173
Guido van Rossum98f33732002-11-25 21:36:54 +00001174 /* Find a superclass linearization that honors the constraints
1175 of the explicit lists of bases and the constraints implied by
Tim Petersea7f75d2002-12-07 21:39:16 +00001176 each base class.
Guido van Rossum98f33732002-11-25 21:36:54 +00001177
1178 to_merge is a list of lists, where each list is a superclass
1179 linearization implied by a base class. The last element of
1180 to_merge is the declared list of bases.
1181 */
1182
Tim Peters6d6c1a32001-08-02 04:15:00 +00001183 bases = type->tp_bases;
1184 n = PyTuple_GET_SIZE(bases);
Guido van Rossum1f121312002-11-14 19:49:16 +00001185
1186 to_merge = PyList_New(n+1);
1187 if (to_merge == NULL)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001188 return NULL;
Guido van Rossum1f121312002-11-14 19:49:16 +00001189
Tim Peters6d6c1a32001-08-02 04:15:00 +00001190 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00001191 PyObject *base = PyTuple_GET_ITEM(bases, i);
1192 PyObject *parentMRO;
Guido van Rossum50e9fb92006-08-17 05:42:55 +00001193 parentMRO = PySequence_List(((PyTypeObject*)base)->tp_mro);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001194 if (parentMRO == NULL) {
Guido van Rossum1f121312002-11-14 19:49:16 +00001195 Py_DECREF(to_merge);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001196 return NULL;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001197 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001198
1199 PyList_SET_ITEM(to_merge, i, parentMRO);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001200 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001201
1202 bases_aslist = PySequence_List(bases);
1203 if (bases_aslist == NULL) {
1204 Py_DECREF(to_merge);
1205 return NULL;
1206 }
Guido van Rossum98f33732002-11-25 21:36:54 +00001207 /* This is just a basic sanity check. */
1208 if (check_duplicates(bases_aslist) < 0) {
1209 Py_DECREF(to_merge);
1210 Py_DECREF(bases_aslist);
1211 return NULL;
1212 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001213 PyList_SET_ITEM(to_merge, n, bases_aslist);
1214
1215 result = Py_BuildValue("[O]", (PyObject *)type);
1216 if (result == NULL) {
1217 Py_DECREF(to_merge);
1218 return NULL;
1219 }
1220
1221 ok = pmerge(result, to_merge);
1222 Py_DECREF(to_merge);
1223 if (ok < 0) {
1224 Py_DECREF(result);
1225 return NULL;
1226 }
1227
Tim Peters6d6c1a32001-08-02 04:15:00 +00001228 return result;
1229}
1230
1231static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001232mro_external(PyObject *self)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001233{
1234 PyTypeObject *type = (PyTypeObject *)self;
1235
Tim Peters6d6c1a32001-08-02 04:15:00 +00001236 return mro_implementation(type);
1237}
1238
1239static int
1240mro_internal(PyTypeObject *type)
1241{
1242 PyObject *mro, *result, *tuple;
Armin Rigo037d1e02005-12-29 17:07:39 +00001243 int checkit = 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001244
1245 if (type->ob_type == &PyType_Type) {
1246 result = mro_implementation(type);
1247 }
1248 else {
Guido van Rossum60718732001-08-28 17:47:51 +00001249 static PyObject *mro_str;
Armin Rigo037d1e02005-12-29 17:07:39 +00001250 checkit = 1;
Guido van Rossum60718732001-08-28 17:47:51 +00001251 mro = lookup_method((PyObject *)type, "mro", &mro_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001252 if (mro == NULL)
1253 return -1;
1254 result = PyObject_CallObject(mro, NULL);
1255 Py_DECREF(mro);
1256 }
1257 if (result == NULL)
1258 return -1;
1259 tuple = PySequence_Tuple(result);
1260 Py_DECREF(result);
Armin Rigo037d1e02005-12-29 17:07:39 +00001261 if (tuple == NULL)
1262 return -1;
1263 if (checkit) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001264 Py_ssize_t i, len;
Armin Rigo037d1e02005-12-29 17:07:39 +00001265 PyObject *cls;
1266 PyTypeObject *solid;
1267
1268 solid = solid_base(type);
1269
1270 len = PyTuple_GET_SIZE(tuple);
1271
1272 for (i = 0; i < len; i++) {
1273 PyTypeObject *t;
1274 cls = PyTuple_GET_ITEM(tuple, i);
Guido van Rossum50e9fb92006-08-17 05:42:55 +00001275 if (!PyType_Check(cls)) {
Armin Rigo037d1e02005-12-29 17:07:39 +00001276 PyErr_Format(PyExc_TypeError,
1277 "mro() returned a non-class ('%.500s')",
1278 cls->ob_type->tp_name);
Neal Norwitz50bf51a2006-01-02 02:46:54 +00001279 Py_DECREF(tuple);
Armin Rigo037d1e02005-12-29 17:07:39 +00001280 return -1;
1281 }
1282 t = (PyTypeObject*)cls;
1283 if (!PyType_IsSubtype(solid, solid_base(t))) {
1284 PyErr_Format(PyExc_TypeError,
1285 "mro() returned base with unsuitable layout ('%.500s')",
1286 t->tp_name);
Neal Norwitz50bf51a2006-01-02 02:46:54 +00001287 Py_DECREF(tuple);
Armin Rigo037d1e02005-12-29 17:07:39 +00001288 return -1;
1289 }
1290 }
1291 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001292 type->tp_mro = tuple;
1293 return 0;
1294}
1295
1296
1297/* Calculate the best base amongst multiple base classes.
1298 This is the first one that's on the path to the "solid base". */
1299
1300static PyTypeObject *
1301best_base(PyObject *bases)
1302{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001303 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001304 PyTypeObject *base, *winner, *candidate, *base_i;
Tim Petersa91e9642001-11-14 23:32:33 +00001305 PyObject *base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001306
1307 assert(PyTuple_Check(bases));
1308 n = PyTuple_GET_SIZE(bases);
1309 assert(n > 0);
Tim Petersa91e9642001-11-14 23:32:33 +00001310 base = NULL;
1311 winner = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001312 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00001313 base_proto = PyTuple_GET_ITEM(bases, i);
Tim Petersa91e9642001-11-14 23:32:33 +00001314 if (!PyType_Check(base_proto)) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001315 PyErr_SetString(
1316 PyExc_TypeError,
1317 "bases must be types");
1318 return NULL;
1319 }
Tim Petersa91e9642001-11-14 23:32:33 +00001320 base_i = (PyTypeObject *)base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001321 if (base_i->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001322 if (PyType_Ready(base_i) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001323 return NULL;
1324 }
1325 candidate = solid_base(base_i);
Tim Petersa91e9642001-11-14 23:32:33 +00001326 if (winner == NULL) {
1327 winner = candidate;
1328 base = base_i;
1329 }
1330 else if (PyType_IsSubtype(winner, candidate))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001331 ;
1332 else if (PyType_IsSubtype(candidate, winner)) {
1333 winner = candidate;
1334 base = base_i;
1335 }
1336 else {
1337 PyErr_SetString(
1338 PyExc_TypeError,
1339 "multiple bases have "
1340 "instance lay-out conflict");
1341 return NULL;
1342 }
1343 }
Guido van Rossume54616c2001-12-14 04:19:56 +00001344 if (base == NULL)
1345 PyErr_SetString(PyExc_TypeError,
1346 "a new-style class can't have only classic bases");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001347 return base;
1348}
1349
1350static int
1351extra_ivars(PyTypeObject *type, PyTypeObject *base)
1352{
Neil Schemenauerc806c882001-08-29 23:54:54 +00001353 size_t t_size = type->tp_basicsize;
1354 size_t b_size = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001355
Guido van Rossum9676b222001-08-17 20:32:36 +00001356 assert(t_size >= b_size); /* Else type smaller than base! */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001357 if (type->tp_itemsize || base->tp_itemsize) {
1358 /* If itemsize is involved, stricter rules */
1359 return t_size != b_size ||
1360 type->tp_itemsize != base->tp_itemsize;
1361 }
Guido van Rossum9676b222001-08-17 20:32:36 +00001362 if (type->tp_weaklistoffset && base->tp_weaklistoffset == 0 &&
Guido van Rossum360e4b82007-05-14 22:51:27 +00001363 type->tp_weaklistoffset + sizeof(PyObject *) == t_size &&
1364 type->tp_flags & Py_TPFLAGS_HEAPTYPE)
Guido van Rossum9676b222001-08-17 20:32:36 +00001365 t_size -= sizeof(PyObject *);
1366 if (type->tp_dictoffset && base->tp_dictoffset == 0 &&
Guido van Rossum360e4b82007-05-14 22:51:27 +00001367 type->tp_dictoffset + sizeof(PyObject *) == t_size &&
1368 type->tp_flags & Py_TPFLAGS_HEAPTYPE)
Guido van Rossum9676b222001-08-17 20:32:36 +00001369 t_size -= sizeof(PyObject *);
1370
1371 return t_size != b_size;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001372}
1373
1374static PyTypeObject *
1375solid_base(PyTypeObject *type)
1376{
1377 PyTypeObject *base;
1378
1379 if (type->tp_base)
1380 base = solid_base(type->tp_base);
1381 else
1382 base = &PyBaseObject_Type;
1383 if (extra_ivars(type, base))
1384 return type;
1385 else
1386 return base;
1387}
1388
Jeremy Hylton938ace62002-07-17 16:30:39 +00001389static void object_dealloc(PyObject *);
1390static int object_init(PyObject *, PyObject *, PyObject *);
1391static int update_slot(PyTypeObject *, PyObject *);
1392static void fixup_slot_dispatchers(PyTypeObject *);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001393
Guido van Rossum360e4b82007-05-14 22:51:27 +00001394/*
1395 * Helpers for __dict__ descriptor. We don't want to expose the dicts
1396 * inherited from various builtin types. The builtin base usually provides
1397 * its own __dict__ descriptor, so we use that when we can.
1398 */
1399static PyTypeObject *
1400get_builtin_base_with_dict(PyTypeObject *type)
1401{
1402 while (type->tp_base != NULL) {
1403 if (type->tp_dictoffset != 0 &&
1404 !(type->tp_flags & Py_TPFLAGS_HEAPTYPE))
1405 return type;
1406 type = type->tp_base;
1407 }
1408 return NULL;
1409}
1410
1411static PyObject *
1412get_dict_descriptor(PyTypeObject *type)
1413{
1414 static PyObject *dict_str;
1415 PyObject *descr;
1416
1417 if (dict_str == NULL) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00001418 dict_str = PyUnicode_InternFromString("__dict__");
Guido van Rossum360e4b82007-05-14 22:51:27 +00001419 if (dict_str == NULL)
1420 return NULL;
1421 }
1422 descr = _PyType_Lookup(type, dict_str);
1423 if (descr == NULL || !PyDescr_IsData(descr))
1424 return NULL;
1425
1426 return descr;
1427}
1428
1429static void
1430raise_dict_descr_error(PyObject *obj)
1431{
1432 PyErr_Format(PyExc_TypeError,
1433 "this __dict__ descriptor does not support "
1434 "'%.200s' objects", obj->ob_type->tp_name);
1435}
1436
Tim Peters6d6c1a32001-08-02 04:15:00 +00001437static PyObject *
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001438subtype_dict(PyObject *obj, void *context)
1439{
Guido van Rossum360e4b82007-05-14 22:51:27 +00001440 PyObject **dictptr;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001441 PyObject *dict;
Guido van Rossum360e4b82007-05-14 22:51:27 +00001442 PyTypeObject *base;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001443
Guido van Rossum360e4b82007-05-14 22:51:27 +00001444 base = get_builtin_base_with_dict(obj->ob_type);
1445 if (base != NULL) {
1446 descrgetfunc func;
1447 PyObject *descr = get_dict_descriptor(base);
1448 if (descr == NULL) {
1449 raise_dict_descr_error(obj);
1450 return NULL;
1451 }
1452 func = descr->ob_type->tp_descr_get;
1453 if (func == NULL) {
1454 raise_dict_descr_error(obj);
1455 return NULL;
1456 }
1457 return func(descr, obj, (PyObject *)(obj->ob_type));
1458 }
1459
1460 dictptr = _PyObject_GetDictPtr(obj);
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001461 if (dictptr == NULL) {
1462 PyErr_SetString(PyExc_AttributeError,
1463 "This object has no __dict__");
1464 return NULL;
1465 }
1466 dict = *dictptr;
Guido van Rossum3926a632001-09-25 16:25:58 +00001467 if (dict == NULL)
1468 *dictptr = dict = PyDict_New();
1469 Py_XINCREF(dict);
1470 return dict;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001471}
1472
Guido van Rossum6661be32001-10-26 04:26:12 +00001473static int
1474subtype_setdict(PyObject *obj, PyObject *value, void *context)
1475{
Guido van Rossum360e4b82007-05-14 22:51:27 +00001476 PyObject **dictptr;
Guido van Rossum6661be32001-10-26 04:26:12 +00001477 PyObject *dict;
Guido van Rossum360e4b82007-05-14 22:51:27 +00001478 PyTypeObject *base;
Guido van Rossum6661be32001-10-26 04:26:12 +00001479
Guido van Rossum360e4b82007-05-14 22:51:27 +00001480 base = get_builtin_base_with_dict(obj->ob_type);
1481 if (base != NULL) {
1482 descrsetfunc func;
1483 PyObject *descr = get_dict_descriptor(base);
1484 if (descr == NULL) {
1485 raise_dict_descr_error(obj);
1486 return -1;
1487 }
1488 func = descr->ob_type->tp_descr_set;
1489 if (func == NULL) {
1490 raise_dict_descr_error(obj);
1491 return -1;
1492 }
1493 return func(descr, obj, value);
1494 }
1495
1496 dictptr = _PyObject_GetDictPtr(obj);
Guido van Rossum6661be32001-10-26 04:26:12 +00001497 if (dictptr == NULL) {
1498 PyErr_SetString(PyExc_AttributeError,
1499 "This object has no __dict__");
1500 return -1;
1501 }
Guido van Rossumd331cb52001-12-05 19:46:42 +00001502 if (value != NULL && !PyDict_Check(value)) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001503 PyErr_Format(PyExc_TypeError,
1504 "__dict__ must be set to a dictionary, "
1505 "not a '%.200s'", value->ob_type->tp_name);
Guido van Rossum6661be32001-10-26 04:26:12 +00001506 return -1;
1507 }
1508 dict = *dictptr;
Guido van Rossumd331cb52001-12-05 19:46:42 +00001509 Py_XINCREF(value);
Guido van Rossum6661be32001-10-26 04:26:12 +00001510 *dictptr = value;
1511 Py_XDECREF(dict);
1512 return 0;
1513}
1514
Guido van Rossumad47da02002-08-12 19:05:44 +00001515static PyObject *
1516subtype_getweakref(PyObject *obj, void *context)
1517{
1518 PyObject **weaklistptr;
1519 PyObject *result;
1520
1521 if (obj->ob_type->tp_weaklistoffset == 0) {
1522 PyErr_SetString(PyExc_AttributeError,
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001523 "This object has no __weakref__");
Guido van Rossumad47da02002-08-12 19:05:44 +00001524 return NULL;
1525 }
1526 assert(obj->ob_type->tp_weaklistoffset > 0);
1527 assert(obj->ob_type->tp_weaklistoffset + sizeof(PyObject *) <=
Guido van Rossum3747a0f2002-08-12 19:25:08 +00001528 (size_t)(obj->ob_type->tp_basicsize));
Guido van Rossumad47da02002-08-12 19:05:44 +00001529 weaklistptr = (PyObject **)
Guido van Rossum3747a0f2002-08-12 19:25:08 +00001530 ((char *)obj + obj->ob_type->tp_weaklistoffset);
Guido van Rossumad47da02002-08-12 19:05:44 +00001531 if (*weaklistptr == NULL)
1532 result = Py_None;
1533 else
1534 result = *weaklistptr;
1535 Py_INCREF(result);
1536 return result;
1537}
1538
Guido van Rossum373c7412003-01-07 13:41:37 +00001539/* Three variants on the subtype_getsets list. */
1540
1541static PyGetSetDef subtype_getsets_full[] = {
Guido van Rossumad47da02002-08-12 19:05:44 +00001542 {"__dict__", subtype_dict, subtype_setdict,
Neal Norwitz858e34f2002-08-13 17:18:45 +00001543 PyDoc_STR("dictionary for instance variables (if defined)")},
Guido van Rossumad47da02002-08-12 19:05:44 +00001544 {"__weakref__", subtype_getweakref, NULL,
Neal Norwitz858e34f2002-08-13 17:18:45 +00001545 PyDoc_STR("list of weak references to the object (if defined)")},
Guido van Rossumad47da02002-08-12 19:05:44 +00001546 {0}
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001547};
1548
Guido van Rossum373c7412003-01-07 13:41:37 +00001549static PyGetSetDef subtype_getsets_dict_only[] = {
1550 {"__dict__", subtype_dict, subtype_setdict,
1551 PyDoc_STR("dictionary for instance variables (if defined)")},
1552 {0}
1553};
1554
1555static PyGetSetDef subtype_getsets_weakref_only[] = {
1556 {"__weakref__", subtype_getweakref, NULL,
1557 PyDoc_STR("list of weak references to the object (if defined)")},
1558 {0}
1559};
1560
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001561static int
1562valid_identifier(PyObject *s)
1563{
Guido van Rossum03013a02002-07-16 14:30:28 +00001564 unsigned char *p;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001565 Py_ssize_t i, n;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001566
Martin v. Löwis5b222132007-06-10 09:51:05 +00001567 if (!PyUnicode_Check(s)) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001568 PyErr_Format(PyExc_TypeError,
1569 "__slots__ items must be strings, not '%.200s'",
1570 s->ob_type->tp_name);
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001571 return 0;
1572 }
Martin v. Löwis5b222132007-06-10 09:51:05 +00001573 p = (unsigned char *) PyUnicode_AsString(s);
1574 n = strlen((char*)p)/*XXX PyString_GET_SIZE(s)*/;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001575 /* We must reject an empty name. As a hack, we bump the
1576 length to 1 so that the loop will balk on the trailing \0. */
1577 if (n == 0)
1578 n = 1;
1579 for (i = 0; i < n; i++, p++) {
1580 if (!(i == 0 ? isalpha(*p) : isalnum(*p)) && *p != '_') {
1581 PyErr_SetString(PyExc_TypeError,
1582 "__slots__ must be identifiers");
1583 return 0;
1584 }
1585 }
1586 return 1;
1587}
1588
Martin v. Löwisd919a592002-10-14 21:07:28 +00001589/* Replace Unicode objects in slots. */
1590
1591static PyObject *
Martin v. Löwiseb079f12006-02-16 14:32:27 +00001592_unicode_to_string(PyObject *slots, Py_ssize_t nslots)
Martin v. Löwisd919a592002-10-14 21:07:28 +00001593{
Guido van Rossumd8faa362007-04-27 19:54:29 +00001594 PyObject *tmp = NULL;
1595 PyObject *slot_name, *new_name;
Martin v. Löwiseb079f12006-02-16 14:32:27 +00001596 Py_ssize_t i;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001597
Martin v. Löwisd919a592002-10-14 21:07:28 +00001598 for (i = 0; i < nslots; i++) {
Guido van Rossumd8faa362007-04-27 19:54:29 +00001599 if (PyUnicode_Check(slot_name = PyTuple_GET_ITEM(slots, i))) {
1600 if (tmp == NULL) {
1601 tmp = PySequence_List(slots);
Martin v. Löwisd919a592002-10-14 21:07:28 +00001602 if (tmp == NULL)
1603 return NULL;
1604 }
Guido van Rossumd8faa362007-04-27 19:54:29 +00001605 new_name = _PyUnicode_AsDefaultEncodedString(slot_name,
1606 NULL);
1607 if (new_name == NULL) {
Martin v. Löwisd919a592002-10-14 21:07:28 +00001608 Py_DECREF(tmp);
Guido van Rossumd8faa362007-04-27 19:54:29 +00001609 return NULL;
Martin v. Löwisd919a592002-10-14 21:07:28 +00001610 }
Guido van Rossumd8faa362007-04-27 19:54:29 +00001611 Py_INCREF(new_name);
1612 PyList_SET_ITEM(tmp, i, new_name);
1613 Py_DECREF(slot_name);
Martin v. Löwisd919a592002-10-14 21:07:28 +00001614 }
1615 }
Guido van Rossumd8faa362007-04-27 19:54:29 +00001616 if (tmp != NULL) {
1617 slots = PyList_AsTuple(tmp);
1618 Py_DECREF(tmp);
1619 }
1620 return slots;
Martin v. Löwisd919a592002-10-14 21:07:28 +00001621}
Martin v. Löwisd919a592002-10-14 21:07:28 +00001622
Guido van Rossumd8faa362007-04-27 19:54:29 +00001623/* Forward */
1624static int
1625object_init(PyObject *self, PyObject *args, PyObject *kwds);
1626
1627static int
1628type_init(PyObject *cls, PyObject *args, PyObject *kwds)
1629{
1630 int res;
1631
1632 assert(args != NULL && PyTuple_Check(args));
1633 assert(kwds == NULL || PyDict_Check(kwds));
1634
1635 if (kwds != NULL && PyDict_Check(kwds) && PyDict_Size(kwds) != 0) {
1636 PyErr_SetString(PyExc_TypeError,
1637 "type.__init__() takes no keyword arguments");
1638 return -1;
1639 }
1640
1641 if (args != NULL && PyTuple_Check(args) &&
1642 (PyTuple_GET_SIZE(args) != 1 && PyTuple_GET_SIZE(args) != 3)) {
1643 PyErr_SetString(PyExc_TypeError,
1644 "type.__init__() takes 1 or 3 arguments");
1645 return -1;
1646 }
1647
1648 /* Call object.__init__(self) now. */
1649 /* XXX Could call super(type, cls).__init__() but what's the point? */
1650 args = PyTuple_GetSlice(args, 0, 0);
1651 res = object_init(cls, args, NULL);
1652 Py_DECREF(args);
1653 return res;
1654}
1655
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001656static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00001657type_new(PyTypeObject *metatype, PyObject *args, PyObject *kwds)
1658{
1659 PyObject *name, *bases, *dict;
Martin v. Löwis15e62742006-02-27 16:46:16 +00001660 static char *kwlist[] = {"name", "bases", "dict", 0};
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001661 PyObject *slots, *tmp, *newslots;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001662 PyTypeObject *type, *base, *tmptype, *winner;
Guido van Rossume5c691a2003-03-07 15:13:17 +00001663 PyHeapTypeObject *et;
Guido van Rossum6f799372001-09-20 20:46:19 +00001664 PyMemberDef *mp;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001665 Py_ssize_t i, nbases, nslots, slotoffset, add_dict, add_weak;
Guido van Rossumad47da02002-08-12 19:05:44 +00001666 int j, may_add_dict, may_add_weak;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001667
Tim Peters3abca122001-10-27 19:37:48 +00001668 assert(args != NULL && PyTuple_Check(args));
1669 assert(kwds == NULL || PyDict_Check(kwds));
1670
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001671 /* Special case: type(x) should return x->ob_type */
Tim Peters3abca122001-10-27 19:37:48 +00001672 {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001673 const Py_ssize_t nargs = PyTuple_GET_SIZE(args);
1674 const Py_ssize_t nkwds = kwds == NULL ? 0 : PyDict_Size(kwds);
Tim Peters3abca122001-10-27 19:37:48 +00001675
1676 if (PyType_CheckExact(metatype) && nargs == 1 && nkwds == 0) {
1677 PyObject *x = PyTuple_GET_ITEM(args, 0);
1678 Py_INCREF(x->ob_type);
1679 return (PyObject *) x->ob_type;
1680 }
1681
1682 /* SF bug 475327 -- if that didn't trigger, we need 3
1683 arguments. but PyArg_ParseTupleAndKeywords below may give
1684 a msg saying type() needs exactly 3. */
1685 if (nargs + nkwds != 3) {
1686 PyErr_SetString(PyExc_TypeError,
1687 "type() takes 1 or 3 arguments");
1688 return NULL;
1689 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001690 }
1691
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001692 /* Check arguments: (name, bases, dict) */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001693 if (!PyArg_ParseTupleAndKeywords(args, kwds, "SO!O!:type", kwlist,
1694 &name,
1695 &PyTuple_Type, &bases,
1696 &PyDict_Type, &dict))
1697 return NULL;
1698
1699 /* Determine the proper metatype to deal with this,
1700 and check for metatype conflicts while we're at it.
1701 Note that if some other metatype wins to contract,
1702 it's possible that its instances are not types. */
1703 nbases = PyTuple_GET_SIZE(bases);
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001704 winner = metatype;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001705 for (i = 0; i < nbases; i++) {
1706 tmp = PyTuple_GET_ITEM(bases, i);
1707 tmptype = tmp->ob_type;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001708 if (PyType_IsSubtype(winner, tmptype))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001709 continue;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001710 if (PyType_IsSubtype(tmptype, winner)) {
1711 winner = tmptype;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001712 continue;
1713 }
1714 PyErr_SetString(PyExc_TypeError,
Guido van Rossum636688d2003-04-23 12:07:22 +00001715 "metaclass conflict: "
1716 "the metaclass of a derived class "
1717 "must be a (non-strict) subclass "
1718 "of the metaclasses of all its bases");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001719 return NULL;
1720 }
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001721 if (winner != metatype) {
1722 if (winner->tp_new != type_new) /* Pass it to the winner */
1723 return winner->tp_new(winner, args, kwds);
1724 metatype = winner;
1725 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001726
1727 /* Adjust for empty tuple bases */
1728 if (nbases == 0) {
Raymond Hettinger8ae46892003-10-12 19:09:37 +00001729 bases = PyTuple_Pack(1, &PyBaseObject_Type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001730 if (bases == NULL)
1731 return NULL;
1732 nbases = 1;
1733 }
1734 else
1735 Py_INCREF(bases);
1736
1737 /* XXX From here until type is allocated, "return NULL" leaks bases! */
1738
1739 /* Calculate best base, and check that all bases are type objects */
1740 base = best_base(bases);
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001741 if (base == NULL) {
1742 Py_DECREF(bases);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001743 return NULL;
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001744 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001745 if (!PyType_HasFeature(base, Py_TPFLAGS_BASETYPE)) {
1746 PyErr_Format(PyExc_TypeError,
1747 "type '%.100s' is not an acceptable base type",
1748 base->tp_name);
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001749 Py_DECREF(bases);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001750 return NULL;
1751 }
1752
Tim Peters6d6c1a32001-08-02 04:15:00 +00001753 /* Check for a __slots__ sequence variable in dict, and count it */
1754 slots = PyDict_GetItemString(dict, "__slots__");
1755 nslots = 0;
Guido van Rossum9676b222001-08-17 20:32:36 +00001756 add_dict = 0;
1757 add_weak = 0;
Guido van Rossumad47da02002-08-12 19:05:44 +00001758 may_add_dict = base->tp_dictoffset == 0;
1759 may_add_weak = base->tp_weaklistoffset == 0 && base->tp_itemsize == 0;
1760 if (slots == NULL) {
1761 if (may_add_dict) {
1762 add_dict++;
1763 }
1764 if (may_add_weak) {
1765 add_weak++;
1766 }
1767 }
1768 else {
1769 /* Have slots */
1770
Tim Peters6d6c1a32001-08-02 04:15:00 +00001771 /* Make it into a tuple */
Guido van Rossumd8faa362007-04-27 19:54:29 +00001772 if (PyString_Check(slots) || PyUnicode_Check(slots))
Raymond Hettinger8ae46892003-10-12 19:09:37 +00001773 slots = PyTuple_Pack(1, slots);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001774 else
1775 slots = PySequence_Tuple(slots);
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001776 if (slots == NULL) {
1777 Py_DECREF(bases);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001778 return NULL;
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001779 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001780 assert(PyTuple_Check(slots));
1781
1782 /* Are slots allowed? */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001783 nslots = PyTuple_GET_SIZE(slots);
Jeremy Hylton1c7a0ea2003-07-16 16:08:23 +00001784 if (nslots > 0 && base->tp_itemsize != 0) {
Guido van Rossumc4141872001-08-30 04:43:35 +00001785 PyErr_Format(PyExc_TypeError,
1786 "nonempty __slots__ "
1787 "not supported for subtype of '%s'",
1788 base->tp_name);
Guido van Rossumad47da02002-08-12 19:05:44 +00001789 bad_slots:
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001790 Py_DECREF(bases);
Guido van Rossumad47da02002-08-12 19:05:44 +00001791 Py_DECREF(slots);
Guido van Rossumc4141872001-08-30 04:43:35 +00001792 return NULL;
1793 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001794
1795 /* Check for valid slot names and two special cases */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001796 for (i = 0; i < nslots; i++) {
Guido van Rossumad47da02002-08-12 19:05:44 +00001797 PyObject *tmp = PyTuple_GET_ITEM(slots, i);
Guido van Rossumad47da02002-08-12 19:05:44 +00001798 if (!valid_identifier(tmp))
1799 goto bad_slots;
Martin v. Löwis5b222132007-06-10 09:51:05 +00001800 assert(PyUnicode_Check(tmp));
1801 if (PyUnicode_CompareWithASCIIString(tmp, "__dict__") == 0) {
Guido van Rossumad47da02002-08-12 19:05:44 +00001802 if (!may_add_dict || add_dict) {
1803 PyErr_SetString(PyExc_TypeError,
1804 "__dict__ slot disallowed: "
1805 "we already got one");
1806 goto bad_slots;
1807 }
1808 add_dict++;
1809 }
Martin v. Löwis5b222132007-06-10 09:51:05 +00001810 if (PyUnicode_CompareWithASCIIString(tmp, "__weakref__") == 0) {
Guido van Rossumad47da02002-08-12 19:05:44 +00001811 if (!may_add_weak || add_weak) {
1812 PyErr_SetString(PyExc_TypeError,
1813 "__weakref__ slot disallowed: "
1814 "either we already got one, "
1815 "or __itemsize__ != 0");
1816 goto bad_slots;
1817 }
1818 add_weak++;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001819 }
1820 }
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001821
Guido van Rossumd8faa362007-04-27 19:54:29 +00001822 /* Copy slots into a list, mangle names and sort them.
1823 Sorted names are needed for __class__ assignment.
1824 Convert them back to tuple at the end.
1825 */
1826 newslots = PyList_New(nslots - add_dict - add_weak);
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001827 if (newslots == NULL)
Guido van Rossumad47da02002-08-12 19:05:44 +00001828 goto bad_slots;
1829 for (i = j = 0; i < nslots; i++) {
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001830 tmp = PyTuple_GET_ITEM(slots, i);
Martin v. Löwis5b222132007-06-10 09:51:05 +00001831 if ((add_dict &&
1832 PyUnicode_CompareWithASCIIString(tmp, "__dict__") == 0) ||
1833 (add_weak &&
1834 PyUnicode_CompareWithASCIIString(tmp, "__weakref__") == 0))
Guido van Rossumad47da02002-08-12 19:05:44 +00001835 continue;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001836 tmp =_Py_Mangle(name, tmp);
Guido van Rossumd8faa362007-04-27 19:54:29 +00001837 if (!tmp)
1838 goto bad_slots;
1839 PyList_SET_ITEM(newslots, j, tmp);
Guido van Rossumad47da02002-08-12 19:05:44 +00001840 j++;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001841 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001842 assert(j == nslots - add_dict - add_weak);
1843 nslots = j;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001844 Py_DECREF(slots);
Guido van Rossumd8faa362007-04-27 19:54:29 +00001845 if (PyList_Sort(newslots) == -1) {
1846 Py_DECREF(bases);
1847 Py_DECREF(newslots);
1848 return NULL;
1849 }
1850 slots = PyList_AsTuple(newslots);
1851 Py_DECREF(newslots);
1852 if (slots == NULL) {
1853 Py_DECREF(bases);
1854 return NULL;
1855 }
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001856
Guido van Rossumad47da02002-08-12 19:05:44 +00001857 /* Secondary bases may provide weakrefs or dict */
1858 if (nbases > 1 &&
1859 ((may_add_dict && !add_dict) ||
1860 (may_add_weak && !add_weak))) {
1861 for (i = 0; i < nbases; i++) {
1862 tmp = PyTuple_GET_ITEM(bases, i);
1863 if (tmp == (PyObject *)base)
1864 continue; /* Skip primary base */
Guido van Rossumad47da02002-08-12 19:05:44 +00001865 assert(PyType_Check(tmp));
1866 tmptype = (PyTypeObject *)tmp;
1867 if (may_add_dict && !add_dict &&
1868 tmptype->tp_dictoffset != 0)
1869 add_dict++;
1870 if (may_add_weak && !add_weak &&
1871 tmptype->tp_weaklistoffset != 0)
1872 add_weak++;
1873 if (may_add_dict && !add_dict)
1874 continue;
1875 if (may_add_weak && !add_weak)
1876 continue;
1877 /* Nothing more to check */
1878 break;
1879 }
1880 }
Guido van Rossum9676b222001-08-17 20:32:36 +00001881 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001882
1883 /* XXX From here until type is safely allocated,
1884 "return NULL" may leak slots! */
1885
1886 /* Allocate the type object */
1887 type = (PyTypeObject *)metatype->tp_alloc(metatype, nslots);
Guido van Rossumad47da02002-08-12 19:05:44 +00001888 if (type == NULL) {
1889 Py_XDECREF(slots);
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001890 Py_DECREF(bases);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001891 return NULL;
Guido van Rossumad47da02002-08-12 19:05:44 +00001892 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001893
1894 /* Keep name and slots alive in the extended type object */
Guido van Rossume5c691a2003-03-07 15:13:17 +00001895 et = (PyHeapTypeObject *)type;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001896 Py_INCREF(name);
Georg Brandlc255c7b2006-02-20 22:27:28 +00001897 et->ht_name = name;
1898 et->ht_slots = slots;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001899
Guido van Rossumdc91b992001-08-08 22:26:22 +00001900 /* Initialize tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001901 type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE |
1902 Py_TPFLAGS_BASETYPE;
Guido van Rossum048eb752001-10-02 21:24:57 +00001903 if (base->tp_flags & Py_TPFLAGS_HAVE_GC)
1904 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossumdc91b992001-08-08 22:26:22 +00001905
Guido van Rossumdc91b992001-08-08 22:26:22 +00001906 /* Initialize essential fields */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001907 type->tp_as_number = &et->as_number;
1908 type->tp_as_sequence = &et->as_sequence;
1909 type->tp_as_mapping = &et->as_mapping;
1910 type->tp_as_buffer = &et->as_buffer;
Martin v. Löwis5b222132007-06-10 09:51:05 +00001911 if (PyString_Check(name))
1912 type->tp_name = PyString_AsString(name);
1913 else {
1914 type->tp_name = PyUnicode_AsString(name);
1915 if (!type->tp_name) {
1916 Py_DECREF(type);
1917 return NULL;
1918 }
1919 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001920
1921 /* Set tp_base and tp_bases */
1922 type->tp_bases = bases;
1923 Py_INCREF(base);
1924 type->tp_base = base;
1925
Guido van Rossum687ae002001-10-15 22:03:32 +00001926 /* Initialize tp_dict from passed-in dict */
1927 type->tp_dict = dict = PyDict_Copy(dict);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001928 if (dict == NULL) {
1929 Py_DECREF(type);
1930 return NULL;
1931 }
1932
Guido van Rossumc3542212001-08-16 09:18:56 +00001933 /* Set __module__ in the dict */
1934 if (PyDict_GetItemString(dict, "__module__") == NULL) {
1935 tmp = PyEval_GetGlobals();
1936 if (tmp != NULL) {
1937 tmp = PyDict_GetItemString(tmp, "__name__");
1938 if (tmp != NULL) {
1939 if (PyDict_SetItemString(dict, "__module__",
1940 tmp) < 0)
1941 return NULL;
1942 }
1943 }
1944 }
1945
Tim Peters2f93e282001-10-04 05:27:00 +00001946 /* Set tp_doc to a copy of dict['__doc__'], if the latter is there
Tim Peters24008312002-03-17 18:56:20 +00001947 and is a string. The __doc__ accessor will first look for tp_doc;
1948 if that fails, it will still look into __dict__.
Tim Peters2f93e282001-10-04 05:27:00 +00001949 */
1950 {
1951 PyObject *doc = PyDict_GetItemString(dict, "__doc__");
1952 if (doc != NULL && PyString_Check(doc)) {
1953 const size_t n = (size_t)PyString_GET_SIZE(doc);
Guido van Rossumd8faa362007-04-27 19:54:29 +00001954 char *tp_doc = (char *)PyObject_MALLOC(n+1);
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00001955 if (tp_doc == NULL) {
Tim Peters2f93e282001-10-04 05:27:00 +00001956 Py_DECREF(type);
1957 return NULL;
1958 }
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00001959 memcpy(tp_doc, PyString_AS_STRING(doc), n+1);
Guido van Rossumd8faa362007-04-27 19:54:29 +00001960 type->tp_doc = tp_doc;
Tim Peters2f93e282001-10-04 05:27:00 +00001961 }
1962 }
1963
Tim Peters6d6c1a32001-08-02 04:15:00 +00001964 /* Special-case __new__: if it's a plain function,
1965 make it a static function */
1966 tmp = PyDict_GetItemString(dict, "__new__");
1967 if (tmp != NULL && PyFunction_Check(tmp)) {
1968 tmp = PyStaticMethod_New(tmp);
1969 if (tmp == NULL) {
1970 Py_DECREF(type);
1971 return NULL;
1972 }
1973 PyDict_SetItemString(dict, "__new__", tmp);
1974 Py_DECREF(tmp);
1975 }
1976
1977 /* Add descriptors for custom slots from __slots__, or for __dict__ */
Guido van Rossume5c691a2003-03-07 15:13:17 +00001978 mp = PyHeapType_GET_MEMBERS(et);
Neil Schemenauerc806c882001-08-29 23:54:54 +00001979 slotoffset = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001980 if (slots != NULL) {
1981 for (i = 0; i < nslots; i++, mp++) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00001982 mp->name = PyUnicode_AsString(
Tim Peters6d6c1a32001-08-02 04:15:00 +00001983 PyTuple_GET_ITEM(slots, i));
Guido van Rossum64b206c2001-12-04 17:13:22 +00001984 mp->type = T_OBJECT_EX;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001985 mp->offset = slotoffset;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001986
1987 /* __dict__ and __weakref__ are already filtered out */
1988 assert(strcmp(mp->name, "__dict__") != 0);
1989 assert(strcmp(mp->name, "__weakref__") != 0);
1990
Tim Peters6d6c1a32001-08-02 04:15:00 +00001991 slotoffset += sizeof(PyObject *);
1992 }
1993 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001994 if (add_dict) {
1995 if (base->tp_itemsize)
1996 type->tp_dictoffset = -(long)sizeof(PyObject *);
1997 else
1998 type->tp_dictoffset = slotoffset;
1999 slotoffset += sizeof(PyObject *);
2000 }
2001 if (add_weak) {
2002 assert(!base->tp_itemsize);
2003 type->tp_weaklistoffset = slotoffset;
2004 slotoffset += sizeof(PyObject *);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002005 }
2006 type->tp_basicsize = slotoffset;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00002007 type->tp_itemsize = base->tp_itemsize;
Guido van Rossume5c691a2003-03-07 15:13:17 +00002008 type->tp_members = PyHeapType_GET_MEMBERS(et);
Guido van Rossum373c7412003-01-07 13:41:37 +00002009
2010 if (type->tp_weaklistoffset && type->tp_dictoffset)
2011 type->tp_getset = subtype_getsets_full;
2012 else if (type->tp_weaklistoffset && !type->tp_dictoffset)
2013 type->tp_getset = subtype_getsets_weakref_only;
2014 else if (!type->tp_weaklistoffset && type->tp_dictoffset)
2015 type->tp_getset = subtype_getsets_dict_only;
2016 else
2017 type->tp_getset = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002018
2019 /* Special case some slots */
2020 if (type->tp_dictoffset != 0 || nslots > 0) {
2021 if (base->tp_getattr == NULL && base->tp_getattro == NULL)
2022 type->tp_getattro = PyObject_GenericGetAttr;
2023 if (base->tp_setattr == NULL && base->tp_setattro == NULL)
2024 type->tp_setattro = PyObject_GenericSetAttr;
2025 }
2026 type->tp_dealloc = subtype_dealloc;
2027
Guido van Rossum9475a232001-10-05 20:51:39 +00002028 /* Enable GC unless there are really no instance variables possible */
2029 if (!(type->tp_basicsize == sizeof(PyObject) &&
2030 type->tp_itemsize == 0))
2031 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
2032
Tim Peters6d6c1a32001-08-02 04:15:00 +00002033 /* Always override allocation strategy to use regular heap */
2034 type->tp_alloc = PyType_GenericAlloc;
Guido van Rossum048eb752001-10-02 21:24:57 +00002035 if (type->tp_flags & Py_TPFLAGS_HAVE_GC) {
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00002036 type->tp_free = PyObject_GC_Del;
Guido van Rossum9475a232001-10-05 20:51:39 +00002037 type->tp_traverse = subtype_traverse;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00002038 type->tp_clear = subtype_clear;
Guido van Rossum048eb752001-10-02 21:24:57 +00002039 }
2040 else
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00002041 type->tp_free = PyObject_Del;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002042
2043 /* Initialize the rest */
Guido van Rossum528b7eb2001-08-07 17:24:28 +00002044 if (PyType_Ready(type) < 0) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00002045 Py_DECREF(type);
2046 return NULL;
2047 }
2048
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002049 /* Put the proper slots in place */
2050 fixup_slot_dispatchers(type);
Guido van Rossumf040ede2001-08-07 16:40:56 +00002051
Tim Peters6d6c1a32001-08-02 04:15:00 +00002052 return (PyObject *)type;
2053}
2054
2055/* Internal API to look for a name through the MRO.
2056 This returns a borrowed reference, and doesn't set an exception! */
2057PyObject *
2058_PyType_Lookup(PyTypeObject *type, PyObject *name)
2059{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002060 Py_ssize_t i, n;
Tim Petersa91e9642001-11-14 23:32:33 +00002061 PyObject *mro, *res, *base, *dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002062
Guido van Rossum687ae002001-10-15 22:03:32 +00002063 /* Look in tp_dict of types in MRO */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002064 mro = type->tp_mro;
Guido van Rossum23094982002-06-10 14:30:43 +00002065
2066 /* If mro is NULL, the type is either not yet initialized
2067 by PyType_Ready(), or already cleared by type_clear().
2068 Either way the safest thing to do is to return NULL. */
2069 if (mro == NULL)
2070 return NULL;
2071
Tim Peters6d6c1a32001-08-02 04:15:00 +00002072 assert(PyTuple_Check(mro));
2073 n = PyTuple_GET_SIZE(mro);
2074 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00002075 base = PyTuple_GET_ITEM(mro, i);
Guido van Rossum50e9fb92006-08-17 05:42:55 +00002076 assert(PyType_Check(base));
2077 dict = ((PyTypeObject *)base)->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002078 assert(dict && PyDict_Check(dict));
2079 res = PyDict_GetItem(dict, name);
2080 if (res != NULL)
2081 return res;
2082 }
2083 return NULL;
2084}
2085
2086/* This is similar to PyObject_GenericGetAttr(),
2087 but uses _PyType_Lookup() instead of just looking in type->tp_dict. */
2088static PyObject *
2089type_getattro(PyTypeObject *type, PyObject *name)
2090{
2091 PyTypeObject *metatype = type->ob_type;
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002092 PyObject *meta_attribute, *attribute;
2093 descrgetfunc meta_get;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002094
2095 /* Initialize this type (we'll assume the metatype is initialized) */
2096 if (type->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00002097 if (PyType_Ready(type) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002098 return NULL;
2099 }
2100
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002101 /* No readable descriptor found yet */
2102 meta_get = NULL;
Tim Peters34592512002-07-11 06:23:50 +00002103
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002104 /* Look for the attribute in the metatype */
2105 meta_attribute = _PyType_Lookup(metatype, name);
2106
2107 if (meta_attribute != NULL) {
2108 meta_get = meta_attribute->ob_type->tp_descr_get;
Tim Peters34592512002-07-11 06:23:50 +00002109
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002110 if (meta_get != NULL && PyDescr_IsData(meta_attribute)) {
2111 /* Data descriptors implement tp_descr_set to intercept
2112 * writes. Assume the attribute is not overridden in
2113 * type's tp_dict (and bases): call the descriptor now.
2114 */
2115 return meta_get(meta_attribute, (PyObject *)type,
2116 (PyObject *)metatype);
2117 }
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00002118 Py_INCREF(meta_attribute);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002119 }
2120
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002121 /* No data descriptor found on metatype. Look in tp_dict of this
2122 * type and its bases */
2123 attribute = _PyType_Lookup(type, name);
2124 if (attribute != NULL) {
2125 /* Implement descriptor functionality, if any */
2126 descrgetfunc local_get = attribute->ob_type->tp_descr_get;
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00002127
2128 Py_XDECREF(meta_attribute);
2129
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002130 if (local_get != NULL) {
2131 /* NULL 2nd argument indicates the descriptor was
2132 * found on the target object itself (or a base) */
2133 return local_get(attribute, (PyObject *)NULL,
2134 (PyObject *)type);
2135 }
Tim Peters34592512002-07-11 06:23:50 +00002136
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002137 Py_INCREF(attribute);
2138 return attribute;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002139 }
2140
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002141 /* No attribute found in local __dict__ (or bases): use the
2142 * descriptor from the metatype, if any */
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00002143 if (meta_get != NULL) {
2144 PyObject *res;
2145 res = meta_get(meta_attribute, (PyObject *)type,
2146 (PyObject *)metatype);
2147 Py_DECREF(meta_attribute);
2148 return res;
2149 }
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002150
2151 /* If an ordinary attribute was found on the metatype, return it now */
2152 if (meta_attribute != NULL) {
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002153 return meta_attribute;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002154 }
2155
2156 /* Give up */
2157 PyErr_Format(PyExc_AttributeError,
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002158 "type object '%.50s' has no attribute '%.400s'",
Martin v. Löwis5b222132007-06-10 09:51:05 +00002159 type->tp_name, PyUnicode_AsString(name));
Tim Peters6d6c1a32001-08-02 04:15:00 +00002160 return NULL;
2161}
2162
2163static int
2164type_setattro(PyTypeObject *type, PyObject *name, PyObject *value)
2165{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002166 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
2167 PyErr_Format(
2168 PyExc_TypeError,
2169 "can't set attributes of built-in/extension type '%s'",
2170 type->tp_name);
2171 return -1;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002172 }
Guido van Rossum8d24ee92003-03-24 23:49:49 +00002173 /* XXX Example of how I expect this to be used...
2174 if (update_subclasses(type, name, invalidate_cache, NULL) < 0)
2175 return -1;
2176 */
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002177 if (PyObject_GenericSetAttr((PyObject *)type, name, value) < 0)
2178 return -1;
2179 return update_slot(type, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002180}
2181
2182static void
2183type_dealloc(PyTypeObject *type)
2184{
Guido van Rossume5c691a2003-03-07 15:13:17 +00002185 PyHeapTypeObject *et;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002186
2187 /* Assert this is a heap-allocated type object */
2188 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002189 _PyObject_GC_UNTRACK(type);
Guido van Rossum1c450732001-10-08 15:18:27 +00002190 PyObject_ClearWeakRefs((PyObject *)type);
Guido van Rossume5c691a2003-03-07 15:13:17 +00002191 et = (PyHeapTypeObject *)type;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002192 Py_XDECREF(type->tp_base);
2193 Py_XDECREF(type->tp_dict);
2194 Py_XDECREF(type->tp_bases);
2195 Py_XDECREF(type->tp_mro);
Guido van Rossum687ae002001-10-15 22:03:32 +00002196 Py_XDECREF(type->tp_cache);
Guido van Rossum1c450732001-10-08 15:18:27 +00002197 Py_XDECREF(type->tp_subclasses);
Guido van Rossumd8faa362007-04-27 19:54:29 +00002198 /* A type's tp_doc is heap allocated, unlike the tp_doc slots
2199 * of most other objects. It's okay to cast it to char *.
2200 */
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00002201 PyObject_Free((char *)type->tp_doc);
Georg Brandlc255c7b2006-02-20 22:27:28 +00002202 Py_XDECREF(et->ht_name);
2203 Py_XDECREF(et->ht_slots);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002204 type->ob_type->tp_free((PyObject *)type);
2205}
2206
Guido van Rossum1c450732001-10-08 15:18:27 +00002207static PyObject *
2208type_subclasses(PyTypeObject *type, PyObject *args_ignored)
2209{
2210 PyObject *list, *raw, *ref;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002211 Py_ssize_t i, n;
Guido van Rossum1c450732001-10-08 15:18:27 +00002212
2213 list = PyList_New(0);
2214 if (list == NULL)
2215 return NULL;
2216 raw = type->tp_subclasses;
2217 if (raw == NULL)
2218 return list;
2219 assert(PyList_Check(raw));
2220 n = PyList_GET_SIZE(raw);
2221 for (i = 0; i < n; i++) {
2222 ref = PyList_GET_ITEM(raw, i);
Tim Peters44383382001-10-08 16:49:26 +00002223 assert(PyWeakref_CheckRef(ref));
Guido van Rossum1c450732001-10-08 15:18:27 +00002224 ref = PyWeakref_GET_OBJECT(ref);
2225 if (ref != Py_None) {
2226 if (PyList_Append(list, ref) < 0) {
2227 Py_DECREF(list);
2228 return NULL;
2229 }
2230 }
2231 }
2232 return list;
2233}
2234
Tim Peters6d6c1a32001-08-02 04:15:00 +00002235static PyMethodDef type_methods[] = {
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002236 {"mro", (PyCFunction)mro_external, METH_NOARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002237 PyDoc_STR("mro() -> list\nreturn a type's method resolution order")},
Guido van Rossum1c450732001-10-08 15:18:27 +00002238 {"__subclasses__", (PyCFunction)type_subclasses, METH_NOARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002239 PyDoc_STR("__subclasses__() -> list of immediate subclasses")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002240 {0}
2241};
2242
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002243PyDoc_STRVAR(type_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00002244"type(object) -> the object's type\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002245"type(name, bases, dict) -> a new type");
Tim Peters6d6c1a32001-08-02 04:15:00 +00002246
Guido van Rossum048eb752001-10-02 21:24:57 +00002247static int
2248type_traverse(PyTypeObject *type, visitproc visit, void *arg)
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
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002254 Py_VISIT(type->tp_dict);
2255 Py_VISIT(type->tp_cache);
2256 Py_VISIT(type->tp_mro);
2257 Py_VISIT(type->tp_bases);
2258 Py_VISIT(type->tp_base);
Guido van Rossuma3862092002-06-10 15:24:42 +00002259
2260 /* There's no need to visit type->tp_subclasses or
Georg Brandlc255c7b2006-02-20 22:27:28 +00002261 ((PyHeapTypeObject *)type)->ht_slots, because they can't be involved
Guido van Rossuma3862092002-06-10 15:24:42 +00002262 in cycles; tp_subclasses is a list of weak references,
2263 and slots is a tuple of strings. */
Guido van Rossum048eb752001-10-02 21:24:57 +00002264
Guido van Rossum048eb752001-10-02 21:24:57 +00002265 return 0;
2266}
2267
2268static int
2269type_clear(PyTypeObject *type)
2270{
Guido van Rossuma3862092002-06-10 15:24:42 +00002271 /* Because of type_is_gc(), the collector only calls this
2272 for heaptypes. */
2273 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002274
Guido van Rossuma3862092002-06-10 15:24:42 +00002275 /* The only field we need to clear is tp_mro, which is part of a
2276 hard cycle (its first element is the class itself) that won't
2277 be broken otherwise (it's a tuple and tuples don't have a
2278 tp_clear handler). None of the other fields need to be
2279 cleared, and here's why:
Guido van Rossum048eb752001-10-02 21:24:57 +00002280
Guido van Rossuma3862092002-06-10 15:24:42 +00002281 tp_dict:
2282 It is a dict, so the collector will call its tp_clear.
2283
2284 tp_cache:
2285 Not used; if it were, it would be a dict.
2286
2287 tp_bases, tp_base:
2288 If these are involved in a cycle, there must be at least
2289 one other, mutable object in the cycle, e.g. a base
2290 class's dict; the cycle will be broken that way.
2291
2292 tp_subclasses:
2293 A list of weak references can't be part of a cycle; and
2294 lists have their own tp_clear.
2295
Guido van Rossume5c691a2003-03-07 15:13:17 +00002296 slots (in PyHeapTypeObject):
Guido van Rossuma3862092002-06-10 15:24:42 +00002297 A tuple of strings can't be part of a cycle.
2298 */
2299
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002300 Py_CLEAR(type->tp_mro);
Guido van Rossum048eb752001-10-02 21:24:57 +00002301
2302 return 0;
2303}
2304
2305static int
2306type_is_gc(PyTypeObject *type)
2307{
2308 return type->tp_flags & Py_TPFLAGS_HEAPTYPE;
2309}
2310
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002311PyTypeObject PyType_Type = {
2312 PyObject_HEAD_INIT(&PyType_Type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002313 0, /* ob_size */
2314 "type", /* tp_name */
Guido van Rossume5c691a2003-03-07 15:13:17 +00002315 sizeof(PyHeapTypeObject), /* tp_basicsize */
Guido van Rossum6f799372001-09-20 20:46:19 +00002316 sizeof(PyMemberDef), /* tp_itemsize */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002317 (destructor)type_dealloc, /* tp_dealloc */
2318 0, /* tp_print */
Guido van Rossumd8faa362007-04-27 19:54:29 +00002319 0, /* tp_getattr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002320 0, /* tp_setattr */
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002321 0, /* tp_compare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002322 (reprfunc)type_repr, /* tp_repr */
2323 0, /* tp_as_number */
2324 0, /* tp_as_sequence */
2325 0, /* tp_as_mapping */
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002326 0, /* tp_hash */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002327 (ternaryfunc)type_call, /* tp_call */
2328 0, /* tp_str */
2329 (getattrofunc)type_getattro, /* tp_getattro */
2330 (setattrofunc)type_setattro, /* tp_setattro */
2331 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00002332 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
Thomas Wouters27d517b2007-02-25 20:39:11 +00002333 Py_TPFLAGS_BASETYPE | Py_TPFLAGS_TYPE_SUBCLASS, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002334 type_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00002335 (traverseproc)type_traverse, /* tp_traverse */
2336 (inquiry)type_clear, /* tp_clear */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002337 0, /* tp_richcompare */
Guido van Rossum1c450732001-10-08 15:18:27 +00002338 offsetof(PyTypeObject, tp_weaklist), /* tp_weaklistoffset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002339 0, /* tp_iter */
2340 0, /* tp_iternext */
2341 type_methods, /* tp_methods */
2342 type_members, /* tp_members */
2343 type_getsets, /* tp_getset */
2344 0, /* tp_base */
2345 0, /* tp_dict */
2346 0, /* tp_descr_get */
2347 0, /* tp_descr_set */
2348 offsetof(PyTypeObject, tp_dict), /* tp_dictoffset */
Guido van Rossumd8faa362007-04-27 19:54:29 +00002349 type_init, /* tp_init */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002350 0, /* tp_alloc */
2351 type_new, /* tp_new */
Guido van Rossumd8faa362007-04-27 19:54:29 +00002352 PyObject_GC_Del, /* tp_free */
Guido van Rossum048eb752001-10-02 21:24:57 +00002353 (inquiry)type_is_gc, /* tp_is_gc */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002354};
Tim Peters6d6c1a32001-08-02 04:15:00 +00002355
2356
2357/* The base type of all types (eventually)... except itself. */
2358
Guido van Rossumd8faa362007-04-27 19:54:29 +00002359/* You may wonder why object.__new__() only complains about arguments
2360 when object.__init__() is not overridden, and vice versa.
2361
2362 Consider the use cases:
2363
2364 1. When neither is overridden, we want to hear complaints about
2365 excess (i.e., any) arguments, since their presence could
2366 indicate there's a bug.
2367
2368 2. When defining an Immutable type, we are likely to override only
2369 __new__(), since __init__() is called too late to initialize an
2370 Immutable object. Since __new__() defines the signature for the
2371 type, it would be a pain to have to override __init__() just to
2372 stop it from complaining about excess arguments.
2373
2374 3. When defining a Mutable type, we are likely to override only
2375 __init__(). So here the converse reasoning applies: we don't
2376 want to have to override __new__() just to stop it from
2377 complaining.
2378
2379 4. When __init__() is overridden, and the subclass __init__() calls
2380 object.__init__(), the latter should complain about excess
2381 arguments; ditto for __new__().
2382
2383 Use cases 2 and 3 make it unattractive to unconditionally check for
2384 excess arguments. The best solution that addresses all four use
2385 cases is as follows: __init__() complains about excess arguments
2386 unless __new__() is overridden and __init__() is not overridden
2387 (IOW, if __init__() is overridden or __new__() is not overridden);
2388 symmetrically, __new__() complains about excess arguments unless
2389 __init__() is overridden and __new__() is not overridden
2390 (IOW, if __new__() is overridden or __init__() is not overridden).
2391
2392 However, for backwards compatibility, this breaks too much code.
2393 Therefore, in 2.6, we'll *warn* about excess arguments when both
2394 methods are overridden; for all other cases we'll use the above
2395 rules.
2396
2397*/
2398
2399/* Forward */
2400static PyObject *
2401object_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
2402
2403static int
2404excess_args(PyObject *args, PyObject *kwds)
2405{
2406 return PyTuple_GET_SIZE(args) ||
2407 (kwds && PyDict_Check(kwds) && PyDict_Size(kwds));
2408}
2409
Tim Peters6d6c1a32001-08-02 04:15:00 +00002410static int
2411object_init(PyObject *self, PyObject *args, PyObject *kwds)
2412{
Guido van Rossumd8faa362007-04-27 19:54:29 +00002413 int err = 0;
2414 if (excess_args(args, kwds)) {
2415 PyTypeObject *type = self->ob_type;
2416 if (type->tp_init != object_init &&
2417 type->tp_new != object_new)
2418 {
2419 err = PyErr_WarnEx(PyExc_DeprecationWarning,
2420 "object.__init__() takes no parameters",
2421 1);
2422 }
2423 else if (type->tp_init != object_init ||
2424 type->tp_new == object_new)
2425 {
2426 PyErr_SetString(PyExc_TypeError,
2427 "object.__init__() takes no parameters");
2428 err = -1;
2429 }
2430 }
2431 return err;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002432}
2433
Guido van Rossum298e4212003-02-13 16:30:16 +00002434static PyObject *
2435object_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2436{
Guido van Rossumd8faa362007-04-27 19:54:29 +00002437 int err = 0;
2438 if (excess_args(args, kwds)) {
2439 if (type->tp_new != object_new &&
2440 type->tp_init != object_init)
2441 {
2442 err = PyErr_WarnEx(PyExc_DeprecationWarning,
2443 "object.__new__() takes no parameters",
2444 1);
2445 }
2446 else if (type->tp_new != object_new ||
2447 type->tp_init == object_init)
2448 {
2449 PyErr_SetString(PyExc_TypeError,
2450 "object.__new__() takes no parameters");
2451 err = -1;
2452 }
Guido van Rossum298e4212003-02-13 16:30:16 +00002453 }
Guido van Rossumd8faa362007-04-27 19:54:29 +00002454 if (err < 0)
2455 return NULL;
Guido van Rossum298e4212003-02-13 16:30:16 +00002456 return type->tp_alloc(type, 0);
2457}
2458
Tim Peters6d6c1a32001-08-02 04:15:00 +00002459static void
2460object_dealloc(PyObject *self)
2461{
2462 self->ob_type->tp_free(self);
2463}
2464
Guido van Rossum8e248182001-08-12 05:17:56 +00002465static PyObject *
2466object_repr(PyObject *self)
2467{
Guido van Rossum76e69632001-08-16 18:52:43 +00002468 PyTypeObject *type;
Barry Warsaw7ce36942001-08-24 18:34:26 +00002469 PyObject *mod, *name, *rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00002470
Guido van Rossum76e69632001-08-16 18:52:43 +00002471 type = self->ob_type;
2472 mod = type_module(type, NULL);
2473 if (mod == NULL)
2474 PyErr_Clear();
Martin v. Löwis5b222132007-06-10 09:51:05 +00002475 else if (!PyUnicode_Check(mod)) {
Guido van Rossum76e69632001-08-16 18:52:43 +00002476 Py_DECREF(mod);
2477 mod = NULL;
2478 }
2479 name = type_name(type, NULL);
2480 if (name == NULL)
2481 return NULL;
2482 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__"))
Walter Dörwald1ab83302007-05-18 17:15:44 +00002483 rtn = PyUnicode_FromFormat("<%s.%s object at %p>",
Martin v. Löwis5b222132007-06-10 09:51:05 +00002484 PyUnicode_AsString(mod),
2485 PyUnicode_AsString(name),
Barry Warsaw7ce36942001-08-24 18:34:26 +00002486 self);
Guido van Rossum76e69632001-08-16 18:52:43 +00002487 else
Walter Dörwald1ab83302007-05-18 17:15:44 +00002488 rtn = PyUnicode_FromFormat("<%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00002489 type->tp_name, self);
Guido van Rossum76e69632001-08-16 18:52:43 +00002490 Py_XDECREF(mod);
2491 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +00002492 return rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00002493}
2494
Guido van Rossumb8f63662001-08-15 23:57:02 +00002495static PyObject *
2496object_str(PyObject *self)
2497{
2498 unaryfunc f;
2499
2500 f = self->ob_type->tp_repr;
2501 if (f == NULL)
2502 f = object_repr;
2503 return f(self);
2504}
2505
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002506static PyObject *
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002507object_richcompare(PyObject *self, PyObject *other, int op)
2508{
2509 PyObject *res;
2510
2511 switch (op) {
2512
2513 case Py_EQ:
2514 res = (self == other) ? Py_True : Py_False;
Guido van Rossum6b18a5b2007-03-29 20:49:57 +00002515 Py_INCREF(res);
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002516 break;
2517
2518 case Py_NE:
Guido van Rossume27dc722007-03-27 22:37:34 +00002519 /* By default, != returns the opposite of ==,
2520 unless the latter returns NotImplemented. */
2521 res = PyObject_RichCompare(self, other, Py_EQ);
2522 if (res != NULL && res != Py_NotImplemented) {
2523 int ok = PyObject_IsTrue(res);
2524 Py_DECREF(res);
2525 if (ok < 0)
2526 res = NULL;
2527 else {
2528 if (ok)
2529 res = Py_False;
2530 else
2531 res = Py_True;
2532 Py_INCREF(res);
2533 }
2534 }
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002535 break;
2536
2537 default:
2538 res = Py_NotImplemented;
Guido van Rossum6b18a5b2007-03-29 20:49:57 +00002539 Py_INCREF(res);
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002540 break;
2541 }
2542
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002543 return res;
2544}
2545
2546static PyObject *
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002547object_get_class(PyObject *self, void *closure)
2548{
2549 Py_INCREF(self->ob_type);
2550 return (PyObject *)(self->ob_type);
2551}
2552
2553static int
2554equiv_structs(PyTypeObject *a, PyTypeObject *b)
2555{
2556 return a == b ||
2557 (a != NULL &&
2558 b != NULL &&
2559 a->tp_basicsize == b->tp_basicsize &&
2560 a->tp_itemsize == b->tp_itemsize &&
2561 a->tp_dictoffset == b->tp_dictoffset &&
2562 a->tp_weaklistoffset == b->tp_weaklistoffset &&
2563 ((a->tp_flags & Py_TPFLAGS_HAVE_GC) ==
2564 (b->tp_flags & Py_TPFLAGS_HAVE_GC)));
2565}
2566
2567static int
2568same_slots_added(PyTypeObject *a, PyTypeObject *b)
2569{
2570 PyTypeObject *base = a->tp_base;
Martin v. Löwiseb079f12006-02-16 14:32:27 +00002571 Py_ssize_t size;
Guido van Rossumd8faa362007-04-27 19:54:29 +00002572 PyObject *slots_a, *slots_b;
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002573
2574 if (base != b->tp_base)
2575 return 0;
2576 if (equiv_structs(a, base) && equiv_structs(b, base))
2577 return 1;
2578 size = base->tp_basicsize;
2579 if (a->tp_dictoffset == size && b->tp_dictoffset == size)
2580 size += sizeof(PyObject *);
2581 if (a->tp_weaklistoffset == size && b->tp_weaklistoffset == size)
2582 size += sizeof(PyObject *);
Guido van Rossumd8faa362007-04-27 19:54:29 +00002583
2584 /* Check slots compliance */
2585 slots_a = ((PyHeapTypeObject *)a)->ht_slots;
2586 slots_b = ((PyHeapTypeObject *)b)->ht_slots;
2587 if (slots_a && slots_b) {
2588 if (PyObject_Compare(slots_a, slots_b) != 0)
2589 return 0;
2590 size += sizeof(PyObject *) * PyTuple_GET_SIZE(slots_a);
2591 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002592 return size == a->tp_basicsize && size == b->tp_basicsize;
2593}
2594
2595static int
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002596compatible_for_assignment(PyTypeObject* oldto, PyTypeObject* newto, char* attr)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002597{
2598 PyTypeObject *newbase, *oldbase;
2599
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002600 if (newto->tp_dealloc != oldto->tp_dealloc ||
2601 newto->tp_free != oldto->tp_free)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002602 {
2603 PyErr_Format(PyExc_TypeError,
2604 "%s assignment: "
2605 "'%s' deallocator differs from '%s'",
2606 attr,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002607 newto->tp_name,
2608 oldto->tp_name);
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002609 return 0;
2610 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002611 newbase = newto;
2612 oldbase = oldto;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002613 while (equiv_structs(newbase, newbase->tp_base))
2614 newbase = newbase->tp_base;
2615 while (equiv_structs(oldbase, oldbase->tp_base))
2616 oldbase = oldbase->tp_base;
2617 if (newbase != oldbase &&
2618 (newbase->tp_base != oldbase->tp_base ||
2619 !same_slots_added(newbase, oldbase))) {
2620 PyErr_Format(PyExc_TypeError,
2621 "%s assignment: "
2622 "'%s' object layout differs from '%s'",
2623 attr,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002624 newto->tp_name,
2625 oldto->tp_name);
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002626 return 0;
2627 }
Tim Petersea7f75d2002-12-07 21:39:16 +00002628
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002629 return 1;
2630}
2631
2632static int
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002633object_set_class(PyObject *self, PyObject *value, void *closure)
2634{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002635 PyTypeObject *oldto = self->ob_type;
2636 PyTypeObject *newto;
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002637
Guido van Rossumb6b89422002-04-15 01:03:30 +00002638 if (value == NULL) {
2639 PyErr_SetString(PyExc_TypeError,
2640 "can't delete __class__ attribute");
2641 return -1;
2642 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002643 if (!PyType_Check(value)) {
2644 PyErr_Format(PyExc_TypeError,
2645 "__class__ must be set to new-style class, not '%s' object",
2646 value->ob_type->tp_name);
2647 return -1;
2648 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002649 newto = (PyTypeObject *)value;
2650 if (!(newto->tp_flags & Py_TPFLAGS_HEAPTYPE) ||
2651 !(oldto->tp_flags & Py_TPFLAGS_HEAPTYPE))
Guido van Rossum40af8892002-08-10 05:42:07 +00002652 {
2653 PyErr_Format(PyExc_TypeError,
2654 "__class__ assignment: only for heap types");
2655 return -1;
2656 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002657 if (compatible_for_assignment(newto, oldto, "__class__")) {
2658 Py_INCREF(newto);
2659 self->ob_type = newto;
2660 Py_DECREF(oldto);
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002661 return 0;
2662 }
2663 else {
Guido van Rossum9ee4b942002-05-24 18:47:47 +00002664 return -1;
2665 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002666}
2667
2668static PyGetSetDef object_getsets[] = {
2669 {"__class__", object_get_class, object_set_class,
Neal Norwitz858e34f2002-08-13 17:18:45 +00002670 PyDoc_STR("the object's class")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002671 {0}
2672};
2673
Guido van Rossumc53f0092003-02-18 22:05:12 +00002674
Guido van Rossum036f9992003-02-21 22:02:54 +00002675/* Stuff to implement __reduce_ex__ for pickle protocols >= 2.
2676 We fall back to helpers in copy_reg for:
2677 - pickle protocols < 2
2678 - calculating the list of slot names (done only once per class)
2679 - the __newobj__ function (which is used as a token but never called)
2680*/
2681
2682static PyObject *
2683import_copy_reg(void)
2684{
2685 static PyObject *copy_reg_str;
Guido van Rossum3926a632001-09-25 16:25:58 +00002686
2687 if (!copy_reg_str) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00002688 copy_reg_str = PyUnicode_InternFromString("copy_reg");
Guido van Rossum3926a632001-09-25 16:25:58 +00002689 if (copy_reg_str == NULL)
2690 return NULL;
2691 }
Guido van Rossum036f9992003-02-21 22:02:54 +00002692
2693 return PyImport_Import(copy_reg_str);
2694}
2695
2696static PyObject *
2697slotnames(PyObject *cls)
2698{
2699 PyObject *clsdict;
2700 PyObject *copy_reg;
2701 PyObject *slotnames;
2702
2703 if (!PyType_Check(cls)) {
2704 Py_INCREF(Py_None);
2705 return Py_None;
2706 }
2707
2708 clsdict = ((PyTypeObject *)cls)->tp_dict;
2709 slotnames = PyDict_GetItemString(clsdict, "__slotnames__");
Armin Rigoec862b92005-09-24 22:58:41 +00002710 if (slotnames != NULL && PyList_Check(slotnames)) {
Guido van Rossum036f9992003-02-21 22:02:54 +00002711 Py_INCREF(slotnames);
2712 return slotnames;
2713 }
2714
2715 copy_reg = import_copy_reg();
2716 if (copy_reg == NULL)
2717 return NULL;
2718
2719 slotnames = PyObject_CallMethod(copy_reg, "_slotnames", "O", cls);
2720 Py_DECREF(copy_reg);
2721 if (slotnames != NULL &&
2722 slotnames != Py_None &&
2723 !PyList_Check(slotnames))
2724 {
2725 PyErr_SetString(PyExc_TypeError,
2726 "copy_reg._slotnames didn't return a list or None");
2727 Py_DECREF(slotnames);
2728 slotnames = NULL;
2729 }
2730
2731 return slotnames;
2732}
2733
2734static PyObject *
2735reduce_2(PyObject *obj)
2736{
2737 PyObject *cls, *getnewargs;
2738 PyObject *args = NULL, *args2 = NULL;
2739 PyObject *getstate = NULL, *state = NULL, *names = NULL;
2740 PyObject *slots = NULL, *listitems = NULL, *dictitems = NULL;
2741 PyObject *copy_reg = NULL, *newobj = NULL, *res = NULL;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002742 Py_ssize_t i, n;
Guido van Rossum036f9992003-02-21 22:02:54 +00002743
2744 cls = PyObject_GetAttrString(obj, "__class__");
2745 if (cls == NULL)
2746 return NULL;
2747
2748 getnewargs = PyObject_GetAttrString(obj, "__getnewargs__");
2749 if (getnewargs != NULL) {
2750 args = PyObject_CallObject(getnewargs, NULL);
2751 Py_DECREF(getnewargs);
2752 if (args != NULL && !PyTuple_Check(args)) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002753 PyErr_Format(PyExc_TypeError,
2754 "__getnewargs__ should return a tuple, "
2755 "not '%.200s'", args->ob_type->tp_name);
Guido van Rossum036f9992003-02-21 22:02:54 +00002756 goto end;
2757 }
2758 }
2759 else {
2760 PyErr_Clear();
2761 args = PyTuple_New(0);
2762 }
2763 if (args == NULL)
2764 goto end;
2765
2766 getstate = PyObject_GetAttrString(obj, "__getstate__");
2767 if (getstate != NULL) {
2768 state = PyObject_CallObject(getstate, NULL);
2769 Py_DECREF(getstate);
Neal Norwitze2fdc612003-06-08 13:19:58 +00002770 if (state == NULL)
2771 goto end;
Guido van Rossum036f9992003-02-21 22:02:54 +00002772 }
2773 else {
Jim Fulton8a1a5942004-02-08 04:21:26 +00002774 PyErr_Clear();
Guido van Rossum036f9992003-02-21 22:02:54 +00002775 state = PyObject_GetAttrString(obj, "__dict__");
2776 if (state == NULL) {
2777 PyErr_Clear();
2778 state = Py_None;
2779 Py_INCREF(state);
2780 }
2781 names = slotnames(cls);
2782 if (names == NULL)
2783 goto end;
2784 if (names != Py_None) {
2785 assert(PyList_Check(names));
2786 slots = PyDict_New();
2787 if (slots == NULL)
2788 goto end;
2789 n = 0;
2790 /* Can't pre-compute the list size; the list
2791 is stored on the class so accessible to other
2792 threads, which may be run by DECREF */
2793 for (i = 0; i < PyList_GET_SIZE(names); i++) {
2794 PyObject *name, *value;
2795 name = PyList_GET_ITEM(names, i);
2796 value = PyObject_GetAttr(obj, name);
2797 if (value == NULL)
2798 PyErr_Clear();
2799 else {
2800 int err = PyDict_SetItem(slots, name,
2801 value);
2802 Py_DECREF(value);
2803 if (err)
2804 goto end;
2805 n++;
2806 }
2807 }
2808 if (n) {
2809 state = Py_BuildValue("(NO)", state, slots);
2810 if (state == NULL)
2811 goto end;
2812 }
2813 }
2814 }
2815
2816 if (!PyList_Check(obj)) {
2817 listitems = Py_None;
2818 Py_INCREF(listitems);
2819 }
2820 else {
2821 listitems = PyObject_GetIter(obj);
2822 if (listitems == NULL)
2823 goto end;
2824 }
2825
2826 if (!PyDict_Check(obj)) {
2827 dictitems = Py_None;
2828 Py_INCREF(dictitems);
2829 }
2830 else {
Guido van Rossumcc2b0162007-02-11 06:12:03 +00002831 PyObject *items = PyObject_CallMethod(obj, "items", "");
2832 if (items == NULL)
2833 goto end;
2834 dictitems = PyObject_GetIter(items);
2835 Py_DECREF(items);
Guido van Rossum036f9992003-02-21 22:02:54 +00002836 if (dictitems == NULL)
2837 goto end;
2838 }
2839
2840 copy_reg = import_copy_reg();
2841 if (copy_reg == NULL)
2842 goto end;
2843 newobj = PyObject_GetAttrString(copy_reg, "__newobj__");
2844 if (newobj == NULL)
2845 goto end;
2846
2847 n = PyTuple_GET_SIZE(args);
2848 args2 = PyTuple_New(n+1);
2849 if (args2 == NULL)
2850 goto end;
2851 PyTuple_SET_ITEM(args2, 0, cls);
2852 cls = NULL;
2853 for (i = 0; i < n; i++) {
2854 PyObject *v = PyTuple_GET_ITEM(args, i);
2855 Py_INCREF(v);
2856 PyTuple_SET_ITEM(args2, i+1, v);
2857 }
2858
Raymond Hettinger8ae46892003-10-12 19:09:37 +00002859 res = PyTuple_Pack(5, newobj, args2, state, listitems, dictitems);
Guido van Rossum036f9992003-02-21 22:02:54 +00002860
2861 end:
2862 Py_XDECREF(cls);
2863 Py_XDECREF(args);
2864 Py_XDECREF(args2);
Jeremy Hyltond06483c2003-04-09 21:01:42 +00002865 Py_XDECREF(slots);
Guido van Rossum036f9992003-02-21 22:02:54 +00002866 Py_XDECREF(state);
2867 Py_XDECREF(names);
2868 Py_XDECREF(listitems);
2869 Py_XDECREF(dictitems);
2870 Py_XDECREF(copy_reg);
2871 Py_XDECREF(newobj);
2872 return res;
2873}
2874
Guido van Rossumd8faa362007-04-27 19:54:29 +00002875/*
2876 * There were two problems when object.__reduce__ and object.__reduce_ex__
2877 * were implemented in the same function:
2878 * - trying to pickle an object with a custom __reduce__ method that
2879 * fell back to object.__reduce__ in certain circumstances led to
2880 * infinite recursion at Python level and eventual RuntimeError.
2881 * - Pickling objects that lied about their type by overwriting the
2882 * __class__ descriptor could lead to infinite recursion at C level
2883 * and eventual segfault.
2884 *
2885 * Because of backwards compatibility, the two methods still have to
2886 * behave in the same way, even if this is not required by the pickle
2887 * protocol. This common functionality was moved to the _common_reduce
2888 * function.
2889 */
2890static PyObject *
2891_common_reduce(PyObject *self, int proto)
2892{
2893 PyObject *copy_reg, *res;
2894
2895 if (proto >= 2)
2896 return reduce_2(self);
2897
2898 copy_reg = import_copy_reg();
2899 if (!copy_reg)
2900 return NULL;
2901
2902 res = PyEval_CallMethod(copy_reg, "_reduce_ex", "(Oi)", self, proto);
2903 Py_DECREF(copy_reg);
2904
2905 return res;
2906}
2907
2908static PyObject *
2909object_reduce(PyObject *self, PyObject *args)
2910{
2911 int proto = 0;
2912
2913 if (!PyArg_ParseTuple(args, "|i:__reduce__", &proto))
2914 return NULL;
2915
2916 return _common_reduce(self, proto);
2917}
2918
Guido van Rossum036f9992003-02-21 22:02:54 +00002919static PyObject *
2920object_reduce_ex(PyObject *self, PyObject *args)
2921{
Guido van Rossumd8faa362007-04-27 19:54:29 +00002922 PyObject *reduce, *res;
Guido van Rossum036f9992003-02-21 22:02:54 +00002923 int proto = 0;
2924
2925 if (!PyArg_ParseTuple(args, "|i:__reduce_ex__", &proto))
2926 return NULL;
2927
2928 reduce = PyObject_GetAttrString(self, "__reduce__");
2929 if (reduce == NULL)
2930 PyErr_Clear();
2931 else {
2932 PyObject *cls, *clsreduce, *objreduce;
2933 int override;
2934 cls = PyObject_GetAttrString(self, "__class__");
2935 if (cls == NULL) {
2936 Py_DECREF(reduce);
2937 return NULL;
2938 }
2939 clsreduce = PyObject_GetAttrString(cls, "__reduce__");
2940 Py_DECREF(cls);
2941 if (clsreduce == NULL) {
2942 Py_DECREF(reduce);
2943 return NULL;
2944 }
2945 objreduce = PyDict_GetItemString(PyBaseObject_Type.tp_dict,
2946 "__reduce__");
2947 override = (clsreduce != objreduce);
2948 Py_DECREF(clsreduce);
2949 if (override) {
2950 res = PyObject_CallObject(reduce, NULL);
2951 Py_DECREF(reduce);
2952 return res;
2953 }
2954 else
2955 Py_DECREF(reduce);
2956 }
2957
Guido van Rossumd8faa362007-04-27 19:54:29 +00002958 return _common_reduce(self, proto);
Guido van Rossum3926a632001-09-25 16:25:58 +00002959}
2960
2961static PyMethodDef object_methods[] = {
Guido van Rossumc53f0092003-02-18 22:05:12 +00002962 {"__reduce_ex__", object_reduce_ex, METH_VARARGS,
2963 PyDoc_STR("helper for pickle")},
Guido van Rossumd8faa362007-04-27 19:54:29 +00002964 {"__reduce__", object_reduce, METH_VARARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002965 PyDoc_STR("helper for pickle")},
Guido van Rossum3926a632001-09-25 16:25:58 +00002966 {0}
2967};
2968
Guido van Rossum036f9992003-02-21 22:02:54 +00002969
Tim Peters6d6c1a32001-08-02 04:15:00 +00002970PyTypeObject PyBaseObject_Type = {
2971 PyObject_HEAD_INIT(&PyType_Type)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002972 0, /* ob_size */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002973 "object", /* tp_name */
2974 sizeof(PyObject), /* tp_basicsize */
2975 0, /* tp_itemsize */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002976 object_dealloc, /* tp_dealloc */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002977 0, /* tp_print */
Guido van Rossumd8faa362007-04-27 19:54:29 +00002978 0, /* tp_getattr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002979 0, /* tp_setattr */
2980 0, /* tp_compare */
Guido van Rossumb8f63662001-08-15 23:57:02 +00002981 object_repr, /* tp_repr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002982 0, /* tp_as_number */
2983 0, /* tp_as_sequence */
2984 0, /* tp_as_mapping */
Guido van Rossum50e9fb92006-08-17 05:42:55 +00002985 (hashfunc)_Py_HashPointer, /* tp_hash */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002986 0, /* tp_call */
Guido van Rossumb8f63662001-08-15 23:57:02 +00002987 object_str, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002988 PyObject_GenericGetAttr, /* tp_getattro */
Guido van Rossum13d52f02001-08-10 21:24:08 +00002989 PyObject_GenericSetAttr, /* tp_setattro */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002990 0, /* tp_as_buffer */
2991 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002992 PyDoc_STR("The most base type"), /* tp_doc */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002993 0, /* tp_traverse */
2994 0, /* tp_clear */
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002995 object_richcompare, /* tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002996 0, /* tp_weaklistoffset */
2997 0, /* tp_iter */
2998 0, /* tp_iternext */
Guido van Rossum3926a632001-09-25 16:25:58 +00002999 object_methods, /* tp_methods */
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003000 0, /* tp_members */
3001 object_getsets, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003002 0, /* tp_base */
3003 0, /* tp_dict */
3004 0, /* tp_descr_get */
3005 0, /* tp_descr_set */
3006 0, /* tp_dictoffset */
3007 object_init, /* tp_init */
3008 PyType_GenericAlloc, /* tp_alloc */
Guido van Rossum298e4212003-02-13 16:30:16 +00003009 object_new, /* tp_new */
Guido van Rossumd8faa362007-04-27 19:54:29 +00003010 PyObject_Del, /* tp_free */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003011};
3012
3013
Guido van Rossum50e9fb92006-08-17 05:42:55 +00003014/* Add the methods from tp_methods to the __dict__ in a type object */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003015
3016static int
3017add_methods(PyTypeObject *type, PyMethodDef *meth)
3018{
Guido van Rossum687ae002001-10-15 22:03:32 +00003019 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003020
3021 for (; meth->ml_name != NULL; meth++) {
3022 PyObject *descr;
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00003023 if (PyDict_GetItemString(dict, meth->ml_name) &&
3024 !(meth->ml_flags & METH_COEXIST))
3025 continue;
Fred Drake7bf97152002-03-28 05:33:33 +00003026 if (meth->ml_flags & METH_CLASS) {
3027 if (meth->ml_flags & METH_STATIC) {
3028 PyErr_SetString(PyExc_ValueError,
3029 "method cannot be both class and static");
3030 return -1;
3031 }
Tim Petersbca1cbc2002-12-09 22:56:13 +00003032 descr = PyDescr_NewClassMethod(type, meth);
Fred Drake7bf97152002-03-28 05:33:33 +00003033 }
3034 else if (meth->ml_flags & METH_STATIC) {
Guido van Rossum9af48ff2003-02-11 17:12:46 +00003035 PyObject *cfunc = PyCFunction_New(meth, NULL);
3036 if (cfunc == NULL)
3037 return -1;
3038 descr = PyStaticMethod_New(cfunc);
3039 Py_DECREF(cfunc);
Fred Drake7bf97152002-03-28 05:33:33 +00003040 }
3041 else {
3042 descr = PyDescr_NewMethod(type, meth);
3043 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003044 if (descr == NULL)
3045 return -1;
Fred Drake7bf97152002-03-28 05:33:33 +00003046 if (PyDict_SetItemString(dict, meth->ml_name, descr) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003047 return -1;
3048 Py_DECREF(descr);
3049 }
3050 return 0;
3051}
3052
3053static int
Guido van Rossum6f799372001-09-20 20:46:19 +00003054add_members(PyTypeObject *type, PyMemberDef *memb)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003055{
Guido van Rossum687ae002001-10-15 22:03:32 +00003056 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003057
3058 for (; memb->name != NULL; memb++) {
3059 PyObject *descr;
3060 if (PyDict_GetItemString(dict, memb->name))
3061 continue;
3062 descr = PyDescr_NewMember(type, memb);
3063 if (descr == NULL)
3064 return -1;
3065 if (PyDict_SetItemString(dict, memb->name, descr) < 0)
3066 return -1;
3067 Py_DECREF(descr);
3068 }
3069 return 0;
3070}
3071
3072static int
Guido van Rossum32d34c82001-09-20 21:45:26 +00003073add_getset(PyTypeObject *type, PyGetSetDef *gsp)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003074{
Guido van Rossum687ae002001-10-15 22:03:32 +00003075 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003076
3077 for (; gsp->name != NULL; gsp++) {
3078 PyObject *descr;
3079 if (PyDict_GetItemString(dict, gsp->name))
3080 continue;
3081 descr = PyDescr_NewGetSet(type, gsp);
3082
3083 if (descr == NULL)
3084 return -1;
3085 if (PyDict_SetItemString(dict, gsp->name, descr) < 0)
3086 return -1;
3087 Py_DECREF(descr);
3088 }
3089 return 0;
3090}
3091
Guido van Rossum13d52f02001-08-10 21:24:08 +00003092static void
3093inherit_special(PyTypeObject *type, PyTypeObject *base)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003094{
Martin v. Löwiseb079f12006-02-16 14:32:27 +00003095 Py_ssize_t oldsize, newsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003096
Guido van Rossum13d52f02001-08-10 21:24:08 +00003097 /* Copying basicsize is connected to the GC flags */
Neil Schemenauerc806c882001-08-29 23:54:54 +00003098 oldsize = base->tp_basicsize;
3099 newsize = type->tp_basicsize ? type->tp_basicsize : oldsize;
3100 if (!(type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
3101 (base->tp_flags & Py_TPFLAGS_HAVE_GC) &&
Guido van Rossum13d52f02001-08-10 21:24:08 +00003102 (!type->tp_traverse && !type->tp_clear)) {
Neil Schemenauerc806c882001-08-29 23:54:54 +00003103 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossum13d52f02001-08-10 21:24:08 +00003104 if (type->tp_traverse == NULL)
3105 type->tp_traverse = base->tp_traverse;
3106 if (type->tp_clear == NULL)
3107 type->tp_clear = base->tp_clear;
3108 }
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00003109 {
Guido van Rossumf884b742001-12-17 17:14:22 +00003110 /* The condition below could use some explanation.
3111 It appears that tp_new is not inherited for static types
3112 whose base class is 'object'; this seems to be a precaution
3113 so that old extension types don't suddenly become
3114 callable (object.__new__ wouldn't insure the invariants
3115 that the extension type's own factory function ensures).
3116 Heap types, of course, are under our control, so they do
3117 inherit tp_new; static extension types that specify some
3118 other built-in type as the default are considered
3119 new-style-aware so they also inherit object.__new__. */
Guido van Rossum13d52f02001-08-10 21:24:08 +00003120 if (base != &PyBaseObject_Type ||
3121 (type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
3122 if (type->tp_new == NULL)
3123 type->tp_new = base->tp_new;
3124 }
3125 }
Neil Schemenauerc806c882001-08-29 23:54:54 +00003126 type->tp_basicsize = newsize;
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00003127
3128 /* Copy other non-function slots */
3129
3130#undef COPYVAL
3131#define COPYVAL(SLOT) \
3132 if (type->SLOT == 0) type->SLOT = base->SLOT
3133
3134 COPYVAL(tp_itemsize);
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00003135 COPYVAL(tp_weaklistoffset);
3136 COPYVAL(tp_dictoffset);
Thomas Wouters27d517b2007-02-25 20:39:11 +00003137
3138 /* Setup fast subclass flags */
3139 if (PyType_IsSubtype(base, (PyTypeObject*)PyExc_BaseException))
3140 type->tp_flags |= Py_TPFLAGS_BASE_EXC_SUBCLASS;
3141 else if (PyType_IsSubtype(base, &PyType_Type))
3142 type->tp_flags |= Py_TPFLAGS_TYPE_SUBCLASS;
3143 else if (PyType_IsSubtype(base, &PyLong_Type))
3144 type->tp_flags |= Py_TPFLAGS_LONG_SUBCLASS;
3145 else if (PyType_IsSubtype(base, &PyString_Type))
3146 type->tp_flags |= Py_TPFLAGS_STRING_SUBCLASS;
3147 else if (PyType_IsSubtype(base, &PyUnicode_Type))
3148 type->tp_flags |= Py_TPFLAGS_UNICODE_SUBCLASS;
3149 else if (PyType_IsSubtype(base, &PyTuple_Type))
3150 type->tp_flags |= Py_TPFLAGS_TUPLE_SUBCLASS;
3151 else if (PyType_IsSubtype(base, &PyList_Type))
3152 type->tp_flags |= Py_TPFLAGS_LIST_SUBCLASS;
3153 else if (PyType_IsSubtype(base, &PyDict_Type))
3154 type->tp_flags |= Py_TPFLAGS_DICT_SUBCLASS;
Guido van Rossum13d52f02001-08-10 21:24:08 +00003155}
3156
Guido van Rossum38938152006-08-21 23:36:26 +00003157/* Map rich comparison operators to their __xx__ namesakes */
3158static char *name_op[] = {
3159 "__lt__",
3160 "__le__",
3161 "__eq__",
3162 "__ne__",
3163 "__gt__",
3164 "__ge__",
3165 /* These are only for overrides_cmp_or_hash(): */
3166 "__cmp__",
3167 "__hash__",
3168};
3169
3170static int
3171overrides_cmp_or_hash(PyTypeObject *type)
3172{
3173 int i;
3174 PyObject *dict = type->tp_dict;
3175
3176 assert(dict != NULL);
3177 for (i = 0; i < 8; i++) {
3178 if (PyDict_GetItemString(dict, name_op[i]) != NULL)
3179 return 1;
3180 }
3181 return 0;
3182}
3183
Guido van Rossum13d52f02001-08-10 21:24:08 +00003184static void
3185inherit_slots(PyTypeObject *type, PyTypeObject *base)
3186{
3187 PyTypeObject *basebase;
3188
3189#undef SLOTDEFINED
Tim Peters6d6c1a32001-08-02 04:15:00 +00003190#undef COPYSLOT
3191#undef COPYNUM
3192#undef COPYSEQ
3193#undef COPYMAP
Guido van Rossum5af588b2001-10-12 14:13:21 +00003194#undef COPYBUF
Guido van Rossum13d52f02001-08-10 21:24:08 +00003195
3196#define SLOTDEFINED(SLOT) \
3197 (base->SLOT != 0 && \
3198 (basebase == NULL || base->SLOT != basebase->SLOT))
3199
Tim Peters6d6c1a32001-08-02 04:15:00 +00003200#define COPYSLOT(SLOT) \
Guido van Rossum13d52f02001-08-10 21:24:08 +00003201 if (!type->SLOT && SLOTDEFINED(SLOT)) type->SLOT = base->SLOT
Tim Peters6d6c1a32001-08-02 04:15:00 +00003202
3203#define COPYNUM(SLOT) COPYSLOT(tp_as_number->SLOT)
3204#define COPYSEQ(SLOT) COPYSLOT(tp_as_sequence->SLOT)
3205#define COPYMAP(SLOT) COPYSLOT(tp_as_mapping->SLOT)
Tim Petersfc57ccb2001-10-12 02:38:24 +00003206#define COPYBUF(SLOT) COPYSLOT(tp_as_buffer->SLOT)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003207
Guido van Rossum13d52f02001-08-10 21:24:08 +00003208 /* This won't inherit indirect slots (from tp_as_number etc.)
3209 if type doesn't provide the space. */
3210
3211 if (type->tp_as_number != NULL && base->tp_as_number != NULL) {
3212 basebase = base->tp_base;
3213 if (basebase->tp_as_number == NULL)
3214 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003215 COPYNUM(nb_add);
3216 COPYNUM(nb_subtract);
3217 COPYNUM(nb_multiply);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003218 COPYNUM(nb_remainder);
3219 COPYNUM(nb_divmod);
3220 COPYNUM(nb_power);
3221 COPYNUM(nb_negative);
3222 COPYNUM(nb_positive);
3223 COPYNUM(nb_absolute);
Jack Diederich4dafcc42006-11-28 19:15:13 +00003224 COPYNUM(nb_bool);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003225 COPYNUM(nb_invert);
3226 COPYNUM(nb_lshift);
3227 COPYNUM(nb_rshift);
3228 COPYNUM(nb_and);
3229 COPYNUM(nb_xor);
3230 COPYNUM(nb_or);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003231 COPYNUM(nb_int);
3232 COPYNUM(nb_long);
3233 COPYNUM(nb_float);
3234 COPYNUM(nb_oct);
3235 COPYNUM(nb_hex);
3236 COPYNUM(nb_inplace_add);
3237 COPYNUM(nb_inplace_subtract);
3238 COPYNUM(nb_inplace_multiply);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003239 COPYNUM(nb_inplace_remainder);
3240 COPYNUM(nb_inplace_power);
3241 COPYNUM(nb_inplace_lshift);
3242 COPYNUM(nb_inplace_rshift);
3243 COPYNUM(nb_inplace_and);
3244 COPYNUM(nb_inplace_xor);
3245 COPYNUM(nb_inplace_or);
Neal Norwitzbcc0db82006-03-24 08:14:36 +00003246 COPYNUM(nb_true_divide);
3247 COPYNUM(nb_floor_divide);
3248 COPYNUM(nb_inplace_true_divide);
3249 COPYNUM(nb_inplace_floor_divide);
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00003250 COPYNUM(nb_index);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003251 }
3252
Guido van Rossum13d52f02001-08-10 21:24:08 +00003253 if (type->tp_as_sequence != NULL && base->tp_as_sequence != NULL) {
3254 basebase = base->tp_base;
3255 if (basebase->tp_as_sequence == NULL)
3256 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003257 COPYSEQ(sq_length);
3258 COPYSEQ(sq_concat);
3259 COPYSEQ(sq_repeat);
3260 COPYSEQ(sq_item);
3261 COPYSEQ(sq_slice);
3262 COPYSEQ(sq_ass_item);
3263 COPYSEQ(sq_ass_slice);
3264 COPYSEQ(sq_contains);
3265 COPYSEQ(sq_inplace_concat);
3266 COPYSEQ(sq_inplace_repeat);
3267 }
3268
Guido van Rossum13d52f02001-08-10 21:24:08 +00003269 if (type->tp_as_mapping != NULL && base->tp_as_mapping != NULL) {
3270 basebase = base->tp_base;
3271 if (basebase->tp_as_mapping == NULL)
3272 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003273 COPYMAP(mp_length);
3274 COPYMAP(mp_subscript);
3275 COPYMAP(mp_ass_subscript);
3276 }
3277
Tim Petersfc57ccb2001-10-12 02:38:24 +00003278 if (type->tp_as_buffer != NULL && base->tp_as_buffer != NULL) {
3279 basebase = base->tp_base;
3280 if (basebase->tp_as_buffer == NULL)
3281 basebase = NULL;
3282 COPYBUF(bf_getreadbuffer);
3283 COPYBUF(bf_getwritebuffer);
3284 COPYBUF(bf_getsegcount);
3285 COPYBUF(bf_getcharbuffer);
3286 }
3287
Guido van Rossum13d52f02001-08-10 21:24:08 +00003288 basebase = base->tp_base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003289
Tim Peters6d6c1a32001-08-02 04:15:00 +00003290 COPYSLOT(tp_dealloc);
3291 COPYSLOT(tp_print);
3292 if (type->tp_getattr == NULL && type->tp_getattro == NULL) {
3293 type->tp_getattr = base->tp_getattr;
3294 type->tp_getattro = base->tp_getattro;
3295 }
3296 if (type->tp_setattr == NULL && type->tp_setattro == NULL) {
3297 type->tp_setattr = base->tp_setattr;
3298 type->tp_setattro = base->tp_setattro;
3299 }
3300 /* tp_compare see tp_richcompare */
3301 COPYSLOT(tp_repr);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003302 /* tp_hash see tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003303 COPYSLOT(tp_call);
3304 COPYSLOT(tp_str);
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00003305 {
Guido van Rossum38938152006-08-21 23:36:26 +00003306 /* Copy comparison-related slots only when
3307 not overriding them anywhere */
Guido van Rossumb8f63662001-08-15 23:57:02 +00003308 if (type->tp_compare == NULL &&
3309 type->tp_richcompare == NULL &&
Guido van Rossum38938152006-08-21 23:36:26 +00003310 type->tp_hash == NULL &&
3311 !overrides_cmp_or_hash(type))
Guido van Rossumb8f63662001-08-15 23:57:02 +00003312 {
Tim Peters6d6c1a32001-08-02 04:15:00 +00003313 type->tp_compare = base->tp_compare;
3314 type->tp_richcompare = base->tp_richcompare;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003315 type->tp_hash = base->tp_hash;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003316 }
3317 }
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00003318 {
Tim Peters6d6c1a32001-08-02 04:15:00 +00003319 COPYSLOT(tp_iter);
3320 COPYSLOT(tp_iternext);
3321 }
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00003322 {
Tim Peters6d6c1a32001-08-02 04:15:00 +00003323 COPYSLOT(tp_descr_get);
3324 COPYSLOT(tp_descr_set);
3325 COPYSLOT(tp_dictoffset);
3326 COPYSLOT(tp_init);
3327 COPYSLOT(tp_alloc);
Guido van Rossumcc8fe042002-04-05 17:10:16 +00003328 COPYSLOT(tp_is_gc);
Tim Peters3cfe7542003-05-21 21:29:48 +00003329 if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) ==
3330 (base->tp_flags & Py_TPFLAGS_HAVE_GC)) {
3331 /* They agree about gc. */
3332 COPYSLOT(tp_free);
3333 }
3334 else if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
3335 type->tp_free == NULL &&
3336 base->tp_free == _PyObject_Del) {
3337 /* A bit of magic to plug in the correct default
3338 * tp_free function when a derived class adds gc,
3339 * didn't define tp_free, and the base uses the
3340 * default non-gc tp_free.
3341 */
3342 type->tp_free = PyObject_GC_Del;
3343 }
3344 /* else they didn't agree about gc, and there isn't something
3345 * obvious to be done -- the type is on its own.
3346 */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003347 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003348}
3349
Jeremy Hylton938ace62002-07-17 16:30:39 +00003350static int add_operators(PyTypeObject *);
Guido van Rossum13d52f02001-08-10 21:24:08 +00003351
Tim Peters6d6c1a32001-08-02 04:15:00 +00003352int
Guido van Rossum528b7eb2001-08-07 17:24:28 +00003353PyType_Ready(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003354{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00003355 PyObject *dict, *bases;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003356 PyTypeObject *base;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003357 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003358
Guido van Rossumcab05802002-06-10 15:29:03 +00003359 if (type->tp_flags & Py_TPFLAGS_READY) {
3360 assert(type->tp_dict != NULL);
Guido van Rossumd614f972001-08-10 17:39:49 +00003361 return 0;
Guido van Rossumcab05802002-06-10 15:29:03 +00003362 }
Guido van Rossumd614f972001-08-10 17:39:49 +00003363 assert((type->tp_flags & Py_TPFLAGS_READYING) == 0);
Guido van Rossumd614f972001-08-10 17:39:49 +00003364
3365 type->tp_flags |= Py_TPFLAGS_READYING;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003366
Tim Peters36eb4df2003-03-23 03:33:13 +00003367#ifdef Py_TRACE_REFS
3368 /* PyType_Ready is the closest thing we have to a choke point
3369 * for type objects, so is the best place I can think of to try
3370 * to get type objects into the doubly-linked list of all objects.
3371 * Still, not all type objects go thru PyType_Ready.
3372 */
Tim Peters7571a0f2003-03-23 17:52:28 +00003373 _Py_AddToAllObjects((PyObject *)type, 0);
Tim Peters36eb4df2003-03-23 03:33:13 +00003374#endif
3375
Tim Peters6d6c1a32001-08-02 04:15:00 +00003376 /* Initialize tp_base (defaults to BaseObject unless that's us) */
3377 base = type->tp_base;
Martin v. Löwisbf608752004-08-18 13:16:54 +00003378 if (base == NULL && type != &PyBaseObject_Type) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00003379 base = type->tp_base = &PyBaseObject_Type;
Martin v. Löwisbf608752004-08-18 13:16:54 +00003380 Py_INCREF(base);
3381 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003382
Guido van Rossumd8faa362007-04-27 19:54:29 +00003383 /* Now the only way base can still be NULL is if type is
3384 * &PyBaseObject_Type.
3385 */
Guido van Rossum692cdbc2006-03-10 02:04:28 +00003386
Guido van Rossum323a9cf2002-08-14 17:26:30 +00003387 /* Initialize the base class */
Guido van Rossum50e9fb92006-08-17 05:42:55 +00003388 if (base != NULL && base->tp_dict == NULL) {
Guido van Rossum323a9cf2002-08-14 17:26:30 +00003389 if (PyType_Ready(base) < 0)
3390 goto error;
3391 }
3392
Guido van Rossumd8faa362007-04-27 19:54:29 +00003393 /* Initialize ob_type if NULL. This means extensions that want to be
Guido van Rossum0986d822002-04-08 01:38:42 +00003394 compilable separately on Windows can call PyType_Ready() instead of
3395 initializing the ob_type field of their type objects. */
Guido van Rossumd8faa362007-04-27 19:54:29 +00003396 /* The test for base != NULL is really unnecessary, since base is only
3397 NULL when type is &PyBaseObject_Type, and we know its ob_type is
3398 not NULL (it's initialized to &PyType_Type). But coverity doesn't
3399 know that. */
Guido van Rossum692cdbc2006-03-10 02:04:28 +00003400 if (type->ob_type == NULL && base != NULL)
Guido van Rossum0986d822002-04-08 01:38:42 +00003401 type->ob_type = base->ob_type;
3402
Tim Peters6d6c1a32001-08-02 04:15:00 +00003403 /* Initialize tp_bases */
3404 bases = type->tp_bases;
3405 if (bases == NULL) {
3406 if (base == NULL)
3407 bases = PyTuple_New(0);
3408 else
Raymond Hettinger8ae46892003-10-12 19:09:37 +00003409 bases = PyTuple_Pack(1, base);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003410 if (bases == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00003411 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003412 type->tp_bases = bases;
3413 }
3414
Guido van Rossum687ae002001-10-15 22:03:32 +00003415 /* Initialize tp_dict */
3416 dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003417 if (dict == NULL) {
3418 dict = PyDict_New();
3419 if (dict == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00003420 goto error;
Guido van Rossum687ae002001-10-15 22:03:32 +00003421 type->tp_dict = dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003422 }
3423
Guido van Rossum687ae002001-10-15 22:03:32 +00003424 /* Add type-specific descriptors to tp_dict */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003425 if (add_operators(type) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003426 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003427 if (type->tp_methods != NULL) {
3428 if (add_methods(type, type->tp_methods) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003429 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003430 }
3431 if (type->tp_members != NULL) {
3432 if (add_members(type, type->tp_members) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003433 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003434 }
3435 if (type->tp_getset != NULL) {
3436 if (add_getset(type, type->tp_getset) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003437 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003438 }
3439
Tim Peters6d6c1a32001-08-02 04:15:00 +00003440 /* Calculate method resolution order */
3441 if (mro_internal(type) < 0) {
Guido van Rossumd614f972001-08-10 17:39:49 +00003442 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003443 }
3444
Guido van Rossum13d52f02001-08-10 21:24:08 +00003445 /* Inherit special flags from dominant base */
3446 if (type->tp_base != NULL)
3447 inherit_special(type, type->tp_base);
3448
Tim Peters6d6c1a32001-08-02 04:15:00 +00003449 /* Initialize tp_dict properly */
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00003450 bases = type->tp_mro;
3451 assert(bases != NULL);
3452 assert(PyTuple_Check(bases));
3453 n = PyTuple_GET_SIZE(bases);
3454 for (i = 1; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00003455 PyObject *b = PyTuple_GET_ITEM(bases, i);
3456 if (PyType_Check(b))
3457 inherit_slots(type, (PyTypeObject *)b);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003458 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003459
Tim Peters3cfe7542003-05-21 21:29:48 +00003460 /* Sanity check for tp_free. */
3461 if (PyType_IS_GC(type) && (type->tp_flags & Py_TPFLAGS_BASETYPE) &&
3462 (type->tp_free == NULL || type->tp_free == PyObject_Del)) {
Guido van Rossumd8faa362007-04-27 19:54:29 +00003463 /* This base class needs to call tp_free, but doesn't have
3464 * one, or its tp_free is for non-gc'ed objects.
3465 */
Tim Peters3cfe7542003-05-21 21:29:48 +00003466 PyErr_Format(PyExc_TypeError, "type '%.100s' participates in "
3467 "gc and is a base type but has inappropriate "
3468 "tp_free slot",
3469 type->tp_name);
3470 goto error;
3471 }
3472
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00003473 /* if the type dictionary doesn't contain a __doc__, set it from
3474 the tp_doc slot.
3475 */
3476 if (PyDict_GetItemString(type->tp_dict, "__doc__") == NULL) {
3477 if (type->tp_doc != NULL) {
3478 PyObject *doc = PyString_FromString(type->tp_doc);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003479 if (doc == NULL)
3480 goto error;
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00003481 PyDict_SetItemString(type->tp_dict, "__doc__", doc);
3482 Py_DECREF(doc);
3483 } else {
Guido van Rossumd4641072002-04-03 02:13:37 +00003484 PyDict_SetItemString(type->tp_dict,
3485 "__doc__", Py_None);
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00003486 }
3487 }
3488
Guido van Rossum38938152006-08-21 23:36:26 +00003489 /* Hack for tp_hash and __hash__.
3490 If after all that, tp_hash is still NULL, and __hash__ is not in
3491 tp_dict, set tp_dict['__hash__'] equal to None.
3492 This signals that __hash__ is not inherited.
3493 */
3494 if (type->tp_hash == NULL) {
3495 if (PyDict_GetItemString(type->tp_dict, "__hash__") == NULL) {
3496 if (PyDict_SetItemString(type->tp_dict, "__hash__", Py_None) < 0)
3497 goto error;
3498 }
3499 }
3500
Guido van Rossum13d52f02001-08-10 21:24:08 +00003501 /* Some more special stuff */
3502 base = type->tp_base;
3503 if (base != NULL) {
3504 if (type->tp_as_number == NULL)
3505 type->tp_as_number = base->tp_as_number;
3506 if (type->tp_as_sequence == NULL)
3507 type->tp_as_sequence = base->tp_as_sequence;
3508 if (type->tp_as_mapping == NULL)
3509 type->tp_as_mapping = base->tp_as_mapping;
Guido van Rossumeea47182003-02-11 20:39:59 +00003510 if (type->tp_as_buffer == NULL)
3511 type->tp_as_buffer = base->tp_as_buffer;
Guido van Rossum13d52f02001-08-10 21:24:08 +00003512 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003513
Guido van Rossum1c450732001-10-08 15:18:27 +00003514 /* Link into each base class's list of subclasses */
3515 bases = type->tp_bases;
3516 n = PyTuple_GET_SIZE(bases);
3517 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00003518 PyObject *b = PyTuple_GET_ITEM(bases, i);
3519 if (PyType_Check(b) &&
3520 add_subclass((PyTypeObject *)b, type) < 0)
Guido van Rossum1c450732001-10-08 15:18:27 +00003521 goto error;
3522 }
3523
Guido van Rossum13d52f02001-08-10 21:24:08 +00003524 /* All done -- set the ready flag */
Guido van Rossumd614f972001-08-10 17:39:49 +00003525 assert(type->tp_dict != NULL);
3526 type->tp_flags =
3527 (type->tp_flags & ~Py_TPFLAGS_READYING) | Py_TPFLAGS_READY;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003528 return 0;
Guido van Rossumd614f972001-08-10 17:39:49 +00003529
3530 error:
3531 type->tp_flags &= ~Py_TPFLAGS_READYING;
3532 return -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003533}
3534
Guido van Rossum1c450732001-10-08 15:18:27 +00003535static int
3536add_subclass(PyTypeObject *base, PyTypeObject *type)
3537{
Martin v. Löwiseb079f12006-02-16 14:32:27 +00003538 Py_ssize_t i;
3539 int result;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003540 PyObject *list, *ref, *newobj;
Guido van Rossum1c450732001-10-08 15:18:27 +00003541
3542 list = base->tp_subclasses;
3543 if (list == NULL) {
3544 base->tp_subclasses = list = PyList_New(0);
3545 if (list == NULL)
3546 return -1;
3547 }
3548 assert(PyList_Check(list));
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003549 newobj = PyWeakref_NewRef((PyObject *)type, NULL);
Guido van Rossum1c450732001-10-08 15:18:27 +00003550 i = PyList_GET_SIZE(list);
3551 while (--i >= 0) {
3552 ref = PyList_GET_ITEM(list, i);
3553 assert(PyWeakref_CheckRef(ref));
Guido van Rossum3930bc32002-10-18 13:51:49 +00003554 if (PyWeakref_GET_OBJECT(ref) == Py_None)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003555 return PyList_SetItem(list, i, newobj);
Guido van Rossum1c450732001-10-08 15:18:27 +00003556 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003557 result = PyList_Append(list, newobj);
3558 Py_DECREF(newobj);
Martin v. Löwiseb079f12006-02-16 14:32:27 +00003559 return result;
Guido van Rossum1c450732001-10-08 15:18:27 +00003560}
3561
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003562static void
3563remove_subclass(PyTypeObject *base, PyTypeObject *type)
3564{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003565 Py_ssize_t i;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003566 PyObject *list, *ref;
3567
3568 list = base->tp_subclasses;
3569 if (list == NULL) {
3570 return;
3571 }
3572 assert(PyList_Check(list));
3573 i = PyList_GET_SIZE(list);
3574 while (--i >= 0) {
3575 ref = PyList_GET_ITEM(list, i);
3576 assert(PyWeakref_CheckRef(ref));
3577 if (PyWeakref_GET_OBJECT(ref) == (PyObject*)type) {
3578 /* this can't fail, right? */
3579 PySequence_DelItem(list, i);
3580 return;
3581 }
3582 }
3583}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003584
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003585static int
3586check_num_args(PyObject *ob, int n)
3587{
3588 if (!PyTuple_CheckExact(ob)) {
3589 PyErr_SetString(PyExc_SystemError,
3590 "PyArg_UnpackTuple() argument list is not a tuple");
3591 return 0;
3592 }
3593 if (n == PyTuple_GET_SIZE(ob))
3594 return 1;
3595 PyErr_Format(
3596 PyExc_TypeError,
Martin v. Löwis2c95cc62006-02-16 06:54:25 +00003597 "expected %d arguments, got %zd", n, PyTuple_GET_SIZE(ob));
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003598 return 0;
3599}
3600
Tim Peters6d6c1a32001-08-02 04:15:00 +00003601/* Generic wrappers for overloadable 'operators' such as __getitem__ */
3602
3603/* There's a wrapper *function* for each distinct function typedef used
Guido van Rossumd8faa362007-04-27 19:54:29 +00003604 for type object slots (e.g. binaryfunc, ternaryfunc, etc.). There's a
Tim Peters6d6c1a32001-08-02 04:15:00 +00003605 wrapper *table* for each distinct operation (e.g. __len__, __add__).
3606 Most tables have only one entry; the tables for binary operators have two
3607 entries, one regular and one with reversed arguments. */
3608
3609static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00003610wrap_lenfunc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003611{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003612 lenfunc func = (lenfunc)wrapped;
3613 Py_ssize_t res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003614
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003615 if (!check_num_args(args, 0))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003616 return NULL;
3617 res = (*func)(self);
3618 if (res == -1 && PyErr_Occurred())
3619 return NULL;
3620 return PyInt_FromLong((long)res);
3621}
3622
Tim Peters6d6c1a32001-08-02 04:15:00 +00003623static PyObject *
Raymond Hettingerf34f2642003-10-11 17:29:04 +00003624wrap_inquirypred(PyObject *self, PyObject *args, void *wrapped)
3625{
3626 inquiry func = (inquiry)wrapped;
3627 int res;
3628
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003629 if (!check_num_args(args, 0))
Raymond Hettingerf34f2642003-10-11 17:29:04 +00003630 return NULL;
3631 res = (*func)(self);
3632 if (res == -1 && PyErr_Occurred())
3633 return NULL;
3634 return PyBool_FromLong((long)res);
3635}
3636
3637static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00003638wrap_binaryfunc(PyObject *self, PyObject *args, void *wrapped)
3639{
3640 binaryfunc func = (binaryfunc)wrapped;
3641 PyObject *other;
3642
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003643 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003644 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003645 other = PyTuple_GET_ITEM(args, 0);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003646 return (*func)(self, other);
3647}
3648
3649static PyObject *
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003650wrap_binaryfunc_l(PyObject *self, PyObject *args, void *wrapped)
3651{
3652 binaryfunc func = (binaryfunc)wrapped;
3653 PyObject *other;
3654
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003655 if (!check_num_args(args, 1))
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003656 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003657 other = PyTuple_GET_ITEM(args, 0);
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003658 return (*func)(self, other);
3659}
3660
3661static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00003662wrap_binaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
3663{
3664 binaryfunc func = (binaryfunc)wrapped;
3665 PyObject *other;
3666
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003667 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003668 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003669 other = PyTuple_GET_ITEM(args, 0);
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00003670 if (!PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003671 Py_INCREF(Py_NotImplemented);
3672 return Py_NotImplemented;
3673 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003674 return (*func)(other, self);
3675}
3676
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003677static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00003678wrap_ternaryfunc(PyObject *self, PyObject *args, void *wrapped)
3679{
3680 ternaryfunc func = (ternaryfunc)wrapped;
3681 PyObject *other;
3682 PyObject *third = Py_None;
3683
3684 /* Note: This wrapper only works for __pow__() */
3685
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00003686 if (!PyArg_UnpackTuple(args, "", 1, 2, &other, &third))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003687 return NULL;
3688 return (*func)(self, other, third);
3689}
3690
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00003691static PyObject *
3692wrap_ternaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
3693{
3694 ternaryfunc func = (ternaryfunc)wrapped;
3695 PyObject *other;
3696 PyObject *third = Py_None;
3697
3698 /* Note: This wrapper only works for __pow__() */
3699
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00003700 if (!PyArg_UnpackTuple(args, "", 1, 2, &other, &third))
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00003701 return NULL;
3702 return (*func)(other, self, third);
3703}
3704
Tim Peters6d6c1a32001-08-02 04:15:00 +00003705static PyObject *
3706wrap_unaryfunc(PyObject *self, PyObject *args, void *wrapped)
3707{
3708 unaryfunc func = (unaryfunc)wrapped;
3709
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003710 if (!check_num_args(args, 0))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003711 return NULL;
3712 return (*func)(self);
3713}
3714
Tim Peters6d6c1a32001-08-02 04:15:00 +00003715static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003716wrap_indexargfunc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003717{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003718 ssizeargfunc func = (ssizeargfunc)wrapped;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003719 PyObject* o;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003720 Py_ssize_t i;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003721
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003722 if (!PyArg_UnpackTuple(args, "", 1, 1, &o))
3723 return NULL;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00003724 i = PyNumber_AsSsize_t(o, PyExc_OverflowError);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003725 if (i == -1 && PyErr_Occurred())
Tim Peters6d6c1a32001-08-02 04:15:00 +00003726 return NULL;
3727 return (*func)(self, i);
3728}
3729
Martin v. Löwis18e16552006-02-15 17:27:45 +00003730static Py_ssize_t
Guido van Rossum5d815f32001-08-17 21:57:47 +00003731getindex(PyObject *self, PyObject *arg)
3732{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003733 Py_ssize_t i;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003734
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00003735 i = PyNumber_AsSsize_t(arg, PyExc_OverflowError);
Guido van Rossum5d815f32001-08-17 21:57:47 +00003736 if (i == -1 && PyErr_Occurred())
3737 return -1;
3738 if (i < 0) {
3739 PySequenceMethods *sq = self->ob_type->tp_as_sequence;
3740 if (sq && sq->sq_length) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00003741 Py_ssize_t n = (*sq->sq_length)(self);
Guido van Rossum5d815f32001-08-17 21:57:47 +00003742 if (n < 0)
3743 return -1;
3744 i += n;
3745 }
3746 }
3747 return i;
3748}
3749
3750static PyObject *
3751wrap_sq_item(PyObject *self, PyObject *args, void *wrapped)
3752{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003753 ssizeargfunc func = (ssizeargfunc)wrapped;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003754 PyObject *arg;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003755 Py_ssize_t i;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003756
Guido van Rossumf4593e02001-10-03 12:09:30 +00003757 if (PyTuple_GET_SIZE(args) == 1) {
3758 arg = PyTuple_GET_ITEM(args, 0);
3759 i = getindex(self, arg);
3760 if (i == -1 && PyErr_Occurred())
3761 return NULL;
3762 return (*func)(self, i);
3763 }
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003764 check_num_args(args, 1);
Guido van Rossumf4593e02001-10-03 12:09:30 +00003765 assert(PyErr_Occurred());
3766 return NULL;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003767}
3768
Tim Peters6d6c1a32001-08-02 04:15:00 +00003769static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00003770wrap_ssizessizeargfunc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003771{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003772 ssizessizeargfunc func = (ssizessizeargfunc)wrapped;
3773 Py_ssize_t i, j;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003774
Martin v. Löwis18e16552006-02-15 17:27:45 +00003775 if (!PyArg_ParseTuple(args, "nn", &i, &j))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003776 return NULL;
3777 return (*func)(self, i, j);
3778}
3779
Tim Peters6d6c1a32001-08-02 04:15:00 +00003780static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00003781wrap_sq_setitem(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003782{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003783 ssizeobjargproc func = (ssizeobjargproc)wrapped;
3784 Py_ssize_t i;
3785 int res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003786 PyObject *arg, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003787
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00003788 if (!PyArg_UnpackTuple(args, "", 2, 2, &arg, &value))
Guido van Rossum5d815f32001-08-17 21:57:47 +00003789 return NULL;
3790 i = getindex(self, arg);
3791 if (i == -1 && PyErr_Occurred())
Tim Peters6d6c1a32001-08-02 04:15:00 +00003792 return NULL;
3793 res = (*func)(self, i, value);
3794 if (res == -1 && PyErr_Occurred())
3795 return NULL;
3796 Py_INCREF(Py_None);
3797 return Py_None;
3798}
3799
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003800static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00003801wrap_sq_delitem(PyObject *self, PyObject *args, void *wrapped)
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003802{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003803 ssizeobjargproc func = (ssizeobjargproc)wrapped;
3804 Py_ssize_t i;
3805 int res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003806 PyObject *arg;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003807
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003808 if (!check_num_args(args, 1))
Guido van Rossum5d815f32001-08-17 21:57:47 +00003809 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003810 arg = PyTuple_GET_ITEM(args, 0);
Guido van Rossum5d815f32001-08-17 21:57:47 +00003811 i = getindex(self, arg);
3812 if (i == -1 && PyErr_Occurred())
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003813 return NULL;
3814 res = (*func)(self, i, NULL);
3815 if (res == -1 && PyErr_Occurred())
3816 return NULL;
3817 Py_INCREF(Py_None);
3818 return Py_None;
3819}
3820
Tim Peters6d6c1a32001-08-02 04:15:00 +00003821static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00003822wrap_ssizessizeobjargproc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003823{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003824 ssizessizeobjargproc func = (ssizessizeobjargproc)wrapped;
3825 Py_ssize_t i, j;
3826 int res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003827 PyObject *value;
3828
Martin v. Löwis18e16552006-02-15 17:27:45 +00003829 if (!PyArg_ParseTuple(args, "nnO", &i, &j, &value))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003830 return NULL;
3831 res = (*func)(self, i, j, value);
3832 if (res == -1 && PyErr_Occurred())
3833 return NULL;
3834 Py_INCREF(Py_None);
3835 return Py_None;
3836}
3837
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003838static PyObject *
3839wrap_delslice(PyObject *self, PyObject *args, void *wrapped)
3840{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003841 ssizessizeobjargproc func = (ssizessizeobjargproc)wrapped;
3842 Py_ssize_t i, j;
3843 int res;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003844
Martin v. Löwis18e16552006-02-15 17:27:45 +00003845 if (!PyArg_ParseTuple(args, "nn", &i, &j))
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003846 return NULL;
3847 res = (*func)(self, i, j, NULL);
3848 if (res == -1 && PyErr_Occurred())
3849 return NULL;
3850 Py_INCREF(Py_None);
3851 return Py_None;
3852}
3853
Tim Peters6d6c1a32001-08-02 04:15:00 +00003854/* XXX objobjproc is a misnomer; should be objargpred */
3855static PyObject *
3856wrap_objobjproc(PyObject *self, PyObject *args, void *wrapped)
3857{
3858 objobjproc func = (objobjproc)wrapped;
3859 int res;
Guido van Rossum22c3dda2003-10-09 03:46:35 +00003860 PyObject *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003861
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003862 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003863 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003864 value = PyTuple_GET_ITEM(args, 0);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003865 res = (*func)(self, value);
3866 if (res == -1 && PyErr_Occurred())
3867 return NULL;
Guido van Rossum22c3dda2003-10-09 03:46:35 +00003868 else
3869 return PyBool_FromLong(res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003870}
3871
Tim Peters6d6c1a32001-08-02 04:15:00 +00003872static PyObject *
3873wrap_objobjargproc(PyObject *self, PyObject *args, void *wrapped)
3874{
3875 objobjargproc func = (objobjargproc)wrapped;
3876 int res;
3877 PyObject *key, *value;
3878
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00003879 if (!PyArg_UnpackTuple(args, "", 2, 2, &key, &value))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003880 return NULL;
3881 res = (*func)(self, key, value);
3882 if (res == -1 && PyErr_Occurred())
3883 return NULL;
3884 Py_INCREF(Py_None);
3885 return Py_None;
3886}
3887
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003888static PyObject *
3889wrap_delitem(PyObject *self, PyObject *args, void *wrapped)
3890{
3891 objobjargproc func = (objobjargproc)wrapped;
3892 int res;
3893 PyObject *key;
3894
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003895 if (!check_num_args(args, 1))
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003896 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003897 key = PyTuple_GET_ITEM(args, 0);
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003898 res = (*func)(self, key, NULL);
3899 if (res == -1 && PyErr_Occurred())
3900 return NULL;
3901 Py_INCREF(Py_None);
3902 return Py_None;
3903}
3904
Tim Peters6d6c1a32001-08-02 04:15:00 +00003905static PyObject *
3906wrap_cmpfunc(PyObject *self, PyObject *args, void *wrapped)
3907{
3908 cmpfunc func = (cmpfunc)wrapped;
3909 int res;
3910 PyObject *other;
3911
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003912 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003913 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003914 other = PyTuple_GET_ITEM(args, 0);
Guido van Rossum3d45d8f2001-09-24 18:47:40 +00003915 if (other->ob_type->tp_compare != func &&
3916 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossumceccae52001-09-18 20:03:57 +00003917 PyErr_Format(
3918 PyExc_TypeError,
3919 "%s.__cmp__(x,y) requires y to be a '%s', not a '%s'",
3920 self->ob_type->tp_name,
3921 self->ob_type->tp_name,
3922 other->ob_type->tp_name);
3923 return NULL;
3924 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003925 res = (*func)(self, other);
3926 if (PyErr_Occurred())
3927 return NULL;
3928 return PyInt_FromLong((long)res);
3929}
3930
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003931/* Helper to check for object.__setattr__ or __delattr__ applied to a type.
Guido van Rossum52b27052003-04-15 20:05:10 +00003932 This is called the Carlo Verre hack after its discoverer. */
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003933static int
3934hackcheck(PyObject *self, setattrofunc func, char *what)
3935{
3936 PyTypeObject *type = self->ob_type;
3937 while (type && type->tp_flags & Py_TPFLAGS_HEAPTYPE)
3938 type = type->tp_base;
Guido van Rossumd8faa362007-04-27 19:54:29 +00003939 /* If type is NULL now, this is a really weird type.
3940 In the spirit of backwards compatibility (?), just shut up. */
Guido van Rossum692cdbc2006-03-10 02:04:28 +00003941 if (type && type->tp_setattro != func) {
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003942 PyErr_Format(PyExc_TypeError,
3943 "can't apply this %s to %s object",
3944 what,
3945 type->tp_name);
3946 return 0;
3947 }
3948 return 1;
3949}
3950
Tim Peters6d6c1a32001-08-02 04:15:00 +00003951static PyObject *
3952wrap_setattr(PyObject *self, PyObject *args, void *wrapped)
3953{
3954 setattrofunc func = (setattrofunc)wrapped;
3955 int res;
3956 PyObject *name, *value;
3957
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00003958 if (!PyArg_UnpackTuple(args, "", 2, 2, &name, &value))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003959 return NULL;
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003960 if (!hackcheck(self, func, "__setattr__"))
3961 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003962 res = (*func)(self, name, value);
3963 if (res < 0)
3964 return NULL;
3965 Py_INCREF(Py_None);
3966 return Py_None;
3967}
3968
3969static PyObject *
3970wrap_delattr(PyObject *self, PyObject *args, void *wrapped)
3971{
3972 setattrofunc func = (setattrofunc)wrapped;
3973 int res;
3974 PyObject *name;
3975
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003976 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003977 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003978 name = PyTuple_GET_ITEM(args, 0);
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003979 if (!hackcheck(self, func, "__delattr__"))
3980 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003981 res = (*func)(self, name, NULL);
3982 if (res < 0)
3983 return NULL;
3984 Py_INCREF(Py_None);
3985 return Py_None;
3986}
3987
Tim Peters6d6c1a32001-08-02 04:15:00 +00003988static PyObject *
3989wrap_hashfunc(PyObject *self, PyObject *args, void *wrapped)
3990{
3991 hashfunc func = (hashfunc)wrapped;
3992 long res;
3993
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003994 if (!check_num_args(args, 0))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003995 return NULL;
3996 res = (*func)(self);
3997 if (res == -1 && PyErr_Occurred())
3998 return NULL;
3999 return PyInt_FromLong(res);
4000}
4001
Tim Peters6d6c1a32001-08-02 04:15:00 +00004002static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00004003wrap_call(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004004{
4005 ternaryfunc func = (ternaryfunc)wrapped;
4006
Guido van Rossumc8e56452001-10-22 00:43:43 +00004007 return (*func)(self, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004008}
4009
Tim Peters6d6c1a32001-08-02 04:15:00 +00004010static PyObject *
4011wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op)
4012{
4013 richcmpfunc func = (richcmpfunc)wrapped;
4014 PyObject *other;
4015
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004016 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004017 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004018 other = PyTuple_GET_ITEM(args, 0);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004019 return (*func)(self, other, op);
4020}
4021
4022#undef RICHCMP_WRAPPER
4023#define RICHCMP_WRAPPER(NAME, OP) \
4024static PyObject * \
4025richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \
4026{ \
4027 return wrap_richcmpfunc(self, args, wrapped, OP); \
4028}
4029
Jack Jansen8e938b42001-08-08 15:29:49 +00004030RICHCMP_WRAPPER(lt, Py_LT)
4031RICHCMP_WRAPPER(le, Py_LE)
4032RICHCMP_WRAPPER(eq, Py_EQ)
4033RICHCMP_WRAPPER(ne, Py_NE)
4034RICHCMP_WRAPPER(gt, Py_GT)
4035RICHCMP_WRAPPER(ge, Py_GE)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004036
Tim Peters6d6c1a32001-08-02 04:15:00 +00004037static PyObject *
4038wrap_next(PyObject *self, PyObject *args, void *wrapped)
4039{
4040 unaryfunc func = (unaryfunc)wrapped;
4041 PyObject *res;
4042
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004043 if (!check_num_args(args, 0))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004044 return NULL;
4045 res = (*func)(self);
4046 if (res == NULL && !PyErr_Occurred())
4047 PyErr_SetNone(PyExc_StopIteration);
4048 return res;
4049}
4050
Tim Peters6d6c1a32001-08-02 04:15:00 +00004051static PyObject *
4052wrap_descr_get(PyObject *self, PyObject *args, void *wrapped)
4053{
4054 descrgetfunc func = (descrgetfunc)wrapped;
4055 PyObject *obj;
4056 PyObject *type = NULL;
4057
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00004058 if (!PyArg_UnpackTuple(args, "", 1, 2, &obj, &type))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004059 return NULL;
Guido van Rossum82ed25c2003-02-11 16:25:43 +00004060 if (obj == Py_None)
4061 obj = NULL;
4062 if (type == Py_None)
4063 type = NULL;
4064 if (type == NULL &&obj == NULL) {
4065 PyErr_SetString(PyExc_TypeError,
4066 "__get__(None, None) is invalid");
4067 return NULL;
4068 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004069 return (*func)(self, obj, type);
4070}
4071
Tim Peters6d6c1a32001-08-02 04:15:00 +00004072static PyObject *
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004073wrap_descr_set(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004074{
4075 descrsetfunc func = (descrsetfunc)wrapped;
4076 PyObject *obj, *value;
4077 int ret;
4078
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00004079 if (!PyArg_UnpackTuple(args, "", 2, 2, &obj, &value))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004080 return NULL;
4081 ret = (*func)(self, obj, value);
4082 if (ret < 0)
4083 return NULL;
4084 Py_INCREF(Py_None);
4085 return Py_None;
4086}
Guido van Rossum22b13872002-08-06 21:41:44 +00004087
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00004088static PyObject *
4089wrap_descr_delete(PyObject *self, PyObject *args, void *wrapped)
4090{
4091 descrsetfunc func = (descrsetfunc)wrapped;
4092 PyObject *obj;
4093 int ret;
4094
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004095 if (!check_num_args(args, 1))
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00004096 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004097 obj = PyTuple_GET_ITEM(args, 0);
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00004098 ret = (*func)(self, obj, NULL);
4099 if (ret < 0)
4100 return NULL;
4101 Py_INCREF(Py_None);
4102 return Py_None;
4103}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004104
Tim Peters6d6c1a32001-08-02 04:15:00 +00004105static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00004106wrap_init(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004107{
4108 initproc func = (initproc)wrapped;
4109
Guido van Rossumc8e56452001-10-22 00:43:43 +00004110 if (func(self, args, kwds) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004111 return NULL;
4112 Py_INCREF(Py_None);
4113 return Py_None;
4114}
4115
Tim Peters6d6c1a32001-08-02 04:15:00 +00004116static PyObject *
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004117tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004118{
Barry Warsaw60f01882001-08-22 19:24:42 +00004119 PyTypeObject *type, *subtype, *staticbase;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004120 PyObject *arg0, *res;
4121
4122 if (self == NULL || !PyType_Check(self))
4123 Py_FatalError("__new__() called with non-type 'self'");
4124 type = (PyTypeObject *)self;
4125 if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) {
Barry Warsaw60f01882001-08-22 19:24:42 +00004126 PyErr_Format(PyExc_TypeError,
4127 "%s.__new__(): not enough arguments",
4128 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004129 return NULL;
4130 }
4131 arg0 = PyTuple_GET_ITEM(args, 0);
4132 if (!PyType_Check(arg0)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00004133 PyErr_Format(PyExc_TypeError,
4134 "%s.__new__(X): X is not a type object (%s)",
4135 type->tp_name,
4136 arg0->ob_type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004137 return NULL;
4138 }
4139 subtype = (PyTypeObject *)arg0;
4140 if (!PyType_IsSubtype(subtype, type)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00004141 PyErr_Format(PyExc_TypeError,
4142 "%s.__new__(%s): %s is not a subtype of %s",
4143 type->tp_name,
4144 subtype->tp_name,
4145 subtype->tp_name,
4146 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004147 return NULL;
4148 }
Barry Warsaw60f01882001-08-22 19:24:42 +00004149
4150 /* Check that the use doesn't do something silly and unsafe like
Tim Petersa427a2b2001-10-29 22:25:45 +00004151 object.__new__(dict). To do this, we check that the
Barry Warsaw60f01882001-08-22 19:24:42 +00004152 most derived base that's not a heap type is this type. */
4153 staticbase = subtype;
4154 while (staticbase && (staticbase->tp_flags & Py_TPFLAGS_HEAPTYPE))
4155 staticbase = staticbase->tp_base;
Guido van Rossumd8faa362007-04-27 19:54:29 +00004156 /* If staticbase is NULL now, it is a really weird type.
4157 In the spirit of backwards compatibility (?), just shut up. */
Guido van Rossum692cdbc2006-03-10 02:04:28 +00004158 if (staticbase && staticbase->tp_new != type->tp_new) {
Barry Warsaw60f01882001-08-22 19:24:42 +00004159 PyErr_Format(PyExc_TypeError,
4160 "%s.__new__(%s) is not safe, use %s.__new__()",
4161 type->tp_name,
4162 subtype->tp_name,
4163 staticbase == NULL ? "?" : staticbase->tp_name);
4164 return NULL;
4165 }
4166
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004167 args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
4168 if (args == NULL)
4169 return NULL;
4170 res = type->tp_new(subtype, args, kwds);
4171 Py_DECREF(args);
4172 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004173}
4174
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004175static struct PyMethodDef tp_new_methoddef[] = {
Guido van Rossumd59da4b2007-05-22 18:11:13 +00004176 {"__new__", (PyCFunction)tp_new_wrapper, METH_VARARGS|METH_KEYWORDS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00004177 PyDoc_STR("T.__new__(S, ...) -> "
Guido van Rossumd8faa362007-04-27 19:54:29 +00004178 "a new object with type S, a subtype of T")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00004179 {0}
4180};
4181
4182static int
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004183add_tp_new_wrapper(PyTypeObject *type)
4184{
Guido van Rossumf040ede2001-08-07 16:40:56 +00004185 PyObject *func;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004186
Guido van Rossum687ae002001-10-15 22:03:32 +00004187 if (PyDict_GetItemString(type->tp_dict, "__new__") != NULL)
Guido van Rossumf040ede2001-08-07 16:40:56 +00004188 return 0;
4189 func = PyCFunction_New(tp_new_methoddef, (PyObject *)type);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004190 if (func == NULL)
4191 return -1;
Raymond Hettinger8d726ee2004-06-25 22:24:35 +00004192 if (PyDict_SetItemString(type->tp_dict, "__new__", func)) {
Raymond Hettingerd56cbe52004-06-25 22:17:39 +00004193 Py_DECREF(func);
4194 return -1;
4195 }
4196 Py_DECREF(func);
4197 return 0;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004198}
4199
Guido van Rossumf040ede2001-08-07 16:40:56 +00004200/* Slot wrappers that call the corresponding __foo__ slot. See comments
4201 below at override_slots() for more explanation. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004202
Guido van Rossumdc91b992001-08-08 22:26:22 +00004203#define SLOT0(FUNCNAME, OPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004204static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004205FUNCNAME(PyObject *self) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004206{ \
Guido van Rossum5592e4d2001-08-28 18:28:21 +00004207 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00004208 return call_method(self, OPSTR, &cache_str, "()"); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004209}
4210
Guido van Rossumdc91b992001-08-08 22:26:22 +00004211#define SLOT1(FUNCNAME, OPSTR, ARG1TYPE, ARGCODES) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004212static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004213FUNCNAME(PyObject *self, ARG1TYPE arg1) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004214{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00004215 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00004216 return call_method(self, OPSTR, &cache_str, "(" ARGCODES ")", arg1); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004217}
4218
Guido van Rossumcd118802003-01-06 22:57:47 +00004219/* Boolean helper for SLOT1BINFULL().
4220 right.__class__ is a nontrivial subclass of left.__class__. */
4221static int
4222method_is_overloaded(PyObject *left, PyObject *right, char *name)
4223{
4224 PyObject *a, *b;
4225 int ok;
4226
4227 b = PyObject_GetAttrString((PyObject *)(right->ob_type), name);
4228 if (b == NULL) {
4229 PyErr_Clear();
4230 /* If right doesn't have it, it's not overloaded */
4231 return 0;
4232 }
4233
4234 a = PyObject_GetAttrString((PyObject *)(left->ob_type), name);
4235 if (a == NULL) {
4236 PyErr_Clear();
4237 Py_DECREF(b);
4238 /* If right has it but left doesn't, it's overloaded */
4239 return 1;
4240 }
4241
4242 ok = PyObject_RichCompareBool(a, b, Py_NE);
4243 Py_DECREF(a);
4244 Py_DECREF(b);
4245 if (ok < 0) {
4246 PyErr_Clear();
4247 return 0;
4248 }
4249
4250 return ok;
4251}
4252
Guido van Rossumdc91b992001-08-08 22:26:22 +00004253
4254#define SLOT1BINFULL(FUNCNAME, TESTFUNC, SLOTNAME, OPSTR, ROPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004255static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004256FUNCNAME(PyObject *self, PyObject *other) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004257{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00004258 static PyObject *cache_str, *rcache_str; \
Guido van Rossum55f20992001-10-01 17:18:22 +00004259 int do_other = self->ob_type != other->ob_type && \
4260 other->ob_type->tp_as_number != NULL && \
4261 other->ob_type->tp_as_number->SLOTNAME == TESTFUNC; \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004262 if (self->ob_type->tp_as_number != NULL && \
4263 self->ob_type->tp_as_number->SLOTNAME == TESTFUNC) { \
4264 PyObject *r; \
Guido van Rossum55f20992001-10-01 17:18:22 +00004265 if (do_other && \
Guido van Rossumcd118802003-01-06 22:57:47 +00004266 PyType_IsSubtype(other->ob_type, self->ob_type) && \
4267 method_is_overloaded(self, other, ROPSTR)) { \
Guido van Rossum55f20992001-10-01 17:18:22 +00004268 r = call_maybe( \
4269 other, ROPSTR, &rcache_str, "(O)", self); \
4270 if (r != Py_NotImplemented) \
4271 return r; \
4272 Py_DECREF(r); \
4273 do_other = 0; \
4274 } \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00004275 r = call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00004276 self, OPSTR, &cache_str, "(O)", other); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004277 if (r != Py_NotImplemented || \
4278 other->ob_type == self->ob_type) \
4279 return r; \
4280 Py_DECREF(r); \
4281 } \
Guido van Rossum55f20992001-10-01 17:18:22 +00004282 if (do_other) { \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00004283 return call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00004284 other, ROPSTR, &rcache_str, "(O)", self); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004285 } \
4286 Py_INCREF(Py_NotImplemented); \
4287 return Py_NotImplemented; \
4288}
4289
4290#define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) \
4291 SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR)
4292
4293#define SLOT2(FUNCNAME, OPSTR, ARG1TYPE, ARG2TYPE, ARGCODES) \
4294static PyObject * \
4295FUNCNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \
4296{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00004297 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00004298 return call_method(self, OPSTR, &cache_str, \
4299 "(" ARGCODES ")", arg1, arg2); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004300}
4301
Martin v. Löwis18e16552006-02-15 17:27:45 +00004302static Py_ssize_t
Tim Peters6d6c1a32001-08-02 04:15:00 +00004303slot_sq_length(PyObject *self)
4304{
Guido van Rossum2730b132001-08-28 18:22:14 +00004305 static PyObject *len_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00004306 PyObject *res = call_method(self, "__len__", &len_str, "()");
Martin v. Löwis18e16552006-02-15 17:27:45 +00004307 Py_ssize_t len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004308
4309 if (res == NULL)
4310 return -1;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00004311 len = PyInt_AsSsize_t(res);
Guido van Rossum26111622001-10-01 16:42:49 +00004312 Py_DECREF(res);
Jeremy Hyltonf20fcf92002-07-25 16:06:15 +00004313 if (len < 0) {
Thomas Wouters89f507f2006-12-13 04:49:30 +00004314 if (!PyErr_Occurred())
4315 PyErr_SetString(PyExc_ValueError,
4316 "__len__() should return >= 0");
Jeremy Hyltonf20fcf92002-07-25 16:06:15 +00004317 return -1;
4318 }
Guido van Rossum26111622001-10-01 16:42:49 +00004319 return len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004320}
4321
Guido van Rossumf4593e02001-10-03 12:09:30 +00004322/* Super-optimized version of slot_sq_item.
4323 Other slots could do the same... */
4324static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00004325slot_sq_item(PyObject *self, Py_ssize_t i)
Guido van Rossumf4593e02001-10-03 12:09:30 +00004326{
4327 static PyObject *getitem_str;
4328 PyObject *func, *args = NULL, *ival = NULL, *retval = NULL;
4329 descrgetfunc f;
4330
4331 if (getitem_str == NULL) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00004332 getitem_str = PyUnicode_InternFromString("__getitem__");
Guido van Rossumf4593e02001-10-03 12:09:30 +00004333 if (getitem_str == NULL)
4334 return NULL;
4335 }
4336 func = _PyType_Lookup(self->ob_type, getitem_str);
4337 if (func != NULL) {
Guido van Rossumf4593e02001-10-03 12:09:30 +00004338 if ((f = func->ob_type->tp_descr_get) == NULL)
4339 Py_INCREF(func);
Neal Norwitz673cd822002-10-18 16:33:13 +00004340 else {
Guido van Rossumf4593e02001-10-03 12:09:30 +00004341 func = f(func, self, (PyObject *)(self->ob_type));
Neal Norwitz673cd822002-10-18 16:33:13 +00004342 if (func == NULL) {
4343 return NULL;
4344 }
4345 }
Martin v. Löwiseb079f12006-02-16 14:32:27 +00004346 ival = PyInt_FromSsize_t(i);
Guido van Rossumf4593e02001-10-03 12:09:30 +00004347 if (ival != NULL) {
4348 args = PyTuple_New(1);
4349 if (args != NULL) {
4350 PyTuple_SET_ITEM(args, 0, ival);
4351 retval = PyObject_Call(func, args, NULL);
4352 Py_XDECREF(args);
4353 Py_XDECREF(func);
4354 return retval;
4355 }
4356 }
4357 }
4358 else {
4359 PyErr_SetObject(PyExc_AttributeError, getitem_str);
4360 }
4361 Py_XDECREF(args);
4362 Py_XDECREF(ival);
4363 Py_XDECREF(func);
4364 return NULL;
4365}
4366
Martin v. Löwis18e16552006-02-15 17:27:45 +00004367SLOT2(slot_sq_slice, "__getslice__", Py_ssize_t, Py_ssize_t, "nn")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004368
4369static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00004370slot_sq_ass_item(PyObject *self, Py_ssize_t index, PyObject *value)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004371{
4372 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004373 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004374
4375 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004376 res = call_method(self, "__delitem__", &delitem_str,
Thomas Wouters3fc2ca32006-04-21 11:28:17 +00004377 "(n)", index);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004378 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004379 res = call_method(self, "__setitem__", &setitem_str,
Thomas Wouters3fc2ca32006-04-21 11:28:17 +00004380 "(nO)", index, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004381 if (res == NULL)
4382 return -1;
4383 Py_DECREF(res);
4384 return 0;
4385}
4386
4387static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00004388slot_sq_ass_slice(PyObject *self, Py_ssize_t i, Py_ssize_t j, PyObject *value)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004389{
4390 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004391 static PyObject *delslice_str, *setslice_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004392
4393 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004394 res = call_method(self, "__delslice__", &delslice_str,
Thomas Wouters3fc2ca32006-04-21 11:28:17 +00004395 "(nn)", i, j);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004396 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004397 res = call_method(self, "__setslice__", &setslice_str,
Thomas Wouters3fc2ca32006-04-21 11:28:17 +00004398 "(nnO)", i, j, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004399 if (res == NULL)
4400 return -1;
4401 Py_DECREF(res);
4402 return 0;
4403}
4404
4405static int
4406slot_sq_contains(PyObject *self, PyObject *value)
4407{
Guido van Rossumb8f63662001-08-15 23:57:02 +00004408 PyObject *func, *res, *args;
Tim Petersbf9b2442003-03-23 05:35:36 +00004409 int result = -1;
4410
Guido van Rossum60718732001-08-28 17:47:51 +00004411 static PyObject *contains_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004412
Guido van Rossum55f20992001-10-01 17:18:22 +00004413 func = lookup_maybe(self, "__contains__", &contains_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004414 if (func != NULL) {
Raymond Hettinger8ae46892003-10-12 19:09:37 +00004415 args = PyTuple_Pack(1, value);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004416 if (args == NULL)
4417 res = NULL;
4418 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00004419 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004420 Py_DECREF(args);
4421 }
4422 Py_DECREF(func);
Tim Petersbf9b2442003-03-23 05:35:36 +00004423 if (res != NULL) {
4424 result = PyObject_IsTrue(res);
4425 Py_DECREF(res);
4426 }
Guido van Rossumb8f63662001-08-15 23:57:02 +00004427 }
Tim Petersbf9b2442003-03-23 05:35:36 +00004428 else if (! PyErr_Occurred()) {
Martin v. Löwis725507b2006-03-07 12:08:51 +00004429 /* Possible results: -1 and 1 */
4430 result = (int)_PySequence_IterSearch(self, value,
Tim Petersbf9b2442003-03-23 05:35:36 +00004431 PY_ITERSEARCH_CONTAINS);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004432 }
Tim Petersbf9b2442003-03-23 05:35:36 +00004433 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004434}
4435
Tim Peters6d6c1a32001-08-02 04:15:00 +00004436#define slot_mp_length slot_sq_length
4437
Guido van Rossumdc91b992001-08-08 22:26:22 +00004438SLOT1(slot_mp_subscript, "__getitem__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004439
4440static int
4441slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value)
4442{
4443 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004444 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004445
4446 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004447 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004448 "(O)", key);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004449 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004450 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004451 "(OO)", key, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004452 if (res == NULL)
4453 return -1;
4454 Py_DECREF(res);
4455 return 0;
4456}
4457
Guido van Rossumdc91b992001-08-08 22:26:22 +00004458SLOT1BIN(slot_nb_add, nb_add, "__add__", "__radd__")
4459SLOT1BIN(slot_nb_subtract, nb_subtract, "__sub__", "__rsub__")
4460SLOT1BIN(slot_nb_multiply, nb_multiply, "__mul__", "__rmul__")
Guido van Rossumdc91b992001-08-08 22:26:22 +00004461SLOT1BIN(slot_nb_remainder, nb_remainder, "__mod__", "__rmod__")
4462SLOT1BIN(slot_nb_divmod, nb_divmod, "__divmod__", "__rdivmod__")
4463
Jeremy Hylton938ace62002-07-17 16:30:39 +00004464static PyObject *slot_nb_power(PyObject *, PyObject *, PyObject *);
Guido van Rossumdc91b992001-08-08 22:26:22 +00004465
4466SLOT1BINFULL(slot_nb_power_binary, slot_nb_power,
4467 nb_power, "__pow__", "__rpow__")
4468
4469static PyObject *
4470slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus)
4471{
Guido van Rossum2730b132001-08-28 18:22:14 +00004472 static PyObject *pow_str;
4473
Guido van Rossumdc91b992001-08-08 22:26:22 +00004474 if (modulus == Py_None)
4475 return slot_nb_power_binary(self, other);
Guido van Rossum23094982002-06-10 14:30:43 +00004476 /* Three-arg power doesn't use __rpow__. But ternary_op
4477 can call this when the second argument's type uses
4478 slot_nb_power, so check before calling self.__pow__. */
4479 if (self->ob_type->tp_as_number != NULL &&
4480 self->ob_type->tp_as_number->nb_power == slot_nb_power) {
4481 return call_method(self, "__pow__", &pow_str,
4482 "(OO)", other, modulus);
4483 }
4484 Py_INCREF(Py_NotImplemented);
4485 return Py_NotImplemented;
Guido van Rossumdc91b992001-08-08 22:26:22 +00004486}
4487
4488SLOT0(slot_nb_negative, "__neg__")
4489SLOT0(slot_nb_positive, "__pos__")
4490SLOT0(slot_nb_absolute, "__abs__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004491
4492static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00004493slot_nb_bool(PyObject *self)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004494{
Tim Petersea7f75d2002-12-07 21:39:16 +00004495 PyObject *func, *args;
Jack Diederich4dafcc42006-11-28 19:15:13 +00004496 static PyObject *bool_str, *len_str;
Tim Petersea7f75d2002-12-07 21:39:16 +00004497 int result = -1;
Jack Diederich4dafcc42006-11-28 19:15:13 +00004498 int from_len = 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004499
Jack Diederich4dafcc42006-11-28 19:15:13 +00004500 func = lookup_maybe(self, "__bool__", &bool_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004501 if (func == NULL) {
Guido van Rossum55f20992001-10-01 17:18:22 +00004502 if (PyErr_Occurred())
Guido van Rossumb8f63662001-08-15 23:57:02 +00004503 return -1;
Guido van Rossum55f20992001-10-01 17:18:22 +00004504 func = lookup_maybe(self, "__len__", &len_str);
Tim Petersea7f75d2002-12-07 21:39:16 +00004505 if (func == NULL)
4506 return PyErr_Occurred() ? -1 : 1;
Jack Diederich4dafcc42006-11-28 19:15:13 +00004507 from_len = 1;
Tim Petersea7f75d2002-12-07 21:39:16 +00004508 }
4509 args = PyTuple_New(0);
4510 if (args != NULL) {
4511 PyObject *temp = PyObject_Call(func, args, NULL);
4512 Py_DECREF(args);
4513 if (temp != NULL) {
Jack Diederich4dafcc42006-11-28 19:15:13 +00004514 if (from_len) {
4515 /* enforced by slot_nb_len */
Jeremy Hylton090a3492003-06-27 16:46:45 +00004516 result = PyObject_IsTrue(temp);
Jack Diederich4dafcc42006-11-28 19:15:13 +00004517 }
4518 else if (PyBool_Check(temp)) {
4519 result = PyObject_IsTrue(temp);
4520 }
Jeremy Hylton090a3492003-06-27 16:46:45 +00004521 else {
4522 PyErr_Format(PyExc_TypeError,
Jack Diederich4dafcc42006-11-28 19:15:13 +00004523 "__bool__ should return "
4524 "bool, returned %s",
4525 temp->ob_type->tp_name);
Jeremy Hylton3e3159c2003-06-27 17:38:27 +00004526 result = -1;
Jeremy Hylton090a3492003-06-27 16:46:45 +00004527 }
Tim Petersea7f75d2002-12-07 21:39:16 +00004528 Py_DECREF(temp);
Guido van Rossum55f20992001-10-01 17:18:22 +00004529 }
Guido van Rossumb8f63662001-08-15 23:57:02 +00004530 }
Guido van Rossum55f20992001-10-01 17:18:22 +00004531 Py_DECREF(func);
Tim Petersea7f75d2002-12-07 21:39:16 +00004532 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004533}
4534
Guido van Rossum38fff8c2006-03-07 18:50:55 +00004535
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00004536static PyObject *
Guido van Rossum38fff8c2006-03-07 18:50:55 +00004537slot_nb_index(PyObject *self)
4538{
Guido van Rossum38fff8c2006-03-07 18:50:55 +00004539 static PyObject *index_str;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00004540 return call_method(self, "__index__", &index_str, "()");
Guido van Rossum38fff8c2006-03-07 18:50:55 +00004541}
4542
4543
Guido van Rossumdc91b992001-08-08 22:26:22 +00004544SLOT0(slot_nb_invert, "__invert__")
4545SLOT1BIN(slot_nb_lshift, nb_lshift, "__lshift__", "__rlshift__")
4546SLOT1BIN(slot_nb_rshift, nb_rshift, "__rshift__", "__rrshift__")
4547SLOT1BIN(slot_nb_and, nb_and, "__and__", "__rand__")
4548SLOT1BIN(slot_nb_xor, nb_xor, "__xor__", "__rxor__")
4549SLOT1BIN(slot_nb_or, nb_or, "__or__", "__ror__")
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004550
Guido van Rossumdc91b992001-08-08 22:26:22 +00004551SLOT0(slot_nb_int, "__int__")
4552SLOT0(slot_nb_long, "__long__")
4553SLOT0(slot_nb_float, "__float__")
4554SLOT0(slot_nb_oct, "__oct__")
4555SLOT0(slot_nb_hex, "__hex__")
4556SLOT1(slot_nb_inplace_add, "__iadd__", PyObject *, "O")
4557SLOT1(slot_nb_inplace_subtract, "__isub__", PyObject *, "O")
4558SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *, "O")
Guido van Rossumdc91b992001-08-08 22:26:22 +00004559SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *, "O")
Thomas Wouterscf297e42007-02-23 15:07:44 +00004560/* Can't use SLOT1 here, because nb_inplace_power is ternary */
4561static PyObject *
4562slot_nb_inplace_power(PyObject *self, PyObject * arg1, PyObject *arg2)
4563{
4564 static PyObject *cache_str;
4565 return call_method(self, "__ipow__", &cache_str, "(" "O" ")", arg1);
4566}
Guido van Rossumdc91b992001-08-08 22:26:22 +00004567SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *, "O")
4568SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *, "O")
4569SLOT1(slot_nb_inplace_and, "__iand__", PyObject *, "O")
4570SLOT1(slot_nb_inplace_xor, "__ixor__", PyObject *, "O")
4571SLOT1(slot_nb_inplace_or, "__ior__", PyObject *, "O")
4572SLOT1BIN(slot_nb_floor_divide, nb_floor_divide,
4573 "__floordiv__", "__rfloordiv__")
4574SLOT1BIN(slot_nb_true_divide, nb_true_divide, "__truediv__", "__rtruediv__")
4575SLOT1(slot_nb_inplace_floor_divide, "__ifloordiv__", PyObject *, "O")
4576SLOT1(slot_nb_inplace_true_divide, "__itruediv__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004577
4578static int
Guido van Rossumb8f63662001-08-15 23:57:02 +00004579half_compare(PyObject *self, PyObject *other)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004580{
Guido van Rossumb8f63662001-08-15 23:57:02 +00004581 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004582 static PyObject *cmp_str;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004583 Py_ssize_t c;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004584
Guido van Rossum60718732001-08-28 17:47:51 +00004585 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004586 if (func == NULL) {
4587 PyErr_Clear();
4588 }
4589 else {
Raymond Hettinger8ae46892003-10-12 19:09:37 +00004590 args = PyTuple_Pack(1, other);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004591 if (args == NULL)
4592 res = NULL;
4593 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00004594 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004595 Py_DECREF(args);
4596 }
Raymond Hettingerab5dae32002-06-24 13:08:16 +00004597 Py_DECREF(func);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004598 if (res != Py_NotImplemented) {
4599 if (res == NULL)
4600 return -2;
4601 c = PyInt_AsLong(res);
4602 Py_DECREF(res);
4603 if (c == -1 && PyErr_Occurred())
4604 return -2;
4605 return (c < 0) ? -1 : (c > 0) ? 1 : 0;
4606 }
4607 Py_DECREF(res);
4608 }
4609 return 2;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004610}
4611
Guido van Rossumab3b0342001-09-18 20:38:53 +00004612/* This slot is published for the benefit of try_3way_compare in object.c */
4613int
4614_PyObject_SlotCompare(PyObject *self, PyObject *other)
Guido van Rossumb8f63662001-08-15 23:57:02 +00004615{
4616 int c;
4617
Guido van Rossumab3b0342001-09-18 20:38:53 +00004618 if (self->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00004619 c = half_compare(self, other);
4620 if (c <= 1)
4621 return c;
4622 }
Guido van Rossumab3b0342001-09-18 20:38:53 +00004623 if (other->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00004624 c = half_compare(other, self);
4625 if (c < -1)
4626 return -2;
4627 if (c <= 1)
4628 return -c;
4629 }
4630 return (void *)self < (void *)other ? -1 :
4631 (void *)self > (void *)other ? 1 : 0;
4632}
4633
4634static PyObject *
4635slot_tp_repr(PyObject *self)
4636{
4637 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004638 static PyObject *repr_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004639
Guido van Rossum60718732001-08-28 17:47:51 +00004640 func = lookup_method(self, "__repr__", &repr_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004641 if (func != NULL) {
4642 res = PyEval_CallObject(func, NULL);
4643 Py_DECREF(func);
4644 return res;
4645 }
Barry Warsaw7ce36942001-08-24 18:34:26 +00004646 PyErr_Clear();
Walter Dörwald1ab83302007-05-18 17:15:44 +00004647 return PyUnicode_FromFormat("<%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00004648 self->ob_type->tp_name, self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004649}
4650
4651static PyObject *
4652slot_tp_str(PyObject *self)
4653{
4654 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004655 static PyObject *str_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004656
Guido van Rossum60718732001-08-28 17:47:51 +00004657 func = lookup_method(self, "__str__", &str_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004658 if (func != NULL) {
4659 res = PyEval_CallObject(func, NULL);
4660 Py_DECREF(func);
4661 return res;
4662 }
4663 else {
Walter Dörwald1ab83302007-05-18 17:15:44 +00004664 PyObject *ress;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004665 PyErr_Clear();
Walter Dörwald1ab83302007-05-18 17:15:44 +00004666 res = slot_tp_repr(self);
4667 if (!res)
4668 return NULL;
4669 ress = _PyUnicode_AsDefaultEncodedString(res, NULL);
4670 Py_DECREF(res);
4671 return ress;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004672 }
4673}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004674
4675static long
4676slot_tp_hash(PyObject *self)
4677{
Guido van Rossum4011a242006-08-17 23:09:57 +00004678 PyObject *func, *res;
Guido van Rossum50e9fb92006-08-17 05:42:55 +00004679 static PyObject *hash_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004680 long h;
4681
Guido van Rossum60718732001-08-28 17:47:51 +00004682 func = lookup_method(self, "__hash__", &hash_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004683
Guido van Rossum50e9fb92006-08-17 05:42:55 +00004684 if (func == Py_None) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00004685 Py_DECREF(func);
Guido van Rossum50e9fb92006-08-17 05:42:55 +00004686 func = NULL;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004687 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +00004688
4689 if (func == NULL) {
Guido van Rossum50e9fb92006-08-17 05:42:55 +00004690 PyErr_Format(PyExc_TypeError, "unhashable type: '%.200s'",
4691 self->ob_type->tp_name);
4692 return -1;
4693 }
4694
Guido van Rossum4011a242006-08-17 23:09:57 +00004695 res = PyEval_CallObject(func, NULL);
Guido van Rossum50e9fb92006-08-17 05:42:55 +00004696 Py_DECREF(func);
4697 if (res == NULL)
4698 return -1;
4699 if (PyLong_Check(res))
4700 h = PyLong_Type.tp_hash(res);
4701 else
4702 h = PyInt_AsLong(res);
4703 Py_DECREF(res);
4704 if (h == -1 && !PyErr_Occurred())
4705 h = -2;
4706 return h;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004707}
4708
4709static PyObject *
4710slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds)
4711{
Guido van Rossum60718732001-08-28 17:47:51 +00004712 static PyObject *call_str;
4713 PyObject *meth = lookup_method(self, "__call__", &call_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004714 PyObject *res;
4715
4716 if (meth == NULL)
4717 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004718
4719 /* PyObject_Call() will end up calling slot_tp_call() again if
4720 the object returned for __call__ has __call__ itself defined
4721 upon it. This can be an infinite recursion if you set
4722 __call__ in a class to an instance of it. */
4723 if (Py_EnterRecursiveCall(" in __call__")) {
4724 Py_DECREF(meth);
4725 return NULL;
4726 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004727 res = PyObject_Call(meth, args, kwds);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004728 Py_LeaveRecursiveCall();
4729
Tim Peters6d6c1a32001-08-02 04:15:00 +00004730 Py_DECREF(meth);
4731 return res;
4732}
4733
Guido van Rossum14a6f832001-10-17 13:59:09 +00004734/* There are two slot dispatch functions for tp_getattro.
4735
4736 - slot_tp_getattro() is used when __getattribute__ is overridden
4737 but no __getattr__ hook is present;
4738
4739 - slot_tp_getattr_hook() is used when a __getattr__ hook is present.
4740
Guido van Rossumc334df52002-04-04 23:44:47 +00004741 The code in update_one_slot() always installs slot_tp_getattr_hook(); this
4742 detects the absence of __getattr__ and then installs the simpler slot if
4743 necessary. */
Guido van Rossum14a6f832001-10-17 13:59:09 +00004744
Tim Peters6d6c1a32001-08-02 04:15:00 +00004745static PyObject *
4746slot_tp_getattro(PyObject *self, PyObject *name)
4747{
Guido van Rossum14a6f832001-10-17 13:59:09 +00004748 static PyObject *getattribute_str = NULL;
4749 return call_method(self, "__getattribute__", &getattribute_str,
4750 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004751}
4752
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004753static PyObject *
4754slot_tp_getattr_hook(PyObject *self, PyObject *name)
4755{
4756 PyTypeObject *tp = self->ob_type;
4757 PyObject *getattr, *getattribute, *res;
4758 static PyObject *getattribute_str = NULL;
4759 static PyObject *getattr_str = NULL;
4760
4761 if (getattr_str == NULL) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00004762 getattr_str = PyUnicode_InternFromString("__getattr__");
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004763 if (getattr_str == NULL)
4764 return NULL;
4765 }
4766 if (getattribute_str == NULL) {
4767 getattribute_str =
Martin v. Löwis5b222132007-06-10 09:51:05 +00004768 PyUnicode_InternFromString("__getattribute__");
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004769 if (getattribute_str == NULL)
4770 return NULL;
4771 }
4772 getattr = _PyType_Lookup(tp, getattr_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00004773 if (getattr == NULL) {
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004774 /* No __getattr__ hook: use a simpler dispatcher */
4775 tp->tp_getattro = slot_tp_getattro;
4776 return slot_tp_getattro(self, name);
4777 }
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004778 getattribute = _PyType_Lookup(tp, getattribute_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00004779 if (getattribute == NULL ||
4780 (getattribute->ob_type == &PyWrapperDescr_Type &&
4781 ((PyWrapperDescrObject *)getattribute)->d_wrapped ==
4782 (void *)PyObject_GenericGetAttr))
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004783 res = PyObject_GenericGetAttr(self, name);
4784 else
Thomas Wouters477c8d52006-05-27 19:21:47 +00004785 res = PyObject_CallFunctionObjArgs(getattribute, self, name, NULL);
Guido van Rossum14a6f832001-10-17 13:59:09 +00004786 if (res == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) {
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004787 PyErr_Clear();
Thomas Wouters477c8d52006-05-27 19:21:47 +00004788 res = PyObject_CallFunctionObjArgs(getattr, self, name, NULL);
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004789 }
4790 return res;
4791}
4792
Tim Peters6d6c1a32001-08-02 04:15:00 +00004793static int
4794slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value)
4795{
4796 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004797 static PyObject *delattr_str, *setattr_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004798
4799 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004800 res = call_method(self, "__delattr__", &delattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004801 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004802 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004803 res = call_method(self, "__setattr__", &setattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004804 "(OO)", name, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004805 if (res == NULL)
4806 return -1;
4807 Py_DECREF(res);
4808 return 0;
4809}
4810
Tim Peters6d6c1a32001-08-02 04:15:00 +00004811static PyObject *
Guido van Rossumb8f63662001-08-15 23:57:02 +00004812half_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004813{
Guido van Rossumb8f63662001-08-15 23:57:02 +00004814 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004815 static PyObject *op_str[6];
Tim Peters6d6c1a32001-08-02 04:15:00 +00004816
Guido van Rossum60718732001-08-28 17:47:51 +00004817 func = lookup_method(self, name_op[op], &op_str[op]);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004818 if (func == NULL) {
4819 PyErr_Clear();
4820 Py_INCREF(Py_NotImplemented);
4821 return Py_NotImplemented;
4822 }
Raymond Hettinger8ae46892003-10-12 19:09:37 +00004823 args = PyTuple_Pack(1, other);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004824 if (args == NULL)
4825 res = NULL;
4826 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00004827 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004828 Py_DECREF(args);
4829 }
4830 Py_DECREF(func);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004831 return res;
4832}
4833
Guido van Rossumb8f63662001-08-15 23:57:02 +00004834static PyObject *
4835slot_tp_richcompare(PyObject *self, PyObject *other, int op)
4836{
4837 PyObject *res;
4838
4839 if (self->ob_type->tp_richcompare == slot_tp_richcompare) {
4840 res = half_richcompare(self, other, op);
4841 if (res != Py_NotImplemented)
4842 return res;
4843 Py_DECREF(res);
4844 }
4845 if (other->ob_type->tp_richcompare == slot_tp_richcompare) {
Tim Petersf4aca752004-09-23 02:39:37 +00004846 res = half_richcompare(other, self, _Py_SwappedOp[op]);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004847 if (res != Py_NotImplemented) {
4848 return res;
4849 }
4850 Py_DECREF(res);
4851 }
4852 Py_INCREF(Py_NotImplemented);
4853 return Py_NotImplemented;
4854}
4855
4856static PyObject *
4857slot_tp_iter(PyObject *self)
4858{
4859 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004860 static PyObject *iter_str, *getitem_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004861
Guido van Rossum60718732001-08-28 17:47:51 +00004862 func = lookup_method(self, "__iter__", &iter_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004863 if (func != NULL) {
Guido van Rossum84b2bed2002-08-16 17:01:09 +00004864 PyObject *args;
4865 args = res = PyTuple_New(0);
4866 if (args != NULL) {
4867 res = PyObject_Call(func, args, NULL);
4868 Py_DECREF(args);
4869 }
4870 Py_DECREF(func);
4871 return res;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004872 }
4873 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00004874 func = lookup_method(self, "__getitem__", &getitem_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004875 if (func == NULL) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004876 PyErr_Format(PyExc_TypeError,
4877 "'%.200s' object is not iterable",
4878 self->ob_type->tp_name);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004879 return NULL;
4880 }
4881 Py_DECREF(func);
4882 return PySeqIter_New(self);
4883}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004884
4885static PyObject *
4886slot_tp_iternext(PyObject *self)
4887{
Guido van Rossum2730b132001-08-28 18:22:14 +00004888 static PyObject *next_str;
Georg Brandla18af4e2007-04-21 15:47:16 +00004889 return call_method(self, "__next__", &next_str, "()");
Tim Peters6d6c1a32001-08-02 04:15:00 +00004890}
4891
Guido van Rossum1a493502001-08-17 16:47:50 +00004892static PyObject *
4893slot_tp_descr_get(PyObject *self, PyObject *obj, PyObject *type)
4894{
4895 PyTypeObject *tp = self->ob_type;
4896 PyObject *get;
4897 static PyObject *get_str = NULL;
4898
4899 if (get_str == NULL) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00004900 get_str = PyUnicode_InternFromString("__get__");
Guido van Rossum1a493502001-08-17 16:47:50 +00004901 if (get_str == NULL)
4902 return NULL;
4903 }
4904 get = _PyType_Lookup(tp, get_str);
4905 if (get == NULL) {
4906 /* Avoid further slowdowns */
4907 if (tp->tp_descr_get == slot_tp_descr_get)
4908 tp->tp_descr_get = NULL;
4909 Py_INCREF(self);
4910 return self;
4911 }
Guido van Rossum2c252392001-08-24 10:13:31 +00004912 if (obj == NULL)
4913 obj = Py_None;
4914 if (type == NULL)
4915 type = Py_None;
Thomas Wouters477c8d52006-05-27 19:21:47 +00004916 return PyObject_CallFunctionObjArgs(get, self, obj, type, NULL);
Guido van Rossum1a493502001-08-17 16:47:50 +00004917}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004918
4919static int
4920slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value)
4921{
Guido van Rossum2c252392001-08-24 10:13:31 +00004922 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004923 static PyObject *del_str, *set_str;
Guido van Rossum2c252392001-08-24 10:13:31 +00004924
4925 if (value == NULL)
Guido van Rossum1d5b3f22001-12-03 00:08:33 +00004926 res = call_method(self, "__delete__", &del_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004927 "(O)", target);
Guido van Rossum2c252392001-08-24 10:13:31 +00004928 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004929 res = call_method(self, "__set__", &set_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004930 "(OO)", target, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004931 if (res == NULL)
4932 return -1;
4933 Py_DECREF(res);
4934 return 0;
4935}
4936
4937static int
4938slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds)
4939{
Guido van Rossum60718732001-08-28 17:47:51 +00004940 static PyObject *init_str;
4941 PyObject *meth = lookup_method(self, "__init__", &init_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004942 PyObject *res;
4943
4944 if (meth == NULL)
4945 return -1;
4946 res = PyObject_Call(meth, args, kwds);
4947 Py_DECREF(meth);
4948 if (res == NULL)
4949 return -1;
Raymond Hettingerb67cc802005-03-03 16:45:19 +00004950 if (res != Py_None) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004951 PyErr_Format(PyExc_TypeError,
4952 "__init__() should return None, not '%.200s'",
4953 res->ob_type->tp_name);
Raymond Hettingerb67cc802005-03-03 16:45:19 +00004954 Py_DECREF(res);
4955 return -1;
4956 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004957 Py_DECREF(res);
4958 return 0;
4959}
4960
4961static PyObject *
4962slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
4963{
Guido van Rossum7bed2132002-08-08 21:57:53 +00004964 static PyObject *new_str;
4965 PyObject *func;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004966 PyObject *newargs, *x;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004967 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004968
Guido van Rossum7bed2132002-08-08 21:57:53 +00004969 if (new_str == NULL) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00004970 new_str = PyUnicode_InternFromString("__new__");
Guido van Rossum7bed2132002-08-08 21:57:53 +00004971 if (new_str == NULL)
4972 return NULL;
4973 }
4974 func = PyObject_GetAttr((PyObject *)type, new_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004975 if (func == NULL)
4976 return NULL;
4977 assert(PyTuple_Check(args));
4978 n = PyTuple_GET_SIZE(args);
4979 newargs = PyTuple_New(n+1);
4980 if (newargs == NULL)
4981 return NULL;
4982 Py_INCREF(type);
4983 PyTuple_SET_ITEM(newargs, 0, (PyObject *)type);
4984 for (i = 0; i < n; i++) {
4985 x = PyTuple_GET_ITEM(args, i);
4986 Py_INCREF(x);
4987 PyTuple_SET_ITEM(newargs, i+1, x);
4988 }
4989 x = PyObject_Call(func, newargs, kwds);
Guido van Rossum25d18072001-10-01 15:55:28 +00004990 Py_DECREF(newargs);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004991 Py_DECREF(func);
4992 return x;
4993}
4994
Guido van Rossumfebd61d2002-08-08 20:55:20 +00004995static void
4996slot_tp_del(PyObject *self)
4997{
4998 static PyObject *del_str = NULL;
4999 PyObject *del, *res;
5000 PyObject *error_type, *error_value, *error_traceback;
5001
5002 /* Temporarily resurrect the object. */
5003 assert(self->ob_refcnt == 0);
5004 self->ob_refcnt = 1;
5005
5006 /* Save the current exception, if any. */
5007 PyErr_Fetch(&error_type, &error_value, &error_traceback);
5008
5009 /* Execute __del__ method, if any. */
5010 del = lookup_maybe(self, "__del__", &del_str);
5011 if (del != NULL) {
5012 res = PyEval_CallObject(del, NULL);
5013 if (res == NULL)
5014 PyErr_WriteUnraisable(del);
5015 else
5016 Py_DECREF(res);
5017 Py_DECREF(del);
5018 }
5019
5020 /* Restore the saved exception. */
5021 PyErr_Restore(error_type, error_value, error_traceback);
5022
5023 /* Undo the temporary resurrection; can't use DECREF here, it would
5024 * cause a recursive call.
5025 */
5026 assert(self->ob_refcnt > 0);
5027 if (--self->ob_refcnt == 0)
5028 return; /* this is the normal path out */
5029
5030 /* __del__ resurrected it! Make it look like the original Py_DECREF
5031 * never happened.
5032 */
5033 {
Martin v. Löwis725507b2006-03-07 12:08:51 +00005034 Py_ssize_t refcnt = self->ob_refcnt;
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005035 _Py_NewReference(self);
5036 self->ob_refcnt = refcnt;
5037 }
5038 assert(!PyType_IS_GC(self->ob_type) ||
5039 _Py_AS_GC(self)->gc.gc_refs != _PyGC_REFS_UNTRACKED);
Michael W. Hudson3f3b6682004-08-03 10:21:03 +00005040 /* If Py_REF_DEBUG, _Py_NewReference bumped _Py_RefTotal, so
5041 * we need to undo that. */
5042 _Py_DEC_REFTOTAL;
5043 /* If Py_TRACE_REFS, _Py_NewReference re-added self to the object
5044 * chain, so no more to do there.
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005045 * If COUNT_ALLOCS, the original decref bumped tp_frees, and
5046 * _Py_NewReference bumped tp_allocs: both of those need to be
5047 * undone.
5048 */
5049#ifdef COUNT_ALLOCS
5050 --self->ob_type->tp_frees;
5051 --self->ob_type->tp_allocs;
5052#endif
5053}
5054
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005055
5056/* Table mapping __foo__ names to tp_foo offsets and slot_tp_foo wrapper
Tim Petersbf9b2442003-03-23 05:35:36 +00005057 functions. The offsets here are relative to the 'PyHeapTypeObject'
Guido van Rossume5c691a2003-03-07 15:13:17 +00005058 structure, which incorporates the additional structures used for numbers,
5059 sequences and mappings.
5060 Note that multiple names may map to the same slot (e.g. __eq__,
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005061 __ne__ etc. all map to tp_richcompare) and one name may map to multiple
Guido van Rossumc334df52002-04-04 23:44:47 +00005062 slots (e.g. __str__ affects tp_str as well as tp_repr). The table is
5063 terminated with an all-zero entry. (This table is further initialized and
5064 sorted in init_slotdefs() below.) */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005065
Guido van Rossum6d204072001-10-21 00:44:31 +00005066typedef struct wrapperbase slotdef;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005067
5068#undef TPSLOT
Guido van Rossumc8e56452001-10-22 00:43:43 +00005069#undef FLSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005070#undef ETSLOT
5071#undef SQSLOT
5072#undef MPSLOT
5073#undef NBSLOT
Guido van Rossum6d204072001-10-21 00:44:31 +00005074#undef UNSLOT
5075#undef IBSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005076#undef BINSLOT
5077#undef RBINSLOT
5078
Guido van Rossum6d204072001-10-21 00:44:31 +00005079#define TPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Neal Norwitzd47714a2002-08-13 19:01:38 +00005080 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
5081 PyDoc_STR(DOC)}
Guido van Rossumc8e56452001-10-22 00:43:43 +00005082#define FLSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC, FLAGS) \
5083 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
Neal Norwitzd47714a2002-08-13 19:01:38 +00005084 PyDoc_STR(DOC), FLAGS}
Guido van Rossum6d204072001-10-21 00:44:31 +00005085#define ETSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Guido van Rossume5c691a2003-03-07 15:13:17 +00005086 {NAME, offsetof(PyHeapTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
Neal Norwitzd47714a2002-08-13 19:01:38 +00005087 PyDoc_STR(DOC)}
Guido van Rossum6d204072001-10-21 00:44:31 +00005088#define SQSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
5089 ETSLOT(NAME, as_sequence.SLOT, FUNCTION, WRAPPER, DOC)
5090#define MPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
5091 ETSLOT(NAME, as_mapping.SLOT, FUNCTION, WRAPPER, DOC)
5092#define NBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
5093 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, DOC)
5094#define UNSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
5095 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
5096 "x." NAME "() <==> " DOC)
5097#define IBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
5098 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
5099 "x." NAME "(y) <==> x" DOC "y")
5100#define BINSLOT(NAME, SLOT, FUNCTION, DOC) \
5101 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
5102 "x." NAME "(y) <==> x" DOC "y")
5103#define RBINSLOT(NAME, SLOT, FUNCTION, DOC) \
5104 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
5105 "x." NAME "(y) <==> y" DOC "x")
Anthony Baxter56616992005-06-03 14:12:21 +00005106#define BINSLOTNOTINFIX(NAME, SLOT, FUNCTION, DOC) \
5107 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
5108 "x." NAME "(y) <==> " DOC)
5109#define RBINSLOTNOTINFIX(NAME, SLOT, FUNCTION, DOC) \
5110 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
5111 "x." NAME "(y) <==> " DOC)
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005112
5113static slotdef slotdefs[] = {
Martin v. Löwis18e16552006-02-15 17:27:45 +00005114 SQSLOT("__len__", sq_length, slot_sq_length, wrap_lenfunc,
Guido van Rossum6d204072001-10-21 00:44:31 +00005115 "x.__len__() <==> len(x)"),
Armin Rigofd163f92005-12-29 15:59:19 +00005116 /* Heap types defining __add__/__mul__ have sq_concat/sq_repeat == NULL.
5117 The logic in abstract.c always falls back to nb_add/nb_multiply in
5118 this case. Defining both the nb_* and the sq_* slots to call the
5119 user-defined methods has unexpected side-effects, as shown by
5120 test_descr.notimplemented() */
5121 SQSLOT("__add__", sq_concat, NULL, wrap_binaryfunc,
Guido van Rossumd8faa362007-04-27 19:54:29 +00005122 "x.__add__(y) <==> x+y"),
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00005123 SQSLOT("__mul__", sq_repeat, NULL, wrap_indexargfunc,
Guido van Rossumd8faa362007-04-27 19:54:29 +00005124 "x.__mul__(n) <==> x*n"),
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00005125 SQSLOT("__rmul__", sq_repeat, NULL, wrap_indexargfunc,
Guido van Rossumd8faa362007-04-27 19:54:29 +00005126 "x.__rmul__(n) <==> n*x"),
Guido van Rossum6d204072001-10-21 00:44:31 +00005127 SQSLOT("__getitem__", sq_item, slot_sq_item, wrap_sq_item,
5128 "x.__getitem__(y) <==> x[y]"),
Martin v. Löwis18e16552006-02-15 17:27:45 +00005129 SQSLOT("__getslice__", sq_slice, slot_sq_slice, wrap_ssizessizeargfunc,
Brett Cannon154da9b2003-05-20 02:30:04 +00005130 "x.__getslice__(i, j) <==> x[i:j]\n\
Guido van Rossumd8faa362007-04-27 19:54:29 +00005131 \n\
5132 Use of negative indices is not supported."),
Guido van Rossum6d204072001-10-21 00:44:31 +00005133 SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_setitem,
Brett Cannonbe67d872003-05-20 02:40:12 +00005134 "x.__setitem__(i, y) <==> x[i]=y"),
Guido van Rossum6d204072001-10-21 00:44:31 +00005135 SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_delitem,
Brett Cannonbe67d872003-05-20 02:40:12 +00005136 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005137 SQSLOT("__setslice__", sq_ass_slice, slot_sq_ass_slice,
Martin v. Löwis18e16552006-02-15 17:27:45 +00005138 wrap_ssizessizeobjargproc,
Brett Cannonbe67d872003-05-20 02:40:12 +00005139 "x.__setslice__(i, j, y) <==> x[i:j]=y\n\
Guido van Rossumd8faa362007-04-27 19:54:29 +00005140 \n\
5141 Use of negative indices is not supported."),
Guido van Rossum6d204072001-10-21 00:44:31 +00005142 SQSLOT("__delslice__", sq_ass_slice, slot_sq_ass_slice, wrap_delslice,
Brett Cannonbe67d872003-05-20 02:40:12 +00005143 "x.__delslice__(i, j) <==> del x[i:j]\n\
Guido van Rossumd8faa362007-04-27 19:54:29 +00005144 \n\
5145 Use of negative indices is not supported."),
Guido van Rossum6d204072001-10-21 00:44:31 +00005146 SQSLOT("__contains__", sq_contains, slot_sq_contains, wrap_objobjproc,
5147 "x.__contains__(y) <==> y in x"),
Armin Rigofd163f92005-12-29 15:59:19 +00005148 SQSLOT("__iadd__", sq_inplace_concat, NULL,
Guido van Rossumd8faa362007-04-27 19:54:29 +00005149 wrap_binaryfunc, "x.__iadd__(y) <==> x+=y"),
Armin Rigofd163f92005-12-29 15:59:19 +00005150 SQSLOT("__imul__", sq_inplace_repeat, NULL,
Guido van Rossumd8faa362007-04-27 19:54:29 +00005151 wrap_indexargfunc, "x.__imul__(y) <==> x*=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005152
Martin v. Löwis18e16552006-02-15 17:27:45 +00005153 MPSLOT("__len__", mp_length, slot_mp_length, wrap_lenfunc,
Guido van Rossum6d204072001-10-21 00:44:31 +00005154 "x.__len__() <==> len(x)"),
Guido van Rossumfd38f8e2001-10-09 20:17:57 +00005155 MPSLOT("__getitem__", mp_subscript, slot_mp_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00005156 wrap_binaryfunc,
5157 "x.__getitem__(y) <==> x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005158 MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00005159 wrap_objobjargproc,
5160 "x.__setitem__(i, y) <==> x[i]=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005161 MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00005162 wrap_delitem,
5163 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005164
Guido van Rossum6d204072001-10-21 00:44:31 +00005165 BINSLOT("__add__", nb_add, slot_nb_add,
5166 "+"),
5167 RBINSLOT("__radd__", nb_add, slot_nb_add,
5168 "+"),
5169 BINSLOT("__sub__", nb_subtract, slot_nb_subtract,
5170 "-"),
5171 RBINSLOT("__rsub__", nb_subtract, slot_nb_subtract,
5172 "-"),
5173 BINSLOT("__mul__", nb_multiply, slot_nb_multiply,
5174 "*"),
5175 RBINSLOT("__rmul__", nb_multiply, slot_nb_multiply,
5176 "*"),
Guido van Rossum6d204072001-10-21 00:44:31 +00005177 BINSLOT("__mod__", nb_remainder, slot_nb_remainder,
5178 "%"),
5179 RBINSLOT("__rmod__", nb_remainder, slot_nb_remainder,
5180 "%"),
Anthony Baxter56616992005-06-03 14:12:21 +00005181 BINSLOTNOTINFIX("__divmod__", nb_divmod, slot_nb_divmod,
Guido van Rossum6d204072001-10-21 00:44:31 +00005182 "divmod(x, y)"),
Anthony Baxter56616992005-06-03 14:12:21 +00005183 RBINSLOTNOTINFIX("__rdivmod__", nb_divmod, slot_nb_divmod,
Guido van Rossum6d204072001-10-21 00:44:31 +00005184 "divmod(y, x)"),
5185 NBSLOT("__pow__", nb_power, slot_nb_power, wrap_ternaryfunc,
5186 "x.__pow__(y[, z]) <==> pow(x, y[, z])"),
5187 NBSLOT("__rpow__", nb_power, slot_nb_power, wrap_ternaryfunc_r,
5188 "y.__rpow__(x[, z]) <==> pow(x, y[, z])"),
5189 UNSLOT("__neg__", nb_negative, slot_nb_negative, wrap_unaryfunc, "-x"),
5190 UNSLOT("__pos__", nb_positive, slot_nb_positive, wrap_unaryfunc, "+x"),
5191 UNSLOT("__abs__", nb_absolute, slot_nb_absolute, wrap_unaryfunc,
5192 "abs(x)"),
Jack Diederich4dafcc42006-11-28 19:15:13 +00005193 UNSLOT("__bool__", nb_bool, slot_nb_bool, wrap_inquirypred,
Guido van Rossum6d204072001-10-21 00:44:31 +00005194 "x != 0"),
5195 UNSLOT("__invert__", nb_invert, slot_nb_invert, wrap_unaryfunc, "~x"),
5196 BINSLOT("__lshift__", nb_lshift, slot_nb_lshift, "<<"),
5197 RBINSLOT("__rlshift__", nb_lshift, slot_nb_lshift, "<<"),
5198 BINSLOT("__rshift__", nb_rshift, slot_nb_rshift, ">>"),
5199 RBINSLOT("__rrshift__", nb_rshift, slot_nb_rshift, ">>"),
5200 BINSLOT("__and__", nb_and, slot_nb_and, "&"),
5201 RBINSLOT("__rand__", nb_and, slot_nb_and, "&"),
5202 BINSLOT("__xor__", nb_xor, slot_nb_xor, "^"),
5203 RBINSLOT("__rxor__", nb_xor, slot_nb_xor, "^"),
5204 BINSLOT("__or__", nb_or, slot_nb_or, "|"),
5205 RBINSLOT("__ror__", nb_or, slot_nb_or, "|"),
Guido van Rossum6d204072001-10-21 00:44:31 +00005206 UNSLOT("__int__", nb_int, slot_nb_int, wrap_unaryfunc,
5207 "int(x)"),
5208 UNSLOT("__long__", nb_long, slot_nb_long, wrap_unaryfunc,
5209 "long(x)"),
5210 UNSLOT("__float__", nb_float, slot_nb_float, wrap_unaryfunc,
5211 "float(x)"),
5212 UNSLOT("__oct__", nb_oct, slot_nb_oct, wrap_unaryfunc,
5213 "oct(x)"),
5214 UNSLOT("__hex__", nb_hex, slot_nb_hex, wrap_unaryfunc,
5215 "hex(x)"),
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00005216 NBSLOT("__index__", nb_index, slot_nb_index, wrap_unaryfunc,
Guido van Rossum38fff8c2006-03-07 18:50:55 +00005217 "x[y:z] <==> x[y.__index__():z.__index__()]"),
Guido van Rossum6d204072001-10-21 00:44:31 +00005218 IBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add,
5219 wrap_binaryfunc, "+"),
5220 IBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract,
5221 wrap_binaryfunc, "-"),
5222 IBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply,
5223 wrap_binaryfunc, "*"),
Guido van Rossum6d204072001-10-21 00:44:31 +00005224 IBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder,
5225 wrap_binaryfunc, "%"),
5226 IBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power,
Guido van Rossum6e5680f2002-10-15 01:01:53 +00005227 wrap_binaryfunc, "**"),
Guido van Rossum6d204072001-10-21 00:44:31 +00005228 IBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift,
5229 wrap_binaryfunc, "<<"),
5230 IBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift,
5231 wrap_binaryfunc, ">>"),
5232 IBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and,
5233 wrap_binaryfunc, "&"),
5234 IBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor,
5235 wrap_binaryfunc, "^"),
5236 IBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or,
5237 wrap_binaryfunc, "|"),
5238 BINSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
5239 RBINSLOT("__rfloordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
5240 BINSLOT("__truediv__", nb_true_divide, slot_nb_true_divide, "/"),
5241 RBINSLOT("__rtruediv__", nb_true_divide, slot_nb_true_divide, "/"),
5242 IBSLOT("__ifloordiv__", nb_inplace_floor_divide,
5243 slot_nb_inplace_floor_divide, wrap_binaryfunc, "//"),
5244 IBSLOT("__itruediv__", nb_inplace_true_divide,
5245 slot_nb_inplace_true_divide, wrap_binaryfunc, "/"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005246
Guido van Rossum6d204072001-10-21 00:44:31 +00005247 TPSLOT("__str__", tp_str, slot_tp_str, wrap_unaryfunc,
5248 "x.__str__() <==> str(x)"),
Guido van Rossumafe7a942001-10-29 14:33:44 +00005249 TPSLOT("__str__", tp_print, NULL, NULL, ""),
Guido van Rossum6d204072001-10-21 00:44:31 +00005250 TPSLOT("__repr__", tp_repr, slot_tp_repr, wrap_unaryfunc,
5251 "x.__repr__() <==> repr(x)"),
Guido van Rossumafe7a942001-10-29 14:33:44 +00005252 TPSLOT("__repr__", tp_print, NULL, NULL, ""),
Guido van Rossum6d204072001-10-21 00:44:31 +00005253 TPSLOT("__cmp__", tp_compare, _PyObject_SlotCompare, wrap_cmpfunc,
5254 "x.__cmp__(y) <==> cmp(x,y)"),
5255 TPSLOT("__hash__", tp_hash, slot_tp_hash, wrap_hashfunc,
5256 "x.__hash__() <==> hash(x)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00005257 FLSLOT("__call__", tp_call, slot_tp_call, (wrapperfunc)wrap_call,
5258 "x.__call__(...) <==> x(...)", PyWrapperFlag_KEYWORDS),
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005259 TPSLOT("__getattribute__", tp_getattro, slot_tp_getattr_hook,
Guido van Rossum6d204072001-10-21 00:44:31 +00005260 wrap_binaryfunc, "x.__getattribute__('name') <==> x.name"),
5261 TPSLOT("__getattribute__", tp_getattr, NULL, NULL, ""),
5262 TPSLOT("__getattr__", tp_getattro, slot_tp_getattr_hook, NULL, ""),
5263 TPSLOT("__getattr__", tp_getattr, NULL, NULL, ""),
5264 TPSLOT("__setattr__", tp_setattro, slot_tp_setattro, wrap_setattr,
5265 "x.__setattr__('name', value) <==> x.name = value"),
5266 TPSLOT("__setattr__", tp_setattr, NULL, NULL, ""),
5267 TPSLOT("__delattr__", tp_setattro, slot_tp_setattro, wrap_delattr,
5268 "x.__delattr__('name') <==> del x.name"),
5269 TPSLOT("__delattr__", tp_setattr, NULL, NULL, ""),
5270 TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare, richcmp_lt,
5271 "x.__lt__(y) <==> x<y"),
5272 TPSLOT("__le__", tp_richcompare, slot_tp_richcompare, richcmp_le,
5273 "x.__le__(y) <==> x<=y"),
5274 TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare, richcmp_eq,
5275 "x.__eq__(y) <==> x==y"),
5276 TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare, richcmp_ne,
5277 "x.__ne__(y) <==> x!=y"),
5278 TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare, richcmp_gt,
5279 "x.__gt__(y) <==> x>y"),
5280 TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare, richcmp_ge,
5281 "x.__ge__(y) <==> x>=y"),
5282 TPSLOT("__iter__", tp_iter, slot_tp_iter, wrap_unaryfunc,
5283 "x.__iter__() <==> iter(x)"),
Georg Brandla18af4e2007-04-21 15:47:16 +00005284 TPSLOT("__next__", tp_iternext, slot_tp_iternext, wrap_next,
5285 "x.__next__() <==> next(x)"),
Guido van Rossum6d204072001-10-21 00:44:31 +00005286 TPSLOT("__get__", tp_descr_get, slot_tp_descr_get, wrap_descr_get,
5287 "descr.__get__(obj[, type]) -> value"),
5288 TPSLOT("__set__", tp_descr_set, slot_tp_descr_set, wrap_descr_set,
5289 "descr.__set__(obj, value)"),
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00005290 TPSLOT("__delete__", tp_descr_set, slot_tp_descr_set,
5291 wrap_descr_delete, "descr.__delete__(obj)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00005292 FLSLOT("__init__", tp_init, slot_tp_init, (wrapperfunc)wrap_init,
Guido van Rossum6d204072001-10-21 00:44:31 +00005293 "x.__init__(...) initializes x; "
Guido van Rossumc8e56452001-10-22 00:43:43 +00005294 "see x.__class__.__doc__ for signature",
5295 PyWrapperFlag_KEYWORDS),
5296 TPSLOT("__new__", tp_new, slot_tp_new, NULL, ""),
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005297 TPSLOT("__del__", tp_del, slot_tp_del, NULL, ""),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005298 {NULL}
5299};
5300
Guido van Rossumc334df52002-04-04 23:44:47 +00005301/* Given a type pointer and an offset gotten from a slotdef entry, return a
Guido van Rossumd8faa362007-04-27 19:54:29 +00005302 pointer to the actual slot. This is not quite the same as simply adding
Guido van Rossumc334df52002-04-04 23:44:47 +00005303 the offset to the type pointer, since it takes care to indirect through the
5304 proper indirection pointer (as_buffer, etc.); it returns NULL if the
5305 indirection pointer is NULL. */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005306static void **
Martin v. Löwis18e16552006-02-15 17:27:45 +00005307slotptr(PyTypeObject *type, int ioffset)
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005308{
5309 char *ptr;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005310 long offset = ioffset;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005311
Guido van Rossume5c691a2003-03-07 15:13:17 +00005312 /* Note: this depends on the order of the members of PyHeapTypeObject! */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005313 assert(offset >= 0);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00005314 assert((size_t)offset < offsetof(PyHeapTypeObject, as_buffer));
5315 if ((size_t)offset >= offsetof(PyHeapTypeObject, as_sequence)) {
5316 ptr = (char *)type->tp_as_sequence;
Guido van Rossume5c691a2003-03-07 15:13:17 +00005317 offset -= offsetof(PyHeapTypeObject, as_sequence);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005318 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00005319 else if ((size_t)offset >= offsetof(PyHeapTypeObject, as_mapping)) {
5320 ptr = (char *)type->tp_as_mapping;
Guido van Rossume5c691a2003-03-07 15:13:17 +00005321 offset -= offsetof(PyHeapTypeObject, as_mapping);
Guido van Rossum09638c12002-06-13 19:17:46 +00005322 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00005323 else if ((size_t)offset >= offsetof(PyHeapTypeObject, as_number)) {
5324 ptr = (char *)type->tp_as_number;
Guido van Rossume5c691a2003-03-07 15:13:17 +00005325 offset -= offsetof(PyHeapTypeObject, as_number);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005326 }
5327 else {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00005328 ptr = (char *)type;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005329 }
5330 if (ptr != NULL)
5331 ptr += offset;
5332 return (void **)ptr;
5333}
Guido van Rossumf040ede2001-08-07 16:40:56 +00005334
Guido van Rossumc334df52002-04-04 23:44:47 +00005335/* Length of array of slotdef pointers used to store slots with the
5336 same __name__. There should be at most MAX_EQUIV-1 slotdef entries with
5337 the same __name__, for any __name__. Since that's a static property, it is
5338 appropriate to declare fixed-size arrays for this. */
5339#define MAX_EQUIV 10
5340
5341/* Return a slot pointer for a given name, but ONLY if the attribute has
5342 exactly one slot function. The name must be an interned string. */
5343static void **
5344resolve_slotdups(PyTypeObject *type, PyObject *name)
5345{
5346 /* XXX Maybe this could be optimized more -- but is it worth it? */
5347
5348 /* pname and ptrs act as a little cache */
5349 static PyObject *pname;
5350 static slotdef *ptrs[MAX_EQUIV];
5351 slotdef *p, **pp;
5352 void **res, **ptr;
5353
5354 if (pname != name) {
5355 /* Collect all slotdefs that match name into ptrs. */
5356 pname = name;
5357 pp = ptrs;
5358 for (p = slotdefs; p->name_strobj; p++) {
5359 if (p->name_strobj == name)
5360 *pp++ = p;
5361 }
5362 *pp = NULL;
5363 }
5364
5365 /* Look in all matching slots of the type; if exactly one of these has
Guido van Rossumd8faa362007-04-27 19:54:29 +00005366 a filled-in slot, return its value. Otherwise return NULL. */
Guido van Rossumc334df52002-04-04 23:44:47 +00005367 res = NULL;
5368 for (pp = ptrs; *pp; pp++) {
5369 ptr = slotptr(type, (*pp)->offset);
5370 if (ptr == NULL || *ptr == NULL)
5371 continue;
5372 if (res != NULL)
5373 return NULL;
5374 res = ptr;
5375 }
5376 return res;
5377}
5378
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005379/* Common code for update_slots_callback() and fixup_slot_dispatchers(). This
Guido van Rossumc334df52002-04-04 23:44:47 +00005380 does some incredibly complex thinking and then sticks something into the
5381 slot. (It sees if the adjacent slotdefs for the same slot have conflicting
5382 interests, and then stores a generic wrapper or a specific function into
5383 the slot.) Return a pointer to the next slotdef with a different offset,
5384 because that's convenient for fixup_slot_dispatchers(). */
5385static slotdef *
5386update_one_slot(PyTypeObject *type, slotdef *p)
5387{
5388 PyObject *descr;
5389 PyWrapperDescrObject *d;
5390 void *generic = NULL, *specific = NULL;
5391 int use_generic = 0;
5392 int offset = p->offset;
5393 void **ptr = slotptr(type, offset);
5394
5395 if (ptr == NULL) {
5396 do {
5397 ++p;
5398 } while (p->offset == offset);
5399 return p;
5400 }
5401 do {
5402 descr = _PyType_Lookup(type, p->name_strobj);
5403 if (descr == NULL)
5404 continue;
5405 if (descr->ob_type == &PyWrapperDescr_Type) {
5406 void **tptr = resolve_slotdups(type, p->name_strobj);
5407 if (tptr == NULL || tptr == ptr)
5408 generic = p->function;
5409 d = (PyWrapperDescrObject *)descr;
5410 if (d->d_base->wrapper == p->wrapper &&
5411 PyType_IsSubtype(type, d->d_type))
5412 {
5413 if (specific == NULL ||
5414 specific == d->d_wrapped)
5415 specific = d->d_wrapped;
5416 else
5417 use_generic = 1;
5418 }
5419 }
Guido van Rossum721f62e2002-08-09 02:14:34 +00005420 else if (descr->ob_type == &PyCFunction_Type &&
5421 PyCFunction_GET_FUNCTION(descr) ==
5422 (PyCFunction)tp_new_wrapper &&
5423 strcmp(p->name, "__new__") == 0)
5424 {
5425 /* The __new__ wrapper is not a wrapper descriptor,
5426 so must be special-cased differently.
5427 If we don't do this, creating an instance will
5428 always use slot_tp_new which will look up
5429 __new__ in the MRO which will call tp_new_wrapper
5430 which will look through the base classes looking
5431 for a static base and call its tp_new (usually
5432 PyType_GenericNew), after performing various
5433 sanity checks and constructing a new argument
5434 list. Cut all that nonsense short -- this speeds
5435 up instance creation tremendously. */
Martin v. Löwisa94568a2003-05-10 07:36:56 +00005436 specific = (void *)type->tp_new;
Guido van Rossum721f62e2002-08-09 02:14:34 +00005437 /* XXX I'm not 100% sure that there isn't a hole
5438 in this reasoning that requires additional
5439 sanity checks. I'll buy the first person to
5440 point out a bug in this reasoning a beer. */
5441 }
Guido van Rossumc334df52002-04-04 23:44:47 +00005442 else {
5443 use_generic = 1;
5444 generic = p->function;
5445 }
5446 } while ((++p)->offset == offset);
5447 if (specific && !use_generic)
5448 *ptr = specific;
5449 else
5450 *ptr = generic;
5451 return p;
5452}
5453
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005454/* In the type, update the slots whose slotdefs are gathered in the pp array.
5455 This is a callback for update_subclasses(). */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005456static int
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005457update_slots_callback(PyTypeObject *type, void *data)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005458{
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005459 slotdef **pp = (slotdef **)data;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005460
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005461 for (; *pp; pp++)
Guido van Rossumc334df52002-04-04 23:44:47 +00005462 update_one_slot(type, *pp);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005463 return 0;
5464}
5465
Guido van Rossumc334df52002-04-04 23:44:47 +00005466/* Comparison function for qsort() to compare slotdefs by their offset, and
5467 for equal offset by their address (to force a stable sort). */
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005468static int
5469slotdef_cmp(const void *aa, const void *bb)
5470{
5471 const slotdef *a = (const slotdef *)aa, *b = (const slotdef *)bb;
5472 int c = a->offset - b->offset;
5473 if (c != 0)
5474 return c;
5475 else
Martin v. Löwis18e16552006-02-15 17:27:45 +00005476 /* Cannot use a-b, as this gives off_t,
5477 which may lose precision when converted to int. */
5478 return (a > b) ? 1 : (a < b) ? -1 : 0;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005479}
5480
Guido van Rossumc334df52002-04-04 23:44:47 +00005481/* Initialize the slotdefs table by adding interned string objects for the
5482 names and sorting the entries. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005483static void
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005484init_slotdefs(void)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005485{
5486 slotdef *p;
5487 static int initialized = 0;
5488
5489 if (initialized)
5490 return;
5491 for (p = slotdefs; p->name; p++) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00005492 p->name_strobj = PyUnicode_InternFromString(p->name);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005493 if (!p->name_strobj)
Guido van Rossumc334df52002-04-04 23:44:47 +00005494 Py_FatalError("Out of memory interning slotdef names");
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005495 }
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005496 qsort((void *)slotdefs, (size_t)(p-slotdefs), sizeof(slotdef),
5497 slotdef_cmp);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005498 initialized = 1;
5499}
5500
Guido van Rossumc334df52002-04-04 23:44:47 +00005501/* Update the slots after assignment to a class (type) attribute. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005502static int
5503update_slot(PyTypeObject *type, PyObject *name)
5504{
Guido van Rossumc334df52002-04-04 23:44:47 +00005505 slotdef *ptrs[MAX_EQUIV];
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005506 slotdef *p;
5507 slotdef **pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005508 int offset;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005509
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005510 init_slotdefs();
5511 pp = ptrs;
5512 for (p = slotdefs; p->name; p++) {
5513 /* XXX assume name is interned! */
5514 if (p->name_strobj == name)
5515 *pp++ = p;
5516 }
5517 *pp = NULL;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005518 for (pp = ptrs; *pp; pp++) {
5519 p = *pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005520 offset = p->offset;
5521 while (p > slotdefs && (p-1)->offset == offset)
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005522 --p;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005523 *pp = p;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005524 }
Guido van Rossumc334df52002-04-04 23:44:47 +00005525 if (ptrs[0] == NULL)
5526 return 0; /* Not an attribute that affects any slots */
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005527 return update_subclasses(type, name,
5528 update_slots_callback, (void *)ptrs);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005529}
5530
Guido van Rossumc334df52002-04-04 23:44:47 +00005531/* Store the proper functions in the slot dispatches at class (type)
5532 definition time, based upon which operations the class overrides in its
5533 dict. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00005534static void
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005535fixup_slot_dispatchers(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005536{
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005537 slotdef *p;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005538
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005539 init_slotdefs();
Guido van Rossumc334df52002-04-04 23:44:47 +00005540 for (p = slotdefs; p->name; )
5541 p = update_one_slot(type, p);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005542}
Guido van Rossum705f0f52001-08-24 16:47:00 +00005543
Michael W. Hudson98bbc492002-11-26 14:47:27 +00005544static void
5545update_all_slots(PyTypeObject* type)
5546{
5547 slotdef *p;
5548
5549 init_slotdefs();
5550 for (p = slotdefs; p->name; p++) {
5551 /* update_slot returns int but can't actually fail */
5552 update_slot(type, p->name_strobj);
5553 }
5554}
5555
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005556/* recurse_down_subclasses() and update_subclasses() are mutually
5557 recursive functions to call a callback for all subclasses,
5558 but refraining from recursing into subclasses that define 'name'. */
5559
5560static int
5561update_subclasses(PyTypeObject *type, PyObject *name,
5562 update_callback callback, void *data)
5563{
5564 if (callback(type, data) < 0)
5565 return -1;
5566 return recurse_down_subclasses(type, name, callback, data);
5567}
5568
5569static int
5570recurse_down_subclasses(PyTypeObject *type, PyObject *name,
5571 update_callback callback, void *data)
5572{
5573 PyTypeObject *subclass;
5574 PyObject *ref, *subclasses, *dict;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005575 Py_ssize_t i, n;
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005576
5577 subclasses = type->tp_subclasses;
5578 if (subclasses == NULL)
5579 return 0;
5580 assert(PyList_Check(subclasses));
5581 n = PyList_GET_SIZE(subclasses);
5582 for (i = 0; i < n; i++) {
5583 ref = PyList_GET_ITEM(subclasses, i);
5584 assert(PyWeakref_CheckRef(ref));
5585 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
5586 assert(subclass != NULL);
5587 if ((PyObject *)subclass == Py_None)
5588 continue;
5589 assert(PyType_Check(subclass));
5590 /* Avoid recursing down into unaffected classes */
5591 dict = subclass->tp_dict;
5592 if (dict != NULL && PyDict_Check(dict) &&
5593 PyDict_GetItem(dict, name) != NULL)
5594 continue;
5595 if (update_subclasses(subclass, name, callback, data) < 0)
5596 return -1;
5597 }
5598 return 0;
5599}
5600
Guido van Rossum6d204072001-10-21 00:44:31 +00005601/* This function is called by PyType_Ready() to populate the type's
5602 dictionary with method descriptors for function slots. For each
Guido van Rossum09638c12002-06-13 19:17:46 +00005603 function slot (like tp_repr) that's defined in the type, one or more
5604 corresponding descriptors are added in the type's tp_dict dictionary
Guido van Rossumd8faa362007-04-27 19:54:29 +00005605 under the appropriate name (like __repr__). Some function slots
Guido van Rossum09638c12002-06-13 19:17:46 +00005606 cause more than one descriptor to be added (for example, the nb_add
5607 slot adds both __add__ and __radd__ descriptors) and some function
5608 slots compete for the same descriptor (for example both sq_item and
5609 mp_subscript generate a __getitem__ descriptor).
5610
Guido van Rossumd8faa362007-04-27 19:54:29 +00005611 In the latter case, the first slotdef entry encoutered wins. Since
Tim Petersbf9b2442003-03-23 05:35:36 +00005612 slotdef entries are sorted by the offset of the slot in the
Guido van Rossume5c691a2003-03-07 15:13:17 +00005613 PyHeapTypeObject, this gives us some control over disambiguating
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005614 between competing slots: the members of PyHeapTypeObject are listed
5615 from most general to least general, so the most general slot is
5616 preferred. In particular, because as_mapping comes before as_sequence,
5617 for a type that defines both mp_subscript and sq_item, mp_subscript
5618 wins.
Guido van Rossum09638c12002-06-13 19:17:46 +00005619
5620 This only adds new descriptors and doesn't overwrite entries in
5621 tp_dict that were previously defined. The descriptors contain a
5622 reference to the C function they must call, so that it's safe if they
5623 are copied into a subtype's __dict__ and the subtype has a different
5624 C function in its slot -- calling the method defined by the
5625 descriptor will call the C function that was used to create it,
5626 rather than the C function present in the slot when it is called.
5627 (This is important because a subtype may have a C function in the
5628 slot that calls the method from the dictionary, and we want to avoid
5629 infinite recursion here.) */
Guido van Rossum6d204072001-10-21 00:44:31 +00005630
5631static int
5632add_operators(PyTypeObject *type)
5633{
5634 PyObject *dict = type->tp_dict;
5635 slotdef *p;
5636 PyObject *descr;
5637 void **ptr;
5638
5639 init_slotdefs();
5640 for (p = slotdefs; p->name; p++) {
5641 if (p->wrapper == NULL)
5642 continue;
5643 ptr = slotptr(type, p->offset);
5644 if (!ptr || !*ptr)
5645 continue;
5646 if (PyDict_GetItem(dict, p->name_strobj))
5647 continue;
5648 descr = PyDescr_NewWrapper(type, p, *ptr);
5649 if (descr == NULL)
5650 return -1;
5651 if (PyDict_SetItem(dict, p->name_strobj, descr) < 0)
5652 return -1;
5653 Py_DECREF(descr);
5654 }
5655 if (type->tp_new != NULL) {
5656 if (add_tp_new_wrapper(type) < 0)
5657 return -1;
5658 }
5659 return 0;
5660}
5661
Guido van Rossum705f0f52001-08-24 16:47:00 +00005662
5663/* Cooperative 'super' */
5664
5665typedef struct {
5666 PyObject_HEAD
Guido van Rossume705ef12001-08-29 15:47:06 +00005667 PyTypeObject *type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005668 PyObject *obj;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005669 PyTypeObject *obj_type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005670} superobject;
5671
Guido van Rossum6f799372001-09-20 20:46:19 +00005672static PyMemberDef super_members[] = {
5673 {"__thisclass__", T_OBJECT, offsetof(superobject, type), READONLY,
5674 "the class invoking super()"},
5675 {"__self__", T_OBJECT, offsetof(superobject, obj), READONLY,
5676 "the instance invoking super(); may be None"},
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005677 {"__self_class__", T_OBJECT, offsetof(superobject, obj_type), READONLY,
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +00005678 "the type of the instance invoking super(); may be None"},
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005679 {0}
5680};
5681
Guido van Rossum705f0f52001-08-24 16:47:00 +00005682static void
5683super_dealloc(PyObject *self)
5684{
5685 superobject *su = (superobject *)self;
5686
Guido van Rossum048eb752001-10-02 21:24:57 +00005687 _PyObject_GC_UNTRACK(self);
Guido van Rossum705f0f52001-08-24 16:47:00 +00005688 Py_XDECREF(su->obj);
5689 Py_XDECREF(su->type);
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005690 Py_XDECREF(su->obj_type);
Guido van Rossum705f0f52001-08-24 16:47:00 +00005691 self->ob_type->tp_free(self);
5692}
5693
5694static PyObject *
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005695super_repr(PyObject *self)
5696{
5697 superobject *su = (superobject *)self;
5698
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005699 if (su->obj_type)
Walter Dörwald1ab83302007-05-18 17:15:44 +00005700 return PyUnicode_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00005701 "<super: <class '%s'>, <%s object>>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005702 su->type ? su->type->tp_name : "NULL",
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005703 su->obj_type->tp_name);
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005704 else
Walter Dörwald1ab83302007-05-18 17:15:44 +00005705 return PyUnicode_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00005706 "<super: <class '%s'>, NULL>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005707 su->type ? su->type->tp_name : "NULL");
5708}
5709
5710static PyObject *
Guido van Rossum705f0f52001-08-24 16:47:00 +00005711super_getattro(PyObject *self, PyObject *name)
5712{
5713 superobject *su = (superobject *)self;
Guido van Rossum76ba09f2003-04-16 19:40:58 +00005714 int skip = su->obj_type == NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005715
Guido van Rossum76ba09f2003-04-16 19:40:58 +00005716 if (!skip) {
5717 /* We want __class__ to return the class of the super object
5718 (i.e. super, or a subclass), not the class of su->obj. */
Martin v. Löwis5b222132007-06-10 09:51:05 +00005719 skip = (PyUnicode_Check(name) &&
5720 PyUnicode_GET_SIZE(name) == 9 &&
5721 PyUnicode_CompareWithASCIIString(name, "__class__") == 0);
Guido van Rossum76ba09f2003-04-16 19:40:58 +00005722 }
5723
5724 if (!skip) {
Tim Petersa91e9642001-11-14 23:32:33 +00005725 PyObject *mro, *res, *tmp, *dict;
Guido van Rossum155db9a2002-04-02 17:53:47 +00005726 PyTypeObject *starttype;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005727 descrgetfunc f;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005728 Py_ssize_t i, n;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005729
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005730 starttype = su->obj_type;
Guido van Rossum155db9a2002-04-02 17:53:47 +00005731 mro = starttype->tp_mro;
5732
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005733 if (mro == NULL)
5734 n = 0;
5735 else {
5736 assert(PyTuple_Check(mro));
5737 n = PyTuple_GET_SIZE(mro);
5738 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00005739 for (i = 0; i < n; i++) {
Guido van Rossume705ef12001-08-29 15:47:06 +00005740 if ((PyObject *)(su->type) == PyTuple_GET_ITEM(mro, i))
Guido van Rossum705f0f52001-08-24 16:47:00 +00005741 break;
5742 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00005743 i++;
5744 res = NULL;
5745 for (; i < n; i++) {
5746 tmp = PyTuple_GET_ITEM(mro, i);
Tim Petersa91e9642001-11-14 23:32:33 +00005747 if (PyType_Check(tmp))
5748 dict = ((PyTypeObject *)tmp)->tp_dict;
Tim Petersa91e9642001-11-14 23:32:33 +00005749 else
5750 continue;
5751 res = PyDict_GetItem(dict, name);
Guido van Rossum6cc5bb62003-04-16 20:01:36 +00005752 if (res != NULL) {
Guido van Rossum705f0f52001-08-24 16:47:00 +00005753 Py_INCREF(res);
5754 f = res->ob_type->tp_descr_get;
5755 if (f != NULL) {
Phillip J. Eby91a968a2004-03-25 02:19:34 +00005756 tmp = f(res,
5757 /* Only pass 'obj' param if
5758 this is instance-mode super
5759 (See SF ID #743627)
5760 */
Hye-Shik Changff365c92004-03-25 16:37:03 +00005761 (su->obj == (PyObject *)
5762 su->obj_type
Phillip J. Eby91a968a2004-03-25 02:19:34 +00005763 ? (PyObject *)NULL
5764 : su->obj),
Guido van Rossumd4641072002-04-03 02:13:37 +00005765 (PyObject *)starttype);
Guido van Rossum705f0f52001-08-24 16:47:00 +00005766 Py_DECREF(res);
5767 res = tmp;
5768 }
5769 return res;
5770 }
5771 }
5772 }
5773 return PyObject_GenericGetAttr(self, name);
5774}
5775
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005776static PyTypeObject *
Guido van Rossum5b443c62001-12-03 15:38:28 +00005777supercheck(PyTypeObject *type, PyObject *obj)
5778{
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005779 /* Check that a super() call makes sense. Return a type object.
5780
5781 obj can be a new-style class, or an instance of one:
5782
Guido van Rossumd8faa362007-04-27 19:54:29 +00005783 - If it is a class, it must be a subclass of 'type'. This case is
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005784 used for class methods; the return value is obj.
5785
5786 - If it is an instance, it must be an instance of 'type'. This is
5787 the normal case; the return value is obj.__class__.
5788
5789 But... when obj is an instance, we want to allow for the case where
5790 obj->ob_type is not a subclass of type, but obj.__class__ is!
5791 This will allow using super() with a proxy for obj.
5792 */
5793
Guido van Rossum8e80a722003-02-18 19:22:22 +00005794 /* Check for first bullet above (special case) */
5795 if (PyType_Check(obj) && PyType_IsSubtype((PyTypeObject *)obj, type)) {
5796 Py_INCREF(obj);
5797 return (PyTypeObject *)obj;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005798 }
Guido van Rossum8e80a722003-02-18 19:22:22 +00005799
5800 /* Normal case */
5801 if (PyType_IsSubtype(obj->ob_type, type)) {
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005802 Py_INCREF(obj->ob_type);
5803 return obj->ob_type;
5804 }
5805 else {
5806 /* Try the slow way */
5807 static PyObject *class_str = NULL;
5808 PyObject *class_attr;
5809
5810 if (class_str == NULL) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00005811 class_str = PyUnicode_FromString("__class__");
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005812 if (class_str == NULL)
5813 return NULL;
5814 }
5815
5816 class_attr = PyObject_GetAttr(obj, class_str);
5817
5818 if (class_attr != NULL &&
5819 PyType_Check(class_attr) &&
5820 (PyTypeObject *)class_attr != obj->ob_type)
5821 {
5822 int ok = PyType_IsSubtype(
5823 (PyTypeObject *)class_attr, type);
5824 if (ok)
5825 return (PyTypeObject *)class_attr;
5826 }
5827
5828 if (class_attr == NULL)
5829 PyErr_Clear();
5830 else
5831 Py_DECREF(class_attr);
5832 }
5833
Guido van Rossumd8faa362007-04-27 19:54:29 +00005834 PyErr_SetString(PyExc_TypeError,
Guido van Rossum5b443c62001-12-03 15:38:28 +00005835 "super(type, obj): "
5836 "obj must be an instance or subtype of type");
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005837 return NULL;
Guido van Rossum5b443c62001-12-03 15:38:28 +00005838}
5839
Guido van Rossum705f0f52001-08-24 16:47:00 +00005840static PyObject *
5841super_descr_get(PyObject *self, PyObject *obj, PyObject *type)
5842{
5843 superobject *su = (superobject *)self;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00005844 superobject *newobj;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005845
5846 if (obj == NULL || obj == Py_None || su->obj != NULL) {
5847 /* Not binding to an object, or already bound */
5848 Py_INCREF(self);
5849 return self;
5850 }
Guido van Rossum5b443c62001-12-03 15:38:28 +00005851 if (su->ob_type != &PySuper_Type)
Armin Rigo7726dc02005-05-15 15:32:08 +00005852 /* If su is an instance of a (strict) subclass of super,
Guido van Rossum5b443c62001-12-03 15:38:28 +00005853 call its type */
Thomas Wouters477c8d52006-05-27 19:21:47 +00005854 return PyObject_CallFunctionObjArgs((PyObject *)su->ob_type,
Guido van Rossumd8faa362007-04-27 19:54:29 +00005855 su->type, obj, NULL);
Guido van Rossum5b443c62001-12-03 15:38:28 +00005856 else {
5857 /* Inline the common case */
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005858 PyTypeObject *obj_type = supercheck(su->type, obj);
5859 if (obj_type == NULL)
Guido van Rossum5b443c62001-12-03 15:38:28 +00005860 return NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00005861 newobj = (superobject *)PySuper_Type.tp_new(&PySuper_Type,
Guido van Rossum5b443c62001-12-03 15:38:28 +00005862 NULL, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00005863 if (newobj == NULL)
Guido van Rossum5b443c62001-12-03 15:38:28 +00005864 return NULL;
5865 Py_INCREF(su->type);
5866 Py_INCREF(obj);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00005867 newobj->type = su->type;
5868 newobj->obj = obj;
5869 newobj->obj_type = obj_type;
5870 return (PyObject *)newobj;
Guido van Rossum5b443c62001-12-03 15:38:28 +00005871 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00005872}
5873
5874static int
5875super_init(PyObject *self, PyObject *args, PyObject *kwds)
5876{
5877 superobject *su = (superobject *)self;
Guido van Rossume705ef12001-08-29 15:47:06 +00005878 PyTypeObject *type;
5879 PyObject *obj = NULL;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005880 PyTypeObject *obj_type = NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005881
Thomas Wouters89f507f2006-12-13 04:49:30 +00005882 if (!_PyArg_NoKeywords("super", kwds))
5883 return -1;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005884 if (!PyArg_ParseTuple(args, "O!|O:super", &PyType_Type, &type, &obj))
5885 return -1;
5886 if (obj == Py_None)
5887 obj = NULL;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005888 if (obj != NULL) {
5889 obj_type = supercheck(type, obj);
5890 if (obj_type == NULL)
5891 return -1;
5892 Py_INCREF(obj);
5893 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00005894 Py_INCREF(type);
Guido van Rossum705f0f52001-08-24 16:47:00 +00005895 su->type = type;
5896 su->obj = obj;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005897 su->obj_type = obj_type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005898 return 0;
5899}
5900
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005901PyDoc_STRVAR(super_doc,
Guido van Rossum705f0f52001-08-24 16:47:00 +00005902"super(type) -> unbound super object\n"
5903"super(type, obj) -> bound super object; requires isinstance(obj, type)\n"
Guido van Rossume705ef12001-08-29 15:47:06 +00005904"super(type, type2) -> bound super object; requires issubclass(type2, type)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00005905"Typical use to call a cooperative superclass method:\n"
5906"class C(B):\n"
5907" def meth(self, arg):\n"
Guido van Rossumd8faa362007-04-27 19:54:29 +00005908" super(C, self).meth(arg)");
Guido van Rossum705f0f52001-08-24 16:47:00 +00005909
Guido van Rossum048eb752001-10-02 21:24:57 +00005910static int
5911super_traverse(PyObject *self, visitproc visit, void *arg)
5912{
5913 superobject *su = (superobject *)self;
Guido van Rossum048eb752001-10-02 21:24:57 +00005914
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00005915 Py_VISIT(su->obj);
5916 Py_VISIT(su->type);
5917 Py_VISIT(su->obj_type);
Guido van Rossum048eb752001-10-02 21:24:57 +00005918
5919 return 0;
5920}
5921
Guido van Rossum705f0f52001-08-24 16:47:00 +00005922PyTypeObject PySuper_Type = {
5923 PyObject_HEAD_INIT(&PyType_Type)
5924 0, /* ob_size */
5925 "super", /* tp_name */
5926 sizeof(superobject), /* tp_basicsize */
5927 0, /* tp_itemsize */
5928 /* methods */
Guido van Rossumd8faa362007-04-27 19:54:29 +00005929 super_dealloc, /* tp_dealloc */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005930 0, /* tp_print */
5931 0, /* tp_getattr */
5932 0, /* tp_setattr */
5933 0, /* tp_compare */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005934 super_repr, /* tp_repr */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005935 0, /* tp_as_number */
5936 0, /* tp_as_sequence */
Guido van Rossumd8faa362007-04-27 19:54:29 +00005937 0, /* tp_as_mapping */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005938 0, /* tp_hash */
5939 0, /* tp_call */
5940 0, /* tp_str */
5941 super_getattro, /* tp_getattro */
5942 0, /* tp_setattro */
5943 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00005944 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
5945 Py_TPFLAGS_BASETYPE, /* tp_flags */
Guido van Rossumd8faa362007-04-27 19:54:29 +00005946 super_doc, /* tp_doc */
5947 super_traverse, /* tp_traverse */
5948 0, /* tp_clear */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005949 0, /* tp_richcompare */
5950 0, /* tp_weaklistoffset */
5951 0, /* tp_iter */
5952 0, /* tp_iternext */
5953 0, /* tp_methods */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005954 super_members, /* tp_members */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005955 0, /* tp_getset */
5956 0, /* tp_base */
5957 0, /* tp_dict */
5958 super_descr_get, /* tp_descr_get */
5959 0, /* tp_descr_set */
5960 0, /* tp_dictoffset */
5961 super_init, /* tp_init */
5962 PyType_GenericAlloc, /* tp_alloc */
5963 PyType_GenericNew, /* tp_new */
Guido van Rossumd8faa362007-04-27 19:54:29 +00005964 PyObject_GC_Del, /* tp_free */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005965};