blob: f26ddd6bd3b7bdbf6f51b33dedb2b56817d7a7ae [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{
24 char *s;
25
Michael W. Hudsonade8c8b2002-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
Michael W. Hudsonade8c8b2002-11-27 16:29:26 +000029 Py_INCREF(et->name);
30 return et->name;
31 }
32 else {
33 s = strrchr(type->tp_name, '.');
34 if (s == NULL)
35 s = type->tp_name;
36 else
37 s++;
38 return PyString_FromString(s);
39 }
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
74 Py_DECREF(et->name);
75 et->name = value;
76
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. Hudsonade8c8b2002-11-27 16:29:26 +000088 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
89 mod = PyDict_GetItemString(type->tp_dict, "__module__");
90 Py_XINCREF(mod);
Guido van Rossumc3542212001-08-16 09:18:56 +000091 return mod;
92 }
Michael W. Hudsonade8c8b2002-11-27 16:29:26 +000093 else {
94 s = strrchr(type->tp_name, '.');
95 if (s != NULL)
96 return PyString_FromStringAndSize(
97 type->tp_name, (int)(s - type->tp_name));
98 return PyString_FromString("__builtin__");
99 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000100}
101
Guido van Rossum3926a632001-09-25 16:25:58 +0000102static int
103type_set_module(PyTypeObject *type, PyObject *value, void *context)
104{
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000105 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
Guido van Rossum3926a632001-09-25 16:25:58 +0000106 PyErr_Format(PyExc_TypeError,
107 "can't set %s.__module__", type->tp_name);
108 return -1;
109 }
110 if (!value) {
111 PyErr_Format(PyExc_TypeError,
112 "can't delete %s.__module__", type->tp_name);
113 return -1;
114 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000115
Guido van Rossum3926a632001-09-25 16:25:58 +0000116 return PyDict_SetItemString(type->tp_dict, "__module__", value);
117}
118
Tim Peters6d6c1a32001-08-02 04:15:00 +0000119static PyObject *
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000120type_get_bases(PyTypeObject *type, void *context)
121{
122 Py_INCREF(type->tp_bases);
123 return type->tp_bases;
124}
125
126static PyTypeObject *best_base(PyObject *);
127static int mro_internal(PyTypeObject *);
128static int compatible_for_assignment(PyTypeObject *, PyTypeObject *, char *);
129static int add_subclass(PyTypeObject*, PyTypeObject*);
130static void remove_subclass(PyTypeObject *, PyTypeObject *);
131static void update_all_slots(PyTypeObject *);
132
Guido van Rossum8d24ee92003-03-24 23:49:49 +0000133typedef int (*update_callback)(PyTypeObject *, void *);
134static int update_subclasses(PyTypeObject *type, PyObject *name,
135 update_callback callback, void *data);
136static int recurse_down_subclasses(PyTypeObject *type, PyObject *name,
137 update_callback callback, void *data);
138
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000139static int
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000140mro_subclasses(PyTypeObject *type, PyObject* temp)
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000141{
142 PyTypeObject *subclass;
143 PyObject *ref, *subclasses, *old_mro;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000144 int i, n;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000145
146 subclasses = type->tp_subclasses;
147 if (subclasses == NULL)
148 return 0;
149 assert(PyList_Check(subclasses));
150 n = PyList_GET_SIZE(subclasses);
151 for (i = 0; i < n; i++) {
152 ref = PyList_GET_ITEM(subclasses, i);
153 assert(PyWeakref_CheckRef(ref));
154 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
155 assert(subclass != NULL);
156 if ((PyObject *)subclass == Py_None)
157 continue;
158 assert(PyType_Check(subclass));
159 old_mro = subclass->tp_mro;
160 if (mro_internal(subclass) < 0) {
161 subclass->tp_mro = old_mro;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000162 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000163 }
164 else {
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000165 PyObject* tuple;
Raymond Hettinger8ae46892003-10-12 19:09:37 +0000166 tuple = PyTuple_Pack(2, subclass, old_mro);
Guido van Rossum19a02ba2003-04-15 22:09:45 +0000167 Py_DECREF(old_mro);
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000168 if (!tuple)
169 return -1;
170 if (PyList_Append(temp, tuple) < 0)
171 return -1;
Guido van Rossum19a02ba2003-04-15 22:09:45 +0000172 Py_DECREF(tuple);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000173 }
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000174 if (mro_subclasses(subclass, temp) < 0)
175 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000176 }
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000177 return 0;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000178}
179
180static int
181type_set_bases(PyTypeObject *type, PyObject *value, void *context)
182{
183 int i, r = 0;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000184 PyObject *ob, *temp;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000185 PyTypeObject *new_base, *old_base;
186 PyObject *old_bases, *old_mro;
187
188 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
189 PyErr_Format(PyExc_TypeError,
190 "can't set %s.__bases__", type->tp_name);
191 return -1;
192 }
193 if (!value) {
194 PyErr_Format(PyExc_TypeError,
195 "can't delete %s.__bases__", type->tp_name);
196 return -1;
197 }
198 if (!PyTuple_Check(value)) {
199 PyErr_Format(PyExc_TypeError,
200 "can only assign tuple to %s.__bases__, not %s",
201 type->tp_name, value->ob_type->tp_name);
202 return -1;
203 }
Guido van Rossum3bbc0ee2002-12-13 17:49:38 +0000204 if (PyTuple_GET_SIZE(value) == 0) {
205 PyErr_Format(PyExc_TypeError,
206 "can only assign non-empty tuple to %s.__bases__, not ()",
207 type->tp_name);
208 return -1;
209 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000210 for (i = 0; i < PyTuple_GET_SIZE(value); i++) {
211 ob = PyTuple_GET_ITEM(value, i);
212 if (!PyClass_Check(ob) && !PyType_Check(ob)) {
213 PyErr_Format(
214 PyExc_TypeError,
215 "%s.__bases__ must be tuple of old- or new-style classes, not '%s'",
216 type->tp_name, ob->ob_type->tp_name);
217 return -1;
218 }
Michael W. Hudsoncaf17be2002-11-27 10:24:44 +0000219 if (PyType_Check(ob)) {
220 if (PyType_IsSubtype((PyTypeObject*)ob, type)) {
221 PyErr_SetString(PyExc_TypeError,
222 "a __bases__ item causes an inheritance cycle");
223 return -1;
224 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000225 }
226 }
227
228 new_base = best_base(value);
229
230 if (!new_base) {
231 return -1;
232 }
233
234 if (!compatible_for_assignment(type->tp_base, new_base, "__bases__"))
235 return -1;
236
237 Py_INCREF(new_base);
238 Py_INCREF(value);
239
240 old_bases = type->tp_bases;
241 old_base = type->tp_base;
242 old_mro = type->tp_mro;
243
244 type->tp_bases = value;
245 type->tp_base = new_base;
246
247 if (mro_internal(type) < 0) {
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000248 goto bail;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000249 }
250
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000251 temp = PyList_New(0);
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000252 if (!temp)
253 goto bail;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000254
255 r = mro_subclasses(type, temp);
256
257 if (r < 0) {
258 for (i = 0; i < PyList_Size(temp); i++) {
259 PyTypeObject* cls;
260 PyObject* mro;
Raymond Hettinger8ae46892003-10-12 19:09:37 +0000261 PyArg_UnpackTuple(PyList_GET_ITEM(temp, i),
262 "", 2, 2, &cls, &mro);
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000263 Py_DECREF(cls->tp_mro);
264 cls->tp_mro = mro;
265 Py_INCREF(cls->tp_mro);
266 }
267 Py_DECREF(temp);
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000268 goto bail;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000269 }
270
271 Py_DECREF(temp);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000272
273 /* any base that was in __bases__ but now isn't, we
Raymond Hettingera8285862002-12-14 17:17:56 +0000274 need to remove |type| from its tp_subclasses.
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000275 conversely, any class now in __bases__ that wasn't
Raymond Hettingera8285862002-12-14 17:17:56 +0000276 needs to have |type| added to its subclasses. */
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000277
278 /* for now, sod that: just remove from all old_bases,
279 add to all new_bases */
280
281 for (i = PyTuple_GET_SIZE(old_bases) - 1; i >= 0; i--) {
282 ob = PyTuple_GET_ITEM(old_bases, i);
283 if (PyType_Check(ob)) {
284 remove_subclass(
285 (PyTypeObject*)ob, type);
286 }
287 }
288
289 for (i = PyTuple_GET_SIZE(value) - 1; i >= 0; i--) {
290 ob = PyTuple_GET_ITEM(value, i);
291 if (PyType_Check(ob)) {
292 if (add_subclass((PyTypeObject*)ob, type) < 0)
293 r = -1;
294 }
295 }
296
297 update_all_slots(type);
298
299 Py_DECREF(old_bases);
300 Py_DECREF(old_base);
301 Py_DECREF(old_mro);
302
303 return r;
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000304
305 bail:
Michael W. Hudsone723e452003-08-07 14:58:10 +0000306 Py_DECREF(type->tp_bases);
307 Py_DECREF(type->tp_base);
308 if (type->tp_mro != old_mro) {
309 Py_DECREF(type->tp_mro);
310 }
311
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000312 type->tp_bases = old_bases;
313 type->tp_base = old_base;
314 type->tp_mro = old_mro;
Tim Petersea7f75d2002-12-07 21:39:16 +0000315
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000316 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000317}
318
319static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000320type_dict(PyTypeObject *type, void *context)
321{
322 if (type->tp_dict == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000323 Py_INCREF(Py_None);
324 return Py_None;
Guido van Rossum29ca26e1995-01-07 11:58:15 +0000325 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000326 return PyDictProxy_New(type->tp_dict);
Guido van Rossum29ca26e1995-01-07 11:58:15 +0000327}
328
Tim Peters24008312002-03-17 18:56:20 +0000329static PyObject *
330type_get_doc(PyTypeObject *type, void *context)
331{
332 PyObject *result;
Guido van Rossum6ca7d412002-04-18 00:22:00 +0000333 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE) && type->tp_doc != NULL)
Tim Peters24008312002-03-17 18:56:20 +0000334 return PyString_FromString(type->tp_doc);
Tim Peters24008312002-03-17 18:56:20 +0000335 result = PyDict_GetItemString(type->tp_dict, "__doc__");
Guido van Rossum6ca7d412002-04-18 00:22:00 +0000336 if (result == NULL) {
337 result = Py_None;
338 Py_INCREF(result);
339 }
340 else if (result->ob_type->tp_descr_get) {
Tim Peters2b858972002-04-18 04:12:28 +0000341 result = result->ob_type->tp_descr_get(result, NULL,
342 (PyObject *)type);
Guido van Rossum6ca7d412002-04-18 00:22:00 +0000343 }
344 else {
345 Py_INCREF(result);
346 }
Tim Peters24008312002-03-17 18:56:20 +0000347 return result;
348}
349
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000350static PyGetSetDef type_getsets[] = {
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000351 {"__name__", (getter)type_name, (setter)type_set_name, NULL},
352 {"__bases__", (getter)type_get_bases, (setter)type_set_bases, NULL},
Guido van Rossum3926a632001-09-25 16:25:58 +0000353 {"__module__", (getter)type_module, (setter)type_set_module, NULL},
Tim Peters6d6c1a32001-08-02 04:15:00 +0000354 {"__dict__", (getter)type_dict, NULL, NULL},
Tim Peters24008312002-03-17 18:56:20 +0000355 {"__doc__", (getter)type_get_doc, NULL, NULL},
Tim Peters6d6c1a32001-08-02 04:15:00 +0000356 {0}
357};
358
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000359static int
360type_compare(PyObject *v, PyObject *w)
361{
362 /* This is called with type objects only. So we
363 can just compare the addresses. */
364 Py_uintptr_t vv = (Py_uintptr_t)v;
365 Py_uintptr_t ww = (Py_uintptr_t)w;
366 return (vv < ww) ? -1 : (vv > ww) ? 1 : 0;
367}
368
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000369static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000370type_repr(PyTypeObject *type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000371{
Barry Warsaw7ce36942001-08-24 18:34:26 +0000372 PyObject *mod, *name, *rtn;
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000373 char *kind;
Guido van Rossumc3542212001-08-16 09:18:56 +0000374
375 mod = type_module(type, NULL);
376 if (mod == NULL)
377 PyErr_Clear();
378 else if (!PyString_Check(mod)) {
379 Py_DECREF(mod);
380 mod = NULL;
381 }
382 name = type_name(type, NULL);
383 if (name == NULL)
384 return NULL;
Barry Warsaw7ce36942001-08-24 18:34:26 +0000385
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000386 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
387 kind = "class";
388 else
389 kind = "type";
390
Barry Warsaw7ce36942001-08-24 18:34:26 +0000391 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__")) {
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000392 rtn = PyString_FromFormat("<%s '%s.%s'>",
393 kind,
Barry Warsaw7ce36942001-08-24 18:34:26 +0000394 PyString_AS_STRING(mod),
395 PyString_AS_STRING(name));
396 }
Guido van Rossumc3542212001-08-16 09:18:56 +0000397 else
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000398 rtn = PyString_FromFormat("<%s '%s'>", kind, type->tp_name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000399
Guido van Rossumc3542212001-08-16 09:18:56 +0000400 Py_XDECREF(mod);
401 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000402 return rtn;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000403}
404
Tim Peters6d6c1a32001-08-02 04:15:00 +0000405static PyObject *
406type_call(PyTypeObject *type, PyObject *args, PyObject *kwds)
407{
408 PyObject *obj;
409
410 if (type->tp_new == NULL) {
411 PyErr_Format(PyExc_TypeError,
412 "cannot create '%.100s' instances",
413 type->tp_name);
414 return NULL;
415 }
416
Tim Peters3f996e72001-09-13 19:18:27 +0000417 obj = type->tp_new(type, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000418 if (obj != NULL) {
Guido van Rossumf76de622001-10-18 15:49:21 +0000419 /* Ugly exception: when the call was type(something),
420 don't call tp_init on the result. */
421 if (type == &PyType_Type &&
422 PyTuple_Check(args) && PyTuple_GET_SIZE(args) == 1 &&
423 (kwds == NULL ||
424 (PyDict_Check(kwds) && PyDict_Size(kwds) == 0)))
425 return obj;
Guido van Rossum8ace1ab2002-04-06 01:05:01 +0000426 /* If the returned object is not an instance of type,
427 it won't be initialized. */
428 if (!PyType_IsSubtype(obj->ob_type, type))
429 return obj;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000430 type = obj->ob_type;
Jeremy Hylton719841e2002-07-16 19:39:38 +0000431 if (PyType_HasFeature(type, Py_TPFLAGS_HAVE_CLASS) &&
432 type->tp_init != NULL &&
Tim Peters6d6c1a32001-08-02 04:15:00 +0000433 type->tp_init(obj, args, kwds) < 0) {
434 Py_DECREF(obj);
435 obj = NULL;
436 }
437 }
438 return obj;
439}
440
441PyObject *
442PyType_GenericAlloc(PyTypeObject *type, int nitems)
443{
Tim Peters6d6c1a32001-08-02 04:15:00 +0000444 PyObject *obj;
Guido van Rossume5c691a2003-03-07 15:13:17 +0000445 const size_t size = _PyObject_VAR_SIZE(type, nitems+1);
446 /* note that we need to add one, for the sentinel */
Tim Peters406fe3b2001-10-06 19:04:01 +0000447
448 if (PyType_IS_GC(type))
Neil Schemenauer09a2ae52002-04-12 03:06:53 +0000449 obj = _PyObject_GC_Malloc(size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000450 else
Neil Schemenauerc806c882001-08-29 23:54:54 +0000451 obj = PyObject_MALLOC(size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000452
Neil Schemenauerc806c882001-08-29 23:54:54 +0000453 if (obj == NULL)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000454 return PyErr_NoMemory();
Tim Peters406fe3b2001-10-06 19:04:01 +0000455
Neil Schemenauerc806c882001-08-29 23:54:54 +0000456 memset(obj, '\0', size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000457
Tim Peters6d6c1a32001-08-02 04:15:00 +0000458 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
459 Py_INCREF(type);
Tim Peters406fe3b2001-10-06 19:04:01 +0000460
Tim Peters6d6c1a32001-08-02 04:15:00 +0000461 if (type->tp_itemsize == 0)
462 PyObject_INIT(obj, type);
463 else
464 (void) PyObject_INIT_VAR((PyVarObject *)obj, type, nitems);
Tim Peters406fe3b2001-10-06 19:04:01 +0000465
Tim Peters6d6c1a32001-08-02 04:15:00 +0000466 if (PyType_IS_GC(type))
Neil Schemenauerc806c882001-08-29 23:54:54 +0000467 _PyObject_GC_TRACK(obj);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000468 return obj;
469}
470
471PyObject *
472PyType_GenericNew(PyTypeObject *type, PyObject *args, PyObject *kwds)
473{
474 return type->tp_alloc(type, 0);
475}
476
Guido van Rossum9475a232001-10-05 20:51:39 +0000477/* Helpers for subtyping */
478
479static int
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000480traverse_slots(PyTypeObject *type, PyObject *self, visitproc visit, void *arg)
481{
482 int i, n;
483 PyMemberDef *mp;
484
485 n = type->ob_size;
Guido van Rossume5c691a2003-03-07 15:13:17 +0000486 mp = PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000487 for (i = 0; i < n; i++, mp++) {
488 if (mp->type == T_OBJECT_EX) {
489 char *addr = (char *)self + mp->offset;
490 PyObject *obj = *(PyObject **)addr;
491 if (obj != NULL) {
492 int err = visit(obj, arg);
493 if (err)
494 return err;
495 }
496 }
497 }
498 return 0;
499}
500
501static int
Guido van Rossum9475a232001-10-05 20:51:39 +0000502subtype_traverse(PyObject *self, visitproc visit, void *arg)
503{
504 PyTypeObject *type, *base;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000505 traverseproc basetraverse;
Guido van Rossum9475a232001-10-05 20:51:39 +0000506
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000507 /* Find the nearest base with a different tp_traverse,
508 and traverse slots while we're at it */
Guido van Rossum9475a232001-10-05 20:51:39 +0000509 type = self->ob_type;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000510 base = type;
511 while ((basetraverse = base->tp_traverse) == subtype_traverse) {
512 if (base->ob_size) {
513 int err = traverse_slots(base, self, visit, arg);
514 if (err)
515 return err;
516 }
Guido van Rossum9475a232001-10-05 20:51:39 +0000517 base = base->tp_base;
518 assert(base);
519 }
520
521 if (type->tp_dictoffset != base->tp_dictoffset) {
522 PyObject **dictptr = _PyObject_GetDictPtr(self);
523 if (dictptr && *dictptr) {
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000524 int err = visit(*dictptr, arg);
Guido van Rossum9475a232001-10-05 20:51:39 +0000525 if (err)
526 return err;
527 }
528 }
529
Guido van Rossuma3862092002-06-10 15:24:42 +0000530 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
531 /* For a heaptype, the instances count as references
532 to the type. Traverse the type so the collector
533 can find cycles involving this link. */
534 int err = visit((PyObject *)type, arg);
535 if (err)
536 return err;
537 }
538
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000539 if (basetraverse)
540 return basetraverse(self, visit, arg);
541 return 0;
542}
543
544static void
545clear_slots(PyTypeObject *type, PyObject *self)
546{
547 int i, n;
548 PyMemberDef *mp;
549
550 n = type->ob_size;
Guido van Rossume5c691a2003-03-07 15:13:17 +0000551 mp = PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000552 for (i = 0; i < n; i++, mp++) {
553 if (mp->type == T_OBJECT_EX && !(mp->flags & READONLY)) {
554 char *addr = (char *)self + mp->offset;
555 PyObject *obj = *(PyObject **)addr;
556 if (obj != NULL) {
557 Py_DECREF(obj);
558 *(PyObject **)addr = NULL;
559 }
560 }
561 }
562}
563
564static int
565subtype_clear(PyObject *self)
566{
567 PyTypeObject *type, *base;
568 inquiry baseclear;
569
570 /* Find the nearest base with a different tp_clear
571 and clear slots while we're at it */
572 type = self->ob_type;
573 base = type;
574 while ((baseclear = base->tp_clear) == subtype_clear) {
575 if (base->ob_size)
576 clear_slots(base, self);
577 base = base->tp_base;
578 assert(base);
579 }
580
Guido van Rossuma3862092002-06-10 15:24:42 +0000581 /* There's no need to clear the instance dict (if any);
582 the collector will call its tp_clear handler. */
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000583
584 if (baseclear)
585 return baseclear(self);
Guido van Rossum9475a232001-10-05 20:51:39 +0000586 return 0;
587}
Tim Peters6d6c1a32001-08-02 04:15:00 +0000588
589static void
590subtype_dealloc(PyObject *self)
591{
Guido van Rossum14227b42001-12-06 02:35:58 +0000592 PyTypeObject *type, *base;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000593 destructor basedealloc;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000594
Guido van Rossum22b13872002-08-06 21:41:44 +0000595 /* Extract the type; we expect it to be a heap type */
596 type = self->ob_type;
597 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000598
Guido van Rossum22b13872002-08-06 21:41:44 +0000599 /* Test whether the type has GC exactly once */
600
601 if (!PyType_IS_GC(type)) {
602 /* It's really rare to find a dynamic type that doesn't have
603 GC; it can only happen when deriving from 'object' and not
604 adding any slots or instance variables. This allows
605 certain simplifications: there's no need to call
606 clear_slots(), or DECREF the dict, or clear weakrefs. */
607
608 /* Maybe call finalizer; exit early if resurrected */
Guido van Rossumfebd61d2002-08-08 20:55:20 +0000609 if (type->tp_del) {
610 type->tp_del(self);
611 if (self->ob_refcnt > 0)
612 return;
613 }
Guido van Rossum22b13872002-08-06 21:41:44 +0000614
615 /* Find the nearest base with a different tp_dealloc */
616 base = type;
617 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
618 assert(base->ob_size == 0);
619 base = base->tp_base;
620 assert(base);
621 }
622
623 /* Call the base tp_dealloc() */
624 assert(basedealloc);
625 basedealloc(self);
626
627 /* Can't reference self beyond this point */
628 Py_DECREF(type);
629
630 /* Done */
631 return;
632 }
633
634 /* We get here only if the type has GC */
635
636 /* UnTrack and re-Track around the trashcan macro, alas */
Andrew M. Kuchlingc9172d32003-02-06 15:22:49 +0000637 /* See explanation at end of function for full disclosure */
Guido van Rossum0906e072002-08-07 20:42:09 +0000638 PyObject_GC_UnTrack(self);
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000639 ++_PyTrash_delete_nesting;
Guido van Rossum22b13872002-08-06 21:41:44 +0000640 Py_TRASHCAN_SAFE_BEGIN(self);
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000641 --_PyTrash_delete_nesting;
Tim Petersf7f9e992003-11-13 21:59:32 +0000642 /* DO NOT restore GC tracking at this point. weakref callbacks
643 * (if any, and whether directly here or indirectly in something we
644 * call) may trigger GC, and if self is tracked at that point, it
645 * will look like trash to GC and GC will try to delete self again.
Tim Petersadd09b42003-11-12 20:43:28 +0000646 */
Guido van Rossum22b13872002-08-06 21:41:44 +0000647
Guido van Rossum59195fd2003-06-13 20:54:40 +0000648 /* Find the nearest base with a different tp_dealloc */
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000649 base = type;
650 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
Tim Peters6d6c1a32001-08-02 04:15:00 +0000651 base = base->tp_base;
652 assert(base);
Guido van Rossum14227b42001-12-06 02:35:58 +0000653 }
654
Guido van Rossum1987c662003-05-29 14:29:23 +0000655 /* If we added a weaklist, we clear it. Do this *before* calling
Guido van Rossum59195fd2003-06-13 20:54:40 +0000656 the finalizer (__del__), clearing slots, or clearing the instance
657 dict. */
658
Guido van Rossum1987c662003-05-29 14:29:23 +0000659 if (type->tp_weaklistoffset && !base->tp_weaklistoffset)
660 PyObject_ClearWeakRefs(self);
661
662 /* Maybe call finalizer; exit early if resurrected */
663 if (type->tp_del) {
Tim Petersf7f9e992003-11-13 21:59:32 +0000664 _PyObject_GC_TRACK(self);
Guido van Rossum1987c662003-05-29 14:29:23 +0000665 type->tp_del(self);
666 if (self->ob_refcnt > 0)
Tim Petersf7f9e992003-11-13 21:59:32 +0000667 goto endlabel; /* resurrected */
668 else
669 _PyObject_GC_UNTRACK(self);
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
715 before the trashcan begin macro. Without understanding the
716 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
723 probably GC-untracks the object. If it does that using the
724 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
731 GC untrack
732 trashcan begin
733 GC track
734
Tim Petersf7f9e992003-11-13 21:59:32 +0000735 Q. Why did the last question say "immediately GC-track again"?
736 It's nowhere near immediately.
737
738 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.
744
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
756 is incremented and the code between trashcan begin and end is
757 executed
758
759 - this destroys much of the object's contents, including its
760 slots and __dict__
761
762 - basedealloc() is called; this is really list_dealloc(), or
763 some other type which also uses the trashcan macros
764
765 - the trashcan limit is now reached, so the object is put on the
766 trashcan's to-be-deleted-later list
767
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
775 to-be-deleted-later list
776
777 - subtype_dealloc() is called *AGAIN* for the same object
778
779 - at the very least (if the destroyed slots and __dict__ don't
780 cause problems) the object's type gets decref'ed a second
781 time, which is *BAD*!!!
782
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
793 that the effective level never reaches the limit. Therefore, we
794 *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
Guido van Rossum9478d072001-09-07 18:52:13 +0000817 if (!(a->tp_flags & Py_TPFLAGS_HAVE_CLASS))
818 return b == a || b == &PyBaseObject_Type;
819
Tim Peters6d6c1a32001-08-02 04:15:00 +0000820 mro = a->tp_mro;
821 if (mro != NULL) {
822 /* Deal with multiple inheritance without recursion
823 by walking the MRO tuple */
824 int i, n;
825 assert(PyTuple_Check(mro));
826 n = PyTuple_GET_SIZE(mro);
827 for (i = 0; i < n; i++) {
828 if (PyTuple_GET_ITEM(mro, i) == (PyObject *)b)
829 return 1;
830 }
831 return 0;
832 }
833 else {
834 /* a is not completely initilized yet; follow tp_base */
835 do {
836 if (a == b)
837 return 1;
838 a = a->tp_base;
839 } while (a != NULL);
840 return b == &PyBaseObject_Type;
841 }
842}
843
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000844/* Internal routines to do a method lookup in the type
Guido van Rossum60718732001-08-28 17:47:51 +0000845 without looking in the instance dictionary
846 (so we can't use PyObject_GetAttr) but still binding
847 it to the instance. The arguments are the object,
848 the method name as a C string, and the address of a
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000849 static variable used to cache the interned Python string.
850
851 Two variants:
852
853 - lookup_maybe() returns NULL without raising an exception
854 when the _PyType_Lookup() call fails;
855
856 - lookup_method() always raises an exception upon errors.
857*/
Guido van Rossum60718732001-08-28 17:47:51 +0000858
859static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000860lookup_maybe(PyObject *self, char *attrstr, PyObject **attrobj)
Guido van Rossum60718732001-08-28 17:47:51 +0000861{
862 PyObject *res;
863
864 if (*attrobj == NULL) {
865 *attrobj = PyString_InternFromString(attrstr);
866 if (*attrobj == NULL)
867 return NULL;
868 }
869 res = _PyType_Lookup(self->ob_type, *attrobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000870 if (res != NULL) {
Guido van Rossum60718732001-08-28 17:47:51 +0000871 descrgetfunc f;
872 if ((f = res->ob_type->tp_descr_get) == NULL)
873 Py_INCREF(res);
874 else
875 res = f(res, self, (PyObject *)(self->ob_type));
876 }
877 return res;
878}
879
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000880static PyObject *
881lookup_method(PyObject *self, char *attrstr, PyObject **attrobj)
882{
883 PyObject *res = lookup_maybe(self, attrstr, attrobj);
884 if (res == NULL && !PyErr_Occurred())
885 PyErr_SetObject(PyExc_AttributeError, *attrobj);
886 return res;
887}
888
Guido van Rossum2730b132001-08-28 18:22:14 +0000889/* A variation of PyObject_CallMethod that uses lookup_method()
890 instead of PyObject_GetAttrString(). This uses the same convention
891 as lookup_method to cache the interned name string object. */
892
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000893static PyObject *
Guido van Rossum2730b132001-08-28 18:22:14 +0000894call_method(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
895{
896 va_list va;
897 PyObject *args, *func = 0, *retval;
Guido van Rossum2730b132001-08-28 18:22:14 +0000898 va_start(va, format);
899
Guido van Rossumda21c012001-10-03 00:50:18 +0000900 func = lookup_maybe(o, name, nameobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000901 if (func == NULL) {
902 va_end(va);
903 if (!PyErr_Occurred())
Guido van Rossumda21c012001-10-03 00:50:18 +0000904 PyErr_SetObject(PyExc_AttributeError, *nameobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000905 return NULL;
906 }
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000907
908 if (format && *format)
909 args = Py_VaBuildValue(format, va);
910 else
911 args = PyTuple_New(0);
912
913 va_end(va);
914
915 if (args == NULL)
916 return NULL;
917
918 assert(PyTuple_Check(args));
919 retval = PyObject_Call(func, args, NULL);
920
921 Py_DECREF(args);
922 Py_DECREF(func);
923
924 return retval;
925}
926
927/* Clone of call_method() that returns NotImplemented when the lookup fails. */
928
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000929static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000930call_maybe(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
931{
932 va_list va;
933 PyObject *args, *func = 0, *retval;
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000934 va_start(va, format);
935
Guido van Rossumda21c012001-10-03 00:50:18 +0000936 func = lookup_maybe(o, name, nameobj);
Guido van Rossum2730b132001-08-28 18:22:14 +0000937 if (func == NULL) {
938 va_end(va);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000939 if (!PyErr_Occurred()) {
940 Py_INCREF(Py_NotImplemented);
941 return Py_NotImplemented;
942 }
Guido van Rossum717ce002001-09-14 16:58:08 +0000943 return NULL;
Guido van Rossum2730b132001-08-28 18:22:14 +0000944 }
945
946 if (format && *format)
947 args = Py_VaBuildValue(format, va);
948 else
949 args = PyTuple_New(0);
950
951 va_end(va);
952
Guido van Rossum717ce002001-09-14 16:58:08 +0000953 if (args == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +0000954 return NULL;
955
Guido van Rossum717ce002001-09-14 16:58:08 +0000956 assert(PyTuple_Check(args));
957 retval = PyObject_Call(func, args, NULL);
Guido van Rossum2730b132001-08-28 18:22:14 +0000958
959 Py_DECREF(args);
960 Py_DECREF(func);
961
962 return retval;
963}
964
Tim Petersa91e9642001-11-14 23:32:33 +0000965static int
966fill_classic_mro(PyObject *mro, PyObject *cls)
967{
968 PyObject *bases, *base;
969 int i, n;
970
971 assert(PyList_Check(mro));
972 assert(PyClass_Check(cls));
973 i = PySequence_Contains(mro, cls);
974 if (i < 0)
975 return -1;
976 if (!i) {
977 if (PyList_Append(mro, cls) < 0)
978 return -1;
979 }
980 bases = ((PyClassObject *)cls)->cl_bases;
981 assert(bases && PyTuple_Check(bases));
982 n = PyTuple_GET_SIZE(bases);
983 for (i = 0; i < n; i++) {
984 base = PyTuple_GET_ITEM(bases, i);
985 if (fill_classic_mro(mro, base) < 0)
986 return -1;
987 }
988 return 0;
989}
990
991static PyObject *
992classic_mro(PyObject *cls)
993{
994 PyObject *mro;
995
996 assert(PyClass_Check(cls));
997 mro = PyList_New(0);
998 if (mro != NULL) {
999 if (fill_classic_mro(mro, cls) == 0)
1000 return mro;
1001 Py_DECREF(mro);
1002 }
1003 return NULL;
1004}
1005
Tim Petersea7f75d2002-12-07 21:39:16 +00001006/*
Guido van Rossum1f121312002-11-14 19:49:16 +00001007 Method resolution order algorithm C3 described in
1008 "A Monotonic Superclass Linearization for Dylan",
1009 by Kim Barrett, Bob Cassel, Paul Haahr,
Tim Petersea7f75d2002-12-07 21:39:16 +00001010 David A. Moon, Keith Playford, and P. Tucker Withington.
Guido van Rossum1f121312002-11-14 19:49:16 +00001011 (OOPSLA 1996)
1012
Guido van Rossum98f33732002-11-25 21:36:54 +00001013 Some notes about the rules implied by C3:
1014
Tim Petersea7f75d2002-12-07 21:39:16 +00001015 No duplicate bases.
Guido van Rossum98f33732002-11-25 21:36:54 +00001016 It isn't legal to repeat a class in a list of base classes.
1017
1018 The next three properties are the 3 constraints in "C3".
1019
Tim Petersea7f75d2002-12-07 21:39:16 +00001020 Local precendece order.
Guido van Rossum98f33732002-11-25 21:36:54 +00001021 If A precedes B in C's MRO, then A will precede B in the MRO of all
1022 subclasses of C.
1023
1024 Monotonicity.
1025 The MRO of a class must be an extension without reordering of the
1026 MRO of each of its superclasses.
1027
1028 Extended Precedence Graph (EPG).
1029 Linearization is consistent if there is a path in the EPG from
1030 each class to all its successors in the linearization. See
1031 the paper for definition of EPG.
Guido van Rossum1f121312002-11-14 19:49:16 +00001032 */
1033
Tim Petersea7f75d2002-12-07 21:39:16 +00001034static int
Guido van Rossum1f121312002-11-14 19:49:16 +00001035tail_contains(PyObject *list, int whence, PyObject *o) {
1036 int j, size;
1037 size = PyList_GET_SIZE(list);
1038
1039 for (j = whence+1; j < size; j++) {
1040 if (PyList_GET_ITEM(list, j) == o)
1041 return 1;
1042 }
1043 return 0;
1044}
1045
Guido van Rossum98f33732002-11-25 21:36:54 +00001046static PyObject *
1047class_name(PyObject *cls)
1048{
1049 PyObject *name = PyObject_GetAttrString(cls, "__name__");
1050 if (name == NULL) {
1051 PyErr_Clear();
1052 Py_XDECREF(name);
1053 name = PyObject_Repr(cls);
1054 }
1055 if (name == NULL)
1056 return NULL;
1057 if (!PyString_Check(name)) {
1058 Py_DECREF(name);
1059 return NULL;
1060 }
1061 return name;
1062}
1063
1064static int
1065check_duplicates(PyObject *list)
1066{
1067 int i, j, n;
1068 /* Let's use a quadratic time algorithm,
1069 assuming that the bases lists is short.
1070 */
1071 n = PyList_GET_SIZE(list);
1072 for (i = 0; i < n; i++) {
1073 PyObject *o = PyList_GET_ITEM(list, i);
1074 for (j = i + 1; j < n; j++) {
1075 if (PyList_GET_ITEM(list, j) == o) {
1076 o = class_name(o);
1077 PyErr_Format(PyExc_TypeError,
1078 "duplicate base class %s",
1079 o ? PyString_AS_STRING(o) : "?");
1080 Py_XDECREF(o);
1081 return -1;
1082 }
1083 }
1084 }
1085 return 0;
1086}
1087
1088/* Raise a TypeError for an MRO order disagreement.
1089
1090 It's hard to produce a good error message. In the absence of better
1091 insight into error reporting, report the classes that were candidates
1092 to be put next into the MRO. There is some conflict between the
1093 order in which they should be put in the MRO, but it's hard to
1094 diagnose what constraint can't be satisfied.
1095*/
1096
1097static void
1098set_mro_error(PyObject *to_merge, int *remain)
1099{
1100 int i, n, off, to_merge_size;
1101 char buf[1000];
1102 PyObject *k, *v;
1103 PyObject *set = PyDict_New();
1104
1105 to_merge_size = PyList_GET_SIZE(to_merge);
1106 for (i = 0; i < to_merge_size; i++) {
1107 PyObject *L = PyList_GET_ITEM(to_merge, i);
1108 if (remain[i] < PyList_GET_SIZE(L)) {
1109 PyObject *c = PyList_GET_ITEM(L, remain[i]);
1110 if (PyDict_SetItem(set, c, Py_None) < 0)
1111 return;
1112 }
1113 }
1114 n = PyDict_Size(set);
1115
Raymond Hettingerf394df42003-04-06 19:13:41 +00001116 off = PyOS_snprintf(buf, sizeof(buf), "Cannot create a \
1117consistent method resolution\norder (MRO) for bases");
Guido van Rossum98f33732002-11-25 21:36:54 +00001118 i = 0;
1119 while (PyDict_Next(set, &i, &k, &v) && off < sizeof(buf)) {
1120 PyObject *name = class_name(k);
1121 off += PyOS_snprintf(buf + off, sizeof(buf) - off, " %s",
1122 name ? PyString_AS_STRING(name) : "?");
1123 Py_XDECREF(name);
1124 if (--n && off+1 < sizeof(buf)) {
1125 buf[off++] = ',';
1126 buf[off] = '\0';
1127 }
1128 }
1129 PyErr_SetString(PyExc_TypeError, buf);
1130 Py_DECREF(set);
1131}
1132
Tim Petersea7f75d2002-12-07 21:39:16 +00001133static int
Guido van Rossum1f121312002-11-14 19:49:16 +00001134pmerge(PyObject *acc, PyObject* to_merge) {
1135 int i, j, to_merge_size;
1136 int *remain;
1137 int ok, empty_cnt;
Tim Petersea7f75d2002-12-07 21:39:16 +00001138
Guido van Rossum1f121312002-11-14 19:49:16 +00001139 to_merge_size = PyList_GET_SIZE(to_merge);
1140
Guido van Rossum98f33732002-11-25 21:36:54 +00001141 /* remain stores an index into each sublist of to_merge.
1142 remain[i] is the index of the next base in to_merge[i]
1143 that is not included in acc.
1144 */
Guido van Rossum1f121312002-11-14 19:49:16 +00001145 remain = PyMem_MALLOC(SIZEOF_INT*to_merge_size);
1146 if (remain == NULL)
1147 return -1;
1148 for (i = 0; i < to_merge_size; i++)
1149 remain[i] = 0;
1150
1151 again:
1152 empty_cnt = 0;
1153 for (i = 0; i < to_merge_size; i++) {
1154 PyObject *candidate;
Tim Petersea7f75d2002-12-07 21:39:16 +00001155
Guido van Rossum1f121312002-11-14 19:49:16 +00001156 PyObject *cur_list = PyList_GET_ITEM(to_merge, i);
1157
1158 if (remain[i] >= PyList_GET_SIZE(cur_list)) {
1159 empty_cnt++;
1160 continue;
1161 }
1162
Guido van Rossum98f33732002-11-25 21:36:54 +00001163 /* Choose next candidate for MRO.
1164
1165 The input sequences alone can determine the choice.
1166 If not, choose the class which appears in the MRO
1167 of the earliest direct superclass of the new class.
1168 */
1169
Guido van Rossum1f121312002-11-14 19:49:16 +00001170 candidate = PyList_GET_ITEM(cur_list, remain[i]);
1171 for (j = 0; j < to_merge_size; j++) {
1172 PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
Guido van Rossum98f33732002-11-25 21:36:54 +00001173 if (tail_contains(j_lst, remain[j], candidate)) {
Guido van Rossum1f121312002-11-14 19:49:16 +00001174 goto skip; /* continue outer loop */
Guido van Rossum98f33732002-11-25 21:36:54 +00001175 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001176 }
1177 ok = PyList_Append(acc, candidate);
1178 if (ok < 0) {
1179 PyMem_Free(remain);
1180 return -1;
1181 }
1182 for (j = 0; j < to_merge_size; j++) {
1183 PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
Guido van Rossum768158c2002-12-31 16:33:01 +00001184 if (remain[j] < PyList_GET_SIZE(j_lst) &&
1185 PyList_GET_ITEM(j_lst, remain[j]) == candidate) {
Guido van Rossum1f121312002-11-14 19:49:16 +00001186 remain[j]++;
1187 }
1188 }
1189 goto again;
Tim Peters9a6b8d82002-11-14 23:22:33 +00001190 skip: ;
Guido van Rossum1f121312002-11-14 19:49:16 +00001191 }
1192
Guido van Rossum98f33732002-11-25 21:36:54 +00001193 if (empty_cnt == to_merge_size) {
1194 PyMem_FREE(remain);
Guido van Rossum1f121312002-11-14 19:49:16 +00001195 return 0;
Guido van Rossum98f33732002-11-25 21:36:54 +00001196 }
1197 set_mro_error(to_merge, remain);
1198 PyMem_FREE(remain);
Guido van Rossum1f121312002-11-14 19:49:16 +00001199 return -1;
1200}
1201
Tim Peters6d6c1a32001-08-02 04:15:00 +00001202static PyObject *
1203mro_implementation(PyTypeObject *type)
1204{
1205 int i, n, ok;
1206 PyObject *bases, *result;
Guido van Rossum1f121312002-11-14 19:49:16 +00001207 PyObject *to_merge, *bases_aslist;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001208
Guido van Rossum63517572002-06-18 16:44:57 +00001209 if(type->tp_dict == NULL) {
1210 if(PyType_Ready(type) < 0)
1211 return NULL;
1212 }
1213
Guido van Rossum98f33732002-11-25 21:36:54 +00001214 /* Find a superclass linearization that honors the constraints
1215 of the explicit lists of bases and the constraints implied by
Tim Petersea7f75d2002-12-07 21:39:16 +00001216 each base class.
Guido van Rossum98f33732002-11-25 21:36:54 +00001217
1218 to_merge is a list of lists, where each list is a superclass
1219 linearization implied by a base class. The last element of
1220 to_merge is the declared list of bases.
1221 */
1222
Tim Peters6d6c1a32001-08-02 04:15:00 +00001223 bases = type->tp_bases;
1224 n = PyTuple_GET_SIZE(bases);
Guido van Rossum1f121312002-11-14 19:49:16 +00001225
1226 to_merge = PyList_New(n+1);
1227 if (to_merge == NULL)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001228 return NULL;
Guido van Rossum1f121312002-11-14 19:49:16 +00001229
Tim Peters6d6c1a32001-08-02 04:15:00 +00001230 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00001231 PyObject *base = PyTuple_GET_ITEM(bases, i);
1232 PyObject *parentMRO;
1233 if (PyType_Check(base))
1234 parentMRO = PySequence_List(
1235 ((PyTypeObject*)base)->tp_mro);
1236 else
1237 parentMRO = classic_mro(base);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001238 if (parentMRO == NULL) {
Guido van Rossum1f121312002-11-14 19:49:16 +00001239 Py_DECREF(to_merge);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001240 return NULL;
Guido van Rossum1f121312002-11-14 19:49:16 +00001241 }
1242
1243 PyList_SET_ITEM(to_merge, i, parentMRO);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001244 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001245
1246 bases_aslist = PySequence_List(bases);
1247 if (bases_aslist == NULL) {
1248 Py_DECREF(to_merge);
1249 return NULL;
1250 }
Guido van Rossum98f33732002-11-25 21:36:54 +00001251 /* This is just a basic sanity check. */
1252 if (check_duplicates(bases_aslist) < 0) {
1253 Py_DECREF(to_merge);
1254 Py_DECREF(bases_aslist);
1255 return NULL;
1256 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001257 PyList_SET_ITEM(to_merge, n, bases_aslist);
1258
1259 result = Py_BuildValue("[O]", (PyObject *)type);
1260 if (result == NULL) {
1261 Py_DECREF(to_merge);
1262 return NULL;
1263 }
1264
1265 ok = pmerge(result, to_merge);
1266 Py_DECREF(to_merge);
1267 if (ok < 0) {
1268 Py_DECREF(result);
1269 return NULL;
1270 }
1271
Tim Peters6d6c1a32001-08-02 04:15:00 +00001272 return result;
1273}
1274
1275static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001276mro_external(PyObject *self)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001277{
1278 PyTypeObject *type = (PyTypeObject *)self;
1279
Tim Peters6d6c1a32001-08-02 04:15:00 +00001280 return mro_implementation(type);
1281}
1282
1283static int
1284mro_internal(PyTypeObject *type)
1285{
1286 PyObject *mro, *result, *tuple;
1287
1288 if (type->ob_type == &PyType_Type) {
1289 result = mro_implementation(type);
1290 }
1291 else {
Guido van Rossum60718732001-08-28 17:47:51 +00001292 static PyObject *mro_str;
1293 mro = lookup_method((PyObject *)type, "mro", &mro_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001294 if (mro == NULL)
1295 return -1;
1296 result = PyObject_CallObject(mro, NULL);
1297 Py_DECREF(mro);
1298 }
1299 if (result == NULL)
1300 return -1;
1301 tuple = PySequence_Tuple(result);
1302 Py_DECREF(result);
1303 type->tp_mro = tuple;
1304 return 0;
1305}
1306
1307
1308/* Calculate the best base amongst multiple base classes.
1309 This is the first one that's on the path to the "solid base". */
1310
1311static PyTypeObject *
1312best_base(PyObject *bases)
1313{
1314 int i, n;
1315 PyTypeObject *base, *winner, *candidate, *base_i;
Tim Petersa91e9642001-11-14 23:32:33 +00001316 PyObject *base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001317
1318 assert(PyTuple_Check(bases));
1319 n = PyTuple_GET_SIZE(bases);
1320 assert(n > 0);
Tim Petersa91e9642001-11-14 23:32:33 +00001321 base = NULL;
1322 winner = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001323 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00001324 base_proto = PyTuple_GET_ITEM(bases, i);
1325 if (PyClass_Check(base_proto))
1326 continue;
1327 if (!PyType_Check(base_proto)) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001328 PyErr_SetString(
1329 PyExc_TypeError,
1330 "bases must be types");
1331 return NULL;
1332 }
Tim Petersa91e9642001-11-14 23:32:33 +00001333 base_i = (PyTypeObject *)base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001334 if (base_i->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001335 if (PyType_Ready(base_i) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001336 return NULL;
1337 }
1338 candidate = solid_base(base_i);
Tim Petersa91e9642001-11-14 23:32:33 +00001339 if (winner == NULL) {
1340 winner = candidate;
1341 base = base_i;
1342 }
1343 else if (PyType_IsSubtype(winner, candidate))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001344 ;
1345 else if (PyType_IsSubtype(candidate, winner)) {
1346 winner = candidate;
1347 base = base_i;
1348 }
1349 else {
1350 PyErr_SetString(
1351 PyExc_TypeError,
1352 "multiple bases have "
1353 "instance lay-out conflict");
1354 return NULL;
1355 }
1356 }
Guido van Rossume54616c2001-12-14 04:19:56 +00001357 if (base == NULL)
1358 PyErr_SetString(PyExc_TypeError,
1359 "a new-style class can't have only classic bases");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001360 return base;
1361}
1362
1363static int
1364extra_ivars(PyTypeObject *type, PyTypeObject *base)
1365{
Neil Schemenauerc806c882001-08-29 23:54:54 +00001366 size_t t_size = type->tp_basicsize;
1367 size_t b_size = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001368
Guido van Rossum9676b222001-08-17 20:32:36 +00001369 assert(t_size >= b_size); /* Else type smaller than base! */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001370 if (type->tp_itemsize || base->tp_itemsize) {
1371 /* If itemsize is involved, stricter rules */
1372 return t_size != b_size ||
1373 type->tp_itemsize != base->tp_itemsize;
1374 }
Guido van Rossum9676b222001-08-17 20:32:36 +00001375 if (type->tp_weaklistoffset && base->tp_weaklistoffset == 0 &&
1376 type->tp_weaklistoffset + sizeof(PyObject *) == t_size)
1377 t_size -= sizeof(PyObject *);
1378 if (type->tp_dictoffset && base->tp_dictoffset == 0 &&
1379 type->tp_dictoffset + sizeof(PyObject *) == t_size)
1380 t_size -= sizeof(PyObject *);
1381
1382 return t_size != b_size;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001383}
1384
1385static PyTypeObject *
1386solid_base(PyTypeObject *type)
1387{
1388 PyTypeObject *base;
1389
1390 if (type->tp_base)
1391 base = solid_base(type->tp_base);
1392 else
1393 base = &PyBaseObject_Type;
1394 if (extra_ivars(type, base))
1395 return type;
1396 else
1397 return base;
1398}
1399
Jeremy Hylton938ace62002-07-17 16:30:39 +00001400static void object_dealloc(PyObject *);
1401static int object_init(PyObject *, PyObject *, PyObject *);
1402static int update_slot(PyTypeObject *, PyObject *);
1403static void fixup_slot_dispatchers(PyTypeObject *);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001404
1405static PyObject *
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001406subtype_dict(PyObject *obj, void *context)
1407{
1408 PyObject **dictptr = _PyObject_GetDictPtr(obj);
1409 PyObject *dict;
1410
1411 if (dictptr == NULL) {
1412 PyErr_SetString(PyExc_AttributeError,
1413 "This object has no __dict__");
1414 return NULL;
1415 }
1416 dict = *dictptr;
Guido van Rossum3926a632001-09-25 16:25:58 +00001417 if (dict == NULL)
1418 *dictptr = dict = PyDict_New();
1419 Py_XINCREF(dict);
1420 return dict;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001421}
1422
Guido van Rossum6661be32001-10-26 04:26:12 +00001423static int
1424subtype_setdict(PyObject *obj, PyObject *value, void *context)
1425{
1426 PyObject **dictptr = _PyObject_GetDictPtr(obj);
1427 PyObject *dict;
1428
1429 if (dictptr == NULL) {
1430 PyErr_SetString(PyExc_AttributeError,
1431 "This object has no __dict__");
1432 return -1;
1433 }
Guido van Rossumd331cb52001-12-05 19:46:42 +00001434 if (value != NULL && !PyDict_Check(value)) {
Guido van Rossum6661be32001-10-26 04:26:12 +00001435 PyErr_SetString(PyExc_TypeError,
1436 "__dict__ must be set to a dictionary");
1437 return -1;
1438 }
1439 dict = *dictptr;
Guido van Rossumd331cb52001-12-05 19:46:42 +00001440 Py_XINCREF(value);
Guido van Rossum6661be32001-10-26 04:26:12 +00001441 *dictptr = value;
1442 Py_XDECREF(dict);
1443 return 0;
1444}
1445
Guido van Rossumad47da02002-08-12 19:05:44 +00001446static PyObject *
1447subtype_getweakref(PyObject *obj, void *context)
1448{
1449 PyObject **weaklistptr;
1450 PyObject *result;
1451
1452 if (obj->ob_type->tp_weaklistoffset == 0) {
1453 PyErr_SetString(PyExc_AttributeError,
1454 "This object has no __weaklist__");
1455 return NULL;
1456 }
1457 assert(obj->ob_type->tp_weaklistoffset > 0);
1458 assert(obj->ob_type->tp_weaklistoffset + sizeof(PyObject *) <=
Guido van Rossum3747a0f2002-08-12 19:25:08 +00001459 (size_t)(obj->ob_type->tp_basicsize));
Guido van Rossumad47da02002-08-12 19:05:44 +00001460 weaklistptr = (PyObject **)
Guido van Rossum3747a0f2002-08-12 19:25:08 +00001461 ((char *)obj + obj->ob_type->tp_weaklistoffset);
Guido van Rossumad47da02002-08-12 19:05:44 +00001462 if (*weaklistptr == NULL)
1463 result = Py_None;
1464 else
1465 result = *weaklistptr;
1466 Py_INCREF(result);
1467 return result;
1468}
1469
Guido van Rossum373c7412003-01-07 13:41:37 +00001470/* Three variants on the subtype_getsets list. */
1471
1472static PyGetSetDef subtype_getsets_full[] = {
Guido van Rossumad47da02002-08-12 19:05:44 +00001473 {"__dict__", subtype_dict, subtype_setdict,
Neal Norwitz858e34f2002-08-13 17:18:45 +00001474 PyDoc_STR("dictionary for instance variables (if defined)")},
Guido van Rossumad47da02002-08-12 19:05:44 +00001475 {"__weakref__", subtype_getweakref, NULL,
Neal Norwitz858e34f2002-08-13 17:18:45 +00001476 PyDoc_STR("list of weak references to the object (if defined)")},
Guido van Rossumad47da02002-08-12 19:05:44 +00001477 {0}
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001478};
1479
Guido van Rossum373c7412003-01-07 13:41:37 +00001480static PyGetSetDef subtype_getsets_dict_only[] = {
1481 {"__dict__", subtype_dict, subtype_setdict,
1482 PyDoc_STR("dictionary for instance variables (if defined)")},
1483 {0}
1484};
1485
1486static PyGetSetDef subtype_getsets_weakref_only[] = {
1487 {"__weakref__", subtype_getweakref, NULL,
1488 PyDoc_STR("list of weak references to the object (if defined)")},
1489 {0}
1490};
1491
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001492static int
1493valid_identifier(PyObject *s)
1494{
Guido van Rossum03013a02002-07-16 14:30:28 +00001495 unsigned char *p;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001496 int i, n;
1497
1498 if (!PyString_Check(s)) {
1499 PyErr_SetString(PyExc_TypeError,
1500 "__slots__ must be strings");
1501 return 0;
1502 }
Guido van Rossum03013a02002-07-16 14:30:28 +00001503 p = (unsigned char *) PyString_AS_STRING(s);
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001504 n = PyString_GET_SIZE(s);
1505 /* We must reject an empty name. As a hack, we bump the
1506 length to 1 so that the loop will balk on the trailing \0. */
1507 if (n == 0)
1508 n = 1;
1509 for (i = 0; i < n; i++, p++) {
1510 if (!(i == 0 ? isalpha(*p) : isalnum(*p)) && *p != '_') {
1511 PyErr_SetString(PyExc_TypeError,
1512 "__slots__ must be identifiers");
1513 return 0;
1514 }
1515 }
1516 return 1;
1517}
1518
Martin v. Löwisd919a592002-10-14 21:07:28 +00001519#ifdef Py_USING_UNICODE
1520/* Replace Unicode objects in slots. */
1521
1522static PyObject *
1523_unicode_to_string(PyObject *slots, int nslots)
1524{
1525 PyObject *tmp = slots;
1526 PyObject *o, *o1;
1527 int i;
1528 intintargfunc copy = slots->ob_type->tp_as_sequence->sq_slice;
1529 for (i = 0; i < nslots; i++) {
1530 if (PyUnicode_Check(o = PyTuple_GET_ITEM(tmp, i))) {
1531 if (tmp == slots) {
1532 tmp = copy(slots, 0, PyTuple_GET_SIZE(slots));
1533 if (tmp == NULL)
1534 return NULL;
1535 }
1536 o1 = _PyUnicode_AsDefaultEncodedString
1537 (o, NULL);
1538 if (o1 == NULL) {
1539 Py_DECREF(tmp);
1540 return 0;
1541 }
1542 Py_INCREF(o1);
1543 Py_DECREF(o);
1544 PyTuple_SET_ITEM(tmp, i, o1);
1545 }
1546 }
1547 return tmp;
1548}
1549#endif
1550
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001551static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00001552type_new(PyTypeObject *metatype, PyObject *args, PyObject *kwds)
1553{
1554 PyObject *name, *bases, *dict;
1555 static char *kwlist[] = {"name", "bases", "dict", 0};
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001556 PyObject *slots, *tmp, *newslots;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001557 PyTypeObject *type, *base, *tmptype, *winner;
Guido van Rossume5c691a2003-03-07 15:13:17 +00001558 PyHeapTypeObject *et;
Guido van Rossum6f799372001-09-20 20:46:19 +00001559 PyMemberDef *mp;
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001560 int i, nbases, nslots, slotoffset, add_dict, add_weak;
Guido van Rossumad47da02002-08-12 19:05:44 +00001561 int j, may_add_dict, may_add_weak;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001562
Tim Peters3abca122001-10-27 19:37:48 +00001563 assert(args != NULL && PyTuple_Check(args));
1564 assert(kwds == NULL || PyDict_Check(kwds));
1565
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001566 /* Special case: type(x) should return x->ob_type */
Tim Peters3abca122001-10-27 19:37:48 +00001567 {
1568 const int nargs = PyTuple_GET_SIZE(args);
1569 const int nkwds = kwds == NULL ? 0 : PyDict_Size(kwds);
1570
1571 if (PyType_CheckExact(metatype) && nargs == 1 && nkwds == 0) {
1572 PyObject *x = PyTuple_GET_ITEM(args, 0);
1573 Py_INCREF(x->ob_type);
1574 return (PyObject *) x->ob_type;
1575 }
1576
1577 /* SF bug 475327 -- if that didn't trigger, we need 3
1578 arguments. but PyArg_ParseTupleAndKeywords below may give
1579 a msg saying type() needs exactly 3. */
1580 if (nargs + nkwds != 3) {
1581 PyErr_SetString(PyExc_TypeError,
1582 "type() takes 1 or 3 arguments");
1583 return NULL;
1584 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001585 }
1586
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001587 /* Check arguments: (name, bases, dict) */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001588 if (!PyArg_ParseTupleAndKeywords(args, kwds, "SO!O!:type", kwlist,
1589 &name,
1590 &PyTuple_Type, &bases,
1591 &PyDict_Type, &dict))
1592 return NULL;
1593
1594 /* Determine the proper metatype to deal with this,
1595 and check for metatype conflicts while we're at it.
1596 Note that if some other metatype wins to contract,
1597 it's possible that its instances are not types. */
1598 nbases = PyTuple_GET_SIZE(bases);
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001599 winner = metatype;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001600 for (i = 0; i < nbases; i++) {
1601 tmp = PyTuple_GET_ITEM(bases, i);
1602 tmptype = tmp->ob_type;
Tim Petersa91e9642001-11-14 23:32:33 +00001603 if (tmptype == &PyClass_Type)
1604 continue; /* Special case classic classes */
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001605 if (PyType_IsSubtype(winner, tmptype))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001606 continue;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001607 if (PyType_IsSubtype(tmptype, winner)) {
1608 winner = tmptype;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001609 continue;
1610 }
1611 PyErr_SetString(PyExc_TypeError,
Guido van Rossum636688d2003-04-23 12:07:22 +00001612 "metaclass conflict: "
1613 "the metaclass of a derived class "
1614 "must be a (non-strict) subclass "
1615 "of the metaclasses of all its bases");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001616 return NULL;
1617 }
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001618 if (winner != metatype) {
1619 if (winner->tp_new != type_new) /* Pass it to the winner */
1620 return winner->tp_new(winner, args, kwds);
1621 metatype = winner;
1622 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001623
1624 /* Adjust for empty tuple bases */
1625 if (nbases == 0) {
Raymond Hettinger8ae46892003-10-12 19:09:37 +00001626 bases = PyTuple_Pack(1, &PyBaseObject_Type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001627 if (bases == NULL)
1628 return NULL;
1629 nbases = 1;
1630 }
1631 else
1632 Py_INCREF(bases);
1633
1634 /* XXX From here until type is allocated, "return NULL" leaks bases! */
1635
1636 /* Calculate best base, and check that all bases are type objects */
1637 base = best_base(bases);
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001638 if (base == NULL) {
1639 Py_DECREF(bases);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001640 return NULL;
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001641 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001642 if (!PyType_HasFeature(base, Py_TPFLAGS_BASETYPE)) {
1643 PyErr_Format(PyExc_TypeError,
1644 "type '%.100s' is not an acceptable base type",
1645 base->tp_name);
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001646 Py_DECREF(bases);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001647 return NULL;
1648 }
1649
Tim Peters6d6c1a32001-08-02 04:15:00 +00001650 /* Check for a __slots__ sequence variable in dict, and count it */
1651 slots = PyDict_GetItemString(dict, "__slots__");
1652 nslots = 0;
Guido van Rossum9676b222001-08-17 20:32:36 +00001653 add_dict = 0;
1654 add_weak = 0;
Guido van Rossumad47da02002-08-12 19:05:44 +00001655 may_add_dict = base->tp_dictoffset == 0;
1656 may_add_weak = base->tp_weaklistoffset == 0 && base->tp_itemsize == 0;
1657 if (slots == NULL) {
1658 if (may_add_dict) {
1659 add_dict++;
1660 }
1661 if (may_add_weak) {
1662 add_weak++;
1663 }
1664 }
1665 else {
1666 /* Have slots */
1667
Tim Peters6d6c1a32001-08-02 04:15:00 +00001668 /* Make it into a tuple */
1669 if (PyString_Check(slots))
Raymond Hettinger8ae46892003-10-12 19:09:37 +00001670 slots = PyTuple_Pack(1, slots);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001671 else
1672 slots = PySequence_Tuple(slots);
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001673 if (slots == NULL) {
1674 Py_DECREF(bases);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001675 return NULL;
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001676 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001677 assert(PyTuple_Check(slots));
1678
1679 /* Are slots allowed? */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001680 nslots = PyTuple_GET_SIZE(slots);
Jeremy Hylton1c7a0ea2003-07-16 16:08:23 +00001681 if (nslots > 0 && base->tp_itemsize != 0) {
Guido van Rossumc4141872001-08-30 04:43:35 +00001682 PyErr_Format(PyExc_TypeError,
1683 "nonempty __slots__ "
1684 "not supported for subtype of '%s'",
1685 base->tp_name);
Guido van Rossumad47da02002-08-12 19:05:44 +00001686 bad_slots:
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001687 Py_DECREF(bases);
Guido van Rossumad47da02002-08-12 19:05:44 +00001688 Py_DECREF(slots);
Guido van Rossumc4141872001-08-30 04:43:35 +00001689 return NULL;
1690 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001691
Martin v. Löwisd919a592002-10-14 21:07:28 +00001692#ifdef Py_USING_UNICODE
1693 tmp = _unicode_to_string(slots, nslots);
Martin v. Löwis13b1a5c2002-10-14 21:11:34 +00001694 if (tmp != slots) {
1695 Py_DECREF(slots);
1696 slots = tmp;
1697 }
Martin v. Löwisd919a592002-10-14 21:07:28 +00001698 if (!tmp)
1699 return NULL;
1700#endif
Guido van Rossumad47da02002-08-12 19:05:44 +00001701 /* Check for valid slot names and two special cases */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001702 for (i = 0; i < nslots; i++) {
Guido van Rossumad47da02002-08-12 19:05:44 +00001703 PyObject *tmp = PyTuple_GET_ITEM(slots, i);
1704 char *s;
1705 if (!valid_identifier(tmp))
1706 goto bad_slots;
1707 assert(PyString_Check(tmp));
1708 s = PyString_AS_STRING(tmp);
1709 if (strcmp(s, "__dict__") == 0) {
1710 if (!may_add_dict || add_dict) {
1711 PyErr_SetString(PyExc_TypeError,
1712 "__dict__ slot disallowed: "
1713 "we already got one");
1714 goto bad_slots;
1715 }
1716 add_dict++;
1717 }
1718 if (strcmp(s, "__weakref__") == 0) {
1719 if (!may_add_weak || add_weak) {
1720 PyErr_SetString(PyExc_TypeError,
1721 "__weakref__ slot disallowed: "
1722 "either we already got one, "
1723 "or __itemsize__ != 0");
1724 goto bad_slots;
1725 }
1726 add_weak++;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001727 }
1728 }
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001729
Guido van Rossumad47da02002-08-12 19:05:44 +00001730 /* Copy slots into yet another tuple, demangling names */
1731 newslots = PyTuple_New(nslots - add_dict - add_weak);
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001732 if (newslots == NULL)
Guido van Rossumad47da02002-08-12 19:05:44 +00001733 goto bad_slots;
1734 for (i = j = 0; i < nslots; i++) {
1735 char *s;
Guido van Rossum8e829202002-08-16 03:47:49 +00001736 char buffer[256];
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001737 tmp = PyTuple_GET_ITEM(slots, i);
Guido van Rossumad47da02002-08-12 19:05:44 +00001738 s = PyString_AS_STRING(tmp);
1739 if ((add_dict && strcmp(s, "__dict__") == 0) ||
1740 (add_weak && strcmp(s, "__weakref__") == 0))
1741 continue;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001742 if (_Py_Mangle(PyString_AS_STRING(name),
Guido van Rossumad47da02002-08-12 19:05:44 +00001743 PyString_AS_STRING(tmp),
1744 buffer, sizeof(buffer)))
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001745 {
1746 tmp = PyString_FromString(buffer);
1747 } else {
1748 Py_INCREF(tmp);
1749 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001750 PyTuple_SET_ITEM(newslots, j, tmp);
1751 j++;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001752 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001753 assert(j == nslots - add_dict - add_weak);
1754 nslots = j;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001755 Py_DECREF(slots);
1756 slots = newslots;
1757
Guido van Rossumad47da02002-08-12 19:05:44 +00001758 /* Secondary bases may provide weakrefs or dict */
1759 if (nbases > 1 &&
1760 ((may_add_dict && !add_dict) ||
1761 (may_add_weak && !add_weak))) {
1762 for (i = 0; i < nbases; i++) {
1763 tmp = PyTuple_GET_ITEM(bases, i);
1764 if (tmp == (PyObject *)base)
1765 continue; /* Skip primary base */
1766 if (PyClass_Check(tmp)) {
1767 /* Classic base class provides both */
1768 if (may_add_dict && !add_dict)
1769 add_dict++;
1770 if (may_add_weak && !add_weak)
1771 add_weak++;
1772 break;
1773 }
1774 assert(PyType_Check(tmp));
1775 tmptype = (PyTypeObject *)tmp;
1776 if (may_add_dict && !add_dict &&
1777 tmptype->tp_dictoffset != 0)
1778 add_dict++;
1779 if (may_add_weak && !add_weak &&
1780 tmptype->tp_weaklistoffset != 0)
1781 add_weak++;
1782 if (may_add_dict && !add_dict)
1783 continue;
1784 if (may_add_weak && !add_weak)
1785 continue;
1786 /* Nothing more to check */
1787 break;
1788 }
1789 }
Guido van Rossum9676b222001-08-17 20:32:36 +00001790 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001791
1792 /* XXX From here until type is safely allocated,
1793 "return NULL" may leak slots! */
1794
1795 /* Allocate the type object */
1796 type = (PyTypeObject *)metatype->tp_alloc(metatype, nslots);
Guido van Rossumad47da02002-08-12 19:05:44 +00001797 if (type == NULL) {
1798 Py_XDECREF(slots);
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001799 Py_DECREF(bases);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001800 return NULL;
Guido van Rossumad47da02002-08-12 19:05:44 +00001801 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001802
1803 /* Keep name and slots alive in the extended type object */
Guido van Rossume5c691a2003-03-07 15:13:17 +00001804 et = (PyHeapTypeObject *)type;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001805 Py_INCREF(name);
1806 et->name = name;
1807 et->slots = slots;
1808
Guido van Rossumdc91b992001-08-08 22:26:22 +00001809 /* Initialize tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001810 type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE |
1811 Py_TPFLAGS_BASETYPE;
Guido van Rossum048eb752001-10-02 21:24:57 +00001812 if (base->tp_flags & Py_TPFLAGS_HAVE_GC)
1813 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossumdc91b992001-08-08 22:26:22 +00001814
1815 /* It's a new-style number unless it specifically inherits any
1816 old-style numeric behavior */
1817 if ((base->tp_flags & Py_TPFLAGS_CHECKTYPES) ||
1818 (base->tp_as_number == NULL))
1819 type->tp_flags |= Py_TPFLAGS_CHECKTYPES;
1820
1821 /* Initialize essential fields */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001822 type->tp_as_number = &et->as_number;
1823 type->tp_as_sequence = &et->as_sequence;
1824 type->tp_as_mapping = &et->as_mapping;
1825 type->tp_as_buffer = &et->as_buffer;
1826 type->tp_name = PyString_AS_STRING(name);
1827
1828 /* Set tp_base and tp_bases */
1829 type->tp_bases = bases;
1830 Py_INCREF(base);
1831 type->tp_base = base;
1832
Guido van Rossum687ae002001-10-15 22:03:32 +00001833 /* Initialize tp_dict from passed-in dict */
1834 type->tp_dict = dict = PyDict_Copy(dict);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001835 if (dict == NULL) {
1836 Py_DECREF(type);
1837 return NULL;
1838 }
1839
Guido van Rossumc3542212001-08-16 09:18:56 +00001840 /* Set __module__ in the dict */
1841 if (PyDict_GetItemString(dict, "__module__") == NULL) {
1842 tmp = PyEval_GetGlobals();
1843 if (tmp != NULL) {
1844 tmp = PyDict_GetItemString(tmp, "__name__");
1845 if (tmp != NULL) {
1846 if (PyDict_SetItemString(dict, "__module__",
1847 tmp) < 0)
1848 return NULL;
1849 }
1850 }
1851 }
1852
Tim Peters2f93e282001-10-04 05:27:00 +00001853 /* Set tp_doc to a copy of dict['__doc__'], if the latter is there
Tim Peters24008312002-03-17 18:56:20 +00001854 and is a string. The __doc__ accessor will first look for tp_doc;
1855 if that fails, it will still look into __dict__.
Tim Peters2f93e282001-10-04 05:27:00 +00001856 */
1857 {
1858 PyObject *doc = PyDict_GetItemString(dict, "__doc__");
1859 if (doc != NULL && PyString_Check(doc)) {
1860 const size_t n = (size_t)PyString_GET_SIZE(doc);
Tim Peters59f809d2001-10-04 05:43:02 +00001861 type->tp_doc = (char *)PyObject_MALLOC(n+1);
Tim Peters2f93e282001-10-04 05:27:00 +00001862 if (type->tp_doc == NULL) {
1863 Py_DECREF(type);
1864 return NULL;
1865 }
1866 memcpy(type->tp_doc, PyString_AS_STRING(doc), n+1);
1867 }
1868 }
1869
Tim Peters6d6c1a32001-08-02 04:15:00 +00001870 /* Special-case __new__: if it's a plain function,
1871 make it a static function */
1872 tmp = PyDict_GetItemString(dict, "__new__");
1873 if (tmp != NULL && PyFunction_Check(tmp)) {
1874 tmp = PyStaticMethod_New(tmp);
1875 if (tmp == NULL) {
1876 Py_DECREF(type);
1877 return NULL;
1878 }
1879 PyDict_SetItemString(dict, "__new__", tmp);
1880 Py_DECREF(tmp);
1881 }
1882
1883 /* Add descriptors for custom slots from __slots__, or for __dict__ */
Guido van Rossume5c691a2003-03-07 15:13:17 +00001884 mp = PyHeapType_GET_MEMBERS(et);
Neil Schemenauerc806c882001-08-29 23:54:54 +00001885 slotoffset = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001886 if (slots != NULL) {
1887 for (i = 0; i < nslots; i++, mp++) {
1888 mp->name = PyString_AS_STRING(
1889 PyTuple_GET_ITEM(slots, i));
Guido van Rossum64b206c2001-12-04 17:13:22 +00001890 mp->type = T_OBJECT_EX;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001891 mp->offset = slotoffset;
Guido van Rossum9676b222001-08-17 20:32:36 +00001892 if (base->tp_weaklistoffset == 0 &&
Guido van Rossum64b206c2001-12-04 17:13:22 +00001893 strcmp(mp->name, "__weakref__") == 0) {
Guido van Rossumad47da02002-08-12 19:05:44 +00001894 add_weak++;
Guido van Rossum64b206c2001-12-04 17:13:22 +00001895 mp->type = T_OBJECT;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001896 mp->flags = READONLY;
Guido van Rossum9676b222001-08-17 20:32:36 +00001897 type->tp_weaklistoffset = slotoffset;
Guido van Rossum64b206c2001-12-04 17:13:22 +00001898 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001899 slotoffset += sizeof(PyObject *);
1900 }
1901 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001902 if (add_dict) {
1903 if (base->tp_itemsize)
1904 type->tp_dictoffset = -(long)sizeof(PyObject *);
1905 else
1906 type->tp_dictoffset = slotoffset;
1907 slotoffset += sizeof(PyObject *);
1908 }
1909 if (add_weak) {
1910 assert(!base->tp_itemsize);
1911 type->tp_weaklistoffset = slotoffset;
1912 slotoffset += sizeof(PyObject *);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001913 }
1914 type->tp_basicsize = slotoffset;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001915 type->tp_itemsize = base->tp_itemsize;
Guido van Rossume5c691a2003-03-07 15:13:17 +00001916 type->tp_members = PyHeapType_GET_MEMBERS(et);
Guido van Rossum373c7412003-01-07 13:41:37 +00001917
1918 if (type->tp_weaklistoffset && type->tp_dictoffset)
1919 type->tp_getset = subtype_getsets_full;
1920 else if (type->tp_weaklistoffset && !type->tp_dictoffset)
1921 type->tp_getset = subtype_getsets_weakref_only;
1922 else if (!type->tp_weaklistoffset && type->tp_dictoffset)
1923 type->tp_getset = subtype_getsets_dict_only;
1924 else
1925 type->tp_getset = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001926
1927 /* Special case some slots */
1928 if (type->tp_dictoffset != 0 || nslots > 0) {
1929 if (base->tp_getattr == NULL && base->tp_getattro == NULL)
1930 type->tp_getattro = PyObject_GenericGetAttr;
1931 if (base->tp_setattr == NULL && base->tp_setattro == NULL)
1932 type->tp_setattro = PyObject_GenericSetAttr;
1933 }
1934 type->tp_dealloc = subtype_dealloc;
1935
Guido van Rossum9475a232001-10-05 20:51:39 +00001936 /* Enable GC unless there are really no instance variables possible */
1937 if (!(type->tp_basicsize == sizeof(PyObject) &&
1938 type->tp_itemsize == 0))
1939 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
1940
Tim Peters6d6c1a32001-08-02 04:15:00 +00001941 /* Always override allocation strategy to use regular heap */
1942 type->tp_alloc = PyType_GenericAlloc;
Guido van Rossum048eb752001-10-02 21:24:57 +00001943 if (type->tp_flags & Py_TPFLAGS_HAVE_GC) {
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00001944 type->tp_free = PyObject_GC_Del;
Guido van Rossum9475a232001-10-05 20:51:39 +00001945 type->tp_traverse = subtype_traverse;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001946 type->tp_clear = subtype_clear;
Guido van Rossum048eb752001-10-02 21:24:57 +00001947 }
1948 else
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00001949 type->tp_free = PyObject_Del;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001950
1951 /* Initialize the rest */
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001952 if (PyType_Ready(type) < 0) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001953 Py_DECREF(type);
1954 return NULL;
1955 }
1956
Guido van Rossum7b9144b2001-10-09 19:39:46 +00001957 /* Put the proper slots in place */
1958 fixup_slot_dispatchers(type);
Guido van Rossumf040ede2001-08-07 16:40:56 +00001959
Tim Peters6d6c1a32001-08-02 04:15:00 +00001960 return (PyObject *)type;
1961}
1962
1963/* Internal API to look for a name through the MRO.
1964 This returns a borrowed reference, and doesn't set an exception! */
1965PyObject *
1966_PyType_Lookup(PyTypeObject *type, PyObject *name)
1967{
1968 int i, n;
Tim Petersa91e9642001-11-14 23:32:33 +00001969 PyObject *mro, *res, *base, *dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001970
Guido van Rossum687ae002001-10-15 22:03:32 +00001971 /* Look in tp_dict of types in MRO */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001972 mro = type->tp_mro;
Guido van Rossum23094982002-06-10 14:30:43 +00001973
1974 /* If mro is NULL, the type is either not yet initialized
1975 by PyType_Ready(), or already cleared by type_clear().
1976 Either way the safest thing to do is to return NULL. */
1977 if (mro == NULL)
1978 return NULL;
1979
Tim Peters6d6c1a32001-08-02 04:15:00 +00001980 assert(PyTuple_Check(mro));
1981 n = PyTuple_GET_SIZE(mro);
1982 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00001983 base = PyTuple_GET_ITEM(mro, i);
1984 if (PyClass_Check(base))
1985 dict = ((PyClassObject *)base)->cl_dict;
1986 else {
1987 assert(PyType_Check(base));
1988 dict = ((PyTypeObject *)base)->tp_dict;
1989 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001990 assert(dict && PyDict_Check(dict));
1991 res = PyDict_GetItem(dict, name);
1992 if (res != NULL)
1993 return res;
1994 }
1995 return NULL;
1996}
1997
1998/* This is similar to PyObject_GenericGetAttr(),
1999 but uses _PyType_Lookup() instead of just looking in type->tp_dict. */
2000static PyObject *
2001type_getattro(PyTypeObject *type, PyObject *name)
2002{
2003 PyTypeObject *metatype = type->ob_type;
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002004 PyObject *meta_attribute, *attribute;
2005 descrgetfunc meta_get;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002006
2007 /* Initialize this type (we'll assume the metatype is initialized) */
2008 if (type->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00002009 if (PyType_Ready(type) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002010 return NULL;
2011 }
2012
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002013 /* No readable descriptor found yet */
2014 meta_get = NULL;
Tim Peters34592512002-07-11 06:23:50 +00002015
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002016 /* Look for the attribute in the metatype */
2017 meta_attribute = _PyType_Lookup(metatype, name);
2018
2019 if (meta_attribute != NULL) {
2020 meta_get = meta_attribute->ob_type->tp_descr_get;
Tim Peters34592512002-07-11 06:23:50 +00002021
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002022 if (meta_get != NULL && PyDescr_IsData(meta_attribute)) {
2023 /* Data descriptors implement tp_descr_set to intercept
2024 * writes. Assume the attribute is not overridden in
2025 * type's tp_dict (and bases): call the descriptor now.
2026 */
2027 return meta_get(meta_attribute, (PyObject *)type,
2028 (PyObject *)metatype);
2029 }
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00002030 Py_INCREF(meta_attribute);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002031 }
2032
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002033 /* No data descriptor found on metatype. Look in tp_dict of this
2034 * type and its bases */
2035 attribute = _PyType_Lookup(type, name);
2036 if (attribute != NULL) {
2037 /* Implement descriptor functionality, if any */
2038 descrgetfunc local_get = attribute->ob_type->tp_descr_get;
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00002039
2040 Py_XDECREF(meta_attribute);
2041
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002042 if (local_get != NULL) {
2043 /* NULL 2nd argument indicates the descriptor was
2044 * found on the target object itself (or a base) */
2045 return local_get(attribute, (PyObject *)NULL,
2046 (PyObject *)type);
2047 }
Tim Peters34592512002-07-11 06:23:50 +00002048
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002049 Py_INCREF(attribute);
2050 return attribute;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002051 }
2052
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002053 /* No attribute found in local __dict__ (or bases): use the
2054 * descriptor from the metatype, if any */
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00002055 if (meta_get != NULL) {
2056 PyObject *res;
2057 res = meta_get(meta_attribute, (PyObject *)type,
2058 (PyObject *)metatype);
2059 Py_DECREF(meta_attribute);
2060 return res;
2061 }
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002062
2063 /* If an ordinary attribute was found on the metatype, return it now */
2064 if (meta_attribute != NULL) {
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002065 return meta_attribute;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002066 }
2067
2068 /* Give up */
2069 PyErr_Format(PyExc_AttributeError,
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002070 "type object '%.50s' has no attribute '%.400s'",
2071 type->tp_name, PyString_AS_STRING(name));
Tim Peters6d6c1a32001-08-02 04:15:00 +00002072 return NULL;
2073}
2074
2075static int
2076type_setattro(PyTypeObject *type, PyObject *name, PyObject *value)
2077{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002078 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
2079 PyErr_Format(
2080 PyExc_TypeError,
2081 "can't set attributes of built-in/extension type '%s'",
2082 type->tp_name);
2083 return -1;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002084 }
Guido van Rossum8d24ee92003-03-24 23:49:49 +00002085 /* XXX Example of how I expect this to be used...
2086 if (update_subclasses(type, name, invalidate_cache, NULL) < 0)
2087 return -1;
2088 */
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002089 if (PyObject_GenericSetAttr((PyObject *)type, name, value) < 0)
2090 return -1;
2091 return update_slot(type, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002092}
2093
2094static void
2095type_dealloc(PyTypeObject *type)
2096{
Guido van Rossume5c691a2003-03-07 15:13:17 +00002097 PyHeapTypeObject *et;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002098
2099 /* Assert this is a heap-allocated type object */
2100 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002101 _PyObject_GC_UNTRACK(type);
Guido van Rossum1c450732001-10-08 15:18:27 +00002102 PyObject_ClearWeakRefs((PyObject *)type);
Guido van Rossume5c691a2003-03-07 15:13:17 +00002103 et = (PyHeapTypeObject *)type;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002104 Py_XDECREF(type->tp_base);
2105 Py_XDECREF(type->tp_dict);
2106 Py_XDECREF(type->tp_bases);
2107 Py_XDECREF(type->tp_mro);
Guido van Rossum687ae002001-10-15 22:03:32 +00002108 Py_XDECREF(type->tp_cache);
Guido van Rossum1c450732001-10-08 15:18:27 +00002109 Py_XDECREF(type->tp_subclasses);
Neal Norwitzcee5ca02002-07-30 00:42:06 +00002110 PyObject_Free(type->tp_doc);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002111 Py_XDECREF(et->name);
2112 Py_XDECREF(et->slots);
2113 type->ob_type->tp_free((PyObject *)type);
2114}
2115
Guido van Rossum1c450732001-10-08 15:18:27 +00002116static PyObject *
2117type_subclasses(PyTypeObject *type, PyObject *args_ignored)
2118{
2119 PyObject *list, *raw, *ref;
2120 int i, n;
2121
2122 list = PyList_New(0);
2123 if (list == NULL)
2124 return NULL;
2125 raw = type->tp_subclasses;
2126 if (raw == NULL)
2127 return list;
2128 assert(PyList_Check(raw));
2129 n = PyList_GET_SIZE(raw);
2130 for (i = 0; i < n; i++) {
2131 ref = PyList_GET_ITEM(raw, i);
Tim Peters44383382001-10-08 16:49:26 +00002132 assert(PyWeakref_CheckRef(ref));
Guido van Rossum1c450732001-10-08 15:18:27 +00002133 ref = PyWeakref_GET_OBJECT(ref);
2134 if (ref != Py_None) {
2135 if (PyList_Append(list, ref) < 0) {
2136 Py_DECREF(list);
2137 return NULL;
2138 }
2139 }
2140 }
2141 return list;
2142}
2143
Tim Peters6d6c1a32001-08-02 04:15:00 +00002144static PyMethodDef type_methods[] = {
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002145 {"mro", (PyCFunction)mro_external, METH_NOARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002146 PyDoc_STR("mro() -> list\nreturn a type's method resolution order")},
Guido van Rossum1c450732001-10-08 15:18:27 +00002147 {"__subclasses__", (PyCFunction)type_subclasses, METH_NOARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002148 PyDoc_STR("__subclasses__() -> list of immediate subclasses")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002149 {0}
2150};
2151
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002152PyDoc_STRVAR(type_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00002153"type(object) -> the object's type\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002154"type(name, bases, dict) -> a new type");
Tim Peters6d6c1a32001-08-02 04:15:00 +00002155
Guido van Rossum048eb752001-10-02 21:24:57 +00002156static int
2157type_traverse(PyTypeObject *type, visitproc visit, void *arg)
2158{
Guido van Rossum048eb752001-10-02 21:24:57 +00002159 int err;
2160
Guido van Rossuma3862092002-06-10 15:24:42 +00002161 /* Because of type_is_gc(), the collector only calls this
2162 for heaptypes. */
2163 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002164
2165#define VISIT(SLOT) \
2166 if (SLOT) { \
2167 err = visit((PyObject *)(SLOT), arg); \
2168 if (err) \
2169 return err; \
2170 }
2171
2172 VISIT(type->tp_dict);
Guido van Rossum687ae002001-10-15 22:03:32 +00002173 VISIT(type->tp_cache);
Guido van Rossum048eb752001-10-02 21:24:57 +00002174 VISIT(type->tp_mro);
2175 VISIT(type->tp_bases);
2176 VISIT(type->tp_base);
Guido van Rossuma3862092002-06-10 15:24:42 +00002177
2178 /* There's no need to visit type->tp_subclasses or
Guido van Rossume5c691a2003-03-07 15:13:17 +00002179 ((PyHeapTypeObject *)type)->slots, because they can't be involved
Guido van Rossuma3862092002-06-10 15:24:42 +00002180 in cycles; tp_subclasses is a list of weak references,
2181 and slots is a tuple of strings. */
Guido van Rossum048eb752001-10-02 21:24:57 +00002182
2183#undef VISIT
2184
2185 return 0;
2186}
2187
2188static int
2189type_clear(PyTypeObject *type)
2190{
Guido van Rossum048eb752001-10-02 21:24:57 +00002191 PyObject *tmp;
2192
Guido van Rossuma3862092002-06-10 15:24:42 +00002193 /* Because of type_is_gc(), the collector only calls this
2194 for heaptypes. */
2195 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002196
2197#define CLEAR(SLOT) \
2198 if (SLOT) { \
2199 tmp = (PyObject *)(SLOT); \
2200 SLOT = NULL; \
2201 Py_DECREF(tmp); \
2202 }
2203
Guido van Rossuma3862092002-06-10 15:24:42 +00002204 /* The only field we need to clear is tp_mro, which is part of a
2205 hard cycle (its first element is the class itself) that won't
2206 be broken otherwise (it's a tuple and tuples don't have a
2207 tp_clear handler). None of the other fields need to be
2208 cleared, and here's why:
Guido van Rossum048eb752001-10-02 21:24:57 +00002209
Guido van Rossuma3862092002-06-10 15:24:42 +00002210 tp_dict:
2211 It is a dict, so the collector will call its tp_clear.
2212
2213 tp_cache:
2214 Not used; if it were, it would be a dict.
2215
2216 tp_bases, tp_base:
2217 If these are involved in a cycle, there must be at least
2218 one other, mutable object in the cycle, e.g. a base
2219 class's dict; the cycle will be broken that way.
2220
2221 tp_subclasses:
2222 A list of weak references can't be part of a cycle; and
2223 lists have their own tp_clear.
2224
Guido van Rossume5c691a2003-03-07 15:13:17 +00002225 slots (in PyHeapTypeObject):
Guido van Rossuma3862092002-06-10 15:24:42 +00002226 A tuple of strings can't be part of a cycle.
2227 */
2228
2229 CLEAR(type->tp_mro);
Tim Peters2f93e282001-10-04 05:27:00 +00002230
Guido van Rossum048eb752001-10-02 21:24:57 +00002231#undef CLEAR
2232
2233 return 0;
2234}
2235
2236static int
2237type_is_gc(PyTypeObject *type)
2238{
2239 return type->tp_flags & Py_TPFLAGS_HEAPTYPE;
2240}
2241
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002242PyTypeObject PyType_Type = {
2243 PyObject_HEAD_INIT(&PyType_Type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002244 0, /* ob_size */
2245 "type", /* tp_name */
Guido van Rossume5c691a2003-03-07 15:13:17 +00002246 sizeof(PyHeapTypeObject), /* tp_basicsize */
Guido van Rossum6f799372001-09-20 20:46:19 +00002247 sizeof(PyMemberDef), /* tp_itemsize */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002248 (destructor)type_dealloc, /* tp_dealloc */
2249 0, /* tp_print */
2250 0, /* tp_getattr */
2251 0, /* tp_setattr */
2252 type_compare, /* tp_compare */
2253 (reprfunc)type_repr, /* tp_repr */
2254 0, /* tp_as_number */
2255 0, /* tp_as_sequence */
2256 0, /* tp_as_mapping */
2257 (hashfunc)_Py_HashPointer, /* tp_hash */
2258 (ternaryfunc)type_call, /* tp_call */
2259 0, /* tp_str */
2260 (getattrofunc)type_getattro, /* tp_getattro */
2261 (setattrofunc)type_setattro, /* tp_setattro */
2262 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00002263 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
2264 Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002265 type_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00002266 (traverseproc)type_traverse, /* tp_traverse */
2267 (inquiry)type_clear, /* tp_clear */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002268 0, /* tp_richcompare */
Guido van Rossum1c450732001-10-08 15:18:27 +00002269 offsetof(PyTypeObject, tp_weaklist), /* tp_weaklistoffset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002270 0, /* tp_iter */
2271 0, /* tp_iternext */
2272 type_methods, /* tp_methods */
2273 type_members, /* tp_members */
2274 type_getsets, /* tp_getset */
2275 0, /* tp_base */
2276 0, /* tp_dict */
2277 0, /* tp_descr_get */
2278 0, /* tp_descr_set */
2279 offsetof(PyTypeObject, tp_dict), /* tp_dictoffset */
2280 0, /* tp_init */
2281 0, /* tp_alloc */
2282 type_new, /* tp_new */
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00002283 PyObject_GC_Del, /* tp_free */
Guido van Rossum048eb752001-10-02 21:24:57 +00002284 (inquiry)type_is_gc, /* tp_is_gc */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002285};
Tim Peters6d6c1a32001-08-02 04:15:00 +00002286
2287
2288/* The base type of all types (eventually)... except itself. */
2289
2290static int
2291object_init(PyObject *self, PyObject *args, PyObject *kwds)
2292{
2293 return 0;
2294}
2295
Guido van Rossum298e4212003-02-13 16:30:16 +00002296/* If we don't have a tp_new for a new-style class, new will use this one.
2297 Therefore this should take no arguments/keywords. However, this new may
2298 also be inherited by objects that define a tp_init but no tp_new. These
2299 objects WILL pass argumets to tp_new, because it gets the same args as
2300 tp_init. So only allow arguments if we aren't using the default init, in
2301 which case we expect init to handle argument parsing. */
2302static PyObject *
2303object_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2304{
2305 if (type->tp_init == object_init && (PyTuple_GET_SIZE(args) ||
2306 (kwds && PyDict_Check(kwds) && PyDict_Size(kwds)))) {
2307 PyErr_SetString(PyExc_TypeError,
2308 "default __new__ takes no parameters");
2309 return NULL;
2310 }
2311 return type->tp_alloc(type, 0);
2312}
2313
Tim Peters6d6c1a32001-08-02 04:15:00 +00002314static void
2315object_dealloc(PyObject *self)
2316{
2317 self->ob_type->tp_free(self);
2318}
2319
Guido van Rossum8e248182001-08-12 05:17:56 +00002320static PyObject *
2321object_repr(PyObject *self)
2322{
Guido van Rossum76e69632001-08-16 18:52:43 +00002323 PyTypeObject *type;
Barry Warsaw7ce36942001-08-24 18:34:26 +00002324 PyObject *mod, *name, *rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00002325
Guido van Rossum76e69632001-08-16 18:52:43 +00002326 type = self->ob_type;
2327 mod = type_module(type, NULL);
2328 if (mod == NULL)
2329 PyErr_Clear();
2330 else if (!PyString_Check(mod)) {
2331 Py_DECREF(mod);
2332 mod = NULL;
2333 }
2334 name = type_name(type, NULL);
2335 if (name == NULL)
2336 return NULL;
2337 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__"))
Guido van Rossumff0e6d62001-09-24 16:03:59 +00002338 rtn = PyString_FromFormat("<%s.%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00002339 PyString_AS_STRING(mod),
2340 PyString_AS_STRING(name),
2341 self);
Guido van Rossum76e69632001-08-16 18:52:43 +00002342 else
Guido van Rossumff0e6d62001-09-24 16:03:59 +00002343 rtn = PyString_FromFormat("<%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00002344 type->tp_name, self);
Guido van Rossum76e69632001-08-16 18:52:43 +00002345 Py_XDECREF(mod);
2346 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +00002347 return rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00002348}
2349
Guido van Rossumb8f63662001-08-15 23:57:02 +00002350static PyObject *
2351object_str(PyObject *self)
2352{
2353 unaryfunc f;
2354
2355 f = self->ob_type->tp_repr;
2356 if (f == NULL)
2357 f = object_repr;
2358 return f(self);
2359}
2360
Guido van Rossum8e248182001-08-12 05:17:56 +00002361static long
2362object_hash(PyObject *self)
2363{
2364 return _Py_HashPointer(self);
2365}
Guido van Rossum8e248182001-08-12 05:17:56 +00002366
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002367static PyObject *
2368object_get_class(PyObject *self, void *closure)
2369{
2370 Py_INCREF(self->ob_type);
2371 return (PyObject *)(self->ob_type);
2372}
2373
2374static int
2375equiv_structs(PyTypeObject *a, PyTypeObject *b)
2376{
2377 return a == b ||
2378 (a != NULL &&
2379 b != NULL &&
2380 a->tp_basicsize == b->tp_basicsize &&
2381 a->tp_itemsize == b->tp_itemsize &&
2382 a->tp_dictoffset == b->tp_dictoffset &&
2383 a->tp_weaklistoffset == b->tp_weaklistoffset &&
2384 ((a->tp_flags & Py_TPFLAGS_HAVE_GC) ==
2385 (b->tp_flags & Py_TPFLAGS_HAVE_GC)));
2386}
2387
2388static int
2389same_slots_added(PyTypeObject *a, PyTypeObject *b)
2390{
2391 PyTypeObject *base = a->tp_base;
2392 int size;
2393
2394 if (base != b->tp_base)
2395 return 0;
2396 if (equiv_structs(a, base) && equiv_structs(b, base))
2397 return 1;
2398 size = base->tp_basicsize;
2399 if (a->tp_dictoffset == size && b->tp_dictoffset == size)
2400 size += sizeof(PyObject *);
2401 if (a->tp_weaklistoffset == size && b->tp_weaklistoffset == size)
2402 size += sizeof(PyObject *);
2403 return size == a->tp_basicsize && size == b->tp_basicsize;
2404}
2405
2406static int
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002407compatible_for_assignment(PyTypeObject* old, PyTypeObject* new, char* attr)
2408{
2409 PyTypeObject *newbase, *oldbase;
2410
2411 if (new->tp_dealloc != old->tp_dealloc ||
2412 new->tp_free != old->tp_free)
2413 {
2414 PyErr_Format(PyExc_TypeError,
2415 "%s assignment: "
2416 "'%s' deallocator differs from '%s'",
2417 attr,
2418 new->tp_name,
2419 old->tp_name);
2420 return 0;
2421 }
2422 newbase = new;
2423 oldbase = old;
2424 while (equiv_structs(newbase, newbase->tp_base))
2425 newbase = newbase->tp_base;
2426 while (equiv_structs(oldbase, oldbase->tp_base))
2427 oldbase = oldbase->tp_base;
2428 if (newbase != oldbase &&
2429 (newbase->tp_base != oldbase->tp_base ||
2430 !same_slots_added(newbase, oldbase))) {
2431 PyErr_Format(PyExc_TypeError,
2432 "%s assignment: "
2433 "'%s' object layout differs from '%s'",
2434 attr,
2435 new->tp_name,
2436 old->tp_name);
2437 return 0;
2438 }
Tim Petersea7f75d2002-12-07 21:39:16 +00002439
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002440 return 1;
2441}
2442
2443static int
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002444object_set_class(PyObject *self, PyObject *value, void *closure)
2445{
2446 PyTypeObject *old = self->ob_type;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002447 PyTypeObject *new;
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002448
Guido van Rossumb6b89422002-04-15 01:03:30 +00002449 if (value == NULL) {
2450 PyErr_SetString(PyExc_TypeError,
2451 "can't delete __class__ attribute");
2452 return -1;
2453 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002454 if (!PyType_Check(value)) {
2455 PyErr_Format(PyExc_TypeError,
2456 "__class__ must be set to new-style class, not '%s' object",
2457 value->ob_type->tp_name);
2458 return -1;
2459 }
2460 new = (PyTypeObject *)value;
Guido van Rossum40af8892002-08-10 05:42:07 +00002461 if (!(new->tp_flags & Py_TPFLAGS_HEAPTYPE) ||
2462 !(old->tp_flags & Py_TPFLAGS_HEAPTYPE))
2463 {
2464 PyErr_Format(PyExc_TypeError,
2465 "__class__ assignment: only for heap types");
2466 return -1;
2467 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002468 if (compatible_for_assignment(new, old, "__class__")) {
2469 Py_INCREF(new);
2470 self->ob_type = new;
2471 Py_DECREF(old);
2472 return 0;
2473 }
2474 else {
Guido van Rossum9ee4b942002-05-24 18:47:47 +00002475 return -1;
2476 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002477}
2478
2479static PyGetSetDef object_getsets[] = {
2480 {"__class__", object_get_class, object_set_class,
Neal Norwitz858e34f2002-08-13 17:18:45 +00002481 PyDoc_STR("the object's class")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002482 {0}
2483};
2484
Guido van Rossumc53f0092003-02-18 22:05:12 +00002485
Guido van Rossum036f9992003-02-21 22:02:54 +00002486/* Stuff to implement __reduce_ex__ for pickle protocols >= 2.
2487 We fall back to helpers in copy_reg for:
2488 - pickle protocols < 2
2489 - calculating the list of slot names (done only once per class)
2490 - the __newobj__ function (which is used as a token but never called)
2491*/
2492
2493static PyObject *
2494import_copy_reg(void)
2495{
2496 static PyObject *copy_reg_str;
Guido van Rossum3926a632001-09-25 16:25:58 +00002497
2498 if (!copy_reg_str) {
2499 copy_reg_str = PyString_InternFromString("copy_reg");
2500 if (copy_reg_str == NULL)
2501 return NULL;
2502 }
Guido van Rossum036f9992003-02-21 22:02:54 +00002503
2504 return PyImport_Import(copy_reg_str);
2505}
2506
2507static PyObject *
2508slotnames(PyObject *cls)
2509{
2510 PyObject *clsdict;
2511 PyObject *copy_reg;
2512 PyObject *slotnames;
2513
2514 if (!PyType_Check(cls)) {
2515 Py_INCREF(Py_None);
2516 return Py_None;
2517 }
2518
2519 clsdict = ((PyTypeObject *)cls)->tp_dict;
2520 slotnames = PyDict_GetItemString(clsdict, "__slotnames__");
2521 if (slotnames != NULL) {
2522 Py_INCREF(slotnames);
2523 return slotnames;
2524 }
2525
2526 copy_reg = import_copy_reg();
2527 if (copy_reg == NULL)
2528 return NULL;
2529
2530 slotnames = PyObject_CallMethod(copy_reg, "_slotnames", "O", cls);
2531 Py_DECREF(copy_reg);
2532 if (slotnames != NULL &&
2533 slotnames != Py_None &&
2534 !PyList_Check(slotnames))
2535 {
2536 PyErr_SetString(PyExc_TypeError,
2537 "copy_reg._slotnames didn't return a list or None");
2538 Py_DECREF(slotnames);
2539 slotnames = NULL;
2540 }
2541
2542 return slotnames;
2543}
2544
2545static PyObject *
2546reduce_2(PyObject *obj)
2547{
2548 PyObject *cls, *getnewargs;
2549 PyObject *args = NULL, *args2 = NULL;
2550 PyObject *getstate = NULL, *state = NULL, *names = NULL;
2551 PyObject *slots = NULL, *listitems = NULL, *dictitems = NULL;
2552 PyObject *copy_reg = NULL, *newobj = NULL, *res = NULL;
2553 int i, n;
2554
2555 cls = PyObject_GetAttrString(obj, "__class__");
2556 if (cls == NULL)
2557 return NULL;
2558
2559 getnewargs = PyObject_GetAttrString(obj, "__getnewargs__");
2560 if (getnewargs != NULL) {
2561 args = PyObject_CallObject(getnewargs, NULL);
2562 Py_DECREF(getnewargs);
2563 if (args != NULL && !PyTuple_Check(args)) {
2564 PyErr_SetString(PyExc_TypeError,
2565 "__getnewargs__ should return a tuple");
2566 goto end;
2567 }
2568 }
2569 else {
2570 PyErr_Clear();
2571 args = PyTuple_New(0);
2572 }
2573 if (args == NULL)
2574 goto end;
2575
2576 getstate = PyObject_GetAttrString(obj, "__getstate__");
2577 if (getstate != NULL) {
2578 state = PyObject_CallObject(getstate, NULL);
2579 Py_DECREF(getstate);
Neal Norwitze2fdc612003-06-08 13:19:58 +00002580 if (state == NULL)
2581 goto end;
Guido van Rossum036f9992003-02-21 22:02:54 +00002582 }
2583 else {
Jim Fulton8a1a5942004-02-08 04:21:26 +00002584 PyErr_Clear();
Guido van Rossum036f9992003-02-21 22:02:54 +00002585 state = PyObject_GetAttrString(obj, "__dict__");
2586 if (state == NULL) {
2587 PyErr_Clear();
2588 state = Py_None;
2589 Py_INCREF(state);
2590 }
2591 names = slotnames(cls);
2592 if (names == NULL)
2593 goto end;
2594 if (names != Py_None) {
2595 assert(PyList_Check(names));
2596 slots = PyDict_New();
2597 if (slots == NULL)
2598 goto end;
2599 n = 0;
2600 /* Can't pre-compute the list size; the list
2601 is stored on the class so accessible to other
2602 threads, which may be run by DECREF */
2603 for (i = 0; i < PyList_GET_SIZE(names); i++) {
2604 PyObject *name, *value;
2605 name = PyList_GET_ITEM(names, i);
2606 value = PyObject_GetAttr(obj, name);
2607 if (value == NULL)
2608 PyErr_Clear();
2609 else {
2610 int err = PyDict_SetItem(slots, name,
2611 value);
2612 Py_DECREF(value);
2613 if (err)
2614 goto end;
2615 n++;
2616 }
2617 }
2618 if (n) {
2619 state = Py_BuildValue("(NO)", state, slots);
2620 if (state == NULL)
2621 goto end;
2622 }
2623 }
2624 }
2625
2626 if (!PyList_Check(obj)) {
2627 listitems = Py_None;
2628 Py_INCREF(listitems);
2629 }
2630 else {
2631 listitems = PyObject_GetIter(obj);
2632 if (listitems == NULL)
2633 goto end;
2634 }
2635
2636 if (!PyDict_Check(obj)) {
2637 dictitems = Py_None;
2638 Py_INCREF(dictitems);
2639 }
2640 else {
2641 dictitems = PyObject_CallMethod(obj, "iteritems", "");
2642 if (dictitems == NULL)
2643 goto end;
2644 }
2645
2646 copy_reg = import_copy_reg();
2647 if (copy_reg == NULL)
2648 goto end;
2649 newobj = PyObject_GetAttrString(copy_reg, "__newobj__");
2650 if (newobj == NULL)
2651 goto end;
2652
2653 n = PyTuple_GET_SIZE(args);
2654 args2 = PyTuple_New(n+1);
2655 if (args2 == NULL)
2656 goto end;
2657 PyTuple_SET_ITEM(args2, 0, cls);
2658 cls = NULL;
2659 for (i = 0; i < n; i++) {
2660 PyObject *v = PyTuple_GET_ITEM(args, i);
2661 Py_INCREF(v);
2662 PyTuple_SET_ITEM(args2, i+1, v);
2663 }
2664
Raymond Hettinger8ae46892003-10-12 19:09:37 +00002665 res = PyTuple_Pack(5, newobj, args2, state, listitems, dictitems);
Guido van Rossum036f9992003-02-21 22:02:54 +00002666
2667 end:
2668 Py_XDECREF(cls);
2669 Py_XDECREF(args);
2670 Py_XDECREF(args2);
Jeremy Hyltond06483c2003-04-09 21:01:42 +00002671 Py_XDECREF(slots);
Guido van Rossum036f9992003-02-21 22:02:54 +00002672 Py_XDECREF(state);
2673 Py_XDECREF(names);
2674 Py_XDECREF(listitems);
2675 Py_XDECREF(dictitems);
2676 Py_XDECREF(copy_reg);
2677 Py_XDECREF(newobj);
2678 return res;
2679}
2680
2681static PyObject *
2682object_reduce_ex(PyObject *self, PyObject *args)
2683{
2684 /* Call copy_reg._reduce_ex(self, proto) */
2685 PyObject *reduce, *copy_reg, *res;
2686 int proto = 0;
2687
2688 if (!PyArg_ParseTuple(args, "|i:__reduce_ex__", &proto))
2689 return NULL;
2690
2691 reduce = PyObject_GetAttrString(self, "__reduce__");
2692 if (reduce == NULL)
2693 PyErr_Clear();
2694 else {
2695 PyObject *cls, *clsreduce, *objreduce;
2696 int override;
2697 cls = PyObject_GetAttrString(self, "__class__");
2698 if (cls == NULL) {
2699 Py_DECREF(reduce);
2700 return NULL;
2701 }
2702 clsreduce = PyObject_GetAttrString(cls, "__reduce__");
2703 Py_DECREF(cls);
2704 if (clsreduce == NULL) {
2705 Py_DECREF(reduce);
2706 return NULL;
2707 }
2708 objreduce = PyDict_GetItemString(PyBaseObject_Type.tp_dict,
2709 "__reduce__");
2710 override = (clsreduce != objreduce);
2711 Py_DECREF(clsreduce);
2712 if (override) {
2713 res = PyObject_CallObject(reduce, NULL);
2714 Py_DECREF(reduce);
2715 return res;
2716 }
2717 else
2718 Py_DECREF(reduce);
2719 }
2720
2721 if (proto >= 2)
2722 return reduce_2(self);
2723
2724 copy_reg = import_copy_reg();
Guido van Rossum3926a632001-09-25 16:25:58 +00002725 if (!copy_reg)
2726 return NULL;
Guido van Rossum036f9992003-02-21 22:02:54 +00002727
Guido van Rossumc53f0092003-02-18 22:05:12 +00002728 res = PyEval_CallMethod(copy_reg, "_reduce_ex", "(Oi)", self, proto);
Guido van Rossum3926a632001-09-25 16:25:58 +00002729 Py_DECREF(copy_reg);
Guido van Rossum036f9992003-02-21 22:02:54 +00002730
Guido van Rossum3926a632001-09-25 16:25:58 +00002731 return res;
2732}
2733
2734static PyMethodDef object_methods[] = {
Guido van Rossumc53f0092003-02-18 22:05:12 +00002735 {"__reduce_ex__", object_reduce_ex, METH_VARARGS,
2736 PyDoc_STR("helper for pickle")},
2737 {"__reduce__", object_reduce_ex, METH_VARARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002738 PyDoc_STR("helper for pickle")},
Guido van Rossum3926a632001-09-25 16:25:58 +00002739 {0}
2740};
2741
Guido van Rossum036f9992003-02-21 22:02:54 +00002742
Tim Peters6d6c1a32001-08-02 04:15:00 +00002743PyTypeObject PyBaseObject_Type = {
2744 PyObject_HEAD_INIT(&PyType_Type)
2745 0, /* ob_size */
2746 "object", /* tp_name */
2747 sizeof(PyObject), /* tp_basicsize */
2748 0, /* tp_itemsize */
2749 (destructor)object_dealloc, /* tp_dealloc */
2750 0, /* tp_print */
2751 0, /* tp_getattr */
2752 0, /* tp_setattr */
2753 0, /* tp_compare */
Guido van Rossumb8f63662001-08-15 23:57:02 +00002754 object_repr, /* tp_repr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002755 0, /* tp_as_number */
2756 0, /* tp_as_sequence */
2757 0, /* tp_as_mapping */
Guido van Rossumb8f63662001-08-15 23:57:02 +00002758 object_hash, /* tp_hash */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002759 0, /* tp_call */
Guido van Rossumb8f63662001-08-15 23:57:02 +00002760 object_str, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002761 PyObject_GenericGetAttr, /* tp_getattro */
Guido van Rossum13d52f02001-08-10 21:24:08 +00002762 PyObject_GenericSetAttr, /* tp_setattro */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002763 0, /* tp_as_buffer */
2764 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002765 PyDoc_STR("The most base type"), /* tp_doc */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002766 0, /* tp_traverse */
2767 0, /* tp_clear */
2768 0, /* tp_richcompare */
2769 0, /* tp_weaklistoffset */
2770 0, /* tp_iter */
2771 0, /* tp_iternext */
Guido van Rossum3926a632001-09-25 16:25:58 +00002772 object_methods, /* tp_methods */
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002773 0, /* tp_members */
2774 object_getsets, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002775 0, /* tp_base */
2776 0, /* tp_dict */
2777 0, /* tp_descr_get */
2778 0, /* tp_descr_set */
2779 0, /* tp_dictoffset */
2780 object_init, /* tp_init */
2781 PyType_GenericAlloc, /* tp_alloc */
Guido van Rossum298e4212003-02-13 16:30:16 +00002782 object_new, /* tp_new */
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00002783 PyObject_Del, /* tp_free */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002784};
2785
2786
2787/* Initialize the __dict__ in a type object */
2788
2789static int
2790add_methods(PyTypeObject *type, PyMethodDef *meth)
2791{
Guido van Rossum687ae002001-10-15 22:03:32 +00002792 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002793
2794 for (; meth->ml_name != NULL; meth++) {
2795 PyObject *descr;
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00002796 if (PyDict_GetItemString(dict, meth->ml_name) &&
2797 !(meth->ml_flags & METH_COEXIST))
2798 continue;
Fred Drake7bf97152002-03-28 05:33:33 +00002799 if (meth->ml_flags & METH_CLASS) {
2800 if (meth->ml_flags & METH_STATIC) {
2801 PyErr_SetString(PyExc_ValueError,
2802 "method cannot be both class and static");
2803 return -1;
2804 }
Tim Petersbca1cbc2002-12-09 22:56:13 +00002805 descr = PyDescr_NewClassMethod(type, meth);
Fred Drake7bf97152002-03-28 05:33:33 +00002806 }
2807 else if (meth->ml_flags & METH_STATIC) {
Guido van Rossum9af48ff2003-02-11 17:12:46 +00002808 PyObject *cfunc = PyCFunction_New(meth, NULL);
2809 if (cfunc == NULL)
2810 return -1;
2811 descr = PyStaticMethod_New(cfunc);
2812 Py_DECREF(cfunc);
Fred Drake7bf97152002-03-28 05:33:33 +00002813 }
2814 else {
2815 descr = PyDescr_NewMethod(type, meth);
2816 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002817 if (descr == NULL)
2818 return -1;
Fred Drake7bf97152002-03-28 05:33:33 +00002819 if (PyDict_SetItemString(dict, meth->ml_name, descr) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002820 return -1;
2821 Py_DECREF(descr);
2822 }
2823 return 0;
2824}
2825
2826static int
Guido van Rossum6f799372001-09-20 20:46:19 +00002827add_members(PyTypeObject *type, PyMemberDef *memb)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002828{
Guido van Rossum687ae002001-10-15 22:03:32 +00002829 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002830
2831 for (; memb->name != NULL; memb++) {
2832 PyObject *descr;
2833 if (PyDict_GetItemString(dict, memb->name))
2834 continue;
2835 descr = PyDescr_NewMember(type, memb);
2836 if (descr == NULL)
2837 return -1;
2838 if (PyDict_SetItemString(dict, memb->name, descr) < 0)
2839 return -1;
2840 Py_DECREF(descr);
2841 }
2842 return 0;
2843}
2844
2845static int
Guido van Rossum32d34c82001-09-20 21:45:26 +00002846add_getset(PyTypeObject *type, PyGetSetDef *gsp)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002847{
Guido van Rossum687ae002001-10-15 22:03:32 +00002848 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002849
2850 for (; gsp->name != NULL; gsp++) {
2851 PyObject *descr;
2852 if (PyDict_GetItemString(dict, gsp->name))
2853 continue;
2854 descr = PyDescr_NewGetSet(type, gsp);
2855
2856 if (descr == NULL)
2857 return -1;
2858 if (PyDict_SetItemString(dict, gsp->name, descr) < 0)
2859 return -1;
2860 Py_DECREF(descr);
2861 }
2862 return 0;
2863}
2864
Guido van Rossum13d52f02001-08-10 21:24:08 +00002865static void
2866inherit_special(PyTypeObject *type, PyTypeObject *base)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002867{
2868 int oldsize, newsize;
2869
Guido van Rossum13d52f02001-08-10 21:24:08 +00002870 /* Special flag magic */
2871 if (!type->tp_as_buffer && base->tp_as_buffer) {
2872 type->tp_flags &= ~Py_TPFLAGS_HAVE_GETCHARBUFFER;
2873 type->tp_flags |=
2874 base->tp_flags & Py_TPFLAGS_HAVE_GETCHARBUFFER;
2875 }
2876 if (!type->tp_as_sequence && base->tp_as_sequence) {
2877 type->tp_flags &= ~Py_TPFLAGS_HAVE_SEQUENCE_IN;
2878 type->tp_flags |= base->tp_flags & Py_TPFLAGS_HAVE_SEQUENCE_IN;
2879 }
2880 if ((type->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS) !=
2881 (base->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS)) {
2882 if ((!type->tp_as_number && base->tp_as_number) ||
2883 (!type->tp_as_sequence && base->tp_as_sequence)) {
2884 type->tp_flags &= ~Py_TPFLAGS_HAVE_INPLACEOPS;
2885 if (!type->tp_as_number && !type->tp_as_sequence) {
2886 type->tp_flags |= base->tp_flags &
2887 Py_TPFLAGS_HAVE_INPLACEOPS;
2888 }
2889 }
2890 /* Wow */
2891 }
2892 if (!type->tp_as_number && base->tp_as_number) {
2893 type->tp_flags &= ~Py_TPFLAGS_CHECKTYPES;
2894 type->tp_flags |= base->tp_flags & Py_TPFLAGS_CHECKTYPES;
2895 }
2896
2897 /* Copying basicsize is connected to the GC flags */
Neil Schemenauerc806c882001-08-29 23:54:54 +00002898 oldsize = base->tp_basicsize;
2899 newsize = type->tp_basicsize ? type->tp_basicsize : oldsize;
2900 if (!(type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
2901 (base->tp_flags & Py_TPFLAGS_HAVE_GC) &&
Guido van Rossum13d52f02001-08-10 21:24:08 +00002902 (type->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE/*GC slots exist*/) &&
2903 (!type->tp_traverse && !type->tp_clear)) {
Neil Schemenauerc806c882001-08-29 23:54:54 +00002904 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossum13d52f02001-08-10 21:24:08 +00002905 if (type->tp_traverse == NULL)
2906 type->tp_traverse = base->tp_traverse;
2907 if (type->tp_clear == NULL)
2908 type->tp_clear = base->tp_clear;
2909 }
2910 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
Guido van Rossumf884b742001-12-17 17:14:22 +00002911 /* The condition below could use some explanation.
2912 It appears that tp_new is not inherited for static types
2913 whose base class is 'object'; this seems to be a precaution
2914 so that old extension types don't suddenly become
2915 callable (object.__new__ wouldn't insure the invariants
2916 that the extension type's own factory function ensures).
2917 Heap types, of course, are under our control, so they do
2918 inherit tp_new; static extension types that specify some
2919 other built-in type as the default are considered
2920 new-style-aware so they also inherit object.__new__. */
Guido van Rossum13d52f02001-08-10 21:24:08 +00002921 if (base != &PyBaseObject_Type ||
2922 (type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
2923 if (type->tp_new == NULL)
2924 type->tp_new = base->tp_new;
2925 }
2926 }
Neil Schemenauerc806c882001-08-29 23:54:54 +00002927 type->tp_basicsize = newsize;
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00002928
2929 /* Copy other non-function slots */
2930
2931#undef COPYVAL
2932#define COPYVAL(SLOT) \
2933 if (type->SLOT == 0) type->SLOT = base->SLOT
2934
2935 COPYVAL(tp_itemsize);
2936 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_WEAKREFS) {
2937 COPYVAL(tp_weaklistoffset);
2938 }
2939 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
2940 COPYVAL(tp_dictoffset);
2941 }
Guido van Rossum13d52f02001-08-10 21:24:08 +00002942}
2943
2944static void
2945inherit_slots(PyTypeObject *type, PyTypeObject *base)
2946{
2947 PyTypeObject *basebase;
2948
2949#undef SLOTDEFINED
Tim Peters6d6c1a32001-08-02 04:15:00 +00002950#undef COPYSLOT
2951#undef COPYNUM
2952#undef COPYSEQ
2953#undef COPYMAP
Guido van Rossum5af588b2001-10-12 14:13:21 +00002954#undef COPYBUF
Guido van Rossum13d52f02001-08-10 21:24:08 +00002955
2956#define SLOTDEFINED(SLOT) \
2957 (base->SLOT != 0 && \
2958 (basebase == NULL || base->SLOT != basebase->SLOT))
2959
Tim Peters6d6c1a32001-08-02 04:15:00 +00002960#define COPYSLOT(SLOT) \
Guido van Rossum13d52f02001-08-10 21:24:08 +00002961 if (!type->SLOT && SLOTDEFINED(SLOT)) type->SLOT = base->SLOT
Tim Peters6d6c1a32001-08-02 04:15:00 +00002962
2963#define COPYNUM(SLOT) COPYSLOT(tp_as_number->SLOT)
2964#define COPYSEQ(SLOT) COPYSLOT(tp_as_sequence->SLOT)
2965#define COPYMAP(SLOT) COPYSLOT(tp_as_mapping->SLOT)
Tim Petersfc57ccb2001-10-12 02:38:24 +00002966#define COPYBUF(SLOT) COPYSLOT(tp_as_buffer->SLOT)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002967
Guido van Rossum13d52f02001-08-10 21:24:08 +00002968 /* This won't inherit indirect slots (from tp_as_number etc.)
2969 if type doesn't provide the space. */
2970
2971 if (type->tp_as_number != NULL && base->tp_as_number != NULL) {
2972 basebase = base->tp_base;
2973 if (basebase->tp_as_number == NULL)
2974 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002975 COPYNUM(nb_add);
2976 COPYNUM(nb_subtract);
2977 COPYNUM(nb_multiply);
2978 COPYNUM(nb_divide);
2979 COPYNUM(nb_remainder);
2980 COPYNUM(nb_divmod);
2981 COPYNUM(nb_power);
2982 COPYNUM(nb_negative);
2983 COPYNUM(nb_positive);
2984 COPYNUM(nb_absolute);
2985 COPYNUM(nb_nonzero);
2986 COPYNUM(nb_invert);
2987 COPYNUM(nb_lshift);
2988 COPYNUM(nb_rshift);
2989 COPYNUM(nb_and);
2990 COPYNUM(nb_xor);
2991 COPYNUM(nb_or);
2992 COPYNUM(nb_coerce);
2993 COPYNUM(nb_int);
2994 COPYNUM(nb_long);
2995 COPYNUM(nb_float);
2996 COPYNUM(nb_oct);
2997 COPYNUM(nb_hex);
2998 COPYNUM(nb_inplace_add);
2999 COPYNUM(nb_inplace_subtract);
3000 COPYNUM(nb_inplace_multiply);
3001 COPYNUM(nb_inplace_divide);
3002 COPYNUM(nb_inplace_remainder);
3003 COPYNUM(nb_inplace_power);
3004 COPYNUM(nb_inplace_lshift);
3005 COPYNUM(nb_inplace_rshift);
3006 COPYNUM(nb_inplace_and);
3007 COPYNUM(nb_inplace_xor);
3008 COPYNUM(nb_inplace_or);
Guido van Rossumdc91b992001-08-08 22:26:22 +00003009 if (base->tp_flags & Py_TPFLAGS_CHECKTYPES) {
3010 COPYNUM(nb_true_divide);
3011 COPYNUM(nb_floor_divide);
3012 COPYNUM(nb_inplace_true_divide);
3013 COPYNUM(nb_inplace_floor_divide);
3014 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003015 }
3016
Guido van Rossum13d52f02001-08-10 21:24:08 +00003017 if (type->tp_as_sequence != NULL && base->tp_as_sequence != NULL) {
3018 basebase = base->tp_base;
3019 if (basebase->tp_as_sequence == NULL)
3020 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003021 COPYSEQ(sq_length);
3022 COPYSEQ(sq_concat);
3023 COPYSEQ(sq_repeat);
3024 COPYSEQ(sq_item);
3025 COPYSEQ(sq_slice);
3026 COPYSEQ(sq_ass_item);
3027 COPYSEQ(sq_ass_slice);
3028 COPYSEQ(sq_contains);
3029 COPYSEQ(sq_inplace_concat);
3030 COPYSEQ(sq_inplace_repeat);
3031 }
3032
Guido van Rossum13d52f02001-08-10 21:24:08 +00003033 if (type->tp_as_mapping != NULL && base->tp_as_mapping != NULL) {
3034 basebase = base->tp_base;
3035 if (basebase->tp_as_mapping == NULL)
3036 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003037 COPYMAP(mp_length);
3038 COPYMAP(mp_subscript);
3039 COPYMAP(mp_ass_subscript);
3040 }
3041
Tim Petersfc57ccb2001-10-12 02:38:24 +00003042 if (type->tp_as_buffer != NULL && base->tp_as_buffer != NULL) {
3043 basebase = base->tp_base;
3044 if (basebase->tp_as_buffer == NULL)
3045 basebase = NULL;
3046 COPYBUF(bf_getreadbuffer);
3047 COPYBUF(bf_getwritebuffer);
3048 COPYBUF(bf_getsegcount);
3049 COPYBUF(bf_getcharbuffer);
3050 }
3051
Guido van Rossum13d52f02001-08-10 21:24:08 +00003052 basebase = base->tp_base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003053
Tim Peters6d6c1a32001-08-02 04:15:00 +00003054 COPYSLOT(tp_dealloc);
3055 COPYSLOT(tp_print);
3056 if (type->tp_getattr == NULL && type->tp_getattro == NULL) {
3057 type->tp_getattr = base->tp_getattr;
3058 type->tp_getattro = base->tp_getattro;
3059 }
3060 if (type->tp_setattr == NULL && type->tp_setattro == NULL) {
3061 type->tp_setattr = base->tp_setattr;
3062 type->tp_setattro = base->tp_setattro;
3063 }
3064 /* tp_compare see tp_richcompare */
3065 COPYSLOT(tp_repr);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003066 /* tp_hash see tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003067 COPYSLOT(tp_call);
3068 COPYSLOT(tp_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003069 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00003070 if (type->tp_compare == NULL &&
3071 type->tp_richcompare == NULL &&
3072 type->tp_hash == NULL)
3073 {
Tim Peters6d6c1a32001-08-02 04:15:00 +00003074 type->tp_compare = base->tp_compare;
3075 type->tp_richcompare = base->tp_richcompare;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003076 type->tp_hash = base->tp_hash;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003077 }
3078 }
3079 else {
3080 COPYSLOT(tp_compare);
3081 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003082 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_ITER) {
3083 COPYSLOT(tp_iter);
3084 COPYSLOT(tp_iternext);
3085 }
3086 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
3087 COPYSLOT(tp_descr_get);
3088 COPYSLOT(tp_descr_set);
3089 COPYSLOT(tp_dictoffset);
3090 COPYSLOT(tp_init);
3091 COPYSLOT(tp_alloc);
Guido van Rossumcc8fe042002-04-05 17:10:16 +00003092 COPYSLOT(tp_is_gc);
Tim Peters3cfe7542003-05-21 21:29:48 +00003093 if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) ==
3094 (base->tp_flags & Py_TPFLAGS_HAVE_GC)) {
3095 /* They agree about gc. */
3096 COPYSLOT(tp_free);
3097 }
3098 else if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
3099 type->tp_free == NULL &&
3100 base->tp_free == _PyObject_Del) {
3101 /* A bit of magic to plug in the correct default
3102 * tp_free function when a derived class adds gc,
3103 * didn't define tp_free, and the base uses the
3104 * default non-gc tp_free.
3105 */
3106 type->tp_free = PyObject_GC_Del;
3107 }
3108 /* else they didn't agree about gc, and there isn't something
3109 * obvious to be done -- the type is on its own.
3110 */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003111 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003112}
3113
Jeremy Hylton938ace62002-07-17 16:30:39 +00003114static int add_operators(PyTypeObject *);
Guido van Rossum13d52f02001-08-10 21:24:08 +00003115
Tim Peters6d6c1a32001-08-02 04:15:00 +00003116int
Guido van Rossum528b7eb2001-08-07 17:24:28 +00003117PyType_Ready(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003118{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00003119 PyObject *dict, *bases;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003120 PyTypeObject *base;
3121 int i, n;
3122
Guido van Rossumcab05802002-06-10 15:29:03 +00003123 if (type->tp_flags & Py_TPFLAGS_READY) {
3124 assert(type->tp_dict != NULL);
Guido van Rossumd614f972001-08-10 17:39:49 +00003125 return 0;
Guido van Rossumcab05802002-06-10 15:29:03 +00003126 }
Guido van Rossumd614f972001-08-10 17:39:49 +00003127 assert((type->tp_flags & Py_TPFLAGS_READYING) == 0);
Guido van Rossumd614f972001-08-10 17:39:49 +00003128
3129 type->tp_flags |= Py_TPFLAGS_READYING;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003130
Tim Peters36eb4df2003-03-23 03:33:13 +00003131#ifdef Py_TRACE_REFS
3132 /* PyType_Ready is the closest thing we have to a choke point
3133 * for type objects, so is the best place I can think of to try
3134 * to get type objects into the doubly-linked list of all objects.
3135 * Still, not all type objects go thru PyType_Ready.
3136 */
Tim Peters7571a0f2003-03-23 17:52:28 +00003137 _Py_AddToAllObjects((PyObject *)type, 0);
Tim Peters36eb4df2003-03-23 03:33:13 +00003138#endif
3139
Tim Peters6d6c1a32001-08-02 04:15:00 +00003140 /* Initialize tp_base (defaults to BaseObject unless that's us) */
3141 base = type->tp_base;
3142 if (base == NULL && type != &PyBaseObject_Type)
3143 base = type->tp_base = &PyBaseObject_Type;
3144
Guido van Rossum323a9cf2002-08-14 17:26:30 +00003145 /* Initialize the base class */
3146 if (base && base->tp_dict == NULL) {
3147 if (PyType_Ready(base) < 0)
3148 goto error;
3149 }
3150
Guido van Rossum0986d822002-04-08 01:38:42 +00003151 /* Initialize ob_type if NULL. This means extensions that want to be
3152 compilable separately on Windows can call PyType_Ready() instead of
3153 initializing the ob_type field of their type objects. */
3154 if (type->ob_type == NULL)
3155 type->ob_type = base->ob_type;
3156
Tim Peters6d6c1a32001-08-02 04:15:00 +00003157 /* Initialize tp_bases */
3158 bases = type->tp_bases;
3159 if (bases == NULL) {
3160 if (base == NULL)
3161 bases = PyTuple_New(0);
3162 else
Raymond Hettinger8ae46892003-10-12 19:09:37 +00003163 bases = PyTuple_Pack(1, base);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003164 if (bases == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00003165 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003166 type->tp_bases = bases;
3167 }
3168
Guido van Rossum687ae002001-10-15 22:03:32 +00003169 /* Initialize tp_dict */
3170 dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003171 if (dict == NULL) {
3172 dict = PyDict_New();
3173 if (dict == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00003174 goto error;
Guido van Rossum687ae002001-10-15 22:03:32 +00003175 type->tp_dict = dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003176 }
3177
Guido van Rossum687ae002001-10-15 22:03:32 +00003178 /* Add type-specific descriptors to tp_dict */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003179 if (add_operators(type) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003180 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003181 if (type->tp_methods != NULL) {
3182 if (add_methods(type, type->tp_methods) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003183 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003184 }
3185 if (type->tp_members != NULL) {
3186 if (add_members(type, type->tp_members) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003187 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003188 }
3189 if (type->tp_getset != NULL) {
3190 if (add_getset(type, type->tp_getset) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003191 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003192 }
3193
Tim Peters6d6c1a32001-08-02 04:15:00 +00003194 /* Calculate method resolution order */
3195 if (mro_internal(type) < 0) {
Guido van Rossumd614f972001-08-10 17:39:49 +00003196 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003197 }
3198
Guido van Rossum13d52f02001-08-10 21:24:08 +00003199 /* Inherit special flags from dominant base */
3200 if (type->tp_base != NULL)
3201 inherit_special(type, type->tp_base);
3202
Tim Peters6d6c1a32001-08-02 04:15:00 +00003203 /* Initialize tp_dict properly */
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00003204 bases = type->tp_mro;
3205 assert(bases != NULL);
3206 assert(PyTuple_Check(bases));
3207 n = PyTuple_GET_SIZE(bases);
3208 for (i = 1; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00003209 PyObject *b = PyTuple_GET_ITEM(bases, i);
3210 if (PyType_Check(b))
3211 inherit_slots(type, (PyTypeObject *)b);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003212 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003213
Tim Peters3cfe7542003-05-21 21:29:48 +00003214 /* Sanity check for tp_free. */
3215 if (PyType_IS_GC(type) && (type->tp_flags & Py_TPFLAGS_BASETYPE) &&
3216 (type->tp_free == NULL || type->tp_free == PyObject_Del)) {
3217 /* This base class needs to call tp_free, but doesn't have
3218 * one, or its tp_free is for non-gc'ed objects.
3219 */
3220 PyErr_Format(PyExc_TypeError, "type '%.100s' participates in "
3221 "gc and is a base type but has inappropriate "
3222 "tp_free slot",
3223 type->tp_name);
3224 goto error;
3225 }
3226
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00003227 /* if the type dictionary doesn't contain a __doc__, set it from
3228 the tp_doc slot.
3229 */
3230 if (PyDict_GetItemString(type->tp_dict, "__doc__") == NULL) {
3231 if (type->tp_doc != NULL) {
3232 PyObject *doc = PyString_FromString(type->tp_doc);
3233 PyDict_SetItemString(type->tp_dict, "__doc__", doc);
3234 Py_DECREF(doc);
3235 } else {
Guido van Rossumd4641072002-04-03 02:13:37 +00003236 PyDict_SetItemString(type->tp_dict,
3237 "__doc__", Py_None);
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00003238 }
3239 }
3240
Guido van Rossum13d52f02001-08-10 21:24:08 +00003241 /* Some more special stuff */
3242 base = type->tp_base;
3243 if (base != NULL) {
3244 if (type->tp_as_number == NULL)
3245 type->tp_as_number = base->tp_as_number;
3246 if (type->tp_as_sequence == NULL)
3247 type->tp_as_sequence = base->tp_as_sequence;
3248 if (type->tp_as_mapping == NULL)
3249 type->tp_as_mapping = base->tp_as_mapping;
Guido van Rossumeea47182003-02-11 20:39:59 +00003250 if (type->tp_as_buffer == NULL)
3251 type->tp_as_buffer = base->tp_as_buffer;
Guido van Rossum13d52f02001-08-10 21:24:08 +00003252 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003253
Guido van Rossum1c450732001-10-08 15:18:27 +00003254 /* Link into each base class's list of subclasses */
3255 bases = type->tp_bases;
3256 n = PyTuple_GET_SIZE(bases);
3257 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00003258 PyObject *b = PyTuple_GET_ITEM(bases, i);
3259 if (PyType_Check(b) &&
3260 add_subclass((PyTypeObject *)b, type) < 0)
Guido van Rossum1c450732001-10-08 15:18:27 +00003261 goto error;
3262 }
3263
Guido van Rossum13d52f02001-08-10 21:24:08 +00003264 /* All done -- set the ready flag */
Guido van Rossumd614f972001-08-10 17:39:49 +00003265 assert(type->tp_dict != NULL);
3266 type->tp_flags =
3267 (type->tp_flags & ~Py_TPFLAGS_READYING) | Py_TPFLAGS_READY;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003268 return 0;
Guido van Rossumd614f972001-08-10 17:39:49 +00003269
3270 error:
3271 type->tp_flags &= ~Py_TPFLAGS_READYING;
3272 return -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003273}
3274
Guido van Rossum1c450732001-10-08 15:18:27 +00003275static int
3276add_subclass(PyTypeObject *base, PyTypeObject *type)
3277{
3278 int i;
3279 PyObject *list, *ref, *new;
3280
3281 list = base->tp_subclasses;
3282 if (list == NULL) {
3283 base->tp_subclasses = list = PyList_New(0);
3284 if (list == NULL)
3285 return -1;
3286 }
3287 assert(PyList_Check(list));
3288 new = PyWeakref_NewRef((PyObject *)type, NULL);
3289 i = PyList_GET_SIZE(list);
3290 while (--i >= 0) {
3291 ref = PyList_GET_ITEM(list, i);
3292 assert(PyWeakref_CheckRef(ref));
Guido van Rossum3930bc32002-10-18 13:51:49 +00003293 if (PyWeakref_GET_OBJECT(ref) == Py_None)
3294 return PyList_SetItem(list, i, new);
Guido van Rossum1c450732001-10-08 15:18:27 +00003295 }
3296 i = PyList_Append(list, new);
3297 Py_DECREF(new);
3298 return i;
3299}
3300
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003301static void
3302remove_subclass(PyTypeObject *base, PyTypeObject *type)
3303{
3304 int i;
3305 PyObject *list, *ref;
3306
3307 list = base->tp_subclasses;
3308 if (list == NULL) {
3309 return;
3310 }
3311 assert(PyList_Check(list));
3312 i = PyList_GET_SIZE(list);
3313 while (--i >= 0) {
3314 ref = PyList_GET_ITEM(list, i);
3315 assert(PyWeakref_CheckRef(ref));
3316 if (PyWeakref_GET_OBJECT(ref) == (PyObject*)type) {
3317 /* this can't fail, right? */
3318 PySequence_DelItem(list, i);
3319 return;
3320 }
3321 }
3322}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003323
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003324static int
3325check_num_args(PyObject *ob, int n)
3326{
3327 if (!PyTuple_CheckExact(ob)) {
3328 PyErr_SetString(PyExc_SystemError,
3329 "PyArg_UnpackTuple() argument list is not a tuple");
3330 return 0;
3331 }
3332 if (n == PyTuple_GET_SIZE(ob))
3333 return 1;
3334 PyErr_Format(
3335 PyExc_TypeError,
3336 "expected %d arguments, got %d", n, PyTuple_GET_SIZE(ob));
3337 return 0;
3338}
3339
Tim Peters6d6c1a32001-08-02 04:15:00 +00003340/* Generic wrappers for overloadable 'operators' such as __getitem__ */
3341
3342/* There's a wrapper *function* for each distinct function typedef used
3343 for type object slots (e.g. binaryfunc, ternaryfunc, etc.). There's a
3344 wrapper *table* for each distinct operation (e.g. __len__, __add__).
3345 Most tables have only one entry; the tables for binary operators have two
3346 entries, one regular and one with reversed arguments. */
3347
3348static PyObject *
3349wrap_inquiry(PyObject *self, PyObject *args, void *wrapped)
3350{
3351 inquiry func = (inquiry)wrapped;
3352 int res;
3353
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003354 if (!check_num_args(args, 0))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003355 return NULL;
3356 res = (*func)(self);
3357 if (res == -1 && PyErr_Occurred())
3358 return NULL;
3359 return PyInt_FromLong((long)res);
3360}
3361
Tim Peters6d6c1a32001-08-02 04:15:00 +00003362static PyObject *
Raymond Hettingerf34f2642003-10-11 17:29:04 +00003363wrap_inquirypred(PyObject *self, PyObject *args, void *wrapped)
3364{
3365 inquiry func = (inquiry)wrapped;
3366 int res;
3367
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003368 if (!check_num_args(args, 0))
Raymond Hettingerf34f2642003-10-11 17:29:04 +00003369 return NULL;
3370 res = (*func)(self);
3371 if (res == -1 && PyErr_Occurred())
3372 return NULL;
3373 return PyBool_FromLong((long)res);
3374}
3375
3376static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00003377wrap_binaryfunc(PyObject *self, PyObject *args, void *wrapped)
3378{
3379 binaryfunc func = (binaryfunc)wrapped;
3380 PyObject *other;
3381
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003382 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003383 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003384 other = PyTuple_GET_ITEM(args, 0);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003385 return (*func)(self, other);
3386}
3387
3388static PyObject *
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003389wrap_binaryfunc_l(PyObject *self, PyObject *args, void *wrapped)
3390{
3391 binaryfunc func = (binaryfunc)wrapped;
3392 PyObject *other;
3393
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003394 if (!check_num_args(args, 1))
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003395 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003396 other = PyTuple_GET_ITEM(args, 0);
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003397 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003398 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003399 Py_INCREF(Py_NotImplemented);
3400 return Py_NotImplemented;
3401 }
3402 return (*func)(self, other);
3403}
3404
3405static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00003406wrap_binaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
3407{
3408 binaryfunc func = (binaryfunc)wrapped;
3409 PyObject *other;
3410
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003411 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003412 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003413 other = PyTuple_GET_ITEM(args, 0);
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003414 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003415 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003416 Py_INCREF(Py_NotImplemented);
3417 return Py_NotImplemented;
3418 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003419 return (*func)(other, self);
3420}
3421
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003422static PyObject *
3423wrap_coercefunc(PyObject *self, PyObject *args, void *wrapped)
3424{
3425 coercion func = (coercion)wrapped;
3426 PyObject *other, *res;
3427 int ok;
3428
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003429 if (!check_num_args(args, 1))
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003430 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003431 other = PyTuple_GET_ITEM(args, 0);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003432 ok = func(&self, &other);
3433 if (ok < 0)
3434 return NULL;
3435 if (ok > 0) {
3436 Py_INCREF(Py_NotImplemented);
3437 return Py_NotImplemented;
3438 }
3439 res = PyTuple_New(2);
3440 if (res == NULL) {
3441 Py_DECREF(self);
3442 Py_DECREF(other);
3443 return NULL;
3444 }
3445 PyTuple_SET_ITEM(res, 0, self);
3446 PyTuple_SET_ITEM(res, 1, other);
3447 return res;
3448}
3449
Tim Peters6d6c1a32001-08-02 04:15:00 +00003450static PyObject *
3451wrap_ternaryfunc(PyObject *self, PyObject *args, void *wrapped)
3452{
3453 ternaryfunc func = (ternaryfunc)wrapped;
3454 PyObject *other;
3455 PyObject *third = Py_None;
3456
3457 /* Note: This wrapper only works for __pow__() */
3458
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00003459 if (!PyArg_UnpackTuple(args, "", 1, 2, &other, &third))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003460 return NULL;
3461 return (*func)(self, other, third);
3462}
3463
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00003464static PyObject *
3465wrap_ternaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
3466{
3467 ternaryfunc func = (ternaryfunc)wrapped;
3468 PyObject *other;
3469 PyObject *third = Py_None;
3470
3471 /* Note: This wrapper only works for __pow__() */
3472
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00003473 if (!PyArg_UnpackTuple(args, "", 1, 2, &other, &third))
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00003474 return NULL;
3475 return (*func)(other, self, third);
3476}
3477
Tim Peters6d6c1a32001-08-02 04:15:00 +00003478static PyObject *
3479wrap_unaryfunc(PyObject *self, PyObject *args, void *wrapped)
3480{
3481 unaryfunc func = (unaryfunc)wrapped;
3482
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003483 if (!check_num_args(args, 0))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003484 return NULL;
3485 return (*func)(self);
3486}
3487
Tim Peters6d6c1a32001-08-02 04:15:00 +00003488static PyObject *
3489wrap_intargfunc(PyObject *self, PyObject *args, void *wrapped)
3490{
3491 intargfunc func = (intargfunc)wrapped;
3492 int i;
3493
3494 if (!PyArg_ParseTuple(args, "i", &i))
3495 return NULL;
3496 return (*func)(self, i);
3497}
3498
Guido van Rossum5d815f32001-08-17 21:57:47 +00003499static int
3500getindex(PyObject *self, PyObject *arg)
3501{
3502 int i;
3503
3504 i = PyInt_AsLong(arg);
3505 if (i == -1 && PyErr_Occurred())
3506 return -1;
3507 if (i < 0) {
3508 PySequenceMethods *sq = self->ob_type->tp_as_sequence;
3509 if (sq && sq->sq_length) {
3510 int n = (*sq->sq_length)(self);
3511 if (n < 0)
3512 return -1;
3513 i += n;
3514 }
3515 }
3516 return i;
3517}
3518
3519static PyObject *
3520wrap_sq_item(PyObject *self, PyObject *args, void *wrapped)
3521{
3522 intargfunc func = (intargfunc)wrapped;
3523 PyObject *arg;
3524 int i;
3525
Guido van Rossumf4593e02001-10-03 12:09:30 +00003526 if (PyTuple_GET_SIZE(args) == 1) {
3527 arg = PyTuple_GET_ITEM(args, 0);
3528 i = getindex(self, arg);
3529 if (i == -1 && PyErr_Occurred())
3530 return NULL;
3531 return (*func)(self, i);
3532 }
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003533 check_num_args(args, 1);
Guido van Rossumf4593e02001-10-03 12:09:30 +00003534 assert(PyErr_Occurred());
3535 return NULL;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003536}
3537
Tim Peters6d6c1a32001-08-02 04:15:00 +00003538static PyObject *
3539wrap_intintargfunc(PyObject *self, PyObject *args, void *wrapped)
3540{
3541 intintargfunc func = (intintargfunc)wrapped;
3542 int i, j;
3543
3544 if (!PyArg_ParseTuple(args, "ii", &i, &j))
3545 return NULL;
3546 return (*func)(self, i, j);
3547}
3548
Tim Peters6d6c1a32001-08-02 04:15:00 +00003549static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00003550wrap_sq_setitem(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003551{
3552 intobjargproc func = (intobjargproc)wrapped;
3553 int i, res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003554 PyObject *arg, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003555
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00003556 if (!PyArg_UnpackTuple(args, "", 2, 2, &arg, &value))
Guido van Rossum5d815f32001-08-17 21:57:47 +00003557 return NULL;
3558 i = getindex(self, arg);
3559 if (i == -1 && PyErr_Occurred())
Tim Peters6d6c1a32001-08-02 04:15:00 +00003560 return NULL;
3561 res = (*func)(self, i, value);
3562 if (res == -1 && PyErr_Occurred())
3563 return NULL;
3564 Py_INCREF(Py_None);
3565 return Py_None;
3566}
3567
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003568static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00003569wrap_sq_delitem(PyObject *self, PyObject *args, void *wrapped)
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003570{
3571 intobjargproc func = (intobjargproc)wrapped;
3572 int i, res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003573 PyObject *arg;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003574
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003575 if (!check_num_args(args, 1))
Guido van Rossum5d815f32001-08-17 21:57:47 +00003576 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003577 arg = PyTuple_GET_ITEM(args, 0);
Guido van Rossum5d815f32001-08-17 21:57:47 +00003578 i = getindex(self, arg);
3579 if (i == -1 && PyErr_Occurred())
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003580 return NULL;
3581 res = (*func)(self, i, NULL);
3582 if (res == -1 && PyErr_Occurred())
3583 return NULL;
3584 Py_INCREF(Py_None);
3585 return Py_None;
3586}
3587
Tim Peters6d6c1a32001-08-02 04:15:00 +00003588static PyObject *
3589wrap_intintobjargproc(PyObject *self, PyObject *args, void *wrapped)
3590{
3591 intintobjargproc func = (intintobjargproc)wrapped;
3592 int i, j, res;
3593 PyObject *value;
3594
3595 if (!PyArg_ParseTuple(args, "iiO", &i, &j, &value))
3596 return NULL;
3597 res = (*func)(self, i, j, value);
3598 if (res == -1 && PyErr_Occurred())
3599 return NULL;
3600 Py_INCREF(Py_None);
3601 return Py_None;
3602}
3603
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003604static PyObject *
3605wrap_delslice(PyObject *self, PyObject *args, void *wrapped)
3606{
3607 intintobjargproc func = (intintobjargproc)wrapped;
3608 int i, j, res;
3609
3610 if (!PyArg_ParseTuple(args, "ii", &i, &j))
3611 return NULL;
3612 res = (*func)(self, i, j, NULL);
3613 if (res == -1 && PyErr_Occurred())
3614 return NULL;
3615 Py_INCREF(Py_None);
3616 return Py_None;
3617}
3618
Tim Peters6d6c1a32001-08-02 04:15:00 +00003619/* XXX objobjproc is a misnomer; should be objargpred */
3620static PyObject *
3621wrap_objobjproc(PyObject *self, PyObject *args, void *wrapped)
3622{
3623 objobjproc func = (objobjproc)wrapped;
3624 int res;
Guido van Rossum22c3dda2003-10-09 03:46:35 +00003625 PyObject *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003626
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003627 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003628 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003629 value = PyTuple_GET_ITEM(args, 0);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003630 res = (*func)(self, value);
3631 if (res == -1 && PyErr_Occurred())
3632 return NULL;
Guido van Rossum22c3dda2003-10-09 03:46:35 +00003633 else
3634 return PyBool_FromLong(res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003635}
3636
Tim Peters6d6c1a32001-08-02 04:15:00 +00003637static PyObject *
3638wrap_objobjargproc(PyObject *self, PyObject *args, void *wrapped)
3639{
3640 objobjargproc func = (objobjargproc)wrapped;
3641 int res;
3642 PyObject *key, *value;
3643
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00003644 if (!PyArg_UnpackTuple(args, "", 2, 2, &key, &value))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003645 return NULL;
3646 res = (*func)(self, key, value);
3647 if (res == -1 && PyErr_Occurred())
3648 return NULL;
3649 Py_INCREF(Py_None);
3650 return Py_None;
3651}
3652
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003653static PyObject *
3654wrap_delitem(PyObject *self, PyObject *args, void *wrapped)
3655{
3656 objobjargproc func = (objobjargproc)wrapped;
3657 int res;
3658 PyObject *key;
3659
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003660 if (!check_num_args(args, 1))
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003661 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003662 key = PyTuple_GET_ITEM(args, 0);
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003663 res = (*func)(self, key, NULL);
3664 if (res == -1 && PyErr_Occurred())
3665 return NULL;
3666 Py_INCREF(Py_None);
3667 return Py_None;
3668}
3669
Tim Peters6d6c1a32001-08-02 04:15:00 +00003670static PyObject *
3671wrap_cmpfunc(PyObject *self, PyObject *args, void *wrapped)
3672{
3673 cmpfunc func = (cmpfunc)wrapped;
3674 int res;
3675 PyObject *other;
3676
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003677 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003678 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003679 other = PyTuple_GET_ITEM(args, 0);
Guido van Rossum3d45d8f2001-09-24 18:47:40 +00003680 if (other->ob_type->tp_compare != func &&
3681 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossumceccae52001-09-18 20:03:57 +00003682 PyErr_Format(
3683 PyExc_TypeError,
3684 "%s.__cmp__(x,y) requires y to be a '%s', not a '%s'",
3685 self->ob_type->tp_name,
3686 self->ob_type->tp_name,
3687 other->ob_type->tp_name);
3688 return NULL;
3689 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003690 res = (*func)(self, other);
3691 if (PyErr_Occurred())
3692 return NULL;
3693 return PyInt_FromLong((long)res);
3694}
3695
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003696/* Helper to check for object.__setattr__ or __delattr__ applied to a type.
Guido van Rossum52b27052003-04-15 20:05:10 +00003697 This is called the Carlo Verre hack after its discoverer. */
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003698static int
3699hackcheck(PyObject *self, setattrofunc func, char *what)
3700{
3701 PyTypeObject *type = self->ob_type;
3702 while (type && type->tp_flags & Py_TPFLAGS_HEAPTYPE)
3703 type = type->tp_base;
3704 if (type->tp_setattro != func) {
3705 PyErr_Format(PyExc_TypeError,
3706 "can't apply this %s to %s object",
3707 what,
3708 type->tp_name);
3709 return 0;
3710 }
3711 return 1;
3712}
3713
Tim Peters6d6c1a32001-08-02 04:15:00 +00003714static PyObject *
3715wrap_setattr(PyObject *self, PyObject *args, void *wrapped)
3716{
3717 setattrofunc func = (setattrofunc)wrapped;
3718 int res;
3719 PyObject *name, *value;
3720
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00003721 if (!PyArg_UnpackTuple(args, "", 2, 2, &name, &value))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003722 return NULL;
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003723 if (!hackcheck(self, func, "__setattr__"))
3724 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003725 res = (*func)(self, name, value);
3726 if (res < 0)
3727 return NULL;
3728 Py_INCREF(Py_None);
3729 return Py_None;
3730}
3731
3732static PyObject *
3733wrap_delattr(PyObject *self, PyObject *args, void *wrapped)
3734{
3735 setattrofunc func = (setattrofunc)wrapped;
3736 int res;
3737 PyObject *name;
3738
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003739 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003740 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003741 name = PyTuple_GET_ITEM(args, 0);
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003742 if (!hackcheck(self, func, "__delattr__"))
3743 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003744 res = (*func)(self, name, NULL);
3745 if (res < 0)
3746 return NULL;
3747 Py_INCREF(Py_None);
3748 return Py_None;
3749}
3750
Tim Peters6d6c1a32001-08-02 04:15:00 +00003751static PyObject *
3752wrap_hashfunc(PyObject *self, PyObject *args, void *wrapped)
3753{
3754 hashfunc func = (hashfunc)wrapped;
3755 long res;
3756
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003757 if (!check_num_args(args, 0))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003758 return NULL;
3759 res = (*func)(self);
3760 if (res == -1 && PyErr_Occurred())
3761 return NULL;
3762 return PyInt_FromLong(res);
3763}
3764
Tim Peters6d6c1a32001-08-02 04:15:00 +00003765static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00003766wrap_call(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003767{
3768 ternaryfunc func = (ternaryfunc)wrapped;
3769
Guido van Rossumc8e56452001-10-22 00:43:43 +00003770 return (*func)(self, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003771}
3772
Tim Peters6d6c1a32001-08-02 04:15:00 +00003773static PyObject *
3774wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op)
3775{
3776 richcmpfunc func = (richcmpfunc)wrapped;
3777 PyObject *other;
3778
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003779 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003780 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003781 other = PyTuple_GET_ITEM(args, 0);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003782 return (*func)(self, other, op);
3783}
3784
3785#undef RICHCMP_WRAPPER
3786#define RICHCMP_WRAPPER(NAME, OP) \
3787static PyObject * \
3788richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \
3789{ \
3790 return wrap_richcmpfunc(self, args, wrapped, OP); \
3791}
3792
Jack Jansen8e938b42001-08-08 15:29:49 +00003793RICHCMP_WRAPPER(lt, Py_LT)
3794RICHCMP_WRAPPER(le, Py_LE)
3795RICHCMP_WRAPPER(eq, Py_EQ)
3796RICHCMP_WRAPPER(ne, Py_NE)
3797RICHCMP_WRAPPER(gt, Py_GT)
3798RICHCMP_WRAPPER(ge, Py_GE)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003799
Tim Peters6d6c1a32001-08-02 04:15:00 +00003800static PyObject *
3801wrap_next(PyObject *self, PyObject *args, void *wrapped)
3802{
3803 unaryfunc func = (unaryfunc)wrapped;
3804 PyObject *res;
3805
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003806 if (!check_num_args(args, 0))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003807 return NULL;
3808 res = (*func)(self);
3809 if (res == NULL && !PyErr_Occurred())
3810 PyErr_SetNone(PyExc_StopIteration);
3811 return res;
3812}
3813
Tim Peters6d6c1a32001-08-02 04:15:00 +00003814static PyObject *
3815wrap_descr_get(PyObject *self, PyObject *args, void *wrapped)
3816{
3817 descrgetfunc func = (descrgetfunc)wrapped;
3818 PyObject *obj;
3819 PyObject *type = NULL;
3820
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00003821 if (!PyArg_UnpackTuple(args, "", 1, 2, &obj, &type))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003822 return NULL;
Guido van Rossum82ed25c2003-02-11 16:25:43 +00003823 if (obj == Py_None)
3824 obj = NULL;
3825 if (type == Py_None)
3826 type = NULL;
3827 if (type == NULL &&obj == NULL) {
3828 PyErr_SetString(PyExc_TypeError,
3829 "__get__(None, None) is invalid");
3830 return NULL;
3831 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003832 return (*func)(self, obj, type);
3833}
3834
Tim Peters6d6c1a32001-08-02 04:15:00 +00003835static PyObject *
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003836wrap_descr_set(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003837{
3838 descrsetfunc func = (descrsetfunc)wrapped;
3839 PyObject *obj, *value;
3840 int ret;
3841
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00003842 if (!PyArg_UnpackTuple(args, "", 2, 2, &obj, &value))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003843 return NULL;
3844 ret = (*func)(self, obj, value);
3845 if (ret < 0)
3846 return NULL;
3847 Py_INCREF(Py_None);
3848 return Py_None;
3849}
Guido van Rossum22b13872002-08-06 21:41:44 +00003850
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00003851static PyObject *
3852wrap_descr_delete(PyObject *self, PyObject *args, void *wrapped)
3853{
3854 descrsetfunc func = (descrsetfunc)wrapped;
3855 PyObject *obj;
3856 int ret;
3857
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003858 if (!check_num_args(args, 1))
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00003859 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003860 obj = PyTuple_GET_ITEM(args, 0);
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00003861 ret = (*func)(self, obj, NULL);
3862 if (ret < 0)
3863 return NULL;
3864 Py_INCREF(Py_None);
3865 return Py_None;
3866}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003867
Tim Peters6d6c1a32001-08-02 04:15:00 +00003868static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00003869wrap_init(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003870{
3871 initproc func = (initproc)wrapped;
3872
Guido van Rossumc8e56452001-10-22 00:43:43 +00003873 if (func(self, args, kwds) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003874 return NULL;
3875 Py_INCREF(Py_None);
3876 return Py_None;
3877}
3878
Tim Peters6d6c1a32001-08-02 04:15:00 +00003879static PyObject *
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003880tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003881{
Barry Warsaw60f01882001-08-22 19:24:42 +00003882 PyTypeObject *type, *subtype, *staticbase;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003883 PyObject *arg0, *res;
3884
3885 if (self == NULL || !PyType_Check(self))
3886 Py_FatalError("__new__() called with non-type 'self'");
3887 type = (PyTypeObject *)self;
3888 if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) {
Barry Warsaw60f01882001-08-22 19:24:42 +00003889 PyErr_Format(PyExc_TypeError,
3890 "%s.__new__(): not enough arguments",
3891 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003892 return NULL;
3893 }
3894 arg0 = PyTuple_GET_ITEM(args, 0);
3895 if (!PyType_Check(arg0)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00003896 PyErr_Format(PyExc_TypeError,
3897 "%s.__new__(X): X is not a type object (%s)",
3898 type->tp_name,
3899 arg0->ob_type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003900 return NULL;
3901 }
3902 subtype = (PyTypeObject *)arg0;
3903 if (!PyType_IsSubtype(subtype, type)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00003904 PyErr_Format(PyExc_TypeError,
3905 "%s.__new__(%s): %s is not a subtype of %s",
3906 type->tp_name,
3907 subtype->tp_name,
3908 subtype->tp_name,
3909 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003910 return NULL;
3911 }
Barry Warsaw60f01882001-08-22 19:24:42 +00003912
3913 /* Check that the use doesn't do something silly and unsafe like
Tim Petersa427a2b2001-10-29 22:25:45 +00003914 object.__new__(dict). To do this, we check that the
Barry Warsaw60f01882001-08-22 19:24:42 +00003915 most derived base that's not a heap type is this type. */
3916 staticbase = subtype;
3917 while (staticbase && (staticbase->tp_flags & Py_TPFLAGS_HEAPTYPE))
3918 staticbase = staticbase->tp_base;
Guido van Rossuma8c60f42001-09-14 19:43:36 +00003919 if (staticbase->tp_new != type->tp_new) {
Barry Warsaw60f01882001-08-22 19:24:42 +00003920 PyErr_Format(PyExc_TypeError,
3921 "%s.__new__(%s) is not safe, use %s.__new__()",
3922 type->tp_name,
3923 subtype->tp_name,
3924 staticbase == NULL ? "?" : staticbase->tp_name);
3925 return NULL;
3926 }
3927
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003928 args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
3929 if (args == NULL)
3930 return NULL;
3931 res = type->tp_new(subtype, args, kwds);
3932 Py_DECREF(args);
3933 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003934}
3935
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003936static struct PyMethodDef tp_new_methoddef[] = {
3937 {"__new__", (PyCFunction)tp_new_wrapper, METH_KEYWORDS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00003938 PyDoc_STR("T.__new__(S, ...) -> "
3939 "a new object with type S, a subtype of T")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00003940 {0}
3941};
3942
3943static int
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003944add_tp_new_wrapper(PyTypeObject *type)
3945{
Guido van Rossumf040ede2001-08-07 16:40:56 +00003946 PyObject *func;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003947
Guido van Rossum687ae002001-10-15 22:03:32 +00003948 if (PyDict_GetItemString(type->tp_dict, "__new__") != NULL)
Guido van Rossumf040ede2001-08-07 16:40:56 +00003949 return 0;
3950 func = PyCFunction_New(tp_new_methoddef, (PyObject *)type);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003951 if (func == NULL)
3952 return -1;
Guido van Rossum687ae002001-10-15 22:03:32 +00003953 return PyDict_SetItemString(type->tp_dict, "__new__", func);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003954}
3955
Guido van Rossumf040ede2001-08-07 16:40:56 +00003956/* Slot wrappers that call the corresponding __foo__ slot. See comments
3957 below at override_slots() for more explanation. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003958
Guido van Rossumdc91b992001-08-08 22:26:22 +00003959#define SLOT0(FUNCNAME, OPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003960static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003961FUNCNAME(PyObject *self) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003962{ \
Guido van Rossum5592e4d2001-08-28 18:28:21 +00003963 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00003964 return call_method(self, OPSTR, &cache_str, "()"); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003965}
3966
Guido van Rossumdc91b992001-08-08 22:26:22 +00003967#define SLOT1(FUNCNAME, OPSTR, ARG1TYPE, ARGCODES) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003968static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003969FUNCNAME(PyObject *self, ARG1TYPE arg1) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003970{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00003971 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00003972 return call_method(self, OPSTR, &cache_str, "(" ARGCODES ")", arg1); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003973}
3974
Guido van Rossumcd118802003-01-06 22:57:47 +00003975/* Boolean helper for SLOT1BINFULL().
3976 right.__class__ is a nontrivial subclass of left.__class__. */
3977static int
3978method_is_overloaded(PyObject *left, PyObject *right, char *name)
3979{
3980 PyObject *a, *b;
3981 int ok;
3982
3983 b = PyObject_GetAttrString((PyObject *)(right->ob_type), name);
3984 if (b == NULL) {
3985 PyErr_Clear();
3986 /* If right doesn't have it, it's not overloaded */
3987 return 0;
3988 }
3989
3990 a = PyObject_GetAttrString((PyObject *)(left->ob_type), name);
3991 if (a == NULL) {
3992 PyErr_Clear();
3993 Py_DECREF(b);
3994 /* If right has it but left doesn't, it's overloaded */
3995 return 1;
3996 }
3997
3998 ok = PyObject_RichCompareBool(a, b, Py_NE);
3999 Py_DECREF(a);
4000 Py_DECREF(b);
4001 if (ok < 0) {
4002 PyErr_Clear();
4003 return 0;
4004 }
4005
4006 return ok;
4007}
4008
Guido van Rossumdc91b992001-08-08 22:26:22 +00004009
4010#define SLOT1BINFULL(FUNCNAME, TESTFUNC, SLOTNAME, OPSTR, ROPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004011static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004012FUNCNAME(PyObject *self, PyObject *other) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004013{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00004014 static PyObject *cache_str, *rcache_str; \
Guido van Rossum55f20992001-10-01 17:18:22 +00004015 int do_other = self->ob_type != other->ob_type && \
4016 other->ob_type->tp_as_number != NULL && \
4017 other->ob_type->tp_as_number->SLOTNAME == TESTFUNC; \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004018 if (self->ob_type->tp_as_number != NULL && \
4019 self->ob_type->tp_as_number->SLOTNAME == TESTFUNC) { \
4020 PyObject *r; \
Guido van Rossum55f20992001-10-01 17:18:22 +00004021 if (do_other && \
Guido van Rossumcd118802003-01-06 22:57:47 +00004022 PyType_IsSubtype(other->ob_type, self->ob_type) && \
4023 method_is_overloaded(self, other, ROPSTR)) { \
Guido van Rossum55f20992001-10-01 17:18:22 +00004024 r = call_maybe( \
4025 other, ROPSTR, &rcache_str, "(O)", self); \
4026 if (r != Py_NotImplemented) \
4027 return r; \
4028 Py_DECREF(r); \
4029 do_other = 0; \
4030 } \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00004031 r = call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00004032 self, OPSTR, &cache_str, "(O)", other); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004033 if (r != Py_NotImplemented || \
4034 other->ob_type == self->ob_type) \
4035 return r; \
4036 Py_DECREF(r); \
4037 } \
Guido van Rossum55f20992001-10-01 17:18:22 +00004038 if (do_other) { \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00004039 return call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00004040 other, ROPSTR, &rcache_str, "(O)", self); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004041 } \
4042 Py_INCREF(Py_NotImplemented); \
4043 return Py_NotImplemented; \
4044}
4045
4046#define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) \
4047 SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR)
4048
4049#define SLOT2(FUNCNAME, OPSTR, ARG1TYPE, ARG2TYPE, ARGCODES) \
4050static PyObject * \
4051FUNCNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \
4052{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00004053 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00004054 return call_method(self, OPSTR, &cache_str, \
4055 "(" ARGCODES ")", arg1, arg2); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004056}
4057
4058static int
4059slot_sq_length(PyObject *self)
4060{
Guido van Rossum2730b132001-08-28 18:22:14 +00004061 static PyObject *len_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00004062 PyObject *res = call_method(self, "__len__", &len_str, "()");
Guido van Rossum26111622001-10-01 16:42:49 +00004063 int len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004064
4065 if (res == NULL)
4066 return -1;
Guido van Rossum26111622001-10-01 16:42:49 +00004067 len = (int)PyInt_AsLong(res);
4068 Py_DECREF(res);
Jeremy Hylton73a088e2002-07-25 16:43:29 +00004069 if (len == -1 && PyErr_Occurred())
4070 return -1;
Jeremy Hyltonf20fcf92002-07-25 16:06:15 +00004071 if (len < 0) {
Guido van Rossum22b13872002-08-06 21:41:44 +00004072 PyErr_SetString(PyExc_ValueError,
Jeremy Hyltonf20fcf92002-07-25 16:06:15 +00004073 "__len__() should return >= 0");
4074 return -1;
4075 }
Guido van Rossum26111622001-10-01 16:42:49 +00004076 return len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004077}
4078
Guido van Rossumdc91b992001-08-08 22:26:22 +00004079SLOT1(slot_sq_concat, "__add__", PyObject *, "O")
4080SLOT1(slot_sq_repeat, "__mul__", int, "i")
Guido van Rossumf4593e02001-10-03 12:09:30 +00004081
4082/* Super-optimized version of slot_sq_item.
4083 Other slots could do the same... */
4084static PyObject *
4085slot_sq_item(PyObject *self, int i)
4086{
4087 static PyObject *getitem_str;
4088 PyObject *func, *args = NULL, *ival = NULL, *retval = NULL;
4089 descrgetfunc f;
4090
4091 if (getitem_str == NULL) {
4092 getitem_str = PyString_InternFromString("__getitem__");
4093 if (getitem_str == NULL)
4094 return NULL;
4095 }
4096 func = _PyType_Lookup(self->ob_type, getitem_str);
4097 if (func != NULL) {
Guido van Rossumf4593e02001-10-03 12:09:30 +00004098 if ((f = func->ob_type->tp_descr_get) == NULL)
4099 Py_INCREF(func);
Neal Norwitz673cd822002-10-18 16:33:13 +00004100 else {
Guido van Rossumf4593e02001-10-03 12:09:30 +00004101 func = f(func, self, (PyObject *)(self->ob_type));
Neal Norwitz673cd822002-10-18 16:33:13 +00004102 if (func == NULL) {
4103 return NULL;
4104 }
4105 }
Guido van Rossumf4593e02001-10-03 12:09:30 +00004106 ival = PyInt_FromLong(i);
4107 if (ival != NULL) {
4108 args = PyTuple_New(1);
4109 if (args != NULL) {
4110 PyTuple_SET_ITEM(args, 0, ival);
4111 retval = PyObject_Call(func, args, NULL);
4112 Py_XDECREF(args);
4113 Py_XDECREF(func);
4114 return retval;
4115 }
4116 }
4117 }
4118 else {
4119 PyErr_SetObject(PyExc_AttributeError, getitem_str);
4120 }
4121 Py_XDECREF(args);
4122 Py_XDECREF(ival);
4123 Py_XDECREF(func);
4124 return NULL;
4125}
4126
Guido van Rossumdc91b992001-08-08 22:26:22 +00004127SLOT2(slot_sq_slice, "__getslice__", int, int, "ii")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004128
4129static int
4130slot_sq_ass_item(PyObject *self, int index, PyObject *value)
4131{
4132 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004133 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004134
4135 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004136 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004137 "(i)", index);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004138 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004139 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004140 "(iO)", index, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004141 if (res == NULL)
4142 return -1;
4143 Py_DECREF(res);
4144 return 0;
4145}
4146
4147static int
4148slot_sq_ass_slice(PyObject *self, int i, int j, PyObject *value)
4149{
4150 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004151 static PyObject *delslice_str, *setslice_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004152
4153 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004154 res = call_method(self, "__delslice__", &delslice_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004155 "(ii)", i, j);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004156 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004157 res = call_method(self, "__setslice__", &setslice_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004158 "(iiO)", i, j, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004159 if (res == NULL)
4160 return -1;
4161 Py_DECREF(res);
4162 return 0;
4163}
4164
4165static int
4166slot_sq_contains(PyObject *self, PyObject *value)
4167{
Guido van Rossumb8f63662001-08-15 23:57:02 +00004168 PyObject *func, *res, *args;
Tim Petersbf9b2442003-03-23 05:35:36 +00004169 int result = -1;
4170
Guido van Rossum60718732001-08-28 17:47:51 +00004171 static PyObject *contains_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004172
Guido van Rossum55f20992001-10-01 17:18:22 +00004173 func = lookup_maybe(self, "__contains__", &contains_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004174 if (func != NULL) {
Raymond Hettinger8ae46892003-10-12 19:09:37 +00004175 args = PyTuple_Pack(1, value);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004176 if (args == NULL)
4177 res = NULL;
4178 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00004179 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004180 Py_DECREF(args);
4181 }
4182 Py_DECREF(func);
Tim Petersbf9b2442003-03-23 05:35:36 +00004183 if (res != NULL) {
4184 result = PyObject_IsTrue(res);
4185 Py_DECREF(res);
4186 }
Guido van Rossumb8f63662001-08-15 23:57:02 +00004187 }
Tim Petersbf9b2442003-03-23 05:35:36 +00004188 else if (! PyErr_Occurred()) {
4189 result = _PySequence_IterSearch(self, value,
4190 PY_ITERSEARCH_CONTAINS);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004191 }
Tim Petersbf9b2442003-03-23 05:35:36 +00004192 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004193}
4194
Guido van Rossumdc91b992001-08-08 22:26:22 +00004195SLOT1(slot_sq_inplace_concat, "__iadd__", PyObject *, "O")
4196SLOT1(slot_sq_inplace_repeat, "__imul__", int, "i")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004197
4198#define slot_mp_length slot_sq_length
4199
Guido van Rossumdc91b992001-08-08 22:26:22 +00004200SLOT1(slot_mp_subscript, "__getitem__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004201
4202static int
4203slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value)
4204{
4205 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004206 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004207
4208 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004209 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004210 "(O)", key);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004211 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004212 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004213 "(OO)", key, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004214 if (res == NULL)
4215 return -1;
4216 Py_DECREF(res);
4217 return 0;
4218}
4219
Guido van Rossumdc91b992001-08-08 22:26:22 +00004220SLOT1BIN(slot_nb_add, nb_add, "__add__", "__radd__")
4221SLOT1BIN(slot_nb_subtract, nb_subtract, "__sub__", "__rsub__")
4222SLOT1BIN(slot_nb_multiply, nb_multiply, "__mul__", "__rmul__")
4223SLOT1BIN(slot_nb_divide, nb_divide, "__div__", "__rdiv__")
4224SLOT1BIN(slot_nb_remainder, nb_remainder, "__mod__", "__rmod__")
4225SLOT1BIN(slot_nb_divmod, nb_divmod, "__divmod__", "__rdivmod__")
4226
Jeremy Hylton938ace62002-07-17 16:30:39 +00004227static PyObject *slot_nb_power(PyObject *, PyObject *, PyObject *);
Guido van Rossumdc91b992001-08-08 22:26:22 +00004228
4229SLOT1BINFULL(slot_nb_power_binary, slot_nb_power,
4230 nb_power, "__pow__", "__rpow__")
4231
4232static PyObject *
4233slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus)
4234{
Guido van Rossum2730b132001-08-28 18:22:14 +00004235 static PyObject *pow_str;
4236
Guido van Rossumdc91b992001-08-08 22:26:22 +00004237 if (modulus == Py_None)
4238 return slot_nb_power_binary(self, other);
Guido van Rossum23094982002-06-10 14:30:43 +00004239 /* Three-arg power doesn't use __rpow__. But ternary_op
4240 can call this when the second argument's type uses
4241 slot_nb_power, so check before calling self.__pow__. */
4242 if (self->ob_type->tp_as_number != NULL &&
4243 self->ob_type->tp_as_number->nb_power == slot_nb_power) {
4244 return call_method(self, "__pow__", &pow_str,
4245 "(OO)", other, modulus);
4246 }
4247 Py_INCREF(Py_NotImplemented);
4248 return Py_NotImplemented;
Guido van Rossumdc91b992001-08-08 22:26:22 +00004249}
4250
4251SLOT0(slot_nb_negative, "__neg__")
4252SLOT0(slot_nb_positive, "__pos__")
4253SLOT0(slot_nb_absolute, "__abs__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004254
4255static int
4256slot_nb_nonzero(PyObject *self)
4257{
Tim Petersea7f75d2002-12-07 21:39:16 +00004258 PyObject *func, *args;
Guido van Rossum60718732001-08-28 17:47:51 +00004259 static PyObject *nonzero_str, *len_str;
Tim Petersea7f75d2002-12-07 21:39:16 +00004260 int result = -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004261
Guido van Rossum55f20992001-10-01 17:18:22 +00004262 func = lookup_maybe(self, "__nonzero__", &nonzero_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004263 if (func == NULL) {
Guido van Rossum55f20992001-10-01 17:18:22 +00004264 if (PyErr_Occurred())
Guido van Rossumb8f63662001-08-15 23:57:02 +00004265 return -1;
Guido van Rossum55f20992001-10-01 17:18:22 +00004266 func = lookup_maybe(self, "__len__", &len_str);
Tim Petersea7f75d2002-12-07 21:39:16 +00004267 if (func == NULL)
4268 return PyErr_Occurred() ? -1 : 1;
4269 }
4270 args = PyTuple_New(0);
4271 if (args != NULL) {
4272 PyObject *temp = PyObject_Call(func, args, NULL);
4273 Py_DECREF(args);
4274 if (temp != NULL) {
Jeremy Hylton3e3159c2003-06-27 17:38:27 +00004275 if (PyInt_CheckExact(temp) || PyBool_Check(temp))
Jeremy Hylton090a3492003-06-27 16:46:45 +00004276 result = PyObject_IsTrue(temp);
4277 else {
4278 PyErr_Format(PyExc_TypeError,
4279 "__nonzero__ should return "
4280 "bool or int, returned %s",
4281 temp->ob_type->tp_name);
Jeremy Hylton3e3159c2003-06-27 17:38:27 +00004282 result = -1;
Jeremy Hylton090a3492003-06-27 16:46:45 +00004283 }
Tim Petersea7f75d2002-12-07 21:39:16 +00004284 Py_DECREF(temp);
Guido van Rossum55f20992001-10-01 17:18:22 +00004285 }
Guido van Rossumb8f63662001-08-15 23:57:02 +00004286 }
Guido van Rossum55f20992001-10-01 17:18:22 +00004287 Py_DECREF(func);
Tim Petersea7f75d2002-12-07 21:39:16 +00004288 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004289}
4290
Guido van Rossumdc91b992001-08-08 22:26:22 +00004291SLOT0(slot_nb_invert, "__invert__")
4292SLOT1BIN(slot_nb_lshift, nb_lshift, "__lshift__", "__rlshift__")
4293SLOT1BIN(slot_nb_rshift, nb_rshift, "__rshift__", "__rrshift__")
4294SLOT1BIN(slot_nb_and, nb_and, "__and__", "__rand__")
4295SLOT1BIN(slot_nb_xor, nb_xor, "__xor__", "__rxor__")
4296SLOT1BIN(slot_nb_or, nb_or, "__or__", "__ror__")
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004297
4298static int
4299slot_nb_coerce(PyObject **a, PyObject **b)
4300{
4301 static PyObject *coerce_str;
4302 PyObject *self = *a, *other = *b;
4303
4304 if (self->ob_type->tp_as_number != NULL &&
4305 self->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
4306 PyObject *r;
4307 r = call_maybe(
4308 self, "__coerce__", &coerce_str, "(O)", other);
4309 if (r == NULL)
4310 return -1;
4311 if (r == Py_NotImplemented) {
4312 Py_DECREF(r);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004313 }
Guido van Rossum55f20992001-10-01 17:18:22 +00004314 else {
4315 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
4316 PyErr_SetString(PyExc_TypeError,
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004317 "__coerce__ didn't return a 2-tuple");
Guido van Rossum55f20992001-10-01 17:18:22 +00004318 Py_DECREF(r);
4319 return -1;
4320 }
4321 *a = PyTuple_GET_ITEM(r, 0);
4322 Py_INCREF(*a);
4323 *b = PyTuple_GET_ITEM(r, 1);
4324 Py_INCREF(*b);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004325 Py_DECREF(r);
Guido van Rossum55f20992001-10-01 17:18:22 +00004326 return 0;
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004327 }
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004328 }
4329 if (other->ob_type->tp_as_number != NULL &&
4330 other->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
4331 PyObject *r;
4332 r = call_maybe(
4333 other, "__coerce__", &coerce_str, "(O)", self);
4334 if (r == NULL)
4335 return -1;
4336 if (r == Py_NotImplemented) {
4337 Py_DECREF(r);
4338 return 1;
4339 }
4340 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
4341 PyErr_SetString(PyExc_TypeError,
4342 "__coerce__ didn't return a 2-tuple");
4343 Py_DECREF(r);
4344 return -1;
4345 }
4346 *a = PyTuple_GET_ITEM(r, 1);
4347 Py_INCREF(*a);
4348 *b = PyTuple_GET_ITEM(r, 0);
4349 Py_INCREF(*b);
4350 Py_DECREF(r);
4351 return 0;
4352 }
4353 return 1;
4354}
4355
Guido van Rossumdc91b992001-08-08 22:26:22 +00004356SLOT0(slot_nb_int, "__int__")
4357SLOT0(slot_nb_long, "__long__")
4358SLOT0(slot_nb_float, "__float__")
4359SLOT0(slot_nb_oct, "__oct__")
4360SLOT0(slot_nb_hex, "__hex__")
4361SLOT1(slot_nb_inplace_add, "__iadd__", PyObject *, "O")
4362SLOT1(slot_nb_inplace_subtract, "__isub__", PyObject *, "O")
4363SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *, "O")
4364SLOT1(slot_nb_inplace_divide, "__idiv__", PyObject *, "O")
4365SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *, "O")
Guido van Rossum6e5680f2002-10-15 01:01:53 +00004366SLOT1(slot_nb_inplace_power, "__ipow__", PyObject *, "O")
Guido van Rossumdc91b992001-08-08 22:26:22 +00004367SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *, "O")
4368SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *, "O")
4369SLOT1(slot_nb_inplace_and, "__iand__", PyObject *, "O")
4370SLOT1(slot_nb_inplace_xor, "__ixor__", PyObject *, "O")
4371SLOT1(slot_nb_inplace_or, "__ior__", PyObject *, "O")
4372SLOT1BIN(slot_nb_floor_divide, nb_floor_divide,
4373 "__floordiv__", "__rfloordiv__")
4374SLOT1BIN(slot_nb_true_divide, nb_true_divide, "__truediv__", "__rtruediv__")
4375SLOT1(slot_nb_inplace_floor_divide, "__ifloordiv__", PyObject *, "O")
4376SLOT1(slot_nb_inplace_true_divide, "__itruediv__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004377
4378static int
Guido van Rossumb8f63662001-08-15 23:57:02 +00004379half_compare(PyObject *self, PyObject *other)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004380{
Guido van Rossumb8f63662001-08-15 23:57:02 +00004381 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004382 static PyObject *cmp_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004383 int c;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004384
Guido van Rossum60718732001-08-28 17:47:51 +00004385 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004386 if (func == NULL) {
4387 PyErr_Clear();
4388 }
4389 else {
Raymond Hettinger8ae46892003-10-12 19:09:37 +00004390 args = PyTuple_Pack(1, other);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004391 if (args == NULL)
4392 res = NULL;
4393 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00004394 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004395 Py_DECREF(args);
4396 }
Raymond Hettingerab5dae32002-06-24 13:08:16 +00004397 Py_DECREF(func);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004398 if (res != Py_NotImplemented) {
4399 if (res == NULL)
4400 return -2;
4401 c = PyInt_AsLong(res);
4402 Py_DECREF(res);
4403 if (c == -1 && PyErr_Occurred())
4404 return -2;
4405 return (c < 0) ? -1 : (c > 0) ? 1 : 0;
4406 }
4407 Py_DECREF(res);
4408 }
4409 return 2;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004410}
4411
Guido van Rossumab3b0342001-09-18 20:38:53 +00004412/* This slot is published for the benefit of try_3way_compare in object.c */
4413int
4414_PyObject_SlotCompare(PyObject *self, PyObject *other)
Guido van Rossumb8f63662001-08-15 23:57:02 +00004415{
4416 int c;
4417
Guido van Rossumab3b0342001-09-18 20:38:53 +00004418 if (self->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00004419 c = half_compare(self, other);
4420 if (c <= 1)
4421 return c;
4422 }
Guido van Rossumab3b0342001-09-18 20:38:53 +00004423 if (other->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00004424 c = half_compare(other, self);
4425 if (c < -1)
4426 return -2;
4427 if (c <= 1)
4428 return -c;
4429 }
4430 return (void *)self < (void *)other ? -1 :
4431 (void *)self > (void *)other ? 1 : 0;
4432}
4433
4434static PyObject *
4435slot_tp_repr(PyObject *self)
4436{
4437 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004438 static PyObject *repr_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004439
Guido van Rossum60718732001-08-28 17:47:51 +00004440 func = lookup_method(self, "__repr__", &repr_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004441 if (func != NULL) {
4442 res = PyEval_CallObject(func, NULL);
4443 Py_DECREF(func);
4444 return res;
4445 }
Barry Warsaw7ce36942001-08-24 18:34:26 +00004446 PyErr_Clear();
4447 return PyString_FromFormat("<%s object at %p>",
4448 self->ob_type->tp_name, self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004449}
4450
4451static PyObject *
4452slot_tp_str(PyObject *self)
4453{
4454 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004455 static PyObject *str_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004456
Guido van Rossum60718732001-08-28 17:47:51 +00004457 func = lookup_method(self, "__str__", &str_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004458 if (func != NULL) {
4459 res = PyEval_CallObject(func, NULL);
4460 Py_DECREF(func);
4461 return res;
4462 }
4463 else {
4464 PyErr_Clear();
4465 return slot_tp_repr(self);
4466 }
4467}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004468
4469static long
4470slot_tp_hash(PyObject *self)
4471{
Tim Peters61ce0a92002-12-06 23:38:02 +00004472 PyObject *func;
Guido van Rossum60718732001-08-28 17:47:51 +00004473 static PyObject *hash_str, *eq_str, *cmp_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004474 long h;
4475
Guido van Rossum60718732001-08-28 17:47:51 +00004476 func = lookup_method(self, "__hash__", &hash_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004477
4478 if (func != NULL) {
Tim Peters61ce0a92002-12-06 23:38:02 +00004479 PyObject *res = PyEval_CallObject(func, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004480 Py_DECREF(func);
4481 if (res == NULL)
4482 return -1;
4483 h = PyInt_AsLong(res);
Tim Peters61ce0a92002-12-06 23:38:02 +00004484 Py_DECREF(res);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004485 }
4486 else {
4487 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00004488 func = lookup_method(self, "__eq__", &eq_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004489 if (func == NULL) {
4490 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00004491 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004492 }
4493 if (func != NULL) {
4494 Py_DECREF(func);
4495 PyErr_SetString(PyExc_TypeError, "unhashable type");
4496 return -1;
4497 }
4498 PyErr_Clear();
4499 h = _Py_HashPointer((void *)self);
4500 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004501 if (h == -1 && !PyErr_Occurred())
4502 h = -2;
4503 return h;
4504}
4505
4506static PyObject *
4507slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds)
4508{
Guido van Rossum60718732001-08-28 17:47:51 +00004509 static PyObject *call_str;
4510 PyObject *meth = lookup_method(self, "__call__", &call_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004511 PyObject *res;
4512
4513 if (meth == NULL)
4514 return NULL;
4515 res = PyObject_Call(meth, args, kwds);
4516 Py_DECREF(meth);
4517 return res;
4518}
4519
Guido van Rossum14a6f832001-10-17 13:59:09 +00004520/* There are two slot dispatch functions for tp_getattro.
4521
4522 - slot_tp_getattro() is used when __getattribute__ is overridden
4523 but no __getattr__ hook is present;
4524
4525 - slot_tp_getattr_hook() is used when a __getattr__ hook is present.
4526
Guido van Rossumc334df52002-04-04 23:44:47 +00004527 The code in update_one_slot() always installs slot_tp_getattr_hook(); this
4528 detects the absence of __getattr__ and then installs the simpler slot if
4529 necessary. */
Guido van Rossum14a6f832001-10-17 13:59:09 +00004530
Tim Peters6d6c1a32001-08-02 04:15:00 +00004531static PyObject *
4532slot_tp_getattro(PyObject *self, PyObject *name)
4533{
Guido van Rossum14a6f832001-10-17 13:59:09 +00004534 static PyObject *getattribute_str = NULL;
4535 return call_method(self, "__getattribute__", &getattribute_str,
4536 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004537}
4538
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004539static PyObject *
4540slot_tp_getattr_hook(PyObject *self, PyObject *name)
4541{
4542 PyTypeObject *tp = self->ob_type;
4543 PyObject *getattr, *getattribute, *res;
4544 static PyObject *getattribute_str = NULL;
4545 static PyObject *getattr_str = NULL;
4546
4547 if (getattr_str == NULL) {
4548 getattr_str = PyString_InternFromString("__getattr__");
4549 if (getattr_str == NULL)
4550 return NULL;
4551 }
4552 if (getattribute_str == NULL) {
4553 getattribute_str =
4554 PyString_InternFromString("__getattribute__");
4555 if (getattribute_str == NULL)
4556 return NULL;
4557 }
4558 getattr = _PyType_Lookup(tp, getattr_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00004559 if (getattr == NULL) {
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004560 /* No __getattr__ hook: use a simpler dispatcher */
4561 tp->tp_getattro = slot_tp_getattro;
4562 return slot_tp_getattro(self, name);
4563 }
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004564 getattribute = _PyType_Lookup(tp, getattribute_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00004565 if (getattribute == NULL ||
4566 (getattribute->ob_type == &PyWrapperDescr_Type &&
4567 ((PyWrapperDescrObject *)getattribute)->d_wrapped ==
4568 (void *)PyObject_GenericGetAttr))
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004569 res = PyObject_GenericGetAttr(self, name);
4570 else
4571 res = PyObject_CallFunction(getattribute, "OO", self, name);
Guido van Rossum14a6f832001-10-17 13:59:09 +00004572 if (res == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) {
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004573 PyErr_Clear();
4574 res = PyObject_CallFunction(getattr, "OO", self, name);
4575 }
4576 return res;
4577}
4578
Tim Peters6d6c1a32001-08-02 04:15:00 +00004579static int
4580slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value)
4581{
4582 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004583 static PyObject *delattr_str, *setattr_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004584
4585 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004586 res = call_method(self, "__delattr__", &delattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004587 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004588 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004589 res = call_method(self, "__setattr__", &setattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004590 "(OO)", name, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004591 if (res == NULL)
4592 return -1;
4593 Py_DECREF(res);
4594 return 0;
4595}
4596
4597/* Map rich comparison operators to their __xx__ namesakes */
4598static char *name_op[] = {
4599 "__lt__",
4600 "__le__",
4601 "__eq__",
4602 "__ne__",
4603 "__gt__",
4604 "__ge__",
4605};
4606
4607static PyObject *
Guido van Rossumb8f63662001-08-15 23:57:02 +00004608half_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004609{
Guido van Rossumb8f63662001-08-15 23:57:02 +00004610 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004611 static PyObject *op_str[6];
Tim Peters6d6c1a32001-08-02 04:15:00 +00004612
Guido van Rossum60718732001-08-28 17:47:51 +00004613 func = lookup_method(self, name_op[op], &op_str[op]);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004614 if (func == NULL) {
4615 PyErr_Clear();
4616 Py_INCREF(Py_NotImplemented);
4617 return Py_NotImplemented;
4618 }
Raymond Hettinger8ae46892003-10-12 19:09:37 +00004619 args = PyTuple_Pack(1, other);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004620 if (args == NULL)
4621 res = NULL;
4622 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00004623 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004624 Py_DECREF(args);
4625 }
4626 Py_DECREF(func);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004627 return res;
4628}
4629
Guido van Rossumb8f63662001-08-15 23:57:02 +00004630/* Map rich comparison operators to their swapped version, e.g. LT --> GT */
4631static int swapped_op[] = {Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE};
4632
4633static PyObject *
4634slot_tp_richcompare(PyObject *self, PyObject *other, int op)
4635{
4636 PyObject *res;
4637
4638 if (self->ob_type->tp_richcompare == slot_tp_richcompare) {
4639 res = half_richcompare(self, other, op);
4640 if (res != Py_NotImplemented)
4641 return res;
4642 Py_DECREF(res);
4643 }
4644 if (other->ob_type->tp_richcompare == slot_tp_richcompare) {
4645 res = half_richcompare(other, self, swapped_op[op]);
4646 if (res != Py_NotImplemented) {
4647 return res;
4648 }
4649 Py_DECREF(res);
4650 }
4651 Py_INCREF(Py_NotImplemented);
4652 return Py_NotImplemented;
4653}
4654
4655static PyObject *
4656slot_tp_iter(PyObject *self)
4657{
4658 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004659 static PyObject *iter_str, *getitem_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004660
Guido van Rossum60718732001-08-28 17:47:51 +00004661 func = lookup_method(self, "__iter__", &iter_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004662 if (func != NULL) {
Guido van Rossum84b2bed2002-08-16 17:01:09 +00004663 PyObject *args;
4664 args = res = PyTuple_New(0);
4665 if (args != NULL) {
4666 res = PyObject_Call(func, args, NULL);
4667 Py_DECREF(args);
4668 }
4669 Py_DECREF(func);
4670 return res;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004671 }
4672 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00004673 func = lookup_method(self, "__getitem__", &getitem_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004674 if (func == NULL) {
Guido van Rossumd4641072002-04-03 02:13:37 +00004675 PyErr_SetString(PyExc_TypeError,
4676 "iteration over non-sequence");
Guido van Rossumb8f63662001-08-15 23:57:02 +00004677 return NULL;
4678 }
4679 Py_DECREF(func);
4680 return PySeqIter_New(self);
4681}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004682
4683static PyObject *
4684slot_tp_iternext(PyObject *self)
4685{
Guido van Rossum2730b132001-08-28 18:22:14 +00004686 static PyObject *next_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00004687 return call_method(self, "next", &next_str, "()");
Tim Peters6d6c1a32001-08-02 04:15:00 +00004688}
4689
Guido van Rossum1a493502001-08-17 16:47:50 +00004690static PyObject *
4691slot_tp_descr_get(PyObject *self, PyObject *obj, PyObject *type)
4692{
4693 PyTypeObject *tp = self->ob_type;
4694 PyObject *get;
4695 static PyObject *get_str = NULL;
4696
4697 if (get_str == NULL) {
4698 get_str = PyString_InternFromString("__get__");
4699 if (get_str == NULL)
4700 return NULL;
4701 }
4702 get = _PyType_Lookup(tp, get_str);
4703 if (get == NULL) {
4704 /* Avoid further slowdowns */
4705 if (tp->tp_descr_get == slot_tp_descr_get)
4706 tp->tp_descr_get = NULL;
4707 Py_INCREF(self);
4708 return self;
4709 }
Guido van Rossum2c252392001-08-24 10:13:31 +00004710 if (obj == NULL)
4711 obj = Py_None;
4712 if (type == NULL)
4713 type = Py_None;
Guido van Rossum1a493502001-08-17 16:47:50 +00004714 return PyObject_CallFunction(get, "OOO", self, obj, type);
4715}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004716
4717static int
4718slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value)
4719{
Guido van Rossum2c252392001-08-24 10:13:31 +00004720 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004721 static PyObject *del_str, *set_str;
Guido van Rossum2c252392001-08-24 10:13:31 +00004722
4723 if (value == NULL)
Guido van Rossum1d5b3f22001-12-03 00:08:33 +00004724 res = call_method(self, "__delete__", &del_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004725 "(O)", target);
Guido van Rossum2c252392001-08-24 10:13:31 +00004726 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004727 res = call_method(self, "__set__", &set_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004728 "(OO)", target, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004729 if (res == NULL)
4730 return -1;
4731 Py_DECREF(res);
4732 return 0;
4733}
4734
4735static int
4736slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds)
4737{
Guido van Rossum60718732001-08-28 17:47:51 +00004738 static PyObject *init_str;
4739 PyObject *meth = lookup_method(self, "__init__", &init_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004740 PyObject *res;
4741
4742 if (meth == NULL)
4743 return -1;
4744 res = PyObject_Call(meth, args, kwds);
4745 Py_DECREF(meth);
4746 if (res == NULL)
4747 return -1;
4748 Py_DECREF(res);
4749 return 0;
4750}
4751
4752static PyObject *
4753slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
4754{
Guido van Rossum7bed2132002-08-08 21:57:53 +00004755 static PyObject *new_str;
4756 PyObject *func;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004757 PyObject *newargs, *x;
4758 int i, n;
4759
Guido van Rossum7bed2132002-08-08 21:57:53 +00004760 if (new_str == NULL) {
4761 new_str = PyString_InternFromString("__new__");
4762 if (new_str == NULL)
4763 return NULL;
4764 }
4765 func = PyObject_GetAttr((PyObject *)type, new_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004766 if (func == NULL)
4767 return NULL;
4768 assert(PyTuple_Check(args));
4769 n = PyTuple_GET_SIZE(args);
4770 newargs = PyTuple_New(n+1);
4771 if (newargs == NULL)
4772 return NULL;
4773 Py_INCREF(type);
4774 PyTuple_SET_ITEM(newargs, 0, (PyObject *)type);
4775 for (i = 0; i < n; i++) {
4776 x = PyTuple_GET_ITEM(args, i);
4777 Py_INCREF(x);
4778 PyTuple_SET_ITEM(newargs, i+1, x);
4779 }
4780 x = PyObject_Call(func, newargs, kwds);
Guido van Rossum25d18072001-10-01 15:55:28 +00004781 Py_DECREF(newargs);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004782 Py_DECREF(func);
4783 return x;
4784}
4785
Guido van Rossumfebd61d2002-08-08 20:55:20 +00004786static void
4787slot_tp_del(PyObject *self)
4788{
4789 static PyObject *del_str = NULL;
4790 PyObject *del, *res;
4791 PyObject *error_type, *error_value, *error_traceback;
4792
4793 /* Temporarily resurrect the object. */
4794 assert(self->ob_refcnt == 0);
4795 self->ob_refcnt = 1;
4796
4797 /* Save the current exception, if any. */
4798 PyErr_Fetch(&error_type, &error_value, &error_traceback);
4799
4800 /* Execute __del__ method, if any. */
4801 del = lookup_maybe(self, "__del__", &del_str);
4802 if (del != NULL) {
4803 res = PyEval_CallObject(del, NULL);
4804 if (res == NULL)
4805 PyErr_WriteUnraisable(del);
4806 else
4807 Py_DECREF(res);
4808 Py_DECREF(del);
4809 }
4810
4811 /* Restore the saved exception. */
4812 PyErr_Restore(error_type, error_value, error_traceback);
4813
4814 /* Undo the temporary resurrection; can't use DECREF here, it would
4815 * cause a recursive call.
4816 */
4817 assert(self->ob_refcnt > 0);
4818 if (--self->ob_refcnt == 0)
4819 return; /* this is the normal path out */
4820
4821 /* __del__ resurrected it! Make it look like the original Py_DECREF
4822 * never happened.
4823 */
4824 {
4825 int refcnt = self->ob_refcnt;
4826 _Py_NewReference(self);
4827 self->ob_refcnt = refcnt;
4828 }
4829 assert(!PyType_IS_GC(self->ob_type) ||
4830 _Py_AS_GC(self)->gc.gc_refs != _PyGC_REFS_UNTRACKED);
4831 /* If Py_REF_DEBUG, the original decref dropped _Py_RefTotal, but
4832 * _Py_NewReference bumped it again, so that's a wash.
4833 * If Py_TRACE_REFS, _Py_NewReference re-added self to the object
4834 * chain, so no more to do there either.
4835 * If COUNT_ALLOCS, the original decref bumped tp_frees, and
4836 * _Py_NewReference bumped tp_allocs: both of those need to be
4837 * undone.
4838 */
4839#ifdef COUNT_ALLOCS
4840 --self->ob_type->tp_frees;
4841 --self->ob_type->tp_allocs;
4842#endif
4843}
4844
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004845
4846/* Table mapping __foo__ names to tp_foo offsets and slot_tp_foo wrapper
Tim Petersbf9b2442003-03-23 05:35:36 +00004847 functions. The offsets here are relative to the 'PyHeapTypeObject'
Guido van Rossume5c691a2003-03-07 15:13:17 +00004848 structure, which incorporates the additional structures used for numbers,
4849 sequences and mappings.
4850 Note that multiple names may map to the same slot (e.g. __eq__,
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004851 __ne__ etc. all map to tp_richcompare) and one name may map to multiple
Guido van Rossumc334df52002-04-04 23:44:47 +00004852 slots (e.g. __str__ affects tp_str as well as tp_repr). The table is
4853 terminated with an all-zero entry. (This table is further initialized and
4854 sorted in init_slotdefs() below.) */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004855
Guido van Rossum6d204072001-10-21 00:44:31 +00004856typedef struct wrapperbase slotdef;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004857
4858#undef TPSLOT
Guido van Rossumc8e56452001-10-22 00:43:43 +00004859#undef FLSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004860#undef ETSLOT
4861#undef SQSLOT
4862#undef MPSLOT
4863#undef NBSLOT
Guido van Rossum6d204072001-10-21 00:44:31 +00004864#undef UNSLOT
4865#undef IBSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004866#undef BINSLOT
4867#undef RBINSLOT
4868
Guido van Rossum6d204072001-10-21 00:44:31 +00004869#define TPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Neal Norwitzd47714a2002-08-13 19:01:38 +00004870 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
4871 PyDoc_STR(DOC)}
Guido van Rossumc8e56452001-10-22 00:43:43 +00004872#define FLSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC, FLAGS) \
4873 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
Neal Norwitzd47714a2002-08-13 19:01:38 +00004874 PyDoc_STR(DOC), FLAGS}
Guido van Rossum6d204072001-10-21 00:44:31 +00004875#define ETSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Guido van Rossume5c691a2003-03-07 15:13:17 +00004876 {NAME, offsetof(PyHeapTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
Neal Norwitzd47714a2002-08-13 19:01:38 +00004877 PyDoc_STR(DOC)}
Guido van Rossum6d204072001-10-21 00:44:31 +00004878#define SQSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4879 ETSLOT(NAME, as_sequence.SLOT, FUNCTION, WRAPPER, DOC)
4880#define MPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4881 ETSLOT(NAME, as_mapping.SLOT, FUNCTION, WRAPPER, DOC)
4882#define NBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4883 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, DOC)
4884#define UNSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4885 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
4886 "x." NAME "() <==> " DOC)
4887#define IBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4888 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
4889 "x." NAME "(y) <==> x" DOC "y")
4890#define BINSLOT(NAME, SLOT, FUNCTION, DOC) \
4891 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
4892 "x." NAME "(y) <==> x" DOC "y")
4893#define RBINSLOT(NAME, SLOT, FUNCTION, DOC) \
4894 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
4895 "x." NAME "(y) <==> y" DOC "x")
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004896
4897static slotdef slotdefs[] = {
Guido van Rossum6d204072001-10-21 00:44:31 +00004898 SQSLOT("__len__", sq_length, slot_sq_length, wrap_inquiry,
4899 "x.__len__() <==> len(x)"),
4900 SQSLOT("__add__", sq_concat, slot_sq_concat, wrap_binaryfunc,
4901 "x.__add__(y) <==> x+y"),
4902 SQSLOT("__mul__", sq_repeat, slot_sq_repeat, wrap_intargfunc,
4903 "x.__mul__(n) <==> x*n"),
4904 SQSLOT("__rmul__", sq_repeat, slot_sq_repeat, wrap_intargfunc,
4905 "x.__rmul__(n) <==> n*x"),
4906 SQSLOT("__getitem__", sq_item, slot_sq_item, wrap_sq_item,
4907 "x.__getitem__(y) <==> x[y]"),
4908 SQSLOT("__getslice__", sq_slice, slot_sq_slice, wrap_intintargfunc,
Brett Cannon154da9b2003-05-20 02:30:04 +00004909 "x.__getslice__(i, j) <==> x[i:j]\n\
4910 \n\
4911 Use of negative indices is not supported."),
Guido van Rossum6d204072001-10-21 00:44:31 +00004912 SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_setitem,
Brett Cannonbe67d872003-05-20 02:40:12 +00004913 "x.__setitem__(i, y) <==> x[i]=y"),
Guido van Rossum6d204072001-10-21 00:44:31 +00004914 SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_delitem,
Brett Cannonbe67d872003-05-20 02:40:12 +00004915 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004916 SQSLOT("__setslice__", sq_ass_slice, slot_sq_ass_slice,
Guido van Rossum6d204072001-10-21 00:44:31 +00004917 wrap_intintobjargproc,
Brett Cannonbe67d872003-05-20 02:40:12 +00004918 "x.__setslice__(i, j, y) <==> x[i:j]=y\n\
4919 \n\
4920 Use of negative indices is not supported."),
Guido van Rossum6d204072001-10-21 00:44:31 +00004921 SQSLOT("__delslice__", sq_ass_slice, slot_sq_ass_slice, wrap_delslice,
Brett Cannonbe67d872003-05-20 02:40:12 +00004922 "x.__delslice__(i, j) <==> del x[i:j]\n\
4923 \n\
4924 Use of negative indices is not supported."),
Guido van Rossum6d204072001-10-21 00:44:31 +00004925 SQSLOT("__contains__", sq_contains, slot_sq_contains, wrap_objobjproc,
4926 "x.__contains__(y) <==> y in x"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004927 SQSLOT("__iadd__", sq_inplace_concat, slot_sq_inplace_concat,
Guido van Rossum6d204072001-10-21 00:44:31 +00004928 wrap_binaryfunc, "x.__iadd__(y) <==> x+=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004929 SQSLOT("__imul__", sq_inplace_repeat, slot_sq_inplace_repeat,
Guido van Rossum6d204072001-10-21 00:44:31 +00004930 wrap_intargfunc, "x.__imul__(y) <==> x*=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004931
Guido van Rossum6d204072001-10-21 00:44:31 +00004932 MPSLOT("__len__", mp_length, slot_mp_length, wrap_inquiry,
4933 "x.__len__() <==> len(x)"),
Guido van Rossumfd38f8e2001-10-09 20:17:57 +00004934 MPSLOT("__getitem__", mp_subscript, slot_mp_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00004935 wrap_binaryfunc,
4936 "x.__getitem__(y) <==> x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004937 MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00004938 wrap_objobjargproc,
4939 "x.__setitem__(i, y) <==> x[i]=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004940 MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00004941 wrap_delitem,
4942 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004943
Guido van Rossum6d204072001-10-21 00:44:31 +00004944 BINSLOT("__add__", nb_add, slot_nb_add,
4945 "+"),
4946 RBINSLOT("__radd__", nb_add, slot_nb_add,
4947 "+"),
4948 BINSLOT("__sub__", nb_subtract, slot_nb_subtract,
4949 "-"),
4950 RBINSLOT("__rsub__", nb_subtract, slot_nb_subtract,
4951 "-"),
4952 BINSLOT("__mul__", nb_multiply, slot_nb_multiply,
4953 "*"),
4954 RBINSLOT("__rmul__", nb_multiply, slot_nb_multiply,
4955 "*"),
4956 BINSLOT("__div__", nb_divide, slot_nb_divide,
4957 "/"),
4958 RBINSLOT("__rdiv__", nb_divide, slot_nb_divide,
4959 "/"),
4960 BINSLOT("__mod__", nb_remainder, slot_nb_remainder,
4961 "%"),
4962 RBINSLOT("__rmod__", nb_remainder, slot_nb_remainder,
4963 "%"),
4964 BINSLOT("__divmod__", nb_divmod, slot_nb_divmod,
4965 "divmod(x, y)"),
4966 RBINSLOT("__rdivmod__", nb_divmod, slot_nb_divmod,
4967 "divmod(y, x)"),
4968 NBSLOT("__pow__", nb_power, slot_nb_power, wrap_ternaryfunc,
4969 "x.__pow__(y[, z]) <==> pow(x, y[, z])"),
4970 NBSLOT("__rpow__", nb_power, slot_nb_power, wrap_ternaryfunc_r,
4971 "y.__rpow__(x[, z]) <==> pow(x, y[, z])"),
4972 UNSLOT("__neg__", nb_negative, slot_nb_negative, wrap_unaryfunc, "-x"),
4973 UNSLOT("__pos__", nb_positive, slot_nb_positive, wrap_unaryfunc, "+x"),
4974 UNSLOT("__abs__", nb_absolute, slot_nb_absolute, wrap_unaryfunc,
4975 "abs(x)"),
Raymond Hettingerf34f2642003-10-11 17:29:04 +00004976 UNSLOT("__nonzero__", nb_nonzero, slot_nb_nonzero, wrap_inquirypred,
Guido van Rossum6d204072001-10-21 00:44:31 +00004977 "x != 0"),
4978 UNSLOT("__invert__", nb_invert, slot_nb_invert, wrap_unaryfunc, "~x"),
4979 BINSLOT("__lshift__", nb_lshift, slot_nb_lshift, "<<"),
4980 RBINSLOT("__rlshift__", nb_lshift, slot_nb_lshift, "<<"),
4981 BINSLOT("__rshift__", nb_rshift, slot_nb_rshift, ">>"),
4982 RBINSLOT("__rrshift__", nb_rshift, slot_nb_rshift, ">>"),
4983 BINSLOT("__and__", nb_and, slot_nb_and, "&"),
4984 RBINSLOT("__rand__", nb_and, slot_nb_and, "&"),
4985 BINSLOT("__xor__", nb_xor, slot_nb_xor, "^"),
4986 RBINSLOT("__rxor__", nb_xor, slot_nb_xor, "^"),
4987 BINSLOT("__or__", nb_or, slot_nb_or, "|"),
4988 RBINSLOT("__ror__", nb_or, slot_nb_or, "|"),
4989 NBSLOT("__coerce__", nb_coerce, slot_nb_coerce, wrap_coercefunc,
4990 "x.__coerce__(y) <==> coerce(x, y)"),
4991 UNSLOT("__int__", nb_int, slot_nb_int, wrap_unaryfunc,
4992 "int(x)"),
4993 UNSLOT("__long__", nb_long, slot_nb_long, wrap_unaryfunc,
4994 "long(x)"),
4995 UNSLOT("__float__", nb_float, slot_nb_float, wrap_unaryfunc,
4996 "float(x)"),
4997 UNSLOT("__oct__", nb_oct, slot_nb_oct, wrap_unaryfunc,
4998 "oct(x)"),
4999 UNSLOT("__hex__", nb_hex, slot_nb_hex, wrap_unaryfunc,
5000 "hex(x)"),
5001 IBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add,
5002 wrap_binaryfunc, "+"),
5003 IBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract,
5004 wrap_binaryfunc, "-"),
5005 IBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply,
5006 wrap_binaryfunc, "*"),
5007 IBSLOT("__idiv__", nb_inplace_divide, slot_nb_inplace_divide,
5008 wrap_binaryfunc, "/"),
5009 IBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder,
5010 wrap_binaryfunc, "%"),
5011 IBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power,
Guido van Rossum6e5680f2002-10-15 01:01:53 +00005012 wrap_binaryfunc, "**"),
Guido van Rossum6d204072001-10-21 00:44:31 +00005013 IBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift,
5014 wrap_binaryfunc, "<<"),
5015 IBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift,
5016 wrap_binaryfunc, ">>"),
5017 IBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and,
5018 wrap_binaryfunc, "&"),
5019 IBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor,
5020 wrap_binaryfunc, "^"),
5021 IBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or,
5022 wrap_binaryfunc, "|"),
5023 BINSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
5024 RBINSLOT("__rfloordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
5025 BINSLOT("__truediv__", nb_true_divide, slot_nb_true_divide, "/"),
5026 RBINSLOT("__rtruediv__", nb_true_divide, slot_nb_true_divide, "/"),
5027 IBSLOT("__ifloordiv__", nb_inplace_floor_divide,
5028 slot_nb_inplace_floor_divide, wrap_binaryfunc, "//"),
5029 IBSLOT("__itruediv__", nb_inplace_true_divide,
5030 slot_nb_inplace_true_divide, wrap_binaryfunc, "/"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005031
Guido van Rossum6d204072001-10-21 00:44:31 +00005032 TPSLOT("__str__", tp_str, slot_tp_str, wrap_unaryfunc,
5033 "x.__str__() <==> str(x)"),
Guido van Rossumafe7a942001-10-29 14:33:44 +00005034 TPSLOT("__str__", tp_print, NULL, NULL, ""),
Guido van Rossum6d204072001-10-21 00:44:31 +00005035 TPSLOT("__repr__", tp_repr, slot_tp_repr, wrap_unaryfunc,
5036 "x.__repr__() <==> repr(x)"),
Guido van Rossumafe7a942001-10-29 14:33:44 +00005037 TPSLOT("__repr__", tp_print, NULL, NULL, ""),
Guido van Rossum6d204072001-10-21 00:44:31 +00005038 TPSLOT("__cmp__", tp_compare, _PyObject_SlotCompare, wrap_cmpfunc,
5039 "x.__cmp__(y) <==> cmp(x,y)"),
5040 TPSLOT("__hash__", tp_hash, slot_tp_hash, wrap_hashfunc,
5041 "x.__hash__() <==> hash(x)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00005042 FLSLOT("__call__", tp_call, slot_tp_call, (wrapperfunc)wrap_call,
5043 "x.__call__(...) <==> x(...)", PyWrapperFlag_KEYWORDS),
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005044 TPSLOT("__getattribute__", tp_getattro, slot_tp_getattr_hook,
Guido van Rossum6d204072001-10-21 00:44:31 +00005045 wrap_binaryfunc, "x.__getattribute__('name') <==> x.name"),
5046 TPSLOT("__getattribute__", tp_getattr, NULL, NULL, ""),
5047 TPSLOT("__getattr__", tp_getattro, slot_tp_getattr_hook, NULL, ""),
5048 TPSLOT("__getattr__", tp_getattr, NULL, NULL, ""),
5049 TPSLOT("__setattr__", tp_setattro, slot_tp_setattro, wrap_setattr,
5050 "x.__setattr__('name', value) <==> x.name = value"),
5051 TPSLOT("__setattr__", tp_setattr, NULL, NULL, ""),
5052 TPSLOT("__delattr__", tp_setattro, slot_tp_setattro, wrap_delattr,
5053 "x.__delattr__('name') <==> del x.name"),
5054 TPSLOT("__delattr__", tp_setattr, NULL, NULL, ""),
5055 TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare, richcmp_lt,
5056 "x.__lt__(y) <==> x<y"),
5057 TPSLOT("__le__", tp_richcompare, slot_tp_richcompare, richcmp_le,
5058 "x.__le__(y) <==> x<=y"),
5059 TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare, richcmp_eq,
5060 "x.__eq__(y) <==> x==y"),
5061 TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare, richcmp_ne,
5062 "x.__ne__(y) <==> x!=y"),
5063 TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare, richcmp_gt,
5064 "x.__gt__(y) <==> x>y"),
5065 TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare, richcmp_ge,
5066 "x.__ge__(y) <==> x>=y"),
5067 TPSLOT("__iter__", tp_iter, slot_tp_iter, wrap_unaryfunc,
5068 "x.__iter__() <==> iter(x)"),
5069 TPSLOT("next", tp_iternext, slot_tp_iternext, wrap_next,
5070 "x.next() -> the next value, or raise StopIteration"),
5071 TPSLOT("__get__", tp_descr_get, slot_tp_descr_get, wrap_descr_get,
5072 "descr.__get__(obj[, type]) -> value"),
5073 TPSLOT("__set__", tp_descr_set, slot_tp_descr_set, wrap_descr_set,
5074 "descr.__set__(obj, value)"),
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00005075 TPSLOT("__delete__", tp_descr_set, slot_tp_descr_set,
5076 wrap_descr_delete, "descr.__delete__(obj)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00005077 FLSLOT("__init__", tp_init, slot_tp_init, (wrapperfunc)wrap_init,
Guido van Rossum6d204072001-10-21 00:44:31 +00005078 "x.__init__(...) initializes x; "
Guido van Rossumc8e56452001-10-22 00:43:43 +00005079 "see x.__class__.__doc__ for signature",
5080 PyWrapperFlag_KEYWORDS),
5081 TPSLOT("__new__", tp_new, slot_tp_new, NULL, ""),
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005082 TPSLOT("__del__", tp_del, slot_tp_del, NULL, ""),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005083 {NULL}
5084};
5085
Guido van Rossumc334df52002-04-04 23:44:47 +00005086/* Given a type pointer and an offset gotten from a slotdef entry, return a
5087 pointer to the actual slot. This is not quite the same as simply adding
5088 the offset to the type pointer, since it takes care to indirect through the
5089 proper indirection pointer (as_buffer, etc.); it returns NULL if the
5090 indirection pointer is NULL. */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005091static void **
5092slotptr(PyTypeObject *type, int offset)
5093{
5094 char *ptr;
5095
Guido van Rossume5c691a2003-03-07 15:13:17 +00005096 /* Note: this depends on the order of the members of PyHeapTypeObject! */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005097 assert(offset >= 0);
Guido van Rossume5c691a2003-03-07 15:13:17 +00005098 assert(offset < offsetof(PyHeapTypeObject, as_buffer));
5099 if (offset >= offsetof(PyHeapTypeObject, as_sequence)) {
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005100 ptr = (void *)type->tp_as_sequence;
Guido van Rossume5c691a2003-03-07 15:13:17 +00005101 offset -= offsetof(PyHeapTypeObject, as_sequence);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005102 }
Guido van Rossume5c691a2003-03-07 15:13:17 +00005103 else if (offset >= offsetof(PyHeapTypeObject, as_mapping)) {
Guido van Rossum09638c12002-06-13 19:17:46 +00005104 ptr = (void *)type->tp_as_mapping;
Guido van Rossume5c691a2003-03-07 15:13:17 +00005105 offset -= offsetof(PyHeapTypeObject, as_mapping);
Guido van Rossum09638c12002-06-13 19:17:46 +00005106 }
Guido van Rossume5c691a2003-03-07 15:13:17 +00005107 else if (offset >= offsetof(PyHeapTypeObject, as_number)) {
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005108 ptr = (void *)type->tp_as_number;
Guido van Rossume5c691a2003-03-07 15:13:17 +00005109 offset -= offsetof(PyHeapTypeObject, as_number);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005110 }
5111 else {
5112 ptr = (void *)type;
5113 }
5114 if (ptr != NULL)
5115 ptr += offset;
5116 return (void **)ptr;
5117}
Guido van Rossumf040ede2001-08-07 16:40:56 +00005118
Guido van Rossumc334df52002-04-04 23:44:47 +00005119/* Length of array of slotdef pointers used to store slots with the
5120 same __name__. There should be at most MAX_EQUIV-1 slotdef entries with
5121 the same __name__, for any __name__. Since that's a static property, it is
5122 appropriate to declare fixed-size arrays for this. */
5123#define MAX_EQUIV 10
5124
5125/* Return a slot pointer for a given name, but ONLY if the attribute has
5126 exactly one slot function. The name must be an interned string. */
5127static void **
5128resolve_slotdups(PyTypeObject *type, PyObject *name)
5129{
5130 /* XXX Maybe this could be optimized more -- but is it worth it? */
5131
5132 /* pname and ptrs act as a little cache */
5133 static PyObject *pname;
5134 static slotdef *ptrs[MAX_EQUIV];
5135 slotdef *p, **pp;
5136 void **res, **ptr;
5137
5138 if (pname != name) {
5139 /* Collect all slotdefs that match name into ptrs. */
5140 pname = name;
5141 pp = ptrs;
5142 for (p = slotdefs; p->name_strobj; p++) {
5143 if (p->name_strobj == name)
5144 *pp++ = p;
5145 }
5146 *pp = NULL;
5147 }
5148
5149 /* Look in all matching slots of the type; if exactly one of these has
5150 a filled-in slot, return its value. Otherwise return NULL. */
5151 res = NULL;
5152 for (pp = ptrs; *pp; pp++) {
5153 ptr = slotptr(type, (*pp)->offset);
5154 if (ptr == NULL || *ptr == NULL)
5155 continue;
5156 if (res != NULL)
5157 return NULL;
5158 res = ptr;
5159 }
5160 return res;
5161}
5162
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005163/* Common code for update_slots_callback() and fixup_slot_dispatchers(). This
Guido van Rossumc334df52002-04-04 23:44:47 +00005164 does some incredibly complex thinking and then sticks something into the
5165 slot. (It sees if the adjacent slotdefs for the same slot have conflicting
5166 interests, and then stores a generic wrapper or a specific function into
5167 the slot.) Return a pointer to the next slotdef with a different offset,
5168 because that's convenient for fixup_slot_dispatchers(). */
5169static slotdef *
5170update_one_slot(PyTypeObject *type, slotdef *p)
5171{
5172 PyObject *descr;
5173 PyWrapperDescrObject *d;
5174 void *generic = NULL, *specific = NULL;
5175 int use_generic = 0;
5176 int offset = p->offset;
5177 void **ptr = slotptr(type, offset);
5178
5179 if (ptr == NULL) {
5180 do {
5181 ++p;
5182 } while (p->offset == offset);
5183 return p;
5184 }
5185 do {
5186 descr = _PyType_Lookup(type, p->name_strobj);
5187 if (descr == NULL)
5188 continue;
5189 if (descr->ob_type == &PyWrapperDescr_Type) {
5190 void **tptr = resolve_slotdups(type, p->name_strobj);
5191 if (tptr == NULL || tptr == ptr)
5192 generic = p->function;
5193 d = (PyWrapperDescrObject *)descr;
5194 if (d->d_base->wrapper == p->wrapper &&
5195 PyType_IsSubtype(type, d->d_type))
5196 {
5197 if (specific == NULL ||
5198 specific == d->d_wrapped)
5199 specific = d->d_wrapped;
5200 else
5201 use_generic = 1;
5202 }
5203 }
Guido van Rossum721f62e2002-08-09 02:14:34 +00005204 else if (descr->ob_type == &PyCFunction_Type &&
5205 PyCFunction_GET_FUNCTION(descr) ==
5206 (PyCFunction)tp_new_wrapper &&
5207 strcmp(p->name, "__new__") == 0)
5208 {
5209 /* The __new__ wrapper is not a wrapper descriptor,
5210 so must be special-cased differently.
5211 If we don't do this, creating an instance will
5212 always use slot_tp_new which will look up
5213 __new__ in the MRO which will call tp_new_wrapper
5214 which will look through the base classes looking
5215 for a static base and call its tp_new (usually
5216 PyType_GenericNew), after performing various
5217 sanity checks and constructing a new argument
5218 list. Cut all that nonsense short -- this speeds
5219 up instance creation tremendously. */
Martin v. Löwisa94568a2003-05-10 07:36:56 +00005220 specific = (void *)type->tp_new;
Guido van Rossum721f62e2002-08-09 02:14:34 +00005221 /* XXX I'm not 100% sure that there isn't a hole
5222 in this reasoning that requires additional
5223 sanity checks. I'll buy the first person to
5224 point out a bug in this reasoning a beer. */
5225 }
Guido van Rossumc334df52002-04-04 23:44:47 +00005226 else {
5227 use_generic = 1;
5228 generic = p->function;
5229 }
5230 } while ((++p)->offset == offset);
5231 if (specific && !use_generic)
5232 *ptr = specific;
5233 else
5234 *ptr = generic;
5235 return p;
5236}
5237
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005238/* In the type, update the slots whose slotdefs are gathered in the pp array.
5239 This is a callback for update_subclasses(). */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005240static int
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005241update_slots_callback(PyTypeObject *type, void *data)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005242{
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005243 slotdef **pp = (slotdef **)data;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005244
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005245 for (; *pp; pp++)
Guido van Rossumc334df52002-04-04 23:44:47 +00005246 update_one_slot(type, *pp);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005247 return 0;
5248}
5249
Guido van Rossumc334df52002-04-04 23:44:47 +00005250/* Comparison function for qsort() to compare slotdefs by their offset, and
5251 for equal offset by their address (to force a stable sort). */
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005252static int
5253slotdef_cmp(const void *aa, const void *bb)
5254{
5255 const slotdef *a = (const slotdef *)aa, *b = (const slotdef *)bb;
5256 int c = a->offset - b->offset;
5257 if (c != 0)
5258 return c;
5259 else
5260 return a - b;
5261}
5262
Guido van Rossumc334df52002-04-04 23:44:47 +00005263/* Initialize the slotdefs table by adding interned string objects for the
5264 names and sorting the entries. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005265static void
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005266init_slotdefs(void)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005267{
5268 slotdef *p;
5269 static int initialized = 0;
5270
5271 if (initialized)
5272 return;
5273 for (p = slotdefs; p->name; p++) {
5274 p->name_strobj = PyString_InternFromString(p->name);
5275 if (!p->name_strobj)
Guido van Rossumc334df52002-04-04 23:44:47 +00005276 Py_FatalError("Out of memory interning slotdef names");
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005277 }
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005278 qsort((void *)slotdefs, (size_t)(p-slotdefs), sizeof(slotdef),
5279 slotdef_cmp);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005280 initialized = 1;
5281}
5282
Guido van Rossumc334df52002-04-04 23:44:47 +00005283/* Update the slots after assignment to a class (type) attribute. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005284static int
5285update_slot(PyTypeObject *type, PyObject *name)
5286{
Guido van Rossumc334df52002-04-04 23:44:47 +00005287 slotdef *ptrs[MAX_EQUIV];
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005288 slotdef *p;
5289 slotdef **pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005290 int offset;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005291
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005292 init_slotdefs();
5293 pp = ptrs;
5294 for (p = slotdefs; p->name; p++) {
5295 /* XXX assume name is interned! */
5296 if (p->name_strobj == name)
5297 *pp++ = p;
5298 }
5299 *pp = NULL;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005300 for (pp = ptrs; *pp; pp++) {
5301 p = *pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005302 offset = p->offset;
5303 while (p > slotdefs && (p-1)->offset == offset)
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005304 --p;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005305 *pp = p;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005306 }
Guido van Rossumc334df52002-04-04 23:44:47 +00005307 if (ptrs[0] == NULL)
5308 return 0; /* Not an attribute that affects any slots */
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005309 return update_subclasses(type, name,
5310 update_slots_callback, (void *)ptrs);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005311}
5312
Guido van Rossumc334df52002-04-04 23:44:47 +00005313/* Store the proper functions in the slot dispatches at class (type)
5314 definition time, based upon which operations the class overrides in its
5315 dict. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00005316static void
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005317fixup_slot_dispatchers(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005318{
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005319 slotdef *p;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005320
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005321 init_slotdefs();
Guido van Rossumc334df52002-04-04 23:44:47 +00005322 for (p = slotdefs; p->name; )
5323 p = update_one_slot(type, p);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005324}
Guido van Rossum705f0f52001-08-24 16:47:00 +00005325
Michael W. Hudson98bbc492002-11-26 14:47:27 +00005326static void
5327update_all_slots(PyTypeObject* type)
5328{
5329 slotdef *p;
5330
5331 init_slotdefs();
5332 for (p = slotdefs; p->name; p++) {
5333 /* update_slot returns int but can't actually fail */
5334 update_slot(type, p->name_strobj);
5335 }
5336}
5337
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005338/* recurse_down_subclasses() and update_subclasses() are mutually
5339 recursive functions to call a callback for all subclasses,
5340 but refraining from recursing into subclasses that define 'name'. */
5341
5342static int
5343update_subclasses(PyTypeObject *type, PyObject *name,
5344 update_callback callback, void *data)
5345{
5346 if (callback(type, data) < 0)
5347 return -1;
5348 return recurse_down_subclasses(type, name, callback, data);
5349}
5350
5351static int
5352recurse_down_subclasses(PyTypeObject *type, PyObject *name,
5353 update_callback callback, void *data)
5354{
5355 PyTypeObject *subclass;
5356 PyObject *ref, *subclasses, *dict;
5357 int i, n;
5358
5359 subclasses = type->tp_subclasses;
5360 if (subclasses == NULL)
5361 return 0;
5362 assert(PyList_Check(subclasses));
5363 n = PyList_GET_SIZE(subclasses);
5364 for (i = 0; i < n; i++) {
5365 ref = PyList_GET_ITEM(subclasses, i);
5366 assert(PyWeakref_CheckRef(ref));
5367 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
5368 assert(subclass != NULL);
5369 if ((PyObject *)subclass == Py_None)
5370 continue;
5371 assert(PyType_Check(subclass));
5372 /* Avoid recursing down into unaffected classes */
5373 dict = subclass->tp_dict;
5374 if (dict != NULL && PyDict_Check(dict) &&
5375 PyDict_GetItem(dict, name) != NULL)
5376 continue;
5377 if (update_subclasses(subclass, name, callback, data) < 0)
5378 return -1;
5379 }
5380 return 0;
5381}
5382
Guido van Rossum6d204072001-10-21 00:44:31 +00005383/* This function is called by PyType_Ready() to populate the type's
5384 dictionary with method descriptors for function slots. For each
Guido van Rossum09638c12002-06-13 19:17:46 +00005385 function slot (like tp_repr) that's defined in the type, one or more
5386 corresponding descriptors are added in the type's tp_dict dictionary
5387 under the appropriate name (like __repr__). Some function slots
5388 cause more than one descriptor to be added (for example, the nb_add
5389 slot adds both __add__ and __radd__ descriptors) and some function
5390 slots compete for the same descriptor (for example both sq_item and
5391 mp_subscript generate a __getitem__ descriptor).
5392
5393 In the latter case, the first slotdef entry encoutered wins. Since
Tim Petersbf9b2442003-03-23 05:35:36 +00005394 slotdef entries are sorted by the offset of the slot in the
Guido van Rossume5c691a2003-03-07 15:13:17 +00005395 PyHeapTypeObject, this gives us some control over disambiguating
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005396 between competing slots: the members of PyHeapTypeObject are listed
5397 from most general to least general, so the most general slot is
5398 preferred. In particular, because as_mapping comes before as_sequence,
5399 for a type that defines both mp_subscript and sq_item, mp_subscript
5400 wins.
Guido van Rossum09638c12002-06-13 19:17:46 +00005401
5402 This only adds new descriptors and doesn't overwrite entries in
5403 tp_dict that were previously defined. The descriptors contain a
5404 reference to the C function they must call, so that it's safe if they
5405 are copied into a subtype's __dict__ and the subtype has a different
5406 C function in its slot -- calling the method defined by the
5407 descriptor will call the C function that was used to create it,
5408 rather than the C function present in the slot when it is called.
5409 (This is important because a subtype may have a C function in the
5410 slot that calls the method from the dictionary, and we want to avoid
5411 infinite recursion here.) */
Guido van Rossum6d204072001-10-21 00:44:31 +00005412
5413static int
5414add_operators(PyTypeObject *type)
5415{
5416 PyObject *dict = type->tp_dict;
5417 slotdef *p;
5418 PyObject *descr;
5419 void **ptr;
5420
5421 init_slotdefs();
5422 for (p = slotdefs; p->name; p++) {
5423 if (p->wrapper == NULL)
5424 continue;
5425 ptr = slotptr(type, p->offset);
5426 if (!ptr || !*ptr)
5427 continue;
5428 if (PyDict_GetItem(dict, p->name_strobj))
5429 continue;
5430 descr = PyDescr_NewWrapper(type, p, *ptr);
5431 if (descr == NULL)
5432 return -1;
5433 if (PyDict_SetItem(dict, p->name_strobj, descr) < 0)
5434 return -1;
5435 Py_DECREF(descr);
5436 }
5437 if (type->tp_new != NULL) {
5438 if (add_tp_new_wrapper(type) < 0)
5439 return -1;
5440 }
5441 return 0;
5442}
5443
Guido van Rossum705f0f52001-08-24 16:47:00 +00005444
5445/* Cooperative 'super' */
5446
5447typedef struct {
5448 PyObject_HEAD
Guido van Rossume705ef12001-08-29 15:47:06 +00005449 PyTypeObject *type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005450 PyObject *obj;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005451 PyTypeObject *obj_type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005452} superobject;
5453
Guido van Rossum6f799372001-09-20 20:46:19 +00005454static PyMemberDef super_members[] = {
5455 {"__thisclass__", T_OBJECT, offsetof(superobject, type), READONLY,
5456 "the class invoking super()"},
5457 {"__self__", T_OBJECT, offsetof(superobject, obj), READONLY,
5458 "the instance invoking super(); may be None"},
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005459 {"__self_class__", T_OBJECT, offsetof(superobject, obj_type), READONLY,
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +00005460 "the type of the instance invoking super(); may be None"},
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005461 {0}
5462};
5463
Guido van Rossum705f0f52001-08-24 16:47:00 +00005464static void
5465super_dealloc(PyObject *self)
5466{
5467 superobject *su = (superobject *)self;
5468
Guido van Rossum048eb752001-10-02 21:24:57 +00005469 _PyObject_GC_UNTRACK(self);
Guido van Rossum705f0f52001-08-24 16:47:00 +00005470 Py_XDECREF(su->obj);
5471 Py_XDECREF(su->type);
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005472 Py_XDECREF(su->obj_type);
Guido van Rossum705f0f52001-08-24 16:47:00 +00005473 self->ob_type->tp_free(self);
5474}
5475
5476static PyObject *
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005477super_repr(PyObject *self)
5478{
5479 superobject *su = (superobject *)self;
5480
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005481 if (su->obj_type)
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005482 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00005483 "<super: <class '%s'>, <%s object>>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005484 su->type ? su->type->tp_name : "NULL",
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005485 su->obj_type->tp_name);
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005486 else
5487 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00005488 "<super: <class '%s'>, NULL>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005489 su->type ? su->type->tp_name : "NULL");
5490}
5491
5492static PyObject *
Guido van Rossum705f0f52001-08-24 16:47:00 +00005493super_getattro(PyObject *self, PyObject *name)
5494{
5495 superobject *su = (superobject *)self;
Guido van Rossum76ba09f2003-04-16 19:40:58 +00005496 int skip = su->obj_type == NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005497
Guido van Rossum76ba09f2003-04-16 19:40:58 +00005498 if (!skip) {
5499 /* We want __class__ to return the class of the super object
5500 (i.e. super, or a subclass), not the class of su->obj. */
5501 skip = (PyString_Check(name) &&
5502 PyString_GET_SIZE(name) == 9 &&
5503 strcmp(PyString_AS_STRING(name), "__class__") == 0);
5504 }
5505
5506 if (!skip) {
Tim Petersa91e9642001-11-14 23:32:33 +00005507 PyObject *mro, *res, *tmp, *dict;
Guido van Rossum155db9a2002-04-02 17:53:47 +00005508 PyTypeObject *starttype;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005509 descrgetfunc f;
5510 int i, n;
5511
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005512 starttype = su->obj_type;
Guido van Rossum155db9a2002-04-02 17:53:47 +00005513 mro = starttype->tp_mro;
5514
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005515 if (mro == NULL)
5516 n = 0;
5517 else {
5518 assert(PyTuple_Check(mro));
5519 n = PyTuple_GET_SIZE(mro);
5520 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00005521 for (i = 0; i < n; i++) {
Guido van Rossume705ef12001-08-29 15:47:06 +00005522 if ((PyObject *)(su->type) == PyTuple_GET_ITEM(mro, i))
Guido van Rossum705f0f52001-08-24 16:47:00 +00005523 break;
5524 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00005525 i++;
5526 res = NULL;
5527 for (; i < n; i++) {
5528 tmp = PyTuple_GET_ITEM(mro, i);
Tim Petersa91e9642001-11-14 23:32:33 +00005529 if (PyType_Check(tmp))
5530 dict = ((PyTypeObject *)tmp)->tp_dict;
5531 else if (PyClass_Check(tmp))
5532 dict = ((PyClassObject *)tmp)->cl_dict;
5533 else
5534 continue;
5535 res = PyDict_GetItem(dict, name);
Guido van Rossum6cc5bb62003-04-16 20:01:36 +00005536 if (res != NULL) {
Guido van Rossum705f0f52001-08-24 16:47:00 +00005537 Py_INCREF(res);
5538 f = res->ob_type->tp_descr_get;
5539 if (f != NULL) {
Guido van Rossumd4641072002-04-03 02:13:37 +00005540 tmp = f(res, su->obj,
5541 (PyObject *)starttype);
Guido van Rossum705f0f52001-08-24 16:47:00 +00005542 Py_DECREF(res);
5543 res = tmp;
5544 }
5545 return res;
5546 }
5547 }
5548 }
5549 return PyObject_GenericGetAttr(self, name);
5550}
5551
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005552static PyTypeObject *
Guido van Rossum5b443c62001-12-03 15:38:28 +00005553supercheck(PyTypeObject *type, PyObject *obj)
5554{
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005555 /* Check that a super() call makes sense. Return a type object.
5556
5557 obj can be a new-style class, or an instance of one:
5558
5559 - If it is a class, it must be a subclass of 'type'. This case is
5560 used for class methods; the return value is obj.
5561
5562 - If it is an instance, it must be an instance of 'type'. This is
5563 the normal case; the return value is obj.__class__.
5564
5565 But... when obj is an instance, we want to allow for the case where
5566 obj->ob_type is not a subclass of type, but obj.__class__ is!
5567 This will allow using super() with a proxy for obj.
5568 */
5569
Guido van Rossum8e80a722003-02-18 19:22:22 +00005570 /* Check for first bullet above (special case) */
5571 if (PyType_Check(obj) && PyType_IsSubtype((PyTypeObject *)obj, type)) {
5572 Py_INCREF(obj);
5573 return (PyTypeObject *)obj;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005574 }
Guido van Rossum8e80a722003-02-18 19:22:22 +00005575
5576 /* Normal case */
5577 if (PyType_IsSubtype(obj->ob_type, type)) {
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005578 Py_INCREF(obj->ob_type);
5579 return obj->ob_type;
5580 }
5581 else {
5582 /* Try the slow way */
5583 static PyObject *class_str = NULL;
5584 PyObject *class_attr;
5585
5586 if (class_str == NULL) {
5587 class_str = PyString_FromString("__class__");
5588 if (class_str == NULL)
5589 return NULL;
5590 }
5591
5592 class_attr = PyObject_GetAttr(obj, class_str);
5593
5594 if (class_attr != NULL &&
5595 PyType_Check(class_attr) &&
5596 (PyTypeObject *)class_attr != obj->ob_type)
5597 {
5598 int ok = PyType_IsSubtype(
5599 (PyTypeObject *)class_attr, type);
5600 if (ok)
5601 return (PyTypeObject *)class_attr;
5602 }
5603
5604 if (class_attr == NULL)
5605 PyErr_Clear();
5606 else
5607 Py_DECREF(class_attr);
5608 }
5609
Tim Peters97e5ff52003-02-18 19:32:50 +00005610 PyErr_SetString(PyExc_TypeError,
Guido van Rossum5b443c62001-12-03 15:38:28 +00005611 "super(type, obj): "
5612 "obj must be an instance or subtype of type");
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005613 return NULL;
Guido van Rossum5b443c62001-12-03 15:38:28 +00005614}
5615
Guido van Rossum705f0f52001-08-24 16:47:00 +00005616static PyObject *
5617super_descr_get(PyObject *self, PyObject *obj, PyObject *type)
5618{
5619 superobject *su = (superobject *)self;
5620 superobject *new;
5621
5622 if (obj == NULL || obj == Py_None || su->obj != NULL) {
5623 /* Not binding to an object, or already bound */
5624 Py_INCREF(self);
5625 return self;
5626 }
Guido van Rossum5b443c62001-12-03 15:38:28 +00005627 if (su->ob_type != &PySuper_Type)
Brett Cannon10147f72003-06-11 20:50:33 +00005628 /* If su is not an instance of a subclass of super,
Guido van Rossum5b443c62001-12-03 15:38:28 +00005629 call its type */
5630 return PyObject_CallFunction((PyObject *)su->ob_type,
5631 "OO", su->type, obj);
5632 else {
5633 /* Inline the common case */
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005634 PyTypeObject *obj_type = supercheck(su->type, obj);
5635 if (obj_type == NULL)
Guido van Rossum5b443c62001-12-03 15:38:28 +00005636 return NULL;
5637 new = (superobject *)PySuper_Type.tp_new(&PySuper_Type,
5638 NULL, NULL);
5639 if (new == NULL)
5640 return NULL;
5641 Py_INCREF(su->type);
5642 Py_INCREF(obj);
5643 new->type = su->type;
5644 new->obj = obj;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005645 new->obj_type = obj_type;
Guido van Rossum5b443c62001-12-03 15:38:28 +00005646 return (PyObject *)new;
5647 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00005648}
5649
5650static int
5651super_init(PyObject *self, PyObject *args, PyObject *kwds)
5652{
5653 superobject *su = (superobject *)self;
Guido van Rossume705ef12001-08-29 15:47:06 +00005654 PyTypeObject *type;
5655 PyObject *obj = NULL;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005656 PyTypeObject *obj_type = NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005657
5658 if (!PyArg_ParseTuple(args, "O!|O:super", &PyType_Type, &type, &obj))
5659 return -1;
5660 if (obj == Py_None)
5661 obj = NULL;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005662 if (obj != NULL) {
5663 obj_type = supercheck(type, obj);
5664 if (obj_type == NULL)
5665 return -1;
5666 Py_INCREF(obj);
5667 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00005668 Py_INCREF(type);
Guido van Rossum705f0f52001-08-24 16:47:00 +00005669 su->type = type;
5670 su->obj = obj;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005671 su->obj_type = obj_type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005672 return 0;
5673}
5674
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005675PyDoc_STRVAR(super_doc,
Guido van Rossum705f0f52001-08-24 16:47:00 +00005676"super(type) -> unbound super object\n"
5677"super(type, obj) -> bound super object; requires isinstance(obj, type)\n"
Guido van Rossume705ef12001-08-29 15:47:06 +00005678"super(type, type2) -> bound super object; requires issubclass(type2, type)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00005679"Typical use to call a cooperative superclass method:\n"
5680"class C(B):\n"
5681" def meth(self, arg):\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005682" super(C, self).meth(arg)");
Guido van Rossum705f0f52001-08-24 16:47:00 +00005683
Guido van Rossum048eb752001-10-02 21:24:57 +00005684static int
5685super_traverse(PyObject *self, visitproc visit, void *arg)
5686{
5687 superobject *su = (superobject *)self;
5688 int err;
5689
5690#define VISIT(SLOT) \
5691 if (SLOT) { \
5692 err = visit((PyObject *)(SLOT), arg); \
5693 if (err) \
5694 return err; \
5695 }
5696
5697 VISIT(su->obj);
5698 VISIT(su->type);
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005699 VISIT(su->obj_type);
Guido van Rossum048eb752001-10-02 21:24:57 +00005700
5701#undef VISIT
5702
5703 return 0;
5704}
5705
Guido van Rossum705f0f52001-08-24 16:47:00 +00005706PyTypeObject PySuper_Type = {
5707 PyObject_HEAD_INIT(&PyType_Type)
5708 0, /* ob_size */
5709 "super", /* tp_name */
5710 sizeof(superobject), /* tp_basicsize */
5711 0, /* tp_itemsize */
5712 /* methods */
5713 super_dealloc, /* tp_dealloc */
5714 0, /* tp_print */
5715 0, /* tp_getattr */
5716 0, /* tp_setattr */
5717 0, /* tp_compare */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005718 super_repr, /* tp_repr */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005719 0, /* tp_as_number */
5720 0, /* tp_as_sequence */
5721 0, /* tp_as_mapping */
5722 0, /* tp_hash */
5723 0, /* tp_call */
5724 0, /* tp_str */
5725 super_getattro, /* tp_getattro */
5726 0, /* tp_setattro */
5727 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00005728 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
5729 Py_TPFLAGS_BASETYPE, /* tp_flags */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005730 super_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00005731 super_traverse, /* tp_traverse */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005732 0, /* tp_clear */
5733 0, /* tp_richcompare */
5734 0, /* tp_weaklistoffset */
5735 0, /* tp_iter */
5736 0, /* tp_iternext */
5737 0, /* tp_methods */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005738 super_members, /* tp_members */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005739 0, /* tp_getset */
5740 0, /* tp_base */
5741 0, /* tp_dict */
5742 super_descr_get, /* tp_descr_get */
5743 0, /* tp_descr_set */
5744 0, /* tp_dictoffset */
5745 super_init, /* tp_init */
5746 PyType_GenericAlloc, /* tp_alloc */
5747 PyType_GenericNew, /* tp_new */
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00005748 PyObject_GC_Del, /* tp_free */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005749};