blob: 8b51a53fb4849fc9733ed07d1a799f1b1c40afbc [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
8/* The *real* layout of a type object when allocated on the heap */
9/* XXX Should we publish this in a header file? */
10typedef struct {
11 PyTypeObject type;
12 PyNumberMethods as_number;
13 PySequenceMethods as_sequence;
14 PyMappingMethods as_mapping;
15 PyBufferProcs as_buffer;
16 PyObject *name, *slots;
17 PyMemberDef members[1];
18} etype;
19
Guido van Rossum6f799372001-09-20 20:46:19 +000020static PyMemberDef type_members[] = {
Tim Peters6d6c1a32001-08-02 04:15:00 +000021 {"__basicsize__", T_INT, offsetof(PyTypeObject,tp_basicsize),READONLY},
22 {"__itemsize__", T_INT, offsetof(PyTypeObject, tp_itemsize), READONLY},
23 {"__flags__", T_LONG, offsetof(PyTypeObject, tp_flags), READONLY},
Guido van Rossum9676b222001-08-17 20:32:36 +000024 {"__weakrefoffset__", T_LONG,
Tim Peters6d6c1a32001-08-02 04:15:00 +000025 offsetof(PyTypeObject, tp_weaklistoffset), READONLY},
26 {"__base__", T_OBJECT, offsetof(PyTypeObject, tp_base), READONLY},
27 {"__dictoffset__", T_LONG,
28 offsetof(PyTypeObject, tp_dictoffset), READONLY},
29 {"__bases__", T_OBJECT, offsetof(PyTypeObject, tp_bases), READONLY},
30 {"__mro__", T_OBJECT, offsetof(PyTypeObject, tp_mro), READONLY},
31 {0}
32};
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000033
Guido van Rossumc0b618a1997-05-02 03:12:38 +000034static PyObject *
Guido van Rossumc3542212001-08-16 09:18:56 +000035type_name(PyTypeObject *type, void *context)
36{
37 char *s;
38
39 s = strrchr(type->tp_name, '.');
40 if (s == NULL)
41 s = type->tp_name;
42 else
43 s++;
44 return PyString_FromString(s);
45}
46
47static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +000048type_module(PyTypeObject *type, void *context)
Guido van Rossum29ca26e1995-01-07 11:58:15 +000049{
Guido van Rossumc3542212001-08-16 09:18:56 +000050 PyObject *mod;
51 char *s;
52
53 s = strrchr(type->tp_name, '.');
54 if (s != NULL)
55 return PyString_FromStringAndSize(type->tp_name,
56 (int)(s - type->tp_name));
57 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE))
58 return PyString_FromString("__builtin__");
Guido van Rossum687ae002001-10-15 22:03:32 +000059 mod = PyDict_GetItemString(type->tp_dict, "__module__");
Guido van Rossumc3542212001-08-16 09:18:56 +000060 if (mod != NULL && PyString_Check(mod)) {
61 Py_INCREF(mod);
62 return mod;
63 }
64 PyErr_SetString(PyExc_AttributeError, "__module__");
65 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +000066}
67
Guido van Rossum3926a632001-09-25 16:25:58 +000068static int
69type_set_module(PyTypeObject *type, PyObject *value, void *context)
70{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +000071 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE) ||
Guido van Rossum3926a632001-09-25 16:25:58 +000072 strrchr(type->tp_name, '.')) {
73 PyErr_Format(PyExc_TypeError,
74 "can't set %s.__module__", type->tp_name);
75 return -1;
76 }
77 if (!value) {
78 PyErr_Format(PyExc_TypeError,
79 "can't delete %s.__module__", type->tp_name);
80 return -1;
81 }
82 return PyDict_SetItemString(type->tp_dict, "__module__", value);
83}
84
Tim Peters6d6c1a32001-08-02 04:15:00 +000085static PyObject *
86type_dict(PyTypeObject *type, void *context)
87{
88 if (type->tp_dict == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +000089 Py_INCREF(Py_None);
90 return Py_None;
Guido van Rossum29ca26e1995-01-07 11:58:15 +000091 }
Tim Peters6d6c1a32001-08-02 04:15:00 +000092 return PyDictProxy_New(type->tp_dict);
Guido van Rossum29ca26e1995-01-07 11:58:15 +000093}
94
Tim Peters24008312002-03-17 18:56:20 +000095static PyObject *
96type_get_doc(PyTypeObject *type, void *context)
97{
98 PyObject *result;
Guido van Rossum6ca7d412002-04-18 00:22:00 +000099 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE) && type->tp_doc != NULL)
Tim Peters24008312002-03-17 18:56:20 +0000100 return PyString_FromString(type->tp_doc);
Tim Peters24008312002-03-17 18:56:20 +0000101 result = PyDict_GetItemString(type->tp_dict, "__doc__");
Guido van Rossum6ca7d412002-04-18 00:22:00 +0000102 if (result == NULL) {
103 result = Py_None;
104 Py_INCREF(result);
105 }
106 else if (result->ob_type->tp_descr_get) {
Tim Peters2b858972002-04-18 04:12:28 +0000107 result = result->ob_type->tp_descr_get(result, NULL,
108 (PyObject *)type);
Guido van Rossum6ca7d412002-04-18 00:22:00 +0000109 }
110 else {
111 Py_INCREF(result);
112 }
Tim Peters24008312002-03-17 18:56:20 +0000113 return result;
114}
115
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000116static PyGetSetDef type_getsets[] = {
Guido van Rossumc3542212001-08-16 09:18:56 +0000117 {"__name__", (getter)type_name, NULL, NULL},
Guido van Rossum3926a632001-09-25 16:25:58 +0000118 {"__module__", (getter)type_module, (setter)type_set_module, NULL},
Tim Peters6d6c1a32001-08-02 04:15:00 +0000119 {"__dict__", (getter)type_dict, NULL, NULL},
Tim Peters24008312002-03-17 18:56:20 +0000120 {"__doc__", (getter)type_get_doc, NULL, NULL},
Tim Peters6d6c1a32001-08-02 04:15:00 +0000121 {0}
122};
123
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000124static int
125type_compare(PyObject *v, PyObject *w)
126{
127 /* This is called with type objects only. So we
128 can just compare the addresses. */
129 Py_uintptr_t vv = (Py_uintptr_t)v;
130 Py_uintptr_t ww = (Py_uintptr_t)w;
131 return (vv < ww) ? -1 : (vv > ww) ? 1 : 0;
132}
133
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000134static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000135type_repr(PyTypeObject *type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000136{
Barry Warsaw7ce36942001-08-24 18:34:26 +0000137 PyObject *mod, *name, *rtn;
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000138 char *kind;
Guido van Rossumc3542212001-08-16 09:18:56 +0000139
140 mod = type_module(type, NULL);
141 if (mod == NULL)
142 PyErr_Clear();
143 else if (!PyString_Check(mod)) {
144 Py_DECREF(mod);
145 mod = NULL;
146 }
147 name = type_name(type, NULL);
148 if (name == NULL)
149 return NULL;
Barry Warsaw7ce36942001-08-24 18:34:26 +0000150
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000151 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
152 kind = "class";
153 else
154 kind = "type";
155
Barry Warsaw7ce36942001-08-24 18:34:26 +0000156 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__")) {
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000157 rtn = PyString_FromFormat("<%s '%s.%s'>",
158 kind,
Barry Warsaw7ce36942001-08-24 18:34:26 +0000159 PyString_AS_STRING(mod),
160 PyString_AS_STRING(name));
161 }
Guido van Rossumc3542212001-08-16 09:18:56 +0000162 else
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000163 rtn = PyString_FromFormat("<%s '%s'>", kind, type->tp_name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000164
Guido van Rossumc3542212001-08-16 09:18:56 +0000165 Py_XDECREF(mod);
166 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000167 return rtn;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000168}
169
Tim Peters6d6c1a32001-08-02 04:15:00 +0000170static PyObject *
171type_call(PyTypeObject *type, PyObject *args, PyObject *kwds)
172{
173 PyObject *obj;
174
175 if (type->tp_new == NULL) {
176 PyErr_Format(PyExc_TypeError,
177 "cannot create '%.100s' instances",
178 type->tp_name);
179 return NULL;
180 }
181
Tim Peters3f996e72001-09-13 19:18:27 +0000182 obj = type->tp_new(type, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000183 if (obj != NULL) {
Guido van Rossumf76de622001-10-18 15:49:21 +0000184 /* Ugly exception: when the call was type(something),
185 don't call tp_init on the result. */
186 if (type == &PyType_Type &&
187 PyTuple_Check(args) && PyTuple_GET_SIZE(args) == 1 &&
188 (kwds == NULL ||
189 (PyDict_Check(kwds) && PyDict_Size(kwds) == 0)))
190 return obj;
Guido van Rossum8ace1ab2002-04-06 01:05:01 +0000191 /* If the returned object is not an instance of type,
192 it won't be initialized. */
193 if (!PyType_IsSubtype(obj->ob_type, type))
194 return obj;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000195 type = obj->ob_type;
196 if (type->tp_init != NULL &&
197 type->tp_init(obj, args, kwds) < 0) {
198 Py_DECREF(obj);
199 obj = NULL;
200 }
201 }
202 return obj;
203}
204
205PyObject *
206PyType_GenericAlloc(PyTypeObject *type, int nitems)
207{
Tim Peters6d6c1a32001-08-02 04:15:00 +0000208 PyObject *obj;
Tim Petersf2a67da2001-10-07 03:54:51 +0000209 const size_t size = _PyObject_VAR_SIZE(type, nitems);
Tim Peters406fe3b2001-10-06 19:04:01 +0000210
211 if (PyType_IS_GC(type))
Neil Schemenauer09a2ae52002-04-12 03:06:53 +0000212 obj = _PyObject_GC_Malloc(size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000213 else
Neil Schemenauerc806c882001-08-29 23:54:54 +0000214 obj = PyObject_MALLOC(size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000215
Neil Schemenauerc806c882001-08-29 23:54:54 +0000216 if (obj == NULL)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000217 return PyErr_NoMemory();
Tim Peters406fe3b2001-10-06 19:04:01 +0000218
Neil Schemenauerc806c882001-08-29 23:54:54 +0000219 memset(obj, '\0', size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000220
Tim Peters6d6c1a32001-08-02 04:15:00 +0000221 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
222 Py_INCREF(type);
Tim Peters406fe3b2001-10-06 19:04:01 +0000223
Tim Peters6d6c1a32001-08-02 04:15:00 +0000224 if (type->tp_itemsize == 0)
225 PyObject_INIT(obj, type);
226 else
227 (void) PyObject_INIT_VAR((PyVarObject *)obj, type, nitems);
Tim Peters406fe3b2001-10-06 19:04:01 +0000228
Tim Peters6d6c1a32001-08-02 04:15:00 +0000229 if (PyType_IS_GC(type))
Neil Schemenauerc806c882001-08-29 23:54:54 +0000230 _PyObject_GC_TRACK(obj);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000231 return obj;
232}
233
234PyObject *
235PyType_GenericNew(PyTypeObject *type, PyObject *args, PyObject *kwds)
236{
237 return type->tp_alloc(type, 0);
238}
239
Guido van Rossum9475a232001-10-05 20:51:39 +0000240/* Helpers for subtyping */
241
242static int
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000243traverse_slots(PyTypeObject *type, PyObject *self, visitproc visit, void *arg)
244{
245 int i, n;
246 PyMemberDef *mp;
247
248 n = type->ob_size;
249 mp = ((etype *)type)->members;
250 for (i = 0; i < n; i++, mp++) {
251 if (mp->type == T_OBJECT_EX) {
252 char *addr = (char *)self + mp->offset;
253 PyObject *obj = *(PyObject **)addr;
254 if (obj != NULL) {
255 int err = visit(obj, arg);
256 if (err)
257 return err;
258 }
259 }
260 }
261 return 0;
262}
263
264static int
Guido van Rossum9475a232001-10-05 20:51:39 +0000265subtype_traverse(PyObject *self, visitproc visit, void *arg)
266{
267 PyTypeObject *type, *base;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000268 traverseproc basetraverse;
Guido van Rossum9475a232001-10-05 20:51:39 +0000269
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000270 /* Find the nearest base with a different tp_traverse,
271 and traverse slots while we're at it */
Guido van Rossum9475a232001-10-05 20:51:39 +0000272 type = self->ob_type;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000273 base = type;
274 while ((basetraverse = base->tp_traverse) == subtype_traverse) {
275 if (base->ob_size) {
276 int err = traverse_slots(base, self, visit, arg);
277 if (err)
278 return err;
279 }
Guido van Rossum9475a232001-10-05 20:51:39 +0000280 base = base->tp_base;
281 assert(base);
282 }
283
284 if (type->tp_dictoffset != base->tp_dictoffset) {
285 PyObject **dictptr = _PyObject_GetDictPtr(self);
286 if (dictptr && *dictptr) {
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000287 int err = visit(*dictptr, arg);
Guido van Rossum9475a232001-10-05 20:51:39 +0000288 if (err)
289 return err;
290 }
291 }
292
Guido van Rossuma3862092002-06-10 15:24:42 +0000293 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
294 /* For a heaptype, the instances count as references
295 to the type. Traverse the type so the collector
296 can find cycles involving this link. */
297 int err = visit((PyObject *)type, arg);
298 if (err)
299 return err;
300 }
301
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000302 if (basetraverse)
303 return basetraverse(self, visit, arg);
304 return 0;
305}
306
307static void
308clear_slots(PyTypeObject *type, PyObject *self)
309{
310 int i, n;
311 PyMemberDef *mp;
312
313 n = type->ob_size;
314 mp = ((etype *)type)->members;
315 for (i = 0; i < n; i++, mp++) {
316 if (mp->type == T_OBJECT_EX && !(mp->flags & READONLY)) {
317 char *addr = (char *)self + mp->offset;
318 PyObject *obj = *(PyObject **)addr;
319 if (obj != NULL) {
320 Py_DECREF(obj);
321 *(PyObject **)addr = NULL;
322 }
323 }
324 }
325}
326
327static int
328subtype_clear(PyObject *self)
329{
330 PyTypeObject *type, *base;
331 inquiry baseclear;
332
333 /* Find the nearest base with a different tp_clear
334 and clear slots while we're at it */
335 type = self->ob_type;
336 base = type;
337 while ((baseclear = base->tp_clear) == subtype_clear) {
338 if (base->ob_size)
339 clear_slots(base, self);
340 base = base->tp_base;
341 assert(base);
342 }
343
Guido van Rossuma3862092002-06-10 15:24:42 +0000344 /* There's no need to clear the instance dict (if any);
345 the collector will call its tp_clear handler. */
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000346
347 if (baseclear)
348 return baseclear(self);
Guido van Rossum9475a232001-10-05 20:51:39 +0000349 return 0;
350}
Tim Peters6d6c1a32001-08-02 04:15:00 +0000351
Guido van Rossum7ad2d1e2001-10-29 22:11:00 +0000352staticforward PyObject *lookup_maybe(PyObject *, char *, PyObject **);
353
354static int
355call_finalizer(PyObject *self)
356{
357 static PyObject *del_str = NULL;
358 PyObject *del, *res;
359 PyObject *error_type, *error_value, *error_traceback;
360
361 /* Temporarily resurrect the object. */
362#ifdef Py_TRACE_REFS
363#ifndef Py_REF_DEBUG
364# error "Py_TRACE_REFS defined but Py_REF_DEBUG not."
365#endif
366 /* much too complicated if Py_TRACE_REFS defined */
367 _Py_NewReference((PyObject *)self);
368#ifdef COUNT_ALLOCS
369 /* compensate for boost in _Py_NewReference; note that
370 * _Py_RefTotal was also boosted; we'll knock that down later.
371 */
372 self->ob_type->tp_allocs--;
373#endif
374#else /* !Py_TRACE_REFS */
375 /* Py_INCREF boosts _Py_RefTotal if Py_REF_DEBUG is defined */
376 Py_INCREF(self);
377#endif /* !Py_TRACE_REFS */
378
379 /* Save the current exception, if any. */
380 PyErr_Fetch(&error_type, &error_value, &error_traceback);
381
382 /* Execute __del__ method, if any. */
383 del = lookup_maybe(self, "__del__", &del_str);
384 if (del != NULL) {
385 res = PyEval_CallObject(del, NULL);
386 if (res == NULL)
387 PyErr_WriteUnraisable(del);
388 else
389 Py_DECREF(res);
390 Py_DECREF(del);
391 }
392
393 /* Restore the saved exception. */
394 PyErr_Restore(error_type, error_value, error_traceback);
395
396 /* Undo the temporary resurrection; can't use DECREF here, it would
397 * cause a recursive call.
398 */
399#ifdef Py_REF_DEBUG
400 /* _Py_RefTotal was boosted either by _Py_NewReference or
401 * Py_INCREF above.
402 */
403 _Py_RefTotal--;
404#endif
405 if (--self->ob_refcnt > 0) {
406#ifdef COUNT_ALLOCS
407 self->ob_type->tp_frees--;
408#endif
409 _PyObject_GC_TRACK(self);
410 return -1; /* __del__ added a reference; don't delete now */
411 }
412#ifdef Py_TRACE_REFS
413 _Py_ForgetReference((PyObject *)self);
414#ifdef COUNT_ALLOCS
415 /* compensate for increment in _Py_ForgetReference */
416 self->ob_type->tp_frees--;
417#endif
418#endif
419
420 return 0;
421}
422
Tim Peters6d6c1a32001-08-02 04:15:00 +0000423static void
424subtype_dealloc(PyObject *self)
425{
Guido van Rossum14227b42001-12-06 02:35:58 +0000426 PyTypeObject *type, *base;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000427 destructor basedealloc;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000428
429 /* This exists so we can DECREF self->ob_type */
430
Guido van Rossum7ad2d1e2001-10-29 22:11:00 +0000431 if (call_finalizer(self) < 0)
432 return;
433
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000434 /* Find the nearest base with a different tp_dealloc
435 and clear slots while we're at it */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000436 type = self->ob_type;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000437 base = type;
438 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
439 if (base->ob_size)
440 clear_slots(base, self);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000441 base = base->tp_base;
442 assert(base);
Guido van Rossum14227b42001-12-06 02:35:58 +0000443 }
444
Tim Peters6d6c1a32001-08-02 04:15:00 +0000445 /* If we added a dict, DECREF it */
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000446 if (type->tp_dictoffset && !base->tp_dictoffset) {
447 PyObject **dictptr = _PyObject_GetDictPtr(self);
448 if (dictptr != NULL) {
449 PyObject *dict = *dictptr;
450 if (dict != NULL) {
451 Py_DECREF(dict);
452 *dictptr = NULL;
453 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000454 }
455 }
456
Guido van Rossum9676b222001-08-17 20:32:36 +0000457 /* If we added weaklist, we clear it */
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000458 if (type->tp_weaklistoffset && !base->tp_weaklistoffset)
Guido van Rossum9676b222001-08-17 20:32:36 +0000459 PyObject_ClearWeakRefs(self);
460
Tim Peters6d6c1a32001-08-02 04:15:00 +0000461 /* Finalize GC if the base doesn't do GC and we do */
462 if (PyType_IS_GC(type) && !PyType_IS_GC(base))
Guido van Rossum048eb752001-10-02 21:24:57 +0000463 _PyObject_GC_UNTRACK(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000464
465 /* Call the base tp_dealloc() */
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000466 assert(basedealloc);
467 basedealloc(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000468
469 /* Can't reference self beyond this point */
470 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
471 Py_DECREF(type);
472 }
473}
474
Tim Peters6d6c1a32001-08-02 04:15:00 +0000475staticforward PyTypeObject *solid_base(PyTypeObject *type);
476
Tim Peters6d6c1a32001-08-02 04:15:00 +0000477/* type test with subclassing support */
478
479int
480PyType_IsSubtype(PyTypeObject *a, PyTypeObject *b)
481{
482 PyObject *mro;
483
Guido van Rossum9478d072001-09-07 18:52:13 +0000484 if (!(a->tp_flags & Py_TPFLAGS_HAVE_CLASS))
485 return b == a || b == &PyBaseObject_Type;
486
Tim Peters6d6c1a32001-08-02 04:15:00 +0000487 mro = a->tp_mro;
488 if (mro != NULL) {
489 /* Deal with multiple inheritance without recursion
490 by walking the MRO tuple */
491 int i, n;
492 assert(PyTuple_Check(mro));
493 n = PyTuple_GET_SIZE(mro);
494 for (i = 0; i < n; i++) {
495 if (PyTuple_GET_ITEM(mro, i) == (PyObject *)b)
496 return 1;
497 }
498 return 0;
499 }
500 else {
501 /* a is not completely initilized yet; follow tp_base */
502 do {
503 if (a == b)
504 return 1;
505 a = a->tp_base;
506 } while (a != NULL);
507 return b == &PyBaseObject_Type;
508 }
509}
510
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000511/* Internal routines to do a method lookup in the type
Guido van Rossum60718732001-08-28 17:47:51 +0000512 without looking in the instance dictionary
513 (so we can't use PyObject_GetAttr) but still binding
514 it to the instance. The arguments are the object,
515 the method name as a C string, and the address of a
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000516 static variable used to cache the interned Python string.
517
518 Two variants:
519
520 - lookup_maybe() returns NULL without raising an exception
521 when the _PyType_Lookup() call fails;
522
523 - lookup_method() always raises an exception upon errors.
524*/
Guido van Rossum60718732001-08-28 17:47:51 +0000525
526static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000527lookup_maybe(PyObject *self, char *attrstr, PyObject **attrobj)
Guido van Rossum60718732001-08-28 17:47:51 +0000528{
529 PyObject *res;
530
531 if (*attrobj == NULL) {
532 *attrobj = PyString_InternFromString(attrstr);
533 if (*attrobj == NULL)
534 return NULL;
535 }
536 res = _PyType_Lookup(self->ob_type, *attrobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000537 if (res != NULL) {
Guido van Rossum60718732001-08-28 17:47:51 +0000538 descrgetfunc f;
539 if ((f = res->ob_type->tp_descr_get) == NULL)
540 Py_INCREF(res);
541 else
542 res = f(res, self, (PyObject *)(self->ob_type));
543 }
544 return res;
545}
546
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000547static PyObject *
548lookup_method(PyObject *self, char *attrstr, PyObject **attrobj)
549{
550 PyObject *res = lookup_maybe(self, attrstr, attrobj);
551 if (res == NULL && !PyErr_Occurred())
552 PyErr_SetObject(PyExc_AttributeError, *attrobj);
553 return res;
554}
555
Guido van Rossum2730b132001-08-28 18:22:14 +0000556/* A variation of PyObject_CallMethod that uses lookup_method()
557 instead of PyObject_GetAttrString(). This uses the same convention
558 as lookup_method to cache the interned name string object. */
559
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000560static PyObject *
Guido van Rossum2730b132001-08-28 18:22:14 +0000561call_method(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
562{
563 va_list va;
564 PyObject *args, *func = 0, *retval;
Guido van Rossum2730b132001-08-28 18:22:14 +0000565 va_start(va, format);
566
Guido van Rossumda21c012001-10-03 00:50:18 +0000567 func = lookup_maybe(o, name, nameobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000568 if (func == NULL) {
569 va_end(va);
570 if (!PyErr_Occurred())
Guido van Rossumda21c012001-10-03 00:50:18 +0000571 PyErr_SetObject(PyExc_AttributeError, *nameobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000572 return NULL;
573 }
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000574
575 if (format && *format)
576 args = Py_VaBuildValue(format, va);
577 else
578 args = PyTuple_New(0);
579
580 va_end(va);
581
582 if (args == NULL)
583 return NULL;
584
585 assert(PyTuple_Check(args));
586 retval = PyObject_Call(func, args, NULL);
587
588 Py_DECREF(args);
589 Py_DECREF(func);
590
591 return retval;
592}
593
594/* Clone of call_method() that returns NotImplemented when the lookup fails. */
595
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000596static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000597call_maybe(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
598{
599 va_list va;
600 PyObject *args, *func = 0, *retval;
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000601 va_start(va, format);
602
Guido van Rossumda21c012001-10-03 00:50:18 +0000603 func = lookup_maybe(o, name, nameobj);
Guido van Rossum2730b132001-08-28 18:22:14 +0000604 if (func == NULL) {
605 va_end(va);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000606 if (!PyErr_Occurred()) {
607 Py_INCREF(Py_NotImplemented);
608 return Py_NotImplemented;
609 }
Guido van Rossum717ce002001-09-14 16:58:08 +0000610 return NULL;
Guido van Rossum2730b132001-08-28 18:22:14 +0000611 }
612
613 if (format && *format)
614 args = Py_VaBuildValue(format, va);
615 else
616 args = PyTuple_New(0);
617
618 va_end(va);
619
Guido van Rossum717ce002001-09-14 16:58:08 +0000620 if (args == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +0000621 return NULL;
622
Guido van Rossum717ce002001-09-14 16:58:08 +0000623 assert(PyTuple_Check(args));
624 retval = PyObject_Call(func, args, NULL);
Guido van Rossum2730b132001-08-28 18:22:14 +0000625
626 Py_DECREF(args);
627 Py_DECREF(func);
628
629 return retval;
630}
631
Tim Peters6d6c1a32001-08-02 04:15:00 +0000632/* Method resolution order algorithm from "Putting Metaclasses to Work"
633 by Forman and Danforth (Addison-Wesley 1999). */
634
635static int
636conservative_merge(PyObject *left, PyObject *right)
637{
638 int left_size;
639 int right_size;
640 int i, j, r, ok;
641 PyObject *temp, *rr;
642
643 assert(PyList_Check(left));
644 assert(PyList_Check(right));
645
646 again:
647 left_size = PyList_GET_SIZE(left);
648 right_size = PyList_GET_SIZE(right);
649 for (i = 0; i < left_size; i++) {
650 for (j = 0; j < right_size; j++) {
651 if (PyList_GET_ITEM(left, i) ==
652 PyList_GET_ITEM(right, j)) {
653 /* found a merge point */
654 temp = PyList_New(0);
655 if (temp == NULL)
656 return -1;
657 for (r = 0; r < j; r++) {
658 rr = PyList_GET_ITEM(right, r);
659 ok = PySequence_Contains(left, rr);
660 if (ok < 0) {
661 Py_DECREF(temp);
662 return -1;
663 }
664 if (!ok) {
665 ok = PyList_Append(temp, rr);
666 if (ok < 0) {
667 Py_DECREF(temp);
668 return -1;
669 }
670 }
671 }
672 ok = PyList_SetSlice(left, i, i, temp);
673 Py_DECREF(temp);
674 if (ok < 0)
675 return -1;
676 ok = PyList_SetSlice(right, 0, j+1, NULL);
677 if (ok < 0)
678 return -1;
679 goto again;
680 }
681 }
682 }
683 return PyList_SetSlice(left, left_size, left_size, right);
684}
685
686static int
687serious_order_disagreements(PyObject *left, PyObject *right)
688{
689 return 0; /* XXX later -- for now, we cheat: "don't do that" */
690}
691
Tim Petersa91e9642001-11-14 23:32:33 +0000692static int
693fill_classic_mro(PyObject *mro, PyObject *cls)
694{
695 PyObject *bases, *base;
696 int i, n;
697
698 assert(PyList_Check(mro));
699 assert(PyClass_Check(cls));
700 i = PySequence_Contains(mro, cls);
701 if (i < 0)
702 return -1;
703 if (!i) {
704 if (PyList_Append(mro, cls) < 0)
705 return -1;
706 }
707 bases = ((PyClassObject *)cls)->cl_bases;
708 assert(bases && PyTuple_Check(bases));
709 n = PyTuple_GET_SIZE(bases);
710 for (i = 0; i < n; i++) {
711 base = PyTuple_GET_ITEM(bases, i);
712 if (fill_classic_mro(mro, base) < 0)
713 return -1;
714 }
715 return 0;
716}
717
718static PyObject *
719classic_mro(PyObject *cls)
720{
721 PyObject *mro;
722
723 assert(PyClass_Check(cls));
724 mro = PyList_New(0);
725 if (mro != NULL) {
726 if (fill_classic_mro(mro, cls) == 0)
727 return mro;
728 Py_DECREF(mro);
729 }
730 return NULL;
731}
732
Tim Peters6d6c1a32001-08-02 04:15:00 +0000733static PyObject *
734mro_implementation(PyTypeObject *type)
735{
736 int i, n, ok;
737 PyObject *bases, *result;
738
739 bases = type->tp_bases;
740 n = PyTuple_GET_SIZE(bases);
741 result = Py_BuildValue("[O]", (PyObject *)type);
742 if (result == NULL)
743 return NULL;
744 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +0000745 PyObject *base = PyTuple_GET_ITEM(bases, i);
746 PyObject *parentMRO;
747 if (PyType_Check(base))
748 parentMRO = PySequence_List(
749 ((PyTypeObject*)base)->tp_mro);
750 else
751 parentMRO = classic_mro(base);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000752 if (parentMRO == NULL) {
753 Py_DECREF(result);
754 return NULL;
755 }
756 if (serious_order_disagreements(result, parentMRO)) {
757 Py_DECREF(result);
758 return NULL;
759 }
760 ok = conservative_merge(result, parentMRO);
761 Py_DECREF(parentMRO);
762 if (ok < 0) {
763 Py_DECREF(result);
764 return NULL;
765 }
766 }
767 return result;
768}
769
770static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000771mro_external(PyObject *self)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000772{
773 PyTypeObject *type = (PyTypeObject *)self;
774
Tim Peters6d6c1a32001-08-02 04:15:00 +0000775 return mro_implementation(type);
776}
777
778static int
779mro_internal(PyTypeObject *type)
780{
781 PyObject *mro, *result, *tuple;
782
783 if (type->ob_type == &PyType_Type) {
784 result = mro_implementation(type);
785 }
786 else {
Guido van Rossum60718732001-08-28 17:47:51 +0000787 static PyObject *mro_str;
788 mro = lookup_method((PyObject *)type, "mro", &mro_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000789 if (mro == NULL)
790 return -1;
791 result = PyObject_CallObject(mro, NULL);
792 Py_DECREF(mro);
793 }
794 if (result == NULL)
795 return -1;
796 tuple = PySequence_Tuple(result);
797 Py_DECREF(result);
798 type->tp_mro = tuple;
799 return 0;
800}
801
802
803/* Calculate the best base amongst multiple base classes.
804 This is the first one that's on the path to the "solid base". */
805
806static PyTypeObject *
807best_base(PyObject *bases)
808{
809 int i, n;
810 PyTypeObject *base, *winner, *candidate, *base_i;
Tim Petersa91e9642001-11-14 23:32:33 +0000811 PyObject *base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000812
813 assert(PyTuple_Check(bases));
814 n = PyTuple_GET_SIZE(bases);
815 assert(n > 0);
Tim Petersa91e9642001-11-14 23:32:33 +0000816 base = NULL;
817 winner = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000818 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +0000819 base_proto = PyTuple_GET_ITEM(bases, i);
820 if (PyClass_Check(base_proto))
821 continue;
822 if (!PyType_Check(base_proto)) {
Tim Peters6d6c1a32001-08-02 04:15:00 +0000823 PyErr_SetString(
824 PyExc_TypeError,
825 "bases must be types");
826 return NULL;
827 }
Tim Petersa91e9642001-11-14 23:32:33 +0000828 base_i = (PyTypeObject *)base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000829 if (base_i->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +0000830 if (PyType_Ready(base_i) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000831 return NULL;
832 }
833 candidate = solid_base(base_i);
Tim Petersa91e9642001-11-14 23:32:33 +0000834 if (winner == NULL) {
835 winner = candidate;
836 base = base_i;
837 }
838 else if (PyType_IsSubtype(winner, candidate))
Tim Peters6d6c1a32001-08-02 04:15:00 +0000839 ;
840 else if (PyType_IsSubtype(candidate, winner)) {
841 winner = candidate;
842 base = base_i;
843 }
844 else {
845 PyErr_SetString(
846 PyExc_TypeError,
847 "multiple bases have "
848 "instance lay-out conflict");
849 return NULL;
850 }
851 }
Guido van Rossume54616c2001-12-14 04:19:56 +0000852 if (base == NULL)
853 PyErr_SetString(PyExc_TypeError,
854 "a new-style class can't have only classic bases");
Tim Peters6d6c1a32001-08-02 04:15:00 +0000855 return base;
856}
857
858static int
859extra_ivars(PyTypeObject *type, PyTypeObject *base)
860{
Neil Schemenauerc806c882001-08-29 23:54:54 +0000861 size_t t_size = type->tp_basicsize;
862 size_t b_size = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000863
Guido van Rossum9676b222001-08-17 20:32:36 +0000864 assert(t_size >= b_size); /* Else type smaller than base! */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000865 if (type->tp_itemsize || base->tp_itemsize) {
866 /* If itemsize is involved, stricter rules */
867 return t_size != b_size ||
868 type->tp_itemsize != base->tp_itemsize;
869 }
Guido van Rossum9676b222001-08-17 20:32:36 +0000870 if (type->tp_weaklistoffset && base->tp_weaklistoffset == 0 &&
871 type->tp_weaklistoffset + sizeof(PyObject *) == t_size)
872 t_size -= sizeof(PyObject *);
873 if (type->tp_dictoffset && base->tp_dictoffset == 0 &&
874 type->tp_dictoffset + sizeof(PyObject *) == t_size)
875 t_size -= sizeof(PyObject *);
876
877 return t_size != b_size;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000878}
879
880static PyTypeObject *
881solid_base(PyTypeObject *type)
882{
883 PyTypeObject *base;
884
885 if (type->tp_base)
886 base = solid_base(type->tp_base);
887 else
888 base = &PyBaseObject_Type;
889 if (extra_ivars(type, base))
890 return type;
891 else
892 return base;
893}
894
895staticforward void object_dealloc(PyObject *);
896staticforward int object_init(PyObject *, PyObject *, PyObject *);
Guido van Rossum875eeaa2001-10-11 18:33:53 +0000897staticforward int update_slot(PyTypeObject *, PyObject *);
Guido van Rossum7b9144b2001-10-09 19:39:46 +0000898staticforward void fixup_slot_dispatchers(PyTypeObject *);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000899
900static PyObject *
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000901subtype_dict(PyObject *obj, void *context)
902{
903 PyObject **dictptr = _PyObject_GetDictPtr(obj);
904 PyObject *dict;
905
906 if (dictptr == NULL) {
907 PyErr_SetString(PyExc_AttributeError,
908 "This object has no __dict__");
909 return NULL;
910 }
911 dict = *dictptr;
Guido van Rossum3926a632001-09-25 16:25:58 +0000912 if (dict == NULL)
913 *dictptr = dict = PyDict_New();
914 Py_XINCREF(dict);
915 return dict;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000916}
917
Guido van Rossum6661be32001-10-26 04:26:12 +0000918static int
919subtype_setdict(PyObject *obj, PyObject *value, void *context)
920{
921 PyObject **dictptr = _PyObject_GetDictPtr(obj);
922 PyObject *dict;
923
924 if (dictptr == NULL) {
925 PyErr_SetString(PyExc_AttributeError,
926 "This object has no __dict__");
927 return -1;
928 }
Guido van Rossumd331cb52001-12-05 19:46:42 +0000929 if (value != NULL && !PyDict_Check(value)) {
Guido van Rossum6661be32001-10-26 04:26:12 +0000930 PyErr_SetString(PyExc_TypeError,
931 "__dict__ must be set to a dictionary");
932 return -1;
933 }
934 dict = *dictptr;
Guido van Rossumd331cb52001-12-05 19:46:42 +0000935 Py_XINCREF(value);
Guido van Rossum6661be32001-10-26 04:26:12 +0000936 *dictptr = value;
937 Py_XDECREF(dict);
938 return 0;
939}
940
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000941static PyGetSetDef subtype_getsets[] = {
Guido van Rossum6661be32001-10-26 04:26:12 +0000942 {"__dict__", subtype_dict, subtype_setdict, NULL},
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000943 {0},
944};
945
Guido van Rossum0628dcf2002-03-14 23:03:14 +0000946/* bozo: __getstate__ that raises TypeError */
947
948static PyObject *
949bozo_func(PyObject *self, PyObject *args)
950{
951 PyErr_SetString(PyExc_TypeError,
952 "a class that defines __slots__ without "
953 "defining __getstate__ cannot be pickled");
954 return NULL;
955}
956
Neal Norwitz93c1e232002-03-31 16:06:11 +0000957static PyMethodDef bozo_ml = {"__getstate__", bozo_func, METH_VARARGS};
Guido van Rossum0628dcf2002-03-14 23:03:14 +0000958
959static PyObject *bozo_obj = NULL;
960
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000961static int
962valid_identifier(PyObject *s)
963{
964 char *p;
965 int i, n;
966
967 if (!PyString_Check(s)) {
968 PyErr_SetString(PyExc_TypeError,
969 "__slots__ must be strings");
970 return 0;
971 }
972 p = PyString_AS_STRING(s);
973 n = PyString_GET_SIZE(s);
974 /* We must reject an empty name. As a hack, we bump the
975 length to 1 so that the loop will balk on the trailing \0. */
976 if (n == 0)
977 n = 1;
978 for (i = 0; i < n; i++, p++) {
979 if (!(i == 0 ? isalpha(*p) : isalnum(*p)) && *p != '_') {
980 PyErr_SetString(PyExc_TypeError,
981 "__slots__ must be identifiers");
982 return 0;
983 }
984 }
985 return 1;
986}
987
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000988static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000989type_new(PyTypeObject *metatype, PyObject *args, PyObject *kwds)
990{
991 PyObject *name, *bases, *dict;
992 static char *kwlist[] = {"name", "bases", "dict", 0};
993 PyObject *slots, *tmp;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000994 PyTypeObject *type, *base, *tmptype, *winner;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000995 etype *et;
Guido van Rossum6f799372001-09-20 20:46:19 +0000996 PyMemberDef *mp;
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +0000997 int i, nbases, nslots, slotoffset, add_dict, add_weak;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000998
Tim Peters3abca122001-10-27 19:37:48 +0000999 assert(args != NULL && PyTuple_Check(args));
1000 assert(kwds == NULL || PyDict_Check(kwds));
1001
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001002 /* Special case: type(x) should return x->ob_type */
Tim Peters3abca122001-10-27 19:37:48 +00001003 {
1004 const int nargs = PyTuple_GET_SIZE(args);
1005 const int nkwds = kwds == NULL ? 0 : PyDict_Size(kwds);
1006
1007 if (PyType_CheckExact(metatype) && nargs == 1 && nkwds == 0) {
1008 PyObject *x = PyTuple_GET_ITEM(args, 0);
1009 Py_INCREF(x->ob_type);
1010 return (PyObject *) x->ob_type;
1011 }
1012
1013 /* SF bug 475327 -- if that didn't trigger, we need 3
1014 arguments. but PyArg_ParseTupleAndKeywords below may give
1015 a msg saying type() needs exactly 3. */
1016 if (nargs + nkwds != 3) {
1017 PyErr_SetString(PyExc_TypeError,
1018 "type() takes 1 or 3 arguments");
1019 return NULL;
1020 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001021 }
1022
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001023 /* Check arguments: (name, bases, dict) */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001024 if (!PyArg_ParseTupleAndKeywords(args, kwds, "SO!O!:type", kwlist,
1025 &name,
1026 &PyTuple_Type, &bases,
1027 &PyDict_Type, &dict))
1028 return NULL;
1029
1030 /* Determine the proper metatype to deal with this,
1031 and check for metatype conflicts while we're at it.
1032 Note that if some other metatype wins to contract,
1033 it's possible that its instances are not types. */
1034 nbases = PyTuple_GET_SIZE(bases);
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001035 winner = metatype;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001036 for (i = 0; i < nbases; i++) {
1037 tmp = PyTuple_GET_ITEM(bases, i);
1038 tmptype = tmp->ob_type;
Tim Petersa91e9642001-11-14 23:32:33 +00001039 if (tmptype == &PyClass_Type)
1040 continue; /* Special case classic classes */
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001041 if (PyType_IsSubtype(winner, tmptype))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001042 continue;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001043 if (PyType_IsSubtype(tmptype, winner)) {
1044 winner = tmptype;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001045 continue;
1046 }
1047 PyErr_SetString(PyExc_TypeError,
1048 "metatype conflict among bases");
1049 return NULL;
1050 }
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001051 if (winner != metatype) {
1052 if (winner->tp_new != type_new) /* Pass it to the winner */
1053 return winner->tp_new(winner, args, kwds);
1054 metatype = winner;
1055 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001056
1057 /* Adjust for empty tuple bases */
1058 if (nbases == 0) {
1059 bases = Py_BuildValue("(O)", &PyBaseObject_Type);
1060 if (bases == NULL)
1061 return NULL;
1062 nbases = 1;
1063 }
1064 else
1065 Py_INCREF(bases);
1066
1067 /* XXX From here until type is allocated, "return NULL" leaks bases! */
1068
1069 /* Calculate best base, and check that all bases are type objects */
1070 base = best_base(bases);
1071 if (base == NULL)
1072 return NULL;
1073 if (!PyType_HasFeature(base, Py_TPFLAGS_BASETYPE)) {
1074 PyErr_Format(PyExc_TypeError,
1075 "type '%.100s' is not an acceptable base type",
1076 base->tp_name);
1077 return NULL;
1078 }
1079
Tim Peters6d6c1a32001-08-02 04:15:00 +00001080 /* Check for a __slots__ sequence variable in dict, and count it */
1081 slots = PyDict_GetItemString(dict, "__slots__");
1082 nslots = 0;
Guido van Rossum9676b222001-08-17 20:32:36 +00001083 add_dict = 0;
1084 add_weak = 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001085 if (slots != NULL) {
1086 /* Make it into a tuple */
1087 if (PyString_Check(slots))
1088 slots = Py_BuildValue("(O)", slots);
1089 else
1090 slots = PySequence_Tuple(slots);
1091 if (slots == NULL)
1092 return NULL;
1093 nslots = PyTuple_GET_SIZE(slots);
Guido van Rossumc4141872001-08-30 04:43:35 +00001094 if (nslots > 0 && base->tp_itemsize != 0) {
1095 PyErr_Format(PyExc_TypeError,
1096 "nonempty __slots__ "
1097 "not supported for subtype of '%s'",
1098 base->tp_name);
1099 return NULL;
1100 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001101 for (i = 0; i < nslots; i++) {
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001102 if (!valid_identifier(PyTuple_GET_ITEM(slots, i))) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001103 Py_DECREF(slots);
1104 return NULL;
1105 }
1106 }
1107 }
Guido van Rossum0628dcf2002-03-14 23:03:14 +00001108 if (slots != NULL) {
1109 /* See if *this* class defines __getstate__ */
1110 PyObject *getstate = PyDict_GetItemString(dict,
1111 "__getstate__");
1112 if (getstate == NULL) {
1113 /* If not, provide a bozo that raises TypeError */
1114 if (bozo_obj == NULL) {
1115 bozo_obj = PyCFunction_New(&bozo_ml, NULL);
1116 if (bozo_obj == NULL) {
1117 /* XXX decref various things */
1118 return NULL;
1119 }
1120 }
1121 if (PyDict_SetItemString(dict,
1122 "__getstate__",
1123 bozo_obj) < 0) {
1124 /* XXX decref various things */
1125 return NULL;
1126 }
1127 }
1128 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001129 if (slots == NULL && base->tp_dictoffset == 0 &&
1130 (base->tp_setattro == PyObject_GenericSetAttr ||
Guido van Rossum9676b222001-08-17 20:32:36 +00001131 base->tp_setattro == NULL)) {
Guido van Rossum9676b222001-08-17 20:32:36 +00001132 add_dict++;
1133 }
Guido van Rossumc4141872001-08-30 04:43:35 +00001134 if (slots == NULL && base->tp_weaklistoffset == 0 &&
1135 base->tp_itemsize == 0) {
Guido van Rossum9676b222001-08-17 20:32:36 +00001136 nslots++;
1137 add_weak++;
1138 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001139
1140 /* XXX From here until type is safely allocated,
1141 "return NULL" may leak slots! */
1142
1143 /* Allocate the type object */
1144 type = (PyTypeObject *)metatype->tp_alloc(metatype, nslots);
1145 if (type == NULL)
1146 return NULL;
1147
1148 /* Keep name and slots alive in the extended type object */
1149 et = (etype *)type;
1150 Py_INCREF(name);
1151 et->name = name;
1152 et->slots = slots;
1153
Guido van Rossumdc91b992001-08-08 22:26:22 +00001154 /* Initialize tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001155 type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE |
1156 Py_TPFLAGS_BASETYPE;
Guido van Rossum048eb752001-10-02 21:24:57 +00001157 if (base->tp_flags & Py_TPFLAGS_HAVE_GC)
1158 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossumdc91b992001-08-08 22:26:22 +00001159
1160 /* It's a new-style number unless it specifically inherits any
1161 old-style numeric behavior */
1162 if ((base->tp_flags & Py_TPFLAGS_CHECKTYPES) ||
1163 (base->tp_as_number == NULL))
1164 type->tp_flags |= Py_TPFLAGS_CHECKTYPES;
1165
1166 /* Initialize essential fields */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001167 type->tp_as_number = &et->as_number;
1168 type->tp_as_sequence = &et->as_sequence;
1169 type->tp_as_mapping = &et->as_mapping;
1170 type->tp_as_buffer = &et->as_buffer;
1171 type->tp_name = PyString_AS_STRING(name);
1172
1173 /* Set tp_base and tp_bases */
1174 type->tp_bases = bases;
1175 Py_INCREF(base);
1176 type->tp_base = base;
1177
Guido van Rossum687ae002001-10-15 22:03:32 +00001178 /* Initialize tp_dict from passed-in dict */
1179 type->tp_dict = dict = PyDict_Copy(dict);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001180 if (dict == NULL) {
1181 Py_DECREF(type);
1182 return NULL;
1183 }
1184
Guido van Rossumc3542212001-08-16 09:18:56 +00001185 /* Set __module__ in the dict */
1186 if (PyDict_GetItemString(dict, "__module__") == NULL) {
1187 tmp = PyEval_GetGlobals();
1188 if (tmp != NULL) {
1189 tmp = PyDict_GetItemString(tmp, "__name__");
1190 if (tmp != NULL) {
1191 if (PyDict_SetItemString(dict, "__module__",
1192 tmp) < 0)
1193 return NULL;
1194 }
1195 }
1196 }
1197
Tim Peters2f93e282001-10-04 05:27:00 +00001198 /* Set tp_doc to a copy of dict['__doc__'], if the latter is there
Tim Peters24008312002-03-17 18:56:20 +00001199 and is a string. The __doc__ accessor will first look for tp_doc;
1200 if that fails, it will still look into __dict__.
Tim Peters2f93e282001-10-04 05:27:00 +00001201 */
1202 {
1203 PyObject *doc = PyDict_GetItemString(dict, "__doc__");
1204 if (doc != NULL && PyString_Check(doc)) {
1205 const size_t n = (size_t)PyString_GET_SIZE(doc);
Tim Peters59f809d2001-10-04 05:43:02 +00001206 type->tp_doc = (char *)PyObject_MALLOC(n+1);
Tim Peters2f93e282001-10-04 05:27:00 +00001207 if (type->tp_doc == NULL) {
1208 Py_DECREF(type);
1209 return NULL;
1210 }
1211 memcpy(type->tp_doc, PyString_AS_STRING(doc), n+1);
1212 }
1213 }
1214
Tim Peters6d6c1a32001-08-02 04:15:00 +00001215 /* Special-case __new__: if it's a plain function,
1216 make it a static function */
1217 tmp = PyDict_GetItemString(dict, "__new__");
1218 if (tmp != NULL && PyFunction_Check(tmp)) {
1219 tmp = PyStaticMethod_New(tmp);
1220 if (tmp == NULL) {
1221 Py_DECREF(type);
1222 return NULL;
1223 }
1224 PyDict_SetItemString(dict, "__new__", tmp);
1225 Py_DECREF(tmp);
1226 }
1227
1228 /* Add descriptors for custom slots from __slots__, or for __dict__ */
1229 mp = et->members;
Neil Schemenauerc806c882001-08-29 23:54:54 +00001230 slotoffset = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001231 if (slots != NULL) {
1232 for (i = 0; i < nslots; i++, mp++) {
1233 mp->name = PyString_AS_STRING(
1234 PyTuple_GET_ITEM(slots, i));
Guido van Rossum64b206c2001-12-04 17:13:22 +00001235 mp->type = T_OBJECT_EX;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001236 mp->offset = slotoffset;
Guido van Rossum9676b222001-08-17 20:32:36 +00001237 if (base->tp_weaklistoffset == 0 &&
Guido van Rossum64b206c2001-12-04 17:13:22 +00001238 strcmp(mp->name, "__weakref__") == 0) {
1239 mp->type = T_OBJECT;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001240 mp->flags = READONLY;
Guido van Rossum9676b222001-08-17 20:32:36 +00001241 type->tp_weaklistoffset = slotoffset;
Guido van Rossum64b206c2001-12-04 17:13:22 +00001242 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001243 slotoffset += sizeof(PyObject *);
1244 }
1245 }
Guido van Rossum9676b222001-08-17 20:32:36 +00001246 else {
1247 if (add_dict) {
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001248 if (base->tp_itemsize)
Guido van Rossum048eb752001-10-02 21:24:57 +00001249 type->tp_dictoffset =
1250 -(long)sizeof(PyObject *);
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001251 else
1252 type->tp_dictoffset = slotoffset;
Guido van Rossum9676b222001-08-17 20:32:36 +00001253 slotoffset += sizeof(PyObject *);
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001254 type->tp_getset = subtype_getsets;
Guido van Rossum9676b222001-08-17 20:32:36 +00001255 }
1256 if (add_weak) {
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001257 assert(!base->tp_itemsize);
Guido van Rossum9676b222001-08-17 20:32:36 +00001258 type->tp_weaklistoffset = slotoffset;
1259 mp->name = "__weakref__";
1260 mp->type = T_OBJECT;
1261 mp->offset = slotoffset;
Tim Peters26f68f52001-09-18 00:23:33 +00001262 mp->flags = READONLY;
Guido van Rossum9676b222001-08-17 20:32:36 +00001263 mp++;
1264 slotoffset += sizeof(PyObject *);
1265 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001266 }
1267 type->tp_basicsize = slotoffset;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001268 type->tp_itemsize = base->tp_itemsize;
Guido van Rossum13d52f02001-08-10 21:24:08 +00001269 type->tp_members = et->members;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001270
1271 /* Special case some slots */
1272 if (type->tp_dictoffset != 0 || nslots > 0) {
1273 if (base->tp_getattr == NULL && base->tp_getattro == NULL)
1274 type->tp_getattro = PyObject_GenericGetAttr;
1275 if (base->tp_setattr == NULL && base->tp_setattro == NULL)
1276 type->tp_setattro = PyObject_GenericSetAttr;
1277 }
1278 type->tp_dealloc = subtype_dealloc;
1279
Guido van Rossum9475a232001-10-05 20:51:39 +00001280 /* Enable GC unless there are really no instance variables possible */
1281 if (!(type->tp_basicsize == sizeof(PyObject) &&
1282 type->tp_itemsize == 0))
1283 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
1284
Tim Peters6d6c1a32001-08-02 04:15:00 +00001285 /* Always override allocation strategy to use regular heap */
1286 type->tp_alloc = PyType_GenericAlloc;
Guido van Rossum048eb752001-10-02 21:24:57 +00001287 if (type->tp_flags & Py_TPFLAGS_HAVE_GC) {
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00001288 type->tp_free = PyObject_GC_Del;
Guido van Rossum9475a232001-10-05 20:51:39 +00001289 type->tp_traverse = subtype_traverse;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001290 type->tp_clear = subtype_clear;
Guido van Rossum048eb752001-10-02 21:24:57 +00001291 }
1292 else
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00001293 type->tp_free = PyObject_Del;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001294
1295 /* Initialize the rest */
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001296 if (PyType_Ready(type) < 0) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001297 Py_DECREF(type);
1298 return NULL;
1299 }
1300
Guido van Rossum7b9144b2001-10-09 19:39:46 +00001301 /* Put the proper slots in place */
1302 fixup_slot_dispatchers(type);
Guido van Rossumf040ede2001-08-07 16:40:56 +00001303
Tim Peters6d6c1a32001-08-02 04:15:00 +00001304 return (PyObject *)type;
1305}
1306
1307/* Internal API to look for a name through the MRO.
1308 This returns a borrowed reference, and doesn't set an exception! */
1309PyObject *
1310_PyType_Lookup(PyTypeObject *type, PyObject *name)
1311{
1312 int i, n;
Tim Petersa91e9642001-11-14 23:32:33 +00001313 PyObject *mro, *res, *base, *dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001314
Guido van Rossum687ae002001-10-15 22:03:32 +00001315 /* Look in tp_dict of types in MRO */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001316 mro = type->tp_mro;
Guido van Rossum23094982002-06-10 14:30:43 +00001317
1318 /* If mro is NULL, the type is either not yet initialized
1319 by PyType_Ready(), or already cleared by type_clear().
1320 Either way the safest thing to do is to return NULL. */
1321 if (mro == NULL)
1322 return NULL;
1323
Tim Peters6d6c1a32001-08-02 04:15:00 +00001324 assert(PyTuple_Check(mro));
1325 n = PyTuple_GET_SIZE(mro);
1326 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00001327 base = PyTuple_GET_ITEM(mro, i);
1328 if (PyClass_Check(base))
1329 dict = ((PyClassObject *)base)->cl_dict;
1330 else {
1331 assert(PyType_Check(base));
1332 dict = ((PyTypeObject *)base)->tp_dict;
1333 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001334 assert(dict && PyDict_Check(dict));
1335 res = PyDict_GetItem(dict, name);
1336 if (res != NULL)
1337 return res;
1338 }
1339 return NULL;
1340}
1341
1342/* This is similar to PyObject_GenericGetAttr(),
1343 but uses _PyType_Lookup() instead of just looking in type->tp_dict. */
1344static PyObject *
1345type_getattro(PyTypeObject *type, PyObject *name)
1346{
1347 PyTypeObject *metatype = type->ob_type;
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001348 PyObject *meta_attribute, *attribute;
1349 descrgetfunc meta_get;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001350
1351 /* Initialize this type (we'll assume the metatype is initialized) */
1352 if (type->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001353 if (PyType_Ready(type) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001354 return NULL;
1355 }
1356
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001357 /* No readable descriptor found yet */
1358 meta_get = NULL;
1359
1360 /* Look for the attribute in the metatype */
1361 meta_attribute = _PyType_Lookup(metatype, name);
1362
1363 if (meta_attribute != NULL) {
1364 meta_get = meta_attribute->ob_type->tp_descr_get;
1365
1366 if (meta_get != NULL && PyDescr_IsData(meta_attribute)) {
1367 /* Data descriptors implement tp_descr_set to intercept
1368 * writes. Assume the attribute is not overridden in
1369 * type's tp_dict (and bases): call the descriptor now.
1370 */
1371 return meta_get(meta_attribute, (PyObject *)type,
1372 (PyObject *)metatype);
1373 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001374 }
1375
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001376 /* No data descriptor found on metatype. Look in tp_dict of this
1377 * type and its bases */
1378 attribute = _PyType_Lookup(type, name);
1379 if (attribute != NULL) {
1380 /* Implement descriptor functionality, if any */
1381 descrgetfunc local_get = attribute->ob_type->tp_descr_get;
1382 if (local_get != NULL) {
1383 /* NULL 2nd argument indicates the descriptor was
1384 * found on the target object itself (or a base) */
1385 return local_get(attribute, (PyObject *)NULL,
1386 (PyObject *)type);
1387 }
1388
1389 Py_INCREF(attribute);
1390 return attribute;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001391 }
1392
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001393 /* No attribute found in local __dict__ (or bases): use the
1394 * descriptor from the metatype, if any */
1395 if (meta_get != NULL)
1396 return meta_get(meta_attribute, (PyObject *)type,
1397 (PyObject *)metatype);
1398
1399 /* If an ordinary attribute was found on the metatype, return it now */
1400 if (meta_attribute != NULL) {
1401 Py_INCREF(meta_attribute);
1402 return meta_attribute;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001403 }
1404
1405 /* Give up */
1406 PyErr_Format(PyExc_AttributeError,
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001407 "type object '%.50s' has no attribute '%.400s'",
1408 type->tp_name, PyString_AS_STRING(name));
Tim Peters6d6c1a32001-08-02 04:15:00 +00001409 return NULL;
1410}
1411
1412static int
1413type_setattro(PyTypeObject *type, PyObject *name, PyObject *value)
1414{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001415 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
1416 PyErr_Format(
1417 PyExc_TypeError,
1418 "can't set attributes of built-in/extension type '%s'",
1419 type->tp_name);
1420 return -1;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00001421 }
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001422 if (PyObject_GenericSetAttr((PyObject *)type, name, value) < 0)
1423 return -1;
1424 return update_slot(type, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001425}
1426
1427static void
1428type_dealloc(PyTypeObject *type)
1429{
1430 etype *et;
1431
1432 /* Assert this is a heap-allocated type object */
1433 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00001434 _PyObject_GC_UNTRACK(type);
Guido van Rossum1c450732001-10-08 15:18:27 +00001435 PyObject_ClearWeakRefs((PyObject *)type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001436 et = (etype *)type;
1437 Py_XDECREF(type->tp_base);
1438 Py_XDECREF(type->tp_dict);
1439 Py_XDECREF(type->tp_bases);
1440 Py_XDECREF(type->tp_mro);
Guido van Rossum687ae002001-10-15 22:03:32 +00001441 Py_XDECREF(type->tp_cache);
Guido van Rossum1c450732001-10-08 15:18:27 +00001442 Py_XDECREF(type->tp_subclasses);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001443 Py_XDECREF(et->name);
1444 Py_XDECREF(et->slots);
1445 type->ob_type->tp_free((PyObject *)type);
1446}
1447
Guido van Rossum1c450732001-10-08 15:18:27 +00001448static PyObject *
1449type_subclasses(PyTypeObject *type, PyObject *args_ignored)
1450{
1451 PyObject *list, *raw, *ref;
1452 int i, n;
1453
1454 list = PyList_New(0);
1455 if (list == NULL)
1456 return NULL;
1457 raw = type->tp_subclasses;
1458 if (raw == NULL)
1459 return list;
1460 assert(PyList_Check(raw));
1461 n = PyList_GET_SIZE(raw);
1462 for (i = 0; i < n; i++) {
1463 ref = PyList_GET_ITEM(raw, i);
Tim Peters44383382001-10-08 16:49:26 +00001464 assert(PyWeakref_CheckRef(ref));
Guido van Rossum1c450732001-10-08 15:18:27 +00001465 ref = PyWeakref_GET_OBJECT(ref);
1466 if (ref != Py_None) {
1467 if (PyList_Append(list, ref) < 0) {
1468 Py_DECREF(list);
1469 return NULL;
1470 }
1471 }
1472 }
1473 return list;
1474}
1475
Tim Peters6d6c1a32001-08-02 04:15:00 +00001476static PyMethodDef type_methods[] = {
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001477 {"mro", (PyCFunction)mro_external, METH_NOARGS,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001478 "mro() -> list\nreturn a type's method resolution order"},
Guido van Rossum1c450732001-10-08 15:18:27 +00001479 {"__subclasses__", (PyCFunction)type_subclasses, METH_NOARGS,
1480 "__subclasses__() -> list of immediate subclasses"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00001481 {0}
1482};
1483
1484static char type_doc[] =
1485"type(object) -> the object's type\n"
1486"type(name, bases, dict) -> a new type";
1487
Guido van Rossum048eb752001-10-02 21:24:57 +00001488static int
1489type_traverse(PyTypeObject *type, visitproc visit, void *arg)
1490{
Guido van Rossum048eb752001-10-02 21:24:57 +00001491 int err;
1492
Guido van Rossuma3862092002-06-10 15:24:42 +00001493 /* Because of type_is_gc(), the collector only calls this
1494 for heaptypes. */
1495 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00001496
1497#define VISIT(SLOT) \
1498 if (SLOT) { \
1499 err = visit((PyObject *)(SLOT), arg); \
1500 if (err) \
1501 return err; \
1502 }
1503
1504 VISIT(type->tp_dict);
Guido van Rossum687ae002001-10-15 22:03:32 +00001505 VISIT(type->tp_cache);
Guido van Rossum048eb752001-10-02 21:24:57 +00001506 VISIT(type->tp_mro);
1507 VISIT(type->tp_bases);
1508 VISIT(type->tp_base);
Guido van Rossuma3862092002-06-10 15:24:42 +00001509
1510 /* There's no need to visit type->tp_subclasses or
1511 ((etype *)type)->slots, because they can't be involved
1512 in cycles; tp_subclasses is a list of weak references,
1513 and slots is a tuple of strings. */
Guido van Rossum048eb752001-10-02 21:24:57 +00001514
1515#undef VISIT
1516
1517 return 0;
1518}
1519
1520static int
1521type_clear(PyTypeObject *type)
1522{
Guido van Rossum048eb752001-10-02 21:24:57 +00001523 PyObject *tmp;
1524
Guido van Rossuma3862092002-06-10 15:24:42 +00001525 /* Because of type_is_gc(), the collector only calls this
1526 for heaptypes. */
1527 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00001528
1529#define CLEAR(SLOT) \
1530 if (SLOT) { \
1531 tmp = (PyObject *)(SLOT); \
1532 SLOT = NULL; \
1533 Py_DECREF(tmp); \
1534 }
1535
Guido van Rossuma3862092002-06-10 15:24:42 +00001536 /* The only field we need to clear is tp_mro, which is part of a
1537 hard cycle (its first element is the class itself) that won't
1538 be broken otherwise (it's a tuple and tuples don't have a
1539 tp_clear handler). None of the other fields need to be
1540 cleared, and here's why:
Guido van Rossum048eb752001-10-02 21:24:57 +00001541
Guido van Rossuma3862092002-06-10 15:24:42 +00001542 tp_dict:
1543 It is a dict, so the collector will call its tp_clear.
1544
1545 tp_cache:
1546 Not used; if it were, it would be a dict.
1547
1548 tp_bases, tp_base:
1549 If these are involved in a cycle, there must be at least
1550 one other, mutable object in the cycle, e.g. a base
1551 class's dict; the cycle will be broken that way.
1552
1553 tp_subclasses:
1554 A list of weak references can't be part of a cycle; and
1555 lists have their own tp_clear.
1556
1557 slots (in etype):
1558 A tuple of strings can't be part of a cycle.
1559 */
1560
1561 CLEAR(type->tp_mro);
Tim Peters2f93e282001-10-04 05:27:00 +00001562
Guido van Rossum048eb752001-10-02 21:24:57 +00001563#undef CLEAR
1564
1565 return 0;
1566}
1567
1568static int
1569type_is_gc(PyTypeObject *type)
1570{
1571 return type->tp_flags & Py_TPFLAGS_HEAPTYPE;
1572}
1573
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001574PyTypeObject PyType_Type = {
1575 PyObject_HEAD_INIT(&PyType_Type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001576 0, /* ob_size */
1577 "type", /* tp_name */
1578 sizeof(etype), /* tp_basicsize */
Guido van Rossum6f799372001-09-20 20:46:19 +00001579 sizeof(PyMemberDef), /* tp_itemsize */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001580 (destructor)type_dealloc, /* tp_dealloc */
1581 0, /* tp_print */
1582 0, /* tp_getattr */
1583 0, /* tp_setattr */
1584 type_compare, /* tp_compare */
1585 (reprfunc)type_repr, /* tp_repr */
1586 0, /* tp_as_number */
1587 0, /* tp_as_sequence */
1588 0, /* tp_as_mapping */
1589 (hashfunc)_Py_HashPointer, /* tp_hash */
1590 (ternaryfunc)type_call, /* tp_call */
1591 0, /* tp_str */
1592 (getattrofunc)type_getattro, /* tp_getattro */
1593 (setattrofunc)type_setattro, /* tp_setattro */
1594 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00001595 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
1596 Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001597 type_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00001598 (traverseproc)type_traverse, /* tp_traverse */
1599 (inquiry)type_clear, /* tp_clear */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001600 0, /* tp_richcompare */
Guido van Rossum1c450732001-10-08 15:18:27 +00001601 offsetof(PyTypeObject, tp_weaklist), /* tp_weaklistoffset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001602 0, /* tp_iter */
1603 0, /* tp_iternext */
1604 type_methods, /* tp_methods */
1605 type_members, /* tp_members */
1606 type_getsets, /* tp_getset */
1607 0, /* tp_base */
1608 0, /* tp_dict */
1609 0, /* tp_descr_get */
1610 0, /* tp_descr_set */
1611 offsetof(PyTypeObject, tp_dict), /* tp_dictoffset */
1612 0, /* tp_init */
1613 0, /* tp_alloc */
1614 type_new, /* tp_new */
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00001615 PyObject_GC_Del, /* tp_free */
Guido van Rossum048eb752001-10-02 21:24:57 +00001616 (inquiry)type_is_gc, /* tp_is_gc */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001617};
Tim Peters6d6c1a32001-08-02 04:15:00 +00001618
1619
1620/* The base type of all types (eventually)... except itself. */
1621
1622static int
1623object_init(PyObject *self, PyObject *args, PyObject *kwds)
1624{
1625 return 0;
1626}
1627
1628static void
1629object_dealloc(PyObject *self)
1630{
1631 self->ob_type->tp_free(self);
1632}
1633
Guido van Rossum8e248182001-08-12 05:17:56 +00001634static PyObject *
1635object_repr(PyObject *self)
1636{
Guido van Rossum76e69632001-08-16 18:52:43 +00001637 PyTypeObject *type;
Barry Warsaw7ce36942001-08-24 18:34:26 +00001638 PyObject *mod, *name, *rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00001639
Guido van Rossum76e69632001-08-16 18:52:43 +00001640 type = self->ob_type;
1641 mod = type_module(type, NULL);
1642 if (mod == NULL)
1643 PyErr_Clear();
1644 else if (!PyString_Check(mod)) {
1645 Py_DECREF(mod);
1646 mod = NULL;
1647 }
1648 name = type_name(type, NULL);
1649 if (name == NULL)
1650 return NULL;
1651 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__"))
Guido van Rossumff0e6d62001-09-24 16:03:59 +00001652 rtn = PyString_FromFormat("<%s.%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00001653 PyString_AS_STRING(mod),
1654 PyString_AS_STRING(name),
1655 self);
Guido van Rossum76e69632001-08-16 18:52:43 +00001656 else
Guido van Rossumff0e6d62001-09-24 16:03:59 +00001657 rtn = PyString_FromFormat("<%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00001658 type->tp_name, self);
Guido van Rossum76e69632001-08-16 18:52:43 +00001659 Py_XDECREF(mod);
1660 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +00001661 return rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00001662}
1663
Guido van Rossumb8f63662001-08-15 23:57:02 +00001664static PyObject *
1665object_str(PyObject *self)
1666{
1667 unaryfunc f;
1668
1669 f = self->ob_type->tp_repr;
1670 if (f == NULL)
1671 f = object_repr;
1672 return f(self);
1673}
1674
Guido van Rossum8e248182001-08-12 05:17:56 +00001675static long
1676object_hash(PyObject *self)
1677{
1678 return _Py_HashPointer(self);
1679}
Guido van Rossum8e248182001-08-12 05:17:56 +00001680
Guido van Rossum5c294fb2001-09-25 03:43:42 +00001681static PyObject *
1682object_get_class(PyObject *self, void *closure)
1683{
1684 Py_INCREF(self->ob_type);
1685 return (PyObject *)(self->ob_type);
1686}
1687
1688static int
1689equiv_structs(PyTypeObject *a, PyTypeObject *b)
1690{
1691 return a == b ||
1692 (a != NULL &&
1693 b != NULL &&
1694 a->tp_basicsize == b->tp_basicsize &&
1695 a->tp_itemsize == b->tp_itemsize &&
1696 a->tp_dictoffset == b->tp_dictoffset &&
1697 a->tp_weaklistoffset == b->tp_weaklistoffset &&
1698 ((a->tp_flags & Py_TPFLAGS_HAVE_GC) ==
1699 (b->tp_flags & Py_TPFLAGS_HAVE_GC)));
1700}
1701
1702static int
1703same_slots_added(PyTypeObject *a, PyTypeObject *b)
1704{
1705 PyTypeObject *base = a->tp_base;
1706 int size;
1707
1708 if (base != b->tp_base)
1709 return 0;
1710 if (equiv_structs(a, base) && equiv_structs(b, base))
1711 return 1;
1712 size = base->tp_basicsize;
1713 if (a->tp_dictoffset == size && b->tp_dictoffset == size)
1714 size += sizeof(PyObject *);
1715 if (a->tp_weaklistoffset == size && b->tp_weaklistoffset == size)
1716 size += sizeof(PyObject *);
1717 return size == a->tp_basicsize && size == b->tp_basicsize;
1718}
1719
1720static int
1721object_set_class(PyObject *self, PyObject *value, void *closure)
1722{
1723 PyTypeObject *old = self->ob_type;
1724 PyTypeObject *new, *newbase, *oldbase;
1725
Guido van Rossumb6b89422002-04-15 01:03:30 +00001726 if (value == NULL) {
1727 PyErr_SetString(PyExc_TypeError,
1728 "can't delete __class__ attribute");
1729 return -1;
1730 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00001731 if (!PyType_Check(value)) {
1732 PyErr_Format(PyExc_TypeError,
1733 "__class__ must be set to new-style class, not '%s' object",
1734 value->ob_type->tp_name);
1735 return -1;
1736 }
1737 new = (PyTypeObject *)value;
Guido van Rossum9ee4b942002-05-24 18:47:47 +00001738 if (new->tp_dealloc != old->tp_dealloc ||
1739 new->tp_free != old->tp_free)
1740 {
1741 PyErr_Format(PyExc_TypeError,
1742 "__class__ assignment: "
1743 "'%s' deallocator differs from '%s'",
1744 new->tp_name,
1745 old->tp_name);
1746 return -1;
1747 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00001748 newbase = new;
1749 oldbase = old;
1750 while (equiv_structs(newbase, newbase->tp_base))
1751 newbase = newbase->tp_base;
1752 while (equiv_structs(oldbase, oldbase->tp_base))
1753 oldbase = oldbase->tp_base;
1754 if (newbase != oldbase &&
1755 (newbase->tp_base != oldbase->tp_base ||
1756 !same_slots_added(newbase, oldbase))) {
1757 PyErr_Format(PyExc_TypeError,
1758 "__class__ assignment: "
1759 "'%s' object layout differs from '%s'",
Tim Peters2f93e282001-10-04 05:27:00 +00001760 new->tp_name,
Guido van Rossum5c294fb2001-09-25 03:43:42 +00001761 old->tp_name);
1762 return -1;
1763 }
1764 if (new->tp_flags & Py_TPFLAGS_HEAPTYPE) {
1765 Py_INCREF(new);
1766 }
1767 self->ob_type = new;
1768 if (old->tp_flags & Py_TPFLAGS_HEAPTYPE) {
1769 Py_DECREF(old);
1770 }
1771 return 0;
1772}
1773
1774static PyGetSetDef object_getsets[] = {
1775 {"__class__", object_get_class, object_set_class,
1776 "the object's class"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00001777 {0}
1778};
1779
Guido van Rossum3926a632001-09-25 16:25:58 +00001780static PyObject *
1781object_reduce(PyObject *self, PyObject *args)
1782{
1783 /* Call copy_reg._reduce(self) */
1784 static PyObject *copy_reg_str;
1785 PyObject *copy_reg, *res;
1786
1787 if (!copy_reg_str) {
1788 copy_reg_str = PyString_InternFromString("copy_reg");
1789 if (copy_reg_str == NULL)
1790 return NULL;
1791 }
1792 copy_reg = PyImport_Import(copy_reg_str);
1793 if (!copy_reg)
1794 return NULL;
1795 res = PyEval_CallMethod(copy_reg, "_reduce", "(O)", self);
1796 Py_DECREF(copy_reg);
1797 return res;
1798}
1799
1800static PyMethodDef object_methods[] = {
1801 {"__reduce__", object_reduce, METH_NOARGS, "helper for pickle"},
1802 {0}
1803};
1804
Tim Peters6d6c1a32001-08-02 04:15:00 +00001805PyTypeObject PyBaseObject_Type = {
1806 PyObject_HEAD_INIT(&PyType_Type)
1807 0, /* ob_size */
1808 "object", /* tp_name */
1809 sizeof(PyObject), /* tp_basicsize */
1810 0, /* tp_itemsize */
1811 (destructor)object_dealloc, /* tp_dealloc */
1812 0, /* tp_print */
1813 0, /* tp_getattr */
1814 0, /* tp_setattr */
1815 0, /* tp_compare */
Guido van Rossumb8f63662001-08-15 23:57:02 +00001816 object_repr, /* tp_repr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001817 0, /* tp_as_number */
1818 0, /* tp_as_sequence */
1819 0, /* tp_as_mapping */
Guido van Rossumb8f63662001-08-15 23:57:02 +00001820 object_hash, /* tp_hash */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001821 0, /* tp_call */
Guido van Rossumb8f63662001-08-15 23:57:02 +00001822 object_str, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001823 PyObject_GenericGetAttr, /* tp_getattro */
Guido van Rossum13d52f02001-08-10 21:24:08 +00001824 PyObject_GenericSetAttr, /* tp_setattro */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001825 0, /* tp_as_buffer */
1826 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
1827 "The most base type", /* tp_doc */
1828 0, /* tp_traverse */
1829 0, /* tp_clear */
1830 0, /* tp_richcompare */
1831 0, /* tp_weaklistoffset */
1832 0, /* tp_iter */
1833 0, /* tp_iternext */
Guido van Rossum3926a632001-09-25 16:25:58 +00001834 object_methods, /* tp_methods */
Guido van Rossum5c294fb2001-09-25 03:43:42 +00001835 0, /* tp_members */
1836 object_getsets, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001837 0, /* tp_base */
1838 0, /* tp_dict */
1839 0, /* tp_descr_get */
1840 0, /* tp_descr_set */
1841 0, /* tp_dictoffset */
1842 object_init, /* tp_init */
1843 PyType_GenericAlloc, /* tp_alloc */
Guido van Rossumc11e1922001-08-09 19:38:15 +00001844 PyType_GenericNew, /* tp_new */
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00001845 PyObject_Del, /* tp_free */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001846};
1847
1848
1849/* Initialize the __dict__ in a type object */
1850
Fred Drake7bf97152002-03-28 05:33:33 +00001851static PyObject *
1852create_specialmethod(PyMethodDef *meth, PyObject *(*func)(PyObject *))
1853{
1854 PyObject *cfunc;
1855 PyObject *result;
1856
1857 cfunc = PyCFunction_New(meth, NULL);
1858 if (cfunc == NULL)
1859 return NULL;
1860 result = func(cfunc);
1861 Py_DECREF(cfunc);
1862 return result;
1863}
1864
Tim Peters6d6c1a32001-08-02 04:15:00 +00001865static int
1866add_methods(PyTypeObject *type, PyMethodDef *meth)
1867{
Guido van Rossum687ae002001-10-15 22:03:32 +00001868 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001869
1870 for (; meth->ml_name != NULL; meth++) {
1871 PyObject *descr;
1872 if (PyDict_GetItemString(dict, meth->ml_name))
1873 continue;
Fred Drake7bf97152002-03-28 05:33:33 +00001874 if (meth->ml_flags & METH_CLASS) {
1875 if (meth->ml_flags & METH_STATIC) {
1876 PyErr_SetString(PyExc_ValueError,
1877 "method cannot be both class and static");
1878 return -1;
1879 }
1880 descr = create_specialmethod(meth, PyClassMethod_New);
1881 }
1882 else if (meth->ml_flags & METH_STATIC) {
1883 descr = create_specialmethod(meth, PyStaticMethod_New);
1884 }
1885 else {
1886 descr = PyDescr_NewMethod(type, meth);
1887 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001888 if (descr == NULL)
1889 return -1;
Fred Drake7bf97152002-03-28 05:33:33 +00001890 if (PyDict_SetItemString(dict, meth->ml_name, descr) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001891 return -1;
1892 Py_DECREF(descr);
1893 }
1894 return 0;
1895}
1896
1897static int
Guido van Rossum6f799372001-09-20 20:46:19 +00001898add_members(PyTypeObject *type, PyMemberDef *memb)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001899{
Guido van Rossum687ae002001-10-15 22:03:32 +00001900 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001901
1902 for (; memb->name != NULL; memb++) {
1903 PyObject *descr;
1904 if (PyDict_GetItemString(dict, memb->name))
1905 continue;
1906 descr = PyDescr_NewMember(type, memb);
1907 if (descr == NULL)
1908 return -1;
1909 if (PyDict_SetItemString(dict, memb->name, descr) < 0)
1910 return -1;
1911 Py_DECREF(descr);
1912 }
1913 return 0;
1914}
1915
1916static int
Guido van Rossum32d34c82001-09-20 21:45:26 +00001917add_getset(PyTypeObject *type, PyGetSetDef *gsp)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001918{
Guido van Rossum687ae002001-10-15 22:03:32 +00001919 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001920
1921 for (; gsp->name != NULL; gsp++) {
1922 PyObject *descr;
1923 if (PyDict_GetItemString(dict, gsp->name))
1924 continue;
1925 descr = PyDescr_NewGetSet(type, gsp);
1926
1927 if (descr == NULL)
1928 return -1;
1929 if (PyDict_SetItemString(dict, gsp->name, descr) < 0)
1930 return -1;
1931 Py_DECREF(descr);
1932 }
1933 return 0;
1934}
1935
Guido van Rossum13d52f02001-08-10 21:24:08 +00001936static void
1937inherit_special(PyTypeObject *type, PyTypeObject *base)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001938{
1939 int oldsize, newsize;
1940
Guido van Rossum13d52f02001-08-10 21:24:08 +00001941 /* Special flag magic */
1942 if (!type->tp_as_buffer && base->tp_as_buffer) {
1943 type->tp_flags &= ~Py_TPFLAGS_HAVE_GETCHARBUFFER;
1944 type->tp_flags |=
1945 base->tp_flags & Py_TPFLAGS_HAVE_GETCHARBUFFER;
1946 }
1947 if (!type->tp_as_sequence && base->tp_as_sequence) {
1948 type->tp_flags &= ~Py_TPFLAGS_HAVE_SEQUENCE_IN;
1949 type->tp_flags |= base->tp_flags & Py_TPFLAGS_HAVE_SEQUENCE_IN;
1950 }
1951 if ((type->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS) !=
1952 (base->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS)) {
1953 if ((!type->tp_as_number && base->tp_as_number) ||
1954 (!type->tp_as_sequence && base->tp_as_sequence)) {
1955 type->tp_flags &= ~Py_TPFLAGS_HAVE_INPLACEOPS;
1956 if (!type->tp_as_number && !type->tp_as_sequence) {
1957 type->tp_flags |= base->tp_flags &
1958 Py_TPFLAGS_HAVE_INPLACEOPS;
1959 }
1960 }
1961 /* Wow */
1962 }
1963 if (!type->tp_as_number && base->tp_as_number) {
1964 type->tp_flags &= ~Py_TPFLAGS_CHECKTYPES;
1965 type->tp_flags |= base->tp_flags & Py_TPFLAGS_CHECKTYPES;
1966 }
1967
1968 /* Copying basicsize is connected to the GC flags */
Neil Schemenauerc806c882001-08-29 23:54:54 +00001969 oldsize = base->tp_basicsize;
1970 newsize = type->tp_basicsize ? type->tp_basicsize : oldsize;
1971 if (!(type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
1972 (base->tp_flags & Py_TPFLAGS_HAVE_GC) &&
Guido van Rossum13d52f02001-08-10 21:24:08 +00001973 (type->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE/*GC slots exist*/) &&
1974 (!type->tp_traverse && !type->tp_clear)) {
Neil Schemenauerc806c882001-08-29 23:54:54 +00001975 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossum13d52f02001-08-10 21:24:08 +00001976 if (type->tp_traverse == NULL)
1977 type->tp_traverse = base->tp_traverse;
1978 if (type->tp_clear == NULL)
1979 type->tp_clear = base->tp_clear;
1980 }
1981 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
Guido van Rossumf884b742001-12-17 17:14:22 +00001982 /* The condition below could use some explanation.
1983 It appears that tp_new is not inherited for static types
1984 whose base class is 'object'; this seems to be a precaution
1985 so that old extension types don't suddenly become
1986 callable (object.__new__ wouldn't insure the invariants
1987 that the extension type's own factory function ensures).
1988 Heap types, of course, are under our control, so they do
1989 inherit tp_new; static extension types that specify some
1990 other built-in type as the default are considered
1991 new-style-aware so they also inherit object.__new__. */
Guido van Rossum13d52f02001-08-10 21:24:08 +00001992 if (base != &PyBaseObject_Type ||
1993 (type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
1994 if (type->tp_new == NULL)
1995 type->tp_new = base->tp_new;
1996 }
1997 }
Neil Schemenauerc806c882001-08-29 23:54:54 +00001998 type->tp_basicsize = newsize;
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00001999
2000 /* Copy other non-function slots */
2001
2002#undef COPYVAL
2003#define COPYVAL(SLOT) \
2004 if (type->SLOT == 0) type->SLOT = base->SLOT
2005
2006 COPYVAL(tp_itemsize);
2007 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_WEAKREFS) {
2008 COPYVAL(tp_weaklistoffset);
2009 }
2010 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
2011 COPYVAL(tp_dictoffset);
2012 }
Guido van Rossum13d52f02001-08-10 21:24:08 +00002013}
2014
2015static void
2016inherit_slots(PyTypeObject *type, PyTypeObject *base)
2017{
2018 PyTypeObject *basebase;
2019
2020#undef SLOTDEFINED
Tim Peters6d6c1a32001-08-02 04:15:00 +00002021#undef COPYSLOT
2022#undef COPYNUM
2023#undef COPYSEQ
2024#undef COPYMAP
Guido van Rossum5af588b2001-10-12 14:13:21 +00002025#undef COPYBUF
Guido van Rossum13d52f02001-08-10 21:24:08 +00002026
2027#define SLOTDEFINED(SLOT) \
2028 (base->SLOT != 0 && \
2029 (basebase == NULL || base->SLOT != basebase->SLOT))
2030
Tim Peters6d6c1a32001-08-02 04:15:00 +00002031#define COPYSLOT(SLOT) \
Guido van Rossum13d52f02001-08-10 21:24:08 +00002032 if (!type->SLOT && SLOTDEFINED(SLOT)) type->SLOT = base->SLOT
Tim Peters6d6c1a32001-08-02 04:15:00 +00002033
2034#define COPYNUM(SLOT) COPYSLOT(tp_as_number->SLOT)
2035#define COPYSEQ(SLOT) COPYSLOT(tp_as_sequence->SLOT)
2036#define COPYMAP(SLOT) COPYSLOT(tp_as_mapping->SLOT)
Tim Petersfc57ccb2001-10-12 02:38:24 +00002037#define COPYBUF(SLOT) COPYSLOT(tp_as_buffer->SLOT)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002038
Guido van Rossum13d52f02001-08-10 21:24:08 +00002039 /* This won't inherit indirect slots (from tp_as_number etc.)
2040 if type doesn't provide the space. */
2041
2042 if (type->tp_as_number != NULL && base->tp_as_number != NULL) {
2043 basebase = base->tp_base;
2044 if (basebase->tp_as_number == NULL)
2045 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002046 COPYNUM(nb_add);
2047 COPYNUM(nb_subtract);
2048 COPYNUM(nb_multiply);
2049 COPYNUM(nb_divide);
2050 COPYNUM(nb_remainder);
2051 COPYNUM(nb_divmod);
2052 COPYNUM(nb_power);
2053 COPYNUM(nb_negative);
2054 COPYNUM(nb_positive);
2055 COPYNUM(nb_absolute);
2056 COPYNUM(nb_nonzero);
2057 COPYNUM(nb_invert);
2058 COPYNUM(nb_lshift);
2059 COPYNUM(nb_rshift);
2060 COPYNUM(nb_and);
2061 COPYNUM(nb_xor);
2062 COPYNUM(nb_or);
2063 COPYNUM(nb_coerce);
2064 COPYNUM(nb_int);
2065 COPYNUM(nb_long);
2066 COPYNUM(nb_float);
2067 COPYNUM(nb_oct);
2068 COPYNUM(nb_hex);
2069 COPYNUM(nb_inplace_add);
2070 COPYNUM(nb_inplace_subtract);
2071 COPYNUM(nb_inplace_multiply);
2072 COPYNUM(nb_inplace_divide);
2073 COPYNUM(nb_inplace_remainder);
2074 COPYNUM(nb_inplace_power);
2075 COPYNUM(nb_inplace_lshift);
2076 COPYNUM(nb_inplace_rshift);
2077 COPYNUM(nb_inplace_and);
2078 COPYNUM(nb_inplace_xor);
2079 COPYNUM(nb_inplace_or);
Guido van Rossumdc91b992001-08-08 22:26:22 +00002080 if (base->tp_flags & Py_TPFLAGS_CHECKTYPES) {
2081 COPYNUM(nb_true_divide);
2082 COPYNUM(nb_floor_divide);
2083 COPYNUM(nb_inplace_true_divide);
2084 COPYNUM(nb_inplace_floor_divide);
2085 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002086 }
2087
Guido van Rossum13d52f02001-08-10 21:24:08 +00002088 if (type->tp_as_sequence != NULL && base->tp_as_sequence != NULL) {
2089 basebase = base->tp_base;
2090 if (basebase->tp_as_sequence == NULL)
2091 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002092 COPYSEQ(sq_length);
2093 COPYSEQ(sq_concat);
2094 COPYSEQ(sq_repeat);
2095 COPYSEQ(sq_item);
2096 COPYSEQ(sq_slice);
2097 COPYSEQ(sq_ass_item);
2098 COPYSEQ(sq_ass_slice);
2099 COPYSEQ(sq_contains);
2100 COPYSEQ(sq_inplace_concat);
2101 COPYSEQ(sq_inplace_repeat);
2102 }
2103
Guido van Rossum13d52f02001-08-10 21:24:08 +00002104 if (type->tp_as_mapping != NULL && base->tp_as_mapping != NULL) {
2105 basebase = base->tp_base;
2106 if (basebase->tp_as_mapping == NULL)
2107 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002108 COPYMAP(mp_length);
2109 COPYMAP(mp_subscript);
2110 COPYMAP(mp_ass_subscript);
2111 }
2112
Tim Petersfc57ccb2001-10-12 02:38:24 +00002113 if (type->tp_as_buffer != NULL && base->tp_as_buffer != NULL) {
2114 basebase = base->tp_base;
2115 if (basebase->tp_as_buffer == NULL)
2116 basebase = NULL;
2117 COPYBUF(bf_getreadbuffer);
2118 COPYBUF(bf_getwritebuffer);
2119 COPYBUF(bf_getsegcount);
2120 COPYBUF(bf_getcharbuffer);
2121 }
2122
Guido van Rossum13d52f02001-08-10 21:24:08 +00002123 basebase = base->tp_base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002124
Tim Peters6d6c1a32001-08-02 04:15:00 +00002125 COPYSLOT(tp_dealloc);
2126 COPYSLOT(tp_print);
2127 if (type->tp_getattr == NULL && type->tp_getattro == NULL) {
2128 type->tp_getattr = base->tp_getattr;
2129 type->tp_getattro = base->tp_getattro;
2130 }
2131 if (type->tp_setattr == NULL && type->tp_setattro == NULL) {
2132 type->tp_setattr = base->tp_setattr;
2133 type->tp_setattro = base->tp_setattro;
2134 }
2135 /* tp_compare see tp_richcompare */
2136 COPYSLOT(tp_repr);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002137 /* tp_hash see tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002138 COPYSLOT(tp_call);
2139 COPYSLOT(tp_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002140 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00002141 if (type->tp_compare == NULL &&
2142 type->tp_richcompare == NULL &&
2143 type->tp_hash == NULL)
2144 {
Tim Peters6d6c1a32001-08-02 04:15:00 +00002145 type->tp_compare = base->tp_compare;
2146 type->tp_richcompare = base->tp_richcompare;
Guido van Rossumb8f63662001-08-15 23:57:02 +00002147 type->tp_hash = base->tp_hash;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002148 }
2149 }
2150 else {
2151 COPYSLOT(tp_compare);
2152 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002153 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_ITER) {
2154 COPYSLOT(tp_iter);
2155 COPYSLOT(tp_iternext);
2156 }
2157 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
2158 COPYSLOT(tp_descr_get);
2159 COPYSLOT(tp_descr_set);
2160 COPYSLOT(tp_dictoffset);
2161 COPYSLOT(tp_init);
2162 COPYSLOT(tp_alloc);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002163 COPYSLOT(tp_free);
Guido van Rossumcc8fe042002-04-05 17:10:16 +00002164 COPYSLOT(tp_is_gc);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002165 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002166}
2167
Guido van Rossum13d52f02001-08-10 21:24:08 +00002168staticforward int add_operators(PyTypeObject *);
Guido van Rossum1c450732001-10-08 15:18:27 +00002169staticforward int add_subclass(PyTypeObject *base, PyTypeObject *type);
Guido van Rossum13d52f02001-08-10 21:24:08 +00002170
Tim Peters6d6c1a32001-08-02 04:15:00 +00002171int
Guido van Rossum528b7eb2001-08-07 17:24:28 +00002172PyType_Ready(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002173{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002174 PyObject *dict, *bases;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002175 PyTypeObject *base;
2176 int i, n;
2177
Guido van Rossuma3862092002-06-10 15:24:42 +00002178 if (type->tp_flags & Py_TPFLAGS_READY)
Guido van Rossumd614f972001-08-10 17:39:49 +00002179 return 0;
Guido van Rossumd614f972001-08-10 17:39:49 +00002180 assert((type->tp_flags & Py_TPFLAGS_READYING) == 0);
Guido van Rossumd614f972001-08-10 17:39:49 +00002181
2182 type->tp_flags |= Py_TPFLAGS_READYING;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002183
2184 /* Initialize tp_base (defaults to BaseObject unless that's us) */
2185 base = type->tp_base;
2186 if (base == NULL && type != &PyBaseObject_Type)
2187 base = type->tp_base = &PyBaseObject_Type;
2188
Guido van Rossum0986d822002-04-08 01:38:42 +00002189 /* Initialize ob_type if NULL. This means extensions that want to be
2190 compilable separately on Windows can call PyType_Ready() instead of
2191 initializing the ob_type field of their type objects. */
2192 if (type->ob_type == NULL)
2193 type->ob_type = base->ob_type;
2194
Tim Peters6d6c1a32001-08-02 04:15:00 +00002195 /* Initialize tp_bases */
2196 bases = type->tp_bases;
2197 if (bases == NULL) {
2198 if (base == NULL)
2199 bases = PyTuple_New(0);
2200 else
2201 bases = Py_BuildValue("(O)", base);
2202 if (bases == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00002203 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002204 type->tp_bases = bases;
2205 }
2206
2207 /* Initialize the base class */
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002208 if (base && base->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00002209 if (PyType_Ready(base) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00002210 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002211 }
2212
Guido van Rossum687ae002001-10-15 22:03:32 +00002213 /* Initialize tp_dict */
2214 dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002215 if (dict == NULL) {
2216 dict = PyDict_New();
2217 if (dict == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00002218 goto error;
Guido van Rossum687ae002001-10-15 22:03:32 +00002219 type->tp_dict = dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002220 }
2221
Guido van Rossum687ae002001-10-15 22:03:32 +00002222 /* Add type-specific descriptors to tp_dict */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002223 if (add_operators(type) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00002224 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002225 if (type->tp_methods != NULL) {
2226 if (add_methods(type, type->tp_methods) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00002227 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002228 }
2229 if (type->tp_members != NULL) {
2230 if (add_members(type, type->tp_members) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00002231 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002232 }
2233 if (type->tp_getset != NULL) {
2234 if (add_getset(type, type->tp_getset) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00002235 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002236 }
2237
Tim Peters6d6c1a32001-08-02 04:15:00 +00002238 /* Calculate method resolution order */
2239 if (mro_internal(type) < 0) {
Guido van Rossumd614f972001-08-10 17:39:49 +00002240 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002241 }
2242
Guido van Rossum13d52f02001-08-10 21:24:08 +00002243 /* Inherit special flags from dominant base */
2244 if (type->tp_base != NULL)
2245 inherit_special(type, type->tp_base);
2246
Tim Peters6d6c1a32001-08-02 04:15:00 +00002247 /* Initialize tp_dict properly */
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002248 bases = type->tp_mro;
2249 assert(bases != NULL);
2250 assert(PyTuple_Check(bases));
2251 n = PyTuple_GET_SIZE(bases);
2252 for (i = 1; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00002253 PyObject *b = PyTuple_GET_ITEM(bases, i);
2254 if (PyType_Check(b))
2255 inherit_slots(type, (PyTypeObject *)b);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002256 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002257
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00002258 /* if the type dictionary doesn't contain a __doc__, set it from
2259 the tp_doc slot.
2260 */
2261 if (PyDict_GetItemString(type->tp_dict, "__doc__") == NULL) {
2262 if (type->tp_doc != NULL) {
2263 PyObject *doc = PyString_FromString(type->tp_doc);
2264 PyDict_SetItemString(type->tp_dict, "__doc__", doc);
2265 Py_DECREF(doc);
2266 } else {
Guido van Rossumd4641072002-04-03 02:13:37 +00002267 PyDict_SetItemString(type->tp_dict,
2268 "__doc__", Py_None);
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00002269 }
2270 }
2271
Guido van Rossum13d52f02001-08-10 21:24:08 +00002272 /* Some more special stuff */
2273 base = type->tp_base;
2274 if (base != NULL) {
2275 if (type->tp_as_number == NULL)
2276 type->tp_as_number = base->tp_as_number;
2277 if (type->tp_as_sequence == NULL)
2278 type->tp_as_sequence = base->tp_as_sequence;
2279 if (type->tp_as_mapping == NULL)
2280 type->tp_as_mapping = base->tp_as_mapping;
2281 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002282
Guido van Rossum1c450732001-10-08 15:18:27 +00002283 /* Link into each base class's list of subclasses */
2284 bases = type->tp_bases;
2285 n = PyTuple_GET_SIZE(bases);
2286 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00002287 PyObject *b = PyTuple_GET_ITEM(bases, i);
2288 if (PyType_Check(b) &&
2289 add_subclass((PyTypeObject *)b, type) < 0)
Guido van Rossum1c450732001-10-08 15:18:27 +00002290 goto error;
2291 }
2292
Guido van Rossum13d52f02001-08-10 21:24:08 +00002293 /* All done -- set the ready flag */
Guido van Rossumd614f972001-08-10 17:39:49 +00002294 assert(type->tp_dict != NULL);
2295 type->tp_flags =
2296 (type->tp_flags & ~Py_TPFLAGS_READYING) | Py_TPFLAGS_READY;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002297 return 0;
Guido van Rossumd614f972001-08-10 17:39:49 +00002298
2299 error:
2300 type->tp_flags &= ~Py_TPFLAGS_READYING;
2301 return -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002302}
2303
Guido van Rossum1c450732001-10-08 15:18:27 +00002304static int
2305add_subclass(PyTypeObject *base, PyTypeObject *type)
2306{
2307 int i;
2308 PyObject *list, *ref, *new;
2309
2310 list = base->tp_subclasses;
2311 if (list == NULL) {
2312 base->tp_subclasses = list = PyList_New(0);
2313 if (list == NULL)
2314 return -1;
2315 }
2316 assert(PyList_Check(list));
2317 new = PyWeakref_NewRef((PyObject *)type, NULL);
2318 i = PyList_GET_SIZE(list);
2319 while (--i >= 0) {
2320 ref = PyList_GET_ITEM(list, i);
2321 assert(PyWeakref_CheckRef(ref));
2322 if (PyWeakref_GET_OBJECT(ref) == Py_None)
2323 return PyList_SetItem(list, i, new);
2324 }
2325 i = PyList_Append(list, new);
2326 Py_DECREF(new);
2327 return i;
2328}
2329
Tim Peters6d6c1a32001-08-02 04:15:00 +00002330
2331/* Generic wrappers for overloadable 'operators' such as __getitem__ */
2332
2333/* There's a wrapper *function* for each distinct function typedef used
2334 for type object slots (e.g. binaryfunc, ternaryfunc, etc.). There's a
2335 wrapper *table* for each distinct operation (e.g. __len__, __add__).
2336 Most tables have only one entry; the tables for binary operators have two
2337 entries, one regular and one with reversed arguments. */
2338
2339static PyObject *
2340wrap_inquiry(PyObject *self, PyObject *args, void *wrapped)
2341{
2342 inquiry func = (inquiry)wrapped;
2343 int res;
2344
2345 if (!PyArg_ParseTuple(args, ""))
2346 return NULL;
2347 res = (*func)(self);
2348 if (res == -1 && PyErr_Occurred())
2349 return NULL;
2350 return PyInt_FromLong((long)res);
2351}
2352
Tim Peters6d6c1a32001-08-02 04:15:00 +00002353static PyObject *
2354wrap_binaryfunc(PyObject *self, PyObject *args, void *wrapped)
2355{
2356 binaryfunc func = (binaryfunc)wrapped;
2357 PyObject *other;
2358
2359 if (!PyArg_ParseTuple(args, "O", &other))
2360 return NULL;
2361 return (*func)(self, other);
2362}
2363
2364static PyObject *
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002365wrap_binaryfunc_l(PyObject *self, PyObject *args, void *wrapped)
2366{
2367 binaryfunc func = (binaryfunc)wrapped;
2368 PyObject *other;
2369
2370 if (!PyArg_ParseTuple(args, "O", &other))
2371 return NULL;
2372 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002373 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002374 Py_INCREF(Py_NotImplemented);
2375 return Py_NotImplemented;
2376 }
2377 return (*func)(self, other);
2378}
2379
2380static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00002381wrap_binaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
2382{
2383 binaryfunc func = (binaryfunc)wrapped;
2384 PyObject *other;
2385
2386 if (!PyArg_ParseTuple(args, "O", &other))
2387 return NULL;
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002388 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002389 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002390 Py_INCREF(Py_NotImplemented);
2391 return Py_NotImplemented;
2392 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002393 return (*func)(other, self);
2394}
2395
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00002396static PyObject *
2397wrap_coercefunc(PyObject *self, PyObject *args, void *wrapped)
2398{
2399 coercion func = (coercion)wrapped;
2400 PyObject *other, *res;
2401 int ok;
2402
2403 if (!PyArg_ParseTuple(args, "O", &other))
2404 return NULL;
2405 ok = func(&self, &other);
2406 if (ok < 0)
2407 return NULL;
2408 if (ok > 0) {
2409 Py_INCREF(Py_NotImplemented);
2410 return Py_NotImplemented;
2411 }
2412 res = PyTuple_New(2);
2413 if (res == NULL) {
2414 Py_DECREF(self);
2415 Py_DECREF(other);
2416 return NULL;
2417 }
2418 PyTuple_SET_ITEM(res, 0, self);
2419 PyTuple_SET_ITEM(res, 1, other);
2420 return res;
2421}
2422
Tim Peters6d6c1a32001-08-02 04:15:00 +00002423static PyObject *
2424wrap_ternaryfunc(PyObject *self, PyObject *args, void *wrapped)
2425{
2426 ternaryfunc func = (ternaryfunc)wrapped;
2427 PyObject *other;
2428 PyObject *third = Py_None;
2429
2430 /* Note: This wrapper only works for __pow__() */
2431
2432 if (!PyArg_ParseTuple(args, "O|O", &other, &third))
2433 return NULL;
2434 return (*func)(self, other, third);
2435}
2436
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00002437static PyObject *
2438wrap_ternaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
2439{
2440 ternaryfunc func = (ternaryfunc)wrapped;
2441 PyObject *other;
2442 PyObject *third = Py_None;
2443
2444 /* Note: This wrapper only works for __pow__() */
2445
2446 if (!PyArg_ParseTuple(args, "O|O", &other, &third))
2447 return NULL;
2448 return (*func)(other, self, third);
2449}
2450
Tim Peters6d6c1a32001-08-02 04:15:00 +00002451static PyObject *
2452wrap_unaryfunc(PyObject *self, PyObject *args, void *wrapped)
2453{
2454 unaryfunc func = (unaryfunc)wrapped;
2455
2456 if (!PyArg_ParseTuple(args, ""))
2457 return NULL;
2458 return (*func)(self);
2459}
2460
Tim Peters6d6c1a32001-08-02 04:15:00 +00002461static PyObject *
2462wrap_intargfunc(PyObject *self, PyObject *args, void *wrapped)
2463{
2464 intargfunc func = (intargfunc)wrapped;
2465 int i;
2466
2467 if (!PyArg_ParseTuple(args, "i", &i))
2468 return NULL;
2469 return (*func)(self, i);
2470}
2471
Guido van Rossum5d815f32001-08-17 21:57:47 +00002472static int
2473getindex(PyObject *self, PyObject *arg)
2474{
2475 int i;
2476
2477 i = PyInt_AsLong(arg);
2478 if (i == -1 && PyErr_Occurred())
2479 return -1;
2480 if (i < 0) {
2481 PySequenceMethods *sq = self->ob_type->tp_as_sequence;
2482 if (sq && sq->sq_length) {
2483 int n = (*sq->sq_length)(self);
2484 if (n < 0)
2485 return -1;
2486 i += n;
2487 }
2488 }
2489 return i;
2490}
2491
2492static PyObject *
2493wrap_sq_item(PyObject *self, PyObject *args, void *wrapped)
2494{
2495 intargfunc func = (intargfunc)wrapped;
2496 PyObject *arg;
2497 int i;
2498
Guido van Rossumf4593e02001-10-03 12:09:30 +00002499 if (PyTuple_GET_SIZE(args) == 1) {
2500 arg = PyTuple_GET_ITEM(args, 0);
2501 i = getindex(self, arg);
2502 if (i == -1 && PyErr_Occurred())
2503 return NULL;
2504 return (*func)(self, i);
2505 }
2506 PyArg_ParseTuple(args, "O", &arg);
2507 assert(PyErr_Occurred());
2508 return NULL;
Guido van Rossum5d815f32001-08-17 21:57:47 +00002509}
2510
Tim Peters6d6c1a32001-08-02 04:15:00 +00002511static PyObject *
2512wrap_intintargfunc(PyObject *self, PyObject *args, void *wrapped)
2513{
2514 intintargfunc func = (intintargfunc)wrapped;
2515 int i, j;
2516
2517 if (!PyArg_ParseTuple(args, "ii", &i, &j))
2518 return NULL;
2519 return (*func)(self, i, j);
2520}
2521
Tim Peters6d6c1a32001-08-02 04:15:00 +00002522static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00002523wrap_sq_setitem(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002524{
2525 intobjargproc func = (intobjargproc)wrapped;
2526 int i, res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00002527 PyObject *arg, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002528
Guido van Rossum5d815f32001-08-17 21:57:47 +00002529 if (!PyArg_ParseTuple(args, "OO", &arg, &value))
2530 return NULL;
2531 i = getindex(self, arg);
2532 if (i == -1 && PyErr_Occurred())
Tim Peters6d6c1a32001-08-02 04:15:00 +00002533 return NULL;
2534 res = (*func)(self, i, value);
2535 if (res == -1 && PyErr_Occurred())
2536 return NULL;
2537 Py_INCREF(Py_None);
2538 return Py_None;
2539}
2540
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002541static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00002542wrap_sq_delitem(PyObject *self, PyObject *args, void *wrapped)
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002543{
2544 intobjargproc func = (intobjargproc)wrapped;
2545 int i, res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00002546 PyObject *arg;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002547
Guido van Rossum5d815f32001-08-17 21:57:47 +00002548 if (!PyArg_ParseTuple(args, "O", &arg))
2549 return NULL;
2550 i = getindex(self, arg);
2551 if (i == -1 && PyErr_Occurred())
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002552 return NULL;
2553 res = (*func)(self, i, NULL);
2554 if (res == -1 && PyErr_Occurred())
2555 return NULL;
2556 Py_INCREF(Py_None);
2557 return Py_None;
2558}
2559
Tim Peters6d6c1a32001-08-02 04:15:00 +00002560static PyObject *
2561wrap_intintobjargproc(PyObject *self, PyObject *args, void *wrapped)
2562{
2563 intintobjargproc func = (intintobjargproc)wrapped;
2564 int i, j, res;
2565 PyObject *value;
2566
2567 if (!PyArg_ParseTuple(args, "iiO", &i, &j, &value))
2568 return NULL;
2569 res = (*func)(self, i, j, value);
2570 if (res == -1 && PyErr_Occurred())
2571 return NULL;
2572 Py_INCREF(Py_None);
2573 return Py_None;
2574}
2575
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002576static PyObject *
2577wrap_delslice(PyObject *self, PyObject *args, void *wrapped)
2578{
2579 intintobjargproc func = (intintobjargproc)wrapped;
2580 int i, j, res;
2581
2582 if (!PyArg_ParseTuple(args, "ii", &i, &j))
2583 return NULL;
2584 res = (*func)(self, i, j, NULL);
2585 if (res == -1 && PyErr_Occurred())
2586 return NULL;
2587 Py_INCREF(Py_None);
2588 return Py_None;
2589}
2590
Tim Peters6d6c1a32001-08-02 04:15:00 +00002591/* XXX objobjproc is a misnomer; should be objargpred */
2592static PyObject *
2593wrap_objobjproc(PyObject *self, PyObject *args, void *wrapped)
2594{
2595 objobjproc func = (objobjproc)wrapped;
2596 int res;
2597 PyObject *value;
2598
2599 if (!PyArg_ParseTuple(args, "O", &value))
2600 return NULL;
2601 res = (*func)(self, value);
2602 if (res == -1 && PyErr_Occurred())
2603 return NULL;
2604 return PyInt_FromLong((long)res);
2605}
2606
Tim Peters6d6c1a32001-08-02 04:15:00 +00002607static PyObject *
2608wrap_objobjargproc(PyObject *self, PyObject *args, void *wrapped)
2609{
2610 objobjargproc func = (objobjargproc)wrapped;
2611 int res;
2612 PyObject *key, *value;
2613
2614 if (!PyArg_ParseTuple(args, "OO", &key, &value))
2615 return NULL;
2616 res = (*func)(self, key, value);
2617 if (res == -1 && PyErr_Occurred())
2618 return NULL;
2619 Py_INCREF(Py_None);
2620 return Py_None;
2621}
2622
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002623static PyObject *
2624wrap_delitem(PyObject *self, PyObject *args, void *wrapped)
2625{
2626 objobjargproc func = (objobjargproc)wrapped;
2627 int res;
2628 PyObject *key;
2629
2630 if (!PyArg_ParseTuple(args, "O", &key))
2631 return NULL;
2632 res = (*func)(self, key, NULL);
2633 if (res == -1 && PyErr_Occurred())
2634 return NULL;
2635 Py_INCREF(Py_None);
2636 return Py_None;
2637}
2638
Tim Peters6d6c1a32001-08-02 04:15:00 +00002639static PyObject *
2640wrap_cmpfunc(PyObject *self, PyObject *args, void *wrapped)
2641{
2642 cmpfunc func = (cmpfunc)wrapped;
2643 int res;
2644 PyObject *other;
2645
2646 if (!PyArg_ParseTuple(args, "O", &other))
2647 return NULL;
Guido van Rossum3d45d8f2001-09-24 18:47:40 +00002648 if (other->ob_type->tp_compare != func &&
2649 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossumceccae52001-09-18 20:03:57 +00002650 PyErr_Format(
2651 PyExc_TypeError,
2652 "%s.__cmp__(x,y) requires y to be a '%s', not a '%s'",
2653 self->ob_type->tp_name,
2654 self->ob_type->tp_name,
2655 other->ob_type->tp_name);
2656 return NULL;
2657 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002658 res = (*func)(self, other);
2659 if (PyErr_Occurred())
2660 return NULL;
2661 return PyInt_FromLong((long)res);
2662}
2663
Tim Peters6d6c1a32001-08-02 04:15:00 +00002664static PyObject *
2665wrap_setattr(PyObject *self, PyObject *args, void *wrapped)
2666{
2667 setattrofunc func = (setattrofunc)wrapped;
2668 int res;
2669 PyObject *name, *value;
2670
2671 if (!PyArg_ParseTuple(args, "OO", &name, &value))
2672 return NULL;
2673 res = (*func)(self, name, value);
2674 if (res < 0)
2675 return NULL;
2676 Py_INCREF(Py_None);
2677 return Py_None;
2678}
2679
2680static PyObject *
2681wrap_delattr(PyObject *self, PyObject *args, void *wrapped)
2682{
2683 setattrofunc func = (setattrofunc)wrapped;
2684 int res;
2685 PyObject *name;
2686
2687 if (!PyArg_ParseTuple(args, "O", &name))
2688 return NULL;
2689 res = (*func)(self, name, NULL);
2690 if (res < 0)
2691 return NULL;
2692 Py_INCREF(Py_None);
2693 return Py_None;
2694}
2695
Tim Peters6d6c1a32001-08-02 04:15:00 +00002696static PyObject *
2697wrap_hashfunc(PyObject *self, PyObject *args, void *wrapped)
2698{
2699 hashfunc func = (hashfunc)wrapped;
2700 long res;
2701
2702 if (!PyArg_ParseTuple(args, ""))
2703 return NULL;
2704 res = (*func)(self);
2705 if (res == -1 && PyErr_Occurred())
2706 return NULL;
2707 return PyInt_FromLong(res);
2708}
2709
Tim Peters6d6c1a32001-08-02 04:15:00 +00002710static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00002711wrap_call(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002712{
2713 ternaryfunc func = (ternaryfunc)wrapped;
2714
Guido van Rossumc8e56452001-10-22 00:43:43 +00002715 return (*func)(self, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002716}
2717
Tim Peters6d6c1a32001-08-02 04:15:00 +00002718static PyObject *
2719wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op)
2720{
2721 richcmpfunc func = (richcmpfunc)wrapped;
2722 PyObject *other;
2723
2724 if (!PyArg_ParseTuple(args, "O", &other))
2725 return NULL;
2726 return (*func)(self, other, op);
2727}
2728
2729#undef RICHCMP_WRAPPER
2730#define RICHCMP_WRAPPER(NAME, OP) \
2731static PyObject * \
2732richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \
2733{ \
2734 return wrap_richcmpfunc(self, args, wrapped, OP); \
2735}
2736
Jack Jansen8e938b42001-08-08 15:29:49 +00002737RICHCMP_WRAPPER(lt, Py_LT)
2738RICHCMP_WRAPPER(le, Py_LE)
2739RICHCMP_WRAPPER(eq, Py_EQ)
2740RICHCMP_WRAPPER(ne, Py_NE)
2741RICHCMP_WRAPPER(gt, Py_GT)
2742RICHCMP_WRAPPER(ge, Py_GE)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002743
Tim Peters6d6c1a32001-08-02 04:15:00 +00002744static PyObject *
2745wrap_next(PyObject *self, PyObject *args, void *wrapped)
2746{
2747 unaryfunc func = (unaryfunc)wrapped;
2748 PyObject *res;
2749
2750 if (!PyArg_ParseTuple(args, ""))
2751 return NULL;
2752 res = (*func)(self);
2753 if (res == NULL && !PyErr_Occurred())
2754 PyErr_SetNone(PyExc_StopIteration);
2755 return res;
2756}
2757
Tim Peters6d6c1a32001-08-02 04:15:00 +00002758static PyObject *
2759wrap_descr_get(PyObject *self, PyObject *args, void *wrapped)
2760{
2761 descrgetfunc func = (descrgetfunc)wrapped;
2762 PyObject *obj;
2763 PyObject *type = NULL;
2764
2765 if (!PyArg_ParseTuple(args, "O|O", &obj, &type))
2766 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002767 return (*func)(self, obj, type);
2768}
2769
Tim Peters6d6c1a32001-08-02 04:15:00 +00002770static PyObject *
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002771wrap_descr_set(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002772{
2773 descrsetfunc func = (descrsetfunc)wrapped;
2774 PyObject *obj, *value;
2775 int ret;
2776
2777 if (!PyArg_ParseTuple(args, "OO", &obj, &value))
2778 return NULL;
2779 ret = (*func)(self, obj, value);
2780 if (ret < 0)
2781 return NULL;
2782 Py_INCREF(Py_None);
2783 return Py_None;
2784}
2785
Tim Peters6d6c1a32001-08-02 04:15:00 +00002786static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00002787wrap_init(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002788{
2789 initproc func = (initproc)wrapped;
2790
Guido van Rossumc8e56452001-10-22 00:43:43 +00002791 if (func(self, args, kwds) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002792 return NULL;
2793 Py_INCREF(Py_None);
2794 return Py_None;
2795}
2796
Tim Peters6d6c1a32001-08-02 04:15:00 +00002797static PyObject *
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002798tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002799{
Barry Warsaw60f01882001-08-22 19:24:42 +00002800 PyTypeObject *type, *subtype, *staticbase;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002801 PyObject *arg0, *res;
2802
2803 if (self == NULL || !PyType_Check(self))
2804 Py_FatalError("__new__() called with non-type 'self'");
2805 type = (PyTypeObject *)self;
2806 if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002807 PyErr_Format(PyExc_TypeError,
2808 "%s.__new__(): not enough arguments",
2809 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002810 return NULL;
2811 }
2812 arg0 = PyTuple_GET_ITEM(args, 0);
2813 if (!PyType_Check(arg0)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002814 PyErr_Format(PyExc_TypeError,
2815 "%s.__new__(X): X is not a type object (%s)",
2816 type->tp_name,
2817 arg0->ob_type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002818 return NULL;
2819 }
2820 subtype = (PyTypeObject *)arg0;
2821 if (!PyType_IsSubtype(subtype, type)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002822 PyErr_Format(PyExc_TypeError,
2823 "%s.__new__(%s): %s is not a subtype of %s",
2824 type->tp_name,
2825 subtype->tp_name,
2826 subtype->tp_name,
2827 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002828 return NULL;
2829 }
Barry Warsaw60f01882001-08-22 19:24:42 +00002830
2831 /* Check that the use doesn't do something silly and unsafe like
Tim Petersa427a2b2001-10-29 22:25:45 +00002832 object.__new__(dict). To do this, we check that the
Barry Warsaw60f01882001-08-22 19:24:42 +00002833 most derived base that's not a heap type is this type. */
2834 staticbase = subtype;
2835 while (staticbase && (staticbase->tp_flags & Py_TPFLAGS_HEAPTYPE))
2836 staticbase = staticbase->tp_base;
Guido van Rossuma8c60f42001-09-14 19:43:36 +00002837 if (staticbase->tp_new != type->tp_new) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002838 PyErr_Format(PyExc_TypeError,
2839 "%s.__new__(%s) is not safe, use %s.__new__()",
2840 type->tp_name,
2841 subtype->tp_name,
2842 staticbase == NULL ? "?" : staticbase->tp_name);
2843 return NULL;
2844 }
2845
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002846 args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
2847 if (args == NULL)
2848 return NULL;
2849 res = type->tp_new(subtype, args, kwds);
2850 Py_DECREF(args);
2851 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002852}
2853
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002854static struct PyMethodDef tp_new_methoddef[] = {
2855 {"__new__", (PyCFunction)tp_new_wrapper, METH_KEYWORDS,
2856 "T.__new__(S, ...) -> a new object with type S, a subtype of T"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002857 {0}
2858};
2859
2860static int
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002861add_tp_new_wrapper(PyTypeObject *type)
2862{
Guido van Rossumf040ede2001-08-07 16:40:56 +00002863 PyObject *func;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002864
Guido van Rossum687ae002001-10-15 22:03:32 +00002865 if (PyDict_GetItemString(type->tp_dict, "__new__") != NULL)
Guido van Rossumf040ede2001-08-07 16:40:56 +00002866 return 0;
2867 func = PyCFunction_New(tp_new_methoddef, (PyObject *)type);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002868 if (func == NULL)
2869 return -1;
Guido van Rossum687ae002001-10-15 22:03:32 +00002870 return PyDict_SetItemString(type->tp_dict, "__new__", func);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002871}
2872
Guido van Rossumf040ede2001-08-07 16:40:56 +00002873/* Slot wrappers that call the corresponding __foo__ slot. See comments
2874 below at override_slots() for more explanation. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002875
Guido van Rossumdc91b992001-08-08 22:26:22 +00002876#define SLOT0(FUNCNAME, OPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002877static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002878FUNCNAME(PyObject *self) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002879{ \
Guido van Rossum5592e4d2001-08-28 18:28:21 +00002880 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00002881 return call_method(self, OPSTR, &cache_str, "()"); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002882}
2883
Guido van Rossumdc91b992001-08-08 22:26:22 +00002884#define SLOT1(FUNCNAME, OPSTR, ARG1TYPE, ARGCODES) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002885static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002886FUNCNAME(PyObject *self, ARG1TYPE arg1) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002887{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00002888 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00002889 return call_method(self, OPSTR, &cache_str, "(" ARGCODES ")", arg1); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002890}
2891
Guido van Rossumdc91b992001-08-08 22:26:22 +00002892
2893#define SLOT1BINFULL(FUNCNAME, TESTFUNC, SLOTNAME, OPSTR, ROPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002894static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002895FUNCNAME(PyObject *self, PyObject *other) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002896{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00002897 static PyObject *cache_str, *rcache_str; \
Guido van Rossum55f20992001-10-01 17:18:22 +00002898 int do_other = self->ob_type != other->ob_type && \
2899 other->ob_type->tp_as_number != NULL && \
2900 other->ob_type->tp_as_number->SLOTNAME == TESTFUNC; \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002901 if (self->ob_type->tp_as_number != NULL && \
2902 self->ob_type->tp_as_number->SLOTNAME == TESTFUNC) { \
2903 PyObject *r; \
Guido van Rossum55f20992001-10-01 17:18:22 +00002904 if (do_other && \
2905 PyType_IsSubtype(other->ob_type, self->ob_type)) { \
2906 r = call_maybe( \
2907 other, ROPSTR, &rcache_str, "(O)", self); \
2908 if (r != Py_NotImplemented) \
2909 return r; \
2910 Py_DECREF(r); \
2911 do_other = 0; \
2912 } \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00002913 r = call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00002914 self, OPSTR, &cache_str, "(O)", other); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002915 if (r != Py_NotImplemented || \
2916 other->ob_type == self->ob_type) \
2917 return r; \
2918 Py_DECREF(r); \
2919 } \
Guido van Rossum55f20992001-10-01 17:18:22 +00002920 if (do_other) { \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00002921 return call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00002922 other, ROPSTR, &rcache_str, "(O)", self); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002923 } \
2924 Py_INCREF(Py_NotImplemented); \
2925 return Py_NotImplemented; \
2926}
2927
2928#define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) \
2929 SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR)
2930
2931#define SLOT2(FUNCNAME, OPSTR, ARG1TYPE, ARG2TYPE, ARGCODES) \
2932static PyObject * \
2933FUNCNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \
2934{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00002935 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00002936 return call_method(self, OPSTR, &cache_str, \
2937 "(" ARGCODES ")", arg1, arg2); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002938}
2939
2940static int
2941slot_sq_length(PyObject *self)
2942{
Guido van Rossum2730b132001-08-28 18:22:14 +00002943 static PyObject *len_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00002944 PyObject *res = call_method(self, "__len__", &len_str, "()");
Guido van Rossum26111622001-10-01 16:42:49 +00002945 int len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002946
2947 if (res == NULL)
2948 return -1;
Guido van Rossum26111622001-10-01 16:42:49 +00002949 len = (int)PyInt_AsLong(res);
2950 Py_DECREF(res);
2951 return len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002952}
2953
Guido van Rossumdc91b992001-08-08 22:26:22 +00002954SLOT1(slot_sq_concat, "__add__", PyObject *, "O")
2955SLOT1(slot_sq_repeat, "__mul__", int, "i")
Guido van Rossumf4593e02001-10-03 12:09:30 +00002956
2957/* Super-optimized version of slot_sq_item.
2958 Other slots could do the same... */
2959static PyObject *
2960slot_sq_item(PyObject *self, int i)
2961{
2962 static PyObject *getitem_str;
2963 PyObject *func, *args = NULL, *ival = NULL, *retval = NULL;
2964 descrgetfunc f;
2965
2966 if (getitem_str == NULL) {
2967 getitem_str = PyString_InternFromString("__getitem__");
2968 if (getitem_str == NULL)
2969 return NULL;
2970 }
2971 func = _PyType_Lookup(self->ob_type, getitem_str);
2972 if (func != NULL) {
Guido van Rossumf4593e02001-10-03 12:09:30 +00002973 if ((f = func->ob_type->tp_descr_get) == NULL)
2974 Py_INCREF(func);
2975 else
2976 func = f(func, self, (PyObject *)(self->ob_type));
2977 ival = PyInt_FromLong(i);
2978 if (ival != NULL) {
2979 args = PyTuple_New(1);
2980 if (args != NULL) {
2981 PyTuple_SET_ITEM(args, 0, ival);
2982 retval = PyObject_Call(func, args, NULL);
2983 Py_XDECREF(args);
2984 Py_XDECREF(func);
2985 return retval;
2986 }
2987 }
2988 }
2989 else {
2990 PyErr_SetObject(PyExc_AttributeError, getitem_str);
2991 }
2992 Py_XDECREF(args);
2993 Py_XDECREF(ival);
2994 Py_XDECREF(func);
2995 return NULL;
2996}
2997
Guido van Rossumdc91b992001-08-08 22:26:22 +00002998SLOT2(slot_sq_slice, "__getslice__", int, int, "ii")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002999
3000static int
3001slot_sq_ass_item(PyObject *self, int index, PyObject *value)
3002{
3003 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003004 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003005
3006 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003007 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003008 "(i)", index);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003009 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003010 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003011 "(iO)", index, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003012 if (res == NULL)
3013 return -1;
3014 Py_DECREF(res);
3015 return 0;
3016}
3017
3018static int
3019slot_sq_ass_slice(PyObject *self, int i, int j, PyObject *value)
3020{
3021 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003022 static PyObject *delslice_str, *setslice_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003023
3024 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003025 res = call_method(self, "__delslice__", &delslice_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003026 "(ii)", i, j);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003027 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003028 res = call_method(self, "__setslice__", &setslice_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003029 "(iiO)", i, j, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003030 if (res == NULL)
3031 return -1;
3032 Py_DECREF(res);
3033 return 0;
3034}
3035
3036static int
3037slot_sq_contains(PyObject *self, PyObject *value)
3038{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003039 PyObject *func, *res, *args;
Guido van Rossum60718732001-08-28 17:47:51 +00003040 static PyObject *contains_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003041
Guido van Rossum55f20992001-10-01 17:18:22 +00003042 func = lookup_maybe(self, "__contains__", &contains_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003043
3044 if (func != NULL) {
3045 args = Py_BuildValue("(O)", value);
3046 if (args == NULL)
3047 res = NULL;
3048 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00003049 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003050 Py_DECREF(args);
3051 }
3052 Py_DECREF(func);
3053 if (res == NULL)
3054 return -1;
3055 return PyObject_IsTrue(res);
3056 }
Guido van Rossum55f20992001-10-01 17:18:22 +00003057 else if (PyErr_Occurred())
3058 return -1;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003059 else {
Tim Peters16a77ad2001-09-08 04:00:12 +00003060 return _PySequence_IterSearch(self, value,
3061 PY_ITERSEARCH_CONTAINS);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003062 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003063}
3064
Guido van Rossumdc91b992001-08-08 22:26:22 +00003065SLOT1(slot_sq_inplace_concat, "__iadd__", PyObject *, "O")
3066SLOT1(slot_sq_inplace_repeat, "__imul__", int, "i")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003067
3068#define slot_mp_length slot_sq_length
3069
Guido van Rossumdc91b992001-08-08 22:26:22 +00003070SLOT1(slot_mp_subscript, "__getitem__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003071
3072static int
3073slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value)
3074{
3075 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003076 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003077
3078 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003079 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003080 "(O)", key);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003081 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003082 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003083 "(OO)", key, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003084 if (res == NULL)
3085 return -1;
3086 Py_DECREF(res);
3087 return 0;
3088}
3089
Guido van Rossumdc91b992001-08-08 22:26:22 +00003090SLOT1BIN(slot_nb_add, nb_add, "__add__", "__radd__")
3091SLOT1BIN(slot_nb_subtract, nb_subtract, "__sub__", "__rsub__")
3092SLOT1BIN(slot_nb_multiply, nb_multiply, "__mul__", "__rmul__")
3093SLOT1BIN(slot_nb_divide, nb_divide, "__div__", "__rdiv__")
3094SLOT1BIN(slot_nb_remainder, nb_remainder, "__mod__", "__rmod__")
3095SLOT1BIN(slot_nb_divmod, nb_divmod, "__divmod__", "__rdivmod__")
3096
3097staticforward PyObject *slot_nb_power(PyObject *, PyObject *, PyObject *);
3098
3099SLOT1BINFULL(slot_nb_power_binary, slot_nb_power,
3100 nb_power, "__pow__", "__rpow__")
3101
3102static PyObject *
3103slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus)
3104{
Guido van Rossum2730b132001-08-28 18:22:14 +00003105 static PyObject *pow_str;
3106
Guido van Rossumdc91b992001-08-08 22:26:22 +00003107 if (modulus == Py_None)
3108 return slot_nb_power_binary(self, other);
Guido van Rossum23094982002-06-10 14:30:43 +00003109 /* Three-arg power doesn't use __rpow__. But ternary_op
3110 can call this when the second argument's type uses
3111 slot_nb_power, so check before calling self.__pow__. */
3112 if (self->ob_type->tp_as_number != NULL &&
3113 self->ob_type->tp_as_number->nb_power == slot_nb_power) {
3114 return call_method(self, "__pow__", &pow_str,
3115 "(OO)", other, modulus);
3116 }
3117 Py_INCREF(Py_NotImplemented);
3118 return Py_NotImplemented;
Guido van Rossumdc91b992001-08-08 22:26:22 +00003119}
3120
3121SLOT0(slot_nb_negative, "__neg__")
3122SLOT0(slot_nb_positive, "__pos__")
3123SLOT0(slot_nb_absolute, "__abs__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003124
3125static int
3126slot_nb_nonzero(PyObject *self)
3127{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003128 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003129 static PyObject *nonzero_str, *len_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003130
Guido van Rossum55f20992001-10-01 17:18:22 +00003131 func = lookup_maybe(self, "__nonzero__", &nonzero_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003132 if (func == NULL) {
Guido van Rossum55f20992001-10-01 17:18:22 +00003133 if (PyErr_Occurred())
Guido van Rossumb8f63662001-08-15 23:57:02 +00003134 return -1;
Guido van Rossum55f20992001-10-01 17:18:22 +00003135 func = lookup_maybe(self, "__len__", &len_str);
3136 if (func == NULL) {
3137 if (PyErr_Occurred())
3138 return -1;
3139 else
3140 return 1;
3141 }
Guido van Rossumb8f63662001-08-15 23:57:02 +00003142 }
Guido van Rossum55f20992001-10-01 17:18:22 +00003143 res = PyObject_CallObject(func, NULL);
3144 Py_DECREF(func);
3145 if (res == NULL)
3146 return -1;
3147 return PyObject_IsTrue(res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003148}
3149
Guido van Rossumdc91b992001-08-08 22:26:22 +00003150SLOT0(slot_nb_invert, "__invert__")
3151SLOT1BIN(slot_nb_lshift, nb_lshift, "__lshift__", "__rlshift__")
3152SLOT1BIN(slot_nb_rshift, nb_rshift, "__rshift__", "__rrshift__")
3153SLOT1BIN(slot_nb_and, nb_and, "__and__", "__rand__")
3154SLOT1BIN(slot_nb_xor, nb_xor, "__xor__", "__rxor__")
3155SLOT1BIN(slot_nb_or, nb_or, "__or__", "__ror__")
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003156
3157static int
3158slot_nb_coerce(PyObject **a, PyObject **b)
3159{
3160 static PyObject *coerce_str;
3161 PyObject *self = *a, *other = *b;
3162
3163 if (self->ob_type->tp_as_number != NULL &&
3164 self->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
3165 PyObject *r;
3166 r = call_maybe(
3167 self, "__coerce__", &coerce_str, "(O)", other);
3168 if (r == NULL)
3169 return -1;
3170 if (r == Py_NotImplemented) {
3171 Py_DECREF(r);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003172 }
Guido van Rossum55f20992001-10-01 17:18:22 +00003173 else {
3174 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
3175 PyErr_SetString(PyExc_TypeError,
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003176 "__coerce__ didn't return a 2-tuple");
Guido van Rossum55f20992001-10-01 17:18:22 +00003177 Py_DECREF(r);
3178 return -1;
3179 }
3180 *a = PyTuple_GET_ITEM(r, 0);
3181 Py_INCREF(*a);
3182 *b = PyTuple_GET_ITEM(r, 1);
3183 Py_INCREF(*b);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003184 Py_DECREF(r);
Guido van Rossum55f20992001-10-01 17:18:22 +00003185 return 0;
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003186 }
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003187 }
3188 if (other->ob_type->tp_as_number != NULL &&
3189 other->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
3190 PyObject *r;
3191 r = call_maybe(
3192 other, "__coerce__", &coerce_str, "(O)", self);
3193 if (r == NULL)
3194 return -1;
3195 if (r == Py_NotImplemented) {
3196 Py_DECREF(r);
3197 return 1;
3198 }
3199 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
3200 PyErr_SetString(PyExc_TypeError,
3201 "__coerce__ didn't return a 2-tuple");
3202 Py_DECREF(r);
3203 return -1;
3204 }
3205 *a = PyTuple_GET_ITEM(r, 1);
3206 Py_INCREF(*a);
3207 *b = PyTuple_GET_ITEM(r, 0);
3208 Py_INCREF(*b);
3209 Py_DECREF(r);
3210 return 0;
3211 }
3212 return 1;
3213}
3214
Guido van Rossumdc91b992001-08-08 22:26:22 +00003215SLOT0(slot_nb_int, "__int__")
3216SLOT0(slot_nb_long, "__long__")
3217SLOT0(slot_nb_float, "__float__")
3218SLOT0(slot_nb_oct, "__oct__")
3219SLOT0(slot_nb_hex, "__hex__")
3220SLOT1(slot_nb_inplace_add, "__iadd__", PyObject *, "O")
3221SLOT1(slot_nb_inplace_subtract, "__isub__", PyObject *, "O")
3222SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *, "O")
3223SLOT1(slot_nb_inplace_divide, "__idiv__", PyObject *, "O")
3224SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *, "O")
3225SLOT2(slot_nb_inplace_power, "__ipow__", PyObject *, PyObject *, "OO")
3226SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *, "O")
3227SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *, "O")
3228SLOT1(slot_nb_inplace_and, "__iand__", PyObject *, "O")
3229SLOT1(slot_nb_inplace_xor, "__ixor__", PyObject *, "O")
3230SLOT1(slot_nb_inplace_or, "__ior__", PyObject *, "O")
3231SLOT1BIN(slot_nb_floor_divide, nb_floor_divide,
3232 "__floordiv__", "__rfloordiv__")
3233SLOT1BIN(slot_nb_true_divide, nb_true_divide, "__truediv__", "__rtruediv__")
3234SLOT1(slot_nb_inplace_floor_divide, "__ifloordiv__", PyObject *, "O")
3235SLOT1(slot_nb_inplace_true_divide, "__itruediv__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003236
3237static int
Guido van Rossumb8f63662001-08-15 23:57:02 +00003238half_compare(PyObject *self, PyObject *other)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003239{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003240 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003241 static PyObject *cmp_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003242 int c;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003243
Guido van Rossum60718732001-08-28 17:47:51 +00003244 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003245 if (func == NULL) {
3246 PyErr_Clear();
3247 }
3248 else {
3249 args = Py_BuildValue("(O)", other);
3250 if (args == NULL)
3251 res = NULL;
3252 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00003253 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003254 Py_DECREF(args);
3255 }
3256 if (res != Py_NotImplemented) {
3257 if (res == NULL)
3258 return -2;
3259 c = PyInt_AsLong(res);
3260 Py_DECREF(res);
3261 if (c == -1 && PyErr_Occurred())
3262 return -2;
3263 return (c < 0) ? -1 : (c > 0) ? 1 : 0;
3264 }
3265 Py_DECREF(res);
3266 }
3267 return 2;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003268}
3269
Guido van Rossumab3b0342001-09-18 20:38:53 +00003270/* This slot is published for the benefit of try_3way_compare in object.c */
3271int
3272_PyObject_SlotCompare(PyObject *self, PyObject *other)
Guido van Rossumb8f63662001-08-15 23:57:02 +00003273{
3274 int c;
3275
Guido van Rossumab3b0342001-09-18 20:38:53 +00003276 if (self->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00003277 c = half_compare(self, other);
3278 if (c <= 1)
3279 return c;
3280 }
Guido van Rossumab3b0342001-09-18 20:38:53 +00003281 if (other->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00003282 c = half_compare(other, self);
3283 if (c < -1)
3284 return -2;
3285 if (c <= 1)
3286 return -c;
3287 }
3288 return (void *)self < (void *)other ? -1 :
3289 (void *)self > (void *)other ? 1 : 0;
3290}
3291
3292static PyObject *
3293slot_tp_repr(PyObject *self)
3294{
3295 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003296 static PyObject *repr_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003297
Guido van Rossum60718732001-08-28 17:47:51 +00003298 func = lookup_method(self, "__repr__", &repr_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003299 if (func != NULL) {
3300 res = PyEval_CallObject(func, NULL);
3301 Py_DECREF(func);
3302 return res;
3303 }
Barry Warsaw7ce36942001-08-24 18:34:26 +00003304 PyErr_Clear();
3305 return PyString_FromFormat("<%s object at %p>",
3306 self->ob_type->tp_name, self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003307}
3308
3309static PyObject *
3310slot_tp_str(PyObject *self)
3311{
3312 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003313 static PyObject *str_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003314
Guido van Rossum60718732001-08-28 17:47:51 +00003315 func = lookup_method(self, "__str__", &str_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003316 if (func != NULL) {
3317 res = PyEval_CallObject(func, NULL);
3318 Py_DECREF(func);
3319 return res;
3320 }
3321 else {
3322 PyErr_Clear();
3323 return slot_tp_repr(self);
3324 }
3325}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003326
3327static long
3328slot_tp_hash(PyObject *self)
3329{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003330 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003331 static PyObject *hash_str, *eq_str, *cmp_str;
3332
Tim Peters6d6c1a32001-08-02 04:15:00 +00003333 long h;
3334
Guido van Rossum60718732001-08-28 17:47:51 +00003335 func = lookup_method(self, "__hash__", &hash_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003336
3337 if (func != NULL) {
3338 res = PyEval_CallObject(func, NULL);
3339 Py_DECREF(func);
3340 if (res == NULL)
3341 return -1;
3342 h = PyInt_AsLong(res);
3343 }
3344 else {
3345 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00003346 func = lookup_method(self, "__eq__", &eq_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003347 if (func == NULL) {
3348 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00003349 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003350 }
3351 if (func != NULL) {
3352 Py_DECREF(func);
3353 PyErr_SetString(PyExc_TypeError, "unhashable type");
3354 return -1;
3355 }
3356 PyErr_Clear();
3357 h = _Py_HashPointer((void *)self);
3358 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003359 if (h == -1 && !PyErr_Occurred())
3360 h = -2;
3361 return h;
3362}
3363
3364static PyObject *
3365slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds)
3366{
Guido van Rossum60718732001-08-28 17:47:51 +00003367 static PyObject *call_str;
3368 PyObject *meth = lookup_method(self, "__call__", &call_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003369 PyObject *res;
3370
3371 if (meth == NULL)
3372 return NULL;
3373 res = PyObject_Call(meth, args, kwds);
3374 Py_DECREF(meth);
3375 return res;
3376}
3377
Guido van Rossum14a6f832001-10-17 13:59:09 +00003378/* There are two slot dispatch functions for tp_getattro.
3379
3380 - slot_tp_getattro() is used when __getattribute__ is overridden
3381 but no __getattr__ hook is present;
3382
3383 - slot_tp_getattr_hook() is used when a __getattr__ hook is present.
3384
Guido van Rossumc334df52002-04-04 23:44:47 +00003385 The code in update_one_slot() always installs slot_tp_getattr_hook(); this
3386 detects the absence of __getattr__ and then installs the simpler slot if
3387 necessary. */
Guido van Rossum14a6f832001-10-17 13:59:09 +00003388
Tim Peters6d6c1a32001-08-02 04:15:00 +00003389static PyObject *
3390slot_tp_getattro(PyObject *self, PyObject *name)
3391{
Guido van Rossum14a6f832001-10-17 13:59:09 +00003392 static PyObject *getattribute_str = NULL;
3393 return call_method(self, "__getattribute__", &getattribute_str,
3394 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003395}
3396
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003397static PyObject *
3398slot_tp_getattr_hook(PyObject *self, PyObject *name)
3399{
3400 PyTypeObject *tp = self->ob_type;
3401 PyObject *getattr, *getattribute, *res;
3402 static PyObject *getattribute_str = NULL;
3403 static PyObject *getattr_str = NULL;
3404
3405 if (getattr_str == NULL) {
3406 getattr_str = PyString_InternFromString("__getattr__");
3407 if (getattr_str == NULL)
3408 return NULL;
3409 }
3410 if (getattribute_str == NULL) {
3411 getattribute_str =
3412 PyString_InternFromString("__getattribute__");
3413 if (getattribute_str == NULL)
3414 return NULL;
3415 }
3416 getattr = _PyType_Lookup(tp, getattr_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00003417 if (getattr == NULL) {
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003418 /* No __getattr__ hook: use a simpler dispatcher */
3419 tp->tp_getattro = slot_tp_getattro;
3420 return slot_tp_getattro(self, name);
3421 }
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003422 getattribute = _PyType_Lookup(tp, getattribute_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00003423 if (getattribute == NULL ||
3424 (getattribute->ob_type == &PyWrapperDescr_Type &&
3425 ((PyWrapperDescrObject *)getattribute)->d_wrapped ==
3426 (void *)PyObject_GenericGetAttr))
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003427 res = PyObject_GenericGetAttr(self, name);
3428 else
3429 res = PyObject_CallFunction(getattribute, "OO", self, name);
Guido van Rossum14a6f832001-10-17 13:59:09 +00003430 if (res == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) {
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003431 PyErr_Clear();
3432 res = PyObject_CallFunction(getattr, "OO", self, name);
3433 }
3434 return res;
3435}
3436
Tim Peters6d6c1a32001-08-02 04:15:00 +00003437static int
3438slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value)
3439{
3440 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003441 static PyObject *delattr_str, *setattr_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003442
3443 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003444 res = call_method(self, "__delattr__", &delattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003445 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003446 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003447 res = call_method(self, "__setattr__", &setattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003448 "(OO)", name, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003449 if (res == NULL)
3450 return -1;
3451 Py_DECREF(res);
3452 return 0;
3453}
3454
3455/* Map rich comparison operators to their __xx__ namesakes */
3456static char *name_op[] = {
3457 "__lt__",
3458 "__le__",
3459 "__eq__",
3460 "__ne__",
3461 "__gt__",
3462 "__ge__",
3463};
3464
3465static PyObject *
Guido van Rossumb8f63662001-08-15 23:57:02 +00003466half_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003467{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003468 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003469 static PyObject *op_str[6];
Tim Peters6d6c1a32001-08-02 04:15:00 +00003470
Guido van Rossum60718732001-08-28 17:47:51 +00003471 func = lookup_method(self, name_op[op], &op_str[op]);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003472 if (func == NULL) {
3473 PyErr_Clear();
3474 Py_INCREF(Py_NotImplemented);
3475 return Py_NotImplemented;
3476 }
3477 args = Py_BuildValue("(O)", other);
3478 if (args == NULL)
3479 res = NULL;
3480 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00003481 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003482 Py_DECREF(args);
3483 }
3484 Py_DECREF(func);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003485 return res;
3486}
3487
Guido van Rossumb8f63662001-08-15 23:57:02 +00003488/* Map rich comparison operators to their swapped version, e.g. LT --> GT */
3489static int swapped_op[] = {Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE};
3490
3491static PyObject *
3492slot_tp_richcompare(PyObject *self, PyObject *other, int op)
3493{
3494 PyObject *res;
3495
3496 if (self->ob_type->tp_richcompare == slot_tp_richcompare) {
3497 res = half_richcompare(self, other, op);
3498 if (res != Py_NotImplemented)
3499 return res;
3500 Py_DECREF(res);
3501 }
3502 if (other->ob_type->tp_richcompare == slot_tp_richcompare) {
3503 res = half_richcompare(other, self, swapped_op[op]);
3504 if (res != Py_NotImplemented) {
3505 return res;
3506 }
3507 Py_DECREF(res);
3508 }
3509 Py_INCREF(Py_NotImplemented);
3510 return Py_NotImplemented;
3511}
3512
3513static PyObject *
3514slot_tp_iter(PyObject *self)
3515{
3516 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003517 static PyObject *iter_str, *getitem_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003518
Guido van Rossum60718732001-08-28 17:47:51 +00003519 func = lookup_method(self, "__iter__", &iter_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003520 if (func != NULL) {
3521 res = PyObject_CallObject(func, NULL);
3522 Py_DECREF(func);
3523 return res;
3524 }
3525 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00003526 func = lookup_method(self, "__getitem__", &getitem_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003527 if (func == NULL) {
Guido van Rossumd4641072002-04-03 02:13:37 +00003528 PyErr_SetString(PyExc_TypeError,
3529 "iteration over non-sequence");
Guido van Rossumb8f63662001-08-15 23:57:02 +00003530 return NULL;
3531 }
3532 Py_DECREF(func);
3533 return PySeqIter_New(self);
3534}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003535
3536static PyObject *
3537slot_tp_iternext(PyObject *self)
3538{
Guido van Rossum2730b132001-08-28 18:22:14 +00003539 static PyObject *next_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00003540 return call_method(self, "next", &next_str, "()");
Tim Peters6d6c1a32001-08-02 04:15:00 +00003541}
3542
Guido van Rossum1a493502001-08-17 16:47:50 +00003543static PyObject *
3544slot_tp_descr_get(PyObject *self, PyObject *obj, PyObject *type)
3545{
3546 PyTypeObject *tp = self->ob_type;
3547 PyObject *get;
3548 static PyObject *get_str = NULL;
3549
3550 if (get_str == NULL) {
3551 get_str = PyString_InternFromString("__get__");
3552 if (get_str == NULL)
3553 return NULL;
3554 }
3555 get = _PyType_Lookup(tp, get_str);
3556 if (get == NULL) {
3557 /* Avoid further slowdowns */
3558 if (tp->tp_descr_get == slot_tp_descr_get)
3559 tp->tp_descr_get = NULL;
3560 Py_INCREF(self);
3561 return self;
3562 }
Guido van Rossum2c252392001-08-24 10:13:31 +00003563 if (obj == NULL)
3564 obj = Py_None;
3565 if (type == NULL)
3566 type = Py_None;
Guido van Rossum1a493502001-08-17 16:47:50 +00003567 return PyObject_CallFunction(get, "OOO", self, obj, type);
3568}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003569
3570static int
3571slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value)
3572{
Guido van Rossum2c252392001-08-24 10:13:31 +00003573 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003574 static PyObject *del_str, *set_str;
Guido van Rossum2c252392001-08-24 10:13:31 +00003575
3576 if (value == NULL)
Guido van Rossum1d5b3f22001-12-03 00:08:33 +00003577 res = call_method(self, "__delete__", &del_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003578 "(O)", target);
Guido van Rossum2c252392001-08-24 10:13:31 +00003579 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003580 res = call_method(self, "__set__", &set_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003581 "(OO)", target, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003582 if (res == NULL)
3583 return -1;
3584 Py_DECREF(res);
3585 return 0;
3586}
3587
3588static int
3589slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds)
3590{
Guido van Rossum60718732001-08-28 17:47:51 +00003591 static PyObject *init_str;
3592 PyObject *meth = lookup_method(self, "__init__", &init_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003593 PyObject *res;
3594
3595 if (meth == NULL)
3596 return -1;
3597 res = PyObject_Call(meth, args, kwds);
3598 Py_DECREF(meth);
3599 if (res == NULL)
3600 return -1;
3601 Py_DECREF(res);
3602 return 0;
3603}
3604
3605static PyObject *
3606slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3607{
3608 PyObject *func = PyObject_GetAttrString((PyObject *)type, "__new__");
3609 PyObject *newargs, *x;
3610 int i, n;
3611
3612 if (func == NULL)
3613 return NULL;
3614 assert(PyTuple_Check(args));
3615 n = PyTuple_GET_SIZE(args);
3616 newargs = PyTuple_New(n+1);
3617 if (newargs == NULL)
3618 return NULL;
3619 Py_INCREF(type);
3620 PyTuple_SET_ITEM(newargs, 0, (PyObject *)type);
3621 for (i = 0; i < n; i++) {
3622 x = PyTuple_GET_ITEM(args, i);
3623 Py_INCREF(x);
3624 PyTuple_SET_ITEM(newargs, i+1, x);
3625 }
3626 x = PyObject_Call(func, newargs, kwds);
Guido van Rossum25d18072001-10-01 15:55:28 +00003627 Py_DECREF(newargs);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003628 Py_DECREF(func);
3629 return x;
3630}
3631
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003632
3633/* Table mapping __foo__ names to tp_foo offsets and slot_tp_foo wrapper
3634 functions. The offsets here are relative to the 'etype' structure, which
3635 incorporates the additional structures used for numbers, sequences and
3636 mappings. Note that multiple names may map to the same slot (e.g. __eq__,
3637 __ne__ etc. all map to tp_richcompare) and one name may map to multiple
Guido van Rossumc334df52002-04-04 23:44:47 +00003638 slots (e.g. __str__ affects tp_str as well as tp_repr). The table is
3639 terminated with an all-zero entry. (This table is further initialized and
3640 sorted in init_slotdefs() below.) */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003641
Guido van Rossum6d204072001-10-21 00:44:31 +00003642typedef struct wrapperbase slotdef;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003643
3644#undef TPSLOT
Guido van Rossumc8e56452001-10-22 00:43:43 +00003645#undef FLSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003646#undef ETSLOT
3647#undef SQSLOT
3648#undef MPSLOT
3649#undef NBSLOT
Guido van Rossum6d204072001-10-21 00:44:31 +00003650#undef UNSLOT
3651#undef IBSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003652#undef BINSLOT
3653#undef RBINSLOT
3654
Guido van Rossum6d204072001-10-21 00:44:31 +00003655#define TPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3656 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, DOC}
Guido van Rossumc8e56452001-10-22 00:43:43 +00003657#define FLSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC, FLAGS) \
3658 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
3659 DOC, FLAGS}
Guido van Rossum6d204072001-10-21 00:44:31 +00003660#define ETSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3661 {NAME, offsetof(etype, SLOT), (void *)(FUNCTION), WRAPPER, DOC}
3662#define SQSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3663 ETSLOT(NAME, as_sequence.SLOT, FUNCTION, WRAPPER, DOC)
3664#define MPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3665 ETSLOT(NAME, as_mapping.SLOT, FUNCTION, WRAPPER, DOC)
3666#define NBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3667 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, DOC)
3668#define UNSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3669 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
3670 "x." NAME "() <==> " DOC)
3671#define IBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3672 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
3673 "x." NAME "(y) <==> x" DOC "y")
3674#define BINSLOT(NAME, SLOT, FUNCTION, DOC) \
3675 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
3676 "x." NAME "(y) <==> x" DOC "y")
3677#define RBINSLOT(NAME, SLOT, FUNCTION, DOC) \
3678 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
3679 "x." NAME "(y) <==> y" DOC "x")
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003680
3681static slotdef slotdefs[] = {
Guido van Rossum6d204072001-10-21 00:44:31 +00003682 SQSLOT("__len__", sq_length, slot_sq_length, wrap_inquiry,
3683 "x.__len__() <==> len(x)"),
3684 SQSLOT("__add__", sq_concat, slot_sq_concat, wrap_binaryfunc,
3685 "x.__add__(y) <==> x+y"),
3686 SQSLOT("__mul__", sq_repeat, slot_sq_repeat, wrap_intargfunc,
3687 "x.__mul__(n) <==> x*n"),
3688 SQSLOT("__rmul__", sq_repeat, slot_sq_repeat, wrap_intargfunc,
3689 "x.__rmul__(n) <==> n*x"),
3690 SQSLOT("__getitem__", sq_item, slot_sq_item, wrap_sq_item,
3691 "x.__getitem__(y) <==> x[y]"),
3692 SQSLOT("__getslice__", sq_slice, slot_sq_slice, wrap_intintargfunc,
3693 "x.__getslice__(i, j) <==> x[i:j]"),
3694 SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_setitem,
3695 "x.__setitem__(i, y) <==> x[i]=y"),
3696 SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_delitem,
3697 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003698 SQSLOT("__setslice__", sq_ass_slice, slot_sq_ass_slice,
Guido van Rossum6d204072001-10-21 00:44:31 +00003699 wrap_intintobjargproc,
3700 "x.__setslice__(i, j, y) <==> x[i:j]=y"),
3701 SQSLOT("__delslice__", sq_ass_slice, slot_sq_ass_slice, wrap_delslice,
3702 "x.__delslice__(i, j) <==> del x[i:j]"),
3703 SQSLOT("__contains__", sq_contains, slot_sq_contains, wrap_objobjproc,
3704 "x.__contains__(y) <==> y in x"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003705 SQSLOT("__iadd__", sq_inplace_concat, slot_sq_inplace_concat,
Guido van Rossum6d204072001-10-21 00:44:31 +00003706 wrap_binaryfunc, "x.__iadd__(y) <==> x+=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003707 SQSLOT("__imul__", sq_inplace_repeat, slot_sq_inplace_repeat,
Guido van Rossum6d204072001-10-21 00:44:31 +00003708 wrap_intargfunc, "x.__imul__(y) <==> x*=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003709
Guido van Rossum6d204072001-10-21 00:44:31 +00003710 MPSLOT("__len__", mp_length, slot_mp_length, wrap_inquiry,
3711 "x.__len__() <==> len(x)"),
Guido van Rossumfd38f8e2001-10-09 20:17:57 +00003712 MPSLOT("__getitem__", mp_subscript, slot_mp_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00003713 wrap_binaryfunc,
3714 "x.__getitem__(y) <==> x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003715 MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00003716 wrap_objobjargproc,
3717 "x.__setitem__(i, y) <==> x[i]=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003718 MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00003719 wrap_delitem,
3720 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003721
Guido van Rossum6d204072001-10-21 00:44:31 +00003722 BINSLOT("__add__", nb_add, slot_nb_add,
3723 "+"),
3724 RBINSLOT("__radd__", nb_add, slot_nb_add,
3725 "+"),
3726 BINSLOT("__sub__", nb_subtract, slot_nb_subtract,
3727 "-"),
3728 RBINSLOT("__rsub__", nb_subtract, slot_nb_subtract,
3729 "-"),
3730 BINSLOT("__mul__", nb_multiply, slot_nb_multiply,
3731 "*"),
3732 RBINSLOT("__rmul__", nb_multiply, slot_nb_multiply,
3733 "*"),
3734 BINSLOT("__div__", nb_divide, slot_nb_divide,
3735 "/"),
3736 RBINSLOT("__rdiv__", nb_divide, slot_nb_divide,
3737 "/"),
3738 BINSLOT("__mod__", nb_remainder, slot_nb_remainder,
3739 "%"),
3740 RBINSLOT("__rmod__", nb_remainder, slot_nb_remainder,
3741 "%"),
3742 BINSLOT("__divmod__", nb_divmod, slot_nb_divmod,
3743 "divmod(x, y)"),
3744 RBINSLOT("__rdivmod__", nb_divmod, slot_nb_divmod,
3745 "divmod(y, x)"),
3746 NBSLOT("__pow__", nb_power, slot_nb_power, wrap_ternaryfunc,
3747 "x.__pow__(y[, z]) <==> pow(x, y[, z])"),
3748 NBSLOT("__rpow__", nb_power, slot_nb_power, wrap_ternaryfunc_r,
3749 "y.__rpow__(x[, z]) <==> pow(x, y[, z])"),
3750 UNSLOT("__neg__", nb_negative, slot_nb_negative, wrap_unaryfunc, "-x"),
3751 UNSLOT("__pos__", nb_positive, slot_nb_positive, wrap_unaryfunc, "+x"),
3752 UNSLOT("__abs__", nb_absolute, slot_nb_absolute, wrap_unaryfunc,
3753 "abs(x)"),
Guido van Rossumdfce3bf2002-03-10 14:11:16 +00003754 UNSLOT("__nonzero__", nb_nonzero, slot_nb_nonzero, wrap_inquiry,
Guido van Rossum6d204072001-10-21 00:44:31 +00003755 "x != 0"),
3756 UNSLOT("__invert__", nb_invert, slot_nb_invert, wrap_unaryfunc, "~x"),
3757 BINSLOT("__lshift__", nb_lshift, slot_nb_lshift, "<<"),
3758 RBINSLOT("__rlshift__", nb_lshift, slot_nb_lshift, "<<"),
3759 BINSLOT("__rshift__", nb_rshift, slot_nb_rshift, ">>"),
3760 RBINSLOT("__rrshift__", nb_rshift, slot_nb_rshift, ">>"),
3761 BINSLOT("__and__", nb_and, slot_nb_and, "&"),
3762 RBINSLOT("__rand__", nb_and, slot_nb_and, "&"),
3763 BINSLOT("__xor__", nb_xor, slot_nb_xor, "^"),
3764 RBINSLOT("__rxor__", nb_xor, slot_nb_xor, "^"),
3765 BINSLOT("__or__", nb_or, slot_nb_or, "|"),
3766 RBINSLOT("__ror__", nb_or, slot_nb_or, "|"),
3767 NBSLOT("__coerce__", nb_coerce, slot_nb_coerce, wrap_coercefunc,
3768 "x.__coerce__(y) <==> coerce(x, y)"),
3769 UNSLOT("__int__", nb_int, slot_nb_int, wrap_unaryfunc,
3770 "int(x)"),
3771 UNSLOT("__long__", nb_long, slot_nb_long, wrap_unaryfunc,
3772 "long(x)"),
3773 UNSLOT("__float__", nb_float, slot_nb_float, wrap_unaryfunc,
3774 "float(x)"),
3775 UNSLOT("__oct__", nb_oct, slot_nb_oct, wrap_unaryfunc,
3776 "oct(x)"),
3777 UNSLOT("__hex__", nb_hex, slot_nb_hex, wrap_unaryfunc,
3778 "hex(x)"),
3779 IBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add,
3780 wrap_binaryfunc, "+"),
3781 IBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract,
3782 wrap_binaryfunc, "-"),
3783 IBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply,
3784 wrap_binaryfunc, "*"),
3785 IBSLOT("__idiv__", nb_inplace_divide, slot_nb_inplace_divide,
3786 wrap_binaryfunc, "/"),
3787 IBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder,
3788 wrap_binaryfunc, "%"),
3789 IBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power,
3790 wrap_ternaryfunc, "**"),
3791 IBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift,
3792 wrap_binaryfunc, "<<"),
3793 IBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift,
3794 wrap_binaryfunc, ">>"),
3795 IBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and,
3796 wrap_binaryfunc, "&"),
3797 IBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor,
3798 wrap_binaryfunc, "^"),
3799 IBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or,
3800 wrap_binaryfunc, "|"),
3801 BINSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
3802 RBINSLOT("__rfloordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
3803 BINSLOT("__truediv__", nb_true_divide, slot_nb_true_divide, "/"),
3804 RBINSLOT("__rtruediv__", nb_true_divide, slot_nb_true_divide, "/"),
3805 IBSLOT("__ifloordiv__", nb_inplace_floor_divide,
3806 slot_nb_inplace_floor_divide, wrap_binaryfunc, "//"),
3807 IBSLOT("__itruediv__", nb_inplace_true_divide,
3808 slot_nb_inplace_true_divide, wrap_binaryfunc, "/"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003809
Guido van Rossum6d204072001-10-21 00:44:31 +00003810 TPSLOT("__str__", tp_str, slot_tp_str, wrap_unaryfunc,
3811 "x.__str__() <==> str(x)"),
Guido van Rossumafe7a942001-10-29 14:33:44 +00003812 TPSLOT("__str__", tp_print, NULL, NULL, ""),
Guido van Rossum6d204072001-10-21 00:44:31 +00003813 TPSLOT("__repr__", tp_repr, slot_tp_repr, wrap_unaryfunc,
3814 "x.__repr__() <==> repr(x)"),
Guido van Rossumafe7a942001-10-29 14:33:44 +00003815 TPSLOT("__repr__", tp_print, NULL, NULL, ""),
Guido van Rossum6d204072001-10-21 00:44:31 +00003816 TPSLOT("__cmp__", tp_compare, _PyObject_SlotCompare, wrap_cmpfunc,
3817 "x.__cmp__(y) <==> cmp(x,y)"),
3818 TPSLOT("__hash__", tp_hash, slot_tp_hash, wrap_hashfunc,
3819 "x.__hash__() <==> hash(x)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00003820 FLSLOT("__call__", tp_call, slot_tp_call, (wrapperfunc)wrap_call,
3821 "x.__call__(...) <==> x(...)", PyWrapperFlag_KEYWORDS),
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003822 TPSLOT("__getattribute__", tp_getattro, slot_tp_getattr_hook,
Guido van Rossum6d204072001-10-21 00:44:31 +00003823 wrap_binaryfunc, "x.__getattribute__('name') <==> x.name"),
3824 TPSLOT("__getattribute__", tp_getattr, NULL, NULL, ""),
3825 TPSLOT("__getattr__", tp_getattro, slot_tp_getattr_hook, NULL, ""),
3826 TPSLOT("__getattr__", tp_getattr, NULL, NULL, ""),
3827 TPSLOT("__setattr__", tp_setattro, slot_tp_setattro, wrap_setattr,
3828 "x.__setattr__('name', value) <==> x.name = value"),
3829 TPSLOT("__setattr__", tp_setattr, NULL, NULL, ""),
3830 TPSLOT("__delattr__", tp_setattro, slot_tp_setattro, wrap_delattr,
3831 "x.__delattr__('name') <==> del x.name"),
3832 TPSLOT("__delattr__", tp_setattr, NULL, NULL, ""),
3833 TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare, richcmp_lt,
3834 "x.__lt__(y) <==> x<y"),
3835 TPSLOT("__le__", tp_richcompare, slot_tp_richcompare, richcmp_le,
3836 "x.__le__(y) <==> x<=y"),
3837 TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare, richcmp_eq,
3838 "x.__eq__(y) <==> x==y"),
3839 TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare, richcmp_ne,
3840 "x.__ne__(y) <==> x!=y"),
3841 TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare, richcmp_gt,
3842 "x.__gt__(y) <==> x>y"),
3843 TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare, richcmp_ge,
3844 "x.__ge__(y) <==> x>=y"),
3845 TPSLOT("__iter__", tp_iter, slot_tp_iter, wrap_unaryfunc,
3846 "x.__iter__() <==> iter(x)"),
3847 TPSLOT("next", tp_iternext, slot_tp_iternext, wrap_next,
3848 "x.next() -> the next value, or raise StopIteration"),
3849 TPSLOT("__get__", tp_descr_get, slot_tp_descr_get, wrap_descr_get,
3850 "descr.__get__(obj[, type]) -> value"),
3851 TPSLOT("__set__", tp_descr_set, slot_tp_descr_set, wrap_descr_set,
3852 "descr.__set__(obj, value)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00003853 FLSLOT("__init__", tp_init, slot_tp_init, (wrapperfunc)wrap_init,
Guido van Rossum6d204072001-10-21 00:44:31 +00003854 "x.__init__(...) initializes x; "
Guido van Rossumc8e56452001-10-22 00:43:43 +00003855 "see x.__class__.__doc__ for signature",
3856 PyWrapperFlag_KEYWORDS),
3857 TPSLOT("__new__", tp_new, slot_tp_new, NULL, ""),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003858 {NULL}
3859};
3860
Guido van Rossumc334df52002-04-04 23:44:47 +00003861/* Given a type pointer and an offset gotten from a slotdef entry, return a
3862 pointer to the actual slot. This is not quite the same as simply adding
3863 the offset to the type pointer, since it takes care to indirect through the
3864 proper indirection pointer (as_buffer, etc.); it returns NULL if the
3865 indirection pointer is NULL. */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003866static void **
3867slotptr(PyTypeObject *type, int offset)
3868{
3869 char *ptr;
3870
3871 assert(offset >= 0);
3872 assert(offset < offsetof(etype, as_buffer));
3873 if (offset >= offsetof(etype, as_mapping)) {
3874 ptr = (void *)type->tp_as_mapping;
3875 offset -= offsetof(etype, as_mapping);
3876 }
3877 else if (offset >= offsetof(etype, as_sequence)) {
3878 ptr = (void *)type->tp_as_sequence;
3879 offset -= offsetof(etype, as_sequence);
3880 }
3881 else if (offset >= offsetof(etype, as_number)) {
3882 ptr = (void *)type->tp_as_number;
3883 offset -= offsetof(etype, as_number);
3884 }
3885 else {
3886 ptr = (void *)type;
3887 }
3888 if (ptr != NULL)
3889 ptr += offset;
3890 return (void **)ptr;
3891}
Guido van Rossumf040ede2001-08-07 16:40:56 +00003892
Guido van Rossumc334df52002-04-04 23:44:47 +00003893/* Length of array of slotdef pointers used to store slots with the
3894 same __name__. There should be at most MAX_EQUIV-1 slotdef entries with
3895 the same __name__, for any __name__. Since that's a static property, it is
3896 appropriate to declare fixed-size arrays for this. */
3897#define MAX_EQUIV 10
3898
3899/* Return a slot pointer for a given name, but ONLY if the attribute has
3900 exactly one slot function. The name must be an interned string. */
3901static void **
3902resolve_slotdups(PyTypeObject *type, PyObject *name)
3903{
3904 /* XXX Maybe this could be optimized more -- but is it worth it? */
3905
3906 /* pname and ptrs act as a little cache */
3907 static PyObject *pname;
3908 static slotdef *ptrs[MAX_EQUIV];
3909 slotdef *p, **pp;
3910 void **res, **ptr;
3911
3912 if (pname != name) {
3913 /* Collect all slotdefs that match name into ptrs. */
3914 pname = name;
3915 pp = ptrs;
3916 for (p = slotdefs; p->name_strobj; p++) {
3917 if (p->name_strobj == name)
3918 *pp++ = p;
3919 }
3920 *pp = NULL;
3921 }
3922
3923 /* Look in all matching slots of the type; if exactly one of these has
3924 a filled-in slot, return its value. Otherwise return NULL. */
3925 res = NULL;
3926 for (pp = ptrs; *pp; pp++) {
3927 ptr = slotptr(type, (*pp)->offset);
3928 if (ptr == NULL || *ptr == NULL)
3929 continue;
3930 if (res != NULL)
3931 return NULL;
3932 res = ptr;
3933 }
3934 return res;
3935}
3936
3937/* Common code for update_these_slots() and fixup_slot_dispatchers(). This
3938 does some incredibly complex thinking and then sticks something into the
3939 slot. (It sees if the adjacent slotdefs for the same slot have conflicting
3940 interests, and then stores a generic wrapper or a specific function into
3941 the slot.) Return a pointer to the next slotdef with a different offset,
3942 because that's convenient for fixup_slot_dispatchers(). */
3943static slotdef *
3944update_one_slot(PyTypeObject *type, slotdef *p)
3945{
3946 PyObject *descr;
3947 PyWrapperDescrObject *d;
3948 void *generic = NULL, *specific = NULL;
3949 int use_generic = 0;
3950 int offset = p->offset;
3951 void **ptr = slotptr(type, offset);
3952
3953 if (ptr == NULL) {
3954 do {
3955 ++p;
3956 } while (p->offset == offset);
3957 return p;
3958 }
3959 do {
3960 descr = _PyType_Lookup(type, p->name_strobj);
3961 if (descr == NULL)
3962 continue;
3963 if (descr->ob_type == &PyWrapperDescr_Type) {
3964 void **tptr = resolve_slotdups(type, p->name_strobj);
3965 if (tptr == NULL || tptr == ptr)
3966 generic = p->function;
3967 d = (PyWrapperDescrObject *)descr;
3968 if (d->d_base->wrapper == p->wrapper &&
3969 PyType_IsSubtype(type, d->d_type))
3970 {
3971 if (specific == NULL ||
3972 specific == d->d_wrapped)
3973 specific = d->d_wrapped;
3974 else
3975 use_generic = 1;
3976 }
3977 }
3978 else {
3979 use_generic = 1;
3980 generic = p->function;
3981 }
3982 } while ((++p)->offset == offset);
3983 if (specific && !use_generic)
3984 *ptr = specific;
3985 else
3986 *ptr = generic;
3987 return p;
3988}
3989
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003990staticforward int recurse_down_subclasses(PyTypeObject *type,
3991 slotdef **pp, PyObject *name);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003992
Guido van Rossumc334df52002-04-04 23:44:47 +00003993/* In the type, update the slots whose slotdefs are gathered in the pp0 array,
3994 and then do the same for all this type's subtypes. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003995static int
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003996update_these_slots(PyTypeObject *type, slotdef **pp0, PyObject *name)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003997{
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003998 slotdef **pp;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003999
Guido van Rossumc334df52002-04-04 23:44:47 +00004000 for (pp = pp0; *pp; pp++)
4001 update_one_slot(type, *pp);
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004002 return recurse_down_subclasses(type, pp0, name);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004003}
4004
Guido van Rossumc334df52002-04-04 23:44:47 +00004005/* Update the slots whose slotdefs are gathered in the pp array in all (direct
4006 or indirect) subclasses of type. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004007static int
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004008recurse_down_subclasses(PyTypeObject *type, slotdef **pp, PyObject *name)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004009{
4010 PyTypeObject *subclass;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004011 PyObject *ref, *subclasses, *dict;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004012 int i, n;
4013
4014 subclasses = type->tp_subclasses;
4015 if (subclasses == NULL)
4016 return 0;
4017 assert(PyList_Check(subclasses));
4018 n = PyList_GET_SIZE(subclasses);
4019 for (i = 0; i < n; i++) {
4020 ref = PyList_GET_ITEM(subclasses, i);
4021 assert(PyWeakref_CheckRef(ref));
4022 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
4023 if (subclass == NULL)
4024 continue;
4025 assert(PyType_Check(subclass));
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004026 /* Avoid recursing down into unaffected classes */
4027 dict = subclass->tp_dict;
4028 if (dict != NULL && PyDict_Check(dict) &&
4029 PyDict_GetItem(dict, name) != NULL)
4030 continue;
4031 if (update_these_slots(subclass, pp, name) < 0)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004032 return -1;
4033 }
4034 return 0;
4035}
4036
Guido van Rossumc334df52002-04-04 23:44:47 +00004037/* Comparison function for qsort() to compare slotdefs by their offset, and
4038 for equal offset by their address (to force a stable sort). */
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004039static int
4040slotdef_cmp(const void *aa, const void *bb)
4041{
4042 const slotdef *a = (const slotdef *)aa, *b = (const slotdef *)bb;
4043 int c = a->offset - b->offset;
4044 if (c != 0)
4045 return c;
4046 else
4047 return a - b;
4048}
4049
Guido van Rossumc334df52002-04-04 23:44:47 +00004050/* Initialize the slotdefs table by adding interned string objects for the
4051 names and sorting the entries. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004052static void
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004053init_slotdefs(void)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004054{
4055 slotdef *p;
4056 static int initialized = 0;
4057
4058 if (initialized)
4059 return;
4060 for (p = slotdefs; p->name; p++) {
4061 p->name_strobj = PyString_InternFromString(p->name);
4062 if (!p->name_strobj)
Guido van Rossumc334df52002-04-04 23:44:47 +00004063 Py_FatalError("Out of memory interning slotdef names");
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004064 }
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004065 qsort((void *)slotdefs, (size_t)(p-slotdefs), sizeof(slotdef),
4066 slotdef_cmp);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004067 initialized = 1;
4068}
4069
Guido van Rossumc334df52002-04-04 23:44:47 +00004070/* Update the slots after assignment to a class (type) attribute. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004071static int
4072update_slot(PyTypeObject *type, PyObject *name)
4073{
Guido van Rossumc334df52002-04-04 23:44:47 +00004074 slotdef *ptrs[MAX_EQUIV];
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004075 slotdef *p;
4076 slotdef **pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004077 int offset;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004078
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004079 init_slotdefs();
4080 pp = ptrs;
4081 for (p = slotdefs; p->name; p++) {
4082 /* XXX assume name is interned! */
4083 if (p->name_strobj == name)
4084 *pp++ = p;
4085 }
4086 *pp = NULL;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004087 for (pp = ptrs; *pp; pp++) {
4088 p = *pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004089 offset = p->offset;
4090 while (p > slotdefs && (p-1)->offset == offset)
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004091 --p;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004092 *pp = p;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004093 }
Guido van Rossumc334df52002-04-04 23:44:47 +00004094 if (ptrs[0] == NULL)
4095 return 0; /* Not an attribute that affects any slots */
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004096 return update_these_slots(type, ptrs, name);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004097}
4098
Guido van Rossumc334df52002-04-04 23:44:47 +00004099/* Store the proper functions in the slot dispatches at class (type)
4100 definition time, based upon which operations the class overrides in its
4101 dict. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004102static void
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004103fixup_slot_dispatchers(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004104{
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004105 slotdef *p;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004106
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004107 init_slotdefs();
Guido van Rossumc334df52002-04-04 23:44:47 +00004108 for (p = slotdefs; p->name; )
4109 p = update_one_slot(type, p);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004110}
Guido van Rossum705f0f52001-08-24 16:47:00 +00004111
Guido van Rossum6d204072001-10-21 00:44:31 +00004112/* This function is called by PyType_Ready() to populate the type's
4113 dictionary with method descriptors for function slots. For each
4114 function slot (like tp_repr) that's defined in the type, one or
4115 more corresponding descriptors are added in the type's tp_dict
4116 dictionary under the appropriate name (like __repr__). Some
4117 function slots cause more than one descriptor to be added (for
4118 example, the nb_add slot adds both __add__ and __radd__
4119 descriptors) and some function slots compete for the same
4120 descriptor (for example both sq_item and mp_subscript generate a
4121 __getitem__ descriptor). This only adds new descriptors and
4122 doesn't overwrite entries in tp_dict that were previously
4123 defined. The descriptors contain a reference to the C function
4124 they must call, so that it's safe if they are copied into a
4125 subtype's __dict__ and the subtype has a different C function in
4126 its slot -- calling the method defined by the descriptor will call
4127 the C function that was used to create it, rather than the C
4128 function present in the slot when it is called. (This is important
4129 because a subtype may have a C function in the slot that calls the
4130 method from the dictionary, and we want to avoid infinite recursion
4131 here.) */
4132
4133static int
4134add_operators(PyTypeObject *type)
4135{
4136 PyObject *dict = type->tp_dict;
4137 slotdef *p;
4138 PyObject *descr;
4139 void **ptr;
4140
4141 init_slotdefs();
4142 for (p = slotdefs; p->name; p++) {
4143 if (p->wrapper == NULL)
4144 continue;
4145 ptr = slotptr(type, p->offset);
4146 if (!ptr || !*ptr)
4147 continue;
4148 if (PyDict_GetItem(dict, p->name_strobj))
4149 continue;
4150 descr = PyDescr_NewWrapper(type, p, *ptr);
4151 if (descr == NULL)
4152 return -1;
4153 if (PyDict_SetItem(dict, p->name_strobj, descr) < 0)
4154 return -1;
4155 Py_DECREF(descr);
4156 }
4157 if (type->tp_new != NULL) {
4158 if (add_tp_new_wrapper(type) < 0)
4159 return -1;
4160 }
4161 return 0;
4162}
4163
Guido van Rossum705f0f52001-08-24 16:47:00 +00004164
4165/* Cooperative 'super' */
4166
4167typedef struct {
4168 PyObject_HEAD
Guido van Rossume705ef12001-08-29 15:47:06 +00004169 PyTypeObject *type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00004170 PyObject *obj;
4171} superobject;
4172
Guido van Rossum6f799372001-09-20 20:46:19 +00004173static PyMemberDef super_members[] = {
4174 {"__thisclass__", T_OBJECT, offsetof(superobject, type), READONLY,
4175 "the class invoking super()"},
4176 {"__self__", T_OBJECT, offsetof(superobject, obj), READONLY,
4177 "the instance invoking super(); may be None"},
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004178 {0}
4179};
4180
Guido van Rossum705f0f52001-08-24 16:47:00 +00004181static void
4182super_dealloc(PyObject *self)
4183{
4184 superobject *su = (superobject *)self;
4185
Guido van Rossum048eb752001-10-02 21:24:57 +00004186 _PyObject_GC_UNTRACK(self);
Guido van Rossum705f0f52001-08-24 16:47:00 +00004187 Py_XDECREF(su->obj);
4188 Py_XDECREF(su->type);
4189 self->ob_type->tp_free(self);
4190}
4191
4192static PyObject *
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004193super_repr(PyObject *self)
4194{
4195 superobject *su = (superobject *)self;
4196
4197 if (su->obj)
4198 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00004199 "<super: <class '%s'>, <%s object>>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004200 su->type ? su->type->tp_name : "NULL",
4201 su->obj->ob_type->tp_name);
4202 else
4203 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00004204 "<super: <class '%s'>, NULL>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004205 su->type ? su->type->tp_name : "NULL");
4206}
4207
4208static PyObject *
Guido van Rossum705f0f52001-08-24 16:47:00 +00004209super_getattro(PyObject *self, PyObject *name)
4210{
4211 superobject *su = (superobject *)self;
4212
4213 if (su->obj != NULL) {
Tim Petersa91e9642001-11-14 23:32:33 +00004214 PyObject *mro, *res, *tmp, *dict;
Guido van Rossum155db9a2002-04-02 17:53:47 +00004215 PyTypeObject *starttype;
Guido van Rossum705f0f52001-08-24 16:47:00 +00004216 descrgetfunc f;
4217 int i, n;
4218
Guido van Rossum155db9a2002-04-02 17:53:47 +00004219 starttype = su->obj->ob_type;
4220 mro = starttype->tp_mro;
4221
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004222 if (mro == NULL)
4223 n = 0;
4224 else {
4225 assert(PyTuple_Check(mro));
4226 n = PyTuple_GET_SIZE(mro);
4227 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00004228 for (i = 0; i < n; i++) {
Guido van Rossume705ef12001-08-29 15:47:06 +00004229 if ((PyObject *)(su->type) == PyTuple_GET_ITEM(mro, i))
Guido van Rossum705f0f52001-08-24 16:47:00 +00004230 break;
4231 }
Guido van Rossume705ef12001-08-29 15:47:06 +00004232 if (i >= n && PyType_Check(su->obj)) {
Guido van Rossum155db9a2002-04-02 17:53:47 +00004233 starttype = (PyTypeObject *)(su->obj);
4234 mro = starttype->tp_mro;
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004235 if (mro == NULL)
4236 n = 0;
4237 else {
4238 assert(PyTuple_Check(mro));
4239 n = PyTuple_GET_SIZE(mro);
4240 }
Guido van Rossume705ef12001-08-29 15:47:06 +00004241 for (i = 0; i < n; i++) {
4242 if ((PyObject *)(su->type) ==
4243 PyTuple_GET_ITEM(mro, i))
4244 break;
4245 }
Guido van Rossume705ef12001-08-29 15:47:06 +00004246 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00004247 i++;
4248 res = NULL;
4249 for (; i < n; i++) {
4250 tmp = PyTuple_GET_ITEM(mro, i);
Tim Petersa91e9642001-11-14 23:32:33 +00004251 if (PyType_Check(tmp))
4252 dict = ((PyTypeObject *)tmp)->tp_dict;
4253 else if (PyClass_Check(tmp))
4254 dict = ((PyClassObject *)tmp)->cl_dict;
4255 else
4256 continue;
4257 res = PyDict_GetItem(dict, name);
Guido van Rossum5b443c62001-12-03 15:38:28 +00004258 if (res != NULL && !PyDescr_IsData(res)) {
Guido van Rossum705f0f52001-08-24 16:47:00 +00004259 Py_INCREF(res);
4260 f = res->ob_type->tp_descr_get;
4261 if (f != NULL) {
Guido van Rossumd4641072002-04-03 02:13:37 +00004262 tmp = f(res, su->obj,
4263 (PyObject *)starttype);
Guido van Rossum705f0f52001-08-24 16:47:00 +00004264 Py_DECREF(res);
4265 res = tmp;
4266 }
4267 return res;
4268 }
4269 }
4270 }
4271 return PyObject_GenericGetAttr(self, name);
4272}
4273
Guido van Rossum5b443c62001-12-03 15:38:28 +00004274static int
4275supercheck(PyTypeObject *type, PyObject *obj)
4276{
4277 if (!PyType_IsSubtype(obj->ob_type, type) &&
4278 !(PyType_Check(obj) &&
4279 PyType_IsSubtype((PyTypeObject *)obj, type))) {
4280 PyErr_SetString(PyExc_TypeError,
4281 "super(type, obj): "
4282 "obj must be an instance or subtype of type");
4283 return -1;
4284 }
4285 else
4286 return 0;
4287}
4288
Guido van Rossum705f0f52001-08-24 16:47:00 +00004289static PyObject *
4290super_descr_get(PyObject *self, PyObject *obj, PyObject *type)
4291{
4292 superobject *su = (superobject *)self;
4293 superobject *new;
4294
4295 if (obj == NULL || obj == Py_None || su->obj != NULL) {
4296 /* Not binding to an object, or already bound */
4297 Py_INCREF(self);
4298 return self;
4299 }
Guido van Rossum5b443c62001-12-03 15:38:28 +00004300 if (su->ob_type != &PySuper_Type)
4301 /* If su is an instance of a subclass of super,
4302 call its type */
4303 return PyObject_CallFunction((PyObject *)su->ob_type,
4304 "OO", su->type, obj);
4305 else {
4306 /* Inline the common case */
4307 if (supercheck(su->type, obj) < 0)
4308 return NULL;
4309 new = (superobject *)PySuper_Type.tp_new(&PySuper_Type,
4310 NULL, NULL);
4311 if (new == NULL)
4312 return NULL;
4313 Py_INCREF(su->type);
4314 Py_INCREF(obj);
4315 new->type = su->type;
4316 new->obj = obj;
4317 return (PyObject *)new;
4318 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00004319}
4320
4321static int
4322super_init(PyObject *self, PyObject *args, PyObject *kwds)
4323{
4324 superobject *su = (superobject *)self;
Guido van Rossume705ef12001-08-29 15:47:06 +00004325 PyTypeObject *type;
4326 PyObject *obj = NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00004327
4328 if (!PyArg_ParseTuple(args, "O!|O:super", &PyType_Type, &type, &obj))
4329 return -1;
4330 if (obj == Py_None)
4331 obj = NULL;
Guido van Rossum5b443c62001-12-03 15:38:28 +00004332 if (obj != NULL && supercheck(type, obj) < 0)
Guido van Rossum705f0f52001-08-24 16:47:00 +00004333 return -1;
Guido van Rossum705f0f52001-08-24 16:47:00 +00004334 Py_INCREF(type);
4335 Py_XINCREF(obj);
4336 su->type = type;
4337 su->obj = obj;
4338 return 0;
4339}
4340
4341static char super_doc[] =
4342"super(type) -> unbound super object\n"
4343"super(type, obj) -> bound super object; requires isinstance(obj, type)\n"
Guido van Rossume705ef12001-08-29 15:47:06 +00004344"super(type, type2) -> bound super object; requires issubclass(type2, type)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00004345"Typical use to call a cooperative superclass method:\n"
4346"class C(B):\n"
4347" def meth(self, arg):\n"
4348" super(C, self).meth(arg)";
4349
Guido van Rossum048eb752001-10-02 21:24:57 +00004350static int
4351super_traverse(PyObject *self, visitproc visit, void *arg)
4352{
4353 superobject *su = (superobject *)self;
4354 int err;
4355
4356#define VISIT(SLOT) \
4357 if (SLOT) { \
4358 err = visit((PyObject *)(SLOT), arg); \
4359 if (err) \
4360 return err; \
4361 }
4362
4363 VISIT(su->obj);
4364 VISIT(su->type);
4365
4366#undef VISIT
4367
4368 return 0;
4369}
4370
Guido van Rossum705f0f52001-08-24 16:47:00 +00004371PyTypeObject PySuper_Type = {
4372 PyObject_HEAD_INIT(&PyType_Type)
4373 0, /* ob_size */
4374 "super", /* tp_name */
4375 sizeof(superobject), /* tp_basicsize */
4376 0, /* tp_itemsize */
4377 /* methods */
4378 super_dealloc, /* tp_dealloc */
4379 0, /* tp_print */
4380 0, /* tp_getattr */
4381 0, /* tp_setattr */
4382 0, /* tp_compare */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004383 super_repr, /* tp_repr */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004384 0, /* tp_as_number */
4385 0, /* tp_as_sequence */
4386 0, /* tp_as_mapping */
4387 0, /* tp_hash */
4388 0, /* tp_call */
4389 0, /* tp_str */
4390 super_getattro, /* tp_getattro */
4391 0, /* tp_setattro */
4392 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00004393 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
4394 Py_TPFLAGS_BASETYPE, /* tp_flags */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004395 super_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00004396 super_traverse, /* tp_traverse */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004397 0, /* tp_clear */
4398 0, /* tp_richcompare */
4399 0, /* tp_weaklistoffset */
4400 0, /* tp_iter */
4401 0, /* tp_iternext */
4402 0, /* tp_methods */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004403 super_members, /* tp_members */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004404 0, /* tp_getset */
4405 0, /* tp_base */
4406 0, /* tp_dict */
4407 super_descr_get, /* tp_descr_get */
4408 0, /* tp_descr_set */
4409 0, /* tp_dictoffset */
4410 super_init, /* tp_init */
4411 PyType_GenericAlloc, /* tp_alloc */
4412 PyType_GenericNew, /* tp_new */
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00004413 PyObject_GC_Del, /* tp_free */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004414};