blob: 49c7d5250fac10a647107fe8a04f71c0dcf4bf84 [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 Rossumcab05802002-06-10 15:29:03 +00002178 if (type->tp_flags & Py_TPFLAGS_READY) {
2179 assert(type->tp_dict != NULL);
Guido van Rossumd614f972001-08-10 17:39:49 +00002180 return 0;
Guido van Rossumcab05802002-06-10 15:29:03 +00002181 }
Guido van Rossumd614f972001-08-10 17:39:49 +00002182 assert((type->tp_flags & Py_TPFLAGS_READYING) == 0);
Guido van Rossumd614f972001-08-10 17:39:49 +00002183
2184 type->tp_flags |= Py_TPFLAGS_READYING;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002185
2186 /* Initialize tp_base (defaults to BaseObject unless that's us) */
2187 base = type->tp_base;
2188 if (base == NULL && type != &PyBaseObject_Type)
2189 base = type->tp_base = &PyBaseObject_Type;
2190
Guido van Rossum0986d822002-04-08 01:38:42 +00002191 /* Initialize ob_type if NULL. This means extensions that want to be
2192 compilable separately on Windows can call PyType_Ready() instead of
2193 initializing the ob_type field of their type objects. */
2194 if (type->ob_type == NULL)
2195 type->ob_type = base->ob_type;
2196
Tim Peters6d6c1a32001-08-02 04:15:00 +00002197 /* Initialize tp_bases */
2198 bases = type->tp_bases;
2199 if (bases == NULL) {
2200 if (base == NULL)
2201 bases = PyTuple_New(0);
2202 else
2203 bases = Py_BuildValue("(O)", base);
2204 if (bases == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00002205 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002206 type->tp_bases = bases;
2207 }
2208
2209 /* Initialize the base class */
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002210 if (base && base->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00002211 if (PyType_Ready(base) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00002212 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002213 }
2214
Guido van Rossum687ae002001-10-15 22:03:32 +00002215 /* Initialize tp_dict */
2216 dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002217 if (dict == NULL) {
2218 dict = PyDict_New();
2219 if (dict == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00002220 goto error;
Guido van Rossum687ae002001-10-15 22:03:32 +00002221 type->tp_dict = dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002222 }
2223
Guido van Rossum687ae002001-10-15 22:03:32 +00002224 /* Add type-specific descriptors to tp_dict */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002225 if (add_operators(type) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00002226 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002227 if (type->tp_methods != NULL) {
2228 if (add_methods(type, type->tp_methods) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00002229 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002230 }
2231 if (type->tp_members != NULL) {
2232 if (add_members(type, type->tp_members) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00002233 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002234 }
2235 if (type->tp_getset != NULL) {
2236 if (add_getset(type, type->tp_getset) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00002237 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002238 }
2239
Tim Peters6d6c1a32001-08-02 04:15:00 +00002240 /* Calculate method resolution order */
2241 if (mro_internal(type) < 0) {
Guido van Rossumd614f972001-08-10 17:39:49 +00002242 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002243 }
2244
Guido van Rossum13d52f02001-08-10 21:24:08 +00002245 /* Inherit special flags from dominant base */
2246 if (type->tp_base != NULL)
2247 inherit_special(type, type->tp_base);
2248
Tim Peters6d6c1a32001-08-02 04:15:00 +00002249 /* Initialize tp_dict properly */
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002250 bases = type->tp_mro;
2251 assert(bases != NULL);
2252 assert(PyTuple_Check(bases));
2253 n = PyTuple_GET_SIZE(bases);
2254 for (i = 1; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00002255 PyObject *b = PyTuple_GET_ITEM(bases, i);
2256 if (PyType_Check(b))
2257 inherit_slots(type, (PyTypeObject *)b);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002258 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002259
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00002260 /* if the type dictionary doesn't contain a __doc__, set it from
2261 the tp_doc slot.
2262 */
2263 if (PyDict_GetItemString(type->tp_dict, "__doc__") == NULL) {
2264 if (type->tp_doc != NULL) {
2265 PyObject *doc = PyString_FromString(type->tp_doc);
2266 PyDict_SetItemString(type->tp_dict, "__doc__", doc);
2267 Py_DECREF(doc);
2268 } else {
Guido van Rossumd4641072002-04-03 02:13:37 +00002269 PyDict_SetItemString(type->tp_dict,
2270 "__doc__", Py_None);
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00002271 }
2272 }
2273
Guido van Rossum13d52f02001-08-10 21:24:08 +00002274 /* Some more special stuff */
2275 base = type->tp_base;
2276 if (base != NULL) {
2277 if (type->tp_as_number == NULL)
2278 type->tp_as_number = base->tp_as_number;
2279 if (type->tp_as_sequence == NULL)
2280 type->tp_as_sequence = base->tp_as_sequence;
2281 if (type->tp_as_mapping == NULL)
2282 type->tp_as_mapping = base->tp_as_mapping;
2283 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002284
Guido van Rossum1c450732001-10-08 15:18:27 +00002285 /* Link into each base class's list of subclasses */
2286 bases = type->tp_bases;
2287 n = PyTuple_GET_SIZE(bases);
2288 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00002289 PyObject *b = PyTuple_GET_ITEM(bases, i);
2290 if (PyType_Check(b) &&
2291 add_subclass((PyTypeObject *)b, type) < 0)
Guido van Rossum1c450732001-10-08 15:18:27 +00002292 goto error;
2293 }
2294
Guido van Rossum13d52f02001-08-10 21:24:08 +00002295 /* All done -- set the ready flag */
Guido van Rossumd614f972001-08-10 17:39:49 +00002296 assert(type->tp_dict != NULL);
2297 type->tp_flags =
2298 (type->tp_flags & ~Py_TPFLAGS_READYING) | Py_TPFLAGS_READY;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002299 return 0;
Guido van Rossumd614f972001-08-10 17:39:49 +00002300
2301 error:
2302 type->tp_flags &= ~Py_TPFLAGS_READYING;
2303 return -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002304}
2305
Guido van Rossum1c450732001-10-08 15:18:27 +00002306static int
2307add_subclass(PyTypeObject *base, PyTypeObject *type)
2308{
2309 int i;
2310 PyObject *list, *ref, *new;
2311
2312 list = base->tp_subclasses;
2313 if (list == NULL) {
2314 base->tp_subclasses = list = PyList_New(0);
2315 if (list == NULL)
2316 return -1;
2317 }
2318 assert(PyList_Check(list));
2319 new = PyWeakref_NewRef((PyObject *)type, NULL);
2320 i = PyList_GET_SIZE(list);
2321 while (--i >= 0) {
2322 ref = PyList_GET_ITEM(list, i);
2323 assert(PyWeakref_CheckRef(ref));
2324 if (PyWeakref_GET_OBJECT(ref) == Py_None)
2325 return PyList_SetItem(list, i, new);
2326 }
2327 i = PyList_Append(list, new);
2328 Py_DECREF(new);
2329 return i;
2330}
2331
Tim Peters6d6c1a32001-08-02 04:15:00 +00002332
2333/* Generic wrappers for overloadable 'operators' such as __getitem__ */
2334
2335/* There's a wrapper *function* for each distinct function typedef used
2336 for type object slots (e.g. binaryfunc, ternaryfunc, etc.). There's a
2337 wrapper *table* for each distinct operation (e.g. __len__, __add__).
2338 Most tables have only one entry; the tables for binary operators have two
2339 entries, one regular and one with reversed arguments. */
2340
2341static PyObject *
2342wrap_inquiry(PyObject *self, PyObject *args, void *wrapped)
2343{
2344 inquiry func = (inquiry)wrapped;
2345 int res;
2346
2347 if (!PyArg_ParseTuple(args, ""))
2348 return NULL;
2349 res = (*func)(self);
2350 if (res == -1 && PyErr_Occurred())
2351 return NULL;
2352 return PyInt_FromLong((long)res);
2353}
2354
Tim Peters6d6c1a32001-08-02 04:15:00 +00002355static PyObject *
2356wrap_binaryfunc(PyObject *self, PyObject *args, void *wrapped)
2357{
2358 binaryfunc func = (binaryfunc)wrapped;
2359 PyObject *other;
2360
2361 if (!PyArg_ParseTuple(args, "O", &other))
2362 return NULL;
2363 return (*func)(self, other);
2364}
2365
2366static PyObject *
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002367wrap_binaryfunc_l(PyObject *self, PyObject *args, void *wrapped)
2368{
2369 binaryfunc func = (binaryfunc)wrapped;
2370 PyObject *other;
2371
2372 if (!PyArg_ParseTuple(args, "O", &other))
2373 return NULL;
2374 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002375 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002376 Py_INCREF(Py_NotImplemented);
2377 return Py_NotImplemented;
2378 }
2379 return (*func)(self, other);
2380}
2381
2382static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00002383wrap_binaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
2384{
2385 binaryfunc func = (binaryfunc)wrapped;
2386 PyObject *other;
2387
2388 if (!PyArg_ParseTuple(args, "O", &other))
2389 return NULL;
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002390 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002391 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002392 Py_INCREF(Py_NotImplemented);
2393 return Py_NotImplemented;
2394 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002395 return (*func)(other, self);
2396}
2397
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00002398static PyObject *
2399wrap_coercefunc(PyObject *self, PyObject *args, void *wrapped)
2400{
2401 coercion func = (coercion)wrapped;
2402 PyObject *other, *res;
2403 int ok;
2404
2405 if (!PyArg_ParseTuple(args, "O", &other))
2406 return NULL;
2407 ok = func(&self, &other);
2408 if (ok < 0)
2409 return NULL;
2410 if (ok > 0) {
2411 Py_INCREF(Py_NotImplemented);
2412 return Py_NotImplemented;
2413 }
2414 res = PyTuple_New(2);
2415 if (res == NULL) {
2416 Py_DECREF(self);
2417 Py_DECREF(other);
2418 return NULL;
2419 }
2420 PyTuple_SET_ITEM(res, 0, self);
2421 PyTuple_SET_ITEM(res, 1, other);
2422 return res;
2423}
2424
Tim Peters6d6c1a32001-08-02 04:15:00 +00002425static PyObject *
2426wrap_ternaryfunc(PyObject *self, PyObject *args, void *wrapped)
2427{
2428 ternaryfunc func = (ternaryfunc)wrapped;
2429 PyObject *other;
2430 PyObject *third = Py_None;
2431
2432 /* Note: This wrapper only works for __pow__() */
2433
2434 if (!PyArg_ParseTuple(args, "O|O", &other, &third))
2435 return NULL;
2436 return (*func)(self, other, third);
2437}
2438
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00002439static PyObject *
2440wrap_ternaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
2441{
2442 ternaryfunc func = (ternaryfunc)wrapped;
2443 PyObject *other;
2444 PyObject *third = Py_None;
2445
2446 /* Note: This wrapper only works for __pow__() */
2447
2448 if (!PyArg_ParseTuple(args, "O|O", &other, &third))
2449 return NULL;
2450 return (*func)(other, self, third);
2451}
2452
Tim Peters6d6c1a32001-08-02 04:15:00 +00002453static PyObject *
2454wrap_unaryfunc(PyObject *self, PyObject *args, void *wrapped)
2455{
2456 unaryfunc func = (unaryfunc)wrapped;
2457
2458 if (!PyArg_ParseTuple(args, ""))
2459 return NULL;
2460 return (*func)(self);
2461}
2462
Tim Peters6d6c1a32001-08-02 04:15:00 +00002463static PyObject *
2464wrap_intargfunc(PyObject *self, PyObject *args, void *wrapped)
2465{
2466 intargfunc func = (intargfunc)wrapped;
2467 int i;
2468
2469 if (!PyArg_ParseTuple(args, "i", &i))
2470 return NULL;
2471 return (*func)(self, i);
2472}
2473
Guido van Rossum5d815f32001-08-17 21:57:47 +00002474static int
2475getindex(PyObject *self, PyObject *arg)
2476{
2477 int i;
2478
2479 i = PyInt_AsLong(arg);
2480 if (i == -1 && PyErr_Occurred())
2481 return -1;
2482 if (i < 0) {
2483 PySequenceMethods *sq = self->ob_type->tp_as_sequence;
2484 if (sq && sq->sq_length) {
2485 int n = (*sq->sq_length)(self);
2486 if (n < 0)
2487 return -1;
2488 i += n;
2489 }
2490 }
2491 return i;
2492}
2493
2494static PyObject *
2495wrap_sq_item(PyObject *self, PyObject *args, void *wrapped)
2496{
2497 intargfunc func = (intargfunc)wrapped;
2498 PyObject *arg;
2499 int i;
2500
Guido van Rossumf4593e02001-10-03 12:09:30 +00002501 if (PyTuple_GET_SIZE(args) == 1) {
2502 arg = PyTuple_GET_ITEM(args, 0);
2503 i = getindex(self, arg);
2504 if (i == -1 && PyErr_Occurred())
2505 return NULL;
2506 return (*func)(self, i);
2507 }
2508 PyArg_ParseTuple(args, "O", &arg);
2509 assert(PyErr_Occurred());
2510 return NULL;
Guido van Rossum5d815f32001-08-17 21:57:47 +00002511}
2512
Tim Peters6d6c1a32001-08-02 04:15:00 +00002513static PyObject *
2514wrap_intintargfunc(PyObject *self, PyObject *args, void *wrapped)
2515{
2516 intintargfunc func = (intintargfunc)wrapped;
2517 int i, j;
2518
2519 if (!PyArg_ParseTuple(args, "ii", &i, &j))
2520 return NULL;
2521 return (*func)(self, i, j);
2522}
2523
Tim Peters6d6c1a32001-08-02 04:15:00 +00002524static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00002525wrap_sq_setitem(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002526{
2527 intobjargproc func = (intobjargproc)wrapped;
2528 int i, res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00002529 PyObject *arg, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002530
Guido van Rossum5d815f32001-08-17 21:57:47 +00002531 if (!PyArg_ParseTuple(args, "OO", &arg, &value))
2532 return NULL;
2533 i = getindex(self, arg);
2534 if (i == -1 && PyErr_Occurred())
Tim Peters6d6c1a32001-08-02 04:15:00 +00002535 return NULL;
2536 res = (*func)(self, i, value);
2537 if (res == -1 && PyErr_Occurred())
2538 return NULL;
2539 Py_INCREF(Py_None);
2540 return Py_None;
2541}
2542
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002543static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00002544wrap_sq_delitem(PyObject *self, PyObject *args, void *wrapped)
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002545{
2546 intobjargproc func = (intobjargproc)wrapped;
2547 int i, res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00002548 PyObject *arg;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002549
Guido van Rossum5d815f32001-08-17 21:57:47 +00002550 if (!PyArg_ParseTuple(args, "O", &arg))
2551 return NULL;
2552 i = getindex(self, arg);
2553 if (i == -1 && PyErr_Occurred())
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002554 return NULL;
2555 res = (*func)(self, i, NULL);
2556 if (res == -1 && PyErr_Occurred())
2557 return NULL;
2558 Py_INCREF(Py_None);
2559 return Py_None;
2560}
2561
Tim Peters6d6c1a32001-08-02 04:15:00 +00002562static PyObject *
2563wrap_intintobjargproc(PyObject *self, PyObject *args, void *wrapped)
2564{
2565 intintobjargproc func = (intintobjargproc)wrapped;
2566 int i, j, res;
2567 PyObject *value;
2568
2569 if (!PyArg_ParseTuple(args, "iiO", &i, &j, &value))
2570 return NULL;
2571 res = (*func)(self, i, j, value);
2572 if (res == -1 && PyErr_Occurred())
2573 return NULL;
2574 Py_INCREF(Py_None);
2575 return Py_None;
2576}
2577
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002578static PyObject *
2579wrap_delslice(PyObject *self, PyObject *args, void *wrapped)
2580{
2581 intintobjargproc func = (intintobjargproc)wrapped;
2582 int i, j, res;
2583
2584 if (!PyArg_ParseTuple(args, "ii", &i, &j))
2585 return NULL;
2586 res = (*func)(self, i, j, NULL);
2587 if (res == -1 && PyErr_Occurred())
2588 return NULL;
2589 Py_INCREF(Py_None);
2590 return Py_None;
2591}
2592
Tim Peters6d6c1a32001-08-02 04:15:00 +00002593/* XXX objobjproc is a misnomer; should be objargpred */
2594static PyObject *
2595wrap_objobjproc(PyObject *self, PyObject *args, void *wrapped)
2596{
2597 objobjproc func = (objobjproc)wrapped;
2598 int res;
2599 PyObject *value;
2600
2601 if (!PyArg_ParseTuple(args, "O", &value))
2602 return NULL;
2603 res = (*func)(self, value);
2604 if (res == -1 && PyErr_Occurred())
2605 return NULL;
2606 return PyInt_FromLong((long)res);
2607}
2608
Tim Peters6d6c1a32001-08-02 04:15:00 +00002609static PyObject *
2610wrap_objobjargproc(PyObject *self, PyObject *args, void *wrapped)
2611{
2612 objobjargproc func = (objobjargproc)wrapped;
2613 int res;
2614 PyObject *key, *value;
2615
2616 if (!PyArg_ParseTuple(args, "OO", &key, &value))
2617 return NULL;
2618 res = (*func)(self, key, value);
2619 if (res == -1 && PyErr_Occurred())
2620 return NULL;
2621 Py_INCREF(Py_None);
2622 return Py_None;
2623}
2624
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002625static PyObject *
2626wrap_delitem(PyObject *self, PyObject *args, void *wrapped)
2627{
2628 objobjargproc func = (objobjargproc)wrapped;
2629 int res;
2630 PyObject *key;
2631
2632 if (!PyArg_ParseTuple(args, "O", &key))
2633 return NULL;
2634 res = (*func)(self, key, NULL);
2635 if (res == -1 && PyErr_Occurred())
2636 return NULL;
2637 Py_INCREF(Py_None);
2638 return Py_None;
2639}
2640
Tim Peters6d6c1a32001-08-02 04:15:00 +00002641static PyObject *
2642wrap_cmpfunc(PyObject *self, PyObject *args, void *wrapped)
2643{
2644 cmpfunc func = (cmpfunc)wrapped;
2645 int res;
2646 PyObject *other;
2647
2648 if (!PyArg_ParseTuple(args, "O", &other))
2649 return NULL;
Guido van Rossum3d45d8f2001-09-24 18:47:40 +00002650 if (other->ob_type->tp_compare != func &&
2651 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossumceccae52001-09-18 20:03:57 +00002652 PyErr_Format(
2653 PyExc_TypeError,
2654 "%s.__cmp__(x,y) requires y to be a '%s', not a '%s'",
2655 self->ob_type->tp_name,
2656 self->ob_type->tp_name,
2657 other->ob_type->tp_name);
2658 return NULL;
2659 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002660 res = (*func)(self, other);
2661 if (PyErr_Occurred())
2662 return NULL;
2663 return PyInt_FromLong((long)res);
2664}
2665
Tim Peters6d6c1a32001-08-02 04:15:00 +00002666static PyObject *
2667wrap_setattr(PyObject *self, PyObject *args, void *wrapped)
2668{
2669 setattrofunc func = (setattrofunc)wrapped;
2670 int res;
2671 PyObject *name, *value;
2672
2673 if (!PyArg_ParseTuple(args, "OO", &name, &value))
2674 return NULL;
2675 res = (*func)(self, name, value);
2676 if (res < 0)
2677 return NULL;
2678 Py_INCREF(Py_None);
2679 return Py_None;
2680}
2681
2682static PyObject *
2683wrap_delattr(PyObject *self, PyObject *args, void *wrapped)
2684{
2685 setattrofunc func = (setattrofunc)wrapped;
2686 int res;
2687 PyObject *name;
2688
2689 if (!PyArg_ParseTuple(args, "O", &name))
2690 return NULL;
2691 res = (*func)(self, name, NULL);
2692 if (res < 0)
2693 return NULL;
2694 Py_INCREF(Py_None);
2695 return Py_None;
2696}
2697
Tim Peters6d6c1a32001-08-02 04:15:00 +00002698static PyObject *
2699wrap_hashfunc(PyObject *self, PyObject *args, void *wrapped)
2700{
2701 hashfunc func = (hashfunc)wrapped;
2702 long res;
2703
2704 if (!PyArg_ParseTuple(args, ""))
2705 return NULL;
2706 res = (*func)(self);
2707 if (res == -1 && PyErr_Occurred())
2708 return NULL;
2709 return PyInt_FromLong(res);
2710}
2711
Tim Peters6d6c1a32001-08-02 04:15:00 +00002712static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00002713wrap_call(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002714{
2715 ternaryfunc func = (ternaryfunc)wrapped;
2716
Guido van Rossumc8e56452001-10-22 00:43:43 +00002717 return (*func)(self, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002718}
2719
Tim Peters6d6c1a32001-08-02 04:15:00 +00002720static PyObject *
2721wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op)
2722{
2723 richcmpfunc func = (richcmpfunc)wrapped;
2724 PyObject *other;
2725
2726 if (!PyArg_ParseTuple(args, "O", &other))
2727 return NULL;
2728 return (*func)(self, other, op);
2729}
2730
2731#undef RICHCMP_WRAPPER
2732#define RICHCMP_WRAPPER(NAME, OP) \
2733static PyObject * \
2734richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \
2735{ \
2736 return wrap_richcmpfunc(self, args, wrapped, OP); \
2737}
2738
Jack Jansen8e938b42001-08-08 15:29:49 +00002739RICHCMP_WRAPPER(lt, Py_LT)
2740RICHCMP_WRAPPER(le, Py_LE)
2741RICHCMP_WRAPPER(eq, Py_EQ)
2742RICHCMP_WRAPPER(ne, Py_NE)
2743RICHCMP_WRAPPER(gt, Py_GT)
2744RICHCMP_WRAPPER(ge, Py_GE)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002745
Tim Peters6d6c1a32001-08-02 04:15:00 +00002746static PyObject *
2747wrap_next(PyObject *self, PyObject *args, void *wrapped)
2748{
2749 unaryfunc func = (unaryfunc)wrapped;
2750 PyObject *res;
2751
2752 if (!PyArg_ParseTuple(args, ""))
2753 return NULL;
2754 res = (*func)(self);
2755 if (res == NULL && !PyErr_Occurred())
2756 PyErr_SetNone(PyExc_StopIteration);
2757 return res;
2758}
2759
Tim Peters6d6c1a32001-08-02 04:15:00 +00002760static PyObject *
2761wrap_descr_get(PyObject *self, PyObject *args, void *wrapped)
2762{
2763 descrgetfunc func = (descrgetfunc)wrapped;
2764 PyObject *obj;
2765 PyObject *type = NULL;
2766
2767 if (!PyArg_ParseTuple(args, "O|O", &obj, &type))
2768 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002769 return (*func)(self, obj, type);
2770}
2771
Tim Peters6d6c1a32001-08-02 04:15:00 +00002772static PyObject *
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002773wrap_descr_set(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002774{
2775 descrsetfunc func = (descrsetfunc)wrapped;
2776 PyObject *obj, *value;
2777 int ret;
2778
2779 if (!PyArg_ParseTuple(args, "OO", &obj, &value))
2780 return NULL;
2781 ret = (*func)(self, obj, value);
2782 if (ret < 0)
2783 return NULL;
2784 Py_INCREF(Py_None);
2785 return Py_None;
2786}
2787
Tim Peters6d6c1a32001-08-02 04:15:00 +00002788static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00002789wrap_init(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002790{
2791 initproc func = (initproc)wrapped;
2792
Guido van Rossumc8e56452001-10-22 00:43:43 +00002793 if (func(self, args, kwds) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002794 return NULL;
2795 Py_INCREF(Py_None);
2796 return Py_None;
2797}
2798
Tim Peters6d6c1a32001-08-02 04:15:00 +00002799static PyObject *
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002800tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002801{
Barry Warsaw60f01882001-08-22 19:24:42 +00002802 PyTypeObject *type, *subtype, *staticbase;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002803 PyObject *arg0, *res;
2804
2805 if (self == NULL || !PyType_Check(self))
2806 Py_FatalError("__new__() called with non-type 'self'");
2807 type = (PyTypeObject *)self;
2808 if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002809 PyErr_Format(PyExc_TypeError,
2810 "%s.__new__(): not enough arguments",
2811 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002812 return NULL;
2813 }
2814 arg0 = PyTuple_GET_ITEM(args, 0);
2815 if (!PyType_Check(arg0)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002816 PyErr_Format(PyExc_TypeError,
2817 "%s.__new__(X): X is not a type object (%s)",
2818 type->tp_name,
2819 arg0->ob_type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002820 return NULL;
2821 }
2822 subtype = (PyTypeObject *)arg0;
2823 if (!PyType_IsSubtype(subtype, type)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002824 PyErr_Format(PyExc_TypeError,
2825 "%s.__new__(%s): %s is not a subtype of %s",
2826 type->tp_name,
2827 subtype->tp_name,
2828 subtype->tp_name,
2829 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002830 return NULL;
2831 }
Barry Warsaw60f01882001-08-22 19:24:42 +00002832
2833 /* Check that the use doesn't do something silly and unsafe like
Tim Petersa427a2b2001-10-29 22:25:45 +00002834 object.__new__(dict). To do this, we check that the
Barry Warsaw60f01882001-08-22 19:24:42 +00002835 most derived base that's not a heap type is this type. */
2836 staticbase = subtype;
2837 while (staticbase && (staticbase->tp_flags & Py_TPFLAGS_HEAPTYPE))
2838 staticbase = staticbase->tp_base;
Guido van Rossuma8c60f42001-09-14 19:43:36 +00002839 if (staticbase->tp_new != type->tp_new) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002840 PyErr_Format(PyExc_TypeError,
2841 "%s.__new__(%s) is not safe, use %s.__new__()",
2842 type->tp_name,
2843 subtype->tp_name,
2844 staticbase == NULL ? "?" : staticbase->tp_name);
2845 return NULL;
2846 }
2847
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002848 args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
2849 if (args == NULL)
2850 return NULL;
2851 res = type->tp_new(subtype, args, kwds);
2852 Py_DECREF(args);
2853 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002854}
2855
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002856static struct PyMethodDef tp_new_methoddef[] = {
2857 {"__new__", (PyCFunction)tp_new_wrapper, METH_KEYWORDS,
2858 "T.__new__(S, ...) -> a new object with type S, a subtype of T"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002859 {0}
2860};
2861
2862static int
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002863add_tp_new_wrapper(PyTypeObject *type)
2864{
Guido van Rossumf040ede2001-08-07 16:40:56 +00002865 PyObject *func;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002866
Guido van Rossum687ae002001-10-15 22:03:32 +00002867 if (PyDict_GetItemString(type->tp_dict, "__new__") != NULL)
Guido van Rossumf040ede2001-08-07 16:40:56 +00002868 return 0;
2869 func = PyCFunction_New(tp_new_methoddef, (PyObject *)type);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002870 if (func == NULL)
2871 return -1;
Guido van Rossum687ae002001-10-15 22:03:32 +00002872 return PyDict_SetItemString(type->tp_dict, "__new__", func);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002873}
2874
Guido van Rossumf040ede2001-08-07 16:40:56 +00002875/* Slot wrappers that call the corresponding __foo__ slot. See comments
2876 below at override_slots() for more explanation. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002877
Guido van Rossumdc91b992001-08-08 22:26:22 +00002878#define SLOT0(FUNCNAME, OPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002879static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002880FUNCNAME(PyObject *self) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002881{ \
Guido van Rossum5592e4d2001-08-28 18:28:21 +00002882 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00002883 return call_method(self, OPSTR, &cache_str, "()"); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002884}
2885
Guido van Rossumdc91b992001-08-08 22:26:22 +00002886#define SLOT1(FUNCNAME, OPSTR, ARG1TYPE, ARGCODES) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002887static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002888FUNCNAME(PyObject *self, ARG1TYPE arg1) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002889{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00002890 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00002891 return call_method(self, OPSTR, &cache_str, "(" ARGCODES ")", arg1); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002892}
2893
Guido van Rossumdc91b992001-08-08 22:26:22 +00002894
2895#define SLOT1BINFULL(FUNCNAME, TESTFUNC, SLOTNAME, OPSTR, ROPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002896static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002897FUNCNAME(PyObject *self, PyObject *other) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002898{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00002899 static PyObject *cache_str, *rcache_str; \
Guido van Rossum55f20992001-10-01 17:18:22 +00002900 int do_other = self->ob_type != other->ob_type && \
2901 other->ob_type->tp_as_number != NULL && \
2902 other->ob_type->tp_as_number->SLOTNAME == TESTFUNC; \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002903 if (self->ob_type->tp_as_number != NULL && \
2904 self->ob_type->tp_as_number->SLOTNAME == TESTFUNC) { \
2905 PyObject *r; \
Guido van Rossum55f20992001-10-01 17:18:22 +00002906 if (do_other && \
2907 PyType_IsSubtype(other->ob_type, self->ob_type)) { \
2908 r = call_maybe( \
2909 other, ROPSTR, &rcache_str, "(O)", self); \
2910 if (r != Py_NotImplemented) \
2911 return r; \
2912 Py_DECREF(r); \
2913 do_other = 0; \
2914 } \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00002915 r = call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00002916 self, OPSTR, &cache_str, "(O)", other); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002917 if (r != Py_NotImplemented || \
2918 other->ob_type == self->ob_type) \
2919 return r; \
2920 Py_DECREF(r); \
2921 } \
Guido van Rossum55f20992001-10-01 17:18:22 +00002922 if (do_other) { \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00002923 return call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00002924 other, ROPSTR, &rcache_str, "(O)", self); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002925 } \
2926 Py_INCREF(Py_NotImplemented); \
2927 return Py_NotImplemented; \
2928}
2929
2930#define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) \
2931 SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR)
2932
2933#define SLOT2(FUNCNAME, OPSTR, ARG1TYPE, ARG2TYPE, ARGCODES) \
2934static PyObject * \
2935FUNCNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \
2936{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00002937 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00002938 return call_method(self, OPSTR, &cache_str, \
2939 "(" ARGCODES ")", arg1, arg2); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002940}
2941
2942static int
2943slot_sq_length(PyObject *self)
2944{
Guido van Rossum2730b132001-08-28 18:22:14 +00002945 static PyObject *len_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00002946 PyObject *res = call_method(self, "__len__", &len_str, "()");
Guido van Rossum26111622001-10-01 16:42:49 +00002947 int len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002948
2949 if (res == NULL)
2950 return -1;
Guido van Rossum26111622001-10-01 16:42:49 +00002951 len = (int)PyInt_AsLong(res);
2952 Py_DECREF(res);
2953 return len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002954}
2955
Guido van Rossumdc91b992001-08-08 22:26:22 +00002956SLOT1(slot_sq_concat, "__add__", PyObject *, "O")
2957SLOT1(slot_sq_repeat, "__mul__", int, "i")
Guido van Rossumf4593e02001-10-03 12:09:30 +00002958
2959/* Super-optimized version of slot_sq_item.
2960 Other slots could do the same... */
2961static PyObject *
2962slot_sq_item(PyObject *self, int i)
2963{
2964 static PyObject *getitem_str;
2965 PyObject *func, *args = NULL, *ival = NULL, *retval = NULL;
2966 descrgetfunc f;
2967
2968 if (getitem_str == NULL) {
2969 getitem_str = PyString_InternFromString("__getitem__");
2970 if (getitem_str == NULL)
2971 return NULL;
2972 }
2973 func = _PyType_Lookup(self->ob_type, getitem_str);
2974 if (func != NULL) {
Guido van Rossumf4593e02001-10-03 12:09:30 +00002975 if ((f = func->ob_type->tp_descr_get) == NULL)
2976 Py_INCREF(func);
2977 else
2978 func = f(func, self, (PyObject *)(self->ob_type));
2979 ival = PyInt_FromLong(i);
2980 if (ival != NULL) {
2981 args = PyTuple_New(1);
2982 if (args != NULL) {
2983 PyTuple_SET_ITEM(args, 0, ival);
2984 retval = PyObject_Call(func, args, NULL);
2985 Py_XDECREF(args);
2986 Py_XDECREF(func);
2987 return retval;
2988 }
2989 }
2990 }
2991 else {
2992 PyErr_SetObject(PyExc_AttributeError, getitem_str);
2993 }
2994 Py_XDECREF(args);
2995 Py_XDECREF(ival);
2996 Py_XDECREF(func);
2997 return NULL;
2998}
2999
Guido van Rossumdc91b992001-08-08 22:26:22 +00003000SLOT2(slot_sq_slice, "__getslice__", int, int, "ii")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003001
3002static int
3003slot_sq_ass_item(PyObject *self, int index, PyObject *value)
3004{
3005 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003006 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003007
3008 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003009 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003010 "(i)", index);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003011 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003012 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003013 "(iO)", index, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003014 if (res == NULL)
3015 return -1;
3016 Py_DECREF(res);
3017 return 0;
3018}
3019
3020static int
3021slot_sq_ass_slice(PyObject *self, int i, int j, PyObject *value)
3022{
3023 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003024 static PyObject *delslice_str, *setslice_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003025
3026 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003027 res = call_method(self, "__delslice__", &delslice_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003028 "(ii)", i, j);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003029 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003030 res = call_method(self, "__setslice__", &setslice_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003031 "(iiO)", i, j, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003032 if (res == NULL)
3033 return -1;
3034 Py_DECREF(res);
3035 return 0;
3036}
3037
3038static int
3039slot_sq_contains(PyObject *self, PyObject *value)
3040{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003041 PyObject *func, *res, *args;
Guido van Rossum60718732001-08-28 17:47:51 +00003042 static PyObject *contains_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003043
Guido van Rossum55f20992001-10-01 17:18:22 +00003044 func = lookup_maybe(self, "__contains__", &contains_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003045
3046 if (func != NULL) {
3047 args = Py_BuildValue("(O)", value);
3048 if (args == NULL)
3049 res = NULL;
3050 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00003051 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003052 Py_DECREF(args);
3053 }
3054 Py_DECREF(func);
3055 if (res == NULL)
3056 return -1;
3057 return PyObject_IsTrue(res);
3058 }
Guido van Rossum55f20992001-10-01 17:18:22 +00003059 else if (PyErr_Occurred())
3060 return -1;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003061 else {
Tim Peters16a77ad2001-09-08 04:00:12 +00003062 return _PySequence_IterSearch(self, value,
3063 PY_ITERSEARCH_CONTAINS);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003064 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003065}
3066
Guido van Rossumdc91b992001-08-08 22:26:22 +00003067SLOT1(slot_sq_inplace_concat, "__iadd__", PyObject *, "O")
3068SLOT1(slot_sq_inplace_repeat, "__imul__", int, "i")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003069
3070#define slot_mp_length slot_sq_length
3071
Guido van Rossumdc91b992001-08-08 22:26:22 +00003072SLOT1(slot_mp_subscript, "__getitem__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003073
3074static int
3075slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value)
3076{
3077 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003078 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003079
3080 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003081 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003082 "(O)", key);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003083 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003084 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003085 "(OO)", key, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003086 if (res == NULL)
3087 return -1;
3088 Py_DECREF(res);
3089 return 0;
3090}
3091
Guido van Rossumdc91b992001-08-08 22:26:22 +00003092SLOT1BIN(slot_nb_add, nb_add, "__add__", "__radd__")
3093SLOT1BIN(slot_nb_subtract, nb_subtract, "__sub__", "__rsub__")
3094SLOT1BIN(slot_nb_multiply, nb_multiply, "__mul__", "__rmul__")
3095SLOT1BIN(slot_nb_divide, nb_divide, "__div__", "__rdiv__")
3096SLOT1BIN(slot_nb_remainder, nb_remainder, "__mod__", "__rmod__")
3097SLOT1BIN(slot_nb_divmod, nb_divmod, "__divmod__", "__rdivmod__")
3098
3099staticforward PyObject *slot_nb_power(PyObject *, PyObject *, PyObject *);
3100
3101SLOT1BINFULL(slot_nb_power_binary, slot_nb_power,
3102 nb_power, "__pow__", "__rpow__")
3103
3104static PyObject *
3105slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus)
3106{
Guido van Rossum2730b132001-08-28 18:22:14 +00003107 static PyObject *pow_str;
3108
Guido van Rossumdc91b992001-08-08 22:26:22 +00003109 if (modulus == Py_None)
3110 return slot_nb_power_binary(self, other);
Guido van Rossum23094982002-06-10 14:30:43 +00003111 /* Three-arg power doesn't use __rpow__. But ternary_op
3112 can call this when the second argument's type uses
3113 slot_nb_power, so check before calling self.__pow__. */
3114 if (self->ob_type->tp_as_number != NULL &&
3115 self->ob_type->tp_as_number->nb_power == slot_nb_power) {
3116 return call_method(self, "__pow__", &pow_str,
3117 "(OO)", other, modulus);
3118 }
3119 Py_INCREF(Py_NotImplemented);
3120 return Py_NotImplemented;
Guido van Rossumdc91b992001-08-08 22:26:22 +00003121}
3122
3123SLOT0(slot_nb_negative, "__neg__")
3124SLOT0(slot_nb_positive, "__pos__")
3125SLOT0(slot_nb_absolute, "__abs__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003126
3127static int
3128slot_nb_nonzero(PyObject *self)
3129{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003130 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003131 static PyObject *nonzero_str, *len_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003132
Guido van Rossum55f20992001-10-01 17:18:22 +00003133 func = lookup_maybe(self, "__nonzero__", &nonzero_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003134 if (func == NULL) {
Guido van Rossum55f20992001-10-01 17:18:22 +00003135 if (PyErr_Occurred())
Guido van Rossumb8f63662001-08-15 23:57:02 +00003136 return -1;
Guido van Rossum55f20992001-10-01 17:18:22 +00003137 func = lookup_maybe(self, "__len__", &len_str);
3138 if (func == NULL) {
3139 if (PyErr_Occurred())
3140 return -1;
3141 else
3142 return 1;
3143 }
Guido van Rossumb8f63662001-08-15 23:57:02 +00003144 }
Guido van Rossum55f20992001-10-01 17:18:22 +00003145 res = PyObject_CallObject(func, NULL);
3146 Py_DECREF(func);
3147 if (res == NULL)
3148 return -1;
3149 return PyObject_IsTrue(res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003150}
3151
Guido van Rossumdc91b992001-08-08 22:26:22 +00003152SLOT0(slot_nb_invert, "__invert__")
3153SLOT1BIN(slot_nb_lshift, nb_lshift, "__lshift__", "__rlshift__")
3154SLOT1BIN(slot_nb_rshift, nb_rshift, "__rshift__", "__rrshift__")
3155SLOT1BIN(slot_nb_and, nb_and, "__and__", "__rand__")
3156SLOT1BIN(slot_nb_xor, nb_xor, "__xor__", "__rxor__")
3157SLOT1BIN(slot_nb_or, nb_or, "__or__", "__ror__")
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003158
3159static int
3160slot_nb_coerce(PyObject **a, PyObject **b)
3161{
3162 static PyObject *coerce_str;
3163 PyObject *self = *a, *other = *b;
3164
3165 if (self->ob_type->tp_as_number != NULL &&
3166 self->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
3167 PyObject *r;
3168 r = call_maybe(
3169 self, "__coerce__", &coerce_str, "(O)", other);
3170 if (r == NULL)
3171 return -1;
3172 if (r == Py_NotImplemented) {
3173 Py_DECREF(r);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003174 }
Guido van Rossum55f20992001-10-01 17:18:22 +00003175 else {
3176 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
3177 PyErr_SetString(PyExc_TypeError,
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003178 "__coerce__ didn't return a 2-tuple");
Guido van Rossum55f20992001-10-01 17:18:22 +00003179 Py_DECREF(r);
3180 return -1;
3181 }
3182 *a = PyTuple_GET_ITEM(r, 0);
3183 Py_INCREF(*a);
3184 *b = PyTuple_GET_ITEM(r, 1);
3185 Py_INCREF(*b);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003186 Py_DECREF(r);
Guido van Rossum55f20992001-10-01 17:18:22 +00003187 return 0;
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003188 }
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003189 }
3190 if (other->ob_type->tp_as_number != NULL &&
3191 other->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
3192 PyObject *r;
3193 r = call_maybe(
3194 other, "__coerce__", &coerce_str, "(O)", self);
3195 if (r == NULL)
3196 return -1;
3197 if (r == Py_NotImplemented) {
3198 Py_DECREF(r);
3199 return 1;
3200 }
3201 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
3202 PyErr_SetString(PyExc_TypeError,
3203 "__coerce__ didn't return a 2-tuple");
3204 Py_DECREF(r);
3205 return -1;
3206 }
3207 *a = PyTuple_GET_ITEM(r, 1);
3208 Py_INCREF(*a);
3209 *b = PyTuple_GET_ITEM(r, 0);
3210 Py_INCREF(*b);
3211 Py_DECREF(r);
3212 return 0;
3213 }
3214 return 1;
3215}
3216
Guido van Rossumdc91b992001-08-08 22:26:22 +00003217SLOT0(slot_nb_int, "__int__")
3218SLOT0(slot_nb_long, "__long__")
3219SLOT0(slot_nb_float, "__float__")
3220SLOT0(slot_nb_oct, "__oct__")
3221SLOT0(slot_nb_hex, "__hex__")
3222SLOT1(slot_nb_inplace_add, "__iadd__", PyObject *, "O")
3223SLOT1(slot_nb_inplace_subtract, "__isub__", PyObject *, "O")
3224SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *, "O")
3225SLOT1(slot_nb_inplace_divide, "__idiv__", PyObject *, "O")
3226SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *, "O")
3227SLOT2(slot_nb_inplace_power, "__ipow__", PyObject *, PyObject *, "OO")
3228SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *, "O")
3229SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *, "O")
3230SLOT1(slot_nb_inplace_and, "__iand__", PyObject *, "O")
3231SLOT1(slot_nb_inplace_xor, "__ixor__", PyObject *, "O")
3232SLOT1(slot_nb_inplace_or, "__ior__", PyObject *, "O")
3233SLOT1BIN(slot_nb_floor_divide, nb_floor_divide,
3234 "__floordiv__", "__rfloordiv__")
3235SLOT1BIN(slot_nb_true_divide, nb_true_divide, "__truediv__", "__rtruediv__")
3236SLOT1(slot_nb_inplace_floor_divide, "__ifloordiv__", PyObject *, "O")
3237SLOT1(slot_nb_inplace_true_divide, "__itruediv__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003238
3239static int
Guido van Rossumb8f63662001-08-15 23:57:02 +00003240half_compare(PyObject *self, PyObject *other)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003241{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003242 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003243 static PyObject *cmp_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003244 int c;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003245
Guido van Rossum60718732001-08-28 17:47:51 +00003246 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003247 if (func == NULL) {
3248 PyErr_Clear();
3249 }
3250 else {
3251 args = Py_BuildValue("(O)", other);
3252 if (args == NULL)
3253 res = NULL;
3254 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00003255 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003256 Py_DECREF(args);
3257 }
3258 if (res != Py_NotImplemented) {
3259 if (res == NULL)
3260 return -2;
3261 c = PyInt_AsLong(res);
3262 Py_DECREF(res);
3263 if (c == -1 && PyErr_Occurred())
3264 return -2;
3265 return (c < 0) ? -1 : (c > 0) ? 1 : 0;
3266 }
3267 Py_DECREF(res);
3268 }
3269 return 2;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003270}
3271
Guido van Rossumab3b0342001-09-18 20:38:53 +00003272/* This slot is published for the benefit of try_3way_compare in object.c */
3273int
3274_PyObject_SlotCompare(PyObject *self, PyObject *other)
Guido van Rossumb8f63662001-08-15 23:57:02 +00003275{
3276 int c;
3277
Guido van Rossumab3b0342001-09-18 20:38:53 +00003278 if (self->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00003279 c = half_compare(self, other);
3280 if (c <= 1)
3281 return c;
3282 }
Guido van Rossumab3b0342001-09-18 20:38:53 +00003283 if (other->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00003284 c = half_compare(other, self);
3285 if (c < -1)
3286 return -2;
3287 if (c <= 1)
3288 return -c;
3289 }
3290 return (void *)self < (void *)other ? -1 :
3291 (void *)self > (void *)other ? 1 : 0;
3292}
3293
3294static PyObject *
3295slot_tp_repr(PyObject *self)
3296{
3297 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003298 static PyObject *repr_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003299
Guido van Rossum60718732001-08-28 17:47:51 +00003300 func = lookup_method(self, "__repr__", &repr_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003301 if (func != NULL) {
3302 res = PyEval_CallObject(func, NULL);
3303 Py_DECREF(func);
3304 return res;
3305 }
Barry Warsaw7ce36942001-08-24 18:34:26 +00003306 PyErr_Clear();
3307 return PyString_FromFormat("<%s object at %p>",
3308 self->ob_type->tp_name, self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003309}
3310
3311static PyObject *
3312slot_tp_str(PyObject *self)
3313{
3314 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003315 static PyObject *str_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003316
Guido van Rossum60718732001-08-28 17:47:51 +00003317 func = lookup_method(self, "__str__", &str_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003318 if (func != NULL) {
3319 res = PyEval_CallObject(func, NULL);
3320 Py_DECREF(func);
3321 return res;
3322 }
3323 else {
3324 PyErr_Clear();
3325 return slot_tp_repr(self);
3326 }
3327}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003328
3329static long
3330slot_tp_hash(PyObject *self)
3331{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003332 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003333 static PyObject *hash_str, *eq_str, *cmp_str;
3334
Tim Peters6d6c1a32001-08-02 04:15:00 +00003335 long h;
3336
Guido van Rossum60718732001-08-28 17:47:51 +00003337 func = lookup_method(self, "__hash__", &hash_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003338
3339 if (func != NULL) {
3340 res = PyEval_CallObject(func, NULL);
3341 Py_DECREF(func);
3342 if (res == NULL)
3343 return -1;
3344 h = PyInt_AsLong(res);
3345 }
3346 else {
3347 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00003348 func = lookup_method(self, "__eq__", &eq_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003349 if (func == NULL) {
3350 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00003351 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003352 }
3353 if (func != NULL) {
3354 Py_DECREF(func);
3355 PyErr_SetString(PyExc_TypeError, "unhashable type");
3356 return -1;
3357 }
3358 PyErr_Clear();
3359 h = _Py_HashPointer((void *)self);
3360 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003361 if (h == -1 && !PyErr_Occurred())
3362 h = -2;
3363 return h;
3364}
3365
3366static PyObject *
3367slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds)
3368{
Guido van Rossum60718732001-08-28 17:47:51 +00003369 static PyObject *call_str;
3370 PyObject *meth = lookup_method(self, "__call__", &call_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003371 PyObject *res;
3372
3373 if (meth == NULL)
3374 return NULL;
3375 res = PyObject_Call(meth, args, kwds);
3376 Py_DECREF(meth);
3377 return res;
3378}
3379
Guido van Rossum14a6f832001-10-17 13:59:09 +00003380/* There are two slot dispatch functions for tp_getattro.
3381
3382 - slot_tp_getattro() is used when __getattribute__ is overridden
3383 but no __getattr__ hook is present;
3384
3385 - slot_tp_getattr_hook() is used when a __getattr__ hook is present.
3386
Guido van Rossumc334df52002-04-04 23:44:47 +00003387 The code in update_one_slot() always installs slot_tp_getattr_hook(); this
3388 detects the absence of __getattr__ and then installs the simpler slot if
3389 necessary. */
Guido van Rossum14a6f832001-10-17 13:59:09 +00003390
Tim Peters6d6c1a32001-08-02 04:15:00 +00003391static PyObject *
3392slot_tp_getattro(PyObject *self, PyObject *name)
3393{
Guido van Rossum14a6f832001-10-17 13:59:09 +00003394 static PyObject *getattribute_str = NULL;
3395 return call_method(self, "__getattribute__", &getattribute_str,
3396 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003397}
3398
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003399static PyObject *
3400slot_tp_getattr_hook(PyObject *self, PyObject *name)
3401{
3402 PyTypeObject *tp = self->ob_type;
3403 PyObject *getattr, *getattribute, *res;
3404 static PyObject *getattribute_str = NULL;
3405 static PyObject *getattr_str = NULL;
3406
3407 if (getattr_str == NULL) {
3408 getattr_str = PyString_InternFromString("__getattr__");
3409 if (getattr_str == NULL)
3410 return NULL;
3411 }
3412 if (getattribute_str == NULL) {
3413 getattribute_str =
3414 PyString_InternFromString("__getattribute__");
3415 if (getattribute_str == NULL)
3416 return NULL;
3417 }
3418 getattr = _PyType_Lookup(tp, getattr_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00003419 if (getattr == NULL) {
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003420 /* No __getattr__ hook: use a simpler dispatcher */
3421 tp->tp_getattro = slot_tp_getattro;
3422 return slot_tp_getattro(self, name);
3423 }
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003424 getattribute = _PyType_Lookup(tp, getattribute_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00003425 if (getattribute == NULL ||
3426 (getattribute->ob_type == &PyWrapperDescr_Type &&
3427 ((PyWrapperDescrObject *)getattribute)->d_wrapped ==
3428 (void *)PyObject_GenericGetAttr))
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003429 res = PyObject_GenericGetAttr(self, name);
3430 else
3431 res = PyObject_CallFunction(getattribute, "OO", self, name);
Guido van Rossum14a6f832001-10-17 13:59:09 +00003432 if (res == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) {
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003433 PyErr_Clear();
3434 res = PyObject_CallFunction(getattr, "OO", self, name);
3435 }
3436 return res;
3437}
3438
Tim Peters6d6c1a32001-08-02 04:15:00 +00003439static int
3440slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value)
3441{
3442 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003443 static PyObject *delattr_str, *setattr_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003444
3445 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003446 res = call_method(self, "__delattr__", &delattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003447 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003448 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003449 res = call_method(self, "__setattr__", &setattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003450 "(OO)", name, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003451 if (res == NULL)
3452 return -1;
3453 Py_DECREF(res);
3454 return 0;
3455}
3456
3457/* Map rich comparison operators to their __xx__ namesakes */
3458static char *name_op[] = {
3459 "__lt__",
3460 "__le__",
3461 "__eq__",
3462 "__ne__",
3463 "__gt__",
3464 "__ge__",
3465};
3466
3467static PyObject *
Guido van Rossumb8f63662001-08-15 23:57:02 +00003468half_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003469{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003470 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003471 static PyObject *op_str[6];
Tim Peters6d6c1a32001-08-02 04:15:00 +00003472
Guido van Rossum60718732001-08-28 17:47:51 +00003473 func = lookup_method(self, name_op[op], &op_str[op]);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003474 if (func == NULL) {
3475 PyErr_Clear();
3476 Py_INCREF(Py_NotImplemented);
3477 return Py_NotImplemented;
3478 }
3479 args = Py_BuildValue("(O)", other);
3480 if (args == NULL)
3481 res = NULL;
3482 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00003483 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003484 Py_DECREF(args);
3485 }
3486 Py_DECREF(func);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003487 return res;
3488}
3489
Guido van Rossumb8f63662001-08-15 23:57:02 +00003490/* Map rich comparison operators to their swapped version, e.g. LT --> GT */
3491static int swapped_op[] = {Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE};
3492
3493static PyObject *
3494slot_tp_richcompare(PyObject *self, PyObject *other, int op)
3495{
3496 PyObject *res;
3497
3498 if (self->ob_type->tp_richcompare == slot_tp_richcompare) {
3499 res = half_richcompare(self, other, op);
3500 if (res != Py_NotImplemented)
3501 return res;
3502 Py_DECREF(res);
3503 }
3504 if (other->ob_type->tp_richcompare == slot_tp_richcompare) {
3505 res = half_richcompare(other, self, swapped_op[op]);
3506 if (res != Py_NotImplemented) {
3507 return res;
3508 }
3509 Py_DECREF(res);
3510 }
3511 Py_INCREF(Py_NotImplemented);
3512 return Py_NotImplemented;
3513}
3514
3515static PyObject *
3516slot_tp_iter(PyObject *self)
3517{
3518 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003519 static PyObject *iter_str, *getitem_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003520
Guido van Rossum60718732001-08-28 17:47:51 +00003521 func = lookup_method(self, "__iter__", &iter_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003522 if (func != NULL) {
3523 res = PyObject_CallObject(func, NULL);
3524 Py_DECREF(func);
3525 return res;
3526 }
3527 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00003528 func = lookup_method(self, "__getitem__", &getitem_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003529 if (func == NULL) {
Guido van Rossumd4641072002-04-03 02:13:37 +00003530 PyErr_SetString(PyExc_TypeError,
3531 "iteration over non-sequence");
Guido van Rossumb8f63662001-08-15 23:57:02 +00003532 return NULL;
3533 }
3534 Py_DECREF(func);
3535 return PySeqIter_New(self);
3536}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003537
3538static PyObject *
3539slot_tp_iternext(PyObject *self)
3540{
Guido van Rossum2730b132001-08-28 18:22:14 +00003541 static PyObject *next_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00003542 return call_method(self, "next", &next_str, "()");
Tim Peters6d6c1a32001-08-02 04:15:00 +00003543}
3544
Guido van Rossum1a493502001-08-17 16:47:50 +00003545static PyObject *
3546slot_tp_descr_get(PyObject *self, PyObject *obj, PyObject *type)
3547{
3548 PyTypeObject *tp = self->ob_type;
3549 PyObject *get;
3550 static PyObject *get_str = NULL;
3551
3552 if (get_str == NULL) {
3553 get_str = PyString_InternFromString("__get__");
3554 if (get_str == NULL)
3555 return NULL;
3556 }
3557 get = _PyType_Lookup(tp, get_str);
3558 if (get == NULL) {
3559 /* Avoid further slowdowns */
3560 if (tp->tp_descr_get == slot_tp_descr_get)
3561 tp->tp_descr_get = NULL;
3562 Py_INCREF(self);
3563 return self;
3564 }
Guido van Rossum2c252392001-08-24 10:13:31 +00003565 if (obj == NULL)
3566 obj = Py_None;
3567 if (type == NULL)
3568 type = Py_None;
Guido van Rossum1a493502001-08-17 16:47:50 +00003569 return PyObject_CallFunction(get, "OOO", self, obj, type);
3570}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003571
3572static int
3573slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value)
3574{
Guido van Rossum2c252392001-08-24 10:13:31 +00003575 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003576 static PyObject *del_str, *set_str;
Guido van Rossum2c252392001-08-24 10:13:31 +00003577
3578 if (value == NULL)
Guido van Rossum1d5b3f22001-12-03 00:08:33 +00003579 res = call_method(self, "__delete__", &del_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003580 "(O)", target);
Guido van Rossum2c252392001-08-24 10:13:31 +00003581 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003582 res = call_method(self, "__set__", &set_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003583 "(OO)", target, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003584 if (res == NULL)
3585 return -1;
3586 Py_DECREF(res);
3587 return 0;
3588}
3589
3590static int
3591slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds)
3592{
Guido van Rossum60718732001-08-28 17:47:51 +00003593 static PyObject *init_str;
3594 PyObject *meth = lookup_method(self, "__init__", &init_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003595 PyObject *res;
3596
3597 if (meth == NULL)
3598 return -1;
3599 res = PyObject_Call(meth, args, kwds);
3600 Py_DECREF(meth);
3601 if (res == NULL)
3602 return -1;
3603 Py_DECREF(res);
3604 return 0;
3605}
3606
3607static PyObject *
3608slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3609{
3610 PyObject *func = PyObject_GetAttrString((PyObject *)type, "__new__");
3611 PyObject *newargs, *x;
3612 int i, n;
3613
3614 if (func == NULL)
3615 return NULL;
3616 assert(PyTuple_Check(args));
3617 n = PyTuple_GET_SIZE(args);
3618 newargs = PyTuple_New(n+1);
3619 if (newargs == NULL)
3620 return NULL;
3621 Py_INCREF(type);
3622 PyTuple_SET_ITEM(newargs, 0, (PyObject *)type);
3623 for (i = 0; i < n; i++) {
3624 x = PyTuple_GET_ITEM(args, i);
3625 Py_INCREF(x);
3626 PyTuple_SET_ITEM(newargs, i+1, x);
3627 }
3628 x = PyObject_Call(func, newargs, kwds);
Guido van Rossum25d18072001-10-01 15:55:28 +00003629 Py_DECREF(newargs);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003630 Py_DECREF(func);
3631 return x;
3632}
3633
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003634
3635/* Table mapping __foo__ names to tp_foo offsets and slot_tp_foo wrapper
3636 functions. The offsets here are relative to the 'etype' structure, which
3637 incorporates the additional structures used for numbers, sequences and
3638 mappings. Note that multiple names may map to the same slot (e.g. __eq__,
3639 __ne__ etc. all map to tp_richcompare) and one name may map to multiple
Guido van Rossumc334df52002-04-04 23:44:47 +00003640 slots (e.g. __str__ affects tp_str as well as tp_repr). The table is
3641 terminated with an all-zero entry. (This table is further initialized and
3642 sorted in init_slotdefs() below.) */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003643
Guido van Rossum6d204072001-10-21 00:44:31 +00003644typedef struct wrapperbase slotdef;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003645
3646#undef TPSLOT
Guido van Rossumc8e56452001-10-22 00:43:43 +00003647#undef FLSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003648#undef ETSLOT
3649#undef SQSLOT
3650#undef MPSLOT
3651#undef NBSLOT
Guido van Rossum6d204072001-10-21 00:44:31 +00003652#undef UNSLOT
3653#undef IBSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003654#undef BINSLOT
3655#undef RBINSLOT
3656
Guido van Rossum6d204072001-10-21 00:44:31 +00003657#define TPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3658 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, DOC}
Guido van Rossumc8e56452001-10-22 00:43:43 +00003659#define FLSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC, FLAGS) \
3660 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
3661 DOC, FLAGS}
Guido van Rossum6d204072001-10-21 00:44:31 +00003662#define ETSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3663 {NAME, offsetof(etype, SLOT), (void *)(FUNCTION), WRAPPER, DOC}
3664#define SQSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3665 ETSLOT(NAME, as_sequence.SLOT, FUNCTION, WRAPPER, DOC)
3666#define MPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3667 ETSLOT(NAME, as_mapping.SLOT, FUNCTION, WRAPPER, DOC)
3668#define NBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3669 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, DOC)
3670#define UNSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3671 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
3672 "x." NAME "() <==> " DOC)
3673#define IBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3674 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
3675 "x." NAME "(y) <==> x" DOC "y")
3676#define BINSLOT(NAME, SLOT, FUNCTION, DOC) \
3677 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
3678 "x." NAME "(y) <==> x" DOC "y")
3679#define RBINSLOT(NAME, SLOT, FUNCTION, DOC) \
3680 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
3681 "x." NAME "(y) <==> y" DOC "x")
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003682
3683static slotdef slotdefs[] = {
Guido van Rossum6d204072001-10-21 00:44:31 +00003684 SQSLOT("__len__", sq_length, slot_sq_length, wrap_inquiry,
3685 "x.__len__() <==> len(x)"),
3686 SQSLOT("__add__", sq_concat, slot_sq_concat, wrap_binaryfunc,
3687 "x.__add__(y) <==> x+y"),
3688 SQSLOT("__mul__", sq_repeat, slot_sq_repeat, wrap_intargfunc,
3689 "x.__mul__(n) <==> x*n"),
3690 SQSLOT("__rmul__", sq_repeat, slot_sq_repeat, wrap_intargfunc,
3691 "x.__rmul__(n) <==> n*x"),
3692 SQSLOT("__getitem__", sq_item, slot_sq_item, wrap_sq_item,
3693 "x.__getitem__(y) <==> x[y]"),
3694 SQSLOT("__getslice__", sq_slice, slot_sq_slice, wrap_intintargfunc,
3695 "x.__getslice__(i, j) <==> x[i:j]"),
3696 SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_setitem,
3697 "x.__setitem__(i, y) <==> x[i]=y"),
3698 SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_delitem,
3699 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003700 SQSLOT("__setslice__", sq_ass_slice, slot_sq_ass_slice,
Guido van Rossum6d204072001-10-21 00:44:31 +00003701 wrap_intintobjargproc,
3702 "x.__setslice__(i, j, y) <==> x[i:j]=y"),
3703 SQSLOT("__delslice__", sq_ass_slice, slot_sq_ass_slice, wrap_delslice,
3704 "x.__delslice__(i, j) <==> del x[i:j]"),
3705 SQSLOT("__contains__", sq_contains, slot_sq_contains, wrap_objobjproc,
3706 "x.__contains__(y) <==> y in x"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003707 SQSLOT("__iadd__", sq_inplace_concat, slot_sq_inplace_concat,
Guido van Rossum6d204072001-10-21 00:44:31 +00003708 wrap_binaryfunc, "x.__iadd__(y) <==> x+=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003709 SQSLOT("__imul__", sq_inplace_repeat, slot_sq_inplace_repeat,
Guido van Rossum6d204072001-10-21 00:44:31 +00003710 wrap_intargfunc, "x.__imul__(y) <==> x*=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003711
Guido van Rossum6d204072001-10-21 00:44:31 +00003712 MPSLOT("__len__", mp_length, slot_mp_length, wrap_inquiry,
3713 "x.__len__() <==> len(x)"),
Guido van Rossumfd38f8e2001-10-09 20:17:57 +00003714 MPSLOT("__getitem__", mp_subscript, slot_mp_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00003715 wrap_binaryfunc,
3716 "x.__getitem__(y) <==> x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003717 MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00003718 wrap_objobjargproc,
3719 "x.__setitem__(i, y) <==> x[i]=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003720 MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00003721 wrap_delitem,
3722 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003723
Guido van Rossum6d204072001-10-21 00:44:31 +00003724 BINSLOT("__add__", nb_add, slot_nb_add,
3725 "+"),
3726 RBINSLOT("__radd__", nb_add, slot_nb_add,
3727 "+"),
3728 BINSLOT("__sub__", nb_subtract, slot_nb_subtract,
3729 "-"),
3730 RBINSLOT("__rsub__", nb_subtract, slot_nb_subtract,
3731 "-"),
3732 BINSLOT("__mul__", nb_multiply, slot_nb_multiply,
3733 "*"),
3734 RBINSLOT("__rmul__", nb_multiply, slot_nb_multiply,
3735 "*"),
3736 BINSLOT("__div__", nb_divide, slot_nb_divide,
3737 "/"),
3738 RBINSLOT("__rdiv__", nb_divide, slot_nb_divide,
3739 "/"),
3740 BINSLOT("__mod__", nb_remainder, slot_nb_remainder,
3741 "%"),
3742 RBINSLOT("__rmod__", nb_remainder, slot_nb_remainder,
3743 "%"),
3744 BINSLOT("__divmod__", nb_divmod, slot_nb_divmod,
3745 "divmod(x, y)"),
3746 RBINSLOT("__rdivmod__", nb_divmod, slot_nb_divmod,
3747 "divmod(y, x)"),
3748 NBSLOT("__pow__", nb_power, slot_nb_power, wrap_ternaryfunc,
3749 "x.__pow__(y[, z]) <==> pow(x, y[, z])"),
3750 NBSLOT("__rpow__", nb_power, slot_nb_power, wrap_ternaryfunc_r,
3751 "y.__rpow__(x[, z]) <==> pow(x, y[, z])"),
3752 UNSLOT("__neg__", nb_negative, slot_nb_negative, wrap_unaryfunc, "-x"),
3753 UNSLOT("__pos__", nb_positive, slot_nb_positive, wrap_unaryfunc, "+x"),
3754 UNSLOT("__abs__", nb_absolute, slot_nb_absolute, wrap_unaryfunc,
3755 "abs(x)"),
Guido van Rossumdfce3bf2002-03-10 14:11:16 +00003756 UNSLOT("__nonzero__", nb_nonzero, slot_nb_nonzero, wrap_inquiry,
Guido van Rossum6d204072001-10-21 00:44:31 +00003757 "x != 0"),
3758 UNSLOT("__invert__", nb_invert, slot_nb_invert, wrap_unaryfunc, "~x"),
3759 BINSLOT("__lshift__", nb_lshift, slot_nb_lshift, "<<"),
3760 RBINSLOT("__rlshift__", nb_lshift, slot_nb_lshift, "<<"),
3761 BINSLOT("__rshift__", nb_rshift, slot_nb_rshift, ">>"),
3762 RBINSLOT("__rrshift__", nb_rshift, slot_nb_rshift, ">>"),
3763 BINSLOT("__and__", nb_and, slot_nb_and, "&"),
3764 RBINSLOT("__rand__", nb_and, slot_nb_and, "&"),
3765 BINSLOT("__xor__", nb_xor, slot_nb_xor, "^"),
3766 RBINSLOT("__rxor__", nb_xor, slot_nb_xor, "^"),
3767 BINSLOT("__or__", nb_or, slot_nb_or, "|"),
3768 RBINSLOT("__ror__", nb_or, slot_nb_or, "|"),
3769 NBSLOT("__coerce__", nb_coerce, slot_nb_coerce, wrap_coercefunc,
3770 "x.__coerce__(y) <==> coerce(x, y)"),
3771 UNSLOT("__int__", nb_int, slot_nb_int, wrap_unaryfunc,
3772 "int(x)"),
3773 UNSLOT("__long__", nb_long, slot_nb_long, wrap_unaryfunc,
3774 "long(x)"),
3775 UNSLOT("__float__", nb_float, slot_nb_float, wrap_unaryfunc,
3776 "float(x)"),
3777 UNSLOT("__oct__", nb_oct, slot_nb_oct, wrap_unaryfunc,
3778 "oct(x)"),
3779 UNSLOT("__hex__", nb_hex, slot_nb_hex, wrap_unaryfunc,
3780 "hex(x)"),
3781 IBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add,
3782 wrap_binaryfunc, "+"),
3783 IBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract,
3784 wrap_binaryfunc, "-"),
3785 IBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply,
3786 wrap_binaryfunc, "*"),
3787 IBSLOT("__idiv__", nb_inplace_divide, slot_nb_inplace_divide,
3788 wrap_binaryfunc, "/"),
3789 IBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder,
3790 wrap_binaryfunc, "%"),
3791 IBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power,
3792 wrap_ternaryfunc, "**"),
3793 IBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift,
3794 wrap_binaryfunc, "<<"),
3795 IBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift,
3796 wrap_binaryfunc, ">>"),
3797 IBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and,
3798 wrap_binaryfunc, "&"),
3799 IBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor,
3800 wrap_binaryfunc, "^"),
3801 IBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or,
3802 wrap_binaryfunc, "|"),
3803 BINSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
3804 RBINSLOT("__rfloordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
3805 BINSLOT("__truediv__", nb_true_divide, slot_nb_true_divide, "/"),
3806 RBINSLOT("__rtruediv__", nb_true_divide, slot_nb_true_divide, "/"),
3807 IBSLOT("__ifloordiv__", nb_inplace_floor_divide,
3808 slot_nb_inplace_floor_divide, wrap_binaryfunc, "//"),
3809 IBSLOT("__itruediv__", nb_inplace_true_divide,
3810 slot_nb_inplace_true_divide, wrap_binaryfunc, "/"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003811
Guido van Rossum6d204072001-10-21 00:44:31 +00003812 TPSLOT("__str__", tp_str, slot_tp_str, wrap_unaryfunc,
3813 "x.__str__() <==> str(x)"),
Guido van Rossumafe7a942001-10-29 14:33:44 +00003814 TPSLOT("__str__", tp_print, NULL, NULL, ""),
Guido van Rossum6d204072001-10-21 00:44:31 +00003815 TPSLOT("__repr__", tp_repr, slot_tp_repr, wrap_unaryfunc,
3816 "x.__repr__() <==> repr(x)"),
Guido van Rossumafe7a942001-10-29 14:33:44 +00003817 TPSLOT("__repr__", tp_print, NULL, NULL, ""),
Guido van Rossum6d204072001-10-21 00:44:31 +00003818 TPSLOT("__cmp__", tp_compare, _PyObject_SlotCompare, wrap_cmpfunc,
3819 "x.__cmp__(y) <==> cmp(x,y)"),
3820 TPSLOT("__hash__", tp_hash, slot_tp_hash, wrap_hashfunc,
3821 "x.__hash__() <==> hash(x)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00003822 FLSLOT("__call__", tp_call, slot_tp_call, (wrapperfunc)wrap_call,
3823 "x.__call__(...) <==> x(...)", PyWrapperFlag_KEYWORDS),
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003824 TPSLOT("__getattribute__", tp_getattro, slot_tp_getattr_hook,
Guido van Rossum6d204072001-10-21 00:44:31 +00003825 wrap_binaryfunc, "x.__getattribute__('name') <==> x.name"),
3826 TPSLOT("__getattribute__", tp_getattr, NULL, NULL, ""),
3827 TPSLOT("__getattr__", tp_getattro, slot_tp_getattr_hook, NULL, ""),
3828 TPSLOT("__getattr__", tp_getattr, NULL, NULL, ""),
3829 TPSLOT("__setattr__", tp_setattro, slot_tp_setattro, wrap_setattr,
3830 "x.__setattr__('name', value) <==> x.name = value"),
3831 TPSLOT("__setattr__", tp_setattr, NULL, NULL, ""),
3832 TPSLOT("__delattr__", tp_setattro, slot_tp_setattro, wrap_delattr,
3833 "x.__delattr__('name') <==> del x.name"),
3834 TPSLOT("__delattr__", tp_setattr, NULL, NULL, ""),
3835 TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare, richcmp_lt,
3836 "x.__lt__(y) <==> x<y"),
3837 TPSLOT("__le__", tp_richcompare, slot_tp_richcompare, richcmp_le,
3838 "x.__le__(y) <==> x<=y"),
3839 TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare, richcmp_eq,
3840 "x.__eq__(y) <==> x==y"),
3841 TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare, richcmp_ne,
3842 "x.__ne__(y) <==> x!=y"),
3843 TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare, richcmp_gt,
3844 "x.__gt__(y) <==> x>y"),
3845 TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare, richcmp_ge,
3846 "x.__ge__(y) <==> x>=y"),
3847 TPSLOT("__iter__", tp_iter, slot_tp_iter, wrap_unaryfunc,
3848 "x.__iter__() <==> iter(x)"),
3849 TPSLOT("next", tp_iternext, slot_tp_iternext, wrap_next,
3850 "x.next() -> the next value, or raise StopIteration"),
3851 TPSLOT("__get__", tp_descr_get, slot_tp_descr_get, wrap_descr_get,
3852 "descr.__get__(obj[, type]) -> value"),
3853 TPSLOT("__set__", tp_descr_set, slot_tp_descr_set, wrap_descr_set,
3854 "descr.__set__(obj, value)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00003855 FLSLOT("__init__", tp_init, slot_tp_init, (wrapperfunc)wrap_init,
Guido van Rossum6d204072001-10-21 00:44:31 +00003856 "x.__init__(...) initializes x; "
Guido van Rossumc8e56452001-10-22 00:43:43 +00003857 "see x.__class__.__doc__ for signature",
3858 PyWrapperFlag_KEYWORDS),
3859 TPSLOT("__new__", tp_new, slot_tp_new, NULL, ""),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003860 {NULL}
3861};
3862
Guido van Rossumc334df52002-04-04 23:44:47 +00003863/* Given a type pointer and an offset gotten from a slotdef entry, return a
3864 pointer to the actual slot. This is not quite the same as simply adding
3865 the offset to the type pointer, since it takes care to indirect through the
3866 proper indirection pointer (as_buffer, etc.); it returns NULL if the
3867 indirection pointer is NULL. */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003868static void **
3869slotptr(PyTypeObject *type, int offset)
3870{
3871 char *ptr;
3872
3873 assert(offset >= 0);
3874 assert(offset < offsetof(etype, as_buffer));
3875 if (offset >= offsetof(etype, as_mapping)) {
3876 ptr = (void *)type->tp_as_mapping;
3877 offset -= offsetof(etype, as_mapping);
3878 }
3879 else if (offset >= offsetof(etype, as_sequence)) {
3880 ptr = (void *)type->tp_as_sequence;
3881 offset -= offsetof(etype, as_sequence);
3882 }
3883 else if (offset >= offsetof(etype, as_number)) {
3884 ptr = (void *)type->tp_as_number;
3885 offset -= offsetof(etype, as_number);
3886 }
3887 else {
3888 ptr = (void *)type;
3889 }
3890 if (ptr != NULL)
3891 ptr += offset;
3892 return (void **)ptr;
3893}
Guido van Rossumf040ede2001-08-07 16:40:56 +00003894
Guido van Rossumc334df52002-04-04 23:44:47 +00003895/* Length of array of slotdef pointers used to store slots with the
3896 same __name__. There should be at most MAX_EQUIV-1 slotdef entries with
3897 the same __name__, for any __name__. Since that's a static property, it is
3898 appropriate to declare fixed-size arrays for this. */
3899#define MAX_EQUIV 10
3900
3901/* Return a slot pointer for a given name, but ONLY if the attribute has
3902 exactly one slot function. The name must be an interned string. */
3903static void **
3904resolve_slotdups(PyTypeObject *type, PyObject *name)
3905{
3906 /* XXX Maybe this could be optimized more -- but is it worth it? */
3907
3908 /* pname and ptrs act as a little cache */
3909 static PyObject *pname;
3910 static slotdef *ptrs[MAX_EQUIV];
3911 slotdef *p, **pp;
3912 void **res, **ptr;
3913
3914 if (pname != name) {
3915 /* Collect all slotdefs that match name into ptrs. */
3916 pname = name;
3917 pp = ptrs;
3918 for (p = slotdefs; p->name_strobj; p++) {
3919 if (p->name_strobj == name)
3920 *pp++ = p;
3921 }
3922 *pp = NULL;
3923 }
3924
3925 /* Look in all matching slots of the type; if exactly one of these has
3926 a filled-in slot, return its value. Otherwise return NULL. */
3927 res = NULL;
3928 for (pp = ptrs; *pp; pp++) {
3929 ptr = slotptr(type, (*pp)->offset);
3930 if (ptr == NULL || *ptr == NULL)
3931 continue;
3932 if (res != NULL)
3933 return NULL;
3934 res = ptr;
3935 }
3936 return res;
3937}
3938
3939/* Common code for update_these_slots() and fixup_slot_dispatchers(). This
3940 does some incredibly complex thinking and then sticks something into the
3941 slot. (It sees if the adjacent slotdefs for the same slot have conflicting
3942 interests, and then stores a generic wrapper or a specific function into
3943 the slot.) Return a pointer to the next slotdef with a different offset,
3944 because that's convenient for fixup_slot_dispatchers(). */
3945static slotdef *
3946update_one_slot(PyTypeObject *type, slotdef *p)
3947{
3948 PyObject *descr;
3949 PyWrapperDescrObject *d;
3950 void *generic = NULL, *specific = NULL;
3951 int use_generic = 0;
3952 int offset = p->offset;
3953 void **ptr = slotptr(type, offset);
3954
3955 if (ptr == NULL) {
3956 do {
3957 ++p;
3958 } while (p->offset == offset);
3959 return p;
3960 }
3961 do {
3962 descr = _PyType_Lookup(type, p->name_strobj);
3963 if (descr == NULL)
3964 continue;
3965 if (descr->ob_type == &PyWrapperDescr_Type) {
3966 void **tptr = resolve_slotdups(type, p->name_strobj);
3967 if (tptr == NULL || tptr == ptr)
3968 generic = p->function;
3969 d = (PyWrapperDescrObject *)descr;
3970 if (d->d_base->wrapper == p->wrapper &&
3971 PyType_IsSubtype(type, d->d_type))
3972 {
3973 if (specific == NULL ||
3974 specific == d->d_wrapped)
3975 specific = d->d_wrapped;
3976 else
3977 use_generic = 1;
3978 }
3979 }
3980 else {
3981 use_generic = 1;
3982 generic = p->function;
3983 }
3984 } while ((++p)->offset == offset);
3985 if (specific && !use_generic)
3986 *ptr = specific;
3987 else
3988 *ptr = generic;
3989 return p;
3990}
3991
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003992staticforward int recurse_down_subclasses(PyTypeObject *type,
3993 slotdef **pp, PyObject *name);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003994
Guido van Rossumc334df52002-04-04 23:44:47 +00003995/* In the type, update the slots whose slotdefs are gathered in the pp0 array,
3996 and then do the same for all this type's subtypes. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003997static int
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003998update_these_slots(PyTypeObject *type, slotdef **pp0, PyObject *name)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003999{
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004000 slotdef **pp;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004001
Guido van Rossumc334df52002-04-04 23:44:47 +00004002 for (pp = pp0; *pp; pp++)
4003 update_one_slot(type, *pp);
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004004 return recurse_down_subclasses(type, pp0, name);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004005}
4006
Guido van Rossumc334df52002-04-04 23:44:47 +00004007/* Update the slots whose slotdefs are gathered in the pp array in all (direct
4008 or indirect) subclasses of type. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004009static int
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004010recurse_down_subclasses(PyTypeObject *type, slotdef **pp, PyObject *name)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004011{
4012 PyTypeObject *subclass;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004013 PyObject *ref, *subclasses, *dict;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004014 int i, n;
4015
4016 subclasses = type->tp_subclasses;
4017 if (subclasses == NULL)
4018 return 0;
4019 assert(PyList_Check(subclasses));
4020 n = PyList_GET_SIZE(subclasses);
4021 for (i = 0; i < n; i++) {
4022 ref = PyList_GET_ITEM(subclasses, i);
4023 assert(PyWeakref_CheckRef(ref));
4024 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
4025 if (subclass == NULL)
4026 continue;
4027 assert(PyType_Check(subclass));
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004028 /* Avoid recursing down into unaffected classes */
4029 dict = subclass->tp_dict;
4030 if (dict != NULL && PyDict_Check(dict) &&
4031 PyDict_GetItem(dict, name) != NULL)
4032 continue;
4033 if (update_these_slots(subclass, pp, name) < 0)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004034 return -1;
4035 }
4036 return 0;
4037}
4038
Guido van Rossumc334df52002-04-04 23:44:47 +00004039/* Comparison function for qsort() to compare slotdefs by their offset, and
4040 for equal offset by their address (to force a stable sort). */
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004041static int
4042slotdef_cmp(const void *aa, const void *bb)
4043{
4044 const slotdef *a = (const slotdef *)aa, *b = (const slotdef *)bb;
4045 int c = a->offset - b->offset;
4046 if (c != 0)
4047 return c;
4048 else
4049 return a - b;
4050}
4051
Guido van Rossumc334df52002-04-04 23:44:47 +00004052/* Initialize the slotdefs table by adding interned string objects for the
4053 names and sorting the entries. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004054static void
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004055init_slotdefs(void)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004056{
4057 slotdef *p;
4058 static int initialized = 0;
4059
4060 if (initialized)
4061 return;
4062 for (p = slotdefs; p->name; p++) {
4063 p->name_strobj = PyString_InternFromString(p->name);
4064 if (!p->name_strobj)
Guido van Rossumc334df52002-04-04 23:44:47 +00004065 Py_FatalError("Out of memory interning slotdef names");
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004066 }
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004067 qsort((void *)slotdefs, (size_t)(p-slotdefs), sizeof(slotdef),
4068 slotdef_cmp);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004069 initialized = 1;
4070}
4071
Guido van Rossumc334df52002-04-04 23:44:47 +00004072/* Update the slots after assignment to a class (type) attribute. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004073static int
4074update_slot(PyTypeObject *type, PyObject *name)
4075{
Guido van Rossumc334df52002-04-04 23:44:47 +00004076 slotdef *ptrs[MAX_EQUIV];
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004077 slotdef *p;
4078 slotdef **pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004079 int offset;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004080
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004081 init_slotdefs();
4082 pp = ptrs;
4083 for (p = slotdefs; p->name; p++) {
4084 /* XXX assume name is interned! */
4085 if (p->name_strobj == name)
4086 *pp++ = p;
4087 }
4088 *pp = NULL;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004089 for (pp = ptrs; *pp; pp++) {
4090 p = *pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004091 offset = p->offset;
4092 while (p > slotdefs && (p-1)->offset == offset)
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004093 --p;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004094 *pp = p;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004095 }
Guido van Rossumc334df52002-04-04 23:44:47 +00004096 if (ptrs[0] == NULL)
4097 return 0; /* Not an attribute that affects any slots */
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004098 return update_these_slots(type, ptrs, name);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004099}
4100
Guido van Rossumc334df52002-04-04 23:44:47 +00004101/* Store the proper functions in the slot dispatches at class (type)
4102 definition time, based upon which operations the class overrides in its
4103 dict. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004104static void
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004105fixup_slot_dispatchers(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004106{
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004107 slotdef *p;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004108
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004109 init_slotdefs();
Guido van Rossumc334df52002-04-04 23:44:47 +00004110 for (p = slotdefs; p->name; )
4111 p = update_one_slot(type, p);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004112}
Guido van Rossum705f0f52001-08-24 16:47:00 +00004113
Guido van Rossum6d204072001-10-21 00:44:31 +00004114/* This function is called by PyType_Ready() to populate the type's
4115 dictionary with method descriptors for function slots. For each
4116 function slot (like tp_repr) that's defined in the type, one or
4117 more corresponding descriptors are added in the type's tp_dict
4118 dictionary under the appropriate name (like __repr__). Some
4119 function slots cause more than one descriptor to be added (for
4120 example, the nb_add slot adds both __add__ and __radd__
4121 descriptors) and some function slots compete for the same
4122 descriptor (for example both sq_item and mp_subscript generate a
4123 __getitem__ descriptor). This only adds new descriptors and
4124 doesn't overwrite entries in tp_dict that were previously
4125 defined. The descriptors contain a reference to the C function
4126 they must call, so that it's safe if they are copied into a
4127 subtype's __dict__ and the subtype has a different C function in
4128 its slot -- calling the method defined by the descriptor will call
4129 the C function that was used to create it, rather than the C
4130 function present in the slot when it is called. (This is important
4131 because a subtype may have a C function in the slot that calls the
4132 method from the dictionary, and we want to avoid infinite recursion
4133 here.) */
4134
4135static int
4136add_operators(PyTypeObject *type)
4137{
4138 PyObject *dict = type->tp_dict;
4139 slotdef *p;
4140 PyObject *descr;
4141 void **ptr;
4142
4143 init_slotdefs();
4144 for (p = slotdefs; p->name; p++) {
4145 if (p->wrapper == NULL)
4146 continue;
4147 ptr = slotptr(type, p->offset);
4148 if (!ptr || !*ptr)
4149 continue;
4150 if (PyDict_GetItem(dict, p->name_strobj))
4151 continue;
4152 descr = PyDescr_NewWrapper(type, p, *ptr);
4153 if (descr == NULL)
4154 return -1;
4155 if (PyDict_SetItem(dict, p->name_strobj, descr) < 0)
4156 return -1;
4157 Py_DECREF(descr);
4158 }
4159 if (type->tp_new != NULL) {
4160 if (add_tp_new_wrapper(type) < 0)
4161 return -1;
4162 }
4163 return 0;
4164}
4165
Guido van Rossum705f0f52001-08-24 16:47:00 +00004166
4167/* Cooperative 'super' */
4168
4169typedef struct {
4170 PyObject_HEAD
Guido van Rossume705ef12001-08-29 15:47:06 +00004171 PyTypeObject *type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00004172 PyObject *obj;
4173} superobject;
4174
Guido van Rossum6f799372001-09-20 20:46:19 +00004175static PyMemberDef super_members[] = {
4176 {"__thisclass__", T_OBJECT, offsetof(superobject, type), READONLY,
4177 "the class invoking super()"},
4178 {"__self__", T_OBJECT, offsetof(superobject, obj), READONLY,
4179 "the instance invoking super(); may be None"},
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004180 {0}
4181};
4182
Guido van Rossum705f0f52001-08-24 16:47:00 +00004183static void
4184super_dealloc(PyObject *self)
4185{
4186 superobject *su = (superobject *)self;
4187
Guido van Rossum048eb752001-10-02 21:24:57 +00004188 _PyObject_GC_UNTRACK(self);
Guido van Rossum705f0f52001-08-24 16:47:00 +00004189 Py_XDECREF(su->obj);
4190 Py_XDECREF(su->type);
4191 self->ob_type->tp_free(self);
4192}
4193
4194static PyObject *
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004195super_repr(PyObject *self)
4196{
4197 superobject *su = (superobject *)self;
4198
4199 if (su->obj)
4200 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00004201 "<super: <class '%s'>, <%s object>>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004202 su->type ? su->type->tp_name : "NULL",
4203 su->obj->ob_type->tp_name);
4204 else
4205 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00004206 "<super: <class '%s'>, NULL>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004207 su->type ? su->type->tp_name : "NULL");
4208}
4209
4210static PyObject *
Guido van Rossum705f0f52001-08-24 16:47:00 +00004211super_getattro(PyObject *self, PyObject *name)
4212{
4213 superobject *su = (superobject *)self;
4214
4215 if (su->obj != NULL) {
Tim Petersa91e9642001-11-14 23:32:33 +00004216 PyObject *mro, *res, *tmp, *dict;
Guido van Rossum155db9a2002-04-02 17:53:47 +00004217 PyTypeObject *starttype;
Guido van Rossum705f0f52001-08-24 16:47:00 +00004218 descrgetfunc f;
4219 int i, n;
4220
Guido van Rossum155db9a2002-04-02 17:53:47 +00004221 starttype = su->obj->ob_type;
4222 mro = starttype->tp_mro;
4223
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004224 if (mro == NULL)
4225 n = 0;
4226 else {
4227 assert(PyTuple_Check(mro));
4228 n = PyTuple_GET_SIZE(mro);
4229 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00004230 for (i = 0; i < n; i++) {
Guido van Rossume705ef12001-08-29 15:47:06 +00004231 if ((PyObject *)(su->type) == PyTuple_GET_ITEM(mro, i))
Guido van Rossum705f0f52001-08-24 16:47:00 +00004232 break;
4233 }
Guido van Rossume705ef12001-08-29 15:47:06 +00004234 if (i >= n && PyType_Check(su->obj)) {
Guido van Rossum155db9a2002-04-02 17:53:47 +00004235 starttype = (PyTypeObject *)(su->obj);
4236 mro = starttype->tp_mro;
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004237 if (mro == NULL)
4238 n = 0;
4239 else {
4240 assert(PyTuple_Check(mro));
4241 n = PyTuple_GET_SIZE(mro);
4242 }
Guido van Rossume705ef12001-08-29 15:47:06 +00004243 for (i = 0; i < n; i++) {
4244 if ((PyObject *)(su->type) ==
4245 PyTuple_GET_ITEM(mro, i))
4246 break;
4247 }
Guido van Rossume705ef12001-08-29 15:47:06 +00004248 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00004249 i++;
4250 res = NULL;
4251 for (; i < n; i++) {
4252 tmp = PyTuple_GET_ITEM(mro, i);
Tim Petersa91e9642001-11-14 23:32:33 +00004253 if (PyType_Check(tmp))
4254 dict = ((PyTypeObject *)tmp)->tp_dict;
4255 else if (PyClass_Check(tmp))
4256 dict = ((PyClassObject *)tmp)->cl_dict;
4257 else
4258 continue;
4259 res = PyDict_GetItem(dict, name);
Guido van Rossum5b443c62001-12-03 15:38:28 +00004260 if (res != NULL && !PyDescr_IsData(res)) {
Guido van Rossum705f0f52001-08-24 16:47:00 +00004261 Py_INCREF(res);
4262 f = res->ob_type->tp_descr_get;
4263 if (f != NULL) {
Guido van Rossumd4641072002-04-03 02:13:37 +00004264 tmp = f(res, su->obj,
4265 (PyObject *)starttype);
Guido van Rossum705f0f52001-08-24 16:47:00 +00004266 Py_DECREF(res);
4267 res = tmp;
4268 }
4269 return res;
4270 }
4271 }
4272 }
4273 return PyObject_GenericGetAttr(self, name);
4274}
4275
Guido van Rossum5b443c62001-12-03 15:38:28 +00004276static int
4277supercheck(PyTypeObject *type, PyObject *obj)
4278{
4279 if (!PyType_IsSubtype(obj->ob_type, type) &&
4280 !(PyType_Check(obj) &&
4281 PyType_IsSubtype((PyTypeObject *)obj, type))) {
4282 PyErr_SetString(PyExc_TypeError,
4283 "super(type, obj): "
4284 "obj must be an instance or subtype of type");
4285 return -1;
4286 }
4287 else
4288 return 0;
4289}
4290
Guido van Rossum705f0f52001-08-24 16:47:00 +00004291static PyObject *
4292super_descr_get(PyObject *self, PyObject *obj, PyObject *type)
4293{
4294 superobject *su = (superobject *)self;
4295 superobject *new;
4296
4297 if (obj == NULL || obj == Py_None || su->obj != NULL) {
4298 /* Not binding to an object, or already bound */
4299 Py_INCREF(self);
4300 return self;
4301 }
Guido van Rossum5b443c62001-12-03 15:38:28 +00004302 if (su->ob_type != &PySuper_Type)
4303 /* If su is an instance of a subclass of super,
4304 call its type */
4305 return PyObject_CallFunction((PyObject *)su->ob_type,
4306 "OO", su->type, obj);
4307 else {
4308 /* Inline the common case */
4309 if (supercheck(su->type, obj) < 0)
4310 return NULL;
4311 new = (superobject *)PySuper_Type.tp_new(&PySuper_Type,
4312 NULL, NULL);
4313 if (new == NULL)
4314 return NULL;
4315 Py_INCREF(su->type);
4316 Py_INCREF(obj);
4317 new->type = su->type;
4318 new->obj = obj;
4319 return (PyObject *)new;
4320 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00004321}
4322
4323static int
4324super_init(PyObject *self, PyObject *args, PyObject *kwds)
4325{
4326 superobject *su = (superobject *)self;
Guido van Rossume705ef12001-08-29 15:47:06 +00004327 PyTypeObject *type;
4328 PyObject *obj = NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00004329
4330 if (!PyArg_ParseTuple(args, "O!|O:super", &PyType_Type, &type, &obj))
4331 return -1;
4332 if (obj == Py_None)
4333 obj = NULL;
Guido van Rossum5b443c62001-12-03 15:38:28 +00004334 if (obj != NULL && supercheck(type, obj) < 0)
Guido van Rossum705f0f52001-08-24 16:47:00 +00004335 return -1;
Guido van Rossum705f0f52001-08-24 16:47:00 +00004336 Py_INCREF(type);
4337 Py_XINCREF(obj);
4338 su->type = type;
4339 su->obj = obj;
4340 return 0;
4341}
4342
4343static char super_doc[] =
4344"super(type) -> unbound super object\n"
4345"super(type, obj) -> bound super object; requires isinstance(obj, type)\n"
Guido van Rossume705ef12001-08-29 15:47:06 +00004346"super(type, type2) -> bound super object; requires issubclass(type2, type)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00004347"Typical use to call a cooperative superclass method:\n"
4348"class C(B):\n"
4349" def meth(self, arg):\n"
4350" super(C, self).meth(arg)";
4351
Guido van Rossum048eb752001-10-02 21:24:57 +00004352static int
4353super_traverse(PyObject *self, visitproc visit, void *arg)
4354{
4355 superobject *su = (superobject *)self;
4356 int err;
4357
4358#define VISIT(SLOT) \
4359 if (SLOT) { \
4360 err = visit((PyObject *)(SLOT), arg); \
4361 if (err) \
4362 return err; \
4363 }
4364
4365 VISIT(su->obj);
4366 VISIT(su->type);
4367
4368#undef VISIT
4369
4370 return 0;
4371}
4372
Guido van Rossum705f0f52001-08-24 16:47:00 +00004373PyTypeObject PySuper_Type = {
4374 PyObject_HEAD_INIT(&PyType_Type)
4375 0, /* ob_size */
4376 "super", /* tp_name */
4377 sizeof(superobject), /* tp_basicsize */
4378 0, /* tp_itemsize */
4379 /* methods */
4380 super_dealloc, /* tp_dealloc */
4381 0, /* tp_print */
4382 0, /* tp_getattr */
4383 0, /* tp_setattr */
4384 0, /* tp_compare */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004385 super_repr, /* tp_repr */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004386 0, /* tp_as_number */
4387 0, /* tp_as_sequence */
4388 0, /* tp_as_mapping */
4389 0, /* tp_hash */
4390 0, /* tp_call */
4391 0, /* tp_str */
4392 super_getattro, /* tp_getattro */
4393 0, /* tp_setattro */
4394 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00004395 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
4396 Py_TPFLAGS_BASETYPE, /* tp_flags */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004397 super_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00004398 super_traverse, /* tp_traverse */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004399 0, /* tp_clear */
4400 0, /* tp_richcompare */
4401 0, /* tp_weaklistoffset */
4402 0, /* tp_iter */
4403 0, /* tp_iternext */
4404 0, /* tp_methods */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004405 super_members, /* tp_members */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004406 0, /* tp_getset */
4407 0, /* tp_base */
4408 0, /* tp_dict */
4409 super_descr_get, /* tp_descr_get */
4410 0, /* tp_descr_set */
4411 0, /* tp_dictoffset */
4412 super_init, /* tp_init */
4413 PyType_GenericAlloc, /* tp_alloc */
4414 PyType_GenericNew, /* tp_new */
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00004415 PyObject_GC_Del, /* tp_free */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004416};