blob: fc93d897ae4b794cd5098b1688fd2355fff1b040 [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 Petersa91e9642001-11-14 23:32:33 +0000616static int
617fill_classic_mro(PyObject *mro, PyObject *cls)
618{
619 PyObject *bases, *base;
620 int i, n;
621
622 assert(PyList_Check(mro));
623 assert(PyClass_Check(cls));
624 i = PySequence_Contains(mro, cls);
625 if (i < 0)
626 return -1;
627 if (!i) {
628 if (PyList_Append(mro, cls) < 0)
629 return -1;
630 }
631 bases = ((PyClassObject *)cls)->cl_bases;
632 assert(bases && PyTuple_Check(bases));
633 n = PyTuple_GET_SIZE(bases);
634 for (i = 0; i < n; i++) {
635 base = PyTuple_GET_ITEM(bases, i);
636 if (fill_classic_mro(mro, base) < 0)
637 return -1;
638 }
639 return 0;
640}
641
642static PyObject *
643classic_mro(PyObject *cls)
644{
645 PyObject *mro;
646
647 assert(PyClass_Check(cls));
648 mro = PyList_New(0);
649 if (mro != NULL) {
650 if (fill_classic_mro(mro, cls) == 0)
651 return mro;
652 Py_DECREF(mro);
653 }
654 return NULL;
655}
656
Guido van Rossum1f121312002-11-14 19:49:16 +0000657/*
658 Method resolution order algorithm C3 described in
659 "A Monotonic Superclass Linearization for Dylan",
660 by Kim Barrett, Bob Cassel, Paul Haahr,
661 David A. Moon, Keith Playford, and P. Tucker Withington.
662 (OOPSLA 1996)
663
Guido van Rossum98f33732002-11-25 21:36:54 +0000664 Some notes about the rules implied by C3:
665
666 No duplicate bases.
667 It isn't legal to repeat a class in a list of base classes.
668
669 The next three properties are the 3 constraints in "C3".
670
671 Local precendece order.
672 If A precedes B in C's MRO, then A will precede B in the MRO of all
673 subclasses of C.
674
675 Monotonicity.
676 The MRO of a class must be an extension without reordering of the
677 MRO of each of its superclasses.
678
679 Extended Precedence Graph (EPG).
680 Linearization is consistent if there is a path in the EPG from
681 each class to all its successors in the linearization. See
682 the paper for definition of EPG.
Guido van Rossum1f121312002-11-14 19:49:16 +0000683 */
684
685static int
686tail_contains(PyObject *list, int whence, PyObject *o) {
687 int j, size;
688 size = PyList_GET_SIZE(list);
689
690 for (j = whence+1; j < size; j++) {
691 if (PyList_GET_ITEM(list, j) == o)
692 return 1;
693 }
694 return 0;
695}
696
Guido van Rossum98f33732002-11-25 21:36:54 +0000697static PyObject *
698class_name(PyObject *cls)
699{
700 PyObject *name = PyObject_GetAttrString(cls, "__name__");
701 if (name == NULL) {
702 PyErr_Clear();
703 Py_XDECREF(name);
704 name = PyObject_Repr(cls);
705 }
706 if (name == NULL)
707 return NULL;
708 if (!PyString_Check(name)) {
709 Py_DECREF(name);
710 return NULL;
711 }
712 return name;
713}
714
715static int
716check_duplicates(PyObject *list)
717{
718 int i, j, n;
719 /* Let's use a quadratic time algorithm,
720 assuming that the bases lists is short.
721 */
722 n = PyList_GET_SIZE(list);
723 for (i = 0; i < n; i++) {
724 PyObject *o = PyList_GET_ITEM(list, i);
725 for (j = i + 1; j < n; j++) {
726 if (PyList_GET_ITEM(list, j) == o) {
727 o = class_name(o);
728 PyErr_Format(PyExc_TypeError,
729 "duplicate base class %s",
730 o ? PyString_AS_STRING(o) : "?");
731 Py_XDECREF(o);
732 return -1;
733 }
734 }
735 }
736 return 0;
737}
738
739/* Raise a TypeError for an MRO order disagreement.
740
741 It's hard to produce a good error message. In the absence of better
742 insight into error reporting, report the classes that were candidates
743 to be put next into the MRO. There is some conflict between the
744 order in which they should be put in the MRO, but it's hard to
745 diagnose what constraint can't be satisfied.
746*/
747
748static void
749set_mro_error(PyObject *to_merge, int *remain)
750{
751 int i, n, off, to_merge_size;
752 char buf[1000];
753 PyObject *k, *v;
754 PyObject *set = PyDict_New();
755
756 to_merge_size = PyList_GET_SIZE(to_merge);
757 for (i = 0; i < to_merge_size; i++) {
758 PyObject *L = PyList_GET_ITEM(to_merge, i);
759 if (remain[i] < PyList_GET_SIZE(L)) {
760 PyObject *c = PyList_GET_ITEM(L, remain[i]);
761 if (PyDict_SetItem(set, c, Py_None) < 0)
762 return;
763 }
764 }
765 n = PyDict_Size(set);
766
767 off = PyOS_snprintf(buf, sizeof(buf), "MRO conflict among bases");
768 i = 0;
769 while (PyDict_Next(set, &i, &k, &v) && off < sizeof(buf)) {
770 PyObject *name = class_name(k);
771 off += PyOS_snprintf(buf + off, sizeof(buf) - off, " %s",
772 name ? PyString_AS_STRING(name) : "?");
773 Py_XDECREF(name);
774 if (--n && off+1 < sizeof(buf)) {
775 buf[off++] = ',';
776 buf[off] = '\0';
777 }
778 }
779 PyErr_SetString(PyExc_TypeError, buf);
780 Py_DECREF(set);
781}
782
Guido van Rossum1f121312002-11-14 19:49:16 +0000783static int
784pmerge(PyObject *acc, PyObject* to_merge) {
785 int i, j, to_merge_size;
786 int *remain;
787 int ok, empty_cnt;
788
789 to_merge_size = PyList_GET_SIZE(to_merge);
790
Guido van Rossum98f33732002-11-25 21:36:54 +0000791 /* remain stores an index into each sublist of to_merge.
792 remain[i] is the index of the next base in to_merge[i]
793 that is not included in acc.
794 */
Guido van Rossum1f121312002-11-14 19:49:16 +0000795 remain = PyMem_MALLOC(SIZEOF_INT*to_merge_size);
796 if (remain == NULL)
797 return -1;
798 for (i = 0; i < to_merge_size; i++)
799 remain[i] = 0;
800
801 again:
802 empty_cnt = 0;
803 for (i = 0; i < to_merge_size; i++) {
804 PyObject *candidate;
805
806 PyObject *cur_list = PyList_GET_ITEM(to_merge, i);
807
808 if (remain[i] >= PyList_GET_SIZE(cur_list)) {
809 empty_cnt++;
810 continue;
811 }
812
Guido van Rossum98f33732002-11-25 21:36:54 +0000813 /* Choose next candidate for MRO.
814
815 The input sequences alone can determine the choice.
816 If not, choose the class which appears in the MRO
817 of the earliest direct superclass of the new class.
818 */
819
Guido van Rossum1f121312002-11-14 19:49:16 +0000820 candidate = PyList_GET_ITEM(cur_list, remain[i]);
821 for (j = 0; j < to_merge_size; j++) {
822 PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
Guido van Rossum98f33732002-11-25 21:36:54 +0000823 if (tail_contains(j_lst, remain[j], candidate)) {
Guido van Rossum1f121312002-11-14 19:49:16 +0000824 goto skip; /* continue outer loop */
Guido van Rossum98f33732002-11-25 21:36:54 +0000825 }
Guido van Rossum1f121312002-11-14 19:49:16 +0000826 }
827 ok = PyList_Append(acc, candidate);
828 if (ok < 0) {
829 PyMem_Free(remain);
830 return -1;
831 }
832 for (j = 0; j < to_merge_size; j++) {
833 PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
834 if (PyList_GET_ITEM(j_lst, remain[j]) == candidate) {
835 remain[j]++;
836 }
837 }
838 goto again;
Tim Peters9a6b8d82002-11-14 23:22:33 +0000839 skip: ;
Guido van Rossum1f121312002-11-14 19:49:16 +0000840 }
841
Guido van Rossum98f33732002-11-25 21:36:54 +0000842 if (empty_cnt == to_merge_size) {
843 PyMem_FREE(remain);
Guido van Rossum1f121312002-11-14 19:49:16 +0000844 return 0;
Guido van Rossum98f33732002-11-25 21:36:54 +0000845 }
846 set_mro_error(to_merge, remain);
847 PyMem_FREE(remain);
Guido van Rossum1f121312002-11-14 19:49:16 +0000848 return -1;
849}
850
Tim Peters6d6c1a32001-08-02 04:15:00 +0000851static PyObject *
852mro_implementation(PyTypeObject *type)
853{
854 int i, n, ok;
855 PyObject *bases, *result;
Guido van Rossum1f121312002-11-14 19:49:16 +0000856 PyObject *to_merge, *bases_aslist;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000857
Guido van Rossum63517572002-06-18 16:44:57 +0000858 if(type->tp_dict == NULL) {
859 if(PyType_Ready(type) < 0)
860 return NULL;
861 }
862
Guido van Rossum98f33732002-11-25 21:36:54 +0000863 /* Find a superclass linearization that honors the constraints
864 of the explicit lists of bases and the constraints implied by
865 each base class.
866
867 to_merge is a list of lists, where each list is a superclass
868 linearization implied by a base class. The last element of
869 to_merge is the declared list of bases.
870 */
871
Tim Peters6d6c1a32001-08-02 04:15:00 +0000872 bases = type->tp_bases;
873 n = PyTuple_GET_SIZE(bases);
Guido van Rossum1f121312002-11-14 19:49:16 +0000874
875 to_merge = PyList_New(n+1);
876 if (to_merge == NULL)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000877 return NULL;
Guido van Rossum1f121312002-11-14 19:49:16 +0000878
Tim Peters6d6c1a32001-08-02 04:15:00 +0000879 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +0000880 PyObject *base = PyTuple_GET_ITEM(bases, i);
881 PyObject *parentMRO;
882 if (PyType_Check(base))
883 parentMRO = PySequence_List(
884 ((PyTypeObject*)base)->tp_mro);
885 else
886 parentMRO = classic_mro(base);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000887 if (parentMRO == NULL) {
Guido van Rossum1f121312002-11-14 19:49:16 +0000888 Py_DECREF(to_merge);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000889 return NULL;
Guido van Rossum1f121312002-11-14 19:49:16 +0000890 }
891
892 PyList_SET_ITEM(to_merge, i, parentMRO);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000893 }
Guido van Rossum1f121312002-11-14 19:49:16 +0000894
895 bases_aslist = PySequence_List(bases);
896 if (bases_aslist == NULL) {
897 Py_DECREF(to_merge);
898 return NULL;
899 }
Guido van Rossum98f33732002-11-25 21:36:54 +0000900 /* This is just a basic sanity check. */
901 if (check_duplicates(bases_aslist) < 0) {
902 Py_DECREF(to_merge);
903 Py_DECREF(bases_aslist);
904 return NULL;
905 }
Guido van Rossum1f121312002-11-14 19:49:16 +0000906 PyList_SET_ITEM(to_merge, n, bases_aslist);
907
908 result = Py_BuildValue("[O]", (PyObject *)type);
909 if (result == NULL) {
910 Py_DECREF(to_merge);
911 return NULL;
912 }
913
914 ok = pmerge(result, to_merge);
915 Py_DECREF(to_merge);
916 if (ok < 0) {
917 Py_DECREF(result);
918 return NULL;
919 }
920
Tim Peters6d6c1a32001-08-02 04:15:00 +0000921 return result;
922}
923
924static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000925mro_external(PyObject *self)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000926{
927 PyTypeObject *type = (PyTypeObject *)self;
928
Tim Peters6d6c1a32001-08-02 04:15:00 +0000929 return mro_implementation(type);
930}
931
932static int
933mro_internal(PyTypeObject *type)
934{
935 PyObject *mro, *result, *tuple;
936
937 if (type->ob_type == &PyType_Type) {
938 result = mro_implementation(type);
939 }
940 else {
Guido van Rossum60718732001-08-28 17:47:51 +0000941 static PyObject *mro_str;
942 mro = lookup_method((PyObject *)type, "mro", &mro_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000943 if (mro == NULL)
944 return -1;
945 result = PyObject_CallObject(mro, NULL);
946 Py_DECREF(mro);
947 }
948 if (result == NULL)
949 return -1;
950 tuple = PySequence_Tuple(result);
951 Py_DECREF(result);
952 type->tp_mro = tuple;
953 return 0;
954}
955
956
957/* Calculate the best base amongst multiple base classes.
958 This is the first one that's on the path to the "solid base". */
959
960static PyTypeObject *
961best_base(PyObject *bases)
962{
963 int i, n;
964 PyTypeObject *base, *winner, *candidate, *base_i;
Tim Petersa91e9642001-11-14 23:32:33 +0000965 PyObject *base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000966
967 assert(PyTuple_Check(bases));
968 n = PyTuple_GET_SIZE(bases);
969 assert(n > 0);
Tim Petersa91e9642001-11-14 23:32:33 +0000970 base = NULL;
971 winner = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000972 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +0000973 base_proto = PyTuple_GET_ITEM(bases, i);
974 if (PyClass_Check(base_proto))
975 continue;
976 if (!PyType_Check(base_proto)) {
Tim Peters6d6c1a32001-08-02 04:15:00 +0000977 PyErr_SetString(
978 PyExc_TypeError,
979 "bases must be types");
980 return NULL;
981 }
Tim Petersa91e9642001-11-14 23:32:33 +0000982 base_i = (PyTypeObject *)base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000983 if (base_i->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +0000984 if (PyType_Ready(base_i) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000985 return NULL;
986 }
987 candidate = solid_base(base_i);
Tim Petersa91e9642001-11-14 23:32:33 +0000988 if (winner == NULL) {
989 winner = candidate;
990 base = base_i;
991 }
992 else if (PyType_IsSubtype(winner, candidate))
Tim Peters6d6c1a32001-08-02 04:15:00 +0000993 ;
994 else if (PyType_IsSubtype(candidate, winner)) {
995 winner = candidate;
996 base = base_i;
997 }
998 else {
999 PyErr_SetString(
1000 PyExc_TypeError,
1001 "multiple bases have "
1002 "instance lay-out conflict");
1003 return NULL;
1004 }
1005 }
Guido van Rossume54616c2001-12-14 04:19:56 +00001006 if (base == NULL)
1007 PyErr_SetString(PyExc_TypeError,
1008 "a new-style class can't have only classic bases");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001009 return base;
1010}
1011
1012static int
1013extra_ivars(PyTypeObject *type, PyTypeObject *base)
1014{
Neil Schemenauerc806c882001-08-29 23:54:54 +00001015 size_t t_size = type->tp_basicsize;
1016 size_t b_size = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001017
Guido van Rossum9676b222001-08-17 20:32:36 +00001018 assert(t_size >= b_size); /* Else type smaller than base! */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001019 if (type->tp_itemsize || base->tp_itemsize) {
1020 /* If itemsize is involved, stricter rules */
1021 return t_size != b_size ||
1022 type->tp_itemsize != base->tp_itemsize;
1023 }
Guido van Rossum9676b222001-08-17 20:32:36 +00001024 if (type->tp_weaklistoffset && base->tp_weaklistoffset == 0 &&
1025 type->tp_weaklistoffset + sizeof(PyObject *) == t_size)
1026 t_size -= sizeof(PyObject *);
1027 if (type->tp_dictoffset && base->tp_dictoffset == 0 &&
1028 type->tp_dictoffset + sizeof(PyObject *) == t_size)
1029 t_size -= sizeof(PyObject *);
1030
1031 return t_size != b_size;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001032}
1033
1034static PyTypeObject *
1035solid_base(PyTypeObject *type)
1036{
1037 PyTypeObject *base;
1038
1039 if (type->tp_base)
1040 base = solid_base(type->tp_base);
1041 else
1042 base = &PyBaseObject_Type;
1043 if (extra_ivars(type, base))
1044 return type;
1045 else
1046 return base;
1047}
1048
Jeremy Hylton938ace62002-07-17 16:30:39 +00001049static void object_dealloc(PyObject *);
1050static int object_init(PyObject *, PyObject *, PyObject *);
1051static int update_slot(PyTypeObject *, PyObject *);
1052static void fixup_slot_dispatchers(PyTypeObject *);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001053
1054static PyObject *
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001055subtype_dict(PyObject *obj, void *context)
1056{
1057 PyObject **dictptr = _PyObject_GetDictPtr(obj);
1058 PyObject *dict;
1059
1060 if (dictptr == NULL) {
1061 PyErr_SetString(PyExc_AttributeError,
1062 "This object has no __dict__");
1063 return NULL;
1064 }
1065 dict = *dictptr;
Guido van Rossum3926a632001-09-25 16:25:58 +00001066 if (dict == NULL)
1067 *dictptr = dict = PyDict_New();
1068 Py_XINCREF(dict);
1069 return dict;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001070}
1071
Guido van Rossum6661be32001-10-26 04:26:12 +00001072static int
1073subtype_setdict(PyObject *obj, PyObject *value, void *context)
1074{
1075 PyObject **dictptr = _PyObject_GetDictPtr(obj);
1076 PyObject *dict;
1077
1078 if (dictptr == NULL) {
1079 PyErr_SetString(PyExc_AttributeError,
1080 "This object has no __dict__");
1081 return -1;
1082 }
Guido van Rossumd331cb52001-12-05 19:46:42 +00001083 if (value != NULL && !PyDict_Check(value)) {
Guido van Rossum6661be32001-10-26 04:26:12 +00001084 PyErr_SetString(PyExc_TypeError,
1085 "__dict__ must be set to a dictionary");
1086 return -1;
1087 }
1088 dict = *dictptr;
Guido van Rossumd331cb52001-12-05 19:46:42 +00001089 Py_XINCREF(value);
Guido van Rossum6661be32001-10-26 04:26:12 +00001090 *dictptr = value;
1091 Py_XDECREF(dict);
1092 return 0;
1093}
1094
Guido van Rossumad47da02002-08-12 19:05:44 +00001095static PyObject *
1096subtype_getweakref(PyObject *obj, void *context)
1097{
1098 PyObject **weaklistptr;
1099 PyObject *result;
1100
1101 if (obj->ob_type->tp_weaklistoffset == 0) {
1102 PyErr_SetString(PyExc_AttributeError,
1103 "This object has no __weaklist__");
1104 return NULL;
1105 }
1106 assert(obj->ob_type->tp_weaklistoffset > 0);
1107 assert(obj->ob_type->tp_weaklistoffset + sizeof(PyObject *) <=
Guido van Rossum3747a0f2002-08-12 19:25:08 +00001108 (size_t)(obj->ob_type->tp_basicsize));
Guido van Rossumad47da02002-08-12 19:05:44 +00001109 weaklistptr = (PyObject **)
Guido van Rossum3747a0f2002-08-12 19:25:08 +00001110 ((char *)obj + obj->ob_type->tp_weaklistoffset);
Guido van Rossumad47da02002-08-12 19:05:44 +00001111 if (*weaklistptr == NULL)
1112 result = Py_None;
1113 else
1114 result = *weaklistptr;
1115 Py_INCREF(result);
1116 return result;
1117}
1118
Neil Schemenauerf23473f2001-10-21 22:28:58 +00001119static PyGetSetDef subtype_getsets[] = {
Guido van Rossumad47da02002-08-12 19:05:44 +00001120 /* Not all objects have these attributes!
1121 The descriptor's __get__ method may raise AttributeError. */
1122 {"__dict__", subtype_dict, subtype_setdict,
Neal Norwitz858e34f2002-08-13 17:18:45 +00001123 PyDoc_STR("dictionary for instance variables (if defined)")},
Guido van Rossumad47da02002-08-12 19:05:44 +00001124 {"__weakref__", subtype_getweakref, NULL,
Neal Norwitz858e34f2002-08-13 17:18:45 +00001125 PyDoc_STR("list of weak references to the object (if defined)")},
Guido van Rossumad47da02002-08-12 19:05:44 +00001126 {0}
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001127};
1128
Guido van Rossum0628dcf2002-03-14 23:03:14 +00001129/* bozo: __getstate__ that raises TypeError */
1130
1131static PyObject *
1132bozo_func(PyObject *self, PyObject *args)
1133{
1134 PyErr_SetString(PyExc_TypeError,
1135 "a class that defines __slots__ without "
1136 "defining __getstate__ cannot be pickled");
1137 return NULL;
1138}
1139
Neal Norwitz93c1e232002-03-31 16:06:11 +00001140static PyMethodDef bozo_ml = {"__getstate__", bozo_func, METH_VARARGS};
Guido van Rossum0628dcf2002-03-14 23:03:14 +00001141
1142static PyObject *bozo_obj = NULL;
1143
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001144static int
1145valid_identifier(PyObject *s)
1146{
Guido van Rossum03013a02002-07-16 14:30:28 +00001147 unsigned char *p;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001148 int i, n;
1149
1150 if (!PyString_Check(s)) {
1151 PyErr_SetString(PyExc_TypeError,
1152 "__slots__ must be strings");
1153 return 0;
1154 }
Guido van Rossum03013a02002-07-16 14:30:28 +00001155 p = (unsigned char *) PyString_AS_STRING(s);
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001156 n = PyString_GET_SIZE(s);
1157 /* We must reject an empty name. As a hack, we bump the
1158 length to 1 so that the loop will balk on the trailing \0. */
1159 if (n == 0)
1160 n = 1;
1161 for (i = 0; i < n; i++, p++) {
1162 if (!(i == 0 ? isalpha(*p) : isalnum(*p)) && *p != '_') {
1163 PyErr_SetString(PyExc_TypeError,
1164 "__slots__ must be identifiers");
1165 return 0;
1166 }
1167 }
1168 return 1;
1169}
1170
Martin v. Löwisd919a592002-10-14 21:07:28 +00001171#ifdef Py_USING_UNICODE
1172/* Replace Unicode objects in slots. */
1173
1174static PyObject *
1175_unicode_to_string(PyObject *slots, int nslots)
1176{
1177 PyObject *tmp = slots;
1178 PyObject *o, *o1;
1179 int i;
1180 intintargfunc copy = slots->ob_type->tp_as_sequence->sq_slice;
1181 for (i = 0; i < nslots; i++) {
1182 if (PyUnicode_Check(o = PyTuple_GET_ITEM(tmp, i))) {
1183 if (tmp == slots) {
1184 tmp = copy(slots, 0, PyTuple_GET_SIZE(slots));
1185 if (tmp == NULL)
1186 return NULL;
1187 }
1188 o1 = _PyUnicode_AsDefaultEncodedString
1189 (o, NULL);
1190 if (o1 == NULL) {
1191 Py_DECREF(tmp);
1192 return 0;
1193 }
1194 Py_INCREF(o1);
1195 Py_DECREF(o);
1196 PyTuple_SET_ITEM(tmp, i, o1);
1197 }
1198 }
1199 return tmp;
1200}
1201#endif
1202
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001203static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00001204type_new(PyTypeObject *metatype, PyObject *args, PyObject *kwds)
1205{
1206 PyObject *name, *bases, *dict;
1207 static char *kwlist[] = {"name", "bases", "dict", 0};
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001208 PyObject *slots, *tmp, *newslots;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001209 PyTypeObject *type, *base, *tmptype, *winner;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001210 etype *et;
Guido van Rossum6f799372001-09-20 20:46:19 +00001211 PyMemberDef *mp;
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001212 int i, nbases, nslots, slotoffset, add_dict, add_weak;
Guido van Rossumad47da02002-08-12 19:05:44 +00001213 int j, may_add_dict, may_add_weak;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001214
Tim Peters3abca122001-10-27 19:37:48 +00001215 assert(args != NULL && PyTuple_Check(args));
1216 assert(kwds == NULL || PyDict_Check(kwds));
1217
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001218 /* Special case: type(x) should return x->ob_type */
Tim Peters3abca122001-10-27 19:37:48 +00001219 {
1220 const int nargs = PyTuple_GET_SIZE(args);
1221 const int nkwds = kwds == NULL ? 0 : PyDict_Size(kwds);
1222
1223 if (PyType_CheckExact(metatype) && nargs == 1 && nkwds == 0) {
1224 PyObject *x = PyTuple_GET_ITEM(args, 0);
1225 Py_INCREF(x->ob_type);
1226 return (PyObject *) x->ob_type;
1227 }
1228
1229 /* SF bug 475327 -- if that didn't trigger, we need 3
1230 arguments. but PyArg_ParseTupleAndKeywords below may give
1231 a msg saying type() needs exactly 3. */
1232 if (nargs + nkwds != 3) {
1233 PyErr_SetString(PyExc_TypeError,
1234 "type() takes 1 or 3 arguments");
1235 return NULL;
1236 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001237 }
1238
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001239 /* Check arguments: (name, bases, dict) */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001240 if (!PyArg_ParseTupleAndKeywords(args, kwds, "SO!O!:type", kwlist,
1241 &name,
1242 &PyTuple_Type, &bases,
1243 &PyDict_Type, &dict))
1244 return NULL;
1245
1246 /* Determine the proper metatype to deal with this,
1247 and check for metatype conflicts while we're at it.
1248 Note that if some other metatype wins to contract,
1249 it's possible that its instances are not types. */
1250 nbases = PyTuple_GET_SIZE(bases);
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001251 winner = metatype;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001252 for (i = 0; i < nbases; i++) {
1253 tmp = PyTuple_GET_ITEM(bases, i);
1254 tmptype = tmp->ob_type;
Tim Petersa91e9642001-11-14 23:32:33 +00001255 if (tmptype == &PyClass_Type)
1256 continue; /* Special case classic classes */
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001257 if (PyType_IsSubtype(winner, tmptype))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001258 continue;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001259 if (PyType_IsSubtype(tmptype, winner)) {
1260 winner = tmptype;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001261 continue;
1262 }
1263 PyErr_SetString(PyExc_TypeError,
1264 "metatype conflict among bases");
1265 return NULL;
1266 }
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001267 if (winner != metatype) {
1268 if (winner->tp_new != type_new) /* Pass it to the winner */
1269 return winner->tp_new(winner, args, kwds);
1270 metatype = winner;
1271 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001272
1273 /* Adjust for empty tuple bases */
1274 if (nbases == 0) {
1275 bases = Py_BuildValue("(O)", &PyBaseObject_Type);
1276 if (bases == NULL)
1277 return NULL;
1278 nbases = 1;
1279 }
1280 else
1281 Py_INCREF(bases);
1282
1283 /* XXX From here until type is allocated, "return NULL" leaks bases! */
1284
1285 /* Calculate best base, and check that all bases are type objects */
1286 base = best_base(bases);
1287 if (base == NULL)
1288 return NULL;
1289 if (!PyType_HasFeature(base, Py_TPFLAGS_BASETYPE)) {
1290 PyErr_Format(PyExc_TypeError,
1291 "type '%.100s' is not an acceptable base type",
1292 base->tp_name);
1293 return NULL;
1294 }
1295
Tim Peters6d6c1a32001-08-02 04:15:00 +00001296 /* Check for a __slots__ sequence variable in dict, and count it */
1297 slots = PyDict_GetItemString(dict, "__slots__");
1298 nslots = 0;
Guido van Rossum9676b222001-08-17 20:32:36 +00001299 add_dict = 0;
1300 add_weak = 0;
Guido van Rossumad47da02002-08-12 19:05:44 +00001301 may_add_dict = base->tp_dictoffset == 0;
1302 may_add_weak = base->tp_weaklistoffset == 0 && base->tp_itemsize == 0;
1303 if (slots == NULL) {
1304 if (may_add_dict) {
1305 add_dict++;
1306 }
1307 if (may_add_weak) {
1308 add_weak++;
1309 }
1310 }
1311 else {
1312 /* Have slots */
1313
Tim Peters6d6c1a32001-08-02 04:15:00 +00001314 /* Make it into a tuple */
1315 if (PyString_Check(slots))
1316 slots = Py_BuildValue("(O)", slots);
1317 else
1318 slots = PySequence_Tuple(slots);
1319 if (slots == NULL)
1320 return NULL;
Guido van Rossumad47da02002-08-12 19:05:44 +00001321 assert(PyTuple_Check(slots));
1322
1323 /* Are slots allowed? */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001324 nslots = PyTuple_GET_SIZE(slots);
Guido van Rossumc4141872001-08-30 04:43:35 +00001325 if (nslots > 0 && base->tp_itemsize != 0) {
1326 PyErr_Format(PyExc_TypeError,
1327 "nonempty __slots__ "
1328 "not supported for subtype of '%s'",
1329 base->tp_name);
Guido van Rossumad47da02002-08-12 19:05:44 +00001330 bad_slots:
1331 Py_DECREF(slots);
Guido van Rossumc4141872001-08-30 04:43:35 +00001332 return NULL;
1333 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001334
Martin v. Löwisd919a592002-10-14 21:07:28 +00001335#ifdef Py_USING_UNICODE
1336 tmp = _unicode_to_string(slots, nslots);
Martin v. Löwis13b1a5c2002-10-14 21:11:34 +00001337 if (tmp != slots) {
1338 Py_DECREF(slots);
1339 slots = tmp;
1340 }
Martin v. Löwisd919a592002-10-14 21:07:28 +00001341 if (!tmp)
1342 return NULL;
1343#endif
Guido van Rossumad47da02002-08-12 19:05:44 +00001344 /* Check for valid slot names and two special cases */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001345 for (i = 0; i < nslots; i++) {
Guido van Rossumad47da02002-08-12 19:05:44 +00001346 PyObject *tmp = PyTuple_GET_ITEM(slots, i);
1347 char *s;
1348 if (!valid_identifier(tmp))
1349 goto bad_slots;
1350 assert(PyString_Check(tmp));
1351 s = PyString_AS_STRING(tmp);
1352 if (strcmp(s, "__dict__") == 0) {
1353 if (!may_add_dict || add_dict) {
1354 PyErr_SetString(PyExc_TypeError,
1355 "__dict__ slot disallowed: "
1356 "we already got one");
1357 goto bad_slots;
1358 }
1359 add_dict++;
1360 }
1361 if (strcmp(s, "__weakref__") == 0) {
1362 if (!may_add_weak || add_weak) {
1363 PyErr_SetString(PyExc_TypeError,
1364 "__weakref__ slot disallowed: "
1365 "either we already got one, "
1366 "or __itemsize__ != 0");
1367 goto bad_slots;
1368 }
1369 add_weak++;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001370 }
1371 }
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001372
Guido van Rossumad47da02002-08-12 19:05:44 +00001373 /* Copy slots into yet another tuple, demangling names */
1374 newslots = PyTuple_New(nslots - add_dict - add_weak);
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001375 if (newslots == NULL)
Guido van Rossumad47da02002-08-12 19:05:44 +00001376 goto bad_slots;
1377 for (i = j = 0; i < nslots; i++) {
1378 char *s;
Guido van Rossum8e829202002-08-16 03:47:49 +00001379 char buffer[256];
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001380 tmp = PyTuple_GET_ITEM(slots, i);
Guido van Rossumad47da02002-08-12 19:05:44 +00001381 s = PyString_AS_STRING(tmp);
1382 if ((add_dict && strcmp(s, "__dict__") == 0) ||
1383 (add_weak && strcmp(s, "__weakref__") == 0))
1384 continue;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001385 if (_Py_Mangle(PyString_AS_STRING(name),
Guido van Rossumad47da02002-08-12 19:05:44 +00001386 PyString_AS_STRING(tmp),
1387 buffer, sizeof(buffer)))
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001388 {
1389 tmp = PyString_FromString(buffer);
1390 } else {
1391 Py_INCREF(tmp);
1392 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001393 PyTuple_SET_ITEM(newslots, j, tmp);
1394 j++;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001395 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001396 assert(j == nslots - add_dict - add_weak);
1397 nslots = j;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001398 Py_DECREF(slots);
1399 slots = newslots;
1400
Guido van Rossum0628dcf2002-03-14 23:03:14 +00001401 /* See if *this* class defines __getstate__ */
Guido van Rossumad47da02002-08-12 19:05:44 +00001402 if (PyDict_GetItemString(dict, "__getstate__") == NULL) {
Guido van Rossum0628dcf2002-03-14 23:03:14 +00001403 /* If not, provide a bozo that raises TypeError */
1404 if (bozo_obj == NULL) {
1405 bozo_obj = PyCFunction_New(&bozo_ml, NULL);
Guido van Rossumad47da02002-08-12 19:05:44 +00001406 if (bozo_obj == NULL)
1407 goto bad_slots;
Guido van Rossum0628dcf2002-03-14 23:03:14 +00001408 }
1409 if (PyDict_SetItemString(dict,
1410 "__getstate__",
Guido van Rossumad47da02002-08-12 19:05:44 +00001411 bozo_obj) < 0)
1412 {
1413 Py_DECREF(bozo_obj);
1414 goto bad_slots;
Guido van Rossum0628dcf2002-03-14 23:03:14 +00001415 }
1416 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001417
1418 /* Secondary bases may provide weakrefs or dict */
1419 if (nbases > 1 &&
1420 ((may_add_dict && !add_dict) ||
1421 (may_add_weak && !add_weak))) {
1422 for (i = 0; i < nbases; i++) {
1423 tmp = PyTuple_GET_ITEM(bases, i);
1424 if (tmp == (PyObject *)base)
1425 continue; /* Skip primary base */
1426 if (PyClass_Check(tmp)) {
1427 /* Classic base class provides both */
1428 if (may_add_dict && !add_dict)
1429 add_dict++;
1430 if (may_add_weak && !add_weak)
1431 add_weak++;
1432 break;
1433 }
1434 assert(PyType_Check(tmp));
1435 tmptype = (PyTypeObject *)tmp;
1436 if (may_add_dict && !add_dict &&
1437 tmptype->tp_dictoffset != 0)
1438 add_dict++;
1439 if (may_add_weak && !add_weak &&
1440 tmptype->tp_weaklistoffset != 0)
1441 add_weak++;
1442 if (may_add_dict && !add_dict)
1443 continue;
1444 if (may_add_weak && !add_weak)
1445 continue;
1446 /* Nothing more to check */
1447 break;
1448 }
1449 }
Guido van Rossum9676b222001-08-17 20:32:36 +00001450 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001451
1452 /* XXX From here until type is safely allocated,
1453 "return NULL" may leak slots! */
1454
1455 /* Allocate the type object */
1456 type = (PyTypeObject *)metatype->tp_alloc(metatype, nslots);
Guido van Rossumad47da02002-08-12 19:05:44 +00001457 if (type == NULL) {
1458 Py_XDECREF(slots);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001459 return NULL;
Guido van Rossumad47da02002-08-12 19:05:44 +00001460 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001461
1462 /* Keep name and slots alive in the extended type object */
1463 et = (etype *)type;
1464 Py_INCREF(name);
1465 et->name = name;
1466 et->slots = slots;
1467
Guido van Rossumdc91b992001-08-08 22:26:22 +00001468 /* Initialize tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001469 type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE |
1470 Py_TPFLAGS_BASETYPE;
Guido van Rossum048eb752001-10-02 21:24:57 +00001471 if (base->tp_flags & Py_TPFLAGS_HAVE_GC)
1472 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossumdc91b992001-08-08 22:26:22 +00001473
1474 /* It's a new-style number unless it specifically inherits any
1475 old-style numeric behavior */
1476 if ((base->tp_flags & Py_TPFLAGS_CHECKTYPES) ||
1477 (base->tp_as_number == NULL))
1478 type->tp_flags |= Py_TPFLAGS_CHECKTYPES;
1479
1480 /* Initialize essential fields */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001481 type->tp_as_number = &et->as_number;
1482 type->tp_as_sequence = &et->as_sequence;
1483 type->tp_as_mapping = &et->as_mapping;
1484 type->tp_as_buffer = &et->as_buffer;
1485 type->tp_name = PyString_AS_STRING(name);
1486
1487 /* Set tp_base and tp_bases */
1488 type->tp_bases = bases;
1489 Py_INCREF(base);
1490 type->tp_base = base;
1491
Guido van Rossum687ae002001-10-15 22:03:32 +00001492 /* Initialize tp_dict from passed-in dict */
1493 type->tp_dict = dict = PyDict_Copy(dict);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001494 if (dict == NULL) {
1495 Py_DECREF(type);
1496 return NULL;
1497 }
1498
Guido van Rossumc3542212001-08-16 09:18:56 +00001499 /* Set __module__ in the dict */
1500 if (PyDict_GetItemString(dict, "__module__") == NULL) {
1501 tmp = PyEval_GetGlobals();
1502 if (tmp != NULL) {
1503 tmp = PyDict_GetItemString(tmp, "__name__");
1504 if (tmp != NULL) {
1505 if (PyDict_SetItemString(dict, "__module__",
1506 tmp) < 0)
1507 return NULL;
1508 }
1509 }
1510 }
1511
Tim Peters2f93e282001-10-04 05:27:00 +00001512 /* Set tp_doc to a copy of dict['__doc__'], if the latter is there
Tim Peters24008312002-03-17 18:56:20 +00001513 and is a string. The __doc__ accessor will first look for tp_doc;
1514 if that fails, it will still look into __dict__.
Tim Peters2f93e282001-10-04 05:27:00 +00001515 */
1516 {
1517 PyObject *doc = PyDict_GetItemString(dict, "__doc__");
1518 if (doc != NULL && PyString_Check(doc)) {
1519 const size_t n = (size_t)PyString_GET_SIZE(doc);
Tim Peters59f809d2001-10-04 05:43:02 +00001520 type->tp_doc = (char *)PyObject_MALLOC(n+1);
Tim Peters2f93e282001-10-04 05:27:00 +00001521 if (type->tp_doc == NULL) {
1522 Py_DECREF(type);
1523 return NULL;
1524 }
1525 memcpy(type->tp_doc, PyString_AS_STRING(doc), n+1);
1526 }
1527 }
1528
Tim Peters6d6c1a32001-08-02 04:15:00 +00001529 /* Special-case __new__: if it's a plain function,
1530 make it a static function */
1531 tmp = PyDict_GetItemString(dict, "__new__");
1532 if (tmp != NULL && PyFunction_Check(tmp)) {
1533 tmp = PyStaticMethod_New(tmp);
1534 if (tmp == NULL) {
1535 Py_DECREF(type);
1536 return NULL;
1537 }
1538 PyDict_SetItemString(dict, "__new__", tmp);
1539 Py_DECREF(tmp);
1540 }
1541
1542 /* Add descriptors for custom slots from __slots__, or for __dict__ */
1543 mp = et->members;
Neil Schemenauerc806c882001-08-29 23:54:54 +00001544 slotoffset = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001545 if (slots != NULL) {
1546 for (i = 0; i < nslots; i++, mp++) {
1547 mp->name = PyString_AS_STRING(
1548 PyTuple_GET_ITEM(slots, i));
Guido van Rossum64b206c2001-12-04 17:13:22 +00001549 mp->type = T_OBJECT_EX;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001550 mp->offset = slotoffset;
Guido van Rossum9676b222001-08-17 20:32:36 +00001551 if (base->tp_weaklistoffset == 0 &&
Guido van Rossum64b206c2001-12-04 17:13:22 +00001552 strcmp(mp->name, "__weakref__") == 0) {
Guido van Rossumad47da02002-08-12 19:05:44 +00001553 add_weak++;
Guido van Rossum64b206c2001-12-04 17:13:22 +00001554 mp->type = T_OBJECT;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001555 mp->flags = READONLY;
Guido van Rossum9676b222001-08-17 20:32:36 +00001556 type->tp_weaklistoffset = slotoffset;
Guido van Rossum64b206c2001-12-04 17:13:22 +00001557 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001558 slotoffset += sizeof(PyObject *);
1559 }
1560 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001561 if (add_dict) {
1562 if (base->tp_itemsize)
1563 type->tp_dictoffset = -(long)sizeof(PyObject *);
1564 else
1565 type->tp_dictoffset = slotoffset;
1566 slotoffset += sizeof(PyObject *);
1567 }
1568 if (add_weak) {
1569 assert(!base->tp_itemsize);
1570 type->tp_weaklistoffset = slotoffset;
1571 slotoffset += sizeof(PyObject *);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001572 }
1573 type->tp_basicsize = slotoffset;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001574 type->tp_itemsize = base->tp_itemsize;
Guido van Rossum13d52f02001-08-10 21:24:08 +00001575 type->tp_members = et->members;
Guido van Rossumad47da02002-08-12 19:05:44 +00001576 type->tp_getset = subtype_getsets;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001577
1578 /* Special case some slots */
1579 if (type->tp_dictoffset != 0 || nslots > 0) {
1580 if (base->tp_getattr == NULL && base->tp_getattro == NULL)
1581 type->tp_getattro = PyObject_GenericGetAttr;
1582 if (base->tp_setattr == NULL && base->tp_setattro == NULL)
1583 type->tp_setattro = PyObject_GenericSetAttr;
1584 }
1585 type->tp_dealloc = subtype_dealloc;
1586
Guido van Rossum9475a232001-10-05 20:51:39 +00001587 /* Enable GC unless there are really no instance variables possible */
1588 if (!(type->tp_basicsize == sizeof(PyObject) &&
1589 type->tp_itemsize == 0))
1590 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
1591
Tim Peters6d6c1a32001-08-02 04:15:00 +00001592 /* Always override allocation strategy to use regular heap */
1593 type->tp_alloc = PyType_GenericAlloc;
Guido van Rossum048eb752001-10-02 21:24:57 +00001594 if (type->tp_flags & Py_TPFLAGS_HAVE_GC) {
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00001595 type->tp_free = PyObject_GC_Del;
Guido van Rossum9475a232001-10-05 20:51:39 +00001596 type->tp_traverse = subtype_traverse;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001597 type->tp_clear = subtype_clear;
Guido van Rossum048eb752001-10-02 21:24:57 +00001598 }
1599 else
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00001600 type->tp_free = PyObject_Del;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001601
1602 /* Initialize the rest */
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001603 if (PyType_Ready(type) < 0) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001604 Py_DECREF(type);
1605 return NULL;
1606 }
1607
Guido van Rossum7b9144b2001-10-09 19:39:46 +00001608 /* Put the proper slots in place */
1609 fixup_slot_dispatchers(type);
Guido van Rossumf040ede2001-08-07 16:40:56 +00001610
Tim Peters6d6c1a32001-08-02 04:15:00 +00001611 return (PyObject *)type;
1612}
1613
1614/* Internal API to look for a name through the MRO.
1615 This returns a borrowed reference, and doesn't set an exception! */
1616PyObject *
1617_PyType_Lookup(PyTypeObject *type, PyObject *name)
1618{
1619 int i, n;
Tim Petersa91e9642001-11-14 23:32:33 +00001620 PyObject *mro, *res, *base, *dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001621
Guido van Rossum687ae002001-10-15 22:03:32 +00001622 /* Look in tp_dict of types in MRO */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001623 mro = type->tp_mro;
Guido van Rossum23094982002-06-10 14:30:43 +00001624
1625 /* If mro is NULL, the type is either not yet initialized
1626 by PyType_Ready(), or already cleared by type_clear().
1627 Either way the safest thing to do is to return NULL. */
1628 if (mro == NULL)
1629 return NULL;
1630
Tim Peters6d6c1a32001-08-02 04:15:00 +00001631 assert(PyTuple_Check(mro));
1632 n = PyTuple_GET_SIZE(mro);
1633 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00001634 base = PyTuple_GET_ITEM(mro, i);
1635 if (PyClass_Check(base))
1636 dict = ((PyClassObject *)base)->cl_dict;
1637 else {
1638 assert(PyType_Check(base));
1639 dict = ((PyTypeObject *)base)->tp_dict;
1640 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001641 assert(dict && PyDict_Check(dict));
1642 res = PyDict_GetItem(dict, name);
1643 if (res != NULL)
1644 return res;
1645 }
1646 return NULL;
1647}
1648
1649/* This is similar to PyObject_GenericGetAttr(),
1650 but uses _PyType_Lookup() instead of just looking in type->tp_dict. */
1651static PyObject *
1652type_getattro(PyTypeObject *type, PyObject *name)
1653{
1654 PyTypeObject *metatype = type->ob_type;
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001655 PyObject *meta_attribute, *attribute;
1656 descrgetfunc meta_get;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001657
1658 /* Initialize this type (we'll assume the metatype is initialized) */
1659 if (type->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001660 if (PyType_Ready(type) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001661 return NULL;
1662 }
1663
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001664 /* No readable descriptor found yet */
1665 meta_get = NULL;
Tim Peters34592512002-07-11 06:23:50 +00001666
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001667 /* Look for the attribute in the metatype */
1668 meta_attribute = _PyType_Lookup(metatype, name);
1669
1670 if (meta_attribute != NULL) {
1671 meta_get = meta_attribute->ob_type->tp_descr_get;
Tim Peters34592512002-07-11 06:23:50 +00001672
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001673 if (meta_get != NULL && PyDescr_IsData(meta_attribute)) {
1674 /* Data descriptors implement tp_descr_set to intercept
1675 * writes. Assume the attribute is not overridden in
1676 * type's tp_dict (and bases): call the descriptor now.
1677 */
1678 return meta_get(meta_attribute, (PyObject *)type,
1679 (PyObject *)metatype);
1680 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001681 }
1682
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001683 /* No data descriptor found on metatype. Look in tp_dict of this
1684 * type and its bases */
1685 attribute = _PyType_Lookup(type, name);
1686 if (attribute != NULL) {
1687 /* Implement descriptor functionality, if any */
1688 descrgetfunc local_get = attribute->ob_type->tp_descr_get;
1689 if (local_get != NULL) {
1690 /* NULL 2nd argument indicates the descriptor was
1691 * found on the target object itself (or a base) */
1692 return local_get(attribute, (PyObject *)NULL,
1693 (PyObject *)type);
1694 }
Tim Peters34592512002-07-11 06:23:50 +00001695
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001696 Py_INCREF(attribute);
1697 return attribute;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001698 }
1699
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001700 /* No attribute found in local __dict__ (or bases): use the
1701 * descriptor from the metatype, if any */
1702 if (meta_get != NULL)
1703 return meta_get(meta_attribute, (PyObject *)type,
1704 (PyObject *)metatype);
1705
1706 /* If an ordinary attribute was found on the metatype, return it now */
1707 if (meta_attribute != NULL) {
1708 Py_INCREF(meta_attribute);
1709 return meta_attribute;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001710 }
1711
1712 /* Give up */
1713 PyErr_Format(PyExc_AttributeError,
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001714 "type object '%.50s' has no attribute '%.400s'",
1715 type->tp_name, PyString_AS_STRING(name));
Tim Peters6d6c1a32001-08-02 04:15:00 +00001716 return NULL;
1717}
1718
1719static int
1720type_setattro(PyTypeObject *type, PyObject *name, PyObject *value)
1721{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001722 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
1723 PyErr_Format(
1724 PyExc_TypeError,
1725 "can't set attributes of built-in/extension type '%s'",
1726 type->tp_name);
1727 return -1;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00001728 }
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001729 if (PyObject_GenericSetAttr((PyObject *)type, name, value) < 0)
1730 return -1;
1731 return update_slot(type, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001732}
1733
1734static void
1735type_dealloc(PyTypeObject *type)
1736{
1737 etype *et;
1738
1739 /* Assert this is a heap-allocated type object */
1740 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00001741 _PyObject_GC_UNTRACK(type);
Guido van Rossum1c450732001-10-08 15:18:27 +00001742 PyObject_ClearWeakRefs((PyObject *)type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001743 et = (etype *)type;
1744 Py_XDECREF(type->tp_base);
1745 Py_XDECREF(type->tp_dict);
1746 Py_XDECREF(type->tp_bases);
1747 Py_XDECREF(type->tp_mro);
Guido van Rossum687ae002001-10-15 22:03:32 +00001748 Py_XDECREF(type->tp_cache);
Guido van Rossum1c450732001-10-08 15:18:27 +00001749 Py_XDECREF(type->tp_subclasses);
Neal Norwitzcee5ca02002-07-30 00:42:06 +00001750 PyObject_Free(type->tp_doc);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001751 Py_XDECREF(et->name);
1752 Py_XDECREF(et->slots);
1753 type->ob_type->tp_free((PyObject *)type);
1754}
1755
Guido van Rossum1c450732001-10-08 15:18:27 +00001756static PyObject *
1757type_subclasses(PyTypeObject *type, PyObject *args_ignored)
1758{
1759 PyObject *list, *raw, *ref;
1760 int i, n;
1761
1762 list = PyList_New(0);
1763 if (list == NULL)
1764 return NULL;
1765 raw = type->tp_subclasses;
1766 if (raw == NULL)
1767 return list;
1768 assert(PyList_Check(raw));
1769 n = PyList_GET_SIZE(raw);
1770 for (i = 0; i < n; i++) {
1771 ref = PyList_GET_ITEM(raw, i);
Tim Peters44383382001-10-08 16:49:26 +00001772 assert(PyWeakref_CheckRef(ref));
Guido van Rossum1c450732001-10-08 15:18:27 +00001773 ref = PyWeakref_GET_OBJECT(ref);
1774 if (ref != Py_None) {
1775 if (PyList_Append(list, ref) < 0) {
1776 Py_DECREF(list);
1777 return NULL;
1778 }
1779 }
1780 }
1781 return list;
1782}
1783
Tim Peters6d6c1a32001-08-02 04:15:00 +00001784static PyMethodDef type_methods[] = {
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001785 {"mro", (PyCFunction)mro_external, METH_NOARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00001786 PyDoc_STR("mro() -> list\nreturn a type's method resolution order")},
Guido van Rossum1c450732001-10-08 15:18:27 +00001787 {"__subclasses__", (PyCFunction)type_subclasses, METH_NOARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00001788 PyDoc_STR("__subclasses__() -> list of immediate subclasses")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00001789 {0}
1790};
1791
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001792PyDoc_STRVAR(type_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001793"type(object) -> the object's type\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001794"type(name, bases, dict) -> a new type");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001795
Guido van Rossum048eb752001-10-02 21:24:57 +00001796static int
1797type_traverse(PyTypeObject *type, visitproc visit, void *arg)
1798{
Guido van Rossum048eb752001-10-02 21:24:57 +00001799 int err;
1800
Guido van Rossuma3862092002-06-10 15:24:42 +00001801 /* Because of type_is_gc(), the collector only calls this
1802 for heaptypes. */
1803 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00001804
1805#define VISIT(SLOT) \
1806 if (SLOT) { \
1807 err = visit((PyObject *)(SLOT), arg); \
1808 if (err) \
1809 return err; \
1810 }
1811
1812 VISIT(type->tp_dict);
Guido van Rossum687ae002001-10-15 22:03:32 +00001813 VISIT(type->tp_cache);
Guido van Rossum048eb752001-10-02 21:24:57 +00001814 VISIT(type->tp_mro);
1815 VISIT(type->tp_bases);
1816 VISIT(type->tp_base);
Guido van Rossuma3862092002-06-10 15:24:42 +00001817
1818 /* There's no need to visit type->tp_subclasses or
1819 ((etype *)type)->slots, because they can't be involved
1820 in cycles; tp_subclasses is a list of weak references,
1821 and slots is a tuple of strings. */
Guido van Rossum048eb752001-10-02 21:24:57 +00001822
1823#undef VISIT
1824
1825 return 0;
1826}
1827
1828static int
1829type_clear(PyTypeObject *type)
1830{
Guido van Rossum048eb752001-10-02 21:24:57 +00001831 PyObject *tmp;
1832
Guido van Rossuma3862092002-06-10 15:24:42 +00001833 /* Because of type_is_gc(), the collector only calls this
1834 for heaptypes. */
1835 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00001836
1837#define CLEAR(SLOT) \
1838 if (SLOT) { \
1839 tmp = (PyObject *)(SLOT); \
1840 SLOT = NULL; \
1841 Py_DECREF(tmp); \
1842 }
1843
Guido van Rossuma3862092002-06-10 15:24:42 +00001844 /* The only field we need to clear is tp_mro, which is part of a
1845 hard cycle (its first element is the class itself) that won't
1846 be broken otherwise (it's a tuple and tuples don't have a
1847 tp_clear handler). None of the other fields need to be
1848 cleared, and here's why:
Guido van Rossum048eb752001-10-02 21:24:57 +00001849
Guido van Rossuma3862092002-06-10 15:24:42 +00001850 tp_dict:
1851 It is a dict, so the collector will call its tp_clear.
1852
1853 tp_cache:
1854 Not used; if it were, it would be a dict.
1855
1856 tp_bases, tp_base:
1857 If these are involved in a cycle, there must be at least
1858 one other, mutable object in the cycle, e.g. a base
1859 class's dict; the cycle will be broken that way.
1860
1861 tp_subclasses:
1862 A list of weak references can't be part of a cycle; and
1863 lists have their own tp_clear.
1864
1865 slots (in etype):
1866 A tuple of strings can't be part of a cycle.
1867 */
1868
1869 CLEAR(type->tp_mro);
Tim Peters2f93e282001-10-04 05:27:00 +00001870
Guido van Rossum048eb752001-10-02 21:24:57 +00001871#undef CLEAR
1872
1873 return 0;
1874}
1875
1876static int
1877type_is_gc(PyTypeObject *type)
1878{
1879 return type->tp_flags & Py_TPFLAGS_HEAPTYPE;
1880}
1881
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001882PyTypeObject PyType_Type = {
1883 PyObject_HEAD_INIT(&PyType_Type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001884 0, /* ob_size */
1885 "type", /* tp_name */
1886 sizeof(etype), /* tp_basicsize */
Guido van Rossum6f799372001-09-20 20:46:19 +00001887 sizeof(PyMemberDef), /* tp_itemsize */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001888 (destructor)type_dealloc, /* tp_dealloc */
1889 0, /* tp_print */
1890 0, /* tp_getattr */
1891 0, /* tp_setattr */
1892 type_compare, /* tp_compare */
1893 (reprfunc)type_repr, /* tp_repr */
1894 0, /* tp_as_number */
1895 0, /* tp_as_sequence */
1896 0, /* tp_as_mapping */
1897 (hashfunc)_Py_HashPointer, /* tp_hash */
1898 (ternaryfunc)type_call, /* tp_call */
1899 0, /* tp_str */
1900 (getattrofunc)type_getattro, /* tp_getattro */
1901 (setattrofunc)type_setattro, /* tp_setattro */
1902 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00001903 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
1904 Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001905 type_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00001906 (traverseproc)type_traverse, /* tp_traverse */
1907 (inquiry)type_clear, /* tp_clear */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001908 0, /* tp_richcompare */
Guido van Rossum1c450732001-10-08 15:18:27 +00001909 offsetof(PyTypeObject, tp_weaklist), /* tp_weaklistoffset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001910 0, /* tp_iter */
1911 0, /* tp_iternext */
1912 type_methods, /* tp_methods */
1913 type_members, /* tp_members */
1914 type_getsets, /* tp_getset */
1915 0, /* tp_base */
1916 0, /* tp_dict */
1917 0, /* tp_descr_get */
1918 0, /* tp_descr_set */
1919 offsetof(PyTypeObject, tp_dict), /* tp_dictoffset */
1920 0, /* tp_init */
1921 0, /* tp_alloc */
1922 type_new, /* tp_new */
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00001923 PyObject_GC_Del, /* tp_free */
Guido van Rossum048eb752001-10-02 21:24:57 +00001924 (inquiry)type_is_gc, /* tp_is_gc */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001925};
Tim Peters6d6c1a32001-08-02 04:15:00 +00001926
1927
1928/* The base type of all types (eventually)... except itself. */
1929
1930static int
1931object_init(PyObject *self, PyObject *args, PyObject *kwds)
1932{
1933 return 0;
1934}
1935
1936static void
1937object_dealloc(PyObject *self)
1938{
1939 self->ob_type->tp_free(self);
1940}
1941
Guido van Rossum8e248182001-08-12 05:17:56 +00001942static PyObject *
1943object_repr(PyObject *self)
1944{
Guido van Rossum76e69632001-08-16 18:52:43 +00001945 PyTypeObject *type;
Barry Warsaw7ce36942001-08-24 18:34:26 +00001946 PyObject *mod, *name, *rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00001947
Guido van Rossum76e69632001-08-16 18:52:43 +00001948 type = self->ob_type;
1949 mod = type_module(type, NULL);
1950 if (mod == NULL)
1951 PyErr_Clear();
1952 else if (!PyString_Check(mod)) {
1953 Py_DECREF(mod);
1954 mod = NULL;
1955 }
1956 name = type_name(type, NULL);
1957 if (name == NULL)
1958 return NULL;
1959 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__"))
Guido van Rossumff0e6d62001-09-24 16:03:59 +00001960 rtn = PyString_FromFormat("<%s.%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00001961 PyString_AS_STRING(mod),
1962 PyString_AS_STRING(name),
1963 self);
Guido van Rossum76e69632001-08-16 18:52:43 +00001964 else
Guido van Rossumff0e6d62001-09-24 16:03:59 +00001965 rtn = PyString_FromFormat("<%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00001966 type->tp_name, self);
Guido van Rossum76e69632001-08-16 18:52:43 +00001967 Py_XDECREF(mod);
1968 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +00001969 return rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00001970}
1971
Guido van Rossumb8f63662001-08-15 23:57:02 +00001972static PyObject *
1973object_str(PyObject *self)
1974{
1975 unaryfunc f;
1976
1977 f = self->ob_type->tp_repr;
1978 if (f == NULL)
1979 f = object_repr;
1980 return f(self);
1981}
1982
Guido van Rossum8e248182001-08-12 05:17:56 +00001983static long
1984object_hash(PyObject *self)
1985{
1986 return _Py_HashPointer(self);
1987}
Guido van Rossum8e248182001-08-12 05:17:56 +00001988
Guido van Rossum5c294fb2001-09-25 03:43:42 +00001989static PyObject *
1990object_get_class(PyObject *self, void *closure)
1991{
1992 Py_INCREF(self->ob_type);
1993 return (PyObject *)(self->ob_type);
1994}
1995
1996static int
1997equiv_structs(PyTypeObject *a, PyTypeObject *b)
1998{
1999 return a == b ||
2000 (a != NULL &&
2001 b != NULL &&
2002 a->tp_basicsize == b->tp_basicsize &&
2003 a->tp_itemsize == b->tp_itemsize &&
2004 a->tp_dictoffset == b->tp_dictoffset &&
2005 a->tp_weaklistoffset == b->tp_weaklistoffset &&
2006 ((a->tp_flags & Py_TPFLAGS_HAVE_GC) ==
2007 (b->tp_flags & Py_TPFLAGS_HAVE_GC)));
2008}
2009
2010static int
2011same_slots_added(PyTypeObject *a, PyTypeObject *b)
2012{
2013 PyTypeObject *base = a->tp_base;
2014 int size;
2015
2016 if (base != b->tp_base)
2017 return 0;
2018 if (equiv_structs(a, base) && equiv_structs(b, base))
2019 return 1;
2020 size = base->tp_basicsize;
2021 if (a->tp_dictoffset == size && b->tp_dictoffset == size)
2022 size += sizeof(PyObject *);
2023 if (a->tp_weaklistoffset == size && b->tp_weaklistoffset == size)
2024 size += sizeof(PyObject *);
2025 return size == a->tp_basicsize && size == b->tp_basicsize;
2026}
2027
2028static int
2029object_set_class(PyObject *self, PyObject *value, void *closure)
2030{
2031 PyTypeObject *old = self->ob_type;
2032 PyTypeObject *new, *newbase, *oldbase;
2033
Guido van Rossumb6b89422002-04-15 01:03:30 +00002034 if (value == NULL) {
2035 PyErr_SetString(PyExc_TypeError,
2036 "can't delete __class__ attribute");
2037 return -1;
2038 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002039 if (!PyType_Check(value)) {
2040 PyErr_Format(PyExc_TypeError,
2041 "__class__ must be set to new-style class, not '%s' object",
2042 value->ob_type->tp_name);
2043 return -1;
2044 }
2045 new = (PyTypeObject *)value;
Guido van Rossum40af8892002-08-10 05:42:07 +00002046 if (!(new->tp_flags & Py_TPFLAGS_HEAPTYPE) ||
2047 !(old->tp_flags & Py_TPFLAGS_HEAPTYPE))
2048 {
2049 PyErr_Format(PyExc_TypeError,
2050 "__class__ assignment: only for heap types");
2051 return -1;
2052 }
Guido van Rossum9ee4b942002-05-24 18:47:47 +00002053 if (new->tp_dealloc != old->tp_dealloc ||
2054 new->tp_free != old->tp_free)
2055 {
2056 PyErr_Format(PyExc_TypeError,
2057 "__class__ assignment: "
2058 "'%s' deallocator differs from '%s'",
2059 new->tp_name,
2060 old->tp_name);
2061 return -1;
2062 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002063 newbase = new;
2064 oldbase = old;
2065 while (equiv_structs(newbase, newbase->tp_base))
2066 newbase = newbase->tp_base;
2067 while (equiv_structs(oldbase, oldbase->tp_base))
2068 oldbase = oldbase->tp_base;
2069 if (newbase != oldbase &&
2070 (newbase->tp_base != oldbase->tp_base ||
2071 !same_slots_added(newbase, oldbase))) {
2072 PyErr_Format(PyExc_TypeError,
2073 "__class__ assignment: "
2074 "'%s' object layout differs from '%s'",
Tim Peters2f93e282001-10-04 05:27:00 +00002075 new->tp_name,
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002076 old->tp_name);
2077 return -1;
2078 }
Guido van Rossum40af8892002-08-10 05:42:07 +00002079 Py_INCREF(new);
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002080 self->ob_type = new;
Guido van Rossum40af8892002-08-10 05:42:07 +00002081 Py_DECREF(old);
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002082 return 0;
2083}
2084
2085static PyGetSetDef object_getsets[] = {
2086 {"__class__", object_get_class, object_set_class,
Neal Norwitz858e34f2002-08-13 17:18:45 +00002087 PyDoc_STR("the object's class")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002088 {0}
2089};
2090
Guido van Rossum3926a632001-09-25 16:25:58 +00002091static PyObject *
2092object_reduce(PyObject *self, PyObject *args)
2093{
2094 /* Call copy_reg._reduce(self) */
2095 static PyObject *copy_reg_str;
2096 PyObject *copy_reg, *res;
2097
2098 if (!copy_reg_str) {
2099 copy_reg_str = PyString_InternFromString("copy_reg");
2100 if (copy_reg_str == NULL)
2101 return NULL;
2102 }
2103 copy_reg = PyImport_Import(copy_reg_str);
2104 if (!copy_reg)
2105 return NULL;
2106 res = PyEval_CallMethod(copy_reg, "_reduce", "(O)", self);
2107 Py_DECREF(copy_reg);
2108 return res;
2109}
2110
2111static PyMethodDef object_methods[] = {
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002112 {"__reduce__", object_reduce, METH_NOARGS,
2113 PyDoc_STR("helper for pickle")},
Guido van Rossum3926a632001-09-25 16:25:58 +00002114 {0}
2115};
2116
Tim Peters6d6c1a32001-08-02 04:15:00 +00002117PyTypeObject PyBaseObject_Type = {
2118 PyObject_HEAD_INIT(&PyType_Type)
2119 0, /* ob_size */
2120 "object", /* tp_name */
2121 sizeof(PyObject), /* tp_basicsize */
2122 0, /* tp_itemsize */
2123 (destructor)object_dealloc, /* tp_dealloc */
2124 0, /* tp_print */
2125 0, /* tp_getattr */
2126 0, /* tp_setattr */
2127 0, /* tp_compare */
Guido van Rossumb8f63662001-08-15 23:57:02 +00002128 object_repr, /* tp_repr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002129 0, /* tp_as_number */
2130 0, /* tp_as_sequence */
2131 0, /* tp_as_mapping */
Guido van Rossumb8f63662001-08-15 23:57:02 +00002132 object_hash, /* tp_hash */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002133 0, /* tp_call */
Guido van Rossumb8f63662001-08-15 23:57:02 +00002134 object_str, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002135 PyObject_GenericGetAttr, /* tp_getattro */
Guido van Rossum13d52f02001-08-10 21:24:08 +00002136 PyObject_GenericSetAttr, /* tp_setattro */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002137 0, /* tp_as_buffer */
2138 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002139 PyDoc_STR("The most base type"), /* tp_doc */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002140 0, /* tp_traverse */
2141 0, /* tp_clear */
2142 0, /* tp_richcompare */
2143 0, /* tp_weaklistoffset */
2144 0, /* tp_iter */
2145 0, /* tp_iternext */
Guido van Rossum3926a632001-09-25 16:25:58 +00002146 object_methods, /* tp_methods */
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002147 0, /* tp_members */
2148 object_getsets, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002149 0, /* tp_base */
2150 0, /* tp_dict */
2151 0, /* tp_descr_get */
2152 0, /* tp_descr_set */
2153 0, /* tp_dictoffset */
2154 object_init, /* tp_init */
2155 PyType_GenericAlloc, /* tp_alloc */
Guido van Rossumc11e1922001-08-09 19:38:15 +00002156 PyType_GenericNew, /* tp_new */
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00002157 PyObject_Del, /* tp_free */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002158};
2159
2160
2161/* Initialize the __dict__ in a type object */
2162
Fred Drake7bf97152002-03-28 05:33:33 +00002163static PyObject *
2164create_specialmethod(PyMethodDef *meth, PyObject *(*func)(PyObject *))
2165{
2166 PyObject *cfunc;
2167 PyObject *result;
2168
2169 cfunc = PyCFunction_New(meth, NULL);
2170 if (cfunc == NULL)
2171 return NULL;
2172 result = func(cfunc);
2173 Py_DECREF(cfunc);
2174 return result;
2175}
2176
Tim Peters6d6c1a32001-08-02 04:15:00 +00002177static int
2178add_methods(PyTypeObject *type, PyMethodDef *meth)
2179{
Guido van Rossum687ae002001-10-15 22:03:32 +00002180 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002181
2182 for (; meth->ml_name != NULL; meth++) {
2183 PyObject *descr;
2184 if (PyDict_GetItemString(dict, meth->ml_name))
2185 continue;
Fred Drake7bf97152002-03-28 05:33:33 +00002186 if (meth->ml_flags & METH_CLASS) {
2187 if (meth->ml_flags & METH_STATIC) {
2188 PyErr_SetString(PyExc_ValueError,
2189 "method cannot be both class and static");
2190 return -1;
2191 }
2192 descr = create_specialmethod(meth, PyClassMethod_New);
2193 }
2194 else if (meth->ml_flags & METH_STATIC) {
2195 descr = create_specialmethod(meth, PyStaticMethod_New);
2196 }
2197 else {
2198 descr = PyDescr_NewMethod(type, meth);
2199 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002200 if (descr == NULL)
2201 return -1;
Fred Drake7bf97152002-03-28 05:33:33 +00002202 if (PyDict_SetItemString(dict, meth->ml_name, descr) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002203 return -1;
2204 Py_DECREF(descr);
2205 }
2206 return 0;
2207}
2208
2209static int
Guido van Rossum6f799372001-09-20 20:46:19 +00002210add_members(PyTypeObject *type, PyMemberDef *memb)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002211{
Guido van Rossum687ae002001-10-15 22:03:32 +00002212 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002213
2214 for (; memb->name != NULL; memb++) {
2215 PyObject *descr;
2216 if (PyDict_GetItemString(dict, memb->name))
2217 continue;
2218 descr = PyDescr_NewMember(type, memb);
2219 if (descr == NULL)
2220 return -1;
2221 if (PyDict_SetItemString(dict, memb->name, descr) < 0)
2222 return -1;
2223 Py_DECREF(descr);
2224 }
2225 return 0;
2226}
2227
2228static int
Guido van Rossum32d34c82001-09-20 21:45:26 +00002229add_getset(PyTypeObject *type, PyGetSetDef *gsp)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002230{
Guido van Rossum687ae002001-10-15 22:03:32 +00002231 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002232
2233 for (; gsp->name != NULL; gsp++) {
2234 PyObject *descr;
2235 if (PyDict_GetItemString(dict, gsp->name))
2236 continue;
2237 descr = PyDescr_NewGetSet(type, gsp);
2238
2239 if (descr == NULL)
2240 return -1;
2241 if (PyDict_SetItemString(dict, gsp->name, descr) < 0)
2242 return -1;
2243 Py_DECREF(descr);
2244 }
2245 return 0;
2246}
2247
Guido van Rossum13d52f02001-08-10 21:24:08 +00002248static void
2249inherit_special(PyTypeObject *type, PyTypeObject *base)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002250{
2251 int oldsize, newsize;
2252
Guido van Rossum13d52f02001-08-10 21:24:08 +00002253 /* Special flag magic */
2254 if (!type->tp_as_buffer && base->tp_as_buffer) {
2255 type->tp_flags &= ~Py_TPFLAGS_HAVE_GETCHARBUFFER;
2256 type->tp_flags |=
2257 base->tp_flags & Py_TPFLAGS_HAVE_GETCHARBUFFER;
2258 }
2259 if (!type->tp_as_sequence && base->tp_as_sequence) {
2260 type->tp_flags &= ~Py_TPFLAGS_HAVE_SEQUENCE_IN;
2261 type->tp_flags |= base->tp_flags & Py_TPFLAGS_HAVE_SEQUENCE_IN;
2262 }
2263 if ((type->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS) !=
2264 (base->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS)) {
2265 if ((!type->tp_as_number && base->tp_as_number) ||
2266 (!type->tp_as_sequence && base->tp_as_sequence)) {
2267 type->tp_flags &= ~Py_TPFLAGS_HAVE_INPLACEOPS;
2268 if (!type->tp_as_number && !type->tp_as_sequence) {
2269 type->tp_flags |= base->tp_flags &
2270 Py_TPFLAGS_HAVE_INPLACEOPS;
2271 }
2272 }
2273 /* Wow */
2274 }
2275 if (!type->tp_as_number && base->tp_as_number) {
2276 type->tp_flags &= ~Py_TPFLAGS_CHECKTYPES;
2277 type->tp_flags |= base->tp_flags & Py_TPFLAGS_CHECKTYPES;
2278 }
2279
2280 /* Copying basicsize is connected to the GC flags */
Neil Schemenauerc806c882001-08-29 23:54:54 +00002281 oldsize = base->tp_basicsize;
2282 newsize = type->tp_basicsize ? type->tp_basicsize : oldsize;
2283 if (!(type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
2284 (base->tp_flags & Py_TPFLAGS_HAVE_GC) &&
Guido van Rossum13d52f02001-08-10 21:24:08 +00002285 (type->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE/*GC slots exist*/) &&
2286 (!type->tp_traverse && !type->tp_clear)) {
Neil Schemenauerc806c882001-08-29 23:54:54 +00002287 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossum13d52f02001-08-10 21:24:08 +00002288 if (type->tp_traverse == NULL)
2289 type->tp_traverse = base->tp_traverse;
2290 if (type->tp_clear == NULL)
2291 type->tp_clear = base->tp_clear;
2292 }
2293 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
Guido van Rossumf884b742001-12-17 17:14:22 +00002294 /* The condition below could use some explanation.
2295 It appears that tp_new is not inherited for static types
2296 whose base class is 'object'; this seems to be a precaution
2297 so that old extension types don't suddenly become
2298 callable (object.__new__ wouldn't insure the invariants
2299 that the extension type's own factory function ensures).
2300 Heap types, of course, are under our control, so they do
2301 inherit tp_new; static extension types that specify some
2302 other built-in type as the default are considered
2303 new-style-aware so they also inherit object.__new__. */
Guido van Rossum13d52f02001-08-10 21:24:08 +00002304 if (base != &PyBaseObject_Type ||
2305 (type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
2306 if (type->tp_new == NULL)
2307 type->tp_new = base->tp_new;
2308 }
2309 }
Neil Schemenauerc806c882001-08-29 23:54:54 +00002310 type->tp_basicsize = newsize;
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00002311
2312 /* Copy other non-function slots */
2313
2314#undef COPYVAL
2315#define COPYVAL(SLOT) \
2316 if (type->SLOT == 0) type->SLOT = base->SLOT
2317
2318 COPYVAL(tp_itemsize);
2319 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_WEAKREFS) {
2320 COPYVAL(tp_weaklistoffset);
2321 }
2322 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
2323 COPYVAL(tp_dictoffset);
2324 }
Guido van Rossum13d52f02001-08-10 21:24:08 +00002325}
2326
2327static void
2328inherit_slots(PyTypeObject *type, PyTypeObject *base)
2329{
2330 PyTypeObject *basebase;
2331
2332#undef SLOTDEFINED
Tim Peters6d6c1a32001-08-02 04:15:00 +00002333#undef COPYSLOT
2334#undef COPYNUM
2335#undef COPYSEQ
2336#undef COPYMAP
Guido van Rossum5af588b2001-10-12 14:13:21 +00002337#undef COPYBUF
Guido van Rossum13d52f02001-08-10 21:24:08 +00002338
2339#define SLOTDEFINED(SLOT) \
2340 (base->SLOT != 0 && \
2341 (basebase == NULL || base->SLOT != basebase->SLOT))
2342
Tim Peters6d6c1a32001-08-02 04:15:00 +00002343#define COPYSLOT(SLOT) \
Guido van Rossum13d52f02001-08-10 21:24:08 +00002344 if (!type->SLOT && SLOTDEFINED(SLOT)) type->SLOT = base->SLOT
Tim Peters6d6c1a32001-08-02 04:15:00 +00002345
2346#define COPYNUM(SLOT) COPYSLOT(tp_as_number->SLOT)
2347#define COPYSEQ(SLOT) COPYSLOT(tp_as_sequence->SLOT)
2348#define COPYMAP(SLOT) COPYSLOT(tp_as_mapping->SLOT)
Tim Petersfc57ccb2001-10-12 02:38:24 +00002349#define COPYBUF(SLOT) COPYSLOT(tp_as_buffer->SLOT)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002350
Guido van Rossum13d52f02001-08-10 21:24:08 +00002351 /* This won't inherit indirect slots (from tp_as_number etc.)
2352 if type doesn't provide the space. */
2353
2354 if (type->tp_as_number != NULL && base->tp_as_number != NULL) {
2355 basebase = base->tp_base;
2356 if (basebase->tp_as_number == NULL)
2357 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002358 COPYNUM(nb_add);
2359 COPYNUM(nb_subtract);
2360 COPYNUM(nb_multiply);
2361 COPYNUM(nb_divide);
2362 COPYNUM(nb_remainder);
2363 COPYNUM(nb_divmod);
2364 COPYNUM(nb_power);
2365 COPYNUM(nb_negative);
2366 COPYNUM(nb_positive);
2367 COPYNUM(nb_absolute);
2368 COPYNUM(nb_nonzero);
2369 COPYNUM(nb_invert);
2370 COPYNUM(nb_lshift);
2371 COPYNUM(nb_rshift);
2372 COPYNUM(nb_and);
2373 COPYNUM(nb_xor);
2374 COPYNUM(nb_or);
2375 COPYNUM(nb_coerce);
2376 COPYNUM(nb_int);
2377 COPYNUM(nb_long);
2378 COPYNUM(nb_float);
2379 COPYNUM(nb_oct);
2380 COPYNUM(nb_hex);
2381 COPYNUM(nb_inplace_add);
2382 COPYNUM(nb_inplace_subtract);
2383 COPYNUM(nb_inplace_multiply);
2384 COPYNUM(nb_inplace_divide);
2385 COPYNUM(nb_inplace_remainder);
2386 COPYNUM(nb_inplace_power);
2387 COPYNUM(nb_inplace_lshift);
2388 COPYNUM(nb_inplace_rshift);
2389 COPYNUM(nb_inplace_and);
2390 COPYNUM(nb_inplace_xor);
2391 COPYNUM(nb_inplace_or);
Guido van Rossumdc91b992001-08-08 22:26:22 +00002392 if (base->tp_flags & Py_TPFLAGS_CHECKTYPES) {
2393 COPYNUM(nb_true_divide);
2394 COPYNUM(nb_floor_divide);
2395 COPYNUM(nb_inplace_true_divide);
2396 COPYNUM(nb_inplace_floor_divide);
2397 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002398 }
2399
Guido van Rossum13d52f02001-08-10 21:24:08 +00002400 if (type->tp_as_sequence != NULL && base->tp_as_sequence != NULL) {
2401 basebase = base->tp_base;
2402 if (basebase->tp_as_sequence == NULL)
2403 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002404 COPYSEQ(sq_length);
2405 COPYSEQ(sq_concat);
2406 COPYSEQ(sq_repeat);
2407 COPYSEQ(sq_item);
2408 COPYSEQ(sq_slice);
2409 COPYSEQ(sq_ass_item);
2410 COPYSEQ(sq_ass_slice);
2411 COPYSEQ(sq_contains);
2412 COPYSEQ(sq_inplace_concat);
2413 COPYSEQ(sq_inplace_repeat);
2414 }
2415
Guido van Rossum13d52f02001-08-10 21:24:08 +00002416 if (type->tp_as_mapping != NULL && base->tp_as_mapping != NULL) {
2417 basebase = base->tp_base;
2418 if (basebase->tp_as_mapping == NULL)
2419 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002420 COPYMAP(mp_length);
2421 COPYMAP(mp_subscript);
2422 COPYMAP(mp_ass_subscript);
2423 }
2424
Tim Petersfc57ccb2001-10-12 02:38:24 +00002425 if (type->tp_as_buffer != NULL && base->tp_as_buffer != NULL) {
2426 basebase = base->tp_base;
2427 if (basebase->tp_as_buffer == NULL)
2428 basebase = NULL;
2429 COPYBUF(bf_getreadbuffer);
2430 COPYBUF(bf_getwritebuffer);
2431 COPYBUF(bf_getsegcount);
2432 COPYBUF(bf_getcharbuffer);
2433 }
2434
Guido van Rossum13d52f02001-08-10 21:24:08 +00002435 basebase = base->tp_base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002436
Tim Peters6d6c1a32001-08-02 04:15:00 +00002437 COPYSLOT(tp_dealloc);
2438 COPYSLOT(tp_print);
2439 if (type->tp_getattr == NULL && type->tp_getattro == NULL) {
2440 type->tp_getattr = base->tp_getattr;
2441 type->tp_getattro = base->tp_getattro;
2442 }
2443 if (type->tp_setattr == NULL && type->tp_setattro == NULL) {
2444 type->tp_setattr = base->tp_setattr;
2445 type->tp_setattro = base->tp_setattro;
2446 }
2447 /* tp_compare see tp_richcompare */
2448 COPYSLOT(tp_repr);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002449 /* tp_hash see tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002450 COPYSLOT(tp_call);
2451 COPYSLOT(tp_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002452 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00002453 if (type->tp_compare == NULL &&
2454 type->tp_richcompare == NULL &&
2455 type->tp_hash == NULL)
2456 {
Tim Peters6d6c1a32001-08-02 04:15:00 +00002457 type->tp_compare = base->tp_compare;
2458 type->tp_richcompare = base->tp_richcompare;
Guido van Rossumb8f63662001-08-15 23:57:02 +00002459 type->tp_hash = base->tp_hash;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002460 }
2461 }
2462 else {
2463 COPYSLOT(tp_compare);
2464 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002465 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_ITER) {
2466 COPYSLOT(tp_iter);
2467 COPYSLOT(tp_iternext);
2468 }
2469 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
2470 COPYSLOT(tp_descr_get);
2471 COPYSLOT(tp_descr_set);
2472 COPYSLOT(tp_dictoffset);
2473 COPYSLOT(tp_init);
2474 COPYSLOT(tp_alloc);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002475 COPYSLOT(tp_free);
Guido van Rossumcc8fe042002-04-05 17:10:16 +00002476 COPYSLOT(tp_is_gc);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002477 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002478}
2479
Jeremy Hylton938ace62002-07-17 16:30:39 +00002480static int add_operators(PyTypeObject *);
2481static int add_subclass(PyTypeObject *base, PyTypeObject *type);
Guido van Rossum13d52f02001-08-10 21:24:08 +00002482
Tim Peters6d6c1a32001-08-02 04:15:00 +00002483int
Guido van Rossum528b7eb2001-08-07 17:24:28 +00002484PyType_Ready(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002485{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002486 PyObject *dict, *bases;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002487 PyTypeObject *base;
2488 int i, n;
2489
Guido van Rossumcab05802002-06-10 15:29:03 +00002490 if (type->tp_flags & Py_TPFLAGS_READY) {
2491 assert(type->tp_dict != NULL);
Guido van Rossumd614f972001-08-10 17:39:49 +00002492 return 0;
Guido van Rossumcab05802002-06-10 15:29:03 +00002493 }
Guido van Rossumd614f972001-08-10 17:39:49 +00002494 assert((type->tp_flags & Py_TPFLAGS_READYING) == 0);
Guido van Rossumd614f972001-08-10 17:39:49 +00002495
2496 type->tp_flags |= Py_TPFLAGS_READYING;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002497
2498 /* Initialize tp_base (defaults to BaseObject unless that's us) */
2499 base = type->tp_base;
2500 if (base == NULL && type != &PyBaseObject_Type)
2501 base = type->tp_base = &PyBaseObject_Type;
2502
Guido van Rossum323a9cf2002-08-14 17:26:30 +00002503 /* Initialize the base class */
2504 if (base && base->tp_dict == NULL) {
2505 if (PyType_Ready(base) < 0)
2506 goto error;
2507 }
2508
Guido van Rossum0986d822002-04-08 01:38:42 +00002509 /* Initialize ob_type if NULL. This means extensions that want to be
2510 compilable separately on Windows can call PyType_Ready() instead of
2511 initializing the ob_type field of their type objects. */
2512 if (type->ob_type == NULL)
2513 type->ob_type = base->ob_type;
2514
Tim Peters6d6c1a32001-08-02 04:15:00 +00002515 /* Initialize tp_bases */
2516 bases = type->tp_bases;
2517 if (bases == NULL) {
2518 if (base == NULL)
2519 bases = PyTuple_New(0);
2520 else
2521 bases = Py_BuildValue("(O)", base);
2522 if (bases == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00002523 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002524 type->tp_bases = bases;
2525 }
2526
Guido van Rossum687ae002001-10-15 22:03:32 +00002527 /* Initialize tp_dict */
2528 dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002529 if (dict == NULL) {
2530 dict = PyDict_New();
2531 if (dict == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00002532 goto error;
Guido van Rossum687ae002001-10-15 22:03:32 +00002533 type->tp_dict = dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002534 }
2535
Guido van Rossum687ae002001-10-15 22:03:32 +00002536 /* Add type-specific descriptors to tp_dict */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002537 if (add_operators(type) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00002538 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002539 if (type->tp_methods != NULL) {
2540 if (add_methods(type, type->tp_methods) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00002541 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002542 }
2543 if (type->tp_members != NULL) {
2544 if (add_members(type, type->tp_members) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00002545 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002546 }
2547 if (type->tp_getset != NULL) {
2548 if (add_getset(type, type->tp_getset) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00002549 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002550 }
2551
Tim Peters6d6c1a32001-08-02 04:15:00 +00002552 /* Calculate method resolution order */
2553 if (mro_internal(type) < 0) {
Guido van Rossumd614f972001-08-10 17:39:49 +00002554 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002555 }
2556
Guido van Rossum13d52f02001-08-10 21:24:08 +00002557 /* Inherit special flags from dominant base */
2558 if (type->tp_base != NULL)
2559 inherit_special(type, type->tp_base);
2560
Tim Peters6d6c1a32001-08-02 04:15:00 +00002561 /* Initialize tp_dict properly */
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002562 bases = type->tp_mro;
2563 assert(bases != NULL);
2564 assert(PyTuple_Check(bases));
2565 n = PyTuple_GET_SIZE(bases);
2566 for (i = 1; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00002567 PyObject *b = PyTuple_GET_ITEM(bases, i);
2568 if (PyType_Check(b))
2569 inherit_slots(type, (PyTypeObject *)b);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002570 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002571
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00002572 /* if the type dictionary doesn't contain a __doc__, set it from
2573 the tp_doc slot.
2574 */
2575 if (PyDict_GetItemString(type->tp_dict, "__doc__") == NULL) {
2576 if (type->tp_doc != NULL) {
2577 PyObject *doc = PyString_FromString(type->tp_doc);
2578 PyDict_SetItemString(type->tp_dict, "__doc__", doc);
2579 Py_DECREF(doc);
2580 } else {
Guido van Rossumd4641072002-04-03 02:13:37 +00002581 PyDict_SetItemString(type->tp_dict,
2582 "__doc__", Py_None);
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00002583 }
2584 }
2585
Guido van Rossum13d52f02001-08-10 21:24:08 +00002586 /* Some more special stuff */
2587 base = type->tp_base;
2588 if (base != NULL) {
2589 if (type->tp_as_number == NULL)
2590 type->tp_as_number = base->tp_as_number;
2591 if (type->tp_as_sequence == NULL)
2592 type->tp_as_sequence = base->tp_as_sequence;
2593 if (type->tp_as_mapping == NULL)
2594 type->tp_as_mapping = base->tp_as_mapping;
2595 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002596
Guido van Rossum1c450732001-10-08 15:18:27 +00002597 /* Link into each base class's list of subclasses */
2598 bases = type->tp_bases;
2599 n = PyTuple_GET_SIZE(bases);
2600 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00002601 PyObject *b = PyTuple_GET_ITEM(bases, i);
2602 if (PyType_Check(b) &&
2603 add_subclass((PyTypeObject *)b, type) < 0)
Guido van Rossum1c450732001-10-08 15:18:27 +00002604 goto error;
2605 }
2606
Guido van Rossum13d52f02001-08-10 21:24:08 +00002607 /* All done -- set the ready flag */
Guido van Rossumd614f972001-08-10 17:39:49 +00002608 assert(type->tp_dict != NULL);
2609 type->tp_flags =
2610 (type->tp_flags & ~Py_TPFLAGS_READYING) | Py_TPFLAGS_READY;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002611 return 0;
Guido van Rossumd614f972001-08-10 17:39:49 +00002612
2613 error:
2614 type->tp_flags &= ~Py_TPFLAGS_READYING;
2615 return -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002616}
2617
Guido van Rossum1c450732001-10-08 15:18:27 +00002618static int
2619add_subclass(PyTypeObject *base, PyTypeObject *type)
2620{
2621 int i;
2622 PyObject *list, *ref, *new;
2623
2624 list = base->tp_subclasses;
2625 if (list == NULL) {
2626 base->tp_subclasses = list = PyList_New(0);
2627 if (list == NULL)
2628 return -1;
2629 }
2630 assert(PyList_Check(list));
2631 new = PyWeakref_NewRef((PyObject *)type, NULL);
2632 i = PyList_GET_SIZE(list);
2633 while (--i >= 0) {
2634 ref = PyList_GET_ITEM(list, i);
2635 assert(PyWeakref_CheckRef(ref));
Guido van Rossum3930bc32002-10-18 13:51:49 +00002636 if (PyWeakref_GET_OBJECT(ref) == Py_None)
2637 return PyList_SetItem(list, i, new);
Guido van Rossum1c450732001-10-08 15:18:27 +00002638 }
2639 i = PyList_Append(list, new);
2640 Py_DECREF(new);
2641 return i;
2642}
2643
Tim Peters6d6c1a32001-08-02 04:15:00 +00002644
2645/* Generic wrappers for overloadable 'operators' such as __getitem__ */
2646
2647/* There's a wrapper *function* for each distinct function typedef used
2648 for type object slots (e.g. binaryfunc, ternaryfunc, etc.). There's a
2649 wrapper *table* for each distinct operation (e.g. __len__, __add__).
2650 Most tables have only one entry; the tables for binary operators have two
2651 entries, one regular and one with reversed arguments. */
2652
2653static PyObject *
2654wrap_inquiry(PyObject *self, PyObject *args, void *wrapped)
2655{
2656 inquiry func = (inquiry)wrapped;
2657 int res;
2658
2659 if (!PyArg_ParseTuple(args, ""))
2660 return NULL;
2661 res = (*func)(self);
2662 if (res == -1 && PyErr_Occurred())
2663 return NULL;
2664 return PyInt_FromLong((long)res);
2665}
2666
Tim Peters6d6c1a32001-08-02 04:15:00 +00002667static PyObject *
2668wrap_binaryfunc(PyObject *self, PyObject *args, void *wrapped)
2669{
2670 binaryfunc func = (binaryfunc)wrapped;
2671 PyObject *other;
2672
2673 if (!PyArg_ParseTuple(args, "O", &other))
2674 return NULL;
2675 return (*func)(self, other);
2676}
2677
2678static PyObject *
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002679wrap_binaryfunc_l(PyObject *self, PyObject *args, void *wrapped)
2680{
2681 binaryfunc func = (binaryfunc)wrapped;
2682 PyObject *other;
2683
2684 if (!PyArg_ParseTuple(args, "O", &other))
2685 return NULL;
2686 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002687 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002688 Py_INCREF(Py_NotImplemented);
2689 return Py_NotImplemented;
2690 }
2691 return (*func)(self, other);
2692}
2693
2694static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00002695wrap_binaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
2696{
2697 binaryfunc func = (binaryfunc)wrapped;
2698 PyObject *other;
2699
2700 if (!PyArg_ParseTuple(args, "O", &other))
2701 return NULL;
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002702 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002703 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002704 Py_INCREF(Py_NotImplemented);
2705 return Py_NotImplemented;
2706 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002707 return (*func)(other, self);
2708}
2709
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00002710static PyObject *
2711wrap_coercefunc(PyObject *self, PyObject *args, void *wrapped)
2712{
2713 coercion func = (coercion)wrapped;
2714 PyObject *other, *res;
2715 int ok;
2716
2717 if (!PyArg_ParseTuple(args, "O", &other))
2718 return NULL;
2719 ok = func(&self, &other);
2720 if (ok < 0)
2721 return NULL;
2722 if (ok > 0) {
2723 Py_INCREF(Py_NotImplemented);
2724 return Py_NotImplemented;
2725 }
2726 res = PyTuple_New(2);
2727 if (res == NULL) {
2728 Py_DECREF(self);
2729 Py_DECREF(other);
2730 return NULL;
2731 }
2732 PyTuple_SET_ITEM(res, 0, self);
2733 PyTuple_SET_ITEM(res, 1, other);
2734 return res;
2735}
2736
Tim Peters6d6c1a32001-08-02 04:15:00 +00002737static PyObject *
2738wrap_ternaryfunc(PyObject *self, PyObject *args, void *wrapped)
2739{
2740 ternaryfunc func = (ternaryfunc)wrapped;
2741 PyObject *other;
2742 PyObject *third = Py_None;
2743
2744 /* Note: This wrapper only works for __pow__() */
2745
2746 if (!PyArg_ParseTuple(args, "O|O", &other, &third))
2747 return NULL;
2748 return (*func)(self, other, third);
2749}
2750
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00002751static PyObject *
2752wrap_ternaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
2753{
2754 ternaryfunc func = (ternaryfunc)wrapped;
2755 PyObject *other;
2756 PyObject *third = Py_None;
2757
2758 /* Note: This wrapper only works for __pow__() */
2759
2760 if (!PyArg_ParseTuple(args, "O|O", &other, &third))
2761 return NULL;
2762 return (*func)(other, self, third);
2763}
2764
Tim Peters6d6c1a32001-08-02 04:15:00 +00002765static PyObject *
2766wrap_unaryfunc(PyObject *self, PyObject *args, void *wrapped)
2767{
2768 unaryfunc func = (unaryfunc)wrapped;
2769
2770 if (!PyArg_ParseTuple(args, ""))
2771 return NULL;
2772 return (*func)(self);
2773}
2774
Tim Peters6d6c1a32001-08-02 04:15:00 +00002775static PyObject *
2776wrap_intargfunc(PyObject *self, PyObject *args, void *wrapped)
2777{
2778 intargfunc func = (intargfunc)wrapped;
2779 int i;
2780
2781 if (!PyArg_ParseTuple(args, "i", &i))
2782 return NULL;
2783 return (*func)(self, i);
2784}
2785
Guido van Rossum5d815f32001-08-17 21:57:47 +00002786static int
2787getindex(PyObject *self, PyObject *arg)
2788{
2789 int i;
2790
2791 i = PyInt_AsLong(arg);
2792 if (i == -1 && PyErr_Occurred())
2793 return -1;
2794 if (i < 0) {
2795 PySequenceMethods *sq = self->ob_type->tp_as_sequence;
2796 if (sq && sq->sq_length) {
2797 int n = (*sq->sq_length)(self);
2798 if (n < 0)
2799 return -1;
2800 i += n;
2801 }
2802 }
2803 return i;
2804}
2805
2806static PyObject *
2807wrap_sq_item(PyObject *self, PyObject *args, void *wrapped)
2808{
2809 intargfunc func = (intargfunc)wrapped;
2810 PyObject *arg;
2811 int i;
2812
Guido van Rossumf4593e02001-10-03 12:09:30 +00002813 if (PyTuple_GET_SIZE(args) == 1) {
2814 arg = PyTuple_GET_ITEM(args, 0);
2815 i = getindex(self, arg);
2816 if (i == -1 && PyErr_Occurred())
2817 return NULL;
2818 return (*func)(self, i);
2819 }
2820 PyArg_ParseTuple(args, "O", &arg);
2821 assert(PyErr_Occurred());
2822 return NULL;
Guido van Rossum5d815f32001-08-17 21:57:47 +00002823}
2824
Tim Peters6d6c1a32001-08-02 04:15:00 +00002825static PyObject *
2826wrap_intintargfunc(PyObject *self, PyObject *args, void *wrapped)
2827{
2828 intintargfunc func = (intintargfunc)wrapped;
2829 int i, j;
2830
2831 if (!PyArg_ParseTuple(args, "ii", &i, &j))
2832 return NULL;
2833 return (*func)(self, i, j);
2834}
2835
Tim Peters6d6c1a32001-08-02 04:15:00 +00002836static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00002837wrap_sq_setitem(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002838{
2839 intobjargproc func = (intobjargproc)wrapped;
2840 int i, res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00002841 PyObject *arg, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002842
Guido van Rossum5d815f32001-08-17 21:57:47 +00002843 if (!PyArg_ParseTuple(args, "OO", &arg, &value))
2844 return NULL;
2845 i = getindex(self, arg);
2846 if (i == -1 && PyErr_Occurred())
Tim Peters6d6c1a32001-08-02 04:15:00 +00002847 return NULL;
2848 res = (*func)(self, i, value);
2849 if (res == -1 && PyErr_Occurred())
2850 return NULL;
2851 Py_INCREF(Py_None);
2852 return Py_None;
2853}
2854
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002855static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00002856wrap_sq_delitem(PyObject *self, PyObject *args, void *wrapped)
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002857{
2858 intobjargproc func = (intobjargproc)wrapped;
2859 int i, res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00002860 PyObject *arg;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002861
Guido van Rossum5d815f32001-08-17 21:57:47 +00002862 if (!PyArg_ParseTuple(args, "O", &arg))
2863 return NULL;
2864 i = getindex(self, arg);
2865 if (i == -1 && PyErr_Occurred())
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002866 return NULL;
2867 res = (*func)(self, i, NULL);
2868 if (res == -1 && PyErr_Occurred())
2869 return NULL;
2870 Py_INCREF(Py_None);
2871 return Py_None;
2872}
2873
Tim Peters6d6c1a32001-08-02 04:15:00 +00002874static PyObject *
2875wrap_intintobjargproc(PyObject *self, PyObject *args, void *wrapped)
2876{
2877 intintobjargproc func = (intintobjargproc)wrapped;
2878 int i, j, res;
2879 PyObject *value;
2880
2881 if (!PyArg_ParseTuple(args, "iiO", &i, &j, &value))
2882 return NULL;
2883 res = (*func)(self, i, j, value);
2884 if (res == -1 && PyErr_Occurred())
2885 return NULL;
2886 Py_INCREF(Py_None);
2887 return Py_None;
2888}
2889
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002890static PyObject *
2891wrap_delslice(PyObject *self, PyObject *args, void *wrapped)
2892{
2893 intintobjargproc func = (intintobjargproc)wrapped;
2894 int i, j, res;
2895
2896 if (!PyArg_ParseTuple(args, "ii", &i, &j))
2897 return NULL;
2898 res = (*func)(self, i, j, NULL);
2899 if (res == -1 && PyErr_Occurred())
2900 return NULL;
2901 Py_INCREF(Py_None);
2902 return Py_None;
2903}
2904
Tim Peters6d6c1a32001-08-02 04:15:00 +00002905/* XXX objobjproc is a misnomer; should be objargpred */
2906static PyObject *
2907wrap_objobjproc(PyObject *self, PyObject *args, void *wrapped)
2908{
2909 objobjproc func = (objobjproc)wrapped;
2910 int res;
2911 PyObject *value;
2912
2913 if (!PyArg_ParseTuple(args, "O", &value))
2914 return NULL;
2915 res = (*func)(self, value);
2916 if (res == -1 && PyErr_Occurred())
2917 return NULL;
2918 return PyInt_FromLong((long)res);
2919}
2920
Tim Peters6d6c1a32001-08-02 04:15:00 +00002921static PyObject *
2922wrap_objobjargproc(PyObject *self, PyObject *args, void *wrapped)
2923{
2924 objobjargproc func = (objobjargproc)wrapped;
2925 int res;
2926 PyObject *key, *value;
2927
2928 if (!PyArg_ParseTuple(args, "OO", &key, &value))
2929 return NULL;
2930 res = (*func)(self, key, value);
2931 if (res == -1 && PyErr_Occurred())
2932 return NULL;
2933 Py_INCREF(Py_None);
2934 return Py_None;
2935}
2936
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002937static PyObject *
2938wrap_delitem(PyObject *self, PyObject *args, void *wrapped)
2939{
2940 objobjargproc func = (objobjargproc)wrapped;
2941 int res;
2942 PyObject *key;
2943
2944 if (!PyArg_ParseTuple(args, "O", &key))
2945 return NULL;
2946 res = (*func)(self, key, NULL);
2947 if (res == -1 && PyErr_Occurred())
2948 return NULL;
2949 Py_INCREF(Py_None);
2950 return Py_None;
2951}
2952
Tim Peters6d6c1a32001-08-02 04:15:00 +00002953static PyObject *
2954wrap_cmpfunc(PyObject *self, PyObject *args, void *wrapped)
2955{
2956 cmpfunc func = (cmpfunc)wrapped;
2957 int res;
2958 PyObject *other;
2959
2960 if (!PyArg_ParseTuple(args, "O", &other))
2961 return NULL;
Guido van Rossum3d45d8f2001-09-24 18:47:40 +00002962 if (other->ob_type->tp_compare != func &&
2963 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossumceccae52001-09-18 20:03:57 +00002964 PyErr_Format(
2965 PyExc_TypeError,
2966 "%s.__cmp__(x,y) requires y to be a '%s', not a '%s'",
2967 self->ob_type->tp_name,
2968 self->ob_type->tp_name,
2969 other->ob_type->tp_name);
2970 return NULL;
2971 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002972 res = (*func)(self, other);
2973 if (PyErr_Occurred())
2974 return NULL;
2975 return PyInt_FromLong((long)res);
2976}
2977
Tim Peters6d6c1a32001-08-02 04:15:00 +00002978static PyObject *
2979wrap_setattr(PyObject *self, PyObject *args, void *wrapped)
2980{
2981 setattrofunc func = (setattrofunc)wrapped;
2982 int res;
2983 PyObject *name, *value;
2984
2985 if (!PyArg_ParseTuple(args, "OO", &name, &value))
2986 return NULL;
2987 res = (*func)(self, name, value);
2988 if (res < 0)
2989 return NULL;
2990 Py_INCREF(Py_None);
2991 return Py_None;
2992}
2993
2994static PyObject *
2995wrap_delattr(PyObject *self, PyObject *args, void *wrapped)
2996{
2997 setattrofunc func = (setattrofunc)wrapped;
2998 int res;
2999 PyObject *name;
3000
3001 if (!PyArg_ParseTuple(args, "O", &name))
3002 return NULL;
3003 res = (*func)(self, name, NULL);
3004 if (res < 0)
3005 return NULL;
3006 Py_INCREF(Py_None);
3007 return Py_None;
3008}
3009
Tim Peters6d6c1a32001-08-02 04:15:00 +00003010static PyObject *
3011wrap_hashfunc(PyObject *self, PyObject *args, void *wrapped)
3012{
3013 hashfunc func = (hashfunc)wrapped;
3014 long res;
3015
3016 if (!PyArg_ParseTuple(args, ""))
3017 return NULL;
3018 res = (*func)(self);
3019 if (res == -1 && PyErr_Occurred())
3020 return NULL;
3021 return PyInt_FromLong(res);
3022}
3023
Tim Peters6d6c1a32001-08-02 04:15:00 +00003024static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00003025wrap_call(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003026{
3027 ternaryfunc func = (ternaryfunc)wrapped;
3028
Guido van Rossumc8e56452001-10-22 00:43:43 +00003029 return (*func)(self, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003030}
3031
Tim Peters6d6c1a32001-08-02 04:15:00 +00003032static PyObject *
3033wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op)
3034{
3035 richcmpfunc func = (richcmpfunc)wrapped;
3036 PyObject *other;
3037
3038 if (!PyArg_ParseTuple(args, "O", &other))
3039 return NULL;
3040 return (*func)(self, other, op);
3041}
3042
3043#undef RICHCMP_WRAPPER
3044#define RICHCMP_WRAPPER(NAME, OP) \
3045static PyObject * \
3046richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \
3047{ \
3048 return wrap_richcmpfunc(self, args, wrapped, OP); \
3049}
3050
Jack Jansen8e938b42001-08-08 15:29:49 +00003051RICHCMP_WRAPPER(lt, Py_LT)
3052RICHCMP_WRAPPER(le, Py_LE)
3053RICHCMP_WRAPPER(eq, Py_EQ)
3054RICHCMP_WRAPPER(ne, Py_NE)
3055RICHCMP_WRAPPER(gt, Py_GT)
3056RICHCMP_WRAPPER(ge, Py_GE)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003057
Tim Peters6d6c1a32001-08-02 04:15:00 +00003058static PyObject *
3059wrap_next(PyObject *self, PyObject *args, void *wrapped)
3060{
3061 unaryfunc func = (unaryfunc)wrapped;
3062 PyObject *res;
3063
3064 if (!PyArg_ParseTuple(args, ""))
3065 return NULL;
3066 res = (*func)(self);
3067 if (res == NULL && !PyErr_Occurred())
3068 PyErr_SetNone(PyExc_StopIteration);
3069 return res;
3070}
3071
Tim Peters6d6c1a32001-08-02 04:15:00 +00003072static PyObject *
3073wrap_descr_get(PyObject *self, PyObject *args, void *wrapped)
3074{
3075 descrgetfunc func = (descrgetfunc)wrapped;
3076 PyObject *obj;
3077 PyObject *type = NULL;
3078
3079 if (!PyArg_ParseTuple(args, "O|O", &obj, &type))
3080 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003081 return (*func)(self, obj, type);
3082}
3083
Tim Peters6d6c1a32001-08-02 04:15:00 +00003084static PyObject *
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003085wrap_descr_set(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003086{
3087 descrsetfunc func = (descrsetfunc)wrapped;
3088 PyObject *obj, *value;
3089 int ret;
3090
3091 if (!PyArg_ParseTuple(args, "OO", &obj, &value))
3092 return NULL;
3093 ret = (*func)(self, obj, value);
3094 if (ret < 0)
3095 return NULL;
3096 Py_INCREF(Py_None);
3097 return Py_None;
3098}
Guido van Rossum22b13872002-08-06 21:41:44 +00003099
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00003100static PyObject *
3101wrap_descr_delete(PyObject *self, PyObject *args, void *wrapped)
3102{
3103 descrsetfunc func = (descrsetfunc)wrapped;
3104 PyObject *obj;
3105 int ret;
3106
3107 if (!PyArg_ParseTuple(args, "O", &obj))
3108 return NULL;
3109 ret = (*func)(self, obj, NULL);
3110 if (ret < 0)
3111 return NULL;
3112 Py_INCREF(Py_None);
3113 return Py_None;
3114}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003115
Tim Peters6d6c1a32001-08-02 04:15:00 +00003116static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00003117wrap_init(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003118{
3119 initproc func = (initproc)wrapped;
3120
Guido van Rossumc8e56452001-10-22 00:43:43 +00003121 if (func(self, args, kwds) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003122 return NULL;
3123 Py_INCREF(Py_None);
3124 return Py_None;
3125}
3126
Tim Peters6d6c1a32001-08-02 04:15:00 +00003127static PyObject *
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003128tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003129{
Barry Warsaw60f01882001-08-22 19:24:42 +00003130 PyTypeObject *type, *subtype, *staticbase;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003131 PyObject *arg0, *res;
3132
3133 if (self == NULL || !PyType_Check(self))
3134 Py_FatalError("__new__() called with non-type 'self'");
3135 type = (PyTypeObject *)self;
3136 if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) {
Barry Warsaw60f01882001-08-22 19:24:42 +00003137 PyErr_Format(PyExc_TypeError,
3138 "%s.__new__(): not enough arguments",
3139 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003140 return NULL;
3141 }
3142 arg0 = PyTuple_GET_ITEM(args, 0);
3143 if (!PyType_Check(arg0)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00003144 PyErr_Format(PyExc_TypeError,
3145 "%s.__new__(X): X is not a type object (%s)",
3146 type->tp_name,
3147 arg0->ob_type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003148 return NULL;
3149 }
3150 subtype = (PyTypeObject *)arg0;
3151 if (!PyType_IsSubtype(subtype, type)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00003152 PyErr_Format(PyExc_TypeError,
3153 "%s.__new__(%s): %s is not a subtype of %s",
3154 type->tp_name,
3155 subtype->tp_name,
3156 subtype->tp_name,
3157 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003158 return NULL;
3159 }
Barry Warsaw60f01882001-08-22 19:24:42 +00003160
3161 /* Check that the use doesn't do something silly and unsafe like
Tim Petersa427a2b2001-10-29 22:25:45 +00003162 object.__new__(dict). To do this, we check that the
Barry Warsaw60f01882001-08-22 19:24:42 +00003163 most derived base that's not a heap type is this type. */
3164 staticbase = subtype;
3165 while (staticbase && (staticbase->tp_flags & Py_TPFLAGS_HEAPTYPE))
3166 staticbase = staticbase->tp_base;
Guido van Rossuma8c60f42001-09-14 19:43:36 +00003167 if (staticbase->tp_new != type->tp_new) {
Barry Warsaw60f01882001-08-22 19:24:42 +00003168 PyErr_Format(PyExc_TypeError,
3169 "%s.__new__(%s) is not safe, use %s.__new__()",
3170 type->tp_name,
3171 subtype->tp_name,
3172 staticbase == NULL ? "?" : staticbase->tp_name);
3173 return NULL;
3174 }
3175
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003176 args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
3177 if (args == NULL)
3178 return NULL;
3179 res = type->tp_new(subtype, args, kwds);
3180 Py_DECREF(args);
3181 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003182}
3183
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003184static struct PyMethodDef tp_new_methoddef[] = {
3185 {"__new__", (PyCFunction)tp_new_wrapper, METH_KEYWORDS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00003186 PyDoc_STR("T.__new__(S, ...) -> "
3187 "a new object with type S, a subtype of T")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00003188 {0}
3189};
3190
3191static int
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003192add_tp_new_wrapper(PyTypeObject *type)
3193{
Guido van Rossumf040ede2001-08-07 16:40:56 +00003194 PyObject *func;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003195
Guido van Rossum687ae002001-10-15 22:03:32 +00003196 if (PyDict_GetItemString(type->tp_dict, "__new__") != NULL)
Guido van Rossumf040ede2001-08-07 16:40:56 +00003197 return 0;
3198 func = PyCFunction_New(tp_new_methoddef, (PyObject *)type);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003199 if (func == NULL)
3200 return -1;
Guido van Rossum687ae002001-10-15 22:03:32 +00003201 return PyDict_SetItemString(type->tp_dict, "__new__", func);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003202}
3203
Guido van Rossumf040ede2001-08-07 16:40:56 +00003204/* Slot wrappers that call the corresponding __foo__ slot. See comments
3205 below at override_slots() for more explanation. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003206
Guido van Rossumdc91b992001-08-08 22:26:22 +00003207#define SLOT0(FUNCNAME, OPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003208static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003209FUNCNAME(PyObject *self) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003210{ \
Guido van Rossum5592e4d2001-08-28 18:28:21 +00003211 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00003212 return call_method(self, OPSTR, &cache_str, "()"); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003213}
3214
Guido van Rossumdc91b992001-08-08 22:26:22 +00003215#define SLOT1(FUNCNAME, OPSTR, ARG1TYPE, ARGCODES) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003216static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003217FUNCNAME(PyObject *self, ARG1TYPE arg1) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003218{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00003219 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00003220 return call_method(self, OPSTR, &cache_str, "(" ARGCODES ")", arg1); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003221}
3222
Guido van Rossumdc91b992001-08-08 22:26:22 +00003223
3224#define SLOT1BINFULL(FUNCNAME, TESTFUNC, SLOTNAME, OPSTR, ROPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003225static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003226FUNCNAME(PyObject *self, PyObject *other) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003227{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00003228 static PyObject *cache_str, *rcache_str; \
Guido van Rossum55f20992001-10-01 17:18:22 +00003229 int do_other = self->ob_type != other->ob_type && \
3230 other->ob_type->tp_as_number != NULL && \
3231 other->ob_type->tp_as_number->SLOTNAME == TESTFUNC; \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003232 if (self->ob_type->tp_as_number != NULL && \
3233 self->ob_type->tp_as_number->SLOTNAME == TESTFUNC) { \
3234 PyObject *r; \
Guido van Rossum55f20992001-10-01 17:18:22 +00003235 if (do_other && \
3236 PyType_IsSubtype(other->ob_type, self->ob_type)) { \
3237 r = call_maybe( \
3238 other, ROPSTR, &rcache_str, "(O)", self); \
3239 if (r != Py_NotImplemented) \
3240 return r; \
3241 Py_DECREF(r); \
3242 do_other = 0; \
3243 } \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00003244 r = call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00003245 self, OPSTR, &cache_str, "(O)", other); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003246 if (r != Py_NotImplemented || \
3247 other->ob_type == self->ob_type) \
3248 return r; \
3249 Py_DECREF(r); \
3250 } \
Guido van Rossum55f20992001-10-01 17:18:22 +00003251 if (do_other) { \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00003252 return call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00003253 other, ROPSTR, &rcache_str, "(O)", self); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003254 } \
3255 Py_INCREF(Py_NotImplemented); \
3256 return Py_NotImplemented; \
3257}
3258
3259#define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) \
3260 SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR)
3261
3262#define SLOT2(FUNCNAME, OPSTR, ARG1TYPE, ARG2TYPE, ARGCODES) \
3263static PyObject * \
3264FUNCNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \
3265{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00003266 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00003267 return call_method(self, OPSTR, &cache_str, \
3268 "(" ARGCODES ")", arg1, arg2); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003269}
3270
3271static int
3272slot_sq_length(PyObject *self)
3273{
Guido van Rossum2730b132001-08-28 18:22:14 +00003274 static PyObject *len_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00003275 PyObject *res = call_method(self, "__len__", &len_str, "()");
Guido van Rossum26111622001-10-01 16:42:49 +00003276 int len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003277
3278 if (res == NULL)
3279 return -1;
Guido van Rossum26111622001-10-01 16:42:49 +00003280 len = (int)PyInt_AsLong(res);
3281 Py_DECREF(res);
Jeremy Hylton73a088e2002-07-25 16:43:29 +00003282 if (len == -1 && PyErr_Occurred())
3283 return -1;
Jeremy Hyltonf20fcf92002-07-25 16:06:15 +00003284 if (len < 0) {
Guido van Rossum22b13872002-08-06 21:41:44 +00003285 PyErr_SetString(PyExc_ValueError,
Jeremy Hyltonf20fcf92002-07-25 16:06:15 +00003286 "__len__() should return >= 0");
3287 return -1;
3288 }
Guido van Rossum26111622001-10-01 16:42:49 +00003289 return len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003290}
3291
Guido van Rossumdc91b992001-08-08 22:26:22 +00003292SLOT1(slot_sq_concat, "__add__", PyObject *, "O")
3293SLOT1(slot_sq_repeat, "__mul__", int, "i")
Guido van Rossumf4593e02001-10-03 12:09:30 +00003294
3295/* Super-optimized version of slot_sq_item.
3296 Other slots could do the same... */
3297static PyObject *
3298slot_sq_item(PyObject *self, int i)
3299{
3300 static PyObject *getitem_str;
3301 PyObject *func, *args = NULL, *ival = NULL, *retval = NULL;
3302 descrgetfunc f;
3303
3304 if (getitem_str == NULL) {
3305 getitem_str = PyString_InternFromString("__getitem__");
3306 if (getitem_str == NULL)
3307 return NULL;
3308 }
3309 func = _PyType_Lookup(self->ob_type, getitem_str);
3310 if (func != NULL) {
Guido van Rossumf4593e02001-10-03 12:09:30 +00003311 if ((f = func->ob_type->tp_descr_get) == NULL)
3312 Py_INCREF(func);
Neal Norwitz673cd822002-10-18 16:33:13 +00003313 else {
Guido van Rossumf4593e02001-10-03 12:09:30 +00003314 func = f(func, self, (PyObject *)(self->ob_type));
Neal Norwitz673cd822002-10-18 16:33:13 +00003315 if (func == NULL) {
3316 return NULL;
3317 }
3318 }
Guido van Rossumf4593e02001-10-03 12:09:30 +00003319 ival = PyInt_FromLong(i);
3320 if (ival != NULL) {
3321 args = PyTuple_New(1);
3322 if (args != NULL) {
3323 PyTuple_SET_ITEM(args, 0, ival);
3324 retval = PyObject_Call(func, args, NULL);
3325 Py_XDECREF(args);
3326 Py_XDECREF(func);
3327 return retval;
3328 }
3329 }
3330 }
3331 else {
3332 PyErr_SetObject(PyExc_AttributeError, getitem_str);
3333 }
3334 Py_XDECREF(args);
3335 Py_XDECREF(ival);
3336 Py_XDECREF(func);
3337 return NULL;
3338}
3339
Guido van Rossumdc91b992001-08-08 22:26:22 +00003340SLOT2(slot_sq_slice, "__getslice__", int, int, "ii")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003341
3342static int
3343slot_sq_ass_item(PyObject *self, int index, PyObject *value)
3344{
3345 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003346 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003347
3348 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003349 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003350 "(i)", index);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003351 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003352 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003353 "(iO)", index, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003354 if (res == NULL)
3355 return -1;
3356 Py_DECREF(res);
3357 return 0;
3358}
3359
3360static int
3361slot_sq_ass_slice(PyObject *self, int i, int j, PyObject *value)
3362{
3363 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003364 static PyObject *delslice_str, *setslice_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003365
3366 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003367 res = call_method(self, "__delslice__", &delslice_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003368 "(ii)", i, j);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003369 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003370 res = call_method(self, "__setslice__", &setslice_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003371 "(iiO)", i, j, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003372 if (res == NULL)
3373 return -1;
3374 Py_DECREF(res);
3375 return 0;
3376}
3377
3378static int
3379slot_sq_contains(PyObject *self, PyObject *value)
3380{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003381 PyObject *func, *res, *args;
Guido van Rossum60718732001-08-28 17:47:51 +00003382 static PyObject *contains_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003383
Guido van Rossum55f20992001-10-01 17:18:22 +00003384 func = lookup_maybe(self, "__contains__", &contains_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003385
3386 if (func != NULL) {
3387 args = Py_BuildValue("(O)", value);
3388 if (args == NULL)
3389 res = NULL;
3390 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00003391 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003392 Py_DECREF(args);
3393 }
3394 Py_DECREF(func);
3395 if (res == NULL)
3396 return -1;
3397 return PyObject_IsTrue(res);
3398 }
Guido van Rossum55f20992001-10-01 17:18:22 +00003399 else if (PyErr_Occurred())
3400 return -1;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003401 else {
Tim Peters16a77ad2001-09-08 04:00:12 +00003402 return _PySequence_IterSearch(self, value,
3403 PY_ITERSEARCH_CONTAINS);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003404 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003405}
3406
Guido van Rossumdc91b992001-08-08 22:26:22 +00003407SLOT1(slot_sq_inplace_concat, "__iadd__", PyObject *, "O")
3408SLOT1(slot_sq_inplace_repeat, "__imul__", int, "i")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003409
3410#define slot_mp_length slot_sq_length
3411
Guido van Rossumdc91b992001-08-08 22:26:22 +00003412SLOT1(slot_mp_subscript, "__getitem__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003413
3414static int
3415slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value)
3416{
3417 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003418 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003419
3420 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003421 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003422 "(O)", key);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003423 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003424 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003425 "(OO)", key, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003426 if (res == NULL)
3427 return -1;
3428 Py_DECREF(res);
3429 return 0;
3430}
3431
Guido van Rossumdc91b992001-08-08 22:26:22 +00003432SLOT1BIN(slot_nb_add, nb_add, "__add__", "__radd__")
3433SLOT1BIN(slot_nb_subtract, nb_subtract, "__sub__", "__rsub__")
3434SLOT1BIN(slot_nb_multiply, nb_multiply, "__mul__", "__rmul__")
3435SLOT1BIN(slot_nb_divide, nb_divide, "__div__", "__rdiv__")
3436SLOT1BIN(slot_nb_remainder, nb_remainder, "__mod__", "__rmod__")
3437SLOT1BIN(slot_nb_divmod, nb_divmod, "__divmod__", "__rdivmod__")
3438
Jeremy Hylton938ace62002-07-17 16:30:39 +00003439static PyObject *slot_nb_power(PyObject *, PyObject *, PyObject *);
Guido van Rossumdc91b992001-08-08 22:26:22 +00003440
3441SLOT1BINFULL(slot_nb_power_binary, slot_nb_power,
3442 nb_power, "__pow__", "__rpow__")
3443
3444static PyObject *
3445slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus)
3446{
Guido van Rossum2730b132001-08-28 18:22:14 +00003447 static PyObject *pow_str;
3448
Guido van Rossumdc91b992001-08-08 22:26:22 +00003449 if (modulus == Py_None)
3450 return slot_nb_power_binary(self, other);
Guido van Rossum23094982002-06-10 14:30:43 +00003451 /* Three-arg power doesn't use __rpow__. But ternary_op
3452 can call this when the second argument's type uses
3453 slot_nb_power, so check before calling self.__pow__. */
3454 if (self->ob_type->tp_as_number != NULL &&
3455 self->ob_type->tp_as_number->nb_power == slot_nb_power) {
3456 return call_method(self, "__pow__", &pow_str,
3457 "(OO)", other, modulus);
3458 }
3459 Py_INCREF(Py_NotImplemented);
3460 return Py_NotImplemented;
Guido van Rossumdc91b992001-08-08 22:26:22 +00003461}
3462
3463SLOT0(slot_nb_negative, "__neg__")
3464SLOT0(slot_nb_positive, "__pos__")
3465SLOT0(slot_nb_absolute, "__abs__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003466
3467static int
3468slot_nb_nonzero(PyObject *self)
3469{
Guido van Rossum84b2bed2002-08-16 17:01:09 +00003470 PyObject *func, *res, *args;
Guido van Rossum60718732001-08-28 17:47:51 +00003471 static PyObject *nonzero_str, *len_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003472
Guido van Rossum55f20992001-10-01 17:18:22 +00003473 func = lookup_maybe(self, "__nonzero__", &nonzero_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003474 if (func == NULL) {
Guido van Rossum55f20992001-10-01 17:18:22 +00003475 if (PyErr_Occurred())
Guido van Rossumb8f63662001-08-15 23:57:02 +00003476 return -1;
Guido van Rossum55f20992001-10-01 17:18:22 +00003477 func = lookup_maybe(self, "__len__", &len_str);
3478 if (func == NULL) {
3479 if (PyErr_Occurred())
3480 return -1;
3481 else
3482 return 1;
3483 }
Guido van Rossumb8f63662001-08-15 23:57:02 +00003484 }
Guido van Rossum84b2bed2002-08-16 17:01:09 +00003485 args = res = PyTuple_New(0);
3486 if (args != NULL) {
3487 res = PyObject_Call(func, args, NULL);
3488 Py_DECREF(args);
3489 }
Guido van Rossum55f20992001-10-01 17:18:22 +00003490 Py_DECREF(func);
3491 if (res == NULL)
3492 return -1;
3493 return PyObject_IsTrue(res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003494}
3495
Guido van Rossumdc91b992001-08-08 22:26:22 +00003496SLOT0(slot_nb_invert, "__invert__")
3497SLOT1BIN(slot_nb_lshift, nb_lshift, "__lshift__", "__rlshift__")
3498SLOT1BIN(slot_nb_rshift, nb_rshift, "__rshift__", "__rrshift__")
3499SLOT1BIN(slot_nb_and, nb_and, "__and__", "__rand__")
3500SLOT1BIN(slot_nb_xor, nb_xor, "__xor__", "__rxor__")
3501SLOT1BIN(slot_nb_or, nb_or, "__or__", "__ror__")
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003502
3503static int
3504slot_nb_coerce(PyObject **a, PyObject **b)
3505{
3506 static PyObject *coerce_str;
3507 PyObject *self = *a, *other = *b;
3508
3509 if (self->ob_type->tp_as_number != NULL &&
3510 self->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
3511 PyObject *r;
3512 r = call_maybe(
3513 self, "__coerce__", &coerce_str, "(O)", other);
3514 if (r == NULL)
3515 return -1;
3516 if (r == Py_NotImplemented) {
3517 Py_DECREF(r);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003518 }
Guido van Rossum55f20992001-10-01 17:18:22 +00003519 else {
3520 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
3521 PyErr_SetString(PyExc_TypeError,
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003522 "__coerce__ didn't return a 2-tuple");
Guido van Rossum55f20992001-10-01 17:18:22 +00003523 Py_DECREF(r);
3524 return -1;
3525 }
3526 *a = PyTuple_GET_ITEM(r, 0);
3527 Py_INCREF(*a);
3528 *b = PyTuple_GET_ITEM(r, 1);
3529 Py_INCREF(*b);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003530 Py_DECREF(r);
Guido van Rossum55f20992001-10-01 17:18:22 +00003531 return 0;
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003532 }
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003533 }
3534 if (other->ob_type->tp_as_number != NULL &&
3535 other->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
3536 PyObject *r;
3537 r = call_maybe(
3538 other, "__coerce__", &coerce_str, "(O)", self);
3539 if (r == NULL)
3540 return -1;
3541 if (r == Py_NotImplemented) {
3542 Py_DECREF(r);
3543 return 1;
3544 }
3545 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
3546 PyErr_SetString(PyExc_TypeError,
3547 "__coerce__ didn't return a 2-tuple");
3548 Py_DECREF(r);
3549 return -1;
3550 }
3551 *a = PyTuple_GET_ITEM(r, 1);
3552 Py_INCREF(*a);
3553 *b = PyTuple_GET_ITEM(r, 0);
3554 Py_INCREF(*b);
3555 Py_DECREF(r);
3556 return 0;
3557 }
3558 return 1;
3559}
3560
Guido van Rossumdc91b992001-08-08 22:26:22 +00003561SLOT0(slot_nb_int, "__int__")
3562SLOT0(slot_nb_long, "__long__")
3563SLOT0(slot_nb_float, "__float__")
3564SLOT0(slot_nb_oct, "__oct__")
3565SLOT0(slot_nb_hex, "__hex__")
3566SLOT1(slot_nb_inplace_add, "__iadd__", PyObject *, "O")
3567SLOT1(slot_nb_inplace_subtract, "__isub__", PyObject *, "O")
3568SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *, "O")
3569SLOT1(slot_nb_inplace_divide, "__idiv__", PyObject *, "O")
3570SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *, "O")
Guido van Rossum6e5680f2002-10-15 01:01:53 +00003571SLOT1(slot_nb_inplace_power, "__ipow__", PyObject *, "O")
Guido van Rossumdc91b992001-08-08 22:26:22 +00003572SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *, "O")
3573SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *, "O")
3574SLOT1(slot_nb_inplace_and, "__iand__", PyObject *, "O")
3575SLOT1(slot_nb_inplace_xor, "__ixor__", PyObject *, "O")
3576SLOT1(slot_nb_inplace_or, "__ior__", PyObject *, "O")
3577SLOT1BIN(slot_nb_floor_divide, nb_floor_divide,
3578 "__floordiv__", "__rfloordiv__")
3579SLOT1BIN(slot_nb_true_divide, nb_true_divide, "__truediv__", "__rtruediv__")
3580SLOT1(slot_nb_inplace_floor_divide, "__ifloordiv__", PyObject *, "O")
3581SLOT1(slot_nb_inplace_true_divide, "__itruediv__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003582
3583static int
Guido van Rossumb8f63662001-08-15 23:57:02 +00003584half_compare(PyObject *self, PyObject *other)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003585{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003586 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003587 static PyObject *cmp_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003588 int c;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003589
Guido van Rossum60718732001-08-28 17:47:51 +00003590 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003591 if (func == NULL) {
3592 PyErr_Clear();
3593 }
3594 else {
3595 args = Py_BuildValue("(O)", other);
3596 if (args == NULL)
3597 res = NULL;
3598 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00003599 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003600 Py_DECREF(args);
3601 }
Raymond Hettingerab5dae32002-06-24 13:08:16 +00003602 Py_DECREF(func);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003603 if (res != Py_NotImplemented) {
3604 if (res == NULL)
3605 return -2;
3606 c = PyInt_AsLong(res);
3607 Py_DECREF(res);
3608 if (c == -1 && PyErr_Occurred())
3609 return -2;
3610 return (c < 0) ? -1 : (c > 0) ? 1 : 0;
3611 }
3612 Py_DECREF(res);
3613 }
3614 return 2;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003615}
3616
Guido van Rossumab3b0342001-09-18 20:38:53 +00003617/* This slot is published for the benefit of try_3way_compare in object.c */
3618int
3619_PyObject_SlotCompare(PyObject *self, PyObject *other)
Guido van Rossumb8f63662001-08-15 23:57:02 +00003620{
3621 int c;
3622
Guido van Rossumab3b0342001-09-18 20:38:53 +00003623 if (self->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00003624 c = half_compare(self, other);
3625 if (c <= 1)
3626 return c;
3627 }
Guido van Rossumab3b0342001-09-18 20:38:53 +00003628 if (other->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00003629 c = half_compare(other, self);
3630 if (c < -1)
3631 return -2;
3632 if (c <= 1)
3633 return -c;
3634 }
3635 return (void *)self < (void *)other ? -1 :
3636 (void *)self > (void *)other ? 1 : 0;
3637}
3638
3639static PyObject *
3640slot_tp_repr(PyObject *self)
3641{
3642 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003643 static PyObject *repr_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003644
Guido van Rossum60718732001-08-28 17:47:51 +00003645 func = lookup_method(self, "__repr__", &repr_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003646 if (func != NULL) {
3647 res = PyEval_CallObject(func, NULL);
3648 Py_DECREF(func);
3649 return res;
3650 }
Barry Warsaw7ce36942001-08-24 18:34:26 +00003651 PyErr_Clear();
3652 return PyString_FromFormat("<%s object at %p>",
3653 self->ob_type->tp_name, self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003654}
3655
3656static PyObject *
3657slot_tp_str(PyObject *self)
3658{
3659 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003660 static PyObject *str_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003661
Guido van Rossum60718732001-08-28 17:47:51 +00003662 func = lookup_method(self, "__str__", &str_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003663 if (func != NULL) {
3664 res = PyEval_CallObject(func, NULL);
3665 Py_DECREF(func);
3666 return res;
3667 }
3668 else {
3669 PyErr_Clear();
3670 return slot_tp_repr(self);
3671 }
3672}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003673
3674static long
3675slot_tp_hash(PyObject *self)
3676{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003677 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003678 static PyObject *hash_str, *eq_str, *cmp_str;
3679
Tim Peters6d6c1a32001-08-02 04:15:00 +00003680 long h;
3681
Guido van Rossum60718732001-08-28 17:47:51 +00003682 func = lookup_method(self, "__hash__", &hash_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003683
3684 if (func != NULL) {
3685 res = PyEval_CallObject(func, NULL);
3686 Py_DECREF(func);
3687 if (res == NULL)
3688 return -1;
3689 h = PyInt_AsLong(res);
3690 }
3691 else {
3692 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00003693 func = lookup_method(self, "__eq__", &eq_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003694 if (func == NULL) {
3695 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00003696 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003697 }
3698 if (func != NULL) {
3699 Py_DECREF(func);
3700 PyErr_SetString(PyExc_TypeError, "unhashable type");
3701 return -1;
3702 }
3703 PyErr_Clear();
3704 h = _Py_HashPointer((void *)self);
3705 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003706 if (h == -1 && !PyErr_Occurred())
3707 h = -2;
3708 return h;
3709}
3710
3711static PyObject *
3712slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds)
3713{
Guido van Rossum60718732001-08-28 17:47:51 +00003714 static PyObject *call_str;
3715 PyObject *meth = lookup_method(self, "__call__", &call_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003716 PyObject *res;
3717
3718 if (meth == NULL)
3719 return NULL;
3720 res = PyObject_Call(meth, args, kwds);
3721 Py_DECREF(meth);
3722 return res;
3723}
3724
Guido van Rossum14a6f832001-10-17 13:59:09 +00003725/* There are two slot dispatch functions for tp_getattro.
3726
3727 - slot_tp_getattro() is used when __getattribute__ is overridden
3728 but no __getattr__ hook is present;
3729
3730 - slot_tp_getattr_hook() is used when a __getattr__ hook is present.
3731
Guido van Rossumc334df52002-04-04 23:44:47 +00003732 The code in update_one_slot() always installs slot_tp_getattr_hook(); this
3733 detects the absence of __getattr__ and then installs the simpler slot if
3734 necessary. */
Guido van Rossum14a6f832001-10-17 13:59:09 +00003735
Tim Peters6d6c1a32001-08-02 04:15:00 +00003736static PyObject *
3737slot_tp_getattro(PyObject *self, PyObject *name)
3738{
Guido van Rossum14a6f832001-10-17 13:59:09 +00003739 static PyObject *getattribute_str = NULL;
3740 return call_method(self, "__getattribute__", &getattribute_str,
3741 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003742}
3743
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003744static PyObject *
3745slot_tp_getattr_hook(PyObject *self, PyObject *name)
3746{
3747 PyTypeObject *tp = self->ob_type;
3748 PyObject *getattr, *getattribute, *res;
3749 static PyObject *getattribute_str = NULL;
3750 static PyObject *getattr_str = NULL;
3751
3752 if (getattr_str == NULL) {
3753 getattr_str = PyString_InternFromString("__getattr__");
3754 if (getattr_str == NULL)
3755 return NULL;
3756 }
3757 if (getattribute_str == NULL) {
3758 getattribute_str =
3759 PyString_InternFromString("__getattribute__");
3760 if (getattribute_str == NULL)
3761 return NULL;
3762 }
3763 getattr = _PyType_Lookup(tp, getattr_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00003764 if (getattr == NULL) {
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003765 /* No __getattr__ hook: use a simpler dispatcher */
3766 tp->tp_getattro = slot_tp_getattro;
3767 return slot_tp_getattro(self, name);
3768 }
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003769 getattribute = _PyType_Lookup(tp, getattribute_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00003770 if (getattribute == NULL ||
3771 (getattribute->ob_type == &PyWrapperDescr_Type &&
3772 ((PyWrapperDescrObject *)getattribute)->d_wrapped ==
3773 (void *)PyObject_GenericGetAttr))
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003774 res = PyObject_GenericGetAttr(self, name);
3775 else
3776 res = PyObject_CallFunction(getattribute, "OO", self, name);
Guido van Rossum14a6f832001-10-17 13:59:09 +00003777 if (res == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) {
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003778 PyErr_Clear();
3779 res = PyObject_CallFunction(getattr, "OO", self, name);
3780 }
3781 return res;
3782}
3783
Tim Peters6d6c1a32001-08-02 04:15:00 +00003784static int
3785slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value)
3786{
3787 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003788 static PyObject *delattr_str, *setattr_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003789
3790 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003791 res = call_method(self, "__delattr__", &delattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003792 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003793 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003794 res = call_method(self, "__setattr__", &setattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003795 "(OO)", name, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003796 if (res == NULL)
3797 return -1;
3798 Py_DECREF(res);
3799 return 0;
3800}
3801
3802/* Map rich comparison operators to their __xx__ namesakes */
3803static char *name_op[] = {
3804 "__lt__",
3805 "__le__",
3806 "__eq__",
3807 "__ne__",
3808 "__gt__",
3809 "__ge__",
3810};
3811
3812static PyObject *
Guido van Rossumb8f63662001-08-15 23:57:02 +00003813half_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003814{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003815 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003816 static PyObject *op_str[6];
Tim Peters6d6c1a32001-08-02 04:15:00 +00003817
Guido van Rossum60718732001-08-28 17:47:51 +00003818 func = lookup_method(self, name_op[op], &op_str[op]);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003819 if (func == NULL) {
3820 PyErr_Clear();
3821 Py_INCREF(Py_NotImplemented);
3822 return Py_NotImplemented;
3823 }
3824 args = Py_BuildValue("(O)", other);
3825 if (args == NULL)
3826 res = NULL;
3827 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00003828 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003829 Py_DECREF(args);
3830 }
3831 Py_DECREF(func);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003832 return res;
3833}
3834
Guido van Rossumb8f63662001-08-15 23:57:02 +00003835/* Map rich comparison operators to their swapped version, e.g. LT --> GT */
3836static int swapped_op[] = {Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE};
3837
3838static PyObject *
3839slot_tp_richcompare(PyObject *self, PyObject *other, int op)
3840{
3841 PyObject *res;
3842
3843 if (self->ob_type->tp_richcompare == slot_tp_richcompare) {
3844 res = half_richcompare(self, other, op);
3845 if (res != Py_NotImplemented)
3846 return res;
3847 Py_DECREF(res);
3848 }
3849 if (other->ob_type->tp_richcompare == slot_tp_richcompare) {
3850 res = half_richcompare(other, self, swapped_op[op]);
3851 if (res != Py_NotImplemented) {
3852 return res;
3853 }
3854 Py_DECREF(res);
3855 }
3856 Py_INCREF(Py_NotImplemented);
3857 return Py_NotImplemented;
3858}
3859
3860static PyObject *
3861slot_tp_iter(PyObject *self)
3862{
3863 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003864 static PyObject *iter_str, *getitem_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003865
Guido van Rossum60718732001-08-28 17:47:51 +00003866 func = lookup_method(self, "__iter__", &iter_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003867 if (func != NULL) {
Guido van Rossum84b2bed2002-08-16 17:01:09 +00003868 PyObject *args;
3869 args = res = PyTuple_New(0);
3870 if (args != NULL) {
3871 res = PyObject_Call(func, args, NULL);
3872 Py_DECREF(args);
3873 }
3874 Py_DECREF(func);
3875 return res;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003876 }
3877 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00003878 func = lookup_method(self, "__getitem__", &getitem_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003879 if (func == NULL) {
Guido van Rossumd4641072002-04-03 02:13:37 +00003880 PyErr_SetString(PyExc_TypeError,
3881 "iteration over non-sequence");
Guido van Rossumb8f63662001-08-15 23:57:02 +00003882 return NULL;
3883 }
3884 Py_DECREF(func);
3885 return PySeqIter_New(self);
3886}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003887
3888static PyObject *
3889slot_tp_iternext(PyObject *self)
3890{
Guido van Rossum2730b132001-08-28 18:22:14 +00003891 static PyObject *next_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00003892 return call_method(self, "next", &next_str, "()");
Tim Peters6d6c1a32001-08-02 04:15:00 +00003893}
3894
Guido van Rossum1a493502001-08-17 16:47:50 +00003895static PyObject *
3896slot_tp_descr_get(PyObject *self, PyObject *obj, PyObject *type)
3897{
3898 PyTypeObject *tp = self->ob_type;
3899 PyObject *get;
3900 static PyObject *get_str = NULL;
3901
3902 if (get_str == NULL) {
3903 get_str = PyString_InternFromString("__get__");
3904 if (get_str == NULL)
3905 return NULL;
3906 }
3907 get = _PyType_Lookup(tp, get_str);
3908 if (get == NULL) {
3909 /* Avoid further slowdowns */
3910 if (tp->tp_descr_get == slot_tp_descr_get)
3911 tp->tp_descr_get = NULL;
3912 Py_INCREF(self);
3913 return self;
3914 }
Guido van Rossum2c252392001-08-24 10:13:31 +00003915 if (obj == NULL)
3916 obj = Py_None;
3917 if (type == NULL)
3918 type = Py_None;
Guido van Rossum1a493502001-08-17 16:47:50 +00003919 return PyObject_CallFunction(get, "OOO", self, obj, type);
3920}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003921
3922static int
3923slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value)
3924{
Guido van Rossum2c252392001-08-24 10:13:31 +00003925 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003926 static PyObject *del_str, *set_str;
Guido van Rossum2c252392001-08-24 10:13:31 +00003927
3928 if (value == NULL)
Guido van Rossum1d5b3f22001-12-03 00:08:33 +00003929 res = call_method(self, "__delete__", &del_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003930 "(O)", target);
Guido van Rossum2c252392001-08-24 10:13:31 +00003931 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003932 res = call_method(self, "__set__", &set_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003933 "(OO)", target, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003934 if (res == NULL)
3935 return -1;
3936 Py_DECREF(res);
3937 return 0;
3938}
3939
3940static int
3941slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds)
3942{
Guido van Rossum60718732001-08-28 17:47:51 +00003943 static PyObject *init_str;
3944 PyObject *meth = lookup_method(self, "__init__", &init_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003945 PyObject *res;
3946
3947 if (meth == NULL)
3948 return -1;
3949 res = PyObject_Call(meth, args, kwds);
3950 Py_DECREF(meth);
3951 if (res == NULL)
3952 return -1;
3953 Py_DECREF(res);
3954 return 0;
3955}
3956
3957static PyObject *
3958slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3959{
Guido van Rossum7bed2132002-08-08 21:57:53 +00003960 static PyObject *new_str;
3961 PyObject *func;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003962 PyObject *newargs, *x;
3963 int i, n;
3964
Guido van Rossum7bed2132002-08-08 21:57:53 +00003965 if (new_str == NULL) {
3966 new_str = PyString_InternFromString("__new__");
3967 if (new_str == NULL)
3968 return NULL;
3969 }
3970 func = PyObject_GetAttr((PyObject *)type, new_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003971 if (func == NULL)
3972 return NULL;
3973 assert(PyTuple_Check(args));
3974 n = PyTuple_GET_SIZE(args);
3975 newargs = PyTuple_New(n+1);
3976 if (newargs == NULL)
3977 return NULL;
3978 Py_INCREF(type);
3979 PyTuple_SET_ITEM(newargs, 0, (PyObject *)type);
3980 for (i = 0; i < n; i++) {
3981 x = PyTuple_GET_ITEM(args, i);
3982 Py_INCREF(x);
3983 PyTuple_SET_ITEM(newargs, i+1, x);
3984 }
3985 x = PyObject_Call(func, newargs, kwds);
Guido van Rossum25d18072001-10-01 15:55:28 +00003986 Py_DECREF(newargs);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003987 Py_DECREF(func);
3988 return x;
3989}
3990
Guido van Rossumfebd61d2002-08-08 20:55:20 +00003991static void
3992slot_tp_del(PyObject *self)
3993{
3994 static PyObject *del_str = NULL;
3995 PyObject *del, *res;
3996 PyObject *error_type, *error_value, *error_traceback;
3997
3998 /* Temporarily resurrect the object. */
3999 assert(self->ob_refcnt == 0);
4000 self->ob_refcnt = 1;
4001
4002 /* Save the current exception, if any. */
4003 PyErr_Fetch(&error_type, &error_value, &error_traceback);
4004
4005 /* Execute __del__ method, if any. */
4006 del = lookup_maybe(self, "__del__", &del_str);
4007 if (del != NULL) {
4008 res = PyEval_CallObject(del, NULL);
4009 if (res == NULL)
4010 PyErr_WriteUnraisable(del);
4011 else
4012 Py_DECREF(res);
4013 Py_DECREF(del);
4014 }
4015
4016 /* Restore the saved exception. */
4017 PyErr_Restore(error_type, error_value, error_traceback);
4018
4019 /* Undo the temporary resurrection; can't use DECREF here, it would
4020 * cause a recursive call.
4021 */
4022 assert(self->ob_refcnt > 0);
4023 if (--self->ob_refcnt == 0)
4024 return; /* this is the normal path out */
4025
4026 /* __del__ resurrected it! Make it look like the original Py_DECREF
4027 * never happened.
4028 */
4029 {
4030 int refcnt = self->ob_refcnt;
4031 _Py_NewReference(self);
4032 self->ob_refcnt = refcnt;
4033 }
4034 assert(!PyType_IS_GC(self->ob_type) ||
4035 _Py_AS_GC(self)->gc.gc_refs != _PyGC_REFS_UNTRACKED);
4036 /* If Py_REF_DEBUG, the original decref dropped _Py_RefTotal, but
4037 * _Py_NewReference bumped it again, so that's a wash.
4038 * If Py_TRACE_REFS, _Py_NewReference re-added self to the object
4039 * chain, so no more to do there either.
4040 * If COUNT_ALLOCS, the original decref bumped tp_frees, and
4041 * _Py_NewReference bumped tp_allocs: both of those need to be
4042 * undone.
4043 */
4044#ifdef COUNT_ALLOCS
4045 --self->ob_type->tp_frees;
4046 --self->ob_type->tp_allocs;
4047#endif
4048}
4049
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004050
4051/* Table mapping __foo__ names to tp_foo offsets and slot_tp_foo wrapper
4052 functions. The offsets here are relative to the 'etype' structure, which
4053 incorporates the additional structures used for numbers, sequences and
4054 mappings. Note that multiple names may map to the same slot (e.g. __eq__,
4055 __ne__ etc. all map to tp_richcompare) and one name may map to multiple
Guido van Rossumc334df52002-04-04 23:44:47 +00004056 slots (e.g. __str__ affects tp_str as well as tp_repr). The table is
4057 terminated with an all-zero entry. (This table is further initialized and
4058 sorted in init_slotdefs() below.) */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004059
Guido van Rossum6d204072001-10-21 00:44:31 +00004060typedef struct wrapperbase slotdef;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004061
4062#undef TPSLOT
Guido van Rossumc8e56452001-10-22 00:43:43 +00004063#undef FLSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004064#undef ETSLOT
4065#undef SQSLOT
4066#undef MPSLOT
4067#undef NBSLOT
Guido van Rossum6d204072001-10-21 00:44:31 +00004068#undef UNSLOT
4069#undef IBSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004070#undef BINSLOT
4071#undef RBINSLOT
4072
Guido van Rossum6d204072001-10-21 00:44:31 +00004073#define TPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Neal Norwitzd47714a2002-08-13 19:01:38 +00004074 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
4075 PyDoc_STR(DOC)}
Guido van Rossumc8e56452001-10-22 00:43:43 +00004076#define FLSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC, FLAGS) \
4077 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
Neal Norwitzd47714a2002-08-13 19:01:38 +00004078 PyDoc_STR(DOC), FLAGS}
Guido van Rossum6d204072001-10-21 00:44:31 +00004079#define ETSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Neal Norwitzd47714a2002-08-13 19:01:38 +00004080 {NAME, offsetof(etype, SLOT), (void *)(FUNCTION), WRAPPER, \
4081 PyDoc_STR(DOC)}
Guido van Rossum6d204072001-10-21 00:44:31 +00004082#define SQSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4083 ETSLOT(NAME, as_sequence.SLOT, FUNCTION, WRAPPER, DOC)
4084#define MPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4085 ETSLOT(NAME, as_mapping.SLOT, FUNCTION, WRAPPER, DOC)
4086#define NBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4087 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, DOC)
4088#define UNSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4089 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
4090 "x." NAME "() <==> " DOC)
4091#define IBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4092 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
4093 "x." NAME "(y) <==> x" DOC "y")
4094#define BINSLOT(NAME, SLOT, FUNCTION, DOC) \
4095 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
4096 "x." NAME "(y) <==> x" DOC "y")
4097#define RBINSLOT(NAME, SLOT, FUNCTION, DOC) \
4098 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
4099 "x." NAME "(y) <==> y" DOC "x")
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004100
4101static slotdef slotdefs[] = {
Guido van Rossum6d204072001-10-21 00:44:31 +00004102 SQSLOT("__len__", sq_length, slot_sq_length, wrap_inquiry,
4103 "x.__len__() <==> len(x)"),
4104 SQSLOT("__add__", sq_concat, slot_sq_concat, wrap_binaryfunc,
4105 "x.__add__(y) <==> x+y"),
4106 SQSLOT("__mul__", sq_repeat, slot_sq_repeat, wrap_intargfunc,
4107 "x.__mul__(n) <==> x*n"),
4108 SQSLOT("__rmul__", sq_repeat, slot_sq_repeat, wrap_intargfunc,
4109 "x.__rmul__(n) <==> n*x"),
4110 SQSLOT("__getitem__", sq_item, slot_sq_item, wrap_sq_item,
4111 "x.__getitem__(y) <==> x[y]"),
4112 SQSLOT("__getslice__", sq_slice, slot_sq_slice, wrap_intintargfunc,
4113 "x.__getslice__(i, j) <==> x[i:j]"),
4114 SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_setitem,
4115 "x.__setitem__(i, y) <==> x[i]=y"),
4116 SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_delitem,
4117 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004118 SQSLOT("__setslice__", sq_ass_slice, slot_sq_ass_slice,
Guido van Rossum6d204072001-10-21 00:44:31 +00004119 wrap_intintobjargproc,
4120 "x.__setslice__(i, j, y) <==> x[i:j]=y"),
4121 SQSLOT("__delslice__", sq_ass_slice, slot_sq_ass_slice, wrap_delslice,
4122 "x.__delslice__(i, j) <==> del x[i:j]"),
4123 SQSLOT("__contains__", sq_contains, slot_sq_contains, wrap_objobjproc,
4124 "x.__contains__(y) <==> y in x"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004125 SQSLOT("__iadd__", sq_inplace_concat, slot_sq_inplace_concat,
Guido van Rossum6d204072001-10-21 00:44:31 +00004126 wrap_binaryfunc, "x.__iadd__(y) <==> x+=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004127 SQSLOT("__imul__", sq_inplace_repeat, slot_sq_inplace_repeat,
Guido van Rossum6d204072001-10-21 00:44:31 +00004128 wrap_intargfunc, "x.__imul__(y) <==> x*=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004129
Guido van Rossum6d204072001-10-21 00:44:31 +00004130 MPSLOT("__len__", mp_length, slot_mp_length, wrap_inquiry,
4131 "x.__len__() <==> len(x)"),
Guido van Rossumfd38f8e2001-10-09 20:17:57 +00004132 MPSLOT("__getitem__", mp_subscript, slot_mp_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00004133 wrap_binaryfunc,
4134 "x.__getitem__(y) <==> x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004135 MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00004136 wrap_objobjargproc,
4137 "x.__setitem__(i, y) <==> x[i]=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004138 MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00004139 wrap_delitem,
4140 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004141
Guido van Rossum6d204072001-10-21 00:44:31 +00004142 BINSLOT("__add__", nb_add, slot_nb_add,
4143 "+"),
4144 RBINSLOT("__radd__", nb_add, slot_nb_add,
4145 "+"),
4146 BINSLOT("__sub__", nb_subtract, slot_nb_subtract,
4147 "-"),
4148 RBINSLOT("__rsub__", nb_subtract, slot_nb_subtract,
4149 "-"),
4150 BINSLOT("__mul__", nb_multiply, slot_nb_multiply,
4151 "*"),
4152 RBINSLOT("__rmul__", nb_multiply, slot_nb_multiply,
4153 "*"),
4154 BINSLOT("__div__", nb_divide, slot_nb_divide,
4155 "/"),
4156 RBINSLOT("__rdiv__", nb_divide, slot_nb_divide,
4157 "/"),
4158 BINSLOT("__mod__", nb_remainder, slot_nb_remainder,
4159 "%"),
4160 RBINSLOT("__rmod__", nb_remainder, slot_nb_remainder,
4161 "%"),
4162 BINSLOT("__divmod__", nb_divmod, slot_nb_divmod,
4163 "divmod(x, y)"),
4164 RBINSLOT("__rdivmod__", nb_divmod, slot_nb_divmod,
4165 "divmod(y, x)"),
4166 NBSLOT("__pow__", nb_power, slot_nb_power, wrap_ternaryfunc,
4167 "x.__pow__(y[, z]) <==> pow(x, y[, z])"),
4168 NBSLOT("__rpow__", nb_power, slot_nb_power, wrap_ternaryfunc_r,
4169 "y.__rpow__(x[, z]) <==> pow(x, y[, z])"),
4170 UNSLOT("__neg__", nb_negative, slot_nb_negative, wrap_unaryfunc, "-x"),
4171 UNSLOT("__pos__", nb_positive, slot_nb_positive, wrap_unaryfunc, "+x"),
4172 UNSLOT("__abs__", nb_absolute, slot_nb_absolute, wrap_unaryfunc,
4173 "abs(x)"),
Guido van Rossumdfce3bf2002-03-10 14:11:16 +00004174 UNSLOT("__nonzero__", nb_nonzero, slot_nb_nonzero, wrap_inquiry,
Guido van Rossum6d204072001-10-21 00:44:31 +00004175 "x != 0"),
4176 UNSLOT("__invert__", nb_invert, slot_nb_invert, wrap_unaryfunc, "~x"),
4177 BINSLOT("__lshift__", nb_lshift, slot_nb_lshift, "<<"),
4178 RBINSLOT("__rlshift__", nb_lshift, slot_nb_lshift, "<<"),
4179 BINSLOT("__rshift__", nb_rshift, slot_nb_rshift, ">>"),
4180 RBINSLOT("__rrshift__", nb_rshift, slot_nb_rshift, ">>"),
4181 BINSLOT("__and__", nb_and, slot_nb_and, "&"),
4182 RBINSLOT("__rand__", nb_and, slot_nb_and, "&"),
4183 BINSLOT("__xor__", nb_xor, slot_nb_xor, "^"),
4184 RBINSLOT("__rxor__", nb_xor, slot_nb_xor, "^"),
4185 BINSLOT("__or__", nb_or, slot_nb_or, "|"),
4186 RBINSLOT("__ror__", nb_or, slot_nb_or, "|"),
4187 NBSLOT("__coerce__", nb_coerce, slot_nb_coerce, wrap_coercefunc,
4188 "x.__coerce__(y) <==> coerce(x, y)"),
4189 UNSLOT("__int__", nb_int, slot_nb_int, wrap_unaryfunc,
4190 "int(x)"),
4191 UNSLOT("__long__", nb_long, slot_nb_long, wrap_unaryfunc,
4192 "long(x)"),
4193 UNSLOT("__float__", nb_float, slot_nb_float, wrap_unaryfunc,
4194 "float(x)"),
4195 UNSLOT("__oct__", nb_oct, slot_nb_oct, wrap_unaryfunc,
4196 "oct(x)"),
4197 UNSLOT("__hex__", nb_hex, slot_nb_hex, wrap_unaryfunc,
4198 "hex(x)"),
4199 IBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add,
4200 wrap_binaryfunc, "+"),
4201 IBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract,
4202 wrap_binaryfunc, "-"),
4203 IBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply,
4204 wrap_binaryfunc, "*"),
4205 IBSLOT("__idiv__", nb_inplace_divide, slot_nb_inplace_divide,
4206 wrap_binaryfunc, "/"),
4207 IBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder,
4208 wrap_binaryfunc, "%"),
4209 IBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power,
Guido van Rossum6e5680f2002-10-15 01:01:53 +00004210 wrap_binaryfunc, "**"),
Guido van Rossum6d204072001-10-21 00:44:31 +00004211 IBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift,
4212 wrap_binaryfunc, "<<"),
4213 IBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift,
4214 wrap_binaryfunc, ">>"),
4215 IBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and,
4216 wrap_binaryfunc, "&"),
4217 IBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor,
4218 wrap_binaryfunc, "^"),
4219 IBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or,
4220 wrap_binaryfunc, "|"),
4221 BINSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
4222 RBINSLOT("__rfloordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
4223 BINSLOT("__truediv__", nb_true_divide, slot_nb_true_divide, "/"),
4224 RBINSLOT("__rtruediv__", nb_true_divide, slot_nb_true_divide, "/"),
4225 IBSLOT("__ifloordiv__", nb_inplace_floor_divide,
4226 slot_nb_inplace_floor_divide, wrap_binaryfunc, "//"),
4227 IBSLOT("__itruediv__", nb_inplace_true_divide,
4228 slot_nb_inplace_true_divide, wrap_binaryfunc, "/"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004229
Guido van Rossum6d204072001-10-21 00:44:31 +00004230 TPSLOT("__str__", tp_str, slot_tp_str, wrap_unaryfunc,
4231 "x.__str__() <==> str(x)"),
Guido van Rossumafe7a942001-10-29 14:33:44 +00004232 TPSLOT("__str__", tp_print, NULL, NULL, ""),
Guido van Rossum6d204072001-10-21 00:44:31 +00004233 TPSLOT("__repr__", tp_repr, slot_tp_repr, wrap_unaryfunc,
4234 "x.__repr__() <==> repr(x)"),
Guido van Rossumafe7a942001-10-29 14:33:44 +00004235 TPSLOT("__repr__", tp_print, NULL, NULL, ""),
Guido van Rossum6d204072001-10-21 00:44:31 +00004236 TPSLOT("__cmp__", tp_compare, _PyObject_SlotCompare, wrap_cmpfunc,
4237 "x.__cmp__(y) <==> cmp(x,y)"),
4238 TPSLOT("__hash__", tp_hash, slot_tp_hash, wrap_hashfunc,
4239 "x.__hash__() <==> hash(x)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00004240 FLSLOT("__call__", tp_call, slot_tp_call, (wrapperfunc)wrap_call,
4241 "x.__call__(...) <==> x(...)", PyWrapperFlag_KEYWORDS),
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004242 TPSLOT("__getattribute__", tp_getattro, slot_tp_getattr_hook,
Guido van Rossum6d204072001-10-21 00:44:31 +00004243 wrap_binaryfunc, "x.__getattribute__('name') <==> x.name"),
4244 TPSLOT("__getattribute__", tp_getattr, NULL, NULL, ""),
4245 TPSLOT("__getattr__", tp_getattro, slot_tp_getattr_hook, NULL, ""),
4246 TPSLOT("__getattr__", tp_getattr, NULL, NULL, ""),
4247 TPSLOT("__setattr__", tp_setattro, slot_tp_setattro, wrap_setattr,
4248 "x.__setattr__('name', value) <==> x.name = value"),
4249 TPSLOT("__setattr__", tp_setattr, NULL, NULL, ""),
4250 TPSLOT("__delattr__", tp_setattro, slot_tp_setattro, wrap_delattr,
4251 "x.__delattr__('name') <==> del x.name"),
4252 TPSLOT("__delattr__", tp_setattr, NULL, NULL, ""),
4253 TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare, richcmp_lt,
4254 "x.__lt__(y) <==> x<y"),
4255 TPSLOT("__le__", tp_richcompare, slot_tp_richcompare, richcmp_le,
4256 "x.__le__(y) <==> x<=y"),
4257 TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare, richcmp_eq,
4258 "x.__eq__(y) <==> x==y"),
4259 TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare, richcmp_ne,
4260 "x.__ne__(y) <==> x!=y"),
4261 TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare, richcmp_gt,
4262 "x.__gt__(y) <==> x>y"),
4263 TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare, richcmp_ge,
4264 "x.__ge__(y) <==> x>=y"),
4265 TPSLOT("__iter__", tp_iter, slot_tp_iter, wrap_unaryfunc,
4266 "x.__iter__() <==> iter(x)"),
4267 TPSLOT("next", tp_iternext, slot_tp_iternext, wrap_next,
4268 "x.next() -> the next value, or raise StopIteration"),
4269 TPSLOT("__get__", tp_descr_get, slot_tp_descr_get, wrap_descr_get,
4270 "descr.__get__(obj[, type]) -> value"),
4271 TPSLOT("__set__", tp_descr_set, slot_tp_descr_set, wrap_descr_set,
4272 "descr.__set__(obj, value)"),
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00004273 TPSLOT("__delete__", tp_descr_set, slot_tp_descr_set,
4274 wrap_descr_delete, "descr.__delete__(obj)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00004275 FLSLOT("__init__", tp_init, slot_tp_init, (wrapperfunc)wrap_init,
Guido van Rossum6d204072001-10-21 00:44:31 +00004276 "x.__init__(...) initializes x; "
Guido van Rossumc8e56452001-10-22 00:43:43 +00004277 "see x.__class__.__doc__ for signature",
4278 PyWrapperFlag_KEYWORDS),
4279 TPSLOT("__new__", tp_new, slot_tp_new, NULL, ""),
Guido van Rossumfebd61d2002-08-08 20:55:20 +00004280 TPSLOT("__del__", tp_del, slot_tp_del, NULL, ""),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004281 {NULL}
4282};
4283
Guido van Rossumc334df52002-04-04 23:44:47 +00004284/* Given a type pointer and an offset gotten from a slotdef entry, return a
4285 pointer to the actual slot. This is not quite the same as simply adding
4286 the offset to the type pointer, since it takes care to indirect through the
4287 proper indirection pointer (as_buffer, etc.); it returns NULL if the
4288 indirection pointer is NULL. */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004289static void **
4290slotptr(PyTypeObject *type, int offset)
4291{
4292 char *ptr;
4293
Guido van Rossum09638c12002-06-13 19:17:46 +00004294 /* Note: this depends on the order of the members of etype! */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004295 assert(offset >= 0);
4296 assert(offset < offsetof(etype, as_buffer));
Guido van Rossum09638c12002-06-13 19:17:46 +00004297 if (offset >= offsetof(etype, as_sequence)) {
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004298 ptr = (void *)type->tp_as_sequence;
4299 offset -= offsetof(etype, as_sequence);
4300 }
Guido van Rossum09638c12002-06-13 19:17:46 +00004301 else if (offset >= offsetof(etype, as_mapping)) {
4302 ptr = (void *)type->tp_as_mapping;
4303 offset -= offsetof(etype, as_mapping);
4304 }
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004305 else if (offset >= offsetof(etype, as_number)) {
4306 ptr = (void *)type->tp_as_number;
4307 offset -= offsetof(etype, as_number);
4308 }
4309 else {
4310 ptr = (void *)type;
4311 }
4312 if (ptr != NULL)
4313 ptr += offset;
4314 return (void **)ptr;
4315}
Guido van Rossumf040ede2001-08-07 16:40:56 +00004316
Guido van Rossumc334df52002-04-04 23:44:47 +00004317/* Length of array of slotdef pointers used to store slots with the
4318 same __name__. There should be at most MAX_EQUIV-1 slotdef entries with
4319 the same __name__, for any __name__. Since that's a static property, it is
4320 appropriate to declare fixed-size arrays for this. */
4321#define MAX_EQUIV 10
4322
4323/* Return a slot pointer for a given name, but ONLY if the attribute has
4324 exactly one slot function. The name must be an interned string. */
4325static void **
4326resolve_slotdups(PyTypeObject *type, PyObject *name)
4327{
4328 /* XXX Maybe this could be optimized more -- but is it worth it? */
4329
4330 /* pname and ptrs act as a little cache */
4331 static PyObject *pname;
4332 static slotdef *ptrs[MAX_EQUIV];
4333 slotdef *p, **pp;
4334 void **res, **ptr;
4335
4336 if (pname != name) {
4337 /* Collect all slotdefs that match name into ptrs. */
4338 pname = name;
4339 pp = ptrs;
4340 for (p = slotdefs; p->name_strobj; p++) {
4341 if (p->name_strobj == name)
4342 *pp++ = p;
4343 }
4344 *pp = NULL;
4345 }
4346
4347 /* Look in all matching slots of the type; if exactly one of these has
4348 a filled-in slot, return its value. Otherwise return NULL. */
4349 res = NULL;
4350 for (pp = ptrs; *pp; pp++) {
4351 ptr = slotptr(type, (*pp)->offset);
4352 if (ptr == NULL || *ptr == NULL)
4353 continue;
4354 if (res != NULL)
4355 return NULL;
4356 res = ptr;
4357 }
4358 return res;
4359}
4360
4361/* Common code for update_these_slots() and fixup_slot_dispatchers(). This
4362 does some incredibly complex thinking and then sticks something into the
4363 slot. (It sees if the adjacent slotdefs for the same slot have conflicting
4364 interests, and then stores a generic wrapper or a specific function into
4365 the slot.) Return a pointer to the next slotdef with a different offset,
4366 because that's convenient for fixup_slot_dispatchers(). */
4367static slotdef *
4368update_one_slot(PyTypeObject *type, slotdef *p)
4369{
4370 PyObject *descr;
4371 PyWrapperDescrObject *d;
4372 void *generic = NULL, *specific = NULL;
4373 int use_generic = 0;
4374 int offset = p->offset;
4375 void **ptr = slotptr(type, offset);
4376
4377 if (ptr == NULL) {
4378 do {
4379 ++p;
4380 } while (p->offset == offset);
4381 return p;
4382 }
4383 do {
4384 descr = _PyType_Lookup(type, p->name_strobj);
4385 if (descr == NULL)
4386 continue;
4387 if (descr->ob_type == &PyWrapperDescr_Type) {
4388 void **tptr = resolve_slotdups(type, p->name_strobj);
4389 if (tptr == NULL || tptr == ptr)
4390 generic = p->function;
4391 d = (PyWrapperDescrObject *)descr;
4392 if (d->d_base->wrapper == p->wrapper &&
4393 PyType_IsSubtype(type, d->d_type))
4394 {
4395 if (specific == NULL ||
4396 specific == d->d_wrapped)
4397 specific = d->d_wrapped;
4398 else
4399 use_generic = 1;
4400 }
4401 }
Guido van Rossum721f62e2002-08-09 02:14:34 +00004402 else if (descr->ob_type == &PyCFunction_Type &&
4403 PyCFunction_GET_FUNCTION(descr) ==
4404 (PyCFunction)tp_new_wrapper &&
4405 strcmp(p->name, "__new__") == 0)
4406 {
4407 /* The __new__ wrapper is not a wrapper descriptor,
4408 so must be special-cased differently.
4409 If we don't do this, creating an instance will
4410 always use slot_tp_new which will look up
4411 __new__ in the MRO which will call tp_new_wrapper
4412 which will look through the base classes looking
4413 for a static base and call its tp_new (usually
4414 PyType_GenericNew), after performing various
4415 sanity checks and constructing a new argument
4416 list. Cut all that nonsense short -- this speeds
4417 up instance creation tremendously. */
4418 specific = type->tp_new;
4419 /* XXX I'm not 100% sure that there isn't a hole
4420 in this reasoning that requires additional
4421 sanity checks. I'll buy the first person to
4422 point out a bug in this reasoning a beer. */
4423 }
Guido van Rossumc334df52002-04-04 23:44:47 +00004424 else {
4425 use_generic = 1;
4426 generic = p->function;
4427 }
4428 } while ((++p)->offset == offset);
4429 if (specific && !use_generic)
4430 *ptr = specific;
4431 else
4432 *ptr = generic;
4433 return p;
4434}
4435
Guido van Rossum22b13872002-08-06 21:41:44 +00004436static int recurse_down_subclasses(PyTypeObject *type, slotdef **pp,
Jeremy Hylton938ace62002-07-17 16:30:39 +00004437 PyObject *name);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004438
Guido van Rossumc334df52002-04-04 23:44:47 +00004439/* In the type, update the slots whose slotdefs are gathered in the pp0 array,
4440 and then do the same for all this type's subtypes. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004441static int
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004442update_these_slots(PyTypeObject *type, slotdef **pp0, PyObject *name)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004443{
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004444 slotdef **pp;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004445
Guido van Rossumc334df52002-04-04 23:44:47 +00004446 for (pp = pp0; *pp; pp++)
4447 update_one_slot(type, *pp);
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004448 return recurse_down_subclasses(type, pp0, name);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004449}
4450
Guido van Rossumc334df52002-04-04 23:44:47 +00004451/* Update the slots whose slotdefs are gathered in the pp array in all (direct
4452 or indirect) subclasses of type. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004453static int
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004454recurse_down_subclasses(PyTypeObject *type, slotdef **pp, PyObject *name)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004455{
4456 PyTypeObject *subclass;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004457 PyObject *ref, *subclasses, *dict;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004458 int i, n;
4459
4460 subclasses = type->tp_subclasses;
4461 if (subclasses == NULL)
4462 return 0;
4463 assert(PyList_Check(subclasses));
4464 n = PyList_GET_SIZE(subclasses);
4465 for (i = 0; i < n; i++) {
4466 ref = PyList_GET_ITEM(subclasses, i);
4467 assert(PyWeakref_CheckRef(ref));
4468 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
Guido van Rossum59e6c532002-06-14 02:27:07 +00004469 assert(subclass != NULL);
4470 if ((PyObject *)subclass == Py_None)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004471 continue;
4472 assert(PyType_Check(subclass));
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004473 /* Avoid recursing down into unaffected classes */
4474 dict = subclass->tp_dict;
4475 if (dict != NULL && PyDict_Check(dict) &&
4476 PyDict_GetItem(dict, name) != NULL)
4477 continue;
4478 if (update_these_slots(subclass, pp, name) < 0)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004479 return -1;
4480 }
4481 return 0;
4482}
4483
Guido van Rossumc334df52002-04-04 23:44:47 +00004484/* Comparison function for qsort() to compare slotdefs by their offset, and
4485 for equal offset by their address (to force a stable sort). */
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004486static int
4487slotdef_cmp(const void *aa, const void *bb)
4488{
4489 const slotdef *a = (const slotdef *)aa, *b = (const slotdef *)bb;
4490 int c = a->offset - b->offset;
4491 if (c != 0)
4492 return c;
4493 else
4494 return a - b;
4495}
4496
Guido van Rossumc334df52002-04-04 23:44:47 +00004497/* Initialize the slotdefs table by adding interned string objects for the
4498 names and sorting the entries. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004499static void
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004500init_slotdefs(void)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004501{
4502 slotdef *p;
4503 static int initialized = 0;
4504
4505 if (initialized)
4506 return;
4507 for (p = slotdefs; p->name; p++) {
4508 p->name_strobj = PyString_InternFromString(p->name);
4509 if (!p->name_strobj)
Guido van Rossumc334df52002-04-04 23:44:47 +00004510 Py_FatalError("Out of memory interning slotdef names");
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004511 }
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004512 qsort((void *)slotdefs, (size_t)(p-slotdefs), sizeof(slotdef),
4513 slotdef_cmp);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004514 initialized = 1;
4515}
4516
Guido van Rossumc334df52002-04-04 23:44:47 +00004517/* Update the slots after assignment to a class (type) attribute. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004518static int
4519update_slot(PyTypeObject *type, PyObject *name)
4520{
Guido van Rossumc334df52002-04-04 23:44:47 +00004521 slotdef *ptrs[MAX_EQUIV];
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004522 slotdef *p;
4523 slotdef **pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004524 int offset;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004525
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004526 init_slotdefs();
4527 pp = ptrs;
4528 for (p = slotdefs; p->name; p++) {
4529 /* XXX assume name is interned! */
4530 if (p->name_strobj == name)
4531 *pp++ = p;
4532 }
4533 *pp = NULL;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004534 for (pp = ptrs; *pp; pp++) {
4535 p = *pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004536 offset = p->offset;
4537 while (p > slotdefs && (p-1)->offset == offset)
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004538 --p;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004539 *pp = p;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004540 }
Guido van Rossumc334df52002-04-04 23:44:47 +00004541 if (ptrs[0] == NULL)
4542 return 0; /* Not an attribute that affects any slots */
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004543 return update_these_slots(type, ptrs, name);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004544}
4545
Guido van Rossumc334df52002-04-04 23:44:47 +00004546/* Store the proper functions in the slot dispatches at class (type)
4547 definition time, based upon which operations the class overrides in its
4548 dict. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004549static void
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004550fixup_slot_dispatchers(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004551{
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004552 slotdef *p;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004553
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004554 init_slotdefs();
Guido van Rossumc334df52002-04-04 23:44:47 +00004555 for (p = slotdefs; p->name; )
4556 p = update_one_slot(type, p);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004557}
Guido van Rossum705f0f52001-08-24 16:47:00 +00004558
Guido van Rossum6d204072001-10-21 00:44:31 +00004559/* This function is called by PyType_Ready() to populate the type's
4560 dictionary with method descriptors for function slots. For each
Guido van Rossum09638c12002-06-13 19:17:46 +00004561 function slot (like tp_repr) that's defined in the type, one or more
4562 corresponding descriptors are added in the type's tp_dict dictionary
4563 under the appropriate name (like __repr__). Some function slots
4564 cause more than one descriptor to be added (for example, the nb_add
4565 slot adds both __add__ and __radd__ descriptors) and some function
4566 slots compete for the same descriptor (for example both sq_item and
4567 mp_subscript generate a __getitem__ descriptor).
4568
4569 In the latter case, the first slotdef entry encoutered wins. Since
4570 slotdef entries are sorted by the offset of the slot in the etype
4571 struct, this gives us some control over disambiguating between
4572 competing slots: the members of struct etype are listed from most
4573 general to least general, so the most general slot is preferred. In
4574 particular, because as_mapping comes before as_sequence, for a type
4575 that defines both mp_subscript and sq_item, mp_subscript wins.
4576
4577 This only adds new descriptors and doesn't overwrite entries in
4578 tp_dict that were previously defined. The descriptors contain a
4579 reference to the C function they must call, so that it's safe if they
4580 are copied into a subtype's __dict__ and the subtype has a different
4581 C function in its slot -- calling the method defined by the
4582 descriptor will call the C function that was used to create it,
4583 rather than the C function present in the slot when it is called.
4584 (This is important because a subtype may have a C function in the
4585 slot that calls the method from the dictionary, and we want to avoid
4586 infinite recursion here.) */
Guido van Rossum6d204072001-10-21 00:44:31 +00004587
4588static int
4589add_operators(PyTypeObject *type)
4590{
4591 PyObject *dict = type->tp_dict;
4592 slotdef *p;
4593 PyObject *descr;
4594 void **ptr;
4595
4596 init_slotdefs();
4597 for (p = slotdefs; p->name; p++) {
4598 if (p->wrapper == NULL)
4599 continue;
4600 ptr = slotptr(type, p->offset);
4601 if (!ptr || !*ptr)
4602 continue;
4603 if (PyDict_GetItem(dict, p->name_strobj))
4604 continue;
4605 descr = PyDescr_NewWrapper(type, p, *ptr);
4606 if (descr == NULL)
4607 return -1;
4608 if (PyDict_SetItem(dict, p->name_strobj, descr) < 0)
4609 return -1;
4610 Py_DECREF(descr);
4611 }
4612 if (type->tp_new != NULL) {
4613 if (add_tp_new_wrapper(type) < 0)
4614 return -1;
4615 }
4616 return 0;
4617}
4618
Guido van Rossum705f0f52001-08-24 16:47:00 +00004619
4620/* Cooperative 'super' */
4621
4622typedef struct {
4623 PyObject_HEAD
Guido van Rossume705ef12001-08-29 15:47:06 +00004624 PyTypeObject *type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00004625 PyObject *obj;
4626} superobject;
4627
Guido van Rossum6f799372001-09-20 20:46:19 +00004628static PyMemberDef super_members[] = {
4629 {"__thisclass__", T_OBJECT, offsetof(superobject, type), READONLY,
4630 "the class invoking super()"},
4631 {"__self__", T_OBJECT, offsetof(superobject, obj), READONLY,
4632 "the instance invoking super(); may be None"},
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004633 {0}
4634};
4635
Guido van Rossum705f0f52001-08-24 16:47:00 +00004636static void
4637super_dealloc(PyObject *self)
4638{
4639 superobject *su = (superobject *)self;
4640
Guido van Rossum048eb752001-10-02 21:24:57 +00004641 _PyObject_GC_UNTRACK(self);
Guido van Rossum705f0f52001-08-24 16:47:00 +00004642 Py_XDECREF(su->obj);
4643 Py_XDECREF(su->type);
4644 self->ob_type->tp_free(self);
4645}
4646
4647static PyObject *
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004648super_repr(PyObject *self)
4649{
4650 superobject *su = (superobject *)self;
4651
4652 if (su->obj)
4653 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00004654 "<super: <class '%s'>, <%s object>>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004655 su->type ? su->type->tp_name : "NULL",
4656 su->obj->ob_type->tp_name);
4657 else
4658 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00004659 "<super: <class '%s'>, NULL>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004660 su->type ? su->type->tp_name : "NULL");
4661}
4662
4663static PyObject *
Guido van Rossum705f0f52001-08-24 16:47:00 +00004664super_getattro(PyObject *self, PyObject *name)
4665{
4666 superobject *su = (superobject *)self;
4667
4668 if (su->obj != NULL) {
Tim Petersa91e9642001-11-14 23:32:33 +00004669 PyObject *mro, *res, *tmp, *dict;
Guido van Rossum155db9a2002-04-02 17:53:47 +00004670 PyTypeObject *starttype;
Guido van Rossum705f0f52001-08-24 16:47:00 +00004671 descrgetfunc f;
4672 int i, n;
4673
Guido van Rossum155db9a2002-04-02 17:53:47 +00004674 starttype = su->obj->ob_type;
4675 mro = starttype->tp_mro;
4676
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004677 if (mro == NULL)
4678 n = 0;
4679 else {
4680 assert(PyTuple_Check(mro));
4681 n = PyTuple_GET_SIZE(mro);
4682 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00004683 for (i = 0; i < n; i++) {
Guido van Rossume705ef12001-08-29 15:47:06 +00004684 if ((PyObject *)(su->type) == PyTuple_GET_ITEM(mro, i))
Guido van Rossum705f0f52001-08-24 16:47:00 +00004685 break;
4686 }
Guido van Rossume705ef12001-08-29 15:47:06 +00004687 if (i >= n && PyType_Check(su->obj)) {
Guido van Rossum155db9a2002-04-02 17:53:47 +00004688 starttype = (PyTypeObject *)(su->obj);
4689 mro = starttype->tp_mro;
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004690 if (mro == NULL)
4691 n = 0;
4692 else {
4693 assert(PyTuple_Check(mro));
4694 n = PyTuple_GET_SIZE(mro);
4695 }
Guido van Rossume705ef12001-08-29 15:47:06 +00004696 for (i = 0; i < n; i++) {
4697 if ((PyObject *)(su->type) ==
4698 PyTuple_GET_ITEM(mro, i))
4699 break;
4700 }
Guido van Rossume705ef12001-08-29 15:47:06 +00004701 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00004702 i++;
4703 res = NULL;
4704 for (; i < n; i++) {
4705 tmp = PyTuple_GET_ITEM(mro, i);
Tim Petersa91e9642001-11-14 23:32:33 +00004706 if (PyType_Check(tmp))
4707 dict = ((PyTypeObject *)tmp)->tp_dict;
4708 else if (PyClass_Check(tmp))
4709 dict = ((PyClassObject *)tmp)->cl_dict;
4710 else
4711 continue;
4712 res = PyDict_GetItem(dict, name);
Guido van Rossum5b443c62001-12-03 15:38:28 +00004713 if (res != NULL && !PyDescr_IsData(res)) {
Guido van Rossum705f0f52001-08-24 16:47:00 +00004714 Py_INCREF(res);
4715 f = res->ob_type->tp_descr_get;
4716 if (f != NULL) {
Guido van Rossumd4641072002-04-03 02:13:37 +00004717 tmp = f(res, su->obj,
4718 (PyObject *)starttype);
Guido van Rossum705f0f52001-08-24 16:47:00 +00004719 Py_DECREF(res);
4720 res = tmp;
4721 }
4722 return res;
4723 }
4724 }
4725 }
4726 return PyObject_GenericGetAttr(self, name);
4727}
4728
Guido van Rossum5b443c62001-12-03 15:38:28 +00004729static int
4730supercheck(PyTypeObject *type, PyObject *obj)
4731{
4732 if (!PyType_IsSubtype(obj->ob_type, type) &&
4733 !(PyType_Check(obj) &&
4734 PyType_IsSubtype((PyTypeObject *)obj, type))) {
4735 PyErr_SetString(PyExc_TypeError,
4736 "super(type, obj): "
4737 "obj must be an instance or subtype of type");
4738 return -1;
4739 }
4740 else
4741 return 0;
4742}
4743
Guido van Rossum705f0f52001-08-24 16:47:00 +00004744static PyObject *
4745super_descr_get(PyObject *self, PyObject *obj, PyObject *type)
4746{
4747 superobject *su = (superobject *)self;
4748 superobject *new;
4749
4750 if (obj == NULL || obj == Py_None || su->obj != NULL) {
4751 /* Not binding to an object, or already bound */
4752 Py_INCREF(self);
4753 return self;
4754 }
Guido van Rossum5b443c62001-12-03 15:38:28 +00004755 if (su->ob_type != &PySuper_Type)
4756 /* If su is an instance of a subclass of super,
4757 call its type */
4758 return PyObject_CallFunction((PyObject *)su->ob_type,
4759 "OO", su->type, obj);
4760 else {
4761 /* Inline the common case */
4762 if (supercheck(su->type, obj) < 0)
4763 return NULL;
4764 new = (superobject *)PySuper_Type.tp_new(&PySuper_Type,
4765 NULL, NULL);
4766 if (new == NULL)
4767 return NULL;
4768 Py_INCREF(su->type);
4769 Py_INCREF(obj);
4770 new->type = su->type;
4771 new->obj = obj;
4772 return (PyObject *)new;
4773 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00004774}
4775
4776static int
4777super_init(PyObject *self, PyObject *args, PyObject *kwds)
4778{
4779 superobject *su = (superobject *)self;
Guido van Rossume705ef12001-08-29 15:47:06 +00004780 PyTypeObject *type;
4781 PyObject *obj = NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00004782
4783 if (!PyArg_ParseTuple(args, "O!|O:super", &PyType_Type, &type, &obj))
4784 return -1;
4785 if (obj == Py_None)
4786 obj = NULL;
Guido van Rossum5b443c62001-12-03 15:38:28 +00004787 if (obj != NULL && supercheck(type, obj) < 0)
Guido van Rossum705f0f52001-08-24 16:47:00 +00004788 return -1;
Guido van Rossum705f0f52001-08-24 16:47:00 +00004789 Py_INCREF(type);
4790 Py_XINCREF(obj);
4791 su->type = type;
4792 su->obj = obj;
4793 return 0;
4794}
4795
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004796PyDoc_STRVAR(super_doc,
Guido van Rossum705f0f52001-08-24 16:47:00 +00004797"super(type) -> unbound super object\n"
4798"super(type, obj) -> bound super object; requires isinstance(obj, type)\n"
Guido van Rossume705ef12001-08-29 15:47:06 +00004799"super(type, type2) -> bound super object; requires issubclass(type2, type)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00004800"Typical use to call a cooperative superclass method:\n"
4801"class C(B):\n"
4802" def meth(self, arg):\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004803" super(C, self).meth(arg)");
Guido van Rossum705f0f52001-08-24 16:47:00 +00004804
Guido van Rossum048eb752001-10-02 21:24:57 +00004805static int
4806super_traverse(PyObject *self, visitproc visit, void *arg)
4807{
4808 superobject *su = (superobject *)self;
4809 int err;
4810
4811#define VISIT(SLOT) \
4812 if (SLOT) { \
4813 err = visit((PyObject *)(SLOT), arg); \
4814 if (err) \
4815 return err; \
4816 }
4817
4818 VISIT(su->obj);
4819 VISIT(su->type);
4820
4821#undef VISIT
4822
4823 return 0;
4824}
4825
Guido van Rossum705f0f52001-08-24 16:47:00 +00004826PyTypeObject PySuper_Type = {
4827 PyObject_HEAD_INIT(&PyType_Type)
4828 0, /* ob_size */
4829 "super", /* tp_name */
4830 sizeof(superobject), /* tp_basicsize */
4831 0, /* tp_itemsize */
4832 /* methods */
4833 super_dealloc, /* tp_dealloc */
4834 0, /* tp_print */
4835 0, /* tp_getattr */
4836 0, /* tp_setattr */
4837 0, /* tp_compare */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004838 super_repr, /* tp_repr */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004839 0, /* tp_as_number */
4840 0, /* tp_as_sequence */
4841 0, /* tp_as_mapping */
4842 0, /* tp_hash */
4843 0, /* tp_call */
4844 0, /* tp_str */
4845 super_getattro, /* tp_getattro */
4846 0, /* tp_setattro */
4847 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00004848 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
4849 Py_TPFLAGS_BASETYPE, /* tp_flags */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004850 super_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00004851 super_traverse, /* tp_traverse */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004852 0, /* tp_clear */
4853 0, /* tp_richcompare */
4854 0, /* tp_weaklistoffset */
4855 0, /* tp_iter */
4856 0, /* tp_iternext */
4857 0, /* tp_methods */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004858 super_members, /* tp_members */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004859 0, /* tp_getset */
4860 0, /* tp_base */
4861 0, /* tp_dict */
4862 super_descr_get, /* tp_descr_get */
4863 0, /* tp_descr_set */
4864 0, /* tp_dictoffset */
4865 super_init, /* tp_init */
4866 PyType_GenericAlloc, /* tp_alloc */
4867 PyType_GenericNew, /* tp_new */
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00004868 PyObject_GC_Del, /* tp_free */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004869};