blob: fddde515eed19190afe9442a572ee96bd4f95892 [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 {
Guido van Rossum09638c12002-06-13 19:17:46 +000011 /* Note: there's a dependency on the order of these members
12 in slotptr() below. */
Guido van Rossum9923ffe2002-06-04 19:52:53 +000013 PyTypeObject type;
14 PyNumberMethods as_number;
Guido van Rossum9923ffe2002-06-04 19:52:53 +000015 PyMappingMethods as_mapping;
Guido van Rossum09638c12002-06-13 19:17:46 +000016 PySequenceMethods as_sequence; /* as_sequence comes after as_mapping,
17 so that the mapping wins when both
18 the mapping and the sequence define
19 a given operator (e.g. __getitem__).
20 see add_operators() below. */
Guido van Rossum9923ffe2002-06-04 19:52:53 +000021 PyBufferProcs as_buffer;
22 PyObject *name, *slots;
23 PyMemberDef members[1];
24} etype;
25
Guido van Rossum6f799372001-09-20 20:46:19 +000026static PyMemberDef type_members[] = {
Tim Peters6d6c1a32001-08-02 04:15:00 +000027 {"__basicsize__", T_INT, offsetof(PyTypeObject,tp_basicsize),READONLY},
28 {"__itemsize__", T_INT, offsetof(PyTypeObject, tp_itemsize), READONLY},
29 {"__flags__", T_LONG, offsetof(PyTypeObject, tp_flags), READONLY},
Guido van Rossum9676b222001-08-17 20:32:36 +000030 {"__weakrefoffset__", T_LONG,
Tim Peters6d6c1a32001-08-02 04:15:00 +000031 offsetof(PyTypeObject, tp_weaklistoffset), READONLY},
32 {"__base__", T_OBJECT, offsetof(PyTypeObject, tp_base), READONLY},
33 {"__dictoffset__", T_LONG,
34 offsetof(PyTypeObject, tp_dictoffset), READONLY},
35 {"__bases__", T_OBJECT, offsetof(PyTypeObject, tp_bases), READONLY},
36 {"__mro__", T_OBJECT, offsetof(PyTypeObject, tp_mro), READONLY},
37 {0}
38};
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000039
Guido van Rossumc0b618a1997-05-02 03:12:38 +000040static PyObject *
Guido van Rossumc3542212001-08-16 09:18:56 +000041type_name(PyTypeObject *type, void *context)
42{
43 char *s;
44
45 s = strrchr(type->tp_name, '.');
46 if (s == NULL)
47 s = type->tp_name;
48 else
49 s++;
50 return PyString_FromString(s);
51}
52
53static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +000054type_module(PyTypeObject *type, void *context)
Guido van Rossum29ca26e1995-01-07 11:58:15 +000055{
Guido van Rossumc3542212001-08-16 09:18:56 +000056 PyObject *mod;
57 char *s;
58
59 s = strrchr(type->tp_name, '.');
60 if (s != NULL)
61 return PyString_FromStringAndSize(type->tp_name,
62 (int)(s - type->tp_name));
63 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE))
64 return PyString_FromString("__builtin__");
Guido van Rossum687ae002001-10-15 22:03:32 +000065 mod = PyDict_GetItemString(type->tp_dict, "__module__");
Guido van Rossumc3542212001-08-16 09:18:56 +000066 if (mod != NULL && PyString_Check(mod)) {
67 Py_INCREF(mod);
68 return mod;
69 }
70 PyErr_SetString(PyExc_AttributeError, "__module__");
71 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +000072}
73
Guido van Rossum3926a632001-09-25 16:25:58 +000074static int
75type_set_module(PyTypeObject *type, PyObject *value, void *context)
76{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +000077 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE) ||
Guido van Rossum3926a632001-09-25 16:25:58 +000078 strrchr(type->tp_name, '.')) {
79 PyErr_Format(PyExc_TypeError,
80 "can't set %s.__module__", type->tp_name);
81 return -1;
82 }
83 if (!value) {
84 PyErr_Format(PyExc_TypeError,
85 "can't delete %s.__module__", type->tp_name);
86 return -1;
87 }
88 return PyDict_SetItemString(type->tp_dict, "__module__", value);
89}
90
Tim Peters6d6c1a32001-08-02 04:15:00 +000091static PyObject *
92type_dict(PyTypeObject *type, void *context)
93{
94 if (type->tp_dict == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +000095 Py_INCREF(Py_None);
96 return Py_None;
Guido van Rossum29ca26e1995-01-07 11:58:15 +000097 }
Tim Peters6d6c1a32001-08-02 04:15:00 +000098 return PyDictProxy_New(type->tp_dict);
Guido van Rossum29ca26e1995-01-07 11:58:15 +000099}
100
Tim Peters24008312002-03-17 18:56:20 +0000101static PyObject *
102type_get_doc(PyTypeObject *type, void *context)
103{
104 PyObject *result;
Guido van Rossum6ca7d412002-04-18 00:22:00 +0000105 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE) && type->tp_doc != NULL)
Tim Peters24008312002-03-17 18:56:20 +0000106 return PyString_FromString(type->tp_doc);
Tim Peters24008312002-03-17 18:56:20 +0000107 result = PyDict_GetItemString(type->tp_dict, "__doc__");
Guido van Rossum6ca7d412002-04-18 00:22:00 +0000108 if (result == NULL) {
109 result = Py_None;
110 Py_INCREF(result);
111 }
112 else if (result->ob_type->tp_descr_get) {
Tim Peters2b858972002-04-18 04:12:28 +0000113 result = result->ob_type->tp_descr_get(result, NULL,
114 (PyObject *)type);
Guido van Rossum6ca7d412002-04-18 00:22:00 +0000115 }
116 else {
117 Py_INCREF(result);
118 }
Tim Peters24008312002-03-17 18:56:20 +0000119 return result;
120}
121
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000122static PyGetSetDef type_getsets[] = {
Guido van Rossumc3542212001-08-16 09:18:56 +0000123 {"__name__", (getter)type_name, NULL, NULL},
Guido van Rossum3926a632001-09-25 16:25:58 +0000124 {"__module__", (getter)type_module, (setter)type_set_module, NULL},
Tim Peters6d6c1a32001-08-02 04:15:00 +0000125 {"__dict__", (getter)type_dict, NULL, NULL},
Tim Peters24008312002-03-17 18:56:20 +0000126 {"__doc__", (getter)type_get_doc, NULL, NULL},
Tim Peters6d6c1a32001-08-02 04:15:00 +0000127 {0}
128};
129
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000130static int
131type_compare(PyObject *v, PyObject *w)
132{
133 /* This is called with type objects only. So we
134 can just compare the addresses. */
135 Py_uintptr_t vv = (Py_uintptr_t)v;
136 Py_uintptr_t ww = (Py_uintptr_t)w;
137 return (vv < ww) ? -1 : (vv > ww) ? 1 : 0;
138}
139
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000140static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000141type_repr(PyTypeObject *type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000142{
Barry Warsaw7ce36942001-08-24 18:34:26 +0000143 PyObject *mod, *name, *rtn;
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000144 char *kind;
Guido van Rossumc3542212001-08-16 09:18:56 +0000145
146 mod = type_module(type, NULL);
147 if (mod == NULL)
148 PyErr_Clear();
149 else if (!PyString_Check(mod)) {
150 Py_DECREF(mod);
151 mod = NULL;
152 }
153 name = type_name(type, NULL);
154 if (name == NULL)
155 return NULL;
Barry Warsaw7ce36942001-08-24 18:34:26 +0000156
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000157 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
158 kind = "class";
159 else
160 kind = "type";
161
Barry Warsaw7ce36942001-08-24 18:34:26 +0000162 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__")) {
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000163 rtn = PyString_FromFormat("<%s '%s.%s'>",
164 kind,
Barry Warsaw7ce36942001-08-24 18:34:26 +0000165 PyString_AS_STRING(mod),
166 PyString_AS_STRING(name));
167 }
Guido van Rossumc3542212001-08-16 09:18:56 +0000168 else
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000169 rtn = PyString_FromFormat("<%s '%s'>", kind, type->tp_name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000170
Guido van Rossumc3542212001-08-16 09:18:56 +0000171 Py_XDECREF(mod);
172 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000173 return rtn;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000174}
175
Tim Peters6d6c1a32001-08-02 04:15:00 +0000176static PyObject *
177type_call(PyTypeObject *type, PyObject *args, PyObject *kwds)
178{
179 PyObject *obj;
180
181 if (type->tp_new == NULL) {
182 PyErr_Format(PyExc_TypeError,
183 "cannot create '%.100s' instances",
184 type->tp_name);
185 return NULL;
186 }
187
Tim Peters3f996e72001-09-13 19:18:27 +0000188 obj = type->tp_new(type, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000189 if (obj != NULL) {
Guido van Rossumf76de622001-10-18 15:49:21 +0000190 /* Ugly exception: when the call was type(something),
191 don't call tp_init on the result. */
192 if (type == &PyType_Type &&
193 PyTuple_Check(args) && PyTuple_GET_SIZE(args) == 1 &&
194 (kwds == NULL ||
195 (PyDict_Check(kwds) && PyDict_Size(kwds) == 0)))
196 return obj;
Guido van Rossum8ace1ab2002-04-06 01:05:01 +0000197 /* If the returned object is not an instance of type,
198 it won't be initialized. */
199 if (!PyType_IsSubtype(obj->ob_type, type))
200 return obj;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000201 type = obj->ob_type;
Jeremy Hylton719841e2002-07-16 19:39:38 +0000202 if (PyType_HasFeature(type, Py_TPFLAGS_HAVE_CLASS) &&
203 type->tp_init != NULL &&
Tim Peters6d6c1a32001-08-02 04:15:00 +0000204 type->tp_init(obj, args, kwds) < 0) {
205 Py_DECREF(obj);
206 obj = NULL;
207 }
208 }
209 return obj;
210}
211
212PyObject *
213PyType_GenericAlloc(PyTypeObject *type, int nitems)
214{
Tim Peters6d6c1a32001-08-02 04:15:00 +0000215 PyObject *obj;
Tim Petersf2a67da2001-10-07 03:54:51 +0000216 const size_t size = _PyObject_VAR_SIZE(type, nitems);
Tim Peters406fe3b2001-10-06 19:04:01 +0000217
218 if (PyType_IS_GC(type))
Neil Schemenauer09a2ae52002-04-12 03:06:53 +0000219 obj = _PyObject_GC_Malloc(size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000220 else
Neil Schemenauerc806c882001-08-29 23:54:54 +0000221 obj = PyObject_MALLOC(size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000222
Neil Schemenauerc806c882001-08-29 23:54:54 +0000223 if (obj == NULL)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000224 return PyErr_NoMemory();
Tim Peters406fe3b2001-10-06 19:04:01 +0000225
Neil Schemenauerc806c882001-08-29 23:54:54 +0000226 memset(obj, '\0', size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000227
Tim Peters6d6c1a32001-08-02 04:15:00 +0000228 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
229 Py_INCREF(type);
Tim Peters406fe3b2001-10-06 19:04:01 +0000230
Tim Peters6d6c1a32001-08-02 04:15:00 +0000231 if (type->tp_itemsize == 0)
232 PyObject_INIT(obj, type);
233 else
234 (void) PyObject_INIT_VAR((PyVarObject *)obj, type, nitems);
Tim Peters406fe3b2001-10-06 19:04:01 +0000235
Tim Peters6d6c1a32001-08-02 04:15:00 +0000236 if (PyType_IS_GC(type))
Neil Schemenauerc806c882001-08-29 23:54:54 +0000237 _PyObject_GC_TRACK(obj);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000238 return obj;
239}
240
241PyObject *
242PyType_GenericNew(PyTypeObject *type, PyObject *args, PyObject *kwds)
243{
244 return type->tp_alloc(type, 0);
245}
246
Guido van Rossum9475a232001-10-05 20:51:39 +0000247/* Helpers for subtyping */
248
249static int
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000250traverse_slots(PyTypeObject *type, PyObject *self, visitproc visit, void *arg)
251{
252 int i, n;
253 PyMemberDef *mp;
254
255 n = type->ob_size;
256 mp = ((etype *)type)->members;
257 for (i = 0; i < n; i++, mp++) {
258 if (mp->type == T_OBJECT_EX) {
259 char *addr = (char *)self + mp->offset;
260 PyObject *obj = *(PyObject **)addr;
261 if (obj != NULL) {
262 int err = visit(obj, arg);
263 if (err)
264 return err;
265 }
266 }
267 }
268 return 0;
269}
270
271static int
Guido van Rossum9475a232001-10-05 20:51:39 +0000272subtype_traverse(PyObject *self, visitproc visit, void *arg)
273{
274 PyTypeObject *type, *base;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000275 traverseproc basetraverse;
Guido van Rossum9475a232001-10-05 20:51:39 +0000276
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000277 /* Find the nearest base with a different tp_traverse,
278 and traverse slots while we're at it */
Guido van Rossum9475a232001-10-05 20:51:39 +0000279 type = self->ob_type;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000280 base = type;
281 while ((basetraverse = base->tp_traverse) == subtype_traverse) {
282 if (base->ob_size) {
283 int err = traverse_slots(base, self, visit, arg);
284 if (err)
285 return err;
286 }
Guido van Rossum9475a232001-10-05 20:51:39 +0000287 base = base->tp_base;
288 assert(base);
289 }
290
291 if (type->tp_dictoffset != base->tp_dictoffset) {
292 PyObject **dictptr = _PyObject_GetDictPtr(self);
293 if (dictptr && *dictptr) {
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000294 int err = visit(*dictptr, arg);
Guido van Rossum9475a232001-10-05 20:51:39 +0000295 if (err)
296 return err;
297 }
298 }
299
Guido van Rossuma3862092002-06-10 15:24:42 +0000300 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
301 /* For a heaptype, the instances count as references
302 to the type. Traverse the type so the collector
303 can find cycles involving this link. */
304 int err = visit((PyObject *)type, arg);
305 if (err)
306 return err;
307 }
308
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000309 if (basetraverse)
310 return basetraverse(self, visit, arg);
311 return 0;
312}
313
314static void
315clear_slots(PyTypeObject *type, PyObject *self)
316{
317 int i, n;
318 PyMemberDef *mp;
319
320 n = type->ob_size;
321 mp = ((etype *)type)->members;
322 for (i = 0; i < n; i++, mp++) {
323 if (mp->type == T_OBJECT_EX && !(mp->flags & READONLY)) {
324 char *addr = (char *)self + mp->offset;
325 PyObject *obj = *(PyObject **)addr;
326 if (obj != NULL) {
327 Py_DECREF(obj);
328 *(PyObject **)addr = NULL;
329 }
330 }
331 }
332}
333
334static int
335subtype_clear(PyObject *self)
336{
337 PyTypeObject *type, *base;
338 inquiry baseclear;
339
340 /* Find the nearest base with a different tp_clear
341 and clear slots while we're at it */
342 type = self->ob_type;
343 base = type;
344 while ((baseclear = base->tp_clear) == subtype_clear) {
345 if (base->ob_size)
346 clear_slots(base, self);
347 base = base->tp_base;
348 assert(base);
349 }
350
Guido van Rossuma3862092002-06-10 15:24:42 +0000351 /* There's no need to clear the instance dict (if any);
352 the collector will call its tp_clear handler. */
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000353
354 if (baseclear)
355 return baseclear(self);
Guido van Rossum9475a232001-10-05 20:51:39 +0000356 return 0;
357}
Tim Peters6d6c1a32001-08-02 04:15:00 +0000358
359static void
360subtype_dealloc(PyObject *self)
361{
Guido van Rossum14227b42001-12-06 02:35:58 +0000362 PyTypeObject *type, *base;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000363 destructor basedealloc;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000364
Guido van Rossum22b13872002-08-06 21:41:44 +0000365 /* Extract the type; we expect it to be a heap type */
366 type = self->ob_type;
367 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000368
Guido van Rossum22b13872002-08-06 21:41:44 +0000369 /* Test whether the type has GC exactly once */
370
371 if (!PyType_IS_GC(type)) {
372 /* It's really rare to find a dynamic type that doesn't have
373 GC; it can only happen when deriving from 'object' and not
374 adding any slots or instance variables. This allows
375 certain simplifications: there's no need to call
376 clear_slots(), or DECREF the dict, or clear weakrefs. */
377
378 /* Maybe call finalizer; exit early if resurrected */
Guido van Rossumfebd61d2002-08-08 20:55:20 +0000379 if (type->tp_del) {
380 type->tp_del(self);
381 if (self->ob_refcnt > 0)
382 return;
383 }
Guido van Rossum22b13872002-08-06 21:41:44 +0000384
385 /* Find the nearest base with a different tp_dealloc */
386 base = type;
387 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
388 assert(base->ob_size == 0);
389 base = base->tp_base;
390 assert(base);
391 }
392
393 /* Call the base tp_dealloc() */
394 assert(basedealloc);
395 basedealloc(self);
396
397 /* Can't reference self beyond this point */
398 Py_DECREF(type);
399
400 /* Done */
401 return;
402 }
403
404 /* We get here only if the type has GC */
405
406 /* UnTrack and re-Track around the trashcan macro, alas */
Guido van Rossum0906e072002-08-07 20:42:09 +0000407 PyObject_GC_UnTrack(self);
Guido van Rossum22b13872002-08-06 21:41:44 +0000408 Py_TRASHCAN_SAFE_BEGIN(self);
409 _PyObject_GC_TRACK(self); /* We'll untrack for real later */
410
411 /* Maybe call finalizer; exit early if resurrected */
Guido van Rossumfebd61d2002-08-08 20:55:20 +0000412 if (type->tp_del) {
413 type->tp_del(self);
414 if (self->ob_refcnt > 0)
415 goto endlabel;
416 }
Guido van Rossum7ad2d1e2001-10-29 22:11:00 +0000417
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000418 /* Find the nearest base with a different tp_dealloc
419 and clear slots while we're at it */
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000420 base = type;
421 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
422 if (base->ob_size)
423 clear_slots(base, self);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000424 base = base->tp_base;
425 assert(base);
Guido van Rossum14227b42001-12-06 02:35:58 +0000426 }
427
Tim Peters6d6c1a32001-08-02 04:15:00 +0000428 /* If we added a dict, DECREF it */
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000429 if (type->tp_dictoffset && !base->tp_dictoffset) {
430 PyObject **dictptr = _PyObject_GetDictPtr(self);
431 if (dictptr != NULL) {
432 PyObject *dict = *dictptr;
433 if (dict != NULL) {
434 Py_DECREF(dict);
435 *dictptr = NULL;
436 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000437 }
438 }
439
Guido van Rossum9676b222001-08-17 20:32:36 +0000440 /* If we added weaklist, we clear it */
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000441 if (type->tp_weaklistoffset && !base->tp_weaklistoffset)
Guido van Rossum9676b222001-08-17 20:32:36 +0000442 PyObject_ClearWeakRefs(self);
443
Tim Peters6d6c1a32001-08-02 04:15:00 +0000444 /* Finalize GC if the base doesn't do GC and we do */
Guido van Rossum22b13872002-08-06 21:41:44 +0000445 if (!PyType_IS_GC(base))
Guido van Rossum048eb752001-10-02 21:24:57 +0000446 _PyObject_GC_UNTRACK(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000447
448 /* Call the base tp_dealloc() */
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000449 assert(basedealloc);
450 basedealloc(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000451
452 /* Can't reference self beyond this point */
Guido van Rossum22b13872002-08-06 21:41:44 +0000453 Py_DECREF(type);
454
Guido van Rossum0906e072002-08-07 20:42:09 +0000455 endlabel:
Guido van Rossum22b13872002-08-06 21:41:44 +0000456 Py_TRASHCAN_SAFE_END(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000457}
458
Jeremy Hylton938ace62002-07-17 16:30:39 +0000459static PyTypeObject *solid_base(PyTypeObject *type);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000460
Tim Peters6d6c1a32001-08-02 04:15:00 +0000461/* type test with subclassing support */
462
463int
464PyType_IsSubtype(PyTypeObject *a, PyTypeObject *b)
465{
466 PyObject *mro;
467
Guido van Rossum9478d072001-09-07 18:52:13 +0000468 if (!(a->tp_flags & Py_TPFLAGS_HAVE_CLASS))
469 return b == a || b == &PyBaseObject_Type;
470
Tim Peters6d6c1a32001-08-02 04:15:00 +0000471 mro = a->tp_mro;
472 if (mro != NULL) {
473 /* Deal with multiple inheritance without recursion
474 by walking the MRO tuple */
475 int i, n;
476 assert(PyTuple_Check(mro));
477 n = PyTuple_GET_SIZE(mro);
478 for (i = 0; i < n; i++) {
479 if (PyTuple_GET_ITEM(mro, i) == (PyObject *)b)
480 return 1;
481 }
482 return 0;
483 }
484 else {
485 /* a is not completely initilized yet; follow tp_base */
486 do {
487 if (a == b)
488 return 1;
489 a = a->tp_base;
490 } while (a != NULL);
491 return b == &PyBaseObject_Type;
492 }
493}
494
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000495/* Internal routines to do a method lookup in the type
Guido van Rossum60718732001-08-28 17:47:51 +0000496 without looking in the instance dictionary
497 (so we can't use PyObject_GetAttr) but still binding
498 it to the instance. The arguments are the object,
499 the method name as a C string, and the address of a
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000500 static variable used to cache the interned Python string.
501
502 Two variants:
503
504 - lookup_maybe() returns NULL without raising an exception
505 when the _PyType_Lookup() call fails;
506
507 - lookup_method() always raises an exception upon errors.
508*/
Guido van Rossum60718732001-08-28 17:47:51 +0000509
510static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000511lookup_maybe(PyObject *self, char *attrstr, PyObject **attrobj)
Guido van Rossum60718732001-08-28 17:47:51 +0000512{
513 PyObject *res;
514
515 if (*attrobj == NULL) {
516 *attrobj = PyString_InternFromString(attrstr);
517 if (*attrobj == NULL)
518 return NULL;
519 }
520 res = _PyType_Lookup(self->ob_type, *attrobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000521 if (res != NULL) {
Guido van Rossum60718732001-08-28 17:47:51 +0000522 descrgetfunc f;
523 if ((f = res->ob_type->tp_descr_get) == NULL)
524 Py_INCREF(res);
525 else
526 res = f(res, self, (PyObject *)(self->ob_type));
527 }
528 return res;
529}
530
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000531static PyObject *
532lookup_method(PyObject *self, char *attrstr, PyObject **attrobj)
533{
534 PyObject *res = lookup_maybe(self, attrstr, attrobj);
535 if (res == NULL && !PyErr_Occurred())
536 PyErr_SetObject(PyExc_AttributeError, *attrobj);
537 return res;
538}
539
Guido van Rossum2730b132001-08-28 18:22:14 +0000540/* A variation of PyObject_CallMethod that uses lookup_method()
541 instead of PyObject_GetAttrString(). This uses the same convention
542 as lookup_method to cache the interned name string object. */
543
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000544static PyObject *
Guido van Rossum2730b132001-08-28 18:22:14 +0000545call_method(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
546{
547 va_list va;
548 PyObject *args, *func = 0, *retval;
Guido van Rossum2730b132001-08-28 18:22:14 +0000549 va_start(va, format);
550
Guido van Rossumda21c012001-10-03 00:50:18 +0000551 func = lookup_maybe(o, name, nameobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000552 if (func == NULL) {
553 va_end(va);
554 if (!PyErr_Occurred())
Guido van Rossumda21c012001-10-03 00:50:18 +0000555 PyErr_SetObject(PyExc_AttributeError, *nameobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000556 return NULL;
557 }
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000558
559 if (format && *format)
560 args = Py_VaBuildValue(format, va);
561 else
562 args = PyTuple_New(0);
563
564 va_end(va);
565
566 if (args == NULL)
567 return NULL;
568
569 assert(PyTuple_Check(args));
570 retval = PyObject_Call(func, args, NULL);
571
572 Py_DECREF(args);
573 Py_DECREF(func);
574
575 return retval;
576}
577
578/* Clone of call_method() that returns NotImplemented when the lookup fails. */
579
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000580static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000581call_maybe(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
582{
583 va_list va;
584 PyObject *args, *func = 0, *retval;
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000585 va_start(va, format);
586
Guido van Rossumda21c012001-10-03 00:50:18 +0000587 func = lookup_maybe(o, name, nameobj);
Guido van Rossum2730b132001-08-28 18:22:14 +0000588 if (func == NULL) {
589 va_end(va);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000590 if (!PyErr_Occurred()) {
591 Py_INCREF(Py_NotImplemented);
592 return Py_NotImplemented;
593 }
Guido van Rossum717ce002001-09-14 16:58:08 +0000594 return NULL;
Guido van Rossum2730b132001-08-28 18:22:14 +0000595 }
596
597 if (format && *format)
598 args = Py_VaBuildValue(format, va);
599 else
600 args = PyTuple_New(0);
601
602 va_end(va);
603
Guido van Rossum717ce002001-09-14 16:58:08 +0000604 if (args == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +0000605 return NULL;
606
Guido van Rossum717ce002001-09-14 16:58:08 +0000607 assert(PyTuple_Check(args));
608 retval = PyObject_Call(func, args, NULL);
Guido van Rossum2730b132001-08-28 18:22:14 +0000609
610 Py_DECREF(args);
611 Py_DECREF(func);
612
613 return retval;
614}
615
Tim Peters6d6c1a32001-08-02 04:15:00 +0000616/* Method resolution order algorithm from "Putting Metaclasses to Work"
617 by Forman and Danforth (Addison-Wesley 1999). */
618
619static int
620conservative_merge(PyObject *left, PyObject *right)
621{
622 int left_size;
623 int right_size;
624 int i, j, r, ok;
625 PyObject *temp, *rr;
626
627 assert(PyList_Check(left));
628 assert(PyList_Check(right));
629
630 again:
631 left_size = PyList_GET_SIZE(left);
632 right_size = PyList_GET_SIZE(right);
633 for (i = 0; i < left_size; i++) {
634 for (j = 0; j < right_size; j++) {
635 if (PyList_GET_ITEM(left, i) ==
636 PyList_GET_ITEM(right, j)) {
637 /* found a merge point */
638 temp = PyList_New(0);
639 if (temp == NULL)
640 return -1;
641 for (r = 0; r < j; r++) {
642 rr = PyList_GET_ITEM(right, r);
643 ok = PySequence_Contains(left, rr);
644 if (ok < 0) {
645 Py_DECREF(temp);
646 return -1;
647 }
648 if (!ok) {
649 ok = PyList_Append(temp, rr);
650 if (ok < 0) {
651 Py_DECREF(temp);
652 return -1;
653 }
654 }
655 }
656 ok = PyList_SetSlice(left, i, i, temp);
657 Py_DECREF(temp);
658 if (ok < 0)
659 return -1;
660 ok = PyList_SetSlice(right, 0, j+1, NULL);
661 if (ok < 0)
662 return -1;
663 goto again;
664 }
665 }
666 }
667 return PyList_SetSlice(left, left_size, left_size, right);
668}
669
670static int
671serious_order_disagreements(PyObject *left, PyObject *right)
672{
673 return 0; /* XXX later -- for now, we cheat: "don't do that" */
674}
675
Tim Petersa91e9642001-11-14 23:32:33 +0000676static int
677fill_classic_mro(PyObject *mro, PyObject *cls)
678{
679 PyObject *bases, *base;
680 int i, n;
681
682 assert(PyList_Check(mro));
683 assert(PyClass_Check(cls));
684 i = PySequence_Contains(mro, cls);
685 if (i < 0)
686 return -1;
687 if (!i) {
688 if (PyList_Append(mro, cls) < 0)
689 return -1;
690 }
691 bases = ((PyClassObject *)cls)->cl_bases;
692 assert(bases && PyTuple_Check(bases));
693 n = PyTuple_GET_SIZE(bases);
694 for (i = 0; i < n; i++) {
695 base = PyTuple_GET_ITEM(bases, i);
696 if (fill_classic_mro(mro, base) < 0)
697 return -1;
698 }
699 return 0;
700}
701
702static PyObject *
703classic_mro(PyObject *cls)
704{
705 PyObject *mro;
706
707 assert(PyClass_Check(cls));
708 mro = PyList_New(0);
709 if (mro != NULL) {
710 if (fill_classic_mro(mro, cls) == 0)
711 return mro;
712 Py_DECREF(mro);
713 }
714 return NULL;
715}
716
Tim Peters6d6c1a32001-08-02 04:15:00 +0000717static PyObject *
718mro_implementation(PyTypeObject *type)
719{
720 int i, n, ok;
721 PyObject *bases, *result;
722
Guido van Rossum63517572002-06-18 16:44:57 +0000723 if(type->tp_dict == NULL) {
724 if(PyType_Ready(type) < 0)
725 return NULL;
726 }
727
Tim Peters6d6c1a32001-08-02 04:15:00 +0000728 bases = type->tp_bases;
729 n = PyTuple_GET_SIZE(bases);
730 result = Py_BuildValue("[O]", (PyObject *)type);
731 if (result == NULL)
732 return NULL;
733 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +0000734 PyObject *base = PyTuple_GET_ITEM(bases, i);
735 PyObject *parentMRO;
736 if (PyType_Check(base))
737 parentMRO = PySequence_List(
738 ((PyTypeObject*)base)->tp_mro);
739 else
740 parentMRO = classic_mro(base);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000741 if (parentMRO == NULL) {
742 Py_DECREF(result);
743 return NULL;
744 }
745 if (serious_order_disagreements(result, parentMRO)) {
746 Py_DECREF(result);
747 return NULL;
748 }
749 ok = conservative_merge(result, parentMRO);
750 Py_DECREF(parentMRO);
751 if (ok < 0) {
752 Py_DECREF(result);
753 return NULL;
754 }
755 }
756 return result;
757}
758
759static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000760mro_external(PyObject *self)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000761{
762 PyTypeObject *type = (PyTypeObject *)self;
763
Tim Peters6d6c1a32001-08-02 04:15:00 +0000764 return mro_implementation(type);
765}
766
767static int
768mro_internal(PyTypeObject *type)
769{
770 PyObject *mro, *result, *tuple;
771
772 if (type->ob_type == &PyType_Type) {
773 result = mro_implementation(type);
774 }
775 else {
Guido van Rossum60718732001-08-28 17:47:51 +0000776 static PyObject *mro_str;
777 mro = lookup_method((PyObject *)type, "mro", &mro_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000778 if (mro == NULL)
779 return -1;
780 result = PyObject_CallObject(mro, NULL);
781 Py_DECREF(mro);
782 }
783 if (result == NULL)
784 return -1;
785 tuple = PySequence_Tuple(result);
786 Py_DECREF(result);
787 type->tp_mro = tuple;
788 return 0;
789}
790
791
792/* Calculate the best base amongst multiple base classes.
793 This is the first one that's on the path to the "solid base". */
794
795static PyTypeObject *
796best_base(PyObject *bases)
797{
798 int i, n;
799 PyTypeObject *base, *winner, *candidate, *base_i;
Tim Petersa91e9642001-11-14 23:32:33 +0000800 PyObject *base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000801
802 assert(PyTuple_Check(bases));
803 n = PyTuple_GET_SIZE(bases);
804 assert(n > 0);
Tim Petersa91e9642001-11-14 23:32:33 +0000805 base = NULL;
806 winner = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000807 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +0000808 base_proto = PyTuple_GET_ITEM(bases, i);
809 if (PyClass_Check(base_proto))
810 continue;
811 if (!PyType_Check(base_proto)) {
Tim Peters6d6c1a32001-08-02 04:15:00 +0000812 PyErr_SetString(
813 PyExc_TypeError,
814 "bases must be types");
815 return NULL;
816 }
Tim Petersa91e9642001-11-14 23:32:33 +0000817 base_i = (PyTypeObject *)base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000818 if (base_i->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +0000819 if (PyType_Ready(base_i) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000820 return NULL;
821 }
822 candidate = solid_base(base_i);
Tim Petersa91e9642001-11-14 23:32:33 +0000823 if (winner == NULL) {
824 winner = candidate;
825 base = base_i;
826 }
827 else if (PyType_IsSubtype(winner, candidate))
Tim Peters6d6c1a32001-08-02 04:15:00 +0000828 ;
829 else if (PyType_IsSubtype(candidate, winner)) {
830 winner = candidate;
831 base = base_i;
832 }
833 else {
834 PyErr_SetString(
835 PyExc_TypeError,
836 "multiple bases have "
837 "instance lay-out conflict");
838 return NULL;
839 }
840 }
Guido van Rossume54616c2001-12-14 04:19:56 +0000841 if (base == NULL)
842 PyErr_SetString(PyExc_TypeError,
843 "a new-style class can't have only classic bases");
Tim Peters6d6c1a32001-08-02 04:15:00 +0000844 return base;
845}
846
847static int
848extra_ivars(PyTypeObject *type, PyTypeObject *base)
849{
Neil Schemenauerc806c882001-08-29 23:54:54 +0000850 size_t t_size = type->tp_basicsize;
851 size_t b_size = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000852
Guido van Rossum9676b222001-08-17 20:32:36 +0000853 assert(t_size >= b_size); /* Else type smaller than base! */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000854 if (type->tp_itemsize || base->tp_itemsize) {
855 /* If itemsize is involved, stricter rules */
856 return t_size != b_size ||
857 type->tp_itemsize != base->tp_itemsize;
858 }
Guido van Rossum9676b222001-08-17 20:32:36 +0000859 if (type->tp_weaklistoffset && base->tp_weaklistoffset == 0 &&
860 type->tp_weaklistoffset + sizeof(PyObject *) == t_size)
861 t_size -= sizeof(PyObject *);
862 if (type->tp_dictoffset && base->tp_dictoffset == 0 &&
863 type->tp_dictoffset + sizeof(PyObject *) == t_size)
864 t_size -= sizeof(PyObject *);
865
866 return t_size != b_size;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000867}
868
869static PyTypeObject *
870solid_base(PyTypeObject *type)
871{
872 PyTypeObject *base;
873
874 if (type->tp_base)
875 base = solid_base(type->tp_base);
876 else
877 base = &PyBaseObject_Type;
878 if (extra_ivars(type, base))
879 return type;
880 else
881 return base;
882}
883
Jeremy Hylton938ace62002-07-17 16:30:39 +0000884static void object_dealloc(PyObject *);
885static int object_init(PyObject *, PyObject *, PyObject *);
886static int update_slot(PyTypeObject *, PyObject *);
887static void fixup_slot_dispatchers(PyTypeObject *);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000888
889static PyObject *
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000890subtype_dict(PyObject *obj, void *context)
891{
892 PyObject **dictptr = _PyObject_GetDictPtr(obj);
893 PyObject *dict;
894
895 if (dictptr == NULL) {
896 PyErr_SetString(PyExc_AttributeError,
897 "This object has no __dict__");
898 return NULL;
899 }
900 dict = *dictptr;
Guido van Rossum3926a632001-09-25 16:25:58 +0000901 if (dict == NULL)
902 *dictptr = dict = PyDict_New();
903 Py_XINCREF(dict);
904 return dict;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000905}
906
Guido van Rossum6661be32001-10-26 04:26:12 +0000907static int
908subtype_setdict(PyObject *obj, PyObject *value, void *context)
909{
910 PyObject **dictptr = _PyObject_GetDictPtr(obj);
911 PyObject *dict;
912
913 if (dictptr == NULL) {
914 PyErr_SetString(PyExc_AttributeError,
915 "This object has no __dict__");
916 return -1;
917 }
Guido van Rossumd331cb52001-12-05 19:46:42 +0000918 if (value != NULL && !PyDict_Check(value)) {
Guido van Rossum6661be32001-10-26 04:26:12 +0000919 PyErr_SetString(PyExc_TypeError,
920 "__dict__ must be set to a dictionary");
921 return -1;
922 }
923 dict = *dictptr;
Guido van Rossumd331cb52001-12-05 19:46:42 +0000924 Py_XINCREF(value);
Guido van Rossum6661be32001-10-26 04:26:12 +0000925 *dictptr = value;
926 Py_XDECREF(dict);
927 return 0;
928}
929
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000930static PyGetSetDef subtype_getsets[] = {
Guido van Rossum6661be32001-10-26 04:26:12 +0000931 {"__dict__", subtype_dict, subtype_setdict, NULL},
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000932 {0},
933};
934
Guido van Rossum0628dcf2002-03-14 23:03:14 +0000935/* bozo: __getstate__ that raises TypeError */
936
937static PyObject *
938bozo_func(PyObject *self, PyObject *args)
939{
940 PyErr_SetString(PyExc_TypeError,
941 "a class that defines __slots__ without "
942 "defining __getstate__ cannot be pickled");
943 return NULL;
944}
945
Neal Norwitz93c1e232002-03-31 16:06:11 +0000946static PyMethodDef bozo_ml = {"__getstate__", bozo_func, METH_VARARGS};
Guido van Rossum0628dcf2002-03-14 23:03:14 +0000947
948static PyObject *bozo_obj = NULL;
949
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000950static int
951valid_identifier(PyObject *s)
952{
Guido van Rossum03013a02002-07-16 14:30:28 +0000953 unsigned char *p;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000954 int i, n;
955
956 if (!PyString_Check(s)) {
957 PyErr_SetString(PyExc_TypeError,
958 "__slots__ must be strings");
959 return 0;
960 }
Guido van Rossum03013a02002-07-16 14:30:28 +0000961 p = (unsigned char *) PyString_AS_STRING(s);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000962 n = PyString_GET_SIZE(s);
963 /* We must reject an empty name. As a hack, we bump the
964 length to 1 so that the loop will balk on the trailing \0. */
965 if (n == 0)
966 n = 1;
967 for (i = 0; i < n; i++, p++) {
968 if (!(i == 0 ? isalpha(*p) : isalnum(*p)) && *p != '_') {
969 PyErr_SetString(PyExc_TypeError,
970 "__slots__ must be identifiers");
971 return 0;
972 }
973 }
974 return 1;
975}
976
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000977static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000978type_new(PyTypeObject *metatype, PyObject *args, PyObject *kwds)
979{
980 PyObject *name, *bases, *dict;
981 static char *kwlist[] = {"name", "bases", "dict", 0};
Raymond Hettinger0ae0c072002-06-20 22:23:15 +0000982 static char buffer[256];
983 PyObject *slots, *tmp, *newslots;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000984 PyTypeObject *type, *base, *tmptype, *winner;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000985 etype *et;
Guido van Rossum6f799372001-09-20 20:46:19 +0000986 PyMemberDef *mp;
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +0000987 int i, nbases, nslots, slotoffset, add_dict, add_weak;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000988
Tim Peters3abca122001-10-27 19:37:48 +0000989 assert(args != NULL && PyTuple_Check(args));
990 assert(kwds == NULL || PyDict_Check(kwds));
991
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000992 /* Special case: type(x) should return x->ob_type */
Tim Peters3abca122001-10-27 19:37:48 +0000993 {
994 const int nargs = PyTuple_GET_SIZE(args);
995 const int nkwds = kwds == NULL ? 0 : PyDict_Size(kwds);
996
997 if (PyType_CheckExact(metatype) && nargs == 1 && nkwds == 0) {
998 PyObject *x = PyTuple_GET_ITEM(args, 0);
999 Py_INCREF(x->ob_type);
1000 return (PyObject *) x->ob_type;
1001 }
1002
1003 /* SF bug 475327 -- if that didn't trigger, we need 3
1004 arguments. but PyArg_ParseTupleAndKeywords below may give
1005 a msg saying type() needs exactly 3. */
1006 if (nargs + nkwds != 3) {
1007 PyErr_SetString(PyExc_TypeError,
1008 "type() takes 1 or 3 arguments");
1009 return NULL;
1010 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001011 }
1012
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001013 /* Check arguments: (name, bases, dict) */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001014 if (!PyArg_ParseTupleAndKeywords(args, kwds, "SO!O!:type", kwlist,
1015 &name,
1016 &PyTuple_Type, &bases,
1017 &PyDict_Type, &dict))
1018 return NULL;
1019
1020 /* Determine the proper metatype to deal with this,
1021 and check for metatype conflicts while we're at it.
1022 Note that if some other metatype wins to contract,
1023 it's possible that its instances are not types. */
1024 nbases = PyTuple_GET_SIZE(bases);
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001025 winner = metatype;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001026 for (i = 0; i < nbases; i++) {
1027 tmp = PyTuple_GET_ITEM(bases, i);
1028 tmptype = tmp->ob_type;
Tim Petersa91e9642001-11-14 23:32:33 +00001029 if (tmptype == &PyClass_Type)
1030 continue; /* Special case classic classes */
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001031 if (PyType_IsSubtype(winner, tmptype))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001032 continue;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001033 if (PyType_IsSubtype(tmptype, winner)) {
1034 winner = tmptype;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001035 continue;
1036 }
1037 PyErr_SetString(PyExc_TypeError,
1038 "metatype conflict among bases");
1039 return NULL;
1040 }
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001041 if (winner != metatype) {
1042 if (winner->tp_new != type_new) /* Pass it to the winner */
1043 return winner->tp_new(winner, args, kwds);
1044 metatype = winner;
1045 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001046
1047 /* Adjust for empty tuple bases */
1048 if (nbases == 0) {
1049 bases = Py_BuildValue("(O)", &PyBaseObject_Type);
1050 if (bases == NULL)
1051 return NULL;
1052 nbases = 1;
1053 }
1054 else
1055 Py_INCREF(bases);
1056
1057 /* XXX From here until type is allocated, "return NULL" leaks bases! */
1058
1059 /* Calculate best base, and check that all bases are type objects */
1060 base = best_base(bases);
1061 if (base == NULL)
1062 return NULL;
1063 if (!PyType_HasFeature(base, Py_TPFLAGS_BASETYPE)) {
1064 PyErr_Format(PyExc_TypeError,
1065 "type '%.100s' is not an acceptable base type",
1066 base->tp_name);
1067 return NULL;
1068 }
1069
Tim Peters6d6c1a32001-08-02 04:15:00 +00001070 /* Check for a __slots__ sequence variable in dict, and count it */
1071 slots = PyDict_GetItemString(dict, "__slots__");
1072 nslots = 0;
Guido van Rossum9676b222001-08-17 20:32:36 +00001073 add_dict = 0;
1074 add_weak = 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001075 if (slots != NULL) {
1076 /* Make it into a tuple */
1077 if (PyString_Check(slots))
1078 slots = Py_BuildValue("(O)", slots);
1079 else
1080 slots = PySequence_Tuple(slots);
1081 if (slots == NULL)
1082 return NULL;
1083 nslots = PyTuple_GET_SIZE(slots);
Guido van Rossumc4141872001-08-30 04:43:35 +00001084 if (nslots > 0 && base->tp_itemsize != 0) {
1085 PyErr_Format(PyExc_TypeError,
1086 "nonempty __slots__ "
1087 "not supported for subtype of '%s'",
1088 base->tp_name);
1089 return NULL;
1090 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001091 for (i = 0; i < nslots; i++) {
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001092 if (!valid_identifier(PyTuple_GET_ITEM(slots, i))) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001093 Py_DECREF(slots);
1094 return NULL;
1095 }
1096 }
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001097
1098 newslots = PyTuple_New(nslots);
1099 if (newslots == NULL)
1100 return NULL;
1101 for (i = 0; i < nslots; i++) {
1102 tmp = PyTuple_GET_ITEM(slots, i);
1103 if (_Py_Mangle(PyString_AS_STRING(name),
1104 PyString_AS_STRING(tmp),
1105 buffer, sizeof(buffer)))
1106 {
1107 tmp = PyString_FromString(buffer);
1108 } else {
1109 Py_INCREF(tmp);
1110 }
1111 PyTuple_SET_ITEM(newslots, i, tmp);
1112 }
1113 Py_DECREF(slots);
1114 slots = newslots;
1115
Tim Peters6d6c1a32001-08-02 04:15:00 +00001116 }
Guido van Rossum0628dcf2002-03-14 23:03:14 +00001117 if (slots != NULL) {
1118 /* See if *this* class defines __getstate__ */
1119 PyObject *getstate = PyDict_GetItemString(dict,
1120 "__getstate__");
1121 if (getstate == NULL) {
1122 /* If not, provide a bozo that raises TypeError */
1123 if (bozo_obj == NULL) {
1124 bozo_obj = PyCFunction_New(&bozo_ml, NULL);
1125 if (bozo_obj == NULL) {
1126 /* XXX decref various things */
1127 return NULL;
1128 }
1129 }
1130 if (PyDict_SetItemString(dict,
1131 "__getstate__",
1132 bozo_obj) < 0) {
1133 /* XXX decref various things */
1134 return NULL;
1135 }
1136 }
1137 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001138 if (slots == NULL && base->tp_dictoffset == 0 &&
1139 (base->tp_setattro == PyObject_GenericSetAttr ||
Guido van Rossum9676b222001-08-17 20:32:36 +00001140 base->tp_setattro == NULL)) {
Guido van Rossum9676b222001-08-17 20:32:36 +00001141 add_dict++;
1142 }
Guido van Rossumc4141872001-08-30 04:43:35 +00001143 if (slots == NULL && base->tp_weaklistoffset == 0 &&
1144 base->tp_itemsize == 0) {
Guido van Rossum9676b222001-08-17 20:32:36 +00001145 nslots++;
1146 add_weak++;
1147 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001148
1149 /* XXX From here until type is safely allocated,
1150 "return NULL" may leak slots! */
1151
1152 /* Allocate the type object */
1153 type = (PyTypeObject *)metatype->tp_alloc(metatype, nslots);
1154 if (type == NULL)
1155 return NULL;
1156
1157 /* Keep name and slots alive in the extended type object */
1158 et = (etype *)type;
1159 Py_INCREF(name);
1160 et->name = name;
1161 et->slots = slots;
1162
Guido van Rossumdc91b992001-08-08 22:26:22 +00001163 /* Initialize tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001164 type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE |
1165 Py_TPFLAGS_BASETYPE;
Guido van Rossum048eb752001-10-02 21:24:57 +00001166 if (base->tp_flags & Py_TPFLAGS_HAVE_GC)
1167 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossumdc91b992001-08-08 22:26:22 +00001168
1169 /* It's a new-style number unless it specifically inherits any
1170 old-style numeric behavior */
1171 if ((base->tp_flags & Py_TPFLAGS_CHECKTYPES) ||
1172 (base->tp_as_number == NULL))
1173 type->tp_flags |= Py_TPFLAGS_CHECKTYPES;
1174
1175 /* Initialize essential fields */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001176 type->tp_as_number = &et->as_number;
1177 type->tp_as_sequence = &et->as_sequence;
1178 type->tp_as_mapping = &et->as_mapping;
1179 type->tp_as_buffer = &et->as_buffer;
1180 type->tp_name = PyString_AS_STRING(name);
1181
1182 /* Set tp_base and tp_bases */
1183 type->tp_bases = bases;
1184 Py_INCREF(base);
1185 type->tp_base = base;
1186
Guido van Rossum687ae002001-10-15 22:03:32 +00001187 /* Initialize tp_dict from passed-in dict */
1188 type->tp_dict = dict = PyDict_Copy(dict);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001189 if (dict == NULL) {
1190 Py_DECREF(type);
1191 return NULL;
1192 }
1193
Guido van Rossumc3542212001-08-16 09:18:56 +00001194 /* Set __module__ in the dict */
1195 if (PyDict_GetItemString(dict, "__module__") == NULL) {
1196 tmp = PyEval_GetGlobals();
1197 if (tmp != NULL) {
1198 tmp = PyDict_GetItemString(tmp, "__name__");
1199 if (tmp != NULL) {
1200 if (PyDict_SetItemString(dict, "__module__",
1201 tmp) < 0)
1202 return NULL;
1203 }
1204 }
1205 }
1206
Tim Peters2f93e282001-10-04 05:27:00 +00001207 /* Set tp_doc to a copy of dict['__doc__'], if the latter is there
Tim Peters24008312002-03-17 18:56:20 +00001208 and is a string. The __doc__ accessor will first look for tp_doc;
1209 if that fails, it will still look into __dict__.
Tim Peters2f93e282001-10-04 05:27:00 +00001210 */
1211 {
1212 PyObject *doc = PyDict_GetItemString(dict, "__doc__");
1213 if (doc != NULL && PyString_Check(doc)) {
1214 const size_t n = (size_t)PyString_GET_SIZE(doc);
Tim Peters59f809d2001-10-04 05:43:02 +00001215 type->tp_doc = (char *)PyObject_MALLOC(n+1);
Tim Peters2f93e282001-10-04 05:27:00 +00001216 if (type->tp_doc == NULL) {
1217 Py_DECREF(type);
1218 return NULL;
1219 }
1220 memcpy(type->tp_doc, PyString_AS_STRING(doc), n+1);
1221 }
1222 }
1223
Tim Peters6d6c1a32001-08-02 04:15:00 +00001224 /* Special-case __new__: if it's a plain function,
1225 make it a static function */
1226 tmp = PyDict_GetItemString(dict, "__new__");
1227 if (tmp != NULL && PyFunction_Check(tmp)) {
1228 tmp = PyStaticMethod_New(tmp);
1229 if (tmp == NULL) {
1230 Py_DECREF(type);
1231 return NULL;
1232 }
1233 PyDict_SetItemString(dict, "__new__", tmp);
1234 Py_DECREF(tmp);
1235 }
1236
1237 /* Add descriptors for custom slots from __slots__, or for __dict__ */
1238 mp = et->members;
Neil Schemenauerc806c882001-08-29 23:54:54 +00001239 slotoffset = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001240 if (slots != NULL) {
1241 for (i = 0; i < nslots; i++, mp++) {
1242 mp->name = PyString_AS_STRING(
1243 PyTuple_GET_ITEM(slots, i));
Guido van Rossum64b206c2001-12-04 17:13:22 +00001244 mp->type = T_OBJECT_EX;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001245 mp->offset = slotoffset;
Guido van Rossum9676b222001-08-17 20:32:36 +00001246 if (base->tp_weaklistoffset == 0 &&
Guido van Rossum64b206c2001-12-04 17:13:22 +00001247 strcmp(mp->name, "__weakref__") == 0) {
1248 mp->type = T_OBJECT;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001249 mp->flags = READONLY;
Guido van Rossum9676b222001-08-17 20:32:36 +00001250 type->tp_weaklistoffset = slotoffset;
Guido van Rossum64b206c2001-12-04 17:13:22 +00001251 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001252 slotoffset += sizeof(PyObject *);
1253 }
1254 }
Guido van Rossum9676b222001-08-17 20:32:36 +00001255 else {
1256 if (add_dict) {
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001257 if (base->tp_itemsize)
Guido van Rossum048eb752001-10-02 21:24:57 +00001258 type->tp_dictoffset =
1259 -(long)sizeof(PyObject *);
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001260 else
1261 type->tp_dictoffset = slotoffset;
Guido van Rossum9676b222001-08-17 20:32:36 +00001262 slotoffset += sizeof(PyObject *);
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001263 type->tp_getset = subtype_getsets;
Guido van Rossum9676b222001-08-17 20:32:36 +00001264 }
1265 if (add_weak) {
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001266 assert(!base->tp_itemsize);
Guido van Rossum9676b222001-08-17 20:32:36 +00001267 type->tp_weaklistoffset = slotoffset;
1268 mp->name = "__weakref__";
1269 mp->type = T_OBJECT;
1270 mp->offset = slotoffset;
Tim Peters26f68f52001-09-18 00:23:33 +00001271 mp->flags = READONLY;
Guido van Rossum9676b222001-08-17 20:32:36 +00001272 mp++;
1273 slotoffset += sizeof(PyObject *);
1274 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001275 }
1276 type->tp_basicsize = slotoffset;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001277 type->tp_itemsize = base->tp_itemsize;
Guido van Rossum13d52f02001-08-10 21:24:08 +00001278 type->tp_members = et->members;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001279
1280 /* Special case some slots */
1281 if (type->tp_dictoffset != 0 || nslots > 0) {
1282 if (base->tp_getattr == NULL && base->tp_getattro == NULL)
1283 type->tp_getattro = PyObject_GenericGetAttr;
1284 if (base->tp_setattr == NULL && base->tp_setattro == NULL)
1285 type->tp_setattro = PyObject_GenericSetAttr;
1286 }
1287 type->tp_dealloc = subtype_dealloc;
1288
Guido van Rossum9475a232001-10-05 20:51:39 +00001289 /* Enable GC unless there are really no instance variables possible */
1290 if (!(type->tp_basicsize == sizeof(PyObject) &&
1291 type->tp_itemsize == 0))
1292 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
1293
Tim Peters6d6c1a32001-08-02 04:15:00 +00001294 /* Always override allocation strategy to use regular heap */
1295 type->tp_alloc = PyType_GenericAlloc;
Guido van Rossum048eb752001-10-02 21:24:57 +00001296 if (type->tp_flags & Py_TPFLAGS_HAVE_GC) {
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00001297 type->tp_free = PyObject_GC_Del;
Guido van Rossum9475a232001-10-05 20:51:39 +00001298 type->tp_traverse = subtype_traverse;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001299 type->tp_clear = subtype_clear;
Guido van Rossum048eb752001-10-02 21:24:57 +00001300 }
1301 else
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00001302 type->tp_free = PyObject_Del;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001303
1304 /* Initialize the rest */
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001305 if (PyType_Ready(type) < 0) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001306 Py_DECREF(type);
1307 return NULL;
1308 }
1309
Guido van Rossum7b9144b2001-10-09 19:39:46 +00001310 /* Put the proper slots in place */
1311 fixup_slot_dispatchers(type);
Guido van Rossumf040ede2001-08-07 16:40:56 +00001312
Tim Peters6d6c1a32001-08-02 04:15:00 +00001313 return (PyObject *)type;
1314}
1315
1316/* Internal API to look for a name through the MRO.
1317 This returns a borrowed reference, and doesn't set an exception! */
1318PyObject *
1319_PyType_Lookup(PyTypeObject *type, PyObject *name)
1320{
1321 int i, n;
Tim Petersa91e9642001-11-14 23:32:33 +00001322 PyObject *mro, *res, *base, *dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001323
Guido van Rossum687ae002001-10-15 22:03:32 +00001324 /* Look in tp_dict of types in MRO */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001325 mro = type->tp_mro;
Guido van Rossum23094982002-06-10 14:30:43 +00001326
1327 /* If mro is NULL, the type is either not yet initialized
1328 by PyType_Ready(), or already cleared by type_clear().
1329 Either way the safest thing to do is to return NULL. */
1330 if (mro == NULL)
1331 return NULL;
1332
Tim Peters6d6c1a32001-08-02 04:15:00 +00001333 assert(PyTuple_Check(mro));
1334 n = PyTuple_GET_SIZE(mro);
1335 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00001336 base = PyTuple_GET_ITEM(mro, i);
1337 if (PyClass_Check(base))
1338 dict = ((PyClassObject *)base)->cl_dict;
1339 else {
1340 assert(PyType_Check(base));
1341 dict = ((PyTypeObject *)base)->tp_dict;
1342 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001343 assert(dict && PyDict_Check(dict));
1344 res = PyDict_GetItem(dict, name);
1345 if (res != NULL)
1346 return res;
1347 }
1348 return NULL;
1349}
1350
1351/* This is similar to PyObject_GenericGetAttr(),
1352 but uses _PyType_Lookup() instead of just looking in type->tp_dict. */
1353static PyObject *
1354type_getattro(PyTypeObject *type, PyObject *name)
1355{
1356 PyTypeObject *metatype = type->ob_type;
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001357 PyObject *meta_attribute, *attribute;
1358 descrgetfunc meta_get;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001359
1360 /* Initialize this type (we'll assume the metatype is initialized) */
1361 if (type->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001362 if (PyType_Ready(type) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001363 return NULL;
1364 }
1365
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001366 /* No readable descriptor found yet */
1367 meta_get = NULL;
Tim Peters34592512002-07-11 06:23:50 +00001368
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001369 /* Look for the attribute in the metatype */
1370 meta_attribute = _PyType_Lookup(metatype, name);
1371
1372 if (meta_attribute != NULL) {
1373 meta_get = meta_attribute->ob_type->tp_descr_get;
Tim Peters34592512002-07-11 06:23:50 +00001374
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001375 if (meta_get != NULL && PyDescr_IsData(meta_attribute)) {
1376 /* Data descriptors implement tp_descr_set to intercept
1377 * writes. Assume the attribute is not overridden in
1378 * type's tp_dict (and bases): call the descriptor now.
1379 */
1380 return meta_get(meta_attribute, (PyObject *)type,
1381 (PyObject *)metatype);
1382 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001383 }
1384
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001385 /* No data descriptor found on metatype. Look in tp_dict of this
1386 * type and its bases */
1387 attribute = _PyType_Lookup(type, name);
1388 if (attribute != NULL) {
1389 /* Implement descriptor functionality, if any */
1390 descrgetfunc local_get = attribute->ob_type->tp_descr_get;
1391 if (local_get != NULL) {
1392 /* NULL 2nd argument indicates the descriptor was
1393 * found on the target object itself (or a base) */
1394 return local_get(attribute, (PyObject *)NULL,
1395 (PyObject *)type);
1396 }
Tim Peters34592512002-07-11 06:23:50 +00001397
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001398 Py_INCREF(attribute);
1399 return attribute;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001400 }
1401
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001402 /* No attribute found in local __dict__ (or bases): use the
1403 * descriptor from the metatype, if any */
1404 if (meta_get != NULL)
1405 return meta_get(meta_attribute, (PyObject *)type,
1406 (PyObject *)metatype);
1407
1408 /* If an ordinary attribute was found on the metatype, return it now */
1409 if (meta_attribute != NULL) {
1410 Py_INCREF(meta_attribute);
1411 return meta_attribute;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001412 }
1413
1414 /* Give up */
1415 PyErr_Format(PyExc_AttributeError,
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001416 "type object '%.50s' has no attribute '%.400s'",
1417 type->tp_name, PyString_AS_STRING(name));
Tim Peters6d6c1a32001-08-02 04:15:00 +00001418 return NULL;
1419}
1420
1421static int
1422type_setattro(PyTypeObject *type, PyObject *name, PyObject *value)
1423{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001424 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
1425 PyErr_Format(
1426 PyExc_TypeError,
1427 "can't set attributes of built-in/extension type '%s'",
1428 type->tp_name);
1429 return -1;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00001430 }
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001431 if (PyObject_GenericSetAttr((PyObject *)type, name, value) < 0)
1432 return -1;
1433 return update_slot(type, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001434}
1435
1436static void
1437type_dealloc(PyTypeObject *type)
1438{
1439 etype *et;
1440
1441 /* Assert this is a heap-allocated type object */
1442 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00001443 _PyObject_GC_UNTRACK(type);
Guido van Rossum1c450732001-10-08 15:18:27 +00001444 PyObject_ClearWeakRefs((PyObject *)type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001445 et = (etype *)type;
1446 Py_XDECREF(type->tp_base);
1447 Py_XDECREF(type->tp_dict);
1448 Py_XDECREF(type->tp_bases);
1449 Py_XDECREF(type->tp_mro);
Guido van Rossum687ae002001-10-15 22:03:32 +00001450 Py_XDECREF(type->tp_cache);
Guido van Rossum1c450732001-10-08 15:18:27 +00001451 Py_XDECREF(type->tp_subclasses);
Neal Norwitzcee5ca02002-07-30 00:42:06 +00001452 PyObject_Free(type->tp_doc);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001453 Py_XDECREF(et->name);
1454 Py_XDECREF(et->slots);
1455 type->ob_type->tp_free((PyObject *)type);
1456}
1457
Guido van Rossum1c450732001-10-08 15:18:27 +00001458static PyObject *
1459type_subclasses(PyTypeObject *type, PyObject *args_ignored)
1460{
1461 PyObject *list, *raw, *ref;
1462 int i, n;
1463
1464 list = PyList_New(0);
1465 if (list == NULL)
1466 return NULL;
1467 raw = type->tp_subclasses;
1468 if (raw == NULL)
1469 return list;
1470 assert(PyList_Check(raw));
1471 n = PyList_GET_SIZE(raw);
1472 for (i = 0; i < n; i++) {
1473 ref = PyList_GET_ITEM(raw, i);
Tim Peters44383382001-10-08 16:49:26 +00001474 assert(PyWeakref_CheckRef(ref));
Guido van Rossum1c450732001-10-08 15:18:27 +00001475 ref = PyWeakref_GET_OBJECT(ref);
1476 if (ref != Py_None) {
1477 if (PyList_Append(list, ref) < 0) {
1478 Py_DECREF(list);
1479 return NULL;
1480 }
1481 }
1482 }
1483 return list;
1484}
1485
Tim Peters6d6c1a32001-08-02 04:15:00 +00001486static PyMethodDef type_methods[] = {
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001487 {"mro", (PyCFunction)mro_external, METH_NOARGS,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001488 "mro() -> list\nreturn a type's method resolution order"},
Guido van Rossum1c450732001-10-08 15:18:27 +00001489 {"__subclasses__", (PyCFunction)type_subclasses, METH_NOARGS,
1490 "__subclasses__() -> list of immediate subclasses"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00001491 {0}
1492};
1493
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001494PyDoc_STRVAR(type_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001495"type(object) -> the object's type\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001496"type(name, bases, dict) -> a new type");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001497
Guido van Rossum048eb752001-10-02 21:24:57 +00001498static int
1499type_traverse(PyTypeObject *type, visitproc visit, void *arg)
1500{
Guido van Rossum048eb752001-10-02 21:24:57 +00001501 int err;
1502
Guido van Rossuma3862092002-06-10 15:24:42 +00001503 /* Because of type_is_gc(), the collector only calls this
1504 for heaptypes. */
1505 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00001506
1507#define VISIT(SLOT) \
1508 if (SLOT) { \
1509 err = visit((PyObject *)(SLOT), arg); \
1510 if (err) \
1511 return err; \
1512 }
1513
1514 VISIT(type->tp_dict);
Guido van Rossum687ae002001-10-15 22:03:32 +00001515 VISIT(type->tp_cache);
Guido van Rossum048eb752001-10-02 21:24:57 +00001516 VISIT(type->tp_mro);
1517 VISIT(type->tp_bases);
1518 VISIT(type->tp_base);
Guido van Rossuma3862092002-06-10 15:24:42 +00001519
1520 /* There's no need to visit type->tp_subclasses or
1521 ((etype *)type)->slots, because they can't be involved
1522 in cycles; tp_subclasses is a list of weak references,
1523 and slots is a tuple of strings. */
Guido van Rossum048eb752001-10-02 21:24:57 +00001524
1525#undef VISIT
1526
1527 return 0;
1528}
1529
1530static int
1531type_clear(PyTypeObject *type)
1532{
Guido van Rossum048eb752001-10-02 21:24:57 +00001533 PyObject *tmp;
1534
Guido van Rossuma3862092002-06-10 15:24:42 +00001535 /* Because of type_is_gc(), the collector only calls this
1536 for heaptypes. */
1537 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00001538
1539#define CLEAR(SLOT) \
1540 if (SLOT) { \
1541 tmp = (PyObject *)(SLOT); \
1542 SLOT = NULL; \
1543 Py_DECREF(tmp); \
1544 }
1545
Guido van Rossuma3862092002-06-10 15:24:42 +00001546 /* The only field we need to clear is tp_mro, which is part of a
1547 hard cycle (its first element is the class itself) that won't
1548 be broken otherwise (it's a tuple and tuples don't have a
1549 tp_clear handler). None of the other fields need to be
1550 cleared, and here's why:
Guido van Rossum048eb752001-10-02 21:24:57 +00001551
Guido van Rossuma3862092002-06-10 15:24:42 +00001552 tp_dict:
1553 It is a dict, so the collector will call its tp_clear.
1554
1555 tp_cache:
1556 Not used; if it were, it would be a dict.
1557
1558 tp_bases, tp_base:
1559 If these are involved in a cycle, there must be at least
1560 one other, mutable object in the cycle, e.g. a base
1561 class's dict; the cycle will be broken that way.
1562
1563 tp_subclasses:
1564 A list of weak references can't be part of a cycle; and
1565 lists have their own tp_clear.
1566
1567 slots (in etype):
1568 A tuple of strings can't be part of a cycle.
1569 */
1570
1571 CLEAR(type->tp_mro);
Tim Peters2f93e282001-10-04 05:27:00 +00001572
Guido van Rossum048eb752001-10-02 21:24:57 +00001573#undef CLEAR
1574
1575 return 0;
1576}
1577
1578static int
1579type_is_gc(PyTypeObject *type)
1580{
1581 return type->tp_flags & Py_TPFLAGS_HEAPTYPE;
1582}
1583
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001584PyTypeObject PyType_Type = {
1585 PyObject_HEAD_INIT(&PyType_Type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001586 0, /* ob_size */
1587 "type", /* tp_name */
1588 sizeof(etype), /* tp_basicsize */
Guido van Rossum6f799372001-09-20 20:46:19 +00001589 sizeof(PyMemberDef), /* tp_itemsize */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001590 (destructor)type_dealloc, /* tp_dealloc */
1591 0, /* tp_print */
1592 0, /* tp_getattr */
1593 0, /* tp_setattr */
1594 type_compare, /* tp_compare */
1595 (reprfunc)type_repr, /* tp_repr */
1596 0, /* tp_as_number */
1597 0, /* tp_as_sequence */
1598 0, /* tp_as_mapping */
1599 (hashfunc)_Py_HashPointer, /* tp_hash */
1600 (ternaryfunc)type_call, /* tp_call */
1601 0, /* tp_str */
1602 (getattrofunc)type_getattro, /* tp_getattro */
1603 (setattrofunc)type_setattro, /* tp_setattro */
1604 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00001605 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
1606 Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001607 type_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00001608 (traverseproc)type_traverse, /* tp_traverse */
1609 (inquiry)type_clear, /* tp_clear */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001610 0, /* tp_richcompare */
Guido van Rossum1c450732001-10-08 15:18:27 +00001611 offsetof(PyTypeObject, tp_weaklist), /* tp_weaklistoffset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001612 0, /* tp_iter */
1613 0, /* tp_iternext */
1614 type_methods, /* tp_methods */
1615 type_members, /* tp_members */
1616 type_getsets, /* tp_getset */
1617 0, /* tp_base */
1618 0, /* tp_dict */
1619 0, /* tp_descr_get */
1620 0, /* tp_descr_set */
1621 offsetof(PyTypeObject, tp_dict), /* tp_dictoffset */
1622 0, /* tp_init */
1623 0, /* tp_alloc */
1624 type_new, /* tp_new */
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00001625 PyObject_GC_Del, /* tp_free */
Guido van Rossum048eb752001-10-02 21:24:57 +00001626 (inquiry)type_is_gc, /* tp_is_gc */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001627};
Tim Peters6d6c1a32001-08-02 04:15:00 +00001628
1629
1630/* The base type of all types (eventually)... except itself. */
1631
1632static int
1633object_init(PyObject *self, PyObject *args, PyObject *kwds)
1634{
1635 return 0;
1636}
1637
1638static void
1639object_dealloc(PyObject *self)
1640{
1641 self->ob_type->tp_free(self);
1642}
1643
Guido van Rossum8e248182001-08-12 05:17:56 +00001644static PyObject *
1645object_repr(PyObject *self)
1646{
Guido van Rossum76e69632001-08-16 18:52:43 +00001647 PyTypeObject *type;
Barry Warsaw7ce36942001-08-24 18:34:26 +00001648 PyObject *mod, *name, *rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00001649
Guido van Rossum76e69632001-08-16 18:52:43 +00001650 type = self->ob_type;
1651 mod = type_module(type, NULL);
1652 if (mod == NULL)
1653 PyErr_Clear();
1654 else if (!PyString_Check(mod)) {
1655 Py_DECREF(mod);
1656 mod = NULL;
1657 }
1658 name = type_name(type, NULL);
1659 if (name == NULL)
1660 return NULL;
1661 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__"))
Guido van Rossumff0e6d62001-09-24 16:03:59 +00001662 rtn = PyString_FromFormat("<%s.%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00001663 PyString_AS_STRING(mod),
1664 PyString_AS_STRING(name),
1665 self);
Guido van Rossum76e69632001-08-16 18:52:43 +00001666 else
Guido van Rossumff0e6d62001-09-24 16:03:59 +00001667 rtn = PyString_FromFormat("<%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00001668 type->tp_name, self);
Guido van Rossum76e69632001-08-16 18:52:43 +00001669 Py_XDECREF(mod);
1670 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +00001671 return rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00001672}
1673
Guido van Rossumb8f63662001-08-15 23:57:02 +00001674static PyObject *
1675object_str(PyObject *self)
1676{
1677 unaryfunc f;
1678
1679 f = self->ob_type->tp_repr;
1680 if (f == NULL)
1681 f = object_repr;
1682 return f(self);
1683}
1684
Guido van Rossum8e248182001-08-12 05:17:56 +00001685static long
1686object_hash(PyObject *self)
1687{
1688 return _Py_HashPointer(self);
1689}
Guido van Rossum8e248182001-08-12 05:17:56 +00001690
Guido van Rossum5c294fb2001-09-25 03:43:42 +00001691static PyObject *
1692object_get_class(PyObject *self, void *closure)
1693{
1694 Py_INCREF(self->ob_type);
1695 return (PyObject *)(self->ob_type);
1696}
1697
1698static int
1699equiv_structs(PyTypeObject *a, PyTypeObject *b)
1700{
1701 return a == b ||
1702 (a != NULL &&
1703 b != NULL &&
1704 a->tp_basicsize == b->tp_basicsize &&
1705 a->tp_itemsize == b->tp_itemsize &&
1706 a->tp_dictoffset == b->tp_dictoffset &&
1707 a->tp_weaklistoffset == b->tp_weaklistoffset &&
1708 ((a->tp_flags & Py_TPFLAGS_HAVE_GC) ==
1709 (b->tp_flags & Py_TPFLAGS_HAVE_GC)));
1710}
1711
1712static int
1713same_slots_added(PyTypeObject *a, PyTypeObject *b)
1714{
1715 PyTypeObject *base = a->tp_base;
1716 int size;
1717
1718 if (base != b->tp_base)
1719 return 0;
1720 if (equiv_structs(a, base) && equiv_structs(b, base))
1721 return 1;
1722 size = base->tp_basicsize;
1723 if (a->tp_dictoffset == size && b->tp_dictoffset == size)
1724 size += sizeof(PyObject *);
1725 if (a->tp_weaklistoffset == size && b->tp_weaklistoffset == size)
1726 size += sizeof(PyObject *);
1727 return size == a->tp_basicsize && size == b->tp_basicsize;
1728}
1729
1730static int
1731object_set_class(PyObject *self, PyObject *value, void *closure)
1732{
1733 PyTypeObject *old = self->ob_type;
1734 PyTypeObject *new, *newbase, *oldbase;
1735
Guido van Rossumb6b89422002-04-15 01:03:30 +00001736 if (value == NULL) {
1737 PyErr_SetString(PyExc_TypeError,
1738 "can't delete __class__ attribute");
1739 return -1;
1740 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00001741 if (!PyType_Check(value)) {
1742 PyErr_Format(PyExc_TypeError,
1743 "__class__ must be set to new-style class, not '%s' object",
1744 value->ob_type->tp_name);
1745 return -1;
1746 }
1747 new = (PyTypeObject *)value;
Guido van Rossum40af8892002-08-10 05:42:07 +00001748 if (!(new->tp_flags & Py_TPFLAGS_HEAPTYPE) ||
1749 !(old->tp_flags & Py_TPFLAGS_HEAPTYPE))
1750 {
1751 PyErr_Format(PyExc_TypeError,
1752 "__class__ assignment: only for heap types");
1753 return -1;
1754 }
Guido van Rossum9ee4b942002-05-24 18:47:47 +00001755 if (new->tp_dealloc != old->tp_dealloc ||
1756 new->tp_free != old->tp_free)
1757 {
1758 PyErr_Format(PyExc_TypeError,
1759 "__class__ assignment: "
1760 "'%s' deallocator differs from '%s'",
1761 new->tp_name,
1762 old->tp_name);
1763 return -1;
1764 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00001765 newbase = new;
1766 oldbase = old;
1767 while (equiv_structs(newbase, newbase->tp_base))
1768 newbase = newbase->tp_base;
1769 while (equiv_structs(oldbase, oldbase->tp_base))
1770 oldbase = oldbase->tp_base;
1771 if (newbase != oldbase &&
1772 (newbase->tp_base != oldbase->tp_base ||
1773 !same_slots_added(newbase, oldbase))) {
1774 PyErr_Format(PyExc_TypeError,
1775 "__class__ assignment: "
1776 "'%s' object layout differs from '%s'",
Tim Peters2f93e282001-10-04 05:27:00 +00001777 new->tp_name,
Guido van Rossum5c294fb2001-09-25 03:43:42 +00001778 old->tp_name);
1779 return -1;
1780 }
Guido van Rossum40af8892002-08-10 05:42:07 +00001781 Py_INCREF(new);
Guido van Rossum5c294fb2001-09-25 03:43:42 +00001782 self->ob_type = new;
Guido van Rossum40af8892002-08-10 05:42:07 +00001783 Py_DECREF(old);
Guido van Rossum5c294fb2001-09-25 03:43:42 +00001784 return 0;
1785}
1786
1787static PyGetSetDef object_getsets[] = {
1788 {"__class__", object_get_class, object_set_class,
1789 "the object's class"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00001790 {0}
1791};
1792
Guido van Rossum3926a632001-09-25 16:25:58 +00001793static PyObject *
1794object_reduce(PyObject *self, PyObject *args)
1795{
1796 /* Call copy_reg._reduce(self) */
1797 static PyObject *copy_reg_str;
1798 PyObject *copy_reg, *res;
1799
1800 if (!copy_reg_str) {
1801 copy_reg_str = PyString_InternFromString("copy_reg");
1802 if (copy_reg_str == NULL)
1803 return NULL;
1804 }
1805 copy_reg = PyImport_Import(copy_reg_str);
1806 if (!copy_reg)
1807 return NULL;
1808 res = PyEval_CallMethod(copy_reg, "_reduce", "(O)", self);
1809 Py_DECREF(copy_reg);
1810 return res;
1811}
1812
1813static PyMethodDef object_methods[] = {
1814 {"__reduce__", object_reduce, METH_NOARGS, "helper for pickle"},
1815 {0}
1816};
1817
Tim Peters6d6c1a32001-08-02 04:15:00 +00001818PyTypeObject PyBaseObject_Type = {
1819 PyObject_HEAD_INIT(&PyType_Type)
1820 0, /* ob_size */
1821 "object", /* tp_name */
1822 sizeof(PyObject), /* tp_basicsize */
1823 0, /* tp_itemsize */
1824 (destructor)object_dealloc, /* tp_dealloc */
1825 0, /* tp_print */
1826 0, /* tp_getattr */
1827 0, /* tp_setattr */
1828 0, /* tp_compare */
Guido van Rossumb8f63662001-08-15 23:57:02 +00001829 object_repr, /* tp_repr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001830 0, /* tp_as_number */
1831 0, /* tp_as_sequence */
1832 0, /* tp_as_mapping */
Guido van Rossumb8f63662001-08-15 23:57:02 +00001833 object_hash, /* tp_hash */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001834 0, /* tp_call */
Guido van Rossumb8f63662001-08-15 23:57:02 +00001835 object_str, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001836 PyObject_GenericGetAttr, /* tp_getattro */
Guido van Rossum13d52f02001-08-10 21:24:08 +00001837 PyObject_GenericSetAttr, /* tp_setattro */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001838 0, /* tp_as_buffer */
1839 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
1840 "The most base type", /* tp_doc */
1841 0, /* tp_traverse */
1842 0, /* tp_clear */
1843 0, /* tp_richcompare */
1844 0, /* tp_weaklistoffset */
1845 0, /* tp_iter */
1846 0, /* tp_iternext */
Guido van Rossum3926a632001-09-25 16:25:58 +00001847 object_methods, /* tp_methods */
Guido van Rossum5c294fb2001-09-25 03:43:42 +00001848 0, /* tp_members */
1849 object_getsets, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001850 0, /* tp_base */
1851 0, /* tp_dict */
1852 0, /* tp_descr_get */
1853 0, /* tp_descr_set */
1854 0, /* tp_dictoffset */
1855 object_init, /* tp_init */
1856 PyType_GenericAlloc, /* tp_alloc */
Guido van Rossumc11e1922001-08-09 19:38:15 +00001857 PyType_GenericNew, /* tp_new */
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00001858 PyObject_Del, /* tp_free */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001859};
1860
1861
1862/* Initialize the __dict__ in a type object */
1863
Fred Drake7bf97152002-03-28 05:33:33 +00001864static PyObject *
1865create_specialmethod(PyMethodDef *meth, PyObject *(*func)(PyObject *))
1866{
1867 PyObject *cfunc;
1868 PyObject *result;
1869
1870 cfunc = PyCFunction_New(meth, NULL);
1871 if (cfunc == NULL)
1872 return NULL;
1873 result = func(cfunc);
1874 Py_DECREF(cfunc);
1875 return result;
1876}
1877
Tim Peters6d6c1a32001-08-02 04:15:00 +00001878static int
1879add_methods(PyTypeObject *type, PyMethodDef *meth)
1880{
Guido van Rossum687ae002001-10-15 22:03:32 +00001881 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001882
1883 for (; meth->ml_name != NULL; meth++) {
1884 PyObject *descr;
1885 if (PyDict_GetItemString(dict, meth->ml_name))
1886 continue;
Fred Drake7bf97152002-03-28 05:33:33 +00001887 if (meth->ml_flags & METH_CLASS) {
1888 if (meth->ml_flags & METH_STATIC) {
1889 PyErr_SetString(PyExc_ValueError,
1890 "method cannot be both class and static");
1891 return -1;
1892 }
1893 descr = create_specialmethod(meth, PyClassMethod_New);
1894 }
1895 else if (meth->ml_flags & METH_STATIC) {
1896 descr = create_specialmethod(meth, PyStaticMethod_New);
1897 }
1898 else {
1899 descr = PyDescr_NewMethod(type, meth);
1900 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001901 if (descr == NULL)
1902 return -1;
Fred Drake7bf97152002-03-28 05:33:33 +00001903 if (PyDict_SetItemString(dict, meth->ml_name, descr) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001904 return -1;
1905 Py_DECREF(descr);
1906 }
1907 return 0;
1908}
1909
1910static int
Guido van Rossum6f799372001-09-20 20:46:19 +00001911add_members(PyTypeObject *type, PyMemberDef *memb)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001912{
Guido van Rossum687ae002001-10-15 22:03:32 +00001913 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001914
1915 for (; memb->name != NULL; memb++) {
1916 PyObject *descr;
1917 if (PyDict_GetItemString(dict, memb->name))
1918 continue;
1919 descr = PyDescr_NewMember(type, memb);
1920 if (descr == NULL)
1921 return -1;
1922 if (PyDict_SetItemString(dict, memb->name, descr) < 0)
1923 return -1;
1924 Py_DECREF(descr);
1925 }
1926 return 0;
1927}
1928
1929static int
Guido van Rossum32d34c82001-09-20 21:45:26 +00001930add_getset(PyTypeObject *type, PyGetSetDef *gsp)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001931{
Guido van Rossum687ae002001-10-15 22:03:32 +00001932 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001933
1934 for (; gsp->name != NULL; gsp++) {
1935 PyObject *descr;
1936 if (PyDict_GetItemString(dict, gsp->name))
1937 continue;
1938 descr = PyDescr_NewGetSet(type, gsp);
1939
1940 if (descr == NULL)
1941 return -1;
1942 if (PyDict_SetItemString(dict, gsp->name, descr) < 0)
1943 return -1;
1944 Py_DECREF(descr);
1945 }
1946 return 0;
1947}
1948
Guido van Rossum13d52f02001-08-10 21:24:08 +00001949static void
1950inherit_special(PyTypeObject *type, PyTypeObject *base)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001951{
1952 int oldsize, newsize;
1953
Guido van Rossum13d52f02001-08-10 21:24:08 +00001954 /* Special flag magic */
1955 if (!type->tp_as_buffer && base->tp_as_buffer) {
1956 type->tp_flags &= ~Py_TPFLAGS_HAVE_GETCHARBUFFER;
1957 type->tp_flags |=
1958 base->tp_flags & Py_TPFLAGS_HAVE_GETCHARBUFFER;
1959 }
1960 if (!type->tp_as_sequence && base->tp_as_sequence) {
1961 type->tp_flags &= ~Py_TPFLAGS_HAVE_SEQUENCE_IN;
1962 type->tp_flags |= base->tp_flags & Py_TPFLAGS_HAVE_SEQUENCE_IN;
1963 }
1964 if ((type->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS) !=
1965 (base->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS)) {
1966 if ((!type->tp_as_number && base->tp_as_number) ||
1967 (!type->tp_as_sequence && base->tp_as_sequence)) {
1968 type->tp_flags &= ~Py_TPFLAGS_HAVE_INPLACEOPS;
1969 if (!type->tp_as_number && !type->tp_as_sequence) {
1970 type->tp_flags |= base->tp_flags &
1971 Py_TPFLAGS_HAVE_INPLACEOPS;
1972 }
1973 }
1974 /* Wow */
1975 }
1976 if (!type->tp_as_number && base->tp_as_number) {
1977 type->tp_flags &= ~Py_TPFLAGS_CHECKTYPES;
1978 type->tp_flags |= base->tp_flags & Py_TPFLAGS_CHECKTYPES;
1979 }
1980
1981 /* Copying basicsize is connected to the GC flags */
Neil Schemenauerc806c882001-08-29 23:54:54 +00001982 oldsize = base->tp_basicsize;
1983 newsize = type->tp_basicsize ? type->tp_basicsize : oldsize;
1984 if (!(type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
1985 (base->tp_flags & Py_TPFLAGS_HAVE_GC) &&
Guido van Rossum13d52f02001-08-10 21:24:08 +00001986 (type->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE/*GC slots exist*/) &&
1987 (!type->tp_traverse && !type->tp_clear)) {
Neil Schemenauerc806c882001-08-29 23:54:54 +00001988 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossum13d52f02001-08-10 21:24:08 +00001989 if (type->tp_traverse == NULL)
1990 type->tp_traverse = base->tp_traverse;
1991 if (type->tp_clear == NULL)
1992 type->tp_clear = base->tp_clear;
1993 }
1994 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
Guido van Rossumf884b742001-12-17 17:14:22 +00001995 /* The condition below could use some explanation.
1996 It appears that tp_new is not inherited for static types
1997 whose base class is 'object'; this seems to be a precaution
1998 so that old extension types don't suddenly become
1999 callable (object.__new__ wouldn't insure the invariants
2000 that the extension type's own factory function ensures).
2001 Heap types, of course, are under our control, so they do
2002 inherit tp_new; static extension types that specify some
2003 other built-in type as the default are considered
2004 new-style-aware so they also inherit object.__new__. */
Guido van Rossum13d52f02001-08-10 21:24:08 +00002005 if (base != &PyBaseObject_Type ||
2006 (type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
2007 if (type->tp_new == NULL)
2008 type->tp_new = base->tp_new;
2009 }
2010 }
Neil Schemenauerc806c882001-08-29 23:54:54 +00002011 type->tp_basicsize = newsize;
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00002012
2013 /* Copy other non-function slots */
2014
2015#undef COPYVAL
2016#define COPYVAL(SLOT) \
2017 if (type->SLOT == 0) type->SLOT = base->SLOT
2018
2019 COPYVAL(tp_itemsize);
2020 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_WEAKREFS) {
2021 COPYVAL(tp_weaklistoffset);
2022 }
2023 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
2024 COPYVAL(tp_dictoffset);
2025 }
Guido van Rossum13d52f02001-08-10 21:24:08 +00002026}
2027
2028static void
2029inherit_slots(PyTypeObject *type, PyTypeObject *base)
2030{
2031 PyTypeObject *basebase;
2032
2033#undef SLOTDEFINED
Tim Peters6d6c1a32001-08-02 04:15:00 +00002034#undef COPYSLOT
2035#undef COPYNUM
2036#undef COPYSEQ
2037#undef COPYMAP
Guido van Rossum5af588b2001-10-12 14:13:21 +00002038#undef COPYBUF
Guido van Rossum13d52f02001-08-10 21:24:08 +00002039
2040#define SLOTDEFINED(SLOT) \
2041 (base->SLOT != 0 && \
2042 (basebase == NULL || base->SLOT != basebase->SLOT))
2043
Tim Peters6d6c1a32001-08-02 04:15:00 +00002044#define COPYSLOT(SLOT) \
Guido van Rossum13d52f02001-08-10 21:24:08 +00002045 if (!type->SLOT && SLOTDEFINED(SLOT)) type->SLOT = base->SLOT
Tim Peters6d6c1a32001-08-02 04:15:00 +00002046
2047#define COPYNUM(SLOT) COPYSLOT(tp_as_number->SLOT)
2048#define COPYSEQ(SLOT) COPYSLOT(tp_as_sequence->SLOT)
2049#define COPYMAP(SLOT) COPYSLOT(tp_as_mapping->SLOT)
Tim Petersfc57ccb2001-10-12 02:38:24 +00002050#define COPYBUF(SLOT) COPYSLOT(tp_as_buffer->SLOT)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002051
Guido van Rossum13d52f02001-08-10 21:24:08 +00002052 /* This won't inherit indirect slots (from tp_as_number etc.)
2053 if type doesn't provide the space. */
2054
2055 if (type->tp_as_number != NULL && base->tp_as_number != NULL) {
2056 basebase = base->tp_base;
2057 if (basebase->tp_as_number == NULL)
2058 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002059 COPYNUM(nb_add);
2060 COPYNUM(nb_subtract);
2061 COPYNUM(nb_multiply);
2062 COPYNUM(nb_divide);
2063 COPYNUM(nb_remainder);
2064 COPYNUM(nb_divmod);
2065 COPYNUM(nb_power);
2066 COPYNUM(nb_negative);
2067 COPYNUM(nb_positive);
2068 COPYNUM(nb_absolute);
2069 COPYNUM(nb_nonzero);
2070 COPYNUM(nb_invert);
2071 COPYNUM(nb_lshift);
2072 COPYNUM(nb_rshift);
2073 COPYNUM(nb_and);
2074 COPYNUM(nb_xor);
2075 COPYNUM(nb_or);
2076 COPYNUM(nb_coerce);
2077 COPYNUM(nb_int);
2078 COPYNUM(nb_long);
2079 COPYNUM(nb_float);
2080 COPYNUM(nb_oct);
2081 COPYNUM(nb_hex);
2082 COPYNUM(nb_inplace_add);
2083 COPYNUM(nb_inplace_subtract);
2084 COPYNUM(nb_inplace_multiply);
2085 COPYNUM(nb_inplace_divide);
2086 COPYNUM(nb_inplace_remainder);
2087 COPYNUM(nb_inplace_power);
2088 COPYNUM(nb_inplace_lshift);
2089 COPYNUM(nb_inplace_rshift);
2090 COPYNUM(nb_inplace_and);
2091 COPYNUM(nb_inplace_xor);
2092 COPYNUM(nb_inplace_or);
Guido van Rossumdc91b992001-08-08 22:26:22 +00002093 if (base->tp_flags & Py_TPFLAGS_CHECKTYPES) {
2094 COPYNUM(nb_true_divide);
2095 COPYNUM(nb_floor_divide);
2096 COPYNUM(nb_inplace_true_divide);
2097 COPYNUM(nb_inplace_floor_divide);
2098 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002099 }
2100
Guido van Rossum13d52f02001-08-10 21:24:08 +00002101 if (type->tp_as_sequence != NULL && base->tp_as_sequence != NULL) {
2102 basebase = base->tp_base;
2103 if (basebase->tp_as_sequence == NULL)
2104 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002105 COPYSEQ(sq_length);
2106 COPYSEQ(sq_concat);
2107 COPYSEQ(sq_repeat);
2108 COPYSEQ(sq_item);
2109 COPYSEQ(sq_slice);
2110 COPYSEQ(sq_ass_item);
2111 COPYSEQ(sq_ass_slice);
2112 COPYSEQ(sq_contains);
2113 COPYSEQ(sq_inplace_concat);
2114 COPYSEQ(sq_inplace_repeat);
2115 }
2116
Guido van Rossum13d52f02001-08-10 21:24:08 +00002117 if (type->tp_as_mapping != NULL && base->tp_as_mapping != NULL) {
2118 basebase = base->tp_base;
2119 if (basebase->tp_as_mapping == NULL)
2120 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002121 COPYMAP(mp_length);
2122 COPYMAP(mp_subscript);
2123 COPYMAP(mp_ass_subscript);
2124 }
2125
Tim Petersfc57ccb2001-10-12 02:38:24 +00002126 if (type->tp_as_buffer != NULL && base->tp_as_buffer != NULL) {
2127 basebase = base->tp_base;
2128 if (basebase->tp_as_buffer == NULL)
2129 basebase = NULL;
2130 COPYBUF(bf_getreadbuffer);
2131 COPYBUF(bf_getwritebuffer);
2132 COPYBUF(bf_getsegcount);
2133 COPYBUF(bf_getcharbuffer);
2134 }
2135
Guido van Rossum13d52f02001-08-10 21:24:08 +00002136 basebase = base->tp_base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002137
Tim Peters6d6c1a32001-08-02 04:15:00 +00002138 COPYSLOT(tp_dealloc);
2139 COPYSLOT(tp_print);
2140 if (type->tp_getattr == NULL && type->tp_getattro == NULL) {
2141 type->tp_getattr = base->tp_getattr;
2142 type->tp_getattro = base->tp_getattro;
2143 }
2144 if (type->tp_setattr == NULL && type->tp_setattro == NULL) {
2145 type->tp_setattr = base->tp_setattr;
2146 type->tp_setattro = base->tp_setattro;
2147 }
2148 /* tp_compare see tp_richcompare */
2149 COPYSLOT(tp_repr);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002150 /* tp_hash see tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002151 COPYSLOT(tp_call);
2152 COPYSLOT(tp_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002153 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00002154 if (type->tp_compare == NULL &&
2155 type->tp_richcompare == NULL &&
2156 type->tp_hash == NULL)
2157 {
Tim Peters6d6c1a32001-08-02 04:15:00 +00002158 type->tp_compare = base->tp_compare;
2159 type->tp_richcompare = base->tp_richcompare;
Guido van Rossumb8f63662001-08-15 23:57:02 +00002160 type->tp_hash = base->tp_hash;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002161 }
2162 }
2163 else {
2164 COPYSLOT(tp_compare);
2165 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002166 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_ITER) {
2167 COPYSLOT(tp_iter);
2168 COPYSLOT(tp_iternext);
2169 }
2170 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
2171 COPYSLOT(tp_descr_get);
2172 COPYSLOT(tp_descr_set);
2173 COPYSLOT(tp_dictoffset);
2174 COPYSLOT(tp_init);
2175 COPYSLOT(tp_alloc);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002176 COPYSLOT(tp_free);
Guido van Rossumcc8fe042002-04-05 17:10:16 +00002177 COPYSLOT(tp_is_gc);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002178 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002179}
2180
Jeremy Hylton938ace62002-07-17 16:30:39 +00002181static int add_operators(PyTypeObject *);
2182static int add_subclass(PyTypeObject *base, PyTypeObject *type);
Guido van Rossum13d52f02001-08-10 21:24:08 +00002183
Tim Peters6d6c1a32001-08-02 04:15:00 +00002184int
Guido van Rossum528b7eb2001-08-07 17:24:28 +00002185PyType_Ready(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002186{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002187 PyObject *dict, *bases;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002188 PyTypeObject *base;
2189 int i, n;
2190
Guido van Rossumcab05802002-06-10 15:29:03 +00002191 if (type->tp_flags & Py_TPFLAGS_READY) {
2192 assert(type->tp_dict != NULL);
Guido van Rossumd614f972001-08-10 17:39:49 +00002193 return 0;
Guido van Rossumcab05802002-06-10 15:29:03 +00002194 }
Guido van Rossumd614f972001-08-10 17:39:49 +00002195 assert((type->tp_flags & Py_TPFLAGS_READYING) == 0);
Guido van Rossumd614f972001-08-10 17:39:49 +00002196
2197 type->tp_flags |= Py_TPFLAGS_READYING;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002198
2199 /* Initialize tp_base (defaults to BaseObject unless that's us) */
2200 base = type->tp_base;
2201 if (base == NULL && type != &PyBaseObject_Type)
2202 base = type->tp_base = &PyBaseObject_Type;
2203
Guido van Rossum0986d822002-04-08 01:38:42 +00002204 /* Initialize ob_type if NULL. This means extensions that want to be
2205 compilable separately on Windows can call PyType_Ready() instead of
2206 initializing the ob_type field of their type objects. */
2207 if (type->ob_type == NULL)
2208 type->ob_type = base->ob_type;
2209
Tim Peters6d6c1a32001-08-02 04:15:00 +00002210 /* Initialize tp_bases */
2211 bases = type->tp_bases;
2212 if (bases == NULL) {
2213 if (base == NULL)
2214 bases = PyTuple_New(0);
2215 else
2216 bases = Py_BuildValue("(O)", base);
2217 if (bases == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00002218 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002219 type->tp_bases = bases;
2220 }
2221
2222 /* Initialize the base class */
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002223 if (base && base->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00002224 if (PyType_Ready(base) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00002225 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002226 }
2227
Guido van Rossum687ae002001-10-15 22:03:32 +00002228 /* Initialize tp_dict */
2229 dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002230 if (dict == NULL) {
2231 dict = PyDict_New();
2232 if (dict == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00002233 goto error;
Guido van Rossum687ae002001-10-15 22:03:32 +00002234 type->tp_dict = dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002235 }
2236
Guido van Rossum687ae002001-10-15 22:03:32 +00002237 /* Add type-specific descriptors to tp_dict */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002238 if (add_operators(type) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00002239 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002240 if (type->tp_methods != NULL) {
2241 if (add_methods(type, type->tp_methods) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00002242 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002243 }
2244 if (type->tp_members != NULL) {
2245 if (add_members(type, type->tp_members) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00002246 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002247 }
2248 if (type->tp_getset != NULL) {
2249 if (add_getset(type, type->tp_getset) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00002250 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002251 }
2252
Tim Peters6d6c1a32001-08-02 04:15:00 +00002253 /* Calculate method resolution order */
2254 if (mro_internal(type) < 0) {
Guido van Rossumd614f972001-08-10 17:39:49 +00002255 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002256 }
2257
Guido van Rossum13d52f02001-08-10 21:24:08 +00002258 /* Inherit special flags from dominant base */
2259 if (type->tp_base != NULL)
2260 inherit_special(type, type->tp_base);
2261
Tim Peters6d6c1a32001-08-02 04:15:00 +00002262 /* Initialize tp_dict properly */
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002263 bases = type->tp_mro;
2264 assert(bases != NULL);
2265 assert(PyTuple_Check(bases));
2266 n = PyTuple_GET_SIZE(bases);
2267 for (i = 1; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00002268 PyObject *b = PyTuple_GET_ITEM(bases, i);
2269 if (PyType_Check(b))
2270 inherit_slots(type, (PyTypeObject *)b);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002271 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002272
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00002273 /* if the type dictionary doesn't contain a __doc__, set it from
2274 the tp_doc slot.
2275 */
2276 if (PyDict_GetItemString(type->tp_dict, "__doc__") == NULL) {
2277 if (type->tp_doc != NULL) {
2278 PyObject *doc = PyString_FromString(type->tp_doc);
2279 PyDict_SetItemString(type->tp_dict, "__doc__", doc);
2280 Py_DECREF(doc);
2281 } else {
Guido van Rossumd4641072002-04-03 02:13:37 +00002282 PyDict_SetItemString(type->tp_dict,
2283 "__doc__", Py_None);
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00002284 }
2285 }
2286
Guido van Rossum13d52f02001-08-10 21:24:08 +00002287 /* Some more special stuff */
2288 base = type->tp_base;
2289 if (base != NULL) {
2290 if (type->tp_as_number == NULL)
2291 type->tp_as_number = base->tp_as_number;
2292 if (type->tp_as_sequence == NULL)
2293 type->tp_as_sequence = base->tp_as_sequence;
2294 if (type->tp_as_mapping == NULL)
2295 type->tp_as_mapping = base->tp_as_mapping;
2296 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002297
Guido van Rossum1c450732001-10-08 15:18:27 +00002298 /* Link into each base class's list of subclasses */
2299 bases = type->tp_bases;
2300 n = PyTuple_GET_SIZE(bases);
2301 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00002302 PyObject *b = PyTuple_GET_ITEM(bases, i);
2303 if (PyType_Check(b) &&
2304 add_subclass((PyTypeObject *)b, type) < 0)
Guido van Rossum1c450732001-10-08 15:18:27 +00002305 goto error;
2306 }
2307
Guido van Rossum13d52f02001-08-10 21:24:08 +00002308 /* All done -- set the ready flag */
Guido van Rossumd614f972001-08-10 17:39:49 +00002309 assert(type->tp_dict != NULL);
2310 type->tp_flags =
2311 (type->tp_flags & ~Py_TPFLAGS_READYING) | Py_TPFLAGS_READY;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002312 return 0;
Guido van Rossumd614f972001-08-10 17:39:49 +00002313
2314 error:
2315 type->tp_flags &= ~Py_TPFLAGS_READYING;
2316 return -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002317}
2318
Guido van Rossum1c450732001-10-08 15:18:27 +00002319static int
2320add_subclass(PyTypeObject *base, PyTypeObject *type)
2321{
2322 int i;
2323 PyObject *list, *ref, *new;
2324
2325 list = base->tp_subclasses;
2326 if (list == NULL) {
2327 base->tp_subclasses = list = PyList_New(0);
2328 if (list == NULL)
2329 return -1;
2330 }
2331 assert(PyList_Check(list));
2332 new = PyWeakref_NewRef((PyObject *)type, NULL);
2333 i = PyList_GET_SIZE(list);
2334 while (--i >= 0) {
2335 ref = PyList_GET_ITEM(list, i);
2336 assert(PyWeakref_CheckRef(ref));
2337 if (PyWeakref_GET_OBJECT(ref) == Py_None)
2338 return PyList_SetItem(list, i, new);
2339 }
2340 i = PyList_Append(list, new);
2341 Py_DECREF(new);
2342 return i;
2343}
2344
Tim Peters6d6c1a32001-08-02 04:15:00 +00002345
2346/* Generic wrappers for overloadable 'operators' such as __getitem__ */
2347
2348/* There's a wrapper *function* for each distinct function typedef used
2349 for type object slots (e.g. binaryfunc, ternaryfunc, etc.). There's a
2350 wrapper *table* for each distinct operation (e.g. __len__, __add__).
2351 Most tables have only one entry; the tables for binary operators have two
2352 entries, one regular and one with reversed arguments. */
2353
2354static PyObject *
2355wrap_inquiry(PyObject *self, PyObject *args, void *wrapped)
2356{
2357 inquiry func = (inquiry)wrapped;
2358 int res;
2359
2360 if (!PyArg_ParseTuple(args, ""))
2361 return NULL;
2362 res = (*func)(self);
2363 if (res == -1 && PyErr_Occurred())
2364 return NULL;
2365 return PyInt_FromLong((long)res);
2366}
2367
Tim Peters6d6c1a32001-08-02 04:15:00 +00002368static PyObject *
2369wrap_binaryfunc(PyObject *self, PyObject *args, void *wrapped)
2370{
2371 binaryfunc func = (binaryfunc)wrapped;
2372 PyObject *other;
2373
2374 if (!PyArg_ParseTuple(args, "O", &other))
2375 return NULL;
2376 return (*func)(self, other);
2377}
2378
2379static PyObject *
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002380wrap_binaryfunc_l(PyObject *self, PyObject *args, void *wrapped)
2381{
2382 binaryfunc func = (binaryfunc)wrapped;
2383 PyObject *other;
2384
2385 if (!PyArg_ParseTuple(args, "O", &other))
2386 return NULL;
2387 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002388 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002389 Py_INCREF(Py_NotImplemented);
2390 return Py_NotImplemented;
2391 }
2392 return (*func)(self, other);
2393}
2394
2395static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00002396wrap_binaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
2397{
2398 binaryfunc func = (binaryfunc)wrapped;
2399 PyObject *other;
2400
2401 if (!PyArg_ParseTuple(args, "O", &other))
2402 return NULL;
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002403 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002404 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002405 Py_INCREF(Py_NotImplemented);
2406 return Py_NotImplemented;
2407 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002408 return (*func)(other, self);
2409}
2410
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00002411static PyObject *
2412wrap_coercefunc(PyObject *self, PyObject *args, void *wrapped)
2413{
2414 coercion func = (coercion)wrapped;
2415 PyObject *other, *res;
2416 int ok;
2417
2418 if (!PyArg_ParseTuple(args, "O", &other))
2419 return NULL;
2420 ok = func(&self, &other);
2421 if (ok < 0)
2422 return NULL;
2423 if (ok > 0) {
2424 Py_INCREF(Py_NotImplemented);
2425 return Py_NotImplemented;
2426 }
2427 res = PyTuple_New(2);
2428 if (res == NULL) {
2429 Py_DECREF(self);
2430 Py_DECREF(other);
2431 return NULL;
2432 }
2433 PyTuple_SET_ITEM(res, 0, self);
2434 PyTuple_SET_ITEM(res, 1, other);
2435 return res;
2436}
2437
Tim Peters6d6c1a32001-08-02 04:15:00 +00002438static PyObject *
2439wrap_ternaryfunc(PyObject *self, PyObject *args, void *wrapped)
2440{
2441 ternaryfunc func = (ternaryfunc)wrapped;
2442 PyObject *other;
2443 PyObject *third = Py_None;
2444
2445 /* Note: This wrapper only works for __pow__() */
2446
2447 if (!PyArg_ParseTuple(args, "O|O", &other, &third))
2448 return NULL;
2449 return (*func)(self, other, third);
2450}
2451
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00002452static PyObject *
2453wrap_ternaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
2454{
2455 ternaryfunc func = (ternaryfunc)wrapped;
2456 PyObject *other;
2457 PyObject *third = Py_None;
2458
2459 /* Note: This wrapper only works for __pow__() */
2460
2461 if (!PyArg_ParseTuple(args, "O|O", &other, &third))
2462 return NULL;
2463 return (*func)(other, self, third);
2464}
2465
Tim Peters6d6c1a32001-08-02 04:15:00 +00002466static PyObject *
2467wrap_unaryfunc(PyObject *self, PyObject *args, void *wrapped)
2468{
2469 unaryfunc func = (unaryfunc)wrapped;
2470
2471 if (!PyArg_ParseTuple(args, ""))
2472 return NULL;
2473 return (*func)(self);
2474}
2475
Tim Peters6d6c1a32001-08-02 04:15:00 +00002476static PyObject *
2477wrap_intargfunc(PyObject *self, PyObject *args, void *wrapped)
2478{
2479 intargfunc func = (intargfunc)wrapped;
2480 int i;
2481
2482 if (!PyArg_ParseTuple(args, "i", &i))
2483 return NULL;
2484 return (*func)(self, i);
2485}
2486
Guido van Rossum5d815f32001-08-17 21:57:47 +00002487static int
2488getindex(PyObject *self, PyObject *arg)
2489{
2490 int i;
2491
2492 i = PyInt_AsLong(arg);
2493 if (i == -1 && PyErr_Occurred())
2494 return -1;
2495 if (i < 0) {
2496 PySequenceMethods *sq = self->ob_type->tp_as_sequence;
2497 if (sq && sq->sq_length) {
2498 int n = (*sq->sq_length)(self);
2499 if (n < 0)
2500 return -1;
2501 i += n;
2502 }
2503 }
2504 return i;
2505}
2506
2507static PyObject *
2508wrap_sq_item(PyObject *self, PyObject *args, void *wrapped)
2509{
2510 intargfunc func = (intargfunc)wrapped;
2511 PyObject *arg;
2512 int i;
2513
Guido van Rossumf4593e02001-10-03 12:09:30 +00002514 if (PyTuple_GET_SIZE(args) == 1) {
2515 arg = PyTuple_GET_ITEM(args, 0);
2516 i = getindex(self, arg);
2517 if (i == -1 && PyErr_Occurred())
2518 return NULL;
2519 return (*func)(self, i);
2520 }
2521 PyArg_ParseTuple(args, "O", &arg);
2522 assert(PyErr_Occurred());
2523 return NULL;
Guido van Rossum5d815f32001-08-17 21:57:47 +00002524}
2525
Tim Peters6d6c1a32001-08-02 04:15:00 +00002526static PyObject *
2527wrap_intintargfunc(PyObject *self, PyObject *args, void *wrapped)
2528{
2529 intintargfunc func = (intintargfunc)wrapped;
2530 int i, j;
2531
2532 if (!PyArg_ParseTuple(args, "ii", &i, &j))
2533 return NULL;
2534 return (*func)(self, i, j);
2535}
2536
Tim Peters6d6c1a32001-08-02 04:15:00 +00002537static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00002538wrap_sq_setitem(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002539{
2540 intobjargproc func = (intobjargproc)wrapped;
2541 int i, res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00002542 PyObject *arg, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002543
Guido van Rossum5d815f32001-08-17 21:57:47 +00002544 if (!PyArg_ParseTuple(args, "OO", &arg, &value))
2545 return NULL;
2546 i = getindex(self, arg);
2547 if (i == -1 && PyErr_Occurred())
Tim Peters6d6c1a32001-08-02 04:15:00 +00002548 return NULL;
2549 res = (*func)(self, i, value);
2550 if (res == -1 && PyErr_Occurred())
2551 return NULL;
2552 Py_INCREF(Py_None);
2553 return Py_None;
2554}
2555
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002556static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00002557wrap_sq_delitem(PyObject *self, PyObject *args, void *wrapped)
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002558{
2559 intobjargproc func = (intobjargproc)wrapped;
2560 int i, res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00002561 PyObject *arg;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002562
Guido van Rossum5d815f32001-08-17 21:57:47 +00002563 if (!PyArg_ParseTuple(args, "O", &arg))
2564 return NULL;
2565 i = getindex(self, arg);
2566 if (i == -1 && PyErr_Occurred())
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002567 return NULL;
2568 res = (*func)(self, i, NULL);
2569 if (res == -1 && PyErr_Occurred())
2570 return NULL;
2571 Py_INCREF(Py_None);
2572 return Py_None;
2573}
2574
Tim Peters6d6c1a32001-08-02 04:15:00 +00002575static PyObject *
2576wrap_intintobjargproc(PyObject *self, PyObject *args, void *wrapped)
2577{
2578 intintobjargproc func = (intintobjargproc)wrapped;
2579 int i, j, res;
2580 PyObject *value;
2581
2582 if (!PyArg_ParseTuple(args, "iiO", &i, &j, &value))
2583 return NULL;
2584 res = (*func)(self, i, j, value);
2585 if (res == -1 && PyErr_Occurred())
2586 return NULL;
2587 Py_INCREF(Py_None);
2588 return Py_None;
2589}
2590
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002591static PyObject *
2592wrap_delslice(PyObject *self, PyObject *args, void *wrapped)
2593{
2594 intintobjargproc func = (intintobjargproc)wrapped;
2595 int i, j, res;
2596
2597 if (!PyArg_ParseTuple(args, "ii", &i, &j))
2598 return NULL;
2599 res = (*func)(self, i, j, NULL);
2600 if (res == -1 && PyErr_Occurred())
2601 return NULL;
2602 Py_INCREF(Py_None);
2603 return Py_None;
2604}
2605
Tim Peters6d6c1a32001-08-02 04:15:00 +00002606/* XXX objobjproc is a misnomer; should be objargpred */
2607static PyObject *
2608wrap_objobjproc(PyObject *self, PyObject *args, void *wrapped)
2609{
2610 objobjproc func = (objobjproc)wrapped;
2611 int res;
2612 PyObject *value;
2613
2614 if (!PyArg_ParseTuple(args, "O", &value))
2615 return NULL;
2616 res = (*func)(self, value);
2617 if (res == -1 && PyErr_Occurred())
2618 return NULL;
2619 return PyInt_FromLong((long)res);
2620}
2621
Tim Peters6d6c1a32001-08-02 04:15:00 +00002622static PyObject *
2623wrap_objobjargproc(PyObject *self, PyObject *args, void *wrapped)
2624{
2625 objobjargproc func = (objobjargproc)wrapped;
2626 int res;
2627 PyObject *key, *value;
2628
2629 if (!PyArg_ParseTuple(args, "OO", &key, &value))
2630 return NULL;
2631 res = (*func)(self, key, value);
2632 if (res == -1 && PyErr_Occurred())
2633 return NULL;
2634 Py_INCREF(Py_None);
2635 return Py_None;
2636}
2637
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002638static PyObject *
2639wrap_delitem(PyObject *self, PyObject *args, void *wrapped)
2640{
2641 objobjargproc func = (objobjargproc)wrapped;
2642 int res;
2643 PyObject *key;
2644
2645 if (!PyArg_ParseTuple(args, "O", &key))
2646 return NULL;
2647 res = (*func)(self, key, NULL);
2648 if (res == -1 && PyErr_Occurred())
2649 return NULL;
2650 Py_INCREF(Py_None);
2651 return Py_None;
2652}
2653
Tim Peters6d6c1a32001-08-02 04:15:00 +00002654static PyObject *
2655wrap_cmpfunc(PyObject *self, PyObject *args, void *wrapped)
2656{
2657 cmpfunc func = (cmpfunc)wrapped;
2658 int res;
2659 PyObject *other;
2660
2661 if (!PyArg_ParseTuple(args, "O", &other))
2662 return NULL;
Guido van Rossum3d45d8f2001-09-24 18:47:40 +00002663 if (other->ob_type->tp_compare != func &&
2664 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossumceccae52001-09-18 20:03:57 +00002665 PyErr_Format(
2666 PyExc_TypeError,
2667 "%s.__cmp__(x,y) requires y to be a '%s', not a '%s'",
2668 self->ob_type->tp_name,
2669 self->ob_type->tp_name,
2670 other->ob_type->tp_name);
2671 return NULL;
2672 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002673 res = (*func)(self, other);
2674 if (PyErr_Occurred())
2675 return NULL;
2676 return PyInt_FromLong((long)res);
2677}
2678
Tim Peters6d6c1a32001-08-02 04:15:00 +00002679static PyObject *
2680wrap_setattr(PyObject *self, PyObject *args, void *wrapped)
2681{
2682 setattrofunc func = (setattrofunc)wrapped;
2683 int res;
2684 PyObject *name, *value;
2685
2686 if (!PyArg_ParseTuple(args, "OO", &name, &value))
2687 return NULL;
2688 res = (*func)(self, name, value);
2689 if (res < 0)
2690 return NULL;
2691 Py_INCREF(Py_None);
2692 return Py_None;
2693}
2694
2695static PyObject *
2696wrap_delattr(PyObject *self, PyObject *args, void *wrapped)
2697{
2698 setattrofunc func = (setattrofunc)wrapped;
2699 int res;
2700 PyObject *name;
2701
2702 if (!PyArg_ParseTuple(args, "O", &name))
2703 return NULL;
2704 res = (*func)(self, name, NULL);
2705 if (res < 0)
2706 return NULL;
2707 Py_INCREF(Py_None);
2708 return Py_None;
2709}
2710
Tim Peters6d6c1a32001-08-02 04:15:00 +00002711static PyObject *
2712wrap_hashfunc(PyObject *self, PyObject *args, void *wrapped)
2713{
2714 hashfunc func = (hashfunc)wrapped;
2715 long res;
2716
2717 if (!PyArg_ParseTuple(args, ""))
2718 return NULL;
2719 res = (*func)(self);
2720 if (res == -1 && PyErr_Occurred())
2721 return NULL;
2722 return PyInt_FromLong(res);
2723}
2724
Tim Peters6d6c1a32001-08-02 04:15:00 +00002725static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00002726wrap_call(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002727{
2728 ternaryfunc func = (ternaryfunc)wrapped;
2729
Guido van Rossumc8e56452001-10-22 00:43:43 +00002730 return (*func)(self, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002731}
2732
Tim Peters6d6c1a32001-08-02 04:15:00 +00002733static PyObject *
2734wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op)
2735{
2736 richcmpfunc func = (richcmpfunc)wrapped;
2737 PyObject *other;
2738
2739 if (!PyArg_ParseTuple(args, "O", &other))
2740 return NULL;
2741 return (*func)(self, other, op);
2742}
2743
2744#undef RICHCMP_WRAPPER
2745#define RICHCMP_WRAPPER(NAME, OP) \
2746static PyObject * \
2747richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \
2748{ \
2749 return wrap_richcmpfunc(self, args, wrapped, OP); \
2750}
2751
Jack Jansen8e938b42001-08-08 15:29:49 +00002752RICHCMP_WRAPPER(lt, Py_LT)
2753RICHCMP_WRAPPER(le, Py_LE)
2754RICHCMP_WRAPPER(eq, Py_EQ)
2755RICHCMP_WRAPPER(ne, Py_NE)
2756RICHCMP_WRAPPER(gt, Py_GT)
2757RICHCMP_WRAPPER(ge, Py_GE)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002758
Tim Peters6d6c1a32001-08-02 04:15:00 +00002759static PyObject *
2760wrap_next(PyObject *self, PyObject *args, void *wrapped)
2761{
2762 unaryfunc func = (unaryfunc)wrapped;
2763 PyObject *res;
2764
2765 if (!PyArg_ParseTuple(args, ""))
2766 return NULL;
2767 res = (*func)(self);
2768 if (res == NULL && !PyErr_Occurred())
2769 PyErr_SetNone(PyExc_StopIteration);
2770 return res;
2771}
2772
Tim Peters6d6c1a32001-08-02 04:15:00 +00002773static PyObject *
2774wrap_descr_get(PyObject *self, PyObject *args, void *wrapped)
2775{
2776 descrgetfunc func = (descrgetfunc)wrapped;
2777 PyObject *obj;
2778 PyObject *type = NULL;
2779
2780 if (!PyArg_ParseTuple(args, "O|O", &obj, &type))
2781 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002782 return (*func)(self, obj, type);
2783}
2784
Tim Peters6d6c1a32001-08-02 04:15:00 +00002785static PyObject *
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002786wrap_descr_set(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002787{
2788 descrsetfunc func = (descrsetfunc)wrapped;
2789 PyObject *obj, *value;
2790 int ret;
2791
2792 if (!PyArg_ParseTuple(args, "OO", &obj, &value))
2793 return NULL;
2794 ret = (*func)(self, obj, value);
2795 if (ret < 0)
2796 return NULL;
2797 Py_INCREF(Py_None);
2798 return Py_None;
2799}
Guido van Rossum22b13872002-08-06 21:41:44 +00002800
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00002801static PyObject *
2802wrap_descr_delete(PyObject *self, PyObject *args, void *wrapped)
2803{
2804 descrsetfunc func = (descrsetfunc)wrapped;
2805 PyObject *obj;
2806 int ret;
2807
2808 if (!PyArg_ParseTuple(args, "O", &obj))
2809 return NULL;
2810 ret = (*func)(self, obj, NULL);
2811 if (ret < 0)
2812 return NULL;
2813 Py_INCREF(Py_None);
2814 return Py_None;
2815}
Tim Peters6d6c1a32001-08-02 04:15:00 +00002816
Tim Peters6d6c1a32001-08-02 04:15:00 +00002817static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00002818wrap_init(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002819{
2820 initproc func = (initproc)wrapped;
2821
Guido van Rossumc8e56452001-10-22 00:43:43 +00002822 if (func(self, args, kwds) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002823 return NULL;
2824 Py_INCREF(Py_None);
2825 return Py_None;
2826}
2827
Tim Peters6d6c1a32001-08-02 04:15:00 +00002828static PyObject *
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002829tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002830{
Barry Warsaw60f01882001-08-22 19:24:42 +00002831 PyTypeObject *type, *subtype, *staticbase;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002832 PyObject *arg0, *res;
2833
2834 if (self == NULL || !PyType_Check(self))
2835 Py_FatalError("__new__() called with non-type 'self'");
2836 type = (PyTypeObject *)self;
2837 if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002838 PyErr_Format(PyExc_TypeError,
2839 "%s.__new__(): not enough arguments",
2840 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002841 return NULL;
2842 }
2843 arg0 = PyTuple_GET_ITEM(args, 0);
2844 if (!PyType_Check(arg0)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002845 PyErr_Format(PyExc_TypeError,
2846 "%s.__new__(X): X is not a type object (%s)",
2847 type->tp_name,
2848 arg0->ob_type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002849 return NULL;
2850 }
2851 subtype = (PyTypeObject *)arg0;
2852 if (!PyType_IsSubtype(subtype, type)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002853 PyErr_Format(PyExc_TypeError,
2854 "%s.__new__(%s): %s is not a subtype of %s",
2855 type->tp_name,
2856 subtype->tp_name,
2857 subtype->tp_name,
2858 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002859 return NULL;
2860 }
Barry Warsaw60f01882001-08-22 19:24:42 +00002861
2862 /* Check that the use doesn't do something silly and unsafe like
Tim Petersa427a2b2001-10-29 22:25:45 +00002863 object.__new__(dict). To do this, we check that the
Barry Warsaw60f01882001-08-22 19:24:42 +00002864 most derived base that's not a heap type is this type. */
2865 staticbase = subtype;
2866 while (staticbase && (staticbase->tp_flags & Py_TPFLAGS_HEAPTYPE))
2867 staticbase = staticbase->tp_base;
Guido van Rossuma8c60f42001-09-14 19:43:36 +00002868 if (staticbase->tp_new != type->tp_new) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002869 PyErr_Format(PyExc_TypeError,
2870 "%s.__new__(%s) is not safe, use %s.__new__()",
2871 type->tp_name,
2872 subtype->tp_name,
2873 staticbase == NULL ? "?" : staticbase->tp_name);
2874 return NULL;
2875 }
2876
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002877 args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
2878 if (args == NULL)
2879 return NULL;
2880 res = type->tp_new(subtype, args, kwds);
2881 Py_DECREF(args);
2882 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002883}
2884
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002885static struct PyMethodDef tp_new_methoddef[] = {
2886 {"__new__", (PyCFunction)tp_new_wrapper, METH_KEYWORDS,
2887 "T.__new__(S, ...) -> a new object with type S, a subtype of T"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002888 {0}
2889};
2890
2891static int
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002892add_tp_new_wrapper(PyTypeObject *type)
2893{
Guido van Rossumf040ede2001-08-07 16:40:56 +00002894 PyObject *func;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002895
Guido van Rossum687ae002001-10-15 22:03:32 +00002896 if (PyDict_GetItemString(type->tp_dict, "__new__") != NULL)
Guido van Rossumf040ede2001-08-07 16:40:56 +00002897 return 0;
2898 func = PyCFunction_New(tp_new_methoddef, (PyObject *)type);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002899 if (func == NULL)
2900 return -1;
Guido van Rossum687ae002001-10-15 22:03:32 +00002901 return PyDict_SetItemString(type->tp_dict, "__new__", func);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002902}
2903
Guido van Rossumf040ede2001-08-07 16:40:56 +00002904/* Slot wrappers that call the corresponding __foo__ slot. See comments
2905 below at override_slots() for more explanation. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002906
Guido van Rossumdc91b992001-08-08 22:26:22 +00002907#define SLOT0(FUNCNAME, OPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002908static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002909FUNCNAME(PyObject *self) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002910{ \
Guido van Rossum5592e4d2001-08-28 18:28:21 +00002911 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00002912 return call_method(self, OPSTR, &cache_str, "()"); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002913}
2914
Guido van Rossumdc91b992001-08-08 22:26:22 +00002915#define SLOT1(FUNCNAME, OPSTR, ARG1TYPE, ARGCODES) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002916static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002917FUNCNAME(PyObject *self, ARG1TYPE arg1) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002918{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00002919 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00002920 return call_method(self, OPSTR, &cache_str, "(" ARGCODES ")", arg1); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002921}
2922
Guido van Rossumdc91b992001-08-08 22:26:22 +00002923
2924#define SLOT1BINFULL(FUNCNAME, TESTFUNC, SLOTNAME, OPSTR, ROPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002925static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002926FUNCNAME(PyObject *self, PyObject *other) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002927{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00002928 static PyObject *cache_str, *rcache_str; \
Guido van Rossum55f20992001-10-01 17:18:22 +00002929 int do_other = self->ob_type != other->ob_type && \
2930 other->ob_type->tp_as_number != NULL && \
2931 other->ob_type->tp_as_number->SLOTNAME == TESTFUNC; \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002932 if (self->ob_type->tp_as_number != NULL && \
2933 self->ob_type->tp_as_number->SLOTNAME == TESTFUNC) { \
2934 PyObject *r; \
Guido van Rossum55f20992001-10-01 17:18:22 +00002935 if (do_other && \
2936 PyType_IsSubtype(other->ob_type, self->ob_type)) { \
2937 r = call_maybe( \
2938 other, ROPSTR, &rcache_str, "(O)", self); \
2939 if (r != Py_NotImplemented) \
2940 return r; \
2941 Py_DECREF(r); \
2942 do_other = 0; \
2943 } \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00002944 r = call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00002945 self, OPSTR, &cache_str, "(O)", other); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002946 if (r != Py_NotImplemented || \
2947 other->ob_type == self->ob_type) \
2948 return r; \
2949 Py_DECREF(r); \
2950 } \
Guido van Rossum55f20992001-10-01 17:18:22 +00002951 if (do_other) { \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00002952 return call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00002953 other, ROPSTR, &rcache_str, "(O)", self); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002954 } \
2955 Py_INCREF(Py_NotImplemented); \
2956 return Py_NotImplemented; \
2957}
2958
2959#define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) \
2960 SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR)
2961
2962#define SLOT2(FUNCNAME, OPSTR, ARG1TYPE, ARG2TYPE, ARGCODES) \
2963static PyObject * \
2964FUNCNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \
2965{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00002966 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00002967 return call_method(self, OPSTR, &cache_str, \
2968 "(" ARGCODES ")", arg1, arg2); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002969}
2970
2971static int
2972slot_sq_length(PyObject *self)
2973{
Guido van Rossum2730b132001-08-28 18:22:14 +00002974 static PyObject *len_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00002975 PyObject *res = call_method(self, "__len__", &len_str, "()");
Guido van Rossum26111622001-10-01 16:42:49 +00002976 int len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002977
2978 if (res == NULL)
2979 return -1;
Guido van Rossum26111622001-10-01 16:42:49 +00002980 len = (int)PyInt_AsLong(res);
2981 Py_DECREF(res);
Jeremy Hylton73a088e2002-07-25 16:43:29 +00002982 if (len == -1 && PyErr_Occurred())
2983 return -1;
Jeremy Hyltonf20fcf92002-07-25 16:06:15 +00002984 if (len < 0) {
Guido van Rossum22b13872002-08-06 21:41:44 +00002985 PyErr_SetString(PyExc_ValueError,
Jeremy Hyltonf20fcf92002-07-25 16:06:15 +00002986 "__len__() should return >= 0");
2987 return -1;
2988 }
Guido van Rossum26111622001-10-01 16:42:49 +00002989 return len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002990}
2991
Guido van Rossumdc91b992001-08-08 22:26:22 +00002992SLOT1(slot_sq_concat, "__add__", PyObject *, "O")
2993SLOT1(slot_sq_repeat, "__mul__", int, "i")
Guido van Rossumf4593e02001-10-03 12:09:30 +00002994
2995/* Super-optimized version of slot_sq_item.
2996 Other slots could do the same... */
2997static PyObject *
2998slot_sq_item(PyObject *self, int i)
2999{
3000 static PyObject *getitem_str;
3001 PyObject *func, *args = NULL, *ival = NULL, *retval = NULL;
3002 descrgetfunc f;
3003
3004 if (getitem_str == NULL) {
3005 getitem_str = PyString_InternFromString("__getitem__");
3006 if (getitem_str == NULL)
3007 return NULL;
3008 }
3009 func = _PyType_Lookup(self->ob_type, getitem_str);
3010 if (func != NULL) {
Guido van Rossumf4593e02001-10-03 12:09:30 +00003011 if ((f = func->ob_type->tp_descr_get) == NULL)
3012 Py_INCREF(func);
3013 else
3014 func = f(func, self, (PyObject *)(self->ob_type));
3015 ival = PyInt_FromLong(i);
3016 if (ival != NULL) {
3017 args = PyTuple_New(1);
3018 if (args != NULL) {
3019 PyTuple_SET_ITEM(args, 0, ival);
3020 retval = PyObject_Call(func, args, NULL);
3021 Py_XDECREF(args);
3022 Py_XDECREF(func);
3023 return retval;
3024 }
3025 }
3026 }
3027 else {
3028 PyErr_SetObject(PyExc_AttributeError, getitem_str);
3029 }
3030 Py_XDECREF(args);
3031 Py_XDECREF(ival);
3032 Py_XDECREF(func);
3033 return NULL;
3034}
3035
Guido van Rossumdc91b992001-08-08 22:26:22 +00003036SLOT2(slot_sq_slice, "__getslice__", int, int, "ii")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003037
3038static int
3039slot_sq_ass_item(PyObject *self, int index, PyObject *value)
3040{
3041 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003042 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003043
3044 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003045 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003046 "(i)", index);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003047 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003048 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003049 "(iO)", index, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003050 if (res == NULL)
3051 return -1;
3052 Py_DECREF(res);
3053 return 0;
3054}
3055
3056static int
3057slot_sq_ass_slice(PyObject *self, int i, int j, PyObject *value)
3058{
3059 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003060 static PyObject *delslice_str, *setslice_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003061
3062 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003063 res = call_method(self, "__delslice__", &delslice_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003064 "(ii)", i, j);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003065 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003066 res = call_method(self, "__setslice__", &setslice_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003067 "(iiO)", i, j, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003068 if (res == NULL)
3069 return -1;
3070 Py_DECREF(res);
3071 return 0;
3072}
3073
3074static int
3075slot_sq_contains(PyObject *self, PyObject *value)
3076{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003077 PyObject *func, *res, *args;
Guido van Rossum60718732001-08-28 17:47:51 +00003078 static PyObject *contains_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003079
Guido van Rossum55f20992001-10-01 17:18:22 +00003080 func = lookup_maybe(self, "__contains__", &contains_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003081
3082 if (func != NULL) {
3083 args = Py_BuildValue("(O)", value);
3084 if (args == NULL)
3085 res = NULL;
3086 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00003087 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003088 Py_DECREF(args);
3089 }
3090 Py_DECREF(func);
3091 if (res == NULL)
3092 return -1;
3093 return PyObject_IsTrue(res);
3094 }
Guido van Rossum55f20992001-10-01 17:18:22 +00003095 else if (PyErr_Occurred())
3096 return -1;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003097 else {
Tim Peters16a77ad2001-09-08 04:00:12 +00003098 return _PySequence_IterSearch(self, value,
3099 PY_ITERSEARCH_CONTAINS);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003100 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003101}
3102
Guido van Rossumdc91b992001-08-08 22:26:22 +00003103SLOT1(slot_sq_inplace_concat, "__iadd__", PyObject *, "O")
3104SLOT1(slot_sq_inplace_repeat, "__imul__", int, "i")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003105
3106#define slot_mp_length slot_sq_length
3107
Guido van Rossumdc91b992001-08-08 22:26:22 +00003108SLOT1(slot_mp_subscript, "__getitem__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003109
3110static int
3111slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value)
3112{
3113 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003114 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003115
3116 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003117 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003118 "(O)", key);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003119 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003120 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003121 "(OO)", key, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003122 if (res == NULL)
3123 return -1;
3124 Py_DECREF(res);
3125 return 0;
3126}
3127
Guido van Rossumdc91b992001-08-08 22:26:22 +00003128SLOT1BIN(slot_nb_add, nb_add, "__add__", "__radd__")
3129SLOT1BIN(slot_nb_subtract, nb_subtract, "__sub__", "__rsub__")
3130SLOT1BIN(slot_nb_multiply, nb_multiply, "__mul__", "__rmul__")
3131SLOT1BIN(slot_nb_divide, nb_divide, "__div__", "__rdiv__")
3132SLOT1BIN(slot_nb_remainder, nb_remainder, "__mod__", "__rmod__")
3133SLOT1BIN(slot_nb_divmod, nb_divmod, "__divmod__", "__rdivmod__")
3134
Jeremy Hylton938ace62002-07-17 16:30:39 +00003135static PyObject *slot_nb_power(PyObject *, PyObject *, PyObject *);
Guido van Rossumdc91b992001-08-08 22:26:22 +00003136
3137SLOT1BINFULL(slot_nb_power_binary, slot_nb_power,
3138 nb_power, "__pow__", "__rpow__")
3139
3140static PyObject *
3141slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus)
3142{
Guido van Rossum2730b132001-08-28 18:22:14 +00003143 static PyObject *pow_str;
3144
Guido van Rossumdc91b992001-08-08 22:26:22 +00003145 if (modulus == Py_None)
3146 return slot_nb_power_binary(self, other);
Guido van Rossum23094982002-06-10 14:30:43 +00003147 /* Three-arg power doesn't use __rpow__. But ternary_op
3148 can call this when the second argument's type uses
3149 slot_nb_power, so check before calling self.__pow__. */
3150 if (self->ob_type->tp_as_number != NULL &&
3151 self->ob_type->tp_as_number->nb_power == slot_nb_power) {
3152 return call_method(self, "__pow__", &pow_str,
3153 "(OO)", other, modulus);
3154 }
3155 Py_INCREF(Py_NotImplemented);
3156 return Py_NotImplemented;
Guido van Rossumdc91b992001-08-08 22:26:22 +00003157}
3158
3159SLOT0(slot_nb_negative, "__neg__")
3160SLOT0(slot_nb_positive, "__pos__")
3161SLOT0(slot_nb_absolute, "__abs__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003162
3163static int
3164slot_nb_nonzero(PyObject *self)
3165{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003166 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003167 static PyObject *nonzero_str, *len_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003168
Guido van Rossum55f20992001-10-01 17:18:22 +00003169 func = lookup_maybe(self, "__nonzero__", &nonzero_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003170 if (func == NULL) {
Guido van Rossum55f20992001-10-01 17:18:22 +00003171 if (PyErr_Occurred())
Guido van Rossumb8f63662001-08-15 23:57:02 +00003172 return -1;
Guido van Rossum55f20992001-10-01 17:18:22 +00003173 func = lookup_maybe(self, "__len__", &len_str);
3174 if (func == NULL) {
3175 if (PyErr_Occurred())
3176 return -1;
3177 else
3178 return 1;
3179 }
Guido van Rossumb8f63662001-08-15 23:57:02 +00003180 }
Guido van Rossum55f20992001-10-01 17:18:22 +00003181 res = PyObject_CallObject(func, NULL);
3182 Py_DECREF(func);
3183 if (res == NULL)
3184 return -1;
3185 return PyObject_IsTrue(res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003186}
3187
Guido van Rossumdc91b992001-08-08 22:26:22 +00003188SLOT0(slot_nb_invert, "__invert__")
3189SLOT1BIN(slot_nb_lshift, nb_lshift, "__lshift__", "__rlshift__")
3190SLOT1BIN(slot_nb_rshift, nb_rshift, "__rshift__", "__rrshift__")
3191SLOT1BIN(slot_nb_and, nb_and, "__and__", "__rand__")
3192SLOT1BIN(slot_nb_xor, nb_xor, "__xor__", "__rxor__")
3193SLOT1BIN(slot_nb_or, nb_or, "__or__", "__ror__")
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003194
3195static int
3196slot_nb_coerce(PyObject **a, PyObject **b)
3197{
3198 static PyObject *coerce_str;
3199 PyObject *self = *a, *other = *b;
3200
3201 if (self->ob_type->tp_as_number != NULL &&
3202 self->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
3203 PyObject *r;
3204 r = call_maybe(
3205 self, "__coerce__", &coerce_str, "(O)", other);
3206 if (r == NULL)
3207 return -1;
3208 if (r == Py_NotImplemented) {
3209 Py_DECREF(r);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003210 }
Guido van Rossum55f20992001-10-01 17:18:22 +00003211 else {
3212 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
3213 PyErr_SetString(PyExc_TypeError,
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003214 "__coerce__ didn't return a 2-tuple");
Guido van Rossum55f20992001-10-01 17:18:22 +00003215 Py_DECREF(r);
3216 return -1;
3217 }
3218 *a = PyTuple_GET_ITEM(r, 0);
3219 Py_INCREF(*a);
3220 *b = PyTuple_GET_ITEM(r, 1);
3221 Py_INCREF(*b);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003222 Py_DECREF(r);
Guido van Rossum55f20992001-10-01 17:18:22 +00003223 return 0;
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003224 }
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003225 }
3226 if (other->ob_type->tp_as_number != NULL &&
3227 other->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
3228 PyObject *r;
3229 r = call_maybe(
3230 other, "__coerce__", &coerce_str, "(O)", self);
3231 if (r == NULL)
3232 return -1;
3233 if (r == Py_NotImplemented) {
3234 Py_DECREF(r);
3235 return 1;
3236 }
3237 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
3238 PyErr_SetString(PyExc_TypeError,
3239 "__coerce__ didn't return a 2-tuple");
3240 Py_DECREF(r);
3241 return -1;
3242 }
3243 *a = PyTuple_GET_ITEM(r, 1);
3244 Py_INCREF(*a);
3245 *b = PyTuple_GET_ITEM(r, 0);
3246 Py_INCREF(*b);
3247 Py_DECREF(r);
3248 return 0;
3249 }
3250 return 1;
3251}
3252
Guido van Rossumdc91b992001-08-08 22:26:22 +00003253SLOT0(slot_nb_int, "__int__")
3254SLOT0(slot_nb_long, "__long__")
3255SLOT0(slot_nb_float, "__float__")
3256SLOT0(slot_nb_oct, "__oct__")
3257SLOT0(slot_nb_hex, "__hex__")
3258SLOT1(slot_nb_inplace_add, "__iadd__", PyObject *, "O")
3259SLOT1(slot_nb_inplace_subtract, "__isub__", PyObject *, "O")
3260SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *, "O")
3261SLOT1(slot_nb_inplace_divide, "__idiv__", PyObject *, "O")
3262SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *, "O")
3263SLOT2(slot_nb_inplace_power, "__ipow__", PyObject *, PyObject *, "OO")
3264SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *, "O")
3265SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *, "O")
3266SLOT1(slot_nb_inplace_and, "__iand__", PyObject *, "O")
3267SLOT1(slot_nb_inplace_xor, "__ixor__", PyObject *, "O")
3268SLOT1(slot_nb_inplace_or, "__ior__", PyObject *, "O")
3269SLOT1BIN(slot_nb_floor_divide, nb_floor_divide,
3270 "__floordiv__", "__rfloordiv__")
3271SLOT1BIN(slot_nb_true_divide, nb_true_divide, "__truediv__", "__rtruediv__")
3272SLOT1(slot_nb_inplace_floor_divide, "__ifloordiv__", PyObject *, "O")
3273SLOT1(slot_nb_inplace_true_divide, "__itruediv__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003274
3275static int
Guido van Rossumb8f63662001-08-15 23:57:02 +00003276half_compare(PyObject *self, PyObject *other)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003277{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003278 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003279 static PyObject *cmp_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003280 int c;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003281
Guido van Rossum60718732001-08-28 17:47:51 +00003282 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003283 if (func == NULL) {
3284 PyErr_Clear();
3285 }
3286 else {
3287 args = Py_BuildValue("(O)", other);
3288 if (args == NULL)
3289 res = NULL;
3290 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00003291 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003292 Py_DECREF(args);
3293 }
Raymond Hettingerab5dae32002-06-24 13:08:16 +00003294 Py_DECREF(func);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003295 if (res != Py_NotImplemented) {
3296 if (res == NULL)
3297 return -2;
3298 c = PyInt_AsLong(res);
3299 Py_DECREF(res);
3300 if (c == -1 && PyErr_Occurred())
3301 return -2;
3302 return (c < 0) ? -1 : (c > 0) ? 1 : 0;
3303 }
3304 Py_DECREF(res);
3305 }
3306 return 2;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003307}
3308
Guido van Rossumab3b0342001-09-18 20:38:53 +00003309/* This slot is published for the benefit of try_3way_compare in object.c */
3310int
3311_PyObject_SlotCompare(PyObject *self, PyObject *other)
Guido van Rossumb8f63662001-08-15 23:57:02 +00003312{
3313 int c;
3314
Guido van Rossumab3b0342001-09-18 20:38:53 +00003315 if (self->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00003316 c = half_compare(self, other);
3317 if (c <= 1)
3318 return c;
3319 }
Guido van Rossumab3b0342001-09-18 20:38:53 +00003320 if (other->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00003321 c = half_compare(other, self);
3322 if (c < -1)
3323 return -2;
3324 if (c <= 1)
3325 return -c;
3326 }
3327 return (void *)self < (void *)other ? -1 :
3328 (void *)self > (void *)other ? 1 : 0;
3329}
3330
3331static PyObject *
3332slot_tp_repr(PyObject *self)
3333{
3334 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003335 static PyObject *repr_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003336
Guido van Rossum60718732001-08-28 17:47:51 +00003337 func = lookup_method(self, "__repr__", &repr_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003338 if (func != NULL) {
3339 res = PyEval_CallObject(func, NULL);
3340 Py_DECREF(func);
3341 return res;
3342 }
Barry Warsaw7ce36942001-08-24 18:34:26 +00003343 PyErr_Clear();
3344 return PyString_FromFormat("<%s object at %p>",
3345 self->ob_type->tp_name, self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003346}
3347
3348static PyObject *
3349slot_tp_str(PyObject *self)
3350{
3351 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003352 static PyObject *str_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003353
Guido van Rossum60718732001-08-28 17:47:51 +00003354 func = lookup_method(self, "__str__", &str_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003355 if (func != NULL) {
3356 res = PyEval_CallObject(func, NULL);
3357 Py_DECREF(func);
3358 return res;
3359 }
3360 else {
3361 PyErr_Clear();
3362 return slot_tp_repr(self);
3363 }
3364}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003365
3366static long
3367slot_tp_hash(PyObject *self)
3368{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003369 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003370 static PyObject *hash_str, *eq_str, *cmp_str;
3371
Tim Peters6d6c1a32001-08-02 04:15:00 +00003372 long h;
3373
Guido van Rossum60718732001-08-28 17:47:51 +00003374 func = lookup_method(self, "__hash__", &hash_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003375
3376 if (func != NULL) {
3377 res = PyEval_CallObject(func, NULL);
3378 Py_DECREF(func);
3379 if (res == NULL)
3380 return -1;
3381 h = PyInt_AsLong(res);
3382 }
3383 else {
3384 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00003385 func = lookup_method(self, "__eq__", &eq_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003386 if (func == NULL) {
3387 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00003388 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003389 }
3390 if (func != NULL) {
3391 Py_DECREF(func);
3392 PyErr_SetString(PyExc_TypeError, "unhashable type");
3393 return -1;
3394 }
3395 PyErr_Clear();
3396 h = _Py_HashPointer((void *)self);
3397 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003398 if (h == -1 && !PyErr_Occurred())
3399 h = -2;
3400 return h;
3401}
3402
3403static PyObject *
3404slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds)
3405{
Guido van Rossum60718732001-08-28 17:47:51 +00003406 static PyObject *call_str;
3407 PyObject *meth = lookup_method(self, "__call__", &call_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003408 PyObject *res;
3409
3410 if (meth == NULL)
3411 return NULL;
3412 res = PyObject_Call(meth, args, kwds);
3413 Py_DECREF(meth);
3414 return res;
3415}
3416
Guido van Rossum14a6f832001-10-17 13:59:09 +00003417/* There are two slot dispatch functions for tp_getattro.
3418
3419 - slot_tp_getattro() is used when __getattribute__ is overridden
3420 but no __getattr__ hook is present;
3421
3422 - slot_tp_getattr_hook() is used when a __getattr__ hook is present.
3423
Guido van Rossumc334df52002-04-04 23:44:47 +00003424 The code in update_one_slot() always installs slot_tp_getattr_hook(); this
3425 detects the absence of __getattr__ and then installs the simpler slot if
3426 necessary. */
Guido van Rossum14a6f832001-10-17 13:59:09 +00003427
Tim Peters6d6c1a32001-08-02 04:15:00 +00003428static PyObject *
3429slot_tp_getattro(PyObject *self, PyObject *name)
3430{
Guido van Rossum14a6f832001-10-17 13:59:09 +00003431 static PyObject *getattribute_str = NULL;
3432 return call_method(self, "__getattribute__", &getattribute_str,
3433 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003434}
3435
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003436static PyObject *
3437slot_tp_getattr_hook(PyObject *self, PyObject *name)
3438{
3439 PyTypeObject *tp = self->ob_type;
3440 PyObject *getattr, *getattribute, *res;
3441 static PyObject *getattribute_str = NULL;
3442 static PyObject *getattr_str = NULL;
3443
3444 if (getattr_str == NULL) {
3445 getattr_str = PyString_InternFromString("__getattr__");
3446 if (getattr_str == NULL)
3447 return NULL;
3448 }
3449 if (getattribute_str == NULL) {
3450 getattribute_str =
3451 PyString_InternFromString("__getattribute__");
3452 if (getattribute_str == NULL)
3453 return NULL;
3454 }
3455 getattr = _PyType_Lookup(tp, getattr_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00003456 if (getattr == NULL) {
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003457 /* No __getattr__ hook: use a simpler dispatcher */
3458 tp->tp_getattro = slot_tp_getattro;
3459 return slot_tp_getattro(self, name);
3460 }
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003461 getattribute = _PyType_Lookup(tp, getattribute_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00003462 if (getattribute == NULL ||
3463 (getattribute->ob_type == &PyWrapperDescr_Type &&
3464 ((PyWrapperDescrObject *)getattribute)->d_wrapped ==
3465 (void *)PyObject_GenericGetAttr))
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003466 res = PyObject_GenericGetAttr(self, name);
3467 else
3468 res = PyObject_CallFunction(getattribute, "OO", self, name);
Guido van Rossum14a6f832001-10-17 13:59:09 +00003469 if (res == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) {
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003470 PyErr_Clear();
3471 res = PyObject_CallFunction(getattr, "OO", self, name);
3472 }
3473 return res;
3474}
3475
Tim Peters6d6c1a32001-08-02 04:15:00 +00003476static int
3477slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value)
3478{
3479 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003480 static PyObject *delattr_str, *setattr_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003481
3482 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003483 res = call_method(self, "__delattr__", &delattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003484 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003485 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003486 res = call_method(self, "__setattr__", &setattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003487 "(OO)", name, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003488 if (res == NULL)
3489 return -1;
3490 Py_DECREF(res);
3491 return 0;
3492}
3493
3494/* Map rich comparison operators to their __xx__ namesakes */
3495static char *name_op[] = {
3496 "__lt__",
3497 "__le__",
3498 "__eq__",
3499 "__ne__",
3500 "__gt__",
3501 "__ge__",
3502};
3503
3504static PyObject *
Guido van Rossumb8f63662001-08-15 23:57:02 +00003505half_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003506{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003507 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003508 static PyObject *op_str[6];
Tim Peters6d6c1a32001-08-02 04:15:00 +00003509
Guido van Rossum60718732001-08-28 17:47:51 +00003510 func = lookup_method(self, name_op[op], &op_str[op]);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003511 if (func == NULL) {
3512 PyErr_Clear();
3513 Py_INCREF(Py_NotImplemented);
3514 return Py_NotImplemented;
3515 }
3516 args = Py_BuildValue("(O)", other);
3517 if (args == NULL)
3518 res = NULL;
3519 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00003520 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003521 Py_DECREF(args);
3522 }
3523 Py_DECREF(func);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003524 return res;
3525}
3526
Guido van Rossumb8f63662001-08-15 23:57:02 +00003527/* Map rich comparison operators to their swapped version, e.g. LT --> GT */
3528static int swapped_op[] = {Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE};
3529
3530static PyObject *
3531slot_tp_richcompare(PyObject *self, PyObject *other, int op)
3532{
3533 PyObject *res;
3534
3535 if (self->ob_type->tp_richcompare == slot_tp_richcompare) {
3536 res = half_richcompare(self, other, op);
3537 if (res != Py_NotImplemented)
3538 return res;
3539 Py_DECREF(res);
3540 }
3541 if (other->ob_type->tp_richcompare == slot_tp_richcompare) {
3542 res = half_richcompare(other, self, swapped_op[op]);
3543 if (res != Py_NotImplemented) {
3544 return res;
3545 }
3546 Py_DECREF(res);
3547 }
3548 Py_INCREF(Py_NotImplemented);
3549 return Py_NotImplemented;
3550}
3551
3552static PyObject *
3553slot_tp_iter(PyObject *self)
3554{
3555 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003556 static PyObject *iter_str, *getitem_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003557
Guido van Rossum60718732001-08-28 17:47:51 +00003558 func = lookup_method(self, "__iter__", &iter_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003559 if (func != NULL) {
3560 res = PyObject_CallObject(func, NULL);
3561 Py_DECREF(func);
3562 return res;
3563 }
3564 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00003565 func = lookup_method(self, "__getitem__", &getitem_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003566 if (func == NULL) {
Guido van Rossumd4641072002-04-03 02:13:37 +00003567 PyErr_SetString(PyExc_TypeError,
3568 "iteration over non-sequence");
Guido van Rossumb8f63662001-08-15 23:57:02 +00003569 return NULL;
3570 }
3571 Py_DECREF(func);
3572 return PySeqIter_New(self);
3573}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003574
3575static PyObject *
3576slot_tp_iternext(PyObject *self)
3577{
Guido van Rossum2730b132001-08-28 18:22:14 +00003578 static PyObject *next_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00003579 return call_method(self, "next", &next_str, "()");
Tim Peters6d6c1a32001-08-02 04:15:00 +00003580}
3581
Guido van Rossum1a493502001-08-17 16:47:50 +00003582static PyObject *
3583slot_tp_descr_get(PyObject *self, PyObject *obj, PyObject *type)
3584{
3585 PyTypeObject *tp = self->ob_type;
3586 PyObject *get;
3587 static PyObject *get_str = NULL;
3588
3589 if (get_str == NULL) {
3590 get_str = PyString_InternFromString("__get__");
3591 if (get_str == NULL)
3592 return NULL;
3593 }
3594 get = _PyType_Lookup(tp, get_str);
3595 if (get == NULL) {
3596 /* Avoid further slowdowns */
3597 if (tp->tp_descr_get == slot_tp_descr_get)
3598 tp->tp_descr_get = NULL;
3599 Py_INCREF(self);
3600 return self;
3601 }
Guido van Rossum2c252392001-08-24 10:13:31 +00003602 if (obj == NULL)
3603 obj = Py_None;
3604 if (type == NULL)
3605 type = Py_None;
Guido van Rossum1a493502001-08-17 16:47:50 +00003606 return PyObject_CallFunction(get, "OOO", self, obj, type);
3607}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003608
3609static int
3610slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value)
3611{
Guido van Rossum2c252392001-08-24 10:13:31 +00003612 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003613 static PyObject *del_str, *set_str;
Guido van Rossum2c252392001-08-24 10:13:31 +00003614
3615 if (value == NULL)
Guido van Rossum1d5b3f22001-12-03 00:08:33 +00003616 res = call_method(self, "__delete__", &del_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003617 "(O)", target);
Guido van Rossum2c252392001-08-24 10:13:31 +00003618 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003619 res = call_method(self, "__set__", &set_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003620 "(OO)", target, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003621 if (res == NULL)
3622 return -1;
3623 Py_DECREF(res);
3624 return 0;
3625}
3626
3627static int
3628slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds)
3629{
Guido van Rossum60718732001-08-28 17:47:51 +00003630 static PyObject *init_str;
3631 PyObject *meth = lookup_method(self, "__init__", &init_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003632 PyObject *res;
3633
3634 if (meth == NULL)
3635 return -1;
3636 res = PyObject_Call(meth, args, kwds);
3637 Py_DECREF(meth);
3638 if (res == NULL)
3639 return -1;
3640 Py_DECREF(res);
3641 return 0;
3642}
3643
3644static PyObject *
3645slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3646{
Guido van Rossum7bed2132002-08-08 21:57:53 +00003647 static PyObject *new_str;
3648 PyObject *func;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003649 PyObject *newargs, *x;
3650 int i, n;
3651
Guido van Rossum7bed2132002-08-08 21:57:53 +00003652 if (new_str == NULL) {
3653 new_str = PyString_InternFromString("__new__");
3654 if (new_str == NULL)
3655 return NULL;
3656 }
3657 func = PyObject_GetAttr((PyObject *)type, new_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003658 if (func == NULL)
3659 return NULL;
3660 assert(PyTuple_Check(args));
3661 n = PyTuple_GET_SIZE(args);
3662 newargs = PyTuple_New(n+1);
3663 if (newargs == NULL)
3664 return NULL;
3665 Py_INCREF(type);
3666 PyTuple_SET_ITEM(newargs, 0, (PyObject *)type);
3667 for (i = 0; i < n; i++) {
3668 x = PyTuple_GET_ITEM(args, i);
3669 Py_INCREF(x);
3670 PyTuple_SET_ITEM(newargs, i+1, x);
3671 }
3672 x = PyObject_Call(func, newargs, kwds);
Guido van Rossum25d18072001-10-01 15:55:28 +00003673 Py_DECREF(newargs);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003674 Py_DECREF(func);
3675 return x;
3676}
3677
Guido van Rossumfebd61d2002-08-08 20:55:20 +00003678static void
3679slot_tp_del(PyObject *self)
3680{
3681 static PyObject *del_str = NULL;
3682 PyObject *del, *res;
3683 PyObject *error_type, *error_value, *error_traceback;
3684
3685 /* Temporarily resurrect the object. */
3686 assert(self->ob_refcnt == 0);
3687 self->ob_refcnt = 1;
3688
3689 /* Save the current exception, if any. */
3690 PyErr_Fetch(&error_type, &error_value, &error_traceback);
3691
3692 /* Execute __del__ method, if any. */
3693 del = lookup_maybe(self, "__del__", &del_str);
3694 if (del != NULL) {
3695 res = PyEval_CallObject(del, NULL);
3696 if (res == NULL)
3697 PyErr_WriteUnraisable(del);
3698 else
3699 Py_DECREF(res);
3700 Py_DECREF(del);
3701 }
3702
3703 /* Restore the saved exception. */
3704 PyErr_Restore(error_type, error_value, error_traceback);
3705
3706 /* Undo the temporary resurrection; can't use DECREF here, it would
3707 * cause a recursive call.
3708 */
3709 assert(self->ob_refcnt > 0);
3710 if (--self->ob_refcnt == 0)
3711 return; /* this is the normal path out */
3712
3713 /* __del__ resurrected it! Make it look like the original Py_DECREF
3714 * never happened.
3715 */
3716 {
3717 int refcnt = self->ob_refcnt;
3718 _Py_NewReference(self);
3719 self->ob_refcnt = refcnt;
3720 }
3721 assert(!PyType_IS_GC(self->ob_type) ||
3722 _Py_AS_GC(self)->gc.gc_refs != _PyGC_REFS_UNTRACKED);
3723 /* If Py_REF_DEBUG, the original decref dropped _Py_RefTotal, but
3724 * _Py_NewReference bumped it again, so that's a wash.
3725 * If Py_TRACE_REFS, _Py_NewReference re-added self to the object
3726 * chain, so no more to do there either.
3727 * If COUNT_ALLOCS, the original decref bumped tp_frees, and
3728 * _Py_NewReference bumped tp_allocs: both of those need to be
3729 * undone.
3730 */
3731#ifdef COUNT_ALLOCS
3732 --self->ob_type->tp_frees;
3733 --self->ob_type->tp_allocs;
3734#endif
3735}
3736
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003737
3738/* Table mapping __foo__ names to tp_foo offsets and slot_tp_foo wrapper
3739 functions. The offsets here are relative to the 'etype' structure, which
3740 incorporates the additional structures used for numbers, sequences and
3741 mappings. Note that multiple names may map to the same slot (e.g. __eq__,
3742 __ne__ etc. all map to tp_richcompare) and one name may map to multiple
Guido van Rossumc334df52002-04-04 23:44:47 +00003743 slots (e.g. __str__ affects tp_str as well as tp_repr). The table is
3744 terminated with an all-zero entry. (This table is further initialized and
3745 sorted in init_slotdefs() below.) */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003746
Guido van Rossum6d204072001-10-21 00:44:31 +00003747typedef struct wrapperbase slotdef;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003748
3749#undef TPSLOT
Guido van Rossumc8e56452001-10-22 00:43:43 +00003750#undef FLSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003751#undef ETSLOT
3752#undef SQSLOT
3753#undef MPSLOT
3754#undef NBSLOT
Guido van Rossum6d204072001-10-21 00:44:31 +00003755#undef UNSLOT
3756#undef IBSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003757#undef BINSLOT
3758#undef RBINSLOT
3759
Guido van Rossum6d204072001-10-21 00:44:31 +00003760#define TPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3761 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, DOC}
Guido van Rossumc8e56452001-10-22 00:43:43 +00003762#define FLSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC, FLAGS) \
3763 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
3764 DOC, FLAGS}
Guido van Rossum6d204072001-10-21 00:44:31 +00003765#define ETSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3766 {NAME, offsetof(etype, SLOT), (void *)(FUNCTION), WRAPPER, DOC}
3767#define SQSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3768 ETSLOT(NAME, as_sequence.SLOT, FUNCTION, WRAPPER, DOC)
3769#define MPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3770 ETSLOT(NAME, as_mapping.SLOT, FUNCTION, WRAPPER, DOC)
3771#define NBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3772 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, DOC)
3773#define UNSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3774 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
3775 "x." NAME "() <==> " DOC)
3776#define IBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3777 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
3778 "x." NAME "(y) <==> x" DOC "y")
3779#define BINSLOT(NAME, SLOT, FUNCTION, DOC) \
3780 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
3781 "x." NAME "(y) <==> x" DOC "y")
3782#define RBINSLOT(NAME, SLOT, FUNCTION, DOC) \
3783 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
3784 "x." NAME "(y) <==> y" DOC "x")
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003785
3786static slotdef slotdefs[] = {
Guido van Rossum6d204072001-10-21 00:44:31 +00003787 SQSLOT("__len__", sq_length, slot_sq_length, wrap_inquiry,
3788 "x.__len__() <==> len(x)"),
3789 SQSLOT("__add__", sq_concat, slot_sq_concat, wrap_binaryfunc,
3790 "x.__add__(y) <==> x+y"),
3791 SQSLOT("__mul__", sq_repeat, slot_sq_repeat, wrap_intargfunc,
3792 "x.__mul__(n) <==> x*n"),
3793 SQSLOT("__rmul__", sq_repeat, slot_sq_repeat, wrap_intargfunc,
3794 "x.__rmul__(n) <==> n*x"),
3795 SQSLOT("__getitem__", sq_item, slot_sq_item, wrap_sq_item,
3796 "x.__getitem__(y) <==> x[y]"),
3797 SQSLOT("__getslice__", sq_slice, slot_sq_slice, wrap_intintargfunc,
3798 "x.__getslice__(i, j) <==> x[i:j]"),
3799 SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_setitem,
3800 "x.__setitem__(i, y) <==> x[i]=y"),
3801 SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_delitem,
3802 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003803 SQSLOT("__setslice__", sq_ass_slice, slot_sq_ass_slice,
Guido van Rossum6d204072001-10-21 00:44:31 +00003804 wrap_intintobjargproc,
3805 "x.__setslice__(i, j, y) <==> x[i:j]=y"),
3806 SQSLOT("__delslice__", sq_ass_slice, slot_sq_ass_slice, wrap_delslice,
3807 "x.__delslice__(i, j) <==> del x[i:j]"),
3808 SQSLOT("__contains__", sq_contains, slot_sq_contains, wrap_objobjproc,
3809 "x.__contains__(y) <==> y in x"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003810 SQSLOT("__iadd__", sq_inplace_concat, slot_sq_inplace_concat,
Guido van Rossum6d204072001-10-21 00:44:31 +00003811 wrap_binaryfunc, "x.__iadd__(y) <==> x+=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003812 SQSLOT("__imul__", sq_inplace_repeat, slot_sq_inplace_repeat,
Guido van Rossum6d204072001-10-21 00:44:31 +00003813 wrap_intargfunc, "x.__imul__(y) <==> x*=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003814
Guido van Rossum6d204072001-10-21 00:44:31 +00003815 MPSLOT("__len__", mp_length, slot_mp_length, wrap_inquiry,
3816 "x.__len__() <==> len(x)"),
Guido van Rossumfd38f8e2001-10-09 20:17:57 +00003817 MPSLOT("__getitem__", mp_subscript, slot_mp_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00003818 wrap_binaryfunc,
3819 "x.__getitem__(y) <==> x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003820 MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00003821 wrap_objobjargproc,
3822 "x.__setitem__(i, y) <==> x[i]=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003823 MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00003824 wrap_delitem,
3825 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003826
Guido van Rossum6d204072001-10-21 00:44:31 +00003827 BINSLOT("__add__", nb_add, slot_nb_add,
3828 "+"),
3829 RBINSLOT("__radd__", nb_add, slot_nb_add,
3830 "+"),
3831 BINSLOT("__sub__", nb_subtract, slot_nb_subtract,
3832 "-"),
3833 RBINSLOT("__rsub__", nb_subtract, slot_nb_subtract,
3834 "-"),
3835 BINSLOT("__mul__", nb_multiply, slot_nb_multiply,
3836 "*"),
3837 RBINSLOT("__rmul__", nb_multiply, slot_nb_multiply,
3838 "*"),
3839 BINSLOT("__div__", nb_divide, slot_nb_divide,
3840 "/"),
3841 RBINSLOT("__rdiv__", nb_divide, slot_nb_divide,
3842 "/"),
3843 BINSLOT("__mod__", nb_remainder, slot_nb_remainder,
3844 "%"),
3845 RBINSLOT("__rmod__", nb_remainder, slot_nb_remainder,
3846 "%"),
3847 BINSLOT("__divmod__", nb_divmod, slot_nb_divmod,
3848 "divmod(x, y)"),
3849 RBINSLOT("__rdivmod__", nb_divmod, slot_nb_divmod,
3850 "divmod(y, x)"),
3851 NBSLOT("__pow__", nb_power, slot_nb_power, wrap_ternaryfunc,
3852 "x.__pow__(y[, z]) <==> pow(x, y[, z])"),
3853 NBSLOT("__rpow__", nb_power, slot_nb_power, wrap_ternaryfunc_r,
3854 "y.__rpow__(x[, z]) <==> pow(x, y[, z])"),
3855 UNSLOT("__neg__", nb_negative, slot_nb_negative, wrap_unaryfunc, "-x"),
3856 UNSLOT("__pos__", nb_positive, slot_nb_positive, wrap_unaryfunc, "+x"),
3857 UNSLOT("__abs__", nb_absolute, slot_nb_absolute, wrap_unaryfunc,
3858 "abs(x)"),
Guido van Rossumdfce3bf2002-03-10 14:11:16 +00003859 UNSLOT("__nonzero__", nb_nonzero, slot_nb_nonzero, wrap_inquiry,
Guido van Rossum6d204072001-10-21 00:44:31 +00003860 "x != 0"),
3861 UNSLOT("__invert__", nb_invert, slot_nb_invert, wrap_unaryfunc, "~x"),
3862 BINSLOT("__lshift__", nb_lshift, slot_nb_lshift, "<<"),
3863 RBINSLOT("__rlshift__", nb_lshift, slot_nb_lshift, "<<"),
3864 BINSLOT("__rshift__", nb_rshift, slot_nb_rshift, ">>"),
3865 RBINSLOT("__rrshift__", nb_rshift, slot_nb_rshift, ">>"),
3866 BINSLOT("__and__", nb_and, slot_nb_and, "&"),
3867 RBINSLOT("__rand__", nb_and, slot_nb_and, "&"),
3868 BINSLOT("__xor__", nb_xor, slot_nb_xor, "^"),
3869 RBINSLOT("__rxor__", nb_xor, slot_nb_xor, "^"),
3870 BINSLOT("__or__", nb_or, slot_nb_or, "|"),
3871 RBINSLOT("__ror__", nb_or, slot_nb_or, "|"),
3872 NBSLOT("__coerce__", nb_coerce, slot_nb_coerce, wrap_coercefunc,
3873 "x.__coerce__(y) <==> coerce(x, y)"),
3874 UNSLOT("__int__", nb_int, slot_nb_int, wrap_unaryfunc,
3875 "int(x)"),
3876 UNSLOT("__long__", nb_long, slot_nb_long, wrap_unaryfunc,
3877 "long(x)"),
3878 UNSLOT("__float__", nb_float, slot_nb_float, wrap_unaryfunc,
3879 "float(x)"),
3880 UNSLOT("__oct__", nb_oct, slot_nb_oct, wrap_unaryfunc,
3881 "oct(x)"),
3882 UNSLOT("__hex__", nb_hex, slot_nb_hex, wrap_unaryfunc,
3883 "hex(x)"),
3884 IBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add,
3885 wrap_binaryfunc, "+"),
3886 IBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract,
3887 wrap_binaryfunc, "-"),
3888 IBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply,
3889 wrap_binaryfunc, "*"),
3890 IBSLOT("__idiv__", nb_inplace_divide, slot_nb_inplace_divide,
3891 wrap_binaryfunc, "/"),
3892 IBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder,
3893 wrap_binaryfunc, "%"),
3894 IBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power,
3895 wrap_ternaryfunc, "**"),
3896 IBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift,
3897 wrap_binaryfunc, "<<"),
3898 IBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift,
3899 wrap_binaryfunc, ">>"),
3900 IBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and,
3901 wrap_binaryfunc, "&"),
3902 IBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor,
3903 wrap_binaryfunc, "^"),
3904 IBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or,
3905 wrap_binaryfunc, "|"),
3906 BINSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
3907 RBINSLOT("__rfloordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
3908 BINSLOT("__truediv__", nb_true_divide, slot_nb_true_divide, "/"),
3909 RBINSLOT("__rtruediv__", nb_true_divide, slot_nb_true_divide, "/"),
3910 IBSLOT("__ifloordiv__", nb_inplace_floor_divide,
3911 slot_nb_inplace_floor_divide, wrap_binaryfunc, "//"),
3912 IBSLOT("__itruediv__", nb_inplace_true_divide,
3913 slot_nb_inplace_true_divide, wrap_binaryfunc, "/"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003914
Guido van Rossum6d204072001-10-21 00:44:31 +00003915 TPSLOT("__str__", tp_str, slot_tp_str, wrap_unaryfunc,
3916 "x.__str__() <==> str(x)"),
Guido van Rossumafe7a942001-10-29 14:33:44 +00003917 TPSLOT("__str__", tp_print, NULL, NULL, ""),
Guido van Rossum6d204072001-10-21 00:44:31 +00003918 TPSLOT("__repr__", tp_repr, slot_tp_repr, wrap_unaryfunc,
3919 "x.__repr__() <==> repr(x)"),
Guido van Rossumafe7a942001-10-29 14:33:44 +00003920 TPSLOT("__repr__", tp_print, NULL, NULL, ""),
Guido van Rossum6d204072001-10-21 00:44:31 +00003921 TPSLOT("__cmp__", tp_compare, _PyObject_SlotCompare, wrap_cmpfunc,
3922 "x.__cmp__(y) <==> cmp(x,y)"),
3923 TPSLOT("__hash__", tp_hash, slot_tp_hash, wrap_hashfunc,
3924 "x.__hash__() <==> hash(x)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00003925 FLSLOT("__call__", tp_call, slot_tp_call, (wrapperfunc)wrap_call,
3926 "x.__call__(...) <==> x(...)", PyWrapperFlag_KEYWORDS),
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003927 TPSLOT("__getattribute__", tp_getattro, slot_tp_getattr_hook,
Guido van Rossum6d204072001-10-21 00:44:31 +00003928 wrap_binaryfunc, "x.__getattribute__('name') <==> x.name"),
3929 TPSLOT("__getattribute__", tp_getattr, NULL, NULL, ""),
3930 TPSLOT("__getattr__", tp_getattro, slot_tp_getattr_hook, NULL, ""),
3931 TPSLOT("__getattr__", tp_getattr, NULL, NULL, ""),
3932 TPSLOT("__setattr__", tp_setattro, slot_tp_setattro, wrap_setattr,
3933 "x.__setattr__('name', value) <==> x.name = value"),
3934 TPSLOT("__setattr__", tp_setattr, NULL, NULL, ""),
3935 TPSLOT("__delattr__", tp_setattro, slot_tp_setattro, wrap_delattr,
3936 "x.__delattr__('name') <==> del x.name"),
3937 TPSLOT("__delattr__", tp_setattr, NULL, NULL, ""),
3938 TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare, richcmp_lt,
3939 "x.__lt__(y) <==> x<y"),
3940 TPSLOT("__le__", tp_richcompare, slot_tp_richcompare, richcmp_le,
3941 "x.__le__(y) <==> x<=y"),
3942 TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare, richcmp_eq,
3943 "x.__eq__(y) <==> x==y"),
3944 TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare, richcmp_ne,
3945 "x.__ne__(y) <==> x!=y"),
3946 TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare, richcmp_gt,
3947 "x.__gt__(y) <==> x>y"),
3948 TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare, richcmp_ge,
3949 "x.__ge__(y) <==> x>=y"),
3950 TPSLOT("__iter__", tp_iter, slot_tp_iter, wrap_unaryfunc,
3951 "x.__iter__() <==> iter(x)"),
3952 TPSLOT("next", tp_iternext, slot_tp_iternext, wrap_next,
3953 "x.next() -> the next value, or raise StopIteration"),
3954 TPSLOT("__get__", tp_descr_get, slot_tp_descr_get, wrap_descr_get,
3955 "descr.__get__(obj[, type]) -> value"),
3956 TPSLOT("__set__", tp_descr_set, slot_tp_descr_set, wrap_descr_set,
3957 "descr.__set__(obj, value)"),
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00003958 TPSLOT("__delete__", tp_descr_set, slot_tp_descr_set,
3959 wrap_descr_delete, "descr.__delete__(obj)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00003960 FLSLOT("__init__", tp_init, slot_tp_init, (wrapperfunc)wrap_init,
Guido van Rossum6d204072001-10-21 00:44:31 +00003961 "x.__init__(...) initializes x; "
Guido van Rossumc8e56452001-10-22 00:43:43 +00003962 "see x.__class__.__doc__ for signature",
3963 PyWrapperFlag_KEYWORDS),
3964 TPSLOT("__new__", tp_new, slot_tp_new, NULL, ""),
Guido van Rossumfebd61d2002-08-08 20:55:20 +00003965 TPSLOT("__del__", tp_del, slot_tp_del, NULL, ""),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003966 {NULL}
3967};
3968
Guido van Rossumc334df52002-04-04 23:44:47 +00003969/* Given a type pointer and an offset gotten from a slotdef entry, return a
3970 pointer to the actual slot. This is not quite the same as simply adding
3971 the offset to the type pointer, since it takes care to indirect through the
3972 proper indirection pointer (as_buffer, etc.); it returns NULL if the
3973 indirection pointer is NULL. */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003974static void **
3975slotptr(PyTypeObject *type, int offset)
3976{
3977 char *ptr;
3978
Guido van Rossum09638c12002-06-13 19:17:46 +00003979 /* Note: this depends on the order of the members of etype! */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003980 assert(offset >= 0);
3981 assert(offset < offsetof(etype, as_buffer));
Guido van Rossum09638c12002-06-13 19:17:46 +00003982 if (offset >= offsetof(etype, as_sequence)) {
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003983 ptr = (void *)type->tp_as_sequence;
3984 offset -= offsetof(etype, as_sequence);
3985 }
Guido van Rossum09638c12002-06-13 19:17:46 +00003986 else if (offset >= offsetof(etype, as_mapping)) {
3987 ptr = (void *)type->tp_as_mapping;
3988 offset -= offsetof(etype, as_mapping);
3989 }
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003990 else if (offset >= offsetof(etype, as_number)) {
3991 ptr = (void *)type->tp_as_number;
3992 offset -= offsetof(etype, as_number);
3993 }
3994 else {
3995 ptr = (void *)type;
3996 }
3997 if (ptr != NULL)
3998 ptr += offset;
3999 return (void **)ptr;
4000}
Guido van Rossumf040ede2001-08-07 16:40:56 +00004001
Guido van Rossumc334df52002-04-04 23:44:47 +00004002/* Length of array of slotdef pointers used to store slots with the
4003 same __name__. There should be at most MAX_EQUIV-1 slotdef entries with
4004 the same __name__, for any __name__. Since that's a static property, it is
4005 appropriate to declare fixed-size arrays for this. */
4006#define MAX_EQUIV 10
4007
4008/* Return a slot pointer for a given name, but ONLY if the attribute has
4009 exactly one slot function. The name must be an interned string. */
4010static void **
4011resolve_slotdups(PyTypeObject *type, PyObject *name)
4012{
4013 /* XXX Maybe this could be optimized more -- but is it worth it? */
4014
4015 /* pname and ptrs act as a little cache */
4016 static PyObject *pname;
4017 static slotdef *ptrs[MAX_EQUIV];
4018 slotdef *p, **pp;
4019 void **res, **ptr;
4020
4021 if (pname != name) {
4022 /* Collect all slotdefs that match name into ptrs. */
4023 pname = name;
4024 pp = ptrs;
4025 for (p = slotdefs; p->name_strobj; p++) {
4026 if (p->name_strobj == name)
4027 *pp++ = p;
4028 }
4029 *pp = NULL;
4030 }
4031
4032 /* Look in all matching slots of the type; if exactly one of these has
4033 a filled-in slot, return its value. Otherwise return NULL. */
4034 res = NULL;
4035 for (pp = ptrs; *pp; pp++) {
4036 ptr = slotptr(type, (*pp)->offset);
4037 if (ptr == NULL || *ptr == NULL)
4038 continue;
4039 if (res != NULL)
4040 return NULL;
4041 res = ptr;
4042 }
4043 return res;
4044}
4045
4046/* Common code for update_these_slots() and fixup_slot_dispatchers(). This
4047 does some incredibly complex thinking and then sticks something into the
4048 slot. (It sees if the adjacent slotdefs for the same slot have conflicting
4049 interests, and then stores a generic wrapper or a specific function into
4050 the slot.) Return a pointer to the next slotdef with a different offset,
4051 because that's convenient for fixup_slot_dispatchers(). */
4052static slotdef *
4053update_one_slot(PyTypeObject *type, slotdef *p)
4054{
4055 PyObject *descr;
4056 PyWrapperDescrObject *d;
4057 void *generic = NULL, *specific = NULL;
4058 int use_generic = 0;
4059 int offset = p->offset;
4060 void **ptr = slotptr(type, offset);
4061
4062 if (ptr == NULL) {
4063 do {
4064 ++p;
4065 } while (p->offset == offset);
4066 return p;
4067 }
4068 do {
4069 descr = _PyType_Lookup(type, p->name_strobj);
4070 if (descr == NULL)
4071 continue;
4072 if (descr->ob_type == &PyWrapperDescr_Type) {
4073 void **tptr = resolve_slotdups(type, p->name_strobj);
4074 if (tptr == NULL || tptr == ptr)
4075 generic = p->function;
4076 d = (PyWrapperDescrObject *)descr;
4077 if (d->d_base->wrapper == p->wrapper &&
4078 PyType_IsSubtype(type, d->d_type))
4079 {
4080 if (specific == NULL ||
4081 specific == d->d_wrapped)
4082 specific = d->d_wrapped;
4083 else
4084 use_generic = 1;
4085 }
4086 }
Guido van Rossum721f62e2002-08-09 02:14:34 +00004087 else if (descr->ob_type == &PyCFunction_Type &&
4088 PyCFunction_GET_FUNCTION(descr) ==
4089 (PyCFunction)tp_new_wrapper &&
4090 strcmp(p->name, "__new__") == 0)
4091 {
4092 /* The __new__ wrapper is not a wrapper descriptor,
4093 so must be special-cased differently.
4094 If we don't do this, creating an instance will
4095 always use slot_tp_new which will look up
4096 __new__ in the MRO which will call tp_new_wrapper
4097 which will look through the base classes looking
4098 for a static base and call its tp_new (usually
4099 PyType_GenericNew), after performing various
4100 sanity checks and constructing a new argument
4101 list. Cut all that nonsense short -- this speeds
4102 up instance creation tremendously. */
4103 specific = type->tp_new;
4104 /* XXX I'm not 100% sure that there isn't a hole
4105 in this reasoning that requires additional
4106 sanity checks. I'll buy the first person to
4107 point out a bug in this reasoning a beer. */
4108 }
Guido van Rossumc334df52002-04-04 23:44:47 +00004109 else {
4110 use_generic = 1;
4111 generic = p->function;
4112 }
4113 } while ((++p)->offset == offset);
4114 if (specific && !use_generic)
4115 *ptr = specific;
4116 else
4117 *ptr = generic;
4118 return p;
4119}
4120
Guido van Rossum22b13872002-08-06 21:41:44 +00004121static int recurse_down_subclasses(PyTypeObject *type, slotdef **pp,
Jeremy Hylton938ace62002-07-17 16:30:39 +00004122 PyObject *name);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004123
Guido van Rossumc334df52002-04-04 23:44:47 +00004124/* In the type, update the slots whose slotdefs are gathered in the pp0 array,
4125 and then do the same for all this type's subtypes. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004126static int
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004127update_these_slots(PyTypeObject *type, slotdef **pp0, PyObject *name)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004128{
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004129 slotdef **pp;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004130
Guido van Rossumc334df52002-04-04 23:44:47 +00004131 for (pp = pp0; *pp; pp++)
4132 update_one_slot(type, *pp);
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004133 return recurse_down_subclasses(type, pp0, name);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004134}
4135
Guido van Rossumc334df52002-04-04 23:44:47 +00004136/* Update the slots whose slotdefs are gathered in the pp array in all (direct
4137 or indirect) subclasses of type. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004138static int
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004139recurse_down_subclasses(PyTypeObject *type, slotdef **pp, PyObject *name)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004140{
4141 PyTypeObject *subclass;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004142 PyObject *ref, *subclasses, *dict;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004143 int i, n;
4144
4145 subclasses = type->tp_subclasses;
4146 if (subclasses == NULL)
4147 return 0;
4148 assert(PyList_Check(subclasses));
4149 n = PyList_GET_SIZE(subclasses);
4150 for (i = 0; i < n; i++) {
4151 ref = PyList_GET_ITEM(subclasses, i);
4152 assert(PyWeakref_CheckRef(ref));
4153 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
Guido van Rossum59e6c532002-06-14 02:27:07 +00004154 assert(subclass != NULL);
4155 if ((PyObject *)subclass == Py_None)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004156 continue;
4157 assert(PyType_Check(subclass));
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004158 /* Avoid recursing down into unaffected classes */
4159 dict = subclass->tp_dict;
4160 if (dict != NULL && PyDict_Check(dict) &&
4161 PyDict_GetItem(dict, name) != NULL)
4162 continue;
4163 if (update_these_slots(subclass, pp, name) < 0)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004164 return -1;
4165 }
4166 return 0;
4167}
4168
Guido van Rossumc334df52002-04-04 23:44:47 +00004169/* Comparison function for qsort() to compare slotdefs by their offset, and
4170 for equal offset by their address (to force a stable sort). */
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004171static int
4172slotdef_cmp(const void *aa, const void *bb)
4173{
4174 const slotdef *a = (const slotdef *)aa, *b = (const slotdef *)bb;
4175 int c = a->offset - b->offset;
4176 if (c != 0)
4177 return c;
4178 else
4179 return a - b;
4180}
4181
Guido van Rossumc334df52002-04-04 23:44:47 +00004182/* Initialize the slotdefs table by adding interned string objects for the
4183 names and sorting the entries. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004184static void
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004185init_slotdefs(void)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004186{
4187 slotdef *p;
4188 static int initialized = 0;
4189
4190 if (initialized)
4191 return;
4192 for (p = slotdefs; p->name; p++) {
4193 p->name_strobj = PyString_InternFromString(p->name);
4194 if (!p->name_strobj)
Guido van Rossumc334df52002-04-04 23:44:47 +00004195 Py_FatalError("Out of memory interning slotdef names");
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004196 }
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004197 qsort((void *)slotdefs, (size_t)(p-slotdefs), sizeof(slotdef),
4198 slotdef_cmp);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004199 initialized = 1;
4200}
4201
Guido van Rossumc334df52002-04-04 23:44:47 +00004202/* Update the slots after assignment to a class (type) attribute. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004203static int
4204update_slot(PyTypeObject *type, PyObject *name)
4205{
Guido van Rossumc334df52002-04-04 23:44:47 +00004206 slotdef *ptrs[MAX_EQUIV];
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004207 slotdef *p;
4208 slotdef **pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004209 int offset;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004210
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004211 init_slotdefs();
4212 pp = ptrs;
4213 for (p = slotdefs; p->name; p++) {
4214 /* XXX assume name is interned! */
4215 if (p->name_strobj == name)
4216 *pp++ = p;
4217 }
4218 *pp = NULL;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004219 for (pp = ptrs; *pp; pp++) {
4220 p = *pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004221 offset = p->offset;
4222 while (p > slotdefs && (p-1)->offset == offset)
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004223 --p;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004224 *pp = p;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004225 }
Guido van Rossumc334df52002-04-04 23:44:47 +00004226 if (ptrs[0] == NULL)
4227 return 0; /* Not an attribute that affects any slots */
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004228 return update_these_slots(type, ptrs, name);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004229}
4230
Guido van Rossumc334df52002-04-04 23:44:47 +00004231/* Store the proper functions in the slot dispatches at class (type)
4232 definition time, based upon which operations the class overrides in its
4233 dict. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004234static void
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004235fixup_slot_dispatchers(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004236{
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004237 slotdef *p;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004238
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004239 init_slotdefs();
Guido van Rossumc334df52002-04-04 23:44:47 +00004240 for (p = slotdefs; p->name; )
4241 p = update_one_slot(type, p);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004242}
Guido van Rossum705f0f52001-08-24 16:47:00 +00004243
Guido van Rossum6d204072001-10-21 00:44:31 +00004244/* This function is called by PyType_Ready() to populate the type's
4245 dictionary with method descriptors for function slots. For each
Guido van Rossum09638c12002-06-13 19:17:46 +00004246 function slot (like tp_repr) that's defined in the type, one or more
4247 corresponding descriptors are added in the type's tp_dict dictionary
4248 under the appropriate name (like __repr__). Some function slots
4249 cause more than one descriptor to be added (for example, the nb_add
4250 slot adds both __add__ and __radd__ descriptors) and some function
4251 slots compete for the same descriptor (for example both sq_item and
4252 mp_subscript generate a __getitem__ descriptor).
4253
4254 In the latter case, the first slotdef entry encoutered wins. Since
4255 slotdef entries are sorted by the offset of the slot in the etype
4256 struct, this gives us some control over disambiguating between
4257 competing slots: the members of struct etype are listed from most
4258 general to least general, so the most general slot is preferred. In
4259 particular, because as_mapping comes before as_sequence, for a type
4260 that defines both mp_subscript and sq_item, mp_subscript wins.
4261
4262 This only adds new descriptors and doesn't overwrite entries in
4263 tp_dict that were previously defined. The descriptors contain a
4264 reference to the C function they must call, so that it's safe if they
4265 are copied into a subtype's __dict__ and the subtype has a different
4266 C function in its slot -- calling the method defined by the
4267 descriptor will call the C function that was used to create it,
4268 rather than the C function present in the slot when it is called.
4269 (This is important because a subtype may have a C function in the
4270 slot that calls the method from the dictionary, and we want to avoid
4271 infinite recursion here.) */
Guido van Rossum6d204072001-10-21 00:44:31 +00004272
4273static int
4274add_operators(PyTypeObject *type)
4275{
4276 PyObject *dict = type->tp_dict;
4277 slotdef *p;
4278 PyObject *descr;
4279 void **ptr;
4280
4281 init_slotdefs();
4282 for (p = slotdefs; p->name; p++) {
4283 if (p->wrapper == NULL)
4284 continue;
4285 ptr = slotptr(type, p->offset);
4286 if (!ptr || !*ptr)
4287 continue;
4288 if (PyDict_GetItem(dict, p->name_strobj))
4289 continue;
4290 descr = PyDescr_NewWrapper(type, p, *ptr);
4291 if (descr == NULL)
4292 return -1;
4293 if (PyDict_SetItem(dict, p->name_strobj, descr) < 0)
4294 return -1;
4295 Py_DECREF(descr);
4296 }
4297 if (type->tp_new != NULL) {
4298 if (add_tp_new_wrapper(type) < 0)
4299 return -1;
4300 }
4301 return 0;
4302}
4303
Guido van Rossum705f0f52001-08-24 16:47:00 +00004304
4305/* Cooperative 'super' */
4306
4307typedef struct {
4308 PyObject_HEAD
Guido van Rossume705ef12001-08-29 15:47:06 +00004309 PyTypeObject *type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00004310 PyObject *obj;
4311} superobject;
4312
Guido van Rossum6f799372001-09-20 20:46:19 +00004313static PyMemberDef super_members[] = {
4314 {"__thisclass__", T_OBJECT, offsetof(superobject, type), READONLY,
4315 "the class invoking super()"},
4316 {"__self__", T_OBJECT, offsetof(superobject, obj), READONLY,
4317 "the instance invoking super(); may be None"},
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004318 {0}
4319};
4320
Guido van Rossum705f0f52001-08-24 16:47:00 +00004321static void
4322super_dealloc(PyObject *self)
4323{
4324 superobject *su = (superobject *)self;
4325
Guido van Rossum048eb752001-10-02 21:24:57 +00004326 _PyObject_GC_UNTRACK(self);
Guido van Rossum705f0f52001-08-24 16:47:00 +00004327 Py_XDECREF(su->obj);
4328 Py_XDECREF(su->type);
4329 self->ob_type->tp_free(self);
4330}
4331
4332static PyObject *
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004333super_repr(PyObject *self)
4334{
4335 superobject *su = (superobject *)self;
4336
4337 if (su->obj)
4338 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00004339 "<super: <class '%s'>, <%s object>>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004340 su->type ? su->type->tp_name : "NULL",
4341 su->obj->ob_type->tp_name);
4342 else
4343 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00004344 "<super: <class '%s'>, NULL>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004345 su->type ? su->type->tp_name : "NULL");
4346}
4347
4348static PyObject *
Guido van Rossum705f0f52001-08-24 16:47:00 +00004349super_getattro(PyObject *self, PyObject *name)
4350{
4351 superobject *su = (superobject *)self;
4352
4353 if (su->obj != NULL) {
Tim Petersa91e9642001-11-14 23:32:33 +00004354 PyObject *mro, *res, *tmp, *dict;
Guido van Rossum155db9a2002-04-02 17:53:47 +00004355 PyTypeObject *starttype;
Guido van Rossum705f0f52001-08-24 16:47:00 +00004356 descrgetfunc f;
4357 int i, n;
4358
Guido van Rossum155db9a2002-04-02 17:53:47 +00004359 starttype = su->obj->ob_type;
4360 mro = starttype->tp_mro;
4361
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004362 if (mro == NULL)
4363 n = 0;
4364 else {
4365 assert(PyTuple_Check(mro));
4366 n = PyTuple_GET_SIZE(mro);
4367 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00004368 for (i = 0; i < n; i++) {
Guido van Rossume705ef12001-08-29 15:47:06 +00004369 if ((PyObject *)(su->type) == PyTuple_GET_ITEM(mro, i))
Guido van Rossum705f0f52001-08-24 16:47:00 +00004370 break;
4371 }
Guido van Rossume705ef12001-08-29 15:47:06 +00004372 if (i >= n && PyType_Check(su->obj)) {
Guido van Rossum155db9a2002-04-02 17:53:47 +00004373 starttype = (PyTypeObject *)(su->obj);
4374 mro = starttype->tp_mro;
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004375 if (mro == NULL)
4376 n = 0;
4377 else {
4378 assert(PyTuple_Check(mro));
4379 n = PyTuple_GET_SIZE(mro);
4380 }
Guido van Rossume705ef12001-08-29 15:47:06 +00004381 for (i = 0; i < n; i++) {
4382 if ((PyObject *)(su->type) ==
4383 PyTuple_GET_ITEM(mro, i))
4384 break;
4385 }
Guido van Rossume705ef12001-08-29 15:47:06 +00004386 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00004387 i++;
4388 res = NULL;
4389 for (; i < n; i++) {
4390 tmp = PyTuple_GET_ITEM(mro, i);
Tim Petersa91e9642001-11-14 23:32:33 +00004391 if (PyType_Check(tmp))
4392 dict = ((PyTypeObject *)tmp)->tp_dict;
4393 else if (PyClass_Check(tmp))
4394 dict = ((PyClassObject *)tmp)->cl_dict;
4395 else
4396 continue;
4397 res = PyDict_GetItem(dict, name);
Guido van Rossum5b443c62001-12-03 15:38:28 +00004398 if (res != NULL && !PyDescr_IsData(res)) {
Guido van Rossum705f0f52001-08-24 16:47:00 +00004399 Py_INCREF(res);
4400 f = res->ob_type->tp_descr_get;
4401 if (f != NULL) {
Guido van Rossumd4641072002-04-03 02:13:37 +00004402 tmp = f(res, su->obj,
4403 (PyObject *)starttype);
Guido van Rossum705f0f52001-08-24 16:47:00 +00004404 Py_DECREF(res);
4405 res = tmp;
4406 }
4407 return res;
4408 }
4409 }
4410 }
4411 return PyObject_GenericGetAttr(self, name);
4412}
4413
Guido van Rossum5b443c62001-12-03 15:38:28 +00004414static int
4415supercheck(PyTypeObject *type, PyObject *obj)
4416{
4417 if (!PyType_IsSubtype(obj->ob_type, type) &&
4418 !(PyType_Check(obj) &&
4419 PyType_IsSubtype((PyTypeObject *)obj, type))) {
4420 PyErr_SetString(PyExc_TypeError,
4421 "super(type, obj): "
4422 "obj must be an instance or subtype of type");
4423 return -1;
4424 }
4425 else
4426 return 0;
4427}
4428
Guido van Rossum705f0f52001-08-24 16:47:00 +00004429static PyObject *
4430super_descr_get(PyObject *self, PyObject *obj, PyObject *type)
4431{
4432 superobject *su = (superobject *)self;
4433 superobject *new;
4434
4435 if (obj == NULL || obj == Py_None || su->obj != NULL) {
4436 /* Not binding to an object, or already bound */
4437 Py_INCREF(self);
4438 return self;
4439 }
Guido van Rossum5b443c62001-12-03 15:38:28 +00004440 if (su->ob_type != &PySuper_Type)
4441 /* If su is an instance of a subclass of super,
4442 call its type */
4443 return PyObject_CallFunction((PyObject *)su->ob_type,
4444 "OO", su->type, obj);
4445 else {
4446 /* Inline the common case */
4447 if (supercheck(su->type, obj) < 0)
4448 return NULL;
4449 new = (superobject *)PySuper_Type.tp_new(&PySuper_Type,
4450 NULL, NULL);
4451 if (new == NULL)
4452 return NULL;
4453 Py_INCREF(su->type);
4454 Py_INCREF(obj);
4455 new->type = su->type;
4456 new->obj = obj;
4457 return (PyObject *)new;
4458 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00004459}
4460
4461static int
4462super_init(PyObject *self, PyObject *args, PyObject *kwds)
4463{
4464 superobject *su = (superobject *)self;
Guido van Rossume705ef12001-08-29 15:47:06 +00004465 PyTypeObject *type;
4466 PyObject *obj = NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00004467
4468 if (!PyArg_ParseTuple(args, "O!|O:super", &PyType_Type, &type, &obj))
4469 return -1;
4470 if (obj == Py_None)
4471 obj = NULL;
Guido van Rossum5b443c62001-12-03 15:38:28 +00004472 if (obj != NULL && supercheck(type, obj) < 0)
Guido van Rossum705f0f52001-08-24 16:47:00 +00004473 return -1;
Guido van Rossum705f0f52001-08-24 16:47:00 +00004474 Py_INCREF(type);
4475 Py_XINCREF(obj);
4476 su->type = type;
4477 su->obj = obj;
4478 return 0;
4479}
4480
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004481PyDoc_STRVAR(super_doc,
Guido van Rossum705f0f52001-08-24 16:47:00 +00004482"super(type) -> unbound super object\n"
4483"super(type, obj) -> bound super object; requires isinstance(obj, type)\n"
Guido van Rossume705ef12001-08-29 15:47:06 +00004484"super(type, type2) -> bound super object; requires issubclass(type2, type)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00004485"Typical use to call a cooperative superclass method:\n"
4486"class C(B):\n"
4487" def meth(self, arg):\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004488" super(C, self).meth(arg)");
Guido van Rossum705f0f52001-08-24 16:47:00 +00004489
Guido van Rossum048eb752001-10-02 21:24:57 +00004490static int
4491super_traverse(PyObject *self, visitproc visit, void *arg)
4492{
4493 superobject *su = (superobject *)self;
4494 int err;
4495
4496#define VISIT(SLOT) \
4497 if (SLOT) { \
4498 err = visit((PyObject *)(SLOT), arg); \
4499 if (err) \
4500 return err; \
4501 }
4502
4503 VISIT(su->obj);
4504 VISIT(su->type);
4505
4506#undef VISIT
4507
4508 return 0;
4509}
4510
Guido van Rossum705f0f52001-08-24 16:47:00 +00004511PyTypeObject PySuper_Type = {
4512 PyObject_HEAD_INIT(&PyType_Type)
4513 0, /* ob_size */
4514 "super", /* tp_name */
4515 sizeof(superobject), /* tp_basicsize */
4516 0, /* tp_itemsize */
4517 /* methods */
4518 super_dealloc, /* tp_dealloc */
4519 0, /* tp_print */
4520 0, /* tp_getattr */
4521 0, /* tp_setattr */
4522 0, /* tp_compare */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004523 super_repr, /* tp_repr */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004524 0, /* tp_as_number */
4525 0, /* tp_as_sequence */
4526 0, /* tp_as_mapping */
4527 0, /* tp_hash */
4528 0, /* tp_call */
4529 0, /* tp_str */
4530 super_getattro, /* tp_getattro */
4531 0, /* tp_setattro */
4532 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00004533 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
4534 Py_TPFLAGS_BASETYPE, /* tp_flags */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004535 super_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00004536 super_traverse, /* tp_traverse */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004537 0, /* tp_clear */
4538 0, /* tp_richcompare */
4539 0, /* tp_weaklistoffset */
4540 0, /* tp_iter */
4541 0, /* tp_iternext */
4542 0, /* tp_methods */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004543 super_members, /* tp_members */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004544 0, /* tp_getset */
4545 0, /* tp_base */
4546 0, /* tp_dict */
4547 super_descr_get, /* tp_descr_get */
4548 0, /* tp_descr_set */
4549 0, /* tp_dictoffset */
4550 super_init, /* tp_init */
4551 PyType_GenericAlloc, /* tp_alloc */
4552 PyType_GenericNew, /* tp_new */
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00004553 PyObject_GC_Del, /* tp_free */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004554};